import java.util.*; import java.util.zip.*; import java.util.List; import java.util.regex.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.concurrent.locks.*; import java.util.function.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.table.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.lang.ref.*; import java.lang.management.*; import java.security.*; import java.security.spec.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.awt.geom.*; import javax.imageio.*; import java.math.*; import java.time.Duration; import java.lang.invoke.VarHandle; import java.lang.invoke.MethodHandles; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.awt.geom.*; import static x30_pkg.x30_util.DynamicObject; import java.text.*; import java.text.NumberFormat; import java.util.TimeZone; class main { static Object serveFile(File file) { return call(getMainBot(), "serveFile", file); } static Object serveFile(File file, String mimeType) { return call(getMainBot(), "serveFile", file, mimeType); } static Object serve404() { return subBot_serve404(); } static Object serve404(String msg) { return subBot_serve404(msg); } //sO serveRedirect(S url) { ret call(getMainBot(), 'serveRedirect, url); } static ThreadLocal youtubeOff = new ThreadLocal(); static int perPage = 20; static boolean pkiValidation = true; static String rawSelfLink(String uri) { return "/blog" + addSlashPrefix(uri); } static Object html(String uri, final Map params) { try { if (domain() == null) return serveDelayed404(); String vis = registerVisitor(); { var __3= domainAndURISwitch(uri, params); if (__3 != null) return __3; } if (!eq(uri, "/") || !domainIsUnder(domain(), "botcompany.de")) { print("404: " + domain() + " / " + uri); return serveDelayed404(); } { var __4= redirectToHTTPS(uri, params); if (__4 != null) return __4; } return serveBlog(uri, params); } catch (Exception __e) { throw rethrow(__e); } } static Object redirectToHTTPS(String uri, Map params) { if (!subBot_isHttps_defaultToTrue()) return subBot_serveRedirect("https://" + domain() + uri + htmlQuery(params)); return null; } static Object serveBlog(String uri, Map params) { tempSetThreadLocal(youtubeOff, eq("1", params.get("youtubeOff")) || eqOneOf(params.get("youtube"), "0", "off", "no")); Object[] linkStyle = litobjectarray("style", "color: inherit; text-decoration: underline"); String uri_orig = uri; uri = dropPrefix("/", uri); int page = startsWithDigit(uri) ? parseFirstInt(uri) : 1; String date = params.get("date"); List allPosts = ll( imagePost("2023/2/20", "The curve we are after", "#1103203", "50%", p("My future trading strategy on the LDO coin simulated over the last half year. $1,800 from a $100 investment. At least that's what the simulator says. Now running it for real to check.") + p("The blue line at the bottom is the comparison investment: Just buying some LDO for $100. It doesn't score quite as well, giving us only a profit of $+77 in 6 months.") + p("Crypto, man... either it breaks you " + b("or it makes you") + "."), "left" , true), /*textPost("2022/5/31", "May 2022: I doubled my investment in 2.2 days", p(targetBlank("https://agi.topicbox.com/groups/agi/Tddc937591514587e", "Details here."))),*/ imagePost("2022/1/12", "Gazelle 22", "#1103059", "50%", p(ahref("https://gaz.ai", "New flagship product") + " in the making. This is a product of a category that didn't exist before.\r\n Team reassembled. Looking for investors right now.")), textPost("2022/1/12", "Vaccines mandates averted?", p("Threat gone. I believe.\r\n Spiritual realities manifest before physical realities, so\r\n the information may take a while to arrive in your reality.")), imagePost("2021/11/21", "Everything will change", "#1103049", "30%", p(ahref("https://www.bitchute.com/video/GHiQTVZqE6Pt/", "There are only 2 groups now."))), imagePost("2021/9/10", "Image recognition news", "#1103002", "30%", mapToLines(__27 -> p(__27), targetBlank("https://agi.topicbox.com/groups/agi/T8ca0db34fc106b16/image-recognizers-should-return-mathematical-proofs", "Image recognizers should return mathematical proofs"), targetBlank("https://agi.topicbox.com/groups/agi/T2771ec3238f217fa/gazelle-looks-at-its-own-logo-and-paints-it-red", "Gazelle looks at its own logo and paints it red") ) ), textPost("2021/8/10", "Getting back into image recognition", p("The pieces are there. We plan to recognize computer screens (e.g. very fast text recognition) as well as photos. And why not drawings too? The approach is called Ultra-Fast Recognition.") + p("Also, a new investment from " + targetBlank("https://adaptroninc.com", "Adaptron Inc") + ". Thanks so much!") + p("Also, getting back into " + targetBlank("https://www.youtube.com/watch?v=bi2BIInFjR4", "streaming") + ".") + p("Also, crowdfunding in preparation. " + targetBlank("https://gazelle.rocks/checkout", "Reserve your AI now already!"))), textPost("2021/6/11", "Work with the Mega Team™ continues", p(targetBlank("https://bea.gazelle.rocks/124479", "mega team") + " International Collab.")), textPost("2021/6/11", "I presented Gazelle at a conference of the smartest people on earth", p(youtubi("LUCnzQyCUhU"))), textPost("2021/5/16", "A cooperation with Adaptron Inc. of Canada!", p("I am porting their demo application " + targetBlank("http://www.adaptroninc.com/BasicPage/smarty-software", "Smarty") + " to Java.") + p("On the way, I am\r\n learning about " + targetBlank("http://www.adaptroninc.com/BookPage/research-architecture-and-design", "binons") + " which are an interesting alternative\r\n to classical artificial neurons. For example, binons only\r\n come to existence when there is a need for them as opposed to\r\n being preallocated by a software engineer. Binons\r\n automatically distinguish between significant and insignificant deltas. And they form hierarchies to reach higher abstraction levels.")), textPost("2021/4/30", "New Live Stream", p("It explains the AGI ideas pretty well.") + p(youtubi("M66H1S90NLU"))), textPost("2021/4/11", "Gazelle AGI Technical Pitch", p(ahref("https://botcompany.de/files/1400466/Gazelle+AGI+Technical+Pitch.pdf", "The Gazelle system implements the most recent advances within the symbolism approach to AI."))), textPost("2021/4/4", "AGI pattern matching", p(targetBlank("https://bea.gazelle.rocks/query?q=a+lot+of+sanitizer+keeps+covid+away&algorithm=Process+new+input", "First steps"))), /*textPost("2021/3/4", "Legal LSD microdoses", p(targetBlank("https://lsd-service.net", "Here."))),*/ textPost("2021/3/4", "Voice chat about AGI with Mani", p(youtubi("eafdxmnsPOo"))), textPost("2021/1/8", "Joining Pays5.com", p(targetBlank("https://pays5.com", "New crowdfunding platform!") + " I'm now CTO there.") + p("Also, more image recognition.") + p(youtubi("3VToiitnzd4"))), textPost("2020/12/10", "Work on Gazelle resumes", p(youtubi("W-NPUlIf2cU"))), textPost("2020/11/25", "Gazelle.rocks launched", p(targetBlank("https://gazelle.rocks", "It works.") + " Now need content.") + youtubi("wC68dU5iTe0")), textPost("2020/10/15", "Gazelle AI probable launch date: Middle/End of November", p("Hopefully. Recruiting for team. " + targetBlank("https://gazelle.rocks", "gazelle.rocks") + ".")), textPost("2020/09/05", "Streaming on Twitch daily now (maybe... or maybe not)", p(targetBlank("https://twitch.tv/stefanreich", "Code them bots"))), textPost("2020/08/16", "Wikify.live—fastest Wikipedia search engine", p(ahref("https://wikify.live/search/yesterday,+all+my", "Try it!"))), textPost("2020/08/07", "Towards like the fastest search engine ever", p(youtubi("7hshUUs_ptw"))), textPost("2020/07/28", "Suffix tree + compression = magic?", p(youtubi("GZ_UDLh8MRc")) + p("We'll find out")), imagePost("2020/07/28", "Indexing Wikipedia", "#1102945", "25%", p("for the fastest search engine ever")), textPost("2020/07/22", "A software that laughs at my jokes", p(youtubi("VLWigKUAJDU")) + p("Humanization in progress!")), textPost("2020/07/21", "The hunt for the sub 1 millisecond search engine", p(youtubi("GgmXoZQ-VUo")) + p("I'm in hot pursuit. A full-text searcher that reacts in a millisecond even with large texts.")), textPost("2020/07/17", "Server problems today [solved]", p("Hoster has a V-server overload... Should be getting fixed today. And we will move to more dedicated hardware soon.") + p("Edit: Looks like it's all solved again.")), textPost("2020/07/15", "New video", p("It's been so long!") + p(youtubi("LI2ow-l8mgI"))), imagePost("2020/07/11", "A booking chat bot that understands free-form date input", "#1102942", "50%", p(targetBlank("https://bookbetternow.com/", "BookBetterNow") + " schedules appointments over Google Calendar, knows your business hours, sends SMS and much more. You too can get one of these cool bots for your home page for a low price!"), "left" , true, "picLink" , "https://bookbetternow.com/", "imageTargetBlank" , true), imagePost("2020/07/06", "Comparing scenarios", "#1102940", "65%", p("Important AI function")), imagePost("2020/07/06", "Chat bot launched", "#1102941", "30%", p(targetBlank("https://contractbox.co", "contractbox.co") + " writes your Word documents for you!"), "left" , true, "picLink" , "https://contractbox.co", "imageTargetBlank" , true), imagePost("2020/07/06", "Syntactic Learning", "#1102939", "30%", p("Still using no neural networks.")), textPost("2020/06/02", "The 3 principles of \"Natural Language Assembly\"", p("A lower-level language that helps bridge the gap between natural language and computers.") + p(youtubi("Ltk275Gn8eA"))), textPost("2020/05/27", "LINECOMP—a compressor that sometimes beats 7-zip", p("OK, not all of the time. But it excels if you want to store many similar text files, e.g. historic versions of a source code.") + p(ahref("https://botcompany.de/files/1400390/linecomp-0.3.jar", "Download.") + " " + targetBlank("https://agi.topicbox.com/groups/agi/Tb2cf064c700f181c/i-made-a-multi-file-compressor-that-beats-7zip-on-real-world-data", "Info & discussion."))), imagePost("2020/05/10", "Tomii Boi: Best Q&A Bot for Discord", "#1102922", "30%", p(ahref("https://tomii.me", "Click here for more info")), "picLink" , "https://tomii.me"), textPost("2020/05/02", "NLP-based shopping list", p(youtubi("fVJcIm7zAGQ"))), imagePost("2020/03/31", "Cruddie, your personal chat bot", "#1102906", "15%", p("This will be a good one. Have the bot store information for you just by talking to it. " + targetBlank("https://cruddie.site", "cruddie.site.") + " Hope to add new functions daily now.") + p(youtubi("gfWTPfGDlTU") + " " + youtubi("dUKYlJ2f9RQ")), "left" , true), textPost("2020/03/18", "Speedrun continues, Pt. X", p(youtubi("XZfubRbbg58") + " " + youtubi("y5viJD0djCU"))), textPost("2020/03/15", "Fluid text files", p("A cool human- and computer-friendly text file format I have wanted for a long time. Now it's here!") + p(youtubi("fYQ603KTMM8"))), textPost("2020/03/06", "Speedrun continues", p("Gathering AI scripts from the database by matching keywords.") + p("Results & an answer to my skeptics at " + ahref("https://www.youtube.com/watch?v=baT5TqNSNqk&t=3520s", "58:40")) + p(youtubi("baT5TqNSNqk"))), textPost("2020/03/02", "Combining image recognition & the logic engine, Pt. 1", p(youtubi("4L1sBLqUbNQ"))), textPost("2020/02/26", "Building an image recognition for Anki Vector, Pt. 1-3", p(youtubi("W-QE_XWmeVs") + " " + youtubi("9FMY3YUTqGM") + " " + youtubi("r6GB52sUl1o"))), imagePost("2020/02/25", "Solving the Winograd Challenge, Pt. 5", "#1102881", "50%", p("Look, a program is forming.") + p(targetBlank("https://agi.topicbox.com/groups/agi/T21bdc2c440c86db7/my-new-anki-vector-and-first-actual-winograd-challenge-solved", "Explanations & heated discussion.")) + p(targetBlank("https://www.youtube.com/watch?v=Pb70CAx-I_o", "Video.")), "imageTargetBlank" , true), textPost("2020/02/23", "Anki Vector! Plus: Solving the Winograd Challenge Pt. 4", p("Fame, here we come...") + p(youtubi("ixEmFESf3L4")) + p("Bob paid for Charlie's college education. He is very [generous/grateful]. Who is [generous/grateful]?")), textPost("2020/02/18", "Solving the Winograd Challenge (Pt. 1 to 3)", p("Understanding everyday scenarios.") + p(youtubi("zbaV5rs94JA") + " " + youtubi("lsXsjA2n7RA") + " " + youtubi("1mrxPK4WaLE"))), textPost("2020/02/10", "AI goes mobile. And speedrun continues", p("Check it ouuut!") + p(youtubi("W4IP3eTTfJ8") + " " + youtubi("f-WHXNWw5bg") )), textPost("2020/02/03", "Training a Voice Activity Detector", p("For always-on devices without Big Tech snooping. More soon.")), textPost("2020/01/19", "Speedrun to AI continues", p(youtubi("uhplXw9VsJ8") + " " + youtubi("alRzPG_JQH8") + " " + youtubi("jvHiAClDOtY") + " " + youtubi("ooSpHbUUUFA") + " " + youtubi("t_txQ4vkDlY") + " " + youtubi("d7XWxMnIUpM")) + p("Results growing by the day")), textPost("2020/01/18", "Auto-jump-cut your videos with this free tool", p(youtubi("eS-QsAh2pT8")) + p("Thanks to Tom for making this video! Download links " + ahref(youtubeURL("eS-QsAh2pT8"), "in the video description") + ".")), textPost("2020/01/18", "Stefan Reich about the future of JITs", p("There is no fundamental reason why JIT [just-in-time compilation] solutions should be slower than precompiled code, if you disregard warm-up time (which may actually happen before the program is shipped). In fact, mathematically, the opposite is true: JITs have the option of optimizing further at runtime which once-compilers like C++ don't have. What we currently have available is another question, but long-term, JITs will basically win the performance race.") + p("(A little sound bite you can quote)")), textPost("2020/01/02", "So what is this mystery logic engine? (and other videos)", p(joinWithSpace(lambdaMap(__28 -> youtubi(__28), splitAtSpace("TuKDBeVSBoo UfezfehUBEQ WKwtl4RWqNo EO2EiqNd91A"))))), textPost("2019/11/26", "Our Services", // Don't change date, it's linked p("We provide custom chat bots at competitive prices with optional advanced features. Custom bots start as low as $50 including hosting. " + targetBlank("https://www.fiverr.com/stefan_reich/create-a-chat-bot-for-your-website-or-chat-platform", "Order now.")) + ul(map(__29 -> dropMinusPrefix(__29), tlft("\r\n-Bot is added to your web site by including one line of HTML\r\n-Bot can greet every customer or pop up on click\r\n-Bots will answer questions from a list you provide\r\n-Bots understand typos and synonyms\r\n-Works on desktop and mobile browsers\r\n-Conversation with user is stored in cookie (not lost when browser is closed)\r\n-Bot can also be deployed on any messenger platform (Slack, Discord, Telegram and Viber available, any other platform on request)\r\n-Bots can serve input forms (e.g. contact form)\r\n-You get a web interface where you can see all the bot's conversations\r\n-After the bot is launched, you can edit its questions and answers in the same interface\r\n-Bots can support multiple languages at once (English/German, other languages on request)\r\n-Bots can send a mail, SMS, Viber message etc. to you on any event (e.g. after user completes a form)\r\n-Bots are usually completed in 7 days or less\r\n-Web site bots are compatible with GoDaddy site builder\r\n-We host your bot for free for one year, after that for a small fee (5€/year)\r\n-Bots can support additional functions like playing music in Discord voice chat\r\n-Bots can be deployed as Windows programs\r\n-You have the option to host the bot yourself if you have your own server infrastructure (VPS/dedicated/cloud)\r\n"))) + p("Example public bots:") + ul( ahref("https://top.gg/bot/625377645982384128", "MKLab FM") + " - plays a 24/7 EDM radio stream in Discord voice chat", ahref("https://top.gg/bot/602481480266153984", "GBot") + " - performs Google searches in Discord", ahref("https://top.gg/bot/631845126095896579", "The Owl") + " - Discord greet & farewell bot" ) + p("Order by " + ahref("mailto:info@botcompany.de", "mail") + " or through " + ahref("https://www.fiverr.com/stefan_reich/create-a-chat-bot-for-your-website-or-chat-platform", "Fiverr" + "."))), textPost("2019/11/25", "Chat bot released", p(targetBlank("https://mmozumder.com/", "Managing customer inquiries") + " :)")), textPost("2019/11/15", "Fiverr bots now ready within 7 days", p(targetBlank("https://www.fiverr.com/stefan_reich/create-a-chat-bot-for-your-website-or-chat-platform", "Updated the gig") + " as there is a ready-made bot kit.")), imagePost("2019/10/28", "Girlfriend Bot", "#1102795", "25%", p("182 rules and 104 synonyms. Always there for you.") + p("And yes, before you ask, we can do \"boyfriend bots\" too :-D") + p("(Not the same as a real one, but what's wrong with some fun and games?)"), "left" , true), imagePost("2019/10/24", "Let's mix English and Python", "#1102774", "25%", pre("\r\ntheory validity {\r\n // a human weighs between 80 and 400 pounds\r\n $x is a human\r\n & $x weighs ($y pounds)\r\n => $y >= 80 & $y <= 400\r\n \r\n contradiction => say (That can't be right)\r\n}") + p("Yes, this works already. " + ahref("https://agi.topicbox.com/groups/agi/Tda20a46822c5bb8d", "Full program and some responses.")) + p("So yes, the speedrun definitely continues—just without videos right now.") + p("Creating a very nice \"girlfriend\" bot with a friend too.")), textPost("2019/10/09", "Speedrun to AI", p("I code until it's done.") + p(youtubi("CLk_volfMR8") + " " + youtubi("MWINSJtoPFQ"))), textPost("2019/10/05", "Philosophy Bot I", p(targetBlank("http://code.botcompany.de/1025576", "Bot") + " receives facts:") + pre("\r\nRAM has a size\r\nI have RAM\r\n") + p("And asks:") + pre("What is the size of my RAM?") + p("To achieve this, we invent and implement a whole new language which mixes English and Python. Complete program: 299 lines.") + p(ahref(youtubeURL("JUaDwmnBTHQ"), "2:45:07 mega-stream.")) + p(youtubi("JUaDwmnBTHQ"))), imagePost("2019/10/03", "A popular comment about JavaX", "#1102746", "25%", p("It is a good idea after all.")), imagePost("2019/09/28", "Music bot delivered!", "#1102724", "15%", p(targetBlank(botCompany_mkLabBotLink(), "Our new bot") + " plays " + targetBlank("https://tinyurl.com/mklabradio", "MKLab FM") + ", a very nice (and free) electronic dance music radio, in " + targetBlank(botCompany_mkLabBotLink(), "your Discord server.")), "left" , true), textPost("2019/09/20", "I'll accept another investment", p("1000 € are a good number and will help this project a lot :)") + p("It can either be a gift, an investment or a bot order, depending on your wishes...") + p("Let's just talk about it.")), textPost("2019/09/28", "A bot in 40 lines—including a DSL translator", p("I introduce a new concept to JavaX—coding on the meta-level. Just write " + targetBlank("http://code.botcompany.de/1025375", tt("meta {}")) + " and put your code-making code inside the brackets.") + p("OK the concept is not completely new, but it does work exceptionally well in JavaX.") + p("In fact, we are creating and using a custom language " + targetBlank("http://code.botcompany.de/1025375", "directly within this example") + ". Oh, and there is now a shortened version with only " + targetBlank("http://code.botcompany.de/1025387", "33 lines") + ".") + p(youtubi("PFyDi1HjU2Y"))), textPost("2019/09/25", "More live coding", p("Spends the time, pays the bills.") + p(youtubi("OluvmrZnA0A"))), textPost("2019/09/21", "A bot that controls YouTube", p(youtubi("ABoAXh8ZaEk"))), textPost("2019/09/20", "selfType", p("Another functioning JavaX keyword invented in a few minutes.") + preWithIdentifierExplanations("\r\nclass Me {\r\n selfType hello() { print(\"hello!\"); this; }\r\n}\r\n\r\nnew Me().hello().hello();\r\n", "selfType", "selfType is replaced with the enclosing class's name") + p("selfType just refers to the enclosing class. Avoid repetition. It really shines in combination with includes.")), textPost("2019/09/19", "A bot that learns synonyms", p(youtubi("0gmwaqmjKhM"))), textPost("2019/09/17", "A new concept of a program", p("Let's say a program is something that describes itself,\r\n tests itself and improves itself.")), /*textPost("2019/09/17", "7 levels (or is it 8?)", p_b("The whole stack of AI.") + pre(htmlJavaIdentifierTooltips([[ ENGLISH -> NL parser -> NL associated to templates -> function maker -> JavaX source -> JavaX transpiler -> Java source -> eclipsec -> Java byte code -> HotSpot -> assembler source -> HotSpot's assembler -> machine code -> a suitable CPU -> actual bit operations ]], "NL", "natural language", "JavaX", "a higher-level extension of Java")) + p("All of these translators exist already—except the top two.")),*/ imagePost("2019/09/16", "Ridiculously Fast Image Recognition", "#1102664", "50%", p("I have a special reconnaissance operation that can be performed in less than 2 nanoseconds (sic, see benchmark to the right) on any image stored in a special smart format. Combining a few of these operations allows us to find things in that image very quickly.") + p("So in total, I expect a time of maybe, say, a millisecond?—for recognizing a typical image's major features. We still need to invent some smart algorithms for this to happen, but this is the goal.") + p("And what that cornerstone operation is? Welll... stay tuned is all I can say.")), textPost("2019/09/13", "Whenever my language bores me", p("...I extend it. (Have I said that before? Deja vu!)") + p("Let's say I am annoyed by the inability to nest a function inside a function in Java. So I invent the \"embedded\" keyword.") + pre(htmlJavaIdentifierTooltips("\r\nsS bla() {\r\n S x = \"hello\";\r\n embedded S calc() { ret x + \" \" + x; }\r\n ret calc() + \" \" + calc();\r\n}\r\n", "sS", "short for: static String", "S", "short for: String", "ret", "short for: return", "embedded", "\"embedded\" allows you to put a function where they would not normally be allowed" )) + p("In this useless but instructive example, I embed the function " + tt("calc") + " in the function " + tt("bla") + " with access to the local variable " + tt("x") + ".") + p("How is it translated? Using a function of " + targetBlank("http://code.botcompany.de/1025200", "a mere 21 lines") + " and an anonymous inner class. (Nota bene: It's currently more or less limited to a single embedded function per \"mother\".)") + p(targetBlank("http://code.botcompany.de/1025201", "Example with translation to Java."))), imagePost("2019/09/10", "A programming language that makes DOOM levels", "#1102659", "50%", p("This is such a wonder. A compiler written in Java compiling a slightly weird, but interesting Logo-inspired special purpose language into actual DOOM levels. Our AI could produce DOOM levels for us from just a simple description.") + p("Oh, ah... " + targetBlank("https://jmtd.net/wadc/", b("link")) + ".")), textPost("2019/09/01", "This program is a Discord fan", p(youtubi("CvcafQ6YTlQ"))), imagePost("2019/08/31", "Beta Software!", "#1102549", "50%", p("But a " + targetBlank("http://recognizer.botcompany.de", "good one") + ".")), textPost("2019/09/01", "Constructs that Java needed", p("Question-dot.") + pre("c ?. setDoubleBuffered(b);") + p(b("=>")) + pre("if (c != null) c.setDoubleBuffered(c);")), textPost("2019/09/01", "Zero Training Time Neural Networks", p("New invention.")), imagePost("2019/09/01", "Paging The Reflex", "#1102552", "50%", p(" ")), imagePost("2019/08/31", "Unix just doesn't understand me...", "#1102550", "50%", p("Huh."), "left" , true), imagePost("2019/08/26", "Chess Board Recognition", "#1102266", "35%", p("Coming up.")), textPost("2019/08/18", "You can help train desktop image segmentation", p(youtubi("W6eJSCGEkSE"))), textPost("2019/08/15", "Giraffe v3—now stores information", p(youtubi("gbQNejT1xdk"))), textPost("2019/08/12", "Building a simple translator in agi.blue", p("The demo is word-based, but we have a function for efficient phrase-based translation too.") + youtubi("w2gJ63tvTW8")), textPost("2019/08/12", "An array with O(log n) time for all operations", p("I invented a new data structure (I think). It's an array (variable-size list) where each add, remove, update and random access completes in O(log n) time.") + p("I call it a " + targetBlank("http://code.botcompany.de/1024413", "Log-N array") + ". The implementation uses an order statistic red-black tree. This could be nice for handling long token lists during JavaX transpilation.")), imagePost("2019/08/11", "Today I wrote a whole bot", "#1101842", "25%", p("...live on stream. Sadly, frame rate dropped to 6 frames a minute at some point. Hopefully fixed next time. " + targetBlank("https://www.twitch.tv/videos/465661725", "Video here.") + " " + targetBlank("http://code.botcompany.de/1024415", "Code made."))), textPost("2019/08/10", "Live Coding For Nerds", p("Stefan Reich builds agi.blue, the Google-killing AI database & chat bot making platform. New functions built: Inter-slice links, Delete page, Checkboxes.") + youtubi("7ZRvktYYHuk")), textPost("2019/08/09", "I did my first live-coding stream", p("...and now it is " + targetBlank("https://www.twitch.tv/stefanreich", "lost") + " because I didn't click \"Save broadcast\". Was fun though, thx to Lemon for participating.") + p("And of course, code got made. Specifically, agi.blue slices now have " + targetBlank("https://agi.blue/?slice=jbmjskptrptihmzk", "owners") + ".")), textPost("2019/08/04", "\"Be Thankful\"", p("Randall Brown & band (including me).") + youtubi("debRuSo8CZk")), textPost("2019/08/04", "Why AGI.blue beats Google", p("Because White-Box.") + youtubi("bwUE_XJMbok")), imagePost("2019/08/01", "Let's make programs", "#1101823", "40%", p("...that understand everything.")), textPost("2019/07/28", "Revamping agi.blue", p(targetBlank("https://agi.blue", "agi.blue") + " now has a query language that looks like this:") + pre("\r\nword types / is plural of / $x\r\n$y / is a / $x\r\nreturn $y\r\n") + p("This example " + targetBlank("https://agi.blue/bot/query?query=word+types+%2F+is+plural+of+%2F+%24x%0A%24y+%2F+is+a+%2F+%24x%0Areturn+%24y", "queries the database") + " for a random " + targetBlank(agiBlue_linkForPhrase("word type"), "word type") + ".")), /*textPost("2019/07/26", "Devastating HTTPS bug in JDK 11+12; fix might be coming", p("This really needs to be fixed. Can't upgrade my web server. "+ ahref(tb_mainServer_pretty() + "/ssl-bugreport.tgz", "Demonstration for download.")) + p("Update: This seems to be fixed in JDK 13 which is nearing general release. Very nice!")),*/ imagePost("2019/07/25", "GBot googles in your Discord", "#1101771", "20%", p("Hey ho, we got " + targetBlank("https://discordbots.org/bot/602481480266153984", "our bot") + " approved. You can " + targetBlank("https://discordapp.com/api/oauth2/authorize?client_id=602481480266153984&scope=bot&permissions=0", "invite it") + " to your Discord group if you have one.")), textPost("2019/07/14", "Coarse Procedures & Power Words", p(targetBlank("http://code.botcompany.de/1023890", "Coarse Procedures.") + " " + targetBlank("http://code.botcompany.de/1023964", "Power Words.")) + p("Concepts we need.")), textPost("2019/07/08", "AI Does Simple Reading Comprehension", p("Consider this text:") + pre("\r\nFirst, I wake up. Then, I get dressed.\r\nI walk to school. I do not ride a bike.\r\n" + targetBlank("https://lingua.com/english/reading/my-day/", "[...]") + "\r\n\r\nQuestion 1: What happens first?\r\n\r\n 1 Get dressed 2 Wake up\r\n 3 Eat lunch 4 Walk to school\r\n \r\n[+4 more questions]\r\n") + p(targetBlank("http://code.botcompany.de/1023742", "Program that solves this.") + " (One screen of code as always.)") + p("The engine is pretty generic. It works by correlating words in the text, the question and the answer. The only additional information we put in is a list of \"important words\"—this time in the form of " + i(targetBlank("https://www.vogella.com/tutorials/JavaRegularExpressions/article.html", "regular expressions")) + ":") + pre_htmlEncode("\"(?cmodule BigInput {\r\n S text; // auto-persisted string field\r\n switchable int fontSize = 40;\r\n visual setFontSize(fontSize, dm_textArea('text));\r\n}" + p("(I just created the 2 new JavaX syntax constructs " + ahref("http://code.botcompany.de/1022743", "'switchable'") + " and " + ahref("http://code.botcompany.de/1022746", "'visual'") + " in like 10 minutes. Hover over the source code for more info.) —" + ahref("http://botcompany.de/1004590/raw/1101628", "Automatic popup menu.")) ), textPost("2019/03/31", "New stuff to test", p("If " + ahref("https://botcompany.de/files/1400204/dialog-kit-dummy.jar", "this") + " runs, you're read-d-dy for making a bot. (Actual software coming up.)")), /*textPost("2019/03/27", "New domain", p("dialogkit.xyz [in preparation] - in two minutes to your bot. And it's free")),*/ textPost("2019/03/27", "From dialog to chat bot 101", p("(In a few steps, that is.)") + pre("\r\nWhat time is it?\r\nIt's 5:30\r\nWhy did you say that?\r\nBecause you asked me what time it is.\r\n")), imagePost("2019/03/26", "Bots now available 'standalone'", "#1101625", "50%", p("One huge jar file. Includes a GUI and a database. And learns from the cloud while running.")), imagePost("2019/03/24", "Gazelle", "#1101622", "30%", p("...will explain itself (as a general principle)."), "left" , true), textPost("2019/03/17", "First professional bot being built", p("Not sure if I'm allowed to tell you more yet... :-)")), textPost("2019/03/22", "My OS is really happy with 8 GB of RAM", p("...and any Windows installation. Enough space for AI experiments—and enough space for memory-hungry Firefox. " + ahref(osInstallerLink(), "Try it out") + " yourself!")), imagePost("2019/03/11", "Accommodating human stuttering", "#1101580", "35%", p("Yes, it's all automatic. The original rule is just matching for " + ahref("http://gazelle.botcompany.de/rule/caehawgpuyqsdiig", "\"what's the rule count\"") + ".")), textPost("2019/03/07", "Coder muscle flexing :)", p("Sometimes I just have to do this—coming up with a really intelligent little solution for common coding questions that, oddly, don't seem to have an answer yet.") + p("Like this one: " + ahref("https://codereview.stackexchange.com/questions/106761/find-if-the-prefix-of-the-string-exists-in-the-values-of-the-hash-table/214969#214969", "How to find out efficiently whether a prefix of a string is contained in a tree set") + ".") + p("PS: Haha, now StackOverflow is saying they want to delete the answer. I was improving on another answer which apparently is not being deleted? StackOverflow is complete madness as I have said before.")), textPost("2019/03/07", "Mini-investment needed", p("Sorry... I can't always turn water to wine. Need some grapes. " + ahref("https://www.meetup.com/Artificial-Intelligence-Meetup/messages/boards/thread/52050719", "Details."))), textPost("2019/03/06", "I just made Gazelle scalable", p("10,000 rules shouldn't be a problem at all. We do want " + ahref("https://en.wikipedia.org/wiki/Artificial_general_intelligence", "AGI") + ", don't we?")), imagePost("2019/03/03", "Gazelle is offended", "#1101557", "15%", p("No further comment."), "left" , true), imagePost("2019/03/02", "Gazelle's Auto-Math Module", "#1101549", "30%", p("Given these example dialogs:") + pre_rtrim("\r\n 10 games of 2 minutes each => that makes 20 minutes\r\n 30 games of 3 minutes each => that makes 90 minutes\r\n ") + p("Gazelle understands what kind of calculation you mean and performs it for you on new input.")), imagePost("2019/02/24", "Gazelle Learns", "#1101499", "50%", p("Come join us over at " + targetBlank(nextGenBotsDiscordInvite(), "Discord") + "."), "left" , true), textPost("2019/02/22", "New Discord Group", p(targetBlank("https://discord.gg/SEAjPqk", "See you there!"))), imagePost("2019/02/16", "Analyzing Wikipedia", "#1101493", "50%", p("Nothing can stop this.") + p("In other news, my current cash level (for the rest of the month) is roundabout 10 €. Money is such a great invention!")), imagePost("2019/02/15", "Gazelle growing", "#1101483", "50%", p(b("Here soon.")), "left" , true), imagePost("2019/02/11", "A new logic engine", "#1101482", "40%", p("A logic engine is what makes machines talk.") + p("This new one I'm making is really impressive.") + p("The new engine merges syntax and semantics; allows humans to teach the machine how to think easily; and it doesn't require a full model of the language in question (say, English).") + p("Surely it needs a cool code name, right? How about... uhm... \"Gazelle\"? \"Panther\"? Goldfish? Rubber duck? Something!") + p("Either way: Expect demos soon. Until then, enjoy the chewing gazelle.")), textPost("2019/02/08", "Who smokes dope?", p("Input:") + pre("I visited the pope. He smokes dope.") + p("Output:") + pre("I visited {the pope} [*1]. He [1] smokes dope.") + p("([*1], [1] and the curly braces mean that \"he\" points to \"the pope\".)") + p(ahref("http://code.botcompany.de//1021323", "Function that does this."))), textPost("2019/02/06", "Ways to eat pizza", p(targetBlank("http://mattmahoney.net/", "Matt Mahoney") + " recently gave this little example of ways in which language is ambiguous:") + pre("\r\nI ate pizza with a fork.\r\nI ate pizza with pepperoni.\r\nI ate pizza with Bob.\r\n") + p("I was inspired to make a program to interpret these different meanings of the word \"with\". I used the 3 lines as training examples, then made some new examples for testing.") + p("My program is a logic engine that takes the following rules:") + pre("\r\n// Some reasonings that everybody will understand.\r\n// Sorry for the curly braces, we have to help out the parser a tiny bit.\r\n// First, the 3 different cases of what \"pizza with...\" can mean.\r\n\r\n I ate pizza with pepperoni.\r\n => {I ate pizza} and {the pizza had pepperoni on it}.\r\n \r\n I ate pizza with Bob.\r\n => {I ate pizza} and {Bob was with me}.\r\n \r\n I ate pizza with a fork.\r\n => I used a fork to eat pizza.\r\n \r\n// Now some more easy rules.\r\n \r\n I used a fork to eat pizza.\r\n => I used a fork.\r\n \r\n I used a fork.\r\n => A fork is a tool.\r\n \r\n The pizza had pepperoni on it.\r\n => Pepperoni is edible.\r\n \r\n Bob was with me.\r\n => Bob is a person.\r\n\r\n// Some VERY basic mathematical logic\r\n\r\n $A and $B.\r\n => $A.\r\n \r\n $A and $B.\r\n => $B.\r\n\r\n// Tell the machine what is not plausible\r\n\r\n Mom is edible. => fail\r\n Mom is a tool. => fail\r\n anchovis are a tool. => fail\r\n anchovis are a person. => fail\r\n ducks are a tool. => fail\r\n ducks are a person. => fail\r\n my hands are edible. => fail\r\n my hands are a person. => fail\r\n") + p("The logic engine performs some analogy reasoning using the rules stated above. Note that most of the rules don't distinguish between variable and non-variable parts, this is usually inferred automatically.") + p("That's it! Now we give the program the following new inputs:") + pre("\r\n I ate pizza with mom.\r\n I ate pizza with anchovis.\r\n I ate pizza with ducks.\r\n I ate pizza with my hands.\r\n") + p("...and it comes up with these clarifications:") + pre("\r\nI ate pizza with anchovis. => I ate pizza and the pizza had anchovis on it.\r\nI ate pizza with ducks. => I ate pizza and the pizza had ducks on it.\r\nI ate pizza with mom. => I ate pizza and mom was with me.\r\nI ate pizza with my hands. => I used my hands to eat pizza.\r\n") + p("\r\nSo nice! It's all correct. Sure, nobody would say \"the pizza had ducks on it\", but that is the most reasonable interpretation of the rather bizarre input sentence after the program eliminated the other two options (ducks as a tool or ducks as a person).") + p("If you remove the line that says ducks are not persons, the program will correctly add the interpretation \"I ate pizza and ducks were with me.\"") + p(targetBlank("http://code.botcompany.de/1021251", "Full program in my fancy language.")) + p("In addition to the results, the program also shows some lines of reasoning, e.g. failed lines:") + pre("\r\nInterpretation: I ate pizza and the pizza had mom on it.\r\n => I ate pizza.\r\n => the pizza had mom on it.\r\n => mom is edible.\r\n => fail\r\n") + p("and successful lines:") + pre("\r\nInterpretation: I used my hands to eat pizza.\r\n => I used my hands.\r\n => my hands are a tool.\r\n") + p("Why did I make a specific program for this puzzle? Well, it's not a special-purpose program really. It's a general-purpose logic engine that supports problems of a certain complexity. Like a child understands everything as long as it's not too complicated. The plan is to make increasingly more capable logic engines until we can solve everything.") + p("The program itself is " + targetBlank("http://code.botcompany.de/1021251", "<100 lines") + " (not counting rules and input), but of course it uses some powerful library functions.")), imagePost("2019/09/04", "New Module Preview", "#1101481", "50%", p("Comin' up.")), textPost("2019/02/03", "English to Rule", p("Input (plain English, not executable):") + pre("If something is heavy, it weighs many grams") + p("This should be converted to this rule which is executable:") + pre("fact($something is heavy) => fact($something weighs many grams)") + p("Actual program that does the conversion:") + pre(ahref("http://code.botcompany.de/1021228", "ai_ifToFactRule_2") + "(\r\n \"If something is heavy, it weighs many grams\",\r\n litciset(\"it\"), // pronouns\r\n litciset(\"something\") // nouns\r\n)\r\n") + p("As you see, the only customization the function requires is a list of pronouns and nouns.") + p("Finally, we can test the new rule.") + pre("\r\nai_applyFactToFactRules(\r\n \"fact($something is heavy) => fact($something weighs many grams)\",\r\n \"John is heavy\")\r\n") + p("which yields:") + pre("[John weighs many grams]") ), textPost("2019/02/03", "Switching back to Chrome", p("YouTube is unusable on Firefox. It's " + ahref("https://www.tubefilter.com/2018/07/25/youtube-slow-firefox-chris-peterson/", "probably deliberate") + ". That's what you get from a monopoly...")), textPost("2019/01/23", "Machine Asks Questions", p("Artificial philosopher in the making.") + p(youtubi("3OD8l25EJ90"))), textPost("2019/01/20", "Collaboration with AIRIS?", p("Here's an " + targetBlank("https://github.com/berickcook/AIRIS_Public", "interesting project") + " for reinforcement learning which, just possibly, may be a good addition to my software infrastructure.") + p("There is a language gap to bridge (Python/JavaX), but that's what we went to university for, didn't we?")), textPost("2019/01/12", "The Best Play List", p("Just thought I'd share this. " + targetBlank("https://www.youtube.com/watch?v=TcVv-hfsMy8&index=1&list=PLI8CaFciVcxjC2o0RQsnKc4Nf4l31e8Xd", "A literal remix heaven") + " by The Reflex.")), textPost("2019/01/09", "JavaX vs Smalltalk [the programming language]", p("You see, I do know a bit of history. I was part of the Smalltalk\r\n movement 'cause yeah, that thing has a tremendous charme. Miles ahead of everything.") + p("In fact, it just dawned on me, JavaX offers a lot of the fabulous Smalltalk experience—an integrated virtual machine where\r\n source, runnable code, GUIs and orthogonally persistent data intersect each other.") + p("So where did Smalltalk " + a("fail", "title" , "IMO, Smalltalk relied too much on a monolithic \"system image\" to hold both code and data, making code versioning and distribution very hard.") + "? Mouse over for more info. And no, JavaX does not suffer from the same problem.")), textPost("2019/01/06", "Tabs++ (or: avoiding the complexity problem)", p(youtubi("FoAJLMbctoQ"))), textPost("2019/01/04", "Why a Java OS? The \"Kilroy\" Demo", p("Because a next generation OS just has more smartness.") + p(youtubi("2AdbbSf3y-M"))), textPost("2019/01/02", "Frantic action", p("I want to finish the big project now: the talking operating system.")), textPost("2019/01/01", "I should be a CEO", p("I'm the right man for the job. I understand technology, people—and I understand the madness that money represents. Also I don't have to do " + ahref("https://www.thisisinsider.com/elon-musk-reportedly-terrified-tesla-staff-with-his-firing-sprees-2018-12?utm_source=quora&utm_medium=referral", "this") + ".")), /*textPost("2018/12/31", "Cryptography is scary", p("...but I got it working fine—see this website's nice new HTTPS certificate (check the lock icon in your browser) which will be good for another full year.")),*/ imagePost("2018/12/30", "The \"Third Wave of AI\"", "#1101469", "", p("In the generally quite rotten IT industry, there is now talk of a \"third wave of AI\". And, interestingly,\r\n this time they float pretty much the ideas I have been pushing for the last 5 years.") + p("Although of course it's fair to say I still have a lot of tricks in petto they didn't even conceive yet.") + p("So is now the time for change?")), /*textPost("2018/12/30", "I have 4 servers now", p([[...registered with 4 different companies, no less. (Diversify!) All nice little Linux v-servers. Interestingly, the hosting companies are all German—for unknown reasons, American v-servers are crazy expensive.]]) + p([[In fact, for less than 10 bucks, I can rent a decently fast server for one month. By running a single shell script, I get it up and running, including a VNC-based GUI and my fabulous Java OS. Tell me again why I would need the Amazon cloud?]])),*/ textPost("2018/12/22", "Humanity is still cursed", p("You realize that right? That humanity is nowhere near as free, enlightened and happy as it could be?") + p("The main reason is that they still believe in \"competition\" instead of collaboration... so almost nobody gets anything done.") + p("Happy Christmas! (?)")) , textPost("2018/12/19", "More information about JavaX", p(ahref("http://javax.botcompany.de/", "Finally... :)"))) , textPost("2018/12/14", "Downloads Fixed", p("So sorry—there was a bug in the download files causing installation to fail for new users. Now fixed!")) , textPost("2018/12/13", "Teaching Colors, Hands-Free", p(youtubi("JhBhqdpuFf8"))) , imagePost("2018/12/10", "\"Alexa Mode\" Works", "#1101451", "60%", p("\"Alexa Mode\" means the computer always listens. Standard feature of my OS."), "left" , true) , imagePost("2018/12/10", "New Language", "#1101450", "60%", p("It's a lower-level natural language. Can you read it?")) , imagePost("2018/12/09", "Circle Finder", "#1101449", "30%", p("God I love image recognition. ") + p(targetBlank("http://code.botcompany.de/1020191", "Source.") + " Ships as part of my operating system."), "left" , true) , imagePost("2018/12/06", "Nice little reload buttons", "#1101445", "23%", p("Whenever there is new code, one click suffices to get it.") + p("In other news, I am looking for a part-time Java job (maybe). Anyway... something's gotta happen.")) , textPost("2018/12/04", "Onboarding Demo", p(youtubi("l09WeK6uHSE"))) , textPost("2018/12/04", "Ordering computers from the universe", p("Can it work?")) , textPost("2018/12/02", "Computer insults me", p("New frontier in computer science. " + targetBlank("http://code.botcompany.de/1019961", 35, linkStyle) + " code lines.") + p(youtubi("XTN0Z60_k00"))) , imagePost("2018/12/02", "My own VNC clone", "#1101444", "30%", p(targetBlank("http://code.botcompany.de/1019894", "Comes for free", "style" , "color: inherit; text-decoration: underline") + " with my OS. Both sides can be behind firewalls. " + targetBlank("http://code.botcompany.de/1019873", "GIF recorder", "style" , "color: inherit; text-decoration: underline") + " also included.")) , imagePost("2018/11/28", "Defeating Java Class Loaders", "#1101439", "40%", p("Java is great, but its need for class loaders means it's somewhat hard to add code at runtime.") + p(targetBlank("http://javax.botcompany.de", "JavaX", "style" , "color: inherit") + " comes to the solution! I have implemented an arsenal of tricks that turn Java into something just about as flexible as JavaScript—while retaining the full power and speed of the Java VM.") + p("In fact, in JavaX, we write and ship only source code; all compilation is done on the fly.") + p("We can pretty much do the \"holy trinity\": maximum speed, complete freedom of assembly and compact code size—all at once.") + p("Also, JavaX has \"zero-effort deployment\": Every new line of code you write anywhere is available everywhere immediately. (If you want that.)") + p("As proof for JavaX's elegance, here's the " + targetBlank("http://code.botcompany.de/1016081", "27 lines source code") + " of the module on the right.")) , textPost("2018/11/27", "Why are my dreams better than reality?", p("I have the greatest dreams... then I wake up to a rather lame reality. How is that even possible?")) , imagePost("2018/11/25", "Much News!", "#1101430", "50%", p(ahref(osInstallerLink(), "OS") + " becomes a Cluster OS.") + p("(Meaning, you can treat 3 PCs as one.)")) , imagePost("2018/11/17", "OS Chat Bot v1", "#1101424", "35%", p("Come on! Talk to me!"), "left" , true) /*, textPost("2018/11/25", "Microsoft Meditation", p(youtubi("nWbD1bFqvOE")) + p("6 minutes."))*/ , textPost("2018/11/11", "Eyebrow Detection", p(youtubi("-XafiqgFM9k")) + p("I promised—and I delivered :)") + p("(This is an example of how even the smallest facial expressions can be used for making a better user interface.)")) , textPost("2018/11/10", "Some Live Programming", p(youtubi("U2Kl4FY-jcE")) + p("Bad audio, good content.")) , textPost("2018/11/10", "AI Testers Wanted!", p("All you need is a Windows, Linux or Apple PC and some enthusiasm. We make voice assistants that will ease your life and provide a lot of entertainment.") + p("To participate, either " + targetBlank("http://download.tinybrain.de", "download") + ", " + targetBlank("mailto:info@botcompany.de", "mail") + " or " + targetBlank("https://github.com/stefan-reich/StefansOS/issues", "create issues") + ".")) , imagePost("2018/11/06", "Checking Log Files", "#1101418", "50%", p("This task may seem trivial to you, but actually it is a key to computer intelligence.")) , textPost("2018/11/04", "To Andrzej", p(youtubi("https://www.youtube.com/watch?v=9P1fF0liFtU"))) , textPost("2018/10/30", "Next meetup on Nov 15", p(targetBlank("https://www.meetup.com/Artificial-Intelligence-Meetup/events/255936823/", "Hamburg.") + " Hoping to prepare a fully intelligent machine until then :D")) , textPost("2018/10/28", "Making a Voice Activity Detection", p("Another one day project. OK, maybe two... I'm squeezing some other AI things in.")) , textPost("2018/10/28", "I'm disappointed with YouTube views", p("1 view on the latest video? Really?")) , textPost("2018/10/27", "Making a face recognition", p("Now things get real.") + p(youtubi("FXJVO2fWztk", 450))) , imagePost("2018/10/25", "Sensory Status: +3", "#1101412", "30%", p(b("Internet, Vision, Sound.") + " (A robot's basic needs.)"), "left" , true) /* , textPost("2018/10/23", "Creator Awards once again awards the wrong creators", p("What can you say... Americans."))*/ , imagePost("2018/10/21", "Faking The Linux Task Bar", "#1101408", "50%", p("Anything's possible.")) , imagePost("2018/10/15", "JavaX makes the impossible possible", "#1101403", "30%", p("Here: Automatically measuring the RAM consumption of individual modules within one Java VM."), "left" , true) , textPost("2018/10/14", "Speech recognition works", p(youtubi("yFEiIWW-heE", 450, 450*9/16)) + p("Who says you need Google for everything?")) , imagePost("2018/10/10", "Making my own speech recognition", "#1101401", "15%", p("It may be possible.")) , textPost("2018/10/04", "We are making a bot net", p("...of the good kind. In fact, you are part of it right now.") + p("(It works through JavaScript in the browser. We're not using it yet though, you're just on idle.)")) , textPost("2018/10/03", "Let's sign stuff!", p("I propose to use asymmetric cryptographic keys for testifying that a certain thing actually happened.") +p("In JavaX, making a public+private key pair is just a single function call:") +hsourcecode("pki_newKeyPair()") +p("...which means we can have as many key pairs as we like.") +p("For example, you can use one specific key (or multiple) to sign your personal quotes. The signed data will speak for itself if one knows that the key is yours.") +hsourcecode("\r\n On October 3rd 2018, I truly said: Oh screw this!\r\n\r\nEdgar the 3rd himself\r\n\r\nsig: MC0CFQCWUB9j0c+8e8wagTNmMXs/cq7tuAIUEoXOBbRvw343wOdunTY47rKrUDE=\r\nsigner: publickey:MIIBtzCCASwGByqGSM44BAEwggEfAoGBAP1/U4E [...] F9Kg=\r\n")) + aname("creatorawards", textPost("2018/09/29", "Applying for Creator Awards", p(youtubi("ZTiqIEbhB8A", 300)) + p("Thanks to Andrzej for video production!"))) , textPost("2019/09/25", "Dogs Are Telepathic", p(targetBlank("https://www.sheldrake.org/files/pdfs/papers/JSE_Vol14.pdf", "Proof.") + " Maybe bots can be too?")) , imagePost("2019/09/20", "Programming In Facts", "#1101379", "55%", p("German, this time.")) , imagePost("2019/09/04", "Bot Simulator", "#1101378", "75%", p(b("Version 1.")), "left" , true) , imagePost("2018/08/28", "Voice-to-voice bot", "#1101376", "50%", p("We now have voice recognition & speech output combined into the " + targetBlank("http://t.me/Hello_Computer", "Telegram bot") + ". Actual sci-fi!") + p("(PS: The bot said \"Good evening dudes\".)") + p("PPS: The Rubik's cube will have to wait a little...\r\n building foundations first.")) , imagePost("2018/08/18", "Teaching the Rubik's cube to the bot", "#1101372", "30%", p("It's a good idea and just about right complexity-wise."), "left" , true) , imagePost("2018/08/18", "Nice trend", "#1101371", "", p("Changing history " + targetBlank("https://www.meetup.com/Artificial-Intelligence-Meetup/", "on Tuesday") + ".")) , imagePost("2018/08/17", "The Study Of Rules", "#1101367", "50%", p("It's the duality—executing & thinking—that makes this project work.")) , imagePost("2018/08/14", "Bot Tests Human", "#1101366", "30%", p("It's only fair that they test us first.") + p("(Yeah it's a joke post.) Next up: The other way around!"), "left" , true) , textPost("2018/08/13", "The Levels Of AI", p(b("Level 1: Literal.") + " Just make some responses. How are you? => I'm good/I have some problems") + p(b("Level 2: Battle it out.") + " Take the rules of level 1 and have them compete against each other. (There are also meta-rules.)") + p(b("Level 3: Fact management.") + " Some things are true, others aren't. Manage this.") + p("That's pretty much it. Now we just need a lot of rules to work with. Oh, and there's a very good parser for German & English.") + p(targetBlank("https://www.meetup.com/Artificial-Intelligence-Meetup/events/253736347/", "Meeting."))) , imagePost("2018/08/10", "How much", "#1101365", "40%", p("...is an AGI? 'cause we deliver.")) , imagePost("2018/08/09", "Learning from longer exchanges", "#1101364", "50%", p("Getting somewhere.") + p("If you could talk to an AI about any topic—which one would you choose?")) , imagePost("2018/08/07", "Politics", "#1101363", "50%", p("Bot knows (sadly)."), "left" , true) , imagePost("2018/08/05", "Bot decides", "#1101362", "45%", p("Who knows what it will do next?")) , textPost("2018/08/04", "Let's improve the onboarding", p(targetBlank("http://t.me/Hello_Computer", "Channel") + "'s waiting dudes.")) , imagePost("2018/08/02", "How the AI is programmed", "#1101361", "30%", p("v1 - Make a basic logic using a bastard language located somewhere\r\n between Prolog and plain English (mostly it's just the latter).") + pre_trim("\r\ninput(I'm a scammer!)\r\n && fact(a scammer scams people)\r\n && relationX(scams people, scam people)\r\n => output(You scam people?!)\r\n") + p("v2 - Add some $ signs and turn spaces into underscores\r\n (making the pattern dynamic).") + pre_trim("\r\n\r\ninput(I'm a $scammer!)\r\n && fact(a $scammer $scams_people)\r\n && relationX($scams_people, $scam_people)\r\n => output(You $scam_people?!)\r\n") + p("v3 - Find out what relationX is (that's not that hard).") + p_b("v4 - Interpret this stuff.") + pre("DONE") + p("Estimated time frame: " + b("2 days")) + p("Edit (2018/08/03): And it's done (see picture).")) , textPost("2018/08/02", "I'm beating them", p("IBM and all the other guys.") + p("My fabulous " + targetBlank("http://code.botcompany.de/1017686", "English Parser") + " just got better, you can now help it out by using some brackets, like this:") +pre("{This time of night} it's usually quite cool.")) , textPost("2018/07/31", "I still contribute to StackOverflow", p("...even though " + targetBlank("https://stackoverflow.com/a/51618656/947488", "that place") + " is the living hell for any sane person. I'm not even allowed to ask questions anymore because they hate dissidents.")) , imagePost("2018/07/31", "Bot Initiative", "#1101360", "45%", p("Shurely an important part.")) , imagePost("2018/07/28", "Bot needs more logic!", "#1101359", "45%", p("We're getting there though."), "left" , true) /*, textPost("2018/07/27", "What is AI?", p("AI is " + i("puzzling stuff out") + ".") + p("(You know which meaning of \"puzzling\" is intended here, right? If yes: Then you're a " + i("good puzzler") + ".)") + p("So that's what we build: a " + i("puzzling engine") + "."))*/ , imagePost("2018/07/27", "Telegram shaping up", "#1101358", "45%", p(targetBlank("http://t.me/Hello_Computer", "Participate!"))) , textPost("2018/07/27", "I should collect money for a new notebook", p("\"What, you're doing AI with 4 gigabytes?\"") + p("Yes, that's right. And 512 MB actually go to the GPU, so yeah... it's tight.")) , textPost("2018/07/26", "The Simplifier", p("Another working AI component. Takes any sentence or phrase, like:") + pre("smart combinations of various fast methods") + p("and outputs:") + pre(trim("\r\n1. combinations\r\n2. combinations of methods\r\n3. smart combinations\r\n4. combinations of fast methods\r\n5. smart combinations of methods\r\n6. combinations of various methods\r\n7. smart combinations of fast methods\r\n8. combinations of various fast methods\r\n9. smart combinations of various methods\r\n10. smart combinations of various fast methods\r\n")) + p("Neat, right? And very useful.")) , textPost("2018/07/22", "Setting Up Telegram", p("There'll be " + targetBlank("http://t.me/Hello_Computer", "a channel") + " and a bot.")) , textPost("2018/07/22", "The implications of this project", p("I'm not sure if you have thought this through yet. This is a project that makes computers think.")) , imagePost("2018/07/20", "A few more steps", "#1101357", "45%", p("...and you'll have the dialog engine you're all waiting for.")) /*, textPost("2018/07/22", "The StackOverflow War", p("StackOverflow is completely intolerable if you try to actually work on it. The trolls are in charge there.") + p("There is a " + targetBlank("https://meta.stackexchange.com/questions/187661/mirrors-of-stack-overflow", "legal way") + " to mirror the site, so: Let's do it! I'm downloading the first archive as we speak. Huge stuff though, gigabytes over gigabytes..."))*/ , textPost("2018/07/18", "English+German Parsers Work", p("Input:") + pre("\"Confessions of a Burglar Video\"") + p("(It's the name of a video on YouTube.) So... is the video confessing—or the burglar? Let's ask the parser.") + pre(rtrim("\r\n1. Confessions {of {a {Burglar Video}}}\r\n2. {Confessions {of {a Burglar}}} Video\r\n ")) + p("Yup, it has found the 2 grammatical possibilities. Next up: Semantic analysis to rate these against each other.")) , textPost("2018/07/18", "500 installations coming up", p("We're reaching a nice number of JavaX-enabled computers. And no, they're not all mine.")) , imagePost("2018/07/12", "Perfect Parser Coming Up", "#1101356", "45%", p("English—no problem.")) , imagePost("2018/07/12", "The Magic OS", "#1101353", "45%", p("In my OS, every computer can control any other one—if the \"victim\" deliberately chooses this (it's a separate module you have to load explicitly, so don't worry).") + p("The communication process behind this is protected using automatic cryptographic signatures.")) , imagePost("2018/07/10", "Teaching Puns To The AI...", "#1101352", "45%", p("52 days to world domination.")) , textPost("2018/07/10", "News from Zuckerberg", p(youtubi("_zCDvOsdL9Q", 400))) , textPost("2018/07/07", "56 days", p("until Stefan's OS takes the world.")) /*, imagePost("2018/07/05", "News From Israel", #1101349, "30%", p(targetBlank("https://www.aljazeera.com/indepth/inpictures/israeli-forces-assault-palestinians-prepare-demolish-village-180704141245982.html", "Great country.")), picLink := "https://www.aljazeera.com/indepth/inpictures/israeli-forces-assault-palestinians-prepare-demolish-village-180704141245982.html")*/ , imagePost("2018/07/02", "Dead Lock-Immune Operating System", "#1101348", "30%", p(targetBlank("http://code.botcompany.de/1016805", "Code.")), "left" , true) /*, textPost("2018/07/02", "Dear Kirill from the Android team,", hParagraphsFromEmptyLines([[I have to get these things off my chest. 1. I used to work at Google. I quit in 2009 because they wanted to waste me. 2. I make an operating system in Java that is ALL THAT ANDROID SHOULD HAVE BEEN. 3. I tried to install WhatsApp on a friend's Android phone yesterday and IT SIMPLY DID NOT WORK. 3b. I got kicked off the Play Store because I dynamically load code from un-servers (non-Google-servers). So it's a fight? Guess who'll win. 4. In my Java OS, ALL MODULES RUN IN ONE VM AND IT'S NOT A PROBLEM. 4b. No, the Java process does not get "wonky" over time as misinformed programmers baselessly claim. They just have more deadlocks than I do (my deadlocks are fixed by the OS). 5. I have an idea for a better Swing PLAF interface. Just two components: a painter and a "clicker" (event handler). Easy & really transparent. 6. My OS has orthogonal persistence which is... slightly easier than your persistence approach. Cheers. Stefan]]))*/ /*, textPost("2018/06/30", "Something must be wrong with reality", p("The movies we watch have a better plot than the life we actually live. How is that possible?"))*/ , textPost("2018/06/30", "We're doing it again", invtag("div", "style" , "float: right; margin-left: 20px; margin-bottom: 20px", youtubi("lAkuJXGldrM", 300)) + p("Stefan's OS has a greater impact than Windows 95. You just wait and see!")) , textPost("2018/06/27", "Computer checks its own voice", p(youtubi("ZRkGdIvW5lM", 600))) , imagePost("2018/06/23", "Stefan's OS v5", "#1101335", "30%", p("See who else is online, world wide (if you load the module).") + p("Also notice the \"AI bar\" at the top which is a novel invention.")) , textPost("2018/06/23", "We are solving the software security crisis", p("The solution is "+ b("source code inspection") + ", and " + ahref("http://javax.botcompany.de", b("JavaX")) + " makes it practical.")) , textPost("2018/06/23", "We will now do the Super-Automation", p("The operating system is the optimal place to automate everything—it sees everything and it can act upon information. Also loading and even making dynamic code on the fly is trivial in my OS.")) , textPost("2018/06/25", "If your language isn't perfect—how about changing it?", p("Let's say " + b("vanilla Java is too verbose") + ". (Everybody knows this.) Instead of this:") + pre("class ShowBackgroundImage extends DynModule {") + p("I want to type (and see) only this:") + pre("class ShowBackgroundImage > DynModule {") + p(b("In JavaX") + ", that takes " + b("exactly one line") + " in the " + targetBlank("http://code.botcompany.de/759", b("translator")) + ":") + pre(htmlencode("jreplace(tok, \"class > {\", \"class $2 extends $4 {\");")) + p("And this easily, my language has been extended.") + p(b(targetBlank("http://code.botcompany.de/1016607", "Proof that this works.")))) , textPost("2018/06/20", "Collaboration!", p(targetBlank("http://www.ort-des-talents.de/", "BrainCircle."))) , textPost("2018/06/20", "Stefan's OS v4", p(ahref("https://stefans-os.botcompany.de", "Numerous small improvements") + ". Finds memory leaks automatically (!). Ability to make \"alternative brains\" (multiple distinct instances of OS on a machine). Still compatible with Windows, Linux and Mac.")) , imagePost("2018/06/19", "Reading my mails", "#1101332", "30%", p("Not pretty (where are the graphic designers?), but it works.") + p(ahref("http://code.botcompany.de/1016066", "Source code") + " (39 lines)") , "left" , true) , imagePost("2018/06/18", "First operating system that learns", "#1101331", "30%", p(b("What is the world?")), "left" , false) , imagePost("2018/06/18", "Advantages of a Java-based OS: Free Profiling", "#1101328", "30%", p("You get so many inspection capabilities for free in my OS.") + p("For example, you can always find out what the CPU is doing, down to every single line of code. And this incurs no performance overhead when not used."), "left" , true) , textPost("2018/06/17", "Memory leak eliminated", p("Gotcha.") + p("I told you Java is stable!")) , imagePost("2018/06/16", "Further chasing the memory", "#1101327", "30%", p("It has to be going somewhere. " + ahref("http://mail.openjdk.java.net/pipermail/discuss/2018-June/thread.html", "jdk-discuss") + " informed (list is moderated, read: another time waster)."), "left" , true) , imagePost("2018/06/16", "New Look&Feel", "#1016391", "30%", p("Pretty, isn't it. Look&Feel is called " + ahref("http://jtattoo.net", "JTattoo") + ".") + p("Image was made with the automatic screenshot module on a very old Windows 7 machine where my OS runs flawlessly."), "left" , true) , textPost("2018/06/15", "Fixing the last memory leaks in Java 10", "\r\n

I submitted this bug report to Oracle, and I'm making\r\n super-fancy functions like cleanDefunctACCsInAllThreads that automatically fix\r\n memory leaks other Java programmers have never heard of.

\r\n

We will sail memory leak-free! :)

\r\n ") + "\r\n\r\n \r\n
\r\n
\r\n \r\n\r\n

New Module: YouTube Downloader

\r\n\r\n

\r\n By Stefan Reich @ 2018/06/14\r\n

\r\n
\r\n \r\n
\r\n
\r\n \r\n \r\n \r\n
\r\n \r\n

\r\n Today we launched bla bla bla.\r\n

\r\n

 

\r\n

(No, seriously—we actually did. There is an awesome YouTube downloader in my operating system. I'm just too lazy to write.)

\r\n

Now I need an awesome screenshot module and an awesome auto-upload-to-blog module.

\r\n
\r\n
\r\n "); // end of posts if (nempty(date)) allPosts = dropFirst(allPosts, indexOfFirstThat(allPosts, post -> cmp(regexpFirstMatch("20\\d\\d/\\d\\d?/\\d\\d?", post), date) <= 0)); List posts = subList(allPosts, (page-1)*perPage, page*perPage); boolean hasPrev = page > 1, hasNext = l(allPosts) > page*perPage; String nav = !hasNext && !hasPrev ? "" : hsection(joinNempties(" | ", hasPrev ? ahref(rawSelfLink(str(page-1)), "Last page") : "", ahref("http://javax.botcompany.de/1020398/raw/contact", "Imprint"), hasNext ? ahref(rawSelfLink(str(page+1)), "Next page") : ""), "class" , "post", "style" , "text-align: right"); // template starts here String html = "\r\n\r\n\r\n\r\n \r\n \r\n BotCompany.de\r\n \r\n \r\n \r\n \r\n \r\n" // BROKEN (deploys.io out of service): + html_nextGenBots_discordWidget() + "\r\n\r\n\r\n\r\n" + "" + "\r\n\r\n
\r\n
\r\n
\r\n

" + himgsnippet("#1102944", "width" , "300", "title" , "BotCompany [logo by sadietwiqs]", "alt" , "BotCompany [logo by sadietwiqs]") //[[Bot]] + html_invisibleSpace() + [[Company]] + "

\r\n

English & German Chat Bots

\r\n\r\n \r\n \r\n

 

\r\n

Stefan's OS
is an inspiring Java program you can try out in Windows, Mac OS or Linux.

\r\n \r\n
\r\n
\r\n\r\n
\r\n
\r\n
\r\n \r\n " + hcss(autoUnindent("\r\n pre { margin-left: 20px; }\r\n tt, pre { font-weight: bold; }\r\n ")) + nav + lines(posts) + nav + "\r\n \r\n
\r\n\r\n
\r\n
\r\n \r\n
\r\n
\r\n
\r\n
\r\n
\r\n\r\n\r\n\r\n"; if (nempty(date)) { String title = contentsOfFirstContainerTagWithParams(first(allPosts), "h2", "class" , "post-title"); if (nempty(title)) html = hreplaceTitle(html, title); else print("Warning: No blog entry title found for date " + date); } return html.replace("\"css/layouts/blog.css\"", htmlQuote(rawSnippetURL("#1016322", "text/css"))) .replaceFirst(regexpQuote(""), "" + hSilentComputatorWithFlag("homepage")) // add stuff before closing body tag .replaceFirst(regexpCaseInsensitivePrefix() + "", /*loadJQuery() + hjavascript_src("https://botcompany.de/1026215/raw") + ""*/ // scribble doesn't use the right background color yet, and it's not clickable /*hjs_includeScribble() + */ ""); } // end of html() static String textPost(String date, String title, String text) { return invtag("section", "class" , "post", "style" , "clear: both", invtag("header", "class" , "post-header", invtag("img", "width" , 48, "height" , 48, "title" , "Stefan Reich", "class" , "post-avatar", "src" , snippetImgLink("#1101324")) + "\r\n

" + title + "

\r\n\r\n

\r\n By Stefan Reich @ " + ahref(hquery("date", date), date) + "\r\n

\r\n") + "\r\n
\r\n " + text + "\r\n
"); } static String imagePost(String date, String title, String imageID, String width, String text, Object... __) { boolean left = boolPar("left", __); boolean imageTargetBlank = boolPar("imageTargetBlank", __); String picLink = (String) (optPar("picLink", __)); return textPost(date, title, invtag("div", "style" , "float: " + (left ? "left" : "right") + "; width: " + width + "; margin-bottom: 30px; margin-" + (left ? "right" : "left") + ": 30px;", ahref(or2(picLink, snippetImageLink(imageID)), invTag("img", "title" , "", "class" , "pure-img-responsive", "src" , snippetImageLink(imageID), "style" , "width: 100%"), "target" , imageTargetBlank ? "target" : null)) + text); } static String youtubi(String url) { return isTrue(youtubeOff.get()) ? "" : youtubeEmbed_newer(url); } static String youtubi(String url, int width) { return isTrue(youtubeOff.get()) ? "" : youtubeEmbed_newer(url, width); } static String youtubi(String url, int width, int height) { return isTrue(youtubeOff.get()) ? "" : youtubeEmbed_newer(url, width, height); } static Object domainAndURISwitch(String uri, Map params) { String domain = domain(); print("BLOG BOT domain: " + domain + ", uri: " + uri); String _uri = uri; uri = addSlashPrefix(uri); if (pkiValidation && startsWith(uri, "/.well-known/")) return subBot_serveText(loadTextFile(userDir("validation.txt"))); if (eqic(domain, "code.botcompany.de")) { long snippetID = parseLong(dropSlashPrefix(uri)); return hrefresh(snippetID == 0 ? tb_mainServer_pretty() + "/tb/snippets.php" : tb_mainServer_pretty() + "/tb/show-snippet.php?id=" + snippetID); } if (swic(domain, "javax.")) { try { Object result = callHtmlMethod2(getBot("#1020398"), uri, params); print("Result: " + className(result)); return result; } catch (Throwable __e) { pcallFail(__e); } } if (eqic(domain, "create.botcompany.de")) return hrefresh(tb_mainServer_pretty() + "/tb/snippets.php?action=create"); if (eqic(domain, "recognizer.botcompany.de")) return subBot_serveRedirect("https://botcompany.de/files/1400260/chess-board-recognizer-0.2.jar"); if (eqic(domain, "discord-fan.botcompany.de")) return subBot_serveRedirect("https://botcompany.de/files/1400274/Discord-Fan.jar"); if (domainIsUnder(domain, "stefans-os.botcompany.de") || domainIsUnder(domain, "stefans-os.site")) return serveStefansOSSite(uri, params); if (domainIsUnder(domain, "zttnn.me")) return serveZTTNN(); if (domainIsUnder(domain, "tomii.me")) return serveTomiiMe(uri); if (domainIsUnder(domain, "phrasecache.best")) return hhtml(hhead_title("PhraseCache - Best NLP System") + hbody(hsansserif() + hfullcenter( p(himagesnippet("#1102923", "title" , "PhraseCache")) + p("by " + ahref("https://botcompany.de", "BotCompany")) + h3("PhraseCache is a simple language for matching natural language inputs.") + p(joinWithBR( ahref("http://code.botcompany.de/1028073", "Latest matching function"), ahref("http://code.botcompany.de/1028083", "Latest scored matching function"), ahref(tb_mainServer_pretty() + "/getraw.php?id=1030319", "Current docs"), ahref("https://tomii.me/nlp patterns.html", "Docs for older version") + " (latest version is backwards-compatible)") )))); if (eqicOneOf(domain, "jumpcut.botcompany.de", "ajc.botcompany.de")) return subBot_serveRedirect("https://botcompany.de/files/1400263/AutoJumpCut-Installer-0.6-win32.exe"); if (isAGIBlueDomain(domain)) { if (eq(uri, "/")) return htitle("AGI.blue is now Gazelle.rocks") + hrefresh(5.0, "https://gazelle.rocks") + hmobilefix() + hsansserif() + hNoBlueLinks() + hfullcenter("You will be redirected to our latest AGI project: " + b(ahref("https://gazelle.rocks", "GAZELLE")) + repString(3, "
") + small(ahref("https://agi.blue/old", "See the old agi.blue system"))); if (eq(uri, "/old")) uri = "/"; return eleu_serveSubBot("#1023558", uri, params); } if (ewic(domain, "abots.space")) return eleu_serveSubBot("#1026318", uri, params); if (swic(domain, "mech.")) return hrefresh("https://botcompany.de/1013927/raw"); // add more domains here // URI switches Matches m = new Matches(); uri = addSlash(uri); if (swic(uri, "/mmozumder/", m)) return callHtmlMethod2(getBot("#1026011"), "/" + m.rest(), params); if (swic(uri, "/smart-iptv-solutions/", m)) return callHtmlMethod2(getBot("#1026223"), "/" + m.rest(), params); if (swic(uri, "/tomii-boi/admin/", m)) return callHtmlMethod2(getBot("#1026409"), "/" + m.rest(), params); if (swic(uri, "/hypercubes/admin/", m)) return callHtmlMethod2(getBot("#1026544"), "/" + m.rest(), params); if (swic(uri, "/smart-home/admin/", m)) return callHtmlMethod2(getBot("#1026867"), "/" + m.rest(), params); if (swic(uri, "/contractbox/admin/", m)) return callHtmlMethod2(getBot("#1028281"), "/" + m.rest(), params); if (swic(uri, "/ada/admin/", m)) return callHtmlMethod2(getBot("#1028301"), "/" + m.rest(), params); if (swic(uri, "/exodontia/admin/", m)) return callHtmlMethod2(getBot("#1028921"), "/" + m.rest(), params); if (swic(uri, "/cspillai/admin/", m)) return hrefresh("https://cspillai.botcompany.de"); if (swic(uri, "/fiverr/")) return hrefresh("https://www.fiverr.com/stefan_reich/create-a-chat -bot-for-your-website-or-chat-platform"); if (swic(uri, "/bookbetternow/admin/", m)) return callHtmlMethod2(getBot("#1028421"), "/" + m.rest(), params); if (swic(uri, "/infinici/admin/", m)) return callHtmlMethod2(getBot("#1029306"), "/" + m.rest(), params); if (swic(uri, "/newdesign/", m)) return new HttpFromFileSystem(javaxDataDir("newdesign")).serve(m.rest()); if (swic(_uri, "/ace-builds/")) try { return subBot_maxCacheHeaders(serveWithMimeType(loadPage(tb_mainServer_pretty() + _uri), "text/javascript")); } catch (Throwable e) { printStackTrace(e); return serve404(); } if (eqic(_uri, "/x30.jar")) return subBot_serveFile(pathToJavaxJar()); // add more URI switches here return null; } static Object serveStefansOSSite(String uri, Map params) { { var __5= redirectToHTTPS(uri, params); if (__5 != null) return __5; } return hhtml(hhead_title("Stefan's OS Download") + hbody(hfullcenter( h1("Stefan's OS") + p(b(ahref(osInstallerLink(), "WINDOWS INSTALLER", "style" , "font-size: 1.25em")) + "
" + " (120 MB) which includes everything you need (including Java).") + p("Mac or Linux users and other weirdos: " + ahref("https://botcompany.de/files/1400497/Stefans-OS.zip", "Download JAR, 3.3 MB")) + p("(For the jar file you may need to install " + targetBlank("https://adoptopenjdk.net/", "OpenJDK 8") + " or later - JDK 16 is perfect)") + p("by " + targetBlank("https://BotCompany.de", "BotCompany")) + p("Stefan's OS is open source software. Sources here: " + ahref("https://code.botcompany.de/1024932", "[OS]") + " " + ahref("https://code.botcompany.de/1001639", "[JavaX]")) ))); } static String serveZTTNN() { return hhtml(hhead_title("Zero Training Time Neural Networks") + hbody(hfullcenter( h1("Zero Training Time Neural Networks") + p(himageSnippet("#1102921")) + p("A classifier trained with a few simple labels")))); } static Object serveTomiiMe(String uri) { String tomiiVersion = "#1400377"; File dir = programFile("tomii.me"); File versionFile = newFile(dir, "version.txt"); if (!eq(loadTextFile(versionFile), tomiiVersion)) { saveTextFile(versionFile, tomiiVersion); print("Updating Tomii to " + tomiiVersion); unzipSnippet(tomiiVersion, dir); } if (eq(uri, "/")) uri = "/index.html"; return new HttpFromFileSystem(dir).serve(uri); } static String osInstallerLink() { return "https://botcompany.de/files/1400496/Install-Stefans-OS-2021-Jun-20.exe"; } static Object call(Object o) { return callF(o); } // varargs assignment fixer for a single string array argument static Object call(Object o, String method, String[] arg) { return call(o, method, new Object[] {arg}); } static Object call(Object o, String method, Object... args) { //ret call_cached(o, method, args); return call_withVarargs(o, method, args); } static Object mainBot; static Object getMainBot() { return mainBot; } static Object subBot_serve404() { return call(getMainBot(), "serve404"); } static Object subBot_serve404(String msg) { return call(getMainBot(), "serve404", msg); } static String addSlashPrefix(String s) { return addPrefix("/", s); } static String domain() { return domainName(); } static String domain(String url) { return hostNameFromURL(url); } static Object serveDelayed404() { sleepSeconds(2); return subBot_serve404(); } static Object serveDelayed404(String msg) { sleepSeconds(2); return subBot_serve404(msg); } static String registerVisitor() { Object visitorsBot = getBot("#1002157"); String visitorStats = visitorsBot == null ? null : str(callHtmlMethod(visitorsBot, "/")); return visitorStats; } static boolean eq(Object a, Object b) { return a == b || a != null && b != null && a.equals(b); } // a little kludge for stuff like eq(symbol, "$X") static boolean eq(Symbol a, String b) { return eq(str(a), b); } static boolean domainIsUnder(String domain, String mainDomain) { return eqic(domain, mainDomain) || ewic(domain, "." + mainDomain); } static volatile StringBuffer local_log = new StringBuffer(); // not redirected static boolean printAlsoToSystemOut = true; static volatile Appendable print_log = local_log; // might be redirected, e.g. to main bot // in bytes - will cut to half that static volatile int print_log_max = 1024*1024; static volatile int local_log_max = 100*1024; static boolean print_silent = false; // total mute if set static Object print_byThread_lock = new Object(); static volatile ThreadLocal print_byThread; // special handling by thread - prefers F1 static volatile Object print_allThreads; static volatile Object print_preprocess; static void print() { print(""); } static A print(String s, A o) { print(combinePrintParameters(s, o)); return o; } // slightly overblown signature to return original object... static A print(A o) { ping_okInCleanUp(); if (print_silent) return o; String s = o + "\n"; print_noNewLine(s); return o; } static void print_noNewLine(String s) { try { Object f = getThreadLocal(print_byThread_dontCreate()); if (f == null) f = print_allThreads; if (f != null) // We do need the general callF machinery here as print_byThread is sometimes shared between modules if (isFalse( f instanceof F1 ? ((F1) f).get(s) : callF(f, s))) return; } catch (Throwable e) { System.out.println(getStackTrace(e)); } print_raw(s); } static void print_raw(String s) { if (print_preprocess != null) s = (String) callF(print_preprocess, s); s = fixNewLines(s); Appendable loc = local_log; Appendable buf = print_log; int loc_max = print_log_max; if (buf != loc && buf != null) { print_append(buf, s, print_log_max); loc_max = local_log_max; } if (loc != null) print_append(loc, s, loc_max); if (printAlsoToSystemOut) System.out.print(s); vmBus_send("printed", mc(), s); } static void print_autoRotate() { } static RuntimeException rethrow(Throwable t) { if (t instanceof Error) _handleError((Error) t); throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static RuntimeException rethrow(String msg, Throwable t) { throw new RuntimeException(msg, t); } static boolean subBot_isHttps_defaultToTrue() { Object httpd = subBot_httpd(); return !(eqOneOf(httpd, getOpt(mainBot(), "serveHttp_server"), getOpt(mainBot(), "serveHttpWithWebsockets_server")) || contains((Collection) getOpt(mainBot(), "serveHttpWithWebsockets_multiplePorts_servers"), httpd)); } static Object subBot_serveRedirect(String url) { return call(getMainBot(), "serveRedirect", url); } static Object subBot_serveRedirect(String url, String contentType) { return call(getMainBot(), "serveRedirect", url, contentType); } static String htmlQuery(Map params) { return empty(params) ? "" : "?" + makePostData(params); } static String htmlQuery(Object... data) { return empty(data) ? "" : "?" + makePostData(data); } 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); }}; } static boolean eqOneOf(Object o, Object... l) { if (l != null) for (Object x : l) if (eq(o, x)) return true; return false; } static Object[] litobjectarray(Object... l) { return litObjectArray(l); } static String dropPrefix(String prefix, String s) { return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s; } static boolean startsWithDigit(String s) { return nempty(s) && isDigit(s.charAt(0)); } static int parseFirstInt(String s) { return parseInt(jextract("", s)); } static int parseFirstInt(Iterable l) { return parseInt(firstIntegerString(l)); } static List ll(A... a) { ArrayList l = new ArrayList(a.length); if (a != null) for (A x : a) l.add(x); return l; } static String p(Object contents, Object... params) { return hfulltag("p", contents, params) + "\n"; } static String p() { return p(""); } static String b(Object contents, Object... params) { return fulltag("b", contents, params); } static String ahref(String link, Object contents, Object... params) { return link == null ? str(contents) : href(link, contents, params); } static List mapToLines(Map map) { List l = new ArrayList(); for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key))); return l; } static String mapToLines(Map map, Object f) { return lines(map(map, f)); } static String mapToLines(Object f, Map map) { return lines(map(map, f)); } static String mapToLines(Object f, Iterable l) { return lines(map(f, l)); } static String mapToLines(Iterable l, IF1 f) { return mapToLines((Object) f, l); } static String mapToLines(IF1 f, Iterable l) { return mapToLines((Object) f, l); } static String mapToLines(Map map, IF2 f) { return lines(map(map, f)); } static String mapToLines(IF1 f, A data1, A... moreData) { return lines(map(f, data1, moreData)); } static String targetBlank(String link, Object contents, Object... params) { return hrefBlank(link, contents, params); } static String youtubeURL(String s) { return formatYouTubeURL_long(s); } static String joinWithSpace(Iterable c) { return join(" ", c); } static String joinWithSpace(Object... c) { return join(" ", c); } static List lambdaMap(IF1 f, Iterable l) { return map(l, f); } static List lambdaMap(IF1 f, A[] l) { return map(l, f); } static List splitAtSpace(String s) { return empty(s) ? emptyList() : asList(s.split("\\s+")); } static String ul(String... list) { return ul(asList(list)); } static String ul(Collection list, Object... params) { StringBuilder buf = new StringBuilder(); int i = indexOf(params, null); // null separates params for ul from params for li if (i == -1) i = l(params); for (Object s : withoutNulls(list)) buf.append(tag("li", s, subArray(params, i+1))).append("\n"); return containerTag("ul", buf, subArray(params, 0, i)) + "\n"; } static List map(Iterable l, Object f) { return map(f, l); } static List map(Object f, Iterable l) { List x = emptyList(l); if (l != null) for (Object o : l) { ping(); x.add(callF(f, o)); } return x; } // map: func(key, value) -> list element static List map(Map map, Object f) { List x = new ArrayList(); if (map != null) for (Object _e : map.entrySet()) { ping(); Map.Entry e = (Map.Entry) _e; x.add(callF(f, e.getKey(), e.getValue())); } return x; } static List map(Object f, Object[] l) { return map(f, asList(l)); } static List map(Object[] l, Object f) { return map(f, l); } static List map(Object f, Map map) { return map(map, f); } static List map(Iterable l, F1 f) { return map(f, l); } static List map(F1 f, Iterable l) { List x = emptyList(l); if (l != null) for (A o : l) { ping(); x.add(callF(f, o)); } return x; } static List map(IF1 f, Iterable l) { return map(l, f); } static List map(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) { var it = l.iterator(); if (it.hasNext()) { var pingSource = pingSource(); do { ping(pingSource); x.add(f.get(it.next())); } while (it.hasNext()); } } return x; } static List map(IF1 f, A[] l) { return map(l, f); } static List map(A[] l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : l) { ping(); x.add(f.get(o)); } return x; } static List map(Map map, IF2 f) { List x = new ArrayList(); if (map != null) for (Map.Entry e : map.entrySet()) { ping(); x.add(f.get(e.getKey(), e.getValue())); } return x; } // new magic alias for mapLL - does it conflict? static List map(IF1 f, A data1, A... moreData) { List x = emptyList(l(moreData)+1); x.add(f.get(data1)); if (moreData != null) for (A o : moreData) { ping(); x.add(f.get(o)); } return x; } static String dropMinusPrefix(String s) { return dropPrefix("-", s); } static List tlft(String s) { return toLinesFullTrim(s); } static List tlft(File f) { return toLinesFullTrim(f); } static String pre(Object contents, Object... params) { return tag("pre", contents, params); } static String botCompany_mkLabBotLink() { return "https://discord.boats/bot/625377645982384128"; } static void tt() { typeWriterConsole(); } static String tt(Object contents, Object... params) { return tag("tt", contents, params); } static String preWithIdentifierExplanations(String text, Object... replacements) { return pre(htmlJavaIdentifierTooltips(text, replacements)); } static String htmlJavaIdentifierTooltips(String text, Object... replacements) { return replaceCodeTokensUsingMap(text, mapMapToMap((Map) litmap(replacements), (a, b) -> pair(a, dottedSpan(a, b)) )); } static String agiBlue_linkForPhrase(String phrase, Object... additionalParams) { return agiBlueURL() + hquery(arrayPlus /* allow multiple "get" parameters */(additionalParams, "q" , phrase)); } static String i(String s, Object... params) { return tag("i", s, params); } static String pre_htmlEncode(Object contents, Object... params) { return pre_htmlencode(contents, params); } static String pre_rtrim(Object contents, Object... params) { return pre(rtrim(str(contents)), params); } static String nextGenBotsDiscordInvite() { return "https://discord.gg/kcKKZEg"; } static String a(String noun) { if (eq(noun, "")) return "?"; return ("aeiou".indexOf(noun.charAt(0)) >= 0 ? "an " : "a ") + noun; } static String a(String contents, Object... params) { return hfulltag("a", contents, params); } static String hsourcecode(Object o) { return sourceCodeToHTML(o); } static String aname(String anchor) { return aname(anchor, ""); } static String aname(String anchor, Object contents, Object... params) { return tag("a", contents, concatArrays(new Object[] {"name", anchor}, params)); } static String pre_trim(Object contents, Object... params) { return pre(trim(str(contents)), params); } static String p_b(Object contents, Object... params) { return p(b(contents), params); } static String trim(String s) { return s == null ? null : s.trim(); } static String trim(StringBuilder buf) { return buf.toString().trim(); } static String trim(StringBuffer buf) { return buf.toString().trim(); } public static String rtrim(String s) { if (s == null) return null; int i = s.length(); while (i > 0 && " \t\r\n".indexOf(s.charAt(i-1)) >= 0) --i; return i < s.length() ? s.substring(0, i) : s; } static String invtag(String tag, Object... paramsAndContents) { if (even(l(paramsAndContents))) return htag(tag, "", paramsAndContents); Object contents = last(paramsAndContents); return tag(tag, contents, dropLastFromObjectArray(paramsAndContents)); } static String htmlencode(Object o) { return htmlencode(str(o)); } 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(); } static String snippetImgLink(String snippetID) { return snippetImageURL(snippetID); } static boolean nempty(Collection c) { return !empty(c); } static boolean nempty(CharSequence s) { return !empty(s); } static boolean nempty(Object[] o) { return !empty(o); } static boolean nempty(byte[] o) { return !empty(o); } static boolean nempty(int[] o) { return !empty(o); } static boolean nempty(BitSet bs) { return !empty(bs); } static boolean nempty(Map m) { return !empty(m); } static boolean nempty(Iterator i) { return i != null && i.hasNext(); } static boolean nempty(IMultiMap mm) { return mm != null && mm.size() != 0; } static boolean nempty(Object o) { return !empty(o); } static boolean nempty(Rect r) { return r != null && r.w != 0 && r.h != 0; } static boolean nempty(IntSize l) { return l != null && l.size() != 0; } static String[] dropFirst(int n, String[] a) { return drop(n, a); } static String[] dropFirst(String[] a) { return drop(1, a); } static Object[] dropFirst(Object[] a) { return drop(1, a); } static List dropFirst(List l) { return dropFirst(1, l); } static List dropFirst(int n, Iterable i) { return dropFirst(n, toList(i)); } static List dropFirst(Iterable i) { return dropFirst(toList(i)); } static List dropFirst(int n, List l) { return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size())); } static List dropFirst(List l, int n) { return dropFirst(n, l); } static String dropFirst(int n, String s) { return substring(s, n); } static String dropFirst(String s, int n) { return substring(s, n); } static String dropFirst(String s) { return substring(s, 1); } static Chain dropFirst(Chain c) { return c == null ? null : c.next; } static int indexOfFirstThat(List l, Object pred) { return indexOfPred(l, pred); } static int indexOfFirstThat(List l, IF1 pred) { return indexOfPred(l, pred); } static int cmp(Number a, Number b) { return a == null ? b == null ? 0 : -1 : cmp(a.doubleValue(), b.doubleValue()); } static int cmp(double a, double b) { return a < b ? -1 : a == b ? 0 : 1; } static int cmp(int a, int b) { return a < b ? -1 : a == b ? 0 : 1; } static int cmp(long a, long b) { return a < b ? -1 : a == b ? 0 : 1; } 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); } static String regexpFirstMatch(String pat, String s) { Matcher m = regexpMatcher(pat, s); return m.find() ? m.group() : null; } static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } static List subList(int startIndex, List l) { return subList(l, startIndex); } static List subList(int startIndex, int endIndex, List l) { return subList(l, startIndex, endIndex); } 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); } static int l(Object[] a) { return a == null ? 0 : a.length; } static int l(boolean[] a) { return a == null ? 0 : a.length; } static int l(byte[] a) { return a == null ? 0 : a.length; } static int l(short[] a) { return a == null ? 0 : a.length; } static int l(long[] a) { return a == null ? 0 : a.length; } static int l(int[] a) { return a == null ? 0 : a.length; } static int l(float[] a) { return a == null ? 0 : a.length; } static int l(double[] a) { return a == null ? 0 : a.length; } static int l(char[] a) { return a == null ? 0 : a.length; } static int l(Collection c) { return c == null ? 0 : c.size(); } static int l(Iterator i) { return iteratorCount_int_close(i); } // consumes the iterator && closes it if possible static int l(Map m) { return m == null ? 0 : m.size(); } static int l(CharSequence s) { return s == null ? 0 : s.length(); } static long l(File f) { return f == null ? 0 : f.length(); } static int l(IMultiMap mm) { return mm == null ? 0 : mm.size(); } static int l(IntSize o) { return o == null ? 0 : o.size(); } static String hsection(Object contents, Object... params) { return htag("section", contents, params); } static String joinNempties(String sep, Object... strings) { return joinStrings(sep, strings); } static String joinNempties(String sep, Iterable strings) { return joinStrings(sep, strings); } static String str(Object o) { return o == null ? "null" : o.toString(); } static String str(char[] c) { return c == null ? "null" : new String(c); } static String str(char[] c, int offset, int count) { return new String(c, offset, count); } static String himgsnippet(String imageID, Object... params) { return hsnippetimg(imageID, params); } static String tag(String tag) { return htag(tag); } static String tag(String tag, Object contents, Object... params) { return htag(tag, str(contents), params); } static String tag(String tag, StringBuilder contents, Object... params) { return htag(tag, contents, params); } static String tag(String tag, StringBuffer contents, Object... params) { return htag(tag, contents, params); } static String li(Object contents, Object... params) { return tag("li", contents, params); } static String hcss(Object contents) { if (contents instanceof String && isRelativeOrAbsoluteURL((String) contents)) return hstylesheetsrc((String) contents); else return htag("style", contents); } static String autoUnindent(String s) { int n = getIndent(s); if (n == 0) return s; List l = toLines(s); for (int i = 0; i < l(l); i++) l.set(i, substring(l.get(i), n)); return fromLines(l); } static String lines(Iterable lines) { return fromLines(lines); } static String lines(Object[] lines) { return fromLines(asList(lines)); } static List lines(String s) { return toLines(s); } // convenience map call static String lines(Iterable l, IF1 f) { return mapToLines(l, f); } // tok must come from htmlTok // returns all container tags found (including content) as CNC // honors nested tags correctly static String contentsOfFirstContainerTagWithParams(List tok, String tag, Object... params) { return joinContentsOfContainerTag(first(findContainerTagWithParams(tok, tag, params))); } static String contentsOfFirstContainerTagWithParams(String html, String tag, Object... params) { return contentsOfFirstContainerTagWithParams(htmlTok(html), tag, params); } static Object first(Object list) { return first((Iterable) list); } static A first(List list) { return empty(list) ? null : list.get(0); } static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } static Pair first(Map map) { return mapEntryToPair(first(entrySet(map))); } static Pair first(MultiMap mm) { if (mm == null) return null; var e = first(mm.data.entrySet()); if (e == null) return null; return pair(e.getKey(), first(e.getValue())); } static A first(IterableIterator i) { return first((Iterator) i); } static A first(Iterator i) { return i == null || !i.hasNext() ? null : i.next(); } static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } static Character first(String s) { return empty(s) ? null : s.charAt(0); } static Character first(CharSequence s) { return empty(s) ? null : s.charAt(0); } static A first(Pair p) { return p == null ? null : p.a; } static Byte first(byte[] l) { return empty(l) ? null : l[0]; } static Double first(double[] l) { return empty(l) ? null : l[0]; } static A first(A[] l, IF1 pred) { return firstThat(l, pred); } static A first(Iterable l, IF1 pred) { return firstThat(l, pred); } static A first(IF1 pred, Iterable l) { return firstThat(pred, l); } static A first(AppendableChain a) { return a == null ? null : a.element; } static String hreplaceTitle(String html, String newTitle) { return hreplacetag(html, "title", htitle(newTitle)); } static String htmlQuote(String s) { return "\"" + htmlencode_forParams(s) + "\""; } static String rawSnippetURL(String snippetID) { return snippetRawURL(snippetID); } static String rawSnippetURL(String snippetID, String contentType) { return snippetRawURL(snippetID, contentType); } static String regexpQuote(String s) { return s.length() == 0 ? "" : Pattern.quote(s); } static String hSilentComputatorWithFlag(String flag) { return hSilentComputator(hSilentComputator_defaultURI(), flag); } static String regexpCaseInsensitivePrefix() { return "(?i)"; } static String hquery(Map params) { return htmlQuery(params); } static String hquery(Object... data) { return htmlQuery(data); } static boolean boolPar(ThreadLocal tl) { return boolOptParam(tl); } // defaults to false static boolean boolPar(Object[] __, String name) { return boolOptParam(__, name); } static boolean boolPar(String name, Object[] __) { return boolOptParam(__, name); } static boolean boolPar(String name, Map __) { return boolOptParam(name, __); } static boolean boolPar(String name, Object[] params, boolean defaultValue) { return optParam(params, name, defaultValue); } static A optPar(ThreadLocal tl, A defaultValue) { A a = tl.get(); if (a != null) { tl.set(null); return a; } return defaultValue; } static A optPar(ThreadLocal tl) { return optPar(tl, null); } static Object optPar(Object[] params, String name) { return optParam(params, name); } static Object optPar(String name, Object[] params) { return optParam(params, name); } static Object optPar(String name, Map params) { return optParam(name, params); } static A optPar(Object[] params, String name, A defaultValue) { return optParam(params, name, defaultValue); } static A optPar(String name, Object[] params, A defaultValue) { return optParam(params, name, defaultValue); } static String or2(String a, String b) { return nempty(a) ? a : b; } static String or2(String a, String b, String c) { return or2(or2(a, b), c); } static String snippetImageLink(String snippetID) { return snippetImageURL(snippetID); } static String invTag(String tag, Object... paramsAndContents) { return invtag(tag, paramsAndContents); } static boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; if (o instanceof ThreadLocal) // TODO: remove this return isTrue(((ThreadLocal) o).get()); throw fail(getClassName(o)); } static boolean isTrue(Boolean b) { return b != null && b.booleanValue(); } static String youtubeEmbed_newer(String youtubeID) { return embedYoutube_newer(youtubeID); } static String youtubeEmbed_newer(String youtubeID, int w) { return embedYoutube_newer(youtubeID, w, null); } static String youtubeEmbed_newer(String youtubeID, int w, int h) { return embedYoutube_newer(youtubeID, w, h, null); } static boolean startsWith(String a, String b) { return a != null && a.startsWith(unnull(b)); } static boolean startsWith(String a, char c) { return nemptyString(a) && a.charAt(0) == c; } static boolean startsWith(String a, String b, Matches m) { if (!startsWith(a, b)) return false; if (m != null) m.m = new String[] {substring(a, strL(b))}; return true; } static boolean startsWith(List a, List b) { if (a == null || listL(b) > listL(a)) return false; for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i))) return false; return true; } static Object subBot_serveText(Object s) { return call(getMainBot(), "serveByteArray", toUtf8(str(s)), "text/plain; charset=utf8"); } static Object subBot_serveText(InputStream in) { return subBot_serveInputStream(in, "text/plain; charset=utf8"); } static Object subBot_serveText(File f) { return subBot_serveFile(f, "text/plain; charset=utf8"); } static String loadTextFile(String fileName) { return loadTextFile(fileName, null); } static String loadTextFile(File f, String defaultContents) { return loadTextFile(f, defaultContents, "UTF-8"); } static String loadTextFile(File f, String defaultContents, String encoding) { try { checkFileNotTooBigToRead(f); if (f == null || !f.exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(f); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, encoding); return loadTextFile(inputStreamReader); } catch (Exception __e) { throw rethrow(__e); } } public static String loadTextFile(File fileName) { return loadTextFile(fileName, null); } static String loadTextFile(String fileName, String defaultContents) { return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents); } 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); } static File userDir() { return new File(userHome()); } static File userDir(String path) { return new File(userHome(), path); } static boolean eqic(String a, String b) { if ((a == null) != (b == null)) return false; if (a == null) return true; return a.equalsIgnoreCase(b); } static boolean eqic(Symbol a, Symbol b) { return eq(a, b); } static boolean eqic(Symbol a, String b) { return eqic(asString(a), b); } 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); } static long parseLong(String s) { if (empty(s)) return 0; return Long.parseLong(dropSuffix("L", s)); } static long parseLong(Object s) { return Long.parseLong((String) s); } static String dropSlashPrefix(String s) { return dropLeadingSlash(s); } static String hrefresh(String target) { return hrefresh(0, target); } static String hrefresh(double seconds) { return hrefresh(seconds, ""); } static String hrefresh(double seconds, String target) { return tag("meta", "", "http-equiv", "refresh", "content", iceil(seconds) + (nempty(target) ? "; url=" + target : "")); } static String tb_mainServer_pretty_cache; static String tb_mainServer_pretty() { if (tb_mainServer_pretty_cache == null) tb_mainServer_pretty_cache = tb_mainServer_pretty_load(); return tb_mainServer_pretty_cache;} static String tb_mainServer_pretty_load() { return "https://code.botcompany.de:9898"; } static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } 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; } // o can be a class, then we search for a static method called "html". static Object callHtmlMethod2(Object o, String uri) { return callHtmlMethod2(o, uri, null); } static Object callHtmlMethod2(Object o, String uri, Map params) { Object s = callOpt(o, "html", uri, params); if (s == null) s = callOpt(o, "html", uri); if (s == null) s = callOpt(o, "html"); return s; } static Object getBot(String botID) { return callOpt(getMainBot(), "getBot", botID); } static String className(Object o) { return getClassName(o); } static void pcallFail(Throwable e) { pcallPolicyForThread().handlePcallFail(e); } static void pcallFail(String msg) { pcallFail(new Throwable(msg)); } static String hhtml(Object contents) { return containerTag("html", contents); } static String hhead_title(String title) { return hhead(htitle(title)); } static String hbody(Object contents, Object... params) { return tag("body", contents, params); } static String hsansserif() { return hcss("body { font-family: Sans-Serif; }"); } static String hfullcenter(Object contents, Object... __) { return tag("table", tr(td(contents, "align" , "center")), paramsPlus(__, "width" , "100%", "height" , "100%")); } static String himagesnippet(String imageID, Object... params) { return hsnippetimg(imageID, params); } static String h3(String s, Object... params) { return tag("h3", s, params) + "\n"; } static String joinWithBR(Iterable l) { return join("
\n", l); } static String joinWithBR(String... l) { return joinWithBR(asList(l)); } static boolean eqicOneOf(String s, String... l) { for (String x : l) if (eqic(s, x)) return true; return false; } static boolean isAGIBlueDomain(String domain) { return domainIsUnder(domain, theAGIBlueDomain()); } static String htitle(String title) { return hfulltag("title", htmlencode_noQuotes(title)); } static String hmobilefix() { return ""; } static String hmobilefix(String html) { return hAddToHead(html, hmobilefix()); } static String hNoBlueLinks() { return hcss(" a { color: inherit; } "); } static String repString(int n, String s) { return repeatString(s, n); } static String repString(String s, int n) { return repeatString(s, n); } static String small(Object contents, Object... params) { return tag("small", contents, params); } static Object eleu_serveSubBot(String botID, String uri, Map params) { sleepWhile(() -> eleu_botIsReloading(botID)); return callHtmlMethod2(getBot(botID), uri, params); } static boolean ewic(String a, String b) { return endsWithIgnoreCase(a, b); } static boolean ewic(String a, String b, Matches m) { return endsWithIgnoreCase(a, b, m); } static String addSlash(String s) { return empty(s) || s.endsWith("/") ? s : s + "/"; } static File javaxDataDir_dir; // can be set to work on different base dir static File javaxDataDir() { return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data"); } static File javaxDataDir(String... subs) { return newFile(javaxDataDir(), subs); } static Object subBot_maxCacheHeaders(Object response) { return callMainBot("maxCacheHeaders", response); } static Object serveWithMimeType(String text, String contentType) { return serveWithContentType(text, contentType); } static int loadPage_defaultTimeout = 60000; static ThreadLocal loadPage_charset = new ThreadLocal(); static boolean loadPage_allowGzip = true, loadPage_debug; static boolean loadPage_anonymous = false; // don't send computer ID static int loadPage_verboseness = 100000; static int loadPage_retries = 1; //60; // seconds static ThreadLocal loadPage_silent = new ThreadLocal(); static volatile int loadPage_forcedTimeout; // ms static ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal(); // ms static ThreadLocal>> loadPage_responseHeaders = new ThreadLocal(); static ThreadLocal> loadPage_extraHeaders = new ThreadLocal(); static ThreadLocal loadPage_sizeLimit = new ThreadLocal(); public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (Exception __e) { throw rethrow(__e); } } public static String loadPageSilently(URL url) { try { if (!networkAllowanceTest(str(url))) throw fail("Not allowed: " + url); IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = loadPage_openConnection(url); return loadPage(con, url); } catch (IOException _e) { e = _e; if (loadPage_debug) print(exceptionToStringShort(e)); if (tries < loadPage_retries-1) sleepSeconds(1); } throw e; } catch (Exception __e) { throw rethrow(__e); } } static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) // don't think we use this anymore url = tb_mainServer() + "/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } 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); } } static String loadPage(URL url) { return loadPage(url.toExternalForm()); } static String loadPage(URLConnection con, URL url) throws IOException { return loadPage(con, url, true); } static String loadPage(URLConnection con, URL url, boolean addHeaders) { try { Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders); if (addHeaders) try { if (!loadPage_anonymous) setHeaders(con); if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("X-No-Cookies", "1"); for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key)); } catch (Throwable e) {} // fails if within doPost return loadPage(con); } catch (Exception __e) { throw rethrow(__e); } } // just download as string, no shenanigans or extra headers or ANYTHING static String loadPage(URLConnection con) { try { Long limit = optPar(loadPage_sizeLimit); URL url = con.getURL(); vm_generalSubMap("URLConnection per thread").put(currentThread(), con); loadPage_responseHeaders.set(con.getHeaderFields()); InputStream in = null; try { in = urlConnection_getInputStream(con); //vm_generalSubMap("InputStream per thread").put(currentThread(), in); if (loadPage_debug) print("Put stream in map: " + currentThread()); String contentType = con.getContentType(); if (contentType == null) { //printStruct("Headers: ", con.getHeaderFields()); throw new IOException("Page could not be read: " + hideCredentials(url)); } //print("Content-Type: " + contentType); String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = newGZIPInputStream(in); } Reader r; try { r = new InputStreamReader(in, unquote(charset)); } catch (UnsupportedEncodingException e) { print(toHex(utf8(charset))); throw e; } boolean silent = isTrue(loadPage_silent.get()); StringBuilder buf = new StringBuilder(); int n = 0; while (limit == null || n < limit) { ping(); int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if (!silent && (n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } finally { if (loadPage_debug) print("loadPage done"); //vm_generalSubMap("InputStream per thread").remove(currentThread()); vm_generalSubMap("URLConnection per thread").remove(currentThread()); if (in != null) in.close(); } } catch (Exception __e) { throw rethrow(__e); } } 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); /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ //return or(match, "ISO-8859-1"); return or(match, "UTF-8"); } 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; } static
A printStackTrace(A e) { // we go to system.out now - system.err is nonsense if (e != null) print(getStackTrace(e)); return e; } static void printStackTrace() { printStackTrace(new Throwable()); } static void printStackTrace(String msg) { printStackTrace(new Throwable(msg)); } static void printStackTrace(String msg, Throwable e) { printStackTrace(new Throwable(msg, e)); } static Object subBot_serveFile(File file) { return call(getMainBot(), "serveFile", file); } static Object subBot_serveFile(File file, String mimeType) { return call(getMainBot(), "serveFile", file, mimeType); } // TODO: use actualUserHome()? // (there was a problem with onLocallyInferiorJavaX() always triggering inside #1013896) static File pathToJavaxJar() { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.pathToJavaXJar(); return pathToJavaxJar_noResourceLoader(); } static File pathToJavaxJar_noResourceLoader() { try { int x = latestInstalledJavaX(); File xfile = new File(userHome(), ".javax/x" + Math.max(x, 30) + ".jar"); if (!xfile.isFile()) { print("Saving " + f2s(xfile)); String url = x30JarServerURL(); 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); } } static String h1(String s, Object... params) { return hfulltag("h1", s, params); } static String himageSnippet(String imageID, Object... params) { return hsnippetimg(imageID, params); } static File programFile(String name) { return prepareProgramFile(name); } static File programFile(String progID, String name) { return prepareProgramFile(progID, name); } static File newFile(File base, String... names) { for (String name : names) base = new File(base, name); return base; } static File newFile(String name) { return name == null ? null : new File(name); } static File newFile(String base, String... names) { return newFile(newFile(base), names); } /** writes safely (to temp file, then rename) */ static File saveTextFile(String fileName, String contents) throws IOException { /*ifdef CriticalActions temp beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)"); endifdef*/ 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()); try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); } finally { _close(fileOutputStream); }} 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; } static File saveTextFile(File fileName, String contents) { try { saveTextFile(fileName.getPath(), contents); return fileName; } catch (Exception __e) { throw rethrow(__e); } } static void unzipSnippet(String snippetID, File toDir) { print("Unzipping snippet " + snippetID + " to " + toDir); zip2dir(loadLibrary(snippetID), toDir); } static AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) { return print_byThread().get() == null ? tempInterceptPrint(f) : null; } static Map> callF_cache = newDangerousWeakHashMap(); static A callF(F0 f) { return f == null ? null : f.get(); } static B callF(F1 f, A a) { return f == null ? null : f.get(a); } static A callF(IF0 f) { return f == null ? null : f.get(); } static B callF(IF1 f, A a) { return f == null ? null : f.get(a); } static B callF(A a, IF1 f) { return f == null ? null : f.get(a); } static C callF(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } static void callF(VF1 f, A a) { if (f != null) f.get(a); } static void callF(A a, IVF1 f) { if (f != null) f.get(a); } static void callF(IVF1 f, A a) { if (f != null) f.get(a); } static Object callF(Runnable r) { { if (r != null) r.run(); } return null; } static Object callF(Object f, Object... args) { return safeCallF(f, args); } static Object safeCallF(Object f, Object... args) { if (f instanceof Runnable) { ((Runnable) f).run(); return null; } if (f == null) return null; Class c = f.getClass(); ArrayList methods; synchronized(callF_cache) { methods = callF_cache.get(c); if (methods == null) methods = callF_makeCache(c); } int n = l(methods); if (n == 0) { if (f instanceof String) throw fail("Legacy call: " + f); throw fail("No get method in " + getClassName(c)); } if (n == 1) return invokeMethod(methods.get(0), f, args); for (int i = 0; i < n; i++) { Method m = methods.get(i); if (call_checkArgs(m, args, false)) return invokeMethod(m, f, args); } throw fail("No matching get method in " + getClassName(c)); } // used internally static ArrayList callF_makeCache(Class c) { ArrayList l = new ArrayList(); Class _c = c; do { for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) { makeAccessible(m); l.add(m); } if (!l.isEmpty()) break; _c = _c.getSuperclass(); } while (_c != null); callF_cache.put(c, l); return l; } static Object call_withVarargs(Object o, String methodName, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Class c = (Class) o; _MethodCache cache = callOpt_getCache(c); Method me = cache.findStaticMethod(methodName, args); if (me != null) return invokeMethod(me, null, args); // try varargs List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } { if (!(isStaticMethod(m))) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, null, newArgs); } throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found"); } else { Class c = o.getClass(); _MethodCache cache = callOpt_getCache(c); Method me = cache.findMethod(methodName, args); if (me != null) return invokeMethod(me, o, args); // try varargs List methods = cache.cache.get(methodName); if (methods != null) methodSearch: for (Method m : methods) { { if (!(m.isVarArgs())) continue; } Object[] newArgs = massageArgsForVarArgsCall(m, args); if (newArgs != null) return invokeMethod(m, o, newArgs); } throw fail("Method " + c.getName() + "." + methodName + "(" + formatArgumentClasses(args) + ") not found"); } } catch (Exception __e) { throw rethrow(__e); } } static String addPrefix(String prefix, String s) { return s.startsWith(prefix) ? s : prefix + s; } 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, ":"); } static String hostNameFromURL(String url) { try { return empty(url) ? null : new URL(url).getHost(); } catch (Exception __e) { throw rethrow(__e); } } static void sleepSeconds(double s) { if (s > 0) sleep(round(s*1000)); } // o can be a class, then we search for a static method called "html". static String callHtmlMethod(Object o, String uri) { return callHtmlMethod(o, uri, null); } static String callHtmlMethod(Object o, String uri, Map params) { String s = (String) callOpt(o, "html", uri, params); if (s == null) s = (String) callOpt(o, "html", uri); if (s == null) s = (String) callOpt(o, "html"); return s; } static String combinePrintParameters(String s, Object o) { return (endsWithLetterOrDigit(s) ? s + ": " : s) + o; } static void ping_okInCleanUp() { if (ping_pauseAll || ping_anyActions) ping_impl(true); } // this syntax should be removed... static Object getThreadLocal(Object o, String name) { ThreadLocal t = (ThreadLocal) (getOpt(o, name)); return t != null ? t.get() : null; } static A getThreadLocal(ThreadLocal tl) { return tl == null ? null : tl.get(); } static A getThreadLocal(ThreadLocal tl, A defaultValue) { return or(getThreadLocal(tl), defaultValue); } static ThreadLocal print_byThread_dontCreate() { return print_byThread; } static boolean isFalse(Object o) { return eq(false, o); } static String getStackTrace(Throwable throwable) { lastException(throwable); return getStackTrace_noRecord(throwable); } static String getStackTrace_noRecord(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return hideCredentials(writer.toString()); } static String getStackTrace() { return getStackTrace_noRecord(new Throwable()); } static String getStackTrace(String msg) { return getStackTrace_noRecord(new Throwable(msg)); } 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(); } 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); } } static void vmBus_send(String msg, Object... args) { Object arg = vmBus_wrapArgs(args); pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg); pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg); } static void vmBus_send(String msg) { vmBus_send(msg, (Object) null); } static Class mc() { return main.class; } static void _handleError(Error e) { //call(javax(), '_handleError, e); } static Object subBot_httpd() { Object httpd = getThreadLocal((ThreadLocal) getOpt(mainBot(), "MyHTTPD_current")); if (httpd == null) httpd = getThreadLocal((ThreadLocal) getOpt(mainBot(), "WebSocketHTTPD_current")); return httpd; } static Object getOpt(Object o, String field) { return getOpt_cached(o, field); } static Object getOpt(String field, Object o) { return getOpt_cached(o, field); } static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; makeAccessible(f); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } // access of static fields is not yet optimized static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; makeAccessible(f); return f.get(null); } catch (Exception __e) { throw rethrow(__e); } } static Field getOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static Object mainBot() { return getMainBot(); } static boolean contains(Collection c, Object o) { return c != null && c.contains(o); } static boolean contains(Iterable it, Object a) { if (it != null) for (Object o : it) if (eq(a, o)) return true; return false; } static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } static boolean contains(BitSet bs, int i) { return bs != null && bs.get(i); } static boolean contains(Rect r, Pt p) { return rectContains(r, p); } static boolean empty(Collection c) { return c == null || c.isEmpty(); } static boolean empty(Iterable c) { return c == null || !c.iterator().hasNext(); } static boolean empty(CharSequence s) { return s == null || s.length() == 0; } static boolean empty(Map map) { return map == null || map.isEmpty(); } static boolean empty(Object[] o) { return o == null || o.length == 0; } static boolean empty(BitSet bs) { return bs == null || bs.isEmpty(); } 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)); } static boolean empty(Iterator i) { return i == null || !i.hasNext(); } static boolean empty(double[] a) { return a == null || a.length == 0; } static boolean empty(float[] a) { return a == null || a.length == 0; } static boolean empty(int[] a) { return a == null || a.length == 0; } static boolean empty(long[] a) { return a == null || a.length == 0; } static boolean empty(byte[] a) { return a == null || a.length == 0; } static boolean empty(short[] a) { return a == null || a.length == 0; } static boolean empty(IMultiMap mm) { return mm == null || mm.size() == 0; } static boolean empty(File f) { return getFileSize(f) == 0; } static boolean empty(Rect r) { return !(r != null && r.w != 0 && r.h != 0); } static boolean empty(Chain c) { return c == null; } static boolean empty(AppendableChain c) { return c == null; } static boolean empty(IntSize l) { return l == null || l.size() == 0; } static String makePostData(Map map) { StringBuilder buf = new StringBuilder(); for (Map.Entry e : castMapToMapO(map).entrySet()) { String key = (String) (e.getKey()); Object val = e.getValue(); if (val != null) { String value = str(val); if (nempty(buf)) buf.append("&"); buf.append(urlencode(key)).append("=").append(urlencode(/*escapeMultichars*/(value))); } } return str(buf); } 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(/*escapeMultichars*/(value))); } } return str(buf); } static A setThreadLocal(ThreadLocal tl, A value) { if (tl == null) return null; A old = tl.get(); tl.set(value); return old; } static Object[] litObjectArray(Object... l) { return l; } static boolean isDigit(char c) { return Character.isDigit(c); } static int parseInt(String s) { return emptyString(s) ? 0 : Integer.parseInt(s); } static int parseInt(char c) { return Integer.parseInt(str(c)); } // returns from C to C static String jextract(String pat, String s) { return jextract(pat, javaTok(s)); } 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); } static String firstIntegerString(Iterable c) { Iterator it = c.iterator(); while (it.hasNext()) { String s = it.next(); if (isInteger(s)) return s; } return null; } static String hfulltag(String tag) { return hfulltag(tag, ""); } static String hfulltag(String tag, Object contents, Object... params) { return hopeningTag(tag, params) + str(contents) + ""; } static String fulltag(String tag) { return hfulltag(tag); } static String fulltag(String tag, Object contents, Object... params) { return hfulltag(tag, contents, params); } static String href(String link, Object contents, Object... params) { if (link == null) return str(contents); return hfulltag("a", contents, arrayPlus(params, "href", link)); } static Set keys(Map map) { return map == null ? new HashSet() : map.keySet(); } // convenience shortcut for keys_gen static Set keys(Object map) { return keys((Map) map); } static Set keys(IMultiMap mm) { return mm.keySet(); } static String hrefBlank(String link, Object contents, Object... params) { return empty(link) ? strOrEmpty(contents) : tag("a", contents, concatArrays(new Object[] { "href" , link, "target" , "_blank" }, params)); } static String formatYouTubeURL_long(String s) { return "https://www.youtube.com/watch?v=" + extractYouTubeID(s); } public static String join(String glue, Iterable strings) { if (strings == null) return ""; if (strings instanceof Collection) { if (((Collection) strings).size() == 1) return strOrEmpty(first((Collection) strings)); } StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(strOrEmpty(i.next())); while (i.hasNext()) buf.append(glue).append(strOrEmpty(i.next())); } return buf.toString(); } public static String join(String glue, String... strings) { return join(glue, Arrays.asList(strings)); } public static String join(String glue, Object... strings) { return join(glue, Arrays.asList(strings)); } static String join(Iterable strings) { return join("", strings); } static String join(Iterable strings, String glue) { return join(glue, strings); } public static String join(String[] strings) { return join("", strings); } static String join(String glue, Pair p) { return p == null ? "" : str(p.a) + glue + str(p.b); } static ArrayList emptyList() { return new ArrayList(); //ret Collections.emptyList(); } static ArrayList emptyList(int capacity) { return new ArrayList(max(0, capacity)); } // Try to match capacity static ArrayList emptyList(Iterable l) { return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList(); } static ArrayList emptyList(Object[] l) { return emptyList(l(l)); } // get correct type at once static ArrayList emptyList(Class c) { return new ArrayList(); } // unclear semantics as to whether return null on null static ArrayList asList(A[] a) { return a == null ? new ArrayList() : new ArrayList(Arrays.asList(a)); } static ArrayList asList(char[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (var i : a) l.add(i); return l; } static ArrayList asList(byte[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (var i : a) l.add(i); return l; } static ArrayList asList(int[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (int i : a) l.add(i); return l; } static ArrayList asList(long[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (long i : a) l.add(i); return l; } static ArrayList asList(float[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (float i : a) l.add(i); return l; } static ArrayList asList(double[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (double i : a) l.add(i); return l; } static ArrayList asList(short[] a) { if (a == null) return null; ArrayList l = emptyList(a.length); for (short i : a) l.add(i); return l; } static ArrayList asList(Iterator it) { ArrayList l = new ArrayList(); if (it != null) while (it.hasNext()) l.add(it.next()); return l; } // disambiguation static ArrayList asList(IterableIterator s) { return asList((Iterator) s); } 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; } static ArrayList asList(Enumeration e) { ArrayList l = new ArrayList(); if (e != null) while (e.hasMoreElements()) l.add(e.nextElement()); return l; } static ArrayList asList(ReverseChain c) { return c == null ? emptyList() : c.toList(); } static List asList(Pair p) { return p == null ? null : ll(p.a, p.b); } 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; } static int indexOf(List l, int startIndex, A a) { return indexOf(l, a, startIndex); } static int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } static int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } static int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } static int indexOf(String a, char b) { return a == null ? -1 : a.indexOf(b); } static int indexOf(String a, int i, char b) { return indexOf(a, b, i); } static int indexOf(String a, char b, int i) { return a == null ? -1 : a.indexOf(b, i); } static int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } 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; } static int indexOf(Iterable l, A a) { if (l == null) return -1; int i = 0; for (A x : l) { if (eq(x, a)) return i; i++; } return -1; } static List withoutNulls(Iterable l) { if (l instanceof List) if (!containsNulls((List) l)) return ((List) l); List l2 = new ArrayList(); for (A a : l) if (a != null) l2.add(a); return l2; } static Map withoutNulls(Map map) { Map map2 = similarEmptyMap(map); for (A a : keys(map)) if (a != null) { B b = map.get(a); if (b != null) map2.put(a, b); } return map2; } static List withoutNulls(A[] l) { List l2 = new ArrayList(); if (l != null) for (A a : l) if (a != null) l2.add(a); return l2; } static int[] subArray(int[] b, int start, int end) { int[] x = new int[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static byte[] subArray(byte[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start >= end) return new byte[0]; byte[] x = new byte[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static long[] subArray(long[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start >= end) return new long[0]; long[] x = new long[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static short[] subArray(short[] b, int start, int end) { if (start <= 0 && end >= l(b)) return b; short[] x = new short[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static float[] subArray(float[] b, int start, int end) { float[] x = new float[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static Object[] subArray(Object[] b, int start) { return subArray(b, start, l(b)); } static Object[] subArray(Object[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start >= end) return new Object[0]; Object[] x = new Object[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static String containerTag(String tag) { return containerTag(tag, ""); } static String containerTag(String tag, Object contents, Object... params) { String openingTag = hopeningTag(tag, params); String s = str(contents); return openingTag + s + ""; } // legacy mode //sbool ping_actions_shareable = true; static volatile boolean ping_pauseAll = false; static int ping_sleep = 100; // poll pauseAll flag every 100 static volatile boolean ping_anyActions = false; static Map ping_actions = newWeakHashMap(); static ThreadLocal ping_isCleanUpThread = new ThreadLocal(); // ignore pingSource if not PingV3 static boolean ping(PingSource pingSource) { return ping(); } // always returns true static boolean ping() { //ifdef useNewPing newPing(); //endifdef if (ping_pauseAll || ping_anyActions) ping_impl(true /* XXX */); //ifndef LeanMode ping_impl(); endifndef return true; } // returns true when it slept static boolean ping_impl(boolean okInCleanUp) { try { if (ping_pauseAll && !isAWTThread()) { do Thread.sleep(ping_sleep); while (ping_pauseAll); return true; } if (ping_anyActions) { // don't allow sharing ping_actions 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); } } // assumptions: // -pingSource() stays constant within a stack frame (so you can cache it) // -all changes happen with tempSetPingSource // -multiple threads can share a PingSource static PingSource pingSource() { return pingSource_tl().get(); } static PingSource pingSource(Thread thread) { return pingSource_tl().get(thread); } static List toLinesFullTrim(String s) { List l = new ArrayList(); for (String line : toLines(s)) if (nempty(line = trim(line))) l.add(line); return l; } static List toLinesFullTrim(File f) { List l = new ArrayList(); for (String line : linesFromFile(f)) if (nempty(line = trim(line))) l.add(line); return l; } static void typeWriterConsole() { if (isHeadless()) return; Font f = typeWriterFont(); consoleFont(f); consoleInputFont(f); } static String replaceCodeTokensUsingMap(String s, Map map) { return join(replaceCodeTokensUsingMap(javaTok(s), map)); } static List replaceCodeTokensUsingMap(List tok, Map map) { List out = emptyList(tok); for (int i = 0; i < l(tok); i++) { out.add(odd(i) ? lookupOrKeep(map, tok.get(i)) : tok.get(i)); } return out; } static String replaceCodeTokensUsingMap(Map map, String s) { return replaceCodeTokensUsingMap(s, map); } static Map mapMapToMap(IF2> f, Map m) { if (m == null) return null; Map map = similarEmptyMap(m); for (Map.Entry e : m.entrySet()) { Pair p = f.get(e.getKey(), e.getValue()); map.put(p.a, p.b); } return map; } static Map mapMapToMap(Map m, IF2> f) { return mapMapToMap(f, m); } static HashMap litmap(Object... x) { HashMap map = new HashMap(); litmap_impl(map, x); return map; } 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]); } static Pair pair(A a, B b) { return new Pair(a, b); } static Pair pair(A a) { return new Pair(a, a); } static String dottedSpan(String contents, String title) { return span(contents, "title", title, "style" , "border-bottom: dotted 1px"); } static boolean agiBlueURL_noHTTPS = false; static String agiBlueURL_url = "https://agi.blue"; static String agiBlueURL() { return agiBlueURL_noHTTPS ? replacePrefix("https://", "http://", agiBlueURL_url) : agiBlueURL_url; } // one array plus more elements static Object[] arrayPlus(Object[] a1, Object... a2) { return concatArrays(a1, a2); } static String pre_htmlencode(Object contents, Object... params) { return pre(htmlencode_noQuotes(str(contents)), params); } static String sourceCodeToHTML(String src) { return sourceCodeToHTML_noEncode(htmlencode2(src)); } // works for String, StringBuffer, StringBuilder static String sourceCodeToHTML(Object o) { return sourceCodeToHTML(str(o)); } 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; } static boolean even(int i) { return (i & 1) == 0; } static boolean even(long i) { return (i & 1) == 0; } static boolean even(BigInteger n) { return even(n.intValue()); } static String htag(String tag) { return htag(tag, ""); } 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 + ""; } static A last(List l) { return empty(l) ? null : l.get(l.size()-1); } static char last(String s) { return empty(s) ? '#' : s.charAt(l(s)-1); } static byte last(byte[] a) { return l(a) != 0 ? a[l(a)-1] : 0; } static int last(int[] a) { return l(a) != 0 ? a[l(a)-1] : 0; } static long last(long[] a) { return l(a) != 0 ? a[l(a)-1] : 0; } static double last(double[] a) { return l(a) != 0 ? a[l(a)-1] : 0; } static A last(A[] a) { return l(a) != 0 ? a[l(a)-1] : null; } static A last(Iterator it) { A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static A last(Collection l) { if (l == null) return null; if (l instanceof List) return (A) last((List) l); if (l instanceof SortedSet) return (A) last((SortedSet) l); Iterator it = iterator(l); A a = null; while (it.hasNext()) { ping(); a = it.next(); } return a; } static A last(SortedSet l) { return l == null ? null : l.last(); } static A last(ReverseChain l) { return l == null ? null : l.element; } static A last(CompactLinkedHashSet set) { return set == null ? null : set.last(); } static Object[] dropLastFromObjectArray(Object[] a) { return dropLastFromObjectArray(a, 1); } static Object[] dropLastFromObjectArray(Object[] a, int n) { if (a == null) return null; n = Math.min(n, a.length); Object[] b = new Object[a.length-n]; System.arraycopy(a, 0, b, 0, b.length); return b; } static String intToHex_flexLength(int i) { return Integer.toHexString(i); } static String snippetImageURL(long snippetID) { return snippetImageURL(fsI(snippetID)); } static String snippetImageURL(String snippetID) { return snippetImageURL(snippetID, "png"); } static String snippetImageURL(String snippetID, String contentType) { if (snippetID == null || isURL(snippetID)) return snippetID; long id = parseSnippetID(snippetID); String url; if (isImageServerSnippet(id)) url = imageServerLink(id); else //url = "http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + id + "&contentType=image/" + contentType; url = "https://botcompany.de/img/" + id; return url; } 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; } 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; } static List drop(Iterable c, Object pred) { return antiFilter(c, pred); } static List drop(Object pred, Iterable c) { return antiFilter(pred, c); } static List drop(Object pred, Object[] c) { return antiFilter(pred, c); } static List drop(Iterable c, F1 pred) { return antiFilter(c, pred); } static List drop(F1 pred, Iterable c) { return antiFilter(pred, c); } static List drop(Iterable c, IF1 pred) { return antiFilter(c, pred); } static List drop(IF1 pred, Iterable c) { return antiFilter(pred, c); } static ArrayList toList(A[] a) { return asList(a); } static ArrayList toList(int[] a) { return asList(a); } static ArrayList toList(short[] a) { return asList(a); } static ArrayList toList(long[] a) { return asList(a); } static ArrayList toList(Set s) { return asList(s); } static ArrayList toList(Iterable s) { return asList(s); } static String substring(String s, int x) { return substring(s, x, strL(s)); } static String substring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; int n = s.length(); if (y < x) y = x; if (y > n) y = n; if (x >= y) return ""; return s.substring(x, y); } // convenience method for quickly dropping a prefix static String substring(String s, CharSequence l) { return substring(s, lCharSequence(l)); } static int indexOfPred(List l, Object pred) { for (int i = 0; i < l(l); i++) if (checkCondition(pred, l.get(i))) return i; return -1; } static int indexOfPred(List l, IF1 pred) { return indexOfPred(l, (Object) pred); } static Matcher regexpMatcher(String pat, String s) { return compileRegexp(pat).matcher(unnull(s)); } static Matcher regexpMatcher(java.util.regex.Pattern pat, String s) { return pat.matcher(unnull(s)); } 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); } } static String joinStrings(String sep, Object... strings) { return joinStrings(sep, Arrays.asList(strings)); } static String joinStrings(String sep, Iterable strings) { StringBuilder buf = new StringBuilder(); for (Object o : unnull(strings)) { String s = strOrNull(o); if (nempty(s)) { if (nempty(buf)) buf.append(sep); buf.append(s); } } return str(buf); } static String hsnippetimg(String imageID, Object... params) { return himg(snippetImageLink(imageID), params); } static boolean isRelativeOrAbsoluteURL(String s) { return isAbsoluteURL(s) || isRelativeURL(s); } static String hstylesheetsrc(String src) { return tag("link", "", "rel" , "stylesheet", "href" , src); } static int getIndent(String s) { int n = Integer.MAX_VALUE; for (String l : toLines(s)) n = min(n, getIndentOfLine(l)); return n; } static IterableIterator toLines(File f) { return linesFromFile(f); } 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; } static int toLines_nextLineBreak(String s, int start) { int n = s.length(); for (int i = start; i < n; i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } // usually L 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(); } static String fromLines(String... lines) { return fromLines(asList(lines)); } static String joinContentsOfContainerTag(List tok) { return tok == null ? null : join(contentsOfContainerTag(tok)); } // tok must come from htmlTok // returns all container tags found (including content) as CNC // honors nested tags correctly static List> findContainerTagWithParams(List tok, String tag, Object... params) { List> l = new ArrayList(); for (List t : findContainerTag(tok, tag)) if (htmlCheckParams(second(t), params)) l.add(t); return l; } static List> findContainerTagWithParams(String html, String tag, Object... params) { return findContainerTagWithParams(htmlTok(html), tag, params); } static List htmlTok(String s) { return htmlcoarsetok(s); } static Pair mapEntryToPair(Map.Entry e) { return e == null ? null : pair(e.getKey(), e.getValue()); } static Set> entrySet(Map map) { return _entrySet(map); } static A firstThat(Iterable l, IF1 pred) { for (A a : unnullForIteration(l)) if (pred.get(a)) return a; return null; } static A firstThat(A[] l, IF1 pred) { for (A a : unnullForIteration(l)) if (pred.get(a)) return a; return null; } static A firstThat(IF1 pred, Iterable l) { return firstThat(l, pred); } static A firstThat(IF1 pred, A[] l) { return firstThat(l, pred); } // tag = tag name // newTag = full new contents including outer tag // replaces only one occurrence static String hreplacetag(String html, String tag, String newTag) { List tok = htmlcoarsetok(html); List> tags = findContainerTag(tok, tag); if (empty(tags)) return html; List theTag = first(tags); List actualTag = subList(theTag, 1, l(theTag)-1); return join(replaceSubList(cloneList(tok), actualTag, litlist(newTag))); } // this should be on by default now I think, but it may break // legacy code... static ThreadLocal htmlencode_forParams_useV2 = new ThreadLocal(); static String htmlencode_forParams(String s) { if (s == null) return ""; if (isTrue(htmlencode_forParams_useV2.get())) return htmlencode_forParams_v2(s); StringBuilder out = new StringBuilder(Math.max(16, s.length())); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c > 127 || c == '"' || c == '<' || c == '>') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static String snippetRawURL(String snippetID) { return snippetRawURL(snippetID, null); } static String snippetRawURL(String snippetID, String contentType) { return "https://botcompany.de/serve/" + psI(snippetID) + htmlQuery("ct" , contentType); } static String hSilentComputator() { return hSilentComputator(hSilentComputator_defaultURI()); } static String hSilentComputator(String wsUri) { return hSilentComputator(wsUri, ""); } 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())); } static String hSilentComputator_defaultURI() { int port = subBot_currentPort(); return (subBot_isHttps() ? "wss://" : "ws://") + domain() + (port == 80 ? "" : ":" + port) + "/"; } static boolean boolOptParam(ThreadLocal tl) { return isTrue(optPar(tl)); } // defaults to false static boolean boolOptParam(Object[] __, String name) { return isTrue(optParam(__, name)); } static boolean boolOptParam(String name, Object[] __) { return boolOptParam(__, name); } static boolean boolOptParam(String name, Map __) { return isTrue(optPar(name, __)); } static A optParam(ThreadLocal tl, A defaultValue) { return optPar(tl, defaultValue); } static A optParam(ThreadLocal tl) { return optPar(tl); } static Object optParam(String name, Map params) { return mapGet(params, name); } // now also takes a map as single array entry 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; } static Object optParam(Object[] opt, String name) { return optParam(opt, name, null); } static Object optParam(String name, Object[] params) { return optParam(params, name); } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(Throwable e) { throw asRuntimeException(e); } static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static RuntimeException fail(Object... objects) { throw new Fail(objects); } static RuntimeException fail(String msg) { throw new RuntimeException(msg == null ? "" : msg); } static RuntimeException fail(String msg, Throwable innerException) { throw new RuntimeException(msg, innerException); } static String getClassName(Object o) { return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName(); } static String embedYoutube_newer(String youtubeID, Object... __) { return embedYoutube_newer(youtubeID, 300, __); } static String embedYoutube_newer(String youtubeID, int w, Object... __) { return embedYoutube_newer(youtubeID, w, sixteenToNine(w), __); } static String embedYoutube_newer(String youtubeID, int w, int h, Object... __) { boolean loop = false; if (first(__) instanceof Boolean) { loop = true; __ = dropFirst(__); } boolean autoPlay = boolPar("autoPlay", __); youtubeID = extractYouTubeID(youtubeID); return iframe(appendQueryToURL("https://www.youtube.com/embed/" + youtubeID, "playlist" , loop ? youtubeID : null, "autoplay" , autoPlay ? 1 : null, "loop" , loop ? 1 : 0), "width" , w, "height" , h, "frameborder" , 0, "allow" , "autoplay; encrypted-media", "allowfullscreen" , html_valueLessParam()); } static String unnull(String s) { return s == null ? "" : s; } static Collection unnull(Collection l) { return l == null ? emptyList() : l; } static List unnull(List l) { return l == null ? emptyList() : l; } static int[] unnull(int[] l) { return l == null ? emptyIntArray() : l; } static char[] unnull(char[] l) { return l == null ? emptyCharArray() : l; } static double[] unnull(double[] l) { return l == null ? emptyDoubleArray() : l; } static float[] unnull(float[] l) { return l == null ? emptyFloatArray() : l; } static Map unnull(Map l) { return l == null ? emptyMap() : l; } static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static A[] unnull(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static BitSet unnull(BitSet b) { return b == null ? new BitSet() : b; } static Pt unnull(Pt p) { return p == null ? new Pt() : p; } //ifclass Symbol static Symbol unnull(Symbol s) { return s == null ? emptySymbol() : s; } //endif static Pair unnull(Pair p) { return p != null ? p : new Pair(null, null); } static int unnull(Integer i) { return i == null ? 0 : i; } static long unnull(Long l) { return l == null ? 0L : l; } static double unnull(Double l) { return l == null ? 0.0 : l; } static boolean nemptyString(String s) { return s != null && s.length() > 0; } static int strL(String s) { return s == null ? 0 : s.length(); } static int listL(Collection l) { return l == null ? 0 : l.size(); } static boolean neq(Object a, Object b) { return !eq(a, b); } static byte[] toUtf8(String s) { try { return s.getBytes(utf8charset()); } catch (Exception __e) { throw rethrow(__e); } } static Object subBot_serveInputStream(InputStream in, String mimeType) { return call(mainBot(), "serveInputStream", in, mimeType); } static ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal(); static void checkFileNotTooBigToRead(File f) { callF(checkFileNotTooBigToRead_tl.get(), f); } static String _userHome; static String userHome() { if (_userHome == null) return actualUserHome(); return _userHome; } static File userHome(String path) { return new File(userDir(), path); } static String asString(Object o) { return o == null ? null : o.toString(); } static String dropSuffix(String suffix, String s) { return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static String dropLeadingSlash(String s) { return dropPrefix("/", s); } static int iceil(double d) { return (int) Math.ceil(d); } static boolean startsWithIgnoreCase(String a, String b) { return regionMatchesIC(a, 0, b, 0, b.length()); } static Object callOpt(Object o) { return callF(o); } static Object callOpt(Object o, String method, Object... args) { return callOpt_withVarargs(o, method, args); } static PCallPolicy pcallPolicyForThread() { var policy = pcallPolicyForThread_tl().get(); if (policy != null) return policy; return defaultPCallPolicy(); } static String hhead(Object contents) { return tag("head", contents); } static String tr(Object contents) { return tag("tr", contents); } static String td(Object contents, Object... params) { return hfulltag("td", contents, params); } static String td() { return td(""); } 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); } static Object[] paramsPlus(Map a1, Object... a2) { return paramsPlus(new Object[] {a1}, a2); } static String theAGIBlueDomain() { return "agi.blue"; } static String htmlencode_noQuotes(String s) { if (s == null) return ""; int n = s.length(); StringBuilder out = null; for (int i = 0; i < n; i++) { char c = s.charAt(i); if (c == '<') { if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out .append("<"); } else if (c == '>') { if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out .append(">"); } else if (c > 127 || c == '&') { int cp = s.codePointAt(i); if (out == null) out = new StringBuilder(Math.max(16, n)).append(takeFirst(i, s)); out .append("&#x"); out.append(intToHex_flexLength(cp)); out.append(';'); i += Character.charCount(cp)-1; } else { if (out != null) out.append(c); } } return out == null ? s : out.toString(); } // if block exists: put tag after // if not: add tag in front of the whole HTML 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); } static String repeatString(String s, int n) { StringBuilder buf = new StringBuilder(l(s)*n); for (int i = 0; i < n; i++) buf.append(s); return str(buf); } // returns last value of predicate static boolean sleepWhile(IF0 pred, Object... __) { int interval = optPar("interval", __, 50); // ms double max = optPar("max", __, 10.0); // seconds long time = sysNow(); do { if (!pred.get()) return false; sleep(interval); } while (sysNow() <= time+toMS(max)); return true; } static boolean eleu_botIsReloading(String botID) { return isTrue_call(call(mainMainClass(), "getDispatcher"), "isReloading", botID); } static boolean endsWithIgnoreCase(String a, String b) { int la = l(a), lb = l(b); return la >= lb && regionMatchesIC(a, la-lb, b, 0, lb); } static boolean endsWithIgnoreCase(String a, String b, Matches m) { if (!endsWithIgnoreCase(a, b)) return false; if (m != null) m.m = new String[] { substring(a, 0, l(a)-l(b)) }; return true; } static Object callMainBot(String method, Object... args) { return call(mainBot(), method, args); } static Object serveWithContentType(String text, String contentType) { return serveByteArray(toUtf8(text), contentType); } static boolean networkAllowanceTest(String url) { return isAllowed("networkAllowanceTest", url); } static String exceptionToStringShort(Throwable e) { try { 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; } catch (Throwable _e) { printStackTrace(_e); return "Error in exceptionToStringShort"; } } static String tb_mainServer_default = "https://code.botcompany.de:9898"; static Object tb_mainServer_override; // func -> S static String tb_mainServer() { if (tb_mainServer_override != null) return (String) callF(tb_mainServer_override); return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default)); } static File tb_mainServer_file() { return getProgramFile("#1001638", "mainserver.txt"); } static boolean tb_mainServer_isDefault() { return eq(tb_mainServer(), tb_mainServer_default); } static A printWithTime(A a) { return printWithTime("", a); } static A printWithTime(String s, A a) { print(hmsWithColons() + ": " + s, a); return a; } static String hideCredentials(URL url) { return url == null ? null : hideCredentials(str(url)); } 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|cookie)=[^&\\s\"]*", "$1$2="); } static String hideCredentials(Object o) { return hideCredentials(str(o)); } static A getAndClearThreadLocal(ThreadLocal tl) { A a = tl.get(); tl.set(null); return a; } 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) { //printShortException(e); } } static Map vm_generalSubMap(Object name) { synchronized(vm_generalMap()) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = synchroMap()); return map; } } static Thread currentThread() { return Thread.currentThread(); } static InputStream urlConnection_getInputStream(URLConnection con) throws IOException { return con.getInputStream(); } static GZIPInputStream newGZIPInputStream(File f) { return gzInputStream(f); } static GZIPInputStream newGZIPInputStream(InputStream in) { return gzInputStream(in); } 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); } } return unquoteSingleOrDoubleQuotes(s); } static String toHex(byte[] bytes) { return bytesToHex(bytes); } static String toHex(byte[] bytes, int ofs, int len) { return bytesToHex(bytes, ofs, len); } static byte[] utf8(String s) { return toUtf8(s); } static A or(A a, A b) { return a != null ? a : b; } static URLConnection openConnection(String url) { try { return openConnection(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static URLConnection openConnection(URL url) { try { ping(); callOpt(javax(), "recordOpenURLConnection", str(url)); return url.openConnection(); } catch (Exception __e) { throw rethrow(__e); } } 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); if (o instanceof Boolean) return boolToInt((Boolean) o); throw fail("woot not int: " + getClassName(o)); } static int toInt(long l) { if (l != (int) l) throw fail("Too large for int: " + l); return (int) l; } 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; } 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; } static IResourceLoader vm_getResourceLoader() { return proxy(IResourceLoader.class, vm_generalMap_get("_officialResourceLoader")); } static int latestInstalledJavaX() { File[] files = new File(userHome(), ".javax").listFiles(); int v = 0; if (files != null) for (File f : files) { Matcher m = regexpMatcher("x(\\d\\d\\d?)\\.jar", f.getName()); if (m.matches()) v = Math.max(v, Integer.parseInt(m.group(1))); } return v; } static String f2s(File f) { return f == null ? null : f.getAbsolutePath(); } static String f2s(String s) { return f2s(newFile(s)); } static String f2s(java.nio.file.Path p) { return p == null ? null : f2s(p.toFile()); } static String x30JarServerURL() { return "https://botcompany.de:9898/x30.jar"; } static ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal(); static ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal(); static byte[] loadBinaryPage(String url) { try { print("Loading " + url); return loadBinaryPage(loadPage_openConnection(new URL(url))); } catch (Exception __e) { throw rethrow(__e); } } 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); } } 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/*Long*/(); } 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); } } /** writes safely (to temp file, then rename) */ 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"; try (FileOutputStream fileOutputStream = newFileOutputStream(tempFileName)) { fileOutputStream.write(contents); } 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); } } static byte[] saveBinaryFile(File fileName, byte[] contents) { return saveBinaryFile(fileName.getPath(), contents); } static File prepareProgramFile(String name) { return mkdirsForFile(getProgramFile(name)); } static File prepareProgramFile(String progID, String name) { return mkdirsForFile(getProgramFile(progID, name)); } public static File mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) { // is null if file is in current dir dir.mkdirs(); if (!dir.isDirectory()) if (dir.isFile()) throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!"); else throw fail("Unknown IO exception during mkdirs of " + f2s(file)); } return file; } public static String mkdirsForFile(String path) { mkdirsForFile(new File(path)); return path; } static long now_virtualTime; static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static File copyFile(File src, File dest) { try { FileInputStream inputStream = new FileInputStream(src.getPath()); FileOutputStream outputStream = newFileOutputStream(dest.getPath()); try { copyStream(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } return dest; } catch (Exception __e) { throw rethrow(__e); } } static FileOutputStream newFileOutputStream(File path) throws IOException { return newFileOutputStream(path.getPath()); } static FileOutputStream newFileOutputStream(String path) throws IOException { return newFileOutputStream(path, false); } static FileOutputStream newFileOutputStream(File path, boolean append) throws IOException { return newFileOutputStream(path.getPath(), append); } static FileOutputStream newFileOutputStream(String path, boolean append) throws IOException { mkdirsForFile(path); FileOutputStream f = new FileOutputStream(path, append); _registerIO(f, path, true); return f; } static void _close(AutoCloseable c) { if (c != null) try { c.close(); } catch (Throwable e) { // Some classes stupidly throw an exception on double-closing if (c instanceof javax.imageio.stream.ImageOutputStream) return; else throw rethrow(e); } } static void zip2dir(File inZip, String outDir) { zip2dir(inZip, newFile(outDir)); } static void zip2dir(File inZip, File outDir) { zip2dir(inZip, outDir, ""); } static void zip2dir(File inZip, String outDir, String prefix) { zip2dir(inZip, newFile(outDir), prefix); } static void zip2dir(File inZip, File outDir, String prefix) { try { if (prefix.length() != 0 && !prefix.endsWith("/")) prefix += "/"; ZipFile zipFile = new ZipFile(inZip); try { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) continue; // We care about files only, really. Directories are made on the fly anyway. if (!entry.getName().startsWith(prefix)) continue; File outFile = new File(outDir, entry.getName()); print("Unzipping " + entry.getName() + " to " + outFile.getAbsolutePath()); stream2file(zipFile.getInputStream(entry), outFile); } } finally { _close(zipFile); }} catch (Exception __e) { throw rethrow(__e); } } static File loadLibrary(String snippetID) { return loadBinarySnippet(snippetID); } static ThreadLocal print_byThread() { synchronized(print_byThread_lock) { if (print_byThread == null) print_byThread = new ThreadLocal(); } return print_byThread; } // f can return false to suppress regular printing // call print_raw within f to actually print something static AutoCloseable tempInterceptPrint(F1 f) { return tempSetThreadLocal(print_byThread(), f); } static Map newDangerousWeakHashMap() { return _registerDangerousWeakMap(synchroMap(new WeakHashMap())); } // initFunction: voidfunc(Map) - is called initially, and after clearing the map static Map newDangerousWeakHashMap(Object initFunction) { return _registerDangerousWeakMap(synchroMap(new WeakHashMap()), initFunction); } 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); } } static boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != l(args)) { if (debug) print("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) { Object arg = args[i]; if (!(arg == null ? !types[i].isPrimitive() : isInstanceX(types[i], arg))) { if (debug) print("Bad parameter " + i + ": " + arg + " vs " + types[i]); return false; } } return true; } static Field makeAccessible(Field f) { try { f.setAccessible(true); } catch (Throwable e) { // Note: The error reporting only works with Java VM option --illegal-access=deny vmBus_send("makeAccessible_error", e, f); } return f; } static Method makeAccessible(Method m) { try { m.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, m); } return m; } static Constructor makeAccessible(Constructor c) { try { c.setAccessible(true); } catch (Throwable e) { vmBus_send("makeAccessible_error", e, c); } return c; } static final Map callOpt_cache = newDangerousWeakHashMap(); 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); // TODO: (super-rare) case where method exists static and non-static // with different args 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); } } // no longer synchronizes! (see #1102990) static _MethodCache callOpt_getCache(Class c) { _MethodCache cache = callOpt_cache.get(c); if (cache == null) callOpt_cache.put(c, cache = new _MethodCache(c)); return cache; } static boolean isStaticMethod(Method m) { return methodIsStatic(m); } static Object[] massageArgsForVarArgsCall(Executable m, Object[] args) { Class[] types = m.getParameterTypes(); int n = types.length-1, nArgs = l(args); if (nArgs < n) return null; for (int i = 0; i < n; i++) if (!argumentCompatibleWithType(args[i], types[i])) return null; Class varArgType = types[n].getComponentType(); for (int i = n; i < nArgs; i++) if (!argumentCompatibleWithType(args[i], varArgType)) return null; Object[] newArgs = new Object[n+1]; arraycopy(args, 0, newArgs, 0, n); // TODO: optimize int nVarArgs = nArgs-n; Object varArgs = Array.newInstance(varArgType, nVarArgs); for (int i = 0; i < nVarArgs; i++) Array.set(varArgs, i, args[n+i]); newArgs[n] = varArgs; return newArgs; } static String formatArgumentClasses(Object[] args) { return joinWithComma(map(__30 -> getClassName(__30), args)); } 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); } static volatile boolean sleep_noSleep = false; static void sleep(long ms) { ping(); if (ms < 0) return; // allow spin locks if (isAWTThread() && ms > 100) throw fail("Should not sleep on AWT thread"); try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static void sleep() { try { if (sleep_noSleep) throw fail("nosleep"); print("Sleeping."); sleepQuietly(); } catch (Exception __e) { throw rethrow(__e); } } static long round(double d) { return Math.round(d); } static String round(String s) { return roundBracket(s); } static Complex round(Complex c) { return new Complex(round(c.re), round(c.im)); } static boolean endsWithLetterOrDigit(String s) { return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length()-1)); } // PersistableThrowable doesn't hold GC-disturbing class references in backtrace static volatile PersistableThrowable lastException_lastException; static PersistableThrowable lastException() { return lastException_lastException; } static void lastException(Throwable e) { lastException_lastException = persistableThrowable(e); } 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); } } 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); } } static Object vmBus_wrapArgs(Object... args) { return empty(args) ? null : l(args) == 1 ? args[0] : args; } static void pcallFAll_minimalExceptionHandling(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) { ping(); pcallF_minimalExceptionHandling(f, args); } } static void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) { while (it.hasNext()) { ping(); pcallF_minimalExceptionHandling(it.next(), args); } } static Set vm_busListeners_live_cache; static Set vm_busListeners_live() { if (vm_busListeners_live_cache == null) vm_busListeners_live_cache = vm_busListeners_live_load(); return vm_busListeners_live_cache;} static Set vm_busListeners_live_load() { return vm_generalIdentityHashSet("busListeners"); } static Map vm_busListenersByMessage_live_cache; static Map vm_busListenersByMessage_live() { if (vm_busListenersByMessage_live_cache == null) vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load(); return vm_busListenersByMessage_live_cache;} static Map vm_busListenersByMessage_live_load() { return vm_generalHashMap("busListenersByMessage"); } //static final Map> getOpt_cache = newDangerousWeakHashMap(f getOpt_special_init); static class getOpt_Map extends WeakHashMap { getOpt_Map() { if (getOpt_special == null) getOpt_special = new HashMap(); clear(); } public void clear() { super.clear(); //print("getOpt clear"); put(Class.class, getOpt_special); put(String.class, getOpt_special); } } static final Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map())); static HashMap getOpt_special; // just a marker /*static void getOpt_special_init(Map map) { map.put(Class.class, getOpt_special); map.put(S.class, getOpt_special); }*/ static Map getOpt_getFieldMap(Object o) { Class c = _getClass(o); HashMap map = getOpt_cache.get(c); if (map == null) map = getOpt_makeCache(c); return map; } static Object getOpt_cached(Object o, String field) { try { if (o == null) return null; Map map = getOpt_getFieldMap(o); if (map == getOpt_special) { if (o instanceof Class) return getOpt((Class) o, field); /*if (o instanceof S) ret getOpt(getBot((S) 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 syncMapGet2(((DynamicObject) o).fieldValues, field); return null; } catch (Exception __e) { throw rethrow(__e); } } // used internally - we are in synchronized block 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()) { makeAccessible(f); 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; } 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; } static boolean rectContains(int x1, int y1, int w, int h, Pt p) { return p.x >= x1 && p.y >= y1 && p.x < x1+w && p.y < y1+h; } static boolean rectContains(Rect a, Rect b) { return b.x >= a.x && b.y >= a.y && b.x2() <= a.x2() && b.y2() <= a.y2(); } static boolean rectContains(Rect a, Rectangle b) { return rectContains(a, toRect(b)); } static boolean rectContains(Rect a, int x, int y) { return a != null && a.contains(x, y); } static boolean rectContains(Rect a, Pt p) { return a != null && p != null && a.contains(p); } static String getType(Object o) { return getClassName(o); } static long getFileSize(String path) { return path == null ? 0 : new File(path).length(); } static long getFileSize(File f) { return f == null ? 0 : f.length(); } static Map castMapToMapO(Map map) { return map; } static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static boolean emptyString(String s) { return s == null || s.length() == 0; } // TODO: extended multi-line strings static int javaTok_n, javaTok_elements; static boolean javaTok_opt = false; static List javaTok(String s) { ++javaTok_n; ArrayList tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0; while (i < l) { int j = i; char c, d; // scan for whitespace while (j < l) { c = s.charAt(j); d = j+1 >= l ? '\0' : s.charAt(j+1); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (c == '/' && d == '*') { do ++j; while (j < l && !regionMatches(s, j, "*/")); j = Math.min(j+2, l); } else if (c == '/' && d == '/') { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(javaTok_substringN(s, i, j)); i = j; if (i >= l) break; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace // Special JavaX syntax: 'identifier 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 == '\'') { // allow multi-line strings, but not for ' ++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) == '\'')); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else if (c == '[' && d == '[') { do ++j; while (j < l && !regionMatches(s, j, "]]")); j = Math.min(j+2, l); } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !regionMatches(s, j, "]=]")); j = Math.min(j+3, l); } else ++j; tok.add(javaTok_substringC(s, i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static List javaTok(List tok) { return javaTokWithExisting(join(tok), tok); } static int jfind(String s, String in) { return jfind(javaTok(s), in); } static int jfind(List tok, String in) { return jfind(tok, 1, in); } static int jfind(List tok, int startIdx, String in) { return jfind(tok, startIdx, in, (ITokCondition) null); } static int jfind(List tok, String in, Object condition) { return jfind(tok, 1, in, condition); } static int jfind(List tok, String in, IIntPred condition) { return jfind(tok, 1, in, condition); } static int jfind(List tok, int startIndex, String in, IIntPred condition) { return jfind(tok, startIndex, in, tokCondition(condition)); } static int jfind(List tok, String in, ITokCondition condition) { return jfind(tok, 1, in, condition); } static int jfind(List tok, int startIndex, String in, ITokCondition condition) { return jfind(tok, startIndex, in, (Object) condition); } static int jfind(List tok, int startIdx, String in, Object condition) { //LS tokin = jfind_preprocess(javaTok(in)); return jfind(tok, startIdx, javaTokForJFind_array(in), condition); } // assumes you preprocessed tokin static int jfind(List tok, List tokin) { return jfind(tok, 1, tokin); } static int jfind(List tok, int startIdx, List tokin) { return jfind(tok, startIdx, tokin, null); } static int jfind(List tok, int startIdx, String[] tokinC, Object condition) { return findCodeTokens(tok, startIdx, false, tokinC, condition); } static int jfind(List tok, int startIdx, List tokin, Object condition) { return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition); } 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; } static String joinSubList(List l, int i, int j) { return join(subList(l, i, j)); } static String joinSubList(List l, int i) { return join(subList(l, i)); } 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; } static String hopeningTag(String tag, Map params) { return hopeningTag(tag, mapToParams(params)); } static String hopeningTag(String tag, Object... params) { StringBuilder buf = new StringBuilder(); buf.append("<" + tag); params = unrollParams(params); for (int i = 0; i < l(params); i += 2) { String name = (String) get(params, i); Object val = get(params, i+1); if (nempty(name) && val != null) { if (eqOneOf(val, html_valueLessParam(), true)) buf.append(" " + name); else { String s = str(val); if (!empty(s)) buf.append(" " + name + "=" + htmlQuote(s)); } } } buf.append(">"); return str(buf); } static String strOrEmpty(Object o) { return o == null ? "" : str(o); } // TODO: check validity static String extractYouTubeID(String s) { if (empty(s)) return null; int i = indexOfAfter(s, "youtu.be/"); if (i >= 0) return substring(s, i); s = substring(s, indexOf(s, '?')+1); try { String __1 = mapGet(decodeHQuery(s), "v"); if (!empty(__1)) return __1; } catch (Throwable _e) {} return s; } static int max(int a, int b) { return Math.max(a, b); } static int max(int a, int b, int c) { return max(max(a, b), c); } static long max(int a, long b) { return Math.max((long) a, b); } static long max(long a, long b) { return Math.max(a, b); } static double max(int a, double b) { return Math.max((double) a, b); } static float max(float a, float b) { return Math.max(a, b); } static double max(double a, double b) { return Math.max(a, b); } static > A max (Iterable l) { A max = null; var it = iterator(l); if (it.hasNext()) { max = it.next(); while (it.hasNext()) { A a = it.next(); if (cmp(a, max) > 0) max = a; } } return max; } /*Nah. static int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); ret x; }*/ 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; } 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; } static byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } static short max(short[] c) { short x = -0x8000; for (short d : c) if (d > x) x = d; return x; } static int max(int[] c) { int x = Integer.MIN_VALUE; for (int d : c) if (d > x) x = d; return x; } static > A max(A a, A b) { return cmp(a, b) >= 0 ? a : b; } static boolean containsNulls(Collection c) { return contains(c, null); } static Map similarEmptyMap(Map m) { if (m instanceof TreeMap) return new TreeMap(((TreeMap) m).comparator()); if (m instanceof LinkedHashMap) return new LinkedHashMap(); // default to a hash map return new HashMap(); } static Map similarEmptyMap(Iterable m) { if (m instanceof TreeSet) return new TreeMap(((TreeSet) m).comparator()); if (m instanceof LinkedHashSet) return new LinkedHashMap(); return new HashMap(); } static int min(int a, int b) { return Math.min(a, b); } static long min(long a, long b) { return Math.min(a, b); } static float min(float a, float b) { return Math.min(a, b); } static float min(float a, float b, float c) { return min(min(a, b), c); } static double min(double a, double b) { return Math.min(a, b); } static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } static float min(float[] c) { float x = Float.MAX_VALUE; for (float d : c) x = Math.min(x, d); return x; } static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } static short min(short[] c) { short x = 0x7FFF; for (short d : c) if (d < x) x = d; return x; } static int min(int[] c) { int x = Integer.MAX_VALUE; for (int d : c) if (d < x) x = d; return x; } static > A min(A a, A b) { return cmp(a, b) <= 0 ? a : b; } static Map newWeakHashMap() { return _registerWeakMap(synchroMap(new WeakHashMap())); } static void newPing() { var tl = newPing_actionTL(); Runnable action = tl == null ? null : tl.get(); { if (action != null) action.run(); } } // TODO: test if android complains about this static boolean isAWTThread() { if (isAndroid()) return false; if (isHeadless()) return false; return isAWTThread_awt(); } static boolean isAWTThread_awt() { return SwingUtilities.isEventDispatchThread(); } static void failIfUnlicensed() { assertTrue("license off", licensed()); } static BetterThreadLocal pingSource_tl_var = new BetterThreadLocal() { @Override public PingSource initialValue() { return ping_v3_pingSourceMaker().get(); } }; static BetterThreadLocal pingSource_tl() { return pingSource_tl_var; } static CloseableIterableIterator linesFromFile(File f) { return linesFromFile(f, null); } static CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) { try { if (!fileExists(f)) return emptyCloseableIterableIterator(); if (ewic(f.getName(), ".gz")) return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder); return linesFromReader(utf8bufferedReader(f), resourceHolder); } catch (Exception __e) { throw rethrow(__e); } } static CloseableIterableIterator linesFromFile(String path) { return linesFromFile(path, null); } static CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) { return linesFromFile(newFile(path), resourceHolder); } static Boolean isHeadless_cache; static boolean isHeadless() { if (isHeadless_cache != null) return isHeadless_cache; if (isAndroid()) return isHeadless_cache = true; if (GraphicsEnvironment.isHeadless()) return isHeadless_cache = true; // Also check if AWT actually works. // If DISPLAY variable is set but no X server up, this will notice. try { SwingUtilities.isEventDispatchThread(); return isHeadless_cache = false; } catch (Throwable e) { return isHeadless_cache = true; } } static Font typeWriterFont() { return typeWriterFont(iround(14*getSwingFontScale())); } static Font typeWriterFont(int size) { return new Font(localCourierFontName(), Font.PLAIN, size); } static A typeWriterFont(A c) { return withTypeWriterFont(c); } static void consoleFont(Font font) { callOpt(getConsoleTextArea_gen(), "setFont", font); } static void consoleInputFont(final Font f) { { swing(() -> { JTextField input = consoleInputField(); if (input != null) { input.setFont(f); revalidateFrame(input); } }); } } static boolean odd(int i) { return (i & 1) != 0; } static boolean odd(long i) { return (i & 1) != 0; } static boolean odd(BigInteger i) { return odd(toInt(i)); } static A lookupOrKeep(Map map, A key) { return map != null && map.containsKey(key) ? map.get(key) : key; } static String span(Object contents, Object... params) { return hfulltag("span", contents, params); } static String span() { return span(""); } static String replacePrefix(String prefix, String replacement, String s) { if (!startsWith(s, prefix)) return s; return replacement + substring(s, l(prefix)); } static String sourceCodeToHTML_noEncode(String html) { return "
" + html + "
"; } static String htmlencode2(String s) { return htmlencode_noQuotes(s); } static boolean neqic(String a, String b) { return !eqic(a, b); } static boolean neqic(char a, char b) { return !eqic(a, b); } static
A[] dropLast(A[] a) { return dropLast(a, 1); } static A[] dropLast(A[] a, int n) { if (a == null) return null; n = Math.min(n, a.length); A[] b = arrayOfSameType(a, a.length-n); System.arraycopy(a, 0, b, 0, b.length); return b; } static List dropLast(List l) { return subList(l, 0, l(l)-1); } static List dropLast(int n, List l) { return subList(l, 0, l(l)-n); } static List dropLast(Iterable l) { return dropLast(asList(l)); } static String dropLast(String s) { return substring(s, 0, l(s)-1); } static String dropLast(String s, int n) { return substring(s, 0, l(s)-n); } static String dropLast(int n, String s) { return dropLast(s, n); } static Iterator iterator(Iterable c) { return c == null ? emptyIterator() : c.iterator(); } static String fsI(String id) { return formatSnippetID(id); } static String fsI(long id) { return formatSnippetID(id); } static boolean isURL(String s) { return startsWithOneOf(s, "http://", "https://", "file:"); } public static long parseSnippetID(String snippetID) { long id = Long.parseLong(shortenSnippetID(snippetID)); if (id == 0) throw fail("0 is not a snippet ID"); return id; } static boolean isImageServerSnippet(long id) { return id >= 1100000 && id < 1200000; } static String imageServerLink(String md5OrID) { if (possibleMD5(md5OrID)) return "https://botcompany.de/images/md5/" + md5OrID; return imageServerLink(parseSnippetID(md5OrID)); } static String imageServerLink(long id) { return "https://botcompany.de/images/" + id; } static List antiFilter(Iterable c, Object pred) { if (pred instanceof F1) return antiFilter(c, (F1) pred); List x = new ArrayList(); if (c != null) for (Object o : c) if (!isTrue(callF(pred, o))) x.add(o); return x; } static List antiFilter(Object pred, Iterable c) { return antiFilter(c, pred); } static List antiFilter(Object pred, Object[] c) { return antiFilter(pred, wrapArrayAsList(c)); } static List antiFilter(Iterable c, F1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } static List antiFilter(F1 pred, Iterable c) { return antiFilter(c, pred); } static List antiFilter(Iterable c, IF1 pred) { List x = new ArrayList(); if (c != null) for (B o : c) if (!pred.get(o).booleanValue()) x.add(o); return x; } static List antiFilter(IF1 pred, Iterable c) { return antiFilter(c, pred); } static int lCharSequence(CharSequence s) { return s == null ? 0 : s.length(); } static boolean checkCondition(Object condition, Object... args) { return isTrue(callF(condition, args)); } static boolean checkCondition(IF1 condition, A arg) { return isTrue(callF(condition, arg)); } static Map compileRegexp_cache = syncMRUCache(10); 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; } static String strOrNull(Object o) { return o == null ? null : str(o); } static String himg(String src, Object... params) { return tag("img", "", arrayPlus(params, "src", isSnippetID(src) ? snippetImageLink(src) : src)); } static String himg(BufferedImage img, Object... params) { return himg(dataURL(jpegMimeType(), toJPEG(img)), params); } static boolean isAbsoluteURL(String s) { return isURL(s); } // does not detect relative urls starting with a letter static boolean isRelativeURL(String s) { return startsWithOneOf(s, "/", "./", "../"); } static int getIndentOfLine(String s) { int i = 0, n = l(s); while (i < n && s.charAt(i) == ' ') ++i; return i; } // drop opening and closing tag, return new CNC static List contentsOfContainerTag(List tok) { return tok == null ? null : subList(tok, 2, l(tok)-2); } static List contentsOfContainerTag(List tok, String tagName) { return contentsOfContainerTag(first(findContainerTag(tok, tagName))); } // tok must come from htmlTok // returns all container tags found (including content) as CNC // should be OK for both HTML and XML 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(subList(tok, i-1, j+2)); // actual CNC break; } } i = j; } return l; } static List> findContainerTag(String html, String tag) { return findContainerTag(htmlTok(html), tag); } static boolean htmlCheckParams(String tag, Object... params) { return checkFields(htmlgetparams(tag), params); } static A second(List l) { return get(l, 1); } 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; } static A second(A[] bla) { return bla == null || bla.length <= 1 ? null : bla[1]; } static B second(Pair p) { return p == null ? null : p.b; } static char second(String s) { return charAt(s, 1); } // TODO: process CDATA, scripts static List htmlcoarsetok(String s) { List tok = new ArrayList(); int l = s == null ? 0 : s.length(); int i = 0; while (i < l) { int j = i; char c; // scan for non-tags while (j < l) { if (s.charAt(j) != '<') // regular character ++j; else if (s.substring(j, Math.min(j+4, l)).equals("")); j = Math.min(j+3, l); } else { char d = charAt(s, j+1); // character after < if (d == '/' || isLetter(d)) // it's a tag break; else ++j; } } tok.add(s.substring(i, j)); // add non-tag content i = j; if (i >= l) break; c = s.charAt(i); // scan over tag if (c == '<') { ++j; while (j < l && s.charAt(j) != '>') ++j; // TODO: strings in tag? if (j < l) ++j; } tok.add(s.substring(i, j)); // add tag i = j; } if ((tok.size() & 1) == 0) tok.add(""); return tok; } static Set> _entrySet(Map map) { return map == null ? Collections.EMPTY_SET : map.entrySet(); } static String unnullForIteration(String s) { return s == null ? "" : s; } static Collection unnullForIteration(Collection l) { return l == null ? immutableEmptyList() : l; } static List unnullForIteration(List l) { return l == null ? immutableEmptyList() : l; } static byte[] unnullForIteration(byte[] l) { return l == null ? emptyByteArray() : l; } static int[] unnullForIteration(int[] l) { return l == null ? emptyIntArray() : l; } static char[] unnullForIteration(char[] l) { return l == null ? emptyCharArray() : l; } static double[] unnullForIteration(double[] l) { return l == null ? emptyDoubleArray() : l; } static short[] unnullForIteration(short[] l) { return l == null ? emptyShortArray() : l; } static Map unnullForIteration(Map l) { return l == null ? immutableEmptyMap() : l; } static Iterable unnullForIteration(Iterable i) { return i == null ? immutableEmptyList() : i; } static A[] unnullForIteration(A[] a) { return a == null ? (A[]) emptyObjectArray() : a; } static BitSet unnullForIteration(BitSet b) { return b == null ? new BitSet() : b; } static Pt unnullForIteration(Pt p) { return p == null ? new Pt() : p; } //ifclass Symbol static Symbol unnullForIteration(Symbol s) { return s == null ? emptySymbol() : s; } //endif static Pair unnullForIteration(Pair p) { return p != null ? p : new Pair(null, null); } static long unnullForIteration(Long l) { return l == null ? 0L : l; } static List replaceSubList(List l, List x, List y) { return replaceSublist(l, x, y); } static List replaceSubList(List l, int fromIndex, int toIndex, List y) { return replaceSublist(l, fromIndex, toIndex, y); } static ArrayList cloneList(Iterable l) { return l instanceof Collection ? cloneList((Collection) l) : asList(l); } static ArrayList cloneList(Collection l) { if (l == null) return new ArrayList(); synchronized(collectionMutex(l)) { return new ArrayList(l); } } static ArrayList litlist(A... a) { ArrayList l = new ArrayList(a.length); for (A x : a) l.add(x); return l; } static String htmlencode_forParams_v2(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 == '&') { out.append("&#"); out.append((int) c); out.append(';'); } else out.append(c); } return out.toString(); } static long psI(String snippetID) { return parseSnippetID(snippetID); } static String div(Object contents, Object... params) { return hdiv(contents, params); } static String div() { return hdiv(); } static BigInteger div(BigInteger a, BigInteger b) { return a.divide(b); } static BigInteger div(BigInteger a, int b) { return a.divide(bigint(b)); } static Complex div(Complex a, double b) { return new Complex(a.re/b, a.im/b); } static double div(double a, double b) { return a/b; } static double div(double a, int b) { return a/b; } static long div(long a, long b) { return a/b; } static int div(int a, int b) { return a/b; } 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 "); } static String hreconnectingWebSockets() { return hjavascript_src_snippet(hreconnectingWebSockets_snippetID()); } static String hjavascript(String scriptOrURL, Object... __) { if (isRelativeOrAbsoluteURL(scriptOrURL) && !startsWithOneOf(scriptOrURL, "//", "/*")) return hjavascript_src(scriptOrURL, __); else return tag("script", scriptOrURL, paramsPlus(__, "type" , "text/javascript")); } 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 "; } static int subBot_currentPort() { return toInt(getOpt(subBot_httpd(), "myPort")); } 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); } static B mapGet(Map map, A a) { return map == null || a == null ? null : map.get(a); } static B mapGet(A a, Map map) { return map == null || a == null ? null : map.get(a); } static RuntimeException asRuntimeException(Throwable t) { if (t instanceof Error) _handleError((Error) t); return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t); } static int sixteenToNine(int w) { return iround(w*9.0/16); } static String iframe(String url, Object... params) { return hfulltag("iframe", "", arrayPlus(params, "src" , url)); } static String appendQueryToURL(String url, Map params) { if (url == null) return null; String data = makePostData(params); if (empty(data)) return url; int idx = smartIndexOf(url, '#'); String url2 = takeFirst(url, idx); return url2 + (url2.contains("?") ? "&" : "?") + data + substring(url, idx); } static String appendQueryToURL(String url, Object... data) { return appendQueryToURL(url, paramsToMap(data)); } static Object html_valueLessParam_cache; static Object html_valueLessParam() { if (html_valueLessParam_cache == null) html_valueLessParam_cache = html_valueLessParam_load(); return html_valueLessParam_cache;} static Object html_valueLessParam_load() { return new Object(); } static int[] emptyIntArray_a = new int[0]; static int[] emptyIntArray() { return emptyIntArray_a; } static char[] emptyCharArray = new char[0]; static char[] emptyCharArray() { return emptyCharArray; } static double[] emptyDoubleArray = new double[0]; static double[] emptyDoubleArray() { return emptyDoubleArray; } static float[] emptyFloatArray = new float[0]; static float[] emptyFloatArray() { return emptyFloatArray; } static Map emptyMap() { return new HashMap(); } static Object[] emptyObjectArray_a = new Object[0]; static Object[] emptyObjectArray() { return emptyObjectArray_a; } static Symbol emptySymbol_value; static Symbol emptySymbol() { if (emptySymbol_value == null) emptySymbol_value = symbol(""); return emptySymbol_value; } static Charset utf8charset_cache; static Charset utf8charset() { if (utf8charset_cache == null) utf8charset_cache = utf8charset_load(); return utf8charset_cache;} static Charset utf8charset_load() { return Charset.forName("UTF-8"); } static String actualUserHome_value; static String actualUserHome() { if (actualUserHome_value == null) { if (isAndroid()) actualUserHome_value = "/storage/emulated/0/"; else actualUserHome_value = System.getProperty("user.home"); } return actualUserHome_value; } static File actualUserHome(String sub) { return newFile(new File(actualUserHome()), sub); } static boolean endsWith(String a, String b) { return a != null && a.endsWith(b); } static boolean endsWith(String a, char c) { return nempty(a) && lastChar(a) == c; } 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; } static boolean regionMatchesIC(String a, int offsetA, String b, int offsetB, int len) { return a != null && a.regionMatches(true, offsetA, b, offsetB, len); } 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) { // TODO: varargs 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); // try varargs 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); } } static ThreadLocal pcallPolicyForThread_tl_tl = new ThreadLocal(); static ThreadLocal pcallPolicyForThread_tl() { return pcallPolicyForThread_tl_tl; } static PCallPolicy defaultPCallPolicy = __1 -> printStackTrace(__1); static PCallPolicy defaultPCallPolicy() { return defaultPCallPolicy; } static void defaultPCallPolicy_set(PCallPolicy policy) { defaultPCallPolicy = policy; } static Map mapPlus(Map m, Object... data) { m = cloneMap(m); litmap_impl(m, data); return m; } static Object[] assertEvenLength(Object[] a) { assertTrue(even(l(a))); return a; } static LinkedHashMap paramsToOrderedMap(Object... params) { return asLinkedHashMap(paramsToMap(params)); } static Object[] mapToParams(Map map) { return mapToObjectArray(map); } static List takeFirst(List l, int n) { return l(l) <= n ? l : newSubListOrSame(l, 0, n); } static List takeFirst(int n, List l) { return takeFirst(l, n); } static String takeFirst(int n, String s) { return substring(s, 0, n); } static String takeFirst(String s, int n) { return substring(s, 0, n); } static CharSequence takeFirst(int n, CharSequence s) { return subCharSequence(s, 0, n); } static List takeFirst(int n, Iterator it) { if (it == null) return null; List l = new ArrayList(); for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) { if (it.hasNext()) l.add(it.next()); else break; } return l; } static List takeFirst(int n, Iterable i) { if (i == null) return null; return i == null ? null : takeFirst(n, i.iterator()); } static List takeFirst(int n, IterableIterator i) { return takeFirst(n, (Iterator) i); } static int[] takeFirst(int n, int[] a) { return takeFirstOfIntArray(n, a); } static short[] takeFirst(int n, short[] a) { return takeFirstOfShortArray(n, a); } static byte[] takeFirst(int n, byte[] a) { return takeFirstOfByteArray(n, a); } static byte[] takeFirst(byte[] a, int n) { return takeFirstOfByteArray(n, a); } static double[] takeFirst(int n, double[] a) { return takeFirstOfDoubleArray(n, a); } static double[] takeFirst(double[] a, int n) { return takeFirstOfDoubleArray(n, a); } static String addLineBreak(String s) { return addSuffix(s, "\n"); } static long sysNow() { ping(); return System.nanoTime()/1000000; } static long toMS(double seconds) { return (long) (seconds*1000); } static long toMS(Duration d) { return d == null ? 0 : d.toMillis(); } static boolean isTrue_call(Object o, String method, Object... args) { return isTrue(call(o, method, args)); } static Object mainMainClass() { return getMainMainClass(); } static Object serveByteArray(byte[] data, String mimeType) { return subBot_serveByteArray(data, mimeType); } static volatile Object isAllowed_function; // func(S, O[]) -> bool static volatile boolean isAllowed_all = true; static boolean isAllowed(String askingMethod, Object... args) { // check on VM level Object f = vm_generalMap_get("isAllowed_function"); if (f != null && !isTrue(callF(f, askingMethod, args))) return false; // check locally return isAllowed_all || isTrue(callF(isAllowed_function, askingMethod, args)); } static Throwable getInnerException(Throwable e) { if (e == null) return null; while (e.getCause() != null) e = e.getCause(); return e; } static Throwable getInnerException(Runnable r) { return getInnerException(getException(r)); } static String baseClassName(String className) { return substring(className, className.lastIndexOf('.')+1); } static String baseClassName(Object o) { return baseClassName(getClassName(o)); } static String prependIfNempty(String prefix, String s) { return empty(s) ? unnull(s) : prefix + s; } static File getProgramFile(String progID, String fileName) { if (new File(fileName).isAbsolute()) return new File(fileName); return new File(getProgramDir(progID), fileName); } static File getProgramFile(String fileName) { return getProgramFile(getProgramID(), fileName); } static String hmsWithColons() { return hmsWithColons(now()); } static String hmsWithColons(long time) { return new SimpleDateFormat("HH:mm:ss").format(time); } static boolean startsWithOneOf(String s, String... l) { for (String x : l) if (startsWith(s, x)) return true; return false; } static boolean startsWithOneOf(String s, Matches m, String... l) { for (String x : l) if (startsWith(s, x, m)) return true; return false; } static String getComputerID_quick() { return computerID(); } static Map vm_generalMap_map; static Map vm_generalMap() { if (vm_generalMap_map == null) vm_generalMap_map = (Map) get(javax(), "generalMap"); return vm_generalMap_map; } static Object vm_generalMap_get(Object key) { return vm_generalMap().get(key); } static Object vm_generalMap_put(Object key, Object value) { return mapPutOrRemove(vm_generalMap(), key, value); } static Map synchroMap() { return synchroHashMap(); } static Map synchroMap(Map map) { return Collections.synchronizedMap(map); } static int gzInputStream_defaultBufferSize = 65536; static GZIPInputStream gzInputStream(File f) { try { return gzInputStream(new FileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static GZIPInputStream gzInputStream(File f, int bufferSize) { try { return gzInputStream(new FileInputStream(f), bufferSize); } catch (Exception __e) { throw rethrow(__e); } } static GZIPInputStream gzInputStream(InputStream in) { return gzInputStream(in, gzInputStream_defaultBufferSize); } static GZIPInputStream gzInputStream(InputStream in, int bufferSize) { try { return _registerIOWrap(new GZIPInputStream(in, gzInputStream_defaultBufferSize), in); } catch (Exception __e) { throw rethrow(__e); } } static String unquoteSingleOrDoubleQuotes(String s) { if (s == null) return null; 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); // Octal escape? 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; // Hex Unicode: u???? 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; // added by Stefan } i++; } sb.append(ch); } return sb.toString(); } } return s; // not quoted - return original } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len*2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs+i]); stringBuilder.append(s.substring(s.length()-2, s.length())); } return stringBuilder.toString(); } static Class javax() { return getJavaX(); } static int boolToInt(boolean b) { return b ? 1 : 0; } 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 proxy_InvocationHandler(target)); } static A proxy(Object target, Class intrface) { return proxy(intrface, target); } static A println(A a) { return print(a); } 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); } } static void _registerIO(Object object, String path, boolean opened) { } // closes the input stream too. static void stream2file(InputStream in, File out) { try { mkdirsForFile(out); FileOutputStream fos = new FileOutputStream(out); copyStream(in, fos); in.close(); fos.close(); } catch (Exception __e) { throw rethrow(__e); } } static File loadBinarySnippet(String snippetID) { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); return loadBinarySnippet_noResourceLoader(snippetID); } static File loadBinarySnippet_noResourceLoader(String snippetID) { try { long id = parseSnippetID(snippetID); if (isImageServerSnippet(id)) return loadImageAsFile(snippetID); File f = DiskSnippetCache_getLibrary(id); if (fileSize(f) == 0) f = loadDataSnippetToFile_noResourceLoader(snippetID); return f; } catch (Exception __e) { throw rethrow(__e); } } static List _registerDangerousWeakMap_preList; static A _registerDangerousWeakMap(A map) { return _registerDangerousWeakMap(map, null); } 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) { // We're in class init if (_registerDangerousWeakMap_preList == null) _registerDangerousWeakMap_preList = synchroList(); _registerDangerousWeakMap_preList.add(pair(map, init)); return map; } call(javax(), "_registerDangerousWeakMap", map, init); return map; } static void _onLoad_registerDangerousWeakMap() { assertNotNull(javax()); if (_registerDangerousWeakMap_preList == null) return; for (Pair p : _registerDangerousWeakMap_preList) _registerDangerousWeakMap(p.a, p.b); _registerDangerousWeakMap_preList = null; } static Throwable getExceptionCause(Throwable e) { Throwable c = e.getCause(); return c != null ? c : e; } static List classNames(Collection l) { return getClassNames(l); } static List classNames(Object[] l) { return getClassNames(asList(l)); } 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); } static boolean methodIsStatic(Method m) { return (m.getModifiers() & Modifier.STATIC) != 0; } static boolean argumentCompatibleWithType(Object arg, Class type) { return arg == null ? !type.isPrimitive() : isInstanceX(type, arg); } static void arraycopy(Object[] a, Object[] b) { if (a != null && b != null) arraycopy(a, 0, b, 0, Math.min(a.length, b.length)); } static void arraycopy(Object src, int srcPos, int destPos, int n) { arraycopy(src, srcPos, src, destPos, n); } static void arraycopy(Object src, int srcPos, Object dest, int destPos, int n) { if (n != 0) System.arraycopy(src, srcPos, dest, destPos, n); } static String joinWithComma(Iterable c) { return join(", ", c); } static String joinWithComma(Object... c) { return join(", ", c); } static String joinWithComma(String... c) { return join(", ", c); } static String joinWithComma(Pair p) { return p == null ? "" : joinWithComma(str(p.a), str(p.b)); } static Object sleepQuietly_monitor = new Object(); static void sleepQuietly() { try { assertFalse(isAWTThread()); synchronized(sleepQuietly_monitor) { sleepQuietly_monitor.wait(); } } catch (Exception __e) { throw rethrow(__e); } } static String roundBracket(String s) { return "(" + s + ")"; } static String roundBracket(Object s) { return roundBracket(str(s)); } static PersistableThrowable persistableThrowable(Throwable e) { return e == null ? null : new PersistableThrowable(e); } static Object pcallF_minimalExceptionHandling(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable e) { System.out.println(getStackTrace(e)); _storeException(e); } return null; } static Set vm_generalIdentityHashSet(Object name) { synchronized(vm_generalMap()) { Set set = (Set) (vm_generalMap_get(name)); if (set == null) vm_generalMap_put(name, set = syncIdentityHashSet()); return set; } } static Map vm_generalHashMap(Object name) { synchronized(vm_generalMap()) { Map m = (Map) (vm_generalMap_get(name)); if (m == null) vm_generalMap_put(name, m = syncHashMap()); return m; } } static void clear(Collection c) { if (c != null) c.clear(); } static void clear(Map map) { if (map != null) map.clear(); } static void put(Map map, A a, B b) { if (map != null) map.put(a, b); } static void put(List l, int i, A a) { if (l != null && i >= 0 && i < l(l)) l.set(i, a); } static Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; // could optimize this } } static Class _getClass(Object o) { return o == null ? null : o instanceof Class ? (Class) o : o.getClass(); } static Class _getClass(Object realm, String name) { try { return classLoaderForObject(realm).loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; // could optimize this } } static B syncMapGet2(Map map, A a) { if (map == null) return null; synchronized(collectionMutex(map)) { return map.get(a); } } static B syncMapGet2(A a, Map map) { return syncMapGet2(map, a); } static boolean isSubtypeOf(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); // << always hated that method, let's replace it! } static Set reflection_classesNotToScan_value = litset( "jdk.internal.loader.URLClassPath" ); static Set reflection_classesNotToScan() { return reflection_classesNotToScan_value; } static Rect toRect(Rectangle r) { return r == null ? null : new Rect(r); } static Rect toRect(RectangularShape r) { return r == null ? null : toRect(r.getBounds()); } static Rect toRect(Rect r) { return r; } static boolean regionMatches(String a, int offsetA, String b, int offsetB, int len) { return a != null && b != null && a.regionMatches(offsetA, b, offsetB, len); } static boolean regionMatches(String a, int offsetA, String b) { return regionMatches(a, offsetA, b, 0, l(b)); } 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); } static String javaTok_substringC(String s, int i, int j) { return s.substring(i, j); } 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; // scan for whitespace 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); // scan for non-whitespace // Special JavaX syntax: 'identifier 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 /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else if (c == '[' && d == '[') { do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]")); j = Math.min(j+2, l); } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]")); j = Math.min(j+3, l); } else ++j; if (n < nExisting && javaTokWithExisting_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static boolean javaTokWithExisting_isCopyable(String t, String s, int i, int j) { return t.length() == j-i && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave } static ITokCondition tokCondition(IIntPred condition) { return condition == null ? null : (tok, nIdx) -> condition.get(nIdx); } static Map javaTokForJFind_array_cache = synchronizedMRUCache(1000); 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; } static int findCodeTokens(List tok, String... tokens) { return findCodeTokens(tok, 1, false, tokens); } static int findCodeTokens(List tok, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, 1, ignoreCase, tokens); } static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String... tokens) { return findCodeTokens(tok, startIdx, ignoreCase, tokens, null); } static HashSet findCodeTokens_specials = lithashset("*", "", "", "", "\\*"); static int findCodeTokens_bails, findCodeTokens_nonbails; static interface findCodeTokens_Matcher { boolean get(String token); } static int findCodeTokens(List tok, int startIdx, boolean ignoreCase, String[] tokens, Object condition) { int end = tok.size()-tokens.length*2+2, nTokens = tokens.length; int i = startIdx | 1; findCodeTokens_Matcher[] matchers = new findCodeTokens_Matcher[nTokens]; IContentsIndexedList2 indexedList = tok instanceof IContentsIndexedList2 ? (IContentsIndexedList2) tok : null; TreeSet indices = null; int indicesOfs = 0; for (int j = 0; j < nTokens; j++) { String p = tokens[j]; findCodeTokens_Matcher matcher; if (p.equals("*")) matcher = t -> true; else if (p.equals("")) matcher = t -> isQuoted(t); else if (p.equals("")) matcher = t -> isIdentifier(t); else if (p.equals("")) matcher = t -> isInteger(t); else if (p.equals("\\*")) matcher = t -> t.equals("*"); else if (ignoreCase) matcher = t -> eqic(p, t); else { matcher = t -> t.equals(p); if (indexedList != null) { TreeSet indices2 = indexedList.indicesOf_treeSetOfHasIndex(p); if (indices2 == null) return -1; if (indices == null || indices2.size() < indices.size()) { // found shorter list indices = indices2; indicesOfs = j; } } } matchers[j] = matcher; } // go over shortest index if (indices != null) { int min = i+indicesOfs*2; SortedSet tailSet = min == 1 ? indices : indices.tailSet(new HasIndex(min)); outer: for (HasIndex h : tailSet) { int idx = h.idx-indicesOfs*2; if (idx >= end) break; for (int j = 0; j < nTokens; j++) try { if (!matchers[j].get(tok.get(idx+j*2))) continue outer; } catch (IndexOutOfBoundsException e) { print("fct indicesOfs=" + indicesOfs + ", h=" + h + ", idx=" + idx); throw e; } if (condition == null || checkTokCondition(condition, tok, idx-1)) return idx; } return -1; } outer: for (; i < end; i += 2) { for (int j = 0; j < nTokens; j++) if (!matchers[j].get(tok.get(i+j*2))) continue outer; if (condition == null || checkTokCondition(condition, tok, i-1)) // pass N index return i; } return -1; } 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; } // syntax 1: replace all occurrences of x in l with y 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; replaceSublist(l, i, i+l(x), y); i += l(y); } return l; } // syntax 2: splice l at fromIndex-toIndex and replace middle part with y static List replaceSublist(List l, int fromIndex, int toIndex, List y) { int n = y.size(), toIndex_new = fromIndex+n; if (toIndex_new < toIndex) { removeSubList(l, toIndex_new, toIndex); copyListPart(y, 0, l, fromIndex, n); } else { copyListPart(y, 0, l, fromIndex, toIndex-fromIndex); if (toIndex_new > toIndex) l.addAll(toIndex, subList(y, toIndex-fromIndex)); } return l; } static Object[] unrollParams(Object[] params) { if (l(params) == 1 && params[0] instanceof Map) return mapToParams((Map) params[0]); return params; } // get purpose 1: access a list/array/map (safer version of x.get(y)) static A get(List l, int idx) { return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null; } // seems to conflict with other signatures /*static B get(Map map, A key) { ret map != null ? map.get(key) : null; }*/ static A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } // default to false static boolean get(boolean[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : false; } // get purpose 2: access a field by reflection or a map 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) { makeAccessible(f); return f.get(o); } if (o instanceof DynamicObject) return getOptDynOnly(((DynamicObject) o), field); } catch (Exception e) { throw asRuntimeException(e); } throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName()); } static Object get_raw(String field, Object o) { return get_raw(o, field); } static Object get_raw(Object o, String field) { try { if (o == null) return null; Field f = get_findField(o.getClass(), field); makeAccessible(f); return f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); makeAccessible(f); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } static Field get_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Field get_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static Object get(String field, Object o) { return get(o, field); } static boolean get(BitSet bs, int idx) { return bs != null && bs.get(idx); } static int indexOfAfter(String a, String b) { int i = indexOf(a, b); return i >= 0 ? i+l(b) : i; } 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; } static List _registerWeakMap_preList; static A _registerWeakMap(A map) { if (javax() == null) { // We're in class init 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; } static void _onLoad_registerWeakMap() { assertNotNull(javax()); if (_registerWeakMap_preList == null) return; for (Object o : _registerWeakMap_preList) _registerWeakMap(o); _registerWeakMap_preList = null; } static x30_pkg.x30_util.BetterThreadLocal newPing_actionTL; static x30_pkg.x30_util.BetterThreadLocal newPing_actionTL() { if (newPing_actionTL == null) newPing_actionTL = vm_generalMap_getOrCreate("newPing_actionTL", () -> { Runnable value = (Runnable) (callF_gen(vm_generalMap_get("newPing_valueForNewThread"))); var tl = new x30_pkg.x30_util.BetterThreadLocal(); tl.set(value); return tl; }); return newPing_actionTL; } static int isAndroid_flag; static boolean isAndroid() { if (isAndroid_flag == 0) isAndroid_flag = System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0 ? 1 : -1; return isAndroid_flag > 0; } static void assertTrue(Object o) { if (!(eq(o, true) /*|| isTrue(pcallF(o))*/)) throw fail(str(o)); } static boolean assertTrue(String msg, boolean b) { if (!b) throw fail(msg); return b; } static boolean assertTrue(boolean b) { if (!b) throw fail("oops"); return b; } static boolean assertTrue(Scorer scorer, boolean b) { scorer.add(b); return b; } static volatile boolean licensed_yes = true; static boolean licensed() { if (!licensed_yes) return false; ping_okInCleanUp(); return true; } static void licensed_off() { licensed_yes = false; } static IF0 ping_v3_pingSourceMaker_cache; static IF0 ping_v3_pingSourceMaker() { if (ping_v3_pingSourceMaker_cache == null) ping_v3_pingSourceMaker_cache = ping_v3_pingSourceMaker_load(); return ping_v3_pingSourceMaker_cache;} static IF0 ping_v3_pingSourceMaker_load() { return or((IF0) vm_generalMap_get("ping_v3_pingSourceMaker"), () -> null); } static boolean fileExists(String path) { return path != null && new File(path).exists(); } static boolean fileExists(File f) { return f != null && f.exists(); } static CloseableIterableIterator emptyCloseableIterableIterator_instance = new CloseableIterableIterator() { public Object next() { throw fail(); } public boolean hasNext() { return false; } }; static CloseableIterableIterator emptyCloseableIterableIterator() { return emptyCloseableIterableIterator_instance; } static CloseableIterableIterator linesFromReader(Reader r) { return linesFromReader(r, null); } static CloseableIterableIterator linesFromReader(Reader r, IResourceHolder resourceHolder) { final BufferedReader br = bufferedReader(r); return holdResource(resourceHolder, iteratorFromFunction_f0_autoCloseable(new F0() { public String get() { try { return readLineFromReaderWithClose(br); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return readLineFromReaderWithClose(br);"; }}, _wrapIOCloseable(r))); } static BufferedReader utf8bufferedReader(InputStream in) { try { return in == null ? null : bufferedReader(_registerIOWrap(new InputStreamReader(in, "UTF-8"), in)); } catch (Exception __e) { throw rethrow(__e); } } static BufferedReader utf8bufferedReader(File f) { try { return utf8bufferedReader(newFileInputStream(f)); } catch (Exception __e) { throw rethrow(__e); } } static int iround(double d) { return (int) Math.round(d); } static int iround(Number n) { return iround(toDouble(n)); } static float getSwingFontScale() { return or((Float) vm_generalMap_get("swingFontScale_value"), 1f); } static String localCourierFontName() { // determined this by trial & error return isLinux() ? "Courier" : "Courier New"; } static A withTypeWriterFont(A c) { return setFont(c, typeWriterFont()); } static Object getConsoleTextArea_gen() { return getOpt(get(getJavaX(), "console"), "textArea"); } static Object swing(Object f) { return swingAndWait(f); } static void swing(Runnable f) { swingAndWait(f); } static A swing(F0 f) { return (A) swingAndWait(f); } static A swing(IF0 f) { return (A) swingAndWait(f); } static JTextField consoleInputField() { Object console = get(getJavaX(), "console"); return (JTextField) getOpt(console, "tfInput"); } static void revalidateFrame(Component c) { revalidate(getFrame(c)); } static A[] arrayOfSameType(A[] a, int n) { return newObjectArrayOfSameType(a, n); } static Iterator emptyIterator() { return Collections.emptyIterator(); } static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } static String formatSnippetID(long id) { return "#" + id; } 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); } static boolean possibleMD5(String s) { return isMD5(s); } static List wrapArrayAsList(A[] a) { return a == null ? null : Arrays.asList(a); } static Map syncMRUCache(int size) { return synchroMap(new MRUCache(size)); } public static boolean isSnippetID(String s) { try { parseSnippetID(s); return true; } catch (RuntimeException e) { return false; } } static String dataURL(String mimeType, byte[] data) { return "data:" + mimeType + ";base64," + base64(data); } static String jpegMimeType() { return "image/jpeg"; } static byte[] toJPEG(BufferedImage img) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); // need to drop alpha channel to avoid JDK bug ImageIO.write(dropAlphaChannelFromBufferedImage(img), "jpeg", stream); return stream.toByteArray(); } catch (Exception __e) { throw rethrow(__e); } } static byte[] toJPEG(File f) { return toJPEG(loadImage2(f)); } static boolean isOpeningTag(String token, String tag) { return isTag(token, tag) && !token.endsWith("/>"); } static boolean isOpeningTag(String token) { return token.startsWith("<") && token.endsWith(">") && !token.endsWith("/>") && isLetter(token.charAt(1)); } 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); } static boolean checkFields(Object x, Object... data) { for (int i = 0; i < l(data); i += 2) if (neq(getOpt(x, (String) data[i]), data[i+1])) return false; return true; } static Map htmlgetparams(String tag) { return getHtmlTagParameters(tag); } static char charAt(String s, int i) { return s != null && i >= 0 && i < s.length() ? s.charAt(i) : '\0'; } static boolean isLetter(char c) { return Character.isLetter(c); } static List immutableEmptyList() { return Collections.emptyList(); } static byte[] emptyByteArray_a = new byte[0]; static byte[] emptyByteArray() { return emptyByteArray_a; } static short[] emptyShortArray = new short[0]; static short[] emptyShortArray() { return emptyShortArray; } static Map immutableEmptyMap() { return Collections.emptyMap(); } // TODO: JDK 17!! ?? No! Yes? Yes!! static Object collectionMutex(List l) { return l; } static Object collectionMutex(Object o) { if (o instanceof List) return o; // TODO: actually use our own maps so we can get the mutex properly String c = className(o); return o; } static String hdiv(Object contents, Object... params) { return hfulltag("div", contents, params); } static String hdiv() { return hdiv(""); } static BigInteger bigint(String s) { return new BigInteger(s); } static BigInteger bigint(long l) { return BigInteger.valueOf(l); } static String hjavascript_src_snippet(String snippetID, Object... __) { return hfulltag("script", "", paramsPlus(__, "src" , snippetRawURL(snippetID, "text/javascript"))); } static String hreconnectingWebSockets_snippetID() { return "#2000597"; } static String hjavascript_src(String src, Object... __) { return hfulltag("script", "", paramsPlus(__, "src", src)); } // returns l(s) if not found 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); } static int smartIndexOf(String s, int i, char c) { return smartIndexOf(s, c, i); } 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); } static int smartIndexOf(String s, String sub) { return smartIndexOf(s, sub, 0); } static int smartIndexOf(String s, char c) { return smartIndexOf(s, c, 0); } static int smartIndexOf(List l, A sub) { return smartIndexOf(l, sub, 0); } static int smartIndexOf(List l, int start, A sub) { return smartIndexOf(l, sub, start); } static int smartIndexOf(List l, A sub, int start) { int i = indexOf(l, sub, start); return i < 0 ? l(l) : i; } 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; } static WeakHasherMap symbol_map = new WeakHasherMap(new Hasher() { public int hashCode(Symbol symbol) { return symbol.text.hashCode(); } public boolean equals(Symbol a, Symbol b) { if (a == null) return b == null; return b != null && eq(a.text, b.text); } }); static Symbol symbol(String s) { if (s == null) return null; synchronized(symbol_map) { // TODO: avoid object creation by passing the string to findKey Symbol symbol = new Symbol(s, true); Symbol existingSymbol = symbol_map.findKey(symbol); if (existingSymbol == null) symbol_map.put(existingSymbol = symbol, true); return existingSymbol; } } static Symbol symbol(CharSequence s) { if (s == null) return null; if (s instanceof Symbol) return (Symbol) s; if (s instanceof String) return symbol((String) s); return symbol(str(s)); } static Symbol symbol(Object o) { return symbol((CharSequence) o); } static char lastChar(String s) { return empty(s) ? '\0' : s.charAt(l(s)-1); } static Map cloneMap(Map map) { if (map == null) return new HashMap(); // assume mutex is equal to map synchronized(map) { return map instanceof TreeMap ? new TreeMap((TreeMap) map) // copies comparator : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map); } } static List cloneMap(Iterable l, IF1 f) { List x = emptyList(l); if (l != null) for (A o : cloneList(l)) x.add(f.get(o)); return x; } static LinkedHashMap asLinkedHashMap(Map map) { if (map instanceof LinkedHashMap) return (LinkedHashMap) map; LinkedHashMap m = new LinkedHashMap(); if (map != null) synchronized(collectionMutex(map)) { m.putAll(map); } return m; } static Object[] mapToObjectArray(Map map) { List l = new ArrayList(); for (Object o : keys(map)) { l.add(o); l.add(map.get(o)); } return toObjectArray(l); } static Object[] mapToObjectArray(Object f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static Object[] mapToObjectArray(Object f, Object[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = callF(f, l[i]); return array; } static Object[] mapToObjectArray(Collection l, IF1 f) { return mapToObjectArray(f, l); } static Object[] mapToObjectArray(A[] l, IF1 f) { return mapToObjectArray(f, l); } static Object[] mapToObjectArray(IF1 f, A[] l) { int n = l(l); Object[] array = new Object[n]; for (int i = 0; i < n; i++) array[i] = f.get(l[i]); return array; } static Object[] mapToObjectArray(IF1 f, Collection l) { int n = l(l); Object[] array = new Object[n]; if (n != 0) { Iterator it = iterator(l); for (int i = 0; i < n; i++) array[i] = callF(f, it.next()); } return array; } static List newSubListOrSame(List l, int startIndex) { return newSubListOrSame(l, startIndex, l(l)); } 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)); } static CharSequence subCharSequence(CharSequence s, int x) { return subCharSequence(s, x, s == null ? 0 : s.length()); } static CharSequence subCharSequence(CharSequence s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x >= s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.subSequence(x, y); } static int[] takeFirstOfIntArray(int[] b, int n) { return subIntArray(b, 0, n); } static int[] takeFirstOfIntArray(int n, int[] b) { return takeFirstOfIntArray(b, n); } static short[] takeFirstOfShortArray(short[] b, int n) { return subShortArray(b, 0, n); } static short[] takeFirstOfShortArray(int n, short[] b) { return takeFirstOfShortArray(b, n); } static byte[] takeFirstOfByteArray(byte[] b, int n) { return subByteArray(b, 0, n); } static byte[] takeFirstOfByteArray(int n, byte[] b) { return takeFirstOfByteArray(b, n); } static double[] takeFirstOfDoubleArray(double[] b, int n) { return subDoubleArray(b, 0, n); } static double[] takeFirstOfDoubleArray(int n, double[] b) { return takeFirstOfDoubleArray(b, n); } static String addSuffix(String s, String suffix) { return s == null || s.endsWith(suffix) ? s : s + suffix; } // get main class of first program (for console) static Object getMainMainClass() { Object paa = first((List) call(getJavaX(), "getInjections")); return getOpt(paa, "mainClass"); } static Object subBot_serveByteArray(byte[] data, String mimeType) { return call(mainBot(), "serveByteArray", data, mimeType); } static Throwable getException(Runnable r) { try { callF(r); return null; } catch (Throwable e) { return e; } } static File getProgramDir() { return programDir(); } static File getProgramDir(String snippetID) { return programDir(snippetID); } static String programID; static String getProgramID() { return nempty(programID) ? formatSnippetIDOpt(programID) : "?"; } // TODO: ask JavaX instead static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } static String _computerID; static Lock computerID_lock = lock(); public static String computerID() { if (_computerID == null) { Lock __0 = computerID_lock; lock(__0); try { if (_computerID != null) return _computerID; File file = computerIDFile(); _computerID = loadTextFile(file.getPath()); if (_computerID == null) { // legacy load _computerID = loadTextFile(userDir(".tinybrain/computer-id")); if (_computerID == null) _computerID = makeRandomID(12, new SecureRandom()); saveTextFile(file, _computerID); } } finally { unlock(__0); } } return _computerID; } 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; } static Map synchroHashMap() { return synchronizedMap(new HashMap()); } static A _registerIOWrap(A wrapper, Object wrapped) { return wrapper; } static Class __javax; static Class getJavaX() { try { return __javax; } catch (Exception __e) { throw rethrow(__e); } } static void __setJavaX(Class j) { __javax = j; _onJavaXSet(); } static boolean isInstance(Class type, Object arg) { return type.isInstance(arg); } 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); } } // If you change this, also change DiskSnippetCache_fileToLibID static File DiskSnippetCache_file(long snippetID) { return new File(getGlobalCache(), "data_" + snippetID + ".jar"); } // Data files are immutable, use centralized cache public static File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = DiskSnippetCache_file(snippetID); return file.exists() ? file : null; } public static File DiskSnippetCache_getLibrary(String snippetID) { try { return DiskSnippetCache_getLibrary(psI(snippetID)); } catch (Exception __e) { throw rethrow(__e); } } public static void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(DiskSnippetCache_file(snippetID), data); } static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL(dataSnippetLink(snippetID)); print("Loading library: " + hideCredentials(url)); try { data = loadBinaryPage(url.openConnection()); } catch (RuntimeException e) { data = null; } if (data == null || data.length == 0) { url = new URL(tb_mainServer() + "/blobs/" + parseSnippetID(snippetID)); print("Loading library: " + hideCredentials(url)); data = loadBinaryPage(url.openConnection()); } print("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static long fileSize(String path) { return getFileSize(path); } static long fileSize(File f) { return getFileSize(f); } static File loadDataSnippetToFile(String snippetID) { try { IResourceLoader rl = vm_getResourceLoader(); if (rl != null) return rl.loadLibrary(snippetID); return loadDataSnippetToFile_noResourceLoader(snippetID); } catch (Exception __e) { throw rethrow(__e); } } static File loadDataSnippetToFile_noResourceLoader(String snippetID) { try { snippetID = fsI(snippetID); File f = DiskSnippetCache_file(parseSnippetID(snippetID)); List urlsTried = new ArrayList(); List errors = new ArrayList(); try { URL url = addAndReturn(urlsTried, new URL(dataSnippetLink(snippetID))); print("Loading library: " + hideCredentials(url)); try { loadBinaryPageToFile(openConnection(url), f); if (fileSize(f) == 0) throw fail(); } catch (Throwable e) { errors.add(e); url = addAndReturn(urlsTried, new URL(tb_mainServer() + "/blobs/" + psI(snippetID))); print(e); print("Trying other server: " + hideCredentials(url)); loadBinaryPageToFile(openConnection(url), f); print("Got bytes: " + fileSize(f)); } // TODO: check if we hit the "LOADING" message if (fileSize(f) == 0) throw fail(); System.err.println("Bytes loaded: " + fileSize(f)); } catch (Throwable e) { //printStackTrace(e); errors.add(e); throw fail("Binary snippet " + snippetID + " not found or not public. URLs tried: " + allToString(urlsTried) + ", errors: " + allToString(errors)); } return f; } catch (Exception __e) { throw rethrow(__e); } } static boolean loadBufferedImage_useImageCache = true; static BufferedImage loadBufferedImage(String snippetIDOrURLOrFile) { try { ping(); if (snippetIDOrURLOrFile == null) return null; if (isURL(snippetIDOrURLOrFile)) return imageIO_readURL(snippetIDOrURLOrFile); if (isSnippetID(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(); // fall back to loading from sourceforge } } 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")); //Log.info("Cached image."); } //Log.info("Loaded image."); return image; } else return loadBufferedImage(new File(snippetIDOrURLOrFile)); } catch (Exception __e) { throw rethrow(__e); } } static BufferedImage loadBufferedImage(File file) { return loadBufferedImageFile(file); } static HashMap> callMC_cache = new HashMap(); static String callMC_key; static Method callMC_value; // varargs assignment fixer for a single string array argument static Object callMC(String method, String[] arg) { return callMC(method, new Object[] {arg}); } static Object callMC(String method, Object... args) { try { Method me; if (callMC_cache == null) callMC_cache = new HashMap(); // initializer time workaround 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 arguments (" + joinWithComma(getClasses(args)) + ") found in main"); } catch (Exception __e) { throw rethrow(__e); } } 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) { makeAccessible(m); multiMapPut(callMC_cache, m.getName(), m); } c = c.getSuperclass(); } } } static List synchroList() { return synchroList(new ArrayList()); } static List synchroList(List l) { return Collections.synchronizedList(l); } static A assertNotNull(A a) { assertTrue(a != null); return a; } static A assertNotNull(String msg, A a) { assertTrue(msg, a != null); return a; } static A assertNotNull(Scorer scorer, String msg, A a) { if (scorer == null) return assertNotNull(msg, a); if (a == null) { print("BAD - " + msg + " is null: " + a); scorer.add(false); } else { print("OK, " + msg + " not null: " + a); scorer.add(true); } return a; } 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; } static void assertFalse(Object o) { if (!(eq(o, false) /*|| isFalse(pcallF(o))*/)) throw fail(str(o)); } static boolean assertFalse(boolean b) { if (b) throw fail("oops"); return b; } static boolean assertFalse(String msg, boolean b) { if (b) throw fail(msg); return b; } static Object callFunction(Object f, Object... args) { return callF(f, args); } static Throwable _storeException_value; static void _storeException(Throwable e) { _storeException_value = e; } static Set syncIdentityHashSet() { return (Set) synchronizedSet(identityHashSet()); } static Map syncHashMap() { return synchroHashMap(); } static ClassLoader classLoaderForObject(Object o) { if (o instanceof ClassLoader) return ((ClassLoader) o); if (o == null) return null; return _getClass(o).getClassLoader(); } // Note: This is actually broken. Inner classes must stay with a $ separator static String classNameToVM(String name) { return name.replace(".", "$"); } static HashSet litset(A... items) { return lithashset(items); } static Map synchronizedMRUCache(int maxSize) { return synchroMap(new MRUCache(maxSize)); } static HashSet lithashset(A... items) { HashSet set = new HashSet(); for (A a : items) set.add(a); return set; } // supports the usual quotings (", variable length double brackets) except ' quoting static boolean isQuoted(String s) { if (isNormalQuoted(s)) return true; // use the exact version return isMultilineQuoted(s); } static boolean isIdentifier(String s) { return isJavaIdentifier(s); } static boolean checkTokCondition(Object condition, List tok, int i) { if (condition instanceof TokCondition) return ((TokCondition) condition).get(tok, i); return checkCondition(condition, tok, i); } static int indexOfSubList(List x, List y) { return indexOfSubList(x, y, 0); } 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; } 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; } static void removeSubList(List l, int from, int to) { if (l != null) subList(l, from, to).clear(); } static void removeSubList(List l, int from) { if (l != null) subList(l, from).clear(); } 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)); } static Object getOptDynOnly(DynamicObject o, String field) { if (o == null || o.fieldValues == null) return null; return o.fieldValues.get(field); } static List splitAtAmpersand(String s) { return s == null ? emptyList() : asList(s.split("&")); } static String urldecode(String x) { try { return URLDecoder.decode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static A printException(A e) { printStackTrace(e); return e; } static A vm_generalMap_getOrCreate(Object key, F0 create) { return vm_generalMap_getOrCreate(key, f0ToIF0(create)); } static A vm_generalMap_getOrCreate(Object key, IF0 create) { Map generalMap = vm_generalMap(); if (generalMap == null) return null; // must be x30 init synchronized(generalMap) { // should switch to locks here A a = (A) (vm_generalMap_get(key)); if (a == null) vm_generalMap_put(key, a = create == null ? null : create.get()); return a; } } static A callF_gen(F0 f) { return f == null ? null : f.get(); } static B callF_gen(F1 f, A a) { return f == null ? null : f.get(a); } static A callF_gen(IF0 f) { return f == null ? null : f.get(); } static B callF_gen(IF1 f, A a) { return f == null ? null : f.get(a); } static B callF_gen(A a, IF1 f) { return f == null ? null : f.get(a); } static C callF_gen(IF2 f, A a, B b) { return f == null ? null : f.get(a, b); } static void callF_gen(VF1 f, A a) { { if (f != null) f.get(a); } } static void callF_gen(A a, IVF1 f) { { if (f != null) f.get(a); } } static void callF_gen(IVF1 f, A a) { { if (f != null) f.get(a); } } static Object callF_gen(Runnable r) { { if (r != null) r.run(); } return null; } static Object callF_gen(Object f, Object... args) { return callF(f, args); } static BufferedReader bufferedReader(Reader r) { return bufferedReader(r, 8192); } static BufferedReader bufferedReader(Reader r, int bufSize) { if (r == null) return null; return r instanceof BufferedReader ? (BufferedReader) r : _registerIOWrap(new BufferedReader(r, bufSize), r); } static BufferedReader bufferedReader(File f) { return utf8bufferedReader(f); } static A holdResource(IResourceHolder holder, A a) { { if (holder != null) holder.add(a); } return a; } static CloseableIterableIterator iteratorFromFunction_f0_autoCloseable(final F0 f, final AutoCloseable closeable) { class IFF2 extends CloseableIterableIterator { A a; boolean done = false; public boolean hasNext() { getNext(); return !done; } public A next() { getNext(); if (done) throw fail(); A _a = a; a = null; return _a; } 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(); } static String readLineFromReaderWithClose(BufferedReader r) { try { String s = r.readLine(); if (s == null) r.close(); return s; } catch (Exception __e) { throw rethrow(__e); } } 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); }}; } static FileInputStream newFileInputStream(File path) throws IOException { return newFileInputStream(path.getPath()); } static FileInputStream newFileInputStream(String path) throws IOException { FileInputStream f = new FileInputStream(path); _registerIO(f, path, true); return f; } static double toDouble(Object o) { if (o instanceof Number) return ((Number) o).doubleValue(); if (o instanceof BigInteger) return ((BigInteger) o).doubleValue(); if (o instanceof String) return parseDouble((String) o); if (o == null) return 0.0; throw fail(o); } static Cache isLinux_cache = new Cache<>(() -> isLinux_load()); static boolean isLinux() { return isLinux_cache.get(); } static Boolean isLinux_load() { return !isWindows() && !isMac() && !isAndroid(); } static A setFont(final Font font, final A a) { if (a != null) { swing(() -> { a.setFont(font); }); } return a; } static A setFont(A a, Font font) { return setFont(font, a); } static A setFont(final String fontID, float fontSize, final A a) { return setFont(loadFont_cached(fontID, fontSize), a); } static void swingAndWait(Runnable r) { try { if (isAWTThread()) r.run(); else { r = addThreadInfoToRunnable(r); executingSwingCode(r); EventQueue.invokeAndWait(r); } } catch (Exception __e) { throw rethrow(__e); } } static Object swingAndWait(Object f) { if (isAWTThread()) return callF(f); else { Var result = new Var(); swingAndWait(new Runnable() { public void run() { try { result.set(callF(f)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "result.set(callF(f));"; }}); return result.get(); } } static A revalidate(final A c) { if (c == null || !c.isShowing()) return c; { swing(() -> { // magic combo to actually relayout and repaint c.revalidate(); c.repaint(); }); } return c; } static void revalidate(JFrame f) { revalidate((Component) f); } static void revalidate(JInternalFrame f) { revalidate((Component) f); } static JFrame getFrame(final Object _o) { return swing(new F0() { public JFrame get() { try { Object o = _o; if (o instanceof ButtonGroup) o = first(buttonsInGroup((ButtonGroup) o)); if (!(o instanceof Component)) return null; Component c = (Component) o; while (c != null) { if (c instanceof JFrame) return (JFrame) c; c = c.getParent(); } return null; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button..."; }}); } static A[] newObjectArrayOfSameType(A[] a) { return newObjectArrayOfSameType(a, a.length); } static A[] newObjectArrayOfSameType(A[] a, int n) { return (A[]) Array.newInstance(a.getClass().getComponentType(), n); } static boolean isMD5(String s) { return l(s) == 32 && isLowerHexString(s); } static String base64(byte[] a) { return base64encode(a); } static BufferedImage dropAlphaChannelFromBufferedImage(BufferedImage img) { if (img == null || img.getType() == BufferedImage.TYPE_INT_RGB) return img; int w = img.getWidth(), h = img.getHeight(); BufferedImage newImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); int[] rgb = img.getRGB(0, 0, w, h, null, 0, w); newImage.setRGB(0, 0, w, h, rgb, 0, w); return newImage; } static BufferedImage loadImage2(String snippetIDOrURL) { return loadBufferedImage(snippetIDOrURL); } static BufferedImage loadImage2(File file) { return loadBufferedImage(file); } static boolean getHtmlTagParameters_debug = false; static Map getHtmlTagParameters(String tag) { if (empty(tag)) return null; List tok = codeTokens(tok_joinMinusIdentifiers(htmlFineTok(tag))); if (getHtmlTagParameters_debug) printStruct(tok); assertEquals("<", tok.get(0)); int i = 1; if (eq(tok.get(1), "/")) ++i; String name = tok.get(i++); if (!isMinusIdentifier(name)) throw fail(tag + " (" + name + ")"); Map map = new HashMap(); while (i < l(tok)) { String t = tok.get(i); if (eqOneOf(t, "/", ">")) break; if (!isMinusIdentifier(t)) throw fail(tag + " (" + t + ")"); ++i; String value = "1"; if (eq(tok.get(i), "=")) { ++i; value = htmlunquote(tok.get(i++)); } map.put(t, value); } return map; } static void mapPut(Map map, A key, B value) { if (map != null && key != null && value != null) map.put(key, value); } static void mapPut(Map map, Pair p) { if (map != null && p != null) map.put(p.a, p.b); } // binary legacy signature static Object[] toObjectArray(Collection c) { return toObjectArray((Iterable) c); } static Object[] toObjectArray(Iterable c) { List l = asList(c); return l.toArray(new Object[l.size()]); } static int[] subIntArray(int[] b, int start) { return subIntArray(b, start, l(b)); } static int[] subIntArray(int[] 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 int[0]; int[] x = new int[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static short[] subShortArray(short[] 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 short[0]; short[] x = new short[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static byte[] subByteArray(byte[] b, int start) { return subByteArray(b, start, l(b)); } 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; } static double[] subDoubleArray(double[] b, int start) { return subDoubleArray(b, start, l(b)); } static double[] subDoubleArray(double[] b, int start, int end) { start = max(start, 0); end = min(end, l(b)); if (start == 0 && end == l(b)) return b; if (start >= end) return new double[0]; double[] x = new double[end-start]; System.arraycopy(b, start, x, 0, end-start); return x; } static File programDir_mine; // set this to relocate program's data static File programDir() { return programDir(getProgramID()); } 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; } static File programDir(String snippetID, String subPath) { return new File(programDir(snippetID), subPath); } static String formatSnippetIDOpt(String s) { return isSnippetID(s) ? formatSnippetID(s) : s; } static Class getMainClass() { return mc(); } static Class getMainClass(Object o) { try { if (o == null) return null; if (o instanceof Class && eq(((Class) o).getName(), "x30")) return (Class) o; ClassLoader cl = (o instanceof Class ? (Class) o : o.getClass()).getClassLoader(); if (cl == null) return null; String name = mainClassNameForClassLoader(cl); return loadClassFromClassLoader_orNull(cl, name); } catch (Exception __e) { throw rethrow(__e); } } static void lock(Lock lock) { try { ping(); if (lock == null) return; try { vmBus_send("locking", lock, "thread" , currentThread()); lock.lockInterruptibly(); vmBus_send("locked", lock, "thread" , currentThread()); } catch (InterruptedException e) { Object reason = vm_threadInterruptionReasonsMap().get(currentThread()); print("Locking interrupted! Reason: " + strOr(reason, "Unknown")); printStackTrace(e); rethrow(e); } // NO call to ping here! Make sure lock is always released. } catch (Exception __e) { throw rethrow(__e); } } static void lock(Lock lock, String msg) { print("Locking: " + msg); lock(lock); } static void lock(Lock lock, String msg, long timeout) { print("Locking: " + msg); lockOrFail(lock, timeout); } static ReentrantLock lock() { return fairLock(); } static File computerIDFile() { return javaxDataDir("Basic Info/computer-id.txt"); } static String makeRandomID(int length) { return makeRandomID(length, defaultRandomGenerator()); } 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); } static String makeRandomID(Random r, int length) { return makeRandomID(length, r); } static void unlock(Lock lock, String msg) { if (lock == null) return; lock.unlock(); vmBus_send("unlocked", lock, "thread" , currentThread()); print("Unlocked: " + msg); // print afterwards to make sure the lock is always unlocked } static void unlock(Lock lock) { if (lock == null) return; lock.unlock(); vmBus_send("unlocked", lock, "thread" , currentThread()); } static Map synchronizedMap() { return synchroMap(); } static Map synchronizedMap(Map map) { return synchroMap(map); } static void _onJavaXSet() {} static File imageSnippetCacheFile(String snippetID) { File dir = imageSnippetsCacheDir(); if (!loadBufferedImage_useImageCache) return null; return new File(dir, parseSnippetID(snippetID) + ".png"); } static String snippetImageURL_noHttps(String snippetID) { return snippetImageURL_noHttps(snippetID, "png"); } 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/"); } static File getGlobalCache() { File file = new File(javaxCachesDir(), "Binary Snippets"); file.mkdirs(); return file; } static String dataSnippetLink(String snippetID) { long id = parseSnippetID(snippetID); if (id >= 1100000 && id < 1200000) return imageServerURL() + id; if (id >= 1200000 && id < 1300000) { // Woody files, actually String pw = muricaPassword(); if (empty(pw)) throw fail("Please set 'murica password by running #1008829"); return "https://botcompany.de/files/" + id + "?_pass=" + pw; // XXX, although it typically gets hidden when printing } return fileServerURL() + "/" + id /*+ "?_pass=" + muricaPassword()*/; } static A addAndReturn(Collection c, A a) { if (c != null) c.add(a); return a; } static A addAndReturn(List c, int idx, A a) { if (c != null) c.add(idx, a); return a; } static void loadBinaryPageToFile(String url, File file) { try { print("Loading " + url); loadBinaryPageToFile(openConnection(new URL(url)), file); } catch (Exception __e) { throw rethrow(__e); } } static void loadBinaryPageToFile(URLConnection con, File file) { try { setHeaders(con); loadBinaryPageToFile_noHeaders(con, file); } catch (Exception __e) { throw rethrow(__e); } } static void loadBinaryPageToFile_noHeaders(URLConnection con, File file) { try { assertNotNull(file); File ftemp = new File(f2s(file) + "_temp"); FileOutputStream buf = newFileOutputStream(mkdirsFor(ftemp)); try { InputStream inputStream = con.getInputStream(); long len = 0; try { len = con.getContentLength/*Long*/(); } 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); } } static List allToString(Iterable c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static List allToString(Object[] c) { List l = new ArrayList(); for (Object o : unnull(c)) l.add(str(o)); return l; } static BufferedImage imageIO_readURL(String url) { try { return ImageIO.read(new URL(url)); } catch (Exception __e) { throw rethrow(__e); } } static File imageSnippetsCacheDir() { return javaxCachesDir("Image-Snippets"); } static String snippetImageURL_http(String snippetID) { return snippetImageURL_http(snippetID, "png"); } static String snippetImageURL_http(String snippetID, String contentType) { return replacePrefix("https://", "http://", snippetImageURL(snippetID, contentType)).replace(":8443", ":8080"); } static BufferedImage loadBufferedImageFile(File file) { try { if (!isFile(file)) return null; return ImageIO.read(file); } catch (Exception __e) { throw rethrow(__e); } } static List getClasses(Object[] array) { List l = emptyList(l(array)); for (Object o : array) l.add(_getClass(o)); return l; } 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); } static void multiMapPut(MultiMap mm, A key, B value) { if (mm != null && key != null && value != null) mm.put(key, value); } static Set synchronizedSet() { return synchroHashSet(); } static Set synchronizedSet(Set set) { return Collections.synchronizedSet(set); } static Set identityHashSet() { return Collections.newSetFromMap(new IdentityHashMap()); } 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; } static boolean isMultilineQuoted(String s) { if (!startsWith(s, "[")) return false; int i = 1, n = s.length(); while (i < n && s.charAt(i) == '=') ++i; return i < n && s.charAt(i) == '['; } 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; } static IF0 f0ToIF0(F0 f) { return f == null ? null : () -> f.get(); } static double parseDouble(String s) { return empty(s) ? 0.0 : Double.parseDouble(s); } public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } static boolean isMac() { return System.getProperty("os.name").toLowerCase().contains("mac"); } static Map loadFont_cached_cache = new HashMap(); static synchronized Font loadFont_cached(String snippetID) { try { snippetID = formatSnippetID(snippetID); Font f = loadFont_cached_cache.get(snippetID); if (f == null) loadFont_cached_cache.put(snippetID, f = loadFont(snippetID, 12f)); return f; } catch (Exception __e) { throw rethrow(__e); } } static synchronized Font loadFont_cached(String snippetID, float size) { try { return loadFont_cached(snippetID).deriveFont(size); } catch (Exception __e) { throw rethrow(__e); } } 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);"; }}; } //static event executingSwingCode(Runnable code); static transient Set> onExecutingSwingCode; public static void onExecutingSwingCode(IVF1 f) { onExecutingSwingCode = createOrAddToSyncLinkedHashSet(onExecutingSwingCode, f); } public static void removeExecutingSwingCodeListener(IVF1 f) { main.remove(onExecutingSwingCode, f); } public static void executingSwingCode(Runnable code) { if (onExecutingSwingCode != null) for (var listener : onExecutingSwingCode) pcallF_typed(listener, code); } static List buttonsInGroup(ButtonGroup g) { if (g == null) return ll(); return asList(g.getElements()); } 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') { // ok } else return false; } return true; } 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; // Translate all full groups from byte array elements to Base64 int inCursor = 0; for (int i=0; i> 2]); result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2)&0x3f | (byte2 >> 6)]); result.append(intToAlpha[byte2 & 0x3f]); } // Translate partial group if present 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 { // assert numBytesInPartialGroup == 2; int byte1 = a[inCursor++] & 0xff; result.append(intToAlpha[(byte0 << 4)&0x3f | (byte1 >> 4)]); result.append(intToAlpha[(byte1 << 2)&0x3f]); result.append('='); } } // assert inCursor == a.length; // assert result.length() == resultLen; return result.toString(); } /** * This array is a lookup table that translates 6-bit positive integer * index values into their "Base64 Alphabet" equivalents as specified * in Table 1 of RFC 2045. */ 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', '+', '/' }; static List codeTokens(List tok) { return codeTokensOnly(tok); } static List tok_joinMinusIdentifiers(List tok) { for (int i = 1; i+4 < l(tok); i += 2) if (isMinusIdentifier(get(tok, i)) && eq(get(tok, i+2), "-") && isIdentifier(get(tok, i+4))) { replaceSublist(tok, i, i+5, ll(join(subList(tok, i, i+5)))); i -= 2; } return tok; } static List htmlFineTok(String s) { List tok = new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c, d; // scan for whitespace 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 break; } tok.add(quickSubstring(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); d = i+1 >= l ? '\0' : s.charAt(i+1); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener /*|| s.charAt(j) == '\n'*/) { // allow multi-line strings ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else ++j; tok.add(quickSubstring(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static A printStruct(String prefix, A a) { printStructure(prefix, a); return a; } static A printStruct(A a) { printStructure(a); return a; } static A assertEquals(Object x, A y) { return assertEquals("", x, y); } 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; } static void assertEquals(Scorer scorer, Object x, Object y) { assertEquals(scorer, "", x, y); } static void assertEquals(Scorer scorer, String msg, Object x, Object y) { if (scorer == null) { assertEquals(msg, x, y); return; } scorer.add(eq(x, y), nullIfEmpty(msg)); } static boolean isMinusIdentifier(String s) { if (empty(s)) return false; if (!Character.isJavaIdentifierStart(s.charAt(0)) && !s.startsWith("-")) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i)) && s.charAt(i) != '-') return false; return true; } static String htmlunquote(String s) { if (s.startsWith("'") && s.endsWith("'") && s.length() >= 2 || s.startsWith("\"") && s.endsWith("\"") && s.length() >= 2) s = s.substring(1, s.length()-1); return htmldecode(s); } static boolean sameSnippetID(String a, String b) { if (!isSnippetID(a) || !isSnippetID(b)) return false; return parseSnippetID(a) == parseSnippetID(b); } static String programID() { return getProgramID(); } static String programID(Object o) { return getProgramID(o); } static volatile String caseID_caseID; static String caseID() { return caseID_caseID; } static void caseID(String id) { caseID_caseID = id; } static String mainClassNameForClassLoader(ClassLoader cl) { return or((String) callOpt(cl, "mainClassName"), "main"); } static Class loadClassFromClassLoader_orNull(ClassLoader cl, String name) { try { return cl == null ? null : cl.loadClass(name); } catch (ClassNotFoundException e) { return null; } } static Map vm_threadInterruptionReasonsMap() { return vm_generalWeakSubMap("Thread interruption reasons"); } static String strOr(Object o, String ifNull) { return o == null ? ifNull : str(o); } static void lockOrFail(Lock lock, long timeout) { try { ping(); vmBus_send("locking", lock, "thread" , currentThread()); if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) { String s = "Couldn't acquire lock after " + timeout + " ms."; if (lock instanceof ReentrantLock) { ReentrantLock l = (ReentrantLock) lock; s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner"); } throw fail(s); } vmBus_send("locked", lock, "thread" , currentThread()); ping(); } catch (Exception __e) { throw rethrow(__e); } } static ReentrantLock fairLock() { return new ReentrantLock(true); } static Random defaultRandomGenerator() { { Random r = customRandomizerForThisThread(); if (r != null) return r; } return ThreadLocalRandom.current(); } static File javaxCachesDir_dir; // can be set to work on different base dir static File javaxCachesDir() { return javaxCachesDir_dir != null ? javaxCachesDir_dir : new File(userHome(), "JavaX-Caches"); } static File javaxCachesDir(String sub) { return newFile(javaxCachesDir(), sub); } static String imageServerURL() { return or2(trim(loadTextFile(javaxDataDir("image-server-url.txt"))), "http://botcompany.de/images/raw/"); } static volatile boolean muricaPassword_pretendNotAuthed = false; static String muricaPassword() { if (muricaPassword_pretendNotAuthed) return null; return trim(loadTextFile(muricaPasswordFile())); } static String fileServerURL() { return "https://botcompany.de/files"; } public static File mkdirsFor(File file) { return mkdirsForFile(file); } 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(100000, total)))); total += n; } } catch (Exception __e) { throw rethrow(__e); } } static File renameFile_assertTrue(File a, File b) { try { if (a.equals(b)) return b; // no rename necessary 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)); return b; } catch (Exception __e) { throw rethrow(__e); } } static boolean isFile(File f) { return f != null && f.isFile(); } static boolean isFile(String path) { return isFile(newFile(path)); } static Set synchroHashSet() { return synchronizedSet(new HashSet()); } static Font loadFont(String snippetID) { try { return loadFont(snippetID, 12f); } catch (Exception __e) { throw rethrow(__e); } } static Font loadFont(InputStream in) { try { return Font.createFont(Font.TRUETYPE_FONT, in); } catch (Exception __e) { throw rethrow(__e); } } static Font loadFont(String snippetID, float fontSize) { return loadFont(loadLibrary(snippetID), fontSize); } static Font loadFont(File f, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, f).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static Font loadFont(InputStream in, float fontSize) { try { return Font.createFont(Font.TRUETYPE_FONT, in).deriveFont(fontSize); } catch (Exception __e) { throw rethrow(__e); } } static List> _threadInfo_makers = synchroList(); static Object _threadInfo() { if (empty(_threadInfo_makers)) return null; HashMap map = new HashMap(); pcallFAll(_threadInfo_makers, map); return map; } static Runnable asRunnable(Object o) { return toRunnable(o); } static void _inheritThreadInfo(Object info) { _threadInheritInfo(info); } static Set createOrAddToSyncLinkedHashSet(Set set, A a) { if (set == null) set = syncLinkedHashSet(); set.add(a); return set; } static Class main() { return getMainClass(); } static void remove(List l, int i) { if (l != null && i >= 0 && i < l(l)) l.remove(i); } static void remove(Collection l, A a) { if (l != null) l.remove(a); } static B remove(Map map, Object a) { return map == null ? null : map.remove(a); } static void remove(BitSet bs, int i) { bs.clear(i); } static A pcallF_typed(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static B pcallF_typed(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static void pcallF_typed(VF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { pcallFail(__e); } } static void pcallF_typed(IVF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { pcallFail(__e); } } static void pcallF_typed(IVF2 f, A a, B b) { try { { if (f != null) f.get(a, b); } } catch (Throwable __e) { pcallFail(__e); } } static Object pcallF_typed(Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable __e) { pcallFail(__e); } return null; } static A pcallF_typed(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static B pcallF_typed(IF1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static List codeTokensOnly(List tok) { int n = l(tok); List l = emptyList(n/2); for (int i = 1; i < n; i += 2) l.add(tok.get(i)); return l; } static String quickSubstring(String s, int i, int j) { if (i >= j) return ""; return s.substring(i, j); } static A printStructure(String prefix, A o) { if (endsWithLetter(prefix)) prefix += ": "; print(prefix + structureForUser(o)); return o; } static A printStructure(A o) { print(structureForUser(o)); return o; } static ThreadLocal assertVerbose_value = new ThreadLocal(); static void assertVerbose(boolean b) { assertVerbose_value.set(b); } static boolean assertVerbose() { return isTrue(assertVerbose_value.get()); } static A assertEqualsVerbose(Object x, A y) { assertEqualsVerbose((String) null, x, y); return y; } // x = expected, y = actual static A assertEqualsVerbose(String msg, Object x, A y) { if (!eq(x, y)) { throw fail((nempty(msg) ? msg + ": " : "") + "expected: "+ x + ", got: " + y); } else print("OK" + (empty(msg) ? "" : " " + msg) + ": " + /*sfu*/(x)); return y; } static void assertEqualsVerbose(Scorer scorer, Object x, Object y) { assertEqualsVerbose(scorer, "", x, y); } static void assertEqualsVerbose(Scorer scorer, String msg, Object x, Object y) { if (scorer == null) { assertEqualsVerbose(x, y); return; } if (!eq(x, y)) { print(appendColonIfNempty(msg) + y + " != " + x); scorer.add(false); } else { print("OK: " + appendColonIfNempty(msg) + x); scorer.add(true); } } static String nullIfEmpty(String s) { return isEmpty(s) ? null : s; } static Map nullIfEmpty(Map map) { return isEmpty(map) ? null : map; } static List nullIfEmpty(List l) { return isEmpty(l) ? null : l; } 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) { // look for '&' while (i < len && input.charAt(i-1) != '&') i++; if (i >= len) break; // found '&', look for ';' 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; } // found escape if (input.charAt(i) == '#') { // numeric escape 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 { // named escape 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); } // skip escape st = j + 1; i = st; } if (writer != null) { writer.append(input.substring(st, len)); return writer.toString(); } return input; } static HashMap htmldecode_lookupMap_cache; static HashMap htmldecode_lookupMap() { if (htmldecode_lookupMap_cache == null) htmldecode_lookupMap_cache = htmldecode_lookupMap_load(); return htmldecode_lookupMap_cache;} static HashMap htmldecode_lookupMap_load() { var map = new HashMap(); for (CharSequence[] seq : htmldecode_escapes()) map.put(seq[1].toString(), seq[0]); return map; } static Map vm_generalWeakSubMap(Object name) { synchronized(vm_generalMap()) { Map map = (Map) (vm_generalMap_get(name)); if (map == null) vm_generalMap_put(name, map = newWeakMap()); return map; } } static Random customRandomizerForThisThread() { return customRandomizerForThisThread_tl().get(); } static File muricaPasswordFile() { return new File(javaxSecretDir(), "murica/muricaPasswordFile"); } // TODO: optimize to x-(x%n) in case that's the same thing // (or x-mod(x,n)?) static int roundDownTo(int n, int x) { return x/n*n; } static long roundDownTo(long n, long x) { return x/n*n; } static double roundDownTo(double n, double x) { return floor(x/n)*n; } static void pcallFAll(Collection l, Object... args) { if (l != null) for (Object f : cloneList(l)) pcallF(f, args); } static void pcallFAll(Iterator it, Object... args) { while (it.hasNext()) pcallF(it.next(), args); } static Runnable toRunnable(final Object o) { if (o == null) return null; if (o instanceof Runnable) return (Runnable) o; if (o instanceof String) throw fail("callF_legacy"); return new Runnable() { public void run() { try { callF(o) ; } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(o)"; }}; } static List> _threadInheritInfo_retrievers = synchroList(); static void _threadInheritInfo(Object info) { if (info == null) return; pcallFAll(_threadInheritInfo_retrievers, (Map) info); } static Set syncLinkedHashSet() { return synchroLinkedHashSet(); } static boolean endsWithLetter(String s) { return nempty(s) && isLetter(last(s)); } static String structureForUser(Object o) { return structureForUser(o, new structure_Data()); } static String structureForUser(Object o, structure_Data d) { d.noStringSharing = true; d.warnIfUnpersistable(false); return beautifyStructure(structure(o, d)); } static String appendColonIfNempty(String s) { return empty(s) ? "" : s + ": "; } static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } static boolean isEmpty(File f) { return f == null || f.length() == 0; } static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } static boolean isEmpty(Object[] a) { return a == null || a.length == 0; } static boolean isEmpty(byte[] a) { return a == null || a.length == 0; } static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } static boolean isEmpty(AppendableChain c) { return c == null; } static boolean isEmpty(IntSize l) { return l == null || l.size() == 0; } static String[][] htmldecode_escapes() { return htmldecode_ESCAPES; } static final String[][] htmldecode_ESCAPES = { {"\"", "quot"}, // " - double-quote {"&", "amp"}, // & - ampersand {"<", "lt"}, // < - less-than {">", "gt"}, // > - greater-than // Mapping to escape ISO-8859-1 characters to their named HTML 3.x equivalents. {"\u00A0", "nbsp"}, // non-breaking space {"\u00A1", "iexcl"}, // inverted exclamation mark {"\u00A2", "cent"}, // cent sign {"\u00A3", "pound"}, // pound sign {"\u00A4", "curren"}, // currency sign {"\u00A5", "yen"}, // yen sign = yuan sign {"\u00A6", "brvbar"}, // broken bar = broken vertical bar {"\u00A7", "sect"}, // section sign {"\u00A8", "uml"}, // diaeresis = spacing diaeresis {"\u00A9", "copy"}, // copyright sign {"\u00AA", "ordf"}, // feminine ordinal indicator {"\u00AB", "laquo"}, // left-pointing double angle quotation mark = left pointing guillemet {"\u00AC", "not"}, // not sign {"\u00AD", "shy"}, // soft hyphen = discretionary hyphen {"\u00AE", "reg"}, // registered trademark sign {"\u00AF", "macr"}, // macron = spacing macron = overline = APL overbar {"\u00B0", "deg"}, // degree sign {"\u00B1", "plusmn"}, // plus-minus sign = plus-or-minus sign {"\u00B2", "sup2"}, // superscript two = superscript digit two = squared {"\u00B3", "sup3"}, // superscript three = superscript digit three = cubed {"\u00B4", "acute"}, // acute accent = spacing acute {"\u00B5", "micro"}, // micro sign {"\u00B6", "para"}, // pilcrow sign = paragraph sign {"\u00B7", "middot"}, // middle dot = Georgian comma = Greek middle dot {"\u00B8", "cedil"}, // cedilla = spacing cedilla {"\u00B9", "sup1"}, // superscript one = superscript digit one {"\u00BA", "ordm"}, // masculine ordinal indicator {"\u00BB", "raquo"}, // right-pointing double angle quotation mark = right pointing guillemet {"\u00BC", "frac14"}, // vulgar fraction one quarter = fraction one quarter {"\u00BD", "frac12"}, // vulgar fraction one half = fraction one half {"\u00BE", "frac34"}, // vulgar fraction three quarters = fraction three quarters {"\u00BF", "iquest"}, // inverted question mark = turned question mark {"\u00C0", "Agrave"}, // ? - uppercase A, grave accent {"\u00C1", "Aacute"}, // ? - uppercase A, acute accent {"\u00C2", "Acirc"}, // ? - uppercase A, circumflex accent {"\u00C3", "Atilde"}, // ? - uppercase A, tilde {"\u00C4", "Auml"}, // ? - uppercase A, umlaut {"\u00C5", "Aring"}, // ? - uppercase A, ring {"\u00C6", "AElig"}, // ? - uppercase AE {"\u00C7", "Ccedil"}, // ? - uppercase C, cedilla {"\u00C8", "Egrave"}, // ? - uppercase E, grave accent {"\u00C9", "Eacute"}, // ? - uppercase E, acute accent {"\u00CA", "Ecirc"}, // ? - uppercase E, circumflex accent {"\u00CB", "Euml"}, // ? - uppercase E, umlaut {"\u00CC", "Igrave"}, // ? - uppercase I, grave accent {"\u00CD", "Iacute"}, // ? - uppercase I, acute accent {"\u00CE", "Icirc"}, // ? - uppercase I, circumflex accent {"\u00CF", "Iuml"}, // ? - uppercase I, umlaut {"\u00D0", "ETH"}, // ? - uppercase Eth, Icelandic {"\u00D1", "Ntilde"}, // ? - uppercase N, tilde {"\u00D2", "Ograve"}, // ? - uppercase O, grave accent {"\u00D3", "Oacute"}, // ? - uppercase O, acute accent {"\u00D4", "Ocirc"}, // ? - uppercase O, circumflex accent {"\u00D5", "Otilde"}, // ? - uppercase O, tilde {"\u00D6", "Ouml"}, // ? - uppercase O, umlaut {"\u00D7", "times"}, // multiplication sign {"\u00D8", "Oslash"}, // ? - uppercase O, slash {"\u00D9", "Ugrave"}, // ? - uppercase U, grave accent {"\u00DA", "Uacute"}, // ? - uppercase U, acute accent {"\u00DB", "Ucirc"}, // ? - uppercase U, circumflex accent {"\u00DC", "Uuml"}, // ? - uppercase U, umlaut {"\u00DD", "Yacute"}, // ? - uppercase Y, acute accent {"\u00DE", "THORN"}, // ? - uppercase THORN, Icelandic {"\u00DF", "szlig"}, // ? - lowercase sharps, German {"\u00E0", "agrave"}, // ? - lowercase a, grave accent {"\u00E1", "aacute"}, // ? - lowercase a, acute accent {"\u00E2", "acirc"}, // ? - lowercase a, circumflex accent {"\u00E3", "atilde"}, // ? - lowercase a, tilde {"\u00E4", "auml"}, // ? - lowercase a, umlaut {"\u00E5", "aring"}, // ? - lowercase a, ring {"\u00E6", "aelig"}, // ? - lowercase ae {"\u00E7", "ccedil"}, // ? - lowercase c, cedilla {"\u00E8", "egrave"}, // ? - lowercase e, grave accent {"\u00E9", "eacute"}, // ? - lowercase e, acute accent {"\u00EA", "ecirc"}, // ? - lowercase e, circumflex accent {"\u00EB", "euml"}, // ? - lowercase e, umlaut {"\u00EC", "igrave"}, // ? - lowercase i, grave accent {"\u00ED", "iacute"}, // ? - lowercase i, acute accent {"\u00EE", "icirc"}, // ? - lowercase i, circumflex accent {"\u00EF", "iuml"}, // ? - lowercase i, umlaut {"\u00F0", "eth"}, // ? - lowercase eth, Icelandic {"\u00F1", "ntilde"}, // ? - lowercase n, tilde {"\u00F2", "ograve"}, // ? - lowercase o, grave accent {"\u00F3", "oacute"}, // ? - lowercase o, acute accent {"\u00F4", "ocirc"}, // ? - lowercase o, circumflex accent {"\u00F5", "otilde"}, // ? - lowercase o, tilde {"\u00F6", "ouml"}, // ? - lowercase o, umlaut {"\u00F7", "divide"}, // division sign {"\u00F8", "oslash"}, // ? - lowercase o, slash {"\u00F9", "ugrave"}, // ? - lowercase u, grave accent {"\u00FA", "uacute"}, // ? - lowercase u, acute accent {"\u00FB", "ucirc"}, // ? - lowercase u, circumflex accent {"\u00FC", "uuml"}, // ? - lowercase u, umlaut {"\u00FD", "yacute"}, // ? - lowercase y, acute accent {"\u00FE", "thorn"}, // ? - lowercase thorn, Icelandic {"\u00FF", "yuml"}, // ? - lowercase y, umlaut {"\u2013", "ndash"}, {"\u2018", "lsquo"}, {"\u2019", "rsquo"}, {"\u201D", "rdquo"}, {"\u201C", "ldquo"}, {"\u2014", "mdash"}, {"'", "apos"}, // the controversial (but who cares!) ' // stackoverflow.com/questions/2083754/why-shouldnt-apos-be-used-to-escape-single-quotes }; static Map newWeakMap() { return newWeakHashMap(); } static ThreadLocal customRandomizerForThisThread_tl = new ThreadLocal(); static ThreadLocal customRandomizerForThisThread_tl() { return customRandomizerForThisThread_tl; } static File javaxSecretDir_dir; // can be set to work on different base dir static File javaxSecretDir() { return javaxSecretDir_dir != null ? javaxSecretDir_dir : new File(userHome(), "JavaX-Secret"); } static File javaxSecretDir(String sub) { return newFile(javaxSecretDir(), sub); } static double floor(double d) { return Math.floor(d); } static Object pcallF(Object f, Object... args) { return pcallFunction(f, args); } static A pcallF(F0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static B pcallF(F1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } static void pcallF(VF1 f, A a) { try { { if (f != null) f.get(a); } } catch (Throwable __e) { pcallFail(__e); } } static Object pcallF(Runnable r) { try { { if (r != null) r.run(); } } catch (Throwable __e) { pcallFail(__e); } return null; } static A pcallF(IF0 f) { try { return f == null ? null : f.get(); } catch (Throwable __e) { pcallFail(__e); } return null; } static B pcallF(IF1 f, A a) { try { return f == null ? null : f.get(a); } catch (Throwable __e) { pcallFail(__e); } return null; } // BREAKING CHANGE! // Also NOTE: Iterators of these sync-wrapped collections // after generally NOT thread-safe! // TODO: change that? static Set synchroLinkedHashSet() { return synchronizedSet(new CompactLinkedHashSet()); } static String beautifyStructure(String s) { List tok = javaTokForStructure(s); structure_addTokenMarkers(tok); jreplace(tok, "lhm", ""); return join(tok); } static boolean structure_showTiming, structure_checkTokenCount; static String structure(Object o) { return structure(o, new structure_Data()); } 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; } static void structure_go(Object o, structure_Data d) { structure_1(o, d); while (nempty(d.stack)) popLast(d.stack).run(); } static void structureToPrintWriter(Object o, PrintWriter out) { structureToPrintWriter(o, out, new structure_Data()); } static void structureToPrintWriter(Object o, PrintWriter out, structure_Data d) { d.out = out; structure_go(o, d); } // leave to false, unless unstructure() breaks static boolean structure_allowShortening = false; // info on how to serialize objects of a certain class static class structure_ClassInfo { Class c; String shortName; List fields; Method customSerializer; IVF1 serializeObject; // can be set by caller of structure function boolean special = false; // various special classes boolean nullInstances = false; // serialize all instances as null (e.g. lambdas/anonymous classes) boolean javafy = false; // always convert to "j ..." Object emptyInstance; // to grab default field values from public String toString() { return commaCombine( "Class " + className(c), stringIf("special", special), stringIf("customSerializer", customSerializer != null), stringIf("javafy", javafy), stringIf("nullInstances", nullInstances)); } void nullInstances(boolean b) { this.nullInstances = b; if (b) special = true; } void javafy(boolean b) { this.javafy = b; if (b) special = true; } // overridable - return true if you wrote the object boolean handle(A o) { return false; } } static class structure_Data { PrintWriter out; int stringSizeLimit; int shareStringsLongerThan = 20; boolean noStringSharing = false; boolean storeBaseClasses = false; boolean honorFieldOrder = true; String mcDollar = actualMCDollar(); final public structure_Data setWarnIfUnpersistable(boolean warnIfUnpersistable){ return warnIfUnpersistable(warnIfUnpersistable); } public structure_Data warnIfUnpersistable(boolean warnIfUnpersistable) { this.warnIfUnpersistable = warnIfUnpersistable; return this; } final public boolean getWarnIfUnpersistable(){ return warnIfUnpersistable(); } public boolean warnIfUnpersistable() { return warnIfUnpersistable; } boolean warnIfUnpersistable = true; final public structure_Data setStackTraceIfUnpersistable(boolean stackTraceIfUnpersistable){ return stackTraceIfUnpersistable(stackTraceIfUnpersistable); } public structure_Data stackTraceIfUnpersistable(boolean stackTraceIfUnpersistable) { this.stackTraceIfUnpersistable = stackTraceIfUnpersistable; return this; } final public boolean getStackTraceIfUnpersistable(){ return stackTraceIfUnpersistable(); } public boolean stackTraceIfUnpersistable() { return stackTraceIfUnpersistable; } boolean stackTraceIfUnpersistable = true; // skip a field if it has the default value defined in the class // -slower, and may cause issues with schema evolution // -OTOH, it can serialize null values for a field with default non-null value final public structure_Data setSkipDefaultValues(boolean skipDefaultValues){ return skipDefaultValues(skipDefaultValues); } public structure_Data skipDefaultValues(boolean skipDefaultValues) { this.skipDefaultValues = skipDefaultValues; return this; } final public boolean getSkipDefaultValues(){ return skipDefaultValues(); } public boolean skipDefaultValues() { return skipDefaultValues; } boolean skipDefaultValues = false; structure_Data d() { return this; } transient IF1 shouldIncludeField; boolean shouldIncludeField(Field f) { return shouldIncludeField != null ? shouldIncludeField.get(f) : shouldIncludeField_base(f); } final boolean shouldIncludeField_fallback(IF1 _f, Field f) { return _f != null ? _f.get(f) : shouldIncludeField_base(f); } boolean shouldIncludeField_base(Field f) { return true; } IdentityHashMap seen = new IdentityHashMap(); //new BitSet refd; HashMap strings = new HashMap(); HashSet concepts = new HashSet(); HashMap infoByClass = new HashMap(); // wrapper for _persistenceInfo field or _persistenceInfo method // by class (taking the object instance) HashMap> persistenceInfo = new HashMap(); int n; // token count List stack = new ArrayList(); // append single token structure_Data append(String token) { out.print(token); ++n; return this; } structure_Data append(int i) { out.print(i); ++n; return this; } // append multiple tokens structure_Data append(String token, int tokCount) { out.print(token); n += tokCount; return this; } // extend last token structure_Data app(String token) { out.print(token); return this; } structure_Data app(int i) { out.print(i); return this; } structure_Data app(char c) { out.print(c); return this; } structure_ClassInfo infoForClass(Class c) { structure_ClassInfo info = infoByClass.get(c); if (info == null) info = newClass(c); return info; } transient IF1 realShortName; String realShortName(String name) { return realShortName != null ? realShortName.get(name) : realShortName_base(name); } final String realShortName_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : realShortName_base(name); } String realShortName_base(String name) { return dropPrefix("main$", dropPrefix("loadableUtils.utils$", dropPrefix(mcDollar, name))); } // called when a new class is detected // can be overridden by clients structure_ClassInfo newClass(Class c) { // special classes here! var d = d(); boolean isJavaXClass = isJavaXClassName(c.getName(), mcDollar); if (c == String.class) return new structure_ClassInfo() { @Override boolean handle(String o) { 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 true; } }; if (c == File.class) return new structure_ClassInfo() { @Override boolean handle(File o) { append("File ").append(quote(o.getPath())); return true; } }; if (!isJavaXClass) { if (isSubClassOf(c, Set.class)) return new structure_ClassInfo() { @Override boolean handle(Set o) { writeSet(o); return true; } }; if (isSubClassOf(c, Collection.class)) return new structure_ClassInfo() { @Override boolean handle(Collection o) { writeCollection(o); return true; } }; if (isSubClassOf(c, Map.class)) return new structure_ClassInfo() { @Override boolean handle(Map o) { writeMap(o); return true; } }; } structure_ClassInfo info = new structure_ClassInfo(); info.c = c; infoByClass.put(c, info); String name = c.getName(); String shortName = realShortName(name); if (startsWithDigit(shortName)) shortName = name; // for anonymous classes info.shortName = shortName; try { if (isSyntheticOrAnonymous(c)) { info.nullInstances(true); return info; } if (c.isEnum()) { info.special = true; return info; } if (c.isArray()) { // info.special? return info; } if ((info.customSerializer = findMethodNamed(c, "_serialize")) != null) info.special = true; if (storeBaseClasses) { Class sup = c.getSuperclass(); if (sup != Object.class) { append("bc "); append(shortDynClassNameForStructure(c)); out.print(" "); append(shortDynClassNameForStructure(sup)); out.print(" "); infoForClass(sup); // transitively write out superclass relations } } if (eqOneOf(name, "java.awt.Color", "java.lang.ThreadLocal")) info.javafy(true); else if (name.startsWith("sun") || !isPersistableClass(c)) { info.javafy(true); if (warnIfUnpersistable) { String msg = "Class not persistable: " + c + " (anonymous or no default constructor), referenced from " + last(stack); if (stackTraceIfUnpersistable) printStackTrace(new Throwable(msg)); else print(msg); } } else if (skipDefaultValues) { var ctor = getDefaultConstructor(c); if (ctor != null) info.emptyInstance = invokeConstructor(ctor); } } catch (Throwable e) { printStackTrace(e); info.nullInstances(true); } return info; } void setFields(structure_ClassInfo info, List fields) { info.fields = fields; } void writeObject(Object o, String shortName, Map fv) { String singleField = fv.size() == 1 ? first(fv.keySet()) : null; append(shortName); n += countDots(shortName)*2; // correct token count int l = n; Iterator it = fv.entrySet().iterator(); class WritingObject implements Runnable { String lastFieldWritten; public void run() { try { if (!it.hasNext()) { if (n != l) append(")"); } else { Map.Entry e = (Map.Entry) (it.next()); append(n == l ? "(" : ", "); append(lastFieldWritten = (String) e.getKey()).append("="); stack.add(this); structure_1(e.getValue(), structure_Data.this); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return shortName + "." + lastFieldWritten; } } stack.add(new WritingObject()); } void writeMap(Map o) { var d = this; String name = o.getClass().getName(); 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") || name.equals("java.util.Collections$SynchronizedSortedMap") || name.equals("java.util.Collections$SynchronizedNavigableMap")) { d.append("sync "); { structure_1(unwrapSynchronizedMap(((Map) o)), d); return; } } d.append("{"); final int l = d.n; final Iterator it = cloneMap((Map) o).entrySet().iterator(); class WritingMap implements Runnable { boolean v = false; Map.Entry e; public String toString() { return renderVars("WritingMap", "e" , mapEntryToPair(e), "v" , !v); } public void run() { try { 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); } } } catch (Exception __e) { throw rethrow(__e); } } } d.stack.add(new WritingMap()); } void writeSet(Set o) { var d = this; String name = o.getClass().getName(); /*O set2 = unwrapSynchronizedSet(o); if (set2 != o) { d.append("sync"); o = set2; } TODO */ if (o instanceof TreeSet) { d.append(isCISet_gen(o) ? "ciset" : "treeset"); structure_1(new ArrayList(o), d); return; } // assume it's a HashSet or LinkedHashSet d.append(o instanceof LinkedHashSet ? "lhs" : "hashset"); structure_1(new ArrayList(o), d); } void writeCollection(Collection o) { var d = this; String name = o.getClass().getName(); if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) { d.append("sync "); { structure_1(unwrapSynchronizedList(((List) o)), d); return; } } else if (name.equals("java.util.LinkedList")) d.append("ll"); d.append("["); int l = d.n; Iterator it = cloneList(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.stack.add..."; }}); } } // end of class structure_Data static void structure_1(Object o, structure_Data d) { try { if (o == null) { d.append("null"); return; } Class c = o.getClass(); boolean concept = false; structure_ClassInfo info = d.infoForClass(c); boolean isJavaXName = isJavaXClassName(c.getName(), d.mcDollar); boolean referencable = isJavaXName && !(o instanceof Number || o instanceof Character || o instanceof Boolean) || o instanceof Collection || o instanceof Map; if (referencable) { Integer ref = d.seen.get(o); if (ref != null) { //d.refd.set(ref); d.append("t").app(ref); return; } d.seen.put(o, d.n); // record token number } if (info.handle(o)) { return; } if (info.special) { if (info.javafy) { d.append("j ").append(quote(str(o))); return; // This is not unstructure-able except for java.awt.Color } if (c.isEnum()) { d.append("enum "); d.append(info.shortName); d.out.append(' '); d.append(((Enum) o).ordinal()); return; } if (info.customSerializer != null) { // custom serialization (_serialize method) Object o2 = invokeMethod(info.customSerializer, o); if (o2 == o) {} // bail out to standard serialization else { d.append("cu "); String name = c.getName(); String shortName = d.realShortName(name); d.append(shortName); d.out.append(' '); structure_1(o2, d); return; } } else if (info.nullInstances) { d.append("null"); return; } else if (info.serializeObject != null) { info.serializeObject.get(o); return; } else throw fail("unknown special type"); } List lFields = info.fields; if (lFields == null) { // these are never back-referenced (for readability) 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; } String name = c.getName(); if (!isJavaXName) { if (o instanceof Set) { d.writeSet((Set) o); return; } if (o instanceof Collection /* && neq(name, "main$Concept$RefL") */) { { d.writeCollection((Collection) o); return; } } if (o instanceof Map) { d.writeMap((Map) o); 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; } if (o instanceof short[]) { String hex = shortArrayToHex_bigEndian((short[]) o); d.append("shortarray \"").append(hex).app('\"'); return; } if (o instanceof long[]) { String hex = longArrayToHex_bigEndian((long[]) o); d.append("longarray \"").append(hex).app('\"'); return; } String atype = "array"/*, sep = ", "*/; // sep is not used yet if (o instanceof int[]) { //ret "intarray " + quote(intArrayToHex((int[]) o)); atype = "intarray"; //sep = " "; } else if (o instanceof double[]) { atype = "dblarray"; //sep = " "; } else { Pair p = arrayTypeAndDimensions(c); if (p.a == int.class) atype = "intarray"; else if (p.a == byte.class) atype = "bytearray"; else if (p.a == boolean.class) atype = "boolarray"; else if (p.a == double.class) atype = "dblarray"; else if (p.a == String.class) { atype = "array S"; d.n++; } else atype = "array"; // fail("Unsupported array type: " + p.a); if (p.b > 1) { atype += "/" + p.b; // add number of dimensions d.n += 2; // 2 additional tokens will be written } } d.append(atype).append("{"); d.stack.add(new Runnable() { 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.equals("main$Lisp")) { fail("lisp not supported right now"); }*/ String dynName = shortDynClassNameForStructure(o); if (concept && !d.concepts.contains(dynName)) { d.concepts.add(dynName); d.append("c "); } // serialize an object with fields. // first, collect all fields and values in fv. 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)) { if (!d.shouldIncludeField(field)) continue; String fieldName = field.getName(); if (fieldName.equals("_persistenceInfo")) d.persistenceInfo.put(c, obj -> (Map) fieldGet(field, obj)); if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0) continue; fields.add(field); // put special cases here...? } cc = cc.getSuperclass(); } Method persistenceInfoMethod = findInstanceMethod(c, "_persistenceInfo"); if (persistenceInfoMethod != null) d.persistenceInfo.put(c, obj -> (Map) invokeMethod(persistenceInfoMethod, obj)); lFields = asList(d.honorFieldOrder ? fieldObjectsInFieldOrder(c, fields) : fields); // Render this$0/this$1 first because unstructure needs it for constructor call. int n = l(lFields); for (int i = 0; i < n; i++) { Field f = lFields.get(i); if (f.getName().startsWith("this$")) { lFields.remove(i); lFields.add(0, f); break; } } d.setFields(info, lFields); } // << if (lFields == null) // get _persistenceInfo from field and/or dynamic field IF1 piGetter = d.persistenceInfo.get(c); Map persistenceInfo = piGetter == null ? null : piGetter.get(o); if (piGetter == null && o instanceof DynamicObject) persistenceInfo = (Map) getOptDynOnly(((DynamicObject) o), "_persistenceInfo"); LinkedHashMap fv = new LinkedHashMap(); Object defaultInstance = info.emptyInstance; for (Field f : lFields) { Object value, defaultValue = null; try { value = f.get(o); defaultValue = defaultInstance == null ? null : f.get(defaultInstance); } catch (Exception e) { value = "?"; } if (!eq(defaultValue, value) && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName())))) fv.put(f.getName(), value); } String shortName = info.shortName; // Now we have fields & values. Process fieldValues if it's a DynamicObject. Object classNameFromFV = fv.get("className"); // omit field "className" if equal to class's name if (concept && eq(classNameFromFV, shortName)) fv.remove("className"); if (o instanceof DynamicObject) { putAll(fv, (Map) fv.get("fieldValues")); fv.remove("fieldValues"); if (((DynamicObject) o).className != null) { // TODO: this probably doesn't work with inner classes shortName = shortDynClassNameForStructure((DynamicObject) o); fv.remove("className"); // special handling for missing Class objects encoded as DynamicObject if (eq(shortName, "java.lang.Class")) { d.append("class("); d.append(quoted(fv.get("name"))); d.append(")"); return; } } } d.writeObject(o, shortName, fv); } catch (Exception __e) { throw rethrow(__e); } } static Object pcallFunction(Object f, Object... args) { try { return callFunction(f, args); } catch (Throwable __e) { pcallFail(__e); } return null; } static List javaTokForStructure(String s) { return javaTok_noMLS(s); } static String structure_addTokenMarkers(String s) { return join(structure_addTokenMarkers(javaTokForStructure(s))); } static List structure_addTokenMarkers(List tok) { // find references 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; // add markers for (int i : refs) { int idx = i*2+1; if (idx >= l(tok)) continue; // broken structure String t = ""; if (endsWithLetterOrDigit(tok.get(idx-1))) t = " "; tok.set(idx, t + "m" + i + " " + tok.get(idx)); } return tok; } static String jreplace(String s, String in, String out) { return jreplace(s, in, out, null); } static String jreplace(String s, String in, String out, Object condition) { List tok = javaTok(s); return jreplace(tok, in, out, condition) ? join(tok) : s; } // leaves tok properly tokenized // returns true iff anything was replaced static boolean jreplace(List tok, String in, String out) { return jreplace(tok, in, out, false, true, null); } static boolean jreplace(List tok, String in, String out, Object condition) { return jreplace(tok, in, out, false, true, condition); } static boolean jreplace(List tok, String in, ITokCondition condition, String out) { return jreplace(tok, in, out, (Object) condition); } static boolean jreplace(List tok, String in, String out, IF2, Integer, Boolean> condition) { return jreplace(tok, in, out, (Object) condition); } 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++) { // TODO: don't need this check anymore i = findCodeTokens(tok, i+1, ignoreCase, toks, condition); if (i < 0) return anyChange; List subList = tok.subList(i-1, i+lTokin-1); // N to N String expansion = jreplaceExpandRefs(out, subList); int end = i+lTokin-2; clearAllTokens(tok, i, end); // C to C tok.set(i, expansion); if (reTok) // would this ever be false?? reTok(tok, i, end); i = end; anyChange = true; } throw fail("woot? 10000! " + quote(in) + " => " + quote(out)); } static boolean jreplace_debug = false; 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; // scan for whitespace 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); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors ++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)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else if (c == '[' && d == '[') { do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]")); j = Math.min(j+2, l); } else if (c == '[' && d == '=' && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]")); j = Math.min(j+3, l); } else ++j; tok.add(javaTok_substringC(s, i, j)); i = j; } return tok; } static A popLast(List l) { return liftLast(l); } static List popLast(int n, List l) { return liftLast(n, l); } static String commaCombine(Object... l) { return joinNemptiesWithComma(flattenCollectionsAndArrays(l)); } static String stringIf(boolean b, String s) { return stringIfTrue(b, s); } static String stringIf(String s, boolean b) { return stringIf(b, s); } static String actualMCDollar() { return actualMC().getName() + "$"; } static boolean isJavaXClassName(String s) { return isJavaXClassName(s, "main$"); } static boolean isJavaXClassName(String s, String mcDollar) { return startsWithOneOf(s, mcDollar, "loadableUtils."); } static int shorten_default = 100; static String shorten(CharSequence s) { return shorten(s, shorten_default); } static String shorten(CharSequence s, int max) { return shorten(s, max, "..."); } static String shorten(CharSequence s, int max, String shortener) { if (s == null) return ""; if (max < 0) return str(s); return s.length() <= max ? str(s) : subCharSequence(s, 0, min(s.length(), max-l(shortener))) + shortener; } static String shorten(int max, CharSequence s) { return shorten(s, max); } 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('"'); } static String quote(Object o) { if (o == null) return "null"; return quote(str(o)); } 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(); } 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 == '\t') out.append("\\t"); else if (c == '\0') out.append("\\0"); else out.append(c); } out.append('"'); } static boolean isSubClassOf(Class a, Class b) { return isSubclass(a, b); } static boolean isSyntheticOrAnonymous(Class c) { return c != null && (c.isSynthetic() || isAnonymousClassName(c.getName())); } // This is a bit rough... finds static and non-static methods. 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); } static Method findMethodNamed(Class c, String method) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method)) { makeAccessible(m); return m; } c = c.getSuperclass(); } return null; } // keeps package names for dynamic code (package dyn.*) static String shortDynClassNameForStructure(Object o) { if (o instanceof DynamicObject && ((DynamicObject) o).className != null) return ((DynamicObject) o).className; if (o == null) return null; Class c = o instanceof Class ? (Class) o : o.getClass(); String name = c.getName(); return name.startsWith("dyn.") ? classNameToVM(name) : shortenClassName(name); } static boolean isPersistableClass(Class c) { String name = c.getName(); if (isSubtypeOf(c, TransientObject.class)) return false; if (isAnonymousClassName(name)) return false; if (isBoxedType(c)) return true; if (isArrayType(c)) return true; if (c == Class.class || c == String.class || c == File.class || c == Color.class) return true; if (name.startsWith("java.util.Collections$Synchronized")) return true; if (hasThisDollarFields(c)) return hasSingleArgumentConstructor(c); else return getDefaultConstructor(c) != null; } static Constructor getDefaultConstructor(Class c) { if (c != null) for (Constructor m : getDeclaredConstructors_cached(c)) if (empty(m.getParameterTypes())) return m; return null; } static Object invokeConstructor(Constructor m, Object... args) { try { makeAccessible(m); return m.newInstance(args); } catch (Exception __e) { throw rethrow(__e); } } static int countDots(String s) { int n = l(s), count = 0; for (int i = 0; i < n; i++) if (s.charAt(i) == '.') ++count; return count; } static boolean isCIMap_gen(Map map) { return map instanceof TreeMap && className(((TreeMap) map).comparator()).contains("CIComp"); } // works for both java.util-wrapped maps as well as our own static Map unwrapSynchronizedMap(Map map) { if (eqOneOf(shortClassName(map), "SynchronizedMap", "SynchronizedSortedMap", "SynchronizedNavigableMap")) return (Map) get_raw(map, "m"); return map; } // Use like this: renderVars(+x, +y) // Or like this: renderVars SomeID(+x, +y) static String renderVars(Object... params) { return renderVars_str(params); } static boolean isCISet_gen(Iterable l) { return l instanceof TreeSet && className(((TreeSet) l).comparator()).contains("CIComp"); } 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; } 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 + "'"; } static String boolArrayToHex(boolean[] a) { return bytesToHex(boolArrayToBytes(a)); } static String shortArrayToHex_bigEndian(short[] a) { return bytesToHex(byteArrayFromShorts_bigEndian(a)); } static String longArrayToHex_bigEndian(long[] a) { return bytesToHex(byteArrayFromLongs_bigEndian(a)); } static Pair arrayTypeAndDimensions(Object o) { return arrayTypeAndDimensions(_getClass(o)); } static Pair arrayTypeAndDimensions(Class c) { if (c == null || !c.isArray()) return null; Class elem = c.getComponentType(); if (elem.isArray()) return mapPairB(arrayTypeAndDimensions(elem), dim -> dim+1); return pair(elem, 1); } static int stdcompare(Number a, Number b) { return cmp(a, b); } static int stdcompare(String a, String b) { return cmp(a, b); } static int stdcompare(long a, long b) { return a < b ? -1 : a > b ? 1 : 0; } static int stdcompare(Object a, Object b) { return cmp(a, b); } static Map getDeclaredFields_cache = newDangerousWeakHashMap(); 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) makeAccessible(f); } } return fields; } static Object fieldGet(Field f, Object o) { try { return f == null ? null : f.get(o); } catch (Exception __e) { throw rethrow(__e); } } static Method findInstanceMethod(Class c, String method, Object... args) { while (c != null) { for (Method m : c.getDeclaredMethods()) if (m.getName().equals(method) && findMethod_checkArgs(m, args, false)) return m; c = c.getSuperclass(); } return null; } static Set fieldObjectsInFieldOrder(Class c, Set fields) { try { var byName = mapToKey(f -> f.getName(), fields); LinkedHashSet out = new LinkedHashSet(); for (String name : unnullForIteration(getFieldOrder(c))) { Field f = byName.get(name); if (f != null) { byName.remove(name); out.add(f); } } addAll(out, fields); return out; } catch (Throwable __0) { printStackTrace(__0); return fields; } } static Map putAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static MultiMap putAll(MultiMap a, Map b) { if (a != null) a.putAll((Map) b); return a; } static Map putAll(Map a, Object... b) { if (a != null) litmap_impl(a, b); return a; } static String quoted(Object o) { return quote(o); } static String quoted(String s) { return quote(s); } static List javaTok_noMLS(String s) { 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; // scan for whitespace 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); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { int c2 = s.charAt(j); if (c2 == opener || c2 == '\n' && opener == '\'') { // allow multi-line strings, but not for ' ++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))); else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else ++j; tok.add(javaTok_substringC(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } // "$1" is first code token, "$2" second code token etc. static String jreplaceExpandRefs(String s, List tokref) { if (!contains(s, '$')) return s; List tok = javaTok(s); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("$") && isInteger(t.substring(1))) { String x = tokref.get(-1+parseInt(t.substring(1))*2); tok.set(i, x); } else if (t.equals("\\")) { tok.set(i, ""); i += 2; } } return join(tok); } static void clearAllTokens(List tok) { for (int i = 0; i < tok.size(); i++) tok.set(i, ""); } static void clearAllTokens(List tok, int i, int j) { for (; i < j; i++) tok.set(i, ""); } static List reTok(List tok) { replaceCollection(tok, javaTok(tok)); return tok; } static List reTok(List tok, int i) { return reTok(tok, i, i+1); } static List reTok(List tok, int i, int j) { // extend i to an "N" token // and j to "C" (so j-1 is an "N" token) i = max(i & ~1, 0); j = min(l(tok), j | 1); if (i >= j) return tok; List t = javaTok(joinSubList(tok, i, j)); replaceListPart(tok, i, j, t); // fallback to safety // reTok(tok); return tok; } static A liftLast(List l) { if (empty(l)) return null; int i = l(l)-1; A a = l.get(i); l.remove(i); return a; } static List liftLast(int n, List l) { int i = l(l)-n; List part = cloneSubList(l, i); removeSubList(l, i); return part; } static String joinNemptiesWithComma(Object... strings) { return joinNempties(", ", strings); } static String joinNemptiesWithComma(Iterable strings) { return joinNempties(", ", strings); } static List flattenCollectionsAndArrays(Iterable a) { List l = new ArrayList(); for (Object x : a) if (x instanceof Collection) l.addAll(flattenCollectionsAndArrays((Collection) x)); else if (x instanceof Object[]) l.addAll(flattenCollectionsAndArrays(asList((Object[]) x))); else l.add(x); return l; } static List flattenCollectionsAndArrays(Object... whatever) { return flattenCollectionsAndArrays(ll(whatever)); } static String stringIfTrue(boolean b, String s) { return b ? s : ""; } static Class actualMC() { return or((Class) realMC(), mc()); } static boolean isSubclass(Class a, Class b) { return a != null && b != null && b.isAssignableFrom(a); } static boolean isAnonymousClassName(String s) { for (int i = 0; i < l(s); i++) if (s.charAt(i) == '$' && Character.isDigit(s.charAt(i+1))) return true; return false; } 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); } static boolean isBoxedType(Class type) { return type == Boolean.class || type == Integer.class || type == Long.class || type == Float.class || type == Short.class || type == Character.class || type == Byte.class || type == Double.class; } static boolean isArrayType(Class type) { return type != null && type.isArray(); } static boolean hasThisDollarFields(Object o) { Matches m = new Matches(); for (var f : allFieldObjects_dontMakeAccessible(o)) if (startsWith(f.getName(), "this$", m) && isInteger(m.rest())) return true; return false; } static boolean hasSingleArgumentConstructor(Class c) { if (c != null) for (Constructor m : getDeclaredConstructors_cached(c)) if (l(m.getParameterTypes()) == 1) return true; return false; } // TODO: convert to regularly cleared normal map static Map getDeclaredConstructors_cached_cache = newDangerousWeakHashMap(); static Constructor[] getDeclaredConstructors_cached(Class c) { Constructor[] ctors; synchronized(getDeclaredConstructors_cached_cache) { ctors = getDeclaredConstructors_cached_cache.get(c); if (ctors == null) { getDeclaredConstructors_cached_cache.put(c, ctors = c.getDeclaredConstructors()); for (var ctor : ctors) makeAccessible(ctor); } } return ctors; } 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); } // Use like this: renderVars(+x, +y) // Or like this: renderVars("bla", +x, +y) static String renderVars_str(Object... params) { List l = new ArrayList(); int i = 0; if (odd(l(params))) { l.add(strOrNull(first(params))); ++i; } for (; i+1 < l(params); i += 2) l.add(params[i] + "=" + params[i+1]); return trim(joinWithComma(l)); } 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; } static byte[] byteArrayFromShorts_bigEndian(short[] a) { return byteArrayFromShorts_bigEndian(a, 0, l(a)); } static byte[] byteArrayFromShorts_bigEndian(short[] a, int from, int to) { byte[] b = new byte[(to-from)*2]; for (int i = 0; i < a.length; i++) { short s = a[from+i]; b[i*2] = (byte) (s >> 8); b[i*2+1] = (byte) s; } return b; } static byte[] byteArrayFromLongs_bigEndian(long[] a) { return byteArrayFromLongs_bigEndian(a, 0, l(a)); } static byte[] byteArrayFromLongs_bigEndian(long[] a, int from, int to) { byte[] b = new byte[(to-from)*8]; for (int i = 0; i < a.length; i++) { long s = a[from+i]; b[i*8] = (byte) (s >> 56); b[i*8+1] = (byte) (s >> 48); b[i*8+2] = (byte) (s >> 40); b[i*8+3] = (byte) (s >> 32); b[i*8+4] = (byte) (s >> 24); b[i*8+5] = (byte) (s >> 16); b[i*8+6] = (byte) (s >> 8); b[i*8+7] = (byte) s; } return b; } static List> mapPairB(final Object f, Iterable> l) { return map(l, new F1, Pair>() { public Pair get(Pair p) { try { return p == null ? null : pair(p.a, (C) callF(f, p.b)); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "p == null ? null : pair(p.a, (C) callF(f, p.b))"; }}); } static List> mapPairB(final F1 f, Iterable> l) { return mapPairB((Object) f, l); } static List> mapPairB(final IF1 f, Iterable> l) { return mapPairB((Object) f, l); } static List> mapPairB(Iterable> l, IF1 f) { return mapPairB((Object) f, l); } static Pair mapPairB(IF1 f, Pair p) { return pairMapB(f, p); } static Pair mapPairB(Pair p, IF1 f) { return pairMapB(f, p); } static Method findMethod(Object o, String method, Object... args) { return findMethod_cached(o, method, args); } 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; } static Map mapToKey(Iterable l, IF1 f) { return mapToKeys(l, f); } static Map mapToKey(IF1 f, Iterable l) { return mapToKeys(f, l); } static Map> getFieldOrder_cache = weakMap(); static List getFieldOrder(Object o) { return getFieldOrder(_getClass(o)); } static List getFieldOrder(Class c) { if (c == null) return null; return getOrCreate(getFieldOrder_cache, c, () -> splitAtSpace(toStringOpt(getOpt(c, "_fieldOrder")))); } static void addAll(Collection c, Iterable b) { if (c != null && b != null) for (A a : b) c.add(a); } static boolean addAll(Collection c, Collection b) { return c != null && b != null && c.addAll(b); } static boolean addAll(Collection c, B... b) { return c != null && b != null && c.addAll(Arrays.asList(b)); } static Map addAll(Map a, Map b) { if (a != null && b != null) a.putAll(b); return a; } static A addAll(A c, Collection components) { return addComponents(c, components); } static A addAll(A c, Component... components) { return addComponents(c, components); } static void replaceCollection(Collection dest, Collection src) { if (dest == src) return; dest.clear(); if (src != null) dest.addAll(src); } static void replaceListPart(List l, int i, int j, List l2) { replaceSublist(l, i, j, l2); } static List cloneSubList(List l, int startIndex, int endIndex) { return newSubList(l, startIndex, endIndex); } static List cloneSubList(List l, int startIndex) { return newSubList(l, startIndex); } static Object realMC() { return getThreadLocal(realMC_tl()); } static int lastIndexOf(String a, String b) { return a == null || b == null ? -1 : a.lastIndexOf(b); } static int lastIndexOf(String a, char b) { return a == null ? -1 : a.lastIndexOf(b); } // starts searching from i-1 static int lastIndexOf(List l, int i, A a) { if (l == null) return -1; for (i = min(l(l), i)-1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static int lastIndexOf(List l, A a) { if (l == null) return -1; for (int i = l(l)-1; i >= 0; i--) if (eq(l.get(i), a)) return i; return -1; } static List allFieldObjects_dontMakeAccessible(Object o) { List fields = new ArrayList(); Class _c = _getClass(o); do { addAll(fields, _c.getDeclaredFields()); _c = _c.getSuperclass(); } while (_c != null); return fields; } static Pair pairMapB(Object f, Pair p) { return p == null ? null : pair(p.a, callF(f, p.b)); } static Pair pairMapB(IF1 f, Pair p) { return p == null ? null : pair(p.a, f.get(p.b)); } static Pair pairMapB(Pair p, Object f) { return pairMap(f, p); } 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); } } static Map mapToKeys(Iterable l, IF1 f) { if (l == null) return null; HashMap map = new HashMap(); for (A a : l) map.put(f.get(a), a); return map; } static Map mapToKeys(IF1 f, A[] l) { return mapToKeys(f, asList(l)); } static Map mapToKeys(IF1 f, Iterable l) { return mapToKeys(l, f); } static Map weakMap() { return newWeakHashMap(); } // allows null keys but not null values 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); } } // f : func -> B 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); } } static B getOrCreate(IF0 f, Map map, A key) { return getOrCreate(map, key, f); } static B getOrCreate(Map map, A key, IF0 f) { B b = map.get(key); if (b == null) map.put(key, b = f.get()); return b; } static B getOrCreate(Class c, Map map, A key) { return getOrCreate(map, key, c); } static String toStringOpt(Object o) { return o instanceof String ? ((String) o) : null; } static A addComponents(A c, Collection components) { if (nempty(components)) { swing(() -> { for (Component comp : components) if (comp != null) c.add(comp); revalidate(c); }); } return c; } static A addComponents(A c, Component... components) { return addComponents(c, asList(components)); } static List newSubList(List l, int startIndex, int endIndex) { return cloneList(subList(l, startIndex, endIndex)); } static List newSubList(List l, int startIndex) { return cloneList(subList(l, startIndex)); } static ThreadLocal realMC_tl_tl = new ThreadLocal(); static ThreadLocal realMC_tl() { return realMC_tl_tl; } static Pair pairMap(Object f, Pair p) { return p == null ? null : pair(callF(f, p.a), callF(f, p.b)); } static Pair pairMap(IF1 f, Pair p) { return p == null ? null : pair(callF(f, p.a), callF(f, p.b)); } static Pair pairMap(Pair p, Object f) { return pairMap(f, p); } static abstract class VF1 implements IVF1 { public abstract void get(A a); } // immutable, has strong refs // Do not run in a synchronized block - it goes wrong in the presence // of elaborate classloaders (like in Gazelle BEA) // see #1102990 and #1102991 final static class _MethodCache { final Class c; final HashMap> cache = new HashMap(); _MethodCache(Class c) { this.c = c; _init(); } void _init() { Class _c = c; java.lang.Module myModule = getClass().getModule(); boolean anyHiddenClasses = false; while (_c != null) { boolean exported = classIsExportedTo(_c, myModule); if (!exported) anyHiddenClasses = true; else for (Method m : _c.getDeclaredMethods()) if ((anyHiddenClasses || !isAbstract(m)) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); _c = _c.getSuperclass(); } // add default methods - this might lead to a duplication // because the overridden method is also added, but it's not // a problem except for minimal performance loss. // If any classes in the hierarchy were inaccessible, we add // all interface methods (see test_callForbiddenMethodByReflection for a test) for (Class intf : allInterfacesImplementedBy(c)) for (Method m : intf.getDeclaredMethods()) if ((anyHiddenClasses || m.isDefault()) && !reflection_isForbiddenMethod(m)) multiMapPut(cache, m.getName(), makeAccessible(m)); } // Returns only matching methods 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); } } 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); } } //Cl allMethods() { ret allValues(cache); } } static class Matches { String[] m; Matches() {} Matches(String... m) { this.m = m;} String get(int i) { return i < m.length ? m[i] : null; } String unq(int i) { return unquote(get(i)); } String tlc(int i) { return unq(i).toLowerCase(); } boolean bool(int i) { return "true".equals(unq(i)); } String rest() { return m[m.length-1]; } // for matchStart 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); } } // for the version with MasterSymbol (used WAY back in "Smart Bot"!) see #1010608 static class Symbol implements CharSequence { String text; Symbol() {} Symbol(String text, boolean dummy) { this.text = text;} // weird signature to prevent accidental calling public int hashCode() { return _hashCode(text); } public String toString() { return text; } public boolean equals(Object o) { return this == o; } // implementation of CharSequence methods public int length() { return text.length(); } public char charAt(int index) { return text.charAt(index); } public CharSequence subSequence(int start, int end) { return text.substring(start, end); } } static class Var implements IVar, ISetter { Var() {} Var(A v) { this.v = v;} A v; // you can access this directly if you use one thread 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 void clear() { set(null); } public synchronized A getAndSet(A a) { var value = v; set(a); return value; } public IF0 getter() { return () -> get(); } public IVF1 setter() { return __42 -> set(__42); } public String toString() { return str(this.get()); } } static class Scorer { double score, total; List successes, errors; // set to non-null if you want them filled boolean verboseFailures, verboseAll; final void add(double score){ addZeroToOne(score); } void addZeroToOne(double score) { ++total; this.score += clamp(score, 0, 1); } void addZeroToOneError(double error) { addZeroToOne(1-error); } void addError() { add(false); } void addError(A info) { add(false, info); } void error(A info) { addError(info); } void addOK() { add(true); } void addOK(A info) { add(true, info); } void ok() { addOK(); } void ok(A info) { addOK(info); } boolean add(boolean correct) { ++total; if (correct) ++score; return correct; } boolean add(boolean correct, A info) { main.add(correct ? successes : errors, info); if (verboseAll || verboseFailures && !correct) _print((correct ? "[GOOD] " : "[BAD] ") + info); return add(correct); } // works if you use Scorer or Scorer void eq(Object a, Object b) { if (_eq(a, b)) add(true); else add(false, (A) (a + " != " + b)); } void print() { main.print(toString()); } public String toString() { return formatDouble(ratioToPercent(score, total), 1) + "% correct (n=" + formatDouble(total, 1) + ")"; } double get() { return ratioToPercent(score, total); } double percentScore() { return get(); } double score() { return get(); } boolean allCorrect() { return score == total; } void add(Scorer scorer) { if (scorer == null) return; total += scorer.total; score += scorer.score; addAll(successes, scorer.successes); addAll(errors, scorer.errors); } void collectErrors() { errors = new ArrayList(); } void collectSuccesses() { successes = new ArrayList(); } } static interface ITokCondition { boolean get(List tok, int i); // i = N Index } static abstract class TokCondition implements ITokCondition { public abstract boolean get(List tok, int i); // i = N Index } // In the newest pinging system (with flag PingV3), a ping source // is the object that "allows" some code to run. // When that code calls ping(), the ping source's action (if defined) // is triggered. // This allows randomly interrupting code execution, for example. static class PingSource { // returns true if it slept final public PingSource setAction(IF0 action){ return action(action); } public PingSource action(IF0 action) { this.action = action; return this; } final public IF0 getAction(){ return action(); } public IF0 action() { return action; } volatile IF0 action; // optional description of this ping source String text; // optional thread pool that this ping source likes to run in ThreadPool threadPool; PingSource() {} PingSource(ThreadPool threadPool) { this.threadPool = threadPool;} PingSource(ThreadPool threadPool, String text) { this.text = text; this.threadPool = threadPool;} PingSource(IF0 action) { this.action = action;} // returns true if it slept final boolean get() { var a = action; return a != null && a.get(); } final void ping() { var a = action; if (a != null) a.get(); } void cancel() { action = new Cancelled(); } class Cancelled implements IF0 { public Boolean get() { throw new PingSourceCancelledException(PingSource.this); } } class Encapsulated implements Runnable , IFieldsToList{ Runnable r; Encapsulated() {} Encapsulated(Runnable r) { this.r = r;}public Object[] _fieldsToList() { return new Object[] {r}; } public void run() { try { //System.out.println("Encapsulated running: " + r); try { pingSource_tl().set(PingSource.this); //System.out.println("Ping source set"); ping(); r.run(); //System.out.println("Done running"); } finally { //System.out.println("Finally"); pingSource_tl().set(null); } } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return PingSource.this + ": " + r; } } void dO(Runnable r) { if (r == null) return; threadPool.acquireThreadOrQueue(new Encapsulated(r)); } public String toString() { String t = text; return nempty(t) ? t : super.toString(); } ISleeper_v2 sleeper() { return threadPool.sleeper(); } } // records its full size (total value count) in a field now static class MultiMap implements IMultiMap { Map> data = new HashMap>(); int fullSize; MultiMap() {} MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } MultiMap(MultiMap map) { putAll(map); } MultiMap(Map> data) { this.data = data;} void put(A key, B value) { synchronized(data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); list.add(value); ++fullSize; }} void add(A key, B value) { put(key, value); } void addAll(A key, Collection values) { putAll(key, values); } void addAllIfNotThere(A key, Collection values) { synchronized(data) { for (B value : values) setPut(key, value); }} void setPut(A key, B value) { synchronized(data) { if (!containsPair(key, value)) put(key, value); }} boolean containsPair(A key, B value) { synchronized(data) { return get(key).contains(value); }} void putAll(Collection keys, B value) { synchronized(data) { for (A key : unnullForIteration(keys)) put(key, value); }} void putAll(A key, Collection values) { synchronized(data) { if (nempty(values)) getActual(key).addAll(values); }} void putAll(Iterable> pairs) { synchronized(data) { for (Pair p : unnullForIteration(pairs)) put(p.a, p.b); }} 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; }} List getOpt(A key) { synchronized(data) { return data.get(key); }} List getAndClear(A key) { synchronized(data) { List l = cloneList(data.get(key)); remove(key); return l; }} // returns actual mutable live list // creates the list if not there List getActual(A key) { synchronized(data) { List list = data.get(key); if (list == null) data.put(key, list = _makeEmptyList()); return list; }} void clean(A key) { synchronized(data) { List list = data.get(key); if (list != null && list.isEmpty()) { fullSize -= l(list); data.remove(key); } }} final public Set keys(){ return keySet(); } public Set keySet() { synchronized(data) { return data.keySet(); }} void remove(A key) { synchronized(data) { fullSize -= l(this.getOpt(key)); data.remove(key); }} final void remove(Pair p){ removePair(p); } void removePair(Pair p) { if (p != null) remove(p.a, p.b); } void remove(A key, B value) { synchronized(data) { List list = data.get(key); if (list != null) { if (list.remove(value)) fullSize--; if (list.isEmpty()) data.remove(key); } }} void clear() { synchronized(data) { data.clear(); }} boolean containsKey(A key) { synchronized(data) { return data.containsKey(key); }} B getFirst(A key) { synchronized(data) { List list = get(key); return list.isEmpty() ? null : list.get(0); }} void addAll(MultiMap map) { putAll(map); } void putAll(MultiMap map) { synchronized(data) { for (A key : map.keySet()) putAll(key, map.get(key)); }} void putAll(Map map) { synchronized(data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); }} final public int keyCount(){ return keysSize(); } public int keysSize() { synchronized(data) { return l(data); }} final public int fullSize(){ return size(); } public int size() { synchronized(data) { return fullSize; }} // expensive operation 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; }} Map> asMap() { synchronized(data) { return cloneMap(data); }} public boolean isEmpty() { synchronized(data) { return data.isEmpty(); }} // override in subclasses List _makeEmptyList() { return new ArrayList(); } // returns live lists Collection> allLists() { synchronized(data) { return new ArrayList(data.values()); } } Collection> values() { return allLists(); } List allValues() { return concatLists(data.values()); } Object mutex() { return data; } public String toString() { return "mm" + str(data); } Map> innerMap() { return data; } } // Note: This does have the values problem (complicated values can cause memory leaks) static class BetterThreadLocal { Map map = newWeakHashMap(); BetterThreadLocal() {} BetterThreadLocal(A value) { set(value); } boolean isSet() { return map.containsKey(currentThread()); } A get() { if (map.containsKey(currentThread())) return map.get(currentThread()); A value = initialValue(); set(value); return value; } A get(Thread thread) { return thread == null ? null : map.get(thread); } void set(A a) { map.put(currentThread(), a); } public A initialValue() { return null; } } interface IntSize { int size(); default boolean isEmpty() { return size() == 0; } } static interface IResourceLoader { String loadSnippet(String snippetID); String getTranspiled(String snippetID); // with libs int getSnippetType(String snippetID); String getSnippetTitle(String snippetID); File loadLibrary(String snippetID); //ifndef NoJavaXJar default File pathToJavaXJar() { return pathToJavaxJar_noResourceLoader(); } //endifndef // may return null, then caller compiles themselves default File getSnippetJar(String snippetID, String transpiledSrc) { return null; } } /* * @(#)WeakHashMap.java 1.5 98/09/30 * * Copyright 1998 by Sun Microsystems, Inc., * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A. * All rights reserved. * * This software is the confidential and proprietary information * of Sun Microsystems, Inc. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with Sun. */ // From https://github.com/mernst/plume-lib/blob/df0bfafc3c16848d88f4ea0ef3c8bf3367ae085e/java/src/plume/WeakHasherMap.java static final class WeakHasherMap extends AbstractMap implements Map { private Hasher hasher = null; /*@Pure*/ private boolean keyEquals(Object k1, Object k2) { return (hasher==null ? k1.equals(k2) : hasher.equals(k1, k2)); } /*@Pure*/ private int keyHashCode(Object k1) { return (hasher==null ? k1.hashCode() : hasher.hashCode(k1)); } // The WeakKey class can't be static because it depends on the hasher. // That in turn means that its methods can't be static. // However, I need to be able to call the methods such as create() that // were static in the original version of this code. // This finesses that. private /*@Nullable*/ WeakKey WeakKeyCreate(K k) { if (k == null) return null; else return new WeakKey(k); } private /*@Nullable*/ WeakKey WeakKeyCreate(K k, ReferenceQueue q) { if (k == null) return null; else return new WeakKey(k, q); } // Cannot be a static class: uses keyHashCode() and keyEquals() private final class WeakKey extends WeakReference { private int hash; /* Hashcode of key, stored here since the key may be tossed by the GC */ private WeakKey(K k) { super(k); hash = keyHashCode(k); } private /*@Nullable*/ WeakKey create(K k) { if (k == null) return null; else return new WeakKey(k); } private WeakKey(K k, ReferenceQueue q) { super(k, q); hash = keyHashCode(k); } private /*@Nullable*/ WeakKey create(K k, ReferenceQueue q) { if (k == null) return null; else return new WeakKey(k, q); } /* A WeakKey is equal to another WeakKey iff they both refer to objects that are, in turn, equal according to their own equals methods */ /*@Pure*/ @Override public boolean equals(/*@Nullable*/ Object o) { if (o == null) return false; // never happens if (this == o) return true; // This test is illegal because WeakKey is a generic type, // so use the getClass hack below instead. // if (!(o instanceof WeakKey)) return false; if (!(o.getClass().equals(WeakKey.class))) return false; Object t = this.get(); @SuppressWarnings("unchecked") Object u = ((WeakKey)o).get(); if ((t == null) || (u == null)) return false; if (t == u) return true; return keyEquals(t, u); } /*@Pure*/ @Override public int hashCode() { return hash; } } /* Hash table mapping WeakKeys to values */ private HashMap hash; /* Reference queue for cleared WeakKeys */ private ReferenceQueue queue = new ReferenceQueue(); /* Remove all invalidated entries from the map, that is, remove all entries whose keys have been discarded. This method should be invoked once by each public mutator in this class. We don't invoke this method in public accessors because that can lead to surprising ConcurrentModificationExceptions. */ @SuppressWarnings("unchecked") private void processQueue() { WeakKey wk; while ((wk = (WeakKey)queue.poll()) != null) { // unchecked cast hash.remove(wk); } } /* -- Constructors -- */ /** * Constructs a new, empty WeakHashMap with the given * initial capacity and the given load factor. * * @param initialCapacity the initial capacity of the * WeakHashMap * * @param loadFactor the load factor of the WeakHashMap * * @throws IllegalArgumentException If the initial capacity is less than * zero, or if the load factor is * nonpositive */ public WeakHasherMap(int initialCapacity, float loadFactor) { hash = new HashMap(initialCapacity, loadFactor); } /** * Constructs a new, empty WeakHashMap with the given * initial capacity and the default load factor, which is * 0.75. * * @param initialCapacity the initial capacity of the * WeakHashMap * * @throws IllegalArgumentException If the initial capacity is less than * zero */ public WeakHasherMap(int initialCapacity) { hash = new HashMap(initialCapacity); } /** * Constructs a new, empty WeakHashMap with the default * capacity and the default load factor, which is 0.75. */ public WeakHasherMap() { hash = new HashMap(); } /** * Constructs a new, empty WeakHashMap with the default * capacity and the default load factor, which is 0.75. * The WeakHashMap uses the specified hasher for hashing * keys and comparing them for equality. * @param h the Hasher to use when hashing values for this map */ public WeakHasherMap(Hasher h) { hash = new HashMap(); hasher = h; } /* -- Simple queries -- */ /** * Returns the number of key-value mappings in this map. * Note: In contrast to most implementations of the * Map interface, the time required by this operation is * linear in the size of the map. */ /*@Pure*/ @Override public int size() { return entrySet().size(); } /** * Returns true if this map contains no key-value mappings. */ /*@Pure*/ @Override public boolean isEmpty() { return entrySet().isEmpty(); } /** * Returns true if this map contains a mapping for the * specified key. * * @param key the key whose presence in this map is to be tested */ /*@Pure*/ @Override public boolean containsKey(Object key) { @SuppressWarnings("unchecked") K kkey = (K) key; return hash.containsKey(WeakKeyCreate(kkey)); } /* -- Lookup and modification operations -- */ /** * Returns the value to which this map maps the specified key. * If this map does not contain a value for this key, then return * null. * * @param key the key whose associated value, if any, is to be returned */ /*@Pure*/ @Override public /*@Nullable*/ V get(Object key) { // type of argument is Object, not K @SuppressWarnings("unchecked") K kkey = (K) key; return hash.get(WeakKeyCreate(kkey)); } /** * Updates this map so that the given key maps to the given * value. If the map previously contained a mapping for * key then that mapping is replaced and the previous value is * returned. * * @param key the key that is to be mapped to the given * value * @param value the value to which the given key is to be * mapped * * @return the previous value to which this key was mapped, or * null if if there was no mapping for the key */ @Override public V put(K key, V value) { processQueue(); return hash.put(WeakKeyCreate(key, queue), value); } /** * Removes the mapping for the given key from this map, if * present. * * @param key the key whose mapping is to be removed * * @return the value to which this key was mapped, or null if * there was no mapping for the key */ @Override public V remove(Object key) { // type of argument is Object, not K processQueue(); @SuppressWarnings("unchecked") K kkey = (K) key; return hash.remove(WeakKeyCreate(kkey)); } /** * Removes all mappings from this map. */ @Override public void clear() { processQueue(); hash.clear(); } /* -- Views -- */ /* Internal class for entries */ // This can't be static, again because of dependence on hasher. @SuppressWarnings("TypeParameterShadowing") private final class Entry implements Map.Entry { private Map.Entry ent; private K key; /* Strong reference to key, so that the GC will leave it alone as long as this Entry exists */ Entry(Map.Entry ent, K key) { this.ent = ent; this.key = key; } /*@Pure*/ @Override public K getKey() { return key; } /*@Pure*/ @Override public V getValue() { return ent.getValue(); } @Override public V setValue(V value) { return ent.setValue(value); } /*@Pure*/ private boolean keyvalEquals(K o1, K o2) { return (o1 == null) ? (o2 == null) : keyEquals(o1, o2); } /*@Pure*/ private boolean valEquals(V o1, V o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } /*@Pure*/ @SuppressWarnings("NonOverridingEquals") public boolean equals(Map.Entry e /* Object o*/) { // if (! (o instanceof Map.Entry)) return false; // Map.Entry e = (Map.Entry)o; return (keyvalEquals(key, e.getKey()) && valEquals(getValue(), e.getValue())); } /*@Pure*/ @Override public int hashCode() { V v; return (((key == null) ? 0 : keyHashCode(key)) ^ (((v = getValue()) == null) ? 0 : v.hashCode())); } } /* Internal class for entry sets */ private final class EntrySet extends AbstractSet> { Set> hashEntrySet = hash.entrySet(); @Override public Iterator> iterator() { return new Iterator>() { Iterator> hashIterator = hashEntrySet.iterator(); Map.Entry next = null; @Override public boolean hasNext() { while (hashIterator.hasNext()) { Map.Entry ent = hashIterator.next(); WeakKey wk = ent.getKey(); K k = null; if ((wk != null) && ((k = wk.get()) == null)) { /* Weak key has been cleared by GC */ continue; } next = new Entry(ent, k); return true; } return false; } @Override public Map.Entry next() { if ((next == null) && !hasNext()) throw new NoSuchElementException(); Map.Entry e = next; next = null; return e; } @Override public void remove() { hashIterator.remove(); } }; } /*@Pure*/ @Override public boolean isEmpty() { return !(iterator().hasNext()); } /*@Pure*/ @Override public int size() { int j = 0; for (Iterator> i = iterator(); i.hasNext(); i.next()) j++; return j; } @Override public boolean remove(Object o) { processQueue(); if (!(o instanceof Map.Entry)) return false; @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry)o; // unchecked cast Object ev = e.getValue(); WeakKey wk = WeakKeyCreate(e.getKey()); Object hv = hash.get(wk); if ((hv == null) ? ((ev == null) && hash.containsKey(wk)) : hv.equals(ev)) { hash.remove(wk); return true; } return false; } /*@Pure*/ @Override public int hashCode() { int h = 0; for (Iterator> i = hashEntrySet.iterator(); i.hasNext(); ) { Map.Entry ent = i.next(); WeakKey wk = ent.getKey(); Object v; if (wk == null) continue; h += (wk.hashCode() ^ (((v = ent.getValue()) == null) ? 0 : v.hashCode())); } return h; } } private /*@Nullable*/ Set> entrySet = null; /** * Returns a Set view of the mappings in this map. */ /*@SideEffectFree*/ @Override public Set> entrySet() { if (entrySet == null) entrySet = new EntrySet(); return entrySet; } // find matching key K findKey(Object key) { processQueue(); K kkey = (K) key; // TODO: use replacement for HashMap to avoid reflection WeakKey wkey = WeakKeyCreate(kkey); WeakKey found = hashMap_findKey(hash, wkey); return found == null ? null : found.get(); } } // just a marker interface for non-persistable classes interface TransientObject {} static class proxy_InvocationHandler implements InvocationHandler { Object target; proxy_InvocationHandler() {} proxy_InvocationHandler(Object target) { this.target = target;} public Object invoke(Object proxy, Method method, Object[] args) { return call(target, method.getName(), unnull(args)); } } // -has fast nextElement() and prevElement() // -design allows for more functions like reordering the list // -Saves up to 34% in space over LinkedHashSet // (e.g. 22% for a set of 1,000 Ints) static class CompactLinkedHashSet extends AbstractSet { UnsynchronizedCompactHashSet> entries = new UnsynchronizedCompactHashSet(); Entry head, tail; static class Entry { A value; Entry prev, next; public int hashCode() { return _hashCode(value); } // "magic" equals function for CompactHashSet lookup without temp object public boolean equals(Object o) { return o == this || eq(value, o); } } public boolean add(A a) { if (entries.contains(a)) return false; Entry n = new Entry(); n.value = a; n.prev = tail; if (tail != null) tail.next = n; tail = n; if (head == null) head = n; entries.add(n); return true; } public boolean remove(Object a) { return remove(entries.find(a)); } public boolean remove(Entry node) { if (node == null) return false; if (node.next != null) node.next.prev = node.prev; else tail = node.prev; if (node.prev != null) node.prev.next = node.next; else head = node.next; entries.remove(node); return true; } public int size() { return entries.size(); } public IterableIterator iterator() { return new IterableIterator() { Entry entry = head, prev = null; public boolean hasNext() { return entry != null; } public A next() { A a = entry.value; prev = entry; entry = entry.next; return a; } // untested public void remove() { if (prev == null) throw new IllegalStateException(); CompactLinkedHashSet.this.remove(prev); prev = null; } }; } public void clear() { entries.clear(); head = tail = null; } public boolean contains(Object a) { return entries.contains(a); } public A find(Object o) { Entry e = entries.find(o); return e == null ? null : e.value; } public A prevElement(A a) { Entry e = entries.find(a); if (e == null || e.prev == null) return null; return e.prev.value; } public A nextElement(A a) { Entry e = entries.find(a); if (e == null || e.next == null) return null; return e.next.value; } public A first() { return head == null ? null : head.value; } public A last() { return tail == null ? null : tail.value; } boolean removeIfSame(Object o) { A value = find(o); if (value == o) { remove(value); return true; } return false; } } static class Pair implements Comparable> { final public Pair setA(A a){ return a(a); } public Pair a(A a) { this.a = a; return this; } final public A getA(){ return a(); } public A a() { return a; } A a; final public Pair setB(B b){ return b(b); } public Pair b(B b) { this.b = b; return this; } final public B getB(){ return b(); } public B b() { return b; } B b; Pair() {} 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); } } static class Fail extends RuntimeException implements IFieldsToList{ Object[] objects; Fail() {} Fail(Object... objects) { this.objects = objects;}public Object[] _fieldsToList() { return new Object[] {objects}; } Fail(Throwable cause, Object... objects) { super(cause); this.objects = objects; } public String toString() { return joinNemptiesWithColon("Fail", getMessage()); } public String getMessage() { return commaCombine(getCause(), objects); } } static interface IResourceHolder { A add(A a); Collection takeAll(); } static class Rect implements WidthAndHeight , IFieldsToList{ static final String _fieldOrder = "x y w h"; int x; int y; int w; int h; Rect() {} Rect(int x, int y, int w, int h) { this.h = h; this.w = w; this.y = y; this.x = x;} public boolean equals(Object o) { if (!(o instanceof Rect)) return false; Rect __1 = (Rect) o; return x == __1.x && y == __1.y && w == __1.w && h == __1.h; } public int hashCode() { int h = 2543108; h = boostHashCombine(h, _hashCode(x)); h = boostHashCombine(h, _hashCode(y)); h = boostHashCombine(h, _hashCode(w)); h = boostHashCombine(h, _hashCode(h)); return h; } public Object[] _fieldsToList() { return new Object[] {x, y, w, h}; } Rect(Rectangle r) { x = r.x; y = r.y; w = r.width; h = r.height; } Rect(Pt p, int w, int h) { this.h = h; this.w = w; x = p.x; y = p.y; } Rect(Rect r) { x = r.x; y = r.y; w = r.w; h = r.h; } final Rectangle getRectangle() { return new Rectangle(x, y, w, h); } public String toString() { return x + "," + y + " / " + w + "," + h; } final int x1() { return x; } final int y1() { return y; } final int x2() { return x + w; } final int y2() { return y + h; } final boolean contains(Pt p) { return contains(p.x, p.y); } final boolean contains(int _x, int _y) { return _x >= x && _y >= y && _x < x+w && _y < y+h; } final boolean contains(Rectangle r) { return rectContains(this, r); } final boolean empty() { return w <= 0 || h <= 0; } final public int getWidth() { return w; } final public int getHeight() { return h; } final public int area() { return w*h; } final public int x() { return x; } final public int y() { return y; } WidthAndHeight widthAndHeight() { return main.widthAndHeight(w, h); } } static class Pt implements Comparable, IDoublePt { int x, y; Pt() {} Pt(Point p) { x = p.x; y = p.y; } Pt(int x, int y) { this.y = y; this.x = x;} Point getPoint() { return new Point(x, y); } public boolean equals(Object o) { return o instanceof Pt && x == ((Pt) o).x && y == ((Pt) o).y; } public int hashCode() { return boostHashCombine(x, y); } // compare in scan order public int compareTo(Pt p) { if (y != p.y) return cmp(y, p.y); return cmp(x, p.x); } public String toString() { return x + ", " + y; } double length() { return sqrt(x*x+y*y); } public Pt minus(Pt p) { return ptMinus(this, p); } public double x_double() { return x; } public double y_double() { return y; } } static class HttpFromFileSystem { File baseDir; boolean serveDirectoryListings = false; // default to false boolean serveIndexHTML = true; boolean maxCache = false; // treat files as immutable boolean debug = false; boolean sendLastModified = true; final public HttpFromFileSystem setServeDirectoriesAsZipFiles(boolean serveDirectoriesAsZipFiles){ return serveDirectoriesAsZipFiles(serveDirectoriesAsZipFiles); } public HttpFromFileSystem serveDirectoriesAsZipFiles(boolean serveDirectoriesAsZipFiles) { this.serveDirectoriesAsZipFiles = serveDirectoriesAsZipFiles; return this; } final public boolean getServeDirectoriesAsZipFiles(){ return serveDirectoriesAsZipFiles(); } public boolean serveDirectoriesAsZipFiles() { return serveDirectoriesAsZipFiles; } boolean serveDirectoriesAsZipFiles = false; Map params, headers; String baseLink = ""; HttpFromFileSystem() {} HttpFromFileSystem(File baseDir) { this.baseDir = baseDir;} HttpFromFileSystem(File baseDir, boolean serveDirectoryListings) { this.serveDirectoryListings = serveDirectoryListings; this.baseDir = baseDir;} Object serve(String uri, Map params) { return serve(uri, params, null); } Object serve(String uri, Map params, Map headers) { if (eq("1", params.get("maxCache"))) maxCache = true; this.params = params; this.headers = headers; return serve(uri); } Object serve(String uri) { String originalURI = uri; uri = urldecode(uri); List parts = nempties(splitAtSlash(uri)); if (baseDir == null) return serve404("No base directory set"); // process . and .. for (int i = 0; i < l(parts); i++) if (eq(parts.get(i), ".")) parts.remove(i); else if (eq(parts.get(i), "..")) if (i == 0) throw fail(".. leading nowhere: " + uri); else { parts.remove(i); parts.remove(--i); } if (!all(__49 -> validFileName(__49), parts)) { print("Parts: " + quoteAll(parts)); throw fail("Bad path: " + uri); } File f = baseDir; if (!isDirectory(baseDir)) print("Base dir not found: " + f2s(f)); for (String part : parts) { f = newFile(f, part); if (!fileExists(f)) return serve404("Path not found: " + uri); } print("Trying to serve: " + f2s(f)); if (isDirectory(f)) if (eq(params.get("asZip"), "1")) return serveDirAsZip(f); else return serveListingOrIndexHTML(uri, f, originalURI); else return serveFile(f); } transient IF1 addHeaders; Object addHeaders(Object response) { return addHeaders != null ? addHeaders.get(response) : addHeaders_base(response); } final Object addHeaders_fallback(IF1 _f, Object response) { return _f != null ? _f.get(response) : addHeaders_base(response); } Object addHeaders_base(Object response) { if (maxCache) return subBot_maxCacheHeaders(response); return response; } transient IF1 serveFile; Object serveFile(File f) { return serveFile != null ? serveFile.get(f) : serveFile_base(f); } final Object serveFile_fallback(IF1 _f, File f) { return _f != null ? _f.get(f) : serveFile_base(f); } Object serveFile_base(File f) { Object response; String range = mapGet(headers, "range"); String ct = contentTypeForFile(f); if (nempty(range)) { print("Serving range query " + f + ": " + range); response = subBot_serveFileRange(f, ct, range); } else { response = main.serveFile(f, ct); if (sendLastModified) addHeader("Last-Modified", formatDateForLastModifiedHeader(f.lastModified()), response); } return addHeaders(response); } Object serveListingOrIndexHTML(String uri, File dir, String originalURI) { if (serveIndexHTML) { File index = newFile(dir, "index.html"); if (fileExists(index)) { /*if (nempty(originalURI) && !endsWithSlash(originalURI)) ret subBot_serveRedirect(baseLink + originalURI + "/");*/ return serveFile(index); } } return serveListing(uri, dir, originalURI); } Object serveListing(String uri, File dir, String originalURI) { if (!serveDirectoryListings) throw fail("Can't serve directory listings"); // take care of directory listing without trailing slash in URI // XXX broken? S local = addSlashIfNempty(afterLast("/" + uri, '/')); String local = addSlashIfNempty(uri); var names = listFileNames(dir); sortInPlaceByCalculatedField(names, name -> { File f = newFile(dir, name); return f.isDirectory() ? pair(false, lower(name)) : pair(true, modificationTime(f)); }); String parent = dropAfterLastSlashOrEmpty(dropTrailingSlash(uri)); String title = "Directory listing of " + htmlEncode2(dropTrailingSlash(baseLink + uri)); String debugText = !debug ? "" : htmlEncode2(renderVars("baseLink", baseLink, "uri", uri, "local", local, "parent", parent)); Object body = postProcessDirListing(h3(title) + pUnlessEmpty(debugText) + (l(parent) >= l(uri) ? "" : p(ahref(addSlashSuffix(baseLink + parent), "Parent directory"))) + ul(map(names, name -> { File f = newFile(dir, name); boolean isDir = isDirectory(f); if (isDir) name += "/"; List l = new ArrayList(); // make the actual link to file/directroy l.add(ahref(baseLink + local + name, htmlEncode2(name))); if (isDir && serveDirectoriesAsZipFiles) l.add(ahref(appendParamsToURL(baseLink + local + name, "asZip" , 1), "[download zip]")); if (!isDir) l.add(bracketed(joinNemptiesWithComma(fileInfoHintsWithDate(f)))); return hcombine(l); }))); return hhtml( hhead(hcombine( htitle_decode(title), hsansserif(), hmobilefix()) + hbody(body))); } transient IF1 contentTypeForFile; String contentTypeForFile(File f) { return contentTypeForFile != null ? contentTypeForFile.get(f) : contentTypeForFile_base(f); } final String contentTypeForFile_fallback(IF1 _f, File f) { return _f != null ? _f.get(f) : contentTypeForFile_base(f); } String contentTypeForFile_base(File f) { return or2(extensionToMimeType(fileExtension(f)), binaryMimeType()); } transient IF1 validFileName; boolean validFileName(String name) { return validFileName != null ? validFileName.get(name) : validFileName_base(name); } final boolean validFileName_fallback(IF1 _f, String name) { return _f != null ? _f.get(name) : validFileName_base(name); } boolean validFileName_base(String name) { return isValidFileName(name); } transient IF1 postProcessDirListing; Object postProcessDirListing(String html) { return postProcessDirListing != null ? postProcessDirListing.get(html) : postProcessDirListing_base(html); } final Object postProcessDirListing_fallback(IF1 _f, String html) { return _f != null ? _f.get(html) : postProcessDirListing_base(html); } Object postProcessDirListing_base(String html) { return html; } Object serveDirAsZip(File dir) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(baos); dir2zip_recurse(dir, zipOut, fileName(dir) + "/", 0); zipOut.close(); byte[] data = baos.toByteArray(); String zipName = dir.getName() + "-" + ymdMinusHMS() + ".zip"; return addFilenameHeader(zipName, subBot_serveInputStream(byteArrayInputStream(data), zipMimeType())); } catch (Exception __e) { throw rethrow(__e); } } } static abstract class F0 { abstract A get(); } static abstract class F1 { abstract B get(A a); } // you still need to implement hasNext() and next() static abstract class IterableIterator implements Iterator, Iterable { public Iterator iterator() { return this; } public void remove() { unsupportedOperation(); } } interface PCallPolicy { void handlePcallFail(Throwable e); } // elements are put to front when added (not when accessed) static class MRUCache extends LinkedHashMap { int maxSize = 10; MRUCache() {} MRUCache(int maxSize) { this.maxSize = maxSize;} protected boolean removeEldestEntry(Map.Entry eldest) { return size() > maxSize; } Object _serialize() { return ll(maxSize, cloneLinkedHashMap(this)); } static MRUCache _deserialize(List l) { MRUCache m = new MRUCache(); m.maxSize = (int) first(l); m.putAll((LinkedHashMap) second(l)); return m; } } public static interface IF0 { A get(); } static interface Hasher { int hashCode(A a); boolean equals(A a, A b); } static interface IContentsIndexedList2 extends List { TreeSet indicesOf_treeSetOfHasIndex(A o); } static abstract class CloseableIterableIterator extends IterableIterator implements AutoCloseable { public void close() throws Exception {} } static interface IF2 { C get(A a, B b); } static interface IF1 { B get(A a); } // TODO: subclass RuntimeException and use Meta instead of DynamicObject static class PersistableThrowable extends DynamicObject { String className; String msg; String stacktrace; final public PersistableThrowable setActualThrowable(Throwable actualThrowable){ return actualThrowable(actualThrowable); } public PersistableThrowable actualThrowable(Throwable actualThrowable) { this.actualThrowable = actualThrowable; return this; } final public Throwable getActualThrowable(){ return actualThrowable(); } public Throwable actualThrowable() { return actualThrowable; } transient Throwable actualThrowable; PersistableThrowable() {} PersistableThrowable(Throwable e) { actualThrowable = 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; } RuntimeException asRuntimeException() { if (actualThrowable != null) return main.asRuntimeException(actualThrowable); return new Fail(this); } } static interface IVF1 { void get(A a); } static interface IVF2 { void get(A a, B b); } static interface IIntPred { boolean get(int a); } static class HasIndex implements Comparable { int idx; HasIndex() {} HasIndex(int idx) { this.idx = idx;} public int compareTo(HasIndex h) { return idx-h.idx; } final int get() { return idx; } } static class Cache { Object maker; // func -> A A value; long loaded; static boolean debug = false; long changeCount; Lock lock = lock(); Cache() {} Cache(Object maker) { this.maker = maker;} Cache(IF0 maker) { this.maker = maker;} A get() { if (hasLock(lock)) return value; // Must be called from within maker Lock __0 = lock; lock(__0); try { if (loaded == 0) { value = make(); changeCount++; loaded = sysNow(); } return value; } finally { unlock(__0); } } void clear() { Lock __1 = lock; lock(__1); try { if (debug && loaded != 0) print("Clearing cache"); value = null; changeCount++; loaded = 0; } finally { unlock(__1); } } // clear if older than x seconds // 0 does not do anything void clear(double seconds) { Lock __2 = lock; lock(__2); try { if (seconds != 0 && loaded != 0 && sysNow() >= loaded+seconds*1000) clear(); } finally { unlock(__2); } } // override void set(A a) { Lock __3 = lock; lock(__3); try { value = a; ++changeCount; loaded = sysNow(); } finally { unlock(__3); } } A make() { return (A) callF(maker); } } static class PingSourceCancelledException extends RuntimeException implements IFieldsToList{ PingSource pingSource; PingSourceCancelledException() {} PingSourceCancelledException(PingSource pingSource) { this.pingSource = pingSource;} public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + pingSource + ")"; }public Object[] _fieldsToList() { return new Object[] {pingSource}; } } static interface IFieldsToList { Object[] _fieldsToList(); } interface ISleeper_v2 { default Sleeping doLater(long targetTime, Runnable r) { return doLater(sysTimeToTimestamp(targetTime), r); } Sleeping doLater(Timestamp targetTime, Runnable r); public default Sleeping doAfter(double seconds, Runnable r) { return doLater(tsNow().plusSeconds(seconds), r); } } static interface ISetter { void set(A a); } // The idea is to leave max as the actual number of cores the system // has (numberOfCores()), and in case of being fully booked, raise an // alert (customerMustWaitAlert) which can be handled by a strategy // object (different reactions are possible). // If nothing is done in such an event, clients are processed serially // (no guarantees of order), split up among the available threads. /* SYNChronisation order: 1. PooledThread 2. ThreadPool */ static class ThreadPool implements AutoCloseable { int max = numberOfCores(); List all = new ArrayList(); Set used = new HashSet(); Set free = new HashSet(); boolean verbose, retired; // our own ping surce so we can start threads & keep them running class InternalPingSource extends PingSource {} InternalPingSource internalPingSource = new InternalPingSource(); MultiSleeper sleeper = new MultiSleeper(); ThreadPool() {} ThreadPool(int max) { this.max = max;} synchronized int maxSize() { return max; } synchronized int total() { return l(used)+l(free); } transient Set onCustomerMustWaitAlert; public ThreadPool onCustomerMustWaitAlert(Runnable r) { onCustomerMustWaitAlert = createOrAddToSyncLinkedHashSet(onCustomerMustWaitAlert, r); return this; } public ThreadPool removeCustomerMustWaitAlertListener(Runnable r) { main.remove(onCustomerMustWaitAlert, r); return this; } public void customerMustWaitAlert() { if (onCustomerMustWaitAlert != null) for (var listener : onCustomerMustWaitAlert) pcallF_typed(listener); } void fireCustomerMustWaitAlert() { vmBus_send("customerMustWaitAlert", this, currentThread()); customerMustWaitAlert(); } // DOESN'T WAIT. adds action to a thread's queue if nothing is // available immediately. PooledThread acquireThreadOrQueue(Runnable action) { if (action == null) return null; PooledThread t; synchronized(this) { if (_hasFreeAfterCreating()) { t = _firstFreeThread(); markUsed(t); } else t = _anyThread(); } t.addWork(action); // will move it from free to used return t; } // run in synchronized block boolean _hasFreeAfterCreating() { checkNotRetired(); if (nempty(free)) return true; if (total() < max) { PooledThread t = newThread(); all.add(t); free.add(t); return true; } return false; } // WAITS until thread is available PooledThread acquireThreadOrWait(Runnable action) { try { if (action == null) return null; PooledThread t; while (true) { synchronized(this) { if (_hasFreeAfterCreating()) { t = _firstFreeThread(); break; } else _waitWaitWait(); } } t.addWork(action); return t; } catch (Exception __e) { throw rethrow(__e); } } PooledThread _firstFreeThread() { return first(free); } PooledThread _anyThread() { return random(used); } class PooledThread extends Thread { PooledThread(String name) { super(name); } AppendableChain q; synchronized Runnable _grabWorkOrSleep() { try { Runnable r = first(q); if (r == null) { markFree(this); if (verbose) print("Thread sleeps"); synchronized(this) { wait(); } if (verbose) print("Thread woke up"); return null; } q = popFirst(q); return r; } catch (Exception __e) { throw rethrow(__e); } } public void run() { try { pingSource_tl().set(internalPingSource); while (!retired()) { ping(); Runnable r = _grabWorkOrSleep(); if (verbose) print(this + " work: " + r); if (r != null) try { if (verbose) print(this + " running: " + r); r.run(); pingSource_tl().set(internalPingSource); if (verbose) print(this + " done"); } catch (Throwable e) { pingSource_tl().set(internalPingSource); if (verbose) print(this + " error"); printStackTrace(e); } finally { pingSource_tl().set(internalPingSource); if (verbose) print("ThreadPool finally"); } } } catch (Exception __e) { throw rethrow(__e); } } synchronized boolean isEmpty() { return empty(q); } // append to q (do later) void addWork(Runnable r) { if (verbose) print("Added work to " + this + ": " + r); synchronized(this) { q = chainPlus(q, r); notifyAll(); } } } PooledThread newThread() { PooledThread t = new PooledThread("Thread Pool Inhabitant " + n2(total()+1)); t.start(); return t; } synchronized void markFree(PooledThread t) { used.remove(t); free.add(t); notifyAll(); } synchronized void markUsed(PooledThread t) { free.remove(t); used.add(t); } synchronized public String toString() { return retired() ? "Retired ThreadPool" : "ThreadPool " + roundBracket(commaCombine( n2(used) + " used out of " + n2(total()), max <= total() ? null : "could grow to " + n2(max))); } synchronized boolean retired() { return retired; } synchronized void retire() { if (verbose) print("ThreadPool Retiring"); retired = true; for (var thread : free) syncNotifyAll(thread); // wake it up so it exits } void checkNotRetired() { if (retired()) throw fail("retired"); } // We could do a soft-close here (stop the idle threads, let running threads finish, then end those too, stop accepting new orders) // or a hard close (interrupt all threads, stop accepting new orders) synchronized public void close() { try { retire(); } catch (Exception __e) { throw rethrow(__e); } } // run in synchronized block void _waitWaitWait() { try { do { fireCustomerMustWaitAlert(); wait(); checkNotRetired(); } while (empty(free)); } catch (Exception __e) { throw rethrow(__e); } } void dO(String text, Runnable r) { if (r == null) return; new PingSource(this, text).dO(r); } ISleeper_v2 sleeper() { return sleeper; } } interface IMultiMap { public Set keySet(); public Collection get(A a); public int size(); public int keyCount(); } /* * #! * Ontopia Engine * #- * Copyright (C) 2001 - 2013 The Ontopia Project * #- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * !# */ // modified by Stefan Reich // Implements the Set interface more compactly than // java.util.HashSet by using a closed hashtable. // Note: equals is always called on the _stored_ object, not the one // passed as an argument to find(), contains() etc. // (In case you want to put special magic in your equals() function) static class UnsynchronizedCompactHashSet extends java.util.AbstractSet { protected final static int INITIAL_SIZE = 3; public final static double LOAD_FACTOR = 0.75; protected final static Object nullObject = new Object(); protected final static Object deletedObject = new Object(); protected int elements; protected int freecells; protected A[] objects; protected int modCount; UnsynchronizedCompactHashSet() { this(INITIAL_SIZE); } UnsynchronizedCompactHashSet(int size) { // NOTE: If array size is 0, we get a // "java.lang.ArithmeticException: / by zero" in add(Object). objects = (A[]) new Object[(size==0 ? 1 : size)]; elements = 0; freecells = objects.length; modCount = 0; } UnsynchronizedCompactHashSet(Collection c) { this(c.size()); addAll(c); } @Override public Iterator iterator() { return new CompactHashIterator(); } @Override public int size() { return elements; } @Override public boolean isEmpty() { return elements == 0; } @Override public boolean contains(Object o) { return find(o) != null; } A find(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; // search for the object (continue while !null and !this object) while(objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset*2 + 1; if (offset == -1) offset = 2; } return objects[index]; } boolean removeIfSame(Object o) { A value = find(o); if (value == o) { remove(value); return true; } return false; } @Override public boolean add(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; int deletedix = -1; // search for the object (continue while !null and !this object) while(objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { // if there's a deleted object here we can put this object here, // provided it's not in here somewhere else already if (objects[index] == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset*2 + 1; if (offset == -1) offset = 2; } if (objects[index] == null) { // wasn't present already if (deletedix != -1) // reusing a deleted cell index = deletedix; else freecells--; modCount++; elements++; // here we face a problem regarding generics: // add(A o) is not possible because of the null Object. We cant do 'new A()' or '(A) new Object()' // so adding an empty object is a problem here // If (! o instanceof A) : This will cause a class cast exception // If (o instanceof A) : This will work fine objects[index] = (A) o; // do we need to rehash? if (1 - (freecells / (double) objects.length) > LOAD_FACTOR) rehash(); return true; } else // was there already return false; } @Override public boolean remove(Object o) { if (o == null) o = nullObject; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % objects.length; int offset = 1; // search for the object (continue while !null and !this object) while(objects[index] != null && !(objects[index].hashCode() == hash && objects[index].equals(o))) { index = ((index + offset) & 0x7FFFFFFF) % objects.length; offset = offset*2 + 1; if (offset == -1) offset = 2; } // we found the right position, now do the removal if (objects[index] != null) { // we found the object // same problem here as with add objects[index] = (A) deletedObject; modCount++; elements--; return true; } else // we did not find the object return false; } @Override public void clear() { elements = 0; for (int ix = 0; ix < objects.length; ix++) objects[ix] = null; freecells = objects.length; modCount++; } @Override public Object[] toArray() { Object[] result = new Object[elements]; Object[] objects = this.objects; int pos = 0; for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) { if (objects[i] == nullObject) result[pos++] = null; else result[pos++] = objects[i]; } // unchecked because it should only contain A return result; } // not sure if this needs to have generics @Override public T[] toArray(T[] a) { int size = elements; if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); A[] objects = this.objects; int pos = 0; for (int i = 0; i < objects.length; i++) if (objects[i] != null && objects[i] != deletedObject) { if (objects[i] == nullObject) a[pos++] = null; else a[pos++] = (T) objects[i]; } return a; } protected void rehash() { int garbagecells = objects.length - (elements + freecells); if (garbagecells / (double) objects.length > 0.05) // rehash with same size rehash(objects.length); else // rehash with increased capacity rehash(objects.length*2 + 1); } protected void rehash(int newCapacity) { int oldCapacity = objects.length; @SuppressWarnings("unchecked") A[] newObjects = (A[]) new Object[newCapacity]; for (int ix = 0; ix < oldCapacity; ix++) { Object o = objects[ix]; if (o == null || o == deletedObject) continue; int hash = o.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; // search for the object while(newObjects[index] != null) { // no need to test for duplicates index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset*2 + 1; if (offset == -1) offset = 2; } newObjects[index] = (A) o; } objects = newObjects; freecells = objects.length - elements; } private class CompactHashIterator implements Iterator { private int index; private int lastReturned = -1; private int expectedModCount; @SuppressWarnings("empty-statement") public CompactHashIterator() { for (index = 0; index < objects.length && (objects[index] == null || objects[index] == deletedObject); index++) ; expectedModCount = modCount; } @Override public boolean hasNext() { return index < objects.length; } @SuppressWarnings("empty-statement") @Override public T next() { /*if (modCount != expectedModCount) throw new ConcurrentModificationException();*/ int length = objects.length; if (index >= length) { lastReturned = -2; throw new NoSuchElementException(); } lastReturned = index; for (index += 1; index < length && (objects[index] == null || objects[index] == deletedObject); index++) ; if (objects[lastReturned] == nullObject) return null; else return (T) objects[lastReturned]; } @Override public void remove() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (lastReturned == -1 || lastReturned == -2) throw new IllegalStateException(); // delete object if (objects[lastReturned] != null && objects[lastReturned] != deletedObject) { objects[lastReturned] = (A) deletedObject; elements--; modCount++; expectedModCount = modCount; // this is expected; we made the change } } } int capacity() { return objects.length; } // returns true if there was a shrink boolean shrinkToFactor(double factor) { if (factor > LOAD_FACTOR) throw fail("Shrink factor must be equal to or smaller than load factor: " + factor + " / " + LOAD_FACTOR); int newCapacity = max(INITIAL_SIZE, iround(size()/factor)); if (newCapacity >= capacity()) return false; rehash(newCapacity); return true; } } interface IDoublePt { public double x_double(); public double y_double(); } static interface IVar extends IF0 { void set(A a); A get(); // reified type of value (if available) default Class getType() { return null; } default IF0 getter() { return () -> get(); } default IVF1 setter() { return __1 -> set(__1); } default boolean has() { return get() != null; } default void clear() { set(null); } } static interface WidthAndHeight { default int w(){ return getWidth(); } default int width(){ return getWidth(); } int getWidth(); default int h(){ return getHeight(); } default int height(){ return getHeight(); } int getHeight(); public default Rect bounds() { return rect(0, 0, getWidth(), getHeight()); } default int area() { return toInt(areaAsLong()); } default long areaAsLong() { return longMul(w(), h()); } } abstract static class Sleeping implements AutoCloseable , IFieldsToList{ Timestamp targetTime; Runnable action; Sleeping() {} Sleeping(Timestamp targetTime, Runnable action) { this.action = action; this.targetTime = targetTime;} public String toString() { return shortClassName_dropNumberPrefix(this) + "(" + targetTime + ", " + action + ")"; }public Object[] _fieldsToList() { return new Object[] {targetTime, action}; } long remainingMS() { return targetTime.minus(tsNow()); } } // AppendableChain has one "smart" head element (with size counter // and pointer to the chain's last element), all the other nodes are // maximally simple (MinimalChain). // This allows O(1) front insertion, front removal and back insertion // (not removal at the back though) which is fine for what I need this // for (event queues). // // Stefan Reich, Oct 21 static class AppendableChain extends MinimalChain implements Iterable, IntSize { MinimalChain last; // pointer to last element in chain (which may be us) final public int getSize(){ return size(); } public int size() { return size; } int size; // total length of chain AppendableChain() {} // only used internally AppendableChain(A element) { this.element = element; size = 1; last = this; } // intermediate constructor called by itemPlusChain() AppendableChain(A element, AppendableChain next) { this.next = next; this.element = element; if (next == null) return; MinimalChain b = new MinimalChain(); b.element = next.element; b.next = next.next; this.next = b; last = next.last; size = next.size+1; } public String toString() { return str(toList()); } // append at the end boolean add(A a) { MinimalChain newLast = new MinimalChain(a); last.next = newLast; last = newLast; ++size; return true; } // drop first element AppendableChain popFirst() { if (next == null) return null; element = next.element; if (last == next) last = this; next = next.next; --size; return this; } ArrayList toList() { ArrayList l = emptyList(size); MinimalChain c = this; while (c != null) { l.add(c.element); c = c.next; } return l; } //public Iterator iterator() { ret toList().iterator(); } class ACIt extends IterableIterator < A > { MinimalChain c = AppendableChain.this; public boolean hasNext() { return c != null; } public A next() { var a = c.element; c = c.next; return a; } } public IterableIterator iterator() { return new ACIt(); } } static class MultiSleeper extends RestartableCountdown implements ISleeper_v2 { MultiSetMap entries = treeMultiSetMap(); void check() { var time = nextWakeUpTime(); var action = firstValue(entries); setTargetTime(time == null ? 0 : time.sysTime(), new Runnable() { public void run() { try { Set toCall; synchronized(MultiSleeper.this) { toCall = entries.get(time); entries.remove(time); check(); } pcallFAll(toCall); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "Set toCall;\r\n synchronized(MultiSleeper.this) {\r\n toCal..."; }}); } synchronized void removeEntry(Timestamp targetTime, Runnable action) { entries.remove(targetTime, action); } // API synchronized Timestamp nextWakeUpTime() { return firstKey(entries); } public synchronized Sleeping doLater(Timestamp targetTime, Runnable r) { if (r == null || targetTime == null) return null; targetTime = max(targetTime, tsNow()); entries.put(targetTime, r); check(); return new Sleeping(targetTime, r) { public void close() { try { removeEntry(targetTime, r); } catch (Exception __e) { throw rethrow(__e); } } }; } } static class Timestamp implements Comparable , IFieldsToList{ long date; Timestamp(long date) { this.date = date;} public boolean equals(Object o) { if (!(o instanceof Timestamp)) return false; Timestamp __1 = (Timestamp) o; return date == __1.date; } public int hashCode() { int h = 2059094262; h = boostHashCombine(h, _hashCode(date)); return h; } public Object[] _fieldsToList() { return new Object[] {date}; } Timestamp() { date = now(); } Timestamp(Date date) { if (date != null) this.date = date.getTime(); } final long toLong(){ return unixDate(); } long unixDate() { return date; } long unixSeconds() { return unixDate()/1000; } public String toString() { return formatLocalDateWithSeconds(date); } // Hmm. Should Timestamp(0) be equal to null? Question, questions... public int compareTo(Timestamp t) { return t == null ? 1 : cmp(date, t.date); } Timestamp plus(Seconds seconds) { return plus(seconds == null ? null : seconds.getDouble()); } final Timestamp plusSeconds(double seconds){ return plus(seconds); } Timestamp plus(double seconds) { return new Timestamp(date+toMS(seconds)); } // returns milliseconds long minus(Timestamp ts) { return unixDate()-ts.unixDate(); } long sysTime() { return clockTimeToSystemTime(date); } Duration minusAsDuration(Timestamp ts) { return Duration.ofMillis(minus(ts)); } } // uses hash sets as inner sets unless subclassed // uses a hash map as the outer map by default static class MultiSetMapimplements IMultiMap { Map> data = new HashMap>(); int size; // number of values MultiSetMap() {} MultiSetMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } MultiSetMap(MultiSetMap map) { putAll(map); } MultiSetMap(Map> data) { this.data = data;} boolean put(A key, B value) { synchronized(data) { Set set = data.get(key); if (set == null) data.put(key, set = _makeEmptySet()); if (!set.add(value)) return false; { ++size; return true; } }} boolean add(A key, B value) { return put(key, value); } void addAll(A key, Collection values) { synchronized(data) { putAll(key, values); }} void addAllIfNotThere(A key, Collection values) { synchronized(data) { for (B value : values) setPut(key, value); }} void setPut(A key, B value) { synchronized(data) { if (!containsPair(key, value)) put(key, value); }} final boolean contains(A key, B value){ return containsPair(key, value); } boolean containsPair(A key, B value) { synchronized(data) { return get(key).contains(value); }} void putAll(A key, Collection values) { synchronized(data) { for (B value : values) put(key, value); }} 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; }} List getAndClear(A key) { synchronized(data) { List l = cloneList(data.get(key)); remove(key); return l; }} // return null if empty Set getOpt(A key) { synchronized(data) { return data.get(key); }} // returns actual mutable live set // creates the set if not there Set getActual(A key) { synchronized(data) { Set set = data.get(key); if (set == null) data.put(key, set = _makeEmptySet()); return set; }} // TODO: this looks unnecessary void clean(A key) { synchronized(data) { Set list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); }} final public Set keys(){ return keySet(); } public Set keySet() { synchronized(data) { return data.keySet(); }} void remove(A key) { synchronized(data) { size -= l(data.get(key)); data.remove(key); }} void remove(A key, B value) { synchronized(data) { Set set = data.get(key); if (set != null) { if (set.remove(value)) { --size; if (set.isEmpty()) data.remove(key); } } }} void clear() { synchronized(data) { data.clear(); size = 0; }} boolean containsKey(A key) { synchronized(data) { return data.containsKey(key); }} B getFirst(A key) { synchronized(data) { return first(get(key)); }} void addAll(MultiSetMap map) { putAll(map); } void putAll(MultiSetMap map) { synchronized(data) { for (A key : map.keySet()) putAll(key, map.get(key)); }} void putAll(Map map) { synchronized(data) { if (map != null) for (Map.Entry e : map.entrySet()) put(e.getKey(), e.getValue()); }} final public int keyCount(){ return keysSize(); } public int keysSize() { synchronized(data) { return l(data); }} // full size public int size() { synchronized(data) { return size; }} // count values for key int getSize(A key) { return l(data.get(key)); } int count(A key) { return getSize(key); } // expensive operation 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; }} // expensive operation A keyForValue(B b) { synchronized(data) { for (A key : data.keySet()) if (data.get(key).contains(b)) return key; return null; }} Map> asMap() { synchronized(data) { return cloneMap(data); }} public boolean isEmpty() { synchronized(data) { return data.isEmpty(); }} // override in subclasses Set _makeEmptySet() { return new HashSet(); } Collection> allLists() { synchronized(data) { return new HashSet(data.values()); } } List allValues() { return concatLists(values(data)); } List> allEntries() { synchronized(data) { List> l = emptyList(size); for (Map.Entry> __0 : _entrySet( data)) { A a = __0.getKey(); Set set = __0.getValue(); for (B b : set) l.add(pair(a, b)); } return l; }} Object mutex() { return data; } public String toString() { return "mm" + str(data); } Pair firstEntry() { synchronized(data) { if (empty(data)) return null; Map.Entry> entry = data.entrySet().iterator().next(); return pair(entry.getKey(), first(entry.getValue())); }} A firstKey() { synchronized(data) { return main.firstKey(data); }} A lastKey() { synchronized(data) { return (A) ((NavigableMap) data).lastKey(); }} A higherKey(Object a) { synchronized(data) { return (A) ((NavigableMap) data).higherKey(a); }} } static class MinimalChain implements Iterable { A element; MinimalChain next; MinimalChain() {} MinimalChain(A element) { this.element = element;} MinimalChain(A element, MinimalChain next) { this.next = next; this.element = element;} public String toString() { return str(toList()); } ArrayList toList() { ArrayList l = new ArrayList(); MinimalChain c = this; while (c != null) { l.add(c.element); c = c.next; } return l; } void setElement(A a) { element = a; } void setNext(MinimalChain next) { this.next = next; } // TODO: optimize public Iterator iterator() { return toList().iterator(); } A get() { return element; } } static class RestartableCountdown implements AutoCloseable { java.util.Timer timer; long targetTime; // in sys time long /*firings,*/ totalSleepTime; // stats synchronized void setTargetTime(long targetTime, Runnable action) { if (targetTime <= 0) stop(); else if (targetTime != this.targetTime) { start(targetTime-sysNow(), action); this.targetTime = targetTime; } } // stops the countdown and restarts it synchronized void start(long delayMS, Object action) { stop(); if (delayMS <= 0) { startThread(new Runnable() { public void run() { try { callF(action); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "callF(action);"; }}); } else { totalSleepTime += delayMS; timer = doLater_daemon(delayMS, action); targetTime = sysNow()+delayMS; } } void start(double delaySeconds, Object action) { start(toMS(delaySeconds), action); } synchronized void stop() { cancelTimer(timer); timer = null; targetTime = 0; } public void close() { stop(); } } static class Seconds implements Comparable , IFieldsToList{ double seconds; Seconds() {} Seconds(double seconds) { this.seconds = seconds;} public boolean equals(Object o) { if (!(o instanceof Seconds)) return false; Seconds __1 = (Seconds) o; return seconds == __1.seconds; } public int hashCode() { int h = -660217249; h = boostHashCombine(h, _hashCode(seconds)); return h; } public Object[] _fieldsToList() { return new Object[] {seconds}; } final double get(){ return seconds(); } final double getDouble(){ return seconds(); } double seconds() { return seconds; } public String toString() { return formatDouble(seconds, 3) + " s"; } public int compareTo(Seconds s) { return cmp(seconds, s.seconds); } Seconds div(double x) { return new Seconds(get()/x); } Seconds minus(Seconds x) { return new Seconds(get()-x.get()); } } /*sinterface ISleeper extends ISleeper_v2, AutoCloseable { void doLater(long targetSysTime, Runnable r); // call only once }*/ static Class getClass(String name) { return _getClass(name); } static Class getClass(Object o) { return _getClass(o); } static Class getClass(Object realm, String name) { return _getClass(realm, name); } static boolean classIsExportedTo(Class c, java.lang.Module destModule) { if (c == null || destModule == null) return false; java.lang.Module srcModule = c.getModule(); String packageName = c.getPackageName(); return srcModule.isExported(packageName, destModule); } static boolean isAbstract(Class c) { return (c.getModifiers() & Modifier.ABSTRACT) != 0; } static boolean isAbstract(Method m) { return (m.getModifiers() & Modifier.ABSTRACT) != 0; } static boolean reflection_isForbiddenMethod(Method m) { return m.getDeclaringClass() == Object.class && eqOneOf(m.getName(), "finalize", "clone", "registerNatives"); } static Set allInterfacesImplementedBy(Object o) { return allInterfacesImplementedBy(_getClass(o)); } static Set allInterfacesImplementedBy(Class c) { if (c == null) return null; HashSet set = new HashSet(); allInterfacesImplementedBy_find(c, set); return set; } 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); } 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; } 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; } static List quoteAll(String[] l) { return quoteAll(asList(l)); } static List quoteAll(Collection l) { List x = new ArrayList(); for (String s : l) x.add(quote(s)); return x; } static int _hashCode(Object a) { return a == null ? 0 : a.hashCode(); } 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; } static float clamp(float x, float a, float b) { return x < a ? a : x > b ? b : x; } static double clamp(double x, double a, double b) { return x < a ? a : x > b ? b : x; } static int clamp(int x, int a, int b) { return x < a ? a : x > b ? b : x; } static long clamp(long x, long a, long b) { return x < a ? a : x > b ? b : x; } static void add(BitSet bs, int i) { bs.set(i); } static boolean add(Collection c, A a) { return c != null && c.add(a); } static void add(Container c, Component x) { addToContainer(c, x); } static long add(AtomicLong l, long b) { return l.addAndGet(b); } static A _print(String s, A a) { return print(s, a); } static A _print(A a) { return print(a); } static void _print() { print(); } static boolean _eq(Object a, Object b) { return eq(a, b); } static String toString(Object o) { return strOrNull(o); } static String formatDouble(double d, int digits) { String format = digits <= 0 ? "0" : "0." + rep(digits, '#'); return decimalFormatEnglish(format, d); } static String formatDouble(double d) { return str(d); } static double ratioToPercent(double x, double y) { return x*100/y; } static A getAndClear(IVar v) { A a = v.get(); v.set(null); return a; } static Set keySet(Map map) { return map == null ? new HashSet() : map.keySet(); } static Set keySet(Object map) { return keys((Map) map); } static Set keySet(MultiMap mm) { return mm.keySet(); } static int keysSize(MultiMap mm) { return lKeys(mm); } 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; } static Collection values(Map map) { return map == null ? emptyList() : map.values(); } // convenience shortcut for values_gen static Collection values(Object map) { return values((Map) map); } static Collection values(MultiMap mm) { return mm == null ? emptyList() : concatLists(values(mm.data)); } static > List allValues(Map map) { List out = new ArrayList(); for (var l : values(map)) addAll(out, l); return out; } static List concatLists(Iterable... lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } static List concatLists(Collection> lists) { List l = new ArrayList(); if (lists != null) for (Iterable list : lists) addAll(l, list); return l; } 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); makeAccessible(f); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } return o; } static void set(Class c, String field, Object value) { if (c == null) return; try { Field f = set_findStaticField(c, field); makeAccessible(f); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field set_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Field set_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } static void set(BitSet bs, int idx) { { if (bs != null) bs.set(idx); } } static boolean hasNext(Iterator it) { return it != null && it.hasNext(); } static Method hashMap_findKey_method; static A hashMap_findKey(HashMap map, Object key) { try { if (hashMap_findKey_method == null) hashMap_findKey_method = findMethodNamed(HashMap.class, "getNode"); Map.Entry entry = (Map.Entry) hashMap_findKey_method.invoke(map, hashMap_internalHash(key), key); // java.util.Map.Entry entry = (java.util.Map.Entry) call(hash, 'getNode, hashMap_internalHash(key), wkey); return entry == null ? null : entry.getKey(); } catch (Exception __e) { throw rethrow(__e); } } static String find(String pattern, String text) { Matcher matcher = Pattern.compile(pattern).matcher(text); if (matcher.find()) return matcher.group(1); return null; } static A find(Collection c, Object... data) { for (A x : c) if (checkFields(x, data)) return x; return null; } static int hashCodeFor(Object a) { return a == null ? 0 : a.hashCode(); } static String joinNemptiesWithColon(String... strings) { return joinNempties(": ", strings); } static String joinNemptiesWithColon(Collection strings) { return joinNempties(": ", strings); } static int boostHashCombine(int a, int b) { return a ^ (b + 0x9e3779b9 + (a << 6) + (a >>> 2)); // OLD (changed) 2022/3/10: ret a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2)); } static WidthAndHeight widthAndHeight(BufferedImage image) { return image == null ? null : widthAndHeight(image.getWidth(), image.getHeight()); } static WidthAndHeight widthAndHeight(int w) { return widthAndHeight(w, w); } static WidthAndHeight widthAndHeight(int w, int h) { return new WidthAndHeightFinal(w, h); } static double sqrt(double x) { return Math.sqrt(x); } static Pt ptMinus(Pt a, Pt b) { if (b == null) return a; return new Pt(a.x-b.x, a.y-b.y); } static List nempties(Collection c) { return filterNempty(c); } static List splitAtSlash(String s) { return trimAll(asList(s.split("/"))); } static boolean all(Object pred, Iterable l) { if (l != null) for (Object o : l) if (!isTrue(callF(pred, o))) return false; return true; } static boolean all(Iterable l, IF1 f) { if (l != null) for (A a : l) if (!f.get(a)) return false; return true; } static boolean all(IF1 f, Iterable l) { return all(l, f); } static boolean all(int[] l, IIntPred f) { if (l != null) for (int i : l) if (!f.get(i)) return false; return true; } static boolean validFileName(String s) { return isValidFileName(s); } static boolean isDirectory(File f) { return f != null && f.isDirectory(); } static boolean isDirectory(String path) { return path != null && isDirectory(newFile(path)); } static Object subBot_serveFileRange(File file, String mimeType, String rangeHeader) { try { String rangeValue = dropPrefix("bytes=", trim(rangeHeader)); long fileLength = file.length(), start, end; if (rangeValue.startsWith("-")) { end = fileLength-1; start = fileLength-1-parseLong(dropPrefix("-", rangeValue)); } else { String[] range = rangeValue.split("-"); start = parseLong(range[0]); end = range.length > 1 ? min(fileLength-1, parseLong(range[1])) : fileLength-1; } if (start <= end) { long contentLength = end-start+1; FileInputStream fileInputStream = new FileInputStream(file); fileInputStream.skip(start); Object response = subBot_servePartialContent(mimeType, fileInputStream, contentLength); call(response, "addHeader", "Content-Range", "bytes " + start + "-" + end + "/" + fileLength); return response; } else return subBot_serveRangeNotSatisfiable(rangeHeader); } catch (Exception __e) { throw rethrow(__e); } } static Object addHeader(String header, String value, Object response) { call(response, "addHeader", header, value); return response; } static String formatDateForLastModifiedHeader() { return formatDateForLastModifiedHeader(now()); } static String formatDateForLastModifiedHeader(long time) { var sdf = simpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", TimeZone.getTimeZone("GMT")); return sdf.format(time); } static String addSlashIfNempty(String s) { return addSlash(s); } static List listFileNames(File dir) { return asList(dir.list()); } static List listFileNames(String dir) { return listFileNames(new File(dir)); } // f: A -> Comparable static List sortInPlaceByCalculatedField(List l, final F1 f) { sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } static List sortInPlaceByCalculatedField(List l, final IF1 f) { sort(l, new Comparator() { public int compare(A a, A b) { return stdcompare(f.get(a), f.get(b)); } }); return l; } static String lower(String s) { return s == null ? null : s.toLowerCase(); } static char lower(char c) { return Character.toLowerCase(c); } static long modificationTime(File f) { return fileModificationTime(f); } static String dropAfterLastSlashOrEmpty(String s) { if (s == null) return null; int i = s.lastIndexOf('/'); return i < 0 ? "" : rtrim(substring(s, 0, i)); } static String dropTrailingSlash(String s) { return dropSuffix("/", s); } static String htmlEncode2(String s) { return htmlencode_noQuotes(s); } static String htmlEncode2(Object o) { return htmlEncode2(strOrEmpty(o)); } static String pUnlessEmpty(String s, Object... __) { return empty(s) ? "" : p(s, __); } static String addSlashSuffix(String s) { return addSlash(s); } static String appendParamsToURL(String url, Map params) { return appendQueryToURL(url, params); } static String appendParamsToURL(String url, Object... data) { return appendQueryToURL(url, data); } static String bracketed(String s) { return roundBracket(s); } static String bracketed(Object s) { return roundBracket(s); } static List fileInfoHintsWithDate(File f) { List hints = new ArrayList(); if (f == null) return hints; if (f.isFile()) { //hints.add("file"); hints.add(n2(fileSize(f)) + " bytes"); hints.add("modified " + renderFileDateWithSeconds(f)); } else if (f.isDirectory()) hints.add("dir"); else hints.add("not found"); return hints; } static String hcombine(Object... l) { return htmlCombine(l); } static String htitle_decode(String titleHTML) { return htitle(hTitleClean(titleHTML)); } static Map extensionToMimeType_map = litCIMap( "cal", "text/plain", "zip", "application/zip", "svg", svgContentType(), "html", "text/html", "txt", "text/plain", "css", "text/css", "js", "text/javascript", "png", "image/png", "jpg", "image/jpeg", "jpeg", "image/jpeg", "wasm", "application/wasm", "mp3", "audio/mpeg"); static String extensionToMimeType(String s) { s = substring(s, lastIndexOf(s, '.')+1); return extensionToMimeType_map.get(s); } static String fileExtension(File f) { if (f == null) return null; return fileExtension(f.getName()); } static String fileExtension(String s) { return substring(s, smartLastIndexOf(s, '.')); } static String binaryMimeType() { return "application/octet-stream"; } static boolean isValidFileName(String s) { return nempty(s) && !eqOneOf(s, ".", "..") && all(characters(s), c -> isValidFileCharacter(c)); } static boolean dir2zip_recurse_verbose = false; static int dir2zip_recurse(File inDir, File zip) { return dir2zip_recurse(inDir, zip, ""); } // TODO: the zero files case? 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); } } static int dir2zip_recurse(File inDir, ZipOutputStream outZip) { return dir2zip_recurse(inDir, outZip, "", 0); } 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()) { if (dir2zip_recurse_verbose) 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; try { fin = new FileInputStream(f); } catch (Throwable e) { print(e); continue; } AutoCloseable __1 = fin; try { copyStream(fin, outZip); ++n; } finally { _close(__1); }} } return n; } catch (Exception __e) { throw rethrow(__e); } } static String fileName(File f) { return f == null ? null : f.getName(); } static String ymdMinusHMS() { return ymdMinusHMS(now()); } static String ymdMinusHMS(long now) { return ymd_minus_hms(now); } static Object addFilenameHeader(Object r, String name) { call(r, "addHeader", "Content-Disposition", "inline; filename=\"" + name + "\""); // todo: encode special characters return r; } static Object addFilenameHeader(String name, Object r) { return addFilenameHeader(r, name); } static ByteArrayInputStream byteArrayInputStream(byte[] data) { return new ByteArrayInputStream(data); } static String zipMimeType() { return "application/zip"; } static UnsupportedOperationException unsupportedOperation() { throw new UnsupportedOperationException(); } static LinkedHashMap cloneLinkedHashMap(Map map) { return map == null ? new LinkedHashMap() : new LinkedHashMap(map); } static boolean hasLock(Lock lock) { return ((ReentrantLock) lock).isHeldByCurrentThread(); } static String shortClassName_dropNumberPrefix(Object o) { return dropNumberPrefix(shortClassName(o)); } 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 vmBus_timerStarted(timer); } static java.util.Timer doLater(double delaySeconds, final Object r) { return doLater(toMS(delaySeconds), r); } static Timestamp sysTimeToTimestamp(long now) { return now == 0 ? null : new Timestamp(now - clockToSysTimeDiff()); } static Timestamp tsNow() { return new Timestamp(); } static volatile int numberOfCores_value; static int numberOfCores() { if (numberOfCores_value == 0) numberOfCores_value = Runtime.getRuntime().availableProcessors(); return numberOfCores_value; } // runnable = Runnable or String (method name) static Thread newThread(Object runnable) { return new BetterThread(_topLevelErrorHandling(toRunnable(runnable))); } static Thread newThread(Object runnable, String name) { if (name == null) name = defaultThreadName(); return new BetterThread(_topLevelErrorHandling(toRunnable(runnable)), name); } static Thread newThread(String name, Object runnable) { return newThread(runnable, name); } static int random(int n) { return random(n, defaultRandomGenerator()); } static int random(int n, Random r) { return random(r, n); } static long random(long n) { return random(n, defaultRandomGenerator()); } static long random(long n, Random r) { return random(r, n); } static int random(Random r, int n) { return n <= 0 ? 0 : getRandomizer(r).nextInt(n); } static long random(Random r, long n) { return n <= 0 ? 0 : getRandomizer(r).nextLong(n); } static double random(double max) { return random()*max; } static double random() { return defaultRandomGenerator().nextInt(100001)/100000.0; } static double random(double min, double max) { return min+random()*(max-min); } // min <= value < max static int random(int min, int max) { return min+random(max-min); } // min <= value < max static long random(long min, long max) { return min+random(max-min); } static int random(int min, int max, Random r) { return random(r, min, max); } static int random(Random r, int min, int max) { return min+random(r, max-min); } static A random(List l) { return oneOf(l); } static A random(Collection c) { if (c instanceof List) return random((List) c); int i = random(l(c)); return collectionGet(c, i); } static Pair random(Map map) { return entryToPair(random(entries(map))); } static A popFirst(List l) { if (empty(l)) return null; A a = first(l); l.remove(0); return a; } static A popFirst(Collection l) { if (empty(l)) return null; A a = first(l); l.remove(a); return a; } static Pair popFirst(Map map) { if (map == null) return null; var it = map.entrySet().iterator(); if (!it.hasNext()) return null; var p = mapEntryToPair(it.next()); it.remove(); return p; } static List popFirst(int n, List l) { List part = cloneSubList(l, 0, n); removeSubList(l, 0, n); return part; } static AppendableChain popFirst(AppendableChain a) { return a == null ? null : a.popFirst(); } // Yes the nomenclature is a bit illogical static Chain chainPlus(Chain chain, A a) { return new Chain(a, chain); } static Chain chainPlus(Chain chain, A... l) { for (A a : unnullForIteration(l)) chain = chainPlus(chain, a); return chain; } static ReverseChain chainPlus(ReverseChain chain, A a) { return new ReverseChain(chain, a); } static ReverseChain chainPlus(ReverseChain chain, A... l) { for (A a : unnullForIteration(l)) chain = chainPlus(chain, a); return chain; } static AppendableChain chainPlus(AppendableChain chain, A a) { if (chain == null) return new AppendableChain(a); chain.add(a); return chain; } static AppendableChain chainPlus(AppendableChain chain, A... l) { for (A a : unnullForIteration(l)) chain = chainPlus(chain, a); return chain; } static String n2(long l) { return formatWithThousands(l); } static String n2(AtomicLong l) { return n2(l.get()); } static String n2(Collection l) { return n2(l(l)); } static String n2(Map map) { return n2(l(map)); } static String n2_getPlural(String singular) { //ret singular + "s"; return plural(singular); } static String n2(double l, String singular) { return empty(singular) ? str(l) : n2(l, singular, n2_getPlural(singular)); } static String n2(double l, String singular, String plural) { if (fraction(l) == 0) return n2((long) l, singular, plural); else return l + " " + plural; } static String n2(long l, String singular, String plural) { return n_fancy2(l, singular, plural); } static String n2(long l, String singular) { return empty(singular) ? n2(l) : n_fancy2(l, singular, n2_getPlural(singular)); } static String n2(Collection l, String singular) { return n2(l(l), singular); } static String n2(Collection l, String singular, String plural) { return n_fancy2(l, singular, plural); } static String n2(Map m, String singular, String plural) { return n_fancy2(m, singular, plural); } static String n2(Map m, String singular) { return n2(l(m), singular); } static String n2(long[] a, String singular) { return n2(l(a), singular); } static String n2(Object[] a, String singular) { return n2(l(a), singular); } static String n2(Object[] a, String singular, String plural) { return n_fancy2(a, singular, plural); } static String n2(IMultiMap mm, String singular) { return n2(mm, singular, n2_getPlural(singular)); } static String n2(IMultiMap mm, String singular, String plural) { return n_fancy2(l(mm), singular, plural); } static void syncNotifyAll(Object o) { if (o != null) synchronized(o) { o.notifyAll(); } } static int getWidth(Component c) { return c == null ? 0 : (int) swingCall(c, "getWidth"); } static int getHeight(Component c) { return c == null ? 0 : (int) swingCall(c, "getHeight"); } static Rect rect(int x, int y, int w, int h) { return new Rect(x, y, w, h); } static Rect rect(Pt p, int w, int h) { return new Rect(p.x, p.y, w, h); } static Rect rect(int w, int h) { return new Rect(0, 0, w, h); } static long longMul(long a, long b) { return a*b; } static MultiSetMap treeMultiSetMap() { return new MultiSetMap(true); } static MultiSetMap treeMultiSetMap(Comparator comparator) { return new MultiSetMap(new TreeMap>(comparator)); } static B firstValue(Map map) { return first(values(map)); } static B firstValue(MultiSetMap map) { return map == null ? null : first(firstValue(map.data)); } static B firstValue(MultiMap map) { return map == null ? null : first(firstValue(map.data)); } static A firstKey(Map map) { return first(keys(map)); } static A firstKey(IMultiMap map) { return map == null ? null : first(map.keySet()); } static String formatLocalDateWithSeconds(long time) { return localDateWithSeconds(time); } static String formatLocalDateWithSeconds() { return localDateWithSeconds(); } static BigInteger plus(BigInteger a, BigInteger b) { return a.add(b); } static BigInteger plus(BigInteger a, long b) { return a.add(bigint(b)); } static long plus(long a, long b) { return a+b; } static int plus(int a, int b) { return a+b; } static float plus(float a, float b) { return a+b; } static double plus(double a, double b) { return a+b; } static long clockTimeToSystemTime(long now) { return now == 0 ? 0 : now + clockToSysTimeDiff(); } static List minus(Collection a, Object... b) { Set set = asSet(b); List l = new ArrayList(); for (Object s : unnull(a)) if (!set.contains(s)) l.add(s); return l; } static BigInteger minus(BigInteger a, BigInteger b) { return a.subtract(b); } static Complex minus(Complex c) { return c == null ? null : complex(-c.re(), -c.im()); } static int minus(int a, int b) { return a-b; } static int minus(int a) { return -a; } static double minus(double a, double b) { return a-b; } static double minus(double a) { return -a; } static long minus(long a, long b) { return a-b; } static long minus(long a) { return -a; } static Set emptySet() { return new HashSet(); } static Map.Entry firstEntry(Map map) { return empty(map) ? null : first(map.entrySet()); } static Thread startThread(Object runnable) { return startThread(defaultThreadName(), runnable); } static Thread startThread(String name, Runnable runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(runnable, name)); } static Thread startThread(String name, Object runnable) { runnable = wrapAsActivity(runnable); return startThread(newThread(toRunnable(runnable), name)); } static Thread startThread(Thread t) { _registerThread(t); t.start(); return t; } static java.util.Timer doLater_daemon(long delay, final Object r) { final java.util.Timer timer = new java.util.Timer(true); timer.schedule(timerTask(r, timer), delay); return timer; } static java.util.Timer doLater_daemon(double delaySeconds, final Object r) { return doLater_daemon(toMS(delaySeconds), r); } static void cancelTimer(javax.swing.Timer timer) { if (timer != null) timer.stop(); } static void cancelTimer(java.util.Timer timer) { if (timer != null) timer.cancel(); } 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) { pcallFail(__e); }} } static int seconds() { return seconds(java.util.Calendar.getInstance()); } static int seconds(java.util.Calendar c) { return c.get(java.util.Calendar.SECOND); } static void addToContainer(Container a, Component... b) { if (a == null) return; { swing(() -> { for (Component c : unnullForIteration(b)) if (c != null) a.add(c); }); } } static String rep(int n, char c) { return repeat(c, n); } static String rep(char c, int n) { return repeat(c, n); } static List rep(A a, int n) { return repeat(a, n); } static List rep(int n, A a) { return repeat(n, a); } static String decimalFormatEnglish(String format, double d) { return decimalFormatEnglish(format).format(d); } static java.text.DecimalFormat decimalFormatEnglish(String format) { return new java.text.DecimalFormat(format, new java.text.DecimalFormatSymbols(Locale.ENGLISH)); } static int lKeys(MultiMap mm) { return mm == null ? 0 : mm.keysSize(); } static void smartSet(Field f, Object o, Object value) throws Exception { try { f.set(o, value); } catch (Exception e) { Class type = f.getType(); // take care of common case (long to int) if (type == int.class && value instanceof Long) { f.set(o, ((Long) value).intValue()); return; } if (type == boolean.class && value instanceof String) { f.set(o, isTrueOrYes(((String) value))); return; } if (type == LinkedHashMap.class && value instanceof Map) { f.set(o, asLinkedHashMap((Map) value)); return; } throw e; } } static int hashMap_internalHash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); } static List filterNempty(Collection c) { List l = new ArrayList(); for (String x : unnull(c)) if (nempty(x)) l.add(x); return l; } static List trimAll(String... l) { return trimAll(asList(l)); } static List trimAll(Collection l) { List l2 = new ArrayList(); if (l != null) for (String s : l) l2.add(trim(s)); return l2; } static Object subBot_servePartialContent(String mimeType, InputStream inputStream, long length) { return call(mainBot(), "servePartialContent", mimeType, inputStream, length); } static Object subBot_serveRangeNotSatisfiable(String msg) { return call(mainBot(), "serveRangeNotSatisfiable", msg); } static java.text.SimpleDateFormat simpleDateFormat(String format, TimeZone timeZone) { java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(format); sdf.setTimeZone(timeZone); return sdf; } static void sort(T[] a, Comparator c) { if (a != null) Arrays.sort(a, c); } static void sort(T[] a) { if (a != null) Arrays.sort(a); } static void sort(int[] a) { if (a != null) Arrays.sort(a); } static void sort(List a, Comparator c) { if (a != null) Collections.sort(a, c); } static void sort(List a) { if (a != null) Collections.sort(a); } static long fileModificationTime(File f) { return f == null ? 0 : f.lastModified(); } static String renderFileDateWithSeconds(File f) { return formatLocalDateWithSeconds(lastModified(f)); } static String htmlCombine(Object... l) { return nemptyLines_extractLists(l); } static String hTitleClean(String title) { return htmldecode(dropTagsAndHTMLComments(title)); } static TreeMap litCIMap(Object... x) { TreeMap map = caseInsensitiveMap(); litmap_impl(map, x); return map; } static String svgContentType() { return "image/svg+xml"; } static int smartLastIndexOf(String s, char c) { if (s == null) return 0; int i = s.lastIndexOf(c); return i >= 0 ? i : l(s); } static int smartLastIndexOf(List l, A sub) { int i = lastIndexOf(l, sub); return i < 0 ? l(l) : i; } static List characters(final String s) { return stringAsCharacterList(s); } static boolean isValidFileCharacter(char c) { return isLetterOrDigit(c) || contains(".-_ %", c); } static File[] listFiles(File dir) { File[] files = dir == null ? null : dir.listFiles(); return files == null ? new File[0] : files; } static File[] listFiles(String dir) { return listFiles(new File(dir)); } static List sortFilesByName(List l) { sort(l, (a, b) -> stdcompare(a.getName(), b.getName())); return l; } static String ymd_minus_hms() { return ymd_minus_hms(now()); } static String ymd_minus_hms(long now) { return ymd(now) + "-" + hms(now); } static String dropNumberPrefix(String s) { return dropFirst(s, indexOfNonDigit(s)); } static TimerTask timerTask(final Object r, final java.util.Timer timer) { return new TimerTask() { public void run() { if (!licensed()) timer.cancel(); else pcallF(r); } }; } static A vmBus_timerStarted(A timer) { vmBus_send("timerStarted", timer, costCenter()); return timer; } static long clockToSysTimeDiff() { return sysNow()-now(); } static Runnable _topLevelErrorHandling(Runnable r) { if (r == null) return null; // maybe we don't want this anymore. just dm_current_generic() Object info = _threadInfo(); Object mod = dm_current_generic(); Runnable r2 = r; if (info != null || mod == null) r2 = new Runnable() { public void run() { try { AutoCloseable __1 = (AutoCloseable) (rcall("enter", mod)); try { _threadInheritInfo(info); r.run(); } finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "temp (AutoCloseable) rcall enter(mod);\r\n _threadInheritInfo(info);\r\n ..."; }}; r2 = rPcall(r2); return r2; } static String defaultThreadName_name; static String defaultThreadName() { if (defaultThreadName_name == null) defaultThreadName_name = "A thread by " + programID(); return defaultThreadName_name; } static Random getRandomizer(Random r) { return r != null ? r : defaultRandomGenerator(); } static A oneOf(List l) { if (empty(l)) return null; int n = l.size(); return n == 1 ? first(l) : l.get(defaultRandomizer().nextInt(n)); } static char oneOf(String s) { return empty(s) ? '?' : s.charAt(random(l(s))); } static A oneOf(A... l) { return oneOf(asList(l)); } 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; } static Pair entryToPair(Map.Entry e) { return mapEntryToPair(e); } static Set> entries(Map map) { return _entrySet(map); } static String formatWithThousands(long l) { return formatWithThousandsSeparator(l); } static String plural(String s) { return getPlural(s); } static double fraction(double d) { return d % 1; } static String n_fancy2(long l, String singular, String plural) { return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural); } static String n_fancy2(Collection l, String singular, String plural) { return n_fancy2(l(l), singular, plural); } static String n_fancy2(Map m, String singular, String plural) { return n_fancy2(l(m), singular, plural); } static String n_fancy2(Object[] a, String singular, String plural) { return n_fancy2(l(a), singular, plural); } static Object swingCall(final Object o, final String method, final Object... args) { return swing(new F0() { public Object get() { try { return call(o, method, args); } catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "return call(o, method, args);"; }}); } static String localDateWithSeconds(long time) { SimpleDateFormat format = simpleDateFormat_local("yyyy/MM/dd HH:mm:ss"); return format.format(time); } static String localDateWithSeconds() { return localDateWithSeconds(now()); } static Set asSet(Object[] array) { HashSet set = new HashSet(); for (Object o : array) if (o != null) set.add(o); return set; } static Set asSet(String[] array) { TreeSet set = new TreeSet(); for (String o : array) if (o != null) set.add(o); return set; } 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; } static Complex complex(double re, double im) { return new Complex(re, im); } static Complex complex(double re) { return new Complex(re, 0.0); } static Complex complex(double[] reIm) { if (empty(reIm)) return null; if (l(reIm) != 2) throw fail("Need 2 doubles to make complex number"); return complex(reIm[0], reIm[1]); } static Runnable wrapAsActivity(Object r) { if (r == null) return null; Runnable r2 = toRunnable(r); Object mod = dm_current_generic(); if (mod == null) return r2; return new Runnable() { public void run() { try { AutoCloseable c = (AutoCloseable) (rcall("enter", mod)); AutoCloseable __1 = c; try { r2.run(); } finally { _close(__1); }} catch (Exception __e) { throw rethrow(__e); } } public String toString() { return "AutoCloseable c = (AutoCloseable) (rcall enter(mod));\r\n temp c;\r\n r2.r..."; }}; } static Map _registerThread_threads; static Object _onRegisterThread; // voidfunc(Thread) 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; } static void _registerThread() { _registerThread(Thread.currentThread()); } 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); } 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; } static List repeat(int n, A a) { return repeat(a, n); } static boolean isTrueOrYes(Object o) { return isTrueOpt(o) || o instanceof String && (eqicOneOf(((String) o), "1", "t", "true") || isYes(((String) o))); } static long lastModified(File f) { return fileModificationTime(f); } static String nemptyLines_extractLists(Object... l) { return nemptyLines(flattenCollectionsAndArrays(ll(l))); } static List dropTagsAndHTMLComments(List tok) { return dropHTMLComments(dropTags(tok)); } static String dropTagsAndHTMLComments(String html) { return join(dropTagsAndHTMLComments(htmlTok(html))); } static TreeMap caseInsensitiveMap() { return new TreeMap(caseInsensitiveComparator()); } static List stringAsCharacterList(final String s) { if (s == null) return null; return new RandomAccessAbstractList() { final int l = l(s); public int size() { return l; } public Character get(int i) { return s.charAt(i); } }; } static boolean isLetterOrDigit(char c) { return Character.isLetterOrDigit(c); } static String ymd() { return ymd(now()); } static String ymd(long now) { return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2); } static String ymd(long now, TimeZone tz) { return year(now, tz) + formatInt(month(now, tz), 2) + formatInt(dayOfMonth(now, tz), 2); } static String hms() { return hms(now()); } static String hms(long time) { return new SimpleDateFormat("HHmmss").format(time); } static int indexOfNonDigit(String s) { int n = l(s); for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i))) return i; return -1; } static Object costCenter() { return mc(); } static Object dm_current_generic() { return getWeakRef(dm_current_generic_tl().get()); } static Object rcall(String method, Object o, Object... args) { return call_withVarargs(o, method, args); } static Runnable rPcall(Runnable r) { return r == null ? null : () -> { try { r.run(); } catch (Throwable __e) { pcallFail(__e); } }; } static Random defaultRandomizer() { return defaultRandomGenerator(); } static A listGet(List l, int idx) { return l != null && idx >= 0 && idx < l.size() ? l.get(idx) : null; } static String formatWithThousandsSeparator(long l) { return NumberFormat.getInstance(new Locale("en_US")).format(l); } static Set getPlural_specials = litciset("sheep", "fish"); static String getPlural(String s) { if (contains(getPlural_specials, s)) return s; if (ewic(s, "y")) return dropSuffixIgnoreCase("y", s) + "ies"; if (ewicOneOf(s, "ss", "ch")) return s + "es"; if (ewic(s, "s")) return s; return s + "s"; } static SimpleDateFormat simpleDateFormat_local(String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); sdf.setTimeZone(localTimeZone()); return sdf; } static WeakReference weakRef(A a) { return newWeakReference(a); } static boolean isTrueOpt(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); return false; } static boolean isTrueOpt(String field, Object o) { return isTrueOpt(getOpt(field, o)); } static List isYes_yesses = litlist("y", "yes", "yeah", "y", "yup", "yo", "corect", "sure", "ok", "afirmative"); // << collapsed words, so "corect" means "correct" static boolean isYes(String s) { return isYes_yesses.contains(collapseWord(toLowerCase(firstWord2(s)))); } static String nemptyLines(Iterable l) { return lines(nempties(allToStrOrNull(l))); } static String nemptyLines(Object... l) { return nemptyLinesLL(l); } static List dropHTMLComments(List tok) { List l = new ArrayList(); for (int idx = 0; idx < l(tok); idx++) { String t = tok.get(idx); if (even(idx)) { int i; while ((i = t.indexOf("", i+4); t = substring(t, 0, i) + substring(t, j+3); } } l.add(t); } return l; } static String dropTags(String html) { return dropAllTags(html); } static List dropTags(List tok) { return dropAllTags(tok); } static Comparator caseInsensitiveComparator() { return betterCIComparator(); } static int year() { return localYear(); } static int year(Timestamp now) { return localYear(toLong(now)); } static int year(long now) { return localYear(now); } static int year(long now, TimeZone tz) { return parseInt(simpleDateFormat("y", tz).format(now)); } static String formatInt(int i, int digits) { return padLeft(str(i), '0', digits); } static String formatInt(long l, int digits) { return padLeft(str(l), '0', digits); } static int month() { return localMonth(); } static int month(Timestamp now) { return localMonth(toLong(now)); } static int month(long now) { return localMonth(now); } static int month(long now, TimeZone tz) { return parseInt(simpleDateFormat("M", tz).format(now)); } static int dayOfMonth() { return localDayOfMonth(); } static int dayOfMonth(long now) { return localDayOfMonth(now); } static int dayOfMonth(long now, TimeZone tz) { return parseInt(simpleDateFormat("d", tz).format(now)); } static A getWeakRef(Reference ref) { return ref == null ? null : ref.get(); } static x30_pkg.x30_util.BetterThreadLocal dm_current_generic_tl; static x30_pkg.x30_util.BetterThreadLocal dm_current_generic_tl() { if (dm_current_generic_tl == null) dm_current_generic_tl = vm_generalMap_getOrCreate("currentModule", () -> new x30_pkg.x30_util.BetterThreadLocal()); return dm_current_generic_tl; } static TreeSet litciset(String... items) { TreeSet set = caseInsensitiveSet(); for (String a : items) set.add(a); return set; } static TreeSet litciset(Symbol... items) { TreeSet set = treeSet(); // HashSet would also do, but we might have the return type fixed somewhere, and they might want a NavigableMap. for (Symbol a : items) set.add(a); return set; } static String dropSuffixIgnoreCase(String suffix, String s) { return ewic(s, suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static boolean ewicOneOf(String s, String... l) { if (s != null) for (String x : l) if (ewic(s, x)) return true; return false; } static TimeZone localTimeZone() { return getTimeZone(standardTimeZone()); // TimeZone.getDefault()? } static WeakReference newWeakReference(A a) { return a == null ? null : new WeakReference(a); } 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(); } static List toLowerCase(List strings) { List x = new ArrayList(); for (String s : strings) x.add(s.toLowerCase()); return x; } static String[] toLowerCase(String[] strings) { String[] x = new String[l(strings)]; for (int i = 0; i < l(strings); i++) x[i] = strings[i].toLowerCase(); return x; } static String toLowerCase(String s) { return s == null ? "" : s.toLowerCase(); } static String firstWord2(String s) { s = xltrim(s); if (empty(s)) return ""; if (isLetterOrDigit(first(s))) return takeCharsWhile(__50 -> isLetterOrDigit(__50), s); else return "" + first(s); } static List allToStrOrNull(Iterable c) { return lmap(__51 -> strOrNull(__51), c); } static List allToStrOrNull(Object... c) { return lmap(__52 -> strOrNull(__52), c); } static String nemptyLinesLL(Object... l) { return nemptyLines(ll(l)); } // tok should be the output of htmlcoarsetok 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; } // alternatively, call this convenient function static String dropAllTags(String html) { if (!contains(html, '<')) return html; return join(dropAllTags(htmlcoarsetok(html))); } static betterCIComparator_C betterCIComparator_instance; static betterCIComparator_C betterCIComparator() { if (betterCIComparator_instance == null) betterCIComparator_instance = new betterCIComparator_C(); return betterCIComparator_instance; } final 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) { // No overflow because of numeric promotion return c1 - c2; } } } } return n1 - n2; } } static int localYear() { return localYear(now()); } static int localYear(long time) { return parseInt(simpleDateFormat_local("yyyy").format(time)); } static long toLong(Object o) { if (o instanceof Number) return ((Number) o).longValue(); if (o instanceof String) return parseLong((String) o); return 0; } static long toLong(Timestamp ts) { return ts == null ? 0 : ts.unixDate(); } static long toLong(Date d) { return d == null ? 0 : d.getTime(); } static String padLeft(String s, char c, int n) { return rep(c, n-l(s)) + s; } // default to space static String padLeft(String s, int n) { return padLeft(s, ' ', n); } static int localMonth(long time) { return parseInt(simpleDateFormat_local("MM").format(time)); } static int localMonth() { return localMonth(now()); } static int localDayOfMonth(long time) { return parseInt(simpleDateFormat_local("dd").format(time)); } static int localDayOfMonth() { return localDayOfMonth(now()); } static TreeSet caseInsensitiveSet() { return caseInsensitiveSet_treeSet(); } static TreeSet caseInsensitiveSet(Collection c) { return caseInsensitiveSet_treeSet(c); } static TreeSet treeSet() { return new TreeSet(); } static TimeZone getTimeZone(String name) { return TimeZone.getTimeZone(name); } static String standardTimeZone_name = "Europe/Berlin"; static String standardTimeZone() { return standardTimeZone_name; } 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); } static String xltrim(String s) { int i = 0, n = l(s); while (i < n && contains(" \t\r\n", s.charAt(i))) ++i; return substr(s, i); } // pred: char -> bool static String takeCharsWhile(String s, Object pred) { int i = 0; while (i < l(s) && isTrue(callF(pred, s.charAt(i)))) ++i; return substring(s, 0, i); } static String takeCharsWhile(IF1 f, String s) { return takeCharsWhile(s, f); } static List lmap(IF1 f, Iterable l) { return lambdaMap(f, l); } static List lmap(IF1 f, A[] l) { return lambdaMap(f, l); } static TreeSet caseInsensitiveSet_treeSet() { return new TreeSet(caseInsensitiveComparator()); } static TreeSet caseInsensitiveSet_treeSet(Collection c) { return toCaseInsensitiveSet_treeSet(c); } static String substr(String s, int x) { return substring(s, x); } static String substr(String s, int x, int y) { return substring(s, x, y); } static TreeSet toCaseInsensitiveSet_treeSet(Iterable c) { if (isCISet(c)) return (TreeSet) c; TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, c); return set; } static TreeSet toCaseInsensitiveSet_treeSet(String... x) { TreeSet set = caseInsensitiveSet_treeSet(); addAll(set, x); return set; } static boolean isCISet(Iterable l) { return l instanceof TreeSet && ((TreeSet) l).comparator() == caseInsensitiveComparator(); } static class Chain implements Iterable { A element; Chain next; int size; Chain() {} Chain(A element) { this.element = element; size = 1; } Chain(A element, Chain next) { this.next = next; this.element = element; size = next != null ? next.size+1 : 1; } public String toString() { return str(toList()); } ArrayList toList() { ArrayList l = emptyList(size); Chain c = this; while (c != null) { l.add(c.element); c = c.next; } return l; } // TODO: optimize public Iterator iterator() { return toList().iterator(); } } static class ReverseChain implements Iterable { A element; ReverseChain prev; int size; ReverseChain() {} ReverseChain(ReverseChain prev, A element) { this.element = element; this.prev = prev; if (prev == null) size = 1; else { prev.check(); size = prev.size+1; } } void check() { if (size < 1) throw fail("You called the ReverseChain default constructor. Don't do that"); } public String toString() { return str(toList()); } ArrayList toList() { check(); ArrayList l = emptyList(size); for (int i = 0; i < size; i++) l.add(null); int i = size; ReverseChain c = this; while (c != null) { l.set(--i, c.element); c = c.prev; } return l; } public Iterator iterator() { return toList().iterator(); } } // a variant of thread where you can get the Runnable target later. // Also notes its existence on the VM bus. // We should use this exclusively instead of Thread. static class BetterThread extends Thread { Runnable target; BetterThread(Runnable target) { this.target = target; _created(); } BetterThread(Runnable target, String name) { super(name); this.target = target; _created(); } void _created() { vmBus_send("threadCreated", this); } public void run() { try { try { vmBus_send("threadStarted", this); if (target != null) target.run(); } finally { vmBus_send("threadEnded", this); } } catch (Exception __e) { throw rethrow(__e); } } Runnable getTarget() { return target; } } abstract static class RandomAccessAbstractList extends AbstractList implements RandomAccess { } static class Complex implements IFieldsToList{ static final String _fieldOrder = "re im"; double re; double im; Complex() {} Complex(double re, double im) { this.im = im; this.re = re;} public boolean equals(Object o) { if (!(o instanceof Complex)) return false; Complex __1 = (Complex) o; return re == __1.re && im == __1.im; } public int hashCode() { int h = -1679819632; h = boostHashCombine(h, _hashCode(re)); h = boostHashCombine(h, _hashCode(im)); return h; } public Object[] _fieldsToList() { return new Object[] {re, im}; } double abs() { return sqrt(re*re+im*im); } double re() { return re; } double im() { return im; } final double angle(){ return phase(); } double phase() { return Math.atan2(im, re); } double fracAngle() { return fracNonNeg(angle()/twoPi()); } // angle as 0 to 1 public String toString() { if (im != 0) return re == 0 ? im + "i" : re + plusPrefixUnlessMinus(str(im)) + "i"; else return str(re); } } static final class WidthAndHeightFinal extends Meta implements WidthAndHeight , IFieldsToList{ static final String _fieldOrder = "width height"; int width; int height; WidthAndHeightFinal() {} WidthAndHeightFinal(int width, int height) { this.height = height; this.width = width;} public boolean equals(Object o) { if (!(o instanceof WidthAndHeightFinal)) return false; WidthAndHeightFinal __0 = (WidthAndHeightFinal) o; return width == __0.width && height == __0.height; } public int hashCode() { int h = -1177452162; h = boostHashCombine(h, _hashCode(width)); h = boostHashCombine(h, _hashCode(height)); return h; } public Object[] _fieldsToList() { return new Object[] {width, height}; } public int getWidth() { return width; } public int getHeight() { return height; } WidthAndHeightFinal(int wAndH) { this(wAndH, wAndH); } public String toString() { return n2(width) + "*" + n2(height) + " px"; } } // Meta - a "minimal" approach to adding meta-level to Java objects static class Meta implements IMeta { // Meta - a "minimal" approach to adding meta-level to Java objects // (implementing the interface IMeta) // We allocate one extra field for each Java object to make it // reasoning-compatible (reasoning-compatible = extensible with // fields of any name at runtime). // // We couldn't go for 0 extra fields (meta values must be linked // directly from the object) and there are no half fields in // Java... so there you go. // // Also, if you don't use any meta data, you are probably not // reasoning about anything. The point of reasoning in JavaX is // to attach information to objects directly used in the program. // Possible information contained in the meta field: // Origin, destination, security level, sender, cost center, // purpose, list of reifications, ... // So here it is. THE FIELD YOU HAVE BEEN WAITING FOR! // [We also have IMeta to retrofit foreign classes (rare but // probably useful).] ////////////////////// // The "meta" field // ////////////////////// // Generic meta value of any kind, but the typical case is it's a // Map with extra field values for the object etc. // "meta" is volatile to avoid synchronization; but you can also synchronize on // _tempMetaMutex() which is usually the object itself. Collections // and maps are exempt from using the collections's monitor as the meta // mutex because their monitor tends to be held for long operations // (e.g. cloneList). For those we use a substantially more complex // algorithm using a weakMap. Probably overkill. I may reconsider. volatile Object meta; // The meta field is not transient, thus by default it will be // persisted like anything else unless you customize your object // to suppress or modulate this. // ...and the interface methods public void _setMeta(Object meta) { this.meta = meta; } public Object _getMeta() { return meta; } // MOST functions are implemented in IMeta (default implementations) // Scaffolding convenience functions final boolean scaffolding(){ return scaffoldingEnabled(); } final boolean scaffolded(){ return scaffoldingEnabled(); } boolean scaffoldingEnabled() { return main.scaffoldingEnabled(this); } boolean scaffoldingEnabled(Object o) { return main.scaffoldingEnabled(o); } // Implementing setMetaToString String toString_base() { return super.toString(); } public String toString() { Object o = metaGet("toString", this); if (o instanceof String) return ((String) o); if (o instanceof IF1) return str(((IF1) o).get(this)); return toString_base(); } } static interface IMeta { // see class "Meta" for the bla bla public void _setMeta(Object meta); public Object _getMeta(); default public IAutoCloseableF0 _tempMetaMutex() { return new IAutoCloseableF0() { public Object get() { return IMeta.this; } public void close() {} }; } // actually query another object default public Object getMeta(Object obj, Object key){ return metaGet(obj, key); } default public Object metaGet(Object obj, Object key) { // call global function return metaMapGet(obj, key); } default public Object metaGet(String key, Object obj) { // call global function return metaMapGet(obj, key); } default public Object getMeta(Object key){ return metaGet(key); } default public Object metaGet(Object key) { if (key == null) return null; Object meta = _getMeta(); if (meta instanceof Map) return ((Map) meta).get(key); return null; } default public void metaSet(IMeta obj, Object key, Object value){ metaPut(obj, key, value); } default public void metaPut(IMeta obj, Object key, Object value) { // call global function metaMapPut(obj, key, value); } default public void metaSet(Object key, Object value){ metaPut(key, value); } default public void metaPut(Object key, Object value) { if (key == null) return; Map map = convertObjectMetaToMap(this); syncMapPutOrRemove(map, key, value); } } static interface IAutoCloseableF0 extends IF0, AutoCloseable {} static double fracNonNeg(double d) { return frac_nonNeg(d); } static double twoPi() { return Math.PI*2; } static String plusPrefixUnlessMinus(String s) { return startsWith(s, "-") ? s : "+" + s; } static Object metaGet(IMeta o, Object key) { return metaMapGet(o, key); } static Object metaGet(Object o, Object key) { return metaMapGet(o, key); } static Object metaGet(String key, IMeta o) { return metaMapGet(o, key); } static Object metaGet(String key, Object o) { return metaMapGet(o, key); } static Object metaMapGet(IMeta o, Object key) { return o == null ? null : o.metaGet(key); // We now let the object itself do it (overridable!) } static Object metaMapGet(Object o, Object key) { return metaMapGet(toIMeta(o), key); } static void metaPut(IMeta o, Object key, Object value) { metaMapPut(o, key, value); } static void metaPut(Object o, Object key, Object value) { metaMapPut(o, key, value); } static void metaMapPut(IMeta o, Object key, Object value) { { if (o != null) o.metaPut(key, value); } } static void metaMapPut(Object o, Object key, Object value) { var meta = initIMeta(o); { if (meta != null) meta.metaPut(key, value); } } static Map convertObjectMetaToMap(IMeta o) { return convertObjectMetaToMap(o, () -> makeObjectMetaMap()); } static Map convertObjectMetaToMap(IMeta o, IF0 createEmptyMap) { if (o == null) return null; // The following shortcut depends on the assumption that a meta field never reverts // to null when it was a map Object meta = o._getMeta(); if (meta instanceof Map) return ((Map) meta); // non-shortcut path (create meta) var mutex = tempMetaMutex(o); try { var actualMutex = mutex.get(); synchronized(actualMutex) { meta = o._getMeta(); if (meta instanceof Map) return ((Map) meta); Map map = createEmptyMap.get(); if (meta != null) map.put("previousMeta" , meta); o._setMeta(map); return map; } } finally { _close(mutex); }} static void syncMapPutOrRemove(Map map, A key, B value) { syncMapPut2(map, key, value); } static double frac_nonNeg(double d) { return mod(d, 1); } static IMeta toIMeta(Object o) { return initIMeta(o); } static IMeta initIMeta(Object o) { if (o == null) return null; if (o instanceof IMeta) return ((IMeta) o); if (o instanceof JComponent) return initMetaOfJComponent((JComponent) o); // This is not really used. Try to use BufferedImageWithMeta instead if (o instanceof BufferedImage) return optCast(IMeta.class, ((BufferedImage) o).getProperty("meta")); return null; } static Map makeObjectMetaMap() { //ret synchroLinkedHashMap(); return new CompactHashMap(); } static IAutoCloseableF0 tempMetaMutex(IMeta o) { return o == null ? null : o._tempMetaMutex(); } static void syncMapPut2(Map map, A key, B value) { if (map != null && key != null) synchronized(collectionMutex(map)) { if (value != null) map.put(key, value); else map.remove(key); } } // better modulo that gives positive numbers always static int mod(int n, int m) { return (n % m + m) % m; } static long mod(long n, long m) { return (n % m + m) % m; } static BigInteger mod(BigInteger n, int m) { return n.mod(bigint(m)); } static double mod(double n, double m) { return (n % m + m) % m; } static IMeta initMetaOfJComponent(JComponent c) { if (c == null) return null; IMeta meta = (IMeta) (c.getClientProperty(IMeta.class)); if (meta == null) c.putClientProperty(IMeta.class, meta = new Meta()); return meta; } static A optCast(Class c, Object o) { return isInstance(c, o) ? (A) o : null; } // size: // 64 bytes for 0 to 1 elements // 96 bytes for 2 to 4 elements /* * #! * Ontopia Engine * #- * Copyright (C) 2001 - 2013 The Ontopia Project * #- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * !# */ static class CompactHashMap extends CompactAbstractMap { final static int INITIAL_SIZE = 3; final static double LOAD_FACTOR = 0.6; // This object is used to represent a null KEY (null value are kept as is) final static Object nullObject = new Object(); /** * When a key is deleted this object is put into the hashtable in * its place, so that other entries with the same key (collisions) * further down the hashtable are not lost after we delete an object * in the collision chain. */ final static Object deletedObject = new Object(); int elements; int freecells; Object[] table; // key, value, key, value, ... //int modCount; CompactHashMap() { this(INITIAL_SIZE); } CompactHashMap(int size) { table = new Object[(size==0 ? 1 : size)*2]; elements = 0; freecells = tableSize(); //modCount = 0; } // TODO: allocate smarter CompactHashMap(Map map) { this(0); if (map != null) putAll(map); } // ===== MAP IMPLEMENTATION ============================================= /** * Returns the number of key/value mappings in this map. */ public synchronized int size() { return elements; } /** * Returns true if this map contains no mappings. */ public synchronized boolean isEmpty() { return elements == 0; } /** * Removes all key/value mappings in the map. */ public synchronized void clear() { elements = 0; for (int ix = 0; ix < tableSize(); ix++) { key(ix, null); value(ix, null); } freecells = tableSize(); //modCount++; } /** * Returns true if this map contains the specified key. */ public synchronized boolean containsKey(Object k) { return key(findKeyIndex(k)) != null; } /** * Returns true if this map contains the specified value. */ public synchronized boolean containsValue(Object v) { if (v == null) v = (V)nullObject; for (int ix = 0; ix < tableSize(); ix++) if (value(ix) != null && value(ix).equals(v)) return true; return false; } /** * Returns a read-only set view of the map's keys. */ public synchronized Set> entrySet() { return new EntrySet(); } /** * Removes the mapping with key k, if there is one, and returns its * value, if there is one, and null if there is none. */ public synchronized V remove(Object k) { int index = findKeyIndex(k); // we found the right position, now do the removal if (key(index) != null) { // we found the object // same problem here as with put V v = value(index); key(index, deletedObject); value(index, deletedObject); //modCount++; elements--; return v; } else // we did not find the key return null; } /** * Adds the specified mapping to this map, returning the old value for * the mapping, if there was one. */ public synchronized V put(K k, V v) { if (k == null) k = (K)nullObject; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % tableSize(); int offset = 1; int deletedix = -1; // search for the key (continue while !null and !this key) while(key(index) != null && !(key(index).hashCode() == hash && key(index).equals(k))) { // if there's a deleted mapping here we can put this mapping here, // provided it's not in here somewhere else already if (key(index) == deletedObject) deletedix = index; index = ((index + offset) & 0x7FFFFFFF) % tableSize(); offset = offset*2 + 1; if (offset == -1) offset = 2; } if (key(index) == null) { // wasn't present already if (deletedix != -1) // reusing a deleted cell index = deletedix; else freecells--; //modCount++; elements++; key(index, k); value(index, v); // rehash with increased capacity if (1 - (freecells / (double) tableSize()) > LOAD_FACTOR) rehash(tableSize()*2 + 1); return null; } else { // was there already //modCount++; V oldv = value(index); value(index, v); return oldv; } } /** * INTERNAL: Rehashes the hashmap to a bigger size. */ void rehash(int newCapacity) { int oldCapacity = tableSize(); Object[] newTable = new Object[newCapacity*2]; for (int ix = 0; ix < oldCapacity; ix++) { Object k = key(ix); if (k == null || k == deletedObject) continue; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % newCapacity; int offset = 1; // search for the key while(newTable[index*2] != null) { // no need to test for duplicates index = ((index + offset) & 0x7FFFFFFF) % newCapacity; offset = offset*2 + 1; if (offset == -1) offset = 2; } newTable[index*2] = k; newTable[index*2+1] = value(ix); } table = newTable; freecells = tableSize() - elements; } /** * Returns the value for the key k, if there is one, and null if * there is none. */ public synchronized V get(Object k) { return value(findKeyIndex(k)); } /** * Returns a virtual read-only collection containing all the values * in the map. */ public synchronized Collection values() { return new ValueCollection(); } /** * Returns a virtual read-only set of all the keys in the map. */ public synchronized Set keySet() { return new KeySet(); } // --- Internal utilities final int findKeyIndex(Object k) { if (k == null) k = nullObject; int hash = k.hashCode(); int index = (hash & 0x7FFFFFFF) % tableSize(); int offset = 1; // search for the key (continue while !null and !this key) while(key(index) != null && !(key(index).hashCode() == hash && key(index).equals(k))) { index = ((index + offset) & 0x7FFFFFFF) % tableSize(); offset = offset*2 + 1; if (offset == -1) offset = 2; } return index; } // --- Key set class KeySet extends AbstractSet { public int size() { synchronized(CompactHashMap.this) { return elements; }} public boolean contains(Object k) { synchronized(CompactHashMap.this) { return containsKey(k); }} public Iterator iterator() { synchronized(CompactHashMap.this) { return new KeyIterator(); }} } class KeyIterator implements Iterator { private int ix; private KeyIterator() { synchronized(CompactHashMap.this) { // walk up to first value, so that hasNext() and next() return // correct results for (; ix < tableSize(); ix++) if (value(ix) != null && key(ix) != deletedObject) break; } } public boolean hasNext() { synchronized(CompactHashMap.this) { return ix < tableSize(); }} public void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public K next() { synchronized(CompactHashMap.this) { if (ix >= tableSize()) throw new NoSuchElementException(); K key = (K) key(ix++); // walk up to next value for (; ix < tableSize(); ix++) if (key(ix) != null && key(ix) != deletedObject) break; // ix now either points to next key, or outside array (if no next) return key; }} } // --- Entry set class EntrySet extends AbstractSet> { public int size() { synchronized(CompactHashMap.this) { return elements; }} public boolean contains(Object o) { synchronized(CompactHashMap.this) { if (o instanceof Map.Entry) { Object key = ((Map.Entry) o).getKey(); if (!containsKey((Map.Entry) o)) return false; return eq(((Map.Entry) o).getValue(), get(key)); } return false; }} public Iterator> iterator() { return new EntryIterator(); } } class EntryIterator implements Iterator> { private int ix; private EntryIterator() { synchronized(CompactHashMap.this) { // walk up to first value, so that hasNext() and next() return // correct results for (; ix < tableSize(); ix++) if (value(ix) != null && key(ix) != deletedObject) break; } } public boolean hasNext() { synchronized(CompactHashMap.this) { return ix < tableSize(); }} public void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public Map.Entry next() { synchronized(CompactHashMap.this) { if (ix >= tableSize()) throw new NoSuchElementException(); K key = key(ix); V val = value(ix); ++ix; // walk up to next value for (; ix < tableSize(); ix++) if (key(ix) != null && key(ix) != deletedObject) break; // ix now either points to next key, or outside array (if no next) return simpleMapEntry(key, val); }} } // --- Value collection class ValueCollection extends AbstractCollection { public int size() { synchronized(CompactHashMap.this) { return elements; }} public Iterator iterator() { return new ValueIterator(); } public boolean contains(Object v) { return containsValue(v); } } class ValueIterator implements Iterator { private int ix; private ValueIterator() { synchronized(CompactHashMap.this) { // walk up to first value, so that hasNext() and next() return // correct results for (; ix < table.length/2; ix++) if (value(ix) != null && value(ix) != deletedObject) break; } } public boolean hasNext() { synchronized(CompactHashMap.this) { return ix < tableSize(); }} public void remove() { throw new UnsupportedOperationException("Collection is read-only"); } public V next() { synchronized(CompactHashMap.this) { if (ix >= tableSize()) throw new NoSuchElementException(); V value = (V) value(ix++); // walk up to next value for (; ix < tableSize(); ix++) if (value(ix) != null && value(ix) != deletedObject) break; // ix now either points to next value, or outside array (if no next) return value; }} } K key(int i) { return (K) table[i*2]; } void key(int i, Object key) { table[i*2] = key; } V value(int i) { return (V) table[i*2+1]; } void value(int i, Object value) { table[i*2+1] = value; } int tableSize() { return table.length/2; } } abstract static class CompactAbstractMap implements Map { public int size() { return entrySet().size(); } public boolean isEmpty() { return size() == 0; } public boolean containsValue(Object value) { Iterator> i = entrySet().iterator(); if (value == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getValue() == null) return true; } } else { while (i.hasNext()) { Entry e = i.next(); if (value.equals(e.getValue())) return true; } } return false; } public boolean containsKey(Object key) { Iterator> i = entrySet().iterator(); if (key == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) return true; } } else { while (i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) return true; } } return false; } public V get(Object key) { Iterator> i = entrySet().iterator(); if (key == null) { while (i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) return e.getValue(); } } else { while (i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) return e.getValue(); } } return null; } public V put(K key, V value) { throw new UnsupportedOperationException(); } public V remove(Object key) { Iterator> i = entrySet().iterator(); Entry correctEntry = null; if (key == null) { while (correctEntry == null && i.hasNext()) { Entry e = i.next(); if (e.getKey() == null) correctEntry = e; } } else { while (correctEntry == null && i.hasNext()) { Entry e = i.next(); if (key.equals(e.getKey())) correctEntry = e; } } V oldValue = null; if (correctEntry != null) { oldValue = correctEntry.getValue(); i.remove(); } return oldValue; } public void putAll(Map m) { for (Entry e : m.entrySet()) put(e.getKey(), e.getValue()); } public void clear() { entrySet().clear(); } public Set keySet() { return new AbstractSet() { public Iterator iterator() { return new Iterator() { private Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public K next() { return i.next().getKey(); } public void remove() { i.remove(); } }; } public int size() { return CompactAbstractMap.this.size(); } public boolean isEmpty() { return CompactAbstractMap.this.isEmpty(); } public void clear() { CompactAbstractMap.this.clear(); } public boolean contains(Object k) { return CompactAbstractMap.this.containsKey(k); } }; } public Collection values() { return new AbstractCollection() { public Iterator iterator() { return new Iterator() { private Iterator> i = entrySet().iterator(); public boolean hasNext() { return i.hasNext(); } public V next() { return i.next().getValue(); } public void remove() { i.remove(); } }; } public int size() { return CompactAbstractMap.this.size(); } public boolean isEmpty() { return CompactAbstractMap.this.isEmpty(); } public void clear() { CompactAbstractMap.this.clear(); } public boolean contains(Object v) { return CompactAbstractMap.this.containsValue(v); } }; } public abstract Set> entrySet(); public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Map)) return false; Map m = (Map) o; if (m.size() != size()) return false; try { for (Entry e : entrySet()) { K key = e.getKey(); V value = e.getValue(); if (value == null) { if (!(m.get(key) == null && m.containsKey(key))) return false; } else { if (!value.equals(m.get(key))) return false; } } } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } return true; } public int hashCode() { int h = 0; for (Entry entry : entrySet()) h += entry.hashCode(); return h; } public String toString() { Iterator> i = entrySet().iterator(); if (!i.hasNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.append('{'); for (; ; ) { Entry e = i.next(); K key = e.getKey(); V value = e.getValue(); sb.append(key == this ? "(this Map)" : key); sb.append('='); sb.append(value == this ? "(this Map)" : value); if (!i.hasNext()) return sb.append('}').toString(); sb.append(',').append(' '); } } protected Object clone() throws CloneNotSupportedException { CompactAbstractMap result = (CompactAbstractMap) super.clone(); return result; } public static class SimpleEntry implements Entry, java.io.Serializable { @java.io.Serial private static final long serialVersionUID = -8499721149061103585L; @SuppressWarnings("serial") private final K key; @SuppressWarnings("serial") private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } } public static class SimpleImmutableEntry implements Entry, java.io.Serializable { @java.io.Serial private static final long serialVersionUID = 7138329143949025153L; @SuppressWarnings("serial") private final K key; @SuppressWarnings("serial") private final V value; public SimpleImmutableEntry(K key, V value) { this.key = key; this.value = value; } public SimpleImmutableEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { throw new UnsupportedOperationException(); } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Entry e = (Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } public int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } public String toString() { return key + "=" + value; } } } static boolean scaffoldingEnabled(Object o) { return metaGet(o, "scaffolding") != null; } static Value value(A a) { return new Value(a); } static boolean containsKey(Map map, A key) { return map != null && map.containsKey(key); } static Map.Entry simpleMapEntry(A key, B value) { return new Map.Entry() { public A getKey() { return key; } public B getValue() { return value; } public B setValue(B newValue) { throw unimplemented(); } }; } static RuntimeException unimplemented() { throw fail("TODO"); } static RuntimeException unimplemented(String msg) { throw fail("TODO: " + msg); } static RuntimeException unimplemented(Object obj) { throw fail("TODO: implement method in " + className(obj)); } static class Value implements IF0 , IFieldsToList{ A value; Value() {} Value(A value) { this.value = value;} public boolean equals(Object o) { if (!(o instanceof Value)) return false; Value __1 = (Value) o; return eq(value, __1.value); } public int hashCode() { int h = 82420049; h = boostHashCombine(h, _hashCode(value)); return h; } public Object[] _fieldsToList() { return new Object[] {value}; } public A get() { return value; } public String toString() { return str(get()); } } }