language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | static async notifyMatchMissed(challengeId) {
let challenge;
try {
challenge = await Challenge.getById(challengeId);
} catch (err) {
throw new Exception("There was an error notifying that a challenge match was missed.", err);
}
try {
await Db.setNotifyMatchMissed(challenge);
} catch (err) {
throw new Exception("There was a database error notifying a match was missed for a challenge.", err);
}
try {
await Discord.queue(`The match time was missed in ${challenge.channel}.`, Discord.alertsChannel);
} catch (err) {
throw new Exception("There was a critical Discord error notifying a match was missed for a challenge. Please resolve this manually as soon as possible.", err);
}
challenge.setNotifyMatchMissed();
} | static async notifyMatchMissed(challengeId) {
let challenge;
try {
challenge = await Challenge.getById(challengeId);
} catch (err) {
throw new Exception("There was an error notifying that a challenge match was missed.", err);
}
try {
await Db.setNotifyMatchMissed(challenge);
} catch (err) {
throw new Exception("There was a database error notifying a match was missed for a challenge.", err);
}
try {
await Discord.queue(`The match time was missed in ${challenge.channel}.`, Discord.alertsChannel);
} catch (err) {
throw new Exception("There was a critical Discord error notifying a match was missed for a challenge. Please resolve this manually as soon as possible.", err);
}
challenge.setNotifyMatchMissed();
} |
JavaScript | static async notifyMatchStarting(challengeId) {
let challenge;
try {
challenge = await Challenge.getById(challengeId);
} catch (err) {
throw new Exception("There was an error notifying that a challenge match is about to start.", err);
}
try {
await Db.setNotifyMatchStarting(challenge);
} catch (err) {
throw new Exception("There was a database error notifying a match starting for a challenge.", err);
}
if (!challenge.channel) {
return;
}
await challenge.loadDetails();
for (const member of challenge.channel.members) {
const activity = member[1].presence.activities.find((p) => p.name === "Twitch");
if (activity && urlParse.test(activity.url)) {
const {groups: {user}} = urlParse.exec(activity.url);
await member[1].addTwitchName(user);
if (activity.state.toLowerCase() === "overload") {
const team = await member[1].getTeam();
if (team && (team.id === challenge.challengingTeam.id || team.id === challenge.challengedTeam.id)) {
await member[1].setStreamer();
}
}
}
}
try {
const msg = Discord.messageEmbed({
fields: []
});
if (Math.round((challenge.details.matchTime.getTime() - new Date().getTime()) / 300000) > 0) {
msg.setTitle(`Polish your gunships, this match begins in ${Math.round((challenge.details.matchTime.getTime() - new Date().getTime()) / 300000) * 5} minutes!`);
} else {
msg.setTitle("Polish your gunships, this match begins NOW!");
}
if (!challenge.details.map) {
msg.addField("Please select your map!", `**${challenge.challengingTeam.id === challenge.details.homeMapTeam.id ? challenge.challengedTeam.tag : challenge.challengingTeam.tag}** must still select from the home maps for this match. Please check the pinned post in this channel to see what your options are.`);
}
if (!challenge.details.teamSize) {
msg.addField("Please select the team size!", "Both teams must agree on the team size the match should be played at. This must be done before reporting the match. Use `!suggestteamsize (2|3|4|5|6|7|8)` to suggest the team size, and your opponent can use `!confirmteamsize` to confirm the suggestion, or suggest their own.");
}
msg.addField("Are you streaming this match on Twitch?", "Don't forget to use the `!streaming` command to indicate that you are streaming to Twitch! This will allow others to watch or cast this match on the website.");
await Discord.richQueue(msg, challenge.channel);
} catch (err) {
throw new Exception("There was a critical Discord error notifying a match starting for a challenge. Please resolve this manually as soon as possible.", err);
}
challenge.setNotifyMatchStarting();
} | static async notifyMatchStarting(challengeId) {
let challenge;
try {
challenge = await Challenge.getById(challengeId);
} catch (err) {
throw new Exception("There was an error notifying that a challenge match is about to start.", err);
}
try {
await Db.setNotifyMatchStarting(challenge);
} catch (err) {
throw new Exception("There was a database error notifying a match starting for a challenge.", err);
}
if (!challenge.channel) {
return;
}
await challenge.loadDetails();
for (const member of challenge.channel.members) {
const activity = member[1].presence.activities.find((p) => p.name === "Twitch");
if (activity && urlParse.test(activity.url)) {
const {groups: {user}} = urlParse.exec(activity.url);
await member[1].addTwitchName(user);
if (activity.state.toLowerCase() === "overload") {
const team = await member[1].getTeam();
if (team && (team.id === challenge.challengingTeam.id || team.id === challenge.challengedTeam.id)) {
await member[1].setStreamer();
}
}
}
}
try {
const msg = Discord.messageEmbed({
fields: []
});
if (Math.round((challenge.details.matchTime.getTime() - new Date().getTime()) / 300000) > 0) {
msg.setTitle(`Polish your gunships, this match begins in ${Math.round((challenge.details.matchTime.getTime() - new Date().getTime()) / 300000) * 5} minutes!`);
} else {
msg.setTitle("Polish your gunships, this match begins NOW!");
}
if (!challenge.details.map) {
msg.addField("Please select your map!", `**${challenge.challengingTeam.id === challenge.details.homeMapTeam.id ? challenge.challengedTeam.tag : challenge.challengingTeam.tag}** must still select from the home maps for this match. Please check the pinned post in this channel to see what your options are.`);
}
if (!challenge.details.teamSize) {
msg.addField("Please select the team size!", "Both teams must agree on the team size the match should be played at. This must be done before reporting the match. Use `!suggestteamsize (2|3|4|5|6|7|8)` to suggest the team size, and your opponent can use `!confirmteamsize` to confirm the suggestion, or suggest their own.");
}
msg.addField("Are you streaming this match on Twitch?", "Don't forget to use the `!streaming` command to indicate that you are streaming to Twitch! This will allow others to watch or cast this match on the website.");
await Discord.richQueue(msg, challenge.channel);
} catch (err) {
throw new Exception("There was a critical Discord error notifying a match starting for a challenge. Please resolve this manually as soon as possible.", err);
}
challenge.setNotifyMatchStarting();
} |
JavaScript | async pickMap(number) {
if (!this.details) {
await this.loadDetails();
}
try {
this.details.map = await Db.pickMap(this, number);
} catch (err) {
throw new Exception("There was a database error picking a map for a challenge.", err);
}
try {
await Discord.queue(`The map for this match has been set to **${this.details.map}**.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error picking a map for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async pickMap(number) {
if (!this.details) {
await this.loadDetails();
}
try {
this.details.map = await Db.pickMap(this, number);
} catch (err) {
throw new Exception("There was a database error picking a map for a challenge.", err);
}
try {
await Discord.queue(`The map for this match has been set to **${this.details.map}**.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error picking a map for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async removeStat(pilot) {
try {
await Db.removeStat(this, pilot);
} catch (err) {
throw new Exception("There was a database error removing a stat from a challenge.", err);
}
await Discord.queue(`Removed stats for ${pilot}.`, this.channel);
} | async removeStat(pilot) {
try {
await Db.removeStat(this, pilot);
} catch (err) {
throw new Exception("There was a database error removing a stat from a challenge.", err);
}
await Discord.queue(`Removed stats for ${pilot}.`, this.channel);
} |
JavaScript | async removeStreamer(member) {
try {
await Db.removeStreamer(this, member);
} catch (err) {
throw new Exception("There was a database error removing a pilot as a streamer for a challenge.", err);
}
try {
await Discord.queue(`${member} is no longer streaming this match.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error removing a pilot as a streamer for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async removeStreamer(member) {
try {
await Db.removeStreamer(this, member);
} catch (err) {
throw new Exception("There was a database error removing a pilot as a streamer for a challenge.", err);
}
try {
await Discord.queue(`${member} is no longer streaming this match.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error removing a pilot as a streamer for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async reportMatch(losingTeam, winningScore, losingScore, displayNotice) {
if (!this.details) {
await this.loadDetails();
}
const winningTeam = losingTeam.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam;
try {
this.details.dateReported = await Db.report(this, losingTeam, losingTeam.id === this.challengingTeam.id ? losingScore : winningScore, losingTeam.id === this.challengingTeam.id ? winningScore : losingScore);
} catch (err) {
throw new Exception("There was a database error reporting a challenge.", err);
}
this.details.reportingTeam = losingTeam;
this.details.challengingTeamScore = losingTeam.id === this.challengingTeam.id ? losingScore : winningScore;
this.details.challengedTeamScore = losingTeam.id === this.challengingTeam.id ? winningScore : losingScore;
try {
if (winningScore === losingScore) {
await Discord.queue(`This match has been reported as a **tie**, **${winningScore}** to **${losingScore}**. If this is correct, **${winningTeam.name}** needs to \`!confirm\` the result. If this was reported in error, the losing team may correct this by re-issuing the \`!report\` command with the correct score.`, this.channel);
} else {
await Discord.richQueue(Discord.messageEmbed({
description: `This match has been reported as a win for **${winningTeam.name}** by the score of **${winningScore}** to **${losingScore}**. If this is correct, **${losingTeam.id === this.challengingTeam.id ? this.challengedTeam.name : this.challengingTeam.name}** needs to \`!confirm\` the result. If this was reported in error, the losing team may correct this by re-issuing the \`!report\` command with the correct score.`,
color: winningTeam.role.color
}), this.channel);
}
if (displayNotice) {
await Discord.queue("If there are multiple games to include in this report, continue to `!report` more tracker URLs. You may `!report 0 0` in order to reset the stats and restart the reporting process.", this.channel);
}
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error reporting a challenge. Please resolve this manually as soon as possible.", err);
}
} | async reportMatch(losingTeam, winningScore, losingScore, displayNotice) {
if (!this.details) {
await this.loadDetails();
}
const winningTeam = losingTeam.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam;
try {
this.details.dateReported = await Db.report(this, losingTeam, losingTeam.id === this.challengingTeam.id ? losingScore : winningScore, losingTeam.id === this.challengingTeam.id ? winningScore : losingScore);
} catch (err) {
throw new Exception("There was a database error reporting a challenge.", err);
}
this.details.reportingTeam = losingTeam;
this.details.challengingTeamScore = losingTeam.id === this.challengingTeam.id ? losingScore : winningScore;
this.details.challengedTeamScore = losingTeam.id === this.challengingTeam.id ? winningScore : losingScore;
try {
if (winningScore === losingScore) {
await Discord.queue(`This match has been reported as a **tie**, **${winningScore}** to **${losingScore}**. If this is correct, **${winningTeam.name}** needs to \`!confirm\` the result. If this was reported in error, the losing team may correct this by re-issuing the \`!report\` command with the correct score.`, this.channel);
} else {
await Discord.richQueue(Discord.messageEmbed({
description: `This match has been reported as a win for **${winningTeam.name}** by the score of **${winningScore}** to **${losingScore}**. If this is correct, **${losingTeam.id === this.challengingTeam.id ? this.challengedTeam.name : this.challengingTeam.name}** needs to \`!confirm\` the result. If this was reported in error, the losing team may correct this by re-issuing the \`!report\` command with the correct score.`,
color: winningTeam.role.color
}), this.channel);
}
if (displayNotice) {
await Discord.queue("If there are multiple games to include in this report, continue to `!report` more tracker URLs. You may `!report 0 0` in order to reset the stats and restart the reporting process.", this.channel);
}
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error reporting a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async requestRematch(team) {
try {
await Db.requestRematch(this, team);
} catch (err) {
throw new Exception("There was a database error requesting a rematch.", err);
}
await Discord.queue(`**${team.name}** is requesting a rematch! **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, do you accept? The match will be scheduled immediately. Use the \`!rematch\` command, and the new challenge will be created!`, this.channel);
} | async requestRematch(team) {
try {
await Db.requestRematch(this, team);
} catch (err) {
throw new Exception("There was a database error requesting a rematch.", err);
}
await Discord.queue(`**${team.name}** is requesting a rematch! **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, do you accept? The match will be scheduled immediately. Use the \`!rematch\` command, and the new challenge will be created!`, this.channel);
} |
JavaScript | async suggestGameType(team, gameType) {
if (!this.details) {
await this.loadDetails();
}
const homes = await this.getHomeMaps(Challenge.getGameTypeForHomes(gameType, this.details.teamSize));
if (!homes || homes.length < 5) {
Discord.queue(`${this.details.homeMapTeam.name} does not have enough home maps set up for this game type and team size. Try lowering the team size with \`!suggestteamsize\` and try again.`, this.channel);
return;
}
try {
await Db.suggestGameType(this, team, gameType);
} catch (err) {
throw new Exception("There was a database error suggesting a game type for a challenge.", err);
}
this.details.suggestedGameType = gameType;
this.details.suggestedGameTypeTeam = team;
try {
await Discord.queue(`**${team.name}** is suggesting to play **${Challenge.getGameTypeName(gameType)}**. **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, use \`!confirmtype\` to agree to this suggestion.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error suggesting a game type for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async suggestGameType(team, gameType) {
if (!this.details) {
await this.loadDetails();
}
const homes = await this.getHomeMaps(Challenge.getGameTypeForHomes(gameType, this.details.teamSize));
if (!homes || homes.length < 5) {
Discord.queue(`${this.details.homeMapTeam.name} does not have enough home maps set up for this game type and team size. Try lowering the team size with \`!suggestteamsize\` and try again.`, this.channel);
return;
}
try {
await Db.suggestGameType(this, team, gameType);
} catch (err) {
throw new Exception("There was a database error suggesting a game type for a challenge.", err);
}
this.details.suggestedGameType = gameType;
this.details.suggestedGameTypeTeam = team;
try {
await Discord.queue(`**${team.name}** is suggesting to play **${Challenge.getGameTypeName(gameType)}**. **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, use \`!confirmtype\` to agree to this suggestion.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error suggesting a game type for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async suggestTeamSize(team, size) {
if (!this.details) {
await this.loadDetails();
}
const homes = await this.getHomeMaps(Challenge.getGameTypeForHomes(this.details.gameType, size));
if (!homes || homes.length < 5) {
Discord.queue(`${this.details.homeMapTeam.name} does not have enough home maps set up for this team size.`, this.channel);
return;
}
try {
await Db.suggestTeamSize(this, team, size);
} catch (err) {
throw new Exception("There was a database error suggesting a team size for a challenge.", err);
}
this.details.suggestedTeamSize = size;
this.details.suggestedTeamSizeTeam = team;
try {
await Discord.queue(`**${team.name}** is suggesting to play a **${size}v${size}**. **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, use \`!confirmteamsize\` to agree to this suggestion.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error suggesting a team size for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async suggestTeamSize(team, size) {
if (!this.details) {
await this.loadDetails();
}
const homes = await this.getHomeMaps(Challenge.getGameTypeForHomes(this.details.gameType, size));
if (!homes || homes.length < 5) {
Discord.queue(`${this.details.homeMapTeam.name} does not have enough home maps set up for this team size.`, this.channel);
return;
}
try {
await Db.suggestTeamSize(this, team, size);
} catch (err) {
throw new Exception("There was a database error suggesting a team size for a challenge.", err);
}
this.details.suggestedTeamSize = size;
this.details.suggestedTeamSizeTeam = team;
try {
await Discord.queue(`**${team.name}** is suggesting to play a **${size}v${size}**. **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, use \`!confirmteamsize\` to agree to this suggestion.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error suggesting a team size for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async suggestTime(team, date) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.suggestTime(this, team, date);
} catch (err) {
throw new Exception("There was a database error suggesting a time for a challenge.", err);
}
this.details.suggestedTime = date;
this.details.suggestedTimeTeam = team;
try {
const times = {};
for (const member of this.channel.members.values()) {
const timezone = await member.getTimezone(),
yearWithTimezone = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, year: "numeric", timeZoneName: "long"});
if (timezoneParse.test(yearWithTimezone)) {
const {groups: {timezoneName}} = timezoneParse.exec(yearWithTimezone);
if (timezoneName) {
times[timezoneName] = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit"});
}
}
}
for (const challengeTeam of [this.challengingTeam, this.challengedTeam]) {
const timezone = await challengeTeam.getTimezone(),
yearWithTimezone = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, year: "numeric", timeZoneName: "long"});
if (timezoneParse.test(yearWithTimezone)) {
const {groups: {timezoneName}} = timezoneParse.exec(yearWithTimezone);
if (timezoneName) {
times[timezoneName] = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit"});
}
}
}
const sortedTimes = Object.keys(times).map((tz) => ({timezone: tz, displayTime: times[tz], value: new Date(times[tz])})).sort((a, b) => {
if (a.value.getTime() !== b.value.getTime()) {
return b.value.getTime() - a.value.getTime();
}
return a.timezone.localeCompare(b.timezone);
});
await Discord.richQueue(Discord.messageEmbed({
description: `**${team.name}** is suggesting to play the match at the time listed below. **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, use \`!confirmtime\` to agree to this suggestion.`,
fields: sortedTimes.map((t) => ({name: t.timezone, value: t.displayTime}))
}), this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error suggesting a time for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async suggestTime(team, date) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.suggestTime(this, team, date);
} catch (err) {
throw new Exception("There was a database error suggesting a time for a challenge.", err);
}
this.details.suggestedTime = date;
this.details.suggestedTimeTeam = team;
try {
const times = {};
for (const member of this.channel.members.values()) {
const timezone = await member.getTimezone(),
yearWithTimezone = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, year: "numeric", timeZoneName: "long"});
if (timezoneParse.test(yearWithTimezone)) {
const {groups: {timezoneName}} = timezoneParse.exec(yearWithTimezone);
if (timezoneName) {
times[timezoneName] = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit"});
}
}
}
for (const challengeTeam of [this.challengingTeam, this.challengedTeam]) {
const timezone = await challengeTeam.getTimezone(),
yearWithTimezone = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, year: "numeric", timeZoneName: "long"});
if (timezoneParse.test(yearWithTimezone)) {
const {groups: {timezoneName}} = timezoneParse.exec(yearWithTimezone);
if (timezoneName) {
times[timezoneName] = this.details.suggestedTime.toLocaleString("en-US", {timeZone: timezone, weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit"});
}
}
}
const sortedTimes = Object.keys(times).map((tz) => ({timezone: tz, displayTime: times[tz], value: new Date(times[tz])})).sort((a, b) => {
if (a.value.getTime() !== b.value.getTime()) {
return b.value.getTime() - a.value.getTime();
}
return a.timezone.localeCompare(b.timezone);
});
await Discord.richQueue(Discord.messageEmbed({
description: `**${team.name}** is suggesting to play the match at the time listed below. **${(team.id === this.challengingTeam.id ? this.challengedTeam : this.challengingTeam).name}**, use \`!confirmtime\` to agree to this suggestion.`,
fields: sortedTimes.map((t) => ({name: t.timezone, value: t.displayTime}))
}), this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error suggesting a time for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async swapColors() {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.swapColors(this);
} catch (err) {
throw new Exception("There was a database error changing the title for a challenge.", err);
}
try {
[this.details.blueTeam, this.details.orangeTeam] = [this.details.orangeTeam, this.details.blueTeam];
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error swapping colors for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async swapColors() {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.swapColors(this);
} catch (err) {
throw new Exception("There was a database error changing the title for a challenge.", err);
}
try {
[this.details.blueTeam, this.details.orangeTeam] = [this.details.orangeTeam, this.details.blueTeam];
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error swapping colors for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async title(title) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.setTitle(this, title);
} catch (err) {
throw new Exception("There was a database error changing the title for a challenge.", err);
}
this.details.title = title && title.length > 0 ? title : void 0;
try {
if (this.details.title) {
await Discord.queue(`The title of this match has been updated to **${title}**.`, this.channel);
} else {
await Discord.queue("The title of this match has been unset.", this.channel);
}
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error changing the title for a challenge. Please resolve this manually as soon as possible.", err);
}
} | async title(title) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.setTitle(this, title);
} catch (err) {
throw new Exception("There was a database error changing the title for a challenge.", err);
}
this.details.title = title && title.length > 0 ? title : void 0;
try {
if (this.details.title) {
await Discord.queue(`The title of this match has been updated to **${title}**.`, this.channel);
} else {
await Discord.queue("The title of this match has been unset.", this.channel);
}
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error changing the title for a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async unlock(member) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.setLock(this, false);
} catch (err) {
throw new Exception("There was a database error unlocking a challenge.", err);
}
this.details.adminCreated = false;
try {
await Discord.queue(`This challenge has been unlocked by ${member}. You may now use \`!suggestmap\` to suggest a neutral map and \`!suggesttime\` to suggest the match time.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error unlocking a challenge. Please resolve this manually as soon as possible.", err);
}
} | async unlock(member) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.setLock(this, false);
} catch (err) {
throw new Exception("There was a database error unlocking a challenge.", err);
}
this.details.adminCreated = false;
try {
await Discord.queue(`This challenge has been unlocked by ${member}. You may now use \`!suggestmap\` to suggest a neutral map and \`!suggesttime\` to suggest the match time.`, this.channel);
await this.updatePinnedPost();
} catch (err) {
throw new Exception("There was a critical Discord error unlocking a challenge. Please resolve this manually as soon as possible.", err);
}
} |
JavaScript | async unsetCaster(member) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.setCaster(this);
} catch (err) {
throw new Exception("There was a database error removing a pilot as a caster from a challenge.", err);
}
this.details.caster = void 0;
if (this.channel) {
try {
if (Discord.findGuildMemberById(member.id)) {
await this.channel.updateOverwrite(
member,
{"VIEW_CHANNEL": null},
`${member} is no longer scheduled to cast this match.`
);
}
await this.updatePinnedPost();
await Discord.queue(`${member} is no longer scheduled to cast this match.`, this.channel);
} catch (err) {
throw new Exception("There was a critical Discord error removing a pilot as a caster from a challenge. Please resolve this manually as soon as possible.", err);
}
}
} | async unsetCaster(member) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.setCaster(this);
} catch (err) {
throw new Exception("There was a database error removing a pilot as a caster from a challenge.", err);
}
this.details.caster = void 0;
if (this.channel) {
try {
if (Discord.findGuildMemberById(member.id)) {
await this.channel.updateOverwrite(
member,
{"VIEW_CHANNEL": null},
`${member} is no longer scheduled to cast this match.`
);
}
await this.updatePinnedPost();
await Discord.queue(`${member} is no longer scheduled to cast this match.`, this.channel);
} catch (err) {
throw new Exception("There was a critical Discord error removing a pilot as a caster from a challenge. Please resolve this manually as soon as possible.", err);
}
}
} |
JavaScript | async unvoid(member) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.unvoid(this);
} catch (err) {
throw new Exception("There was a database error unvoiding a challenge.", err);
}
this.details.dateVoided = void 0;
if (!this.details.dateClockDeadlineNotified) {
this.setNotifyClockExpired(this.details.dateClockDeadline);
}
if (this.details.matchTime) {
this.setNotifyMatchMissed(new Date(this.details.matchTime.getTime() + 3600000));
this.setNotifyMatchStarting(new Date(this.details.matchTime.getTime() - 1800000));
}
try {
if (this.channel) {
await Discord.queue(`${member} has unvoided this challenge.`, this.channel);
await this.updatePinnedPost();
}
if (this.details.dateConfirmed && this.details.dateClosed) {
await Discord.queue(`The following match from ${this.details.matchTime.toLocaleString("en-US", {timeZone: settings.defaultTimezone, month: "numeric", day: "numeric", year: "numeric"})} was restored: **${this.challengingTeam.name}** ${this.details.challengingTeamScore}, **${this.challengedTeam.name}** ${this.details.challengedTeamScore}`, Discord.matchResultsChannel);
}
} catch (err) {
throw new Exception("There was a critical Discord error unvoiding a challenge. Please resolve this manually as soon as possible.", err);
}
if (this.details.dateClosed) {
await Team.updateRatingsForSeasonFromChallenge(this);
}
} | async unvoid(member) {
if (!this.details) {
await this.loadDetails();
}
try {
await Db.unvoid(this);
} catch (err) {
throw new Exception("There was a database error unvoiding a challenge.", err);
}
this.details.dateVoided = void 0;
if (!this.details.dateClockDeadlineNotified) {
this.setNotifyClockExpired(this.details.dateClockDeadline);
}
if (this.details.matchTime) {
this.setNotifyMatchMissed(new Date(this.details.matchTime.getTime() + 3600000));
this.setNotifyMatchStarting(new Date(this.details.matchTime.getTime() - 1800000));
}
try {
if (this.channel) {
await Discord.queue(`${member} has unvoided this challenge.`, this.channel);
await this.updatePinnedPost();
}
if (this.details.dateConfirmed && this.details.dateClosed) {
await Discord.queue(`The following match from ${this.details.matchTime.toLocaleString("en-US", {timeZone: settings.defaultTimezone, month: "numeric", day: "numeric", year: "numeric"})} was restored: **${this.challengingTeam.name}** ${this.details.challengingTeamScore}, **${this.challengedTeam.name}** ${this.details.challengedTeamScore}`, Discord.matchResultsChannel);
}
} catch (err) {
throw new Exception("There was a critical Discord error unvoiding a challenge. Please resolve this manually as soon as possible.", err);
}
if (this.details.dateClosed) {
await Team.updateRatingsForSeasonFromChallenge(this);
}
} |
JavaScript | static async invalidate(invalidationLists) {
try {
const client = await Redis.login(),
keys = [];
for (const list of invalidationLists) {
keys.push(list);
const items = await client.smembers(list);
if (items) {
keys.push(...items);
}
}
await client.del(...keys);
client.disconnect();
} catch (err) {
Log.warning(`Redis error on invalidate: ${err.message}`);
}
} | static async invalidate(invalidationLists) {
try {
const client = await Redis.login(),
keys = [];
for (const list of invalidationLists) {
keys.push(list);
const items = await client.smembers(list);
if (items) {
keys.push(...items);
}
}
await client.del(...keys);
client.disconnect();
} catch (err) {
Log.warning(`Redis error on invalidate: ${err.message}`);
}
} |
JavaScript | static async addCaptain(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblRoster SET Captain = 1 WHERE PlayerId = @playerId AND TeamId = @teamId
MERGE tblCaptainHistory ch
USING (VALUES (@teamId, @playerId)) AS v (TeamId, PlayerId)
ON ch.TeamId = v.TeamId AND ch.PlayerId = v.PlayerId
WHEN NOT MATCHED THEN
INSERT (TeamId, PlayerId) VALUES (v.TeamId, v.PlayerId);
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
} | static async addCaptain(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblRoster SET Captain = 1 WHERE PlayerId = @playerId AND TeamId = @teamId
MERGE tblCaptainHistory ch
USING (VALUES (@teamId, @playerId)) AS v (TeamId, PlayerId)
ON ch.TeamId = v.TeamId AND ch.PlayerId = v.PlayerId
WHEN NOT MATCHED THEN
INSERT (TeamId, PlayerId) VALUES (v.TeamId, v.PlayerId);
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
} |
JavaScript | static async addPilot(member, team) {
/** @type {TeamDbTypes.AddPilotRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
IF @playerId IS NULL
BEGIN
INSERT INTO tblPlayer (DiscordId, Name)
VALUES (@discordId, @name)
SET @playerId = SCOPE_IDENTITY()
END
INSERT INTO tblRoster (TeamId, PlayerId) VALUES (@teamId, @playerId)
DELETE FROM tblRequest WHERE PlayerId = @playerId
DELETE FROM tblInvite WHERE PlayerId = @playerId
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
INSERT INTO tblJoinBan (PlayerId) VALUES (@playerId)
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
SELECT @playerId PlayerId
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
name: {type: Db.VARCHAR(64), value: member.displayName},
teamId: {type: Db.INT, value: team.id}
});
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
} | static async addPilot(member, team) {
/** @type {TeamDbTypes.AddPilotRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
IF @playerId IS NULL
BEGIN
INSERT INTO tblPlayer (DiscordId, Name)
VALUES (@discordId, @name)
SET @playerId = SCOPE_IDENTITY()
END
INSERT INTO tblRoster (TeamId, PlayerId) VALUES (@teamId, @playerId)
DELETE FROM tblRequest WHERE PlayerId = @playerId
DELETE FROM tblInvite WHERE PlayerId = @playerId
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
INSERT INTO tblJoinBan (PlayerId) VALUES (@playerId)
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
SELECT @playerId PlayerId
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
name: {type: Db.VARCHAR(64), value: member.displayName},
teamId: {type: Db.INT, value: team.id}
});
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
} |
JavaScript | static async create(newTeam) {
/** @type {TeamDbTypes.CreateRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
DECLARE @teamId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
INSERT INTO tblTeam (Name, Tag) VALUES (@name, @tag)
SET @teamId = SCOPE_IDENTITY()
INSERT INTO tblRoster (TeamId, PlayerId, Founder) VALUES (@teamId, @playerId, 1)
MERGE tblCaptainHistory ch
USING (VALUES (@teamId, @playerId)) AS v (TeamId, PlayerId)
ON ch.TeamId = v.TeamId AND ch.PlayerId = v.PlayerId
WHEN NOT MATCHED THEN
INSERT (TeamId, PlayerId) VALUES (v.TeamId, v.PlayerId);
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
INSERT INTO tblJoinBan (PlayerId) VALUES (@playerId)
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblNewTeam WHERE NewTeamId = @newTeamId
SELECT @teamId TeamId, @playerId PlayerId
`, {
discordId: {type: Db.VARCHAR(24), value: newTeam.member.id},
name: {type: Db.VARCHAR(25), value: newTeam.name},
tag: {type: Db.VARCHAR(5), value: newTeam.tag},
newTeamId: {type: Db.INT, value: newTeam.id}
});
const teamId = data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].TeamId || void 0;
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
return teamId ? {member: newTeam.member, id: teamId, name: newTeam.name, tag: newTeam.tag, isFounder: true, disbanded: false, locked: false} : void 0;
} | static async create(newTeam) {
/** @type {TeamDbTypes.CreateRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
DECLARE @teamId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
INSERT INTO tblTeam (Name, Tag) VALUES (@name, @tag)
SET @teamId = SCOPE_IDENTITY()
INSERT INTO tblRoster (TeamId, PlayerId, Founder) VALUES (@teamId, @playerId, 1)
MERGE tblCaptainHistory ch
USING (VALUES (@teamId, @playerId)) AS v (TeamId, PlayerId)
ON ch.TeamId = v.TeamId AND ch.PlayerId = v.PlayerId
WHEN NOT MATCHED THEN
INSERT (TeamId, PlayerId) VALUES (v.TeamId, v.PlayerId);
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
INSERT INTO tblJoinBan (PlayerId) VALUES (@playerId)
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblNewTeam WHERE NewTeamId = @newTeamId
SELECT @teamId TeamId, @playerId PlayerId
`, {
discordId: {type: Db.VARCHAR(24), value: newTeam.member.id},
name: {type: Db.VARCHAR(25), value: newTeam.name},
tag: {type: Db.VARCHAR(5), value: newTeam.tag},
newTeamId: {type: Db.INT, value: newTeam.id}
});
const teamId = data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].TeamId || void 0;
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
return teamId ? {member: newTeam.member, id: teamId, name: newTeam.name, tag: newTeam.tag, isFounder: true, disbanded: false, locked: false} : void 0;
} |
JavaScript | static async disband(team) {
/** @type {TeamDbTypes.DisbandRecordsets} */
const data = await db.query(/* sql */`
UPDATE tblTeam SET Disbanded = 1 WHERE TeamId = @teamId
DELETE FROM cs
FROM tblChallengeStreamer cs
INNER JOIN tblChallenge c ON cs.ChallengeId = c.ChallengeId
WHERE c.DateConfirmed IS NULL
AND c.DateVoided IS NULL
AND cs.PlayerId IN (SELECT PlayerId FROM tblRoster WHERE TeamId = @teamId)
DELETE FROM tb
FROM tblTeamBan tb
INNER JOIN tblRoster r
ON tb.TeamId = r.TeamId
AND tb.PlayerId = r.PlayerId
WHERE r.TeamId = @teamId
AND Founder = 1
INSERT INTO tblTeamBan (TeamId, PlayerId)
SELECT @teamId, PlayerId
FROM tblRoster
WHERE TeamId = @teamId
AND Founder = 1
SELECT PlayerId FROM tblRoster WHERE TeamId = @teamId
DELETE FROM tblRoster WHERE TeamId = @teamId
DELETE FROM tblRequest WHERE TeamId = @teamId
DELETE FROM tblInvite WHERE TeamId = @teamId
SELECT ChallengeId
FROM tblChallenge
WHERE (ChallengingTeamId = @teamId OR ChallengedTeamId = @teamId)
AND DateConfirmed IS NULL
AND DateClosed IS NULL
AND DateVoided IS NULL
`, {teamId: {type: Db.INT, value: team.id}});
if (data && data.recordsets && data.recordsets[1]) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`].concat(data.recordsets[1].map((row) => `${settings.redisPrefix}:invalidate:player:${row.PlayerId}:updated`)));
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
return data && data.recordsets && data.recordsets[0] && data.recordsets[0].map((row) => row.ChallengeId) || [];
} | static async disband(team) {
/** @type {TeamDbTypes.DisbandRecordsets} */
const data = await db.query(/* sql */`
UPDATE tblTeam SET Disbanded = 1 WHERE TeamId = @teamId
DELETE FROM cs
FROM tblChallengeStreamer cs
INNER JOIN tblChallenge c ON cs.ChallengeId = c.ChallengeId
WHERE c.DateConfirmed IS NULL
AND c.DateVoided IS NULL
AND cs.PlayerId IN (SELECT PlayerId FROM tblRoster WHERE TeamId = @teamId)
DELETE FROM tb
FROM tblTeamBan tb
INNER JOIN tblRoster r
ON tb.TeamId = r.TeamId
AND tb.PlayerId = r.PlayerId
WHERE r.TeamId = @teamId
AND Founder = 1
INSERT INTO tblTeamBan (TeamId, PlayerId)
SELECT @teamId, PlayerId
FROM tblRoster
WHERE TeamId = @teamId
AND Founder = 1
SELECT PlayerId FROM tblRoster WHERE TeamId = @teamId
DELETE FROM tblRoster WHERE TeamId = @teamId
DELETE FROM tblRequest WHERE TeamId = @teamId
DELETE FROM tblInvite WHERE TeamId = @teamId
SELECT ChallengeId
FROM tblChallenge
WHERE (ChallengingTeamId = @teamId OR ChallengedTeamId = @teamId)
AND DateConfirmed IS NULL
AND DateClosed IS NULL
AND DateVoided IS NULL
`, {teamId: {type: Db.INT, value: team.id}});
if (data && data.recordsets && data.recordsets[1]) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`].concat(data.recordsets[1].map((row) => `${settings.redisPrefix}:invalidate:player:${row.PlayerId}:updated`)));
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
return data && data.recordsets && data.recordsets[0] && data.recordsets[0].map((row) => row.ChallengeId) || [];
} |
JavaScript | static async hasClockedTeamThisSeason(team1, team2) {
/** @type {TeamDbTypes.HasClockedTeamThisSeasonRecordsets} */
const data = await db.query(/* sql */`
SELECT CAST(CASE WHEN COUNT(ChallengeId) > 0 THEN 1 ELSE 0 END AS BIT) HasClocked
FROM tblChallenge
WHERE ClockTeamId = @team1Id
AND (ChallengingTeamId = @team2Id OR ChallengedTeamId = @team2Id)
AND DateVoided IS NULL
AND DateClocked IS NOT NULL
AND DateClocked >= CAST(CAST(((MONTH(GETUTCDATE()) - 1) / 6) * 6 + 1 AS VARCHAR) + '/1/' + CAST(YEAR(GETUTCDATE()) AS VARCHAR) AS DATETIME)
`, {
team1Id: {type: Db.INT, value: team1.id},
team2Id: {type: Db.INT, value: team2.id}
});
return data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].HasClocked || false;
} | static async hasClockedTeamThisSeason(team1, team2) {
/** @type {TeamDbTypes.HasClockedTeamThisSeasonRecordsets} */
const data = await db.query(/* sql */`
SELECT CAST(CASE WHEN COUNT(ChallengeId) > 0 THEN 1 ELSE 0 END AS BIT) HasClocked
FROM tblChallenge
WHERE ClockTeamId = @team1Id
AND (ChallengingTeamId = @team2Id OR ChallengedTeamId = @team2Id)
AND DateVoided IS NULL
AND DateClocked IS NOT NULL
AND DateClocked >= CAST(CAST(((MONTH(GETUTCDATE()) - 1) / 6) * 6 + 1 AS VARCHAR) + '/1/' + CAST(YEAR(GETUTCDATE()) AS VARCHAR) AS DATETIME)
`, {
team1Id: {type: Db.INT, value: team1.id},
team2Id: {type: Db.INT, value: team2.id}
});
return data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].HasClocked || false;
} |
JavaScript | static async invitePilot(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
IF @playerId IS NULL
BEGIN
INSERT INTO tblPlayer (DiscordId, Name)
VALUES (@discordId, @name)
SET @playerId = SCOPE_IDENTITY()
END
DELETE FROM tblRequest WHERE TeamId = @teamId AND PlayerId = @playerId
INSERT INTO tblInvite (TeamId, PlayerId) VALUES (@teamId, @playerId)
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
name: {type: Db.VARCHAR(64), value: member.displayName},
teamId: {type: Db.INT, value: team.id}
});
} | static async invitePilot(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
IF @playerId IS NULL
BEGIN
INSERT INTO tblPlayer (DiscordId, Name)
VALUES (@discordId, @name)
SET @playerId = SCOPE_IDENTITY()
END
DELETE FROM tblRequest WHERE TeamId = @teamId AND PlayerId = @playerId
INSERT INTO tblInvite (TeamId, PlayerId) VALUES (@teamId, @playerId)
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
name: {type: Db.VARCHAR(64), value: member.displayName},
teamId: {type: Db.INT, value: team.id}
});
} |
JavaScript | static async makeFounder(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblRoster SET Founder = 0, Captain = 1 WHERE TeamId = @teamId AND Founder = 1
UPDATE tblRoster SET Founder = 1, Captain = 0 WHERE TeamId = @teamId AND PlayerId = @playerId
MERGE tblCaptainHistory ch
USING (VALUES (@teamId, @playerId)) AS v (TeamId, PlayerId)
ON ch.TeamId = v.TeamId AND ch.PlayerId = v.PlayerId
WHEN NOT MATCHED THEN
INSERT (TeamId, PlayerId) VALUES (v.TeamId, v.PlayerId);
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
} | static async makeFounder(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblRoster SET Founder = 0, Captain = 1 WHERE TeamId = @teamId AND Founder = 1
UPDATE tblRoster SET Founder = 1, Captain = 0 WHERE TeamId = @teamId AND PlayerId = @playerId
MERGE tblCaptainHistory ch
USING (VALUES (@teamId, @playerId)) AS v (TeamId, PlayerId)
ON ch.TeamId = v.TeamId AND ch.PlayerId = v.PlayerId
WHEN NOT MATCHED THEN
INSERT (TeamId, PlayerId) VALUES (v.TeamId, v.PlayerId);
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
} |
JavaScript | static async reinstate(member, team) {
/** @type {TeamDbTypes.ReinstateRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblTeam SET Disbanded = 0 WHERE TeamId = @teamId
INSERT INTO tblRoster (TeamId, PlayerId, Founder) VALUES (@teamId, @playerId, 1)
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
INSERT INTO tblJoinBan (PlayerId) VALUES (@playerId)
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
SELECT @playerId PlayerId
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
} | static async reinstate(member, team) {
/** @type {TeamDbTypes.ReinstateRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblTeam SET Disbanded = 0 WHERE TeamId = @teamId
INSERT INTO tblRoster (TeamId, PlayerId, Founder) VALUES (@teamId, @playerId, 1)
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
INSERT INTO tblJoinBan (PlayerId) VALUES (@playerId)
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
SELECT @playerId PlayerId
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:team:status`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
} |
JavaScript | static async removeCaptain(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblRoster SET Captain = 0 WHERE PlayerId = @playerId AND TeamId = @teamId
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
} | static async removeCaptain(team, member) {
await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
UPDATE tblRoster SET Captain = 0 WHERE PlayerId = @playerId AND TeamId = @teamId
`, {
discordId: {type: Db.VARCHAR(24), value: member.id},
teamId: {type: Db.INT, value: team.id}
});
} |
JavaScript | static async removeNeutralMap(team, gameType, map) {
await db.query(/* sql */`
DELETE FROM tblTeamNeutral WHERE TeamId = @teamId AND Map = @map AND GameType = @gameType
`, {
teamId: {type: Db.INT, value: team.id},
map: {type: Db.VARCHAR(100), value: map},
gameType: {type: Db.VARCHAR(5), value: gameType}
});
} | static async removeNeutralMap(team, gameType, map) {
await db.query(/* sql */`
DELETE FROM tblTeamNeutral WHERE TeamId = @teamId AND Map = @map AND GameType = @gameType
`, {
teamId: {type: Db.INT, value: team.id},
map: {type: Db.VARCHAR(100), value: map},
gameType: {type: Db.VARCHAR(5), value: gameType}
});
} |
JavaScript | static async removePilot(member, team) {
/** @type {TeamDbTypes.RemovePilotRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
IF EXISTS(SELECT TOP 1 1 FROM tblRoster WHERE TeamId = @teamId AND PlayerId = @playerId)
BEGIN
DELETE FROM cs
FROM tblChallengeStreamer cs
INNER JOIN tblChallenge c ON cs.ChallengeId = c.ChallengeId
WHERE c.DateConfirmed IS NULL
AND c.DateVoided IS NULL
AND cs.PlayerId = @playerId
IF EXISTS (
SELECT TOP 1 1
FROM tblStat s
INNER JOIN tblChallenge c ON s.ChallengeId = c.ChallengeId
INNER JOIN tblRoster r ON s.PlayerId = r.PlayerId
WHERE s.PlayerId = @playerId
AND CAST(c.MatchTime AS DATE) >= CAST(r.DateAdded AS DATE)
)
BEGIN
DELETE FROM tblRoster WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
INSERT INTO tblTeamBan (TeamId, PlayerId) VALUES (@teamId, @playerId)
END
ELSE
BEGIN
DELETE FROM tblRoster WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
END
END
DELETE FROM tblChallengeStreamer WHERE PlayerId = @playerId
DELETE FROM tblRequest WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblInvite WHERE TeamId = @teamId AND PlayerId = @playerId
SELECT @playerId PlayerId
`, {
teamId: {type: Db.INT, value: team.id},
discordId: {type: Db.VARCHAR(24), value: member.id}
});
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
} | static async removePilot(member, team) {
/** @type {TeamDbTypes.RemovePilotRecordsets} */
const data = await db.query(/* sql */`
DECLARE @playerId INT
SELECT @playerId = PlayerId FROM tblPlayer WHERE DiscordId = @discordId
IF EXISTS(SELECT TOP 1 1 FROM tblRoster WHERE TeamId = @teamId AND PlayerId = @playerId)
BEGIN
DELETE FROM cs
FROM tblChallengeStreamer cs
INNER JOIN tblChallenge c ON cs.ChallengeId = c.ChallengeId
WHERE c.DateConfirmed IS NULL
AND c.DateVoided IS NULL
AND cs.PlayerId = @playerId
IF EXISTS (
SELECT TOP 1 1
FROM tblStat s
INNER JOIN tblChallenge c ON s.ChallengeId = c.ChallengeId
INNER JOIN tblRoster r ON s.PlayerId = r.PlayerId
WHERE s.PlayerId = @playerId
AND CAST(c.MatchTime AS DATE) >= CAST(r.DateAdded AS DATE)
)
BEGIN
DELETE FROM tblRoster WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
INSERT INTO tblTeamBan (TeamId, PlayerId) VALUES (@teamId, @playerId)
END
ELSE
BEGIN
DELETE FROM tblRoster WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblTeamBan WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblJoinBan WHERE PlayerId = @playerId
END
END
DELETE FROM tblChallengeStreamer WHERE PlayerId = @playerId
DELETE FROM tblRequest WHERE TeamId = @teamId AND PlayerId = @playerId
DELETE FROM tblInvite WHERE TeamId = @teamId AND PlayerId = @playerId
SELECT @playerId PlayerId
`, {
teamId: {type: Db.INT, value: team.id},
discordId: {type: Db.VARCHAR(24), value: member.id}
});
if (data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].PlayerId) {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`, `${settings.redisPrefix}:invalidate:player:${data.recordsets[0][0].PlayerId}:updated`]);
} else {
await Cache.invalidate([`${settings.redisPrefix}:invalidate:player:freeagents`, `${settings.redisPrefix}:invalidate:player:updated`]);
}
} |
JavaScript | static async updateRatingsForSeasonFromChallenge(challenge, ratings, challengeRatings) {
let sql = /* sql */`
DECLARE @matchTime DATETIME
DECLARE @season INT
SELECT @matchTime = MatchTime FROM tblChallenge WHERE ChallengeId = @challengeId
IF @matchTime < (SELECT TOP 1 DateStart FROM tblSeason ORDER BY Season)
BEGIN
SELECT TOP 1 @matchTime = DateStart FROM tblSeason ORDER BY Season
END
SELECT @season = Season FROM tblSeason WHERE DateStart <= @matchTime And DateEnd >= @matchTime
DELETE FROM tblTeamRating WHERE Season = @season
`;
/** @type {DbTypes.Parameters} */
let params = {
challengeId: {type: Db.INT, value: challenge.id}
};
for (const {teamId, rating, index} of Object.keys(ratings).map((r, i) => ({teamId: r, rating: ratings[r], index: i}))) {
sql = /* sql */`
${sql}
INSERT INTO tblTeamRating
(Season, TeamId, Rating)
VALUES
(@season, @team${index}Id, @rating${index})
`;
params[`team${index}id`] = {type: Db.INT, value: teamId};
params[`rating${index}`] = {type: Db.FLOAT, value: rating};
}
let hasData = false;
for (const {challengeId, challengeRating, index} of Object.keys(challengeRatings).map((r, i) => ({challengeId: +r, challengeRating: challengeRatings[+r], index: i}))) {
sql = /* sql */`
${sql}
UPDATE tblChallenge SET
ChallengingTeamRating = @challengingTeamRating${index},
ChallengedTeamRating = @challengedTeamRating${index},
RatingChange = @ratingChange${index}
WHERE ChallengeId = @challenge${index}Id
`;
params[`challengingTeamRating${index}`] = {type: Db.FLOAT, value: challengeRating.challengingTeamRating};
params[`challengedTeamRating${index}`] = {type: Db.FLOAT, value: challengeRating.challengedTeamRating};
params[`ratingChange${index}`] = {type: Db.FLOAT, value: challengeRating.change};
params[`challenge${index}Id`] = {type: Db.INT, value: challengeId};
hasData = true;
if (Object.keys(params).length > 2000) {
await db.query(sql, params);
sql = "";
params = {};
hasData = false;
}
}
if (hasData) {
await db.query(sql, params);
}
await Cache.invalidate([`${settings.redisPrefix}:invalidate:challenge:closed`]);
} | static async updateRatingsForSeasonFromChallenge(challenge, ratings, challengeRatings) {
let sql = /* sql */`
DECLARE @matchTime DATETIME
DECLARE @season INT
SELECT @matchTime = MatchTime FROM tblChallenge WHERE ChallengeId = @challengeId
IF @matchTime < (SELECT TOP 1 DateStart FROM tblSeason ORDER BY Season)
BEGIN
SELECT TOP 1 @matchTime = DateStart FROM tblSeason ORDER BY Season
END
SELECT @season = Season FROM tblSeason WHERE DateStart <= @matchTime And DateEnd >= @matchTime
DELETE FROM tblTeamRating WHERE Season = @season
`;
/** @type {DbTypes.Parameters} */
let params = {
challengeId: {type: Db.INT, value: challenge.id}
};
for (const {teamId, rating, index} of Object.keys(ratings).map((r, i) => ({teamId: r, rating: ratings[r], index: i}))) {
sql = /* sql */`
${sql}
INSERT INTO tblTeamRating
(Season, TeamId, Rating)
VALUES
(@season, @team${index}Id, @rating${index})
`;
params[`team${index}id`] = {type: Db.INT, value: teamId};
params[`rating${index}`] = {type: Db.FLOAT, value: rating};
}
let hasData = false;
for (const {challengeId, challengeRating, index} of Object.keys(challengeRatings).map((r, i) => ({challengeId: +r, challengeRating: challengeRatings[+r], index: i}))) {
sql = /* sql */`
${sql}
UPDATE tblChallenge SET
ChallengingTeamRating = @challengingTeamRating${index},
ChallengedTeamRating = @challengedTeamRating${index},
RatingChange = @ratingChange${index}
WHERE ChallengeId = @challenge${index}Id
`;
params[`challengingTeamRating${index}`] = {type: Db.FLOAT, value: challengeRating.challengingTeamRating};
params[`challengedTeamRating${index}`] = {type: Db.FLOAT, value: challengeRating.challengedTeamRating};
params[`ratingChange${index}`] = {type: Db.FLOAT, value: challengeRating.change};
params[`challenge${index}Id`] = {type: Db.INT, value: challengeId};
hasData = true;
if (Object.keys(params).length > 2000) {
await db.query(sql, params);
sql = "";
params = {};
hasData = false;
}
}
if (hasData) {
await db.query(sql, params);
}
await Cache.invalidate([`${settings.redisPrefix}:invalidate:challenge:closed`]);
} |
JavaScript | static async cssHandler(req, res, next) {
if (!req.query.files || req.query.files === "" || typeof req.query.files !== "string") {
return next();
}
const key = `${settings.redisPrefix}:minify:${req.query.files}`;
let cache;
if (settings.minify.cache) {
cache = await Cache.get(key);
if (cache) {
res.status(200).type("css").send(cache);
return void 0;
}
}
/** @type {string[]} */
const files = req.query.files.split(",");
try {
let str = "";
try {
for (const file of files) {
const dir = path.join(__dirname, "..", "public"),
filePath = path.join(__dirname, "..", "public", file);
if (!filePath.startsWith(dir)) {
return next();
}
str = `${str}${await fs.readFile(filePath, "utf8")}`;
}
} catch (err) {
if (err.code === "ENOENT") {
return next();
}
return next(err);
}
const output = csso.minify(str);
if (settings.minify.cache) {
await Cache.add(key, output.css, new Date(new Date().getTime() + 86400000));
}
res.status(200).type("css").send(output.css);
return void 0;
} catch (err) {
return next(err);
}
} | static async cssHandler(req, res, next) {
if (!req.query.files || req.query.files === "" || typeof req.query.files !== "string") {
return next();
}
const key = `${settings.redisPrefix}:minify:${req.query.files}`;
let cache;
if (settings.minify.cache) {
cache = await Cache.get(key);
if (cache) {
res.status(200).type("css").send(cache);
return void 0;
}
}
/** @type {string[]} */
const files = req.query.files.split(",");
try {
let str = "";
try {
for (const file of files) {
const dir = path.join(__dirname, "..", "public"),
filePath = path.join(__dirname, "..", "public", file);
if (!filePath.startsWith(dir)) {
return next();
}
str = `${str}${await fs.readFile(filePath, "utf8")}`;
}
} catch (err) {
if (err.code === "ENOENT") {
return next();
}
return next(err);
}
const output = csso.minify(str);
if (settings.minify.cache) {
await Cache.add(key, output.css, new Date(new Date().getTime() + 86400000));
}
res.status(200).type("css").send(output.css);
return void 0;
} catch (err) {
return next(err);
}
} |
JavaScript | static async jsHandler(req, res, next) {
if (!req.query.files || req.query.files === "" || typeof req.query.files !== "string") {
return next();
}
const key = `${settings.redisPrefix}:minify:${req.query.files}`;
let cache;
if (settings.minify.cache) {
cache = await Cache.get(key);
if (cache) {
res.status(200).type("js").send(cache);
return void 0;
}
}
/** @type {string[]} */
const files = req.query.files.split(",");
try {
/** @type {Object<string, string>} */
let code;
try {
code = await files.reduce(async (prev, cur) => {
const obj = await prev,
dir = path.join(__dirname, "..", "public"),
filePath = path.join(__dirname, "..", "public", cur);
if (!filePath.startsWith(dir)) {
return next();
}
obj[cur] = await fs.readFile(filePath, "utf8");
return obj;
}, Promise.resolve({}));
} catch (err) {
if (err.code === "ENOENT") {
return next();
}
return next(err);
}
const output = await terser.minify(code, {nameCache});
if (settings.minify.cache) {
await Cache.add(key, output.code, new Date(new Date().getTime() + 86400000));
}
res.status(200).type("js").send(output.code);
return void 0;
} catch (err) {
return next(err);
}
} | static async jsHandler(req, res, next) {
if (!req.query.files || req.query.files === "" || typeof req.query.files !== "string") {
return next();
}
const key = `${settings.redisPrefix}:minify:${req.query.files}`;
let cache;
if (settings.minify.cache) {
cache = await Cache.get(key);
if (cache) {
res.status(200).type("js").send(cache);
return void 0;
}
}
/** @type {string[]} */
const files = req.query.files.split(",");
try {
/** @type {Object<string, string>} */
let code;
try {
code = await files.reduce(async (prev, cur) => {
const obj = await prev,
dir = path.join(__dirname, "..", "public"),
filePath = path.join(__dirname, "..", "public", cur);
if (!filePath.startsWith(dir)) {
return next();
}
obj[cur] = await fs.readFile(filePath, "utf8");
return obj;
}, Promise.resolve({}));
} catch (err) {
if (err.code === "ENOENT") {
return next();
}
return next(err);
}
const output = await terser.minify(code, {nameCache});
if (settings.minify.cache) {
await Cache.add(key, output.code, new Date(new Date().getTime() + 86400000));
}
res.status(200).type("js").send(output.code);
return void 0;
} catch (err) {
return next(err);
}
} |
JavaScript | function handlePassThroughClick(event) {
//console.log( 'pass through:', event )
var el = getForwardedTarget(event)
// IE 9+
var evt = document.createEvent('HTMLEvents')
evt.initEvent(event.type, true, false)
//console.log( ' # ', el.id, ' is dispatching ' )
el.dispatchEvent(evt)
} | function handlePassThroughClick(event) {
//console.log( 'pass through:', event )
var el = getForwardedTarget(event)
// IE 9+
var evt = document.createEvent('HTMLEvents')
evt.initEvent(event.type, true, false)
//console.log( ' # ', el.id, ' is dispatching ' )
el.dispatchEvent(evt)
} |
JavaScript | function startPoint() {
if (!_eventLooping) {
// the end of event loop has been reached, so reset things
_eventLooping = true
_kills = {}
}
} | function startPoint() {
if (!_eventLooping) {
// the end of event loop has been reached, so reset things
_eventLooping = true
_kills = {}
}
} |
JavaScript | register(name, handler) {
var G = this
if (G.debug) console.log('GestureBase.register(', name, ')')
G.eventList.push(name)
G._checkDragEnabled()
// then actually add the listener
G._elemAdd(name, handler)
} | register(name, handler) {
var G = this
if (G.debug) console.log('GestureBase.register(', name, ')')
G.eventList.push(name)
G._checkDragEnabled()
// then actually add the listener
G._elemAdd(name, handler)
} |
JavaScript | _getEventScope(event) {
//if( this.debug ) console.log( 'GestureBase._getEventScope(), event:', event );
// check for existence of changedTouches instead
//return ( Device.os == 'android' && event instanceof TouchEvent ) ? event.changedTouches[0] : event ;
return event.changedTouches ? event.changedTouches[0] : event
} | _getEventScope(event) {
//if( this.debug ) console.log( 'GestureBase._getEventScope(), event:', event );
// check for existence of changedTouches instead
//return ( Device.os == 'android' && event instanceof TouchEvent ) ? event.changedTouches[0] : event ;
return event.changedTouches ? event.changedTouches[0] : event
} |
JavaScript | _handleTouchStart(event) {
var G = this
if (G.debug) console.log('GestureBase._handleTouchStart()')
// Change the native events to listen for the rest of the system
G._cursor = 'touch'
G._start = 'start'
G._end = 'end'
G._handleDown(event)
} | _handleTouchStart(event) {
var G = this
if (G.debug) console.log('GestureBase._handleTouchStart()')
// Change the native events to listen for the rest of the system
G._cursor = 'touch'
G._start = 'start'
G._end = 'end'
G._handleDown(event)
} |
JavaScript | function FrameRateBase(fps) {
var F = this
F.pool = []
F.fps = fps
F._frameTime = Math.floor(1000 / F.fps)
F._prevTime = 0
F._startTime = 0
F._nextTime = 0
F._maxLag = 400
F._shiftLag = 30
F._paused = false
F._prevCallTime = Date.now()
F.diffTime = 0
} | function FrameRateBase(fps) {
var F = this
F.pool = []
F.fps = fps
F._frameTime = Math.floor(1000 / F.fps)
F._prevTime = 0
F._startTime = 0
F._nextTime = 0
F._maxLag = 400
F._shiftLag = 30
F._paused = false
F._prevCallTime = Date.now()
F.diffTime = 0
} |
JavaScript | createBorderTop(x,y,size, colSize, rowSize){
context.beginPath();
context.moveTo(x,y);
context.lineTo(x+size/colSize,y);
context.stroke();
} | createBorderTop(x,y,size, colSize, rowSize){
context.beginPath();
context.moveTo(x,y);
context.lineTo(x+size/colSize,y);
context.stroke();
} |
JavaScript | primMaze(){
maze.width = this.size;
maze.height = this.size;
maze.style.background = "grey";
curr.status = true;
for (let r = 0; r < this.rows; r++){
for(let c = 0; c < this.cols; c++){
let grid = this.grid;
grid[r][c].drawBorder(this.size,this.cols,this.rows);
}
}
if(!nbList.isEmpty){
let random = Math.floor(Math.random()*nbList.length);
let next = nbList[random];
let index = nbList.indexOf(next);
nbList.splice(index,1);
if(!next.status){
next.highlight(this.cols,"yellow");
let temp = next.getAdjacent();
let unvisitedNB = [];
let visitedNB = [];
for(let i = 0; i < temp.length;i++){
if(temp[i].status){
visitedNB.push(temp[i]);
} else{
unvisitedNB.push(temp[i]);
}
}
//connect cell to a random neigbouring visited cell
//add all unvisited cell to list
random = Math.floor(Math.random()*visitedNB.length);
let connected = visitedNB[random]
next.deleteBorder(connected,next);
nbList.push.apply(nbList,unvisitedNB);
//curr = next;
}
curr = next;
}else {
return;
}
requestAnimationFrame(()=>{
this.primMaze();
})
} | primMaze(){
maze.width = this.size;
maze.height = this.size;
maze.style.background = "grey";
curr.status = true;
for (let r = 0; r < this.rows; r++){
for(let c = 0; c < this.cols; c++){
let grid = this.grid;
grid[r][c].drawBorder(this.size,this.cols,this.rows);
}
}
if(!nbList.isEmpty){
let random = Math.floor(Math.random()*nbList.length);
let next = nbList[random];
let index = nbList.indexOf(next);
nbList.splice(index,1);
if(!next.status){
next.highlight(this.cols,"yellow");
let temp = next.getAdjacent();
let unvisitedNB = [];
let visitedNB = [];
for(let i = 0; i < temp.length;i++){
if(temp[i].status){
visitedNB.push(temp[i]);
} else{
unvisitedNB.push(temp[i]);
}
}
//connect cell to a random neigbouring visited cell
//add all unvisited cell to list
random = Math.floor(Math.random()*visitedNB.length);
let connected = visitedNB[random]
next.deleteBorder(connected,next);
nbList.push.apply(nbList,unvisitedNB);
//curr = next;
}
curr = next;
}else {
return;
}
requestAnimationFrame(()=>{
this.primMaze();
})
} |
JavaScript | dfsMaze(){
maze.width = this.size;
maze.height = this.size;
maze.style.background = "grey";
curr.status = true;
for (let r = 0; r < this.rows; r++){
for(let c = 0; c < this.cols; c++){
let grid = this.grid;
grid[r][c].drawBorder(this.size,this.cols,this.rows);
}
}
let next = curr.checkNB();
if(next){
next.visited = true;
this.stacks.push(curr);
curr.highlight(this.cols,"yellow");
curr.deleteBorder(curr,next);
curr = next;
//back tracking if theres no valid neighbours
} else if (this.stacks.length > 0){
let cell = this.stacks.pop();
curr = cell;
curr.highlight(this.cols,"yellow");
}
//finish drawing maze
if(this.stacks.length==0){
let x = (curr.colI * curr.gridSize) / this.cols + 1;
let y = (curr.rowI * curr.gridSize) / this.cols + 1;
// fix for initial cell not getting highlighted correctly
context.fillStyle = "#a4aba6";
context.fillRect(x+1,y+1,curr.gridSize/this.cols -5, curr.gridSize/this.cols -5);
return;
}
requestAnimationFrame(()=>{
this.dfsMaze();
})
} | dfsMaze(){
maze.width = this.size;
maze.height = this.size;
maze.style.background = "grey";
curr.status = true;
for (let r = 0; r < this.rows; r++){
for(let c = 0; c < this.cols; c++){
let grid = this.grid;
grid[r][c].drawBorder(this.size,this.cols,this.rows);
}
}
let next = curr.checkNB();
if(next){
next.visited = true;
this.stacks.push(curr);
curr.highlight(this.cols,"yellow");
curr.deleteBorder(curr,next);
curr = next;
//back tracking if theres no valid neighbours
} else if (this.stacks.length > 0){
let cell = this.stacks.pop();
curr = cell;
curr.highlight(this.cols,"yellow");
}
//finish drawing maze
if(this.stacks.length==0){
let x = (curr.colI * curr.gridSize) / this.cols + 1;
let y = (curr.rowI * curr.gridSize) / this.cols + 1;
// fix for initial cell not getting highlighted correctly
context.fillStyle = "#a4aba6";
context.fillRect(x+1,y+1,curr.gridSize/this.cols -5, curr.gridSize/this.cols -5);
return;
}
requestAnimationFrame(()=>{
this.dfsMaze();
})
} |
JavaScript | backTrackHighlight(cell){
if(cell.isStart === true){
cell.highlight(this.cols,"green");
return;
}
let previous = cell.previous;
previous.highlight(this.cols,"yellow");
requestAnimationFrame(()=>{
this.backTrackHighlight(previous);
})
} | backTrackHighlight(cell){
if(cell.isStart === true){
cell.highlight(this.cols,"green");
return;
}
let previous = cell.previous;
previous.highlight(this.cols,"yellow");
requestAnimationFrame(()=>{
this.backTrackHighlight(previous);
})
} |
JavaScript | listHighlight(list){
let cell = list.shift();
console.log(cell)
if(cell.isTarget){
this.backTrackHighlight(cell);
return;
}
if(!cell.isStart && !cell.isTarget){
cell.highlight(this.cols,"purple");
}
requestAnimationFrame(()=>{
this.listHighlight(list);
});
} | listHighlight(list){
let cell = list.shift();
console.log(cell)
if(cell.isTarget){
this.backTrackHighlight(cell);
return;
}
if(!cell.isStart && !cell.isTarget){
cell.highlight(this.cols,"purple");
}
requestAnimationFrame(()=>{
this.listHighlight(list);
});
} |
JavaScript | enqueue(element, priority)
{
// creating object from queue element
var qElement = new QElement(element, priority);
var contain = false;
// iterating through the entire
// item array to add element at the
// correct location of the Queue
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].priority > qElement.priority) {
// Once the correct location is found it is
// enqueued
this.items.splice(i, 0, qElement);
contain = true;
break;
}
}
// if the element have the highest priority
// it is added at the end of the queue
if (!contain) {
this.items.push(qElement);
}
} | enqueue(element, priority)
{
// creating object from queue element
var qElement = new QElement(element, priority);
var contain = false;
// iterating through the entire
// item array to add element at the
// correct location of the Queue
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].priority > qElement.priority) {
// Once the correct location is found it is
// enqueued
this.items.splice(i, 0, qElement);
contain = true;
break;
}
}
// if the element have the highest priority
// it is added at the end of the queue
if (!contain) {
this.items.push(qElement);
}
} |
JavaScript | contains(cell){
for(let i = 0; i< this.items.length; i++ ){
if(this.items[i].colI == cell.colI && this.items[i].rowI == cell.rowI){
return true;
}
}
return false;
} | contains(cell){
for(let i = 0; i< this.items.length; i++ ){
if(this.items[i].colI == cell.colI && this.items[i].rowI == cell.rowI){
return true;
}
}
return false;
} |
JavaScript | toggleShow(show) {
if (show) {
this.mly.on('image', this.mapillaryEventHandler_);
} else {
this.mly.off('image', this.mapillaryEventHandler_);
}
this.mapillaryElement.hidden = !show;
} | toggleShow(show) {
if (show) {
this.mly.on('image', this.mapillaryEventHandler_);
} else {
this.mly.off('image', this.mapillaryEventHandler_);
}
this.mapillaryElement.hidden = !show;
} |
JavaScript | function contextualDataComponent() {
return {
restrict: 'A',
scope: false,
controller: 'GmfContextualdataController as cdCtrl',
bindToController: {
'displayed': '=gmfContextualdataDisplayed',
'map': '<gmfContextualdataMap',
'callback': '<gmfContextualdataCallback',
},
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController} [controller] Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
},
};
} | function contextualDataComponent() {
return {
restrict: 'A',
scope: false,
controller: 'GmfContextualdataController as cdCtrl',
bindToController: {
'displayed': '=gmfContextualdataDisplayed',
'map': '<gmfContextualdataMap',
'callback': '<gmfContextualdataCallback',
},
/**
* @param {angular.IScope} scope Scope.
* @param {JQuery} element Element.
* @param {angular.IAttributes} attrs Attributes.
* @param {angular.IController} [controller] Controller.
*/
link: (scope, element, attrs, controller) => {
if (!controller) {
throw new Error('Missing controller');
}
controller.init();
},
};
} |
JavaScript | function contextualDataComponentContent(gmfContextualdatacontentTemplateUrl) {
return {
restrict: 'A',
scope: true,
templateUrl: gmfContextualdatacontentTemplateUrl,
};
} | function contextualDataComponentContent(gmfContextualdatacontentTemplateUrl) {
return {
restrict: 'A',
scope: true,
templateUrl: gmfContextualdatacontentTemplateUrl,
};
} |
JavaScript | function addToQueue(author, code) {
if(!inQueue(queue, 'author', author)) queue.push({
author: author,
code: code,
age: 0
});
} | function addToQueue(author, code) {
if(!inQueue(queue, 'author', author)) queue.push({
author: author,
code: code,
age: 0
});
} |
JavaScript | function searchQueue(queue, property, value) {
var i, len;
for(i = 0, len = queue.length; i < len; i++) {
if(queue[i][property] == value) return i;
}
} | function searchQueue(queue, property, value) {
var i, len;
for(i = 0, len = queue.length; i < len; i++) {
if(queue[i][property] == value) return i;
}
} |
JavaScript | function isBracketsBalanced(str) {
const arr1 = [];
let res = true;
const arr = str.split('');
arr.forEach((item) => {
if (item === '[') arr1.push(item);
if (item === ']' && arr1.pop() !== '[') res = false;
if (item === '{') arr1.push(item);
if (item === '}' && arr1.pop() !== '{') res = false;
if (item === '(') arr1.push(item);
if (item === ')' && arr1.pop() !== '(') res = false;
if (item === '<') arr1.push(item);
if (item === '>' && arr1.pop() !== '<') res = false;
});
return arr1.length === 0 && res;
} | function isBracketsBalanced(str) {
const arr1 = [];
let res = true;
const arr = str.split('');
arr.forEach((item) => {
if (item === '[') arr1.push(item);
if (item === ']' && arr1.pop() !== '[') res = false;
if (item === '{') arr1.push(item);
if (item === '}' && arr1.pop() !== '{') res = false;
if (item === '(') arr1.push(item);
if (item === ')' && arr1.pop() !== '(') res = false;
if (item === '<') arr1.push(item);
if (item === '>' && arr1.pop() !== '<') res = false;
});
return arr1.length === 0 && res;
} |
JavaScript | function TCPPool (client) {
var self = this
debug('create tcp pool (port %s)', client.torrentPort)
self.server = net.createServer()
self._client = client
// Temporarily store incoming connections so they can be destroyed if the server is
// closed before the connection is passed off to a Torrent.
self._pendingConns = []
self._onConnectionBound = function (conn) {
self._onConnection(conn)
}
self._onListening = function () {
self._client._onListening()
}
self._onError = function (err) {
self._client._destroy(err)
}
self.server.on('connection', self._onConnectionBound)
self.server.on('listening', self._onListening)
self.server.on('error', self._onError)
self.server.listen(client.torrentPort)
} | function TCPPool (client) {
var self = this
debug('create tcp pool (port %s)', client.torrentPort)
self.server = net.createServer()
self._client = client
// Temporarily store incoming connections so they can be destroyed if the server is
// closed before the connection is passed off to a Torrent.
self._pendingConns = []
self._onConnectionBound = function (conn) {
self._onConnection(conn)
}
self._onListening = function () {
self._client._onListening()
}
self._onError = function (err) {
self._client._destroy(err)
}
self.server.on('connection', self._onConnectionBound)
self.server.on('listening', self._onListening)
self.server.on('error', self._onError)
self.server.listen(client.torrentPort)
} |
JavaScript | function handleEvent(event, vnode)
{
var name = event.type,
tagger = vnode.tagger,
handlers = vnode.data.event;
if (handlers && handlers[name])
{
var handler = handlers[name],
value = A2(_elm_lang$core$Native_Json.run, handler.decoder, event);
if (value.ctor === 'Ok')
{
var options = handler.options;
if (options.stopPropagation)
{
event.stopPropagation();
}
if (options.preventDefault)
{
event.preventDefault();
}
tagger(value._0);
}
}
} | function handleEvent(event, vnode)
{
var name = event.type,
tagger = vnode.tagger,
handlers = vnode.data.event;
if (handlers && handlers[name])
{
var handler = handlers[name],
value = A2(_elm_lang$core$Native_Json.run, handler.decoder, event);
if (value.ctor === 'Ok')
{
var options = handler.options;
if (options.stopPropagation)
{
event.stopPropagation();
}
if (options.preventDefault)
{
event.preventDefault();
}
tagger(value._0);
}
}
} |
JavaScript | function renderHealth() {
var heart = new Image();
heart.src = 'images\\heart.png'
htx.clearRect(0, 0, htx.canvas.width, htx.canvas.height);
if (player.health === 1) {
htx.drawImage(heart, 0, 0);
} else if (player.health === 2) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
} else if (player.health === 3) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
htx.drawImage(heart, 60, 0);
} else if (player.health === 4) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
htx.drawImage(heart, 60, 0);
htx.drawImage(heart, 90, 0);
} else if (player.health === 5) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
htx.drawImage(heart, 60, 0);
htx.drawImage(heart, 90, 0);
htx.drawImage(heart, 120, 0);
}
} | function renderHealth() {
var heart = new Image();
heart.src = 'images\\heart.png'
htx.clearRect(0, 0, htx.canvas.width, htx.canvas.height);
if (player.health === 1) {
htx.drawImage(heart, 0, 0);
} else if (player.health === 2) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
} else if (player.health === 3) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
htx.drawImage(heart, 60, 0);
} else if (player.health === 4) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
htx.drawImage(heart, 60, 0);
htx.drawImage(heart, 90, 0);
} else if (player.health === 5) {
htx.drawImage(heart, 0, 0);
htx.drawImage(heart, 30, 0);
htx.drawImage(heart, 60, 0);
htx.drawImage(heart, 90, 0);
htx.drawImage(heart, 120, 0);
}
} |
JavaScript | function draw() {
//creates variables with images
var grass = new Image();
grass.src = 'images\\grass_block.png';
var dirt = new Image();
dirt.src = 'images\\dirt_block.png';
var goal = new Image();
goal.src = 'images\\podium.png'
if (ctx == null) {
return;
}
for (let y = 0; y < mapH + 1; y++) {
for (let x = 0; x < mapW; x++) {
switch (gameMap[((y * mapW) + x)]) {
//Places dirt image where there is a one in the tiling map
case 1:
ctx.drawImage(dirt, x * tileW, y * tileH);
break;
//Places grass image where there is a one in the tiling map
case 0:
ctx.drawImage(grass, x * tileH, y * tileW);
break;
//Places goal image where there is a one in the tiling map
case 3:
ctx.drawImage(goal, x * tileH, y * tileW);
}
}
}
requestAnimationFrame(draw);
} | function draw() {
//creates variables with images
var grass = new Image();
grass.src = 'images\\grass_block.png';
var dirt = new Image();
dirt.src = 'images\\dirt_block.png';
var goal = new Image();
goal.src = 'images\\podium.png'
if (ctx == null) {
return;
}
for (let y = 0; y < mapH + 1; y++) {
for (let x = 0; x < mapW; x++) {
switch (gameMap[((y * mapW) + x)]) {
//Places dirt image where there is a one in the tiling map
case 1:
ctx.drawImage(dirt, x * tileW, y * tileH);
break;
//Places grass image where there is a one in the tiling map
case 0:
ctx.drawImage(grass, x * tileH, y * tileW);
break;
//Places goal image where there is a one in the tiling map
case 3:
ctx.drawImage(goal, x * tileH, y * tileW);
}
}
}
requestAnimationFrame(draw);
} |
JavaScript | function bigNumber(big, suffixes, base) {
// if the number is a fraction keep to 2 decimal places
if ((big - Math.floor(big)) !== 0)
big = big.toFixed(2);
// If the number is smaller than the base, return the number with no suffix
if (big < base) {
return big;
}
// Finds which suffix to use
var exp = Math.floor(Math.log(big) / Math.log(base));
// Divides the number by the equivalent suffix number
var val = big / Math.pow(base, exp);
// Keeps the number to 2 decimal places and adds the suffix
return val.toFixed(2) + suffixes[exp];
} | function bigNumber(big, suffixes, base) {
// if the number is a fraction keep to 2 decimal places
if ((big - Math.floor(big)) !== 0)
big = big.toFixed(2);
// If the number is smaller than the base, return the number with no suffix
if (big < base) {
return big;
}
// Finds which suffix to use
var exp = Math.floor(Math.log(big) / Math.log(base));
// Divides the number by the equivalent suffix number
var val = big / Math.pow(base, exp);
// Keeps the number to 2 decimal places and adds the suffix
return val.toFixed(2) + suffixes[exp];
} |
JavaScript | function clearTableProblems(tableID) {
var call = '/rest/problems/summary?s=' + tableID;
// Change plus sign to use ASCII value to send it as a URL query parameter
call = sanitize(call);
// make the rest call, passing success function callback
$.post(call, function () {
refreshProblems();
});
} | function clearTableProblems(tableID) {
var call = '/rest/problems/summary?s=' + tableID;
// Change plus sign to use ASCII value to send it as a URL query parameter
call = sanitize(call);
// make the rest call, passing success function callback
$.post(call, function () {
refreshProblems();
});
} |
JavaScript | function clearDetailsProblems(table, resource, type) {
var call = '/rest/problems/details?table=' + table + '&resource=' +
resource + '&ptype=' + type;
// Changes plus sign to use ASCII value to send it as a URL query parameter
call = sanitize(call);
// make the rest call, passing success function callback
$.post(call, function () {
refreshProblems();
});
} | function clearDetailsProblems(table, resource, type) {
var call = '/rest/problems/details?table=' + table + '&resource=' +
resource + '&ptype=' + type;
// Changes plus sign to use ASCII value to send it as a URL query parameter
call = sanitize(call);
// make the rest call, passing success function callback
$.post(call, function () {
refreshProblems();
});
} |
JavaScript | function refreshOverview() {
getManager().then(function() {
refreshManagerTable();
});
var requests = [
getIngestRate(),
getScanEntries(),
getIngestByteRate(),
getQueryByteRate(),
getLoadAverage(),
getLookups(),
getMinorCompactions(),
getMajorCompactions(),
getIndexCacheHitRate(),
getDataCacheHitRate()
];
$.when(...requests).always(function() {
makePlots();
});
} | function refreshOverview() {
getManager().then(function() {
refreshManagerTable();
});
var requests = [
getIngestRate(),
getScanEntries(),
getIngestByteRate(),
getQueryByteRate(),
getLoadAverage(),
getLookups(),
getMinorCompactions(),
getMajorCompactions(),
getIndexCacheHitRate(),
getDataCacheHitRate()
];
$.when(...requests).always(function() {
makePlots();
});
} |
JavaScript | function refreshSidebar() {
getStatus().then(function() {
refreshSideBarNotifications();
});
} | function refreshSidebar() {
getStatus().then(function() {
refreshSideBarNotifications();
});
} |
JavaScript | function refreshSideBarNotifications() {
var data = sessionStorage.status === undefined ?
undefined : JSON.parse(sessionStorage.status);
// Setting individual status notification
if (data.managerStatus === 'OK') {
$('#managerStatusNotification').removeClass('error').addClass('normal');
} else {
$('#managerStatusNotification').removeClass('normal').addClass('error');
}
if (data.tServerStatus === 'OK') {
$('#serverStatusNotification').removeClass('error').removeClass('warning').
addClass('normal');
} else if (data.tServerStatus === 'WARN') {
$('#serverStatusNotification').removeClass('error').removeClass('normal').
addClass('warning');
} else {
$('#serverStatusNotification').removeClass('normal').removeClass('warning').
addClass('error');
}
if (data.gcStatus === 'OK') {
$('#gcStatusNotification').removeClass('error').addClass('normal');
} else {
$('#gcStatusNotification').addClass('error').removeClass('normal');
}
// Setting overall status notification
if (data.managerStatus === 'OK' &&
data.tServerStatus === 'OK' &&
data.gcStatus === 'OK') {
$('#statusNotification').removeClass('error').removeClass('warning').
addClass('normal');
} else if (data.managerStatus === 'ERROR' ||
data.tServerStatus === 'ERROR' ||
data.gcStatus === 'ERROR') {
$('#statusNotification').removeClass('normal').removeClass('warning').
addClass('error');
} else if (data.tServerStatus === 'WARN') {
$('#statusNotification').removeClass('normal').removeClass('error').
addClass('warning');
}
// Setting individual logs notifications
// Color
if (data.logNumber > 0) {
if (data.logsHaveError) {
$('#recentLogsNotifications').removeClass('warning').addClass('error');
} else {
$('#recentLogsNotifications').removeClass('error').addClass('warning');
}
} else {
$('#recentLogsNotifications').removeClass('error').removeClass('warning');
}
// Number
var logNumber = data.logNumber > 99 ? '99+' : data.logNumber;
$('#recentLogsNotifications').html(logNumber);
// Color
if (data.problemNumber > 0) {
$('#tableProblemsNotifications').addClass('error');
} else {
$('#tableProblemsNotifications').removeClass('error');
}
// Number
var problemNumber = data.problemNumber > 99 ? '99+' : data.problemNumber;
$('#tableProblemsNotifications').html(problemNumber);
// Setting overall logs notifications
// Color
if (data.logNumber > 0 || data.problemNumber > 0) {
if (data.logsHaveError || data.problemNumber > 0) {
$('#errorsNotification').removeClass('warning').addClass('error');
} else {
$('#errorsNotification').removeClass('error').addClass('warning');
}
} else {
$('#errorsNotification').removeClass('error').removeClass('warning');
}
// Number
var totalNumber = data.logNumber + data.problemNumber > 99 ?
'99+' : data.logNumber + data.problemNumber;
$('#errorsNotification').html(totalNumber);
} | function refreshSideBarNotifications() {
var data = sessionStorage.status === undefined ?
undefined : JSON.parse(sessionStorage.status);
// Setting individual status notification
if (data.managerStatus === 'OK') {
$('#managerStatusNotification').removeClass('error').addClass('normal');
} else {
$('#managerStatusNotification').removeClass('normal').addClass('error');
}
if (data.tServerStatus === 'OK') {
$('#serverStatusNotification').removeClass('error').removeClass('warning').
addClass('normal');
} else if (data.tServerStatus === 'WARN') {
$('#serverStatusNotification').removeClass('error').removeClass('normal').
addClass('warning');
} else {
$('#serverStatusNotification').removeClass('normal').removeClass('warning').
addClass('error');
}
if (data.gcStatus === 'OK') {
$('#gcStatusNotification').removeClass('error').addClass('normal');
} else {
$('#gcStatusNotification').addClass('error').removeClass('normal');
}
// Setting overall status notification
if (data.managerStatus === 'OK' &&
data.tServerStatus === 'OK' &&
data.gcStatus === 'OK') {
$('#statusNotification').removeClass('error').removeClass('warning').
addClass('normal');
} else if (data.managerStatus === 'ERROR' ||
data.tServerStatus === 'ERROR' ||
data.gcStatus === 'ERROR') {
$('#statusNotification').removeClass('normal').removeClass('warning').
addClass('error');
} else if (data.tServerStatus === 'WARN') {
$('#statusNotification').removeClass('normal').removeClass('error').
addClass('warning');
}
// Setting individual logs notifications
// Color
if (data.logNumber > 0) {
if (data.logsHaveError) {
$('#recentLogsNotifications').removeClass('warning').addClass('error');
} else {
$('#recentLogsNotifications').removeClass('error').addClass('warning');
}
} else {
$('#recentLogsNotifications').removeClass('error').removeClass('warning');
}
// Number
var logNumber = data.logNumber > 99 ? '99+' : data.logNumber;
$('#recentLogsNotifications').html(logNumber);
// Color
if (data.problemNumber > 0) {
$('#tableProblemsNotifications').addClass('error');
} else {
$('#tableProblemsNotifications').removeClass('error');
}
// Number
var problemNumber = data.problemNumber > 99 ? '99+' : data.problemNumber;
$('#tableProblemsNotifications').html(problemNumber);
// Setting overall logs notifications
// Color
if (data.logNumber > 0 || data.problemNumber > 0) {
if (data.logsHaveError || data.problemNumber > 0) {
$('#errorsNotification').removeClass('warning').addClass('error');
} else {
$('#errorsNotification').removeClass('error').addClass('warning');
}
} else {
$('#errorsNotification').removeClass('error').removeClass('warning');
}
// Number
var totalNumber = data.logNumber + data.problemNumber > 99 ?
'99+' : data.logNumber + data.problemNumber;
$('#errorsNotification').html(totalNumber);
} |
JavaScript | render () {
const { managedPaths } = this.props.configContext;
return (
<div>
<h1>Managed Paths</h1>
<ol>
{managedPaths.map((path) => (
<li key={path}>
<span>{path}</span>
<button
type="button"
onClick={() => this.handleRemoveButtonClick(path)}
>
Remove
</button>
</li>
))}
</ol>
<button
type="button"
onClick={this.handleAddButtonClick}
>
Add
</button>
</div>
);
} | render () {
const { managedPaths } = this.props.configContext;
return (
<div>
<h1>Managed Paths</h1>
<ol>
{managedPaths.map((path) => (
<li key={path}>
<span>{path}</span>
<button
type="button"
onClick={() => this.handleRemoveButtonClick(path)}
>
Remove
</button>
</li>
))}
</ol>
<button
type="button"
onClick={this.handleAddButtonClick}
>
Add
</button>
</div>
);
} |
JavaScript | render () {
return (
<div className={styles.container}>
<Link to="/">Album!</Link>
<Link to="/settings" className={styles.settingsLink}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 00.12-.61l-1.92-3.32a.488.488 0 00-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 00-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 00-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z" />
</svg>
</Link>
</div>
);
} | render () {
return (
<div className={styles.container}>
<Link to="/">Album!</Link>
<Link to="/settings" className={styles.settingsLink}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 00.12-.61l-1.92-3.32a.488.488 0 00-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 00-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58a.49.49 0 00-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z" />
</svg>
</Link>
</div>
);
} |
JavaScript | render () {
return (
<div className={styles.container}>
{this.state.files.map((file) => (
<div
key={file}
className={styles.image}
>
<Image file={file} />
</div>
))}
</div>
);
} | render () {
return (
<div className={styles.container}>
{this.state.files.map((file) => (
<div
key={file}
className={styles.image}
>
<Image file={file} />
</div>
))}
</div>
);
} |
JavaScript | render () {
if (!this.state.loaded) {
return <div>Loading</div>;
}
const appContext = {
loadConfig: this.loadConfig,
saveConfig: this.saveConfig,
setConfig: this.setConfig,
ammendConfig: this.ammendConfig,
};
return (
<AppContext.Provider value={appContext}>
<ConfigContext.Provider value={this.state.config}>
{this.renderApp()}
</ConfigContext.Provider>
</AppContext.Provider>
);
} | render () {
if (!this.state.loaded) {
return <div>Loading</div>;
}
const appContext = {
loadConfig: this.loadConfig,
saveConfig: this.saveConfig,
setConfig: this.setConfig,
ammendConfig: this.ammendConfig,
};
return (
<AppContext.Provider value={appContext}>
<ConfigContext.Provider value={this.state.config}>
{this.renderApp()}
</ConfigContext.Provider>
</AppContext.Provider>
);
} |
JavaScript | function displaySearchResults(results) {
var searchArr = [];
if (results.Response === "True") {
$('#searchResults').empty();
$('#searchResults').append('<div id="totalResults"><h4>Total Results: ' + results.totalResults + '</h4></div>');
searchArr = results.Search;
for (var i = 0; i < searchArr.length; i++) {
//hide error from previous search
$('#error').hide();
$('#searchResults').append('<div id="' + searchArr[i].imdbID + '" class="result"><h3>' + searchArr[i].Title + ' (' + searchArr[i].Year + ')</h3></div><hr>');
if (searchArr[i].Type == "movie") {
$('#' + searchArr[i].imdbID).append('<h3 class="icon no-mobile"><i class="fa fa-film"></i></h3>');
} else if (searchArr[i].Type == "series") {
$('#' + searchArr[i].imdbID).append('<h3 class="icon no-mobile"><i class="fa fa-television"></i></h3>');
} else if (searchArr[i].Type == "game") {
$('#' + searchArr[i].imdbID).append('<h3 class="icon no-mobile"><i class="fa fa-gamepad"></i></h3>');
}
}
countPages(results.totalResults);
$('.waiting').hide();
$('#searchResults').show();
resultListener();
$('html, body').animate({
scrollTop: $("#totalResults").offset().top
}, 500);
}
// displays error message if no results was found
else {
$('#searchResults').hide();
$('#error').find('.message').text('No results');
$('.waiting').hide();
$('#error').show();
}
} | function displaySearchResults(results) {
var searchArr = [];
if (results.Response === "True") {
$('#searchResults').empty();
$('#searchResults').append('<div id="totalResults"><h4>Total Results: ' + results.totalResults + '</h4></div>');
searchArr = results.Search;
for (var i = 0; i < searchArr.length; i++) {
//hide error from previous search
$('#error').hide();
$('#searchResults').append('<div id="' + searchArr[i].imdbID + '" class="result"><h3>' + searchArr[i].Title + ' (' + searchArr[i].Year + ')</h3></div><hr>');
if (searchArr[i].Type == "movie") {
$('#' + searchArr[i].imdbID).append('<h3 class="icon no-mobile"><i class="fa fa-film"></i></h3>');
} else if (searchArr[i].Type == "series") {
$('#' + searchArr[i].imdbID).append('<h3 class="icon no-mobile"><i class="fa fa-television"></i></h3>');
} else if (searchArr[i].Type == "game") {
$('#' + searchArr[i].imdbID).append('<h3 class="icon no-mobile"><i class="fa fa-gamepad"></i></h3>');
}
}
countPages(results.totalResults);
$('.waiting').hide();
$('#searchResults').show();
resultListener();
$('html, body').animate({
scrollTop: $("#totalResults").offset().top
}, 500);
}
// displays error message if no results was found
else {
$('#searchResults').hide();
$('#error').find('.message').text('No results');
$('.waiting').hide();
$('#error').show();
}
} |
JavaScript | function addRemoveButton(idList) {
var id = getUrlParameter('id');
if (isLoggedIn()) {
if ($.inArray(id, idList) !== -1) {
$('#details').append('<h2><a id="' + id + '"><span class="glyphicon glyphicon-remove-circle removeFromList"></span></a></h2>');
} else {
$('#details').append('<h2><a id="addToList"><span class="glyphicon glyphicon-ok-circle"></span></a></h2>');
}
addRemoveListener();
}
} | function addRemoveButton(idList) {
var id = getUrlParameter('id');
if (isLoggedIn()) {
if ($.inArray(id, idList) !== -1) {
$('#details').append('<h2><a id="' + id + '"><span class="glyphicon glyphicon-remove-circle removeFromList"></span></a></h2>');
} else {
$('#details').append('<h2><a id="addToList"><span class="glyphicon glyphicon-ok-circle"></span></a></h2>');
}
addRemoveListener();
}
} |
JavaScript | function displayData(data) {
$('#details').empty();
if (data.Response == "True") {
apiGetPoster(data.imdbID);
$('#details').append('<input type="hidden" id="resultImdbID" value="' + data.imdbID + '">');
$('#details').append('<input type="hidden" id="resultTitle" value="' + data.Title + '">');
$('#details').append('<input type="hidden" id="resultType" value="' + data.Type + '">');
$('#details').append('<h2><span class="title">' + data.Title + '</span>(<span class="year">' + data.Year + '</span>)</h2><h4>Plot</h4><p class="plot">' + data.Plot + '</p><p>IMDb rating: ' + data.imdbRating + ' <span class="imdb"></span></p><p>Rotten tomatoes rating: ' + data.tomatoRating + ' <span class="rotten"></span></p>');
// add / remove buttons
myIdList();
// show content when data is received
$('.mylist-tabs').hide();
$('.searchForm').hide();
$('#details').show();
$('#goBack').on('click', function () {
history.back();
});
}
} | function displayData(data) {
$('#details').empty();
if (data.Response == "True") {
apiGetPoster(data.imdbID);
$('#details').append('<input type="hidden" id="resultImdbID" value="' + data.imdbID + '">');
$('#details').append('<input type="hidden" id="resultTitle" value="' + data.Title + '">');
$('#details').append('<input type="hidden" id="resultType" value="' + data.Type + '">');
$('#details').append('<h2><span class="title">' + data.Title + '</span>(<span class="year">' + data.Year + '</span>)</h2><h4>Plot</h4><p class="plot">' + data.Plot + '</p><p>IMDb rating: ' + data.imdbRating + ' <span class="imdb"></span></p><p>Rotten tomatoes rating: ' + data.tomatoRating + ' <span class="rotten"></span></p>');
// add / remove buttons
myIdList();
// show content when data is received
$('.mylist-tabs').hide();
$('.searchForm').hide();
$('#details').show();
$('#goBack').on('click', function () {
history.back();
});
}
} |
JavaScript | function myIdList() {
var url = 'http://watchlist-miikanode.rhcloud.com/getMyList?username=' + currentUser;
var idList = [];
$.get(url, function (response) {
for (var i = 0; i < response.length; i++) {
idList.push(response[i].id);
}
addRemoveButton(idList);
});
} | function myIdList() {
var url = 'http://watchlist-miikanode.rhcloud.com/getMyList?username=' + currentUser;
var idList = [];
$.get(url, function (response) {
for (var i = 0; i < response.length; i++) {
idList.push(response[i].id);
}
addRemoveButton(idList);
});
} |
JavaScript | function recentSearchesList(data) {
var allSearches = [];
for (var i = 0; i < data.length; i++) {
allSearches.push(data[i].title.toLowerCase());
}
var uniqueSearches = [];
$.each(allSearches, function (o, title) {
if ($.inArray(title, uniqueSearches) === -1) {
uniqueSearches.push(title);
if (uniqueSearches.length > 10) {
uniqueSearches.splice(-1, 1);
}
}
});
return uniqueSearches;
} | function recentSearchesList(data) {
var allSearches = [];
for (var i = 0; i < data.length; i++) {
allSearches.push(data[i].title.toLowerCase());
}
var uniqueSearches = [];
$.each(allSearches, function (o, title) {
if ($.inArray(title, uniqueSearches) === -1) {
uniqueSearches.push(title);
if (uniqueSearches.length > 10) {
uniqueSearches.splice(-1, 1);
}
}
});
return uniqueSearches;
} |
JavaScript | function topSearchesList(data) {
var allSearches = [];
for (var i = 0; i < data.length; i++) {
allSearches.push(data[i].title.toLowerCase());
}
allSearches.sort();
var current = null;
var count = 0;
var topSearches = [];
for (var o = 0; o <= allSearches.length; o++) {
if (allSearches[o] != current) {
if (count > 0) {
topSearches.push({
"title": current,
"count": count
});
}
current = allSearches[o];
count = 1;
} else {
count++;
}
}
topSearches.sort(function (a, b) {
return parseFloat(b.count) - parseFloat(a.count);
});
// Turns top searches into a top 10 list
if (topSearches.length > 10) {
for (var n = topSearches.length; n > 10; n--) {
topSearches.splice(-1, 1);
}
}
return topSearches;
} | function topSearchesList(data) {
var allSearches = [];
for (var i = 0; i < data.length; i++) {
allSearches.push(data[i].title.toLowerCase());
}
allSearches.sort();
var current = null;
var count = 0;
var topSearches = [];
for (var o = 0; o <= allSearches.length; o++) {
if (allSearches[o] != current) {
if (count > 0) {
topSearches.push({
"title": current,
"count": count
});
}
current = allSearches[o];
count = 1;
} else {
count++;
}
}
topSearches.sort(function (a, b) {
return parseFloat(b.count) - parseFloat(a.count);
});
// Turns top searches into a top 10 list
if (topSearches.length > 10) {
for (var n = topSearches.length; n > 10; n--) {
topSearches.splice(-1, 1);
}
}
return topSearches;
} |
JavaScript | function isLoggedIn() {
if (sessionStorage.getItem('username') === null) {
return false;
} else {
return true;
}
} | function isLoggedIn() {
if (sessionStorage.getItem('username') === null) {
return false;
} else {
return true;
}
} |
JavaScript | function addUser(username, password) {
var url = 'http://watchlist-miikanode.rhcloud.com/addUser?username=' + username + '&password=' + password;
$.get(url);
logIn(username);
window.location = '../index.html';
} | function addUser(username, password) {
var url = 'http://watchlist-miikanode.rhcloud.com/addUser?username=' + username + '&password=' + password;
$.get(url);
logIn(username);
window.location = '../index.html';
} |
JavaScript | function apiCallSearch(title, type, year) {
var url = 'http://www.omdbapi.com/?s=' + title + '&y=' + year + '&type=' + type + '&tomatoes=true&plot=full';
$.get(url, function (response) {
displaySearchResults(response);
if (response.Response != "False") {
saveSearchTitle(title);
saveRecentSearch(currentUser, title);
}
});
} | function apiCallSearch(title, type, year) {
var url = 'http://www.omdbapi.com/?s=' + title + '&y=' + year + '&type=' + type + '&tomatoes=true&plot=full';
$.get(url, function (response) {
displaySearchResults(response);
if (response.Response != "False") {
saveSearchTitle(title);
saveRecentSearch(currentUser, title);
}
});
} |
JavaScript | function apiCallSearchTitle(title) {
var url = 'http://www.omdbapi.com/?s=' + title;
$.get(url, function (response) {
displaySearchResults(response);
});
} | function apiCallSearchTitle(title) {
var url = 'http://www.omdbapi.com/?s=' + title;
$.get(url, function (response) {
displaySearchResults(response);
});
} |
JavaScript | function apiCallSearchPage(title, type, year, page) {
var url = 'http://www.omdbapi.com/?s=' + title + '&y=' + year + '&type=' + type + '&tomatoes=true&plot=full&page=' + page;
$.get(url, function (response) {
displaySearchResults(response);
});
} | function apiCallSearchPage(title, type, year, page) {
var url = 'http://www.omdbapi.com/?s=' + title + '&y=' + year + '&type=' + type + '&tomatoes=true&plot=full&page=' + page;
$.get(url, function (response) {
displaySearchResults(response);
});
} |
JavaScript | function apiCallDetails(id) {
var url = 'http://www.omdbapi.com/?i=' + id + '&tomatoes=true&plot=full';
$.get(url, function (response) {
displayData(response);
});
} | function apiCallDetails(id) {
var url = 'http://www.omdbapi.com/?i=' + id + '&tomatoes=true&plot=full';
$.get(url, function (response) {
displayData(response);
});
} |
JavaScript | function searchesListener() {
$('.searchTitle').on('click', function (event) {
event.preventDefault();
var title = $(this).attr('id');
$('form').find('#title').val(title);
apiCallSearchTitle(title);
});
} | function searchesListener() {
$('.searchTitle').on('click', function (event) {
event.preventDefault();
var title = $(this).attr('id');
$('form').find('#title').val(title);
apiCallSearchTitle(title);
});
} |
JavaScript | function addRemoveListener() {
$('#addToList').on('click', function () {
var id = $('#resultImdbID').attr('value');
var title = $('#resultTitle').attr('value');
var type = $('#resultType').attr('value');
addToList(currentUser, id, title, type);
location.reload();
$('#addToList').hide();
});
$('.removeFromList').on('click', function () {
var id = $(this).parent().attr('id');
removeFromList(currentUser, id);
$('#allTab').find('#' + id).remove();
$('#moviesTab').find('#' + id).remove();
$('#seriesTab').find('#' + id).remove();
if ($('#details').length > 0) {
location.reload();
}
});
} | function addRemoveListener() {
$('#addToList').on('click', function () {
var id = $('#resultImdbID').attr('value');
var title = $('#resultTitle').attr('value');
var type = $('#resultType').attr('value');
addToList(currentUser, id, title, type);
location.reload();
$('#addToList').hide();
});
$('.removeFromList').on('click', function () {
var id = $(this).parent().attr('id');
removeFromList(currentUser, id);
$('#allTab').find('#' + id).remove();
$('#moviesTab').find('#' + id).remove();
$('#seriesTab').find('#' + id).remove();
if ($('#details').length > 0) {
location.reload();
}
});
} |
JavaScript | function deleteInstance(id) {
for (var i = this.length - 1; i >= 0; i--) {
if (this[i].meta.id === id) {
this.splice(i, 1);
break;
}
}
} | function deleteInstance(id) {
for (var i = this.length - 1; i >= 0; i--) {
if (this[i].meta.id === id) {
this.splice(i, 1);
break;
}
}
} |
JavaScript | function findInstance(id, name) {
if (id) {
return this.filter(function (module) {
if (module.meta.id === id) {
return module;
}
});
} else if (name) {
return this.filter(function (module) {
if (module.name === name) {
return module;
}
});
}
return [];
} | function findInstance(id, name) {
if (id) {
return this.filter(function (module) {
if (module.meta.id === id) {
return module;
}
});
} else if (name) {
return this.filter(function (module) {
if (module.name === name) {
return module;
}
});
}
return [];
} |
JavaScript | function destroyModuleInstance(module, context = window) {
// / Remove module DOM and unsubscribe its events
if (Array.isArray(module)) {
const status = [];
module.forEach((singleModule) => {
status.push(destroyModuleInstance(singleModule));
});
return status;
}
let moduleInstance;
if (typeof module === 'string') {
moduleInstance = moduleS.findInstance(module);
} else if (module.meta) {
moduleInstance = moduleS.findInstance(module.meta.id);
} else {
moduleInstance = moduleS.findInstance(null, module.name);
}
moduleInstance.forEach((module) => {
// Call detroy of module
if (module[CONSTANTS.MODULE_EVENTS.destroy]) {
module[CONSTANTS.MODULE_EVENTS.destroy]();
}
let container = context.document.querySelector(`#${module.getUniqueId()}`);
// Remove element from DOM
if (container) {
container.remove();
container = null;
}
// Remove all subscriptions
const moduleSubscriptions = module.getAllSubscriptions();
moduleSubscriptions.forEach((subscription) => {
module.unsubscribe(subscription.eventName, subscription.callback);
});
if (module.meta.children && module.meta.children.length) {
const childPointers = module.meta.children.map(child => child.pointer);
module.meta.children = [];
childPointers.forEach((childNode) => {
destroyModuleInstance(childNode);
});
}
moduleS.deleteInstance(module.meta.id);
});
return true;
} | function destroyModuleInstance(module, context = window) {
// / Remove module DOM and unsubscribe its events
if (Array.isArray(module)) {
const status = [];
module.forEach((singleModule) => {
status.push(destroyModuleInstance(singleModule));
});
return status;
}
let moduleInstance;
if (typeof module === 'string') {
moduleInstance = moduleS.findInstance(module);
} else if (module.meta) {
moduleInstance = moduleS.findInstance(module.meta.id);
} else {
moduleInstance = moduleS.findInstance(null, module.name);
}
moduleInstance.forEach((module) => {
// Call detroy of module
if (module[CONSTANTS.MODULE_EVENTS.destroy]) {
module[CONSTANTS.MODULE_EVENTS.destroy]();
}
let container = context.document.querySelector(`#${module.getUniqueId()}`);
// Remove element from DOM
if (container) {
container.remove();
container = null;
}
// Remove all subscriptions
const moduleSubscriptions = module.getAllSubscriptions();
moduleSubscriptions.forEach((subscription) => {
module.unsubscribe(subscription.eventName, subscription.callback);
});
if (module.meta.children && module.meta.children.length) {
const childPointers = module.meta.children.map(child => child.pointer);
module.meta.children = [];
childPointers.forEach((childNode) => {
destroyModuleInstance(childNode);
});
}
moduleS.deleteInstance(module.meta.id);
});
return true;
} |
JavaScript | function createInstance(config, parentName) {
config = merge({}, config);
if (!Utils.configValidator(config)) return;
const modulesToDestory = moduleS.filter(moduleInstance => moduleInstance.instanceConfig.container === config.instanceConfig.container);
modulesToDestory.forEach((moduleInstance) => {
destroyModuleInstance(moduleInstance);
});
let moduleResolvePromiseArr = [],
promise,
patchModules = [];
_registerModule.call(this, config.moduleName, config, config.module, config.instanceConfig, patchModules, parentName);
_startExec.call(this, patchModules, moduleResolvePromiseArr);
return new Promise((res, rej) => {
Promise.all(moduleResolvePromiseArr).then(res).catch(rej);
});
} | function createInstance(config, parentName) {
config = merge({}, config);
if (!Utils.configValidator(config)) return;
const modulesToDestory = moduleS.filter(moduleInstance => moduleInstance.instanceConfig.container === config.instanceConfig.container);
modulesToDestory.forEach((moduleInstance) => {
destroyModuleInstance(moduleInstance);
});
let moduleResolvePromiseArr = [],
promise,
patchModules = [];
_registerModule.call(this, config.moduleName, config, config.module, config.instanceConfig, patchModules, parentName);
_startExec.call(this, patchModules, moduleResolvePromiseArr);
return new Promise((res, rej) => {
Promise.all(moduleResolvePromiseArr).then(res).catch(rej);
});
} |
JavaScript | render(placeholderData) {
const containerSelector = this.getUniqueId();
const placeholders = placeholderData || this.instanceConfig.placeholders;
if (!this.template) return;
document.querySelector(`#${containerSelector}`).innerHTML = this.template(placeholders);
} | render(placeholderData) {
const containerSelector = this.getUniqueId();
const placeholders = placeholderData || this.instanceConfig.placeholders;
if (!this.template) return;
document.querySelector(`#${containerSelector}`).innerHTML = this.template(placeholders);
} |
JavaScript | unsubscribe(subscriber, eventName, callback) {
const subscriptionsForEvent = subscriptions[eventName];
if (!subscriptionsForEvent) {
return;
}
// Check if any RE_PLAY event is there and all the event context is of is same as
// destroy its data from eventQ
const replaySubscriptions = subscriptionsForEvent.filter((subscription) => {
if (subscription.type === 'RE_PLAY') return subscription;
});
subscriptions[eventName] = subscriptionsForEvent.filter(subscription => !(subscription.callback === callback && subscription.eventSubscriber === subscriber));
unsubscribeLogger(eventName, subscriptionsForEvent);
if (replaySubscriptions.length) {
if (!subscriptions[eventName].length) {
// Remove all the items from eventQ with eventName
eventQ.store = eventQ.store.filter((evt) => {
if (evt.eventName !== eventName) return evt;
});
}
}
} | unsubscribe(subscriber, eventName, callback) {
const subscriptionsForEvent = subscriptions[eventName];
if (!subscriptionsForEvent) {
return;
}
// Check if any RE_PLAY event is there and all the event context is of is same as
// destroy its data from eventQ
const replaySubscriptions = subscriptionsForEvent.filter((subscription) => {
if (subscription.type === 'RE_PLAY') return subscription;
});
subscriptions[eventName] = subscriptionsForEvent.filter(subscription => !(subscription.callback === callback && subscription.eventSubscriber === subscriber));
unsubscribeLogger(eventName, subscriptionsForEvent);
if (replaySubscriptions.length) {
if (!subscriptions[eventName].length) {
// Remove all the items from eventQ with eventName
eventQ.store = eventQ.store.filter((evt) => {
if (evt.eventName !== eventName) return evt;
});
}
}
} |
JavaScript | function destroyModuleInstance(module) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window;
// / Remove module DOM and unsubscribe its events
if (Array.isArray(module)) {
var status = [];
module.forEach(function (singleModule) {
status.push(destroyModuleInstance(singleModule));
});
return status;
}
var moduleInstance = void 0;
if (typeof module === 'string') {
moduleInstance = moduleS.findInstance(module);
} else if (module.meta) {
moduleInstance = moduleS.findInstance(module.meta.id);
} else {
moduleInstance = moduleS.findInstance(null, module.name);
}
moduleInstance.forEach(function (module) {
// Call detroy of module
if (module[constants_defaultExport.MODULE_EVENTS.destroy]) {
module[constants_defaultExport.MODULE_EVENTS.destroy]();
}
var container = context.document.querySelector('#' + module.getUniqueId());
// Remove element from DOM
if (container) {
container.remove();
container = null;
}
// Remove all subscriptions
var moduleSubscriptions = module.getAllSubscriptions();
moduleSubscriptions.forEach(function (subscription) {
module.unsubscribe(subscription.eventName, subscription.callback);
});
if (module.meta.children && module.meta.children.length) {
var childPointers = module.meta.children.map(function (child) {
return child.pointer;
});
module.meta.children = [];
childPointers.forEach(function (childNode) {
destroyModuleInstance(childNode);
});
}
moduleS.deleteInstance(module.meta.id);
});
return true;
} | function destroyModuleInstance(module) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window;
// / Remove module DOM and unsubscribe its events
if (Array.isArray(module)) {
var status = [];
module.forEach(function (singleModule) {
status.push(destroyModuleInstance(singleModule));
});
return status;
}
var moduleInstance = void 0;
if (typeof module === 'string') {
moduleInstance = moduleS.findInstance(module);
} else if (module.meta) {
moduleInstance = moduleS.findInstance(module.meta.id);
} else {
moduleInstance = moduleS.findInstance(null, module.name);
}
moduleInstance.forEach(function (module) {
// Call detroy of module
if (module[constants_defaultExport.MODULE_EVENTS.destroy]) {
module[constants_defaultExport.MODULE_EVENTS.destroy]();
}
var container = context.document.querySelector('#' + module.getUniqueId());
// Remove element from DOM
if (container) {
container.remove();
container = null;
}
// Remove all subscriptions
var moduleSubscriptions = module.getAllSubscriptions();
moduleSubscriptions.forEach(function (subscription) {
module.unsubscribe(subscription.eventName, subscription.callback);
});
if (module.meta.children && module.meta.children.length) {
var childPointers = module.meta.children.map(function (child) {
return child.pointer;
});
module.meta.children = [];
childPointers.forEach(function (childNode) {
destroyModuleInstance(childNode);
});
}
moduleS.deleteInstance(module.meta.id);
});
return true;
} |
JavaScript | function createInstance(config, parentName) {
config = __WEBPACK_IMPORTED_MODULE_1_lodash_fp__["merge"]({}, config);
if (!utils_defaultExport.configValidator(config)) return;
var modulesToDestory = moduleS.filter(function (moduleInstance) {
return moduleInstance.instanceConfig.container === config.instanceConfig.container;
});
modulesToDestory.forEach(function (moduleInstance) {
destroyModuleInstance(moduleInstance);
});
var moduleResolvePromiseArr = [],
promise = void 0,
patchModules = [];
blinx__registerModule.call(this, config.moduleName, config, config.module, config.instanceConfig, patchModules, parentName);
_startExec.call(this, patchModules, moduleResolvePromiseArr);
return new Promise(function (res, rej) {
Promise.all(moduleResolvePromiseArr).then(res).catch(rej);
});
} | function createInstance(config, parentName) {
config = __WEBPACK_IMPORTED_MODULE_1_lodash_fp__["merge"]({}, config);
if (!utils_defaultExport.configValidator(config)) return;
var modulesToDestory = moduleS.filter(function (moduleInstance) {
return moduleInstance.instanceConfig.container === config.instanceConfig.container;
});
modulesToDestory.forEach(function (moduleInstance) {
destroyModuleInstance(moduleInstance);
});
var moduleResolvePromiseArr = [],
promise = void 0,
patchModules = [];
blinx__registerModule.call(this, config.moduleName, config, config.module, config.instanceConfig, patchModules, parentName);
_startExec.call(this, patchModules, moduleResolvePromiseArr);
return new Promise(function (res, rej) {
Promise.all(moduleResolvePromiseArr).then(res).catch(rej);
});
} |
JavaScript | function observe (data) {
return new Proxy(data, {
get (obj, key) {
if (watchingFn) {
if (!depends[key]) depends[key] = [];
depends[key].push(watchingFn);
}
return obj[key];
},
set (obj, key, val) {
obj[key] = val;
if (depends[key])
depends[key].forEach(cb => cb());
return true;
}
})
} | function observe (data) {
return new Proxy(data, {
get (obj, key) {
if (watchingFn) {
if (!depends[key]) depends[key] = [];
depends[key].push(watchingFn);
}
return obj[key];
},
set (obj, key, val) {
obj[key] = val;
if (depends[key])
depends[key].forEach(cb => cb());
return true;
}
})
} |
JavaScript | function watcher (target) {
watchingFn = target;
target();
watchingFn = null;
} | function watcher (target) {
watchingFn = target;
target();
watchingFn = null;
} |
JavaScript | async sync (bAll = false) {
while (!this.internalProcessingAllowed()) {
// console.log(`sync: await internalProcessing (aIP=${this.aIP})`);
await new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, 200);
});
}
const syncOptions = await this._getSyncOptions(bAll);
debug(`${this.type}.sync(${JSON.stringify(syncOptions)}) started...`);
let self = this;
let result = true;
let [err, snap] = await to( snapshot(this.remoteService, syncOptions) )
if (err) { // we silently ignore any errors
if (err.className === 'timeout') {
debug(` TIMEOUT: ${JSON.stringify(err)}`);
} else {
debug(` ERROR: ${JSON.stringify(err)}`);
}
// Ok, tell anyone interested about the result
this.localService.emit('synced', false);
return false;
}
/*
* For each row returned by snapshot we perform the following:
* - if it already exists locally
* - if it is marked as deleted
* - remove the row
* - otherwise
* - patch the row
* - otherwise
* - if it is not marked as deleted
* - create the row
* Moreover we track the `onServerAt` to determine latest sync timestamp
*/
debug(` Applying received snapshot data... (${snap.length} items)`);
let syncTS = new Date(0).toISOString();
await Promise.all(snap.map(async (v) => {
let [err, res] = await to( self.localService.get(v[self.id]) );
if (res) {
syncTS = syncTS < v[this.myOnServerAt] ? v[this.myOnServerAt] : syncTS;
if (v[this.myDeletedAt]) {
[err, res] = await to( self.localService.remove(v[self.id]));
}
else {
[err, res] = await to( self.localService.patch(v[self.id], v));
}
if (err) { result = false; }
}
else {
if (!v[this.myDeletedAt]) {
syncTS = syncTS < v[this.myOnServerAt] ? v[this.myOnServerAt] : syncTS;
[err, res] = await to( self.localService.create(v));
if (err) { result = false; }
}
}
}));
// Save last sync timestamp
await this.writeSyncedAt(syncTS);
this.syncedAt = syncTS;
if (result) // Wait until internal Processing is ok
while (!await this._processQueuedEvents()) {
await new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, 200);
});
};
// Ok, tell anyone interested about the result
this.localService.emit('synced', result);
return result;
} | async sync (bAll = false) {
while (!this.internalProcessingAllowed()) {
// console.log(`sync: await internalProcessing (aIP=${this.aIP})`);
await new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, 200);
});
}
const syncOptions = await this._getSyncOptions(bAll);
debug(`${this.type}.sync(${JSON.stringify(syncOptions)}) started...`);
let self = this;
let result = true;
let [err, snap] = await to( snapshot(this.remoteService, syncOptions) )
if (err) { // we silently ignore any errors
if (err.className === 'timeout') {
debug(` TIMEOUT: ${JSON.stringify(err)}`);
} else {
debug(` ERROR: ${JSON.stringify(err)}`);
}
// Ok, tell anyone interested about the result
this.localService.emit('synced', false);
return false;
}
/*
* For each row returned by snapshot we perform the following:
* - if it already exists locally
* - if it is marked as deleted
* - remove the row
* - otherwise
* - patch the row
* - otherwise
* - if it is not marked as deleted
* - create the row
* Moreover we track the `onServerAt` to determine latest sync timestamp
*/
debug(` Applying received snapshot data... (${snap.length} items)`);
let syncTS = new Date(0).toISOString();
await Promise.all(snap.map(async (v) => {
let [err, res] = await to( self.localService.get(v[self.id]) );
if (res) {
syncTS = syncTS < v[this.myOnServerAt] ? v[this.myOnServerAt] : syncTS;
if (v[this.myDeletedAt]) {
[err, res] = await to( self.localService.remove(v[self.id]));
}
else {
[err, res] = await to( self.localService.patch(v[self.id], v));
}
if (err) { result = false; }
}
else {
if (!v[this.myDeletedAt]) {
syncTS = syncTS < v[this.myOnServerAt] ? v[this.myOnServerAt] : syncTS;
[err, res] = await to( self.localService.create(v));
if (err) { result = false; }
}
}
}));
// Save last sync timestamp
await this.writeSyncedAt(syncTS);
this.syncedAt = syncTS;
if (result) // Wait until internal Processing is ok
while (!await this._processQueuedEvents()) {
await new Promise(resolve => {
setTimeout(() => {
resolve(true);
}, 200);
});
};
// Ok, tell anyone interested about the result
this.localService.emit('synced', result);
return result;
} |
JavaScript | async _getSyncOptions (bAll, bTesting) {
let offline = bTesting ? {} : { _forceAll: bAll };
let query = Object.assign({}, { offline }, { $sort: {[this.myOnServerAt]: 1}});
let ts = bAll ? new Date(0).toISOString() : this.syncedAt;
query[this.myOnServerAt] = bTesting ? { $gte: new Date(ts).getTime() } : ts;
return query;
} | async _getSyncOptions (bAll, bTesting) {
let offline = bTesting ? {} : { _forceAll: bAll };
let query = Object.assign({}, { offline }, { $sort: {[this.myOnServerAt]: 1}});
let ts = bAll ? new Date(0).toISOString() : this.syncedAt;
query[this.myOnServerAt] = bTesting ? { $gte: new Date(ts).getTime() } : ts;
return query;
} |
JavaScript | function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
//
//
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
} | function detectVerticalSquash( img, iw, ih ) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
sy = 0,
ey = ih,
py = ih,
data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx.drawImage( img, 0, 0 );
data = ctx.getImageData( 0, 0, 1, ih ).data;
//
//
while ( py > sy ) {
alpha = data[ (py - 1) * 4 + 3 ];
if ( alpha === 0 ) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
} |
JavaScript | function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
//
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
//
//
//
//
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
} | function detectSubsampling( img ) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
canvas, ctx;
//
if ( iw * ih > 1024 * 1024 ) {
canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
ctx = canvas.getContext('2d');
ctx.drawImage( img, -iw + 1, 0 );
//
//
//
//
return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0;
} else {
return false;
}
} |
JavaScript | function _allowErrorMessageAfterTimeout(callKey) {
recentCalls[callKey] = setTimeout(function () {
delete recentCalls[callKey];
}, throttleTime);
} | function _allowErrorMessageAfterTimeout(callKey) {
recentCalls[callKey] = setTimeout(function () {
delete recentCalls[callKey];
}, throttleTime);
} |
JavaScript | function _clearRecentCalls() {
Object.keys(recentCalls).forEach(function (callKey) {
clearTimeout(recentCalls[callKey]);
});
} | function _clearRecentCalls() {
Object.keys(recentCalls).forEach(function (callKey) {
clearTimeout(recentCalls[callKey]);
});
} |
JavaScript | parseAi2htmlFontSettings(settings) {
let parsed = [];
_.each(settings, font => {
if (!font.known_postscript_names) {
return;
}
font.known_postscript_names.forEach(p => {
parsed.push({
aifont: p,
family: font.family,
weight: font.weight,
style: font.style
});
});
});
return parsed;
} | parseAi2htmlFontSettings(settings) {
let parsed = [];
_.each(settings, font => {
if (!font.known_postscript_names) {
return;
}
font.known_postscript_names.forEach(p => {
parsed.push({
aifont: p,
family: font.family,
weight: font.weight,
style: font.style
});
});
});
return parsed;
} |
JavaScript | findGlobsPaths(globs) {
return _.flatten(
globs.map(g => {
return glob.sync(g) || [];
})
);
} | findGlobsPaths(globs) {
return _.flatten(
globs.map(g => {
return glob.sync(g) || [];
})
);
} |
JavaScript | canWrite(dir) {
try {
fs.accessSync(dir, fs.constants.W_OK);
return true;
}
catch (e) {
debug(e);
return false;
}
} | canWrite(dir) {
try {
fs.accessSync(dir, fs.constants.W_OK);
return true;
}
catch (e) {
debug(e);
return false;
}
} |
JavaScript | function identity (value){
// takes value
// return value unchanged
return value;
} | function identity (value){
// takes value
// return value unchanged
return value;
} |
JavaScript | function typeOf(value){
// check if the value is equal to null anbd return null
if (value === null){
return "null";
// check if value is an array using comparison assignment
}else if (Array.isArray(value)=== true){
return 'array';
}else {
return typeof (value);
}
} | function typeOf(value){
// check if the value is equal to null anbd return null
if (value === null){
return "null";
// check if value is an array using comparison assignment
}else if (Array.isArray(value)=== true){
return 'array';
}else {
return typeof (value);
}
} |
JavaScript | function last(array, number ){
// check if value is an array using conditional statement
// check if number is not a positive number to return an empty array
if (Array.isArray(array)!== true || number < 0){
return [];
// if zero is not given or not a number
//return the last element in the array
}else if(typeof(number)!== 'number'){
return array[array.length-1];
// if number is positive return the full array.
}else if (number > array.length -1){
return array;
}else {
var i = 0;
while(i !== array.length - number)
array.shift(array[i]);
return array;
}} | function last(array, number ){
// check if value is an array using conditional statement
// check if number is not a positive number to return an empty array
if (Array.isArray(array)!== true || number < 0){
return [];
// if zero is not given or not a number
//return the last element in the array
}else if(typeof(number)!== 'number'){
return array[array.length-1];
// if number is positive return the full array.
}else if (number > array.length -1){
return array;
}else {
var i = 0;
while(i !== array.length - number)
array.shift(array[i]);
return array;
}} |
JavaScript | function filter(array, func){
console.log(array);
// use the _.each function check each element in the array passing the argument
var newArr = [];
each(array, (element, index, array) => {
console.log(array);
if(func(element,index, array) === true){
newArr.push(element);
}
}
);
console.log(newArr);
return newArr ;
} | function filter(array, func){
console.log(array);
// use the _.each function check each element in the array passing the argument
var newArr = [];
each(array, (element, index, array) => {
console.log(array);
if(func(element,index, array) === true){
newArr.push(element);
}
}
);
console.log(newArr);
return newArr ;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.