Warning : session_start(): open(/var/lib/php/sessions/sess_kpnikg32r2tk1o38h1p5lmdkt8, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import java.util.function.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import javax.imageio.*;
import java.math.*;
import net.dv8tion.jda.api.events.Event;
import net.dv8tion.jda.api.events.user.update.*;
import net.dv8tion.jda.api.managers.AudioManager;
import net.dv8tion.jda.api.audio.*;
import net.dv8tion.jda.api.events.guild.voice.*;
import com.sedmelluq.discord.lavaplayer.player.*;
import com.sedmelluq.discord.lavaplayer.player.event.*;
import com.sedmelluq.discord.lavaplayer.track.*;
import com.sedmelluq.discord.lavaplayer.track.playback.*;
import com.sedmelluq.discord.lavaplayer.source.*;
import com.sedmelluq.discord.lavaplayer.tools.*;
import x30_pkg.x30_util;
import static x30_pkg.x30_util.VF1;
import static x30_pkg.x30_util.l;
import static x30_pkg.x30_util.indexOf;
import static x30_pkg.x30_util.getOpt;
import static x30_pkg.x30_util.setOpt;
import static x30_pkg.x30_util.callOpt;
import static x30_pkg.x30_util.newWeakHashMap;
import static x30_pkg.x30_util.newDangerousWeakHashMap;
import static x30_pkg.x30_util.get;
import static x30_pkg.x30_util.get_raw;
import static x30_pkg.x30_util.assertTrue;
import static x30_pkg.x30_util.isHeadless;
import static x30_pkg.x30_util.isAndroid;
import static x30_pkg.x30_util.isTrue;
import x30_pkg.x30_util.DynamicObject;
import loadableUtils.utils;
import static loadableUtils.utils._threadInfo;
import static loadableUtils.utils._threadInheritInfo;
import static loadableUtils.utils.dm_currentModule;
import static loadableUtils.utils.dm_current_mandatory;
import static loadableUtils.utils.match;
import static loadableUtils.utils.fieldType;
import static loadableUtils.utils.vm_generalIdentityHashSet;
import static loadableUtils.utils.vm_generalHashMap;
import static loadableUtils.utils.vm_generalWeakSubMap;
import static loadableUtils.utils.bindToComponent;
import static loadableUtils.utils.struct;
import static loadableUtils.utils.structure;
import static loadableUtils.utils.loadPage;
import static loadableUtils.utils.loadPageSilently;
import static loadableUtils.utils.loadSnippet;
import static loadableUtils.utils.componentPopupMenu;
import static loadableUtils.utils.componentPopupMenu_initForComponent;
import static loadableUtils.utils.dm_current_generic;
import static loadableUtils.utils.dm_current_mandatory_generic;
import static loadableUtils.utils.DynamicObject_loading;
import static loadableUtils.utils.rethrow;
import loadableUtils.utils.F0;
import loadableUtils.utils.F1;
import loadableUtils.utils.IF0;
import loadableUtils.utils.IF1;
import loadableUtils.utils.IVF1;
import loadableUtils.utils.IVF2;
import loadableUtils.utils.Matches;
import loadableUtils.utils.BetterLabel;
import loadableUtils.utils.SingleComponentPanel;
import loadableUtils.utils.Q;
import loadableUtils.utils.structure_Data;
import loadableUtils.utils.structure_ClassInfo;
import loadableUtils.utils.RGBImage;
import loadableUtils.utils.MultiSet;
import loadableUtils.utils.Concept;
import loadableUtils.utils.Concepts;
import loadableUtils.utils.RC;
import loadableUtils.utils.IterableIterator;
import loadableUtils.utils.PersistableThrowable;
import loadableUtils.utils.DynModule;
import loadableUtils.utils.DynPrintLog;
import loadableUtils.utils.Rect;
import loadableUtils.utils.Pt;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.nio.charset.Charset;
import java.text.*;
import java.util.TimeZone;
import net.dv8tion.jda.api.events.guild.member.*;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.requests.restaction.MessageAction;
import net.dv8tion.jda.api.requests.RestAction;
import java.util.function.Consumer;
import javax.swing.undo.UndoManager;
import java.awt.datatransfer.StringSelection;
import java.awt.geom.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import net.dv8tion.jda.api.*;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.hooks.*;
import net.dv8tion.jda.api.events.message.*;
import net.dv8tion.jda.api.events.message.react.*;
import static net.dv8tion.jda.api.requests.GatewayIntent.*;
import javax.swing.border.*;
class main {
abstract static public class DynTalkBot2 extends DynServerAwareDiscordBot {
static public boolean _switchableField_myName = true;
public String myName = "Anonymous bot";
transient public boolean useAGIBlueForDropPunctuation = true;
transient public boolean preprocessAtSelfToMyName = true;
transient public boolean dropPunctuation = true;
transient public boolean ngbCommands = true;
public List authorizedUsers = ll(547706854680297473L);
static public class ISaid implements IFieldsToList {
public long channelID;
public long date;
public String text;
public ISaid() {
}
public ISaid(long channelID, long date, String text) {
this.text = text;
this.date = date;
this.channelID = channelID;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + channelID + ", " + date + ", " + text + ")";
}
public boolean equals(Object o) {
if (!(o instanceof ISaid))
return false;
ISaid __10 = (ISaid) o;
return channelID == __10.channelID && date == __10.date && eq(text, __10.text);
}
public int hashCode() {
int h = 69986258;
h = boostHashCombine(h, _hashCode(channelID));
h = boostHashCombine(h, _hashCode(date));
h = boostHashCombine(h, _hashCode(text));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { channelID, date, text };
}
}
public void init() {
super.init();
onPostedInChannel.add((channel, msg) -> {
if (channel instanceof GuildChannel) {
Guild guild = ((GuildChannel) channel).getGuild();
if (guild == null)
return;
ByServer bs = getByServer(guild);
long channelID = ((GuildChannel) channel).getIdLong();
mapPut(bs.lastSaidInChannel, channelID, nu(ISaid.class, "channelID", channelID, "text", msg));
change();
}
});
dm_vmBus_onMessage_q("discordGuildJoin", new VF1() {
public void get(Map map) {
try {
{
if (!(map.get("module") == module()))
return;
}
print("Got join");
getByServer(getLong("guildID", map), true).onUserJoin(getLong("userID", map), map);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret unless map.get('module) == module();\r\n print(\"Got join\");\r\n get...";
}
});
onDiscordEvent(e -> {
if (e instanceof UserUpdateOnlineStatusEvent)
getByServer(((UserUpdateOnlineStatusEvent) e).getGuild()).onOnlineStatusChange((UserUpdateOnlineStatusEvent) e);
});
}
public class ByServer extends DynServerAwareDiscordBot.ByServer {
transient public Lock lock;
public List guildAuthorizedUsers = synchroList();
public Map lastSaidInChannel = synchroMap();
public long preferredChannelInGuild;
public DynTalkBot2 m2() {
return DynTalkBot2.this;
}
public void onUserJoin(long userID, Object... __) {
}
public void onOnlineStatusChange(UserUpdateOnlineStatusEvent e) {
}
public String myName() {
return myName;
}
@Override
public String answer(String input, Map map) {
if (preferredChannelInGuild == 0) {
long channelID = longPar("channelID", map);
if (channelID != 0) {
preferredChannelInGuild = channelID;
change();
}
}
String answer = processLine(input, map);
{
String __3 = super.answer(input, map);
if (!empty(__3))
return __3;
}
return answer;
}
public String dropMyPrefixOpt(String s) {
return or(dropMyPrefixOrNull(s), s);
}
public String dropMyPrefixOrNull(String s) {
String sOld = s;
s = dropPrefixICTrim_orNull(myPrefix(), s);
if (s == null)
print("no got prefix: " + quote(myPrefix()) + " / " + quote(sOld));
return s;
}
public String processLine(String s, Object... __) {
s = preprocess(s, __);
return processSimplifiedLine(s, __);
}
public String preprocess(String s, Object... __) {
print("Preprocessing: " + quote(s));
if (preprocessAtSelfToMyName && discordBotID != 0) {
List l = ll(atSelf(), atExclamSelf());
print("Replacing " + sfu(l));
s = replace_multi(s, l, " " + myName + " ");
print("Got " + quote(s));
}
if (dropPunctuation)
s = dropPunctuation3_withAGIBlue(useAGIBlueForDropPunctuation, s);
s = trim(simpleSpaces_noTok(s));
print("simplified >> " + quote(s));
return s;
}
public String myPrefix() {
return preprocessAtSelfToMyName ? (endsWithLetterOrDigit(myName()) ? myName() + " " : myName()) : (dropPunctuation ? replace(atSelf(), "@", "") : atSelf()) + " ";
}
synchronized public Lock myLock() {
if (lock == null)
lock = lock();
return lock;
}
public String processSimplifiedLine(String input, Object... __) {
Lock __1 = myLock();
lock(__1);
try {
Matches m = new Matches();
input = dropMyPrefixOrNull(input);
if (input == null)
return null;
if (ngbCommands) {
if (eqicOneOf(input, "support channel", "support server", "support"))
return "Get support for me here: " + nextGenBotsDiscordInvite();
if (eqicOneOf(input, "source", "sources", "source code"))
return snippetLink(programID());
}
if (swic_trim(input, "add master ", m)) {
String __4 = checkAuth(__);
if (!empty(__4))
return __4;
setAdd(authorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. Have " + n2(l(authorizedUsers), "master");
}
if (eqic(input, "masters"))
return linesLL("General: " + renderMasters(), "For this guild: " + renderGuildMasters());
if (eqic(input, "guild masters"))
return renderGuildMasters();
if (swic_trim(input, "delete master ", m)) {
String __5 = checkAuth(__);
if (!empty(__5))
return __5;
remove(authorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. Have " + n2(l(authorizedUsers), "master");
}
if (swic_trim(input, "add guild master ", m)) {
String __6 = checkPerGuildAuth(__);
if (!empty(__6))
return __6;
setAdd(guildAuthorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. " + renderGuildMasters();
}
if (swic_trim(input, "delete guild master ", m)) {
String __7 = checkPerGuildAuth(__);
if (!empty(__7))
return __7;
remove(guildAuthorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. " + renderGuildMasters();
}
if (eqic(input, "guild count")) {
String __8 = checkAuth(__);
if (!empty(__8))
return __8;
return renderGuildCount();
}
if (eqic(input, "guild names")) {
String __9 = checkAuth(__);
if (!empty(__9))
return __9;
return renderGuildNames();
}
return null;
} finally {
unlock(__1);
}
}
public String renderGuildMasters() {
return empty(guildAuthorizedUsers) ? "Only this guild's owner can control me." : "I am controlled by this guild's owner and these people: " + joinWithComma(map(__51 -> discordAtPlusID(__51), guildAuthorizedUsers));
}
public String renderGuildCount() {
return "Total guilds joined: " + guildCount + ". Live guilds: " + liveGuildCount();
}
public String renderGuildNames() {
return lines(map(discord.getGuilds(), g -> g.getName()));
}
public boolean authed(Object... __) {
return contains(authorizedUsers, optPar("userID", __));
}
public boolean perGuildAuthed(Object... __) {
long userID = longPar("userID", __);
return contains(guildAuthorizedUsers, userID) || guildID != 0 && userID == getGuild().getOwnerIdLong();
}
public Guild getGuild() {
return guildID == 0 ? null : discord.getGuildById(guildID);
}
public String checkAuth(Object... __) {
long userID = longPar("userID", __);
boolean result = authed(__);
print("Auth-checking user ID: " + userID + " => " + result);
if (!result)
return "You are not authorized";
return null;
}
public String checkPerGuildAuth(Object... __) {
if (authed(__))
return null;
long userID = longPar("userID", __);
boolean result = perGuildAuthed(__);
print("Guild-auth-checking user ID: " + userID + " => " + result);
if (!result)
return "You are not authorized";
return null;
}
public String guildStructure() {
return structure_nullingInstancesOfClass(_getClass(module()), this);
}
public String atSelfOrMyName() {
return preprocessAtSelfToMyName ? myName() : atSelf();
}
public String atSelfOrMyName_space() {
return preprocessAtSelfToMyName ? appendSpaceIfEndsWithLetter(myName) : atSelf();
}
public String guildMastersHelp() {
return "\r\n@me **masters** -- show who controls me\r\n@me **add guild master @user** -- allow @user to control me\r\n@me **delete guild master @user** -- @user can no longer control me\r\n";
}
}
public String serveGuildBackup(MessageChannel channel, Guild guild, String data) {
if (guild == null)
return "Do this in a guild";
if (containsDiscordToken(data))
return "DISCORD TOKEN EXPOSED ALARM!! NOTIFY ADMINISTRATOR";
String baseName = urlencode(jda_selfUserName(discord)) + "-" + guild.getIdLong() + "-" + ymd_minus_hms();
String zipName = baseName + ".zip";
File zip = programFile("backups/" + zipName);
createZipFileWithSingleTextFile(zip, baseName + ".txt", data);
channel.sendMessage("Here's my latest brain contents for this guild.").addFile(zip).queue();
return null;
}
public String serveGuildBackup(MessageChannel channel, Guild guild, ByServer bs) {
return serveGuildBackup(channel, guild, bs.guildStructure());
}
public String renderMasters() {
return empty(authorizedUsers) ? "I have no masters." : "My masters are: " + joinWithComma(map(__52 -> discordAtPlusID(__52), authorizedUsers));
}
}
static public class MKLabFM extends DynTalkBot2 {
static public boolean _switchableField_radioURL = true;
public String radioURL = "http://streamlive2.hearthis.at:8080/26450.ogg";
static public boolean _switchableField_currentSongURL = true;
public String currentSongURL = "https://widgets.autopo.st/widgets/public/MKLabFM/nowplaying.php";
static public boolean _switchableField_coverArtURL = true;
public String coverArtURL = "http://95.154.196.33:26687/playingart?sid=1&rand=";
static public boolean _switchableField_enableShadowStop = true;
public boolean enableShadowStop = true;
static public boolean _switchableField_putSongInStatus = true;
public boolean putSongInStatus = true;
transient public double bufferSeconds = 30.0;
transient public int grabInterval = 15;
transient public double considerDownInterval = 60.0;
transient public double autoRestartInterval = 20.0;
static public boolean _switchableField_madeBy = true;
public String madeBy = trim("\r\nMKLab: \r\nSupport channel: \r\nBot by: \r\nYou like this bot? Donate: \r\n");
static public boolean _switchableField_voteLink = true;
public String voteLink = "\n\nPlease help us grow by voting here: ";
static public boolean _switchableField_npMsg = true;
public String npMsg = "Now playing: - Listen at }{ https://tinyurl.com/mklab-live-fm }{ #edm #music #radio #ibiza #dance #chillout #psy #live #miami #memes #detroit #techno #dj #synthwave #housemusic #deephouse #onair";
static public boolean _switchableField_uploadImagesAsFiles = true;
public boolean uploadImagesAsFiles = true;
transient public SimpleCircularBuffer buffer;
transient public AudioPlayer player;
static public boolean _switchableField_restartNow = true;
transient public boolean simulateStreamDown, restartNow;
transient public long lastFrameReceived, lastActualFrameReceived;
transient public long moduleStarted;
transient public NotTooOften postRestarting = onlyEveryHour();
transient public String currentSong;
transient public AtomicLong framesReceived = new AtomicLong();
transient public AtomicLong canProvideCalls = new AtomicLong();
transient public AtomicLong provideCalls = new AtomicLong();
transient public AtomicLong dataSent = new AtomicLong();
public Object _getReloadData() {
return currentSong;
}
public void _setReloadData(String data) {
currentSong = data;
}
public void init() {
super.init();
myName = "!!!";
makeByServer = () -> new ByServer();
dropPunctuation = false;
preprocessAtSelfToMyName = true;
ngbCommands = false;
sendToPostedLinesCRUD = false;
initStream();
onDiscordStarted(new Runnable() {
public void run() {
try {
AutoCloseable __27 = enter();
try {
print("Bot back up");
for (Map.Entry extends Long, ? extends ByServer> __22 : _entrySet(cloneMap(dataByServer))) {
Long id = __22.getKey();
ByServer bs = __22.getValue();
try {
bs.restart(discord.getGuildById(id));
} catch (Throwable __e) {
printStackTrace(__e);
}
}
postInChannel(nextGenBotsTestRoomID(), "Rebooted " + computerID() + "/" + dm_moduleID());
} finally {
_close(__27);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter();\r\n print(\"Bot back up\");\r\n for (Map.Entry extends Lo...";
}
});
onDiscordEvent(e -> {
if (e instanceof GenericGuildVoiceEvent)
getByServer(((GenericGuildVoiceEvent) e).getGuild()).handleVoiceUpdateEvent((GenericGuildVoiceEvent) e);
});
doEveryAndNow(20.0, new Runnable() {
public void run() {
try {
grabSong();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "grabSong();";
}
});
doEvery(60.0, new Runnable() {
public void run() {
try {
updateVoiceChannelCount_allServers();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updateVoiceChannelCount_allServers();";
}
});
}
public void initStream() {
buffer = new SimpleCircularBuffer(iround(bufferSeconds * 50));
player = lavaPlayer_createPlayer();
lavaPlayer_printPlayerEvents(player);
print("Have player");
doEvery(grabInterval, new Runnable() {
public void run() {
try {
AutoCloseable __28 = enter();
try {
if (!simulateStreamDown) {
AudioFrame frame = player.provide();
if (frame != null) {
buffer.add(frame.getData());
inc(framesReceived);
lastFrameReceived = lastActualFrameReceived = sysNow();
}
}
} finally {
_close(__28);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter();\r\n if (!simulateStreamDown) {\r\n AudioFrame frame = p...";
}
});
doEvery(1.0, new Runnable() {
public void run() {
try {
AutoCloseable __29 = enter();
try {
if (discord == null)
return;
if (restartNow || elapsedSeconds(lastFrameReceived) >= autoRestartInterval) {
if (postRestarting.yo())
postInChannel(nextGenBotsTestRoomID(), "Restarting radio stream");
simulateStreamDown = restartNow = false;
lastFrameReceived = sysNow();
loadTrack();
lastFrameReceived = sysNow();
}
} finally {
_close(__29);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter();\r\n if (discord == null) return;\r\n if (restartNow || el...";
}
});
}
public class ByServer extends DynTalkBot2.ByServer {
public boolean shouldBePlaying = false;
public long voiceChannelID, lastVoiceChannelID;
public long songChannelID;
transient public String voiceChannelName;
transient public VoiceChannel vc;
transient public MyAudioSendHandler sendHandler;
transient public Set usersInVoiceChannel = synchroSet();
synchronized public String processSimplifiedLine(String s, Object... __) {
AutoCloseable __30 = enter();
try {
try {
return processSimplifiedLine2(s, __);
} catch (Throwable e) {
printStackTrace(e);
if (cic(str(e), "InsufficientPermission"))
return "There were insufficient permissions to perform this action.";
return "Sorry, an error occurred trying to perform this action.";
}
} finally {
_close(__30);
}
}
synchronized public String processSimplifiedLine2(String s, Object... __) {
String __24 = super.processSimplifiedLine(s, __);
if (!empty(__24))
return __24;
Matches m = new Matches();
print("myPrefix", quote(myPrefix()));
s = dropMyPrefixOrNull(s);
print("dropped", quote(s));
if (s == null)
return null;
Message msg = (Message) (optPar("msg", __));
Guild guild = msg.getGuild();
Member member = msg == null ? null : msg.getMember();
if (eqic(s, "help")) {
MessageChannel channel = (MessageChannel) (optPar("channel", __));
String syntax = trim("\r\n`@me play | start` - start playing\r\n`@me stop | pause` - stop playing\r\n`@me leave` - leave voice channel\r\n`@me help` - show this help\r\n`@me np` - show currently playing song\r\n`@me join` - join any voice channel\r\n`@me set channel` - post now playing track names in current channel\r\n`@me stop posting` - stop posting track names\r\n[MORE]\r\n".replace("\n[MORE]", renderChannelListIfNotOne(guild)).replace("@me ", myPrefix())) + voteLink;
EmbedBuilder eb = new EmbedBuilder();
eb.setColor(Color.yellow);
eb.setAuthor("MKLab FM Bot", null, null);
eb.setTitle("Purpose", null);
eb.setDescription("I play MKLab FM, the best Electronic Dance Music Radio, in a voice channel of your choice.");
discordEmbed_addField(eb, "Syntax", syntax);
if (authed(__))
eb.addField("Admin commands", rtrim("\r\n`@me guild count/guild names` - show stats\r\n`@me reboot` - reboot the whole bot (if music stream is completely broken for some reason)\r\n`@me dm owners: ` - DM all guild owners where radio is playing\r\n`@me stream url http...` - set stream URL. current: $STREAMURL\r\n`@me np url http...` - set current song URL. current: $NPURL\r\n`@me cover url http...` - set cover art URL. current: $COVERURL\r\n`@me cover url -` - disable cover art\r\n`@me np msg Playing ...` - set nowplaying message. current: $NPMSG\r\n`@me listeners` - full list of listeners\r\n").replace("@me ", myPrefix()).replace("$STREAMURL", backtickQuote(radioURL)).replace("$NPURL", backtickQuote(currentSongURL)).replace("$NPMSG", backtickQuote(npMsg)).replace("$COVERURL", backtickQuote(coverArtURL)), false);
eb.addField("Made by", madeBy, false);
eb.setThumbnail(imageSnippetURL("#1102722"));
channel.sendMessage(eb.build()).queue();
return null;
}
if (guild == null)
return null;
if (authed(__)) {
if (match("reboot", s)) {
doAfter(2.0, new Runnable() {
public void run() {
try {
AutoCloseable __35 = enter();
try {
dm_reload();
} finally {
_close(__35);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); dm_reload();";
}
});
return "OK, rebooting bot";
}
if (match("simulate stream down", s)) {
simulateStreamDown = true;
return "OK";
}
if (swic_trim(s, "dm owners:", m))
return dmOwners(m.unq(0));
if (swic_trim(s, "stream url ", m) && isWebURL(m.rest())) {
if (!MKLabFM.this.setField("radioURL", m.rest()))
return "No change";
restartNow = true;
return "OK, restarting with radio URL " + radioURL;
}
if (swic_trim(s, "np url ", m) && isWebURL(m.rest())) {
if (!MKLabFM.this.setField("currentSongURL", m.rest()))
return "No change";
return "Current song URL changed to " + currentSongURL;
}
if (swic_trim(s, "cover url ", m)) {
if (!MKLabFM.this.setField("coverArtURL", m.rest()))
return "No change";
return "Cover art URL changed to " + coverArtURL;
}
if (swic_trim(s, "np msg ", m)) {
if (!MKLabFM.this.setField("npMsg", m.rest()))
return "No change";
return "Nowplaying message changed to " + npMsg;
}
if (match("listeners", s))
return or2(listeningUsers_full(), "No listeners");
}
if (matchX2("play ...|start...|radio|radio on", s))
return action_play(guild, member);
if (matchX2("stop ...|pause ...|quiet|silence|shut up|... off", s) && !match("stop posting", s))
return action_stop(guild);
if (matchX2("leave|leave channel|leave voice channel", s))
return action_leave(guild);
if (matchX2("join|join channel|join voice channel", s))
return action_join(guild, member);
if (matchX2("... channel *", s, m) && isInteger(m.unq(0)))
return action_selectChannel(guild, parseInt(m.unq(0)));
if (matchX2("np|n p|... song ...|... playing ...", s))
return "MKLab FM is currently playing: " + (nempty(currentSong) ? backtickQuote(currentSong) : "Hmm. Not sure, I think something went wrong.");
if (matchX2("set channel|post here|set np", s)) {
long channelID = longPar("channelID", __);
if (channelID == 0)
return "Please do this in a channel";
if (songChannelID != channelID) {
songChannelID = channelID;
change();
}
doAfter(2.0, new Runnable() {
public void run() {
try {
postSong();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "postSong();";
}
});
return "OK, I will post the currently playing tracks in this channel. Type `" + atSelfOrMyName_space() + "stop posting` to stop.";
}
if (matchX2("stop posting|no channel", s)) {
songChannelID = 0;
change();
return "OK";
}
if (match("users in channel", s))
return "Users in voice channel: " + n2(usersInVoiceChannel);
if (match("internal stats", s))
return "Frames received: " + n2(framesReceived.get()) + ", canProvide calls: " + n2(canProvideCalls.get()) + ", provide calls: " + n2(provideCalls.get()) + ", bytes sent: " + n2(dataSent.get());
return null;
}
public String renderGuildCount() {
List guilds = discord.getGuilds();
int shouldPlayCount = 0, shadowCount = 0;
for (Guild guild : guilds) {
ByServer bs = getByServer(guild.getIdLong(), true);
if (bs != null) {
if (bs.shouldBePlaying) {
++shouldPlayCount;
if (bs.shadowStopped())
++shadowCount;
}
}
}
return super.renderGuildCount() + ". " + nRadios(shouldPlayCount - shadowCount) + " playing to " + n2(listeningUsers(), "listener") + ", " + shadowCount + " playing without listeners";
}
public void joinVoiceChannel(Guild guild) {
vc = guild.getVoiceChannelById(voiceChannelID);
guild.getAudioManager().openAudioConnection(vc);
voiceChannelName = vc.getName();
updateVoiceChannelCount();
}
public void updateVoiceChannelCount() {
if (vc == null) {
usersInVoiceChannel.clear();
return;
}
List members = vc.getMembers();
int n = l(usersInVoiceChannel);
replaceCollection(usersInVoiceChannel, mapNonNulls_pcall(members, m -> {
User user = m.getUser();
return user.isBot() ? null : user.getIdLong();
}));
int n2 = l(usersInVoiceChannel);
if (n != n2)
print(guildID + " voice channel count corrected: " + n + " -> " + n2);
}
public boolean shadowStopped() {
return enableShadowStop && empty(usersInVoiceChannel);
}
public class MyAudioSendHandler implements AudioSendHandler {
public long counter = -1;
public byte[] data;
public boolean canProvide() {
AutoCloseable __31 = enter();
try {
inc(canProvideCalls);
if (!shouldBePlaying)
return false;
if (shadowStopped()) {
counter = -1;
return false;
}
synchronized (buffer) {
if (!buffer.isFull())
return false;
data = buffer.get(counter);
if (data == null) {
long oldCounter = counter;
counter = buffer.getBase() + buffer.size() / 2;
if (oldCounter >= 0)
printWithTime("RESETTING " + oldCounter + " => " + counter + " (delta=" + (counter - oldCounter) + ")");
data = buffer.get(counter);
}
++counter;
return true;
}
} finally {
_close(__31);
}
}
public java.nio.ByteBuffer provide20MsAudio() {
inc(provideCalls);
inc(dataSent, l(data));
java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(data);
return buf;
}
public boolean isOpus() {
return true;
}
}
public String startPlaying(Guild guild) {
AudioManager am = guild.getAudioManager();
sendHandler = new MyAudioSendHandler();
am.setSendingHandler(sendHandler);
return "Playing radio in channel " + quote(voiceChannelName);
}
public String selectAVoiceChannel(Guild guild, Member member) {
print("selectAVoiceChannel member=" + member);
if (member != null) {
GuildVoiceState vs = member.getVoiceState();
VoiceChannel vc = vs.getChannel();
print("selectAVoiceChannel vc=" + vc);
if (vc != null) {
voiceChannelID = lastVoiceChannelID = vc.getIdLong();
{
change();
return null;
}
}
}
if (voiceChannelID != 0)
return null;
List allChannels = guild.getVoiceChannels();
List channels = filter(allChannels, c -> isJoinableVoiceChannel(guild, c));
if (empty(channels))
if (empty(allChannels))
return "Please create a voice channel.";
else
return "Sorry, I am not allowed to enter any of your voice channels. Maybe my invite link was wrong?";
if (lastVoiceChannelID != 0 && !hasWhereMethodReturns("getIdLong", channels, lastVoiceChannelID)) {
lastVoiceChannelID = 0;
change();
}
voiceChannelID = lastVoiceChannelID != 0 ? lastVoiceChannelID : first(channels).getIdLong();
change();
return null;
}
public String action_play(Guild guild, Member member) {
if (shouldBePlaying && sendHandler != null)
return "I am playing already!";
{
String __25 = selectAVoiceChannel(guild, member);
if (!empty(__25))
return __25;
}
joinVoiceChannel(guild);
shouldBePlaying = true;
change();
return startPlaying(guild);
}
public String action_stop(Guild guild) {
if (shouldBePlaying) {
shouldBePlaying = false;
change();
return "OK, radio switched off";
}
return "I am stopped, I think. No?";
}
public String action_leave(Guild guild) {
voiceChannelID = 0;
change();
this.vc = null;
GuildVoiceState state = getSelfMember(guild).getVoiceState();
VoiceChannel vc = state.getChannel();
if (vc == null)
return "I don't think I am in any voice channel";
guild.getAudioManager().closeAudioConnection();
return "OK, leaving channel " + quote(vc.getName());
}
public String action_join(Guild guild, Member member) {
GuildVoiceState state = getSelfMember(guild).getVoiceState();
VoiceChannel vc = state.getChannel();
{
String __26 = selectAVoiceChannel(guild, member);
if (!empty(__26))
return __26;
}
joinVoiceChannel(guild);
return "OK, joined voice channel " + quote(voiceChannelName);
}
public String action_selectChannel(Guild guild, int i) {
List channels = guild.getVoiceChannels();
channels = filter(channels, c -> isJoinableVoiceChannel(guild, c));
VoiceChannel vc = _get(channels, i - 1);
if (vc == null)
return "Sorry, I count only " + nChannels(channels);
voiceChannelID = lastVoiceChannelID = vc.getIdLong();
change();
joinVoiceChannel(guild);
return "OK, joined voice channel " + quote(voiceChannelName);
}
public String renderChannelListIfNotOne(Guild guild) {
if (guild == null)
return "";
List channels = guild.getVoiceChannels();
channels = filter(channels, c -> isJoinableVoiceChannel(guild, c));
if (empty(channels))
return "\nNote: You don't have any voice channels.";
if (l(channels) == 1)
return "";
List out = new ArrayList();
for (int i = 0; i < l(channels); i++) out.add("`@me join channel " + (i + 1) + "` - join channel " + quote(channels.get(i).getName()));
return "\n" + lines_rtrim(out);
}
public boolean isJoinableVoiceChannel(Guild guild, VoiceChannel vc) {
if (vc == null || guild == null)
return false;
try {
return guild.getSelfMember().hasPermission(vc, Permission.VOICE_CONNECT);
} catch (Throwable e) {
printStackTrace(e);
return false;
}
}
public void restart(Guild guild) {
if (guild == null)
return;
if (shouldBePlaying) {
print("RESTARTING RADIO in " + guild);
print(action_play(guild, null));
} else if (voiceChannelID != 0) {
print("Rejoining voice channel in " + guild);
print(action_join(guild, null));
}
}
public void postSong() {
if (songChannelID == 0)
return;
postInChannel(songChannelID, npMsg.replace("", backtickQuote(currentSong)));
if (isWebURL(coverArtURL)) {
String imageURL = appendQueryToURL(coverArtURL, "rand", randomInt());
if (uploadImagesAsFiles)
uploadFileInChannel(songChannelID, loadBinaryPage(imageURL), "cover-art.jpg", "", null);
else
postImage(getChannel(songChannelID), imageURL, "");
}
}
public void handleUserJoined(long userID, VoiceChannel joined) {
if (joined != null && joined.getIdLong() == voiceChannelID) {
usersInVoiceChannel.add(userID);
print(guildID + " adding user to voice channel: " + userID + " (n=" + l(usersInVoiceChannel));
}
}
public void handleVoiceUpdateEvent(GenericGuildVoiceEvent e) {
User user = ((GenericGuildVoiceEvent) e).getMember().getUser();
if (user.isBot())
return;
long userID = user.getIdLong();
if (e instanceof GuildVoiceUpdateEvent) {
VoiceChannel left = ((GuildVoiceUpdateEvent) e).getChannelLeft();
if (((GuildVoiceUpdateEvent) e).getChannelLeft().getIdLong() == voiceChannelID) {
usersInVoiceChannel.remove(userID);
print(guildID + " removed user from voice channel: " + userID + " (n=" + l(usersInVoiceChannel));
}
}
if (e instanceof GuildVoiceMoveEvent)
handleUserJoined(userID, ((GuildVoiceMoveEvent) e).getChannelJoined());
if (e instanceof GuildVoiceJoinEvent)
handleUserJoined(userID, ((GuildVoiceJoinEvent) e).getChannelJoined());
}
}
public String dmOwners(String msg) {
List guilds = discord.getGuilds();
int n = 0;
for (Guild guild : guilds) {
try {
ByServer bs = getByServer(guild.getIdLong(), true);
if (bs != null && bs.shouldBePlaying) {
gazelle_dmGuildOwner(guild, msg);
++n;
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
return n2(n, "guild owner") + " contacted.";
}
public void loadTrack() {
if (!isURL(radioURL))
return;
lavaPlayer_loadItem(module(), lavaPlayer_playerManager(), player, radioURL.replace("", str(randomInt())));
}
public String currentSong() {
AutoCloseable __32 = tempSetTL(loadPage_sizeLimit, 128 * 1024L);
try {
if (l(currentSongURL) <= 1)
return "";
if (cic(currentSongURL, "autopo.st/"))
return trackTitleFromAutoPostWidget(loadPageWithTimeout(currentSongURL, 10.0));
if (cic(currentSongURL, "caster.fm/"))
return (String) mapGet(jsonDecodeMap(loadPageWithHeaders(currentSongURL, "X-Requested-With", "XMLHttpRequest")), "playing");
if (endsWith(currentSongURL, "status.xsl"))
return trackTitleFromIceCastStatusXSL(loadPageWithTimeout(currentSongURL, 10.0));
return loadPageWithTimeout(currentSongURL, 10.0);
} finally {
_close(__32);
}
}
public void grabSong() {
AutoCloseable __33 = enter();
try {
if (discord == null)
return;
String song = currentSong();
boolean post = nempty(currentSong) && nempty(song) && neq(currentSong, song);
currentSong = song;
if (post)
postSong_allServers();
if (putSongInStatus) {
String s = currentSong;
if (elapsedSeconds(lastActualFrameReceived) >= considerDownInterval && elapsedSeconds(moduleStarted) >= considerDownInterval)
s = "Stream currently down";
if (nempty(s))
gazelle_discord_playingGame(s);
}
} finally {
_close(__33);
}
}
public void postSong_allServers() {
List guilds = discord.getGuilds();
for (Guild guild : guilds) {
try {
ByServer bs = getByServer(guild);
if (bs != null)
bs.postSong();
} catch (Throwable __e) {
printStackTrace(__e);
}
}
}
public void updateVoiceChannelCount_allServers() {
if (discord == null)
return;
for (ByServer bs : cloneValues(dataByServer)) bs.updateVoiceChannelCount();
}
public int listeningUsers() {
int n = 0;
for (Guild guild : discord.getGuilds()) {
ByServer bs = getByServer(guild.getIdLong(), true);
if (bs != null && bs.shouldBePlaying)
n += l(bs.usersInVoiceChannel);
}
return n;
}
public String listeningUsers_full() {
List out = new ArrayList();
for (Guild guild : discord.getGuilds()) {
ByServer bs = getByServer(guild.getIdLong(), true);
if (bs != null && bs.shouldBePlaying) {
List users = cloneList(bs.usersInVoiceChannel);
if (empty(users))
continue;
out.add(guild.getName() + ": playing to " + joinWithComma(map(users, id -> or2(discord_memberIDToEffectiveName(guild, id), str(id)))));
}
}
return lines(out);
}
}
static public boolean _moduleClass_MKLabFM = true;
static public String programID;
static public void _onLoad_initUtils() {
utils.__javax = javax();
}
static public void _onLoad_defaultClassFinder() {
setDefaultClassFinder(new F1() {
public Class get(String name) {
Class c = findClass_fullName(name);
if (c != null)
return c;
if (name.startsWith("main$"))
return loadableUtils.utils.findClass_fullName("loadableUtils.utils" + name.substring(4));
return null;
}
});
}
static public ThreadLocal dynamicObjectIsLoading_threadLocal() {
return DynamicObject_loading;
}
static volatile public Concepts mainConcepts;
static public Concepts db_mainConcepts() {
if (mainConcepts == null)
mainConcepts = newConceptsWithClassFinder(getDBProgramID());
return mainConcepts;
}
static public void cleanMeUp_concepts() {
if (db_mainConcepts() != null)
db_mainConcepts().cleanMeUp();
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public String shortClassName_dropNumberPrefix(Object o) {
return dropNumberPrefix(shortClassName(o));
}
static public boolean eq(Object a, Object b) {
return a == b || a != null && b != null && a.equals(b);
}
static public boolean eq(Symbol a, String b) {
return eq(str(a), b);
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
static public void mapPut(Map map, Pair p) {
if (map != null && p != null)
map.put(p.a, p.b);
}
static public A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
static public void change() {
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF1 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF1 () {
public void get(final A a) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final IVF1 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF1 () {
public void get(final A a) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final IVF2 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF2 () {
public void get(A a, B b) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a, b);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a, b);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final IVF3 onMessage) {
DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF3 () {
public void get(A a, B b, C c) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a, b, c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a, b, c);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a, b, c);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF2 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF2 () {
public void get(final A a, final B b) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a, b);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a, b);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF3 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF3 () {
public void get(final A a, final B b, final C c) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a, b, c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a, b, c);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a, b, c);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final Runnable onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF1 () {
public void get(final A a) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage);";
}
});
}
static volatile public StringBuffer local_log = new StringBuffer();
static public boolean printAlsoToSystemOut = true;
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print(combinePrintParameters(s, o));
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = o + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
try {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
} catch (Throwable e) {
System.out.println(getStackTrace(e));
}
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
if (printAlsoToSystemOut)
System.out.print(s);
vmBus_send("printed", mc(), s);
}
static public void print_autoRotate() {
}
static public long getLong(Object o, String field) {
return toLong(getOpt(o, field));
}
static public long getLong(String field, Object o) {
return getLong(o, field);
}
static public List synchroList() {
return synchroList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public long longPar(String name, Object... params) {
return toLong(optPar(name, params));
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(Iterable c) {
return c == null || !c.iterator().hasNext();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(BitSet bs) {
return bs == null || bs.isEmpty();
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(double[] a) {
return a == null || a.length == 0;
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(MultiSet ms) {
return ms == null || ms.isEmpty();
}
static public boolean empty(MultiMap mm) {
return mm == null || mm.isEmpty();
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public boolean empty(Rect r) {
return !(r != null && r.w != 0 && r.h != 0);
}
static public A or(A a, A b) {
return a != null ? a : b;
}
static public String dropPrefixICTrim_orNull(String prefix, String s) {
return swic(s, prefix) ? trim(s.substring(l(prefix))) : null;
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\t')
out.append("\\t");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public String sfu(Object o) {
return structureForUser(o);
}
static public String replace_multi(String s, Collection a, String b) {
if (s == null || empty(a) || b == null)
return s;
for (String aa : a) s = s.replace(aa, b);
return s;
}
static public String replace_multi(String s, String... replacements) {
if (empty(s) || empty(replacements))
return s;
for (int i = 0; i + 1 < l(replacements); i += 2) s = s.replace(replacements[i], replacements[i + 1]);
return s;
}
static public String dropPunctuation3_withAGIBlue(boolean useAGIBlue, String s) {
return useAGIBlue ? dropPunctuation3_withAGIBlue(s) : dropPunctuation3(s);
}
static public String dropPunctuation3_withAGIBlue(String s) {
if (!agiBlue_validPageName(s))
return dropPunctuation3(s);
String y = dropPunctuation3_cache.get(s);
if (y != null)
return y;
{
String __1 = agiBlue_lookupInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation");
if (!empty(__1))
return __1;
}
y = dropPunctuation3(s);
agiBlue_postInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation", y);
return y;
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public String simpleSpaces_noTok(String s) {
return s == null ? null : s.replaceAll("\\s+", " ");
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static public List replace(A a, A b, List l) {
return replace(l, a, b);
}
static public String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static public String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
vmBus_send("locking", lock, "thread", currentThread());
lock.lockInterruptibly();
vmBus_send("locked", lock, "thread", currentThread());
} catch (InterruptedException e) {
Object reason = vm_threadInterruptionReasonsMap().get(currentThread());
print("Locking interrupted! Reason: " + strOr(reason, "Unknown"));
printStackTrace(e);
rethrow(e);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
static public String nextGenBotsDiscordInvite() {
return "https://discord.gg/kcKKZEg";
}
static public String snippetLink(String id) {
return empty(id) ? id : snippetLink(parseSnippetID(id));
}
static public String snippetLink(long id) {
return "https://code.botcompany.de/" + id;
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public boolean swic_trim(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { trim(substring(a, l(b))) };
return true;
}
static public boolean setAdd(Collection c, A a) {
if (c == null || c.contains(a))
return false;
c.add(a);
return true;
}
static public long parseFirstLong(String s) {
return parseLong(jextract("", s));
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(AtomicLong l) {
return n2(l.get());
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(Map map) {
return n2(l(map));
}
static public String n2(double l, String singular) {
return empty(singular) ? str(l) : n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return empty(singular) ? n2(l) : n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(long[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public String n2(MultiSet ms, String singular, String plural) {
return n_fancy2(ms, singular, plural);
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(Symbol a, Symbol b) {
return eq(a, b);
}
static public boolean eqic(Symbol a, String b) {
return eqic(asString(a), b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public String linesLL(Object... x) {
return lines(ll(x));
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public B remove(Map map, Object a) {
return map == null ? null : map.remove(a);
}
static public void remove(BitSet bs, int i) {
bs.clear(i);
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
print("Unlocked: " + msg);
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
vmBus_send("unlocked", lock, "thread", currentThread());
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(Object... c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(callF(f, o));
}
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) {
ping();
x.add(f.get(o));
}
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
ping();
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public List map(IF1 f, A data1, A... moreData) {
List x = emptyList(l(moreData) + 1);
x.add(f.get(data1));
if (moreData != null)
for (A o : moreData) {
ping();
x.add(f.get(o));
}
return x;
}
static public String discordAtPlusID(long userID) {
return userID == 0 ? "unknown person" : "<@" + userID + "> (" + userID + ")";
}
static public String lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public String lines(Iterable l, IF1 f) {
return mapToLines(l, f);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Iterable it, Object a) {
if (it != null)
for (Object o : it) if (eq(a, o))
return true;
return false;
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public String structure_nullingInstancesOfClass(Class c, Object o) {
if (c == null)
return structure(o);
structure_Data data = new structure_Data();
structure_ClassInfo info = new structure_ClassInfo();
info.special = info.nullInstances = true;
data.infoByClass.put(c, info);
return structure(o, data);
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return classLoaderForObject(realm).loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public String appendSpaceIfEndsWithLetter(String s) {
return endsWithLetter(s) ? s + " " : s;
}
static public boolean containsDiscordToken(String s) {
return regexpFind(discordTokenRegexp(), s);
}
static public String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
static public String jda_selfUserName(JDA jda) {
return jda_selfUser(jda).getName();
}
static public String ymd_minus_hms() {
return ymd() + "-" + hms();
}
static public File programFile(String name) {
return prepareProgramFile(name);
}
static public File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static public File createZipFileWithSingleTextFile(File zipFile, String name, String text) {
ZipOutputStream outZip = newZipOutputStream(zipFile);
try {
zip_addTextFile(outZip, name, text);
return zipFile;
} finally {
_close(outZip);
}
}
static public NotTooOften onlyEveryHour() {
return new NotTooOften(hoursToMS(1));
}
static public Set> _entrySet(Map map) {
return map == null ? Collections.EMPTY_SET : map.entrySet();
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public List cloneMap(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : cloneList(l)) x.add(f.get(o));
return x;
}
static public A printStackTrace(A e) {
if (e != null)
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public long nextGenBotsTestRoomID() {
return 635940070305824794L;
}
static public String _computerID;
static public 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) {
_computerID = loadTextFile(userDir(".tinybrain/computer-id"));
if (_computerID == null)
_computerID = makeRandomID(12, new SecureRandom());
saveTextFile(file, _computerID);
}
} finally {
unlock(__0);
}
}
return _computerID;
}
static public String dm_moduleID(Object module) {
return strOrNull(getOpt(dm_getStem(module), "id"));
}
static public String dm_moduleID() {
return dm_moduleID(dm_current_mandatory_generic());
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public FixedRateTimer doEveryAndNow(int delay, Object r) {
return doEveryStartingNow(delay, r);
}
static public FixedRateTimer doEveryAndNow(double delay, Object r) {
return doEveryStartingNow(toInt(toMS(delay)), r);
}
static public FixedRateTimer doEvery(long delay, final Object r) {
return doEvery(delay, delay, r);
}
static public FixedRateTimer doEvery(long delay, long firstDelay, final Object r) {
FixedRateTimer timer = new FixedRateTimer(shorten(programID() + ": " + r, 80));
timer.scheduleAtFixedRate(smartTimerTask(r, timer, toInt(delay)), toInt(firstDelay), toInt(delay));
return vmBus_timerStarted(timer);
}
static public FixedRateTimer doEvery(double initialSeconds, double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), toMS(initialSeconds), r);
}
static public FixedRateTimer doEvery(double delaySeconds, final Object r) {
return doEvery(toMS(delaySeconds), r);
}
static public int iround(double d) {
return (int) Math.round(d);
}
static public int iround(Number n) {
return iround(toDouble(n));
}
static public AudioPlayer lavaPlayer_createPlayer() {
return vm_registerClassInstance(AudioPlayer.class, lavaPlayer_playerManager().createPlayer());
}
static public void lavaPlayer_printPlayerEvents(AudioPlayer player) {
DynModule mod = dm_current_mandatory();
player.addListener(e -> {
AutoCloseable __1 = dm_enter(mod);
try {
print("Audio event: " + e);
if (e instanceof TrackExceptionEvent)
printStackTrace(((TrackExceptionEvent) e).exception);
} finally {
_close(__1);
}
});
}
static public int inc(AtomicInteger i) {
return incAtomicInt(i);
}
static public int inc(AtomicInteger i, int delta) {
return incAtomicInt(i, delta);
}
static public long inc(AtomicLong l) {
return incAtomicLong(l);
}
static public long inc(AtomicLong l, long b) {
return l.addAndGet(b);
}
static public int inc(IntVar v) {
synchronized (v) {
int val = v.get() + 1;
v.set(val);
return val;
}
}
static public long sysNow() {
ping();
return System.nanoTime() / 1000000;
}
static public double elapsedSeconds(long time) {
return toSeconds(sysNow() - time);
}
static public double elapsedSeconds(Timestamp ts) {
return ts == null ? Double.NaN : toSeconds(now() - ts.date);
}
static public Set synchroSet() {
return synchroHashSet();
}
static public Set synchroSet(Set set) {
return Collections.synchronizedSet(set);
}
static public boolean cic(Collection l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(Collection l, Symbol s) {
return contains(l, s);
}
static public boolean cic(String[] l, String s) {
return containsIgnoreCase(l, s);
}
static public boolean cic(String s, char c) {
return containsIgnoreCase(s, c);
}
static public boolean cic(String a, String b) {
return containsIgnoreCase(a, b);
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public int discordEmbed_addField_maxLength = 800;
static public void discordEmbed_addField(EmbedBuilder eb, String field, String text) {
int n = 1;
while (l(text) > discordEmbed_addField_maxLength) {
ping();
List lines = lines(text);
StringBuilder buf = new StringBuilder();
int i = 0;
while (i < l(lines) && l(buf) + l(lines.get(i)) + 1 <= discordEmbed_addField_maxLength) buf.append(lines.get(i++)).append("\n");
String part = str(buf);
if (i == 0) {
part = takeFirst(text, discordEmbed_addField_maxLength);
text = substring(text, discordEmbed_addField_maxLength);
} else
text = lines(subList(lines, i));
eb.addField(appendNumberUnless1(field, n++), part, false);
}
if (!emptyAfterTrim(text))
eb.addField(appendNumberUnless1(field, n), text, false);
}
public static String rtrim(String s) {
if (s == null)
return null;
int i = s.length();
while (i > 0 && " \t\r\n".indexOf(s.charAt(i - 1)) >= 0) --i;
return i < s.length() ? s.substring(0, i) : s;
}
static public String backtickQuote(String s) {
return encloseInBackticks(s);
}
static public String imageSnippetURL(long snippetID) {
return snippetImageURL(snippetID);
}
static public String imageSnippetURL(String snippetID) {
return snippetImageURL(snippetID);
}
static public String imageSnippetURL(String snippetID, String contentType) {
return snippetImageURL(snippetID, contentType);
}
static public java.util.Timer doAfter(long delay, Object r) {
return doLater(delay, r);
}
static public java.util.Timer doAfter(double delaySeconds, Object r) {
return doLater(delaySeconds, r);
}
static public void dm_reload() {
dm_reloadMe();
}
static public boolean isWebURL(String s) {
return startsWithOneOf(s, "http://", "https://");
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public boolean matchX2(String pat, String s) {
return matchX_vbar(pat, s);
}
static public boolean matchX2(String pat, String s, Matches matches) {
return matchX_vbar(pat, s, matches);
}
static public 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 public int parseInt(String s) {
return emptyString(s) ? 0 : Integer.parseInt(s);
}
static public int parseInt(char c) {
return Integer.parseInt(str(c));
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(BitSet bs) {
return !empty(bs);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(MultiMap mm) {
return mm != null && !mm.isEmpty();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public boolean nempty(Rect r) {
return r != null && r.w != 0 && r.h != 0;
}
static public boolean nempty(MultiSet ms) {
return ms != null && !ms.isEmpty();
}
static public String nRadios(long n) {
return n2(n, "radio");
}
static public String nRadios(Collection l) {
return nRadios(l(l));
}
static public void replaceCollection(Collection dest, Collection src) {
if (dest == src)
return;
dest.clear();
if (src != null)
dest.addAll(src);
}
static public List mapNonNulls_pcall(Iterable l, Object f) {
return map_pcall_notNull(l, f);
}
static public List mapNonNulls_pcall(Object f, Iterable l) {
return map_pcall_notNull(f, l);
}
static public List mapNonNulls_pcall(IF1 f, Iterable l) {
return map_pcall_notNull(f, l);
}
static public List mapNonNulls_pcall(Iterable l, IF1 f) {
return map_pcall_notNull(l, f);
}
static public A printWithTime(A a) {
return printWithTime("", a);
}
static public A printWithTime(String s, A a) {
print(hmsWithColons() + ": " + s, a);
return a;
}
static public List filter(Iterable c, Object pred) {
if (pred instanceof F1)
return filter(c, (F1 ) pred);
List x = new ArrayList();
if (c != null)
for (Object o : c) if (isTrue(callF(pred, o)))
x.add(o);
return x;
}
static public List filter(Object pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, F1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(F1 pred, Iterable c) {
return filter(c, pred);
}
static public List filter(Iterable c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(B[] c, IF1 pred) {
List x = new ArrayList();
if (c != null)
for (B o : c) if (pred.get(o))
x.add(o);
return x;
}
static public List filter(IF1 pred, Iterable c) {
return filter(c, pred);
}
static public boolean hasWhereMethodReturns(String methodName, Iterable l, Object result) {
return firstWhereMethodReturns(methodName, l, result) != null;
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public Pair first(Map map) {
return mapEntryToPair(first(entrySet(map)));
}
static public Pair first(MultiMap mm) {
if (mm == null)
return null;
var e = first(mm.data.entrySet());
if (e == null)
return null;
return pair(e.getKey(), first(e.getValue()));
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public Character first(CharSequence s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public Byte first(byte[] l) {
return empty(l) ? null : l[0];
}
static public A first(A[] l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(Iterable l, IF1 pred) {
return firstThat(l, pred);
}
static public A first(IF1 pred, Iterable l) {
return firstThat(pred, l);
}
static public A _get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static public Object _get(Object o, String field) {
return get(o, field);
}
static public Object _get(String field, Object o) {
return get(o, field);
}
static public A _get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static public String nChannels(long n) {
return n2(n, "channel");
}
static public String nChannels(Collection l) {
return nChannels(l(l));
}
static public String lines_rtrim(Collection lines) {
return rtrim_fromLines(lines);
}
static public 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 public String appendQueryToURL(String url, Object... data) {
return appendQueryToURL(url, paramsToMap(data));
}
static public int randomInt() {
return randomInt(null);
}
static public int randomInt(Random random) {
return getRandomizer(random).nextInt();
}
static public int randomInt(int n) {
return randomInt(null, n);
}
static public int randomInt(Random random, int n) {
return random(random, n);
}
static public ThreadLocal>> loadBinaryPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadBinaryPage_extraHeaders = new ThreadLocal();
static public byte[] loadBinaryPage(String url) {
try {
print("Loading " + url);
return loadBinaryPage(loadPage_openConnection(new URL(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 public byte[] loadBinaryPage_noHeaders(URLConnection con) {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
InputStream inputStream = con.getInputStream();
loadBinaryPage_responseHeaders.set(con.getHeaderFields());
long len = 0;
try {
len = con.getContentLength();
} catch (Throwable e) {
printStackTrace(e);
}
int n = 0;
while (true) {
int ch = inputStream.read();
if (ch < 0)
break;
buf.write(ch);
if (++n % 100000 == 0)
println(" " + n + (len != 0 ? "/" + len : "") + " bytes loaded.");
}
inputStream.close();
return buf.toByteArray();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String getChannel() {
return getChannelName();
}
static public void gazelle_dmGuildOwner(Object guild, String msg) {
dm_callMe("sendPM", rcall("getIdLong", rcall("getUser", rcall("getOwner", guild))), msg);
}
static public boolean isURL(String s) {
return startsWithOneOf(s, "http://", "https://", "file:");
}
static public void lavaPlayer_loadItem(DynModule mod, AudioPlayerManager playerManager, AudioPlayer player, String trackID) {
playerManager.loadItem(print("Loading track: ", trackID), new AudioLoadResultHandler() {
public void trackLoaded(AudioTrack track) {
AutoCloseable __1 = dm_enter(mod);
try {
player.startTrack(track, false);
print("Started track " + track);
} finally {
_close(__1);
}
}
public void playlistLoaded(AudioPlaylist playlist) {
AutoCloseable __2 = dm_enter(mod);
try {
print("Ignoring play list");
} finally {
_close(__2);
}
}
public void noMatches() {
AutoCloseable __3 = dm_enter(mod);
try {
print("Track " + trackID + ": no matches");
} finally {
_close(__3);
}
}
public void loadFailed(FriendlyException e) {
AutoCloseable __4 = dm_enter(mod);
try {
print("Track " + trackID + " load failed: " + e);
printStackTrace(e);
} finally {
_close(__4);
}
}
});
}
static public AudioPlayerManager lavaPlayer_playerManager;
static public void cleanMeUp_lavaPlayer_playerManager() {
if (lavaPlayer_playerManager != null) {
try {
lavaPlayer_playerManager.shutdown();
} catch (Throwable __e) {
printStackTrace(__e);
}
}
lavaPlayer_playerManager = null;
}
static public AudioPlayerManager lavaPlayer_playerManager() {
if (lavaPlayer_playerManager == null) {
DefaultAudioPlayerManager playerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerLocalSource(playerManager);
AudioSourceManagers.registerRemoteSources(playerManager);
lavaPlayer_playerManager = playerManager;
}
return lavaPlayer_playerManager;
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static public String trackTitleFromAutoPostWidget(String html) {
for (String img : findTagsWithParams("img", html)) {
String title = tagParam(img, "title");
if (empty(title))
continue;
String s = dropPrefixTrimIC_orNull("listen to ", title);
if (s == null)
continue;
int idx = lastIndexOfIC(s, " on ");
if (idx < 0)
continue;
s = trim(takeFirst(s, idx));
return s;
}
return null;
}
static public String loadPageWithTimeout(long timeout, String url) {
return loadPageWithTimeout(url, timeout);
}
static public String loadPageWithTimeout(String url, long timeout) {
try {
ping();
url = loadPage_preprocess(url);
print("Loading with timeout: " + hideCredentials(url));
URL _url = new URL(url);
return loadPage(setURLConnectionTimeouts(_url.openConnection(), timeout), _url);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPageWithTimeout(String url, double timeoutSeconds) {
return loadPageWithTimeout(url, toMS(timeoutSeconds));
}
static public String loadPageWithTimeout(double timeoutSeconds, String url) {
return loadPageWithTimeout(url, timeoutSeconds);
}
static public B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static public B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static public Map jsonDecodeMap(String s) {
Object o = jsonDecode(s);
if (o instanceof List && empty((List) o))
return new HashMap();
if (o instanceof Map)
return (Map) o;
else
throw fail("Not a JSON map: " + s);
}
static public String loadPageWithHeaders(String url, String... headers) {
loadPage_extraHeaders.set(litmap(headers));
return loadPage(url);
}
static public String loadPageWithHeaders(String url, Map headers) {
loadPage_extraHeaders.set(headers);
return loadPage(url);
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public 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 public String trackTitleFromIceCastStatusXSL(String html) {
List> tds = findContainerTagWithParams(html, "td");
for (int i = 0; i < l(tds); i++) if (eqic(trim(joinContentsOfContainerTag(tds.get(i))), "current song:"))
return trim(joinContentsOfContainerTag(tds.get(i + 1)));
return null;
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public void gazelle_discord_playingGame(String gameName) {
Object presence = gazelle_discordPresence();
Object game = call(getClass_vmName(gazelle_jda(), "net.dv8tion.jda.core.entities.Game"), "playing", gameName);
if (game != null)
call(presence, "setGame", game);
else {
Object activity = call(getClass_vmName(gazelle_jda(), "net.dv8tion.jda.api.entities.Activity"), "playing", gameName);
call(presence, "setActivity", activity);
}
}
static public List cloneValues(Map map) {
return cloneList(values(map));
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public String discord_memberIDToEffectiveName(Guild guild, long userID) {
Member member = guild.getMemberById(userID);
return member == null ? null : member.getEffectiveName();
}
static public Class javax() {
return getJavaX();
}
static public void setDefaultClassFinder(Object cf) {
_defaultClassFinder_value = cf;
}
static public HashMap findClass_fullName_cache = new HashMap();
static public Class findClass_fullName(String name) {
synchronized (findClass_fullName_cache) {
if (findClass_fullName_cache.containsKey(name))
return findClass_fullName_cache.get(name);
Class c;
try {
c = Class.forName(name);
} catch (ClassNotFoundException e) {
c = null;
}
findClass_fullName_cache.put(name, c);
return c;
}
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Object _defaultClassFinder_value = defaultDefaultClassFinder();
static public Object _defaultClassFinder() {
return _defaultClassFinder_value;
}
static public Concepts newConceptsWithClassFinder(String progID) {
Concepts cc = new Concepts(progID);
cc.classFinder = _defaultClassFinder();
return cc;
}
static public String getDBProgramID_id;
static public String getDBProgramID() {
return nempty(getDBProgramID_id) ? getDBProgramID_id : programIDWithCase();
}
static public String dropNumberPrefix(String s) {
return dropFirst(s, indexOfNonDigit(s));
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public A setAll(A o, Map fields) {
if (fields == null)
return o;
for (String field : keys(fields)) set(o, field, fields.get(field));
return o;
}
static public A setAll(A o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
return o;
}
static public Object getOptMC(String field) {
return getOpt(mc(), field);
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final IVF1 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, ivf1ToVF1(onMessage)));
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final IVF2 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, ivf2ToVF2(onMessage)));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, final VF3 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
return x30_util.callF(f, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callMC(String method, Object... args) {
return call(mc(), method, args);
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public String combinePrintParameters(String s, Object o) {
return (endsWithLetterOrDigit(s) ? s + ": " : s) + o;
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public String getStackTrace(String msg) {
return getStackTrace_noRecord(new Throwable(msg));
}
static public String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll_minimalExceptionHandling(vm_busListeners_live(), msg, arg);
pcallFAll_minimalExceptionHandling(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public Class mc() {
return main.class;
}
static public long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
static public Map synchroHashMap() {
return synchronizedMap(new HashMap());
}
static public RuntimeException fail() {
throw new RuntimeException("fail");
}
static public RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static public RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static public RuntimeException fail(Object... objects) {
throw new Fail(objects);
}
static public RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public String structureForUser(Object o) {
return beautifyStructure(struct_noStringSharing(o));
}
static public List dropPunctuation3_keep = ll("*", "<", ">");
static public Map dropPunctuation3_cache = defaultSizeMRUCache();
static public List dropPunctuation3(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation3_keep.contains(t)) {
tok.set(i - 1, or2(tok.get(i - 1) + tok.get(i + 1), " "));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
static public String dropPunctuation3(String s) {
return getOrCreate_f0(dropPunctuation3_cache, s, () -> join(dropPunctuation3(javaTokNoQuotes(s))));
}
static public boolean agiBlue_validPageName(String s) {
s = trim(s);
return nempty(s) && !containsNewLine(s);
}
static public String agiBlue_lookupInSlice_pcall(String sliceID, String q, String... keys) {
try {
return agiBlue_lookupInSlice(sliceID, q, keys);
} catch (Throwable __e) {
return null;
}
}
static public String agiBlue_postInSlice_pcall(String slice, String a, String b, String c) {
try {
return agiBlue_postInSlice(slice, a, b, c);
} catch (Throwable __e) {
return null;
}
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
newPing();
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Thread currentThread() {
return Thread.currentThread();
}
static public Map vm_threadInterruptionReasonsMap() {
return vm_generalWeakSubMap("Thread interruption reasons");
}
static public String strOr(Object o, String ifNull) {
return o == null ? ifNull : str(o);
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
vmBus_send("locking", lock, "thread", currentThread());
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
vmBus_send("locked", lock, "thread", currentThread());
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
int n = s.length();
if (y < x)
y = x;
if (y > n)
y = n;
if (x >= y)
return "";
return s.substring(x, y);
}
static public String substring(String s, CharSequence l) {
return substring(s, lCharSequence(l));
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static public 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 public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public String n_fancy2(MultiSet ms, String singular, String plural) {
return n_fancy2(l(ms), singular, plural);
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first((Collection) strings));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
public static String join(String glue, Object... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(long[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (long i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(double[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (double i : a) l.add(i);
return l;
}
static public ArrayList asList(short[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (short i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterator it) {
ArrayList l = new ArrayList();
if (it != null)
while (it.hasNext()) l.add(it.next());
return l;
}
static public ArrayList asList(IterableIterator s) {
return asList((Iterator) s);
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public List asList(Pair p) {
return p == null ? null : ll(p.a, p.b);
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
int n = s.length();
for (int i = start; i < n; i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public List mapToLines(Map map) {
List l = new ArrayList();
for (Object key : keys(map)) l.add(str(key) + " = " + str(map.get(key)));
return l;
}
static public String mapToLines(Map map, Object f) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Map map) {
return lines(map(map, f));
}
static public String mapToLines(Object f, Iterable l) {
return lines(map(f, l));
}
static public String mapToLines(Iterable l, IF1 f) {
return mapToLines((Object) f, l);
}
static public String mapToLines(IF1 f, Iterable l) {
return mapToLines((Object) f, l);
}
static public String mapToLines(Map map, IF2 f) {
return lines(map(map, f));
}
static public String mapToLines(IF1 f, A data1, A... moreData) {
return lines(map(f, data1, moreData));
}
static public A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static public A optParam(ThreadLocal tl) {
return optPar(tl);
}
static public Object optParam(String name, Map params) {
return mapGet(params, name);
}
static public A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static public Object optParam(String name, Object[] params) {
return optParam(params, name);
}
static public ClassLoader classLoaderForObject(Object o) {
if (o instanceof ClassLoader)
return ((ClassLoader) o);
if (o == null)
return null;
return _getClass(o).getClassLoader();
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public boolean endsWithLetter(String s) {
return nempty(s) && isLetter(last(s));
}
static public boolean regexpFind(String pat, String s) {
return regexpFinds(pat, s);
}
static public String discordTokenRegexp() {
return "[MN][A-Za-z\\d]{23}\\.[\\w-]{6}\\.[\\w-]{27}";
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public int[] unnull(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnull(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnull(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnull(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public int unnull(Integer i) {
return i == null ? 0 : i;
}
static public long unnull(Long l) {
return l == null ? 0L : l;
}
static public double unnull(Double l) {
return l == null ? 0.0 : l;
}
static public SelfUser jda_selfUser(JDA jda) {
return jda.getSelfUser();
}
static public String ymd() {
return ymd(now());
}
static public String ymd(long now) {
return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2);
}
static public String ymd(long now, TimeZone tz) {
return year(now, tz) + formatInt(month(now, tz), 2) + formatInt(dayOfMonth(now, tz), 2);
}
static public String hms() {
return hms(now());
}
static public String hms(long time) {
return new SimpleDateFormat("HHmmss").format(time);
}
static public File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static public File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static public ZipOutputStream newZipOutputStream(String path) {
return newZipOutputStream(new File(path));
}
static public ZipOutputStream newZipOutputStream(File zip) {
try {
return new ZipOutputStream(newFileOutputStream(zip));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void zip_addTextFile(ZipOutputStream outZip, String name, String text) {
try {
if (text == null)
return;
byte[] utf8 = toUtf8(text);
ZipEntry e = new ZipEntry(name);
e.setSize(l(utf8));
outZip.putNextEntry(e);
outZip.write(utf8, 0, l(utf8));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public long hoursToMS(double hours) {
return round(hours * 60 * 60 * 1000);
}
static public File computerIDFile() {
return javaxDataDir("Basic Info/computer-id.txt");
}
static public String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(File f, String defaultContents) {
return loadTextFile(f, defaultContents, "UTF-8");
}
static public 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 public String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
static public String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
static public File userDir() {
return new File(userHome());
}
static public File userDir(String path) {
return new File(userHome(), path);
}
static public String makeRandomID(int length) {
return makeRandomID(length, defaultRandomGenerator());
}
static public String makeRandomID(int length, Random random) {
char[] id = new char[length];
for (int i = 0; i < id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26));
return new String(id);
}
static public String makeRandomID(Random r, int length) {
return makeRandomID(length, r);
}
static public File saveTextFile(String fileName, String contents) throws IOException {
CriticalAction action = beginCriticalAction("Saving file " + fileName + " (" + l(contents) + " chars)");
try {
File file = new File(fileName);
mkdirsForFile(file);
String tempFileName = fileName + "_temp";
File tempFile = new File(tempFileName);
if (contents != null) {
if (tempFile.exists())
try {
String saveName = tempFileName + ".saved." + now();
copyFile(tempFile, new File(saveName));
} catch (Throwable e) {
printStackTrace(e);
}
FileOutputStream fileOutputStream = newFileOutputStream(tempFile.getPath());
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!tempFile.renameTo(file))
throw new IOException("Can't rename " + tempFile + " to " + file);
vmBus_send("wroteFile", file);
return file;
} finally {
action.done();
}
}
static public File saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
return fileName;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String strOrNull(Object o) {
return o == null ? null : str(o);
}
static public Object dm_getStem(Object moduleOrID) {
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
moduleOrID = dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_getStemByID(moduleOrID);
return or(getOpt(dm_getModule(moduleOrID), "_host"), moduleOrID);
}
static public FixedRateTimer doEveryStartingNow(int delay, Object r) {
return doEvery(delay, 0, r);
}
static public int toInt(Object o) {
if (o == null)
return 0;
if (o instanceof Number)
return ((Number) o).intValue();
if (o instanceof String)
return parseInt((String) o);
if (o instanceof Boolean)
return boolToInt((Boolean) o);
throw fail("woot not int: " + getClassName(o));
}
static public int toInt(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public long toMS(double seconds) {
return (long) (seconds * 1000);
}
static public int shorten_default = 100;
static public String shorten(CharSequence s) {
return shorten(s, shorten_default);
}
static public String shorten(CharSequence s, int max) {
return shorten(s, max, "...");
}
static public 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 public String shorten(int max, CharSequence s) {
return shorten(s, max);
}
static public TimerTask smartTimerTask(Object r, java.util.Timer timer, long delay) {
return new SmartTimerTask(r, timer, delay, _threadInfo());
}
static public class SmartTimerTask extends TimerTask implements IFieldsToList {
public Object r;
public java.util.Timer timer;
public long delay;
public Object threadInfo;
public SmartTimerTask() {
}
public SmartTimerTask(Object r, java.util.Timer timer, long delay, Object threadInfo) {
this.threadInfo = threadInfo;
this.delay = delay;
this.timer = timer;
this.r = r;
}
public String toString() {
return shortClassName_dropNumberPrefix(this) + "(" + r + ", " + timer + ", " + delay + ", " + threadInfo + ")";
}
public Object[] _fieldsToList() {
return new Object[] { r, timer, delay, threadInfo };
}
public long lastRun;
public void run() {
if (!licensed())
timer.cancel();
else {
_threadInheritInfo(threadInfo);
AutoCloseable __1 = tempActivity(r);
try {
lastRun = fixTimestamp(lastRun);
long now = now();
if (now >= lastRun + delay * 0.9) {
lastRun = now;
if (eq(false, pcallF(r)))
timer.cancel();
}
} finally {
_close(__1);
}
}
}
}
static public A vmBus_timerStarted(A timer) {
vmBus_send("timerStarted", timer, costCenter());
return timer;
}
static public double toDouble(Object o) {
if (o instanceof Number)
return ((Number) o).doubleValue();
if (o instanceof BigInteger)
return ((BigInteger) o).doubleValue();
if (o instanceof String)
return parseDouble((String) o);
if (o == null)
return 0.0;
throw fail(o);
}
static public B vm_registerClassInstance(Class c, B o) {
if (c != null && o != null)
vm_registeredInstancesSet(c).add(o);
return o;
}
static public AutoCloseable dm_enter(Object mod) {
return (AutoCloseable) callOpt(dm_getModule(mod), "enter");
}
static public int incAtomicInt(AtomicInteger i) {
return i.incrementAndGet();
}
static public int incAtomicInt(AtomicInteger i, int delta) {
return i.addAndGet(delta);
}
static public long incAtomicLong(AtomicLong l) {
return l.incrementAndGet();
}
static public double toSeconds(long ms) {
return ms / 1000.0;
}
static public String toSeconds(long ms, int digits) {
return formatDouble(toSeconds(ms), digits);
}
static public double toSeconds(double ms) {
return ms / 1000.0;
}
static public String toSeconds(double ms, int digits) {
return formatDouble(toSeconds(ms), digits);
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public Set synchroHashSet() {
return synchronizedSet(new HashSet ());
}
static public boolean containsIgnoreCase(Collection l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String[] l, String s) {
if (l != null)
for (String x : l) if (eqic(x, s))
return true;
return false;
}
static public boolean containsIgnoreCase(String s, char c) {
return indexOfIgnoreCase(s, String.valueOf(c)) >= 0;
}
static public boolean containsIgnoreCase(String a, String b) {
return indexOfIgnoreCase(a, b) >= 0;
}
static public List takeFirst(List l, int n) {
return l(l) <= n ? l : newSubListOrSame(l, 0, n);
}
static public List takeFirst(int n, List l) {
return takeFirst(l, n);
}
static public String takeFirst(int n, String s) {
return substring(s, 0, n);
}
static public String takeFirst(String s, int n) {
return substring(s, 0, n);
}
static public CharSequence takeFirst(int n, CharSequence s) {
return subCharSequence(s, 0, n);
}
static public List takeFirst(int n, Iterator it) {
if (it == null)
return null;
List l = new ArrayList();
for (int _repeat_0 = 0; _repeat_0 < n; _repeat_0++) {
if (it.hasNext())
l.add(it.next());
else
break;
}
return l;
}
static public List takeFirst(int n, Iterable i) {
if (i == null)
return null;
return i == null ? null : takeFirst(n, i.iterator());
}
static public List takeFirst(int n, IterableIterator i) {
return takeFirst(n, (Iterator ) i);
}
static public int[] takeFirst(int n, int[] a) {
return takeFirstOfIntArray(n, a);
}
static public short[] takeFirst(int n, short[] a) {
return takeFirstOfShortArray(n, a);
}
static public byte[] takeFirst(int n, byte[] a) {
return takeFirstOfByteArray(n, a);
}
static public byte[] takeFirst(byte[] a, int n) {
return takeFirstOfByteArray(n, a);
}
static public double[] takeFirst(int n, double[] a) {
return takeFirstOfDoubleArray(n, a);
}
static public double[] takeFirst(double[] a, int n) {
return takeFirstOfDoubleArray(n, a);
}
static public List subList(List l, int startIndex) {
return subList(l, startIndex, l(l));
}
static public List subList(int startIndex, List l) {
return subList(l, startIndex);
}
static public List subList(int startIndex, int endIndex, List l) {
return subList(l, startIndex, endIndex);
}
static public List subList(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = Math.max(0, startIndex);
endIndex = Math.min(n, endIndex);
if (startIndex > endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return l.subList(startIndex, endIndex);
}
static public String appendNumberUnless1(String s, int i) {
return i == 1 ? s : s + " " + i;
}
static public boolean emptyAfterTrim(String s) {
return empty(trim(s));
}
static public String encloseInBackticks(String s) {
return s == null ? null : "`" + s + "`";
}
static public String snippetImageURL(long snippetID) {
return snippetImageURL(fsI(snippetID));
}
static public String snippetImageURL(String snippetID) {
return snippetImageURL(snippetID, "png");
}
static public String snippetImageURL(String snippetID, String contentType) {
if (snippetID == null || isURL(snippetID))
return snippetID;
long id = parseSnippetID(snippetID);
String url;
if (isImageServerSnippet(id))
url = imageServerLink(id);
else
url = "https://botcompany.de/img/" + id;
return url;
}
static public java.util.Timer doLater(long delay, final Object r) {
ping();
final java.util.Timer timer = new java.util.Timer();
timer.schedule(timerTask(r, timer), delay);
return vmBus_timerStarted(timer);
}
static public java.util.Timer doLater(double delaySeconds, final Object r) {
return doLater(toMS(delaySeconds), r);
}
static public void dm_reloadMe() {
dm_reloadModule(dm_currentModule());
}
static public boolean startsWithOneOf(String s, String... l) {
for (String x : l) if (startsWith(s, x))
return true;
return false;
}
static public boolean startsWithOneOf(String s, Matches m, String... l) {
for (String x : l) if (startsWith(s, x, m))
return true;
return false;
}
static public boolean matchX_vbar(String pat, String s) {
return matchX_vbar(pat, s, null);
}
static public boolean matchX_vbar(String pat, String s, Matches matches) {
for (String pat2 : tok_splitAtVerticalBar(pat)) if (matchX(pat2, s, matches))
return true;
return false;
}
static public boolean emptyString(String s) {
return s == null || s.length() == 0;
}
static public List map_pcall_notNull(Iterable l, Object f) {
return map_pcall_notNull(f, l);
}
static public List map_pcall_notNull(Object f, Iterable l) {
List x = new ArrayList();
for (Object o : unnullForIteration(l)) {
try {
addIfNotNull(x, callF(f, o));
} catch (Throwable __e) {
printStackTrace(__e);
}
}
return x;
}
static public List map_pcall_notNull(IF1 f, Iterable l) {
List x = new ArrayList();
for (Object o : unnullForIteration(l)) {
try {
addIfNotNull(x, callF(f, o));
} catch (Throwable __e) {
printStackTrace(__e);
}
}
return x;
}
static public List map_pcall_notNull(Iterable l, IF1 f) {
return map_pcall_notNull(f, l);
}
static public String hmsWithColons() {
return hmsWithColons(now());
}
static public String hmsWithColons(long time) {
return new SimpleDateFormat("HH:mm:ss").format(time);
}
static public A firstWhereMethodReturns(String methodName, Iterable l, Object result) {
return firstThat(l, o -> eq(call(o, methodName), result));
}
static public Pair mapEntryToPair(Map.Entry e) {
return e == null ? null : pair(e.getKey(), e.getValue());
}
static public Set> entrySet(Map map) {
return _entrySet(map);
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public A firstThat(Iterable l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(A[] l, IF1 pred) {
for (A a : unnullForIteration(l)) if (pred.get(a))
return a;
return null;
}
static public A firstThat(IF1 pred, Iterable l) {
return firstThat(l, pred);
}
static public A firstThat(IF1 pred, A[] l) {
return firstThat(l, pred);
}
static public String rtrim_fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null) {
boolean first = true;
for (Object line : lines) {
if (first)
first = false;
else
buf.append('\n');
buf.append(str(line));
}
}
return buf.toString();
}
static public String makePostData(Map map) {
StringBuilder buf = new StringBuilder();
for (Map.Entry e : castMapToMapO(map).entrySet()) {
String key = (String) (e.getKey());
Object val = e.getValue();
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public String makePostData(Object... params) {
StringBuilder buf = new StringBuilder();
int n = l(params);
for (int i = 0; i + 1 < n; i += 2) {
String key = (String) (params[i]);
Object val = params[i + 1];
if (val != null) {
String value = str(val);
if (nempty(buf))
buf.append("&");
buf.append(urlencode(key)).append("=").append(urlencode((value)));
}
}
return str(buf);
}
static public int smartIndexOf(String s, String sub, int i) {
if (s == null)
return 0;
i = s.indexOf(sub, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, int i, char c) {
return smartIndexOf(s, c, i);
}
static public int smartIndexOf(String s, char c, int i) {
if (s == null)
return 0;
i = s.indexOf(c, min(i, l(s)));
return i >= 0 ? i : l(s);
}
static public int smartIndexOf(String s, String sub) {
return smartIndexOf(s, sub, 0);
}
static public int smartIndexOf(String s, char c) {
return smartIndexOf(s, c, 0);
}
static public int smartIndexOf(List l, A sub) {
return smartIndexOf(l, sub, 0);
}
static public int smartIndexOf(List l, int start, A sub) {
return smartIndexOf(l, sub, start);
}
static public int smartIndexOf(List l, A sub, int start) {
int i = indexOf(l, sub, start);
return i < 0 ? l(l) : i;
}
static public Map paramsToMap(Object... params) {
int n = l(params);
if (l(params) == 1 && params[0] instanceof Map)
return (Map) params[0];
LinkedHashMap map = new LinkedHashMap();
for (int i = 0; i + 1 < n; i += 2) mapPut(map, params[i], params[i + 1]);
return map;
}
static public Random getRandomizer(Random r) {
return r != null ? r : defaultRandomGenerator();
}
static public Random random_random = new Random();
static public int random(int n) {
return random(random_random, n);
}
static public int random(int n, Random r) {
return random(r, n);
}
static public int random(Random r, int n) {
return n <= 0 ? 0 : getRandomizer(r).nextInt(n);
}
static public double random(double max) {
return random() * max;
}
static public double random() {
return random_random.nextInt(100001) / 100000.0;
}
static public double random(double min, double max) {
return min + random() * (max - min);
}
static public int random(int min, int max) {
return min + random(max - min);
}
static public int random(int min, int max, Random r) {
return random(r, min, max);
}
static public int random(Random r, int min, int max) {
return min + random(r, max - min);
}
static public A random(List l) {
return oneOf(l);
}
static public A random(Collection c) {
if (c instanceof List)
return random((List ) c);
int i = random(l(c));
return collectionGet(c, i);
}
static public Pair random(Map map) {
return entryToPair(random(entries(map)));
}
static public int loadPage_defaultTimeout = 60000;
static public ThreadLocal loadPage_charset = new ThreadLocal();
static public boolean loadPage_allowGzip = true, loadPage_debug;
static public boolean loadPage_anonymous = false;
static public int loadPage_verboseness = 100000;
static public int loadPage_retries = 1;
static public ThreadLocal loadPage_silent = new ThreadLocal();
static volatile public int loadPage_forcedTimeout;
static public ThreadLocal loadPage_forcedTimeout_byThread = new ThreadLocal();
static public ThreadLocal>> loadPage_responseHeaders = new ThreadLocal();
static public ThreadLocal> loadPage_extraHeaders = new ThreadLocal();
static public ThreadLocal loadPage_sizeLimit = new ThreadLocal();
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadPageSilently(URL url) {
try {
if (!networkAllowanceTest(str(url)))
throw fail("Not allowed: " + url);
IOException e = null;
for (int tries = 0; tries < loadPage_retries; tries++) try {
URLConnection con = loadPage_openConnection(url);
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
if (loadPage_debug)
print(exceptionToStringShort(e));
if (tries < loadPage_retries - 1)
sleepSeconds(1);
}
throw e;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = tb_mainServer() + "/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
static public String loadPage(String url) {
try {
url = loadPage_preprocess(url);
if (!isTrue(loadPage_silent.get()))
printWithTime("Loading: " + hideCredentials(url));
return loadPageSilently(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String loadPage(URL url) {
return loadPage(url.toExternalForm());
}
static public String loadPage(URLConnection con, URL url) throws IOException {
return loadPage(con, url, true);
}
static public String loadPage(URLConnection con, URL url, boolean addHeaders) throws IOException {
Map extraHeaders = getAndClearThreadLocal(loadPage_extraHeaders);
Long limit = optPar(loadPage_sizeLimit);
if (addHeaders)
try {
if (!loadPage_anonymous)
setHeaders(con);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
con.setRequestProperty("X-No-Cookies", "1");
for (String key : keys(extraHeaders)) con.setRequestProperty(key, extraHeaders.get(key));
} catch (Throwable e) {
}
vm_generalSubMap("URLConnection per thread").put(currentThread(), con);
loadPage_responseHeaders.set(con.getHeaderFields());
InputStream in = null;
try {
in = urlConnection_getInputStream(con);
if (loadPage_debug)
print("Put stream in map: " + currentThread());
String contentType = con.getContentType();
if (contentType == null) {
throw new IOException("Page could not be read: " + hideCredentials(url));
}
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null)
charset = loadPage_guessCharset(contentType);
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = newGZIPInputStream(in);
}
Reader r;
try {
r = new InputStreamReader(in, unquote(charset));
} catch (UnsupportedEncodingException e) {
print(toHex(utf8(charset)));
throw e;
}
boolean silent = isTrue(loadPage_silent.get());
StringBuilder buf = new StringBuilder();
int n = 0;
while (limit == null || n < limit) {
ping();
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
++n;
if (!silent && (n % loadPage_verboseness) == 0)
print(" " + n + " chars read");
}
return buf.toString();
} finally {
if (loadPage_debug)
print("loadPage done");
vm_generalSubMap("URLConnection per thread").remove(currentThread());
if (in != null)
in.close();
}
}
static public String loadPage_guessCharset(String contentType) {
Matcher m = regexpMatcher("text/[a-z]+;\\s*charset=([^\\s]+)\\s*", contentType);
String match = m.matches() ? m.group(1) : null;
if (loadPage_debug)
print("loadPage: contentType=" + contentType + ", match: " + match);
return or(match, "UTF-8");
}
static public URLConnection loadPage_openConnection(URL url) {
URLConnection con = openConnection(url);
int timeout = toInt(loadPage_forcedTimeout_byThread.get());
if (timeout == 0)
timeout = loadPage_forcedTimeout;
if (timeout != 0)
setURLConnectionTimeouts(con, loadPage_forcedTimeout);
else
setURLConnectionDefaultTimeouts(con, loadPage_defaultTimeout);
return con;
}
static public A getAndClearThreadLocal(ThreadLocal tl) {
A a = tl.get();
tl.set(null);
return a;
}
static public 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) {
}
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Set keys(MultiSet ms) {
return ms.keySet();
}
static public Set keys(MultiMap mm) {
return mm.keySet();
}
static public A println(A a) {
return print(a);
}
static public String getChannelName() {
return (String) callOpt(getMainBot(), "getChannelName");
}
static public Object dm_callMe(String method, Object... args) {
return dm_callMyself(method, args);
}
static public Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public AutoCloseable tempSetThreadLocalIfNecessary(ThreadLocal tl, A a) {
if (tl == null)
return null;
A prev = tl.get();
if (eq(prev, a))
return null;
tl.set(a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public List findTagsWithParams(String tag, List tok, Object... params) {
List l = new ArrayList();
for (String t : codeTokens(tok)) if (tagIs(t, tag) && htmlCheckParams(t, params))
l.add(t);
return l;
}
static public List findTagsWithParams(String tag, String html, Object... params) {
return findTagsWithParams(tag, htmlTok(html), params);
}
static public String tagParam(String tag, String key) {
return getHtmlTagParameter(tag, key);
}
static public String tagParam(List tok, String key) {
return getHtmlTagParameter(second(tok), key);
}
static public String dropPrefixTrimIC_orNull(String prefix, String s) {
return dropPrefixICTrim_orNull(prefix, s);
}
static public int lastIndexOfIC(String a, String b) {
return lastIndexOfIgnoreCase_manual(a, b);
}
static public int lastIndexOfIC(String a, char b) {
return lastIndexOfIgnoreCase_manual(a, str(b));
}
static public String hideCredentials(URL url) {
return url == null ? null : hideCredentials(str(url));
}
static public String hideCredentials(String url) {
try {
if (startsWithOneOf(url, "http://", "https://") && isAGIBlueDomain(hostNameFromURL(url)))
return url;
} catch (Throwable e) {
print("HideCredentials", e);
}
return url.replaceAll("([&?])(_pass|key|cookie)=[^&\\s\"]*", "$1$2=");
}
static public String hideCredentials(Object o) {
return hideCredentials(str(o));
}
static public 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 public Object jsonDecode(String text) {
return new jsonDecode_Y(text).parse();
}
static public class jsonDecode_Y {
public String text;
public List tok;
public boolean useOrderedMaps = false;
public int i = 1;
public jsonDecode_Y(String text) {
this.text = text;
tok = jsonTok(text);
}
transient public IF1 fail;
public RuntimeException fail(String msg) {
return fail != null ? fail.get(msg) : fail_base(msg);
}
final public RuntimeException fail_fallback(IF1 _f, String msg) {
return _f != null ? _f.get(msg) : fail_base(msg);
}
public RuntimeException fail_base(String msg) {
return main.fail(msg);
}
public Object parse() {
if (l(tok) == 1)
return null;
return parseExpr();
}
public Object parseExpr() {
String t = tok.get(i);
if (t.startsWith("\"") || t.startsWith("'")) {
String s = unquote(tok.get(i));
i += 2;
return s;
}
if (t.equals("{"))
return parseMap();
if (t.equals("["))
return this.parseList();
if (t.equals("null")) {
i += 2;
return null;
}
if (t.equals("false")) {
i += 2;
return false;
}
if (t.equals("true")) {
i += 2;
return true;
}
boolean minus = false;
if (t.equals("-")) {
minus = true;
i += 2;
t = get(tok, i);
}
if (isInteger(t)) {
int j = i;
i += 2;
if (eqOneOf(get(tok, i), ".", "e", "E")) {
while (isInteger(get(tok, i)) || eqOneOf(get(tok, i), ".", "e", "E", "-")) i += 2;
double d = parseDouble(joinSubList(tok, j, i - 1));
if (minus)
d = -d;
return d;
} else {
long l = parseLong(t);
return boxedIntOrLong(minus ? -l : l);
}
}
throw fail("Unknown token " + (i + 1) + ": " + t + ": " + text);
}
public Object parseList() {
consume("[");
List list = new ArrayList();
while (!tok.get(i).equals("]")) {
list.add(parseExpr());
if (tok.get(i).equals(","))
i += 2;
}
consume("]");
return list;
}
public Object parseMap() {
consume("{");
Map map = useOrderedMaps ? new LinkedHashMap() : new TreeMap();
while (!tok.get(i).equals("}")) {
String key = unquote(tok.get(i));
i += 2;
consume(":");
Object value = parseExpr();
map.put(key, value);
if (tok.get(i).equals(","))
i += 2;
}
consume("}");
return map;
}
public void consume(String s) {
if (!tok.get(i).equals(s)) {
String prevToken = i - 2 >= 0 ? tok.get(i - 2) : "";
String nextTokens = join(tok.subList(i, Math.min(i + 4, tok.size())));
throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")");
}
i += 2;
}
}
static public HashMap litmap(Object... x) {
HashMap map = new HashMap();
litmap_impl(map, x);
return map;
}
static public void litmap_impl(Map map, Object... x) {
if (x != null)
for (int i = 0; i < x.length - 1; i += 2) if (x[i + 1] != null)
map.put(x[i], x[i + 1]);
}
static public char lastChar(String s) {
return empty(s) ? '\0' : s.charAt(l(s) - 1);
}
static public A[] dropLast(A[] a) {
return dropLast(a, 1);
}
static public A[] dropLast(A[] a, int n) {
if (a == null)
return null;
n = Math.min(n, a.length);
A[] b = arrayOfSameType(a, a.length - n);
System.arraycopy(a, 0, b, 0, b.length);
return b;
}
static public List dropLast(List l) {
return subList(l, 0, l(l) - 1);
}
static public List dropLast(int n, List l) {
return subList(l, 0, l(l) - n);
}
static public List dropLast(Iterable l) {
return dropLast(asList(l));
}
static public String dropLast(String s) {
return substring(s, 0, l(s) - 1);
}
static public String dropLast(String s, int n) {
return substring(s, 0, l(s) - n);
}
static public String dropLast(int n, String s) {
return dropLast(s, n);
}
static public 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 public List> findContainerTagWithParams(String html, String tag, Object... params) {
return findContainerTagWithParams(htmlTok(html), tag, params);
}
static public String joinContentsOfContainerTag(List tok) {
return tok == null ? null : join(contentsOfContainerTag(tok));
}
static public Object gazelle_discordPresence() {
return call(gazelle_jda(), "getPresence");
}
static public Class getClass_vmName(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(name);
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object gazelle_jda() {
return getFirstNonNullField(dm_current_mandatory_generic(), "discord", "bot");
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public Collection values(Object map) {
return values((Map) map);
}
static public Collection values(MultiMap mm) {
return mm == null ? emptyList() : concatLists(values(mm.data));
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static public Class __javax;
static public Class getJavaX() {
try {
return __javax;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void __setJavaX(Class j) {
__javax = j;
_onJavaXSet();
}
static public ThreadLocal print_byThread() {
synchronized (print_byThread_lock) {
if (print_byThread == null)
print_byThread = new ThreadLocal();
}
return print_byThread;
}
static public AutoCloseable tempInterceptPrint(F1 f) {
return tempSetThreadLocal(print_byThread(), f);
}
static public Object defaultDefaultClassFinder() {
return new F1() {
public Class get(String name) {
Class c = get2(name);
return c;
}
public Class get2(String name) {
if (eq(name, ""))
return mc();
{
Class c = findClass_fullName(name);
if (c != null)
return c;
}
if (startsWithAny(name, "loadableUtils.utils$", "main$", mcDollar()))
for (String pkg : ll("loadableUtils.utils$", mcDollar())) {
String newName = pkg + afterDollar(name);
{
Class c = findClass_fullName(newName);
if (c != null)
return c;
}
}
return null;
}
};
}
static public String programIDWithCase() {
return nempty(caseID()) ? programID() + "/" + quoteUnlessIdentifierOrInteger(caseID()) : programID();
}
static public String[] dropFirst(int n, String[] a) {
return drop(n, a);
}
static public String[] dropFirst(String[] a) {
return drop(1, a);
}
static public Object[] dropFirst(Object[] a) {
return drop(1, a);
}
static public List dropFirst(List l) {
return dropFirst(1, l);
}
static public List dropFirst(int n, Iterable i) {
return dropFirst(n, toList(i));
}
static public List dropFirst(Iterable i) {
return dropFirst(toList(i));
}
static public List dropFirst(int n, List l) {
return n <= 0 ? l : new ArrayList(l.subList(Math.min(n, l.size()), l.size()));
}
static public List dropFirst(List l, int n) {
return dropFirst(n, l);
}
static public String dropFirst(int n, String s) {
return substring(s, n);
}
static public String dropFirst(String s, int n) {
return substring(s, n);
}
static public String dropFirst(String s) {
return substring(s, 1);
}
static public int indexOfNonDigit(String s) {
int n = l(s);
for (int i = 0; i < n; i++) if (!isDigit(s.charAt(i)))
return i;
return -1;
}
static public String shortenClassName(String name) {
if (name == null)
return null;
int i = lastIndexOf(name, "$");
if (i < 0)
i = lastIndexOf(name, ".");
return i < 0 ? name : substring(name, i + 1);
}
static public Map classForName_cache = synchroHashMap();
static public Class classForName(String name) {
return classForName(name, null);
}
static public Class classForName(String name, Object classFinder) {
if (classForName_cache == null || classFinder != null)
return classForName_uncached(name, classFinder);
Class c = classForName_cache.get(name);
if (c == null)
classForName_cache.put(name, c = classForName_uncached(name, null));
return c;
}
static public Class classForName_uncached(String name, Object classFinder) {
try {
if (classFinder != null)
return (Class) callF(classFinder, name);
return Class.forName(name);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Map nuObjectWithoutArguments_cache = newDangerousWeakHashMap();
static public Object nuObjectWithoutArguments(String className) {
try {
return nuObjectWithoutArguments(classForName(className));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObjectWithoutArguments(Class c) {
try {
if (nuObjectWithoutArguments_cache == null)
return (A) nuObjectWithoutArguments_findConstructor(c).newInstance();
Constructor m = nuObjectWithoutArguments_cache.get(c);
if (m == null)
nuObjectWithoutArguments_cache.put(c, m = nuObjectWithoutArguments_findConstructor(c));
return (A) m.newInstance();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObjectWithoutArguments_findConstructor(Class c) {
for (Constructor m : c.getDeclaredConstructors()) if (empty(m.getParameterTypes())) {
makeAccessible(m);
return m;
}
throw fail("No default constructor found in " + c.getName());
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public List getClasses(Object[] array) {
List l = emptyList(l(array));
for (Object o : array) l.add(_getClass(o));
return l;
}
static public boolean isInstanceX(Class type, Object arg) {
if (type == boolean.class)
return arg instanceof Boolean;
if (type == int.class)
return arg instanceof Integer;
if (type == long.class)
return arg instanceof Long;
if (type == float.class)
return arg instanceof Float;
if (type == short.class)
return arg instanceof Short;
if (type == char.class)
return arg instanceof Character;
if (type == byte.class)
return arg instanceof Byte;
if (type == double.class)
return arg instanceof Double;
return type.isInstance(arg);
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public void set(BitSet bs, int idx) {
{
if (bs != null)
bs.set(idx);
}
}
static public void failIfOddCount(Object... list) {
if (odd(l(list)))
throw fail("Odd list size: " + list);
}
static public A dm_ownResource(A resource) {
dm_currentModuleMandatory().ownResource(resource);
return resource;
}
static public AutoCloseable vmBus_onMessage(String msg, IVF1 onMessage) {
return vmBus_onMessage(msg, ivf1ToVF1(onMessage));
}
static public AutoCloseable vmBus_onMessage(final String msg, final VF1 onMessage) {
Map map = vm_busListenersByMessage_live();
synchronized (map) {
Set listeners = map.get(msg);
if (listeners == null)
map.put(msg, listeners = syncIdentityHashSet());
return tempAdd(listeners, new VF2() {
public void get(String _msg, Object arg) {
try {
callF(onMessage, arg);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, arg)";
}
});
}
}
static public AutoCloseable vmBus_onMessage(String msg, final VF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, final IVF2 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, final VF3 onMessage) {
return vmBus_onMessage(msg, new VF1() {
public void get(Object[] o) {
try {
callF(onMessage, first(o), second(o), third(o));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, first(o), second(o), third(o));";
}
});
}
static public AutoCloseable vmBus_onMessage(String msg, Runnable onMessage) {
return vmBus_onMessage(msg, runnableToVF1(onMessage));
}
static public VF1 ivf1ToVF1(IVF1 f) {
return f == null ? null : new VF1 () {
public void get(A a) {
try {
f.get(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.get(a)";
}
};
}
static public VF2 ivf2ToVF2(IVF2 f) {
return f == null ? null : new VF2 () {
public void get(A a, B b) {
try {
f.get(a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.get(a, b)";
}
};
}
static public Object call_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findStaticMethod(method, args);
if (me != null)
return invokeMethod(me, null, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
{
if (!(isStaticMethod(m)))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, null, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List methods = cache.cache.get(method);
if (methods != null)
methodSearch: for (Method m : methods) {
{
if (!(m.isVarArgs()))
continue;
}
Object[] newArgs = massageArgsForVarArgsCall(m, args);
if (newArgs != null)
return invokeMethod(m, o, newArgs);
}
throw fail("Method " + c.getName() + "." + method + "(" + joinWithComma(classNames(args)) + ") not found");
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static volatile public PersistableThrowable lastException_lastException;
static public PersistableThrowable lastException() {
return lastException_lastException;
}
static public void lastException(Throwable e) {
lastException_lastException = persistableThrowable(e);
}
static public void rotateStringBuffer(StringBuffer buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void rotateStringBuilder(StringBuilder buf, int max) {
try {
if (buf == null)
return;
synchronized (buf) {
if (buf.length() <= max)
return;
try {
int newLength = max / 2;
int ofs = buf.length() - newLength;
String newString = buf.substring(ofs);
buf.setLength(0);
buf.append("[...] ").append(newString);
} catch (Exception e) {
buf.setLength(0);
}
buf.trimToSize();
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public void pcallFAll_minimalExceptionHandling(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) {
ping();
pcallF_minimalExceptionHandling(f, args);
}
}
static public void pcallFAll_minimalExceptionHandling(Iterator it, Object... args) {
while (it.hasNext()) {
ping();
pcallF_minimalExceptionHandling(it.next(), args);
}
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public Map synchronizedMap() {
return synchroMap();
}
static public Map synchronizedMap(Map map) {
return synchroMap(map);
}
static public RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public boolean startsWithIgnoreCase(String a, String b) {
return regionMatchesIC(a, 0, b, 0, b.length());
}
static public String beautifyStructure(String s) {
List tok = javaTokForStructure(s);
structure_addTokenMarkers(tok);
jreplace(tok, "lhm", "");
return join(tok);
}
static public String struct_noStringSharing(Object o) {
structure_Data d = new structure_Data();
d.noStringSharing = true;
return structure(o, d);
}
static public Map defaultSizeMRUCache() {
return mruCache(defaultStringTransformerCacheSize());
}
static public B getOrCreate_f0(Map map, A key, F0 create) {
B b = map.get(key);
if (b == null)
mapPut(map, key, b = callF(create));
return b;
}
static public B getOrCreate_f0(Map map, A key, IF0 create) {
B b = map.get(key);
if (b == null)
mapPut(map, key, b = callF(create));
return b;
}
static public List javaTokNoQuotes(String s) {
return quotelessJavaTok(s);
}
static public boolean containsNewLine(String s) {
return contains(s, '\n');
}
static public String agiBlue_lookupInSlice(String sliceID, String q, String... keys) {
return first((List) loadJSONPage(printHidingCredentials(agiBlue_linkForPhrase(q, paramsPlus(paramsWithSameKey("get", keys), "slice", sliceID)))));
}
static public ThreadLocal>> agiBlue_postInSlice_queue = new ThreadLocal();
static public String agiBlue_postInSlice(String slice, String a, String b, String c) {
List> queue = agiBlue_postInSlice_queue.get();
if (queue != null) {
queue.add(ll(slice, a, b, c));
return "Queued";
} else
return loadPage(agiBlueURL() + "/bot/post" + hquery("slice", slice, "q", a, "key", b, "value", c));
}
static public void newPing() {
var tl = newPing_actionTL();
Runnable action = tl == null ? null : tl.get();
{
if (action != null)
action.run();
}
}
static public boolean isAWTThread() {
if (isAndroid())
return false;
if (isHeadless())
return false;
return isAWTThread_awt();
}
static public boolean isAWTThread_awt() {
return SwingUtilities.isEventDispatchThread();
}
static public void failIfUnlicensed() {
assertTrue("license off", licensed());
}
static public String shortenSnippetID(String snippetID) {
if (snippetID.startsWith("#"))
snippetID = snippetID.substring(1);
String httpBlaBla = "http://tinybrain.de/";
if (snippetID.startsWith(httpBlaBla))
snippetID = snippetID.substring(httpBlaBla.length());
return "" + parseLong(snippetID);
}
static public String formatSnippetIDOpt(String s) {
return isSnippetID(s) ? formatSnippetID(s) : s;
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
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 public int strL(String s) {
return s == null ? 0 : s.length();
}
static public int lCharSequence(CharSequence s) {
return s == null ? 0 : s.length();
}
static public String dropSuffix(String suffix, String s) {
return nempty(suffix) && endsWith(s, suffix) ? s.substring(0, l(s) - l(suffix)) : s;
}
static public int javaTok_n, javaTok_elements;
static public boolean javaTok_opt = false;
static public List javaTok(String s) {
++javaTok_n;
ArrayList tok = new ArrayList();
int l = s == null ? 0 : s.length();
int i = 0;
while (i < l) {
int j = i;
char c, d;
while (j < l) {
c = s.charAt(j);
d = j + 1 >= l ? '\0' : s.charAt(j + 1);
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (c == '/' && d == '*') {
do ++j; while (j < l && !regionMatches(s, j, "*/"));
j = Math.min(j + 2, l);
} else if (c == '/' && d == '/') {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(javaTok_substringN(s, i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
d = i + 1 >= l ? '\0' : s.charAt(i + 1);
if (c == '\'' && Character.isJavaIdentifierStart(d) && i + 2 < l && "'\\".indexOf(s.charAt(i + 2)) < 0) {
j += 2;
while (j < l && Character.isJavaIdentifierPart(s.charAt(j))) ++j;
} else if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
int c2 = s.charAt(j);
if (c2 == opener || c2 == '\n' && opener == '\'') {
++j;
break;
} else if (c2 == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isJavaIdentifierStart(c))
do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\''));
else if (Character.isDigit(c)) {
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
if (j < l && s.charAt(j) == 'L')
++j;
} else if (c == '[' && d == '[') {
do ++j; while (j < l && !regionMatches(s, j, "]]"));
j = Math.min(j + 2, l);
} else if (c == '[' && d == '=' && i + 2 < l && s.charAt(i + 2) == '[') {
do ++j; while (j + 2 < l && !regionMatches(s, j, "]=]"));
j = Math.min(j + 3, l);
} else
++j;
tok.add(javaTok_substringC(s, i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
javaTok_elements += tok.size();
return tok;
}
static public List javaTok(List tok) {
return javaTokWithExisting(join(tok), tok);
}
static public int jfind(String s, String in) {
return jfind(javaTok(s), in);
}
static public int jfind(List tok, String in) {
return jfind(tok, 1, in);
}
static public int jfind(List tok, int startIdx, String in) {
return jfind(tok, startIdx, in, null);
}
static public int jfind(List tok, String in, Object condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, String in, ITokCondition condition) {
return jfind(tok, 1, in, condition);
}
static public int jfind(List tok, int startIndex, String in, ITokCondition condition) {
return jfind(tok, startIndex, in, (Object) condition);
}
static public int jfind(List tok, int startIdx, String in, Object condition) {
return jfind(tok, startIdx, javaTokForJFind_array(in), condition);
}
static public int jfind(List tok, List tokin) {
return jfind(tok, 1, tokin);
}
static public int jfind(List tok, int startIdx, List tokin) {
return jfind(tok, startIdx, tokin, null);
}
static public int jfind(List tok, int startIdx, String[] tokinC, Object condition) {
return findCodeTokens(tok, startIdx, false, tokinC, condition);
}
static public int jfind(List tok, int startIdx, List tokin, Object condition) {
return jfind(tok, startIdx, codeTokensAsStringArray(tokin), condition);
}
static public List jfind_preprocess(List tok) {
for (String type : litlist("quoted", "id", "int")) replaceSublist(tok, ll("<", "", type, "", ">"), ll("<" + type + ">"));
replaceSublist(tok, ll("\\", "", "*"), ll("\\*"));
return tok;
}
static public String joinSubList(List l, int i, int j) {
return join(subList(l, i, j));
}
static public String joinSubList(List l, int i) {
return join(subList(l, i));
}
static public String formatWithThousandsSeparator(long l) {
return NumberFormat.getInstance(new Locale("en_US")).format(l);
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public > A max(A a, A b) {
return cmp(a, b) >= 0 ? a : b;
}
static public CloseableIterableIterator linesFromFile(File f) {
return linesFromFile(f, null);
}
static public CloseableIterableIterator linesFromFile(File f, IResourceHolder resourceHolder) {
try {
if (!f.exists())
return emptyCloseableIterableIterator();
if (ewic(f.getName(), ".gz"))
return linesFromReader(utf8bufferedReader(newGZIPInputStream(f)), resourceHolder);
return linesFromReader(utf8bufferedReader(f), resourceHolder);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public CloseableIterableIterator linesFromFile(String path) {
return linesFromFile(path, null);
}
static public CloseableIterableIterator linesFromFile(String path, IResourceHolder resourceHolder) {
return linesFromFile(newFile(path), resourceHolder);
}
static public boolean even(int i) {
return (i & 1) == 0;
}
static public boolean even(long i) {
return (i & 1) == 0;
}
static public boolean even(BigInteger n) {
return even(n.intValue());
}
static public boolean isLetter(char c) {
return Character.isLetter(c);
}
static public A last(List l) {
return empty(l) ? null : l.get(l.size() - 1);
}
static public char last(String s) {
return empty(s) ? '#' : s.charAt(l(s) - 1);
}
static public int last(int[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
static public double last(double[] a) {
return l(a) != 0 ? a[l(a) - 1] : 0;
}
static public A last(A[] a) {
return l(a) != 0 ? a[l(a) - 1] : null;
}
static public A last(Iterator it) {
A a = null;
while (it.hasNext()) {
ping();
a = it.next();
}
return a;
}
static public A last(Collection l) {
if (l == null)
return null;
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 public A last(SortedSet l) {
return l == null ? null : l.last();
}
static public boolean regexpFinds(String pat, String s) {
return regexp(pat, s).find();
}
static public boolean regexpFinds(Pattern pat, String s) {
return regexp(pat, s).find();
}
static public int[] emptyIntArray_a = new int[0];
static public int[] emptyIntArray() {
return emptyIntArray_a;
}
static public char[] emptyCharArray = new char[0];
static public char[] emptyCharArray() {
return emptyCharArray;
}
static public double[] emptyDoubleArray = new double[0];
static public double[] emptyDoubleArray() {
return emptyDoubleArray;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object[] emptyObjectArray_a = new Object[0];
static public Object[] emptyObjectArray() {
return emptyObjectArray_a;
}
static public Symbol emptySymbol_value;
static public Symbol emptySymbol() {
if (emptySymbol_value == null)
emptySymbol_value = symbol("");
return emptySymbol_value;
}
static public int year() {
return localYear();
}
static public int year(long now) {
return localYear(now);
}
static public int year(long now, TimeZone tz) {
return parseInt(simpleDateFormat("y", tz).format(now));
}
static public String formatInt(int i, int digits) {
return padLeft(str(i), '0', digits);
}
static public String formatInt(long l, int digits) {
return padLeft(str(l), '0', digits);
}
static public int month() {
return localMonth();
}
static public int month(long now) {
return localMonth(now);
}
static public int month(long now, TimeZone tz) {
return parseInt(simpleDateFormat("M", tz).format(now));
}
static public int dayOfMonth() {
return localDayOfMonth();
}
static public int dayOfMonth(long now) {
return localDayOfMonth(now);
}
static public int dayOfMonth(long now, TimeZone tz) {
return parseInt(simpleDateFormat("d", tz).format(now));
}
public static File mkdirsForFile(File file) {
File dir = file.getParentFile();
if (dir != null) {
dir.mkdirs();
if (!dir.isDirectory())
if (dir.isFile())
throw fail("Please delete the file " + f2s(dir) + " - it is supposed to be a directory!");
else
throw fail("Unknown IO exception during mkdirs of " + f2s(file));
}
return file;
}
public static String mkdirsForFile(String path) {
mkdirsForFile(new File(path));
return path;
}
static public File getProgramFile(String progID, String fileName) {
if (new File(fileName).isAbsolute())
return new File(fileName);
return new File(getProgramDir(progID), fileName);
}
static public File getProgramFile(String fileName) {
return getProgramFile(getProgramID(), fileName);
}
static public FileOutputStream newFileOutputStream(File path) throws IOException {
return newFileOutputStream(path.getPath());
}
static public FileOutputStream newFileOutputStream(String path) throws IOException {
return newFileOutputStream(path, false);
}
static public FileOutputStream newFileOutputStream(File path, boolean append) throws IOException {
return newFileOutputStream(path.getPath(), append);
}
static public FileOutputStream newFileOutputStream(String path, boolean append) throws IOException {
mkdirsForFile(path);
FileOutputStream f = new FileOutputStream(path, append);
_registerIO(f, path, true);
return f;
}
static public byte[] toUtf8(String s) {
try {
return s.getBytes(utf8charset());
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public long round(double d) {
return Math.round(d);
}
static public String round(String s) {
return roundBracket(s);
}
static public Complex round(Complex c) {
return new Complex(round(c.re), round(c.im));
}
static public File javaxDataDir_dir;
static public File javaxDataDir() {
return javaxDataDir_dir != null ? javaxDataDir_dir : new File(userHome(), "JavaX-Data");
}
static public File javaxDataDir(String... subs) {
return newFile(javaxDataDir(), subs);
}
static public ThreadLocal> checkFileNotTooBigToRead_tl = new ThreadLocal();
static public void checkFileNotTooBigToRead(File f) {
callF(checkFileNotTooBigToRead_tl.get(), f);
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public String _userHome;
static public String userHome() {
if (_userHome == null)
return actualUserHome();
return _userHome;
}
static public File userHome(String path) {
return new File(userDir(), path);
}
static public Random defaultRandomGenerator() {
return ThreadLocalRandom.current();
}
static public List beginCriticalAction_inFlight = synchroList();
static public class CriticalAction {
public String description;
public CriticalAction() {
}
public CriticalAction(String description) {
this.description = description;
}
public void done() {
beginCriticalAction_inFlight.remove(this);
}
}
static public CriticalAction beginCriticalAction(String description) {
ping();
CriticalAction c = new CriticalAction(description);
beginCriticalAction_inFlight.add(c);
return c;
}
static public void cleanMeUp_beginCriticalAction() {
int n = 0;
while (nempty(beginCriticalAction_inFlight)) {
int m = l(beginCriticalAction_inFlight);
if (m != n) {
n = m;
try {
print("Waiting for " + n2(n, "critical actions") + ": " + join(", ", collect(beginCriticalAction_inFlight, "description")));
} catch (Throwable __e) {
printStackTrace(__e);
}
}
sleepInCleanUp(10);
}
}
static public File copyFile(File src, File dest) {
try {
FileInputStream inputStream = new FileInputStream(src.getPath());
FileOutputStream outputStream = newFileOutputStream(dest.getPath());
try {
copyStream(inputStream, outputStream);
inputStream.close();
} finally {
outputStream.close();
}
return dest;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean isString(Object o) {
return o instanceof String;
}
static public boolean isIdentifier(String s) {
return isJavaIdentifier(s);
}
static public Object dm_getService(String serviceName) {
return empty(serviceName) ? null : dm_getModule(vmBus_query(assertIdentifier(serviceName)));
}
static public boolean isStringOrIntOrLong(Object o) {
return o instanceof String || o instanceof Integer || o instanceof Long;
}
static public Object dm_getStemByID(Object id) {
return dm_callOS("getModuleByID", str(id));
}
static public Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
static public int boolToInt(boolean b) {
return b ? 1 : 0;
}
static public CharSequence subCharSequence(CharSequence s, int x) {
return subCharSequence(s, x, s == null ? 0 : s.length());
}
static public CharSequence subCharSequence(CharSequence s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.subSequence(x, y);
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public AutoCloseable tempActivity(Object r) {
return null;
}
static public long fixTimestamp(long timestamp) {
return timestamp > now() ? 0 : timestamp;
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
{
if (f != null)
f.get(a);
}
} catch (Throwable __e) {
printStackTrace(__e);
}
}
static public Object pcallF(Runnable r) {
try {
{
if (r != null)
r.run();
}
return null;
} catch (Throwable __e) {
return null;
}
}
static public A pcallF(IF0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(IF1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public Object costCenter() {
return mc();
}
static public double parseDouble(String s) {
return empty(s) ? 0.0 : Double.parseDouble(s);
}
static public Set vm_registeredInstancesSet(Class c) {
return c == null ? null : vm_generalWeakSet("Instances of " + c.getName());
}
static public Set vm_registeredInstancesSet(String className) {
return className == null ? null : vm_generalWeakSet("Instances of " + className);
}
static public String formatDouble(double d, int digits) {
String format = digits <= 0 ? "0" : "0." + rep(digits, '#');
return decimalFormatEnglish(format, d);
}
static public String formatDouble(double d) {
return str(d);
}
static public Set synchronizedSet() {
return synchroHashSet();
}
static public Set synchronizedSet(Set set) {
return Collections.synchronizedSet(set);
}
static public int indexOfIgnoreCase(List a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static public int indexOfIgnoreCase(List a, String b, int i) {
int n = a == null ? 0 : a.size();
for (; i < n; i++) if (eqic(a.get(i), b))
return i;
return -1;
}
static public int indexOfIgnoreCase(String[] a, String b) {
return indexOfIgnoreCase(a, b, 0);
}
static public int indexOfIgnoreCase(String[] a, String b, int i) {
int n = a == null ? 0 : a.length;
for (; i < n; i++) if (eqic(a[i], b))
return i;
return -1;
}
static public int indexOfIgnoreCase(String a, String b) {
return indexOfIgnoreCase_manual(a, b);
}
static public int indexOfIgnoreCase(String a, String b, int i) {
return indexOfIgnoreCase_manual(a, b, i);
}
static public List newSubListOrSame(List l, int startIndex) {
return newSubListOrSame(l, startIndex, l(l));
}
static public List newSubListOrSame(List l, int startIndex, int endIndex) {
if (l == null)
return null;
int n = l(l);
startIndex = max(0, startIndex);
endIndex = min(n, endIndex);
if (startIndex >= endIndex)
return ll();
if (startIndex == 0 && endIndex == n)
return l;
return cloneList(l.subList(startIndex, endIndex));
}
static public int[] takeFirstOfIntArray(int[] b, int n) {
return subIntArray(b, 0, n);
}
static public int[] takeFirstOfIntArray(int n, int[] b) {
return takeFirstOfIntArray(b, n);
}
static public short[] takeFirstOfShortArray(short[] b, int n) {
return subShortArray(b, 0, n);
}
static public short[] takeFirstOfShortArray(int n, short[] b) {
return takeFirstOfShortArray(b, n);
}
static public byte[] takeFirstOfByteArray(byte[] b, int n) {
return subByteArray(b, 0, n);
}
static public byte[] takeFirstOfByteArray(int n, byte[] b) {
return takeFirstOfByteArray(b, n);
}
static public double[] takeFirstOfDoubleArray(double[] b, int n) {
return subDoubleArray(b, 0, n);
}
static public double[] takeFirstOfDoubleArray(int n, double[] b) {
return takeFirstOfDoubleArray(b, n);
}
static public String fsI(String id) {
return formatSnippetID(id);
}
static public String fsI(long id) {
return formatSnippetID(id);
}
static public boolean isImageServerSnippet(long id) {
return id >= 1100000 && id < 1200000;
}
static public String imageServerLink(String md5OrID) {
if (possibleMD5(md5OrID))
return "https://botcompany.de/images/md5/" + md5OrID;
return imageServerLink(parseSnippetID(md5OrID));
}
static public String imageServerLink(long id) {
return "https://botcompany.de/images/" + id;
}
static public TimerTask timerTask(final Object r, final java.util.Timer timer) {
return new TimerTask() {
public void run() {
if (!licensed())
timer.cancel();
else
pcallF(r);
}
};
}
static public void dm_reloadModule(Object module) {
dm_reloadModuleInBackground(module);
}
static public void dm_reloadModule() {
dm_reloadModuleInBackground();
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(unnull(b));
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
if (m != null)
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public List tok_splitAtVerticalBar(String s) {
if (!contains(s, '|'))
return ll(s);
return splitAtTokens(javaTokPlusBrackets2(s), tok_splitAtVerticalBar_list);
}
static public List tok_splitAtVerticalBar_list = ll("|");
static public boolean matchX(String pat, String s) {
return matchX(pat, s, null);
}
static public boolean matchX(String pat, String s, Matches m) {
if (endsWith(pat, "...")) {
pat = dropSuffixTrim("...", pat);
if (startsWith(pat, "..."))
return find3(dropPrefixTrim("...", pat), s, m);
else
return matchStart(pat, s, m);
}
if (startsWith(pat, "..."))
return matchEndX(pat, s, m);
return match(pat, s, m);
}
static public String unnullForIteration(String s) {
return s == null ? "" : s;
}
static public Collection unnullForIteration(Collection l) {
return l == null ? immutableEmptyList() : l;
}
static public List unnullForIteration(List l) {
return l == null ? immutableEmptyList() : l;
}
static public int[] unnullForIteration(int[] l) {
return l == null ? emptyIntArray() : l;
}
static public char[] unnullForIteration(char[] l) {
return l == null ? emptyCharArray() : l;
}
static public double[] unnullForIteration(double[] l) {
return l == null ? emptyDoubleArray() : l;
}
static public short[] unnullForIteration(short[] l) {
return l == null ? emptyShortArray() : l;
}
static public Map unnullForIteration(Map l) {
return l == null ? immutableEmptyMap() : l;
}
static public Iterable unnullForIteration(Iterable i) {
return i == null ? immutableEmptyList() : i;
}
static public A[] unnullForIteration(A[] a) {
return a == null ? (A[]) emptyObjectArray() : a;
}
static public BitSet unnullForIteration(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnullForIteration(Pt p) {
return p == null ? new Pt() : p;
}
static public Symbol unnullForIteration(Symbol s) {
return s == null ? emptySymbol() : s;
}
static public Pair unnullForIteration(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public long unnullForIteration(Long l) {
return l == null ? 0L : l;
}
static public boolean addIfNotNull(Collection l, A a) {
return a != null && l != null & l.add(a);
}
static public void addIfNotNull(MultiSet ms, A a) {
if (a != null && ms != null)
ms.add(a);
}
static public Map castMapToMapO(Map map) {
return map;
}
static public A oneOf(List l) {
return empty(l) ? null : l.get(new Random().nextInt(l.size()));
}
static public char oneOf(String s) {
return empty(s) ? '?' : s.charAt(random(l(s)));
}
static public String oneOf(String... l) {
return oneOf(asList(l));
}
static public 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 public Pair entryToPair(Map.Entry e) {
return mapEntryToPair(e);
}
static public Set> entries(Map map) {
return _entrySet(map);
}
static public boolean networkAllowanceTest(String url) {
return isAllowed("networkAllowanceTest", url);
}
static public String exceptionToStringShort(Throwable e) {
lastException(e);
e = getInnerException(e);
String msg = hideCredentials(unnull(e.getMessage()));
if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0)
return baseClassName(e) + prependIfNempty(": ", msg);
else
return msg;
}
static public void sleepSeconds(double s) {
if (s > 0)
sleep(round(s * 1000));
}
static public String tb_mainServer_default = "https://code.botcompany.de:9898";
static public Object tb_mainServer_override;
static public String tb_mainServer() {
if (tb_mainServer_override != null)
return (String) callF(tb_mainServer_override);
return trim(loadTextFile(tb_mainServer_file(), tb_mainServer_default));
}
static public File tb_mainServer_file() {
return getProgramFile("#1001638", "mainserver.txt");
}
static public boolean tb_mainServer_isDefault() {
return eq(tb_mainServer(), tb_mainServer_default);
}
static public Map vm_generalSubMap(Object name) {
synchronized (vm_generalMap()) {
Map map = (Map) (vm_generalMap_get(name));
if (map == null)
vm_generalMap_put(name, map = synchroMap());
return map;
}
}
static public InputStream urlConnection_getInputStream(URLConnection con) throws IOException {
return con.getInputStream();
}
static public GZIPInputStream newGZIPInputStream(File f) {
return gzInputStream(f);
}
static public GZIPInputStream newGZIPInputStream(InputStream in) {
return gzInputStream(in);
}
static public String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
static public String toHex(byte[] bytes) {
return bytesToHex(bytes);
}
static public String toHex(byte[] bytes, int ofs, int len) {
return bytesToHex(bytes, ofs, len);
}
static public byte[] utf8(String s) {
return toUtf8(s);
}
static public Matcher regexpMatcher(String pat, String s) {
return compileRegexp(pat).matcher(unnull(s));
}
static public URLConnection openConnection(String url) {
try {
return openConnection(new URL(url));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public URLConnection openConnection(URL url) {
try {
ping();
callOpt(javax(), "recordOpenURLConnection", str(url));
return url.openConnection();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public 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 public String getComputerID_quick() {
return computerID();
}
static public Object mainBot;
static public Object getMainBot() {
return mainBot;
}
static public Object dm_callMyself(String method, Object... args) {
return dm_call(dm_current_mandatory_generic(), method, args);
}
static public A setThreadLocal(ThreadLocal tl, A value) {
if (tl == null)
return null;
A old = tl.get();
tl.set(value);
return old;
}
static public List codeTokens(List tok) {
return codeTokensOnly(tok);
}
static public boolean tagIs(String token, String tag) {
if (!startsWith(token, "<"))
return false;
int l = l(tag);
return regionMatchesIC(token, 1, tag, 0, l) && eqOneOf(charAt(token, l + 1), '>', ' ');
}
static public boolean htmlCheckParams(String tag, Object... params) {
return checkFields(htmlgetparams(tag), params);
}
static public List htmlTok(String s) {
return htmlcoarsetok(s);
}
static public String getHtmlTagParameter(String tag, String key) {
return getHtmlTagParameters(tag).get(key);
}
static public A second(List l) {
return get(l, 1);
}
static public A second(Iterable l) {
if (l == null)
return null;
Iterator it = iterator(l);
if (!it.hasNext())
return null;
it.next();
return it.hasNext() ? it.next() : null;
}
static public A second(A[] bla) {
return bla == null || bla.length <= 1 ? null : bla[1];
}
static public B second(Pair p) {
return p == null ? null : p.b;
}
static public char second(String s) {
return charAt(s, 1);
}
static public B second(Either e) {
return e == null ? null : e.bOpt();
}
static public int lastIndexOfIgnoreCase_manual(String a, String b) {
int la = strL(a), lb = strL(b);
if (la < lb)
return -1;
int n = la - lb;
loop: for (int i = n; i >= 0; i--) {
for (int j = 0; j < lb; j++) {
char c1 = a.charAt(i + j), c2 = b.charAt(j);
if (!eqic(c1, c2))
continue loop;
}
return i;
}
return -1;
}
static public boolean isAGIBlueDomain(String domain) {
return domainIsUnder(domain, theAGIBlueDomain());
}
static public String hostNameFromURL(String url) {
try {
return empty(url) ? null : new URL(url).getHost();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public List jsonTok(String s) {
List tok = new ArrayList();
int l = l(s);
int i = 0;
while (i < l) {
int j = i;
char c;
String cc;
while (j < l) {
c = s.charAt(j);
cc = s.substring(j, Math.min(j + 2, l));
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++j;
else if (cc.equals("/*")) {
do ++j; while (j < l && !s.substring(j, Math.min(j + 2, l)).equals("*/"));
j = Math.min(j + 2, l);
} else if (cc.equals("//")) {
do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0);
} else
break;
}
tok.add(s.substring(i, j));
i = j;
if (i >= l)
break;
c = s.charAt(i);
if (c == '\'' || c == '"') {
char opener = c;
++j;
while (j < l) {
if (s.charAt(j) == opener) {
++j;
break;
} else if (s.charAt(j) == '\\' && j + 1 < l)
j += 2;
else
++j;
}
} else if (Character.isLetter(c))
do ++j; while (j < l && Character.isLetter(s.charAt(j)));
else if (Character.isDigit(c))
do ++j; while (j < l && Character.isDigit(s.charAt(j)));
else
++j;
tok.add(s.substring(i, j));
i = j;
}
if ((tok.size() % 2) == 0)
tok.add("");
return tok;
}
static public Class main() {
return getMainClass();
}
static public boolean eqOneOf(Object o, Object... l) {
for (Object x : l) if (eq(o, x))
return true;
return false;
}
static public Number boxedIntOrLong(long l) {
return l != (int) l ? boxed(l) : boxed((int) l);
}
static public A[] arrayOfSameType(A[] a, int n) {
return newObjectArrayOfSameType(a, n);
}
static public List> findContainerTag(List tok, String tag) {
List> l = new ArrayList();
for (int i = 1; i < l(tok); i += 2) if (isOpeningTag(tok.get(i), tag)) {
int j, level = 1;
for (j = i + 2; j < tok.size(); j += 2) if (isOpeningTag(tok.get(j), tag))
++level;
else if (isTag(tok.get(j), "/" + tag)) {
--level;
if (level == 0) {
l.add(subList(tok, i - 1, j + 2));
break;
}
}
i = j;
}
return l;
}
static public List