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 com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.http.javanet.NetHttpTransport; import java.text.SimpleDateFormat; import java.nio.file.Files; import java.text.NumberFormat; import javax.net.ssl.*; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.nio.file.Path; import java.text.*; import java.util.TimeZone; public class main { public static class Slice extends Concept { public static String _fieldOrder = "globalID caseID name indexed sliceDumped owner"; public GlobalID globalID = aGlobalIDObject(); public String caseID; public String name; public boolean indexed = true; public long sliceDumped; public Ref owner = new Ref(); public String defaultCaseID() { return uniqueFileNameUsingMD5_80_v2(name + " " + globalID); } public GlobalID globalID() { return globalID; } } public static class Page extends Concept { public long gID_1; public short gID_2; { setGlobalID(aGlobalIDObj()); } public void setGlobalID(GlobalID id) { if (id == null) { gID_1 = gID_2 = 0; return; } gID_1 = globalIDPart1(id); gID_2 = globalIDPart2(id); } public void setGlobalID(String id) { setGlobalID(toGlobalIDObj(id)); } public GlobalID globalID() { return globalIDFromParts(gID_1, gID_2); } public short flags; public String q; public void _onLoad() { String id = cget(this, "globalID"); if (id != null) { setGlobalID(id); cset(this, "globalID", null); } } public void quickPost(String key, String value) { agiBlue().new GetEntriesAndPost(_concepts).go(this, litmap("key", key, "value", value)); } public AGIBlue agiBlue() { return (AGIBlue) mapGet(_concepts.miscMap, "agiBlue"); } public AGIBlue.LoadedSlice loadedSlice() { return (AGIBlue.LoadedSlice) mapGet(_concepts.miscMap, "loadedSlice"); } } public abstract static class AbstractEntry extends Concept { public static String _fieldOrder = "page count key ip signer"; public Ref page = new Ref(); public int count; public String key; public String ip; public Ref signer = new Ref(); public String q() { Page p = page.get(); return p == null ? null : page.get().q; } } public static class Entry extends AbstractEntry { public String globalID = aGlobalID(); public String value; } public static class BlobEntry extends AbstractEntry { public static String _fieldOrder = "globalID length md5 contentType"; public GlobalID globalID = aGlobalIDObject(); public long length; public String md5; public String contentType; public GlobalID globalID() { return globalID; } } public static class Signer extends Concept { public static String _fieldOrder = "globalID publicKey trusted approvedBy"; public String globalID = aGlobalID(); public String publicKey; public boolean trusted = false; public String approvedBy; } public static class User extends Concept { public GlobalID globalID = aGlobalIDObject(); public long lastSeen; } public static class CookieUser extends User { public String cookie; public String toString() { return "[cookieUser]"; } } public static class GoogleUser extends User { public static String _fieldOrder = "googleLogInDate googleEmail googleFirstName googleLastName googleEmailVerified"; public long googleLogInDate; public String googleEmail, googleFirstName, googleLastName; public boolean googleEmailVerified = false; public String toString() { return googleFirstName + " " + googleLastName; } } public static class MinimalUser extends User { public static String _fieldOrder = "userName encryptedPassword"; public String userName, encryptedPassword; public String toString() { return "[minimalUser] " + userName; } } public static class JustPasswordUser extends User { public String password; } public static class Session extends Concept { public String cookie; public String selectedSlice; public Page slicePage; public Ref user = new Ref(); } public static class SliceInfo extends Concept { public GlobalID globalID; public List mandatoryBotVMBusIDs; public boolean openPosting = true; } public static class CentralIndexEntry { public Set slices = synchroLinkedHashSet(); } public abstract static class AGIBlue { public boolean asyncSearch = false; public boolean allowMultipleCasesInValues = true; public boolean showSliceSelector = true; public boolean showGoogleLogIn = true; public boolean makeAllKeysPages = true; public boolean makeAllValuesPages = true; public boolean legacy = true; public boolean dumpSlicesOnAnyChange = true; public int maxSliceNameLength = 1024; public int displayLength = 140; public int sideDisplayLength = 50; public int searchResultsToShow = 50; public String sideSearchType = "literal"; public int maxBackgroundSlices = 1000; public long cloningSince, clonedSince; public boolean isClone = false; public File sliceDumpFile(Slice slice) { return programFile("slice-dumps/" + or2(slice.caseID, "main") + ".slice"); } public File dumpSliceToFile(LoadedSlice slice) { return withDBLock(slice.cc, new F0() { public File get() { try { cset(slice.sliceConcept, "sliceDumped", now()); File file = sliceDumpFile(slice.sliceConcept); List lines = new ArrayList(); for (Page p : list(slice.cc, Page.class)) lines.add(quote(p.q)); for (Entry e : list(slice.cc, Entry.class)) lines.add(sfu(tripleToList(entryToTriple(e)))); saveLinesAsTextFile(file, lines); return file; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cset(slice.sliceConcept, sliceDumped := now());\r\n File file = sliceDumpF..."; } }); } public Page pageFromQ(Concepts cc, String q) { return empty(q) ? null : uniqCI_sync(cc, Page.class, "q", q); } public void makeCentralIndex() { newCentralIndex.clear(); long time = now(); try { for (Slice slice : conceptsWhere(Slice.class, "indexed", true)) addToNewCentralIndex(slice); } catch (Throwable __e) { _handleException(__e); } centralIndex.putAll(newCentralIndex); removeAllKeysNotIn(centralIndex, newCentralIndex); newCentralIndex.clear(); centralIndexMade = now(); centralIndexMadeIn = now() - time; } public void addToNewCentralIndex(Slice slice) { for (String s : sliceDump_pageNamesIncludingKeys(sliceDumpFile(slice))) newCentralIndexGet(s).slices.add(slice); } public CentralIndexEntry centralIndexGet(String s) { return getOrCreate(CentralIndexEntry.class, centralIndex, s); } public CentralIndexEntry newCentralIndexGet(String s) { return getOrCreate(CentralIndexEntry.class, newCentralIndex, s); } public Collection centralIndexGetSlices(String s) { CentralIndexEntry e = centralIndexGet(s); return e == null ? null : e.slices; } public void dbLog(Object... params) { logStructure(programFile("db.log"), ll(params)); } public class LoadedSlice { public String caseID; public Concepts cc; public Slice sliceConcept; public SliceInfo sliceInfo; public long lastAccess = sysNow(); public ReliableSingleThread rstDumpSlice = new ReliableSingleThread(new Runnable() { public void run() { try { dumpSliceToFile(LoadedSlice.this); rst_index.trigger(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dumpSliceToFile(LoadedSlice.this);\r\n rst_index.trigger(); // rebuild ind..."; } }); public boolean haltSliceDumping = false; public ConceptFieldIndexDesc idx_latestEntries, idx_latestCreatedPages, idx_latestChangedPages; public LoadedSlice(String caseID, Concepts cc) { this.cc = cc; this.caseID = caseID; csetAll(list(cc, Page.class), "slice", null, "url", null); releaseEmptyFieldValuesOfAllConcepts(cc); indexThings(); onConceptsChange(cc, rOnceAtATimeOnly(new Runnable() { public void run() { try { cset(sliceConcept, "_modified", now()); if (!haltSliceDumping && dumpSlicesOnAnyChange && nempty(caseID)) { rstDumpSlice.trigger(); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "cset(sliceConcept, _modified := now())\r\n ;\r\n if (!haltSliceDumping &&..."; } })); if (makeAllKeysPages && legacy) for (Entry e : list(cc, Entry.class)) pageFromQ(e.key); if (makeAllValuesPages && legacy) for (Entry e : list(cc, Entry.class)) pageFromQ(e.value); } public void initialSetup(GlobalID globalID) { sliceInfo = uniq(cc, SliceInfo.class); cset(sliceInfo, "globalID", globalID); } public SliceInfo sliceInfo() { return sliceInfo; } public Page pageFromQ(String q) { return AGIBlue.this.pageFromQ(cc, q); } public void indexThings() { indexConceptFieldsCI(cc, Page.class, "q", Entry.class, "key", Entry.class, "value"); indexConceptFields(cc, Signer.class, "publicKey"); indexConceptFields(cc, Session.class, "cookie"); indexSingletonConcept(cc, SliceInfo.class); idx_latestCreatedPages = new ConceptFieldIndexDesc(cc, Page.class, "created"); idx_latestChangedPages = new ConceptFieldIndexDesc(cc, Page.class, "_modified"); idx_latestEntries = new ConceptFieldIndexDesc(cc, Entry.class, "created"); } public boolean isMainSlice() { return empty(caseID); } public GlobalID globalID() { return sliceConcept.globalID; } public String name() { return sliceConcept.name; } } public ConceptsLoadedOnDemand fan; public ConceptsLoadedOnDemand backgroundFan; public Map loadedSlices = syncMap(); public Map backgroundSlices = syncMap(); public Map centralIndex = ciMap(); public Map newCentralIndex = ciMap(); public long centralIndexMade; public long centralIndexMadeIn; public ReliableSingleThread rst_index = new ReliableSingleThread(new Runnable() { public void run() { try { makeCentralIndex(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "makeCentralIndex();"; } }); public ConceptFieldIndexDesc idx_slicesByModification, idx_usersBySeen; public ConceptFieldIndexCI idx_slicesByName, idx_usersByName; public class GetEntriesAndPost { public Concepts cc; public List entries; public Entry entry; public boolean newEntry = false; public Signer signer; public Session session; public GetEntriesAndPost(Concepts cc, Session session) { this.session = session; this.cc = cc; } public GetEntriesAndPost(Concepts cc) { this.cc = cc; } public GetEntriesAndPost go(Page page, Map params) { String key = trim(params.get("key")), value = trim(params.get("value")); print("GetEntriesAndPost: " + quote(page.q) + ", " + quote(key) + " := " + quote(value)); { withDBLock(new Runnable() { public void run() { try { entries = findBackRefs(page, Entry.class); if (nempty(key) && nempty(value)) { Slice slice = page.loadedSlice().sliceConcept; SliceInfo sliceInfo = page.loadedSlice().sliceInfo(); if (!sliceInfo.openPosting && session != null && session.user.get() != slice.owner.get()) throw fail("Not owner of slice"); String ip = subBot_clientIP(); entry = firstThat(e -> eqic(e.key, key) && eq_icIf(!allowMultipleCasesInValues, e.value, value) && eq(e.ip, ip), entries); if (entry == null) { print("SAVING"); Entry e = cnew(cc, Entry.class, "page", page, "key", key, "value", value, "ip", ip, "count", l(entries) + 1, "signer", signer); if (makeAllKeysPages) pageFromQ(cc, key); if (makeAllValuesPages) pageFromQ(cc, value); page.change(); entry = e; newEntry = true; entries.add(entry); dbLog("New entry", "page", page.q, "globalID", e.globalID, "count", e.count, "key", key, "value", value); } } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "entries = findBackRefs(page, Entry);\r\n if (nempty(key) && nempty(value..."; } }); } sortByFieldInPlace("created", entries); numberEntriesInConceptField("count", entries); return this; } } public T3 entryToTriple(Entry e) { return e == null ? null : t3(e.page.get().q, e.key, e.value); } } public static Map searchTypeToText = litmap("leven", "Leven", "literal", "Literal", "scored", "Scored"); public static int sourceCodeLines; public static RealAGIBlue agiBlue; public static Renderer renderer = new Renderer1(); public static String classesToShare = "\r\n DynamicObject Concept Concepts Page Entry Slice LoadedSlice\r\n IConceptIndex IFieldIndex IConceptCounter ConceptFieldIndexCI ConceptFieldIndexDesc\r\n AbstractEntry Signer Session User GoogleUser MinimalUser CookieUser\r\n BlobEntry\r\n SliceInfo CentralIndexEntry AGIBlue RealAGIBlue TimedCache\r\n GlobalID Renderer\r\n IterableIterator CloseableIterableIterator\r\n"; public static void main(final String[] args) throws Exception { agiBlue = new RealAGIBlue(); } public static void _onLoad_sourceCodeLines() { sourceCodeLines = countLines(mySource()); } public static void cleanMeUp() { cleanUp(agiBlue); agiBlue = null; } public static interface Renderer { public Object html(String uri, Map params); } public static Object html(String uri, final Map params) { try { printWithTime("Starting request"); Object o = renderer.html(uri, params); printWithTime("Done with request"); return o; } catch (Exception __e) { throw rethrow(__e); } } public static class RealAGIBlue extends AGIBlue { public volatile boolean started, broken; public TimedCache sizeOnDisk = new TimedCache(60.0, "guessClusteredSizeOfProgramDirWithoutBackups"); public RealAGIBlue() { try { if (bootstrapDataFrom("#1023558")) deleteMyBackups(); thinMyBackups(); fan = slicesLoadedOnDemand(loadedSlices); mainConcepts = fan.get("", null); indexConceptFields(Slice.class, "globalID", Slice.class, "caseID"); indexConceptField(CookieUser.class, "cookie"); idx_slicesByName = new ConceptFieldIndexCI(Slice.class, "name"); idx_slicesByModification = new ConceptFieldIndexDesc(Slice.class, "_modified"); idx_usersByName = new ConceptFieldIndexCI(GoogleUser.class, "googleLastName"); idx_usersBySeen = new ConceptFieldIndexDesc(User.class, "lastSeen"); cset(uniq_returnIfNew(Slice.class, "caseID", ""), "name", "main slice"); loadedSlices.get("").initialSetup(toGlobalIDObj(mainSliceGlobalID())); loadedSlices.get("").sliceConcept = sliceConceptForCaseID(""); backgroundFan = slicesLoadedOnDemand(backgroundSlices); backgroundFan.lock = fan.lock; PKIKeyPair machineKey = agiBot_trustedKeyForMachine(); if (machineKey != null) { print("Approving this machine's key: " + machineKey.publicKey); cset(uniq_sync(Signer.class, "publicKey", machineKey.publicKey), "trusted", true, "approvedBy", "local"); } rst_index.trigger(); } catch (Throwable e) { _handleException(e); broken = true; } finally { started = true; } sizeOnDisk.keepValueWhileCalculating = true; doEveryAndNow(60.0, rWatcher(() -> db_mainConceptsChangeCount(), new Runnable() { public void run() { try { sizeOnDisk.get(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "sizeOnDisk.get()"; } })); } public List entriesOnPage(Page p) { return p == null ? null : sortedByField("count", findBackRefs(p, Entry.class)); } public List pagesSortedByLength(List l) { return sortedByCalculatedField(l, p -> l(p.q)); } public static boolean agiBlue_isOriginal() { return amProgram("#1023558"); } public String agiBlueURL(String subUri) { return agiBlueURL() + prependSlash(subUri); } public String agiBlueURL() { return agiBlue_isOriginal() ? "https://agi.blue" : "/" + psI(programID()) + "/raw"; } public String agiBlueName() { return agiBlue_isOriginal() ? "agi.blue" : isProgramID("#1024512") ? "agi.blue productive" : "agi.blue clone " + programID(); } public void cleanMeUp() { cleanUp(fan); } public LoadedSlice loadSlice(Slice slice) { return loadSlice(slice.caseID, str(slice.globalID)); } public LoadedSlice loadSlice(String caseID, String globalID) { caseID = unnull(caseID); Lock __7 = fan.lock; lock(__7); try { Concepts cc = backgroundFan.getIfLoaded(caseID); if (cc != null) { LoadedSlice slice = assertNotNull(backgroundSlices.get(caseID)); backgroundFan.loaded.remove(caseID); fan.loaded.put(caseID, cc); backgroundSlices.remove(caseID); loadedSlices.put(caseID, slice); return slice; } fan.get(caseID, globalID); return loadedSlices.get(caseID); } finally { unlock(__7); } } public void unloadSlice(String caseID) { fan.unloadCase(caseID); backgroundFan.unloadCase(caseID); } public LoadedSlice loadBackgroundSlice(Slice slice) { return loadBackgroundSlice(slice.caseID, str(slice.globalID)); } public LoadedSlice loadBackgroundSlice(String caseID, String globalID) { caseID = unnull(caseID); Lock __8 = fan.lock; lock(__8); try { if (fan.getIfLoaded(caseID) != null) return loadedSlices.get(caseID); backgroundFan.get(caseID, globalID); LoadedSlice slice = assertNotNull(backgroundSlices.get(caseID)); slice.lastAccess = sysNow(); while (l(backgroundSlices) > maxBackgroundSlices) unloadLeastRecentlyAccessedBackgroundSlice(); assertNotNull("slice.sliceConcept", slice.sliceConcept); return slice; } finally { unlock(__8); } } public void unloadLeastRecentlyAccessedBackgroundSlice() { Lock __9 = fan.lock; lock(__9); try { String caseID = lowestByField("lastAccess", keys(backgroundSlices)); if (caseID != null) backgroundFan.unloadCase(caseID); } finally { unlock(__9); } } public Slice sliceConceptForGlobalID(String globalID) { return sliceConceptForGlobalID(toGlobalIDObj(globalID)); } public Slice sliceConceptForGlobalID(GlobalID globalID) { return conceptWhere(Slice.class, "globalID", globalID); } public Slice sliceConceptForCaseID(String caseID) { return conceptWhere(Slice.class, "caseID", caseID); } public Slice sliceForName(String name) { return conceptWhereCI(Slice.class, "name", name); } public class Query extends WorksOnSlice { public Map vars = ciMap(); public Query(LoadedSlice slice) { super(slice); } public Object process(String query) { { Object __11 = processLines(agiBlue_parseQueryScript(query)); if (__11 != null) return __11; } return serveJSON("No return statement"); } public Object processLines(List lines) { for (ALQLLine line : lines) { if (line instanceof ALQLSlice) { Slice slice = sliceForName(((ALQLSlice) line).slice); if (slice == null) return serveJSON("Slice not found: " + ((ALQLSlice) line).slice); LoadedSlice oldSlice = Query.this.slice; try { setSlice(loadSlice(slice)); { Object __12 = processLines(((ALQLSlice) line).contents); if (__12 != null) return __12; } } finally { setSlice(oldSlice); } } else if (line instanceof ALQLReturn) return serveJSON(ll(getOrKeep(vars, ((ALQLReturn) line).var))); else if (line instanceof ALQLTriple) { T3 t = ((ALQLTriple) line).triple; t = tripleMap(t, s -> getOrKeep(vars, s)); Collection pages; String var; if (isDollarVar(t.c)) { var = t.c; if (isDollarVar(t.a)) { if (isDollarVar(t.b)) throw todo(t); Entry e = random(conceptsWhereCI(cc, Entry.class, "key", t.b)); if (e == null) return serveJSON("No results for " + var); pages = pagesForKeyAndValue(t.b, t.c); vars.put(t.a, e.page.get().q); vars.put(t.c, e.value); continue; } else if (isDollarVar(t.b)) { Page page = findPageFromQ(t.a); Entry e = random(findBackRefs(page, Entry.class)); if (e == null) return serveJSON("No results for " + var); vars.put(t.b, e.key); vars.put(t.c, e.value); continue; } else { String val = getValue(t.a, t.b); if (val == null) return serveJSON("No results for " + var); pages = ll(pageFromQ(val)); } } else if (isDollarVar(t.b)) { var = t.b; if (isDollarVar(t.c)) throw todo(t); if (isDollarVar(t.a)) { List entries = conceptsWhereCI(cc, Entry.class, "value", t.c); if (empty(entries)) return serveJSON("No results for " + var); Entry e = random(entries); vars.put(t.a, e.page.get().q); vars.put(t.b, e.key); continue; } else { Collection keys = keysForPageAndValue(t.a, t.c); if (empty(keys)) return serveJSON("No results for " + var); pages = map(new F1() { public Page get(String x) { try { return pageFromQ(x); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pageFromQ(x)"; } }, keys); } } else { var = t.a; if (!isDollarVar(t.a)) throw todo(t); if (isDollarVar(t.b)) throw todo(t); if (isDollarVar(t.c)) throw todo(t); pages = pagesForKeyAndValue(t.b, t.c); } if (empty(pages)) return serveJSON("No results for " + var); vars.put(var, random(pages).q); } else if (line instanceof ALQLPage) { if (eq(((ALQLPage) line).matchMethod, "eqic")) findPageFromQ(((ALQLPage) line).page); else if (eq(((ALQLPage) line).matchMethod, "flexMatchDollarVarsIC_first")) { List> l = new ArrayList(); for (Page p : list(cc, Page.class)) addIfNotNull(l, flexMatchDollarVarsIC_first(((ALQLPage) line).page, p.q)); if (empty(l)) return serveJSON("No results for " + curly(((ALQLPage) line).page)); vars.putAll(random(l)); } else throw fail("Unknown match method: " + ((ALQLPage) line).matchMethod); } else throw fail("Can't interpret: " + line); } return null; } } public String agiBlue_pageURLWithSlice(Page p) { return p == null ? null : agiBlueURL() + hquery("slice", _get(sliceForPage(p), "globalID"), "q", p.q); } public Slice sliceForPage(Page p) { if (p == null) return null; SliceInfo info = conceptWhere(p._concepts, SliceInfo.class); return info == null ? null : sliceConceptForGlobalID(info.globalID); } public GlobalID mainSliceGlobalID() { return conceptWhere(Slice.class, "caseID", "").globalID; } public ConceptsLoadedOnDemand slicesLoadedOnDemand(Map loadedSlices) { ConceptsLoadedOnDemand fan = new ConceptsLoadedOnDemand(); fan.onCaseLoaded(new VF3() { public void get(String caseID, Object globalID, Concepts concepts) { try { LoadedSlice ls = new LoadedSlice(caseID, concepts); concepts.miscMap = mapPutOrCreate_multi(concepts.miscMap, "agiBlue", RealAGIBlue.this, "loadedSlice", ls); ls.sliceConcept = sliceConceptForCaseID(caseID); if (nempty(globalID)) ls.initialSetup(toGlobalIDObj((String) globalID)); loadedSlices.put(caseID, ls); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "LoadedSlice ls = new(caseID, concepts);\r\n concepts.miscMap = mapPutOrCre..."; } }); fan.onUnloadingCase(new VF2() { public void get(String caseID, Concepts concepts) { try { loadedSlices.remove(caseID); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "loadedSlices.remove(caseID);"; } }); return fan; } public String checkDoubleLoads() { List l = sharedKeys(loadedSlices, backgroundSlices); return empty(l) ? null : "ERROR: Slice loaded in background and foreground: " + first(l); } public long estimatedSliceDataSize(Slice slice) { return estimatedSliceDataSize(slice.caseID); } public long estimatedSliceDataSize(String caseID) { return l(conceptsFile(fan.dbID(caseID))); } public void softRestart() { print("Cloning..."); cloningSince = sysNow(); Class c = hotwireDependent(programID()); copyFields(mc(), c, "agiBlue", "mainConcepts", "creator_class"); renderer = (Renderer) get("renderer", c); print("Got new renderer."); } } public static class WorksOnSlice { public Concepts cc; public AGIBlue.LoadedSlice slice; public WorksOnSlice() { } public WorksOnSlice(AGIBlue.LoadedSlice slice) { this.slice = slice; cc = slice.cc; } public void setSlice(AGIBlue.LoadedSlice slice) { this.slice = slice; cc = slice.cc; } public Page findPageFromParams(Map map) { String q = getString("q", map); return empty(q) ? null : findPageFromQ(q); } public Page findOrMakePageFromParams(Map map) { return pageFromQ(getString("q", map)); } public Page findPageFromQ(String q) { return conceptWhereCI(cc, Page.class, "q", q); } public Page pageFromQ(String q) { return slice.pageFromQ(q); } public Set pagesForKeyAndValue(String key, String value) { List entries = conceptsWhereIC(cc, Entry.class, "value", value, "key", key); return asSet(ccollect("page", entries)); } public Collection keysForPageAndValue(String q, String value) { Page page = findPageFromQ(q); if (page == null) return null; return collect("key", conceptsWhereIC(cc, Entry.class, "page", page, "value", value)); } public boolean hasPage(String q) { return hasConceptWhereIC(Page.class, "q", q); } public String getValue(Page page, String key) { return page == null || empty(key) ? null : getString("value", highestByField("count", objectsWhereIC(findBackRefs(page, Entry.class), "key", key))); } public String getValue(String page, String key) { return getValue(findPageFromQ(page), key); } public String pageDisplayName(Page page) { return page.q; } public String renderThing(String s, boolean forceURLDisplay) { return forceURLDisplay || isURL(s) || isAGIDomain(s) ? ahref(fixAGILink(absoluteURL(s)), htmlencode2(shorten(agiBlue.displayLength, s))) : ahref(agiBlue_linkForPhrase(s, "slice", slice.isMainSlice() ? null : slice.sliceConcept.globalID), htmlencode2(shorten(agiBlue.displayLength, s))); } public GlobalID sliceID() { return slice.globalID(); } public SliceInfo sliceInfo() { return slice.sliceInfo; } } public static class Renderer1 implements Renderer { public Object html(String uri, Map params) { sleepWhile(() -> !agiBlue.started); if (agiBlue.broken) return subBot_serve500("Internal error"); return new Request().serve(uri, params); } public class Request extends WorksOnSlice { public String cookie; public Session session; public Slice sliceConcept; public String uri; public Map params; public long started = sysNow(); public String q, domain; public Set get; public List usesAsKey; public boolean isHomeDomain() { String domain = domain(); return eqic(domain, "www.agi.blue") || !ewic(domain, ".agi.blue"); } public Object serve(String uri, Map params) { this.uri = dropMultipleSlashes(uri); this.params = params; Matches m = new Matches(); print(uri + " ? " + unnull(subBot_query())); cookie = cookieFromUser(); if (cookie != null) { session = uniq_sync(Session.class, "cookie", cookie); if (session.user.get() == null) cset(session, "user", uniq_sync(CookieUser.class, "cookie", cookie)); } else session = unlistedWithValues(Session.class); String selectSlice = params.get("slice"); if (isGlobalID(selectSlice)) cset(session, "selectedSlice", selectSlice); if (session.selectedSlice == null) cset(session, "selectedSlice", str(agiBlue.mainSliceGlobalID())); String caseID = ""; sliceConcept = agiBlue.sliceConceptForGlobalID(session.selectedSlice); print("Selected slice: " + session.selectedSlice + ", obj? " + (sliceConcept != null)); if (sliceConcept != null) caseID = sliceConcept.caseID; print("caseID: " + caseID); slice = assertNotNull(agiBlue.loadSlice(caseID, session.selectedSlice)); cc = slice.cc; if (swic(uri, "/bot/")) return serveBot(); if (swic(uri, "/user/", m)) { User user = conceptWhere(User.class, "globalID", toGlobalIDObj(assertGlobalID(m.rest()))); if (user == null) return subBot_serve404("User not found"); String title = "User " + user; return hhtml_miniPage(title, h3(agiBlueNameHTML() + " | " + title) + "User type: " + classShortName(user)); } String uri2 = dropTrailingSlash(uri); if (eqic(uri2, "/google-verify")) { print("Google-verify started."); Payload payload = printStruct(googleVerifyUserToken2(googleSignInID(), params.get("token"))); if (payload == null) return print("google-verify", "No"); String email = payload.getEmail(); if (empty(email)) return print("google-verify", "No"); GoogleUser user = uniqCI_sync(GoogleUser.class, "googleEmail", email); cset(user, "googleEmailVerified", payload.getEmailVerified(), "googleFirstName", strOrNull(payload.get("given_name")), "googleLastName", strOrNull(payload.get("family_name"))); cset(session, "user", user); return print("google-verify", payload.getEmail() + " " + (payload.getEmailVerified() ? "(verified)" : "(not verified)")); } cset(session.user.get(), "lastSeen", now()); if (eqic(uri2, "/users")) return serveUsersList(); if (eqic(uri2, "/slices")) return serveSlicesList(); if (eqic(uri2, "/search")) return serveScoredSearch(); if (eqic(uri2, "/literalSearch")) return serveLiteralSearch(); if (eqic(uri2, "/levenSearch")) return serveLevenSearch(); if (eqic(uri2, "/query")) return serveQueryPage(); if (eqic(uri2, "/createSlice")) return serveCreateSlicePage(); if (eqic(uri2, "/deletePage")) return serveDeletePage(); if (eqic(uri2, "/deleteSlice")) return serveDeleteSlice(); if (eqic(uri2, "/checkboxes")) return serveCheckboxes(); if (eqic(uri2, "/multiAdd")) return serveMultiAdd(); if (eqic(uri2, "/version")) return myTranspilationDate(); if (eqic(uri2, "/restart") && authed()) { agiBlue.softRestart(); return "OK"; } q = params.get("q"); get = asCISet(nempties(subBot_paramsAsMultiMap().get("get"))); domain = or2(params.get("domain"), domain()); String raw = firstKeyWithValue("", params); if (nempty(raw) && empty(q)) q = raw; String url = domain + dropTrailingSlash(uri); if (empty(q)) { String qq = agiBlue_urlToQuery(url); if (neqic(qq, "agi.blue")) q = qq; } Page page; boolean newPage = false; Pair __16 = uniqCI2_sync(cc, Page.class, "q", q); page = __16.a; newPage = __16.b; if (newPage) agiBlue.dbLog("New page", "q", q); if (empty(params.get("q")) && empty(raw) && isHomeDomain()) { List pages = cloneList(slice.idx_latestChangedPages.objectIterator()); int start = parseInt(params.get("start")), step = 100; String nav = pageNav2("/", l(pages), start, step, "start"); String content = hform(b("GIVE ME INPUT:   ") + htextinput("q", "autofocus", true) + " " + hsubmit("Ask")) + h1(sliceAsHTML() + " has " + nPages(countConcepts(cc, Page.class)) + " and " + nConnections(countConcepts(cc, Entry.class))) + p(nav) + p_nemptyLines(map(pageToHTMLLink(), subList(pages, start, start + step))); return hhtml_agiBlue(hhead_title("Slice " + sliceConcept().name + " | agi.blue") + hbody(hfullcenterAndTopLeft(top() + content + footer(), sliceSelector()))); } String key = trim(params.get("key")), value = trim(params.get("value")); List entries = agiBlue.new GetEntriesAndPost(cc).go(page, params).entries; if (nempty(get)) return serveJSON(collect("value", llNotNulls(firstThat(entries, e -> get.contains(e.key))))); String key2 = key, value2 = value; if (nempty(key) && nempty(value)) key2 = value2 = ""; boolean withHidden = eq(params.get("withHidden"), "1"); Set hide = new HashSet(); if (!withHidden) for (Entry e : entries) if (eqic(e.key, "hide") && isSquareBracketedInt(e.value)) addAll(hide, e.count, parseInt(unSquareBracket(e.value))); MultiMap mmMeta = new MultiMap(); for (Entry e : entries) if (isSquareBracketedInt(e.key)) mmMeta.put(parseInt(unSquareBracket(e.key)), e.value); MultiMap mm = new MultiMap(); for (Entry e : entries) mm.put(e.key, e.value); String name = page.q; List refs = concatLists(conceptsWhereIC(cc, Entry.class, "value", name), conceptsWhereIC(cc, Entry.class, "key", name)); Set refPages = asSet(ccollect("page", refs)); refPages.remove(page); List searchResults; int totalResults = 0, searchResultsToShow = 50; if (eq(agiBlue.sideSearchType, "leven")) searchResults = levenSearch(page.q, "max", searchResultsToShow); else if (eq(agiBlue.sideSearchType, "literal")) { searchResults = literalSearch(page.q, "max", maxInt()); print("totalResults", totalResults = l(searchResults)); searchResults = takeFirst(searchResultsToShow, searchResults); } else searchResults = (List) dm_call("agiBlueSearch", "search", page.q, "maxResult", clipIntPlus(searchResultsToShow, 1), "agiBlueBotID", programID(), "cc", cc); searchResults.remove(page); usesAsKey = conceptsWhereIC(cc, Entry.class, "key", page.q); CentralIndexEntry cie = agiBlue.centralIndex.get(page.q); List pageInOtherSlices = cie == null ? null : listMinus(cie.slices, slice.sliceConcept); String pageName_html = htmlEncode2(shorten(agiBlue.displayLength, name)); String mainContents = top() + h1(ahref_unstyled(agiBlue.agiBlue_pageURLWithSlice(page), pageName_html) + (newPage ? " [huh????]" : "")) + p_nemptyLines(map(entries, new F1() { public String get(Entry e) { try { return !withHidden && (hide.contains(e.count) || eqic(e.key, "read as") && eqic(e.value, name)) ? "" : "[" + e.count + "] " + renderThing(e.key, false) + ": " + b(renderThing(e.value, cic(mmMeta.get(e.count), "is a URL"))); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "!withHidden && (hide.contains(e.count) || eqic(e.key, \"read as\") && eqic(e.va..."; } })) + hpostform(h3("Add an entry") + "Key: " + hinputfield("key", key2) + " Value: " + hinputfield("value", value2) + "

" + hsubmit("Add")) + p(ahref(agiBlue.agiBlueURL() + "/literalSearch" + hquery("q", page.q), "[literal search]", "title", "Search pages with a name containing this page's name literally") + " " + ahref(agiBlue.agiBlueURL() + "/levenSearch" + hquery("q", page.q), "[leven search 1]", "title", "Search pages with a Levenshtein similarity of 1 containing this page's name literally") + " " + ahref(agiBlue.agiBlueURL() + "/search" + hquery("q", page.q), "[scored search]", "title", "Search pages with ScoredSearch") + " " + ahref(agiBlue.agiBlueURL() + "/deletePage" + hquery("slice", sliceID(), "q", page.q), "[delete page]")) + (empty(usesAsKey) ? "" : h3(quote(pageName_html) + " as key") + p_nemptyLines_showFirst(50, map(usesAsKey, e -> pageToHTMLLink().get(e.page.get()) + unicode_spacedRightPointingTriangle() + pageName_html + unicode_spacedRightPointingTriangle() + pageToHTMLLink().get(pageFromQ(e.value))))) + (empty(pageInOtherSlices) ? "" : h3(quote(pageName_html) + " in other slices") + p_nemptyLines_showFirst(50, map(slice -> ahref(agiBlue.agiBlueURL() + hquery("slice", slice.globalID, "q", page.q), htmlEncode2(slice.name)), pageInOtherSlices))); String sideContents = hform(b("GIVE ME INPUT:") + " " + htextinput("q") + " " + hsubmit("Ask", "onclick", "document.getElementById('newInputForm').target = '';") + " " + hsubmit("+Tab", "title", "Ask and show result in a new tab", "onclick", "document.getElementById('newInputForm').target = '_blank';"), "id", "newInputForm") + h3("References (" + l(refPages) + ")") + p_nemptyLines_showFirst(10, map(pageToHTMLLink("displayLength", agiBlue.sideDisplayLength), refPages)) + h3(searchTypeToText.get(agiBlue.sideSearchType) + " search results (" + (l(searchResults) >= searchResultsToShow ? searchResultsToShow + "+" : str(l(searchResults))) + (totalResults > l(searchResults) ? " of " + n2(totalResults) : "") + ")") + p_nemptyLines_showFirst(searchResultsToShow, map(pageToHTMLLink("displayLength", agiBlue.sideDisplayLength), searchResults)) + hdiv("", "id", "extraStuff"); if (agiBlue.asyncSearch) doLater(6.0, new Runnable() { public void run() { try { dm_call("agiBlueSearch", "searchAndPost", page.q, "agiBlueBotID", programID(), "cc", cc); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "dm_call(\"agiBlueSearch\", \"searchAndPost\", page.q, agiBlueBotID := programID()..."; } }); vmBus_send("agiBlue_servingConceptPage", this, page); String iframe = params.get("render_iframe"); return hhtml_agiBlue(hhead_title(pageDisplayName(page)) + hbody(tag("table", tr(td(sliceSelector(), "valign", "top") + td(sideContents, "align", "right", "valign", "top", "rowspan", 2)) + tr(td(mainContents + (empty(iframe) ? "" : iframe(iframe, "width", 600, "height", 400)) + footer(), "align", "center", "valign", "top")), "width", "100%", "height", "100%"))); } public Object servePagesToBot(Iterable pages) { return serveListToBot(map(pageToMap(wrapMapAsParams(params)), pages)); } public Object serveListToBot(Collection l) { if (nempty(params.get("max"))) l = takeFirst(parseInt(params.get("max")), l); return serveJSON(l); } public Object serveBot() { String q = params.get("q"); if (eqic(uri, "/bot/hello")) return serveJSON("hello"); if (eqic(uri, "/bot/hasPage")) return serveJSON(hasPage(q)); if (eqic(uri, "/bot/randomPageContaining")) { assertNempty(q); return servePageToBot(random(filter(list(cc, Page.class), p -> cic(p.q, q))), params); } if (eqic(uri, "/bot/allPages")) return servePagesToBot(list(cc, Page.class)); if (eqic(uri, "/bot/allPagesStartingWith")) { assertNempty(q); return servePagesToBot(filter(list(cc, Page.class), p -> swic(p.q, q))); } if (eqic(uri, "/bot/allPagesEndingWith")) { assertNempty(q); return servePagesToBot(filter(list(cc, Page.class), p -> ewic(p.q, q))); } if (eqic(uri, "/bot/allPagesContaining")) { assertNempty(q); return servePagesToBot(filter(list(cc, Page.class), p -> cic(p.q, q))); } if (eqic(uri, "/bot/allPagesContainingRegexp")) { assertNempty(q); Pattern pat = regexpIC(q); return servePagesToBot(filter(list(cc, Page.class), p -> regexpFindIC(pat, p.q))); } if (eqicOneOf(uri, "/bot/postSigned", "/bot/approveTrustRequest")) { String text = rtrim(params.get("text")); String key = getSignerKey(text); if (empty(key)) return subBot_serve500("Please include your public key"); if (!isSignedWithKey(text, key)) return subBot_serve500("Signature didn't verify"); text = dropLastTwoLines(text); Signer signer = uniq_sync(Signer.class, "publicKey", key); if (eqic(uri, "/bot/postSigned")) { List out = new ArrayList(); for (String line : tlft(text)) { Map map = jsonDecodeMap(line); AGIBlue.GetEntriesAndPost x = agiBlue.new GetEntriesAndPost(db_mainConcepts()); x.signer = signer; Page page = findOrMakePageFromParams(map); if (page == null) { out.add("Invalid page reference"); continue; } x.go(page, map); out.add(x.newEntry ? "Saved" : x.entry != null ? "Entry exists" : "Need key and value"); } return serveJSON(out); } if (eqic(uri, "/bot/approveTrustRequest")) { if (!signer.trusted) return subBot_serve500("Untrusted signer"); Signer toApprove = conceptWhere(Signer.class, "publicKey", trim(text)); if (toApprove == null) return subBot_serve500("Signer to approve not found"); cset(toApprove, "trusted", true, "approvedBy", signer.globalID); return serveJSON("Approved: " + trim(text)); } return subBot_serve500("CONFUSION"); } if (eqic(uri, "/bot/post")) { AGIBlue.GetEntriesAndPost x = agiBlue.new GetEntriesAndPost(cc); x.go(pageFromQ(q), params); return serveJSON(x.newEntry ? "Saved" : x.entry != null ? "Entry exists" : "Need key and value"); } if (eqic(uri, "/bot/entriesOnPage")) return serveJSON(map(agiBlue.entriesOnPage(findPageFromParams(params)), entryToMap(false))); if (eqic(uri, "/bot/entriesForKey")) return serveJSON(map(conceptsWhereIC(cc, Entry.class, "key", params.get("key")), entryToMap(true))); if (eqic(uri, "/bot/lookup")) { String key = params.get("key"); if (empty(key)) return serveJSON("Need key"); String value = getValue(findPageFromParams(params), key); return serveJSON(empty(value) ? "" : litmap("value", value)); } if (eqic(uri, "/bot/multiLookup")) { String key = params.get("key"); if (empty(key)) return serveJSON("Need key"); return serveJSON(collect("value", objectsWhereIC(findBackRefs(findPageFromParams(params), Entry.class), "key", key))); } if (eqic(uri, "/bot/multiLookupInAllSlices")) { String key = params.get("key"); if (empty(key)) return serveJSON("Need key"); Collection slices = agiBlue.centralIndexGetSlices(key); List results = new ArrayList(); for (Slice s : unnull(slices)) { WorksOnSlice wos = new WorksOnSlice(agiBlue.loadBackgroundSlice(s)); Page page = wos.findPageFromParams(params); if (page != null) for (Entry e : unnull(objectsWhereIC(findBackRefs(page, Entry.class), "key", key))) results.add(litorderedmap("c", e.value, "slice", str(s.globalID()))); } return serveJSON(results); } if (eqic(uri, "/bot/latestEntries")) return serveJSON(map(takeFirst(10, slice.idx_latestEntries.objectIterator()), entryToMap(true))); if (eqic(uri, "/bot/latestPages")) return serveJSON(map(takeFirst(10, slice.idx_latestCreatedPages.objectIterator()), pageToMap())); if (eqic(uri, "/bot/latestChangedPages")) return serveJSON(map(takeFirst(10, slice.idx_latestChangedPages.objectIterator()), pageToMap())); if (eqic(uri, "/bot/googleUsersCount")) return serveJSON(countConcepts(GoogleUser.class)); if (eqic(uri, "/bot/totalPageCount")) return serveJSON(countConcepts(Page.class)); if (eqic(uri, "/bot/trustedSignersCount")) return serveJSON(countConcepts(Signer.class, "trusted", true)); if (eqic(uri, "/bot/valueSearch")) { String value = params.get("value"); List entries = conceptsWhereIC(cc, Entry.class, "value", value); return serveJSON(map(takeFirst(100, entries), entryToMap(true))); } if (eqic(uri, "/bot/keyAndValueSearch")) { String key = params.get("key"), value = params.get("value"); Collection pages = pagesForKeyAndValue(key, value); return servePagesToBot(pages); } if (eqic(uri, "/bot/aLookup")) { String key = params.get("key"), value = params.get("value"); Collection pages = pagesForKeyAndValue(key, value); return serveJSON(collect("q", pages)); } if (eqic(uri, "/bot/bLookup")) { String value = params.get("value"); return serveJSON(keysForPageAndValue(q, value)); } if (eqic(uri, "/bot/keyValuePairsByPopularity")) { List> pairs = map(list(Entry.class), e -> pair(e.key, e.value)); List> pairs2 = multiSetTopPairs(ciMultiSet(map("pairToUglyStringForCIComparison", pairs))); return serveJSON(map(pairs2, p -> { String key; String value; Pair __17 = pairFromUglyString(p.a); key = __17.a; value = __17.b; return litorderedmap("n", p.b, "key", key, "value", value); })); } if (eqic(uri, "/bot/allKeys")) return serveListToBot(distinctCIFieldValuesOfConcepts(cc, Entry.class, "key")); if (eqic(uri, "/bot/allKeysByPopularity")) return serveListToBot(mapMultiSetByPopularity(distinctCIFieldValuesOfConcepts_multiSet(cc, Entry.class, "key"), (key, n) -> litorderedmap("n", n, "key", key))); if (eqic(uri, "/bot/dbSize")) return serveJSON(l(conceptsFile())); if (eqic(uri, "/bot/query")) return serveBotQuery(); if (eqic(uri, "/bot/createSlice")) { Slice slice = createSlice(assertNempty(params.get("name"))); return serveJSON(litorderedmap("id", str(slice.globalID), "name", slice.name)); } if (eqic(uri, "/bot/dumpAllSlices") && authed()) { List out = new ArrayList(); for (Slice slice : list(Slice.class)) try { out.add(litorderedmap("slice", slice.caseID, "ms", returnTimeFor(() -> agiBlue.dumpSliceToFile(agiBlue.loadBackgroundSlice(slice))))); } catch (Throwable e) { _handleException(e); out.add(litorderedmap(slice.caseID, "error", exceptionToStringShort(e))); } return serveJSON(out); } if (eqic(uri, "/bot/dumpSlice")) { File f = agiBlue.dumpSliceToFile(slice); return "OK, saved as: " + f2s(f); } if (eqic(uri, "/bot/diskStats")) return serveJSON(litcimap("sizeOnDisk", agiBlue.sizeOnDisk.get(), "freeDiskSpace", freeDiskSpace())); if (eqic(uri, "/bot/memStats")) { Map fg = cloneMap(agiBlue.loadedSlices); Map bg = cloneMap(agiBlue.backgroundSlices); return serveJSON(litcimap("error", agiBlue.checkDoubleLoads(), "centralIndexEntries", l(agiBlue.centralIndex), "centralIndexMade", renderHowLongAgo(agiBlue.centralIndexMade), "centralIndexMadeInMS", agiBlue.centralIndexMadeIn, "numLoadedForegroundSlices", l(fg), "numLoadedBackgroundSlices", l(bg), "loadedForegroundSlicesEstimatedSize", longSum(map(s -> agiBlue.estimatedSliceDataSize(s), keys(fg))), "loadedBackgroundSlicesEstimatedSize", longSum(map(s -> agiBlue.estimatedSliceDataSize(s), keys(bg))), "loadedForegroundSlices", sortedIC(keysList(fg)), "loadedBackgroundSlices", sortedIC(keysList(bg)), "sessionsWithGoogleUsers", countPred(list(Session.class), s -> s.user.get() instanceof GoogleUser), "userObjects", countConcepts(User.class), "processSize", getOpt(vmBus_query("processSize"), "processSize"))); } if (eqic(uri, "/bot/centralIndexGet")) { CentralIndexEntry e = agiBlue.centralIndex.get(q); return serveJSON(e == null ? ll() : map(e.slices, sliceToMap())); } if (eqic(uri, "/bot/centralIndexGrab")) { CentralIndexEntry ie = agiBlue.centralIndex.get(q); List out = new ArrayList(); if (ie != null) for (Slice slice : ie.slices) { AGIBlue.LoadedSlice ls = agiBlue.loadBackgroundSlice(slice); WorksOnSlice wos = new WorksOnSlice(ls); Page page = wos.findPageFromQ(q); Iterable entries = agiBlue.entriesOnPage(page); print("Page for " + q + " in slice " + ls.caseID + ": " + yesNo(page != null) + " - " + l(entries)); Entry e = first(entries); if (e != null) out.add(litorderedmap("a", page.q, "b", e.key, "c", e.value, "slice", slice.caseID)); } return serveJSON(out); } if (eqic(uri, "/bot/updateCentralIndex") && authed()) { agiBlue.rst_index.trigger(); return "OK"; } if (eqic(uri, "/bot/allGoogleEmails") && authed()) return serveJSON(collect("googleEmail", list(GoogleUser.class))); if (eqic(uri, "/bot/words2_spaces_all")) return serveJSON(mapToValues_ciMap("words2_spaces_cached", collect("q", conceptsSortedByFieldCI(slice.cc, Page.class, "q")))); if (eqic(uri, "/bot/words2_spaces_collapse_all")) return serveJSON(mapToValues_ciMap("words2_spaces_collapse_cached", collect("q", conceptsSortedByFieldCI(slice.cc, Page.class, "q")))); if (eqic(uri, "/bot/makeManyPages")) { List qs = tlft(params.get("pages")); slice.haltSliceDumping = true; try { for (String _q : unnull(qs)) { ping(); pageFromQ(_q); } } finally { slice.haltSliceDumping = true; slice.rstDumpSlice.trigger(); } return "OK (" + l(qs) + ")"; } if (eqic(uri, "/bot/sliceNamesMap")) return serveJSON(mapToMap(list(Slice.class), s -> pair(str(s.globalID), s.name))); if (eqic(uri, "/bot/allowOpenPosting")) { { Object __13 = errorIfNotOwnerOfSlice(); if (__13 != null) return __13; } boolean allow = eq("1", params.get("allow")); cset(sliceInfo(), "openPosting", allow); return "Set openPosting to " + allow; } if (eqic(uri, "/bot/createUnusedNumberedPage")) { int n = 1; while (findPageFromQ(q + n) != null) ++n; return serveJSON(litmap("q", pageFromQ(q + n).q)); } return subBot_serve404(); } public Object serveBotQuery() { String query = params.get("query"); return agiBlue.new Query(slice).process(query); } public int searchResultsToShow() { return agiBlue.searchResultsToShow; } public Object serveLiteralSearch() { String q = params.get("q"); List searchResults = literalSearch(q); return serveSearchResults("literal search", q, searchResultsToShow(), searchResults); } public List literalSearch(String q, Object... __) { int searchResultsToShow = optPar("max", __, 100); return takeFirst(clipIntPlus(searchResultsToShow, 1), agiBlue.pagesSortedByLength(filter(list(cc, Page.class), p -> cic(p.q, q)))); } public Object serveScoredSearch() { String q = params.get("q"); List searchResults = (List) dm_call("agiBlueSearch", "search", q, "cc", cc); return serveSearchResults("scored search", q, searchResultsToShow(), searchResults); } public Object serveLevenSearch() { String q = params.get("q"); List searchResults = levenSearch(q); return serveSearchResults("leven search with distance 1", q, searchResultsToShow(), searchResults); } public List levenSearch(String q, Object... __) { int searchResultsToShow = optPar("max", __, 100); int maxEditDistance = 1; Map map = new HashMap(); for (Page p : list(cc, Page.class)) { int distance = leven_limitedIC(q, p.q, maxEditDistance + 1); if (distance <= maxEditDistance) map.put(p, distance); } return takeFirst(clipIntPlus(searchResultsToShow, 1), keysSortedByValue(map)); } public Object serveSearchResults(String searchType, String q, int searchResultsToShow, Collection searchResults) { String title = "agi.blue " + searchType + " for " + htmlEncode2(quote(q)) + " (" + (l(searchResults) >= searchResultsToShow ? searchResultsToShow + "+ results" : nResults(l(searchResults))) + ")"; return hhtml_agiBlue(hhead_title(htmldecode_dropAllTags(title)) + hbody(hfullcenter(h3(title) + p_nemptyLines_showFirst(searchResultsToShow, map(pageToHTMLLink(), searchResults))))); } public Object serveQueryPage() { String query = params.get("query"); if (query == null) query = loadSnippet("#1024258"); String title = agiBlueNameHTML() + " | Execute a query script (" + targetBlank("http://code.botcompany.de/1024274", "ALQL") + ")"; return hhtml_miniPage(title, h3(title) + form(htextarea(query, "name", "query", "cols", 80, "rows", 10, "autofocus", true) + "

" + hsubmit("Execute"), "action", "/bot/query")); } public Object hhtml_miniPage(String htmlTitle, Object contents) { return hhtml_agiBlue(hhead_title(htmldecode_dropAllTags(htmlTitle)) + hbody(hfullcenter(contents))); } public String sliceHomeURL() { return slice == null ? agiBlue.agiBlueURL() : sliceHomeURL(slice.sliceConcept.globalID); } public String sliceHomeURL(Slice slice) { return sliceHomeURL(slice.globalID); } public String sliceHomeURL(GlobalID slice) { return agiBlue.agiBlueURL() + hquery("slice", slice); } public String sliceLinkHTML(Slice slice) { return slice == null ? "-" : ahref(sliceHomeURL(slice), htmlEncode2(slice.name)); } public Object serveCreateSlicePage() { String sliceName = trim(params.get("sliceName")); if (eq(params.get("doIt"), "1") && nempty(sliceName)) { Slice slice = createSlice(sliceName); return hrefresh(sliceHomeURL(slice.globalID)); } String title = agiBlueNameHTML() + " | Create slice"; return hhtml_agiBlue(hhead_title(htmldecode_dropAllTags(title)) + hbody(hfullcenter(h3(title) + form(hhidden("doIt", 1) + "Slice name: " + htextinput("sliceName", sliceName, "autofocus", true) + "

" + hsubmit("Create slice"))))); } public Object serveDeletePage() { q = params.get("q"); Page page = findPageFromQ(q); if (page == null) return "Page " + quote(q) + " not found in slice " + htmlEncode(slice.name()); { Object __14 = errorIfNotOwnerOfSlice(); if (__14 != null) return __14; } deleteConcepts(findBackRefs(page, AbstractEntry.class)); cdelete(page); return hrefresh(1.0, sliceHomeURL()) + "Page deleted"; } public Object serveDeleteSlice() { { Object __15 = errorIfNotOwnerOfSlice(); if (__15 != null) return __15; } String caseID = sliceConcept.caseID; agiBlue.unloadSlice(caseID); File dir = sliceDir(sliceConcept); if (!dirExists(dir)) return "Dir not found: " + f2s(dir); moveDirectory(dir, programFile("deletedSlices/" + sliceConcept.caseID)); cset(session, "selectedSlice", null); cdelete(sliceConcept); return serveText("Slice " + caseID + " deleted (& backed up)"); } public Object errorIfNotOwnerOfSlice() { boolean ownage = slice.sliceConcept.owner.get() == session.user.get(); if (!ownage) return subBot_serve403("Sorry, you don't own slice " + htmlEncode(slice.name())); return null; } public F1 pageToHTMLLink(Object... __) { int displayLength = optPar("displayLength", __, agiBlue.displayLength); return new F1() { public String get(Page p) { try { String name = pageDisplayName(p); return ahref(agiBlue.agiBlue_pageURLWithSlice(p), htmlEncode2(shorten(displayLength, name)), "title", name); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "S name = pageDisplayName(p);\r\n ret ahref(agiBlue_pageURLWithSlice(p),\r..."; } }; } public String sliceSelector() { return htag("table", tr((!agiBlue.showGoogleLogIn ? "" : td(googleSignIn_signInButton(agiBlue.agiBlueURL() + "/google-verify", "console.log(data);", ""), "style", "padding-right: 10px;") + td(nobr(ahref("javascript:signOut()", "Sign out")), "style", "padding-right: 10px; padding-bottom: 0.15em")) + (!agiBlue.showSliceSelector ? "" : hform(td("Select reality slice: " + hselect(availableSlices(), session.selectedSlice, "name", "slice", "onchange", "this.form.submit()") + "   | " + ahref(agiBlue.agiBlueURL("/slices"), nSlices(countConcepts(Slice.class))) + " | " + ahref(agiBlue.agiBlueURL() + "/createSlice", "Create slice...")))))); } public String sliceAsHTML() { if (slice.isMainSlice()) return htmlEncode2(agiBlue.agiBlueName() + "'s main slice"); if (slice.sliceConcept == null) return "Slice ???"; return htmlEncode2("Slice " + quote(slice.sliceConcept.name)); } public Slice sliceConcept() { return slice.sliceConcept; } public String footer() { return p(small(elapsedMS_sysNow(started) + " ms")); } public String verifiedEmail() { if (session == null || !(session.user.get() instanceof GoogleUser)) return null; return ((GoogleUser) session.user.get()).googleEmail; } public boolean authed() { boolean ver = eqic(verifiedEmail(), "stefan.reich.maker.of.eye@googlemail.com"); print("Auth check " + verifiedEmail() + " -> " + ver); return ver; } public String googleSignInID() { return eqic(domain(), "botcompany.de") ? botCompanyGoogleSignInID() : agiBlueGoogleSignInID(); } public String hhtml_agiBlue(String contents) { return hhtml(hAddToHead_fast(contents, hIncludeGoogleFont("Source Sans Pro") + loadJQuery() + hmobilefix() + googleSignIn_header("", googleSignInID()) + hstylesheet("body { font-family: Source Sans Pro }"))); } public Object serveSlicesList() { String sort = getAny(params, "sort", "by"); List slices; String shown; if (eqic(sort, "name")) { slices = asList(agiBlue.idx_slicesByName.objectIterator()); shown = "sorted by name"; } else { sort = "date"; slices = asList(agiBlue.idx_slicesByModification.objectIterator()); shown = "last modified first"; } String title = agiBlueNameHTML() + " has " + nSlices(slices); PreIncLongCounter counter = new PreIncLongCounter(); return hhtml_agiBlue(hhead_title_decode(title) + hbody(hfullcenter(h1(title) + p(joinWithSpacedVBar(ahrefIf(neqic(sort, "name"), agiBlue.agiBlueURL() + "/slices" + hquery("sort", "name"), "List by name"), ahrefIf(neqic(sort, "date"), agiBlue.agiBlueURL() + "/slices" + hquery("sort", "date"), "List by date"), ahref(agiBlue.agiBlueURL() + "/createSlice", "Create slice..."))) + htmlTable2(map(slices, slice -> litorderedmap("Name", ahref(sliceHomeURL(slice), htmlEncode2(slice.name)), "ID", ahref(sliceHomeURL(slice), str(slice.globalID)), "Owner", str(slice.owner.get()))), "htmlEncode", false)))); } public Object serveUsersList() { String sort = getAny(params, "sort", "by"); List users; String shown; if (eqic(sort, "name")) users = asList(agiBlue.idx_usersByName.objectIterator()); else { sort = "seen"; users = asList(agiBlue.idx_usersBySeen.objectIterator()); } String title = agiBlueNameHTML() + " has " + nUsers(users); PreIncLongCounter counter = new PreIncLongCounter(); return hhtml_agiBlue(hhead_title_decode(title) + hbody(hfullcenter(h1(title) + p(joinWithSpacedVBar(ahrefIf(neqic(sort, "name"), agiBlue.agiBlueURL() + "/users" + hquery("sort", "name"), "List by name"), ahrefIf(neqic(sort, "seen"), agiBlue.agiBlueURL() + "/users" + hquery("sort", "seen"), "List by last seen"), ahref(agiBlue.agiBlueURL() + "/createSlice", "Create slice..."))) + htmlTable2(map(users, user -> litorderedmap("Name", ahref(userHomeURL(user), htmlEncode2(str(user))), "Last seen", renderHowLongAgo(user.lastSeen))), "htmlEncode", false)))); } public String sliceInfoHTML() { User owner = slice.sliceConcept.owner.get(); return owner == null ? "" : p("This slice is owned by " + userHTML(owner)); } public String userHomeURL(User user) { return user == null ? null : agiBlue.agiBlueURL() + "/user/" + user.globalID; } public String userHTML(User user) { return user == null ? "nobody" : ahref(userHomeURL(user), htmlEncode2(str(user))); } public String top() { return nempty(get) ? "" : hcomment("cookie: " + takeFirst(4, session.cookie)) + hSilentComputatorWithFlag("agi.blue: " + q) + p(ahref(sliceHomeURL(), hsnippetimg("#1101822", "width", 314, "height", 125, "title", "agi.blue - Wikipedia for robots"))) + h2(ahref_unstyled(sliceHomeURL(), htmlEncode2(slice.sliceConcept.name), "style", "color: yellow")) + sliceInfoHTML() + p(small(agiBlueNameHTML_boldWithSize() + (agiBlue.agiBlue_isOriginal() ? "" : " " + targetBlank("http://agi.blue", "[original]")) + " | " + ahref(agiBlue.agiBlueURL("/slices"), nSlices(countConcepts(Slice.class))) + " | " + targetBlank(progLink(), "source code") + " of this web site (" + nLines(sourceCodeLines) + ") | " + targetBlank("https://gitter.im/agi-blue/community", "sponsor https?") + " | by " + targetBlank("https://BotCompany.de", "BC") + " | " + targetBlank("http://fiverr.tinybrain.de/", "Fiverr") + " | " + targetBlank("https://discordapp.com/invite/SEAjPqk", "Discord") + " | " + targetBlank("https://www.youtube.com/watch?v=b6jtRdV3Ev8", "Video") + " | " + targetBlank("http://code.botcompany.de/1024233", "Notes") + " | " + ahref(agiBlue.agiBlueURL() + "/query", "Query"))); } public Slice createSlice(String name) { name = shorten(name, agiBlue.maxSliceNameLength); Slice slice = cnew(Slice.class, "name", name, "owner", session.user); cset(slice, "caseID", slice.defaultCaseID()); agiBlue.loadSlice(slice).initialSetup(slice.globalID); return slice; } public Object serveCheckboxes() { conceptsSortedByFieldCI_verbose = true; int showMax = 1000; Collection pages = takeFirst(showMax, conceptsSortedByFieldCI(slice.cc, Page.class, "q")); String title = "Select pages"; return hhtml_miniPage(title, h3(title) + hpostform(htmlTable2(map(pages, page -> litorderedmap("Page", hcheckbox("page_" + page.globalID()) + " " + pageToHTMLLink().get(page))), "htmlEncode", false) + h3("Add an entry to all selected pages") + p("Key: " + hinputfield("key") + " Value: " + hinputfield("value")) + p(hsubmit("Add entries")), "action", agiBlue.agiBlueURL() + "/multiAdd")); } public Object serveMultiAdd() { String key = trim(params.get("key")), value = trim(params.get("value")); if (empty(key) || empty(value)) return "Need key and value"; Matches m = new Matches(); List pages = new ArrayList(); for (String a : keys(params)) { String b = params.get(a); if (startsWith(a, "page_", m)) addIfNotNull(pages, conceptWhere(cc, Page.class, "globalID", m.rest())); } if (empty(pages)) return "No pages selected"; for (Page page : pages) agiBlue.new GetEntriesAndPost(cc).go(page, params); return "Entry added to " + nPages(pages); } public String agiBlueNameHTML() { return ahref(agiBlue.agiBlueURL(), htmlEncode2(agiBlue.agiBlueName())); } public String agiBlueNameHTML_boldWithSize() { Long size = agiBlue.sizeOnDisk.peek(); return b(agiBlueNameHTML()) + (size == null ? "" : " " + spanTitle("Size of agi.blue's database on disk", "(" + toM(size) + " MB)")); } public IF1 pageToMap(Object... __) { boolean withEntries = boolPar("withEntries", __); boolean nameOnly = eqOneOf(optPar("nameOnly", __), "1", true); if (nameOnly) return (IF1) p -> litmap("q", p.q); return (IF1) p -> { List entries = findBackRefs(p, Entry.class); return litorderedmap("q", p.q, "nEntries", l(entries), "created", p.created, "modified", p._modified, "entries", !withEntries ? null : map(entries, entryToMap(false))); }; } public IF1 entryToMap(boolean withPage) { return (IF1) e -> litorderedmap("created", e.created, "i", e.count, "key", e.key, "value", e.value, "q", withPage ? e.page.get().q : null, "signer", getString("globalID", e.signer.get())); } public IF1 sliceToMap() { return (IF1) s -> litorderedmap("created", s.created, "globalID", str(s.globalID), "name", s.name, "caseID", s.caseID); } public Object servePageToBot(Page page, Map params) { if (page == null) return serveJSON(null); params = asCIMap(params); Map map = pageToMap("withEntries", valueIs1("withEntries", params)).get(page); return serveJSON(map); } public Map availableSlices() { List slices = asList(agiBlue.idx_slicesByName.objectIterator()); return mapToOrderedMap(s -> pair(str(s.globalID), s.name + " [ID: " + s.globalID + "]"), slices); } } } public static JavaXClassLoader hotwire_makeClassLoader(List files) { ClassLoader cl = myClassLoader(); return new JavaXClassLoaderWithParent2(null, files, cl, parseClassesToShareList(classesToShare)); } public static AGIBlue agiBlue() { return agiBlue; } public static File sliceDir(Slice slice) { return programFile(slice.caseID); } public static long guessClusteredSizeOfProgramDirWithoutBackups() { return guessClusteredDirSizeWithoutBackups(programDir()); } public static String pairToUglyStringForCIComparison(Pair p) { return p == null ? null : l(p.a) + "|" + p.a + "|" + p.b; } public static GlobalID aGlobalIDObject() { return aGlobalIDObj(); } public static String uniqueFileNameUsingMD5_80_v2(String fullName) { return uniqueFileNameUsingMD5_80_v2(fullName, md5(fullName)); } public static String uniqueFileNameUsingMD5_80_v2(String fullName, String md5) { return takeFirst(80 - 33, fileNameEncode(fullName)) + " - " + md5; } public static GlobalID aGlobalIDObj() { return asGlobalID(randomID(16)); } public static long globalIDPart1(GlobalID id) { return id == null ? 0 : id.a; } public static short globalIDPart2(GlobalID id) { return id == null ? 0 : (short) id.b; } public static GlobalID toGlobalIDObj(String s) { return s == null ? null : new GlobalID(s); } public static GlobalID toGlobalIDObj(GlobalID globalID) { return globalID; } public static GlobalID globalIDFromParts(long a, short b) { GlobalID id = new GlobalID(); id.a = a; id.b = b; return id; } public static 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; } public static A cget(String field, Object c) { return cget(c, field); } public static int cset(Concept c, Object... values) { try { if (c == null) return 0; int changes = 0; values = expandParams(c.getClass(), values); warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; Field f = setOpt_findField(c.getClass(), field); if (value instanceof RC) value = c._concepts.getConcept((RC) value); value = deref(value); if (value instanceof String && l((String) value) >= concepts_internStringsLongerThan) value = intern((String) value); if (f == null) { c.fieldValues = syncMapPut2_createLinkedHashMap(c.fieldValues, assertIdentifier(field), value instanceof Concept ? c.new Ref((Concept) value) : value); c.change(); } else if (isSubtypeOf(f.getType(), Concept.Ref.class)) { ((Concept.Ref) f.get(c)).set((Concept) derefRef(value)); c.change(); ++changes; } else { Object old = f.get(c); if (neq(value, old)) { f.set(c, value); if ((f.getModifiers() & java.lang.reflect.Modifier.TRANSIENT) == 0) c.change(); ++changes; } } } return changes; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } public static void litmap_impl(Map map, Object... x) { if (x != null) for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null) map.put(x[i], x[i + 1]); } public static B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } public static B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } public static String aGlobalID() { return randomID(globalIDLength()); } public static Set synchroLinkedHashSet() { return Collections.synchronizedSet(new LinkedHashSet()); } public static File programFile(String name) { return prepareProgramFile(name); } public static File programFile(String progID, String name) { return prepareProgramFile(progID, name); } public static String or2(String a, String b) { return nempty(a) ? a : b; } public static String or2(String a, String b, String c) { return or2(or2(a, b), c); } public static Object withDBLock(Object r) { Lock __52 = db_mainConcepts().lock; lock(__52); try { return callF(r); } finally { unlock(__52); } } public static A withDBLock(F0 r) { return (A) withDBLock((Object) r); } public static Object withDBLock(Concepts concepts, Object r) { Lock __53 = concepts.lock; lock(__53); try { return callF(r); } finally { unlock(__53); } } public static A withDBLock(Concepts concepts, F0 r) { return (A) withDBLock(concepts, (Object) r); } public static A get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } public static boolean get(boolean[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : false; } public static Object get(Object o, String field) { try { if (o == null) return null; if (o instanceof Class) return get((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); Field f = getOpt_findField(o.getClass(), field); if (f != null) { f.setAccessible(true); return f.get(o); } if (o instanceof DynamicObject) return ((DynamicObject) o).fieldValues.get(field); } catch (Exception e) { throw asRuntimeException(e); } throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName()); } public static Object get_raw(String field, Object o) { return get_raw(o, field); } public static Object get_raw(Object o, String field) { try { if (o == null) return null; Field f = get_findField(o.getClass(), field); f.setAccessible(true); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } public static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); f.setAccessible(true); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } public static Field get_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } public static Field get_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } public static Object get(String field, Object o) { return get(o, field); } public static long now_virtualTime; public static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } public static List list(Class type) { return db_mainConcepts().list(type); } public static List list(Concepts concepts, Class type) { return concepts.list(type); } public static List list(String type) { return db_mainConcepts().list(type); } public static List list(Concepts concepts, String type) { return concepts.list(type); } public static String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } public static String quote(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2)); quote_impl(s, out); return out.toString(); } public static void quote_impl(String s, StringBuilder out) { out.append('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') out.append('\\').append(c); else if (c == '\r') out.append("\\r"); else if (c == '\n') out.append("\\n"); else if (c == '\0') out.append("\\0"); else out.append(c); } out.append('"'); } public static String sfu(Object o) { return structureForUser(o); } public static List tripleToList(T3 t) { return t == null ? null : ll(t.a, t.b, t.c); } public static File saveLinesAsTextFile(String fileName, Iterable lines) { try { return saveTextFile(fileName, lines(lines)); } catch (Exception __e) { throw rethrow(__e); } } public static File saveLinesAsTextFile(File fileName, Iterable lines) { return saveLinesAsTextFile(fileName.getPath(), lines); } public static RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } public static RuntimeException rethrow(String msg, Throwable t) { throw new RuntimeException(msg, t); } public static boolean empty(Collection c) { return c == null || c.isEmpty(); } public static boolean empty(CharSequence s) { return s == null || s.length() == 0; } public static boolean empty(Map map) { return map == null || map.isEmpty(); } public static boolean empty(Object[] o) { return o == null || o.length == 0; } public static boolean empty(Object o) { if (o instanceof Collection) return empty((Collection) o); if (o instanceof String) return empty((String) o); if (o instanceof Map) return empty((Map) o); if (o instanceof Object[]) return empty((Object[]) o); if (o instanceof byte[]) return empty((byte[]) o); if (o == null) return true; throw fail("unknown type for 'empty': " + getType(o)); } public static boolean empty(float[] a) { return a == null || a.length == 0; } public static boolean empty(int[] a) { return a == null || a.length == 0; } public static boolean empty(long[] a) { return a == null || a.length == 0; } public static boolean empty(byte[] a) { return a == null || a.length == 0; } public static boolean empty(MultiSet ms) { return ms == null || ms.isEmpty(); } public static boolean empty(File f) { return getFileSize(f) == 0; } public static A uniqCI_sync(final Class c, final Object... params) { return uniqCI_sync(db_mainConcepts(), c, params); } public static A uniqCI_sync(Concepts concepts, Class c, final Object... params) { return withDBLock(concepts, new F0() { public A get() { try { return uniqCI(concepts, c, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret uniqCI(concepts, c, params);"; } }); } public static List conceptsWhere(Class c, Object... params) { return findConceptsWhere(c, params); } public static List conceptsWhere(String c, Object... params) { return findConceptsWhere(c, params); } public static volatile PersistableThrowable _handleException_lastException; public static List _handleException_onException = synchroList(ll("printStackTrace2")); public static void _handleException(Throwable e) { _handleException_lastException = persistableThrowable(e); Throwable e2 = innerException(e); if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException) return; for (Object f : cloneList(_handleException_onException)) try { callF(f, e); } catch (Throwable e3) { printStackTrace2(e3); } } public static void removeAllKeysNotIn(Map a, Map b) { if (a != null) removeAllBut(a, keys(b)); } public static Set sliceDump_pageNamesIncludingKeys(File f) { Set names = ciSet(); CloseableIterableIterator it = linesFromFile(f); try { while (it.hasNext()) { try { String s = trim(it.next()); if (empty(s)) continue; if (startsWith(s, '"')) { names.add(unquote(s)); continue; } List l = optCast(List.class, safeUnstructure(s)); if (l(l) != 3) { print("Can't parse: " + s); continue; } names.add((String) second(l)); } catch (Throwable __e) { _handleException(__e); } } return names; } finally { _close(it); } } public static B getOrCreate(Map map, A key, Class c) { try { B b = map.get(key); if (b == null) map.put(key, b = c.newInstance()); return b; } catch (Exception __e) { throw rethrow(__e); } } public static B getOrCreate(Map map, A key, Object f) { try { B b = map.get(key); if (b == null) map.put(key, b = (B) callF(f)); return b; } catch (Exception __e) { throw rethrow(__e); } } public static B getOrCreate(Class c, Map map, A key) { return getOrCreate(map, key, c); } public static void logStructure(File logFile, Object o) { logQuoted(logFile, structure(o)); } public static void logStructure(String fileName, Object o) { logStructure(getProgramFile(fileName), o); } public static void logStructure(String progID, String fileName, Object o) { logStructure(getProgramFile(progID, fileName), o); } public static List ll(A... a) { ArrayList l = new ArrayList(a.length); if (a != null) for (A x : a) l.add(x); return l; } public static long sysNow() { ping(); return System.nanoTime() / 1000000; } public static int csetAll(Concept c, Object... values) { return cset(c, values); } public static int csetAll(Iterable l, Object... values) { int n = 0; for (Concept c : unnull(l)) n += cset(c, values); return n; } public static void releaseEmptyFieldValuesOfAllConcepts(Concepts cc) { for (Concept c : cc.allConcepts()) dynamicObject_releaseEmptyFieldValues(c); } public static void onConceptsChange(Runnable r) { onConceptsChange(db_mainConcepts(), r); } public static void onConceptsChange(Concepts cc, Runnable r) { cc.addConceptIndex(simpleConceptIndex(r)); cc.onAllChanged.add(r); } public static Runnable rOnceAtATimeOnly(Runnable r) { if (r == null) return null; AtomicBoolean running = new AtomicBoolean(); return new Runnable() { public void run() { try { if (!running.compareAndSet(false, true)) return; try { r.run(); } finally { running.set(false); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!running.compareAndSet(false, true)) return;\r\n try {\r\n r.run();\r\n..."; } }; } public static boolean nempty(Collection c) { return !empty(c); } public static boolean nempty(CharSequence s) { return !empty(s); } public static boolean nempty(Object[] o) { return !empty(o); } public static boolean nempty(byte[] o) { return !empty(o); } public static boolean nempty(int[] o) { return !empty(o); } public static boolean nempty(Map m) { return !empty(m); } public static boolean nempty(Iterator i) { return i != null && i.hasNext(); } public static boolean nempty(Object o) { return !empty(o); } public static A uniq(Class c, Object... params) { return uniqueConcept(c, params); } public static A uniq(Concepts cc, Class c, Object... params) { return uniqueConcept(cc, c, params); } public static void indexConceptFieldsCI(Concepts concepts, Object... params) { for (int i = 0; i < l(params); i += 2) indexConceptFieldCI(concepts, (Class) params[i], (String) params[i + 1]); } public static void indexConceptFields(Object... params) { int i = 0; Concepts concepts; if (first(params) instanceof Concepts) { concepts = (Concepts) first(params); ++i; } else concepts = db_mainConcepts(); for (; i < l(params); i += 2) indexConceptField(concepts, (Class) params[i], (String) params[i + 1]); } public static void indexSingletonConcept(Concepts cc, Class c) { indexConceptField(cc, c, "_dummy"); } public static List syncMap(Object f, Map map) { return syncMap(map, f); } public static List syncMap(Map map, Object f) { return map(cloneLinkedHashMap(map), f); } public static Map syncMap() { return synchroHashMap(); } public static TreeMap ciMap() { return caseInsensitiveMap(); } public static String trim(String s) { return s == null ? null : s.trim(); } public static String trim(StringBuilder buf) { return buf.toString().trim(); } public static String trim(StringBuffer buf) { return buf.toString().trim(); } public static volatile StringBuffer local_log = new StringBuffer(); public static volatile Appendable print_log = local_log; public static volatile int print_log_max = 1024 * 1024; public static volatile int local_log_max = 100 * 1024; public static boolean print_silent = false; public static Object print_byThread_lock = new Object(); public static volatile ThreadLocal print_byThread; public static volatile Object print_allThreads; public static volatile Object print_preprocess; public static void print() { print(""); } public static A print(String s, A o) { print((endsWithLetterOrDigit(s) ? s + ": " : s) + o); return o; } public static A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = String.valueOf(o) + "\n"; print_noNewLine(s); return o; } public static void print_noNewLine(String s) { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; print_raw(s); } public static void print_raw(String s) { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = local_log; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); System.out.print(s); } public static void print_autoRotate() { } public static List findBackRefs(Collection concepts, Class type) { IdentityHashMap l = new IdentityHashMap(); for (Concept c : concepts) if (c.backRefs != null) for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) l.put((A) r.concept(), true); return asList(keys(l)); } public static List findBackRefs(Concept c, Class type) { IdentityHashMap l = new IdentityHashMap(); if (c != null && c.backRefs != null) for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) l.put((A) r.concept(), true); return asList(keys(l)); } public static List findBackRefs(Class type, Concept c) { return findBackRefs(c, type); } public static RuntimeException fail() { throw new RuntimeException("fail"); } public static RuntimeException fail(Throwable e) { throw asRuntimeException(e); } public static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } public static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); } public static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); } public static String subBot_clientIP() { return getClientIP_subBot(); } public static A firstThat(Iterable l, Object pred) { if (l != null) for (A a : l) if (checkCondition(pred, a)) return a; return null; } public static A firstThat(Iterable l, IF1 pred) { return firstThat(l, (Object) pred); } public static A firstThat(IF1 pred, Iterable l) { return firstThat(l, pred); } public static boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } public static boolean eqic(char a, char b) { if (a == b) return true; char u1 = Character.toUpperCase(a); char u2 = Character.toUpperCase(b); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } public static boolean eq_icIf(boolean ignoreCase, String a, String b) { return ignoreCase ? eqic(a, b) : eq(a, b); } public static boolean eq(Object a, Object b) { return a == null ? b == null : a == b || b != null && a.equals(b); } public static Concept cnew(String name, Object... values) { Class cc = findClass(name); Concept c = cc != null ? nuObject(cc) : new Concept(name); csetAll(c, values); return c; } public static Concept cnew(Concepts concepts, String name, Object... values) { Class cc = findClass(name); concepts_unlisted.set(true); Concept c; try { c = cc != null ? nuObject(cc) : new Concept(name); } finally { concepts_unlisted.set(null); } concepts.register(c); csetAll(c, values); return c; } public static A cnew(Class cc, Object... values) { A c = nuObject(cc); csetAll(c, values); return c; } public static A cnew(Concepts concepts, Class cc, Object... values) { concepts_unlisted.set(true); A c; try { c = nuObject(cc); } finally { concepts_unlisted.set(null); } concepts.register(c); csetAll(c, values); return c; } public static int l(Object[] a) { return a == null ? 0 : a.length; } public static int l(boolean[] a) { return a == null ? 0 : a.length; } public static int l(byte[] a) { return a == null ? 0 : a.length; } public static int l(short[] a) { return a == null ? 0 : a.length; } public static int l(long[] a) { return a == null ? 0 : a.length; } public static int l(int[] a) { return a == null ? 0 : a.length; } public static int l(float[] a) { return a == null ? 0 : a.length; } public static int l(double[] a) { return a == null ? 0 : a.length; } public static int l(char[] a) { return a == null ? 0 : a.length; } public static int l(Collection c) { return c == null ? 0 : c.size(); } public static int l(Iterator i) { return iteratorCount_int_close(i); } public static int l(Map m) { return m == null ? 0 : m.size(); } public static int l(CharSequence s) { return s == null ? 0 : s.length(); } public static long l(File f) { return f == null ? 0 : f.length(); } public static int l(Object o) { return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size"); } public static int l(MultiSet ms) { return ms == null ? 0 : ms.size(); } public static List sortByFieldInPlace(List l, String field) { sort(l, fieldComparator(field)); return l; } public static List sortByFieldInPlace(String field, List l) { return sortByFieldInPlace(l, field); } public static void numberEntriesInConceptField(String field, List entries) { for (int i = 0; i < l(entries); i++) if (getInt(entries.get(i), field) == 0) cset(entries.get(i), field, i + 1); } public static int count(Collection l, Object o) { int count = 0; for (Object x : l) if (eq(x, o)) ++count; return count; } public static T3 t3(A a, B b, C c) { return new T3(a, b, c); } public static int countLines(String s) { return l(toLines(s)); } public static String mySource() { return loadSnippet(programID()); } public static boolean cleanUp_interruptThreads = false; public static void cleanUp(Object c) { if (c == null) 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()); } public static void cleanUp(Collection l) { if (l == null) return; for (Object c : l) cleanUp(c); l.clear(); } public static A printWithTime(A a) { print(hmsWithColons() + ": " + a); return a; } public static boolean bootstrapDataFrom(String progID) { File otherDir = javaxDataDir(progID); File myDir = programDir(); if (sameFile(otherDir, myDir)) return false; if (!directoryIsEmpty(myDir)) return false; print("Importing data from: " + progID + " to " + programID()); copyAllFilesInDirectory_rec_noOverwrite(otherDir, myDir); return true; } public static void deleteMyBackups() { deleteFiles(conceptBackupFiles(dbProgramID())); } public static void thinMyBackups() { thinAProgramsBackups(dbProgramID(), true); } public static void indexConceptField(Class c, String field) { indexConceptField(db_mainConcepts(), c, field); } public static void indexConceptField(Concepts concepts, Class c, String field) { if (!isConceptFieldIndexed(concepts, c, field)) new ConceptFieldIndex(concepts, c, field); } public static A uniq_returnIfNew(Class c, Object... params) { Pair p = uniq2(c, params); return p.b ? p.a : null; } public static PKIKeyPair agiBot_trustedKeyForMachine() { return pkiKeyPairFromTwoLineFile(agiBot_trustedKeyForMachine_file()); } public static A uniq_sync(final Class c, final Object... params) { return uniq_sync(db_mainConcepts(), c, params); } public static A uniq_sync(Concepts concepts, Class c, final Object... params) { return withDBLock(concepts, new F0() { public A get() { try { return uniq(concepts, c, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret uniq(concepts, c, params);"; } }); } public static java.util.Timer doEveryAndNow(int delay, Object r) { return doEveryStartingNow(delay, r); } public static java.util.Timer doEveryAndNow(double delay, Object r) { return doEveryStartingNow(toInt(toMS(delay)), r); } public static Runnable rWatcher(IF0 calc, Runnable r) { return new Runnable() { public A value; public void run() { A newValue = callF(calc); if (neq(value, newValue)) { value = newValue; callF(r); } } }; } public static long db_mainConceptsChangeCount() { return db_mainConcepts().xchangeCount(); } public static List sortedByField(Collection c, final String field) { List l = new ArrayList(c); sort(l, new Comparator() { public int compare(A a, A b) { return cmp(getOpt(a, field), getOpt(b, field)); } }); return l; } public static List sortedByField(String field, Collection c) { return sortedByField(c, field); } public static List sortedByCalculatedField(Iterable c, Object f) { return sortByCalculatedField(c, f); } public static List sortedByCalculatedField(Object f, Iterable c) { return sortedByCalculatedField(c, f); } public static List sortedByCalculatedField(Iterable c, IF1 f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } public static boolean amProgram(String snippetID) { return sameSnippetID(programID(), snippetID); } public static boolean agiBlueURL_noHTTPS = false; public static String agiBlueURL_url = "https://agi.blue"; public static String agiBlueURL() { return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url; } public static String prependSlash(String s) { return addSlashPrefix(s); } public static long psI(String snippetID) { return parseSnippetID(snippetID); } public static String programID() { return getProgramID(); } public static String programID(Object o) { return getProgramID(o); } public static boolean isProgramID(String snippetID) { return amProgram(snippetID); } public static String str(Object o) { return o == null ? "null" : o.toString(); } public static String str(char[] c) { return new String(c); } public static String unnull(String s) { return s == null ? "" : s; } public static Collection unnull(Collection l) { return l == null ? emptyList() : l; } public static List unnull(List l) { return l == null ? emptyList() : l; } public static Map unnull(Map l) { return l == null ? emptyMap() : l; } public static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } public static A[] unnull(A[] a) { return a == null ? (A[]) new Object[0] : a; } public static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } public static Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } public static void lock(Lock lock) { try { ping(); if (lock == null) return; try { lock.lockInterruptibly(); } catch (InterruptedException e) { print("Locking interrupted! I probably deadlocked, oops."); printStackTrace(e); rethrow(e); } ping(); } catch (Exception __e) { throw rethrow(__e); } } public static void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } public static void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } public static ReentrantLock lock() { return fairLock(); } public static A assertNotNull(A a) { assertTrue(a != null); return a; } public static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } public static void unlock(Lock lock, String msg) { if (lock == null) return; print("Unlocking: " + msg); lock.unlock(); } public static void unlock(Lock lock) { if (lock == null) return; lock.unlock(); } public static A lowestByField(Iterable l, String field) { Lowest lowest = new Lowest(); for (A a : unnull(l)) lowest.put(a, toDouble(getOpt(a, "field"))); return lowest.get(); } public static A lowestByField(String field, Iterable l) { return lowestByField(l, field); } public static Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keys(Object map) { return keys((Map) map); } public static Set keys(MultiSet ms) { return ms.keySet(); } public static Set keys(MultiMap mm) { return mm.keySet(); } public static Set keys(MultiSetMap mm) { return mm.keySet(); } public static A conceptWhere(Class c, Object... params) { return findConceptWhere(c, params); } public static A conceptWhere(Concepts cc, Class c, Object... params) { return findConceptWhere(cc, c, params); } public static A conceptWhereCI(Class c, Object... params) { return findConceptWhereCI(c, params); } public static Concept conceptWhereCI(String c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } public static A conceptWhereCI(Concepts concepts, Class c, Object... params) { return findConceptWhereCI(concepts, c, params); } public static Concept conceptWhereCI(Concepts concepts, String c, Object... params) { return findConceptWhereCI(concepts, c, params); } public static List agiBlue_parseQueryScript(String script) { return map("agiBlue_parseQueryLine", tlftj_honoringBrackets(script)); } public static Object serveJSON(Object data) { return serveJSON_shallowLineBreaks(data); } public static A getOrKeep(Map map, A a) { if (map == null) return a; A v = map.get(a); return v != null ? v : a; } public static T3 tripleMap(Object f, T3 t) { return t == null ? null : triple(callF(f, t.a), callF(f, t.b), callF(f, t.c)); } public static T3 tripleMap(T3 t, IF1 f) { return tripleMap(f, t); } public static T3 tripleMap(IF1 f, T3 t) { return t == null ? null : triple(callF(f, t.a), callF(f, t.b), callF(f, t.c)); } public static T3 tripleMap(T3 t, Object f) { return tripleMap(f, t); } public static boolean isDollarVar(String s) { return startsWith(s, '$') && isJavaIdentifierAfter(s, 1); } public static RuntimeException todo() { throw new RuntimeException("TODO"); } public static RuntimeException todo(Object msg) { throw new RuntimeException("TODO: " + msg); } public static Random random_random = new Random(); public static int random(int n) { return random(random_random, n); } public static int random(Random r, int n) { return n <= 0 ? 0 : r.nextInt(n); } public static double random(double max) { return random() * max; } public static double random() { return random_random.nextInt(100001) / 100000.0; } public static double random(double min, double max) { return min + random() * (max - min); } public static int random(int min, int max) { return min + random(max - min); } public static int random(Random r, int min, int max) { return min + random(r, max - min); } public static A random(List l) { return oneOf(l); } public static A random(Collection c) { if (c instanceof List) return random((List) c); int i = random(l(c)); return collectionGet(c, i); } public static List conceptsWhereCI(Class c, Object... params) { return findConceptsWhereCI(c, params); } public static List conceptsWhereCI(String c, Object... params) { return findConceptsWhereCI(c, params); } public static List conceptsWhereCI(Concepts concepts, Class c, Object... params) { return findConceptsWhereCI(concepts, c, params); } public static List conceptsWhereCI(Concepts concepts, String c, Object... params) { return findConceptsWhereCI(concepts, c, params); } public static List map(Iterable l, Object f) { return map(f, l); } public static List map(Object f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) x.add(callF(f, o)); return x; } public static List map(Iterable l, F1 f) { return map(f, l); } public static List map(F1 f, Iterable l) { List x = emptyList(l); if (l != null) for (A o : l) x.add(callF(f, o)); return x; } public static List map(IF1 f, Iterable l) { return map(l, f); } public static List map(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) x.add(f.get(o)); return x; } public static List map(IF1 f, A[] l) { return map(l, f); } public static List map(A[] l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) x.add(f.get(o)); return x; } public static List map(Object f, Object[] l) { return map(f, asList(l)); } public static List map(Object[] l, Object f) { return map(f, l); } public static List map(Object f, Map map) { return map(map, f); } public static List map(Map map, Object f) { List x = new ArrayList(); if (map != null) for (Object _e : map.entrySet()) { Map.Entry e = (Map.Entry) _e; x.add(callF(f, e.getKey(), e.getValue())); } return x; } public static void addIfNotNull(Collection l, A a) { if (a != null && l != null) l.add(a); } public static void addIfNotNull(MultiSet ms, A a) { if (a != null && ms != null) ms.add(a); } public static Map flexMatchDollarVarsIC_first(String pat, String input) { return grabValueAndCancel(new VF1>>() { public void get(VF1> onMatch) { try { flexMatchDollarVarsIC_iterate(pat, input, onMatch); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "flexMatchDollarVarsIC_iterate(pat, input, onMatch);"; } }); } public static String curly(String s) { return optionalCurlyBrace(s); } public static String hquery(Map params) { return htmlQuery(params); } public static String hquery(Object... data) { return htmlQuery(data); } public static A _get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static Object _get(Object o, String field) { return get(o, field); } public static Object _get(String field, Object o) { return get(o, field); } public static A _get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } public static Map mapPutOrCreate_multi(Map map, Object... keysAndValues) { for (int i = 0; i + 1 < l(keysAndValues); i += 2) { A key = (A) (keysAndValues[i]); B value = (B) (keysAndValues[i + 1]); map = mapPutOrCreate(map, key, value); } return map; } public static List sharedKeys(Map a, Map b) { List l = new ArrayList(); if (nempty(a) && nempty(b)) for (A key : cloneKeys(a)) if (b.containsKey(key)) l.add(key); return l; } public static Object first(Object list) { return first((Iterable) list); } public static A first(List list) { return empty(list) ? null : list.get(0); } public static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } public static A first(IterableIterator i) { return first((Iterator) i); } public static A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } public static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } public static Character first(String s) { return empty(s) ? null : s.charAt(0); } public static A first(Pair p) { return p == null ? null : p.a; } public static A first(T3 t) { return t == null ? null : t.a; } public static File conceptsFile(String progID) { return getProgramFile(progID, conceptsFileName()); } public static File conceptsFile() { return conceptsFile(dbProgramID()); } public static List> hotwire_classes = synchroList(); public static Class hotwireDependent(String src) { Class c = hotwire(src); makeDependent(c); return c; } public static A copyFields(Object x, A y, String... fields) { if (empty(fields)) { Map map = objectToMap(x); for (String field : map.keySet()) setOpt(y, field, map.get(field)); } else for (String field : fields) { Object o = getOpt(x, field); if (o != null) setOpt(y, field, o); } return y; } public static A copyFields(Object x, A y, Collection fields) { return copyFields(x, y, asStringArray(fields)); } public static Class mc() { return main.class; } public static String getString(Map map, Object key) { return map == null ? null : (String) map.get(key); } public static String getString(List l, int idx) { return (String) get(l, idx); } public static String getString(Object o, Object key) { if (o instanceof Map) return getString((Map) o, key); if (key instanceof String) return (String) getOpt(o, (String) key); throw fail("Not a string key: " + getClassName(key)); } public static String getString(String key, Object o) { return getString(o, (Object) key); } public static List conceptsWhereIC(Class c, Object... params) { return conceptsWhereIC(db_mainConcepts(), c, params); } public static List conceptsWhereIC(String c, Object... params) { return conceptsWhereIC(db_mainConcepts(), c, params); } public static List conceptsWhereIC(Concepts concepts, Class c, Object... params) { params = expandParams(c, params); return filterConceptsIC(concepts.list(c), params); } public static List conceptsWhereIC(Concepts concepts, String c, Object... params) { return filterConceptsIC(concepts.list(c), params); } public static Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } public static Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } public static Set asSet(Iterable l) { if (l instanceof Set) return (Set) l; HashSet set = new HashSet(); for (A o : unnull(l)) if (o != null) set.add(o); return set; } public static List ccollect(Collection c, String field) { List l = new ArrayList(); if (c != null) for (Concept a : c) l.add(cget(a, field)); return l; } public static List ccollect(String field, Collection c) { return ccollect(c, field); } public static List collect(Collection c, String field) { return collectField(c, field); } public static List collect(String field, Collection c) { return collectField(c, field); } public static boolean hasConceptWhereIC(Class c, Object... params) { return conceptWhereIC(c, params) != null; } public static A highestByField(String field, Collection l) { A best = null; Object bestValue = null; if (l != null) for (A a : l) { Object val = getOpt(a, field); if (val != null && (bestValue == null || cmp(val, bestValue) > 0)) { best = a; bestValue = val; } } return best; } public static A highestByField(Collection l, String field) { return highestByField(field, l); } public static List objectsWhereIC(Collection c, Object... data) { if (c == null) return null; List l = new ArrayList(); for (A x : c) if (checkFieldsIC(x, data)) l.add(x); return l; } public static boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } public static boolean isAGIDomain(String s) { return regexpMatchesIC("[a-z0-9-]+\\.agi\\.blue", s); } public static String ahref(String link, Object contents, Object... params) { return link == null ? str(contents) : href(link, contents, params); } public static String fixAGILink(String s) { if (!isAbsoluteURL(s)) return s; String host = hostNameFromURL(s); if (!isAGIBlueDomain(host)) return s; String sub = dropSuffixIC(theAGIBlueDomain(), host); if (l(sub) <= maximumDomainPartLength()) return s; return "http://" + theAGIBlueDomain() + hquery(mapPlus(paramsFromURL(s), "domain", host)); } public static String absoluteURL(String url) { return isAbsoluteURL(url) ? url : "http://" + url; } public static String htmlencode2(String s) { return htmlencode_noQuotes(s); } public static int shorten_default = 100; public static String shorten(String s) { return shorten(s, shorten_default); } public static String shorten(String s, int max) { return shorten(s, max, "..."); } public static String shorten(String s, int max, String shortener) { if (s == null) return ""; if (max < 0) return s; return s.length() <= max ? s : substring(s, 0, min(s.length(), max - l(shortener))) + shortener; } public static String shorten(int max, String s) { return shorten(s, max); } public static String agiBlue_linkForPhrase(String phrase, Object... additionalParams) { return agiBlueURL() + hquery(arrayPlus(additionalParams, "q", phrase)); } public static void sleepWhile(IF0 pred, Object... __) { int interval = optPar("interval", __, 50); double max = optPar("max", __, 10.0); long time = sysNow(); while (sysNow() <= time + toMS(max) && pred.get()) sleep(interval); } public static Object subBot_serve500() { return call(getMainBot(), "serve500"); } public static Object subBot_serve500(String msg) { return call(getMainBot(), "serve500", msg); } public static String domain() { return domainName(); } public static boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } public static boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } public static String dropMultipleSlashes(String s) { return regexpReplace_direct(s, "//+", "/"); } public static String subBot_query() { return (String) mapGet(subBot_getHttpFiles(), "query"); } public static String cookieFromUser() { return (String) callOpt(getBot("#1002157"), "cookieFromUser"); } public static A unlistedWithValues(Class c, Object... params) { A a = unlisted(c); cset(a, params); return a; } public static boolean isGlobalID(String s) { return possibleGlobalID(s); } public static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } public static boolean swic(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] { substring(a, l(b)) }; return true; } public static String assertGlobalID(String s) { return assertPossibleGlobalID(s); } public static Object subBot_serve404() { return call(getMainBot(), "serve404"); } public static Object subBot_serve404(String msg) { return call(getMainBot(), "serve404", msg); } public static String h3(String s, Object... params) { return tag("h3", s, params) + "\n"; } public static String classShortName(Object o) { return shortClassName(o); } public static String dropTrailingSlash(String s) { return dropSuffix("/", s); } public static A printStruct(String prefix, A a) { printStructure(prefix, a); return a; } public static A printStruct(A a) { printStructure(a); return a; } public static Payload googleVerifyUserToken2(String clientID, String token) { try { NetHttpTransport transport = new NetHttpTransport(); GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, new JacksonFactory()).setAudience(Collections.singletonList(clientID)).build(); GoogleIdToken idToken = verifier.verify(token); if (idToken != null) return idToken.getPayload(); return null; } catch (Exception __e) { throw rethrow(__e); } } public static String strOrNull(Object o) { return o == null ? null : str(o); } public static long myTranspilationDate_value = 1566066444130L; public static long myTranspilationDate() { return myTranspilationDate_value; } public static TreeSet asCISet(Iterable c) { return toCaseInsensitiveSet(c); } public static TreeSet asCISet(String... x) { return toCaseInsensitiveSet(x); } public static List nempties(Collection c) { return filterNempty(c); } public static MultiMap subBot_paramsAsMultiMap() { return decodeHQueryToMultiMap(mapGet(subBot_getHttpFiles(), "query")); } public static A firstKeyWithValue(Map map, B value) { if (map != null) for (Map.Entry e : map.entrySet()) if (eq(e.getValue(), value)) return e.getKey(); return null; } public static A firstKeyWithValue(B value, Map map) { return firstKeyWithValue(map, value); } public static String agiBlue_urlToQuery(String url) { String s = unpackAGIDomainOpt(url); if (s != null && neqic(s, "www")) return s.replace("-", " "); return url; } public static boolean neqic(String a, String b) { return !eqic(a, b); } public static boolean neqic(char a, char b) { return !eqic(a, b); } public static Pair uniqCI2_sync(Class c, final Object... params) { return uniqCI2_sync(db_mainConcepts(), c, params); } public static Pair uniqCI2_sync(Concepts cc, Class c, final Object... params) { return withDBLock(cc, new F0>() { public Pair get() { try { return uniqCI2(cc, c, params); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret uniqCI2(cc, c, params);"; } }); } public static ArrayList cloneList(Iterable l) { return l instanceof Collection ? cloneList((Collection) l) : asList(l); } public static ArrayList cloneList(Collection l) { if (l == null) return new ArrayList(); synchronized (collectionMutex(l)) { return new ArrayList(l); } } public static int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } public static int parseInt(char c) { return Integer.parseInt(str(c)); } public static String pageNav2(String baseLink, int count, int value, int step, String nVar, Object... __) { List l = new ArrayList(); baseLink += contains(baseLink, "?") ? "&" : "?" + urlencode(nVar) + "="; if (value > 0) l.add(ahref(baseLink + max(0, value - step), stringPar("leftArrow", __, htmlencode(unicode_leftPointingTriangle())))); for (int i = 0; i < count; i += step) { int n = i / step + 1; if (pageNav2_showPage(value, i, step, count)) if (value == i) l.add(b(n)); else l.add(ahref(baseLink + i, n)); } if (value + step < count) l.add(ahref(baseLink + (value + step), stringPar("rightArrow", __, htmlencode(unicode_rightPointingTriangle())))); return p("Pages: " + lines(l)); } public static boolean pageNav2_showPage(int actual, int i, int step, int count) { int diff = abs(actual - i) / step; return i == 0 || i >= (count - 1) / step * step || diff <= 10 || diff < 100 && ((i / step) % 10) == 9 || ((i / step) % 100) == 99; } public static String hform(Object contents, Object... params) { return htag("form", contents, params); } public static String b(Object contents, Object... params) { return tag("b", contents, params); } public static String htextinput(String name, Object... params) { Object value = ""; if (odd(l(params))) { value = params[0]; params = dropFirst(params); } params = html_massageAutofocusParam(params); return tag("input", "", concatArrays(new Object[] { "type", "text", "name", name, "value", value }, params)); } public static String htextinput(String name) { return htextinput(name, ""); } public static String hsubmit(String text, Object... params) { return tag("input", "", concatArrays(new Object[] { "type", "submit", "value", text }, params)); } public static String hsubmit() { return hsubmit("Submit"); } public static String h1(String s, Object... params) { return tag("h1", s, params); } public static String nPages(int n) { return n2(n, "page"); } public static String nPages(Collection l) { return nPages(l(l)); } public static int countConcepts(Concepts concepts, Class c, Object... params) { return concepts.countConcepts(c, params); } public static int countConcepts(Class c, Object... params) { return db_mainConcepts().countConcepts(c, params); } public static int countConcepts() { return db_mainConcepts().countConcepts(); } public static int countConcepts(String className) { return db_mainConcepts().countConcepts(className); } public static int countConcepts(Concepts concepts, String className) { return concepts.countConcepts(className); } public static int countConcepts(Concepts concepts) { return concepts.countConcepts(); } public static String nConnections(int n) { return n2(n, "connection"); } public static String nConnections(Collection l) { return nConnections(l(l)); } public static String p(Object contents, Object... params) { return tag("p", contents, params) + "\n"; } public static String p_nemptyLines(Iterable l) { return p(nlToBr(nemptyLines(l))); } public static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } public static List subList(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = Math.max(0, startIndex); endIndex = Math.min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return l.subList(startIndex, endIndex); } public static String hhead_title(String title) { return hhead(htitle(title)); } public static String hbody(Object contents, Object... params) { return tag("body", contents, params); } public static String hfullcenterAndTopLeft(Object contents, Object topLeft) { return tag("table", tr(td(topLeft, "align", "left", "height", "1")) + tr(td(contents, "align", "center")), "width", "100%", "height", "100%"); } public static List llNotNulls(A... a) { ArrayList l = new ArrayList(a.length); if (a != null) for (A x : a) if (x != null) l.add(x); return l; } public static boolean isSquareBracketedInt(String s) { return isSquareBracketed(s) && isInteger(deSquareBracket(s)); } public static void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } public static boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } public static boolean addAll(Collection c, B... b) { return c != null && c.addAll(Arrays.asList(b)); } public static Map addAll(Map a, Map b) { if (a != null) a.putAll(b); return a; } public static String unSquareBracket(String s) { return deSquareBracket(s); } public static List concatLists(Collection... lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Collection list : lists) if (list != null) l.addAll(list); return l; } public static int maxInt() { return maxIntValue(); } public static List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } public static List takeFirst(int n, List l) { return takeFirst(l, n); } public static String takeFirst(int n, String s) { return substring(s, 0, n); } public static String takeFirst(String s, int n) { return substring(s, 0, n); } public static List takeFirst(int n, Iterable i) { List l = new ArrayList(); Iterator it = i.iterator(); for (int _repeat_375 = 0; _repeat_375 < n; _repeat_375++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } public static Object dm_call(Object moduleOrID, String method, Object... args) { Object mod = dm_getModule(moduleOrID); if (mod == null) return null; AutoCloseable __376 = dm_enter(mod); try { return call_withVarargs(mod, method, args); } finally { _close(__376); } } public static int clipIntPlus(int a, int b) { return longToInt_clip(((long) a) + b); } public static List listMinus(Collection l, Object... stuff) { if (l == null) return null; List l2 = similarEmptyList(l); Set set = lithashset(stuff); for (Object o : l) if (!set.contains(o)) l2.add(o); return l2; } public static String htmlEncode2(String s) { return htmlencode_noQuotes(s); } public static String ahref_unstyled(String link, Object contents, Object... params) { if (link == null) return str(contents); return ahref(link, contents, paramsPlus(params, "style", unparseCSSParameter(mapPlus_noOverwrite(parseCSSParameter(stringPar("style", params)), "text-decoration", "none", "color", "inherit")))); } public static boolean cic(Collection l, String s) { return containsIgnoreCase(l, s); } public static boolean cic(String[] l, String s) { return containsIgnoreCase(l, s); } public static boolean cic(String s, char c) { return containsIgnoreCase(s, c); } public static boolean cic(String a, String b) { return containsIgnoreCase(a, b); } public static String hpostform(Object contents, Object... params) { return tag("form", contents, concatArrays(new Object[] { "method", "POST" }, params)); } public static String hinputfield(String name, Object... params) { return htextinput(name, params); } public static String p_nemptyLines_showFirst(int maxLines, Collection l) { if (l(l) <= maxLines) return p_nemptyLines(l); return p_nemptyLines(listPlus(takeFirst(maxLines, l), "...")); } public static String unicode_spacedRightPointingTriangle() { return spaced(unicode_rightPointingTriangle()); } public static String n2(long l) { return formatWithThousands(l); } public static String n2(Collection l) { return n2(l(l)); } public static String n2(double l, String singular) { return n2(l, singular, singular + "s"); } public static String n2(double l, String singular, String plural) { if (fraction(l) == 0) return n2((long) l, singular, plural); else return l + " " + plural; } public static String n2(long l, String singular, String plural) { return n_fancy2(l, singular, plural); } public static String n2(long l, String singular) { return n_fancy2(l, singular, singular + "s"); } public static String n2(Collection l, String singular) { return n2(l(l), singular); } public static String n2(Collection l, String singular, String plural) { return n_fancy2(l, singular, plural); } public static String n2(Map m, String singular, String plural) { return n_fancy2(m, singular, plural); } public static String n2(Map m, String singular) { return n2(l(m), singular); } public static String n2(Object[] a, String singular) { return n2(l(a), singular); } public static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); } public static String n2(MultiSet ms, String singular, String plural) { return n_fancy2(ms, singular, plural); } public static String hdiv(Object contents, Object... params) { return div(contents, params); } public static java.util.Timer doLater(long delay, final Object r) { ping(); final java.util.Timer timer = new java.util.Timer(); timer.schedule(timerTask(r, timer), delay); return timer; } public static java.util.Timer doLater(double delaySeconds, final Object r) { return doLater(toMS(delaySeconds), r); } public static 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); } public static void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } public static String tag(String tag) { return htag(tag); } public static String tag(String tag, Object contents, Object... params) { return htag(tag, str(contents), params); } public static String tag(String tag, StringBuilder contents, Object... params) { return htag(tag, contents, params); } public static String tag(String tag, StringBuffer contents, Object... params) { return htag(tag, contents, params); } public static String tr(Object contents) { return tag("tr", contents); } public static String td(Object contents, Object... params) { return tag("td", contents, params); } public static String iframe(String url, Object... params) { return hfulltag("iframe", "", arrayPlus(params, "src", url)); } public static Object[] wrapMapAsParams(Map map) { return empty(map) ? null : new Object[] { map }; } public static A assertNempty(A a) { return assertNempty("empty", a); } public static A assertNempty(String msg, A a) { if (empty(a)) throw fail(msg + ": " + a); return a; } public static List filter(Iterable c, Object pred) { if (pred instanceof F1) return filter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) x.add(o); return x; } public static List filter(Object pred, Iterable c) { return filter(c, pred); } public static List filter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } public static List filter(F1 pred, Iterable c) { return filter(c, pred); } public static List filter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (pred.get(o)) x.add(o); return x; } public static List filter(IF1 pred, Iterable c) { return filter(c, pred); } public static Matcher regexpIC(Pattern pat, String s) { return pat.matcher(unnull(s)); } public static Matcher regexpIC(String pat, String s) { return compileRegexpIC(pat).matcher(unnull(s)); } public static Pattern regexpIC(String pat) { return compileRegexpIC(pat); } public static boolean regexpFindIC(Pattern pat, String s) { return regexpICFind(pat, s); } public static boolean regexpFindIC(String pat, String s) { return regexpICFind(pat, s); } public static boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } public static String rtrim(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } public static String getSignerKey(String signed) { String s = fullTrimLastLine(signed); Matches m = new Matches(); if (swic_trim(s, "signer:", m)) return m.rest(); return null; } public static boolean isSignedWithKey_verbose = false; public static boolean isSignedWithKey(String signed, String key) { try { List lines = toLines(signed); if (swic(last(lines), "signer:")) popLast(lines); String sigLine = last(lines); String text = fromLines(dropLast(lines)); String sig = dropPrefixMandatory("sig: ", sigLine); return PKI.verifySignature(PKI.publicKeyFromString(key), PKI.signatureFromString(sig), toUtf8(text)); } catch (RuntimeException e) { if (isSignedWithKey_verbose) printStackTrace(e); return false; } } public static String dropLastTwoLines(String s) { return dropLastLine(dropLastLine(s)); } public static List tlft(String s) { return toLinesFullTrim(s); } public static List tlft(File f) { return toLinesFullTrim(f); } public static Map jsonDecodeMap(String s) { Object o = jsonDecode(s); if (o instanceof List && empty((List) o)) return new HashMap(); if (o instanceof Map) return (Map) o; else throw fail("Not a JSON map: " + s); } public static volatile Concepts mainConcepts; public static Concepts db_mainConcepts() { if (mainConcepts == null) { mainConcepts = new Concepts(getDBProgramID()); mainConcepts.classFinder = _defaultClassFinder(); } return mainConcepts; } public static LinkedHashMap litorderedmap(Object... x) { LinkedHashMap map = new LinkedHashMap(); litmap_impl(map, x); return map; } public static Pair pair(A a, B b) { return new Pair(a, b); } public static Pair pair(A a) { return new Pair(a, a); } public static List> multiSetTopPairs(MultiSet ms) { List> l = new ArrayList(); for (A a : ms.highestFirst()) l.add(pair(a, ms.get(a))); return l; } public static MultiSet ciMultiSet() { MultiSet ms = new MultiSet(); ms.map = ciMap(); return ms; } public static MultiSet ciMultiSet(Iterable l) { return asCIMultiSet(l); } public static Pair pairFromUglyString(String s) { if (empty(s)) return null; int i = indexOf(s, '|'); int lA = parseInt(takeFirst(s, i)); return pair(substring(s, i + 1, i + 1 + lA), substring(s, i + 1 + lA + 1)); } public static Collection distinctCIFieldValuesOfConcepts(Class c, String field) { return distinctCIFieldValuesOfConcepts(db_mainConcepts(), c, field); } public static Collection distinctCIFieldValuesOfConcepts(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getCIFieldIndex(c, field); if (index != null) return index.allValues(); Set set = ciSet(); for (A x : concepts.list(c)) set.add((String) getOpt(x, field)); return set; } public static List mapMultiSetByPopularity(MultiSet ms, F2 f) { List l = new ArrayList(); if (ms != null) for (A key : ms.highestFirst()) l.add(callF(f, key, ms.get(key))); return l; } public static List mapMultiSetByPopularity(MultiSet ms, IF2 f) { List l = new ArrayList(); if (ms != null) for (A key : ms.highestFirst()) l.add(callF(f, key, ms.get(key))); return l; } public static MultiSet distinctCIFieldValuesOfConcepts_multiSet(Class c, String field) { return distinctCIFieldValuesOfConcepts_multiSet(db_mainConcepts(), c, field); } public static MultiSet distinctCIFieldValuesOfConcepts_multiSet(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getCIFieldIndex(c, field); if (index != null) return index.allValues_multiSet(); MultiSet set = ciMultiSet(); for (A x : concepts.list(c)) set.add((String) getOpt(x, field)); return set; } public static long returnTimeFor(int n, Object f) { long time = sysNow(); for (int i = 0; i < n; i++) callF(f); return ratio(sysNow() - time, n); } public static long returnTimeFor(Runnable f) { return returnTimeFor(1, f); } public static String exceptionToStringShort(Throwable e) { lastException(e); e = getInnerException(e); String msg = hideCredentials(unnull(e.getMessage())); if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0) return baseClassName(e) + prependIfNempty(": ", msg); else return msg; } public static String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } public static String f2s(java.nio.file.Path p) { return p == null ? null : f2s(p.toFile()); } public static TreeMap litcimap(Object... x) { return litCIMap(x); } public static long freeDiskSpace() { return userDir().getUsableSpace(); } public static Map cloneMap(Map map) { if (map == null) return new HashMap(); synchronized (map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } public static String renderHowLongAgo(long timestamp) { if (timestamp == 0) return "never"; int seconds = howManySecondsAgo(timestamp); if (seconds <= 0) return "just now"; if (seconds < 60) return n2(seconds, "second") + " ago"; int minutes = iround(seconds / 60.0); if (minutes < 60) return n2(minutes, "minute") + " ago"; int hours = iround(minutes / 60.0); if (hours < 24) return n2(hours, "hour") + " ago"; int days = iround(hours / 24.0); return n2(days, "day") + " ago"; } public static long longSum(Iterable l) { long sum = 0; for (Long i : unnull(l)) if (i != null) sum += i; return sum; } public static List sortedIC(Collection l) { return sortedIgnoreCase(l); } public static List keysList(Map map) { return cloneListSynchronizingOn(keys(map), map); } public static List keysList(MultiSet ms) { return ms == null ? null : keysList(ms.map); } public static int countPred(Iterable c, Object pred) { return nfilter(c, pred); } public static int countPred(Object pred, Iterable c) { return nfilter(pred, c); } public static int countPred(Iterable c, IF1 pred) { return nfilter(c, pred); } public static Object getOpt(Object o, String field) { return getOpt_cached(o, field); } public static Object getOpt(String field, Object o) { return getOpt_cached(o, field); } public static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; f.setAccessible(true); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } public static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; f.setAccessible(true); return f.get(null); } catch (Exception __e) { throw rethrow(__e); } } public static Field getOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } public static Object vmBus_query(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); { Object __478 = pcallFAll_returnFirstNotNull(vm_busListeners_live(), msg, arg); if (__478 != null) return __478; } return pcallFAll_returnFirstNotNull(vm_busListenersByMessage_live().get(msg), msg, arg); } public static Object vmBus_query(String msg) { return vmBus_query(msg, (Object) null); } public static String yesNo(boolean b) { return yesno(b); } public static String yesNo(Boolean b) { return yesno(b); } public static Map mapToValues_ciMap(Iterable l, Object f) { return mapToValues_ciMap(f, l); } public static Map mapToValues_ciMap(Object f, Iterable l) { Map map = ciMap(); if (l != null) for (String o : l) map.put(o, callF(f, o)); return map; } public static Map words2_spaces_cached_cache = synchronizedMRUCache(defaultStringTransformerCacheSize()); public static String words2_spaces_cached(String s) { String out = words2_spaces_cached_cache.get(s); if (out == null) words2_spaces_cached_cache.put(s, out = words2_spaces(s)); return out; } public static boolean conceptsSortedByFieldCI_verbose = false; public static Collection conceptsSortedByFieldCI(Class c, String field) { return conceptsSortedByFieldCI(db_mainConcepts(), c, field); } public static Collection conceptsSortedByFieldCI(Concepts concepts, Class c, String field) { IFieldIndex index = concepts.getCIFieldIndex(c, field); if (index instanceof ConceptFieldIndexCI) return (Collection) asList(((ConceptFieldIndexCI) index).objectIterator()); if (conceptsSortedByFieldCI_verbose) print("conceptsSortedByFieldCI_verbose: Manual sort of " + c + " for " + field); return sortedByFieldIC(field, concepts.list(c)); } public static Map words2_spaces_collapse_cached_cache = synchronizedMRUCache(defaultStringTransformerCacheSize()); public static String words2_spaces_collapse_cached(String s) { String out = words2_spaces_collapse_cached_cache.get(s); if (out == null) words2_spaces_collapse_cached_cache.put(s, out = words2_spaces_collapse(s)); return out; } public static volatile boolean ping_pauseAll = false; public static int ping_sleep = 100; public static volatile boolean ping_anyActions = false; public static Map ping_actions = newWeakHashMap(); public static ThreadLocal ping_isCleanUpThread = new ThreadLocal(); public static boolean ping() { if (ping_pauseAll || ping_anyActions) ping_impl(true); return true; } public static boolean ping_impl(boolean okInCleanUp) { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get())) failIfUnlicensed(); Object action = null; synchronized (ping_actions) { if (!ping_actions.isEmpty()) { action = ping_actions.get(currentThread()); if (action instanceof Runnable) ping_actions.remove(currentThread()); if (ping_actions.isEmpty()) ping_anyActions = false; } } if (action instanceof Runnable) ((Runnable) action).run(); else if (eq(action, "cancelled")) throw fail("Thread cancelled."); } return false; } catch (Exception __e) { throw rethrow(__e); } } public static Map mapToMap(Object f, Iterable l) { Map map = new HashMap(); for (Object o : unnull(l)) { Pair p = (Pair) (callF(f, o)); map.put(p.a, p.b); } return map; } public static Map mapToMap(IF1> f, Iterable l) { Map map = new HashMap(); for (A o : unnull(l)) { Pair p = callF(f, o); map.put(p.a, p.b); } return map; } public static Map mapToMap(Iterable l, IF1> f) { return mapToMap(f, l); } public static A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } public static A optPar(ThreadLocal tl) { return optPar(tl, null); } public static Object optPar(Object[] params, String name) { return optParam(params, name); } public static Object optPar(String name, Object[] params) { return optParam(params, name); } public static Object optPar(String name, Map params) { return optParam(name, params); } public static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } public static A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } public static int max(int a, int b) { return Math.max(a, b); } public static int max(int a, int b, int c) { return max(max(a, b), c); } public static long max(int a, long b) { return Math.max((long) a, b); } public static long max(long a, long b) { return Math.max(a, b); } public static double max(int a, double b) { return Math.max((double) a, b); } public static float max(float a, float b) { return Math.max(a, b); } public static double max(double a, double b) { return Math.max(a, b); } public static int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); return x; } public static double max(double[] c) { if (c.length == 0) return Double.MIN_VALUE; double x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } public static float max(float[] c) { if (c.length == 0) return Float.MAX_VALUE; float x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } public static byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } public static short max(short[] c) { short x = -0x8000; for (short d : c) if (d > x) x = d; return x; } public static int max(int[] c) { int x = Integer.MIN_VALUE; for (int d : c) if (d > x) x = d; return x; } public static int leven_limitedIC(String left, String right, int threshold) { if (--threshold < 0) return 0; int n = l(left); int m = l(right); if (n == 0) return m <= threshold ? m : threshold + 1; if (m == 0) return n <= threshold ? n : threshold + 1; if (abs(m - n) > threshold) return threshold + 1; if (n > m) { final String tmp = left; left = right; right = tmp; n = m; m = right.length(); } int[] p = new int[n + 1]; int[] d = new int[n + 1]; int[] tempD; final int boundary = Math.min(n, threshold) + 1; for (int i = 0; i < boundary; i++) { p[i] = i; } Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE); Arrays.fill(d, Integer.MAX_VALUE); for (long _j = 1; _j <= m; _j++) { int j = (int) _j; final char rightJ = right.charAt(j - 1); d[0] = j; final int min = Math.max(1, j - threshold); final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold); if (min > max) { return threshold + 1; } if (min > 1) { d[min - 1] = Integer.MAX_VALUE; } for (int i = min; i <= max; i++) { if (equalsIgnoreCase(left.charAt(i - 1), rightJ)) { d[i] = p[i - 1]; } else { d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]); } } tempD = p; p = d; d = tempD; } if (p[n] <= threshold) { return p[n]; } return threshold + 1; } public static List keysSortedByValue(Map map) { return keysSortedByValues(map); } public static String nResults(int n) { return n2(n, "result"); } public static String nResults(Collection l) { return nResults(l(l)); } public static String htmldecode_dropAllTags(String html) { return htmldecode(dropAllTags(html)); } public static String hfullcenter(Object contents) { return tag("table", tr(td(contents, "align", "center")), "width", "100%", "height", "100%"); } public static boolean preferCached = false; public static boolean loadSnippet_debug = false; public static ThreadLocal loadSnippet_silent = new ThreadLocal(); public static int loadSnippet_timeout = 30000; public static String loadSnippet(String snippetID) { try { if (snippetID == null) return null; return loadSnippet(parseSnippetID(snippetID), preferCached); } catch (Exception __e) { throw rethrow(__e); } } public static String loadSnippet(String snippetID, boolean preferCached) throws IOException { return loadSnippet(parseSnippetID(snippetID), preferCached); } public static String loadSnippet(long snippetID) { try { return loadSnippet(snippetID, preferCached); } catch (Exception __e) { throw rethrow(__e); } } public static String loadSnippet(long snippetID, boolean preferCached) throws IOException { String text; if (isLocalSnippetID(snippetID)) return loadLocalSnippet(snippetID); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadSnippet(fsI(snippetID)); initSnippetCache(); text = DiskSnippetCache_get(snippetID); if (preferCached && text != null) return text; try { if (loadSnippet_debug && text != null) System.err.println("md5: " + md5(text)); String url = tb_mainServer() + "/getraw.php?id=" + snippetID + "&utf8=1"; if (nempty(text)) url += "&md5=" + md5(text); url += standardCredentials(); String text2 = loadSnippet_loadFromServer(url); boolean same = eq(text2, "==*#*=="); if (loadSnippet_debug) print("loadSnippet: same=" + same); if (!same) text = text2; } catch (RuntimeException e) { e.printStackTrace(); throw new IOException("Snippet #" + snippetID + " not found or not public"); } try { initSnippetCache(); DiskSnippetCache_put(snippetID, text); } catch (IOException e) { System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); } return text; } public static File DiskSnippetCache_dir; public static void initDiskSnippetCache(File dir) { DiskSnippetCache_dir = dir; dir.mkdirs(); } public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); } public static File DiskSnippetCache_getFile(long snippetID) { return new File(DiskSnippetCache_dir, "" + snippetID); } public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); } public static File DiskSnippetCache_getDir() { return DiskSnippetCache_dir; } public static void initSnippetCache() { if (DiskSnippetCache_dir == null) initDiskSnippetCache(getGlobalCache()); } public static String loadSnippet_loadFromServer(String url) { Integer oldTimeout = setThreadLocal(loadPage_forcedTimeout_byThread, loadSnippet_timeout); try { return isTrue(loadSnippet_silent.get()) ? loadPageSilently(url) : loadPage(url); } finally { loadPage_forcedTimeout_byThread.set(oldTimeout); } } public static String targetBlank(String link, Object contents, Object... params) { return hrefBlank(link, contents, params); } public static String form(Object contents, Object... params) { return hform(contents, params); } public static String htextarea(String text, Object... params) { params = html_massageAutofocusParam(params); return hopeningTag("textarea", params) + htmlencode2(text) + ""; } public static String hrefresh(String target) { return hrefresh(0, target); } public static String hrefresh(double seconds) { return hrefresh(seconds, ""); } public static String hrefresh(double seconds, String target) { return tag("meta", "", "http-equiv", "refresh", "content", iceil(seconds) + (nempty(target) ? "; url=" + target : "")); } public static String hhidden(String name, Object value, Object... params) { return tag("input", "", concatArrays(new Object[] { "type", "hidden", "name", name, "value", value }, params)); } public static String htmlEncode(String s) { return htmlencode(s); } public static void deleteConcepts(List conceptsOrIDs) { db_mainConcepts().deleteConcepts(conceptsOrIDs); } public static List deleteConcepts(Class c, Object... params) { List l = findConceptsWhere(c, params); deleteConcepts(l); return l; } public static List cdelete(Class c, Object... params) { return deleteConcepts(c, params); } public static void cdelete(Concept c) { deleteConcept(c); } public static boolean dirExists(String path) { return path != null && new File(path).isDirectory(); } public static boolean dirExists(File f) { return f != null && f.isDirectory(); } public static void moveDirectory(File a, File b) { moveFile(a, b); } public static Object serveText(Object s) { return call(getMainBot(), "serveByteArray", toUtf8(str(s)), "text/plain; charset=utf8"); } public static Object subBot_serve403() { return call(getMainBot(), "serve403"); } public static Object subBot_serve403(String msg) { return call(getMainBot(), "serve403", msg); } public static String htag(String tag) { return htag(tag, ""); } public static 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 + ""; } public static String googleSignIn_signInButton(String verifyURL, String onSuccess, String onSignOut) { return "
\r\n \r\n ".replace("$VERIFYURL", verifyURL).replace("$ONSUCCESS", onSuccess).replace("$ONSIGNOUT", onSignOut); } public static String nobr(Object contents) { return tag("nobr", contents); } public static String hselect(Map map, Object... params) { StringBuilder buf = new StringBuilder(); String selected = null; if (odd(l(params))) { selected = str(first(params)); params = dropFirst(params); } int i = indexOf(params, "allowEmpty"); if (even(i)) { buf.append("\n"); params[i] = params[i + 1] = null; } if (nempty(map)) for (Object key : keys(map)) { Object value = map.get(key); String k = str(key); buf.append(tag("option", htmlencode(str(or(value, ""))), "value", k, "selected", eq(selected, k) ? "selected" : null)).append("\n"); } return tag("select", buf, params) + "\n"; } public static String nSlices(long n) { return n2(n, "slice"); } public static String nSlices(Collection l) { return nSlices(l(l)); } public static String small(Object contents, Object... params) { return tag("small", contents, params); } public static long elapsedMS_sysNow(long time) { return elapsedMS(time); } public static String botCompanyGoogleSignInID() { return "709303807085-rvu63dqa5hjcii6h0j70lhn7me27cegc.apps.googleusercontent.com"; } public static String agiBlueGoogleSignInID() { return "709303807085-l19k12l095cl4c0llu4p6fl1r0phnnki.apps.googleusercontent.com"; } public static String hhtml(Object contents) { return containerTag("html", contents); } public static String hAddToHead_fast(String html, String tag) { int idx = indexOfIC(html, ""); if (idx < 0) return tag + html; return takeFirst(html, idx) + tag + substring(html, idx); } public static String hIncludeGoogleFont(String fontFamily) { return htag("link", "", "href", "https://fonts.googleapis.com/css?family=" + urlencode(fontFamily) + "&display=swap", "rel", "stylesheet"); } public static String loadJQuery() { return ""; } public static String hmobilefix() { return ""; } public static String hmobilefix(String html) { return hAddToHead(html, hmobilefix()); } public static String googleSignIn_header() { return googleSignIn_header(""); } public static String googleSignIn_header(String onLoad) { return googleSignIn_header(onLoad, botCompanyGoogleSignInID()); } public static String googleSignIn_header(String onLoad, String clientID) { return "\r\n ".replace("$PARAM", nempty(onLoad) ? "?onload=" + urlencode(onLoad) : "").replace("$CLIENTID", clientID); } public static String hstylesheet(Object contents) { return hcss(contents); } public static B getAny(Map map, A... keys) { for (A a : unnull(keys)) { B b = map.get(a); if (b != null) return b; } return null; } public static
ArrayList asList(A[] a) { return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a)); } public static ArrayList asList(int[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (int i : a) l.add(i); return l; } public static ArrayList asList(float[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (float i : a) l.add(i); return l; } public static 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; } public static ArrayList asList(Producer p) { ArrayList l = new ArrayList(); A a; if (p != null) while ((a = p.next()) != null) l.add(a); return l; } public static ArrayList asList(Enumeration e) { ArrayList l = new ArrayList(); if (e != null) while (e.hasMoreElements()) l.add(e.nextElement()); return l; } public static String hhead_title_decode(String title) { return hhead_title(htmldecode_dropAllTags(title)); } public static String joinWithSpacedVBar(Iterable l) { return joinWithVBar(l); } public static String joinWithSpacedVBar(String... l) { return joinWithSpacedVBar(asList(l)); } public static String ahrefIf(boolean condition, String link, Object contents, Object... params) { return !condition ? str(contents) : ahref(link, contents, params); } public static ThreadLocal htmlTable2_cellEncoder = new ThreadLocal(); public static String htmlTable2(Object data, Object... __) { boolean htmlEncode = optPar("htmlEncode", __, true); boolean useBr = boolPar("useBr", __); Map paramsByColName = (Map) (optPar("paramsByColName", __)); Object[] tdParams = (Object[]) (optPar("tdParams", __)); Map replaceHeaders = (Map) (optPar("replaceHeaders", __)); List> rows = new ArrayList(); List cols = new ArrayList(); if (data instanceof List) { for (Object x : (List) data) { try { rows.add(dataToTable_makeRow(x, cols)); } catch (Throwable __e) { _handleException(__e); } } } else if (data instanceof Map) { Map map = (Map) data; for (Object key : map.keySet()) { Object value = map.get(key); rows.add(litlist(structureOrText(key), structureOrText(value))); } } else print("Unknown data type: " + data); int w = 0; for (List row : rows) w = max(w, l(row)); StringBuilder buf = new StringBuilder(); buf.append(hopeningtag("table", paramsPlus((Object[]) optPar("tableParams", __), "border", html_valueLessParam())) + "\n"); buf.append("\n"); for (String cell : padList(cols, w, "?")) buf.append(" " + htmlTable2_encodeCell(getOrKeep(replaceHeaders, cell), htmlEncode, useBr) + "\n"); buf.append("\n"); for (List row : rows) { buf.append("\n"); int i = 0; for (String cell : padList(row, w, "")) { String col = get(cols, i++); Object[] params = paramsPlus(tdParams, mapGet(paramsByColName, col)); buf.append(" " + tag("td", htmlTable2_encodeCell(cell, htmlEncode, useBr), params) + "\n"); } buf.append("\n"); } buf.append("\n"); return buf.toString(); } public static String htmlTable2_encodeCell(String cell, boolean useHtmlEncode, boolean useBr) { if (htmlTable2_cellEncoder.get() != null) return (String) callF(htmlTable2_cellEncoder.get(), cell); if (useHtmlEncode) cell = htmlEncode2(cell); if (useBr) cell = nlToBr(cell); return cell; } public static String nUsers(long n) { return n2(n, "user"); } public static String nUsers(Collection l) { return nUsers(l(l)); } public static String hcomment(String text) { return ""; } public static String hSilentComputatorWithFlag(String flag) { return hSilentComputator(hSilentComputator_defaultURI(), flag); } public static String hsnippetimg(String imageID, Object... params) { return himg(snippetImageLink(imageID), params); } public static String h2(String s, Object... params) { return tag("h2", s, params); } public static String progLink(String id) { return "http://tinybrain.de/" + parseSnippetID(id); } public static String progLink() { return progLink(programID()); } public static String nLines(int n) { return n2(n, "line"); } public static String nLines(Collection l) { return nLines(l(l)); } public static String hcheckbox(String name, boolean checked, Object... params) { return tag("input", "", arrayPlus(params, "type", "checkbox", "name", name, checked ? "checked" : null, "1")); } public static String hcheckbox(String name) { return hcheckbox(name, false); } public static boolean startsWith(String a, String b) { return a != null && a.startsWith(b); } public static boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } public static boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; m.m = new String[] { substring(a, strL(b)) }; return true; } public static boolean startsWith(List a, List b) { if (a == null || listL(b) > listL(a)) return false; for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i))) return false; return true; } public static String spanTitle(String title, Object contents) { return span(contents, "title", title); } public static long toM(long l) { return (l + 1024 * 1024 - 1) / (1024 * 1024); } public static String toM(long l, int digits) { return formatDouble(toM_double(l), digits); } public static boolean boolPar(ThreadLocal tl) { return boolOptParam(tl); } public static boolean boolPar(Object[] __, String name) { return boolOptParam(__, name); } public static boolean boolPar(String name, Object[] __) { return boolOptParam(__, name); } public static boolean boolPar(String name, Map __) { return boolOptParam(name, __); } public static boolean boolPar(String name, Object[] params, boolean defaultValue) { return optParam(params, name, defaultValue); } public static boolean eqOneOf(Object o, Object... l) { for (Object x : l) if (eq(o, x)) return true; return false; } public static TreeMap asCIMap(Map map) { return asCaseInsensitiveMap(map); } public static boolean valueIs1(String key, Map map) { return eq("1", mapGet(map, key)); } public static Map mapToOrderedMap(Object f, Iterable l) { LinkedHashMap map = new LinkedHashMap(); for (Object o : unnull(l)) { Pair p = (Pair) (callF(f, o)); map.put(p.a, p.b); } return map; } public static Map mapToOrderedMap(IF1> f, Iterable l) { LinkedHashMap map = new LinkedHashMap(); for (A o : unnull(l)) { Pair p = callF(f, o); map.put(p.a, p.b); } return map; } public static ClassLoader myClassLoader() { return _getClass(mc()).getClassLoader(); } public static List parseClassesToShareList(String s) { return onlyClassNamesThatExist(prependAll("main$", identifiersOnly(javaTokC(s)))); } public static Throwable printStackTrace2(Throwable e) { print(getStackTrace2(e)); return e; } public static void printStackTrace2() { printStackTrace2(new Throwable()); } public static void printStackTrace2(String msg) { printStackTrace2(new Throwable(msg)); } public static long guessClusteredDirSizeWithoutBackups(File dir) { return guessClusteredDirSize(dir, "pred", new F1() { public Object get(File f) { try { return !eqicOneOf(f.getName(), "backup", "backups"); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "!eqicOneOf(f.getName(), \"backup\", \"backups\")"; } }); } public static File programDir_mine; public static File programDir() { return programDir(getProgramID()); } public static 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; } public static File programDir(String snippetID, String subPath) { return new File(programDir(snippetID), subPath); } public static String md5(String text) { try { if (text == null) return "-"; return bytesToHex(md5_impl(toUtf8(text))); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(byte[] data) { if (data == null) return "-"; return bytesToHex(md5_impl(data)); } public static byte[] md5_impl(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (Exception __e) { throw rethrow(__e); } } public static String md5(File file) { return md5OfFile(file); } public static String fileNameEncode_safeChars = " ()[]#,!"; public static String fileNameEncode(String s) { StringBuilder buf = new StringBuilder(); int n = l(s); for (int i = 0; i < n; i++) { char c = s.charAt(i); if (contains(fileNameEncode_safeChars, c)) buf.append(c); else buf.append(urlencode(str(c))); } return str(buf); } public static GlobalID asGlobalID(String id) { return id == null ? null : new GlobalID(id); } public static int randomID_defaultLength = 12; public static String randomID(int length) { return makeRandomID(length); } public static String randomID(Random r, int length) { return makeRandomID(r, length); } public static String randomID() { return randomID(randomID_defaultLength); } public static String randomID(Random r) { return randomID(r, randomID_defaultLength); } public static Object[] expandParams(Class c, Object[] params) { if (l(params) == 1) params = new Object[] { singleFieldName(c), params[0] }; else warnIfOddCount(params); return params; } public static void warnIfOddCount(Object... list) { if (odd(l(list))) printStackTrace("Odd list size: " + list); } public static Field setOpt_findField(Class c, String field) { HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map.get(field); } public static void setOpt(Object o, String field, Object value) { try { if (o == null) return; Class c = o.getClass(); HashMap map; if (getOpt_cache == null) map = getOpt_makeCache(c); else synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) { setOpt((Class) o, field, value); return; } setOpt_raw(o, field, value); return; } Field f = map.get(field); if (f != null) smartSet(f, o, value); } catch (Exception __e) { throw rethrow(__e); } } public static void setOpt(Class c, String field, Object value) { if (c == null) return; try { Field f = setOpt_findStaticField(c, field); if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } public static Field setOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { f.setAccessible(true); return f; } _c = _c.getSuperclass(); } while (_c != null); return null; } public static Object deref(Object o) { if (o instanceof Derefable) o = ((Derefable) o).get(); return o; } public static String intern(String s) { return fastIntern(s); } public static LinkedHashMap syncMapPut2_createLinkedHashMap(LinkedHashMap map, A key, B value) { if (map != null && key != null) if (value != null) { if (map == null) map = new LinkedHashMap(); synchronized (collectionMutex(map)) { map.put(key, value); } } else synchronized (collectionMutex(map)) { map.remove(key); } return map; } public static String assertIdentifier(String s) { return assertIsIdentifier(s); } public static String assertIdentifier(String msg, String s) { return assertIsIdentifier(msg, s); } public static boolean isSubtypeOf(Class a, Class b) { return b.isAssignableFrom(a); } public static Object derefRef(Object o) { if (o instanceof Concept.Ref) o = ((Concept.Ref) o).get(); return o; } public static boolean neq(Object a, Object b) { return !eq(a, b); } public static int globalIDLength() { return 16; } public static File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } public static File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } public static Map> callF_cache = newDangerousWeakHashMap(); public static A callF(F0 f) { return f == null ? null : f.get(); } public static B callF(F1 f, A a) { return f == null ? null : f.get(a); } public static A callF(IF0 f) { return f == null ? null : f.get(); } public static B callF(IF1 f, A a) { return f == null ? null : f.get(a); } public static C callF(F2 f, A a, B b) { return f == null ? null : f.get(a, b); } public static C callF(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } public static void callF(VF1 f, A a) { if (f != null) f.get(a); } public static Object callF(Object f, Object... args) { try { if (f instanceof String) return callMC((String) f, args); if (f instanceof Runnable) { ((Runnable) f).run(); return null; } if (f == null) return null; Class c = f.getClass(); ArrayList methods; synchronized (callF_cache) { methods = callF_cache.get(c); if (methods == null) methods = callF_makeCache(c); } int n = l(methods); if (n == 0) { throw fail("No get method in " + getClassName(c)); } if (n == 1) return invokeMethod(methods.get(0), f, args); for (int i = 0; i < n; i++) { Method m = methods.get(i); if (call_checkArgs(m, args, false)) return invokeMethod(m, f, args); } throw fail("No matching get method in " + getClassName(c)); } catch (Exception __e) { throw rethrow(__e); } } public static ArrayList callF_makeCache(Class c) { ArrayList l = new ArrayList(); Class _c = c; do { for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) { m.setAccessible(true); l.add(m); } if (!l.isEmpty()) break; _c = _c.getSuperclass(); } while (_c != null); callF_cache.put(c, l); return l; } public static Field getOpt_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } public static RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } public static String structureForUser(Object o) { return beautifyStructure(struct_noStringSharing(o)); } public static File saveTextFile(String fileName, String contents) throws IOException { CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)"); try { File file = new File(fileName); mkdirsForFile(file); String tempFileName = fileName + "_temp"; File tempFile = new File(tempFileName); if (contents != null) { if (tempFile.exists()) try { String saveName = tempFileName + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); vmBus_send("wroteFile", file); return file; } finally { action.done(); } } public static File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } public static String lines(Iterable lines) { return fromLines(lines); } public static String lines(Object[] lines) { return fromLines(asList(lines)); } public static List lines(String s) { return toLines(s); } public static void _handleError(Error e) { call(javax(), "_handleError", e); } public static String getType(Object o) { return getClassName(o); } public static long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } public static long getFileSize(File f) { return f == null ? 0 : f.length(); } public static A uniqCI(Class c, Object... params) { return uniqueConcept(db_mainConcepts(), c, params); } public static A uniqCI(Concepts cc, Class c, Object... params) { params = expandParams(c, params); A x = findConceptWhereCI(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); } return x; } public static List findConceptsWhere(Class c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } public static List findConceptsWhere(String c, Object... params) { return findConceptsWhere(db_mainConcepts(), c, params); } public static List findConceptsWhere(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) { List rawList = index.getAll(params[i + 1]); params = dropEntryFromParams(params, i); if (params == null) return rawList; List l = new ArrayList(); for (A x : rawList) if (checkConceptFields(x, params)) l.add(x); return l; } } return filterConcepts(concepts.list(c), params); } public static List findConceptsWhere(Concepts concepts, String c, Object... params) { return filterConcepts(concepts.list(c), params); } public static List synchroList() { return Collections.synchronizedList(new ArrayList()); } public static List synchroList(List l) { return Collections.synchronizedList(l); } public static PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } public static Throwable innerException(Throwable e) { return getInnerException(e); } public static void removeAllBut(Set a, Collection b) { if (a != null) for (Iterator it = a.iterator(); it.hasNext(); ) if (!contains(b, it.next())) it.remove(); } public static void removeAllBut(Map a, Collection b) { if (a != null) removeAllBut(a.keySet(), b); } public static TreeSet ciSet() { return caseInsensitiveSet(); } public static CloseableIterableIterator linesFromFile(File f) { try { if (!f.exists()) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f))); return linesFromReader(utf8bufferedReader(f)); } catch (Exception __e) { throw rethrow(__e); } } public static CloseableIterableIterator linesFromFile(String path) { return linesFromFile(newFile(path)); } public static String unquote(String s) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); StringBuilder sb = new StringBuilder(l - 1); for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } sb.append((char) Integer.parseInt(code, 8)); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); sb.append(Character.toChars(code)); i += 5; continue; default: ch = nextChar; } i++; } sb.append(ch); } return sb.toString(); } } return s; } public static A optCast(Class c, Object o) { return isInstance(c, o) ? (A) o : null; } public static Object safeUnstructure(String s) { return unstructure(s, true); } public static A second(List l) { return get(l, 1); } public static A second(Iterable l) { if (l == null) return null; Iterator it = iterator(l); if (!it.hasNext()) return null; it.next(); return it.hasNext() ? it.next() : null; } public static A second(A[] bla) { return bla == null || bla.length <= 1 ? null : bla[1]; } public static B second(Pair p) { return p == null ? null : p.b; } public static B second(T3 t) { return t == null ? null : t.b; } public static A second(Producer p) { if (p == null) return null; if (p.next() == null) return null; return p.next(); } public static void _close(AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { if (c instanceof javax.imageio.stream.ImageOutputStream) return; else throw rethrow(e); } } public static void logQuoted(String logFile, String line) { logQuoted(getProgramFile(logFile), line); } public static void logQuoted(File logFile, String line) { appendToFile(logFile, quote(line) + "\n"); } public static boolean structure_showTiming, structure_checkTokenCount; public static String structure(Object o) { return structure(o, new structure_Data()); } public static String structure(Object o, structure_Data d) { StringWriter sw = new StringWriter(); d.out = new PrintWriter(sw); structure_go(o, d); String s = str(sw); if (structure_checkTokenCount) { print("token count=" + d.n); assertEquals("token count", l(javaTokC(s)), d.n); } return s; } public static void structure_go(Object o, structure_Data d) { structure_1(o, d); while (nempty(d.stack)) popLast(d.stack).run(); } public static void structureToPrintWriter(Object o, PrintWriter out) { structure_Data d = new structure_Data(); d.out = out; structure_go(o, d); } public static boolean structure_allowShortening = false; public static class structure_Data { public PrintWriter out; public int stringSizeLimit; public int shareStringsLongerThan = 20; public boolean noStringSharing = false; public IdentityHashMap seen = new IdentityHashMap(); public HashMap strings = new HashMap(); public HashSet concepts = new HashSet(); public HashMap> fieldsByClass = new HashMap(); public HashMap persistenceInfo = new HashMap(); public int n; public List stack = new ArrayList(); public structure_Data append(String token) { out.print(token); ++n; return this; } public structure_Data append(int i) { out.print(i); ++n; return this; } public structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; } public structure_Data app(String token) { out.print(token); return this; } public structure_Data app(int i) { out.print(i); return this; } } public static void structure_1(final Object o, final structure_Data d) { try { if (o == null) { d.append("null"); return; } Class c = o.getClass(); boolean concept = false; concept = o instanceof Concept; List lFields = d.fieldsByClass.get(c); if (lFields == null) { if (o instanceof Number) { PrintWriter out = d.out; if (o instanceof Integer) { int i = ((Integer) o).intValue(); out.print(i); d.n += i < 0 ? 2 : 1; return; } if (o instanceof Long) { long l = ((Long) o).longValue(); out.print(l); out.print("L"); d.n += l < 0 ? 2 : 1; return; } if (o instanceof Short) { short s = ((Short) o).shortValue(); d.append("sh "); out.print(s); d.n += s < 0 ? 2 : 1; return; } if (o instanceof Float) { d.append("fl ", 2); quoteToPrintWriter(str(o), out); return; } if (o instanceof Double) { d.append("d(", 3); quoteToPrintWriter(str(o), out); d.append(")"); return; } if (o instanceof BigInteger) { out.print("bigint("); out.print(o); out.print(")"); d.n += ((BigInteger) o).signum() < 0 ? 5 : 4; return; } } if (o instanceof Boolean) { d.append(((Boolean) o).booleanValue() ? "t" : "f"); return; } if (o instanceof Character) { d.append(quoteCharacter((Character) o)); return; } if (o instanceof File) { d.append("File ").append(quote(((File) o).getPath())); return; } Integer ref = d.seen.get(o); if (o instanceof String && ref == null) ref = d.strings.get((String) o); if (ref != null) { d.append("t").app(ref); return; } if (!(o instanceof String)) d.seen.put(o, d.n); else { String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o; if (!d.noStringSharing) { if (d.shareStringsLongerThan == Integer.MAX_VALUE) d.seen.put(o, d.n); if (l(s) >= d.shareStringsLongerThan) d.strings.put(s, d.n); } quoteToPrintWriter(s, d.out); d.n++; return; } if (o instanceof Set) { if (((Set) o) instanceof TreeSet) { d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset"); structure_1(new ArrayList(((Set) o)), d); return; } d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset"); structure_1(new ArrayList(((Set) o)), d); return; } String name = c.getName(); if (o instanceof Collection && !startsWith(name, "main$")) { if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) { if (unwrapSynchronizedList(((List) o)) instanceof LinkedList) d.append("syncLL"); else d.append("sync"); } else if (name.equals("java.util.LinkedList")) d.append("ll"); d.append("["); final int l = d.n; final Iterator it = ((Collection) o).iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) d.append("]"); else { d.stack.add(this); if (d.n != l) d.append(", "); structure_1(it.next(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta..."; } }); return; } if (o instanceof Map && !startsWith(name, "main$")) { if (o instanceof LinkedHashMap) d.append("lhm"); else if (o instanceof HashMap) d.append("hm"); else if (o instanceof TreeMap) d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm"); else if (name.equals("java.util.Collections$SynchronizedMap")) d.append("sync"); else if (name.equals("java.util.Collections$SynchronizedSortedMap")) { d.append("sync tm", 2); } d.append("{"); final int l = d.n; final Iterator it = ((Map) o).entrySet().iterator(); d.stack.add(new Runnable() { public boolean v = false; public Map.Entry e; public void run() { if (v) { d.append("="); v = false; d.stack.add(this); structure_1(e.getValue(), d); } else { if (!it.hasNext()) d.append("}"); else { e = (Map.Entry) it.next(); v = true; d.stack.add(this); if (d.n != l) d.append(", "); structure_1(e.getKey(), d); } } } }); return; } if (c.isArray()) { if (o instanceof byte[]) { d.append("ba ").append(quote(bytesToHex((byte[]) o))); return; } final int n = Array.getLength(o); if (o instanceof boolean[]) { String hex = boolArrayToHex((boolean[]) o); int i = l(hex); while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2; d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i))); return; } String atype = "array", sep = ", "; if (o instanceof int[]) { atype = "intarray"; sep = " "; } d.append(atype).append("{"); d.stack.add(new Runnable() { public int i; public void run() { if (i >= n) d.append("}"); else { d.stack.add(this); if (i > 0) d.append(", "); structure_1(Array.get(o, i++), d); } } }); return; } if (o instanceof Class) { d.append("class(", 2).append(quote(((Class) o).getName())).append(")"); return; } if (o instanceof Throwable) { d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")"); return; } if (o instanceof BitSet) { BitSet bs = (BitSet) o; d.append("bitset{", 2); int l = d.n; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { if (d.n != l) d.append(", "); d.append(i); } d.append("}"); return; } if (name.startsWith("java.") || name.startsWith("javax.")) { d.append("j ").append(quote(str(o))); return; } String dynName = shortDynamicClassName(o); if (concept && !d.concepts.contains(dynName)) { d.concepts.add(dynName); d.append("c "); } TreeSet fields = new TreeSet(new Comparator() { public int compare(Field a, Field b) { return stdcompare(a.getName(), b.getName()); } }); Class cc = c; while (cc != Object.class) { for (Field field : getDeclaredFields_cached(cc)) { String fieldName = field.getName(); if (fieldName.equals("_persistenceInfo")) d.persistenceInfo.put(c, field); if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) continue; fields.add(field); } cc = cc.getSuperclass(); } lFields = asList(fields); for (int i = 0; i < l(lFields); i++) { Field f = lFields.get(i); if (f.getName().equals("this$1")) { lFields.remove(i); lFields.add(0, f); break; } } d.fieldsByClass.put(c, lFields); } else { Integer ref = d.seen.get(o); if (ref != null) { d.append("t").app(ref); return; } d.seen.put(o, d.n); } Field persistenceInfoField = (Field) (d.persistenceInfo.get(c)); Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o); LinkedHashMap fv = new LinkedHashMap(); for (Field f : lFields) { Object value; try { value = f.get(o); } catch (Exception e) { value = "?"; } if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) fv.put(f.getName(), value); } String name = c.getName(); String shortName = dropPrefix("main$", name); if (startsWithDigit(shortName)) shortName = name; if (concept && eq(fv.get("className"), shortName)) fv.remove("className"); if (o instanceof DynamicObject) { putAll(fv, (Map) fv.get("fieldValues")); fv.remove("fieldValues"); shortName = shortDynamicClassName(o); fv.remove("className"); } String singleField = fv.size() == 1 ? first(fv.keySet()) : null; d.append(shortName); final int l = d.n; final Iterator it = fv.entrySet().iterator(); d.stack.add(new Runnable() { public void run() { try { if (!it.hasNext()) { if (d.n != l) d.append(")"); } else { Map.Entry e = (Map.Entry) it.next(); d.append(d.n == l ? "(" : ", "); d.append((String) e.getKey()).append("="); d.stack.add(this); structure_1(e.getValue(), d); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else..."; } }); } catch (Exception __e) { throw rethrow(__e); } } public static File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } public static File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } public static void dynamicObject_releaseEmptyFieldValues(DynamicObject o) { if (o != null && o.fieldValues != null && empty(o.fieldValues)) o.fieldValues = null; } public static IConceptIndex simpleConceptIndex(final Runnable r) { return new IConceptIndex() { public void update(Concept c) { pcallF(r); } public void remove(Concept c) { pcallF(r); } }; } public static A uniqueConcept(Class c, Object... params) { return uniqueConcept(db_mainConcepts(), c, params); } public static A uniqueConcept(Concepts cc, Class c, Object... params) { params = expandParams(c, params); A x = findConceptWhere(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); } return x; } public static ConceptFieldIndexCI indexConceptFieldCI(Class c, String field) { return indexConceptFieldCI(db_mainConcepts(), c, field); } public static ConceptFieldIndexCI indexConceptFieldCI(Concepts concepts, Class c, String field) { ConceptFieldIndexCI idx = getConceptFieldCIIndex(concepts, c, field); return idx != null ? idx : new ConceptFieldIndexCI(concepts, c, field); } public static LinkedHashMap cloneLinkedHashMap(Map map) { return map == null ? new LinkedHashMap() : new LinkedHashMap(map); } public static Map synchroHashMap() { return Collections.synchronizedMap(new HashMap()); } public static TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } public static boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1)); } public static void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } public static Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } public static A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } public static A getThreadLocal(ThreadLocal tl, A defaultValue) { return or(getThreadLocal(tl), defaultValue); } public static ThreadLocal print_byThread_dontCreate() { return print_byThread; } public static boolean isFalse(Object o) { return eq(false, o); } public static String fixNewLines(String s) { int i = indexOf(s, '\r'); if (i < 0) return s; int l = s.length(); StringBuilder out = new StringBuilder(l); out.append(s, 0, i); for (; i < l; i++) { char c = s.charAt(i); if (c != '\r') out.append(c); else { out.append('\n'); if (i + 1 < l && s.charAt(i + 1) == '\n') ++i; } } return out.toString(); } public static void print_append(Appendable buf, String s, int max) { try { synchronized (buf) { buf.append(s); if (buf instanceof StringBuffer) rotateStringBuffer(((StringBuffer) buf), max); else if (buf instanceof StringBuilder) rotateStringBuilder(((StringBuilder) buf), max); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean instanceOf(Object o, String className) { if (o == null) return false; String c = o.getClass().getName(); return eq(c, className) || eq(c, "main$" + className); } public static boolean instanceOf(Object o, Class c) { if (c == null) return false; return c.isInstance(o); } public static String getClientIP_subBot() { Object session = call(getMainBot(), "getSession"); Map headers = (Map) (call(session, "getHeaders")); return getClientIPFromHeaders(headers); } public static boolean checkCondition(Object condition, Object... args) { return isTrue(callF(condition, args)); } public static boolean checkCondition(IF1 condition, A arg) { return isTrue(callF(condition, arg)); } public static String asString(Object o) { return o == null ? null : o.toString(); } public static HashMap findClass_cache = new HashMap(); public static Class findClass(String name) { synchronized (findClass_cache) { if (findClass_cache.containsKey(name)) return findClass_cache.get(name); if (!isJavaIdentifier(name)) return null; Class c; try { c = Class.forName("main$" + name); } catch (ClassNotFoundException e) { c = null; } findClass_cache.put(name, c); return c; } } public static Object nuObject(String className, Object... args) { try { return nuObject(classForName(className), args); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObject(Class c, Object... args) { try { if (args.length == 0) return nuObjectWithoutArguments(c); Constructor m = nuObject_findConstructor(c, args); m.setAccessible(true); return (A) m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : "")); } public static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } public static int iteratorCount_int_close(Iterator i) { try { int n = 0; if (i != null) while (i.hasNext()) { i.next(); ++n; } if (i instanceof AutoCloseable) ((AutoCloseable) i).close(); return n; } catch (Exception __e) { throw rethrow(__e); } } public static Object call(Object o) { return callF(o); } public static Object call(Object o, String method, String[] arg) { return call(o, method, new Object[] { arg }); } public static Object call(Object o, String method, Object... args) { return call_withVarargs(o, method, args); } public static void sort(T[] a, Comparator c) { Arrays.sort(a, c); } public static void sort(T[] a) { Arrays.sort(a); } public static void sort(List a, Comparator c) { Collections.sort(a, c); } public static void sort(List a) { Collections.sort(a); } public static Comparator fieldComparator(final String field) { return new Comparator() { public int compare(A a, A b) { return cmp(getOpt(a, field), getOpt(b, field)); } }; } public static int getInt(List c, int i) { return toInt(get(c, i)); } public static int getInt(Map map, Object key) { return toInt(mapGet(map, key)); } public static int getInt(Object o, String field) { return toInt(getOpt(o, (String) field)); } public static int getInt(String field, Object o) { return getInt(o, field); } public static IterableIterator toLines(File f) { return linesFromFile(f); } public static List toLines(String s) { List lines = new ArrayList(); if (s == null) return lines; int start = 0; while (true) { int i = toLines_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(s.substring(start)); break; } lines.add(s.substring(start, i)); if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n') i += 2; else ++i; start = i; } return lines; } public static int toLines_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } public static Collection values(Map map) { return map == null ? emptyList() : map.values(); } public static Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } public static void preCleanUp(Object c) { if (c instanceof Collection) { for (Object o : ((Collection) c)) cleanUp(o); return; } callOpt(c, "licensed_off"); setOpt(c, "ping_anyActions", true); setOpt(c, "cleaningUp_flag", true); } public static 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); } } public static void innerCleanUp() { innerCleanUp(mc()); } public static Object pcallOpt(Object o, String method, Object... args) { try { return callOpt(o, method, args); } catch (Throwable __e) { _handleException(__e); } return null; } public static List registeredThreads(Object o) { Map map = (Map) (getOpt(o, "_registerThread_threads")); if (map == null) return ll(); map.size(); synchronized (map) { return asList(keys(map)); } } public static List registeredThreads() { _registerThread_threads.size(); return asList(keys(_registerThread_threads)); } public static String joinWithComma(Collection c) { return join(", ", c); } public static String joinWithComma(String... c) { return join(", ", c); } public static String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } public static List allToString(Iterable c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } public static void interruptThreads(Collection threads) { for (Thread t : unnull(threads)) t.interrupt(); } public static void interruptThreads(Class mainClass) { interruptThreads(registeredThreads(mainClass)); } public static void retireClassLoader(ClassLoader cl) { if (isJavaXClassLoader(cl)) setOptAll(cl, "retired", true, "retiredMarker", new DefunctClassLoader()); } public static String hmsWithColons() { return hmsWithColons(now()); } public static String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } public static File javaxDataDir_dir; public static File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } public static File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } public static boolean sameFile(File a, File b) { try { return a == null ? b == null : b != null && eq(a.getCanonicalPath(), b.getCanonicalPath()); } catch (Exception __e) { throw rethrow(__e); } } public static boolean directoryIsEmpty(File f) { return !fileExists(f) || isDirectory(f) && empty(listFiles(f)); } public static void copyAllFilesInDirectory_rec_noOverwrite(File src, File dest) { try { print("Listing " + f2s(src)); for (File f : listFiles(src)) { print("Copying " + f2s(f)); File destFile = newFile(dest, f.getName()); if (fileExists(destFile)) throw fail("Won't overwrite " + f2s(destFile) + " with contents of " + f2s(f)); if (isSymLink(f)) Files.createLink(fileToPath(destFile), fileToPath(f).toRealPath()); else if (isFile(f)) copyFile(f, destFile); else if (isDirectory(f)) { mkdirs(destFile); copyAllFilesInDirectory_rec_noOverwrite(f, newFile(dest, f.getName())); } } } catch (Exception __e) { throw rethrow(__e); } } public static boolean deleteFiles(File... files) { return deleteFiles(asList(files)); } public static boolean deleteFiles(List files) { boolean b = false; for (File f : unnull(files)) if (deleteFile(f)) b = true; return b; } public static List conceptBackupFiles(String progID) { Pattern pat = Pattern.compile("^(.*)\\.backup(20\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d)$"); File dir = programDir(progID); List l = new ArrayList(); for (File f : listFilesNotDirs(dir, newFile(dir, "backups"))) { String s = f.getName(); Matcher matcher = pat.matcher(s); { if (!(matcher.find())) continue; } String originalName = matcher.group(1); { if (!(eq(originalName, "concepts.structure.gz"))) continue; } l.add(f); } return l; } public static String dbProgramID() { return getDBProgramID(); } public static void thinAProgramsBackups(String progID, boolean doIt) { List files = new ArrayList(); Map ageMap = new HashMap(); Pattern pat = Pattern.compile("^(.*)\\.backup(20\\d\\d)(\\d\\d)(\\d\\d)-(\\d\\d)$"); File dir = programDir(progID); for (File f : listFilesNotDirs(dir, newFile(dir, "backups"))) { String s = f.getName(); Matcher matcher = pat.matcher(s); { if (!(matcher.find())) continue; } String originalName = matcher.group(1); { if (!(eq(originalName, "concepts.structure.gz"))) continue; } int year = matcherInt(matcher, 2); int month = matcherInt(matcher, 3); int day = matcherInt(matcher, 4); int hour = matcherInt(matcher, 5); long time = timestampFromYMDH(year, month, day, hour); double age = ((now() - time) / 1000.0 / 60 / 60 / 24); ageMap.put(f, age); files.add(f); } int numDeleted = 0; sortByMap_inPlace(files, ageMap); double lastAge = -1; for (File f : files) { double age = ageMap.get(f); if (!thinAProgramsBackups_shouldKeep(age, lastAge)) { ++numDeleted; if (doIt) { print("Deleting: " + f); f.delete(); } } else { lastAge = age; } } if (numDeleted != 0) print((doIt ? "Deleted: " : "Would delete: ") + n(numDeleted, "file")); } public static boolean thinAProgramsBackups_shouldKeep(double age, double lastAge) { return defaultAgeBasedBackupRetentionStrategy_shouldKeep(age, lastAge); } public static boolean isConceptFieldIndexed(Class c, String field) { return isConceptFieldIndexed(db_mainConcepts(), c, field); } public static boolean isConceptFieldIndexed(Concepts concepts, Class c, String field) { return concepts.getFieldIndex(c, field) != null; } public static Pair uniq2(Class c, Object... params) { return uniq2(db_mainConcepts(), c, params); } public static Pair uniq2(Concepts cc, Class c, Object... params) { params = expandParams(c, params); A x = findConceptWhere(c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); return pair(x, true); } return pair(x, false); } public static PKIKeyPair pkiKeyPairFromTwoLineFile(File f) { List l = tlft(loadTextFile(f)); if (l(l) == 2) return new PKIKeyPair(second(l), first(l)); return null; } public static File agiBot_trustedKeyForMachine_file() { return javaxSecretDir("agi.blue-trusted-key-pair.txt"); } public static java.util.Timer doEveryStartingNow(int delay, Object r) { return doEvery(delay, 0, r); } public static int toInt(Object o) { if (o == null) return 0; if (o instanceof Number) return ((Number) o).intValue(); if (o instanceof String) return parseInt((String) o); throw fail("woot not int: " + getClassName(o)); } public static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } public static long toMS(double seconds) { return (long) (seconds * 1000); } public static int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } public static int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } public static int cmp(Object a, Object b) { if (a == null) return b == null ? 0 : -1; if (b == null) return 1; return ((Comparable) a).compareTo(b); } public static List sortByCalculatedField(Iterable c, final Object f) { List l = cloneList(c); sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(callF(f, a), callF(f, b)); } }); return l; } public static int stdcompare(Number a, Number b) { return cmp(a, b); } public static int stdcompare(String a, String b) { return cmp(a, b); } public static int stdcompare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } public static int stdcompare(Object a, Object b) { return cmp(a, b); } public static boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } public static String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } public static String addSlashPrefix(String s) { return addPrefix("/", s); } public static long parseSnippetID(String snippetID) { long id = Long.parseLong(shortenSnippetID(snippetID)); if (id == 0) throw fail("0 is not a snippet ID"); return id; } public static String programID; public static String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } public static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } public static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } public static ArrayList emptyList() { return new ArrayList(); } public static ArrayList emptyList(int capacity) { return new ArrayList(max(0, capacity)); } public static ArrayList emptyList(Iterable l) { return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList(); } public static ArrayList emptyList(Object[] l) { return emptyList(l(l)); } public static ArrayList emptyList(Class c) { return new ArrayList(); } public static Map emptyMap() { return new HashMap(); } public static A printStackTrace(A e) { print(getStackTrace(e)); return e; } public static void printStackTrace() { printStackTrace(new Throwable()); } public static void printStackTrace(String msg) { printStackTrace(new Throwable(msg)); } public static void printStackTrace(String msg, Throwable e) { printStackTrace(new Throwable(msg, e)); } public static void lockOrFail(Lock lock, long timeout) { try { ping(); if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { String s = "Couldn't acquire lock after " + timeout + " ms."; if (lock instanceof ReentrantLock) { ReentrantLock l = (ReentrantLock) lock; s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner"); } throw fail(s); } ping(); } catch (Exception __e) { throw rethrow(__e); } } public static ReentrantLock fairLock() { return new ReentrantLock(true); } public static void assertTrue(Object o) { if (!(eq(o, true))) throw fail(str(o)); } public static boolean assertTrue(String msg, boolean b) { if (!b) throw fail(msg); return b; } public static boolean assertTrue(boolean b) { if (!b) throw fail("oops"); return b; } public static double toDouble(Object o) { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof BigInteger) return ((BigInteger) o).doubleValue(); if (o == null) return 0.0; throw fail(o); } public static A findConceptWhere(Class c, Object... params) { return findConceptWhere(db_mainConcepts(), c, params); } public static 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; } public static Concept findConceptWhere(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) if (checkConceptFields(x, params)) return x; return null; } public static A findConceptWhereCI(Class c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } public static A findConceptWhereCI(Concepts concepts, Class c, Object... params) { params = expandParams(c, params); if (concepts.ciFieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]); if (index != null) { for (A x : index.getAll(params[i + 1])) if (checkConceptFieldsIC(x, params)) return x; return null; } } for (A x : concepts.list(c)) if (checkConceptFieldsIC(x, params)) return x; return null; } public static Concept findConceptWhereCI(Concepts concepts, String c, Object... params) { for (Concept x : concepts.list(c)) if (checkConceptFieldsIC(x, params)) return x; return null; } public static ALQLLine agiBlue_parseQueryLine(String s) { List tok = javaTokWithBrackets(s); if (lCodeTokens(tok) == 2 && eqGet(tok, 1, "return") && isIdentifier(get(tok, 3))) return new ALQLReturn(tok.get(3)); T3 t = agiBlue_parseTriple(tok); if (t != null) return new ALQLTriple(t); if (lCodeTokens(tok) == 2 && eqGet(tok, 1, "lock")) { t = agiBlue_parseTriple(uncurly(tok.get(3))); if (t == null) throw fail("Bad lock statement: " + s); return new ALQLLockStatement(t); } if (lCodeTokens(tok) == 2 && eqGet(tok, 1, "page")) { String page = uncurly(tok.get(3)); String method = containsDollarVars(page) ? "flexMatchDollarVarsIC_first" : "eqic"; return new ALQLPage(page, method); } if (lCodeTokens(tok) == 3 && eqGet(tok, 1, "slice")) { String slice = unquote(tok.get(3)); String contents = uncurly(tok.get(5)); return new ALQLSlice(slice, agiBlue_parseQueryScript(print("contents", contents))); } throw fail("Can't parse ALQL line: " + s); } public static List tlftj_honoringBrackets(String s) { List tok = javaTokWithBrackets(javaDropComments(s)); List out = new ArrayList(); int j = 1; for (int i = 2; i + 1 < l(tok); i += 2) if (containsNewLine(tok.get(i))) { addIfNempty(out, joinSubList(tok, j, i)); j = i + 1; } if (j < l(tok) - 1) addIfNempty(out, joinSubList(tok, j, l(tok) - 1)); return out; } public static Object serveJSON_shallowLineBreaks(Object data) { return serveText(jsonEncode_shallowLineBreaks(data)); } public static T3 triple(A a, B b, C c) { return new T3(a, b, c); } public static boolean isJavaIdentifierAfter(String s, int i) { int n = l(s); if (i >= n || !Character.isJavaIdentifierStart(s.charAt(i))) return false; for (i++; i < n; i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } public static A oneOf(List l) { return empty(l) ? null : l.get(new Random().nextInt(l.size())); } public static char oneOf(String s) { return empty(s) ? '?' : s.charAt(random(l(s))); } public static String oneOf(String... l) { return oneOf(asList(l)); } public static A collectionGet(Collection c, int idx) { if (c == null || idx < 0 || idx >= l(c)) return null; if (c instanceof List) return listGet((List) c, idx); Iterator it = c.iterator(); for (int i = 0; i < idx; i++) if (it.hasNext()) it.next(); else return null; return it.hasNext() ? it.next() : null; } public static List findConceptsWhereCI(Class c, Object... params) { return findConceptsWhereCI(db_mainConcepts(), c, params); } public static List findConceptsWhereCI(String c, Object... params) { return findConceptsWhereCI(db_mainConcepts(), c, params); } public static List findConceptsWhereCI(Concepts concepts, Class c, Object... params) { params = expandParams(c, params); if (concepts.ciFieldIndices != null) for (int i = 0; i < l(params); i += 2) { IFieldIndex index = concepts.getCIFieldIndex(c, (String) params[i]); if (index != null) { List rawList = index.getAll(params[i + 1]); params = dropEntryFromParams(params, i); if (params == null) return rawList; List l = new ArrayList(); for (A x : rawList) if (checkConceptFieldsIC(x, params)) l.add(x); return l; } } return filterConceptsIC(concepts.list(c), params); } public static List findConceptsWhereCI(Concepts concepts, String c, Object... params) { return filterConceptsIC(concepts.list(c), params); } public static A grabValueAndCancel(VF1> r) { Var var = new Var(); withCancelPoint(new VF1() { public void get(CancelPoint cp) { try { callF(r, new VF1() { public void get(A a) { try { var.set(a); cancelTo(cp); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "var.set(a); cancelTo(cp)"; } }); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(r, voidfunc(A a) { var.set(a); cancelTo(cp) });"; } }); return var.get(); } public static void flexMatchDollarVarsIC_iterate(String pat, String input, VF1> onMatch) { List vars = new ArrayList(); String starsPat = dollarVarsToStars(pat, vars); flexMatchIC_iterate(starsPat, input, new VF1() { public void get(Matches m) { try { Map map = matchesToMapUsingVarList_ciMap(m, vars); if (map != null) callF(onMatch, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "SS map = matchesToMapUsingVarList_ciMap(m, vars);\r\n if (map != null) callF..."; } }); } public static String optionalCurlyBrace(String s) { return isCurlyBraced(s) ? s : curlyBrace(s); } public static String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } public static String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } public static Map mapPutOrCreate(Map map, A key, B value) { if (key != null && value != null) { if (map == null) map = new HashMap(); map.put(key, value); } return map; } public static List cloneKeys(Map map) { return cloneList(keys(map)); } public static String conceptsFileName() { return "concepts.structure.gz"; } public static Class hotwire(String src) { assertFalse(_inCore()); Class j = getJavaX(); if (isAndroid()) { synchronized (j) { List libraries = new ArrayList(); File srcDir = (File) call(j, "transpileMain", src, libraries); if (srcDir == null) throw fail("transpileMain returned null (src=" + quote(src) + ")"); Object androidContext = get(j, "androidContext"); return (Class) call(j, "loadx2android", srcDir, src); } } else { return hotwire_overInternalBot(src); } } public static Object makeDependent_postProcess; public static void makeDependent(Object c) { if (c == null) return; assertTrue("Not a class", c instanceof Class); dependentClasses(); hotwire_classes.add(new WeakReference(c)); Object local_log = getOpt(mc(), "local_log"); if (local_log != null) setOpt(c, "local_log", local_log); Object print_byThread = getOpt(mc(), "print_byThread"); if (print_byThread != null) setOpt(c, "print_byThread", print_byThread); callF(makeDependent_postProcess, c); } public static Map objectToMap(Object o) { try { if (o instanceof Map) return (Map) o; TreeMap map = new TreeMap(); Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (final Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; field.setAccessible(true); final Object value = field.get(o); if (value != null) map.put(field.getName(), value); } c = c.getSuperclass(); } if (o instanceof DynamicObject) map.putAll(((DynamicObject) o).fieldValues); return map; } catch (Exception __e) { throw rethrow(__e); } } public static List> objectToMap(Iterable l) { if (l == null) return null; List x = new ArrayList(); for (Object o : l) x.add(objectToMap(o)); return x; } public static String[] asStringArray(Collection c) { return toStringArray(c); } public static String[] asStringArray(Object o) { return toStringArray(o); } public static String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } public static List filterConceptsIC(List list, Object... params) { List l = new ArrayList(); for (A x : list) if (checkConceptFieldsIC(x, params)) l.add(x); return l; } public static List collectField(Collection c, String field) { List l = new ArrayList(); if (c != null) for (Object a : c) l.add(getOpt(a, field)); return l; } public static List collectField(String field, Collection c) { return collectField(c, field); } public static A conceptWhereIC(Class c, Object... params) { return findConceptWhereCI(c, params); } public static Concept conceptWhereIC(String c, Object... params) { return findConceptWhereCI(db_mainConcepts(), c, params); } public static A conceptWhereIC(Concepts concepts, Class c, Object... params) { return findConceptWhereCI(concepts, c, params); } public static Concept conceptWhereIC(Concepts concepts, String c, Object... params) { return findConceptWhereCI(concepts, c, params); } public static boolean checkFieldsIC(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(getOpt(x, (String) data[i]), data[i + 1])) return false; return true; } public static boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } public static boolean regexpMatchesIC(String pat, String s) { return regexpICMatches(pat, s); } public static boolean regexpMatchesIC(Pattern pat, String s) { return regexpICMatches(pat, s); } public static String href(String link, Object contents, Object... params) { if (link == null) return str(contents); return tag("a", contents, arrayPlus(params, "href", link)); } public static boolean isAbsoluteURL(String s) { return contains(s, "://"); } public static String hostNameFromURL(String url) { try { return new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } public static boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } public static String dropSuffixIC(String suffix, String s) { return s == null ? null : ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static String theAGIBlueDomain() { return "agi.blue"; } public static int maximumDomainPartLength() { return 63; } public static Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } public static Map paramsFromURL(String url) { return decodeHQuery(getQueryFromURL(url)); } public static 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("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp) - 1; } else out.append(c); } return out.toString(); } public static String substring(String s, int x) { return substring(s, x, strL(s)); } public static String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x >= s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.substring(x, y); } public static int min(int a, int b) { return Math.min(a, b); } public static long min(long a, long b) { return Math.min(a, b); } public static float min(float a, float b) { return Math.min(a, b); } public static float min(float a, float b, float c) { return min(min(a, b), c); } public static double min(double a, double b) { return Math.min(a, b); } public static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } public static float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } public static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } public static short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } public static int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } public static Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } public static volatile boolean sleep_noSleep = false; public static void sleep(long ms) { ping(); if (ms < 0) return; if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread"); try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } public static void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } public static Object mainBot; public static Object getMainBot() { return mainBot; } public static String domainName() { Object session = call(getMainBot(), "getSession"); Map headers = (Map) (call(session, "getHeaders")); String host = (String) (headers.get("host")); if (host == null) return null; return dropFrom(host, ":"); } public static boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la - lb, b, 0, lb); } public static boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; m.m = new String[] { substring(a, 0, l(a) - l(b)) }; return true; } public static String regexpReplace_direct(String s, String pat, String replacement) { Matcher m = regexp(pat, s); StringBuffer buf = new StringBuffer(); while (m.find()) m.appendReplacement(buf, replacement); m.appendTail(buf); return str(buf); } public static Map subBot_getHttpFiles() { Object session = call(getMainBot(), "getSession"); return (Map) call(session, "getFiles"); } public static Object callOpt(Object o) { return callF(o); } public static A callOpt(Object o, String method, Object... args) { return (A) callOpt_withVarargs(o, method, args); } public static Object getBot(String botID) { return callOpt(getMainBot(), "getBot", botID); } public static A unlisted(Class c, Object... args) { concepts_unlisted.set(true); try { return nuObject(c, args); } finally { concepts_unlisted.set(null); } } public static boolean possibleGlobalID(String s) { return l(s) == globalIDLength() && allLowerCaseCharacters(s); } public static boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } public static String assertPossibleGlobalID(String s) { if (!possibleGlobalID(s)) throw fail("Not an acceptable global ID: " + s); return s; } public static 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); } public static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static void printStructure(String prefix, Object o) { if (endsWithLetter(prefix)) prefix += ": "; print(prefix + structureForUser(o)); } public static void printStructure(Object o) { print(structureForUser(o)); } public static TreeSet toCaseInsensitiveSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet(); addAll(set, c); return set; } public static TreeSet toCaseInsensitiveSet(String... x) { TreeSet set = caseInsensitiveSet(); addAll(set, x); return set; } public static List filterNempty(Collection c) { List l = new ArrayList(); for (String x : unnull(c)) if (nempty(x)) l.add(x); return l; } public static MultiMap decodeHQueryToMultiMap(String query) { MultiMap map = new MultiMap(); for (String s : splitAtAmpersand(query)) { int i = s.indexOf('='); if (i >= 0) map.put(urldecode(s.substring(0, i)), urldecode(s.substring(i + 1))); } return map; } public static String unpackAGIDomainOpt(String s) { return or(unpackAGIDomain(s), s); } public static Pair uniqCI2(Class c, Object... params) { return uniqCI2(db_mainConcepts(), c, params); } public static Pair uniqCI2(Concepts cc, Class c, Object... params) { params = expandParams(c, params); A x = findConceptWhereCI(cc, c, params); if (x == null) { x = unlisted(c); csetAll(x, params); cc.register(x); return pair(x, true); } return pair(x, false); } public static Object collectionMutex(Object o) { String c = className(o); if (eq(c, "java.util.TreeMap$KeySet")) c = className(o = getOpt(o, "m")); else if (eq(c, "java.util.HashMap$KeySet")) c = className(o = get_raw(o, "this$0")); if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap")) c = className(o = get_raw(o, "m")); return o; } public static boolean contains(Collection c, Object o) { return c != null && c.contains(o); } public static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } public static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } public static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } public static boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } public static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static String stringPar(Object[] params, String name) { return stringOptPar(params, name); } public static String stringPar(String name, Object[] params) { return stringOptPar(params, name); } public static String stringPar(String name, Map params) { return (String) optPar(name, params); } public static String stringPar(String name, Object[] params, String defaultValue) { return optPar(name, params, defaultValue); } public static String htmlencode(Object o) { return htmlencode(str(o)); } public static String htmlencode(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 == '>' || c == '&') { int cp = s.codePointAt(i); out.append("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp) - 1; } else out.append(c); } return out.toString(); } public static String unicode_leftPointingTriangle() { return unicodeFromCodePoint(0x25C2); } public static String unicode_rightPointingTriangle() { return charToString(0x25B8); } public static float abs(float f) { return Math.abs(f); } public static int abs(int i) { return Math.abs(i); } public static double abs(double d) { return Math.abs(d); } public static boolean odd(int i) { return (i & 1) != 0; } public static boolean odd(long i) { return (i & 1) != 0; } public static boolean odd(BigInteger i) { return odd(toInt(i)); } public static String[] dropFirst(int n, String[] a) { return drop(n, a); } public static String[] dropFirst(String[] a) { return drop(1, a); } public static Object[] dropFirst(Object[] a) { return drop(1, a); } public static List dropFirst(List l) { return dropFirst(1, l); } public static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } public static List dropFirst(Iterable i) { return dropFirst(toList(i)); } public static List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } public static List dropFirst(List l, int n) { return dropFirst(n, l); } public static String dropFirst(int n, String s) { return substring(s, n); } public static String dropFirst(String s, int n) { return substring(s, n); } public static String dropFirst(String s) { return substring(s, 1); } public static Object[] html_massageAutofocusParam(Object[] params) { Object autofocus = optPar("autofocus", params); return changeParam(params, "autofocus", eqOneOf(autofocus, true, 1, "1", "autofocus") ? html_valueLessParam() : null); } public static 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; } public static String nlToBr(String s) { return s.replace("\n", "
\n"); } public static String nemptyLines(Iterable l) { return lines(nempties(allToString(l))); } public static String hhead(Object contents) { return tag("head", contents); } public static String htitle(String title) { return tag("title", htmlencode_noQuotes(title)); } public static boolean isSquareBracketed(String s) { return s != null && s.startsWith("[") && s.endsWith("]"); } public static boolean isInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; if (s.charAt(0) == '-') if (++i >= n) return false; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static String deSquareBracket(String s) { if (startsWith(s, "[") && endsWith(s, "]")) return substring(s, 1, l(s) - 1); return s; } public static int maxIntValue() { return Integer.MAX_VALUE; } public static
List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } public static List newSubListOrSame(List l, int startIndex, int endIndex) { if (l == null) return null; int n = l(l); startIndex = max(0, startIndex); endIndex = min(n, endIndex); if (startIndex >= endIndex) return ll(); if (startIndex == 0 && endIndex == n) return l; return cloneList(l.subList(startIndex, endIndex)); } public static 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); } public static AutoCloseable dm_enter(Object mod) { return (AutoCloseable) callOpt(dm_getModule(mod), "enter"); } public static Object call_withVarargs(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(method, args); if (me != null) return invokeMethod(me, null, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found"); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(method, args); if (me != null) return invokeMethod(me, o, args); List methods = cache.cache.get(method); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found in " + c); } } catch (Exception __e) { throw rethrow(__e); } } public static int longToInt_clip(long l) { return l > Integer.MAX_VALUE ? Integer.MAX_VALUE : l < Integer.MIN_VALUE ? Integer.MIN_VALUE : (int) l; } public static List similarEmptyList(Collection m) { return new ArrayList(); } public static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } public static Object[] paramsPlus(Object[] a1, Object... a2) { if (a2 == null) return a1; if (a1 == null) return a2; if (l(a1) == 1 && a1[0] instanceof Map) return new Object[] { mapPlus((Map) a1[0], a2) }; assertEvenLength(a1); assertEvenLength(a2); Map map = paramsToOrderedMap(a1); int n = l(a2); for (int i = 0; i < n; i += 2) { Object key = a2[i]; if (key != null) map.put(key, a2[i + 1]); } return mapToParams(map); } public static String unparseCSSParameter(Map map) { return joinWithSemicolon(map(map, new F2() { public String get(String key, String value) { try { return key + ": " + value; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "key + \": \" + value"; } })); } public static Map mapPlus_noOverwrite(Map m, Object... data) { m = cloneMap(m); litmap_impl_noOverwrite(m, data); return m; } public static Map parseCSSParameter(String s) { Map map = new LinkedHashMap(); for (String x : trimAll(splitAt(s, ";"))) { List y = trimAll(splitAtColon(x)); if (l(y) == 2) map.put(first(y), second(y)); } return map; } public static boolean containsIgnoreCase(Collection l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } public static boolean containsIgnoreCase(String[] l, String s) { if (l != null) for (String x : l) if (eqic(x, s)) return true; return false; } public static boolean containsIgnoreCase(String s, char c) { return indexOfIgnoreCase(s, String.valueOf(c)) >= 0; } public static boolean containsIgnoreCase(String a, String b) { return indexOfIgnoreCase(a, b) >= 0; } public static List listPlus(Collection l, A... more) { return concatLists(l, asList(more)); } public static String spaced(String s) { return " " + unnull(s) + " "; } public static String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } public static double fraction(double d) { return d % 1; } public static String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } public static String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } public static String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } public static String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } public static String n_fancy2(MultiSet ms, String singular, String plural) { return n_fancy2(l(ms), singular, plural); } public static String div(Object contents, Object... params) { return hfulltag("div", contents, params); } public static BigInteger div(BigInteger a, BigInteger b) { return a.divide(b); } public static BigInteger div(BigInteger a, int b) { return a.divide(bigint(b)); } public static TimerTask timerTask(final Object r, final java.util.Timer timer) { return new TimerTask() { public void run() { if (!licensed()) timer.cancel(); else pcallF(r); } }; } public static Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } public static void pcallFAll(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) pcallF(f, args); } public static void pcallFAll(Iterator it, Object... args) { while (it.hasNext()) pcallF(it.next(), args); } public static Set vm_busListeners_live_cache; public static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache; } public static Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } public static Map vm_busListenersByMessage_live_cache; public static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache; } public static Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } public static String hfulltag(String tag) { return hfulltag(tag, ""); } public static String hfulltag(String tag, Object contents, Object... params) { return hopeningTag(tag, params) + str(contents) + ""; } public static boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; if (o instanceof ThreadLocal) return isTrue(((ThreadLocal) o).get()); throw fail(getClassName(o)); } public static Map compileRegexpIC_cache = syncMRUCache(10); public static java.util.regex.Pattern compileRegexpIC(String pat) { java.util.regex.Pattern p = compileRegexpIC_cache.get(pat); if (p == null) { try { compileRegexpIC_cache.put(pat, p = java.util.regex.Pattern.compile(pat, Pattern.CASE_INSENSITIVE)); } catch (PatternSyntaxException e) { throw rethrow(wrapPatternSyntaxException(e)); } } return p; } public static boolean regexpICFind(Pattern pat, String s) { return regexpIC(pat, s).find(); } public static boolean regexpICFind(String pat, String s) { return regexpIC(pat, s).find(); } public static String fullTrimLastLine(String s) { return trimLastLine(rtrim(s)); } public static boolean swic_trim(String a, String b, Matches m) { if (!swic(a, b)) return false; m.m = new String[] { trim(substring(a, l(b))) }; return true; } public static A last(List l) { return empty(l) ? null : l.get(l.size() - 1); } public static char last(String s) { return empty(s) ? '#' : s.charAt(l(s) - 1); } public static int last(int[] a) { return l(a) != 0 ? a[l(a) - 1] : 0; } public static A last(A[] a) { return l(a) != 0 ? a[l(a) - 1] : null; } public static A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } public static A popLast(List l) { return liftLast(l); } public static String fromLines(Iterable lines) { StringBuilder buf = new StringBuilder(); if (lines != null) for (Object line : lines) buf.append(str(line)).append('\n'); return buf.toString(); } public static String fromLines(String... lines) { return fromLines(asList(lines)); } public static 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; } public static List dropLast(List l) { return subList(l, 0, l(l) - 1); } public static List dropLast(int n, List l) { return subList(l, 0, l(l) - n); } public static List dropLast(Iterable l) { return dropLast(asList(l)); } public static String dropLast(String s) { return substring(s, 0, l(s) - 1); } public static String dropLast(String s, int n) { return substring(s, 0, l(s) - n); } public static String dropLast(int n, String s) { return dropLast(s, n); } public static String dropPrefixMandatory(String prefix, String s) { if (s.startsWith(prefix)) return s.substring(prefix.length()); else throw fail("Prefix " + prefix + " not found in: " + s); } public static byte[] toUtf8(String s) { try { return s.getBytes("UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static String dropLastLine(String s) { s = dropSuffix("\r", dropSuffix("\n", s)); int i = s.lastIndexOf('\n'); return i < 0 ? "" : dropSuffix("\r", substring(s, 0, i)); } public static List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } public static List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } public static boolean jsonDecode_useOrderedMaps = true; public static Object jsonDecode(final String text) { final List tok = jsonTok(text); if (l(tok) == 1) return null; class Y { public int i = 1; public Object parse() { String t = tok.get(i); if (t.startsWith("\"")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.equals("{")) return parseMap(); if (t.equals("[")) return this.parseList(); if (t.equals("null")) { i += 2; return null; } if (t.equals("false")) { i += 2; return false; } if (t.equals("true")) { i += 2; return true; } boolean minus = false; if (t.equals("-")) { minus = true; i += 2; t = get(tok, i); } if (isInteger(t)) { i += 2; if (eq(get(tok, i), ".")) { String x = t + "." + get(tok, i + 2); i += 4; double d = parseDouble(x); if (minus) d = -d; return d; } else { long l = parseLong(t); if (minus) l = -l; return l != (int) l ? new Long(l) : new Integer((int) l); } } throw new RuntimeException("Unknown token " + (i + 1) + ": " + t + ": " + text); } public Object parseList() { consume("["); List list = new ArrayList(); while (!tok.get(i).equals("]")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("]"); return list; } public Object parseMap() { consume("{"); Map map = jsonDecode_useOrderedMaps ? new LinkedHashMap() : new TreeMap(); while (!tok.get(i).equals("}")) { String key = unquote(tok.get(i)); i += 2; consume(":"); Object value = parse(); map.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume("}"); return map; } public void consume(String s) { if (!tok.get(i).equals(s)) { String prevToken = i - 2 >= 0 ? tok.get(i - 2) : ""; String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size()))); throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")"); } i += 2; } } return new Y().parse(); } public static String getDBProgramID_id; public static String getDBProgramID() { return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase(); } public static Object _defaultClassFinder_value = defaultDefaultClassFinder(); public static Object _defaultClassFinder() { return _defaultClassFinder_value; } public static MultiSet asCIMultiSet(Iterable l) { MultiSet ms = new MultiSet(); ms.map = ciMap(); ms.addAll(l); return ms; } public static int indexOf(List l, A a, int startIndex) { if (l == null) return -1; int n = l(l); for (int i = startIndex; i < n; i++) if (eq(l.get(i), a)) return i; return -1; } public static int indexOf(List l, int startIndex, A a) { return indexOf(l, a, startIndex); } public static int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } public static int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } public static int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } public static int indexOf(String a, char b) { return a == null ? -1 : a.indexOf(b); } public static int indexOf(String a, int i, char b) { return indexOf(a, b, i); } public static int indexOf(String a, char b, int i) { return a == null ? -1 : a.indexOf(b, i); } public static int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } public static int indexOf(A[] x, A a) { int n = l(x); for (int i = 0; i < n; i++) if (eq(x[i], a)) return i; return -1; } public static long ratio(long x, long y) { return y == 0 ? 0 : x / y; } public static volatile PersistableThrowable lastException_lastException; public static PersistableThrowable lastException() { return lastException_lastException; } public static void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } public static Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } public static Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } public static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } public static 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)=[^&\\s\"]*", "$1$2="); } public static String hideCredentials(Object o) { return hideCredentials(str(o)); } public static String baseClassName(String className) { return substring(className, className.lastIndexOf('.') + 1); } public static String baseClassName(Object o) { return baseClassName(getClassName(o)); } public static String prependIfNempty(String prefix, String s) { return empty(s) ? s : prefix + s; } public static TreeMap litCIMap(Object... x) { TreeMap map = caseInsensitiveMap(); litmap_impl(map, x); return map; } public static File userDir() { return new File(userHome()); } public static File userDir(String path) { return new File(userHome(), path); } public static int howManySecondsAgo(long timestamp) { return iround(toSeconds(now() - timestamp)); } public static int iround(double d) { return (int) Math.round(d); } public static int iround(Number n) { return iround(toDouble(n)); } public static List sortedIgnoreCase(Collection c) { List l = cloneList(c); Collections.sort(l, caseInsensitiveComparator()); return l; } public static ArrayList cloneListSynchronizingOn(Collection l, Object mutex) { if (l == null) return new ArrayList(); synchronized (mutex) { return new ArrayList(l); } } public static int nfilter(Iterable c, IF1 pred) { return nfilter(pred, c); } public static int nfilter(IF1 pred, Iterable c) { int n = 0; if (c != null) for (A o : c) if (pred.get(o)) ++n; return n; } public static int nfilter(Iterable c, Object pred) { int n = 0; if (c != null) for (Object o : c) if (isTrue(callF(pred, o))) ++n; return n; } public static int nfilter(Object pred, Iterable c) { return nfilter(c, pred); } public static class getOpt_Map extends WeakHashMap { public getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } public static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); public static HashMap getOpt_special; public static Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); } Field f = map.get(field); if (f != null) return f.get(o); if (o instanceof DynamicObject) return mapGet2(((DynamicObject) o).fieldValues, field); return null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap getOpt_makeCache(Class c) { HashMap map; if (isSubtypeOf(c, Map.class)) map = getOpt_special; else { map = new HashMap(); if (!reflection_classesNotToScan().contains(c.getName())) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) { f.setAccessible(true); String name = f.getName(); if (!map.containsKey(name)) map.put(name, f); } _c = _c.getSuperclass(); } while (_c != null); } } if (getOpt_cache != null) getOpt_cache.put(c, map); return map; } public static Object pcallFAll_returnFirstNotNull(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { Object __1106 = pcallF(f, args); if (__1106 != null) return __1106; } return null; } public static Object pcallFAll_returnFirstNotNull(Iterator it, Object... args) { while (it.hasNext()) { Object __1107 = pcallF(it.next(), args); if (__1107 != null) return __1107; } return null; } public static String yesno(boolean b) { return yesno((Boolean) b); } public static String yesno(Boolean b) { return eq(b, true) ? "Yes. " : eq(b, false) ? "No. " : "Unknown. "; } public static Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } public static int defaultStringTransformerCacheSize() { return 1000; } public static String words2_spaces(String s) { return joinWithSpace(words2(s)); } public static List sortedByFieldIC(Collection c, final String field) { List l = new ArrayList(c); sort(l, new Comparator() { public int compare(A a, A b) { return compareIC((String) getOpt(a, field), (String) getOpt(b, field)); } }); return l; } public static List sortedByFieldIC(String field, Collection c) { return sortedByFieldIC(c, field); } public static String words2_spaces_collapse(String s) { return collapseString(words2_spaces(s)); } public static Map newWeakHashMap() { return _registerWeakMap(synchroMap(new WeakHashMap())); } public static boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } public static boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } public static void failIfUnlicensed() { assertTrue("license off", licensed()); } public static Thread currentThread() { return Thread.currentThread(); } public static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } public static A optParam(ThreadLocal tl) { return optPar(tl); } public static Object optParam(String name, Map params) { return mapGet(params, name); } public static A optParam(Object[] opt, String name, A defaultValue) { int n = l(opt); if (n == 1 && opt[0] instanceof Map) { Map map = (Map) (opt[0]); return map.containsKey(name) ? (A) map.get(name) : defaultValue; } if (!even(l(opt))) throw fail("Odd parameter length"); for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name)) return (A) opt[i + 1]; return defaultValue; } public static Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } public static boolean equalsIgnoreCase(String a, String b) { return eqic(a, b); } public static boolean equalsIgnoreCase(char a, char b) { return eqic(a, b); } public static List keysSortedByValues(final Map map) { List l = new ArrayList(map.keySet()); sort(l, mapComparator(map)); return l; } public static String htmldecode(final String input) { if (input == null) return null; final int MIN_ESCAPE = 2; final int MAX_ESCAPE = 6; StringWriter writer = null; int len = input.length(); int i = 1; int st = 0; while (true) { while (i < len && input.charAt(i - 1) != '&') i++; if (i >= len) break; int j = i; while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';') j++; if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) { i++; continue; } if (input.charAt(i) == '#') { int k = i + 1; int radix = 10; final char firstChar = input.charAt(k); if (firstChar == 'x' || firstChar == 'X') { k++; radix = 16; } try { int entityValue = Integer.parseInt(input.substring(k, j), radix); if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); if (entityValue > 0xFFFF) { final char[] chrs = Character.toChars(entityValue); writer.write(chrs[0]); writer.write(chrs[1]); } else { writer.write(entityValue); } } catch (NumberFormatException ex) { i++; continue; } } else { CharSequence value = htmldecode_lookupMap.get(input.substring(i, j)); if (value == null) { i++; continue; } if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); writer.append(value); } st = j + 1; i = st; } if (writer != null) { writer.append(input.substring(st, len)); return writer.toString(); } return input; } public static final String[][] htmldecode_ESCAPES = { { "\"", "quot" }, { "&", "amp" }, { "<", "lt" }, { ">", "gt" }, { " ", "nbsp" }, { "¡", "iexcl" }, { "¢", "cent" }, { "£", "pound" }, { "¤", "curren" }, { "¥", "yen" }, { "¦", "brvbar" }, { "§", "sect" }, { "¨", "uml" }, { "©", "copy" }, { "ª", "ordf" }, { "«", "laquo" }, { "¬", "not" }, { "­", "shy" }, { "®", "reg" }, { "¯", "macr" }, { "°", "deg" }, { "±", "plusmn" }, { "²", "sup2" }, { "³", "sup3" }, { "´", "acute" }, { "µ", "micro" }, { "¶", "para" }, { "·", "middot" }, { "¸", "cedil" }, { "¹", "sup1" }, { "º", "ordm" }, { "»", "raquo" }, { "¼", "frac14" }, { "½", "frac12" }, { "¾", "frac34" }, { "¿", "iquest" }, { "À", "Agrave" }, { "Á", "Aacute" }, { "Â", "Acirc" }, { "Ã", "Atilde" }, { "Ä", "Auml" }, { "Å", "Aring" }, { "Æ", "AElig" }, { "Ç", "Ccedil" }, { "È", "Egrave" }, { "É", "Eacute" }, { "Ê", "Ecirc" }, { "Ë", "Euml" }, { "Ì", "Igrave" }, { "Í", "Iacute" }, { "Î", "Icirc" }, { "Ï", "Iuml" }, { "Ð", "ETH" }, { "Ñ", "Ntilde" }, { "Ò", "Ograve" }, { "Ó", "Oacute" }, { "Ô", "Ocirc" }, { "Õ", "Otilde" }, { "Ö", "Ouml" }, { "×", "times" }, { "Ø", "Oslash" }, { "Ù", "Ugrave" }, { "Ú", "Uacute" }, { "Û", "Ucirc" }, { "Ü", "Uuml" }, { "Ý", "Yacute" }, { "Þ", "THORN" }, { "ß", "szlig" }, { "à", "agrave" }, { "á", "aacute" }, { "â", "acirc" }, { "ã", "atilde" }, { "ä", "auml" }, { "å", "aring" }, { "æ", "aelig" }, { "ç", "ccedil" }, { "è", "egrave" }, { "é", "eacute" }, { "ê", "ecirc" }, { "ë", "euml" }, { "ì", "igrave" }, { "í", "iacute" }, { "î", "icirc" }, { "ï", "iuml" }, { "ð", "eth" }, { "ñ", "ntilde" }, { "ò", "ograve" }, { "ó", "oacute" }, { "ô", "ocirc" }, { "õ", "otilde" }, { "ö", "ouml" }, { "÷", "divide" }, { "ø", "oslash" }, { "ù", "ugrave" }, { "ú", "uacute" }, { "û", "ucirc" }, { "ü", "uuml" }, { "ý", "yacute" }, { "þ", "thorn" }, { "ÿ", "yuml" }, { "–", "ndash" }, { "‘", "lsquo" }, { "’", "rsquo" }, { "”", "rdquo" }, { "“", "ldquo" }, { "—", "mdash" }, { "'", "apos" } }; public static final HashMap htmldecode_lookupMap; static { htmldecode_lookupMap = new HashMap(); for (final CharSequence[] seq : htmldecode_ESCAPES) htmldecode_lookupMap.put(seq[1].toString(), seq[0]); } public static List dropAllTags(List tok) { List list = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && t.startsWith("<")) { list.set(list.size() - 1, list.get(list.size() - 1) + tok.get(i + 1)); ++i; } else list.add(t); } return list; } public static String dropAllTags(String html) { return join(dropAllTags(htmlcoarsetok(html))); } public static boolean isLocalSnippetID(String snippetID) { return isSnippetID(snippetID) && isLocalSnippetID(psI(snippetID)); } public static boolean isLocalSnippetID(long snippetID) { return snippetID >= 1000 && snippetID <= 9999; } public static String loadLocalSnippet(String snippetID) { return loadLocalSnippet(psI(snippetID)); } public static String loadLocalSnippet(long snippetID) { return loadTextFile(localSnippetFile(snippetID)); } public static IResourceLoader vm_getResourceLoader() { return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader")); } public static String fsI(String id) { return formatSnippetID(id); } public static String fsI(long id) { return formatSnippetID(id); } public static String tb_mainServer_default = "http://code.botcompany.de:8081"; public static Object tb_mainServer_override; public static String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } public static File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } public static boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } public static String standardCredentials() { String user = standardCredentialsUser(); String pass = standardCredentialsPass(); if (nempty(user) && nempty(pass)) return "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass); return ""; } public static String loadTextFile(String fileName) { return loadTextFile(fileName, null); } public static 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); } public static String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } public static 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); } public static File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } public static A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } public static int loadPage_defaultTimeout = 60000; public static ThreadLocal loadPage_charset = new ThreadLocal(); public static boolean loadPage_allowGzip = true, loadPage_debug; public static boolean loadPage_anonymous = false; public static int loadPage_verboseness = 100000; public static int loadPage_retries = 1; public static ThreadLocal loadPage_silent = new ThreadLocal(); public static volatile int loadPage_forcedTimeout; public static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); public static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); public static ThreadLocal> loadPage_extraHeaders = new ThreadLocal(); public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPageSilently(URL url) { try { if (url.getProtocol().equals("https")) disableCertificateValidation(); if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url); IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = loadPage_openConnection(url); return loadPage(con, url); } catch (IOException _e) { e = _e; if (loadPageThroughProxy_enabled) { print("Trying proxy because of: " + e); try { return loadPageThroughProxy(str(url)); } catch (Throwable e2) { print(" " + exceptionToStringShort(e2)); } } else if (loadPage_debug) print(exceptionToStringShort(e)); if (tries < loadPage_retries - 1) sleepSeconds(1); } throw e; } catch (Exception __e) { throw rethrow(__e); } } public static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } public static String loadPage(String url) { try { url = loadPage_preprocess(url); if (!isTrue(loadPage_silent.get())) printWithTime("Loading: " + hideCredentials(url)); return loadPageSilently(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPage(URL url) { return loadPage(url.toExternalForm()); } public static String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } public static String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); if (addHeaders) try { if (!loadPage_anonymous) setHeaders(con); if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("X-No-Cookies", "1"); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); } catch (Throwable e) { } vm_generalSubMap("URLConnection per thread").put(currentThread(), con); loadPage_responseHeaders.set(con.getHeaderFields()); InputStream in = null; try { in = urlConnection_getInputStream(con); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { throw new IOException("Page could not be read: " + hideCredentials(url)); } String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } public static String loadPage_guessCharset(String contentType) { Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType); String match = m.matches() ? m.group(1) : null; if (loadPage_debug) print("loadPage: contentType=" + contentType + ", match: " + match); return or(match, "UTF-8"); } public static URLConnection loadPage_openConnection(URL url) { URLConnection con = openConnection(url); int timeout = toInt(loadPage_forcedTimeout_byThread.get()); if (timeout == 0) timeout = loadPage_forcedTimeout; if (timeout != 0) setURLConnectionTimeouts(con, loadPage_forcedTimeout); else setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout); return con; } public static String hrefBlank(String link, Object contents, Object... params) { return tag("a", contents, concatArrays(new Object[] { "href", link, "target", "_blank" }, params)); } public static String hopeningTag(String tag, Map params) { return hopeningTag(tag, mapToParams(params)); } public static 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); } public static int iceil(double d) { return (int) Math.ceil(d); } public static void deleteConcept(long id) { db_mainConcepts().deleteConcept(id); } public static void deleteConcept(Concepts concepts, long id) { concepts.deleteConcept(id); } public static void deleteConcept(Concept c) { if (c != null) c.delete(); } public static void deleteConcept(Concept.Ref ref) { if (ref != null) deleteConcept(ref.get()); } public static void moveFile(File a, File b) { if (!renameFile(a, b)) throw fail("File move failed: " + a + " to " + b); } public static boolean even(int i) { return (i & 1) == 0; } public static boolean even(long i) { return (i & 1) == 0; } public static A or(A a, A b) { return a != null ? a : b; } public static long elapsedMS(long time) { ping(); return sysNow() - time; } public static String containerTag(String tag) { return containerTag(tag, ""); } public static String containerTag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); return openingTag + s + ""; } public static int indexOfIC(List a, String b) { return indexOfIgnoreCase(a, b); } public static int indexOfIC(List a, String b, int i) { return indexOfIgnoreCase(a, b, i); } public static int indexOfIC(String a, String b) { return indexOfIgnoreCase(a, b); } public static 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); } public static String hcss(Object contents) { return htag("style", contents); } public static String joinWithVBar(Iterable l) { return join(" | ", l); } public static void dataToTable_dynSet(List l, int i, Object s) { while (i >= l.size()) l.add(""); l.set(i, s); } public static List dataToTable_makeRow(Object x, List cols) { if (instanceOf(x, "DynamicObject")) x = get_raw(x, "fieldValues"); if (x instanceof Map) { Map m = (Map) x; List row = new ArrayList(); for (Object _field : keysWithoutHidden(m)) { String field = (String) _field; Object value = m.get(field); int col = cols.indexOf(field); if (col < 0) { cols.add(field); col = cols.size() - 1; } dataToTable_dynSet(row, col, dataToTable_wrapValue(value)); } return row; } return litlist(structureOrText(x)); } public static Object dataToTable_wrapValue(Object o) { if (o instanceof BufferedImage) return o; if (o instanceof MakesBufferedImage) return ((MakesBufferedImage) o).getBufferedImage(); if (o instanceof Boolean) return o; return structureOrTextForUser(o); } public static ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } public static String structureOrText(Object o) { return o instanceof String ? (String) o : structure(o); } public static String hopeningtag(String tag, Map params) { return hopeningTag(tag, params); } public static String hopeningtag(String tag, Object... params) { return hopeningTag(tag, params); } public static Object html_valueLessParam_cache; public static Object html_valueLessParam() { if (html_valueLessParam_cache == null) html_valueLessParam_cache = html_valueLessParam_load(); return html_valueLessParam_cache; } public static Object html_valueLessParam_load() { return new Object(); } public static List padList(List l, int w, A a) { if (l(l) >= w) return l; List x = cloneList(l); while (l(x) < w) x.add(a); return x; } public static String hSilentComputator() { return hSilentComputator(hSilentComputator_defaultURI()); } public static String hSilentComputator(String wsUri) { return hSilentComputator(wsUri, ""); } public static String hSilentComputator(String wsUri, String flag) { if (nempty(flag)) wsUri = addSlash(wsUri) + flag; return div("Calculating", "id", "calcing") + hcss("#calcing {\r\nposition: fixed;\r\nwidth: 100%;\r\nheight: 100vh;\r\nz-index: 9999;\r\nvisibility: hidden;\r\n}") + hMakeComputerID() + hreconnectingWebSockets() + hjavascript("\r\n function sendPing() {\r\n ${PINGCMD}\r\n }\r\n \r\n var working = false;\r\n var benchResultl;\r\n var ws = new ReconnectingWebSocket(\"${URI}\");\r\n ws.onopen = function(event) {\r\n console.log(\"WebSocket opened.\");\r\n };\r\n ws.onmessage = function(event) {\r\n var d = event.data;\r\n while (d.length > 0 && d.charCodeAt(d.length-1) == 0)\r\n d = d.substring(0, d.length-1);\r\n console.log(\"Evaluating: \" + d);\r\n var geval = eval; // use global scope\r\n geval(d);\r\n console.log(\"Evaluated.\");\r\n };\r\n \r\n //working = true; // XXX\r\n //console.log(\"Eval test: \" + eval('working'));\r\n ".replace("${URI}", wsUri).replace("${PINGCMD}", nodes_pingCmd())); } public static String hSilentComputator_defaultURI() { int port = subBot_currentPort(); return (subBot_isHttps() ? "wss://" : "ws://") + domain() + (port == 80 ? "" : ":" + port) + "/"; } public static String himg(String src, Object... params) { return tag("img", "", arrayPlus(params, "src", src)); } public static String snippetImageLink(String snippetID) { return snippetImageURL(snippetID); } public static boolean nemptyString(String s) { return s != null && s.length() > 0; } public static int strL(String s) { return s == null ? 0 : s.length(); } public static int listL(Collection l) { return l == null ? 0 : l.size(); } public static String span(Object contents, Object... params) { return tag("span", contents, params); } public static String formatDouble(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '#'); return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)).format(d); } public static double toM_double(long l) { return l / (1024 * 1024.0); } public static boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } public static boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } public static boolean boolOptParam(String name, Object[] __) { return boolOptParam(__, name); } public static boolean boolOptParam(String name, Map __) { return isTrue(optPar(name, __)); } public static TreeMap asCaseInsensitiveMap(Map map) { if (isCIMap(map)) return (TreeMap) map; TreeMap m = ciMap(); m.putAll(map); return m; } public static Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } public static Class _getClass(Object realm, String name) { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } public static List onlyClassNamesThatExist(List l) { List out = new ArrayList(); for (String s : l) if (hasClass(s)) out.add(s); return out; } public static List prependAll(final String s, Collection l) { return map(new F1() { public String get(String x) { try { return s + x; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "s + x"; } }, l); } public static List identifiersOnly(Collection l) { List out = new ArrayList(); for (String a : unnull(l)) if (isIdentifier(a)) out.add(a); return out; } public static 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; } public static Map _registerThread_threads; public static Object _onRegisterThread; public static Thread _registerThread(Thread t) { if (_registerThread_threads == null) _registerThread_threads = newWeakHashMap(); _registerThread_threads.put(t, true); vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc())); callF(_onRegisterThread, t); return t; } public static void _registerThread() { _registerThread(Thread.currentThread()); } public static String getStackTrace2(Throwable e) { return hideCredentials(getStackTrace(unwrapTrivialExceptionWraps(e)) + replacePrefix("java.lang.RuntimeException: ", "FAIL: ", hideCredentials(str(innerException2(e)))) + "\n"); } public static long guessClusteredDirSize(File dir, Object... __) { Object pred = (Object) (optPar("pred", __)); long n = 0; long clusterSize = assumedClusterSize(); for (File f : pred == null ? findAllFiles_noDirs(dir) : findAllFiles_noDirs_pred(dir, pred)) n += roundUpTo(clusterSize, f.length()); return n; } public static long guessClusteredDirSize() { return guessClusteredDirSize(programDir()); } public static String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } public static volatile String caseID_caseID; public static String caseID() { return caseID_caseID; } public static void caseID(String id) { caseID_caseID = id; } public static File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } public static File newFile(String name) { return name == null ? null : new File(name); } public static 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(); } public static boolean md5OfFile_verbose = false; public static String md5OfFile(String path) { return md5OfFile(newFile(path)); } public static 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); } } public static String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } public static 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); } public static String makeRandomID(Random r, int length) { return makeRandomID(length, r); } public static 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); } public static void setOpt_raw(Object o, String field, Object value) { try { if (o == null) return; if (o instanceof Class) setOpt_raw((Class) o, field, value); else { Field f = setOpt_raw_findField(o.getClass(), field); if (f != null) { f.setAccessible(true); smartSet(f, o, value); } } } catch (Exception __e) { throw rethrow(__e); } } public static void setOpt_raw(Class c, String field, Object value) { try { if (c == null) return; Field f = setOpt_raw_findStaticField(c, field); if (f != null) { f.setAccessible(true); smartSet(f, null, value); } } catch (Exception __e) { throw rethrow(__e); } } public static Field setOpt_raw_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } public static Field setOpt_raw_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } public static 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; } } public static Method fastIntern_method; public static String fastIntern(String s) { try { if (s == null) return null; if (fastIntern_method == null) { fastIntern_method = findMethodNamed(javax(), "internPerProgram"); if (fastIntern_method == null) upgradeJavaXAndRestart(); } return (String) fastIntern_method.invoke(null, s); } catch (Exception __e) { throw rethrow(__e); } } public static String assertIsIdentifier(String s) { if (!isIdentifier(s)) throw fail("Not an identifier: " + quote(s)); return s; } public static String assertIsIdentifier(String msg, String s) { if (!isIdentifier(s)) throw fail(msg + " - Not an identifier: " + quote(s)); return s; } public static 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; } public static Map newDangerousWeakHashMap() { return _registerDangerousWeakMap(synchroMap(new WeakHashMap())); } public static Map newDangerousWeakHashMap(Object initFunction) { return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction); } public static HashMap> callMC_cache = new HashMap(); public static String callMC_key; public static Method callMC_value; public static Object callMC(String method, String[] arg) { return callMC(method, new Object[] { arg }); } public static Object callMC(String method, Object... args) { try { Method me; if (callMC_cache == null) callMC_cache = new HashMap(); synchronized (callMC_cache) { me = method == callMC_key ? callMC_value : null; } if (me != null) try { return invokeMethod(me, null, args); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e); } List m; synchronized (callMC_cache) { m = callMC_cache.get(method); } if (m == null) { if (callMC_cache.isEmpty()) { callMC_makeCache(); m = callMC_cache.get(method); } if (m == null) throw fail("Method named " + method + " not found in main"); } int n = m.size(); if (n == 1) { me = m.get(0); synchronized (callMC_cache) { callMC_key = method; callMC_value = me; } try { return invokeMethod(me, null, args); } catch (IllegalArgumentException e) { throw new RuntimeException("Can't call " + me + " with arguments " + classNames(args), e); } } for (int i = 0; i < n; i++) { me = m.get(i); if (call_checkArgs(me, args, false)) return invokeMethod(me, null, args); } throw fail("No method called " + method + " with matching arguments found in main"); } catch (Exception __e) { throw rethrow(__e); } } public static void callMC_makeCache() { synchronized (callMC_cache) { callMC_cache.clear(); Class _c = (Class) mc(), c = _c; while (c != null) { for (Method m : c.getDeclaredMethods()) if ((m.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) { m.setAccessible(true); multiMapPut(callMC_cache, m.getName(), m); } c = c.getSuperclass(); } } } public static Object invokeMethod(Method m, Object o, Object... args) { try { try { return m.invoke(o, args); } catch (InvocationTargetException e) { throw rethrow(getExceptionCause(e)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(e.getMessage() + " - was calling: " + m + ", args: " + joinWithSpace(classNames(args))); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) print("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) { Object arg = args[i]; if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) { if (debug) print("Bad parameter " + i + ": " + arg + " vs " + types[i]); return false; } } return true; } public static String beautifyStructure(String s) { List tok = javaTok(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } public static String struct_noStringSharing(Object o) { structure_Data d = new structure_Data(); d.noStringSharing = true; return structure(o, d); } public static List beginCriticalAction_inFlight = synchroList(); public static class CriticalAction { public String description; public CriticalAction() { } public CriticalAction(String description) { this.description = description; } public void done() { beginCriticalAction_inFlight.remove(this); } } public static CriticalAction beginCriticalAction(String description) { ping(); CriticalAction c = new CriticalAction(description); beginCriticalAction_inFlight.add(c); return c; } public static 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 void 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(); } } catch (Exception __e) { throw rethrow(__e); } } public static FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } public static FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } public static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } public static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } public static Class javax() { return getJavaX(); } public static Object[] dropEntryFromParams(Object[] params, int i) { int n = l(params); if (i < 0 || i >= n) return params; if (n == 2) return null; Object[] p = new Object[n - 2]; System.arraycopy(params, 0, p, 0, i); System.arraycopy(params, i + 2, p, i, n - i - 2); return p; } public static 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; } public static List filterConcepts(List list, Object... params) { List l = new ArrayList(); for (A x : list) if (checkConceptFields(x, params)) l.add(x); return l; } public static TreeSet caseInsensitiveSet() { return caseInsensitiveSet_treeSet(); } public static TreeSet caseInsensitiveSet(Collection c) { return caseInsensitiveSet_treeSet(c); } public static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; public static CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } public static CloseableIterableIterator linesFromReader(Reader r) { final BufferedReader br = bufferedReader(r); return iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret readLineFromReaderWithClose(br);"; } }, _wrapIOCloseable(r)); } public static BufferedReader utf8bufferedReader(InputStream in) { try { return bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } public static BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } public static GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } public static boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } public static boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } public static boolean endsWith(String a, String b, Matches m) { if (!endsWith(a, b)) return false; m.m = new String[] { dropLast(l(b), a) }; return true; } public static boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } public static Object unstructure(String text) { return unstructure(text, false); } public static Object unstructure(String text, final boolean allDynamic) { return unstructure(text, allDynamic, null); } public static int structure_internStringsLongerThan = 50; public static int unstructure_unquoteBufSize = 100; public static int unstructure_tokrefs; public abstract static class unstructure_Receiver { public abstract void set(Object o); } public static Object unstructure(String text, boolean allDynamic, Object classFinder) { if (text == null) return null; return unstructure_tok(javaTokC_noMLS_iterator(text), allDynamic, classFinder); } public static Object unstructure_reader(BufferedReader reader) { return unstructure_tok(javaTokC_noMLS_onReader(reader), false, null); } public static Object unstructure_tok(final Producer tok, final boolean allDynamic, final Object _classFinder) { final boolean debug = unstructure_debug; final class X { public int i = -1; public final Object classFinder = _classFinder != null ? _classFinder : _defaultClassFinder(); public HashMap refs = new HashMap(); public HashMap tokrefs = new HashMap(); public HashSet concepts = new HashSet(); public HashMap classesMap = new HashMap(); public List stack = new ArrayList(); public String curT; public char[] unquoteBuf = new char[unstructure_unquoteBufSize]; public String unquote(String s) { return unquoteUsingCharArray(s, unquoteBuf); } public String t() { return curT; } public String tpp() { String t = curT; consume(); return t; } public void parse(final unstructure_Receiver out) { String t = t(); int refID = 0; if (structure_isMarker(t, 0, l(t))) { refID = parseInt(t.substring(1)); consume(); } final int _refID = refID; final int tokIndex = i; parse_inner(refID, tokIndex, new unstructure_Receiver() { public void set(Object o) { if (_refID != 0) refs.put(_refID, o); if (o != null) tokrefs.put(tokIndex, o); out.set(o); } }); } public void parse_inner(int refID, int tokIndex, final unstructure_Receiver out) { String t = t(); Class c = classesMap.get(t); if (c == null) { if (t.startsWith("\"")) { String s = internIfLongerThan(unquote(tpp()), structure_internStringsLongerThan); out.set(s); return; } if (t.startsWith("'")) { out.set(unquoteCharacter(tpp())); return; } if (t.equals("bigint")) { out.set(parseBigInt()); return; } if (t.equals("d")) { out.set(parseDouble()); return; } if (t.equals("fl")) { out.set(parseFloat()); return; } if (t.equals("sh")) { consume(); t = tpp(); if (t.equals("-")) { t = tpp(); out.set((short) (-parseInt(t))); return; } out.set((short) parseInt(t)); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("false") || t.equals("f")) { consume(); out.set(false); return; } if (t.equals("true") || t.equals("t")) { consume(); out.set(true); return; } if (t.equals("-")) { consume(); t = tpp(); out.set(isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t))); return; } if (isInteger(t) || isLongConstant(t)) { consume(); if (isLongConstant(t)) { out.set(parseLong(t)); return; } long l = parseLong(t); boolean isInt = l == (int) l; out.set(isInt ? (Object) Integer.valueOf((int) l) : (Object) Long.valueOf(l)); return; } if (t.equals("File")) { consume(); File f = new File(unquote(tpp())); out.set(f); return; } if (t.startsWith("r") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) throw fail("unsatisfied back reference " + ref); out.set(o); return; } if (t.startsWith("t") && isInteger(t.substring(1))) { consume(); int ref = Integer.parseInt(t.substring(1)); Object o = tokrefs.get(ref); if (o == null) throw fail("unsatisfied token reference " + ref + " at " + tokIndex); out.set(o); return; } if (t.equals("hashset")) { parseHashSet(out); return; } if (t.equals("lhs")) { parseLinkedHashSet(out); return; } if (t.equals("treeset")) { parseTreeSet(out); return; } if (t.equals("ciset")) { parseCISet(out); return; } if (eqOneOf(t, "hashmap", "hm")) { consume(); parseMap(new HashMap(), out); return; } if (t.equals("lhm")) { consume(); parseMap(new LinkedHashMap(), out); return; } if (t.equals("tm")) { consume(); parseMap(new TreeMap(), out); return; } if (t.equals("cimap")) { consume(); parseMap(ciMap(), out); return; } if (t.equals("ll")) { consume(); { parseList(new LinkedList(), out); return; } } if (t.equals("syncLL")) { consume(); { parseList(synchroLinkedList(), out); return; } } if (t.equals("sync")) { consume(); if (t().equals("tm")) { consume(); { parseMap(synchronizedTreeMap(), out); return; } } if (t().equals("[")) { parseList(synchroList(), out); return; } { parseMap(synchronizedMap(), out); return; } } if (t.equals("{")) { parseMap(out); return; } if (t.equals("[")) { this.parseList(new ArrayList(), out); return; } if (t.equals("bitset")) { parseBitSet(out); return; } if (t.equals("array") || t.equals("intarray")) { parseArray(out); return; } if (t.equals("ba")) { consume(); String hex = unquote(tpp()); out.set(hexToBytes(hex)); return; } if (t.equals("boolarray")) { consume(); int n = parseInt(tpp()); String hex = unquote(tpp()); out.set(boolArrayFromBytes(hexToBytes(hex), n)); return; } if (t.equals("class")) { out.set(parseClass()); return; } if (t.equals("l")) { parseLisp(out); return; } if (t.equals("null")) { consume(); out.set(null); return; } if (eq(t, "c")) { consume("c"); t = t(); assertTrue(isJavaIdentifier(t)); concepts.add(t); } } if (eq(t, "j")) { consume("j"); out.set(parseJava()); return; } if (c == null && !isJavaIdentifier(t)) throw new RuntimeException("Unknown token " + (i + 1) + ": " + t); consume(); String className, fullClassName; if (eq(t(), ".")) { consume(); className = fullClassName = t + "." + assertIdentifier(tpp()); } else { className = t; fullClassName = "main$" + t; } if (c == null) { if (allDynamic) c = null; else c = classFinder != null ? (Class) callF(classFinder, fullClassName) : findClass_fullName(fullClassName); if (c != null) classesMap.put(className, c); } boolean hasBracket = eq(t(), "("); if (hasBracket) consume(); boolean hasOuter = hasBracket && eq(t(), "this$1"); DynamicObject dO = null; Object o = null; final String thingName = t; if (c != null) { o = hasOuter ? nuStubInnerObject(c, classFinder) : nuEmptyObject(c); if (o instanceof DynamicObject) dO = (DynamicObject) o; } else { if (concepts.contains(t) && (c = findClass("Concept")) != null) o = dO = (DynamicObject) nuEmptyObject(c); else dO = new DynamicObject(); dO.className = className; } if (refID != 0) refs.put(refID, o != null ? o : dO); tokrefs.put(tokIndex, o != null ? o : dO); final LinkedHashMap fields = new LinkedHashMap(); final Object _o = o; final DynamicObject _dO = dO; if (hasBracket) { stack.add(new Runnable() { public void run() { try { if (eq(t(), ")")) { consume(")"); objRead(_o, _dO, fields); out.set(_o != null ? _o : _dO); } else { final String key = unquote(tpp()); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " after " + quote(key) + " in object " + thingName); stack.add(this); parse(new unstructure_Receiver() { public void set(Object value) { fields.put(key, value); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \")\")) {\r\n consume(\")\");\r\n objRead(_o, _dO, ..."; } }); } else { objRead(o, dO, fields); out.set(o != null ? o : dO); } } public void objRead(Object o, DynamicObject dO, Map fields) { if (o != null) if (dO != null) { setOptAllDyn(dO, fields); } else { setOptAll_pcall(o, fields); } else for (String field : keys(fields)) dO.fieldValues.put(intern(field), fields.get(field)); if (o != null) pcallOpt_noArgs(o, "_doneLoading"); } public void parseSet(final Set set, final unstructure_Receiver out) { this.parseList(new ArrayList(), new unstructure_Receiver() { public void set(Object o) { set.addAll((List) o); out.set(set); } }); } public void parseLisp(final unstructure_Receiver out) { throw fail("class Lisp not included"); } public void parseBitSet(final unstructure_Receiver out) { consume("bitset"); consume("{"); final BitSet bs = new BitSet(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(bs); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { bs.set((Integer) o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(bs);\r\n ..."; } }); } public void parseList(final List list, final unstructure_Receiver out) { consume("["); stack.add(new Runnable() { public void run() { try { if (eq(t(), "]")) { consume("]"); out.set(list); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"]\")) {\r\n consume(\"]\");\r\n out.set(list);\r\n ..."; } }); } public void parseArray(final unstructure_Receiver out) { final String type = tpp(); consume("{"); final List list = new ArrayList(); stack.add(new Runnable() { public void run() { try { if (eq(t(), "}")) { consume("}"); out.set(type.equals("intarray") ? toIntArray(list) : list.toArray()); } else { stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { list.add(o); if (eq(t(), ",")) consume(); } }); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "if (eq(t(), \"}\")) {\r\n consume(\"}\");\r\n out.set(type.equals(\"..."; } }); } public Object parseClass() { consume("class"); consume("("); String name = unquote(tpp()); consume(")"); Class c = allDynamic ? null : classFinder != null ? (Class) callF(classFinder, name) : findClass_fullName(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; name = dropPrefix("main$", name); dO.fieldValues.put("name", name); return dO; } public Object parseBigInt() { consume("bigint"); consume("("); String val = tpp(); if (eq(val, "-")) val = "-" + tpp(); consume(")"); return new BigInteger(val); } public Object parseDouble() { consume("d"); consume("("); String val = unquote(tpp()); consume(")"); return Double.parseDouble(val); } public Object parseFloat() { consume("fl"); String val; if (eq(t(), "(")) { consume("("); val = unquote(tpp()); consume(")"); } else { val = unquote(tpp()); } return Float.parseFloat(val); } public void parseHashSet(unstructure_Receiver out) { consume("hashset"); parseSet(new HashSet(), out); } public void parseLinkedHashSet(unstructure_Receiver out) { consume("lhs"); parseSet(new LinkedHashSet(), out); } public void parseTreeSet(unstructure_Receiver out) { consume("treeset"); parseSet(new TreeSet(), out); } public void parseCISet(unstructure_Receiver out) { consume("ciset"); parseSet(ciSet(), out); } public void parseMap(unstructure_Receiver out) { parseMap(new TreeMap(), out); } public Object parseJava() { String j = unquote(tpp()); Matches m = new Matches(); if (jmatch("java.awt.Color[r=*,g=*,b=*]", j, m)) return nuObject("java.awt.Color", parseInt(m.unq(0)), parseInt(m.unq(1)), parseInt(m.unq(2))); else { warn("Unknown Java object: " + j); return null; } } public void parseMap(final Map map, final unstructure_Receiver out) { consume("{"); stack.add(new Runnable() { public boolean v = false; public Object key; public void run() { if (v) { v = false; stack.add(this); if (!eq(tpp(), "=")) throw fail("= expected, got " + t() + " in map of size " + l(map)); parse(new unstructure_Receiver() { public void set(Object value) { map.put(key, value); if (eq(t(), ",")) consume(); } }); } else { if (eq(t(), "}")) { consume("}"); out.set(map); } else { v = true; stack.add(this); parse(new unstructure_Receiver() { public void set(Object o) { key = o; } }); } } } }); } public void consume() { curT = tok.next(); ++i; } public void consume(String s) { if (!eq(t(), s)) { throw fail(quote(s) + " expected, got " + quote(t())); } consume(); } public void parse_x(unstructure_Receiver out) { consume(); parse(out); while (nempty(stack)) popLast(stack).run(); } } Boolean b = DynamicObject_loading.get(); DynamicObject_loading.set(true); try { final Var v = new Var(); X x = new X(); x.parse_x(new unstructure_Receiver() { public void set(Object o) { v.set(o); } }); unstructure_tokrefs = x.tokrefs.size(); return v.get(); } finally { DynamicObject_loading.set(b); } } public static boolean unstructure_debug = false; public static Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } public static Lock appendToFile_lock = lock(); public static boolean appendToFile_keepOpen = false; public static HashMap appendToFile_writers = new HashMap(); public static void appendToFile(String path, String s) { try { Lock __1298 = appendToFile_lock; lock(__1298); try { mkdirsForFile(new File(path)); path = getCanonicalPath(path); Writer writer = appendToFile_writers.get(path); if (writer == null) { writer = new BufferedWriter(new OutputStreamWriter(newFileOutputStream(path, true), "UTF-8")); if (appendToFile_keepOpen) appendToFile_writers.put(path, writer); } writer.write(s); if (!appendToFile_keepOpen) writer.close(); } finally { unlock(__1298); } } catch (Exception __e) { throw rethrow(__e); } } public static void appendToFile(File path, String s) { if (path != null) appendToFile(path.getPath(), s); } public static void cleanMeUp_appendToFile() { AutoCloseable __1301 = tempCleaningUp(); try { Lock __1300 = appendToFile_lock; lock(__1300); try { closeAllWriters(values(appendToFile_writers)); appendToFile_writers.clear(); } finally { unlock(__1300); } } finally { _close(__1301); } } public static A assertEquals(Object x, A y) { return assertEquals(null, x, y); } public static A assertEquals(String msg, Object x, A y) { if (assertVerbose()) return assertEqualsVerbose(msg, x, y); if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + y + " != " + x); return y; } public static void quoteToPrintWriter(String s, PrintWriter out) { if (s == null) { out.print("null"); return; } out.print('"'); int l = s.length(); for (int i = 0; i < l; i++) { char c = s.charAt(i); if (c == '\\' || c == '"') { out.print('\\'); out.print(c); } else if (c == '\r') out.print("\\r"); else if (c == '\n') out.print("\\n"); else if (c == '\0') out.print("\\0"); else out.print(c); } out.print('"'); } public static String quoteCharacter(char c) { if (c == '\'') return "'\\''"; if (c == '\\') return "'\\\\'"; if (c == '\r') return "'\\r'"; if (c == '\n') return "'\\n'"; if (c == '\t') return "'\\t'"; return "'" + c + "'"; } public static boolean isCISet_gen(Iterable l) { return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp"); } public static List unwrapSynchronizedList(List l) { if (eqOneOf(className(l), "java.util.Collections$SynchronizedList", "java.util.Collections$SynchronizedRandomAccessList")) return (List) get_raw(l, "list"); return l; } public static boolean isCIMap_gen(Map map) { return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp"); } public static String boolArrayToHex(boolean[] a) { return bytesToHex(boolArrayToBytes(a)); } public static Iterator emptyIterator() { return Collections.emptyIterator(); } public static String shortDynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; return shortClassName(o); } public static Map getDeclaredFields_cache = newDangerousWeakHashMap(); public static Field[] getDeclaredFields_cached(Class c) { Field[] fields; synchronized (getDeclaredFields_cache) { fields = getDeclaredFields_cache.get(c); if (fields == null) { getDeclaredFields_cache.put(c, fields = c.getDeclaredFields()); for (Field f : fields) f.setAccessible(true); } } return fields; } public static String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } public static boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } public static Map putAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } public static File getProgramDir() { return programDir(); } public static File getProgramDir(String snippetID) { return programDir(snippetID); } public static Object pcallF(Object f, Object... args) { return pcallFunction(f, args); } public static A pcallF(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { return null; } } public static B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { return null; } } public static void pcallF(VF1 f, A a) { try { if (f != null) f.get(a); } catch (Throwable __e) { _handleException(__e); } } public static ConceptFieldIndexCI getConceptFieldCIIndex(Class c, String field) { return getConceptFieldCIIndex(db_mainConcepts(), c, field); } public static ConceptFieldIndexCI getConceptFieldCIIndex(Concepts concepts, Class c, String field) { return (ConceptFieldIndexCI) concepts.getCIFieldIndex(c, field); } public static Comparator caseInsensitiveComparator() { return betterCIComparator(); } public static void rotateStringBuffer(StringBuffer buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } public static void rotateStringBuilder(StringBuilder buf, int max) { try { if (buf == null) return; synchronized (buf) { if (buf.length() <= max) return; try { int newLength = max / 2; int ofs = buf.length() - newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } buf.trimToSize(); } } catch (Exception __e) { throw rethrow(__e); } } public static String getClientIPFromHeaders(Map headers) { if (headers == null) return null; String remoteAddr = (String) (headers.get("remote-addr")); String client = (String) (headers.get("x-forwarded-for")); if (nempty(client)) remoteAddr += "," + client; return remoteAddr; } public static boolean isJavaIdentifier(String s) { if (empty(s) || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } public static Map classForName_cache = synchroHashMap(); public static 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); } } public static Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap(); public static Object nuObjectWithoutArguments(String className) { try { return nuObjectWithoutArguments(classForName(className)); } catch (Exception __e) { throw rethrow(__e); } } public static A nuObjectWithoutArguments(Class c) { try { if (nuObjectWithoutArguments_cache == null) return (A) nuObjectWithoutArguments_findConstructor(c).newInstance(); Constructor m = nuObjectWithoutArguments_cache.get(c); if (m == null) nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c)); return (A) m.newInstance(); } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuObjectWithoutArguments_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) { m.setAccessible(true); return m; } throw fail("No default constructor found in " + c.getName()); } public static List getClasses(Object[] array) { List l = new ArrayList(); for (Object o : array) l.add(_getClass(o)); return l; } public static boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } public static List sorted(Collection c, final Object comparator) { List l = cloneList(c); sort(l, makeComparator(comparator)); return l; } public static List sorted(Collection c) { List l = cloneList(c); sort(l); return l; } public static 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)"; } }); } public static String join(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return str(first(((Collection) strings))); } StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(Iterable strings) { return join("", strings); } public static String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } public static String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } public static boolean isJavaXClassLoader(ClassLoader cl) { return startsWithOneOf(className(cl), "main$JavaXClassLoader", "x30$JavaXClassLoader"); } public static void setOptAll(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) setOpt(o, field, fields.get(field)); } public static 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); } } public static String _userHome; public static String userHome() { if (_userHome == null) return actualUserHome(); return _userHome; } public static File userHome(String path) { return new File(userDir(), path); } public static boolean fileExists(String path) { return path != null && new File(path).exists(); } public static boolean fileExists(File f) { return f != null && f.exists(); } public static boolean isDirectory(File f) { return f != null && f.isDirectory(); } public static boolean isDirectory(String path) { return path != null && isDirectory(newFile(path)); } public static File[] listFiles(File dir) { File[] files = dir.listFiles(); return files == null ? new File[0] : files; } public static File[] listFiles(String dir) { return listFiles(new File(dir)); } public static boolean isSymLink(File f) { return f != null && Files.isSymbolicLink(toPath(f)); } public static Path fileToPath(File f) { return toPath(f); } public static boolean isFile(File f) { return f != null && f.isFile(); } public static boolean isFile(String path) { return isFile(newFile(path)); } public static File mkdirs(File dir) { if (dir != null) dir.mkdirs(); return dir; } public static boolean deleteFile(File file) { return file != null && file.delete(); } public static List listFilesNotDirs(String dir) { return listFilesOnly(dir); } public static List listFilesNotDirs(File... dirs) { return listFilesOnly(dirs); } public static int matcherInt(Matcher m, int i) { return parseInt(m.group(i)); } public static long timestampFromYMDH(int y, int m, int d, int h) { return new GregorianCalendar(y, m - 1, d, h, 0).getTimeInMillis(); } public static List sortByMap_inPlace(List l, Map map) { sort(l, mapComparator(map)); return l; } public static String n(long l, String name) { return l + " " + trim(l == 1 ? singular(name) : getPlural(name)); } public static String n(Collection l, String name) { return n(l(l), name); } public static String n(Map m, String name) { return n(l(m), name); } public static String n(Object[] a, String name) { return n(l(a), name); } public static String n(MultiSet ms, String name) { return n(l(ms), name); } public static boolean defaultAgeBasedBackupRetentionStrategy_shouldKeep(double age, double lastAge) { if (age <= 0.5) return true; if (age <= 7 && age >= lastAge + 1) return true; if (age >= lastAge + 7) return true; return false; } public static File javaxSecretDir_dir; public static File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } public static File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } public static FixedRateTimer doEvery(long delay, final Object r) { return doEvery(delay, delay, r); } public static FixedRateTimer doEvery(long delay, long firstDelay, final Object r) { FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80)); timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay)); return timer; } public static FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) { return doEvery(toMS(delaySeconds), toMS(initialSeconds), r); } public static FixedRateTimer doEvery(double delaySeconds, final Object r) { return doEvery(toMS(delaySeconds), r); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } public static String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } public static String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return "" + parseLong(snippetID); } public static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } public static String formatSnippetID(long id) { return "#" + id; } public static Class getMainClass() { return mc(); } public static Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Exception __e) { throw rethrow(__e); } } public static String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } public static String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } public static String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } public static boolean checkConceptFieldsIC(Concept x, Object... data) { for (int i = 0; i < l(data); i += 2) if (!eqicOrEq(cget(x, (String) data[i]), deref(data[i + 1]))) return false; return true; } public static List javaTokWithBrackets(String s) { return javaTokPlusBrackets(s); } public static int lCodeTokens(List tok) { return l(tok) / 2; } public static boolean eqGet(List l, int i, Object o) { return eq(get(l, i), o); } public static boolean eqGet(Map map, A key, Object o) { return eq(mapGet(map, key), o); } public static boolean isIdentifier(String s) { return isJavaIdentifier(s); } public static T3 agiBlue_parseTriple(String s) { return agiBlue_parseTriple(javaTokWithBrackets(s)); } public static T3 agiBlue_parseTriple(List tok) { List split = tok_splitAtSlashes(tok); if (l(split) != 3 || !allNempty(split)) return null; return listToTriple(uncurlyAll(split)); } public static String uncurly(String s) { return tok_unCurlyBracket(s); } public static boolean containsDollarVars(String s) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) if (isDollarVar(tok.get(i))) return true; return false; } public static String javaDropComments(String s) { return javaDropAllComments(s); } public static boolean containsNewLine(String s) { return contains(s, '\n'); } public static void addIfNempty(Collection l, String s) { if (nempty(s)) l.add(s); } public static void addIfNempty(Collection l, Map m) { if (nempty(m)) l.add(m); } public static void addIfNempty(Collection l, Collection c) { if (nempty(c)) l.add(c); } public static String joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } public static String joinSubList(List l, int i) { return join(subList(l, i)); } public static String jsonEncode_shallowLineBreaks(Object o) { return jsonEncode_breakAtLevel1(o); } public static void jsonEncode_shallowLineBreaks(Object o, StringBuilder buf, int level) { jsonEncode_breakAtLevel1(o, buf, level); } public static A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } public static void withCancelPoint(VF1 r) { CancelPoint cp = newCancelPoint(); try { try { callF(r, cp); } catch (Throwable e) { e = innerException(e); if (!(e instanceof CancelToCancelPoint && ((CancelToCancelPoint) e).cp == cp)) rethrow(e); } } finally { _close(cp); } } public static RuntimeException cancelTo(CancelPoint cp) { if (cp.closed) throw fail("cancel point closed"); throw new CancelToCancelPoint(cp); } public static String dollarVarsToStars(String s) { return dollarVarsToStars(s, null); } public static String dollarVarsToStars(String s, List varNames_out) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (isDollarVar(t)) { listAdd(varNames_out, t); tok.set(i, "*"); } else if (eq(t, "*")) listAdd(varNames_out, "*"); } return join(tok); } public static boolean flexMatchIC_iterate_debug = false; public static void flexMatchIC_iterate(String pat, String input, VF1 onMatch) { if (flexMatchIC_iterate_debug) print("flexMatchIC_iterate " + pat + " / " + input); List tokPat = javaTokNPunctuation_plusAsterisk(pat), tokInput = javaTokNPunctuation_plusAsterisk(input); List varIndices = new ArrayList(); for (int i = 1; i < l(tokPat); i += 2) { String t = tokPat.get(i); if (eq(t, "*")) varIndices.add(i); else if (isIdentifier(t) && !cicAtOddPosition(tokInput, t)) { if (flexMatchIC_iterate_debug) print("Crucial word fail (" + t + "): " + pat + " / " + input); return; } } if (flexMatchIC_iterate_debug) printStructs("varIndices", varIndices, "tokPat", tokPat, "tokInput", tokInput); List> spreadInputs = ai_spreadCertainIndices_2(tokPat, tokInput, varIndices); for (List tok : spreadInputs) { if (flexMatchIC_iterate_debug) print("Testing spread input: " + sfu(tok)); Matches m = new Matches(); if (match(pat, tok, m)) callF(onMatch, m); } } public static Map matchesToMapUsingVarList_ciMap(Matches m, List vars) { if (m == null) return null; Map map = ciMap(); int n = min(l(m.m), l(vars)); for (int i = 0; i < n; i++) if (!strictPutIC(map, vars.get(i), m.get(i))) return null; return map; } public static boolean isCurlyBraced(String s) { List tok = tok_combineCurlyBrackets_keep(javaTok(s)); return l(tok) == 3 && startsWithAndEndsWith(tok.get(1), "{", "}"); } public static String curlyBrace(String s) { return "{" + s + "}"; } public static String makePostData(Map map) { StringBuilder buf = new StringBuilder(); for (Map.Entry e : map.entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } public static String makePostData(Object... params) { StringBuilder buf = new StringBuilder(); int n = l(params); for (int i = 0; i + 1 < n; i += 2) { String key = (String) (params[i]); Object val = params[i + 1]; if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode((value))); } } return str(buf); } public static void assertFalse(Object o) { if (!(eq(o, false))) throw fail(str(o)); } public static boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } public static boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } public static boolean _inCore() { return false; } public static Class __javax; public static Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } public static int isAndroid_flag; public static boolean isAndroid() { if (isAndroid_flag == 0) isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1; return isAndroid_flag > 0; } public static Object hotwire_onCompile; public static boolean hotwire_serially = false; public static Lock hotwire_overInternalBot_lock = lock(); public static boolean hotwire_compileOnServer = false; public static Class hotwire_overInternalBot(String progID) { return hotwire_overInternalBot(progID, "main"); } public static Class hotwire_overInternalBot(String progID, String mainClass) { try { Pair p; try { p = hotwire_compile(progID); } catch (Throwable e) { throw rethrow("Error hotwiring " + progID, e); } File jar = p.a; assertTrue(jar.getAbsolutePath(), jar.isFile()); List files = hotwire_collectJars(jar); JavaXClassLoader classLoader = hotwire_makeClassLoader(files); classLoader.progID = progID; return hotwire_finish(classLoader, progID, p.b, mainClass); } catch (Exception __e) { throw rethrow(__e); } } public static Pair hotwire_compile(String progID) { Pair p = hotwire_compileOnServer && !isLocalSnippetID(progID) ? compileSnippetThroughServer(progID) : CompilerBot.compileSnippet2(progID); Lock __1465 = hotwire_serially ? hotwire_overInternalBot_lock : null; lock(__1465); try { callF(hotwire_onCompile, p); return p; } finally { unlock(__1465); } } public static List dependentClasses() { return cleanUpAndGetWeakReferencesList(hotwire_classes); } public static String[] toStringArray(Collection c) { String[] a = new String[l(c)]; Iterator it = c.iterator(); for (int i = 0; i < l(a); i++) a[i] = it.next(); return a; } public static String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof Collection) return toStringArray((Collection) o); else throw fail("Not a collection or array: " + getClassName(o)); } public static boolean eqicOrEq(Object a, Object b) { return a instanceof String && b instanceof String ? eqic((String) a, (String) b) : eq(a, b); } public static boolean regexpICMatches(String pat, String s) { return regexpIC(pat, s).matches(); } public static boolean regexpICMatches(Pattern pat, String s) { return pat.matcher(s).matches(); } public static boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } public static Map decodeHQuery(String query) { Map map = new HashMap(); for (String s : splitAtAmpersand(query)) { int i = s.indexOf('='); if (i >= 0) map.put(urldecode(s.substring(0, i)), urldecode(s.substring(i + 1))); } return map; } public static String getQueryFromURL(String url) { return substring(url, smartIndexOf(url, "?") + 1); } public static String intToHex_flexLength(int i) { return Integer.toHexString(i); } public static Object sleepQuietly_monitor = new Object(); public static void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized (sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } public static String dropFrom(String s, String x) { if (s == null) return null; int i = s.indexOf(x); if (i < 0) return s; return substring(s, 0, i); } public static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } public static Matcher regexp(String pat, String s) { return regexp(compileRegexp(pat), unnull(s)); } public static Matcher regexp(Pattern pat, String s) { return pat.matcher(unnull(s)); } public static Pattern regexp(String pat) { return compileRegexp(pat); } public static Object callOpt_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.findMethod(method, args); if (me == null) { return null; } if ((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(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); } return null; } } catch (Exception __e) { throw rethrow(__e); } } public static boolean allLowerCaseCharacters(String s) { for (int i = 0; i < l(s); i++) if (Character.getType(s.charAt(i)) != Character.LOWERCASE_LETTER) return false; return true; } public static String shortenClassName(String name) { if (name == null) return null; int i = lastIndexOf(name, "$"); if (i < 0) i = lastIndexOf(name, "."); return i < 0 ? name : substring(name, i + 1); } public static boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } public static boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } public static List splitAtAmpersand(String s) { return s == null ? emptyList() : asList(s.split("&")); } public static String urldecode(String x) { try { return URLDecoder.decode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static String unpackAGIDomain(String s) { return isAGIDomain(s) ? dropSuffixIC(".agi.blue", s) : null; } public static String className(Object o) { return getClassName(o); } public static String stringOptPar(Object[] params, String name) { return (String) optPar(params, name); } public static String unicodeFromCodePoint(int codePoint) { return codePointToString(codePoint); } public static String charToString(char c) { return String.valueOf(c); } public static String charToString(int c) { return String.valueOf((char) c); } public static 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; } public static 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; } public static ArrayList toList(A[] a) { return asList(a); } public static ArrayList toList(int[] a) { return asList(a); } public static ArrayList toList(Set s) { return asList(s); } public static ArrayList toList(Iterable s) { return asList(s); } public static Object[] changeParam(Object[] params, String name, Object value) { if (eq(optPar(params, name), value)) return params; Map map = paramsToOrderedMap(params); map.put(name, value); return mapToParams(map); } public static boolean isString(Object o) { return o instanceof String; } public static Object dm_getService(String serviceName) { return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName))); } public static boolean isStringOrIntOrLong(Object o) { return o instanceof String || o instanceof Integer || o instanceof Long; } public static Object dm_callOS(String functionName, Object... args) { return call(dm_os(), functionName, args); } public static Object dm_resolveModule(Object moduleOrStem) { return dm_callOS("resolveModule", moduleOrStem); } public static final Map callOpt_cache = newDangerousWeakHashMap(); public static Object callOpt_cached(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null || (me.getModifiers() & Modifier.STATIC) == 0) return null; return invokeMethod(me, null, args); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me == null) return null; return invokeMethod(me, o, args); } } catch (Exception __e) { throw rethrow(__e); } } public static _MethodCache callOpt_getCache(Class c) { synchronized (callOpt_cache) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } } public static boolean isStaticMethod(Method m) { return methodIsStatic(m); } public static Object[] massageArgsForVarArgsCall(Method m, Object[] args) { Class[] types = m.getParameterTypes(); int n = types.length - 1, nArgs = args.length; if (nArgs < n) return null; for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i])) return null; Class varArgType = types[n].getComponentType(); for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType)) return null; Object[] newArgs = new Object[n + 1]; arraycopy(args, 0, newArgs, 0, n); Object[] varArgs = arrayOfType(varArgType, nArgs - n); arraycopy(args, n, varArgs, 0, nArgs - n); newArgs[n] = varArgs; return newArgs; } public static List classNames(Collection l) { return getClassNames(l); } public static List classNames(Object[] l) { return getClassNames(Arrays.asList(l)); } public static Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } public static LinkedHashMap paramsToOrderedMap(Object... params) { return asLinkedHashMap(paramsToMap(params)); } public static Object[] mapToParams(Map map) { return mapToObjectArray(map); } public static String joinWithSemicolon(Iterable l) { return join("; ", l); } public static void litmap_impl_noOverwrite(Map map, Object... x) { if (x != null) for (int i = 0; i < x.length - 1; i += 2) putIfNotThere(map, x[i], x[i + 1]); } public static List trimAll(Collection l) { List l2 = new ArrayList(); if (l != null) for (String s : l) l2.add(trim(s)); return l2; } public static List splitAt(String s, String splitter) { List parts = new ArrayList(); int i = 0; if (s != null) while (i < l(s)) { int j = indexOf(s, splitter, i); if (j < 0) j = l(s); parts.add(substring(s, i, j)); i = j + l(splitter); } return parts; } public static List splitAtColon(String s) { return empty(s) ? emptyList() : asList(s.split(":")); } public static int indexOfIgnoreCase(List a, String b) { return indexOfIgnoreCase(a, b, 0); } public static int indexOfIgnoreCase(List a, String b, int i) { int n = a == null ? 0 : a.size(); for (; i < n; i++) if (eqic(a.get(i), b)) return i; return -1; } public static int indexOfIgnoreCase(String a, String b) { return indexOfIgnoreCase_manual(a, b); } public static String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } public static BigInteger bigint(String s) { return new BigInteger(s); } public static BigInteger bigint(long l) { return BigInteger.valueOf(l); } public static volatile boolean licensed_yes = true; public static boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } public static void licensed_off() { licensed_yes = false; } public static Set vm_generalIdentityHashSet(Object name) { synchronized (get(javax(), "generalMap")) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = syncIdentityHashSet()); return set; } } public static Map vm_generalHashMap(Object name) { synchronized (get(javax(), "generalMap")) { Map m = (Map) (vm_generalMap_get(name)); if (m == null) vm_generalMap_put(name, m = syncHashMap()); return m; } } public static Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } public static RuntimeException wrapPatternSyntaxException(PatternSyntaxException e) { if (e == null) return null; String pat = e.getPattern(); int i = e.getIndex(); return new RuntimeException("Regular expression error between " + multiLineQuoteWithSpaces(substring(pat, 0, i)) + " and " + multiLineQuoteWithSpaces(substring(pat, i)) + " - " + e.getMessage()); } public static String trimLastLine(String s) { return trim(lastLine(s)); } public static A liftLast(List l) { if (l.isEmpty()) return null; int i = l(l) - 1; A a = l.get(i); l.remove(i); return a; } public static List jsonTok(String s) { List tok = new ArrayList(); int l = l(s); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); 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.isLetter(c)) do ++j; while (j < l && Character.isLetter(s.charAt(j))); else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static double parseDouble(String s) { return Double.parseDouble(s); } public static long parseLong(String s) { if (empty(s)) return 0; return Long.parseLong(dropSuffix("L", s)); } public static long parseLong(Object s) { return Long.parseLong((String) s); } public static String programIDWithCase() { return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID(); } public static Object defaultDefaultClassFinder() { return new F1() { public Class get(String name) { try { Class c = findClass_fullName(name); if (c != null) return c; if (startsWith(name, "loadableUtils.utils$")) return findClass_fullName("main" + substring(name, 19)); return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Class c = findClass_fullName(name);\r\n if (c != null) ret c;\r\n if (start..."; } }; } public static Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } public static double toSeconds(long ms) { return ms / 1000.0; } public static String toSeconds(long ms, int digits) { return formatDouble(toSeconds(ms), digits); } public static void clear(Collection c) { if (c != null) c.clear(); } public static void put(Map map, A a, B b) { if (map != null) map.put(a, b); } public static void put(List l, int i, A a) { if (l != null && i >= 0 && i < l(l)) l.set(i, a); } public static List _registerDangerousWeakMap_preList; public static A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } public static A _registerDangerousWeakMap(A map, Object init) { callF(init, map); if (init instanceof String) { final String f = (String) init; init = new VF1() { public void get(Map map) { try { callMC(f, map); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callMC(f, map)"; } }; } if (javax() == null) { if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } public static void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } public static Map synchroMap() { return synchroHashMap(); } public static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } public static B mapGet2(Map map, A a) { return map == null ? null : map.get(a); } public static B mapGet2(A a, Map map) { return map == null ? null : map.get(a); } public static Set reflection_classesNotToScan_value = litset("jdk.internal.loader.URLClassPath"); public static Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } public static String joinWithSpace(Collection c) { return join(" ", c); } public static String joinWithSpace(String... c) { return join(" ", c); } public static List words2(String s) { List l = new ArrayList(); int n = l(s); for (int i = 0; i < n; ) { int j = i; while (j < n && isLetterOrDigit(s.charAt(j))) ++j; if (j > i) l.add(substring(s, i, j)); while (j < n && !isLetterOrDigit(s.charAt(j))) ++j; i = j; } return l; } public static int compareIC(String s1, String s2) { return compareIgnoreCase_jdk(s1, s2); } public static String collapseString(String s) { return collapseWord(s); } public static List _registerWeakMap_preList; public static A _registerWeakMap(A map) { if (javax() == null) { if (_registerWeakMap_preList == null) _registerWeakMap_preList = synchroList(); _registerWeakMap_preList.add(map); return map; } try { call(javax(), "_registerWeakMap", map); } catch (Throwable e) { printException(e); print("Upgrade JavaX!!"); } return map; } public static void _onLoad_registerWeakMap() { assertNotNull(javax()); if (_registerWeakMap_preList == null) return; for (Object o : _registerWeakMap_preList) _registerWeakMap(o); _registerWeakMap_preList = null; } public static Boolean isHeadless_cache; public static boolean isHeadless() { if (isHeadless_cache != null) return isHeadless_cache; if (isAndroid()) return isHeadless_cache = true; if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true; try { SwingUtilities.isEventDispatchThread(); return isHeadless_cache = false; } catch (Throwable e) { return isHeadless_cache = true; } } public static Comparator mapComparator(final Map map) { return new Comparator() { public int compare(A a, A b) { return cmp(map.get(a), map.get(b)); } }; } public static List htmlcoarsetok(String s) { List tok = new ArrayList(); int l = 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; } public static File localSnippetFile(long snippetID) { return localSnippetsDir(snippetID + ".text"); } public static File localSnippetFile(String snippetID) { return localSnippetFile(parseSnippetID(snippetID)); } public static A proxy(Class intrface, final Object target) { if (target == null) return null; if (isInstance(intrface, target)) return (A) target; return (A) java.lang.reflect.Proxy.newProxyInstance(intrface.getClassLoader(), new Class[] { intrface }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { return call(target, method.getName(), unnull(args)); } }); } public static A proxy(Object target, Class intrface) { return proxy(intrface, target); } public static Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } public static String standardCredentialsUser() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-username"), userDir(".tinybrain/username")))); } public static String standardCredentialsPass() { return trim(loadTextFile(oneOfTheFiles(javaxSecretDir("tinybrain-userpass"), userDir(".tinybrain/userpass")))); } public static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); public static void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } public static File javaxCachesDir_dir; public static File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } public static File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } public static volatile boolean disableCertificateValidation_attempted = false; public static void disableCertificateValidation() { try { if (disableCertificateValidation_attempted) return; disableCertificateValidation_attempted = true; try { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } public static final boolean loadPageThroughProxy_enabled = false; public static String loadPageThroughProxy(String url) { return null; } public static void sleepSeconds(double s) { if (s > 0) sleep(round(s * 1000)); } public static A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } public static void setHeaders(URLConnection con) throws IOException { String computerID = getComputerID_quick(); if (computerID != null) try { con.setRequestProperty("X-ComputerID", computerID); con.setRequestProperty("X-OS", System.getProperty("os.name") + " " + System.getProperty("os.version")); } catch (Throwable e) { } } public static Map vm_generalSubMap(Object name) { synchronized (get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } public static InputStream urlConnection_getInputStream(URLConnection con) throws IOException { UnknownHostException lastException = null; for (int _repeat_1637 = 0; _repeat_1637 < 2; _repeat_1637++) { try { if (con instanceof HttpURLConnection) if (((HttpURLConnection) con).getResponseCode() == 500) throw new IOException(joinNemptiesWithColonSpace("Server code 500", tryToReadErrorStreamFromURLConnection(((HttpURLConnection) con)))); return con.getInputStream(); } catch (UnknownHostException e) { lastException = e; print("Retrying because of: " + e); continue; } } throw lastException; } public static String toHex(byte[] bytes) { return bytesToHex(bytes); } public static String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } public static byte[] utf8(String s) { return toUtf8(s); } public static Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } public static URLConnection openConnection(String url) { try { return openConnection(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } public static URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } public static URLConnection setURLConnectionTimeouts(URLConnection con, long timeout) { con.setConnectTimeout(toInt(timeout)); con.setReadTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout || con.getReadTimeout() != timeout) print("Warning: Timeouts not set by JDK."); return con; } public static URLConnection setURLConnectionDefaultTimeouts(URLConnection con, long timeout) { if (con.getConnectTimeout() == 0) { con.setConnectTimeout(toInt(timeout)); if (con.getConnectTimeout() != timeout) print("Warning: URL connect timeout not set by JDK."); } if (con.getReadTimeout() == 0) { con.setReadTimeout(toInt(timeout)); if (con.getReadTimeout() != timeout) print("Warning: URL read timeout not set by JDK."); } return con; } public static String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } public static boolean renameFile(File a, File b) { mkdirsForFile(b); return a.renameTo(b); } public static boolean renameFile(File a, String newName) { return renameFile(a, fileInSameDir(a, newName)); } public static List htmlTok(String s) { return htmlcoarsetok(s); } public static 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; } public static List> findContainerTag(String html, String tag) { return findContainerTag(htmlTok(html), tag); } public static String addLineBreak(String s) { return addSuffix(s, "\n"); } public static List keysWithoutHidden(Map map) { return filter(keys(map), new F1() { public Boolean get(Object o) { try { return !eq(o, "[hidden]") && !isStringStartingWith(o, "[hidden] "); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "!eq(o, \"[hidden]\") && !isStringStartingWith(o, \"[hidden] \")"; } }); } public static String structureOrTextForUser(Object o) { return o == null ? "" : o instanceof String ? (String) o : structureForUser(o); } public static String addSlash(String s) { return empty(s) || s.endsWith("/") ? s : s + "/"; } public static String hMakeComputerID() { return hjavascript("\r\n function makeComputerID() {\r\n var text = \"\";\r\n var possible = \"abcdefghijklmnopqrstuvwxyz\";\r\n\r\n for (var i = 0; i < 12; i++)\r\n text += possible.charAt(Math.floor(Math.random() * possible.length));\r\n return text;\r\n }\r\n \r\n var computerID = localStorage.getItem('computer-id');\r\n if (computerID == null || computerID.length != 12) {\r\n computerID = makeComputerID();\r\n localStorage.setItem('computer-id', computerID);\r\n }\r\n "); } public static String hreconnectingWebSockets() { return hjavascript_src_snippet("#1013374"); } public static String hjavascript(String script) { return tag("script", script, "type", "text/javascript"); } public static String nodes_pingCmd() { return "\r\n ws.send((working ? 'working' : 'idle') + '; cores=' + navigator.hardwareConcurrency + \"; id=\" + window.computerID\r\n + (window.benchResult != null ? \"; bench=\" + window.benchResult : \"\") \r\n + \"; b=\" + navigator.userAgent);\r\n "; } public static int subBot_currentPort() { return toInt(getOpt(subBot_httpd(), "myPort")); } public static boolean subBot_isHttps() { Object httpd = subBot_httpd(); return eqOneOf(httpd, getOpt(mainBot(), "serveHttps_server"), getOpt(mainBot(), "serveHttpsWithWebsockets_server")) || contains((Collection) getOpt(mainBot(), "serveHttpsWithWebsockets_multiplePorts_servers"), httpd); } public static String snippetImageURL(String snippetID) { return snippetImageURL(snippetID, "png"); } public static String snippetImageURL(String snippetID, String contentType) { if (isURL(snippetID)) return snippetID; long id = parseSnippetID(snippetID); String url; if (id == 1000010 || id == 1000012) url = "http://tinybrain.de:8080/tb/show-blobimage.php?id=" + id; else if (isImageServerSnippet(id)) url = imageServerLink(id); else url = "https://www.botcompany.de:8443/img/" + id; return url; } public static String rep(int n, char c) { return repeat(c, n); } public static String rep(char c, int n) { return repeat(c, n); } public static List rep(A a, int n) { return repeat(a, n); } public static List rep(int n, A a) { return repeat(n, a); } public static boolean isCIMap(Map m) { return m instanceof TreeMap && ((TreeMap) m).comparator() == caseInsensitiveComparator(); } public static Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } public static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } public static Class getClass(Object realm, String name) { try { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } catch (Exception __e) { throw rethrow(__e); } } public static String classNameToVM(String name) { return name.replace(".", "$"); } public static boolean hasClass(String name) { try { Class.forName(name); return true; } catch (Throwable _e) { return false; } } public static String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } public static Map vm_generalWeakSubMap(Object name) { synchronized (get(javax(), "generalMap")) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = newWeakMap()); return map; } } public static WeakReference weakRef(A a) { return newWeakReference(a); } public static Throwable unwrapTrivialExceptionWraps(Throwable e) { if (e == null) return e; while (e.getClass() == RuntimeException.class && e.getCause() != null && eq(e.getMessage(), str(e.getCause()))) e = e.getCause(); return e; } public static Throwable innerException2(Throwable e) { if (e == null) return null; while (empty(e.getMessage()) && e.getCause() != null) e = e.getCause(); return e; } public static long assumedClusterSize() { return 32768; } public static List findAllFiles_noDirs(List dirs) { return findAllFiles_noDirs(asObjectArray(dirs)); } public static List findAllFiles_noDirs(Object... dirs) { List l = new ArrayList(); for (Object dir : dirs) { if (dir instanceof String && ((String) dir).endsWith("/.")) { for (File f : listFiles(dropSuffix("/.", (String) dir))) if (f.isFile()) l.add(f); } else findAllFiles_noDirs_impl(toFile(dir), l); } return l; } public static void findAllFiles_noDirs_impl(File dir, List l) { for (File f : listFiles(dir)) { if (f.isDirectory()) findAllFiles_noDirs_impl(f, l); else l.add(f); } } public static List findAllFiles_noDirs_pred(File dir, Object pred) { List l = new ArrayList(); if (isTrue_callF(pred, dir)) findAllFiles_noDirs_pred_impl(dir, pred, l); return l; } public static void findAllFiles_noDirs_pred_impl(File dir, Object pred, List l) { for (File f : listFiles(dir)) { if (!isTrue_callF(pred, f)) continue; if (f.isDirectory()) findAllFiles_noDirs_pred_impl(f, pred, l); else l.add(f); } } public static int roundUpTo(int n, int x) { return (x + n - 1) / n * n; } public static long roundUpTo(long n, long x) { return (x + n - 1) / n * n; } public static Random defaultRandomGenerator() { return ThreadLocalRandom.current(); } public static Set listFields(Object c) { TreeSet fields = new TreeSet(); for (Field f : _getClass(c).getDeclaredFields()) fields.add(f.getName()); return fields; } public static 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; } public static Method findMethodNamed(Object obj, String method) { if (obj == null) return null; if (obj instanceof Class) return findMethodNamed((Class) obj, method); return findMethodNamed(obj.getClass(), method); } public static Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { m.setAccessible(true); return m; } c = c.getSuperclass(); } return null; } public static void upgradeJavaXAndRestart() { run("#1001639"); restart(); sleep(); } public static void multiMapPut(Map> map, A a, B b) { List l = map.get(a); if (l == null) map.put(a, l = new ArrayList()); l.add(b); } public static void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } public static Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } public static int javaTok_n, javaTok_elements; public static boolean javaTok_opt = false; public static List javaTok(String s) { ++javaTok_n; ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { ++j; break; } else if (c2 == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || 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; } public static List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } public static String structure_addTokenMarkers(String s) { return join(structure_addTokenMarkers(javaTok(s))); } public static List structure_addTokenMarkers(List tok) { TreeSet refs = new TreeSet(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("t") && isInteger(t.substring(1))) refs.add(parseInt(t.substring(1))); } if (empty(refs)) return tok; for (int i : refs) { int idx = i * 2 + 1; if (idx >= l(tok)) continue; String t = ""; if (endsWithLetterOrDigit(tok.get(idx - 1))) t = " "; tok.set(idx, t + "m" + i + " " + tok.get(idx)); } return tok; } public static String jreplace(String s, String in, String out) { return jreplace(s, in, out, null); } public static String jreplace(String s, String in, String out, Object condition) { List tok = javaTok(s); return jreplace(tok, in, out, condition) ? join(tok) : s; } public static boolean jreplace(List tok, String in, String out) { return jreplace(tok, in, out, false, true, null); } public static boolean jreplace(List tok, String in, String out, Object condition) { return jreplace(tok, in, out, false, true, condition); } public static boolean jreplace(List tok, String in, String out, boolean ignoreCase, boolean reTok, Object condition) { String[] toks = javaTokForJFind_array(in); int lTokin = toks.length * 2 + 1; boolean anyChange = false; int i = -1; for (int n = 0; n < 10000; n++) { i = findCodeTokens(tok, i + 1, ignoreCase, toks, condition); if (i < 0) return anyChange; List subList = tok.subList(i - 1, i + lTokin - 1); String expansion = jreplaceExpandRefs(out, subList); int end = i + lTokin - 2; clearAllTokens(tok, i, end); tok.set(i, expansion); if (reTok) reTok(tok, i, end); i = end; anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } public static boolean jreplace_debug = false; public static void sleepInCleanUp(long ms) { try { if (ms < 0) return; Thread.sleep(ms); } catch (Exception __e) { throw rethrow(__e); } } public static 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); } } public static void _registerIO(Object object, String path, boolean opened) { } public static TreeSet caseInsensitiveSet_treeSet() { return new TreeSet(caseInsensitiveComparator()); } public static TreeSet caseInsensitiveSet_treeSet(Collection c) { return toCaseInsensitiveSet_treeSet(c); } public static BufferedReader bufferedReader(Reader r) { return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r), r); } public static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } public void close() throws Exception { if (closeable != null) closeable.close(); } } ; return new IFF2(); } public static String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } public static AutoCloseable _wrapIOCloseable(final AutoCloseable c) { return c == null ? null : new AutoCloseable() { public String toString() { return "c.close();\r\n _registerIO(c, null, false);"; } public void close() throws Exception { c.close(); _registerIO(c, null, false); } }; } public static A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } public static FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } public static FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } public static int gzInputStream_defaultBufferSize = 65536; public static GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } public static GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } public static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } public static char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s) - 1); } public static Producer javaTokC_noMLS_iterator(final String s) { return javaTokC_noMLS_iterator(s, 0); } public static Producer javaTokC_noMLS_iterator(final String s, final int startIndex) { return new Producer() { public final int l = s.length(); public int i = startIndex; public String next() { if (i >= l) return null; int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } i = j; if (i >= l) return null; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else ++j; String t = quickSubstring(s, i, j); i = j; return t; } }; } public static Producer javaTokC_noMLS_onReader(final BufferedReader r) { final class X implements Producer { public StringBuilder buf = new StringBuilder(); public char c, d, e = 'x'; public X() { nc(); nc(); nc(); } public void nc() { try { c = d; d = e; if (e == '\0') return; int i = r.read(); e = i < 0 ? '\0' : i == '\0' ? '_' : (char) i; } catch (Exception __e) { throw rethrow(__e); } } public void ncSave() { if (c != '\0') { buf.append(c); nc(); } } public String next() { while (c != '\0') { if (c == ' ' || c == '\t' || c == '\r' || c == '\n') nc(); else if (c == '/' && d == '*') { do nc(); while (c != '\0' && !(c == '*' && d == '/')); nc(); nc(); } else if (c == '/' && d == '/') { do nc(); while (c != '\0' && "\r\n".indexOf(c) < 0); } else break; } if (c == '\0') return null; if (c == '\'' || c == '"') { char opener = c; ncSave(); while (c != '\0') { if (c == opener || c == '\n') { ncSave(); break; } else if (c == '\\') { ncSave(); ncSave(); } else ncSave(); } } else if (Character.isJavaIdentifierStart(c)) do ncSave(); while (Character.isJavaIdentifierPart(c) || c == '\''); else if (Character.isDigit(c)) { do ncSave(); while (Character.isDigit(c)); if (c == 'L') ncSave(); } else ncSave(); String t = buf.toString(); buf.setLength(0); return t; } } return new X(); } public static String unquoteUsingCharArray(String s, char[] buf) { if (s == null) return null; if (startsWith(s, '[')) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i + 1, s.length() - i - 1); } } if (s.length() > 1) { char c = s.charAt(0); if (c == '\"' || c == '\'') { int l = endsWith(s, c) ? s.length() - 1 : s.length(); if (l > buf.length) return unquote(s); int n = 0; for (int i = 1; i < l; i++) { char ch = s.charAt(i); if (ch == '\\') { char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1); if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') { code += s.charAt(i + 1); i++; } } buf[n++] = (char) Integer.parseInt(code, 8); continue; } switch(nextChar) { case '\"': ch = '\"'; break; case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\'': ch = '\''; break; case 'u': if (i >= l - 5) { ch = 'u'; break; } int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16); char[] x = Character.toChars(code); int lx = x.length; for (int j = 0; j < lx; j++) buf[n++] = x[j]; i += 5; continue; default: ch = nextChar; } i++; } buf[n++] = ch; } return new String(buf, 0, n); } } return s; } public static boolean structure_isMarker(String s, int i, int j) { if (i >= j) return false; if (s.charAt(i) != 'm') return false; ++i; while (i < j) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static String internIfLongerThan(String s, int l) { return s == null ? null : l(s) >= l ? intern(s) : s; } public static char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length() - 1 : s.length()) + "\"").charAt(0); } public static float parseFloat(String s) { return Float.parseFloat(s); } public static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s) - 1); return isInteger(s); } public static List parseList(String s) { return (List) safeUnstructure(s); } public static List synchroLinkedList() { return Collections.synchronizedList(new LinkedList()); } public static SortedMap synchronizedTreeMap() { return synchroTreeMap(); } public static Map synchronizedMap() { return synchroMap(); } public static Map synchronizedMap(Map map) { return synchroMap(map); } public static byte[] hexToBytes(String s) { if (odd(l(s))) throw fail("Hex string has odd length: " + quote(shorten(10, s))); int n = l(s) / 2; byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) { int a = parseHexChar(s.charAt(i * 2)); int b = parseHexChar(s.charAt(i * 2 + 1)); if (a < 0 || b < 0) throw fail("Bad hex byte: " + quote(substring(s, i * 2, i * 2 + 2)) + " at " + i * 2 + "/" + l(s)); bytes[i] = (byte) ((a << 4) | b); } return bytes; } public static boolean[] boolArrayFromBytes(byte[] a, int n) { boolean[] b = new boolean[n]; int m = min(n, l(a) * 8); for (int i = 0; i < m; i++) b[i] = (a[i / 8] & 1 << (i & 7)) != 0; return b; } public static HashMap findClass_fullName_cache = new HashMap(); public static Class findClass_fullName(String name) { synchronized (findClass_fullName_cache) { if (findClass_fullName_cache.containsKey(name)) return findClass_fullName_cache.get(name); Class c; try { c = Class.forName(name); } catch (ClassNotFoundException e) { c = null; } findClass_fullName_cache.put(name, c); return c; } } public static A nuStubInnerObject(Class c) { return nuStubInnerObject(c, null); } public static A nuStubInnerObject(Class c, Object classFinder) { try { Class outerType = getOuterClass(c, classFinder); Constructor m = c.getDeclaredConstructor(outerType); m.setAccessible(true); return (A) m.newInstance(new Object[] { null }); } catch (Exception __e) { throw rethrow(__e); } } public static Map nuEmptyObject_cache = newDangerousWeakHashMap(); public static A nuEmptyObject(Class c) { try { Constructor ctr; synchronized (nuEmptyObject_cache) { ctr = nuEmptyObject_cache.get(c); if (ctr == null) { nuEmptyObject_cache.put(c, ctr = nuEmptyObject_findConstructor(c)); ctr.setAccessible(true); } } try { return (A) ctr.newInstance(); } catch (InstantiationException e) { if (empty(e.getMessage())) if ((c.getModifiers() & Modifier.ABSTRACT) != 0) throw fail("Can't instantiate abstract class " + className(c), e); else throw fail("Can't instantiate " + className(c), e); else throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } public static Constructor nuEmptyObject_findConstructor(Class c) { for (Constructor m : c.getDeclaredConstructors()) if (m.getParameterTypes().length == 0) return m; throw fail("No default constructor declared in " + c.getName()); } public static void setOptAllDyn(DynamicObject o, Map fields) { if (fields == null) return; HashMap fieldMap = instanceFieldsMap(o); for (Map.Entry e : fields.entrySet()) { String field = e.getKey(); Object val = e.getValue(); boolean has = fieldMap.containsKey(field); if (has) setOpt(o, field, val); else { o.fieldValues = syncMapPut2_createLinkedHashMap(o.fieldValues, intern(field), val); } } } public static void setOptAll_pcall(Object o, Map fields) { if (fields == null) return; for (String field : keys(fields)) try { setOpt(o, field, fields.get(field)); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } public static void setOptAll_pcall(Object o, Object... values) { warnIfOddCount(values); for (int i = 0; i + 1 < l(values); i += 2) { String field = (String) values[i]; Object value = values[i + 1]; try { setOpt(o, field, value); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } } public static void pcallOpt_noArgs(Object o, String method) { try { callOpt_noArgs(o, method); } catch (Throwable __e) { _handleException(__e); } } public static int[] toIntArray(List l) { int[] a = new int[l(l)]; for (int i = 0; i < a.length; i++) a[i] = l.get(i); return a; } public static boolean jmatch(String pat, String s) { return jmatch(pat, s, null); } public static boolean jmatch(String pat, String s, Matches matches) { if (s == null) return false; return jmatch(pat, javaTok(s), matches); } public static boolean jmatch(String pat, List toks) { return jmatch(pat, toks, null); } public static boolean jmatch(String pat, List toks, Matches matches) { List tokpat = javaTok(pat); String[] m = match2(tokpat, toks); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } public static boolean warn_on = true; public static ThreadLocal> warn_warnings = new ThreadLocal(); public static void warn(String s) { if (warn_on) print("Warning: " + s); } public static void warn(String s, List warnings) { warn(s); if (warnings != null) warnings.add(s); addToCollection(warn_warnings.get(), s); } public static String getCanonicalPath(File f) { try { return f == null ? null : f.getCanonicalPath(); } catch (Exception __e) { throw rethrow(__e); } } public static String getCanonicalPath(String path) { return getCanonicalPath(newFile(path)); } public static AutoCloseable tempCleaningUp() { return tempSetTL(ping_isCleanUpThread, true); } public static void closeAllWriters(Collection l) { for (Writer w : unnull(l)) { try { w.close(); } catch (Throwable __e) { _handleException(__e); } } } public static ThreadLocal assertVerbose_value = new ThreadLocal(); public static void assertVerbose(boolean b) { assertVerbose_value.set(b); } public static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); } public static A assertEqualsVerbose(Object x, A y) { assertEqualsVerbose((String) null, x, y); return y; } public static A assertEqualsVerbose(String msg, Object x, A y) { if (!eq(x, y)) { throw fail((msg != null ? msg + ": " : "") + (y) + " != " + (x)); } else print("OK: " + (x)); return y; } public static byte[] boolArrayToBytes(boolean[] a) { byte[] b = new byte[(l(a) + 7) / 8]; for (int i = 0; i < l(a); i++) if (a[i]) b[i / 8] |= 1 << (i & 7); return b; } public static boolean isDigit(char c) { return Character.isDigit(c); } public static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { _handleException(__e); } return null; } public static betterCIComparator_C betterCIComparator_instance; public static betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } public static class betterCIComparator_C implements Comparator { public int compare(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) { return c1 - c2; } } } } return n1 - n2; } } public static 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); } }; } public static 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); } public static String actualUserHome_value; public static String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/emulated/0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } public static File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } public static Path toPath(File f) { return f == null ? null : f.toPath(); } public static List listFilesOnly(String dir) { return listFilesOnly(new File(dir)); } public static List listFilesOnly(File... dirs) { return concatMap(rcurry("listFilesWithSuffix", ""), dirs); } public static Map singular_specials = litmap("children", "child", "images", "image", "chess", "chess"); public static Set singular_specials2 = litset("time", "machine", "line"); public static String singular(String s) { if (s == null) return null; { String _a_1829 = singular_specials.get(s); if (!empty(_a_1829)) return _a_1829; } 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; } public static List getPlural_specials = ll("sheep", "fish"); public static String getPlural(String s) { if (containsIgnoreCase(getPlural_specials, s)) return s; if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies"; if (ewic(s, "ss")) return s + "es"; if (ewic(s, "s")) return s; return s + "s"; } public static TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) { return new SmartTimerTask(r, timer, delay, _threadInfo()); } public static class SmartTimerTask extends TimerTask { public static String _fieldOrder = "r timer delay threadInfo lastRun"; public Object r; public java.util.Timer timer; public long delay; public Object threadInfo; public SmartTimerTask() { } public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) { this.threadInfo = threadInfo; this.delay = delay; this.timer = timer; this.r = r; } public String toString() { return "SmartTimerTask(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")"; } public long lastRun; public void run() { if (!licensed()) timer.cancel(); else { _threadInheritInfo(threadInfo); AutoCloseable __1836 = tempActivity(r); try { lastRun = fixTimestamp(lastRun); long now = now(); if (now >= lastRun + delay * 0.9) { lastRun = now; if (eq(false, pcallF(r))) timer.cancel(); } } finally { _close(__1836); } } } } public static List javaTokPlusBrackets(String s) { return tok_combineRoundOrCurlyBrackets_keep(javaTok(s)); } public static List tok_splitAtSlashes(String s) { return tok_splitAtSlash(s); } public static List tok_splitAtSlashes(List tok) { return tok_splitAtSlash(tok); } public static boolean allNempty(String... l) { for (String s : unnull(l)) if (empty(s)) return false; return true; } public static boolean allNempty(Iterable l) { for (String s : unnull(l)) if (empty(s)) return false; return true; } public static T3 listToTriple(List l) { return l(l) != 3 ? null : triple(get(l, 0), get(l, 1), get(l, 2)); } public static List uncurlyAll(Collection l) { return map("uncurly", l); } public static String tok_unCurlyBracket(String s) { return isCurlyBraced(s) ? join(dropFirstThreeAndLastThree(javaTok(s))) : s; } public static String javaDropAllComments(String s) { return join(javaDropAllComments(javaTok(s))); } public static List javaDropAllComments(List tok) { for (int i = 0; i < l(tok); i += 2) tok.set(i, tok_javaDropCommentsFromWhitespace(tok.get(i))); return tok; } public static String jsonEncode_breakAtLevel1(Object o) { StringBuilder buf = new StringBuilder(); jsonEncode_breakAtLevel1(o, buf, 1); return str(buf); } public static void jsonEncode_breakAtLevel1(Object o, StringBuilder buf, int level) { if (o == null) buf.append("null"); else if (o instanceof String) buf.append(quote((String) o)); else if (o instanceof Number || o instanceof Boolean) buf.append(o); else if (o instanceof Map) { Map map = (Map) o; buf.append("{"); boolean first = true; for (Object key : keys(map)) { if (first) first = false; else buf.append(","); if (level == 1) buf.append("\n "); buf.append(quote((String) key)); buf.append(":"); jsonEncode_breakAtLevel1(map.get(key), buf, level + 1); } if (level == 1) buf.append("\n"); buf.append("}"); } else if (o instanceof Collection) { Collection l = (Collection) o; buf.append("["); boolean first = true; for (Object element : l) { if (first) first = false; else buf.append(","); if (level == 1) buf.append("\n "); jsonEncode_breakAtLevel1(element, buf, level + 1); } if (level == 1) buf.append("\n"); buf.append("]"); } else throw fail("Unknown object for JSON encoding: " + className(o)); } public static CancelPoint newCancelPoint() { return new CancelPoint(); } public static void listAdd(Collection c, A a) { if (c != null) c.add(a); } public static List javaTokNPunctuation_plusAsterisk(String s) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { int j = i; String t; while (j < l(tok) && l(t = tok.get(j)) == 1 && !Character.isLetterOrDigit(t.charAt(0)) && t.charAt(0) != '*') j += 2; if (j > i) replaceSubList(tok, i - 1, j, ll(joinSubList(tok, i - 1, j))); } return tok; } public static boolean cicAtOddPosition(List l, String s) { int n = l(l); for (int i = 1; i < n; i += 2) if (eqic(l.get(i), s)) return true; return false; } public static void printStructs(Object... params) { print(renderStructs(params)); } public static List> ai_spreadCertainIndices_2(List tokPat, List tokS, List indices) { int extra = (l(tokS) - l(tokPat)) / 2; if (extra < 0 || empty(indices)) return emptyList(); List> results = new ArrayList(); for (List spread : allSpreads(extra, l(indices))) { List tok = new ArrayList(); int pos = 0, iSpread = 0, iIndices = 0; for (int i = 0; i < l(tokPat); i++) if (!eq(get(indices, iIndices), i)) tok.add(tokS.get(pos++)); else { ++iIndices; int take = spread.get(iSpread++) * 2; tok.add(joinSubList(tokS, pos, pos + take + 1)); pos += take + 1; } results.add(tok); } return results; } public static boolean match(String pat, String s) { return match3(pat, s); } public static boolean match(String pat, String s, Matches matches) { return match3(pat, s, matches); } public static boolean match(String pat, List toks, Matches matches) { return match3(pat, toks, matches); } public static boolean strictPutIC(Map map, A key, String value) { if (!(map != null && key != null && value != null)) return true; String old = map.get(key); if (old == null) { map.put(key, value); return true; } return eqic(old, value); } public static List tok_combineCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eq(t, "{")) { int j = findEndOfCurlyBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } public static boolean startsWithAndEndsWith(String s, String prefix, String suffix) { return startsWith(s, prefix) && endsWith(s, suffix); } public static List hotwire_collectJars(File jar) { List libIDs = hotwire_libraryIDsFromJar_deleteJarOnFail(jar); List files = ll(jar); for (String libID : libIDs) files.add(loadLibraryOrSrcLib(libID)); return files; } public static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource) { return hotwire_finish(classLoader, progID, javaSource, "main"); } public static Class hotwire_finish(ClassLoader classLoader, String progID, String javaSource, String mainClass) { try { Class theClass = classLoader.loadClass(mainClass); Class j = getJavaX(); setOpt(theClass, "myJavaSource_code", javaSource); synchronized (j) { call(j, "setVars", theClass, progID); callOpt(j, "addInstance", progID, theClass); } hotwire_copyOver(theClass); return theClass; } catch (Exception __e) { throw rethrow(__e); } } public static Pair compileSnippetThroughServer(String progID) { String transpiledSrc = getServerTranspiled2(progID); String md5 = md5(transpiledSrc + "\n" + progID); File jar = CompilerBot.getJarFile(md5); if (jar == null || jar.length() <= 22) { byte[] jarData = null; boolean dontLoad = false; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) { dontLoad = true; File jar2 = rl.getSnippetJar(progID, transpiledSrc); if (jar2 != null) return pair(jar2, transpiledSrc); } if (!dontLoad) { try { jarData = loadBinaryPage("http://www.botcompany.de/jar/" + psI(progID) + "?md5=" + md5(transpiledSrc)); } catch (Throwable __e) { _handleException(__e); } } if (!isJAR(jarData)) { if (jarData != null) { print(bytesToHex(takeFirstOfByteArray(8, jarData))); print("fallback to CompilerBot: " + fromUtf8(takeFirstOfByteArray(80, jarData))); } return CompilerBot.compileSnippet2(progID); } saveBinaryFile(jar, jarData); } return pair(jar, transpiledSrc); } public static List cleanUpAndGetWeakReferencesList(List> l) { if (l == null) return null; synchronized (l) { List out = new ArrayList(); for (int i = 0; i < l(l); i++) { A a = l.get(i).get(); if (a == null) l.remove(i--); else out.add(a); } return out; } } public static int smartIndexOf(String s, String sub, int i) { if (s == null) return 0; i = s.indexOf(sub, min(i, l(s))); return i >= 0 ? i : l(s); } public static int smartIndexOf(String s, int i, char c) { return smartIndexOf(s, c, i); } public static int smartIndexOf(String s, char c, int i) { if (s == null) return 0; i = s.indexOf(c, min(i, l(s))); return i >= 0 ? i : l(s); } public static int smartIndexOf(String s, String sub) { return smartIndexOf(s, sub, 0); } public static int smartIndexOf(String s, char c) { return smartIndexOf(s, c, 0); } public static int smartIndexOf(List l, A sub) { return smartIndexOf(l, sub, 0); } public static int smartIndexOf(List l, int start, A sub) { return smartIndexOf(l, sub, start); } public static int smartIndexOf(List l, A sub, int start) { int i = indexOf(l, sub, start); return i < 0 ? l(l) : i; } public static Map compileRegexp_cache = syncMRUCache(10); public static java.util.regex.Pattern compileRegexp(String pat) { java.util.regex.Pattern p = compileRegexp_cache.get(pat); if (p == null) { compileRegexp_cache.put(pat, p = java.util.regex.Pattern.compile(pat)); } return p; } public static int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } public static int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } public static boolean isLetter(char c) { return Character.isLetter(c); } public static String codePointToString(int codePoint) { return new String(Character.toChars(codePoint)); } public static Object dm_os() { { Object __1894 = vm_generalMap_get("stefansOS"); if (__1894 != null) return __1894; } return creator(); } public static boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } public static boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } public static void arraycopy(Object[] a, Object[] b) { if (a != null && b != null) arraycopy(a, 0, b, 0, min(a.length, b.length)); } public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { if (n != 0) System.arraycopy(src, srcPos, dest, destPos, n); } public static A[] arrayOfType(Class type, int n) { return makeArray(type, n); } public static A[] arrayOfType(int n, Class type) { return arrayOfType(type, n); } public static List getClassNames(Collection l) { List out = new ArrayList(); if (l != null) for (Object o : l) out.add(o == null ? null : getClassName(o)); return out; } public static Map paramsToMap(Object... params) { int n = l(params); if (l(params) == 1 && params[0] instanceof Map) return (Map) params[0]; LinkedHashMap map = new LinkedHashMap(); for (int i = 0; i + 1 < n; i += 2) mapPut(map, params[i], params[i + 1]); return map; } public static Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } public static void putIfNotThere(Map map, A key, B value) { if (map != null && key != null && value != null && !map.containsKey(key)) map.put(key, value); } public static int indexOfIgnoreCase_manual(String a, String b) { int la = strL(a), lb = strL(b); if (la < lb) return -1; int n = la - lb; loop: for (int i = 0; i <= n; i++) { for (int j = 0; j < lb; j++) { char c1 = a.charAt(i + j), c2 = b.charAt(j); if (!eqic(c1, c2)) continue loop; } return i; } return -1; } public static Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } public static Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } public static Map syncHashMap() { return synchroHashMap(); } public static String multiLineQuoteWithSpaces(String s) { return multiLineQuote(" " + s + " "); } public static String lastLine(String s) { s = dropSuffix("\n", s); s = dropSuffix("\r", s); int i = s.lastIndexOf('\n'); return substring(s, i + 1); } public static String quoteUnlessIdentifierOrInteger(String s) { return quoteIfNotIdentifierOrInteger(s); } public static HashSet litset(A... items) { return lithashset(items); } public static boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } public static int compareIgnoreCase_jdk(String s1, String s2) { if (s1 == null) return s2 == null ? 0 : -1; if (s2 == null) return 1; int n1 = s1.length(); int n2 = s2.length(); int min = Math.min(n1, n2); for (int i = 0; i < min; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 != c2) { c1 = Character.toUpperCase(c1); c2 = Character.toUpperCase(c2); if (c1 != c2) { c1 = Character.toLowerCase(c1); c2 = Character.toLowerCase(c2); if (c1 != c2) return c1 - c2; } } } return n1 - n2; } public static String collapseWord(String s) { if (s == null) return ""; StringBuilder buf = new StringBuilder(); for (int i = 0; i < l(s); i++) if (i == 0 || !charactersEqualIC(s.charAt(i), s.charAt(i - 1))) buf.append(s.charAt(i)); return buf.toString(); } public static A printException(A e) { printStackTrace(e); return e; } public static File localSnippetsDir() { return javaxDataDir("Personal Programs"); } public static File localSnippetsDir(String sub) { return newFile(localSnippetsDir(), sub); } public static Map vm_generalMap_map; public static Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } public static File oneOfTheFiles(String... paths) { if (paths != null) for (String path : paths) if (fileExists(path)) return newFile(path); return null; } public static File oneOfTheFiles(File... files) { if (files != null) for (File f : files) if (fileExists(f)) return f; return null; } public static volatile Object isAllowed_function; public static volatile boolean isAllowed_all = true; public static boolean isAllowed(String askingMethod, Object... args) { Object f = vm_generalMap_get("isAllowed_function"); if (f != null && !isTrue(callF(f, askingMethod, args))) return false; return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args)); } public static long round(double d) { return Math.round(d); } public static String getComputerID_quick() { return computerID(); } public static String joinNemptiesWithColonSpace(String... strings) { return joinNempties(": ", strings); } public static String joinNemptiesWithColonSpace(Collection strings) { return joinNempties(": ", strings); } public static String tryToReadErrorStreamFromURLConnection(URLConnection conn) { try { if (conn instanceof HttpURLConnection) return stream2string(((HttpURLConnection) conn).getErrorStream()); return null; } catch (Throwable __e) { return null; } } public static 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(); } public static File fileInSameDir(File f, String newName) { return newFile(parentFile(f), newName); } public static boolean isOpeningTag(String token, String tag) { return isTag(token, tag) && !token.endsWith("/>"); } public static boolean isOpeningTag(String token) { return token.startsWith("<") && token.endsWith(">") && !token.endsWith("/>") && isLetter(token.charAt(1)); } public static 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); } public static String addSuffix(String s, String suffix) { return s == null || s.endsWith(suffix) ? s : s + suffix; } public static boolean isStringStartingWith(Object o, String prefix) { return o instanceof String && ((String) o).startsWith(prefix); } public static String hjavascript_src_snippet(String snippetID) { return tag("script", "", "src", snippetRawURL(snippetID)); } public static Object subBot_httpd() { Object httpd = getThreadLocal((ThreadLocal) getOpt(mainBot(), "MyHTTPD_current")); if (httpd == null) httpd = getThreadLocal((ThreadLocal) getOpt(mainBot(), "WebSocketHTTPD_current")); return httpd; } public static Object mainBot() { return getMainBot(); } public static boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } public static String imageServerLink(String md5OrID) { if (possibleMD5(md5OrID)) return "https://botcompany.de/images/md5/" + md5OrID; return imageServerLink(parseSnippetID(md5OrID)); } public static String imageServerLink(long id) { return "https://botcompany.de/images/" + id; } public static String repeat(char c, int n) { n = Math.max(n, 0); char[] chars = new char[n]; for (int i = 0; i < n; i++) chars[i] = c; return new String(chars); } public static List repeat(A a, int n) { n = Math.max(n, 0); List l = new ArrayList(n); for (int i = 0; i < n; i++) l.add(a); return l; } public static List repeat(int n, A a) { return repeat(a, n); } public static List listFilesWithSuffix(File dir, String suffix) { List l = new ArrayList(); for (File f : listFiles(dir)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) l.add(f); return l; } public static Map newWeakMap() { return newWeakHashMap(); } public static WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } public static Object[] asObjectArray(List l) { return toObjectArray(l); } public static File toFile(Object o) { if (o instanceof File) return (File) o; if (o instanceof String) return new File((String) o); throw fail("Not a file: " + o); } public static boolean isTrue_callF(Object condition, Object... args) { return isTrue(callF(condition, args)); } public static Class run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } public static void restart() { Object j = getJavaX(); call(j, "cleanRestart", get(j, "fullArgs")); } public static String javaTok_substringN(String s, int i, int j) { if (i == j) return ""; if (j == i + 1 && s.charAt(i) == ' ') return " "; return s.substring(i, j); } public static List javaTokWithExisting(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; ArrayList tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; while (j < l) { c = s.charAt(j); d = j + 1 >= l ? '\0' : s.charAt(j + 1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringN(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i + 1 >= l ? '\0' : s.charAt(i + 1); if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) { j += 2; while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j; } else if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; } else if (c == '[' && d == '[') { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') { do ++j; while (j + 2 < l && !s.substring(j, j + 3).equals("]=]")); j = Math.min(j + 3, l); } else ++j; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } public static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j - i && s.regionMatches(i, t, 0, j - i); } public static Map javaTokForJFind_array_cache = synchronizedMRUCache(1000); public static String[] javaTokForJFind_array(String s) { String[] tok = javaTokForJFind_array_cache.get(s); if (tok == null) javaTokForJFind_array_cache.put(s, tok = codeTokensAsStringArray(jfind_preprocess(javaTok(s)))); return tok; } public static int findCodeTokens(List tok, String... tokens) { return findCodeTokens(tok, 1, false, tokens); } public static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, 1, ignoreCase, tokens); } public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, startIdx, ignoreCase, tokens, null); } public static HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*"); public static boolean findCodeTokens_debug = false; public static int findCodeTokens_indexed, findCodeTokens_unindexed; public static int findCodeTokens_bails, findCodeTokens_nonbails; public static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { if (findCodeTokens_debug) { if (eq(getClassName(tok), "main$IndexedList2")) findCodeTokens_indexed++; else findCodeTokens_unindexed++; } int end = tok.size() - tokens.length * 2 + 2, nTokens = tokens.length; int i = startIdx | 1; String firstToken = tokens[0]; if (!ignoreCase && !findCodeTokens_specials.contains(firstToken)) { while (i < end && !firstToken.equals(tok.get(i))) i += 2; } outer: for (; i < end; i += 2) { for (int j = 0; j < nTokens; j++) { String p = tokens[j], t = tok.get(i + j * 2); boolean match = false; if (eq(p, "*")) match = true; else if (eq(p, "")) match = isQuoted(t); else if (eq(p, "")) match = isIdentifier(t); else if (eq(p, "")) match = isInteger(t); else if (eq(p, "\\*")) match = eq("*", t); else match = ignoreCase ? eqic(p, t) : eq(p, t); if (!match) continue outer; } if (condition == null || checkTokCondition(condition, tok, i - 1)) return i; } return -1; } public static String jreplaceExpandRefs(String s, List tokref) { List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { if (tok.get(i).startsWith("$") && isInteger(tok.get(i).substring(1))) { String x = tokref.get(-1 + parseInt(tok.get(i).substring(1)) * 2); tok.set(i, x); } } return join(tok); } public static void clearAllTokens(List tok) { for (int i = 0; i < tok.size(); i++) tok.set(i, ""); } public static void clearAllTokens(List tok, int i, int j) { for (; i < j; i++) tok.set(i, ""); } public static List reTok(List tok) { replaceCollection(tok, javaTok(tok)); return tok; } public static List reTok(List tok, int i) { return reTok(tok, i, i + 1); } public static List reTok(List tok, int i, int j) { i = i & ~1; j = j | 1; List t = javaTok(join(subList(tok, i, j))); replaceListPart(tok, i, j, t); return tok; } public static TreeSet toCaseInsensitiveSet_treeSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, c); return set; } public static TreeSet toCaseInsensitiveSet_treeSet(String... x) { TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, x); return set; } public static String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } public static NavigableMap synchroTreeMap() { return Collections.synchronizedNavigableMap(new TreeMap()); } public static int parseHexChar(char c) { if (c >= '0' && c <= '9') return charDiff(c, '0'); if (c >= 'a' && c <= 'f') return charDiff(c, 'a') + 10; if (c >= 'A' && c <= 'F') return charDiff(c, 'A') + 10; return -1; } public static Class getOuterClass(Class c) { return getOuterClass(c, null); } public static Class getOuterClass(Class c, Object classFinder) { try { String s = c.getName(); int i = s.lastIndexOf('$'); String name = substring(s, 0, i); if (classFinder != null) return (Class) callF(classFinder, name); return Class.forName(name); } catch (Exception __e) { throw rethrow(__e); } } public static HashMap instanceFieldsMap(Object o) { Class c = o.getClass(); HashMap map; synchronized (getOpt_cache) { map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); } return map; } public static Map> callOpt_noArgs_cache = newDangerousWeakHashMap(); public static Object callOpt_noArgs(Object o, String method) { try { if (o == null) return null; if (o instanceof Class) return callOpt(o, method); Class c = o.getClass(); HashMap map; synchronized (callOpt_noArgs_cache) { map = callOpt_noArgs_cache.get(c); if (map == null) map = callOpt_noArgs_makeCache(c); } Method m = map.get(method); return m != null ? m.invoke(o) : null; } catch (Exception __e) { throw rethrow(__e); } } public static HashMap callOpt_noArgs_makeCache(Class c) { HashMap map = new HashMap(); Class _c = c; do { for (Method m : c.getDeclaredMethods()) if (m.getParameterTypes().length == 0 && !reflection_isForbiddenMethod(m)) { m.setAccessible(true); String name = m.getName(); if (!map.containsKey(name)) map.put(name, m); } _c = _c.getSuperclass(); } while (_c != null); callOpt_noArgs_cache.put(c, map); return map; } public static String[] match2(List pat, List tok) { int i = pat.indexOf("..."); if (i < 0) return match2_match(pat, tok); pat = new ArrayList(pat); pat.set(i, "*"); while (pat.size() < tok.size()) { pat.add(i, "*"); pat.add(i + 1, ""); } return match2_match(pat, tok); } public static String[] match2_match(List pat, List tok) { List result = new ArrayList(); if (pat.size() != tok.size()) { return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) return null; } return result.toArray(new String[result.size()]); } public static boolean addToCollection(Collection c, A a) { return c != null && c.add(a); } public static AutoCloseable tempSetTL(ThreadLocal tl, A a) { return tempSetThreadLocal(tl, a); } public static Object callFunction(Object f, Object... args) { return callF(f, args); } public static List concatMap(Object f, Iterable l) { return concatLists(map(f, l)); } public static List concatMap(Iterable l, Object f) { return concatMap(f, l); } public static List concatMap(Object f, Object[] l) { return concatLists(map(f, l)); } public static List concatMap(Object[] l, Object f) { return concatMap(f, l); } public static Object rcurry(final Object f, final Object arg) { int n = numberOfFunctionArguments(f); if (n == 0) throw fail("function takes no arguments"); if (n == 1) return new F0() { public Object get() { return callF(f, arg); } }; if (n == 2) return new F1() { public Object get(Object a) { return callF(f, a, arg); } }; throw todo("currying a function with " + n + "arguments"); } public static String afterLastSpace(String s) { return s == null ? null : substring(s, s.lastIndexOf(' ') + 1); } public static String dropSuffixIgnoreCase(String suffix, String s) { return ewic(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s; } public static List> _threadInfo_makers = synchroList(); public static Object _threadInfo() { if (empty(_threadInfo_makers)) return null; HashMap map = new HashMap(); pcallFAll(_threadInfo_makers, map); return map; } public static List> _threadInheritInfo_retrievers = synchroList(); public static void _threadInheritInfo(Object info) { if (info == null) return; pcallFAll(_threadInheritInfo_retrievers, (Map) info); } public static AutoCloseable tempActivity(Object r) { return null; } public static long fixTimestamp(long timestamp) { return timestamp > now() ? 0 : timestamp; } public static List tok_combineRoundOrCurlyBrackets_keep(List tok) { List l = new ArrayList(); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && eqOneOf(t, "{", "(")) { int j = findEndOfBracketPart(tok, i); l.add(joinSubList(tok, i, j)); i = j - 1; } else l.add(t); } return l; } public static List tok_splitAtSlash(String s) { return tok_splitAtSlash(javaTok(s)); } public static List tok_splitAtSlash(List tok) { List l = new ArrayList(); int i = 0; while (i < l(tok)) { if (i >= l(tok)) break; int j = indexOf(tok, "/", i); if (j < 0) j = l(tok); l.add(trimJoin(tok.subList(i, j))); i = j + 1; } return l; } public static List dropFirstThreeAndLastThree(List l) { return dropFirstAndLast(3, l); } public static String tok_javaDropCommentsFromWhitespace(String s) { int l = l(s), j = 0; StringBuilder buf = new StringBuilder(); while (j < l) { char c = s.charAt(j); char d = j + 1 >= l ? '\0' : s.charAt(j + 1); 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 { buf.append(c); ++j; } } return str(buf); } public static List replaceSubList(List l, List x, List y) { return replaceSublist(l, x, y); } public static List replaceSubList(List l, int fromIndex, int toIndex, List y) { return replaceSublist(l, fromIndex, toIndex, y); } public static String renderStructs(Object... params) { List l = new ArrayList(); if (odd(l(params))) l.add(addSuffix(str(first(params)), ":")); for (int i = l(params) & 1; i + 1 < l(params); i += 2) l.add(params[i] + "=" + sfu(params[i + 1])); return joinWithSpace(l); } public static class allSpreads_Data { public int n; public List collecting; } public static class allSpreads_StackEntry { public int remaining, take; public int position; public Object step(List stack, allSpreads_Data d) { if (position == 0) { if (l(d.collecting) >= d.n - 1) { List result = listPlus(d.collecting, remaining); popLast(stack); return result; } position++; } if (position == 1) { if (take <= remaining) { d.collecting.add(take); allSpreads_StackEntry e = new allSpreads_StackEntry(); e.remaining = remaining - take; stack.add(e); position++; } else popLast(stack); } else if (position == 2) { removeLast(d.collecting); take++; position = 1; } return null; } } public static IterableIterator> allSpreads(final int toSpread, final int buckets) { final allSpreads_Data d = new allSpreads_Data(); d.n = buckets; d.collecting = new ArrayList(); final List stack = new ArrayList(); allSpreads_StackEntry e = new allSpreads_StackEntry(); e.remaining = toSpread; stack.add(e); return iff(new F0() { public Object get() { try { while (nempty(stack)) { ping(); { Object __2057 = last(stack).step(stack, d); if (__2057 != null) return __2057; } } return endMarker(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "while (nempty(stack)) {\r\n ping();\r\n try object last(stack).step(sta..."; } }); } public static boolean match3(String pat, String s) { return match3(pat, s, null); } public static boolean match3(String pat, String s, Matches matches) { if (pat == null || s == null) return false; return match3(pat, parse3_cachedInput(s), matches); } public static boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3_cachedPattern(pat); return match3(tokpat, toks, matches); } public static boolean match3(List tokpat, List toks, Matches matches) { String[] m = match2(tokpat, toks); if (m == null) return false; if (matches != null) matches.m = m; return true; } public static int findEndOfCurlyBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eq(cnc.get(j), "{")) ++level; else if (eq(cnc.get(j), "}")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } public static List hotwire_libraryIDsFromJar_deleteJarOnFail(File jar) { try { return hotwire_libraryIDsFromJar(jar); } catch (Throwable _e) { jar.delete(); throw rethrow(_e); } } public static boolean loadLibraryOrSrcLib_srcLibsEnabled = true; public static File loadLibraryOrSrcLib(String snippetID) { try { long id = parseSnippetID(snippetID); boolean srcLib = loadLibraryOrSrcLib_srcLibsEnabled && isMarkedAsSrcLib(snippetID); if (srcLib) return pairA(hotwire_compile(snippetID)); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) != 0) return f; try { return loadDataSnippetToFile(snippetID); } catch (Throwable e) { if (loadLibraryOrSrcLib_srcLibsEnabled && nempty(loadSnippet(snippetID))) { markAsSrcLib(snippetID); return pairA(hotwire_compile(snippetID)); } throw rethrow(e); } } catch (Exception __e) { throw rethrow(__e); } } public static List hotwire_copyOver_after = synchroList(); public static void hotwire_copyOver(Class c) { for (String field : ll("print_log", "print_silent", "androidContext", "_userHome")) setOptIfNotNull(c, field, getOpt(mc(), field)); setOptIfNotNull(c, "mainBot", getMainBot()); setOpt(c, "creator_class", new WeakReference(mc())); pcallFAll(hotwire_copyOver_after, c); } public static boolean getServerTranspiled2_allowLocalFallback = true, getServerTranspiled2_localFallbackVerbose = true; public static String getServerTranspiled2(String id) { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getTranspiled(id); String transpiled = loadCachedTranspilation(id); String md5 = null; if (machineIsOffline() || isOfflineMode() || isLocalSnippet(id)) return transpiled; if (transpiled != null) md5 = md5(transpiled); String transpiledSrc; try { transpiledSrc = getServerTranspiled(formatSnippetID(id), md5); } catch (Throwable e) { if (!getServerTranspiled2_allowLocalFallback) rethrow(e); printExceptionShort(e); if (getServerTranspiled2_localFallbackVerbose) print("Fallback to local code"); return transpiled; } if (eq(transpiledSrc, "SAME")) { if (!isTrue(loadPage_silent.get())) print("SAME"); return transpiled; } return transpiledSrc; } public static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); public static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); public static byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryPage(URLConnection con) { try { Map extraHeaders = getAndClearThreadLocal(loadBinaryPage_extraHeaders); setHeaders(con); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); return loadBinaryPage_noHeaders(con); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] loadBinaryPage_noHeaders(URLConnection con) { try { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); loadBinaryPage_responseHeaders.set(con.getHeaderFields()); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] isJAR_magic = bytesFromHex("504B0304"); public static boolean isJAR(byte[] data) { return byteArrayStartsWith(data, isJAR_magic); } public static boolean isJAR(File f) { return isJAR(loadBeginningOfBinaryFile(f, l(isJAR_magic))); } public static byte[] takeFirstOfByteArray(byte[] b, int n) { return subByteArray(b, 0, n); } public static byte[] takeFirstOfByteArray(int n, byte[] b) { return takeFirstOfByteArray(b, n); } public static String fromUtf8(byte[] bytes) { try { return bytes == null ? null : new String(bytes, "UTF-8"); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] saveBinaryFile(String fileName, byte[] contents) { try { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = newFileOutputStream(tempFileName); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); vmBus_send("wroteFile", file); return contents; } catch (Exception __e) { throw rethrow(__e); } } public static byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } public static WeakReference creator_class; public static Object creator() { return creator_class == null ? null : creator_class.get(); } public static A[] makeArray(Class type, int n) { return (A[]) Array.newInstance(type, n); } public static void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } public static Object[] toObjectArray(Collection c) { List l = asList(c); return l.toArray(new Object[l.size()]); } public static B mapPutOrRemove(Map map, A key, B value) { if (map != null && key != null) if (value != null) return map.put(key, value); else return map.remove(key); return null; } public static Set synchronizedSet() { return synchroHashSet(); } public static Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } public static Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } public static String multiLineQuote(String s) { for (int i = 0; ; i++) { String closer = "]" + rep('=', i) + "]"; if (!contains(s, closer)) return "[" + rep('=', i) + "[" + s + closer; } } public static String quoteIfNotIdentifierOrInteger(String s) { if (s == null) return null; return isJavaIdentifier(s) || isInteger(s) ? s : quote(s); } public static boolean charactersEqualIC(char c1, char c2) { if (c1 == c2) return true; char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) return true; return Character.toLowerCase(u1) == Character.toLowerCase(u2); } public static String _computerID; public static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __2097 = computerID_lock; lock(__2097); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__2097); } } return _computerID; } public static String joinNempties(String sep, String... strings) { return joinStrings(sep, strings); } public static String joinNempties(String sep, Collection strings) { return joinStrings(sep, strings); } public static String stream2string(InputStream in) { return utf8streamToString(in); } public static File parentFile(File f) { return dirOfFile(f); } public static String snippetRawURL(String snippetID) { return snippetRawURL(snippetID, null); } public static String snippetRawURL(String snippetID, String contentType) { return "https://www.botcompany.de:8443/serve/" + psI(snippetID) + htmlQuery("ct", contentType); } public static boolean possibleMD5(String s) { return isMD5(s); } public static A callMain(A c, String... args) { callOpt(c, "main", new Object[] { args }); return c; } public static void callMain() { callMain(mc()); } public static String[] codeTokensAsStringArray(List tok) { int n = max(0, (l(tok) - 1) / 2); String[] out = new String[n]; for (int i = 0; i < n; i++) out[i] = tok.get(i * 2 + 1); return out; } public static int jfind(String s, String in) { return jfind(javaTok(s), in); } public static int jfind(List tok, String in) { return jfind(tok, 1, in); } public static int jfind(List tok, int startIdx, String in) { return jfind(tok, startIdx, in, null); } public static int jfind(List tok, String in, Object condition) { return jfind(tok, 1, in, condition); } public static int jfind(List tok, int startIdx, String in, Object condition) { return jfind(tok, startIdx, javaTokForJFind_array(in), condition); } public static int jfind(List tok, List tokin) { return jfind(tok, 1, tokin); } public static int jfind(List tok, int startIdx, List tokin) { return jfind(tok, startIdx, tokin, null); } public static int jfind(List tok, int startIdx, String[] tokinC, Object condition) { return findCodeTokens(tok, startIdx, false, tokinC, condition); } public static int jfind(List tok, int startIdx, List tokin, Object condition) { return findCodeTokens(tok, startIdx, false, codeTokensAsStringArray(tokin), condition); } public static List jfind_preprocess(List tok) { for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">")); replaceSublist(tok, ll("\\", "", "*"), ll("\\*")); return tok; } public static boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; return isMultilineQuoted(s); } public static boolean checkTokCondition(Object condition, List tok, int i) { if (condition instanceof TokCondition) return ((TokCondition) condition).get(tok, i); return checkCondition(condition, tok, i); } public static void replaceCollection(Collection dest, Collection src) { dest.clear(); dest.addAll(src); } public static void replaceListPart(List l, int i, int j, List l2) { int j2 = i + l(l2); if (j2 == j) { copyListPart(l2, 0, l, i, l(l2)); return; } l.subList(i, j).clear(); l.addAll(i, l2); } public static int charDiff(char a, char b) { return (int) a - (int) b; } public static int charDiff(String a, char b) { return charDiff(stringToChar(a), b); } public static boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } public static AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) { if (tl == null) return null; final A prev = setThreadLocal(tl, a); return new AutoCloseable() { public String toString() { return "tl.set(prev);"; } public void close() throws Exception { tl.set(prev); } }; } public static int numberOfFunctionArguments(Object f) { if (f instanceof F0) return 0; if (f instanceof F1) return 1; if (f instanceof F2) return 2; if (f instanceof VF1) return 1; if (f instanceof VF2) return 2; if (f instanceof VF3) return 3; if (f instanceof String) return numberOfMethodArguments(mc(), (String) f); return numberOfMethodArguments(f, "get"); } public static int findEndOfBracketPart(List cnc, int i) { int j = i + 2, level = 1; while (j < cnc.size()) { if (eqOneOf(cnc.get(j), "{", "(")) ++level; else if (eqOneOf(cnc.get(j), "}", ")")) --level; if (level == 0) return j + 1; ++j; } return cnc.size(); } public static String trimJoin(List s) { return trim(join(s)); } public static List dropFirstAndLast(int n, List l) { return new ArrayList(subList(l, n, l(l) - n)); } public static List dropFirstAndLast(List l) { return dropFirstAndLast(1, l); } public static String dropFirstAndLast(String s) { return substring(s, 1, l(s) - 1); } public static List replaceSublist(List l, List x, List y) { if (x == null) return l; int i = 0; while (true) { i = indexOfSubList(l, x, i); if (i < 0) break; removeSubList(l, i, i + l(x)); l.addAll(i, y); i += l(y); } return l; } public static List replaceSublist(List l, int fromIndex, int toIndex, List y) { removeSubList(l, fromIndex, toIndex); l.addAll(fromIndex, y); return l; } public static void removeLast(List l) { if (!l.isEmpty()) l.remove(l(l) - 1); } public static void removeLast(List l, int n) { removeSubList(l, l(l) - n, l(l)); } public static IterableIterator iff(Object f) { return iteratorFromFunction_withEndMarker(f); } public static IterableIterator iff(F0 f) { return iteratorFromFunction_withEndMarker(f); } public static Object endMarker() { return iteratorFromFunction_endMarker; } public static Map> parse3_cachedInput_cache = synchronizedMRUCache(1000); public static List parse3_cachedInput(String s) { List tok = parse3_cachedInput_cache.get(s); if (tok == null) parse3_cachedInput_cache.put(s, tok = parse3(s)); return tok; } public static Map> parse3_cachedPattern_cache = synchronizedMRUCache(1000); public static synchronized List parse3_cachedPattern(String s) { List tok = parse3_cachedPattern_cache.get(s); if (tok == null) parse3_cachedPattern_cache.put(s, tok = parse3(s)); return tok; } public static List hotwire_libraryIDsFromJar(File jar) { String dehlibs = unnull(loadTextFileFromZip(jar, "libraries")); return regexpExtractAll("\\d+", dehlibs); } public static boolean isMarkedAsSrcLib(String snippetID) { if (snippetID == null) return false; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return isJavaxCompilableSnippetType(rl.getSnippetType(snippetID)); return fileExists(javaxCodeDir("srclibs/" + psI(snippetID))); } public static A pairA(Pair p) { return p == null ? null : p.a; } public static File DiskSnippetCache_file(long snippetID) { return new File(getGlobalCache(), "data_" + snippetID + ".jar"); } public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = DiskSnippetCache_file(snippetID); return file.exists() ? file : null; } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(DiskSnippetCache_file(snippetID), data); } public static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL(dataSnippetLink(snippetID)); print("Loading library: " + hideCredentials(url)); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID)); print("Loading library: " + hideCredentials(url)); data = loadBinaryPage(url.openConnection()); } print("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } public static long fileSize(String path) { return getFileSize(path); } public static long fileSize(File f) { return getFileSize(f); } public static File loadDataSnippetToFile(String snippetID) { try { snippetID = fsI(snippetID); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); File f = DiskSnippetCache_file(parseSnippetID(snippetID)); List urlsTried = new ArrayList(); List errors = new ArrayList(); try { URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID))); print("Loading library: " + hideCredentials(url)); try { loadBinaryPageToFile(openConnection(url), f); if (fileSize(f) == 0) throw fail(); } catch (Throwable e) { errors.add(e); url = addAndReturn(urlsTried, new URL("http://data.tinybrain.de/blobs/" + psI(snippetID))); print("Trying other server: " + hideCredentials(url)); loadBinaryPageToFile(openConnection(url), f); print("Got bytes: " + fileSize(f)); } if (fileSize(f) == 0) throw fail(); System.err.println("Bytes loaded: " + fileSize(f)); } catch (Throwable e) { errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } public static void markAsSrcLib(String snippetID) { saveTextFile(javaxCodeDir("srclibs/" + psI(snippetID)), ""); } public static void setOptIfNotNull(Object o, String field, Object value) { if (value != null) setOpt(o, field, value); } public static String loadCachedTranspilation(String id) { try { return loadTextFilePossiblyGZipped(getCachedTranspilationFile(id)); } catch (Throwable __e) { return null; } } public static boolean machineIsOffline() { return isFalse(callF(vmGeneralMap_get("areWeOnline"))); } public static boolean isOfflineMode() { return eq("1", trim(loadProgramTextFile("#1005806", "offline-mode"))); } public static boolean isLocalSnippet(String snippetID) { return isLocalSnippetID(snippetID); } public static boolean isLocalSnippet(long snippetID) { return isLocalSnippetID(snippetID); } public static String getServerTranspiled(String snippetID) { return getServerTranspiled(snippetID, null); } public static String getServerTranspiled(String snippetID, String expectedMD5) { try { long id = parseSnippetID(snippetID); String text = loadPage_utf8(tb_mainServer() + "/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "") + standardCredentials()); if (nempty(text) && neq(text, "SAME")) saveTranspiledCode(snippetID, text); return text; } catch (Exception __e) { throw rethrow(__e); } } public static void printExceptionShort(Throwable e) { print(exceptionToStringShort(e)); } public static A println(A a) { return print(a); } public static byte[] bytesFromHex(String s) { return hexToBytes(s); } public static boolean byteArrayStartsWith(byte[] a, byte[] b) { if (a == null || b == null) return false; if (a.length < b.length) return false; for (int i = 0; i < b.length; i++) if (a[i] != b[i]) return false; return true; } public static byte[] loadBeginningOfBinaryFile(File file, int maxBytes) { return loadBinaryFilePart(file, 0, maxBytes); } public static byte[] subByteArray(byte[] b, int start) { return subByteArray(b, start, l(b)); } public static byte[] subByteArray(byte[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new byte[0]; byte[] x = new byte[end - start]; System.arraycopy(b, start, x, 0, end - start); return x; } public static Set synchroHashSet() { return Collections.synchronizedSet(new HashSet()); } public static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } public static String joinStrings(String sep, String... strings) { return joinStrings(sep, Arrays.asList(strings)); } public static String joinStrings(String sep, Collection strings) { StringBuilder buf = new StringBuilder(); for (String s : unnull(strings)) if (nempty(s)) { if (nempty(buf)) buf.append(sep); buf.append(s); } return str(buf); } public static String utf8streamToString(InputStream in) { return readerToString(utf8bufferedReader(in)); } public static File dirOfFile(File f) { return f == null ? null : f.getParentFile(); } public static boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } public static Object iteratorFromFunction_endMarker = new Object(); public static IterableIterator iteratorFromFunction_withEndMarker(final Object f) { class IFF extends IterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = (A) callF(f); if (a == iteratorFromFunction_endMarker) done = true; } } ; return new IFF(); } public static IterableIterator iteratorFromFunction_withEndMarker(final F0 f) { return iteratorFromFunction_withEndMarker_f0(f); } public static boolean isNormalQuoted(String s) { int l = l(s); if (!(l >= 2 && s.charAt(0) == '"' && lastChar(s) == '"')) return false; int j = 1; while (j < l) if (s.charAt(j) == '"') return j == l - 1; else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; return false; } public static boolean isMultilineQuoted(String s) { if (!startsWith(s, "[")) return false; int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; return i < s.length() && s.charAt(i) == '['; } public static void copyListPart(List a, int i1, List b, int i2, int n) { if (a == null || b == null) return; for (int i = 0; i < n; i++) b.set(i2 + i, a.get(i1 + i)); } public static char stringToChar(String s) { if (l(s) != 1) throw fail("bad stringToChar: " + s); return firstChar(s); } public static int numberOfMethodArguments(Object o, String method) { Class c; boolean mustBeStatic = false; if (o instanceof Class) { c = (Class) o; mustBeStatic = true; } else c = o.getClass(); Class _c = c; int n = -1; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if (mustBeStatic && !methodIsStatic(m)) continue; int nn = l(m.getParameterTypes()); if (n == -1) n = nn; else if (n != nn) throw fail("Variable number of method arguments: " + _c + "." + method); } c = c.getSuperclass(); } if (n == -1) throw fail("Method not found: " + _c + "." + method); return n; } public static int indexOfSubList(List x, List y) { return indexOfSubList(x, y, 0); } public static int indexOfSubList(List x, List y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y.get(j))) continue outer; return i; } return -1; } public static int indexOfSubList(List x, A[] y, int i) { outer: for (; i + l(y) <= l(x); i++) { for (int j = 0; j < l(y); j++) if (neq(x.get(i + j), y[j])) continue outer; return i; } return -1; } public static void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } public static void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } public static List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } public static String loadTextFileFromZip(File inZip, String fileName) { return loadTextFileFromZipFile(inZip, fileName); } public static List regexpExtractAll(String pat, String s) { if (s == null) return null; Matcher m = regexpMatcher(pat, s); List out = new ArrayList(); while (m.find()) out.add(m.group()); return out; } public static boolean isJavaxCompilableSnippetType(int type) { return isJavaxCompilableSnippetTypeExceptInclude(type) || type == javaxIncludeSnippetType(); } public static File javaxCodeDir_dir; public static File javaxCodeDir() { return javaxCodeDir_dir != null ? javaxCodeDir_dir : new File(userHome(), "JavaX-Code"); } public static File javaxCodeDir(String sub) { return newFile(javaxCodeDir(), sub); } public static String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1400000 && id < 1500000) return "http://butter.botcompany.de:8080/files/" + id + "?_pass=" + muricaPassword(); if (id >= 1200000 && id < 1300000) { String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "http://butter.botcompany.de:8080/1008823/raw/" + id + "?_pass=" + pw; } else return "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=application/binary"; } public static A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } public static void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } public static void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } public static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try { File ftemp = new File(f2s(file) + "_temp"); FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp)); try { InputStream inputStream = con.getInputStream(); long len = 0; try { len = con.getContentLength(); } catch (Throwable e) { printStackTrace(e); } String pat = " {*}" + (len != 0 ? "/" + len : "") + " bytes loaded."; copyStreamWithPrints(inputStream, buf, pat); inputStream.close(); buf.close(); file.delete(); renameFile_assertTrue(ftemp, file); } finally { if (buf != null) buf.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFilePossiblyGZipped(String fileName) { return loadTextFilePossiblyGZipped(fileName, null); } public static String loadTextFilePossiblyGZipped(String fileName, String defaultContents) { File gz = new File(fileName + ".gz"); return gz.exists() ? loadGZTextFile(gz) : loadTextFile(fileName, defaultContents); } public static String loadTextFilePossiblyGZipped(File fileName) { return loadTextFilePossiblyGZipped(fileName, null); } public static String loadTextFilePossiblyGZipped(File fileName, String defaultContents) { return loadTextFilePossiblyGZipped(fileName.getPath(), defaultContents); } public static File getCachedTranspilationFile(String id) { return newFile(getCodeProgramDir(id), "Transpilation"); } public static Object vmGeneralMap_get(Object key) { return vm_generalMap_get(key); } public static String loadProgramTextFile(String name) { return loadTextFile(getProgramFile(name)); } public static String loadProgramTextFile(String progID, String name) { return loadTextFile(getProgramFile(progID, name)); } public static String loadProgramTextFile(String progID, String name, String defaultText) { return loadTextFile(getProgramFile(progID, name), defaultText); } public static String loadPage_utf8(URL url) { return loadPage_utf8(url.toString()); } public static String loadPage_utf8(String url) { AutoCloseable __2236 = tempSetTL(loadPage_charset, "UTF-8"); try { return loadPage(url); } finally { _close(__2236); } } public static String loadPage_utf8(URLConnection con, URL url, boolean addHeaders) throws IOException { AutoCloseable __2237 = tempSetTL(loadPage_charset, "UTF-8"); try { return loadPage(con, url, addHeaders); } finally { _close(__2237); } } public static void saveTranspiledCode(String progID, String code) { File dir = getCodeProgramDir(progID); new File(dir, "Transpilation").delete(); saveGZTextFile(new File(dir, "Transpilation.gz"), code); } public static byte[] loadBinaryFilePart(File file, long start, long end) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); int n = toInt(min(raf.length(), end - start)); byte[] buffer = new byte[n]; try { raf.seek(start); raf.readFully(buffer, 0, n); return buffer; } finally { raf.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static String readerToString(Reader r) { try { try { StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; } return buf.toString(); } finally { r.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean isLowerHexString(String s) { for (int i = 0; i < l(s); i++) { char c = s.charAt(i); if (c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { } else return false; } return true; } public static IterableIterator iteratorFromFunction_withEndMarker_f0(final F0 f) { class IFF2 extends IterableIterator { public A a; public boolean have, done; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; have = false; return _a; } public void getNext() { if (done || have) return; a = f.get(); have = true; if (a == iteratorFromFunction_endMarker) done = true; } } ; return new IFF2(); } public static char firstChar(String s) { return s.charAt(0); } public static List dropPunctuation_keep = ll("*", "<", ">"); public static List dropPunctuation(List tok) { tok = new ArrayList(tok); for (int i = 1; i < tok.size(); i += 2) { String t = tok.get(i); if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) { tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } public static String dropPunctuation(String s) { return join(dropPunctuation(nlTok(s))); } public static List javaTokPlusPeriod(String s) { List tok = new ArrayList(); int l = s.length(); int i = 0; while (i < l) { int j = i; char c; String cc; while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j + 2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/")); j = Math.min(j + 2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); cc = s.substring(i, Math.min(i + 2, l)); if (c == (char) 0x201C || c == (char) 0x201D) c = '"'; if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == (char) 0x201C || _c == (char) 0x201D) _c = '"'; if (_c == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j + 1 < l) j += 2; else ++j; } if (j - 1 >= i + 1) { tok.add(opener + s.substring(i + 1, j - 1) + opener); i = j; continue; } } 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))); else if (cc.equals("[[")) { do ++j; while (j + 1 < l && !s.substring(j, j + 2).equals("]]")); j = Math.min(j + 2, l); } else if (cc.equals("[=") && 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 if (s.substring(j, Math.min(j + 3, l)).equals("...")) j += 3; else if (c == '$' || c == '#') do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } public static String loadTextFileFromZipFile(File inZip, String fileName) { try { if (!fileExists(inZip)) return null; try { ZipFile zip = new ZipFile(inZip); try { return loadTextFileFromZipFile(zip, fileName); } finally { _close(zip); } } catch (Throwable e) { throw fail(f2s(inZip), e); } } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFileFromZipFile(ZipFile zip, String fileName) { try { ZipEntry entry = zip.getEntry(fileName); if (entry == null) return null; InputStream fin = zip.getInputStream(entry); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copyStream(fin, baos); return fromUTF8(baos.toByteArray()); } finally { _close(fin); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean isJavaxCompilableSnippetTypeExceptInclude(int type) { return isJavaxApplicationSnippetType(type) || isJavaxModuleSnippetType(type) || type == snippetType_dynModule(); } public static int javaxIncludeSnippetType() { return 42; } public static String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } public static volatile boolean muricaPassword_pretendNotAuthed = false; public static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } public static File mkdirsFor(File file) { return mkdirsForFile(file); } public static void copyStreamWithPrints(InputStream in, OutputStream out, String pat) { try { byte[] buf = new byte[65536]; int total = 0; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); if ((total + n) / 100000 > total / 100000) print(pat.replace("{*}", str(roundDownTo(total, 100000)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } public static void renameFile_assertTrue(File a, File b) { try { if (!a.exists()) throw fail("Source file not found: " + f2s(a)); if (b.exists()) throw fail("Target file exists: " + f2s(b)); mkdirsForFile(b); if (!a.renameTo(b)) throw fail("Can't rename " + f2s(a) + " to " + f2s(b)); } catch (Exception __e) { throw rethrow(__e); } } public static String loadGZTextFile(File file) { try { if (!file.isFile()) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream fis = new FileInputStream(file); GZIPInputStream gis = newGZIPInputStream(fis); try { byte[] buffer = new byte[1024]; int len; while ((len = gis.read(buffer)) != -1) { baos.write(buffer, 0, len); } } finally { fis.close(); } baos.close(); return fromUtf8(baos.toByteArray()); } catch (Exception __e) { throw rethrow(__e); } } public static File getCodeProgramDir() { return getCodeProgramDir(getProgramID()); } public static File getCodeProgramDir(String snippetID) { return new File(javaxCodeDir(), formatSnippetID(snippetID)); } public static File getCodeProgramDir(long snippetID) { return getCodeProgramDir(formatSnippetID(snippetID)); } public static void saveGZTextFile(File file, String contents) { try { File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = file.getPath() + "_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()); GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); gos.close(); fileOutputStream.close(); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + file.getPath()); if (contents != null) if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); } catch (Exception __e) { throw rethrow(__e); } } public static List nlTok(String s) { return javaTokPlusPeriod(s); } public static String fromUTF8(byte[] bytes) { return fromUtf8(bytes); } public static boolean isJavaxApplicationSnippetType(int type) { return type == snippetType_javaxSource() || type == snippetType_JavaXDesktop(); } public static boolean isJavaxModuleSnippetType(int type) { return type == snippetType_javaxModule() || type == snippetType_javaxDesktopModule(); } public static int snippetType_dynModule() { return 57; } public static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } public static int roundDownTo(int x, int n) { return x / n * n; } public static long roundDownTo(long x, long n) { return x / n * n; } public static int snippetType_javaxSource() { return 34; } public static int snippetType_JavaXDesktop() { return 55; } public static int snippetType_javaxModule() { return 54; } public static int snippetType_javaxDesktopModule() { return 58; } public static final class _MethodCache { public final Class c; public final HashMap> cache = new HashMap(); public _MethodCache(Class c) { this.c = c; _init(); } public void _init() { Class _c = c; while (_c != null) { for (Method m : _c.getDeclaredMethods()) if (!reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if (m.isDefault() && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); } public Method findMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } public Method findStaticMethod(String method, Object[] args) { try { List m = cache.get(method); if (m == null) return null; int n = m.size(); for (int i = 0; i < n; i++) { Method me = m.get(i); if (isStaticMethod(me) && call_checkArgs(me, args, false)) return me; } return null; } catch (Exception __e) { throw rethrow(__e); } } } public abstract static class VF1 implements IVF1 { public abstract void get(A a); } public abstract static class VF3 { public abstract void get(A a, B b, C c); } public abstract static class VF2 { public abstract void get(A a, B b); } public static class Matches { public String[] m; public Matches() { } public Matches(String... m) { this.m = m; } public String get(int i) { return i < m.length ? m[i] : null; } public String unq(int i) { return unquote(get(i)); } public String fsi(int i) { return formatSnippetID(unq(i)); } public String fsi() { return fsi(0); } public String tlc(int i) { return unq(i).toLowerCase(); } public boolean bool(int i) { return "true".equals(unq(i)); } public String rest() { return m[m.length - 1]; } public int psi(int i) { return Integer.parseInt(unq(i)); } public String toString() { return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")"; } public int hashCode() { return _hashCode(toList(m)); } public boolean equals(Object o) { return o instanceof Matches && arraysEqual(m, ((Matches) o).m); } } public static class Var implements IVar { public Var() { } public Var(A v) { this.v = v; } public A v; public synchronized void set(A a) { if (v != a) { v = a; notifyAll(); } } public synchronized A get() { return v; } public synchronized boolean has() { return v != null; } public synchronized void clear() { v = null; } public String toString() { return str(get()); } } public static class DefunctClassLoader { } public static class TimedCache { public long timeout; public volatile A value; public Object function; public long set; public Lock lock = lock(); public boolean keepValueWhileCalculating = false; public int stores, fails, hits; public TimedCache(double timeoutSeconds, Object function) { this(function, timeoutSeconds); } public TimedCache(Object function, double timeoutSeconds) { this(timeoutSeconds); this.function = function; } public TimedCache(double timeoutSeconds) { timeout = toMS(timeoutSeconds); } public A set(A a) { Lock __2308 = lock; lock(__2308); try { ++stores; value = a; set = now(); return a; } finally { unlock(__2308); } } public boolean has() { Lock __2309 = lock; lock(__2309); try { clean(); if (set != 0) { ++hits; return true; } ++fails; return false; } finally { unlock(__2309); } } public A get() { Lock __2310 = lock; lock(__2310); try { if (function != null) return get(function); clean(); if (set != 0) ++hits; else ++fails; return value; } finally { unlock(__2310); } } public A get(Object makerFunction) { Lock __2311 = lock; lock(__2311); try { if (keepValueWhileCalculating) { if (value == null || shouldClean()) set((A) callF(makerFunction)); return value; } else { return this.has() ? getNoClean() : set((A) callF(makerFunction)); } } finally { unlock(__2311); } } public A getNoClean() { Lock __2312 = lock; lock(__2312); try { return value; } finally { unlock(__2312); } } public void clean() { Lock __2313 = lock; lock(__2313); try { if (shouldClean()) clear(); } finally { unlock(__2313); } } public boolean shouldClean() { return timeout > 0 && now() > set + timeout; } public void clear() { Lock __2314 = lock; lock(__2314); try { set = 0; value = null; } finally { unlock(__2314); } } public String stats() { return "Stores: " + stores + ", hits: " + hits + ", fails: " + fails; } public A peek() { return value; } } public abstract static class TokCondition { public abstract boolean get(List tok, int i); } public abstract static class ALQLLine { public String toString() { return stdToString(this); } } public static class ALQLReturn extends ALQLLine { public String var; public ALQLReturn() { } public ALQLReturn(String var) { this.var = var; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } public static class ALQLTriple extends ALQLLine { public T3 triple; public ALQLTriple() { } public ALQLTriple(T3 triple) { this.triple = triple; } public ALQLTriple(String a, String b, String c) { triple = t3(a, b, c); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } public static class ALQLLockStatement extends ALQLLine { public T3 triple; public ALQLLockStatement() { } public ALQLLockStatement(T3 triple) { this.triple = triple; } public ALQLLockStatement(String a, String b, String c) { triple = t3(a, b, c); } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } public static class ALQLPage extends ALQLLine { public String page, matchMethod; public ALQLPage() { } public ALQLPage(String page, String matchMethod) { this.matchMethod = matchMethod; this.page = page; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } public static class ALQLSlice extends ALQLLine { public String slice; public List contents; public ALQLSlice() { } public ALQLSlice(String slice, List contents) { this.contents = contents; this.slice = slice; } public boolean equals(Object o) { return stdEq2(this, o); } public int hashCode() { return stdHash2(this); } } public static class GlobalID { public long a; public int b; public GlobalID() { } public GlobalID(String id) { assertGlobalID(id); BigInteger value = bigint(0); for (int i = 0; i < l(id); i++) value = plus(mul(value, 26), charDiff(id.charAt(i), 'a')); a = value.longValue(); value = value.shiftRight(64); b = value.shortValue(); } public String toString() { BigInteger value = bigint(b); value = value.shiftLeft(32); value = plus(value, (a >> 32) & 0xFFFFFFFFL); value = value.shiftLeft(32); value = plus(value, a & 0xFFFFFFFFL); return bigintToGlobalID(value); } public boolean equals(Object o) { if (!(o instanceof GlobalID)) return false; return ((GlobalID) o).a == a && ((GlobalID) o).b == b; } public int hashCode() { return (int) a; } } public static int concepts_internStringsLongerThan = 10; public static ThreadLocal concepts_unlisted = new ThreadLocal(); public static interface Derefable { public Concept get(); } public static interface IConceptIndex { public void update(Concept c); public void remove(Concept c); } public static interface IFieldIndex { public List getAll(Val val); public List allValues(); public MultiSet allValues_multiSet(); } public static class Concepts { public Map concepts = synchroTreeMap(); public HashMap perClassData = new HashMap(); public Map miscMap; public String programID; public long idCounter; public volatile long changes, changesWritten, lastChange; public volatile java.util.Timer autoSaver; public volatile boolean savingConcepts, dontSave, noXFullGrab; public boolean vmBusSend = true; public boolean initialSave = true; public int autoSaveInterval = -1000; public boolean useGZIP = true, quietSave; public ReentrantLock lock = new ReentrantLock(true); public ReentrantLock saverLock = new ReentrantLock(true); public long lastSaveTook, lastSaveWas; public float maxAutoSavePercentage = 10; public List conceptIndices; public Map, Map> fieldIndices; public Map, Map> ciFieldIndices; public List saveActions = synchroList(); public Object classFinder = _defaultClassFinder(); public List onAllChanged = synchroList(); public transient Object saveWrapper; public Concepts() { } public Concepts(String programID) { this.programID = programID; } public synchronized long internalID() { do { ++idCounter; } while (hasConcept(idCounter)); return idCounter; } public void initProgramID() { if (programID == null) programID = getDBProgramID(); } public Concepts load() { return load(false); } public Concepts safeLoad() { return load(true); } public Concepts load(boolean allDynamic) { initProgramID(); try { if (tryToGrab(allDynamic)) return this; } catch (Throwable e) { if (!exceptionMessageContains(e, "no xfullgrab")) printShortException(e); print("xfullgrab failed - loading DB of " + programID + " from disk"); } return loadFromDisk(allDynamic); } public Concepts loadFromDisk() { return loadFromDisk(false); } public Concepts loadFromDisk(boolean allDynamic) { if (nempty(concepts)) clearConcepts(); restoreLatestBackupIfConceptsFileEmpty(programID, "doIt", true); long time = now(); Map _concepts = concepts; readLocally2_allDynamic.set(allDynamic); AutoCloseable __2325 = tempSetTL(readLocally2_classFinder, classFinder); try { readLocally2(this, programID, "concepts"); Map __concepts = concepts; concepts = _concepts; concepts.putAll(__concepts); int l = readLocally_stringLength; int tokrefs = unstructure_tokrefs; assignConceptsToUs(); done("Loaded " + n(l(concepts), "concepts"), time); if (fileSize(getProgramFile(programID, "idCounter.structure")) != 0) readLocally2(this, programID, "idCounter"); else calcIdCounter(); if (initialSave) allChanged(); return this; } finally { _close(__2325); } } public Concepts loadConcepts() { return load(); } public boolean tryToGrab(boolean allDynamic) { if (sameSnippetID(programID, getDBProgramID())) return false; RemoteDB db = connectToDBOpt(programID); try { if (db != null) { loadGrab(db.fullgrab(), allDynamic); return true; } return false; } finally { _close(db); } } public Concepts load(String grab) { return loadGrab(grab, false); } public Concepts safeLoad(String grab) { return loadGrab(grab, true); } public Concepts loadGrab(String grab, boolean allDynamic) { clearConcepts(); DynamicObject_loading.set(true); try { Map map = (Map) unstructure(grab, allDynamic, classFinder); concepts.putAll(map); assignConceptsToUs(); for (long l : map.keySet()) idCounter = max(idCounter, l); } finally { DynamicObject_loading.set(null); } allChanged(); return this; } public void assignConceptsToUs() { for (Concept c : values(concepts)) c._concepts = this; for (Concept c : values(concepts)) callOpt_noArgs(c, "_doneLoading2"); } public String progID() { return programID == null ? getDBProgramID() : programID; } public Concept getConcept(String id) { return empty(id) ? null : getConcept(parseLong(id)); } public Concept getConcept(long id) { return (Concept) concepts.get((long) id); } public Concept getConcept(RC ref) { return ref == null ? null : getConcept(ref.longID()); } public boolean hasConcept(long id) { return concepts.containsKey((long) id); } public void deleteConcept(long id) { Concept c = getConcept(id); if (c == null) print("Concept " + id + " not found"); else c.delete(); } public void calcIdCounter() { long id_ = 0; for (long id : keys(concepts)) id_ = max(id_, id); idCounter = id_ + 1; saveLocally2(this, programID, "idCounter"); } public void saveConceptsIfDirty() { saveConcepts(); } public void save() { saveConcepts(); } public void saveConcepts() { if (dontSave) return; initProgramID(); saverLock.lock(); savingConcepts = true; long start = now(), time; try { String s = null; long _changes = changes; if (_changes == changesWritten) return; final File f = getProgramFile(programID, useGZIP ? "concepts.structure.gz" : "concepts.structure"); lock.lock(); long fullTime = now(); try { saveLocally2(this, programID, "idCounter"); if (useGZIP) { callRunnableWithWrapper(saveWrapper, new Runnable() { public void run() { try { saveGZStructureToFile(f, cloneMap(concepts)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "saveGZStructureToFile(f, cloneMap(concepts));"; } }); getProgramFile(programID, "concepts.structure").delete(); } else s = structure(cloneMap(concepts)); } finally { lock.unlock(); } while (nempty(saveActions)) pcallF(popFirst(saveActions)); changesWritten = _changes; if (!useGZIP) { time = now() - start; if (!quietSave) print("Saving " + toM(l(s)) + "M chars (" + time + " ms)"); start = now(); saveTextFile(f, javaTokWordWrap(s)); getProgramFile(programID, "concepts.structure.gz").delete(); } copyFile(f, getProgramFile(programID, "backups/concepts.structure" + (useGZIP ? ".gz" : "") + ".backup" + ymd() + "-" + formatInt(hours(), 2))); time = now() - start; if (!quietSave) print(programID + ": Saved " + toK(f.length()) + " K, " + n(concepts, "concepts") + " (" + time + " ms)"); lastSaveWas = fullTime; lastSaveTook = now() - fullTime; } finally { savingConcepts = false; saverLock.unlock(); } } public void _autoSaveConcepts() { if (autoSaveInterval < 0 && maxAutoSavePercentage != 0) { long pivotTime = Math.round(lastSaveWas + lastSaveTook * 100.0 / maxAutoSavePercentage); if (now() < pivotTime) { return; } } try { saveConcepts(); } catch (Throwable e) { print("Concept save failed, will try again: " + e); } } public void clearConcepts() { concepts.clear(); allChanged(); } public void allChanged() { synchronized (this) { ++changes; lastChange = sysNow(); } if (vmBusSend) vmBus_send("conceptsChanged", this); pcallFAll(onAllChanged); } public synchronized void autoSaveConcepts() { if (autoSaver == null) { if (isTransient()) throw fail("Can't persist transient database"); autoSaver = doEvery_daemon(abs(autoSaveInterval), new Runnable() { public void run() { try { _autoSaveConcepts(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_autoSaveConcepts()"; } }); } } public void cleanMeUp() { boolean shouldSave = autoSaver != null; if (autoSaver != null) { autoSaver.cancel(); autoSaver = null; } while (savingConcepts) sleepInCleanUp(10); if (shouldSave) saveConceptsIfDirty(); } public Map getIDsAndNames() { Map map = new HashMap(); Map cloned = cloneMap(concepts); for (long id : keys(cloned)) map.put(id, cloned.get(id).className); return map; } public void deleteConcepts(List l) { if (l != null) for (Object o : cloneList(l)) if (o instanceof Long) { Concept c = concepts.get(o); if (c != null) c.delete(); } else if (o instanceof Concept) ((Concept) o).delete(); else warn("Can't delete " + getClassName(o)); } public A conceptOfType(Class type) { IConceptCounter counter = conceptCounterForClass(type); if (counter != null) return (A) first(counter.allConcepts()); return firstOfType(allConcepts(), type); } public List conceptsOfType(Class type) { IConceptCounter counter = conceptCounterForClass(type); if (counter != null) return (List) cloneList(counter.allConcepts()); return filterByType(allConcepts(), type); } public List listConcepts(Class type) { return conceptsOfType(type); } public List list(Class type) { return conceptsOfType(type); } public List list(String type) { return conceptsOfType(type); } public List conceptsOfType(String type) { return filterByDynamicType(allConcepts(), "main$" + type); } public boolean hasConceptOfType(Class type) { return hasType(allConcepts(), type); } public void persistConcepts() { loadConcepts(); autoSaveConcepts(); } public void conceptPersistence() { persistConcepts(); } public Concepts persist() { persistConcepts(); return this; } public void persist(Integer interval) { if (interval != null) autoSaveInterval = interval; persist(); } public A ensureHas(Class c, Runnable r) { A a = conceptOfType(c); if (a == null) { r.run(); a = conceptOfType(c); if (a == null) throw fail("Concept not made by " + r + ": " + shortClassName(c)); } return a; } public void ensureHas(Class c1, Class c2, Object func) { for (Concept a : conceptsOfType(c1)) { Concept b = findBackRef(a, c2); if (b == null) { callF(func, a); b = findBackRef(a, c2); if (b == null) throw fail("Concept not made by " + func + ": " + shortClassName(c2)); } } } public void forEvery(Class type, Object func) { for (Concept c : conceptsOfType(type)) callF(func, c); } public int deleteAll(Class type) { List l = (List) conceptsOfType(type); for (Concept c : l) c.delete(); return l(l); } public Collection allConcepts() { synchronized (concepts) { return new ArrayList(values(concepts)); } } public IConceptCounter conceptCounterForClass(Class c) { for (IFieldIndex idx : values(mapGet(fieldIndices, c))) if (idx instanceof IConceptCounter) return ((IConceptCounter) idx); for (IFieldIndex idx : values(mapGet(ciFieldIndices, c))) if (idx instanceof IConceptCounter) return ((IConceptCounter) idx); return null; } public int countConcepts(Class c, Object... params) { if (empty(params)) { IConceptCounter counter = conceptCounterForClass(c); if (counter != null) return counter.countConcepts(); return l(list(c)); } int n = 0; for (A x : list(c)) if (checkConceptFields(x, params)) ++n; return n; } public int countConcepts(String c, Object... params) { if (empty(params)) return l(list(c)); int n = 0; for (Concept x : list(c)) if (checkConceptFields(x, params)) ++n; return n; } public int countConcepts() { return l(concepts); } public synchronized void addConceptIndex(IConceptIndex index) { if (conceptIndices == null) conceptIndices = new ArrayList(); conceptIndices.add(index); } public synchronized void removeConceptIndex(IConceptIndex index) { if (conceptIndices == null) return; conceptIndices.remove(index); if (empty(conceptIndices)) conceptIndices = null; } public synchronized void addFieldIndex(Class c, String field, IFieldIndex index) { if (fieldIndices == null) fieldIndices = new HashMap(); Map map = fieldIndices.get(c); if (map == null) fieldIndices.put(c, map = new HashMap()); map.put(field, index); } public synchronized IFieldIndex getFieldIndex(Class c, String field) { if (fieldIndices == null) return null; Map map = fieldIndices.get(c); return map == null ? null : map.get(field); } public synchronized void addCIFieldIndex(Class c, String field, IFieldIndex index) { if (ciFieldIndices == null) ciFieldIndices = new HashMap(); Map map = ciFieldIndices.get(c); if (map == null) ciFieldIndices.put(c, map = new HashMap()); map.put(field, index); } public synchronized IFieldIndex getCIFieldIndex(Class c, String field) { if (ciFieldIndices == null) return null; Map map = ciFieldIndices.get(c); return map == null ? null : map.get(field); } public RC xnew(String name, Object... values) { return new RC(cnew(name, values)); } public void xset(long id, String field, Object value) { xset(new RC(id), field, value); } public void xset(RC c, String field, Object value) { if (value instanceof RC) value = getConcept((RC) value); cset(getConcept(c), field, value); } public Object xget(long id, String field) { return xget(new RC(id), field); } public Object xget(RC c, String field) { return xgetPost(cget(getConcept(c), field)); } public Object xgetPost(Object o) { o = deref(o); if (o instanceof Concept) return new RC((Concept) o); return o; } public void xdelete(long id) { xdelete(new RC(id)); } public void xdelete(RC c) { getConcept(c).delete(); } public void xdelete(List l) { for (RC c : l) xdelete(c); } public List xlist() { return map("toPassRef", allConcepts()); } public List xlist(String className) { return map("toPassRef", conceptsOfType(className)); } public boolean isTransient() { return eq(programID, "-"); } public String xfullgrab() { if (noXFullGrab) throw fail("no xfullgrab (DB too large)"); Lock __2324 = lock(); lock(__2324); try { if (changes == changesWritten && !isTransient()) return loadConceptsStructure(programID); return structure(cloneMap(concepts)); } finally { unlock(__2324); } } public void xshutdown() { cleanKillVM(); } public long xchangeCount() { return changes; } public int xcount() { return countConcepts(); } public void register(Concept c) { if (c._concepts == this) return; if (c._concepts != null) throw fail("Can't re-register"); c._concepts = this; c.id = internalID(); c.created = now(); concepts.put((long) c.id, c); c.change(); } public void conceptChanged(Concept c) { allChanged(); if (conceptIndices != null) for (IConceptIndex index : conceptIndices) index.update(c); } public boolean hasUnsavedData() { return changes != changesWritten || savingConcepts; } } public static class Concept extends DynamicObject { public transient Concepts _concepts; public long id; public long created, _modified; public List refs; public List backRefs; public Concept(String className) { super(className); _created(); } public Concept() { if (!_loading()) { _created(); } } public Concept(boolean unlisted) { if (!unlisted) _created(); } public static boolean loading() { return _loading(); } public static boolean _loading() { return dynamicObjectIsLoading(); } public void _created() { if (!isTrue(concepts_unlisted.get())) db_mainConcepts().register(this); } public class Ref { public A value; public Ref() { if (!dynamicObjectIsLoading()) refs = addDyn(refs, this); } public Ref(A value) { this.value = value; refs = addDyn(refs, this); index(); } public Concept concept() { return Concept.this; } public A get() { return value; } public boolean has() { return value != null; } public void set(A a) { if (a == value) return; unindex(); value = a; index(); } public void set(Ref ref) { set(ref.get()); } public void clear() { set((A) null); } public void index() { if (value != null) value._addBackRef(this); change(); } public void unindex() { if (value != null) value._removeBackRef(this); } public void change() { Concept.this.change(); } } public class RefL extends AbstractList { public List> l = new ArrayList(); public A set(int i, A o) { A prev = l.get(i).get(); l.get(i).set(o); return prev; } public void add(int i, A o) { l.add(i, new Ref(o)); } public A get(int i) { return l.get(i).get(); } public A remove(int i) { return l.remove(i).get(); } public int size() { return l.size(); } public boolean contains(Object o) { if (o instanceof Concept) for (Ref r : l) if (eq(r.get(), o)) return true; return super.contains(o); } } public void delete() { for (Ref r : unnull(refs)) r.unindex(); refs = null; for (Ref r : cloneList(backRefs)) r.set((Concept) null); backRefs = null; if (_concepts != null) { _concepts.concepts.remove((long) id); _concepts.allChanged(); if (_concepts.conceptIndices != null) for (IConceptIndex index : _concepts.conceptIndices) index.remove(this); _concepts = null; } id = 0; } public BaseXRef export() { return new BaseXRef(_concepts.progID(), id); } public void change() { _modified = now(); _change_withoutUpdatingModifiedField(); } public void _change_withoutUpdatingModifiedField() { if (_concepts != null) _concepts.conceptChanged(this); } public void _change() { change(); } public String _programID() { return _concepts == null ? getDBProgramID() : _concepts.progID(); } public void _addBackRef(Concept.Ref ref) { backRefs = addDyn(backRefs, ref); } public void _removeBackRef(Concept.Ref ref) { backRefs = removeDyn(backRefs, ref); } public void _setField(String field, Object value) { cset(this, field, value); } public void _setFields(Object... values) { cset(this, values); } } public static class RC { public transient Object owner; public String id; public RC() { } public RC(long id) { this.id = str(id); } public RC(Object owner, long id) { this.id = str(id); this.owner = owner; } public RC(Concept c) { this(c.id); } public long longID() { return parseLong(id); } public String toString() { return id; } public transient RemoteDB db; public String getString(String field) { return db.xS(this, field); } public Object get(String field) { return db.xget(this, field); } public void set(String field, Object value) { db.xset(this, field, value); } } public static class BaseXRef { public String programID; public long id; public BaseXRef() { } public BaseXRef(String programID, long id) { this.id = id; this.programID = programID; } public boolean equals(Object o) { if (!(o instanceof BaseXRef)) return false; BaseXRef r = (BaseXRef) o; return eq(programID, r.programID) && eq(id, r.id); } public int hashCode() { return programID.hashCode() + (int) id; } } public static class XRef extends Concept { public BaseXRef ref; public XRef() { } public XRef(BaseXRef ref) { this.ref = ref; _doneLoading2(); } public void _doneLoading2() { getIndex().put(ref, this); } public HashMap getIndex() { return getXRefIndex(_concepts); } } public static synchronized HashMap getXRefIndex(Concepts concepts) { HashMap cache = (HashMap) concepts.perClassData.get(XRef.class); if (cache == null) concepts.perClassData.put(XRef.class, cache = new HashMap()); return cache; } public static XRef lookupOrCreateXRef(BaseXRef ref) { XRef xref = getXRefIndex(db_mainConcepts()).get(ref); if (xref == null) xref = new XRef(ref); return xref; } public static void cleanMeUp_concepts() { if (db_mainConcepts() != null) db_mainConcepts().cleanMeUp(); } public static void loadAndAutoSaveConcepts() { db_mainConcepts().persist(); } public static void loadAndAutoSaveConcepts(int interval) { db_mainConcepts().persist(interval); } public static RC toPassRef(Concept c) { return new RC(c); } public static class MultiMap { public Map> data = new HashMap>(); public MultiMap() { } public MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiMap(MultiMap map) { putAll(map); } public MultiMap(Map> data) { this.data = data; } public void put(A key, B value) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); } } public void add(A key, B value) { put(key, value); } public void addAll(A key, Collection values) { synchronized (data) { putAll(key, values); } } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(A key, Collection values) { synchronized (data) { for (B value : values) put(key, value); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public List get(A key) { synchronized (data) { List list = data.get(key); return list == null ? Collections.emptyList() : list; } } public List getActual(A key) { synchronized (data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; } } public void clean(A key) { synchronized (data) { List list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); } } public Set keySet() { synchronized (data) { return data.keySet(); } } public Set keys() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { data.remove(key); } } public void remove(A key, B value) { synchronized (data) { List list = data.get(key); if (list != null) { list.remove(value); if (list.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { List list = get(key); return list.isEmpty() ? null : list.get(0); } } public void addAll(MultiMap map) { putAll(map); } public void putAll(MultiMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public void putAll(Map map) { synchronized (data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); } } public int keysSize() { synchronized (data) { return l(data); } } public int size() { synchronized (data) { int n = 0; for (List l : data.values()) n += l(l); return n; } } public List reverseGet(B b) { synchronized (data) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public List _makeEmptyList() { return new ArrayList(); } public Collection> allLists() { synchronized (data) { return new ArrayList(data.values()); } } public List allValues() { return concatLists(values(data)); } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } } public static class CancelToCancelPoint extends QuickException { public CancelPoint cp; public CancelToCancelPoint(CancelPoint cp) { this.cp = cp; } } public static class ConceptFieldIndexDesc implements IConceptIndex, IFieldIndex { public Class cc; public String field; public HashMap objectToValue = new HashMap(); public MultiMap valueToObject; public ConceptFieldIndexDesc() { valueToObject = treeMultiMap(reverseOrder()); } public ConceptFieldIndexDesc(Class cc, String field) { this(mainConcepts, cc, field); } public ConceptFieldIndexDesc(Concepts concepts, Class cc, String field) { this(); this.field = field; this.cc = cc; concepts.addConceptIndex(this); for (A c : list(concepts, cc)) updateImpl(c); concepts.addFieldIndex(cc, field, this); } public void update(Concept c) { if (!isInstance(cc, c)) return; updateImpl(c); } public synchronized void updateImpl(Concept c) { Val newValue = (Val) (cget(c, field)); Val oldValue = objectToValue.get(c); if (newValue == null || newValue != oldValue) { valueToObject.remove(oldValue, (A) c); valueToObject.put(newValue, (A) c); objectToValue.put((A) c, newValue); } } public synchronized void remove(Concept c) { if (!isInstance(cc, c)) return; Val value = (Val) (cget(c, field)); objectToValue.remove(c); valueToObject.remove(value, (A) c); } public synchronized A get(Val value) { return valueToObject.getFirst(value); } public synchronized List getAll(Val value) { return valueToObject.get(value); } public synchronized List allValues() { return cloneKeys_noSync(valueToObject.data); } public IterableIterator objectIterator() { return navigableMultiMapValuesIterator(valueToObject); } public synchronized MultiSet allValues_multiSet() { return multiMapToMultiSet(valueToObject); } } public static class Lowest { public A best; public double score; public transient Object onChange; public synchronized boolean isNewBest(double score) { return best == null || score < this.score; } public synchronized double bestScore() { return best == null ? Double.NaN : score; } public double score() { return bestScore(); } public synchronized float floatScore() { return best == null ? Float.NaN : (float) score; } public synchronized float floatScoreOr(float defaultValue) { return best == null ? defaultValue : (float) score; } public boolean put(A a, double score) { boolean change = false; synchronized (this) { if (a != null && isNewBest(score)) { best = a; this.score = score; change = true; } } if (change) pcallF(onChange); return change; } public synchronized A get() { return best; } public synchronized boolean has() { return best != null; } } public static interface IResourceLoader { public String loadSnippet(String snippetID); public String getTranspiled(String snippetID); public int getSnippetType(String snippetID); public String getSnippetTitle(String snippetID); public File loadLibrary(String snippetID); public File pathToJavaXJar(); public File getSnippetJar(String snippetID, String transpiledSrc); } public static class ReliableSingleThread implements Runnable { public Object runnable; public boolean trigger = false; public Thread thread; public String name = "Single Thread"; public F0 enter; public ReliableSingleThread(Object runnable) { this.runnable = runnable; } public void trigger() { go(); } public synchronized void go() { trigger = true; if (!running()) { AutoCloseable __2339 = callF(enter); try { thread = startThread(name, new Runnable() { public void run() { try { AutoCloseable __2340 = callF(enter); try { _run(); } finally { _close(__2340); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable __2340 = callF(enter); try {\r\n _run();\r\n } finally ..."; } }); } finally { _close(__2339); } } } public void run() { go(); } public void get() { go(); } public synchronized boolean running() { return thread != null; } public void triggerAndWait() { trigger(); while (running()) sleep(1); } public void _run() { while (licensed()) { synchronized (this) { if (!trigger) { thread = null; break; } trigger = false; } pcallF(runnable); } } public synchronized void cancel() { cancelAndInterruptThread(thread); thread = null; } } public static class PKIKeyPair { public String privateKey; public String publicKey; public PKIKeyPair() { } public PKIKeyPair(String privateKey, String publicKey) { this.publicKey = publicKey; this.privateKey = privateKey; } public boolean equals(Object o) { if (!(o instanceof PKIKeyPair)) return false; PKIKeyPair x = (PKIKeyPair) o; return eq(privateKey, x.privateKey) && eq(publicKey, x.publicKey); } public int hashCode() { int h = -1731104693; h = h * 2 + _hashCode(privateKey); h = h * 2 + _hashCode(publicKey); return h; } public String toString() { return "PKIKeyPair([secret], " + quote(publicKey) + ")"; } } public static class MultiSet { public Map map = new HashMap(); public MultiSet(boolean useTreeMap) { if (useTreeMap) map = new TreeMap(); } public MultiSet() { } public MultiSet(Iterable c) { addAll(c); } public MultiSet(MultiSet ms) { synchronized (ms) { for (A a : ms.keySet()) add(a, ms.get(a)); } } public synchronized void add(A key) { add(key, 1); } public synchronized void addAll(Iterable c) { if (c != null) for (A a : c) add(a); } public synchronized void addAll(MultiSet ms) { for (A a : ms.keySet()) add(a, ms.get(a)); } public synchronized void add(A key, int count) { if (count <= 0) return; if (map.containsKey(key)) map.put(key, map.get(key) + count); else map.put(key, count); } public synchronized int get(A key) { Integer i = map.get(key); return i != null ? i : 0; } public synchronized boolean contains(A key) { return map.containsKey(key); } public synchronized void remove(A key) { Integer i = map.get(key); if (i != null && i > 1) map.put(key, i - 1); else map.remove(key); } public synchronized List topTen() { return getTopTen(); } public synchronized List getTopTen() { return getTopTen(10); } public synchronized List getTopTen(int maxSize) { List list = getSortedListDescending(); return list.size() > maxSize ? list.subList(0, maxSize) : list; } public synchronized List highestFirst() { return getSortedListDescending(); } public synchronized List lowestFirst() { return reversedList(getSortedListDescending()); } public synchronized List getSortedListDescending() { List list = new ArrayList(map.keySet()); Collections.sort(list, new Comparator() { public int compare(A a, A b) { return map.get(b).compareTo(map.get(a)); } }); return list; } public synchronized int getNumberOfUniqueElements() { return map.size(); } public synchronized int uniqueSize() { return map.size(); } public synchronized Set asSet() { return map.keySet(); } public synchronized NavigableSet navigableSet() { return navigableKeys((NavigableMap) map); } public synchronized Set keySet() { return map.keySet(); } public synchronized A getMostPopularEntry() { int max = 0; A a = null; for (Map.Entry entry : map.entrySet()) { if (entry.getValue() > max) { max = entry.getValue(); a = entry.getKey(); } } return a; } public synchronized void removeAll(A key) { map.remove(key); } public synchronized int size() { int size = 0; for (int i : map.values()) size += i; return size; } public synchronized MultiSet mergeWith(MultiSet set) { MultiSet result = new MultiSet(); for (A a : set.asSet()) { result.add(a, set.get(a)); } return result; } public synchronized boolean isEmpty() { return map.isEmpty(); } public synchronized String toString() { return str(map); } public synchronized void clear() { map.clear(); } public synchronized Map asMap() { return cloneMap(map); } } public static class FixedRateTimer extends java.util.Timer { public FixedRateTimer() { this(false); } public FixedRateTimer(boolean daemon) { this(defaultTimerName(), daemon); } public FixedRateTimer(String name) { this(name, false); } public FixedRateTimer(String name, boolean daemon) { super(name, daemon); _registerTimer(this); } public List entries = synchroList(); public static class Entry { public static String _fieldOrder = "task firstTime period"; public TimerTask task; public long firstTime; public long period; public Entry() { } public Entry(TimerTask task, long firstTime, long period) { this.period = period; this.firstTime = firstTime; this.task = task; } public String toString() { return "Entry(" + task + ", " + firstTime + ", " + period + ")"; } } public void scheduleAtFixedRate(TimerTask task, long delay, long period) { entries.add(new Entry(task, now() + delay, period)); super.scheduleAtFixedRate(task, delay, period); } public void cancel() { entries.clear(); super.cancel(); } public int purge() { entries.clear(); return super.purge(); } public FixedRateTimer changeRate(int newPeriod) { Object r = ((SmartTimerTask) first(entries).task).r; cancel(); return doEvery(newPeriod, r); } } public static class CompilerBot { public static boolean verbose = false; public static File compileSnippet(String snippetID) { return compileSnippet(snippetID, ""); } public static Pair compileSnippet2(String snippetID) { return compileSnippet2(snippetID, ""); } public static File compileSnippet(String snippetID, String javaTarget) { return compileSnippet2(snippetID, javaTarget).a; } public static Pair compileSnippet2(String snippetID, String javaTarget) { String transpiledSrc = getServerTranspiled2(snippetID); int i = transpiledSrc.indexOf('\n'); String libs = transpiledSrc.substring(0, Math.max(0, i)); if (verbose) print("Compiling snippet: " + snippetID + ". Libs: " + libs); transpiledSrc = transpiledSrc.substring(i + 1); return pair(compile(transpiledSrc, libs, javaTarget, snippetID), transpiledSrc); } public static File compile(String src) { return compile(src, ""); } public static File compile(String src, String libs) { return compile(src, libs, null); } public static File compile(String src, String dehlibs, String javaTarget) { return compile(src, dehlibs, javaTarget, null); } public static File compile(String src, String dehlibs, String javaTarget, String progID) { if (verbose) print("Compiling " + l(src) + " chars"); String md5 = md5(dehlibs + "\n" + src + "\n" + progID); File jar = getJarFile(md5); if (jar == null || jar.length() <= 22) { List mainClass = findMainClass(javaTok(src)); boolean canRename = mainClass != null && useDummyMainClasses() && isSnippetID(progID) && !tok_classHasModifier(mainClass, "public"); if (verbose) print("useRenaming: " + useDummyMainClasses() + ", canRename: " + canRename + ", progID: " + progID); javaCompileToJar_optionalRename(src, dehlibs, jar, canRename ? progID : null, progID); } else { if (verbose) print("Getting classes from cache (" + jar.getAbsolutePath() + ", " + jar.length() + " bytes)"); touchFile(jar); } return jar; } public static File getJarFile(String md5) { assertTrue(isMD5(md5)); return new File(getCacheProgramDir("#1002203"), md5 + ".jar"); } } public static class T3 { public A a; public B b; public C c; public T3() { } public T3(A a, B b, C c) { this.c = c; this.b = b; this.a = a; } public T3(T3 t) { a = t.a; b = t.b; c = t.c; } public int hashCode() { return _hashCode(a) + 2 * _hashCode(b) - 4 * _hashCode(c); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof T3)) return false; T3 t = (T3) o; return eq(a, t.a) && eq(b, t.b) && eq(c, t.c); } public String toString() { return "(" + quoteBorderless(a) + ", " + quoteBorderless(b) + ", " + quoteBorderless(c) + ")"; } } public static class Pair implements Comparable> { public A a; public B b; public Pair() { } public Pair(A a, B b) { this.b = b; this.a = a; } public int hashCode() { return hashCodeFor(a) + 2 * hashCodeFor(b); } public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Pair)) return false; Pair t = (Pair) o; return eq(a, t.a) && eq(b, t.b); } public String toString() { return "<" + a + ", " + b + ">"; } public int compareTo(Pair p) { if (p == null) return 1; int i = ((Comparable) a).compareTo(p.a); if (i != 0) return i; return ((Comparable) b).compareTo(p.b); } } public static class PreIncLongCounter { public long value; public synchronized long get() { return ++value; } public synchronized void set(long value) { this.value = value; } } public static class JavaXClassLoader extends URLClassLoader { public String progID; public List files; public Set triedToLoad = synchroSet(); public Set loadedClasses = synchroSet(); public boolean retired = false; public Object retiredMarker; public JavaXClassLoader(String progID, List files) { this(progID, files, getSystemClassLoader()); } public JavaXClassLoader(String progID, List files, ClassLoader parent) { super(new URL[0], parent); this.progID = progID; this.files = files; { try { for (File f : files) addURL(f.toURI().toURL()); } catch (Exception __e) { throw rethrow(__e); } } fixACCInClassLoader(this); } public Class findClass(String name) throws ClassNotFoundException { boolean triedBefore = !triedToLoad.add(name); try { Class c = super.findClass(name); loadedClasses.add(c); if (eq(name, "main")) callOpt(javax(), "registerAMainClass", c); return c; } catch (ClassNotFoundException e) { throw new ClassNotFoundException("Class " + name + " not found in " + joinWithComma(map("f2s", files)) + " (progID=" + progID + ")" + (triedBefore ? ", tried to load before" : ""), e); } } public String toString() { return "JavaXClassLoader[" + systemHashCodeHex(this) + "] - " + progID; } } public static class ConceptFieldIndex implements IConceptIndex, IFieldIndex, IConceptCounter { public Class cc; public String field; public HashMap objectToValue = new HashMap(); public MultiMap valueToObject = new MultiMap(); public ConceptFieldIndex() { } public ConceptFieldIndex(Class cc, String field) { this(mainConcepts, cc, field); } public ConceptFieldIndex(Concepts concepts, Class cc, String field) { this.field = field; this.cc = cc; concepts.addConceptIndex(this); for (A c : list(concepts, cc)) updateImpl(c); concepts.addFieldIndex(cc, field, this); } public void update(Concept c) { if (!isInstance(cc, c)) return; updateImpl(c); } public synchronized void updateImpl(Concept c) { Val newValue = (Val) (cget(c, field)); Val oldValue = objectToValue.get(c); if (newValue == null || newValue != oldValue) { valueToObject.remove(oldValue, (A) c); valueToObject.put(newValue, (A) c); objectToValue.put((A) c, newValue); } } public synchronized void remove(Concept c) { if (!isInstance(cc, c)) return; Val value = (Val) (cget(c, field)); objectToValue.remove(c); valueToObject.remove(value, (A) c); } public synchronized A get(Val value) { return valueToObject.getFirst(value); } public synchronized List getAll(Val value) { return valueToObject.get(value); } public synchronized List allValues() { return cloneKeys_noSync(valueToObject.data); } public synchronized MultiSet allValues_multiSet() { return multiMapToMultiSet(valueToObject); } public Class conceptClass() { return cc; } public int countConcepts() { return l(objectToValue); } public Collection allConcepts() { return (Collection) keys(objectToValue); } } public abstract static class F0 { public abstract A get(); } public abstract static class F1 { public abstract B get(A a); } public abstract static class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } public abstract static class F2 { public abstract C get(A a, B b); } public static interface MakesBufferedImage { public BufferedImage getBufferedImage(); public int getWidth(); public int getHeight(); } public static class PKI { public static String getProvider() { return isAndroid() ? "BC" : "SUN"; } public static boolean verifySignature(byte[] publicKey, byte[] signature, String file) throws InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, IOException, SignatureException, InvalidKeySpecException { Signature sig = initPublicSignature(publicKey); FileInputStream datafis = new FileInputStream(file); BufferedInputStream bufin = new BufferedInputStream(datafis); byte[] buffer = new byte[1024]; while (bufin.available() != 0) { int len = bufin.read(buffer); sig.update(buffer, 0, len); } bufin.close(); return sig.verify(signature); } public static boolean verifySignature(byte[] publicKey, byte[] signature, byte[] data) { try { Signature sig = initPublicSignature(publicKey); sig.update(data); return sig.verify(signature); } catch (Exception __e) { throw rethrow(__e); } } public static Signature initPublicSignature(byte[] publicKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException { Signature sig = Signature.getInstance("SHA1withDSA", getProvider()); PublicKey pub = KeyFactory.getInstance("DSA", getProvider()).generatePublic(new X509EncodedKeySpec(publicKey)); sig.initVerify(pub); return sig; } public static byte[] sign(String file, byte[] privateKey) { try { Signature dsa = initSignature(privateKey); FileInputStream fis = new FileInputStream(file); BufferedInputStream bufin = new BufferedInputStream(fis); byte[] buffer = new byte[1024]; int len; while ((len = bufin.read(buffer)) >= 0) dsa.update(buffer, 0, len); bufin.close(); return dsa.sign(); } catch (Exception __e) { throw rethrow(__e); } } public static byte[] sign(byte[] data, byte[] privateKey) { try { Signature dsa = initSignature(privateKey); dsa.update(data); return dsa.sign(); } catch (Exception __e) { throw rethrow(__e); } } public static Signature initSignature(byte[] privateKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException { Signature dsa = Signature.getInstance("SHA1withDSA", getProvider()); EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey); PrivateKey priv = KeyFactory.getInstance("DSA", getProvider()).generatePrivate(keySpec); dsa.initSign(priv); return dsa; } public static KeyPair makeKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", getProvider()); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(1024, random); return keyGen.generateKeyPair(); } public static boolean makeStandardKeyPairIfNecessary() { try { File publicKeyPath = getStandardPublicKeyPath(); File privateKeyPath = getStandardPrivateKeyPath(); if (!publicKeyPath.exists()) { print("PKI: Making standard key pair"); KeyPair keyPair = makeKeyPair(); byte[] privateKey = keyPair.getPrivate().getEncoded(); print("PKI: Private key hex (debug) - " + bytesToHex(privateKey)); saveTextFile(privateKeyPath, privateKeyToString(privateKey)); String publicKey = publicKeyToString(keyPair.getPublic()); saveTextFile(publicKeyPath, publicKey); print("PKI: Standard key pair made!"); print(); printInfo(); return true; } return false; } catch (Exception __e) { throw rethrow(__e); } } public static void printInfo() { print("PKI: Machine's public key: " + publicKeyToString(getStandardPublicKey())); print("PKI: Machine's private key in: " + getStandardPrivateKeyPath()); print("PKI: Machine's public key also in: " + getStandardPublicKeyPath()); print("PKI: User's public key: " + publicKeyToString(userPublicKey())); print("PKI: User's private key in: " + userPrivateKeyPath()); print("PKI: User's public key also in: " + userPublicKeyPath()); } public static File getStandardPrivateKeyPath() { return new File(getSecretProgramDir("#1001547"), "Computer-Private-Key"); } public static File userPublicKeyPath() { return new File(getProgramDir("#1001547"), "User-Public-Key"); } public static File userPrivateKeyPath() { return new File(getSecretProgramDir("#1001547"), "User-Private-Key"); } public static File getStandardPublicKeyPath() { return new File(getProgramDir("#1001547"), "Computer-Public-Key"); } public static byte[] getStandardPrivateKey() { makeStandardKeyPairIfNecessary(); return privateKeyFromString(loadTextFile(getStandardPrivateKeyPath())); } public static byte[] getStandardPublicKey() { makeStandardKeyPairIfNecessary(); return publicKeyFromString(loadTextFile(getStandardPublicKeyPath())); } public static byte[] userPrivateKey() { makeUserKeyPairIfNecessary(); return privateKeyFromString(loadTextFile(userPrivateKeyPath())); } public static byte[] userPublicKey() { makeUserKeyPairIfNecessary(); return publicKeyFromString(loadTextFile(userPublicKeyPath())); } public static String publicKeyToString(PublicKey publicKey) { return publicKeyToString(publicKey.getEncoded()); } public static String privateKeyToString(PrivateKey privateKey) { return privateKeyToString(privateKey.getEncoded()); } public static byte[] publicKeyFromString(String key) { return base64decode(dropPrefixMandatory("publickey:", trim(key))); } public static byte[] privateKeyFromString(String key) { return base64decode(dropPrefixMandatory("privatekey:", trim(key))); } public static byte[] signatureFromString(String key) { return base64decode(key); } public static byte[] dataFromString(String text) { return toUtf8(text); } public static String signatureToString(byte[] signature) { return base64encode(signature); } public static String publicKeyToString(byte[] key) { return "publickey:" + base64encode(key); } public static String privateKeyToString(byte[] key) { return "privatekey:" + base64encode(key); } public static boolean makeUserKeyPairIfNecessary() { try { File publicKeyPath = userPublicKeyPath(); File privateKeyPath = userPrivateKeyPath(); if (!publicKeyPath.exists()) { print("PKI: Making user key pair"); KeyPair keyPair = makeKeyPair(); byte[] privateKey = keyPair.getPrivate().getEncoded(); print("PKI: Private key hex (debug) - " + bytesToHex(privateKey)); saveTextFile(privateKeyPath, privateKeyToString(privateKey)); String publicKey = publicKeyToString(keyPair.getPublic()); saveTextFile(publicKeyPath, publicKey); print("PKI: User key pair made!"); print(); printInfo(); return true; } return false; } catch (Exception __e) { throw rethrow(__e); } } } public static class CancelPoint implements AutoCloseable { public volatile boolean closed = false; public void close() { closed = true; } } public static class MRUCache extends LinkedHashMap { public int maxSize = 10; public MRUCache() { } public MRUCache(int maxSize) { this.maxSize = maxSize; } public boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } } public static interface IF0 { public A get(); } public abstract static class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception { } } public static class JavaXClassLoaderWithParent2 extends JavaXClassLoader { public ClassLoader virtualParent; public List classesToSkip; public JavaXClassLoaderWithParent2(String progID, List files, ClassLoader virtualParent, List classesToSkip) { super(progID, files); this.virtualParent = virtualParent; this.classesToSkip = classesToSkip; } public Class findClass(String name) throws ClassNotFoundException { if (shouldDelegate(name)) { Class c = virtualParent.loadClass(name); if (c != null) return c; } return super.findClass(name); } public boolean shouldDelegate(String name) { for (String s : classesToSkip) if (eq(name, s) || startsWith(name, s + "$")) return true; return false; } } public static interface IF2 { public C get(A a, B b); } public static class ConceptFieldIndexCI implements IConceptIndex, IFieldIndex, IConceptCounter { public Class cc; public String field; public HashMap objectToValue = new HashMap(); public MultiSetMap valueToObject = ciMultiSetMap(); public ConceptFieldIndexCI() { } public ConceptFieldIndexCI(Class cc, String field) { this(db_mainConcepts(), cc, field); } public ConceptFieldIndexCI(Concepts concepts, Class cc, String field) { this.field = field; this.cc = cc; concepts.addConceptIndex(this); for (A c : list(concepts, cc)) updateImpl(c); concepts.addCIFieldIndex(cc, field, this); } public void update(Concept c) { if (!isInstance(cc, c)) return; updateImpl(c); } public synchronized void updateImpl(Concept c) { String newValue = (String) (cget(c, field)); String oldValue = objectToValue.get(c); if (newValue == null || newValue != oldValue) { valueToObject.remove(oldValue, (A) c); valueToObject.put(newValue, (A) c); objectToValue.put((A) c, newValue); } } public synchronized void remove(Concept c) { if (!isInstance(cc, c)) return; String value = (String) (cget(c, field)); objectToValue.remove(c); valueToObject.remove(value, (A) c); } public synchronized A get(String value) { return valueToObject.getFirst(value); } public synchronized List getAll(String value) { return cloneList(valueToObject.get(value)); } public Class conceptClass() { return cc; } public int countConcepts() { return l(objectToValue); } public Collection allConcepts() { return (Collection) keys(objectToValue); } public synchronized List allValues() { return cloneKeys_noSync(valueToObject.data); } public synchronized MultiSet allValues_multiSet() { return multiSetMapToMultiSet(valueToObject); } public IterableIterator objectIterator() { return navigableMultiSetMapValuesIterator(valueToObject); } } public static interface Producer { public A next(); } public static ThreadLocal DynamicObject_loading = new ThreadLocal(); public static class DynamicObject { public String className; public LinkedHashMap fieldValues; public DynamicObject() { } public DynamicObject(String className) { this.className = className; } public Map _map() { return fieldValues; } } public static interface IF1 { public B get(A a); } public static class PersistableThrowable { public String className; public String msg; public String stacktrace; public PersistableThrowable() { } public PersistableThrowable(Throwable e) { if (e == null) className = "Crazy Null Error"; else { className = getClassName(e).replace('/', '.'); msg = e.getMessage(); stacktrace = getStackTrace_noRecord(e); } } public String toString() { return nempty(msg) ? className + ": " + msg : className; } } public static class ConceptsLoadedOnDemand { public Map loaded = new HashMap(); public List onCaseLoaded; public List onUnloadingCase; public Lock lock = lock(); public Concepts get(String caseID, Object extraInfo) { return conceptsForCase(caseID, extraInfo); } public Concepts getIfLoaded(String caseID) { Lock __2390 = lock; lock(__2390); try { return loaded.get(unnull(caseID)); } finally { unlock(__2390); } } public Concepts conceptsForCase(String caseID, Object extraInfo) { Lock __2391 = lock; lock(__2391); try { caseID = unnull(caseID); if (loaded.containsKey(caseID)) return assertNotNull("Concepts load error", loaded.get(caseID)); String id = dbID(caseID); print("Loading concepts for case " + id); Concepts cc = new Concepts(id); cc.persist(); loaded.put(caseID, cc); pcallFAll(onCaseLoaded, caseID, extraInfo, cc); return cc; } finally { unlock(__2391); } } public String dbID(String caseID) { return combineWithSlash(getDBProgramID(), caseID); } public void cleanMeUp() { cleanUpAndClear(loaded); } public void onCaseLoaded(VF3 f) { onCaseLoaded = listCreateAndAdd(onCaseLoaded, f); } public void onUnloadingCase(VF2 f) { onUnloadingCase = listCreateAndAdd(onUnloadingCase, f); } public void unloadCase(String caseID) { Lock __2392 = lock; lock(__2392); try { caseID = unnull(caseID); Concepts cc = loaded.get(caseID); if (cc != null) { pcallFAll(onUnloadingCase, caseID, cc); cleanUp(cc); loaded.remove(caseID); } } finally { unlock(__2392); } } } public static class QuickException extends RuntimeException { public Throwable fillInStackTrace() { return this; } public QuickException() { } public QuickException(Throwable e) { super(e); } public QuickException(String msg) { super(msg); } public QuickException(String msg, Throwable e) { super(msg, e); } } public static class MultiSetMap { public Map> data = new HashMap>(); public MultiSetMap() { } public MultiSetMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } public MultiSetMap(MultiSetMap map) { putAll(map); } public MultiSetMap(Map> data) { this.data = data; } public void put(A key, B value) { synchronized (data) { Set set = data.get(key); if (set == null) data.put(key, set = _makeEmptySet()); set.add(value); } } public void add(A key, B value) { put(key, value); } public void addAll(A key, Collection values) { synchronized (data) { putAll(key, values); } } public void addAllIfNotThere(A key, Collection values) { synchronized (data) { for (B value : values) setPut(key, value); } } public void setPut(A key, B value) { synchronized (data) { if (!containsPair(key, value)) put(key, value); } } public boolean containsPair(A key, B value) { synchronized (data) { return get(key).contains(value); } } public void putAll(A key, Collection values) { synchronized (data) { for (B value : values) put(key, value); } } public void removeAll(A key, Collection values) { synchronized (data) { for (B value : values) remove(key, value); } } public Set get(A key) { synchronized (data) { Set set = data.get(key); return set == null ? Collections.emptySet() : set; } } public Set getActual(A key) { synchronized (data) { Set set = data.get(key); if (set == null) data.put(key, set = _makeEmptySet()); return set; } } public void clean(A key) { synchronized (data) { Set list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); } } public Set keySet() { synchronized (data) { return data.keySet(); } } public Set keys() { synchronized (data) { return data.keySet(); } } public void remove(A key) { synchronized (data) { data.remove(key); } } public void remove(A key, B value) { synchronized (data) { Set set = data.get(key); if (set != null) { set.remove(value); if (set.isEmpty()) data.remove(key); } } } public void clear() { synchronized (data) { data.clear(); } } public boolean containsKey(A key) { synchronized (data) { return data.containsKey(key); } } public B getFirst(A key) { synchronized (data) { return first(get(key)); } } public void addAll(MultiSetMap map) { putAll(map); } public void putAll(MultiSetMap map) { synchronized (data) { for (A key : map.keySet()) putAll(key, map.get(key)); } } public void putAll(Map map) { synchronized (data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); } } public int keysSize() { synchronized (data) { return l(data); } } public int size() { synchronized (data) { int n = 0; for (Set l : data.values()) n += l(l); return n; } } public Set reverseGet(B b) { synchronized (data) { Set l = new HashSet(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } public Map> asMap() { synchronized (data) { return cloneMap(data); } } public boolean isEmpty() { synchronized (data) { return data.isEmpty(); } } public Set _makeEmptySet() { return new HashSet(); } public Collection> allLists() { synchronized (data) { return new HashSet(data.values()); } } public List allValues() { return concatLists(values(data)); } public Object mutex() { return data; } public String toString() { return "mm" + str(data); } } public static interface IConceptCounter { public Class conceptClass(); public int countConcepts(); public Collection allConcepts(); } public static interface IVF1 { public void get(A a); } public static interface IVar { public void set(A a); public A get(); public boolean has(); public void clear(); } public static class RemoteDB implements AutoCloseable { public DialogIO db; public String name; public RemoteDB(String s) { this(s, false); } public RemoteDB(String s, boolean autoStart) { name = s; if (isSnippetID(s)) name = dbBotName(s); db = findBot(name); if (db == null) if (autoStart) { nohupJavax(fsI(s)); waitForBotStartUp(name); assertNotNull("Weird problem", db = findBot(s)); } else throw fail("DB " + s + " not running"); } public boolean functional() { return db != null; } public List list() { return adopt((List) rpc(db, "xlist")); } public List list(String className) { return adopt((List) rpc(db, "xlist", className)); } public List xlist() { return list(); } public List xlist(String className) { return list(className); } public List adopt(List l) { if (l != null) for (RC rc : l) adopt(rc); return l; } public RC adopt(RC rc) { if (rc != null) rc.db = this; return rc; } public Object adopt(Object o) { if (o instanceof RC) return adopt((RC) o); return o; } public String xclass(RC o) { return (String) rpc(db, "xclass", o); } public Object xget(RC o, String field) { return adopt(rpc(db, "xget", o, field)); } public String xS(RC o, String field) { return (String) xget(o, field); } public RC xgetref(RC o, String field) { return adopt((RC) xget(o, field)); } public void xset(RC o, String field, Object value) { rpc(db, "xset", o, field, value); } public RC uniq(String className) { RC ref = first(list(className)); if (ref == null) ref = xnew(className); return ref; } public RC xuniq(String className) { return uniq(className); } public RC xnew(String className, Object... values) { return adopt((RC) rpc(db, "xnew", className, values)); } public void xdelete(RC o) { rpc(db, "xdelete", o); } public void xdelete(List l) { rpc(db, "xdelete", l); } public void close() { _close(db); } public String fullgrab() { return (String) rpc(db, "xfullgrab"); } public String xfullgrab() { return fullgrab(); } public void xshutdown() { rpc(db, "xshutdown"); } public long xchangeCount() { return (long) rpc(db, "xchangeCount"); } public int xcount() { return (int) rpc(db, "xcount"); } public void reconnect() { close(); db = findBot(name); } public RC rc(long id) { return new RC(this, id); } } public abstract static class DialogIO implements AutoCloseable { public String line; public boolean eos, loud, noClose; public Lock lock = lock(); public abstract String readLineImpl(); public abstract boolean isStillConnected(); public abstract void sendLine(String line); public abstract boolean isLocalConnection(); public abstract Socket getSocket(); public int getPort() { Socket s = getSocket(); return s == null ? 0 : s.getPort(); } public boolean helloRead = false; public int shortenOutputTo = 500; public String readLineNoBlock() { String l = line; line = null; return l; } public boolean waitForLine() { try { ping(); if (line != null) return true; line = readLineImpl(); if (line == null) eos = true; return line != null; } catch (Exception __e) { throw rethrow(__e); } } public String readLine() { waitForLine(); helloRead = true; return readLineNoBlock(); } public String ask(String s, Object... args) { if (loud) return askLoudly(s, args); if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); sendLine(s); return readLine(); } public String askLoudly(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); print("> " + shorten(s, shortenOutputTo)); sendLine(s); String answer = readLine(); print("< " + shorten(answer, shortenOutputTo)); return answer; } public void pushback(String l) { if (line != null) throw fail(); line = l; helloRead = false; } } public abstract static class DialogHandler { public abstract void run(DialogIO io); } public static Lock dbLock() { return db_mainConcepts().lock; } public static boolean bareDBMode_on = false; public static void bareDBMode() { bareDBMode(null); } public static void bareDBMode(Integer autoSaveInterval) { bareDBMode_on = true; conceptsAndBot(autoSaveInterval); } public static Field makeAccessible(Field f) { f.setAccessible(true); return f; } public static Method makeAccessible(Method m) { m.setAccessible(true); return m; } public static Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } public static void allInterfacesImplementedBy_find(Class c, Set set) { if (c.isInterface() && !set.add(c)) return; do { for (Class intf : c.getInterfaces()) allInterfacesImplementedBy_find(intf, set); } while ((c = c.getSuperclass()) != null); } public static Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } public static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } public static Method findStaticMethod(Class c, String method, Object... args) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (!m.getName().equals(method)) continue; if ((m.getModifiers() & Modifier.STATIC) == 0 || !findStaticMethod_checkArgs(m, args)) continue; return m; } c = c.getSuperclass(); } return null; } public static boolean findStaticMethod_checkArgs(Method m, Object[] args) { Class[] types = m.getParameterTypes(); if (types.length != args.length) return false; for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) return false; return true; } public static String fsi(String id) { return formatSnippetID(id); } public static List quoteAll(Collection l) { List x = new ArrayList(); for (String s : l) x.add(quote(s)); return x; } public static int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } public static boolean arraysEqual(Object[] a, Object[] b) { if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) if (neq(a[i], b[i])) return false; return true; } public static A set(A o, String field, Object value) { if (o == null) return null; if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); f.setAccessible(true); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } return o; } public static void set(Class c, String field, Object value) { if (c == null) return; try { Field f = set_findStaticField(c, field); f.setAccessible(true); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } public static Field set_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } public static Field set_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } public static String stdToString(Object o) { return standard_toString(o); } public static boolean stdEq2(Object a, Object b) { if (a == null) return b == null; if (b == null) return false; if (a.getClass() != b.getClass()) return false; for (String field : allFields(a)) if (neq(getOpt(a, field), getOpt(b, field))) return false; return true; } public static int stdHash2(Object a) { if (a == null) return 0; return stdHash(a, toStringArray(allFields(a))); } public static BigInteger plus(BigInteger a, BigInteger b) { return a.add(b); } public static BigInteger plus(BigInteger a, long b) { return a.add(bigint(b)); } public static BigInteger mul(BigInteger a, BigInteger b) { return a.multiply(b); } public static BigInteger mul(BigInteger a, long b) { return a.multiply(bigint(b)); } public static String bigintToGlobalID(BigInteger value) { char[] buf = new char[16]; for (int i = 16 - 1; i >= 0; i--) { buf[i] = charPlus('a', mod(value, 26).intValue()); value = div(value, 26); } return str(buf); } public static List getAll(Map map, Collection l) { return lookupAllOpt(map, l); } public static List getAll(Collection l, Map map) { return lookupAllOpt(map, l); } public static boolean hasConcept(Class c, Object... params) { return findConceptWhere(c, params) != null; } public static Object load(String varName) { readLocally(varName); return get(mc(), varName); } public static Object load(String progID, String varName) { readLocally(progID, varName); return get(mc(), varName); } public static boolean exceptionMessageContains(Throwable e, String s) { return cic(getInnerMessage(e), s); } public static void printShortException(Throwable e) { print(exceptionToStringShort(e)); } public static void printShortException(String s, Throwable e) { print(s, exceptionToStringShort(e)); } public static void clearConcepts() { db_mainConcepts().clearConcepts(); } public static void clearConcepts(Concepts concepts) { concepts.clearConcepts(); } public static void restoreLatestBackupIfConceptsFileEmpty(String dbID, Object... __) { boolean doIt = boolPar("doIt", __); File file = conceptsFile(dbID); if (fileExists(file) && fileSize(file) == 0) { print(file + " corrupted, trying to restore"); File backup = lastThat("fileNotEmpty", sortByFileName(conceptBackupFiles(dbID))); if (backup == null) { print("No usable backup found :("); return; } String msg = "RESTORING: " + backup; File log = javaxDataDir("db-restores.log"); if (doIt) logQuotedWithTime(log, msg); print(stringIf(!doIt, "[would be] ") + msg); if (doIt) { clearConceptsOf(dbID); copyFile(backup, file); print(msg = "DB RESTORED!"); if (doIt) logQuotedWithTime(log, msg); } } } public static void readLocally(String progID, String varNames) { readLocally2(mc(), progID, varNames); } public static void readLocally(String varNames) { readLocally2(mc(), programID(), varNames); } public static void readLocally2(Object obj, String varNames) { readLocally2(obj, programID(), varNames); } public static int readLocally_stringLength; public static ThreadLocal readLocally2_allDynamic = new ThreadLocal(); public static ThreadLocal readLocally2_classFinder = new ThreadLocal(); public static void readLocally2(Object obj, String progID, String varNames) { try { boolean allDynamic = isTrue(getAndClearThreadLocal(readLocally2_allDynamic)); for (String variableName : javaTokC(varNames)) { File textFile = new File(programDir(progID), variableName + ".text"); String value = loadTextFile(textFile); if (value != null) set(main.class, variableName, value); else { File structureFile = new File(programDir(progID), variableName + ".structure"); value = loadTextFile(structureFile); if (value == null) { File structureGZFile = new File(programDir(progID), variableName + ".structure.gz"); if (!structureGZFile.isFile()) return; InputStream fis = new FileInputStream(structureGZFile); try { GZIPInputStream gis = newGZIPInputStream(fis); InputStreamReader reader = new InputStreamReader(gis, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(reader); Object o = unstructure_tok(javaTokC_noMLS_onReader(bufferedReader), allDynamic, readLocally2_classFinder.get()); readLocally_set(obj, variableName, o); return; } finally { _close(fis); } } readLocally_stringLength = l(value); if (nempty(value)) readLocally_set(obj, variableName, unstructure(value, allDynamic, readLocally2_classFinder.get())); } } } catch (Exception __e) { throw rethrow(__e); } } public static void readLocally_set(Object c, String varName, Object value) { Object oldValue = get(c, varName); if (oldValue instanceof List && !(oldValue instanceof ArrayList) && value != null) { value = synchroList((List) value); } set(c, varName, value); } public static int done_minPrint = 10; public static long done(long startTime, String desc) { long time = now() - startTime; if (time >= done_minPrint) print(desc + " [" + time + " ms]"); return time; } public static long done(String desc, long startTime) { return done(startTime, desc); } public static long done(long startTime) { return done(startTime, ""); } public static RemoteDB connectToDBOpt(String dbNameOrID) { try { return new RemoteDB(dbNameOrID); } catch (Throwable __e) { return null; } } public static Concept getConcept(long id) { return db_mainConcepts().getConcept(id); } public static A getConcept(Class cc, long id) { return getConcept(db_mainConcepts(), cc, id); } public static A getConcept(Concepts concepts, Class cc, long id) { Concept c = concepts.getConcept(id); if (c == null) return null; if (!isInstance(cc, c)) throw fail("Can't convert concept: " + getClassName(c) + " -> " + getClassName(cc) + " (" + id + ")"); return (A) c; } public static void saveLocally(String variableName) { saveLocally(programID(), variableName); } public static void saveLocally(String progID, String variableName) { saveLocally2(mc(), progID, variableName); } public static void saveLocally2(Object obj, String variableName) { saveLocally2(obj, programID(), variableName); } public static void saveLocally2(Object obj, String progID, String variableName) { Lock __2463 = saveLock(); lock(__2463); try { File textFile = new File(programDir(progID), variableName + ".text"); File structureFile = new File(programDir(progID), variableName + ".structure"); Object x = get(obj, variableName); if (x == null) { textFile.delete(); structureFile.delete(); } else if (x instanceof String) { saveTextFile(textFile, (String) x); structureFile.delete(); } else { saveTextFile(structureFile, javaTokWordWrap(structure(x))); textFile.delete(); } } finally { unlock(__2463); } } public static void callRunnableWithWrapper(Object wrapper, Runnable r) { if (wrapper == null) callF(r); else callF(wrapper, r); } public static void saveGZStructureToFile(String file, Object o) { saveGZStructureToFile(getProgramFile(file), o); } public static void saveGZStructureToFile(File file, Object o) { try { File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); File tempFile = tempFileFor(file); if (tempFile.exists()) try { String saveName = tempFile.getPath() + ".saved." + now(); copyFile(tempFile, new File(saveName)); } catch (Throwable e) { printStackTrace(e); } FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath()); try { GZIPOutputStream gos = new GZIPOutputStream(fileOutputStream); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(gos, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); structureToPrintWriter(o, printWriter); printWriter.close(); gos.close(); fileOutputStream.close(); } catch (Throwable e) { fileOutputStream.close(); tempFile.delete(); throw rethrow(e); } if (file.exists() && !file.delete()) throw new IOException("Can't delete " + file.getPath()); if (!tempFile.renameTo(file)) throw new IOException("Can't rename " + tempFile + " to " + file); } catch (Exception __e) { throw rethrow(__e); } } public static A popFirst(List l) { if (empty(l)) return null; A a = first(l); l.remove(0); return a; } public static A popFirst(Collection l) { if (empty(l)) return null; A a = first(l); l.remove(a); return a; } public static String javaTokWordWrap(String s) { return javaTokWordWrap(120, s); } public static String javaTokWordWrap(int cols, String s) { int col = 0; List tok = javaTok(s); for (int i = 0; i < l(tok); i++) { String t = tok.get(i); if (odd(i) && col >= cols && !containsNewLine(t)) tok.set(i, t = rtrimSpaces(t) + "\n"); int idx = t.lastIndexOf('\n'); if (idx >= 0) col = l(t) - (idx + 1); else col += l(t); } return join(tok); } public static String ymd() { return ymd(now()); } public static String ymd(long now) { return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2); } public static String formatInt(int i, int digits) { return padLeft(str(i), '0', digits); } public static String formatInt(long l, int digits) { return padLeft(str(l), '0', digits); } public static int hours() { return hours(java.util.Calendar.getInstance()); } public static int hours(java.util.Calendar c) { return c.get(java.util.Calendar.HOUR_OF_DAY); } public static long toK(long l) { return (l + 1023) / 1024; } public static FixedRateTimer doEvery_daemon(long delay, final Object r) { return doEvery_daemon(delay, delay, r); } public static FixedRateTimer doEvery_daemon(long delay, long firstDelay, final Object r) { FixedRateTimer timer = new FixedRateTimer(true); timer.scheduleAtFixedRate(smartTimerTask(r, timer, delay), firstDelay, delay); return timer; } public static FixedRateTimer doEvery_daemon(double delaySeconds, final Object r) { return doEvery_daemon(toMS(delaySeconds), r); } public static A firstOfType(Collection c, Class type) { for (Object x : c) if (isInstanceX(type, x)) return (A) x; return null; } public static Collection allConcepts() { return db_mainConcepts().allConcepts(); } public static Collection allConcepts(Concepts concepts) { return concepts.allConcepts(); } public static List conceptsOfType(String type) { return db_mainConcepts().conceptsOfType(type); } public static List filterByType(Iterable c, Class type) { List l = new ArrayList(); if (c != null) for (Object x : c) if (isInstanceX(type, x)) l.add((A) x); return l; } public static List filterByType(Object[] c, Class type) { return filterByType(asList(c), type); } public static List filterByType(Class type, Iterable c) { return filterByType(c, type); } public static List filterByDynamicType(Collection c, String type) { List l = new ArrayList(); for (A x : c) if (eq(dynamicClassName(x), type)) l.add(x); return l; } public static boolean hasType(Collection c, Class type) { for (Object x : c) if (isInstanceX(type, x)) return true; return false; } public static A findBackRef(Concept c, Class type) { for (Concept.Ref r : c.backRefs) if (instanceOf(r.concept(), type)) return (A) r.concept(); return null; } public static A findBackRef(Class type, Concept c) { return findBackRef(c, type); } public static String loadConceptsStructure(String progID) { return loadTextFilePossiblyGZipped(getProgramFile(progID, "concepts.structure")); } public static String loadConceptsStructure() { return loadConceptsStructure(dbProgramID()); } public static void cleanKillVM() { try { ping(); assertNotOnAWTThread(); cleanKillVM_noSleep(); Object o = new Object(); synchronized (o) { o.wait(); } } catch (Exception __e) { throw rethrow(__e); } } public static void cleanKillVM_noSleep() { call(getJavaX(), "cleanKill"); } public static boolean dynamicObjectIsLoading() { return isTrue(getThreadLocal(DynamicObject_loading)); } public static List addDyn(List l, A a) { if (l == null) l = new ArrayList(); l.add(a); return l; } public static Str concept(String name) { for (Str s : list(Str.class)) if (eqic(s.name, name) || containsIgnoreCase(s.otherNames, name)) return s; return new Str(name); } public static void change() { callOpt(getOptMC("mainConcepts"), "allChanged"); } public static List removeDyn(List l, A a) { if (l == null) return null; l.remove(a); return empty(l) ? null : l; } public static void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } public static void remove(Collection l, A a) { if (l != null) l.remove(a); } public static Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } public static Set keySet(Object map) { return keys((Map) map); } public static Set keySet(MultiSet ms) { return ms.keySet(); } public static Set keySet(MultiMap mm) { return mm.keySet(); } public static A reverseGet(List l, int idx) { if (l == null || idx < 0) return null; int n = l(l); return idx < n ? l.get(n - 1 - idx) : null; } public static MultiMap treeMultiMap() { return new MultiMap(true); } public static MultiMap treeMultiMap(Comparator comparator) { return new MultiMap(new TreeMap>(comparator)); } public static Comparator reverseOrder() { return new Comparator() { public int compare(Object a, Object b) { return cmp(b, a); } }; } public static List cloneKeys_noSync(Map map) { return cloneList_noSync(keys(map)); } public static IterableIterator navigableMultiMapValuesIterator(final MultiMap mm) { return iteratorFromFunction(new F0() { public Iterator> it = concurrentlyIterateValues((NavigableMap) mm.data); public Iterator it2; public B get() { while (it2 == null || !it2.hasNext()) { if (!it.hasNext()) return null; it2 = concurrentlyIterateList(it.next()); } return it2.next(); } }); } public static MultiSet multiMapToMultiSet(MultiMap mm) { return multiMapAsMultiSet(mm); } public static File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } public static Thread startThread(Object runnable) { return startThread(defaultThreadName(), runnable); } public static Thread startThread(String name, Object runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(toRunnable(runnable), name)); } public static Thread startThread(Thread t) { _registerThread(t); t.start(); return t; } public static Class _run(String progID, String... args) { Class main = hotwire(progID); callMain(main, args); return main; } public static void cancelAndInterruptThread(Thread t) { if (t == null) return; cancelThread(t); t.interrupt(); } public static void add(BitSet bs, int i) { bs.set(i); } public static boolean add(Collection c, A a) { return c != null && c.add(a); } public static void add(Container c, Component x) { addToContainer(c, x); } public static List reversedList(Collection l) { List x = cloneList(l); Collections.reverse(x); return x; } public static NavigableSet navigableKeys(NavigableMap map) { return map == null ? new TreeSet() : map.navigableKeySet(); } public static NavigableSet navigableKeys(MultiSet ms) { return ((NavigableMap) ms.map).navigableKeySet(); } public static NavigableSet navigableKeys(MultiMap mm) { return ((NavigableMap) mm.data).navigableKeySet(); } public static String defaultTimerName_name; public static String defaultTimerName() { if (defaultTimerName_name == null) defaultTimerName_name = "A timer by " + programID(); return defaultTimerName_name; } public static Set _registerTimer_list = newWeakHashSet(); public static void _registerTimer(java.util.Timer timer) { _registerTimer_list.add(timer); } public static void cleanMeUp__registerTimer() { cancelTimers(getAndClearList(_registerTimer_list)); } public static List findMainClass(List tok) { for (List c : reversedList(allClasses(tok))) { String name = getClassDeclarationName(c); if (eq(name, "main") || name.startsWith("x")) return c; } return findBlock("m {", tok); } public static boolean useDummyMainClasses() { return true; } public static boolean tok_classHasModifier(List classDecl, String modifier) { if (classDecl == null) return false; int i = classDecl.indexOf("class"); return subList(classDecl, 0, i).contains(modifier); } public static boolean javaCompileToJar_useRAMDisk = false; public static File javaCompileToJar_optionalRename(String src, File destJar, String progIDForRename) { return javaCompileToJar_optionalRename(src, "", destJar, progIDForRename); } public static synchronized File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename) { return javaCompileToJar_optionalRename(src, dehlibs, destJar, progIDForRename, null); } public static synchronized File javaCompileToJar_optionalRename(String src, String dehlibs, File destJar, String progIDForRename, String progID) { String javaTarget = null; String dummyClass = "main"; if (progIDForRename != null) { dummyClass = dummyMainClassName(progIDForRename); src += "\nclass " + dummyClass + "{}"; } String md5 = md5(src); File jar = destJar; Class j = getJavaX(); if (javaTarget != null) setOpt(j, "javaTarget", javaTarget); File srcDir = tempDir(); String className = "main"; String fileName = dummyClass + ".java"; List tok = javaTok(src); String packageName = tok_packageName(tok); if (packageName != null) fileName = packageName.replace(".", "/") + "/" + tok_firstClassName(tok) + ".java"; File mainJava = new File(srcDir, fileName); saveTextFile(mainJava, src); File classesDir = javaCompileToJar_useRAMDisk ? tempDirPossiblyInRAMDisk() : tempDir(); try { List libraries = new ArrayList(); Matcher m = Pattern.compile("\\d+").matcher(dehlibs); while (m.find()) { String libID = m.group(); assertTrue(isSnippetID(libID)); libraries.add(loadLibraryOrSrcLib(libID)); } libraries.add(pathToJavaxJar()); String compilerOutput; try { compilerOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir); } catch (Throwable e) { compilerOutput = (String) get(getJavaX(), "javaCompilerOutput"); String msg = cleanJavaCompilerOutput(compilerOutput); if (neqic(e.getMessage(), "Java compiler returned errors.") || empty(msg)) msg = appendWithNewLine(msg, str(e)); printStackTrace(e); throw fail(msg); } compilerOutput = cleanJavaCompilerOutput("Annotation processing got disabled, since it requires a 1.6 compliant JVM"); if (nempty(compilerOutput)) { print("Compiler said: " + compilerOutput); } if (!anyFileWithExtensionInDir(classesDir, ".class")) throw fail("No classes generated"); saveTextFile(new File(classesDir, "main.java"), src); if (nempty(dehlibs)) saveTextFile(new File(classesDir, "libraries"), dehlibs); saveTextFile(new File(classesDir, "progID"), progID); dir2zip_recurse_verbose = false; int n = dir2zip_recurse(classesDir, jar); return jar; } finally { if (isInRAMDisk(classesDir)) deleteDirectory(classesDir); } } public static void touchFile(File file) { try { closeRandomAccessFile(newRandomAccessFile(mkdirsForFile(file), "rw")); } catch (Exception __e) { throw rethrow(__e); } } public static File getCacheProgramDir() { return getCacheProgramDir(getProgramID()); } public static File getCacheProgramDir(String snippetID) { return new File(userHome(), "JavaX-Caches/" + formatSnippetIDOpt(snippetID)); } public static String quoteBorderless(Object o) { if (o == null) return "null"; return quoteBorderless(str(o)); } public static String quoteBorderless(String s) { if (s == null) return "null"; StringBuilder out = new StringBuilder((int) (l(s) * 1.5)); quoteBorderless_impl(s, out); return out.toString(); } public static void quoteBorderless_impl(String s, StringBuilder out) { 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 out.append(c); } } public static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } public static Set synchroSet() { return synchroHashSet(); } public static Set synchroSet(Set set) { return Collections.synchronizedSet(set); } public static void fixACCInClassLoader(Object o) { try { AccessControlContext acc = vm_globalACC(); if (acc != null) replaceACCInClassLoader(o, acc); } catch (Throwable __e) { _handleException(__e); } } public static String systemHashCodeHex(Object o) { return intToHex(identityHashCode(o)); } public static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } public static File getSecretProgramDir() { return getSecretProgramDir(getProgramID()); } public static File getSecretProgramDir(String snippetID) { if (empty(snippetID)) return javaxSecretDir(); return newFile(javaxSecretDir(), formatSnippetID(snippetID)); } public static byte[] base64decode(String s) { byte[] alphaToInt = base64decode_base64toint; int sLen = s.length(); int numGroups = sLen / 4; if (4 * numGroups != sLen) throw new IllegalArgumentException("String length must be a multiple of four."); int missingBytesInLastGroup = 0; int numFullGroups = numGroups; if (sLen != 0) { if (s.charAt(sLen - 1) == '=') { missingBytesInLastGroup++; numFullGroups--; } if (s.charAt(sLen - 2) == '=') missingBytesInLastGroup++; } byte[] result = new byte[3 * numGroups - missingBytesInLastGroup]; int inCursor = 0, outCursor = 0; for (int i = 0; i < numFullGroups; i++) { int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch3 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); result[outCursor++] = (byte) ((ch2 << 6) | ch3); } if (missingBytesInLastGroup != 0) { int ch0 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); int ch1 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4)); if (missingBytesInLastGroup == 1) { int ch2 = base64decode_base64toint(s.charAt(inCursor++), alphaToInt); result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2)); } } return result; } public static int base64decode_base64toint(char c, byte[] alphaToInt) { int result = alphaToInt[c]; if (result < 0) throw new IllegalArgumentException("Illegal character " + c); return result; } public static final byte[] base64decode_base64toint = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 }; public static String base64encode(byte[] a) { int aLen = a.length; int numFullGroups = aLen / 3; int numBytesInPartialGroup = aLen - 3 * numFullGroups; int resultLen = 4 * ((aLen + 2) / 3); StringBuffer result = new StringBuffer(resultLen); char[] intToAlpha = intToBase64; int inCursor = 0; for (int i = 0; i < numFullGroups; i++) { int byte0 = a[inCursor++] & 0xff; int byte1 = a[inCursor++] & 0xff; int byte2 = a[inCursor++] & 0xff; result.append(intToAlpha[byte0 >> 2]); result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2) & 0x3f | (byte2 >> 6)]); result.append(intToAlpha[byte2 & 0x3f]); } if (numBytesInPartialGroup != 0) { int byte0 = a[inCursor++] & 0xff; result.append(intToAlpha[byte0 >> 2]); if (numBytesInPartialGroup == 1) { result.append(intToAlpha[(byte0 << 4) & 0x3f]); result.append("=="); } else { int byte1 = a[inCursor++] & 0xff; result.append(intToAlpha[(byte0 << 4) & 0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2) & 0x3f]); result.append('='); } } return result.toString(); } public static final char[] intToBase64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; public static MultiSetMap ciMultiSetMap() { MultiSetMap mm = new MultiSetMap(); mm.data = ciMap(); return mm; } public static MultiSet multiSetMapToMultiSet(MultiSetMap mm) { MultiSet ms = new MultiSet(); for (A a : keys(mm)) ms.add(a, l(mm.get(a))); return ms; } public static IterableIterator navigableMultiSetMapValuesIterator(final MultiSetMap mm) { return iteratorFromFunction(new F0() { public Iterator> it = concurrentlyIterateValues((NavigableMap) mm.data); public Iterator it2; public B get() { while (it2 == null || !it2.hasNext()) { if (!it.hasNext()) return null; it2 = iterator(asList(it.next())); } return it2.next(); } }); } public static String combineWithSlash(String a, String b) { return joinNempties("/", a, b); } public static void cleanUpAndClear(Collection c) { if (c == null) return; cleanUp(c); c.clear(); } public static void cleanUpAndClear(Map map) { if (map == null) return; cleanUp(map); map.clear(); } public static List listCreateAndAdd(List l, A a) { return addDyn(l, a); } public static Set emptySet() { return new HashSet(); } public static String dbBotName(String progIDWithCase) { return fsI_flex(progIDWithCase) + " Concepts"; } public static Map findBot_cache = synchroHashMap(); public static int findBot_timeout = 5000; public static DialogIO findBot(String searchPattern) { String subBot = null; int i = searchPattern.indexOf('/'); if (i >= 0 && (isJavaIdentifier(searchPattern.substring(0, i)) || isInteger(searchPattern.substring(0, i)))) { subBot = searchPattern.substring(i + 1); searchPattern = searchPattern.substring(0, i); if (!isInteger(searchPattern)) searchPattern = "Multi-Port at " + searchPattern + "."; } if (isInteger(searchPattern)) return talkToSubBot(subBot, talkTo(parseInt(searchPattern))); if (eq(searchPattern, "remote")) return talkToSubBot(subBot, talkTo("second.tinybrain.de", 4999)); Integer port = findBot_cache.get(searchPattern); if (port != null) try { DialogIO io = talkTo("localhost", port); io.waitForLine(); String line = io.readLineNoBlock(); if (indexOfIgnoreCase(line, searchPattern) == 0) { call(io, "pushback", line); return talkToSubBot(subBot, io); } } catch (Exception e) { e.printStackTrace(); } List bots = quickBotScan(); for (ProgramScan.Program p : bots) { if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) { findBot_cache.put(searchPattern, p.port); return talkToSubBot(subBot, talkTo("localhost", p.port)); } } for (ProgramScan.Program p : bots) { String botName = firstPartOfHelloString(p.helloString); boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM."); boolean shouldRecurse = startsWithIgnoreCase(botName, "Multi-Port") || isVM; if (shouldRecurse) try { Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots")); for (Number vport : subBots.keySet()) { String name = subBots.get(vport); if (startsWithIgnoreCase(name, searchPattern)) return talkToSubBot(vport.longValue(), talkTo("localhost", p.port)); } } catch (Throwable __e) { print(exceptionToStringShort(__e)); } } return null; } public static void nohupJavax(final String javaxargs) { { startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs);"; } }); } } public static void nohupJavax(final String javaxargs, final String vmArgs) { { startThread(new Runnable() { public void run() { try { call(hotwireOnce("#1008562"), "nohupJavax", javaxargs, vmArgs); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "call(hotwireOnce(\"#1008562\"), \"nohupJavax\", javaxargs, vmArgs);"; } }); } } public static long waitForBotStartUp_timeoutSeconds = 60; public static String waitForBotStartUp(String botName) { for (int i = 0; i < waitForBotStartUp_timeoutSeconds; i++) { sleepSeconds(i == 0 ? 0 : 1); String addr = getBotAddress(botName); if (addr != null) return addr; } throw fail("Bot not found: " + quote(botName)); } public static Object rpc(String botName, String method, Object... args) { return unstructure_matchOK2OrFail(sendToLocalBot(botName, rpc_makeCall(method, args))); } public static Object rpc(DialogIO bot, String method, Object... args) { return unstructure_matchOK2OrFail(bot.ask(rpc_makeCall(method, args))); } public static String rpc_makeCall(String method, Object... args) { if (empty(args)) return "call " + method; return format("call *", concatLists((List) ll(method), asList(args))); } public static void close(AutoCloseable c) { _close(c); } public static volatile boolean readLine_noReadLine = false; public static String readLine_lastInput; public static String readLine_prefix = "[] "; public static String readLine() { if (readLine_noReadLine) return null; String s = readLineHidden(); if (s != null) { readLine_lastInput = s; print(readLine_prefix + s); } return s; } public static String format3(String pat, Object... args) { if (args.length == 0) return pat; List tok = javaTokPlusPeriod(pat); int argidx = 0; for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*")) tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null")); return join(tok); } public static String format3_formatArg(Object arg) { if (arg == null) return "null"; if (arg instanceof String) { String s = (String) arg; return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s); } if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg); return quote(structure(arg)); } public static volatile boolean conceptsAndBot_running = false; public static boolean conceptsAndBot_thinOnStart = true; public static void conceptsAndBot() { conceptsAndBot(null); } public static void conceptsAndBot(Integer autoSaveInterval) { if (conceptsAndBot_running) return; conceptsAndBot_running = true; try { ensureDBNotRunning(dbBotStandardName()); } catch (Throwable _e) { db_mainConcepts().dontSave = true; throw rethrow(_e); } db_mainConcepts().persist(autoSaveInterval); dbBot(); if (conceptsAndBot_thinOnStart) { try { thinAProgramsBackups(getDBProgramID(), true); } catch (Throwable __e) { _handleException(__e); } } } public static Method findMethod_cached(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { _MethodCache cache = callOpt_getCache(((Class) o)); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (isStaticMethod(m) && findMethod_checkArgs(m, args, false)) return m; return null; } else { _MethodCache cache = callOpt_getCache(o.getClass()); List methods = cache.cache.get(method); if (methods != null) for (Method m : methods) if (findMethod_checkArgs(m, args, false)) return m; return null; } } catch (Exception __e) { throw rethrow(__e); } } public static String standard_toString(Object o) { if (o == null) return "null"; String name = shortClassName(o); Set fields = fieldNames(o); if (empty(fields)) return name; return name + "(" + joinWithComma(mapNonNulls(fields, field -> { Object value = get(o, field); if (value == null) return null; return field + "=" + str(value); })) + ")"; } public static Set allFields(Object o) { TreeSet fields = new TreeSet(); Class _c = _getClass(o); do { for (Field f : _c.getDeclaredFields()) fields.add(f.getName()); _c = _c.getSuperclass(); } while (_c != null); return fields; } public static int stdHash(Object a, String... fields) { if (a == null) return 0; int hash = getClassName(a).hashCode(); for (String field : fields) hash = hash * 2 + hashCode(getOpt(a, field)); return hash; } public static char charPlus(char a, int b) { return (char) (((int) a) + b); } public static int mod(int n, int m) { return (n % m + m) % m; } public static long mod(long n, long m) { return (n % m + m) % m; } public static BigInteger mod(BigInteger n, int m) { return n.mod(bigint(m)); } public static double mod(double n, double m) { return (n % m + m) % m; } public static List lookupAllOpt(Map map, Collection l) { List out = new ArrayList(); if (l != null) for (A a : l) addIfNotNull(out, map.get(a)); return out; } public static List lookupAllOpt(Collection l, Map map) { return lookupAllOpt(map, l); } public static String getInnerMessage(Throwable e) { if (e == null) return null; return getInnerException(e).getMessage(); } public static A lastThat(List l, Object pred) { for (int i = l(l) - 1; i >= 0; i--) { A a = l.get(i); if (checkCondition(pred, a)) return a; } return null; } public static A lastThat(Object pred, List l) { return lastThat(l, pred); } public static boolean fileNotEmpty(File f) { return isFile(f) && fileSize(f) > 0; } public static List sortByFileName(List l) { return sortFilesByName(l); } public static void logQuotedWithTime(String s) { logQuotedWithTime(standardLogFile(), s); } public static void logQuotedWithTime(File logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } public static void logQuotedWithTime(String logFile, String s) { logQuoted(logFile, logQuotedWithTime_format(s)); } public static String logQuotedWithTime_format(String s) { return (now()) + " " + s; } public static String stringIf(boolean b, String s) { return stringIfTrue(b, s); } public static void clearConceptsOf(String progID) { getProgramFile(progID, "concepts.structure").delete(); getProgramFile(progID, "idCounter.structure").delete(); } public static Lock saveLock_lock = fairLock(); public static Lock saveLock() { return saveLock_lock; } public static File tempFileFor(File f) { return new File(f.getPath() + "_temp"); } public static String rtrimSpaces(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t".indexOf(s.charAt(i - 1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } public static int year() { return localYear(); } public static int year(long now) { return localYear(now); } public static int month() { return localMonth(); } public static int month(long now) { return localMonth(now); } public static int dayOfMonth() { return localDayOfMonth(); } public static int dayOfMonth(long now) { return localDayOfMonth(now); } public static String padLeft(String s, char c, int n) { return rep(c, n - l(s)) + s; } public static String padLeft(String s, int n) { return padLeft(s, ' ', n); } public static String dynamicClassName(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return "main$" + ((DynamicObject) o).className; return className(o); } public static void assertNotOnAWTThread() { assertFalse("Can't do this in AWT thread", isAWTThread()); } public static Object getOptMC(String field) { return getOpt(mc(), field); } public static ArrayList cloneList_noSync(Iterable l) { return l instanceof Collection ? cloneList_noSync((Collection) l) : asList(l); } public static ArrayList cloneList_noSync(Collection l) { if (l == null) return new ArrayList(); return new ArrayList(l); } public static IterableIterator iteratorFromFunction(final Object f) { class IFF extends IterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = (A) callF(f); done = a == null; } } ; return new IFF(); } public static IterableIterator iteratorFromFunction(final F0 f) { return iteratorFromFunction_f0(f); } public static IterableIterator concurrentlyIterateValues(final NavigableMap map) { return iteratorFromFunction(new F0() { public Iterator it = keys(map).iterator(); public A key; public B get() { synchronized (map) { try { if (!it.hasNext()) return null; return map.get(key = it.next()); } catch (ConcurrentModificationException e) { print("Re-iterating"); it = map.tailMap(key, false).keySet().iterator(); if (!it.hasNext()) return null; return map.get(key = it.next()); } } } }); } public static IterableIterator concurrentlyIterateList(final List l) { return iteratorFromFunction_withEndMarker_f0(new F0() { public int i; public A get() { int _i = i++; synchronized (l) { if (_i < l(l)) { A a = l.get(_i); if (a == iteratorFromFunction_endMarker) throw fail("no"); return a; } return (A) iteratorFromFunction_endMarker; } } }); } public static MultiSet multiMapAsMultiSet(MultiMap mm) { MultiSet ms = new MultiSet(); for (A a : keys(mm)) ms.add(a, l(mm.get(a))); return ms; } public static File loadBinarySnippet(String snippetID) { try { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); long id = parseSnippetID(snippetID); if (isImageServerSnippet(id)) return loadImageAsFile(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } public static String defaultThreadName_name; public static String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } public static Runnable wrapAsActivity(Object r) { return toRunnable(r); } public static Thread newThread(Object runnable) { return new Thread(_topLevelErrorHandling(toRunnable(runnable))); } public static Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name); } public static Thread newThread(String name, Object runnable) { return newThread(runnable, name); } public static Runnable toRunnable(final Object o) { if (o instanceof Runnable) return (Runnable) o; return new Runnable() { public void run() { try { callF(o); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; } }; } public static void cancelThread(Thread t) { if (t == null) return; ping(); synchronized (ping_actions) { ping_actions.put(t, "cancelled"); ping_anyActions = true; } } public static 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);"; } }); } } public static Set newWeakHashSet() { return synchroWeakHashSet(); } public static void cancelTimers(Collection timers) { for (Object timer : timers) cancelTimer(timer); } public static List getAndClearList(Collection l) { if (l == null) return emptyList(); synchronized (collectionMutex(l)) { List out = cloneList(l); l.clear(); return out; } } public static HashSet allClasses_keywords = lithashset("class", "interface", "enum", "sclass", "sinterface", "record", "srecord"); public static List> allClasses(List tok) { List> l = new ArrayList(); int n = tok.size(); HashSet _allClasses_keywords = allClasses_keywords; for (int i = 1; i < n; i += 2) { String t = tok.get(i); if ("{".equals(t)) i = findEndOfBlock(tok, i) - 1; else if (_allClasses_keywords.contains(t) && !eqGetOneOf(tok, i - 2, ".", "include")) { int j = i; while (j < n && !tok.get(j).equals("{")) j += 2; j = findEndOfBlock(tok, j) + 1; i = leftScanModifiers(tok, i); l.add(tok.subList(i - 1, Math.min(n, j))); i = j - 2; } } return l; } public static List> allClasses(String text) { return allClasses(javaTok(text)); } public static String getClassDeclarationName(List tok) { if (tok != null) for (int i = 1; i + 2 < tok.size(); i += 2) if (allClasses_keywords.contains(tok.get(i)) && isIdentifier(tok.get(i + 2))) { if (eqGet(tok, i + 2, "noeq")) i += 2; return tok.get(i + 2); } return null; } public static List findBlock(String pat, List tok) { List tokpat = javaTok(pat); int i = findCodeTokens(tok, toStringArray(codeTokensOnly(tokpat))); if (i < 0) return null; int bracketIdx = i + tokpat.size() - 3; assertEquals("{", tok.get(bracketIdx)); int endIdx = findEndOfBlock(tok, bracketIdx); return subList(tok, i - 1, endIdx + 1); } public static String dummyMainClassName(String progID) { return "m" + psI(progID); } public static File tempDir() { return makeTempDir(); } public static String tok_packageName(List tok) { int i = jfind(tok, "package"); if (i < 0) return ""; i += 2; int j = jfind(tok, i, ";"); if (j < 0) return ""; return join(codeTokensOnly(subList(tok, i - 1, j))); } public static String tok_firstClassName(List tok) { int i = jfind(tok, "class "); return i < 0 ? null : tok.get(i + 2); } public static File tempDirPossiblyInRAMDisk() { File f = linux_fileInRamDisk(aGlobalID()); if (f != null) { f.mkdirs(); return f; } return makeTempDir(); } public static File pathToJavaxJar() { try { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.pathToJavaXJar(); int x = latestInstalledJavaX(); File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar"); if (!xfile.isFile()) { print("Saving " + f2s(xfile)); String url = "http://tinybrain.de/x30.jar"; byte[] data = loadBinaryPage(url); if (data.length < 1000000) throw fail("Could not load " + url); saveBinaryFile(xfile.getPath(), data); } return xfile; } catch (Exception __e) { throw rethrow(__e); } } public static String cleanJavaCompilerOutput(String s) { return dropPrefixTrim("Annotation processing got disabled, since it requires a 1.6 compliant JVM", s); } public static String appendWithNewLine(String a, String b) { if (empty(b)) return a; if (empty(a)) return b; return addSuffix(a, "\n") + b; } public static boolean anyFileWithExtensionInDir(File dir, String ext) { return nempty(filesWithExtension(ext, findAllFiles_noDirs(dir))); } public static boolean dir2zip_recurse_verbose = false; public static int dir2zip_recurse(File inDir, File zip) { return dir2zip_recurse(inDir, zip, ""); } public static int dir2zip_recurse(File inDir, File zip, String outPrefix) { try { mkdirsForFile(zip); FileOutputStream fout = newFileOutputStream(zip); ZipOutputStream outZip = new ZipOutputStream(fout); try { return dir2zip_recurse(inDir, outZip, outPrefix, 0); } finally { outZip.close(); } } catch (Exception __e) { throw rethrow(__e); } } public static int dir2zip_recurse(File inDir, ZipOutputStream outZip) { return dir2zip_recurse(inDir, outZip, "", 0); } public static int dir2zip_recurse(File inDir, ZipOutputStream outZip, String outPrefix, int level) { try { if (++level >= 20) throw fail("woot? 20 levels in zip?"); List files = new ArrayList(); for (File f : listFiles(inDir)) files.add(f); int n = 0; sortFilesByName(files); for (File f : files) { if (f.isDirectory()) { print("dir2zip_recurse: Scanning " + f.getAbsolutePath()); n += dir2zip_recurse(f, outZip, outPrefix + f.getName() + "/", level); } else { if (dir2zip_recurse_verbose) print("Copying " + f.getName()); outZip.putNextEntry(new ZipEntry(outPrefix + f.getName())); InputStream fin = new FileInputStream(f); copyStream(fin, outZip); fin.close(); ++n; } } return n; } catch (Exception __e) { throw rethrow(__e); } } public static boolean isInRAMDisk(File f) { return startsWith(f2s(f), "/dev/shm"); } public static void deleteDirectory(File dir) { deleteDirectory(dir, false, false); } public static void deleteDirectory(File dir, boolean verbose, boolean testRun) { deleteAllFilesInDirectory(dir, verbose, testRun); if (verbose) print((testRun ? "Would delete " : "Deleting ") + dir.getAbsolutePath()); if (!testRun) dir.delete(); } public static void closeRandomAccessFile(RandomAccessFile f) { if (f != null) try { f.close(); callJavaX("dropIO", f); } catch (Throwable e) { printStackTrace(e); } } public static RandomAccessFile newRandomAccessFile(File path, String mode) throws IOException { boolean forWrite = mode.indexOf('w') >= 0; if (forWrite) mkdirsForFile(path); RandomAccessFile f = new RandomAccessFile(path, mode); callJavaX("registerIO", f, path, forWrite); return f; } public static AccessControlContext vm_globalACC() { return (AccessControlContext) vm_generalMap_get("Global ACC"); } public static void replaceACCInClassLoader(Object o, AccessControlContext newACC) { ClassLoader cl = getClassLoaderOrSame(o); if (cl instanceof URLClassLoader) { try { setOpt(cl, "acc", newACC); try { setOpt((Object) getOpt(cl, "ucp"), "acc", newACC); } catch (Throwable e) { printShortException("replaceACCInClassLoader: ", e); if (java10OrHigher()) if (addDefaultVMOption("--add-opens java.base/jdk.internal.loader=ALL-UNNAMED")) print("Please restart the OS"); } } catch (Throwable __e) { _handleException(__e); } } } public static String intToHex(int i) { return bytesToHex(intToBytes(i)); } public static int identityHashCode(Object o) { return System.identityHashCode(o); } public static String fsI_flex(String s) { return startsWithDigit(s) ? "#" + s : s; } public static DialogIO talkToSubBot(final long vport, final DialogIO io) { return talkToSubBot(String.valueOf(vport), io); } public static DialogIO talkToSubBot(final String subBot, final DialogIO io) { if (subBot == null) return io; return new talkToSubBot_IO(subBot, io); } public static class talkToSubBot_IO extends DialogIO { public String subBot; public DialogIO io; public talkToSubBot_IO(String subBot, DialogIO io) { this.io = io; this.subBot = subBot; } public boolean isStillConnected() { return io.isStillConnected(); } public String readLineImpl() { return io.readLineImpl(); } public boolean isLocalConnection() { return io.isLocalConnection(); } public Socket getSocket() { return io.getSocket(); } public void close() { try { io.close(); } catch (Exception __e) { throw rethrow(__e); } } public void sendLine(String line) { io.sendLine(format3("please forward to bot *: *", subBot, line)); } } public static DialogIO talkTo(int port) { return talkTo("localhost", port); } public static int talkTo_defaultTimeout = 10000; public static int talkTo_timeoutForReads = 0; public static ThreadLocal> talkTo_byThread = new ThreadLocal(); public static DialogIO talkTo(String ip, int port) { try { String full = ip + ":" + port; Map map = talkTo_byThread.get(); if (map != null && map.containsKey(full)) return map.get(full); if (isLocalhost(ip) && port == vmPort()) return talkToThisVM(); return new talkTo_IO(ip, port); } catch (Exception __e) { throw rethrow(__e); } } public static class talkTo_IO extends DialogIO { public String ip; public int port; public Socket s; public Writer w; public BufferedReader in; public talkTo_IO(String ip, int port) { this.port = port; this.ip = ip; try { s = new Socket(); try { if (talkTo_timeoutForReads != 0) s.setSoTimeout(talkTo_timeoutForReads); s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout); } catch (Throwable e) { throw fail("Tried talking to " + ip + ":" + port, e); } w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); } catch (Exception __e) { throw rethrow(__e); } } public boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } public boolean isStillConnected() { return !(eos || s.isClosed()); } public void sendLine(String line) { try { Lock __2727 = lock; lock(__2727); try { w.write(line + "\n"); w.flush(); } finally { unlock(__2727); } } catch (Exception __e) { throw rethrow(__e); } } public String readLineImpl() { try { return in.readLine(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { if (!noClose) s.close(); } catch (IOException e) { } } public Socket getSocket() { return s; } } public static List quickBotScan() { return ProgramScan.quickBotScan(); } public static List quickBotScan(int[] preferredPorts) { return ProgramScan.quickBotScan(preferredPorts); } public static List quickBotScan(String searchPattern) { List l = new ArrayList(); for (ProgramScan.Program p : ProgramScan.quickBotScan()) if (indexOfIgnoreCase(p.helloString, searchPattern) == 0) l.add(p); return l; } public static String firstPartOfHelloString(String s) { int i = s.lastIndexOf('/'); return i < 0 ? s : rtrim(s.substring(0, i)); } public static String sendToLocalBotQuietly(String bot, String text, Object... args) { text = format3(text, args); DialogIO channel = newFindBot2(bot); try { if (channel == null) throw fail(quote(bot) + " not found"); try { channel.readLine(); channel.sendLine(text); String s = channel.readLine(); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } public static String sendToLocalBotQuietly(int port, String text, Object... args) { text = format3(text, args); DialogIO channel = talkTo(port); try { try { channel.readLine(); channel.sendLine(text); String s = channel.readLine(); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } public static Class hotwireOnce(String programID) { return hotwireCached(programID, false); } public static String getBotAddress(String bot) { List l = fullBotScan(bot); return empty(l) ? null : first(l).address; } public static Object unstructure_matchOK2OrFail(String s) { if (swic(s, "ok ")) return unstructure_startingAtIndex(s, 3); else throw fail(s); } public static String sendToLocalBot(String bot, String text, Object... args) { text = format3(text, args); DialogIO channel = findBot(bot); try { if (channel == null) throw fail(quote(bot) + " not found"); try { channel.readLine(); print(bot + "> " + shorten(text, 80)); channel.sendLine(text); String s = channel.readLine(); print(bot + "< " + shorten(s, 80)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } public static String sendToLocalBot(int port, String text, Object... args) { text = format3(text, args); DialogIO channel = talkTo(port); try { try { channel.readLine(); print(port + "> " + shorten(text, 80)); channel.sendLine(text); String s = channel.readLine(); print(port + "< " + shorten(s, 80)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } public static String format(String pat, Object... args) { return format3(pat, args); } public static String readLineHidden() { try { if (get(javax(), "readLine_reader") == null) set(javax(), "readLine_reader", new BufferedReader(new InputStreamReader(System.in, "UTF-8"))); try { return ((BufferedReader) get(javax(), "readLine_reader")).readLine(); } finally { consoleClearInput(); } } catch (Exception __e) { throw rethrow(__e); } } public static boolean isNonNegativeInteger(String s) { int n = l(s); if (n == 0) return false; int i = 0; while (i < n) { char c = s.charAt(i); if (c < '0' || c > '9') return false; ++i; } return true; } public static void ensureDBNotRunning(String name) { if (hasBot(name)) { try { String framesBot = dropSuffix(".", name) + " Frames"; print("Trying to activate frames of running DB: " + framesBot); if (isOK(sendOpt(framesBot, "activate frames")) && isMainProgram()) cleanKill(); } catch (Throwable __e) { _handleException(__e); } throw fail("Already running: " + name); } } public static void ensureDBNotRunning() { ensureDBNotRunning(dbBotStandardName()); } public static String dbBotStandardName() { String home = userHome(); String name = dbBotName(getDBProgramID()); if (neq(home, actualUserHome())) name += " " + quote(home); return name + "."; } public static volatile Android3 dbBot_instance; public static Android3 dbBot() { return dbBot(dbBotStandardName()); } public static Android3 dbBot(String name) { ensureDBNotRunning(name); return dbBot_instance = methodsBot2(name, assertNotNull(db_mainConcepts()), db_standardExposedMethods(), db_mainConcepts().lock); } public static Set fieldNames(Object o) { return allFields(o); } public static List mapNonNulls(Iterable l, Object f) { return mapNonNulls(f, l); } public static List mapNonNulls(Object f, Iterable l) { List x = new ArrayList(); if (l != null) for (Object o : l) addIfNotNull(x, callF(f, o)); return x; } public static List mapNonNulls(Object f, Object[] l) { List x = new ArrayList(); if (l != null) for (Object o : l) addIfNotNull(x, callF(f, o)); return x; } public static List mapNonNulls(Iterable l, F1 f) { return mapNonNulls(f, l); } public static List mapNonNulls(F1 f, Iterable l) { List x = new ArrayList(); if (l != null) for (Object o : l) addIfNotNull(x, callF(f, o)); return x; } public static List mapNonNulls(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) addIfNotNull(x, f.get(o)); return x; } public static int hashCode(Object a) { return a == null ? 0 : a.hashCode(); } public static List sortFilesByName(List l) { sort(l, new Comparator() { public int compare(File a, File b) { return stdcompare(a.getName(), b.getName()); } }); return l; } public static File standardLogFile() { return getProgramFile("log"); } public static String stringIfTrue(boolean b, String s) { return b ? s : ""; } public static int localYear() { return localYear(now()); } public static int localYear(long time) { return parseInt(simpleDateFormat_local("yyyy").format(time)); } public static int localMonth(long time) { return parseInt(simpleDateFormat_local("MM").format(time)); } public static int localMonth() { return localMonth(now()); } public static int localDayOfMonth(long time) { return parseInt(simpleDateFormat_local("dd").format(time)); } public static int localDayOfMonth() { return localDayOfMonth(now()); } public static IterableIterator iteratorFromFunction_f0(final F0 f) { class IFF2 extends IterableIterator { public A a; public boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } public void getNext() { if (done || a != null) return; a = f.get(); done = a == null; } } ; return new IFF2(); } public static File loadImageAsFile(String snippetIDOrURL) { try { if (isURL(snippetIDOrURL)) throw fail("not implemented"); if (!isSnippetID(snippetIDOrURL)) throw fail("Not a URL or snippet ID: " + snippetIDOrURL); String snippetID = "" + parseSnippetID(snippetIDOrURL); File file = imageSnippetCacheFile(snippetID); if (fileSize(file) > 0) return file; String imageURL = snippetImageURL_noHttps(snippetID); System.err.println("Loading image: " + imageURL); byte[] data = loadBinaryPage(imageURL); saveBinaryFile(file, data); return file; } catch (Exception __e) { throw rethrow(__e); } } public static Runnable _topLevelErrorHandling(final Runnable runnable) { final Object info = _threadInfo(); return new Runnable() { public void run() { try { try { _threadInheritInfo(info); runnable.run(); } catch (Throwable __e) { _handleException(__e); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "pcall {\r\n _threadInheritInfo(info);\r\n runnable.run();\r\n }"; } }; } public static Object swing(Object f) { return swingAndWait(f); } public static A swing(F0 f) { return (A) swingAndWait(f); } public static A swing(IF0 f) { return (A) swingAndWait(f); } public static Set synchroWeakHashSet() { return Collections.newSetFromMap((Map) newWeakHashMap()); } public static void cancelTimer(javax.swing.Timer timer) { if (timer != null) timer.stop(); } public static void cancelTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } public static void cancelTimer(Object o) { if (o instanceof java.util.Timer) cancelTimer((java.util.Timer) o); else if (o instanceof javax.swing.Timer) cancelTimer((javax.swing.Timer) o); else if (o instanceof AutoCloseable) { try { ((AutoCloseable) o).close(); } catch (Throwable __e) { _handleException(__e); } } } public static int findEndOfBlock(List cnc, int i) { int j = i + 2, level = 1, n = cnc.size(); while (j < n) { String t = cnc.get(j); if ("{".equals(t)) ++level; else if ("}".equals(t)) --level; if (level == 0) return j + 1; j += 2; } return n; } public static boolean eqGetOneOf(List l, int i, A... options) { return eqOneOf(get(l, i), options); } public static int leftScanModifiers(List tok, int i) { List mod = getJavaModifiers(); while (i > 1 && mod.contains(tok.get(i - 2))) i -= 2; return i; } public static List codeTokensOnly(List tok) { int n = tok.size(); List l = emptyList(n / 2); for (int i = 1; i < n; i += 2) l.add(tok.get(i)); return l; } public static File makeTempDir() { return (File) call(getJavaX(), "TempDirMaker_make"); } public static File linux_fileInRamDisk(String name) { if (!isLinux()) return null; File dir = newFile("/dev/shm"); if (dir.isDirectory()) return newFile(dir, name); return null; } public static int latestInstalledJavaX() { File[] files = new File(userHome(), ".javax").listFiles(); int v = 0; if (files != null) for (File f : files) { Matcher m = Pattern.compile("x(\\d\\d\\d?)\\.jar").matcher(f.getName()); if (m.matches()) v = Math.max(v, Integer.parseInt(m.group(1))); } return v; } public static String dropPrefixTrim(String prefix, String s) { return trim(dropPrefix(prefix, s)); } public static List filesWithExtension(String ext, List files) { return filesEndingWith(files, addPrefixIfNotEmpty2(".", ext)); } public static int deleteAllFilesInDirectory_minPathLength = 10; public static void deleteAllFilesInDirectory(File dir) { deleteAllFilesInDirectory(dir, false, false); } public static void deleteAllFilesInDirectory(File dir, boolean verbose, boolean testRun) { dir = getCanonicalFile(dir); assertTrue(f2s(dir), l(f2s(dir)) >= deleteAllFilesInDirectory_minPathLength); File[] files = dir.listFiles(); if (files == null) return; for (File f : files) { if (!isSymLink(f) && f.isDirectory()) deleteDirectory(f, verbose, testRun); else { if (verbose) print((testRun ? "Would delete " : "Deleting ") + f.getAbsolutePath()); if (!testRun) f.delete(); } } } public static Object callJavaX(String method, Object... args) { return callOpt(getJavaX(), method, args); } public static ClassLoader getClassLoaderOrSame(Object o) { return o instanceof ClassLoader ? (ClassLoader) o : getClassLoader(o); } public static boolean java10OrHigher() { return parseFirstInt(javaVersion()) >= 10; } public static boolean addDefaultVMOption(String option) { String s = defaultVMArgs(), old = s; if (!s.contains(option)) s = trim(s + " " + option); if (eq(old, s)) return false; { setDefaultVMArgs(s); return true; } } public static byte[] intToBytes(int i) { return new byte[] { (byte) (i >>> 24), (byte) (i >>> 16), (byte) (i >>> 8), (byte) i }; } public static boolean isLocalhost(String ip) { return isLoopbackIP(ip) || eqic(ip, "localhost"); } public static int vmPort() { return myVMPort(); } public static DialogIO talkToThisVM() { return new talkToThisVM_IO(); } public static class talkToThisVM_IO extends DialogIO { public List answers = ll(thisVMGreeting()); public boolean isLocalConnection() { return true; } public boolean isStillConnected() { return true; } public int getPort() { return vmPort(); } public void sendLine(String line) { answers.add(or2(sendToThisVM_newThread(line), "?")); } public String readLineImpl() { try { return popFirst(answers); } catch (Exception __e) { throw rethrow(__e); } } public void close() { } public Socket getSocket() { return null; } } public static Map newFindBot2_cache = synchroHashMap(); public static boolean newFindBot2_verbose = false; public static DialogIO newFindBot2(String name) { Integer port = newFindBot2_cache.get(name); if (port != null) { if (newFindBot2_verbose) print("newFindBot2: testing " + name + " => " + port); DialogIO io = talkTo(port); String q = format("has bot *", name); String s = io.ask(q); if (match("yes", s)) { io = talkToSubBot(name, io); call(io, "pushback", "?"); return io; } newFindBot2_cache.remove(name); if (newFindBot2_verbose) print("newFindBot2: dropping " + name + " => " + port); } DialogIO io = findBot(name); if (io != null) { newFindBot2_cache.put(name, io.getPort()); if (newFindBot2_verbose) print("newFindBot2: remembering " + name + " => " + port); } return io; } public static TreeMap hotwireCached_cache = new TreeMap(); public static Lock hotwireCached_lock = lock(); public static Class hotwireCached(String programID) { return hotwireCached(programID, true); } public static Class hotwireCached(String programID, boolean runMain) { return hotwireCached(programID, runMain, false); } public static Class hotwireCached(String programID, boolean runMain, boolean dependent) { Lock __2822 = hotwireCached_lock; lock(__2822); try { programID = formatSnippetID(programID); Class c = hotwireCached_cache.get(programID); if (c == null) { c = hotwire(programID); if (dependent) makeDependent(c); if (runMain) callMain(c); hotwireCached_cache.put(programID, c); } return c; } finally { unlock(__2822); } } public static class ScannedBot { public String helloString; public String address; public ScannedBot(String helloString, String address) { this.address = address; this.helloString = helloString; } public ScannedBot() { } } public static List fullBotScan() { return fullBotScan(""); } public static List fullBotScan(String searchPattern) { List bots = new ArrayList(); for (ProgramScan.Program p : quickBotScan()) { String botName = firstPartOfHelloString(p.helloString); boolean isVM = startsWithIgnoreCase(p.helloString, "This is a JavaX VM."); boolean shouldRecurse = swic(botName, "Multi-Port") || isVM; if (swic(botName, searchPattern)) bots.add(new ScannedBot(botName, "" + p.port)); if (shouldRecurse) try { Map subBots = (Map) unstructure(sendToLocalBotQuietly(p.port, "list bots")); for (Number vport : subBots.keySet()) { botName = subBots.get(vport); if (swic(botName, searchPattern)) bots.add(new ScannedBot(botName, p.port + "/" + vport)); } } catch (Exception e) { e.printStackTrace(); } } return bots; } public static Object unstructure_startingAtIndex(String s, int i) { return unstructure_tok(javaTokC_noMLS_iterator(s, i), false, null); } public static void consoleClearInput() { consoleSetInput(""); } public static boolean loadBufferedImage_useImageCache = true; public static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try { ping(); if (snippetIDOrURLOrFile == null) return null; if (isURL(snippetIDOrURLOrFile)) return imageIO_readURL(snippetIDOrURLOrFile); if (isAbsolutePath(snippetIDOrURLOrFile)) return loadBufferedImage(new File(snippetIDOrURLOrFile)); if (!isSnippetID(snippetIDOrURLOrFile)) throw fail("Not a URL or snippet ID or file: " + snippetIDOrURLOrFile); String snippetID = "" + parseSnippetID(snippetIDOrURLOrFile); IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return loadBufferedImage(rl.loadLibrary(snippetID)); File dir = imageSnippetsCacheDir(); if (loadBufferedImage_useImageCache) { dir.mkdirs(); File file = new File(dir, snippetID + ".png"); if (file.exists() && file.length() != 0) try { return ImageIO.read(file); } catch (Throwable e) { e.printStackTrace(); } } String imageURL = snippetImageURL_http(snippetID); print("Loading image: " + imageURL); BufferedImage image = imageIO_readURL(imageURL); if (loadBufferedImage_useImageCache) { File tempFile = new File(dir, snippetID + ".tmp." + System.currentTimeMillis()); ImageIO.write(image, "png", tempFile); tempFile.renameTo(new File(dir, snippetID + ".png")); } return image; } catch (Exception __e) { throw rethrow(__e); } } public static BufferedImage loadBufferedImage(File file) { try { return file.isFile() ? ImageIO.read(file) : null; } catch (Exception __e) { throw rethrow(__e); } } public static boolean hasBot(String searchPattern) { try { DialogIO io = findBot(searchPattern); if (io != null) { io.close(); return true; } else return false; } catch (Exception __e) { throw rethrow(__e); } } public static boolean isOK(String s) { s = trim(s); return swic(s, "ok ") || eqic(s, "ok") || matchStart("ok", s); } public static String sendOpt(String bot, String text, Object... args) { return sendToLocalBotOpt(bot, text, args); } public static boolean isMainProgram() { return creator() == null; } public static void cleanKill() { cleanKillVM(); } public static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods) { return methodsBot2(name, receiver, exposedMethods, null); } public static Android3 methodsBot2(String name, final Object receiver, final List exposedMethods, final Lock lock) { Android3 android = new Android3(); android.greeting = name; android.console = false; android.responder = new Responder() { public String answer(String s, List history) { return exposeMethods2(receiver, s, exposedMethods, lock); } }; return makeBot(android); } public static List db_standardExposedMethods_list = ll("xlist", "xnew", "xset", "xdelete", "xget", "xclass", "xfullgrab", "xshutdown", "xchangeCount", "xcount"); public static List db_standardExposedMethods() { return db_standardExposedMethods_list; } public static SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } public static File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } public static String snippetImageURL_noHttps(String snippetID) { return snippetImageURL_noHttps(snippetID, "png"); } public static String snippetImageURL_noHttps(String snippetID, String contentType) { return snippetImageURL(snippetID, contentType).replace("https://www.botcompany.de:8443/", "http://www.botcompany.de:8080/").replace("https://botcompany.de/", "http://botcompany.de/"); } public static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else EventQueue.invokeAndWait(addThreadInfoToRunnable(r)); } catch (Exception __e) { throw rethrow(__e); } } public static Object swingAndWait(final Object f) { if (isAWTThread()) return callF(f); else { final Var result = new Var(); swingAndWait(new Runnable() { public void run() { try { result.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; } }); return result.get(); } } public static List getJavaModifiers_list = litlist("static", "abstract", "public", "private", "protected", "final", "native", "volatile", "synchronized", "transient"); public static List getJavaModifiers() { return getJavaModifiers_list; } public static Cache isLinux_cache = new Cache("isLinux_load"); public static boolean isLinux() { return isLinux_cache.get(); } public static Boolean isLinux_load() { return !isWindows() && !isMac() && !isAndroid(); } public static List filesEndingWith(File dir, String suffix) { return listFilesWithSuffix(dir, suffix); } public static List filesEndingWith(List l, String suffix) { List out = new ArrayList(); for (File f : unnull(l)) if (!f.isDirectory() && (empty(suffix) || endsWithIgnoreCase(f.getName(), suffix))) out.add(f); return out; } public static String addPrefixIfNotEmpty2(String prefix, String s) { return empty(s) ? "" : addPrefix(prefix, s); } public static File getCanonicalFile(File f) { try { return f == null ? null : f.getCanonicalFile(); } catch (Exception __e) { throw rethrow(__e); } } public static ClassLoader getClassLoader(Object o) { return o == null ? null : _getClass(o).getClassLoader(); } public static int parseFirstInt(String s) { return parseInt(jextract("", s)); } public static String javaVersion() { return System.getProperty("java.version"); } public static String defaultVMArgs() { return javaxDefaultVMArgs(); } public static void setDefaultVMArgs(String args) { String oldArgs = javaxDefaultVMArgs(); args = trim(args); if (neq(unnull(oldArgs), unnull(args))) { print(); print("Changing default VM arguments from"); print(" " + oldArgs); print("to"); print(" " + args); print(); saveTextFile(javaxDataDir("default-vm-args"), nullIfEmpty(args)); } } public static boolean isLoopbackIP(String ip) { return eq(ip, "127.0.0.1"); } public static int myVMPort() { List records = (List) (get(getJavaX(), "record_list")); Object android = last(records); return or0((Integer) get(android, "port")); } public static String thisVMGreeting() { List record_list = (List) (get(getJavaX(), "record_list")); Object android = first(record_list); return getString(android, "greeting"); } public static String sendToThisVM_newThread(String s, Object... args) { final String _s = format(s, args); try { return (String) evalInNewThread(new F0() { public Object get() { try { return callStaticAnswerMethod(getJavaX(), _s); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "ret callStaticAnswerMethod(getJavaX(), _s);"; } }); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); return str(e); } } public static void consoleSetInput(final String text) { if (headless()) return; setTextAndSelectAll(consoleInputField(), text); focusConsole(); } public static BufferedImage imageIO_readURL(String url) { try { if (startsWith(url, "https:")) disableCertificateValidation(); return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } public static boolean isAbsolutePath(String s) { return s != null && new File(s).isAbsolute(); } public static boolean isAbsolutePath(File f) { return f != null && f.isAbsolute(); } public static File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } public static String snippetImageURL_http(String snippetID) { return snippetImageURL_http(snippetID, "png"); } public static String snippetImageURL_http(String snippetID, String contentType) { return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080"); } public static boolean matchStart(String pat, String s) { return matchStart(pat, s, null); } public static boolean matchStart(String pat, String s, Matches matches) { if (s == null) return false; return matchStart(pat, parse3_cachedInput(s), matches); } public static boolean matchStart(String pat, List toks, Matches matches) { if (toks == null) return false; List tokpat = parse3_cachedPattern(pat); if (toks.size() < tokpat.size()) return false; String[] m = match2(tokpat, toks.subList(0, tokpat.size())); if (m == null) return false; if (matches != null) { matches.m = new String[m.length + 1]; arraycopy(m, matches.m); matches.m[m.length] = joinSubList(toks, tokpat.size(), toks.size()); } return true; } public static String sendToLocalBotOpt(String bot, String text, Object... args) { if (bot == null) return null; text = format(text, args); DialogIO channel = findBot(bot); try { if (channel == null) { print(quote(bot) + " not found, skipping send: " + quote(text)); return null; } try { channel.readLine(); print(shorten(bot + "> " + text, 200)); channel.sendLine(text); String s = channel.readLine(); print(shorten(bot + "< " + s, 200)); return s; } catch (Throwable e) { e.printStackTrace(); return null; } } finally { _close(channel); } } public static boolean exposeMethods2_debug = false; public static String exposeMethods2(Object receiver, String s, List methodNames) { return exposeMethods2(receiver, s, methodNames, null); } public static String exposeMethods2(Object receiver, String s, List methodNames, Lock lock) { Matches m = new Matches(); if (exposeMethods2_debug) print("Received: " + s); if (match("call *", s, m)) { List l; if (isIdentifier(m.unq(0))) l = ll(m.unq(0)); else l = (List) unstructure(m.unq(0)); String method = getString(l, 0); if (!contains(methodNames, method)) throw fail("Method not allowed: " + method); if (lock != null) lock.lock(); try { if (exposeMethods2_debug) print("Calling: " + method); Object o = call(receiver, method, asObjectArray(subList(l, 1))); if (exposeMethods2_debug) print("Got: " + getClassName(o)); return ok2(structure(o)); } finally { if (lock != null) lock.unlock(); } } if (match("list methods", s)) return ok2(structure(methodNames)); return null; } public static int makeBot(String greeting) { return makeAndroid3(greeting).port; } public static Android3 makeBot(Android3 a) { makeAndroid3(a); return a; } public static Android3 makeBot(String greeting, Object responder) { Android3 a = new Android3(greeting); a.responder = makeResponder(responder); makeBot(a); return a; } public static Android3 makeBot() { return makeAndroid3(defaultBotName()); } public static TimeZone localTimeZone() { return getTimeZone(standardTimeZone()); } public static Runnable addThreadInfoToRunnable(final Object r) { final Object info = _threadInfo(); return info == null ? asRunnable(r) : new Runnable() { public void run() { try { _inheritThreadInfo(info); callF(r); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "_inheritThreadInfo(info); callF(r);"; } }; } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } public static boolean isMac() { return System.getProperty("os.name").toLowerCase().contains("mac"); } public static String jextract(String pat, String s) { return jextract(pat, javaTok(s)); } public static String jextract(String pat, List tok) { List tokpat = javaTok(pat); jfind_preprocess(tokpat); int i = jfind(tok, tokpat); if (i < 0) return null; int j = i + l(tokpat) - 2; return joinSubList(tok, i, j); } public static String javaxDefaultVMArgs() { File fileNew, fileOld; String text = loadTextFile(fileNew = javaxDataDir("default-vm-args")); if (text == null) { text = loadTextFile(fileOld = programFile("#1005850", "default-vm-args")); if (text != null) moveFile(fileOld, fileNew); } return trim(unnull(text)); } public static String nullIfEmpty(String s) { return isEmpty(s) ? null : s; } public static Map nullIfEmpty(Map map) { return isEmpty(map) ? null : map; } public static List nullIfEmpty(List l) { return isEmpty(l) ? null : l; } public static int or0(Integer i) { return i == null ? 0 : i; } public static long or0(Long l) { return l == null ? 0L : l; } public static double or0(Double d) { return d == null ? 0.0 : d; } public static Object evalInNewThread(final Object f) { final Flag flag = new Flag(); final Var var = new Var(); final Var exception = new Var(); { startThread(new Runnable() { public void run() { try { try { var.set(callF(f)); } catch (Throwable e) { exception.set(e); } flag.raise(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "try {\r\n var.set(callF(f));\r\n } catch (Throwable e) {\r\n exception..."; } }); } flag.waitUntilUp(); if (exception.has()) throw rethrow(exception.get()); return var.get(); } public static String callStaticAnswerMethod(List bots, String s) { for (Object c : bots) try { String answer = callStaticAnswerMethod(c, s); if (!empty(answer)) return answer; } catch (Throwable e) { print("Error calling " + getProgramID(c)); e.printStackTrace(); } return null; } public static String callStaticAnswerMethod(Object c, String s) { String answer = (String) callOpt(c, "answer", s, litlist(s)); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } public static String callStaticAnswerMethod(String s) { return callStaticAnswerMethod(mc(), s); } public static String callStaticAnswerMethod(String s, List history) { return callStaticAnswerMethod(mc(), s, history); } public static String callStaticAnswerMethod(Object c, String s, List history) { String answer = (String) callOpt(c, "answer", s, history); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } public static boolean headless() { return isHeadless(); } public static JTextField setTextAndSelectAll(final JTextField tf, final String text) { { swing(new Runnable() { public void run() { try { tf.setText(text); tf.selectAll(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "tf.setText(text);\r\n tf.selectAll();"; } }); } return tf; } public static JTextField consoleInputField() { Object console = get(getJavaX(), "console"); return (JTextField) getOpt(console, "tfInput"); } public static void focusConsole(String s) { setConsoleInput(s); focusConsole(); } public static void focusConsole() { JComponent tf = consoleInputFieldOrComboBox(); if (tf != null) { tf.requestFocus(); } } public static String ok2(String s) { return "ok " + s; } public static boolean makeAndroid3_disable = false; public static class Android3 { public String greeting; public boolean publicOverride = false; public int startPort = 5000; public Responder responder; public boolean console = true; public boolean quiet = false; public boolean daemon = false; public boolean incomingSilent = false; public int incomingPrintLimit = 200; public boolean useMultiPort = true; public boolean recordHistory = false; public boolean verbose = false; public int answerPrintLimit = 500; public boolean newLineAboveAnswer, newLineBelowAnswer; public int port; public long vport; public DialogHandler handler; public ServerSocket server; public Android3(String greeting) { this.greeting = greeting; } public Android3() { } public synchronized void dispose() { if (server != null) { try { server.close(); } catch (IOException e) { print("[internal] " + e); } server = null; } if (vport != 0) { try { print("Disposing " + this); removeFromMultiPort(vport); vport = 0; } catch (Throwable __e) { _handleException(__e); } } } public String toString() { return "Bot: " + greeting + " [vport " + vport + "]"; } } public abstract static class Responder { public abstract String answer(String s, List history); } public static Android3 makeAndroid3(final String greeting) { return makeAndroid3(new Android3(greeting)); } public static Android3 makeAndroid3(final String greeting, Responder responder) { Android3 android = new Android3(greeting); android.responder = responder; return makeAndroid3(android); } public static Android3 makeAndroid3(final Android3 a) { if (makeAndroid3_disable) return a; if (a.responder == null) a.responder = new Responder() { public String answer(String s, List history) { return callStaticAnswerMethod(s, history); } }; if (!a.quiet) print("[bot] " + a.greeting); if (a.console && (readLine_noReadLine || makeAndroid3_consoleInUse())) a.console = false; record(a); if (a.useMultiPort) a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a)); if (a.console) makeAndroid3_handleConsole(a); if (a.useMultiPort) return a; a.handler = makeAndroid3_makeDialogHandler(a); if (a.quiet) startDialogServer_quiet.set(true); try { a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler); } finally { startDialogServer_quiet.set(null); } a.server = startDialogServer_serverSocket; return a; } public static void makeAndroid3_handleConsole(final Android3 a) { if (!a.quiet) print("You may also type on this console."); { startThread(new Runnable() { public void run() { try { List history = new ArrayList(); while (licensed()) { String line; try { line = readLine(); } catch (Throwable e) { print(getInnerMessage(e)); break; } if (line == null) break; { history.add(line); history.add(makeAndroid3_getAnswer(line, history, a)); } } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "List history = new ArrayList();\r\n while (licensed()) {\r\n Stri..."; } }); } } public static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) { return new DialogHandler() { public void run(final DialogIO io) { if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) { io.sendLine("Sorry, not allowed"); return; } String dialogID = randomID(8); io.sendLine(a.greeting + " / Your ID: " + dialogID); List history = new ArrayList(); while (io.isStillConnected()) { if (io.waitForLine()) { final String line = io.readLineNoBlock(); String s = dialogID + " at " + now() + ": " + quote(line); if (!a.incomingSilent) print(shorten(s, a.incomingPrintLimit)); if (eq(line, "bye")) { io.sendLine("bye stranger"); return; } Matches m = new Matches(); if (a.recordHistory) history.add(line); String answer; if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) { dialogID = unquote(m.m[0]); answer = "ok"; } else try { makeAndroid3_io.set(io); answer = makeAndroid3_getAnswer(line, history, a); } finally { makeAndroid3_io.set(null); } if (a.recordHistory) history.add(answer); io.sendLine(answer); } } } }; } public static String makeAndroid3_getAnswer(String line, List history, Android3 a) { String answer, originalAnswer; try { originalAnswer = a.responder.answer(line, history); answer = makeAndroid3_fallback(line, history, originalAnswer); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); originalAnswer = answer = e.toString(); } if (!a.incomingSilent) { if (originalAnswer == null) originalAnswer = "?"; if (a.newLineAboveAnswer) print(); print(">" + dropFirst(indentx(2, shorten(rtrim(originalAnswer), a.answerPrintLimit)))); if (a.newLineBelowAnswer) print(); } return answer; } public static String makeAndroid3_fallback(String s, List history, String answer) { if (answer == null && match3("what is your pid", s)) return getPID(); if (answer == null && match3("what is your program id", s)) return getProgramID(); if (match3("get injection id", s)) return getInjectionID(); if (answer == null) answer = "?"; if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0) answer = quote(answer); return answer; } public static boolean makeAndroid3_consoleInUse() { if (isTrue(vm_generalMap_get("consoleInUse"))) return true; for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console) return true; return false; } public static Responder makeAndroid3_verboseResponder(final Android3 a) { return new Responder() { public String answer(String s, List history) { if (a.verbose) print("> " + shorten(s, a.incomingPrintLimit)); String answer = a.responder.answer(s, history); if (a.verbose) print("< " + shorten(answer, a.incomingPrintLimit)); return answer; } }; } public static ThreadLocal makeAndroid3_io = new ThreadLocal(); public static Android3 makeAndroid3() { return makeAndroid3(getProgramTitle() + "."); } public static String makeResponder_callAnswerMethod(Object bot, String s, List history) { String answer = (String) callOpt(bot, "answer", s, history); if (answer == null) answer = (String) callOpt(bot, "answer", s); return answer; } public static Responder makeResponder(final Object bot) { if (bot instanceof Responder) return (Responder) bot; if (bot instanceof String) { String f = (String) bot; return new Responder() { public String answer(String s, List history) { String answer = (String) callOptMC((String) bot, s, history); if (answer == null) answer = (String) callOptMC((String) bot, s); return answer; } }; } return new Responder() { public String answer(String s, List history) { return makeResponder_callAnswerMethod(bot, s, history); } }; } public static String defaultBotName() { return getProgramTitle() + "."; } public static TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } public static String standardTimeZone_name = "Europe/Berlin"; public static String standardTimeZone() { return standardTimeZone_name; } public static Runnable asRunnable(Object o) { return toRunnable(o); } public static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } public static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } public static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } public static boolean isEmpty(Object[] a) { return a == null || a.length == 0; } public static boolean isEmpty(byte[] a) { return a == null || a.length == 0; } public static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } public static String emptyToNull(String s) { return eq(s, "") ? null : s; } public static Map emptyToNull(Map map) { return empty(map) ? null : map; } public static void setConsoleInput(String text) { consoleSetInput(text); } public static JComponent consoleInputFieldOrComboBox() { Object console = get(getJavaX(), "console"); JComboBox cb = (JComboBox) (getOpt(console, "cbInput")); if (cb != null) return cb; return (JTextField) getOpt(console, "tfInput"); } public static void removeFromMultiPort(long vport) { if (vport == 0) return; for (Object port : getMultiPorts()) call(port, "removePort", vport); } public static List record_list = synchroList(); public static void record(Object o) { record_list.add(o); } public static Object addToMultiPort_responder; public static long addToMultiPort(final String botName) { return addToMultiPort(botName, new Object() { public String answer(String s, List history) { String answer = (String) (callOpt(getMainClass(), "answer", s, history)); if (answer != null) return answer; answer = (String) callOpt(getMainClass(), "answer", s); if (answer != null) return answer; if (match3("get injection id", s)) return getInjectionID(); return null; } }); } public static long addToMultiPort(final String botName, final Object responder) { addToMultiPort_responder = responder; startMultiPort(); List ports = getMultiPorts(); if (ports == null) return 0; if (ports.isEmpty()) throw fail("No multiports!"); if (ports.size() > 1) print("Multiple multi-ports. Using last one."); Object port = last(ports); Object responder2 = new Object() { public String answer(String s, List history) { if (match3("get injection id", s)) return getInjectionID(); if (match3("your name", s)) return botName; return (String) call(responder, "answer", s, history); } }; record(responder2); return (Long) call(port, "addResponder", botName, responder2); } public static AtomicInteger dialogServer_clients = new AtomicInteger(); public static boolean dialogServer_printConnects = false; public static ThreadLocal startDialogServer_quiet = new ThreadLocal(); public static Set dialogServer_knownClients = synchroTreeSet(); public static int startDialogServerOnPortAbove(int port, DialogHandler handler) { while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler)) ++port; return port; } public static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) { while (!forbiddenPort(port) && !startDialogServerIfPortAvailable(port, handler, true)) ++port; return port; } public static void startDialogServer(int port, DialogHandler handler) { if (!startDialogServerIfPortAvailable(port, handler)) throw fail("Can't start dialog server on port " + port); } public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) { return startDialogServerIfPortAvailable(port, handler, false); } public static ServerSocket startDialogServer_serverSocket; public static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); } catch (IOException e) { return false; } final ServerSocket _serverSocket = serverSocket; startDialogServer_serverSocket = serverSocket; Thread thread = new Thread("Socket accept port " + port) { public void run() { try { while (true) { try { final Socket s = _serverSocket.accept(); String client = s.getInetAddress().toString(); if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) { print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet()); dialogServer_knownClients.add(client); } String threadName = "Handling client " + s.getInetAddress(); Thread t2 = new Thread(threadName) { public void run() { try { final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); DialogIO io = new DialogIO() { public boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } public boolean isStillConnected() { return !(eos || s.isClosed()); } public void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Exception __e) { throw rethrow(__e); } } public String readLineImpl() { try { return in.readLine(); } catch (Exception __e) { throw rethrow(__e); } } public void close() { try { s.close(); } catch (IOException e) { } } public Socket getSocket() { return s; } }; try { handler.run(io); } finally { if (!io.noClose) s.close(); } } catch (IOException e) { print("[internal] " + e); } finally { } } }; t2.setDaemon(true); t2.start(); } catch (SocketTimeoutException e) { } } } catch (IOException e) { print("[internal] " + e); } } }; if (daemon) thread.setDaemon(true); thread.start(); if (!isTrue(getAndClearThreadLocal(startDialogServer_quiet))) print("Dialog server on port " + port + " started."); return true; } public static boolean publicCommOn() { return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication"))); } public static String indentx(String s) { return indentx(indent_default, s); } public static String indentx(int n, String s) { return dropSuffix(repeat(' ', n), indent(n, s)); } public static String indentx(String indent, String s) { return dropSuffix(indent, indent(indent, s)); } public static String processID_cached; public static String getPID() { if (processID_cached == null) { String name = ManagementFactory.getRuntimeMXBean().getName(); processID_cached = name.replaceAll("@.*", ""); } return processID_cached; } public static String getInjectionID() { return (String) call(getJavaX(), "getInjectionID", getMainClass()); } public static String getProgramTitle() { return getProgramName(); } public static Object callOptMC(String method, Object... args) { return callOpt(mc(), method, args); } public static List getMultiPorts() { return (List) callOpt(getJavaX(), "getMultiPorts"); } public static void startMultiPort() { List mp = getMultiPorts(); if (mp != null && mp.isEmpty()) { nohupJavax("#1001639"); throw fail("Upgrading JavaX, please restart this program afterwards."); } } public static Set synchroTreeSet() { return Collections.synchronizedSet(new TreeSet()); } public static boolean forbiddenPort(int port) { return port == 5037; } public static int indent_default = 2; public static String indent(int indent) { return repeat(' ', indent); } public static String indent(int indent, String s) { return indent(repeat(' ', indent), s); } public static String indent(String indent, String s) { return indent + s.replace("\n", "\n" + indent); } public static String indent(String s) { return indent(indent_default, s); } public static List indent(String indent, List lines) { List l = new ArrayList(); if (lines != null) for (String s : lines) l.add(indent + s); return l; } public static String getProgramName_cache; public static String getProgramName() { Lock __2985 = downloadLock(); lock(__2985); try { if (getProgramName_cache == null) getProgramName_cache = getSnippetTitleOpt(programID()); return getProgramName_cache; } finally { unlock(__2985); } } public static void _onLoad_getProgramName() { { startThread(new Runnable() { public void run() { try { getProgramName(); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "getProgramName();"; } }); } } public static Lock downloadLock_lock = fairLock(); public static Lock downloadLock() { return downloadLock_lock; } public static String getSnippetTitleOpt(String s) { return isSnippetID(s) ? getSnippetTitle(s) : s; } public static String getSnippetTitle(String id) { try { if (id == null) return null; if (!isSnippetID(id)) return "?"; IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.getSnippetTitle(id); if (isLocalSnippetID(id)) return localSnippetTitle(id); long parsedID = parseSnippetID(id); String url; if (isImageServerSnippet(parsedID)) url = imageServerURL() + "title/" + parsedID + muricaCredentialsQuery(); else if (isGeneralFileServerSnippet(parsedID)) url = "http://butter.botcompany.de:8080/files/name/" + parsedID; else url = tb_mainServer() + "/tb-int/getfield.php?id=" + parsedID + "&field=title" + standardCredentials_noCookies(); String title = trim(loadPageSilently(url)); if (title != null) try { saveTextFileIfChanged(snippetTitle_cacheFile(id), title); } catch (Throwable __e) { print(exceptionToStringShort(__e)); } return or(title, "?"); } catch (Exception __e) { throw rethrow(__e); } } public static String getSnippetTitle(long id) { return getSnippetTitle(fsI(id)); } public static String localSnippetTitle(String snippetID) { if (!isLocalSnippetID(snippetID)) return null; File f = localSnippetFile(snippetID); if (!f.exists()) return null; return or2(getFileInfoField(dropExtension(f), "Title"), "Unnamed"); } public static String muricaCredentialsQuery() { return htmlQuery(muricaCredentials()); } public static boolean isGeneralFileServerSnippet(long id) { return id >= 1400000 && id < 1500000; } public static String standardCredentials_noCookies() { return standardCredentials() + "&noCookies=1"; } public static boolean saveTextFileIfChanged(File f, String contents) { return saveTextFileIfDifferent(f, contents); } public static File snippetTitle_cacheFile(String snippetID) { return javaxCachesDir("Snippet Titles/" + psI(snippetID)); } public static String getFileInfoField(File f, String field) { return getOneLineFileInfoField(f, field); } public static File dropExtension(File f) { return f == null ? null : fileInSameDir(f, dropExtension(f.getName())); } public static String dropExtension(String s) { return takeFirst(s, smartLastIndexOf(s, '.')); } public static Object[] muricaCredentials() { String pass = muricaPassword(); return nempty(pass) ? new Object[] { "_pass", pass } : new Object[0]; } public static boolean saveTextFileIfDifferent(File f, String contents) { if (eq(loadTextFile(f), contents)) return false; { saveTextFile(f, contents); return true; } } public static String getOneLineFileInfoField(File f, String field) { File infoFile = associatedInfosFile(f); List lines = lines(loadTextFile(infoFile)); return firstStartingWithIC_drop(lines, field + ": "); } public static int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } public static File associatedInfosFile(File f) { return replaceExtension(f, ".infos"); } public static String firstStartingWithIC_drop(Collection l, final String prefix) { for (String s : unnull(l)) if (swic(s, prefix)) return substring(s, l(prefix)); return null; } public static String firstStartingWithIC_drop(String prefix, Collection l) { return firstStartingWithIC_drop(l, prefix); } public static File replaceExtension(File f, String extOld, String extNew) { return newFile(replaceExtension(f2s(f), extOld, extNew)); } public static File replaceExtension(File f, String extNew) { return replaceExtension(f, fileExtension(f), extNew); } public static String replaceExtension(String s, String extOld, String extNew) { s = dropSuffixIC(addPrefixOptIfNempty(".", extOld), s); return s + addPrefixOptIfNempty(".", extNew); } public static String replaceExtension(String name, String extNew) { return replaceExtension(name, fileExtension(name), extNew); } public static String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } public static String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } public static String addPrefixOptIfNempty(String prefix, String s) { return addPrefixIfNotEmpty2(prefix, s); } public static class Str extends Concept { public String name; public List otherNames = new ArrayList(); public Str() { } public Str(String name) { this.name = name; } public String toString() { return name; } } public static class ProgramScan { public static int threads = isWindows() ? 500 : 10; public static int timeout = 5000; public static String ip = "127.0.0.1"; public static int quickScanFrom = 10000, quickScanTo = 10999; public static int maxNumberOfVMs_android = 4; public static int maxNumberOfVMs_nonAndroid = 50; public static int maxNumberOfVMs; public static boolean verbose = false; public static class Program { public int port; public String helloString; public Program(int port, String helloString) { this.helloString = helloString; this.port = port; } } public static List scan() { try { return scan(1, 65535); } catch (Exception __e) { throw rethrow(__e); } } public static List scan(int fromPort, int toPort) { return scan(fromPort, toPort, new int[0]); } public static List scan(int fromPort, int toPort, int[] preferredPorts) { try { Set preferredPortsSet = new HashSet(asList(preferredPorts)); int scanSize = toPort - fromPort + 1; String name = toPort < 10000 ? "bot" : "program"; int threads = isWindows() ? min(500, scanSize) : min(scanSize, 10); final ExecutorService es = Executors.newFixedThreadPool(threads); if (verbose) print(firstToUpper(name) + "-scanning " + ip + " with timeout " + timeout + " ms in " + threads + " threads."); startTiming(); List> futures = new ArrayList(); List ports = new ArrayList(); for (int port : preferredPorts) { futures.add(checkPort(es, ip, port, timeout)); ports.add(port); } for (int port = fromPort; port <= toPort; port++) if (!preferredPortsSet.contains(port) && !forbiddenPort(port)) { futures.add(checkPort(es, ip, port, timeout)); ports.add(port); } es.shutdown(); List programs = new ArrayList(); long time = now(); int i = 0; for (final Future f : futures) { if (verbose) print("Waiting for port " + get(ports, i++) + " at time " + (now() - time)); Program p = f.get(); if (p != null) programs.add(p); } if (verbose) print("Found " + programs.size() + " " + name + "(s) on " + ip); return programs; } catch (Exception __e) { throw rethrow(__e); } } public static Future checkPort(final ExecutorService es, final String ip, final int port, final int timeout) { return es.submit(new Callable() { @Override public Program call() { try { Socket socket = new Socket(); try { socket.setSoTimeout(timeout); socket.connect(new InetSocketAddress(ip, port), timeout); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); String hello = or(in.readLine(), "?"); return new Program(port, hello); } finally { socket.close(); } } catch (Exception ex) { return null; } } }); } public static List quickScan() { return scan(quickScanFrom, quickScanTo); } public static List quickBotScan() { return quickBotScan(new int[0]); } public static List quickBotScan(int[] preferredPorts) { if (maxNumberOfVMs == 0) maxNumberOfVMs = isAndroid() ? maxNumberOfVMs_android : maxNumberOfVMs_nonAndroid; return scan(4999, 5000 + maxNumberOfVMs - 1, preferredPorts); } } public static class Flag implements Runnable { public boolean up = false; public synchronized boolean raise() { if (!up) { up = true; notifyAll(); return true; } else return false; } public synchronized void waitUntilUp() { while (!up) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void waitUntilUp(long timeout) { if (!up) { try { wait(timeout); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized boolean isUp() { return up; } public boolean get() { return isUp(); } public String toString() { return isUp() ? "up" : "down"; } public void waitForThisOr(Flag otherFlag) { try { while (!isUp() && !otherFlag.isUp()) Thread.sleep(50); } catch (Exception __e) { throw rethrow(__e); } } public void run() { raise(); } } public static class Cache { public Object maker; public A value; public long loaded; public static boolean debug = false; public long changeCount; public Lock lock = lock(); public Cache() { } public Cache(Object maker) { this.maker = maker; } public A get() { if (hasLock(lock)) return value; Lock __3046 = lock; lock(__3046); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__3046); } } public void clear() { Lock __3047 = lock; lock(__3047); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__3047); } } public void clear(double seconds) { Lock __3048 = lock; lock(__3048); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded + seconds * 1000) clear(); } finally { unlock(__3048); } } public void set(A a) { Lock __3049 = lock; lock(__3049); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__3049); } } public A make() { return (A) callF(maker); } } public static String firstToUpper(String s) { if (empty(s)) return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } public static long stopTiming_defaultMin = 10; public static long startTiming_startTime; public static void startTiming() { startTiming_startTime = now(); } public static void stopTiming() { stopTiming(null); } public static void stopTiming(String text) { stopTiming(text, stopTiming_defaultMin); } public static void stopTiming(String text, long minToPrint) { long time = now() - startTiming_startTime; if (time >= minToPrint) { text = or2(text, "Time: "); print(text + time + " ms"); } } public static boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } }