language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function editTheme(name, replaceName = undefined) {
trackEvent(`Theme: ${name}`, "edit", "Theme List");
clearInterval(rainbowInterval);
themesListSection.classList.add("hidden");
themeEditorSection.classList.remove("hidden");
let themeToLoad = name ? allThemes[name] : { name: "My Theme", hue: 210 };
if (replaceName) {
themeToLoad.name = replaceName;
}
importAndRender(themeToLoad);
previewSection.classList.add("show-editor-controls");
output.removeAttribute("readonly");
Array.from(iconList.querySelectorAll(".class-name, .icon-url")).map(x => x.setAttribute("contenteditable", "true"));
origThemeName = replaceName || name;
document.querySelector("#json-output + label").textContent = "JSON (Paste to import a theme)";
} | function editTheme(name, replaceName = undefined) {
trackEvent(`Theme: ${name}`, "edit", "Theme List");
clearInterval(rainbowInterval);
themesListSection.classList.add("hidden");
themeEditorSection.classList.remove("hidden");
let themeToLoad = name ? allThemes[name] : { name: "My Theme", hue: 210 };
if (replaceName) {
themeToLoad.name = replaceName;
}
importAndRender(themeToLoad);
previewSection.classList.add("show-editor-controls");
output.removeAttribute("readonly");
Array.from(iconList.querySelectorAll(".class-name, .icon-url")).map(x => x.setAttribute("contenteditable", "true"));
origThemeName = replaceName || name;
document.querySelector("#json-output + label").textContent = "JSON (Paste to import a theme)";
} |
JavaScript | function importTheme() {
PromptModal.open("Import Theme", "Paste theme JSON here", ["Import", "Cancel"], (button, text) => {
if (button === "Import") {
try {
let j = JSON.parse(text);
importAndRender(j);
saveTheme();
}
catch {
ConfirmModal.open("Error Importing Theme", errors.length > 0 ? errors.join() : "Please provide a valid JSON string", ["OK"]);
}
}
});
} | function importTheme() {
PromptModal.open("Import Theme", "Paste theme JSON here", ["Import", "Cancel"], (button, text) => {
if (button === "Import") {
try {
let j = JSON.parse(text);
importAndRender(j);
saveTheme();
}
catch {
ConfirmModal.open("Error Importing Theme", errors.length > 0 ? errors.join() : "Please provide a valid JSON string", ["OK"]);
}
}
});
} |
JavaScript | function sendNotification(notification, name, count) {
chrome.storage.sync.get(null, function (storageContent) {
count = (count || count == 0) ? count : 1;
if (getBrowser() == "Firefox") {
delete notification.requireInteraction;
}
Logger.log("New notification!", notification);
if (count > 0 && (!storageContent.notifications || storageContent.notifications == "enabled" || storageContent.notifications == "badge")) {
chrome.browserAction.getBadgeText({}, x => {
let num = Number.parseInt(x);
chrome.browserAction.setBadgeText({ text: (num ? num + count : count).toString() });
});
} else {
Logger.log("Number badge is disabled");
}
if (!storageContent.notifications || storageContent.notifications == "enabled" || storageContent.notifications == "popup") {
chrome.notifications.create(name, notification, null);
trackEvent(name, "shown", "Notifications");
} else {
Logger.log("Popup notifications are disabled");
}
});
} | function sendNotification(notification, name, count) {
chrome.storage.sync.get(null, function (storageContent) {
count = (count || count == 0) ? count : 1;
if (getBrowser() == "Firefox") {
delete notification.requireInteraction;
}
Logger.log("New notification!", notification);
if (count > 0 && (!storageContent.notifications || storageContent.notifications == "enabled" || storageContent.notifications == "badge")) {
chrome.browserAction.getBadgeText({}, x => {
let num = Number.parseInt(x);
chrome.browserAction.setBadgeText({ text: (num ? num + count : count).toString() });
});
} else {
Logger.log("Number badge is disabled");
}
if (!storageContent.notifications || storageContent.notifications == "enabled" || storageContent.notifications == "popup") {
chrome.notifications.create(name, notification, null);
trackEvent(name, "shown", "Notifications");
} else {
Logger.log("Popup notifications are disabled");
}
});
} |
JavaScript | function wrapHtml(baseString, wrapperTag, wrapperProps) {
let resultString = "<" + wrapperTag;
if (wrapperProps) {
for (let prop in wrapperProps) {
resultString += ` ${prop}="${wrapperProps[prop]}"`;
}
}
resultString += ">";
resultString += baseString;
resultString += "</" + wrapperTag + ">";
return resultString;
} | function wrapHtml(baseString, wrapperTag, wrapperProps) {
let resultString = "<" + wrapperTag;
if (wrapperProps) {
for (let prop in wrapperProps) {
resultString += ` ${prop}="${wrapperProps[prop]}"`;
}
}
resultString += ">";
resultString += baseString;
resultString += "</" + wrapperTag + ">";
return resultString;
} |
JavaScript | function deleteBroadcasts(...ids) {
for (let id of ids) {
let unreadBroadcasts = Setting.getValue("unreadBroadcasts");
if (!unreadBroadcasts) continue;
unreadBroadcasts.splice(unreadBroadcasts.findIndex(x => x.id == id), 1);
Setting.setValue("unreadBroadcasts", unreadBroadcasts);
let broadcastElement = document.getElementById(`broadcast${id}`);
if (broadcastElement) {
broadcastElement.outerHTML = "";
}
}
} | function deleteBroadcasts(...ids) {
for (let id of ids) {
let unreadBroadcasts = Setting.getValue("unreadBroadcasts");
if (!unreadBroadcasts) continue;
unreadBroadcasts.splice(unreadBroadcasts.findIndex(x => x.id == id), 1);
Setting.setValue("unreadBroadcasts", unreadBroadcasts);
let broadcastElement = document.getElementById(`broadcast${id}`);
if (broadcastElement) {
broadcastElement.outerHTML = "";
}
}
} |
JavaScript | static loadFromObject(o) {
return o
? new RainbowColorDefinition(
RainbowColorComponentDefinition.loadFromObject(o.hue),
RainbowColorComponentDefinition.loadFromObject(o.saturation),
RainbowColorComponentDefinition.loadFromObject(o.lightness)
)
: undefined;
} | static loadFromObject(o) {
return o
? new RainbowColorDefinition(
RainbowColorComponentDefinition.loadFromObject(o.hue),
RainbowColorComponentDefinition.loadFromObject(o.saturation),
RainbowColorComponentDefinition.loadFromObject(o.lightness)
)
: undefined;
} |
JavaScript | static loadFromObject(o) {
return o
? new ModernInterfaceColorDefinition(
o.primary,
o.accent,
o.secondary,
o.input,
o.border,
o.highlight,
o.active,
o.grades,
o.error
)
: undefined;
} | static loadFromObject(o) {
return o
? new ModernInterfaceColorDefinition(
o.primary,
o.accent,
o.secondary,
o.input,
o.border,
o.highlight,
o.active,
o.grades,
o.error
)
: undefined;
} |
JavaScript | static loadFromObject(o) {
return o
? new ModernTextColorDefinition(
o.primary,
o.muted,
o.contrast
)
: undefined;
} | static loadFromObject(o) {
return o
? new ModernTextColorDefinition(
o.primary,
o.muted,
o.contrast
)
: undefined;
} |
JavaScript | static loadFromObject(o) {
return o
? new ModernOptionsDefinition(
o.borderRadius,
o.borderSize,
o.padding
)
: undefined;
} | static loadFromObject(o) {
return o
? new ModernOptionsDefinition(
o.borderRadius,
o.borderSize,
o.padding
)
: undefined;
} |
JavaScript | static loadFromObject(o) {
return o
? new ModernColorDefinition(
o.dark,
ModernInterfaceColorDefinition.loadFromObject(o.interface),
o.calendar,
ModernTextColorDefinition.loadFromObject(o.text),
ModernOptionsDefinition.loadFromObject(o.options)
)
: undefined;
} | static loadFromObject(o) {
return o
? new ModernColorDefinition(
o.dark,
ModernInterfaceColorDefinition.loadFromObject(o.interface),
o.calendar,
ModernTextColorDefinition.loadFromObject(o.text),
ModernOptionsDefinition.loadFromObject(o.options)
)
: undefined;
} |
JavaScript | static loadFromObject(o) {
if (o && o.version === SchoologyTheme.CURRENT_VERSION) {
return new SchoologyTheme(
o.name,
o.version,
ThemeColor.loadFromObject(o.color),
ThemeLogo.loadFromObject(o.logo),
ThemeCursor.loadFromObject(o.cursor),
ThemeIcon.loadArrayFromObject(o.icons)
);
}
throw new Error(`Invalid theme object provided. Make sure the provided JSON is a valid version ${SchoologyTheme.CURRENT_VERSION} theme.`);
} | static loadFromObject(o) {
if (o && o.version === SchoologyTheme.CURRENT_VERSION) {
return new SchoologyTheme(
o.name,
o.version,
ThemeColor.loadFromObject(o.color),
ThemeLogo.loadFromObject(o.logo),
ThemeCursor.loadFromObject(o.cursor),
ThemeIcon.loadArrayFromObject(o.icons)
);
}
throw new Error(`Invalid theme object provided. Make sure the provided JSON is a valid version ${SchoologyTheme.CURRENT_VERSION} theme.`);
} |
JavaScript | function convertNotes (notes, sub) {
self.log(`Notes ver: ${notes.ver}`);
if (notes.ver >= TBCore.notesMinSchema) {
if (notes.ver <= 5) {
notes = inflateNotes(notes, sub);
} else if (notes.ver <= 6) {
notes = decompressBlob(notes);
notes = inflateNotes(notes, sub);
}
if (notes.ver <= TBCore.notesDeprecatedSchema) {
self.log(`Found deprecated notes in ${subreddit}: S${notes.ver}`);
TBCore.alert(
`The usernotes in /r/${subreddit} are stored using schema v${notes.ver}, which is deprecated. Please click here to updated to v${TBCore.notesSchema}.`,
clicked => {
if (clicked) {
// Upgrade notes
self.saveUserNotes(subreddit, notes, `Updated notes to schema v${TBCore.notesSchema}`, succ => {
if (succ) {
TB.ui.textFeedback('Notes saved!', TB.ui.FEEDBACK_POSITIVE);
TBCore.clearCache();
window.location.reload();
}
});
}
}
);
}
return notes;
} else {
returnFalse();
}
// Utilities
function decompressBlob (notes) {
const decompressed = TBHelpers.zlibInflate(notes.blob);
// Update notes with actual notes
delete notes.blob;
notes.users = JSON.parse(decompressed);
return notes;
}
} | function convertNotes (notes, sub) {
self.log(`Notes ver: ${notes.ver}`);
if (notes.ver >= TBCore.notesMinSchema) {
if (notes.ver <= 5) {
notes = inflateNotes(notes, sub);
} else if (notes.ver <= 6) {
notes = decompressBlob(notes);
notes = inflateNotes(notes, sub);
}
if (notes.ver <= TBCore.notesDeprecatedSchema) {
self.log(`Found deprecated notes in ${subreddit}: S${notes.ver}`);
TBCore.alert(
`The usernotes in /r/${subreddit} are stored using schema v${notes.ver}, which is deprecated. Please click here to updated to v${TBCore.notesSchema}.`,
clicked => {
if (clicked) {
// Upgrade notes
self.saveUserNotes(subreddit, notes, `Updated notes to schema v${TBCore.notesSchema}`, succ => {
if (succ) {
TB.ui.textFeedback('Notes saved!', TB.ui.FEEDBACK_POSITIVE);
TBCore.clearCache();
window.location.reload();
}
});
}
}
);
}
return notes;
} else {
returnFalse();
}
// Utilities
function decompressBlob (notes) {
const decompressed = TBHelpers.zlibInflate(notes.blob);
// Update notes with actual notes
delete notes.blob;
notes.users = JSON.parse(decompressed);
return notes;
}
} |
JavaScript | function inflateNotes (deflated, sub) {
const inflated = {
ver: deflated.ver,
users: {},
};
const mgr = new self._constManager(deflated.constants);
self.log('Inflating all usernotes');
$.each(deflated.users, (name, user) => {
inflated.users[name] = {
name,
notes: user.ns.map(note => inflateNote(deflated.ver, mgr, note, sub)),
};
});
return inflated;
} | function inflateNotes (deflated, sub) {
const inflated = {
ver: deflated.ver,
users: {},
};
const mgr = new self._constManager(deflated.constants);
self.log('Inflating all usernotes');
$.each(deflated.users, (name, user) => {
inflated.users[name] = {
name,
notes: user.ns.map(note => inflateNote(deflated.ver, mgr, note, sub)),
};
});
return inflated;
} |
JavaScript | function deconvertNotes (notes) {
if (notes.ver <= 5) {
self.log(' Is v5');
return deflateNotes(notes);
} else if (notes.ver <= 6) {
self.log(' Is v6');
notes = deflateNotes(notes);
return compressBlob(notes);
}
return notes;
// Utilities
function compressBlob (notes) {
// Make way for the blob!
const users = JSON.stringify(notes.users);
delete notes.users;
notes.blob = TBHelpers.zlibDeflate(users);
return notes;
}
} | function deconvertNotes (notes) {
if (notes.ver <= 5) {
self.log(' Is v5');
return deflateNotes(notes);
} else if (notes.ver <= 6) {
self.log(' Is v6');
notes = deflateNotes(notes);
return compressBlob(notes);
}
return notes;
// Utilities
function compressBlob (notes) {
// Make way for the blob!
const users = JSON.stringify(notes.users);
delete notes.users;
notes.blob = TBHelpers.zlibDeflate(users);
return notes;
}
} |
JavaScript | function deflateNotes (notes) {
const deflated = {
ver: TBCore.notesSchema > notes.ver ? TBCore.notesSchema : notes.ver, // Prevents downgrading usernotes version like a butt
users: {},
constants: {
users: [],
warnings: [],
},
};
const mgr = new self._constManager(deflated.constants);
$.each(notes.users, (name, user) => {
deflated.users[name] = {
ns: user.notes.filter(note => {
if (note === undefined) {
self.log('WARNING: undefined note removed');
}
return note !== undefined;
}).map(note => deflateNote(notes.ver, note, mgr)),
};
});
return deflated;
} | function deflateNotes (notes) {
const deflated = {
ver: TBCore.notesSchema > notes.ver ? TBCore.notesSchema : notes.ver, // Prevents downgrading usernotes version like a butt
users: {},
constants: {
users: [],
warnings: [],
},
};
const mgr = new self._constManager(deflated.constants);
$.each(notes.users, (name, user) => {
deflated.users[name] = {
ns: user.notes.filter(note => {
if (note === undefined) {
self.log('WARNING: undefined note removed');
}
return note !== undefined;
}).map(note => deflateNote(notes.ver, note, mgr)),
};
});
return deflated;
} |
JavaScript | function postToWiki (page, data, reason, isJSON, updateAM) {
self.log('posting to wiki');
TB.ui.textFeedback('saving to wiki', TB.ui.FEEDBACK_NEUTRAL);
TBApi.postToWiki(page, subreddit, data, reason, isJSON, updateAM, (succ, err) => {
self.log(`save succ = ${succ}`);
if (!succ) {
self.log(err);
if (page === 'config/automoderator') {
const $error = $body.find('.edit_automoderator_config .error');
$error.show();
const saveError = err.responseJSON.special_errors[0];
$error.find('.errorMessage').html(TBStorage.purify(saveError));
TB.ui.textFeedback('Config not saved!', TB.ui.FEEDBACK_NEGATIVE);
} else {
TB.ui.textFeedback(err.responseText, TB.ui.FEEDBACK_NEGATIVE);
}
} else {
if (page === 'config/automoderator') {
$body.find('.edit_automoderator_config .error').hide();
}
self.log('clearing cache');
TBCore.clearCache();
TB.ui.textFeedback('wiki page saved', TB.ui.FEEDBACK_POSITIVE);
}
});
} | function postToWiki (page, data, reason, isJSON, updateAM) {
self.log('posting to wiki');
TB.ui.textFeedback('saving to wiki', TB.ui.FEEDBACK_NEUTRAL);
TBApi.postToWiki(page, subreddit, data, reason, isJSON, updateAM, (succ, err) => {
self.log(`save succ = ${succ}`);
if (!succ) {
self.log(err);
if (page === 'config/automoderator') {
const $error = $body.find('.edit_automoderator_config .error');
$error.show();
const saveError = err.responseJSON.special_errors[0];
$error.find('.errorMessage').html(TBStorage.purify(saveError));
TB.ui.textFeedback('Config not saved!', TB.ui.FEEDBACK_NEGATIVE);
} else {
TB.ui.textFeedback(err.responseText, TB.ui.FEEDBACK_NEGATIVE);
}
} else {
if (page === 'config/automoderator') {
$body.find('.edit_automoderator_config .error').hide();
}
self.log('clearing cache');
TBCore.clearCache();
TB.ui.textFeedback('wiki page saved', TB.ui.FEEDBACK_POSITIVE);
}
});
} |
JavaScript | function wikiTabContent (tabname) {
let page;
let actualPage;
switch (tabname) {
case 'edit_toolbox_config':
page = 'toolbox';
actualPage = 'toolbox';
break;
case 'edit_user_notes':
page = 'usernotes';
actualPage = 'usernotes';
break;
case 'edit_automoderator_config':
page = 'automoderator';
actualPage = 'config/automoderator';
break;
}
const $wikiContentArea = $body.find(`.tb-window-tab.${tabname}`),
$wikiFooterArea = $body.find(`.tb-window-footer.${tabname}`);
const $textArea = $wikiContentArea.find('.edit-wikidata'),
$saveButton = $wikiFooterArea.find('.save-wiki-data');
if (TB.storage.getSetting('Syntax', 'enabled', true)) {
$body.addClass('mod-syntax');
let configEditor;
let defaultMode = 'default';
const selectedTheme = TB.storage.getSetting('Syntax', 'selectedTheme') || 'dracula';
const enableWordWrap = TB.storage.getSetting('Syntax', 'enableWordWrap');
if (page === 'automoderator') {
defaultMode = 'text/x-yaml';
} else {
defaultMode = 'application/json';
}
const keyboardShortcutsHelper = `<div class="tb-syntax-keyboard">
<b>Keyboard shortcuts</b>
<ul>
<li><i>F11:</i> Fullscreen</li>
<li><i>Esc:</i> Close Fullscreen</li>
<li><i>Ctrl-/ / Cmd-/:</i> Toggle comment</li>
<li><i>Ctrl-F / Cmd-F:</i> Start searching</li>
<li><i>Ctrl-Alt-F / Cmd-Alt-F:</i> Persistent search (dialog doesn't autoclose) </li>
<li><i>Ctrl-G / Cmd-G:</i> Find next</li>
<li><i>Shift-Ctrl-G / Shift-Cmd-G:</i> Find previous</li>
<li><i>Shift-Ctrl-F / Cmd-Option-F:</i> Replace</li>
<li><i>Shift-Ctrl-R / Shift-Cmd-Option-F:</i> Replace all</li>
<li><i>Alt-G:</i> Jump to line </li>
<li><i>Ctrl-Space / Cmd-Space:</i> autocomplete</li>
</ul>
</div>`;
$textArea.each((index, elem) => {
// This makes sure codemirror behaves and uses spaces instead of tabs.
function betterTab (cm) {
if (cm.somethingSelected()) {
cm.indentSelection('add');
} else {
cm.replaceSelection(cm.getOption('indentWithTabs') ? '\t' :
Array(cm.getOption('indentUnit') + 1).join(' '), 'end', '+input');
}
}
// Editor setup.
configEditor = CodeMirror.fromTextArea(elem, {
mode: defaultMode,
autoCloseBrackets: true,
lineNumbers: true,
theme: selectedTheme,
indentUnit: 4,
extraKeys: {
'Ctrl-Alt-F': 'findPersistent',
'Ctrl-/': 'toggleComment',
'F11' (cm) {
cm.setOption('fullScreen', !cm.getOption('fullScreen'));
},
'Esc' (cm) {
if (cm.getOption('fullScreen')) {
cm.setOption('fullScreen', false);
}
},
'Tab': betterTab,
'Shift-Tab' (cm) {
cm.indentSelection('subtract');
},
},
lineWrapping: enableWordWrap,
});
$body.find('.CodeMirror.CodeMirror-wrap').prepend(keyboardShortcutsHelper);
});
$textArea.val('getting wiki data...');
configEditor.setValue('getting wiki data...');
configEditor.on('change', () => {
configEditor.save();
});
TBApi.readFromWiki(subreddit, actualPage, false, resp => {
if (resp === TBCore.WIKI_PAGE_UNKNOWN) {
$textArea.val('error getting wiki data.');
configEditor.setValue('error getting wiki data.');
return;
}
if (resp === TBCore.NO_WIKI_PAGE) {
$textArea.val('');
configEditor.setValue('');
$saveButton.show();
$saveButton.attr('page', page);
return;
}
resp = TBHelpers.unescapeJSON(resp);
if (page !== 'automoderator') {
resp = JSON.parse(resp);
resp = JSON.stringify(resp, null, 4);
}
// Found it, show it.
$textArea.val(resp);
configEditor.setValue(resp);
$saveButton.show();
$saveButton.attr('page', page);
});
} else {
// load the text area, but not the save button.
$textArea.val('getting wiki data...');
TBApi.readFromWiki(subreddit, actualPage, false, resp => {
if (resp === TBCore.WIKI_PAGE_UNKNOWN) {
$textArea.val('error getting wiki data.');
return;
}
if (resp === TBCore.NO_WIKI_PAGE) {
$textArea.val('');
$saveButton.show();
$saveButton.attr('page', page);
return;
}
resp = humanizeUsernotes(resp);
resp = TBHelpers.unescapeJSON(resp);
// Found it, show it.
$textArea.val(resp);
$saveButton.show();
$saveButton.attr('page', page);
});
}
function humanizeUsernotes (notes) {
if (notes.ver >= 6) {
return decompressBlob(notes);
} else {
return notes;
}
function decompressBlob (notes) {
const decompressed = TBHelpers.zlibInflate(notes.blob);
// Update notes with actual notes
delete notes.blob;
notes.users = JSON.parse(decompressed);
return notes;
}
}
} | function wikiTabContent (tabname) {
let page;
let actualPage;
switch (tabname) {
case 'edit_toolbox_config':
page = 'toolbox';
actualPage = 'toolbox';
break;
case 'edit_user_notes':
page = 'usernotes';
actualPage = 'usernotes';
break;
case 'edit_automoderator_config':
page = 'automoderator';
actualPage = 'config/automoderator';
break;
}
const $wikiContentArea = $body.find(`.tb-window-tab.${tabname}`),
$wikiFooterArea = $body.find(`.tb-window-footer.${tabname}`);
const $textArea = $wikiContentArea.find('.edit-wikidata'),
$saveButton = $wikiFooterArea.find('.save-wiki-data');
if (TB.storage.getSetting('Syntax', 'enabled', true)) {
$body.addClass('mod-syntax');
let configEditor;
let defaultMode = 'default';
const selectedTheme = TB.storage.getSetting('Syntax', 'selectedTheme') || 'dracula';
const enableWordWrap = TB.storage.getSetting('Syntax', 'enableWordWrap');
if (page === 'automoderator') {
defaultMode = 'text/x-yaml';
} else {
defaultMode = 'application/json';
}
const keyboardShortcutsHelper = `<div class="tb-syntax-keyboard">
<b>Keyboard shortcuts</b>
<ul>
<li><i>F11:</i> Fullscreen</li>
<li><i>Esc:</i> Close Fullscreen</li>
<li><i>Ctrl-/ / Cmd-/:</i> Toggle comment</li>
<li><i>Ctrl-F / Cmd-F:</i> Start searching</li>
<li><i>Ctrl-Alt-F / Cmd-Alt-F:</i> Persistent search (dialog doesn't autoclose) </li>
<li><i>Ctrl-G / Cmd-G:</i> Find next</li>
<li><i>Shift-Ctrl-G / Shift-Cmd-G:</i> Find previous</li>
<li><i>Shift-Ctrl-F / Cmd-Option-F:</i> Replace</li>
<li><i>Shift-Ctrl-R / Shift-Cmd-Option-F:</i> Replace all</li>
<li><i>Alt-G:</i> Jump to line </li>
<li><i>Ctrl-Space / Cmd-Space:</i> autocomplete</li>
</ul>
</div>`;
$textArea.each((index, elem) => {
// This makes sure codemirror behaves and uses spaces instead of tabs.
function betterTab (cm) {
if (cm.somethingSelected()) {
cm.indentSelection('add');
} else {
cm.replaceSelection(cm.getOption('indentWithTabs') ? '\t' :
Array(cm.getOption('indentUnit') + 1).join(' '), 'end', '+input');
}
}
// Editor setup.
configEditor = CodeMirror.fromTextArea(elem, {
mode: defaultMode,
autoCloseBrackets: true,
lineNumbers: true,
theme: selectedTheme,
indentUnit: 4,
extraKeys: {
'Ctrl-Alt-F': 'findPersistent',
'Ctrl-/': 'toggleComment',
'F11' (cm) {
cm.setOption('fullScreen', !cm.getOption('fullScreen'));
},
'Esc' (cm) {
if (cm.getOption('fullScreen')) {
cm.setOption('fullScreen', false);
}
},
'Tab': betterTab,
'Shift-Tab' (cm) {
cm.indentSelection('subtract');
},
},
lineWrapping: enableWordWrap,
});
$body.find('.CodeMirror.CodeMirror-wrap').prepend(keyboardShortcutsHelper);
});
$textArea.val('getting wiki data...');
configEditor.setValue('getting wiki data...');
configEditor.on('change', () => {
configEditor.save();
});
TBApi.readFromWiki(subreddit, actualPage, false, resp => {
if (resp === TBCore.WIKI_PAGE_UNKNOWN) {
$textArea.val('error getting wiki data.');
configEditor.setValue('error getting wiki data.');
return;
}
if (resp === TBCore.NO_WIKI_PAGE) {
$textArea.val('');
configEditor.setValue('');
$saveButton.show();
$saveButton.attr('page', page);
return;
}
resp = TBHelpers.unescapeJSON(resp);
if (page !== 'automoderator') {
resp = JSON.parse(resp);
resp = JSON.stringify(resp, null, 4);
}
// Found it, show it.
$textArea.val(resp);
configEditor.setValue(resp);
$saveButton.show();
$saveButton.attr('page', page);
});
} else {
// load the text area, but not the save button.
$textArea.val('getting wiki data...');
TBApi.readFromWiki(subreddit, actualPage, false, resp => {
if (resp === TBCore.WIKI_PAGE_UNKNOWN) {
$textArea.val('error getting wiki data.');
return;
}
if (resp === TBCore.NO_WIKI_PAGE) {
$textArea.val('');
$saveButton.show();
$saveButton.attr('page', page);
return;
}
resp = humanizeUsernotes(resp);
resp = TBHelpers.unescapeJSON(resp);
// Found it, show it.
$textArea.val(resp);
$saveButton.show();
$saveButton.attr('page', page);
});
}
function humanizeUsernotes (notes) {
if (notes.ver >= 6) {
return decompressBlob(notes);
} else {
return notes;
}
function decompressBlob (notes) {
const decompressed = TBHelpers.zlibInflate(notes.blob);
// Update notes with actual notes
delete notes.blob;
notes.users = JSON.parse(decompressed);
return notes;
}
}
} |
JavaScript | function removalReasonsContent () {
if (config.removalReasons && config.removalReasons.reasons.length > 0) {
let i = 0;
$(config.removalReasons.reasons).each(function () {
let label = unescape(this.text);
if (label === '') {
label = '<span style="color: #cecece">(no reason)</span>';
} else {
if (label.length > 200) {
label = `${label.substring(0, 197)}...`;
}
label = TBHelpers.htmlEncode(label);
}
const removalReasonText = unescape(config.removalReasons.reasons[i].text) || '',
removalReasonTitle = config.removalReasons.reasons[i].title || '',
removalReasonFlairText = config.removalReasons.reasons[i].flairText || '',
removalReasonFlairCSS = config.removalReasons.reasons[i].flairCSS || '';
const removalReasonTemplate = `
<tr class="removal-reason" data-reason="{{i}}" data-subreddit="{{subreddit}}">
<td class="removal-reasons-buttons">
<a href="javascript:;" data-reason="{{i}}" data-subreddit="{{subreddit}}" class="edit tb-icons">${TBui.icons.edit}</a> <br>
<a href="javascript:;" data-reason="{{i}}" data-subreddit="{{subreddit}}" class="delete tb-icons tb-icons-negative">${TBui.icons.delete}</a>
</td>
<td class="removal-reasons-content" data-reason="{{i}}">
<span class="removal-reason-label" data-for="reason-{{subreddit}}-{{i++}}"><span><h3 class="removal-title">{{removalReasonTitle}}</h3>{{label}}</span></span><br>
<span class="removal-reason-edit">
<input type="text" class="tb-input" name="removal-title" placeholder="removal reason title" value="{{removalReasonTitle}}"/><br/>
<textarea class="tb-input edit-area">{{removalReasonText}}</textarea><br/>
<input type="text" class="tb-input" name="flair-text" placeholder="flair text" value="{{removalReasonFlairText}}"/><br/>
<input type="text" class="tb-input" name="flair-css" placeholder="flair css class" value="{{removalReasonFlairCSS}}"/><br/>
<input type="text" class="tb-input" name="edit-note" placeholder="reason for wiki edit (optional)" /><br>
<input class="save-edit-reason tb-action-button" type="button" value="Save reason" /><input class="cancel-edit-reason tb-action-button" type="button" value="Cancel" />
</span>
</td>
</tr>`;
const removalReasonTemplateHTML = TBHelpers.template(removalReasonTemplate, {
i,
subreddit,
'i++': i++,
label,
'removalReasonText': TBHelpers.escapeHTML(removalReasonText),
removalReasonTitle,
removalReasonFlairText,
removalReasonFlairCSS,
});
const $removalReasonsList = $body.find('.edit_removal_reasons #tb-removal-reasons-list');
$removalReasonsList.append(removalReasonTemplateHTML);
});
}
} | function removalReasonsContent () {
if (config.removalReasons && config.removalReasons.reasons.length > 0) {
let i = 0;
$(config.removalReasons.reasons).each(function () {
let label = unescape(this.text);
if (label === '') {
label = '<span style="color: #cecece">(no reason)</span>';
} else {
if (label.length > 200) {
label = `${label.substring(0, 197)}...`;
}
label = TBHelpers.htmlEncode(label);
}
const removalReasonText = unescape(config.removalReasons.reasons[i].text) || '',
removalReasonTitle = config.removalReasons.reasons[i].title || '',
removalReasonFlairText = config.removalReasons.reasons[i].flairText || '',
removalReasonFlairCSS = config.removalReasons.reasons[i].flairCSS || '';
const removalReasonTemplate = `
<tr class="removal-reason" data-reason="{{i}}" data-subreddit="{{subreddit}}">
<td class="removal-reasons-buttons">
<a href="javascript:;" data-reason="{{i}}" data-subreddit="{{subreddit}}" class="edit tb-icons">${TBui.icons.edit}</a> <br>
<a href="javascript:;" data-reason="{{i}}" data-subreddit="{{subreddit}}" class="delete tb-icons tb-icons-negative">${TBui.icons.delete}</a>
</td>
<td class="removal-reasons-content" data-reason="{{i}}">
<span class="removal-reason-label" data-for="reason-{{subreddit}}-{{i++}}"><span><h3 class="removal-title">{{removalReasonTitle}}</h3>{{label}}</span></span><br>
<span class="removal-reason-edit">
<input type="text" class="tb-input" name="removal-title" placeholder="removal reason title" value="{{removalReasonTitle}}"/><br/>
<textarea class="tb-input edit-area">{{removalReasonText}}</textarea><br/>
<input type="text" class="tb-input" name="flair-text" placeholder="flair text" value="{{removalReasonFlairText}}"/><br/>
<input type="text" class="tb-input" name="flair-css" placeholder="flair css class" value="{{removalReasonFlairCSS}}"/><br/>
<input type="text" class="tb-input" name="edit-note" placeholder="reason for wiki edit (optional)" /><br>
<input class="save-edit-reason tb-action-button" type="button" value="Save reason" /><input class="cancel-edit-reason tb-action-button" type="button" value="Cancel" />
</span>
</td>
</tr>`;
const removalReasonTemplateHTML = TBHelpers.template(removalReasonTemplate, {
i,
subreddit,
'i++': i++,
label,
'removalReasonText': TBHelpers.escapeHTML(removalReasonText),
removalReasonTitle,
removalReasonFlairText,
removalReasonFlairCSS,
});
const $removalReasonsList = $body.find('.edit_removal_reasons #tb-removal-reasons-list');
$removalReasonsList.append(removalReasonTemplateHTML);
});
}
} |
JavaScript | function modMacrosContent () {
if (config.modMacros && config.modMacros.length > 0) {
$(config.modMacros).each((i, item) => {
let label = unescape(item.text);
if (label === '') {
label = '<span style="color: #cecece">(no macro)</span>';
} else {
if (label.length > 200) {
label = `${label.substring(0, 197)}...`;
}
label = TBHelpers.htmlEncode(label);
}
const macro = config.modMacros[i];
const modMacroText = unescape(macro.text) || '';
const modMacroTitle = macro.title || '';
const modMacroTemplate = `
<tr class="mod-macro" data-macro="{{i}}" data-subreddit="{{subreddit}}">
<td class="mod-macros-buttons">
<a href="javascript:;" data-macro="{{i}}" data-subreddit="{{subreddit}}" class="edit tb-icons">${TBui.icons.edit}</a> <br>
<a href="javascript:;" data-macro="{{i}}" data-subreddit="{{subreddit}}" class="delete tb-icons tb-icons-negative">${TBui.icons.delete}</a>
</td>
<td class="mod-macros-content" data-macro="{{i}}">
<span class="mod-macro-label" data-for="macro-{{subreddit}}-{{i}}"><span><h3 class="macro-title">{{modMacroTitle}}</h3>{{label}}</span></span><br>
<span class="mod-macro-edit">
<textarea class="tb-input edit-area">{{modMacroText}}</textarea><br/>
<input type="text" class="macro-title tb-input" name="macro-title" placeholder="macro title" value="{{modMacroTitle}}" /><br>
<div class="tb-macro-actions">
<div class="tb-macro-actions-row">
<h2>Reply</h2>
<label><input type="checkbox" class="{{i}}-distinguish" id="distinguish">distinguish</label>
<label><input type="checkbox" class="{{i}}-sticky" id="sticky">sticky comment</label>
<label><input type="checkbox" class="{{i}}-lockreply" id="lockreply">lock reply</label>
</div>
<div class="tb-macro-actions-row">
<h2>Item</h2>
<label><input type="checkbox" class="{{i}}-approveitem" id="approveitem">approve item</label>
<label><input type="checkbox" class="{{i}}-removeitem" id="removeitem">remove item</label>
<label><input type="checkbox" class="{{i}}-lockitem" id="lockitem">lock item</label>
<label><input type="checkbox" class="{{i}}-archivemodmail" id="archivemodmail">archive modmail</label>
<label><input type="checkbox" class="{{i}}-highlightmodmail" id="highlightmodmail">highlight modmail</label><br>
</div>
<div class="tb-macro-actions-row">
<h2>User</h2>
<label><input type="checkbox" class="{{i}}-banuser" id="banuser">ban user</label>
<label><input type="checkbox" class="{{i}}-muteuser" id="muteuser">mute user</label>
</div>
</div>
<input type="text" class="tb-input" name="edit-note" placeholder="reason for wiki edit (optional)" /><br>
<input class="save-edit-macro tb-action-button" type="button" value="Save macro" /><input class="cancel-edit-macro tb-action-button" type="button" value="Cancel editing macro" />
</span>
</td>
</tr>`;
const modMacroTemplateHTML = TBHelpers.template(modMacroTemplate, {
i,
subreddit,
label,
modMacroText,
modMacroTitle,
});
const $removalReasonsList = $body.find('.edit_mod_macros #tb-mod-macros-list');
$removalReasonsList.append(modMacroTemplateHTML);
$(`.${i}-distinguish`).prop('checked', macro.distinguish);
$(`.${i}-banuser`).prop('checked', macro.ban);
$(`.${i}-muteuser`).prop('checked', macro.mute);
$(`.${i}-removeitem`).prop('checked', macro.remove);
$(`.${i}-approveitem`).prop('checked', macro.approve);
$(`.${i}-lockitem`).prop('checked', macro.lockthread);
$(`.${i}-lockreply`).prop('checked', macro.lockreply);
$(`.${i}-sticky`).prop('checked', macro.sticky);
$(`.${i}-archivemodmail`).prop('checked', macro.archivemodmail);
$(`.${i}-highlightmodmail`).prop('checked', macro.highlightmodmail);
});
}
} | function modMacrosContent () {
if (config.modMacros && config.modMacros.length > 0) {
$(config.modMacros).each((i, item) => {
let label = unescape(item.text);
if (label === '') {
label = '<span style="color: #cecece">(no macro)</span>';
} else {
if (label.length > 200) {
label = `${label.substring(0, 197)}...`;
}
label = TBHelpers.htmlEncode(label);
}
const macro = config.modMacros[i];
const modMacroText = unescape(macro.text) || '';
const modMacroTitle = macro.title || '';
const modMacroTemplate = `
<tr class="mod-macro" data-macro="{{i}}" data-subreddit="{{subreddit}}">
<td class="mod-macros-buttons">
<a href="javascript:;" data-macro="{{i}}" data-subreddit="{{subreddit}}" class="edit tb-icons">${TBui.icons.edit}</a> <br>
<a href="javascript:;" data-macro="{{i}}" data-subreddit="{{subreddit}}" class="delete tb-icons tb-icons-negative">${TBui.icons.delete}</a>
</td>
<td class="mod-macros-content" data-macro="{{i}}">
<span class="mod-macro-label" data-for="macro-{{subreddit}}-{{i}}"><span><h3 class="macro-title">{{modMacroTitle}}</h3>{{label}}</span></span><br>
<span class="mod-macro-edit">
<textarea class="tb-input edit-area">{{modMacroText}}</textarea><br/>
<input type="text" class="macro-title tb-input" name="macro-title" placeholder="macro title" value="{{modMacroTitle}}" /><br>
<div class="tb-macro-actions">
<div class="tb-macro-actions-row">
<h2>Reply</h2>
<label><input type="checkbox" class="{{i}}-distinguish" id="distinguish">distinguish</label>
<label><input type="checkbox" class="{{i}}-sticky" id="sticky">sticky comment</label>
<label><input type="checkbox" class="{{i}}-lockreply" id="lockreply">lock reply</label>
</div>
<div class="tb-macro-actions-row">
<h2>Item</h2>
<label><input type="checkbox" class="{{i}}-approveitem" id="approveitem">approve item</label>
<label><input type="checkbox" class="{{i}}-removeitem" id="removeitem">remove item</label>
<label><input type="checkbox" class="{{i}}-lockitem" id="lockitem">lock item</label>
<label><input type="checkbox" class="{{i}}-archivemodmail" id="archivemodmail">archive modmail</label>
<label><input type="checkbox" class="{{i}}-highlightmodmail" id="highlightmodmail">highlight modmail</label><br>
</div>
<div class="tb-macro-actions-row">
<h2>User</h2>
<label><input type="checkbox" class="{{i}}-banuser" id="banuser">ban user</label>
<label><input type="checkbox" class="{{i}}-muteuser" id="muteuser">mute user</label>
</div>
</div>
<input type="text" class="tb-input" name="edit-note" placeholder="reason for wiki edit (optional)" /><br>
<input class="save-edit-macro tb-action-button" type="button" value="Save macro" /><input class="cancel-edit-macro tb-action-button" type="button" value="Cancel editing macro" />
</span>
</td>
</tr>`;
const modMacroTemplateHTML = TBHelpers.template(modMacroTemplate, {
i,
subreddit,
label,
modMacroText,
modMacroTitle,
});
const $removalReasonsList = $body.find('.edit_mod_macros #tb-mod-macros-list');
$removalReasonsList.append(modMacroTemplateHTML);
$(`.${i}-distinguish`).prop('checked', macro.distinguish);
$(`.${i}-banuser`).prop('checked', macro.ban);
$(`.${i}-muteuser`).prop('checked', macro.mute);
$(`.${i}-removeitem`).prop('checked', macro.remove);
$(`.${i}-approveitem`).prop('checked', macro.approve);
$(`.${i}-lockitem`).prop('checked', macro.lockthread);
$(`.${i}-lockreply`).prop('checked', macro.lockreply);
$(`.${i}-sticky`).prop('checked', macro.sticky);
$(`.${i}-archivemodmail`).prop('checked', macro.archivemodmail);
$(`.${i}-highlightmodmail`).prop('checked', macro.highlightmodmail);
});
}
} |
JavaScript | function addNewMMMacro () {
const $thing = $body.find('.InfoBar'),
info = TBCore.getThingInfo($thing, true);
// Don't add macro button twice.
if ($body.find('.tb-usertext-buttons').length) {
return;
}
// are we a mod?
if (!info.subreddit) {
return;
}
self.log(info.subreddit);
// if we don't have a config, get it. If it fails, return.
getConfig(info.subreddit, (success, config) => {
// if we're a mod, add macros to top level reply button.
if (success && config.length > 0) {
const macroButtonHtml = `<select class="tb-macro-select tb-action-button" data-subreddit="${info.subreddit}"><option value=${MACROS}>macros</option></select>`;
$body.find('.ThreadViewerReplyForm__replyOptions').after(`<div class="tb-usertext-buttons tb-macro-newmm">${macroButtonHtml}</div>`);
populateSelect('.tb-macro-select', info.subreddit, config);
}
});
} | function addNewMMMacro () {
const $thing = $body.find('.InfoBar'),
info = TBCore.getThingInfo($thing, true);
// Don't add macro button twice.
if ($body.find('.tb-usertext-buttons').length) {
return;
}
// are we a mod?
if (!info.subreddit) {
return;
}
self.log(info.subreddit);
// if we don't have a config, get it. If it fails, return.
getConfig(info.subreddit, (success, config) => {
// if we're a mod, add macros to top level reply button.
if (success && config.length > 0) {
const macroButtonHtml = `<select class="tb-macro-select tb-action-button" data-subreddit="${info.subreddit}"><option value=${MACROS}>macros</option></select>`;
$body.find('.ThreadViewerReplyForm__replyOptions').after(`<div class="tb-usertext-buttons tb-macro-newmm">${macroButtonHtml}</div>`);
populateSelect('.tb-macro-select', info.subreddit, config);
}
});
} |
JavaScript | async function readPage (path) {
const f = await resolve(path)
if (cache.hasOwnProperty(f)) {
return cache[f]
}
const source = await fs.readFile(f, 'utf8')
const { component } = JSON.parse(source)
cache[f] = component
return component
} | async function readPage (path) {
const f = await resolve(path)
if (cache.hasOwnProperty(f)) {
return cache[f]
}
const source = await fs.readFile(f, 'utf8')
const { component } = JSON.parse(source)
cache[f] = component
return component
} |
JavaScript | transform ({ content, sourceMap, interpolatedName }) {
// Only handle .js files
if (!(/\.js$/.test(interpolatedName))) {
return { content, sourceMap }
}
const transpiled = babelCore.transform(content, {
babelrc: false,
sourceMaps: dev ? 'both' : false,
// Here we need to resolve all modules to the absolute paths.
// Earlier we did it with the babel-preset.
// But since we don't transpile ES2015 in the preset this is not resolving.
// That's why we need to do it here.
// See more: https://github.com/zeit/next.js/issues/951
plugins: [
[require.resolve('babel-plugin-transform-es2015-modules-commonjs')],
[
require.resolve('babel-plugin-module-resolver'),
{
alias: {
'babel-runtime': relativeResolve('babel-runtime/package'),
'next/link': relativeResolve('../../lib/link'),
'next/prefetch': relativeResolve('../../lib/prefetch'),
'next/css': relativeResolve('../../lib/css'),
'next/head': relativeResolve('../../lib/head'),
'next/document': relativeResolve('../../server/document'),
'next/router': relativeResolve('../../lib/router'),
'next/error': relativeResolve('../../lib/error'),
'styled-jsx/style': relativeResolve('styled-jsx/style')
}
}
]
],
inputSourceMap: sourceMap
})
return {
content: transpiled.code,
sourceMap: transpiled.map
}
} | transform ({ content, sourceMap, interpolatedName }) {
// Only handle .js files
if (!(/\.js$/.test(interpolatedName))) {
return { content, sourceMap }
}
const transpiled = babelCore.transform(content, {
babelrc: false,
sourceMaps: dev ? 'both' : false,
// Here we need to resolve all modules to the absolute paths.
// Earlier we did it with the babel-preset.
// But since we don't transpile ES2015 in the preset this is not resolving.
// That's why we need to do it here.
// See more: https://github.com/zeit/next.js/issues/951
plugins: [
[require.resolve('babel-plugin-transform-es2015-modules-commonjs')],
[
require.resolve('babel-plugin-module-resolver'),
{
alias: {
'babel-runtime': relativeResolve('babel-runtime/package'),
'next/link': relativeResolve('../../lib/link'),
'next/prefetch': relativeResolve('../../lib/prefetch'),
'next/css': relativeResolve('../../lib/css'),
'next/head': relativeResolve('../../lib/head'),
'next/document': relativeResolve('../../server/document'),
'next/router': relativeResolve('../../lib/router'),
'next/error': relativeResolve('../../lib/error'),
'styled-jsx/style': relativeResolve('styled-jsx/style')
}
}
]
],
inputSourceMap: sourceMap
})
return {
content: transpiled.code,
sourceMap: transpiled.map
}
} |
JavaScript | async init(initExpress = true) {
logger('Iniciando servidor HTTP ...');
if (this.libraryManager && !this.libraryManager.isCompiled) {
await this.libraryManager.build();
}
logger('Aplicando configuración a servidor HTTP ...');
const profileConfig = this.configLoader.getConfig('GorilaHttp') || {};
if (initExpress) {
this.port = (process.env.PORT ? parseInt(process.env.PORT) : profileConfig.port || 80);
this.app.set('port', this.port);
}
if (profileConfig.dev && profileConfig.dev.showExternalIp) {
const interfaces = require("os").networkInterfaces();
if (profileConfig.dev.interfaceNetwork) {
const inter = interfaces[profileConfig.dev.interfaceNetwork];
if (inter) {
this.externalIp = inter.find(item => {
return item.family == 'IPv4';
}).address;
} else {
console.error(`\nLa interfáz de red "${profileConfig.dev.interfaceNetwork}" no existe!.\nSe pueden usar las isguientes interfaces:\n${Object.keys(interfaces).join(', ')}`);
console.error('\nLa interfáz de red ' + profileConfig.dev.interfaceNetwork + ' no existe!.\nSe pueden usar las isguientes interfaces:\n' + Object.keys(interfaces).join(', '));
}
} else {
console.error('\nNo se definió una interfaz de red.\nSe pueden usar las isguientes interfaces:\n' + Object.keys(interfaces).join(', '));
}
}
if (profileConfig.events && profileConfig.events.beforeConfig) {
this.app = profileConfig.events.beforeConfig(this.app);
}
if (profileConfig.pathsPublic) {
profileConfig.pathsPublic.forEach(path => {
const dirPublic = Path.normalize(path.dir);
this.app.use(path.route, express.static(dirPublic));
});
}
if (profileConfig.engineTemplates) {
this.app.engine(profileConfig.engineTemplates.ext, profileConfig.engineTemplates.callback);
this.app.set('views', Path.normalize(profileConfig.engineTemplates.dirViews));
this.app.set('view engine', profileConfig.engineTemplates.name);
}
if (profileConfig.events && profileConfig.events.afterConfig) {
this.app = profileConfig.events.afterConfig(this.app);
}
this.app.use(express.json())
for (const controller of this.HTTPControllersDeclarations) {
this.HTTPControllersInstances.push(new controller(this.libraryManager));
}
logger('Express instanciado!');
logger('Cargando controladores HTTP ...');
for (const controller of this.HTTPControllersDeclarations) {
this.HTTPControllersInstances.push(new controller(this.libraryManager));
}
for (let index = 0; index < this.HTTPControllersInstances.length; index++) {
const controller = this.HTTPControllersInstances[index];
if (controller.prefix) {
const firsteChart = controller.prefix[0];
const lastChart = controller.prefix[(controller.prefix.length - 1)];
if (lastChart === '/') {
controller.prefix.pop();
}
if (firsteChart !== '/') {
controller.prefix = '/' + controller.prefix;
}
this.app.use(controller.prefix, controller.router);
} else {
this.app.use(controller.router);
}
delete controller.router;
}
logger('Controladores HTTP cargados!');
logger('Iniciando servidor HTTP',);
if (profileConfig.events && profileConfig.events.beforeStarting) {
profileConfig.events.beforeStarting(this.app);
}
if (initExpress) {
await new Promise((resolve) => {
this.app.listen(this.port, () => {
logger('Servidor corriendo en el puerto ' + this.port);
resolve();
});
});
} else {
logger('Servidor HTTP listo!');
}
} | async init(initExpress = true) {
logger('Iniciando servidor HTTP ...');
if (this.libraryManager && !this.libraryManager.isCompiled) {
await this.libraryManager.build();
}
logger('Aplicando configuración a servidor HTTP ...');
const profileConfig = this.configLoader.getConfig('GorilaHttp') || {};
if (initExpress) {
this.port = (process.env.PORT ? parseInt(process.env.PORT) : profileConfig.port || 80);
this.app.set('port', this.port);
}
if (profileConfig.dev && profileConfig.dev.showExternalIp) {
const interfaces = require("os").networkInterfaces();
if (profileConfig.dev.interfaceNetwork) {
const inter = interfaces[profileConfig.dev.interfaceNetwork];
if (inter) {
this.externalIp = inter.find(item => {
return item.family == 'IPv4';
}).address;
} else {
console.error(`\nLa interfáz de red "${profileConfig.dev.interfaceNetwork}" no existe!.\nSe pueden usar las isguientes interfaces:\n${Object.keys(interfaces).join(', ')}`);
console.error('\nLa interfáz de red ' + profileConfig.dev.interfaceNetwork + ' no existe!.\nSe pueden usar las isguientes interfaces:\n' + Object.keys(interfaces).join(', '));
}
} else {
console.error('\nNo se definió una interfaz de red.\nSe pueden usar las isguientes interfaces:\n' + Object.keys(interfaces).join(', '));
}
}
if (profileConfig.events && profileConfig.events.beforeConfig) {
this.app = profileConfig.events.beforeConfig(this.app);
}
if (profileConfig.pathsPublic) {
profileConfig.pathsPublic.forEach(path => {
const dirPublic = Path.normalize(path.dir);
this.app.use(path.route, express.static(dirPublic));
});
}
if (profileConfig.engineTemplates) {
this.app.engine(profileConfig.engineTemplates.ext, profileConfig.engineTemplates.callback);
this.app.set('views', Path.normalize(profileConfig.engineTemplates.dirViews));
this.app.set('view engine', profileConfig.engineTemplates.name);
}
if (profileConfig.events && profileConfig.events.afterConfig) {
this.app = profileConfig.events.afterConfig(this.app);
}
this.app.use(express.json())
for (const controller of this.HTTPControllersDeclarations) {
this.HTTPControllersInstances.push(new controller(this.libraryManager));
}
logger('Express instanciado!');
logger('Cargando controladores HTTP ...');
for (const controller of this.HTTPControllersDeclarations) {
this.HTTPControllersInstances.push(new controller(this.libraryManager));
}
for (let index = 0; index < this.HTTPControllersInstances.length; index++) {
const controller = this.HTTPControllersInstances[index];
if (controller.prefix) {
const firsteChart = controller.prefix[0];
const lastChart = controller.prefix[(controller.prefix.length - 1)];
if (lastChart === '/') {
controller.prefix.pop();
}
if (firsteChart !== '/') {
controller.prefix = '/' + controller.prefix;
}
this.app.use(controller.prefix, controller.router);
} else {
this.app.use(controller.router);
}
delete controller.router;
}
logger('Controladores HTTP cargados!');
logger('Iniciando servidor HTTP',);
if (profileConfig.events && profileConfig.events.beforeStarting) {
profileConfig.events.beforeStarting(this.app);
}
if (initExpress) {
await new Promise((resolve) => {
this.app.listen(this.port, () => {
logger('Servidor corriendo en el puerto ' + this.port);
resolve();
});
});
} else {
logger('Servidor HTTP listo!');
}
} |
JavaScript | rotate() {
let timeGap = Date.now() - this.lastRotateTime;
while (this.isWindowPercentile && timeGap > this.rotateTime) {
// Refresh current window bucket and move to next one
this.windowBuckets[this.currentBucketIndex] = new TDigest();
this.currentBucketIndex++;
// Rotate if reached the end
this.currentBucketIndex =
this.currentBucketIndex >= this.windowBuckets.length
? 0
: this.currentBucketIndex;
// Update time gap
timeGap -= this.rotateTime;
this.lastRotateTime += this.rotateTime;
}
return this.windowBuckets[this.currentBucketIndex];
} | rotate() {
let timeGap = Date.now() - this.lastRotateTime;
while (this.isWindowPercentile && timeGap > this.rotateTime) {
// Refresh current window bucket and move to next one
this.windowBuckets[this.currentBucketIndex] = new TDigest();
this.currentBucketIndex++;
// Rotate if reached the end
this.currentBucketIndex =
this.currentBucketIndex >= this.windowBuckets.length
? 0
: this.currentBucketIndex;
// Update time gap
timeGap -= this.rotateTime;
this.lastRotateTime += this.rotateTime;
}
return this.windowBuckets[this.currentBucketIndex];
} |
JavaScript | function auth(){
return getNewSessionToken(baseURL).then((sessionID)=>{
authenticateAnonymous(baseURL,sessionID)
return sessionID
}).catch((err)=>{
console.error(err)
})
} | function auth(){
return getNewSessionToken(baseURL).then((sessionID)=>{
authenticateAnonymous(baseURL,sessionID)
return sessionID
}).catch((err)=>{
console.error(err)
})
} |
JavaScript | function Yamaha(ip, responseDelay, requestTimeout)
{
if (typeof responseDelay == 'string' || responseDelay instanceof String) responseDelay = parseInt(responseDelay);
if (!responseDelay) responseDelay = 1;
if (typeof requestTimeout == 'string' || requestTimeout instanceof String) requestTimeout = parseInt(requestTimeout); /*add by TS */
if (!requestTimeout) requestTimeout = 5000; /*add by TS */
this.minDB = -800; /*add by TS */
this.maxDB = 0; /*add by TS */
this.ip = ip;
this.responseDelay = responseDelay;
this.pollingDelay = 500; // used for menu ready check, webradio e.g.
this.requestTimeout = requestTimeout;
this.catchRequestErrors = true;
this.minVol = -805;
this.maxVol = 165;
} | function Yamaha(ip, responseDelay, requestTimeout)
{
if (typeof responseDelay == 'string' || responseDelay instanceof String) responseDelay = parseInt(responseDelay);
if (!responseDelay) responseDelay = 1;
if (typeof requestTimeout == 'string' || requestTimeout instanceof String) requestTimeout = parseInt(requestTimeout); /*add by TS */
if (!requestTimeout) requestTimeout = 5000; /*add by TS */
this.minDB = -800; /*add by TS */
this.maxDB = 0; /*add by TS */
this.ip = ip;
this.responseDelay = responseDelay;
this.pollingDelay = 500; // used for menu ready check, webradio e.g.
this.requestTimeout = requestTimeout;
this.catchRequestErrors = true;
this.minVol = -805;
this.maxVol = 165;
} |
JavaScript | function reset() {
currentMonsterHealth = chosenMaxLife;
currentPlayerHealth = chosenMaxLife;
resetGame(chosenMaxLife);
} | function reset() {
currentMonsterHealth = chosenMaxLife;
currentPlayerHealth = chosenMaxLife;
resetGame(chosenMaxLife);
} |
JavaScript | function addMarker(location) {
if( marker) {
marker.setMap(null);
infowindow.setMap(null);
}
marker = new google.maps.Marker({
position: location,
map: map,
title: 'Mike Hand'
});
infowindow = new google.maps.InfoWindow({
content: marker.title
});
infowindow.open(marker.get('map'), marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
} | function addMarker(location) {
if( marker) {
marker.setMap(null);
infowindow.setMap(null);
}
marker = new google.maps.Marker({
position: location,
map: map,
title: 'Mike Hand'
});
infowindow = new google.maps.InfoWindow({
content: marker.title
});
infowindow.open(marker.get('map'), marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(marker.get('map'), marker);
});
} |
JavaScript | function Asteroid(asteroidData) {
this.neo_ref_id = asteroidData.neo_reference_id;
this.name = asteroidData.name;
this.hazardous = asteroidData.is_potentially_hazardous_asteroid;
this.miss_distance_miles = asteroidData.close_approach_data[0].miss_distance.miles;
this.diameter_feet_min = asteroidData.estimated_diameter.feet.estimated_diameter_min;
this.diameter_feet_max = asteroidData.estimated_diameter.feet.estimated_diameter_max;
this.velocity_mph = asteroidData.close_approach_data[0].relative_velocity.miles_per_hour;
this.sentry_object = asteroidData.is_sentry_object;
this.closest_date = asteroidData.close_approach_data[0].close_approach_date;
} | function Asteroid(asteroidData) {
this.neo_ref_id = asteroidData.neo_reference_id;
this.name = asteroidData.name;
this.hazardous = asteroidData.is_potentially_hazardous_asteroid;
this.miss_distance_miles = asteroidData.close_approach_data[0].miss_distance.miles;
this.diameter_feet_min = asteroidData.estimated_diameter.feet.estimated_diameter_min;
this.diameter_feet_max = asteroidData.estimated_diameter.feet.estimated_diameter_max;
this.velocity_mph = asteroidData.close_approach_data[0].relative_velocity.miles_per_hour;
this.sentry_object = asteroidData.is_sentry_object;
this.closest_date = asteroidData.close_approach_data[0].close_approach_date;
} |
JavaScript | function addAsteroidToDatabase(asteroidObj) {
const insertSQL = `INSERT INTO asteroids (neo_ref_id, name, hazardous, miss_distance_miles, diameter_feet_min, diameter_feet_max, velocity_mph, sentry_object, closest_date, img) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id;`;
const insertValues = Object.values(asteroidObj).slice(0, 10);
client
.query(insertSQL, insertValues)
.then((insertReturn) => (asteroidObj.id = insertReturn.rows[0].id))
.catch((error) => handleError(error));
} | function addAsteroidToDatabase(asteroidObj) {
const insertSQL = `INSERT INTO asteroids (neo_ref_id, name, hazardous, miss_distance_miles, diameter_feet_min, diameter_feet_max, velocity_mph, sentry_object, closest_date, img) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id;`;
const insertValues = Object.values(asteroidObj).slice(0, 10);
client
.query(insertSQL, insertValues)
.then((insertReturn) => (asteroidObj.id = insertReturn.rows[0].id))
.catch((error) => handleError(error));
} |
JavaScript | function initMap() {//eslint-disable-line
// Create the map.
let map = new google.maps.Map(document.getElementById('map'), {//eslint-disable-line
zoom: 13,
center: citymap[Object.keys(citymap)[0]].center,
mapTypeId: 'hybrid',
disableDefaultUI: true,
zoomControl: true,
});
// Construct the circle for each value in citymap.
for (let city in citymap) {
// Add the circle for this city to the map.
let minAsteroidCircle = new google.maps.Circle({//eslint-disable-line
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.15,
map: map,
center: citymap[city].center,
radius: asteroidSize['min'],//eslint-disable-line
});
let maxAsteroidCircle = new google.maps.Circle({//eslint-disable-line
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.25,
map: map,
center: citymap[city].center,
radius: asteroidSize['max'],//eslint-disable-line
});
}
} | function initMap() {//eslint-disable-line
// Create the map.
let map = new google.maps.Map(document.getElementById('map'), {//eslint-disable-line
zoom: 13,
center: citymap[Object.keys(citymap)[0]].center,
mapTypeId: 'hybrid',
disableDefaultUI: true,
zoomControl: true,
});
// Construct the circle for each value in citymap.
for (let city in citymap) {
// Add the circle for this city to the map.
let minAsteroidCircle = new google.maps.Circle({//eslint-disable-line
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.15,
map: map,
center: citymap[city].center,
radius: asteroidSize['min'],//eslint-disable-line
});
let maxAsteroidCircle = new google.maps.Circle({//eslint-disable-line
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.25,
map: map,
center: citymap[city].center,
radius: asteroidSize['max'],//eslint-disable-line
});
}
} |
JavaScript | function countValue(value, result, target, duration) {
if(duration) {
var count = 0;
var speed = parseInt(duration / value);
var interval = setInterval(function(){
if(count - 1 < value) {
target.html(count);
}
else {
target.html(result);
clearInterval(interval);
}
count++;
}, speed);
}
else {
target.html(result);
}
} | function countValue(value, result, target, duration) {
if(duration) {
var count = 0;
var speed = parseInt(duration / value);
var interval = setInterval(function(){
if(count - 1 < value) {
target.html(count);
}
else {
target.html(result);
clearInterval(interval);
}
count++;
}, speed);
}
else {
target.html(result);
}
} |
JavaScript | function init_progressBar(duration) {
$('.progress-container').each(function() {
var container = $(this).find('.progress-value');
var value = $(this).find('.progress').attr('data-level');
var result = value;
if(duration) {
$(this).find('.progress-bar').animate({width : value + '%'}, duration);
}
else {
$(this).find('.progress-bar').css({'width' : value + '%'});
}
countValue(value, result, container, duration);
});
} | function init_progressBar(duration) {
$('.progress-container').each(function() {
var container = $(this).find('.progress-value');
var value = $(this).find('.progress').attr('data-level');
var result = value;
if(duration) {
$(this).find('.progress-bar').animate({width : value + '%'}, duration);
}
else {
$(this).find('.progress-bar').css({'width' : value + '%'});
}
countValue(value, result, container, duration);
});
} |
JavaScript | function generatePetrinet(petrinet){
var data=getVisElements(petrinet);
// create a network
var container = document.getElementById('mynetwork');
var options = {
layout: {
randomSeed: undefined,
improvedLayout:true,
hierarchical: {
enabled:true,
levelSeparation: 150,
nodeSpacing: 100,
treeSpacing: 200,
blockShifting: true,
edgeMinimization: true,
parentCentralization: true,
direction: 'LR', // UD, DU, LR, RL
sortMethod: 'directed' // hubsize, directed
}
},
groups: {
places: {color:{background:'#4DB6AC',border: '#00695C'}, borderWidth:3, shape: 'circle'},
transitions: {color:{background:'#FFB74D',border: '#FB8C00',}, shape: 'square', borderWidth:3},
andJoin: {color:{background:'#DCE775',border: '#9E9D24',}, shape: 'square', borderWidth:3},
andSplit: {color:{background:'#DCE775',border: '#9E9D24',}, shape: 'square', borderWidth:3},
xorSplit: {color:{background:'#9575CD',border: '#512DA8',}, shape: 'square', borderWidth:3,image:"/img/and_split.svg"},
xorJoin: {color:{background:'#9575CD',border: '#512DA8',}, shape: 'square', borderWidth:3}
},
interaction:{
zoomView:true,
dragView:true
}
}
// initialize your network!
var network = new vis.Network(container, data, options);
} | function generatePetrinet(petrinet){
var data=getVisElements(petrinet);
// create a network
var container = document.getElementById('mynetwork');
var options = {
layout: {
randomSeed: undefined,
improvedLayout:true,
hierarchical: {
enabled:true,
levelSeparation: 150,
nodeSpacing: 100,
treeSpacing: 200,
blockShifting: true,
edgeMinimization: true,
parentCentralization: true,
direction: 'LR', // UD, DU, LR, RL
sortMethod: 'directed' // hubsize, directed
}
},
groups: {
places: {color:{background:'#4DB6AC',border: '#00695C'}, borderWidth:3, shape: 'circle'},
transitions: {color:{background:'#FFB74D',border: '#FB8C00',}, shape: 'square', borderWidth:3},
andJoin: {color:{background:'#DCE775',border: '#9E9D24',}, shape: 'square', borderWidth:3},
andSplit: {color:{background:'#DCE775',border: '#9E9D24',}, shape: 'square', borderWidth:3},
xorSplit: {color:{background:'#9575CD',border: '#512DA8',}, shape: 'square', borderWidth:3,image:"/img/and_split.svg"},
xorJoin: {color:{background:'#9575CD',border: '#512DA8',}, shape: 'square', borderWidth:3}
},
interaction:{
zoomView:true,
dragView:true
}
}
// initialize your network!
var network = new vis.Network(container, data, options);
} |
JavaScript | process(processingFn) {
if (typeof processingFn !== 'function') {
const type = typeof processingFn;
throw new TypeError(
`Expected argument of type function, but got: ${type}`);
}
this.dataSources.forEach(
source => source.data = processingFn(source.data));
return this;
} | process(processingFn) {
if (typeof processingFn !== 'function') {
const type = typeof processingFn;
throw new TypeError(
`Expected argument of type function, but got: ${type}`);
}
this.dataSources.forEach(
source => source.data = processingFn(source.data));
return this;
} |
JavaScript | static computeCumulativeFrequencies(data) {
const sortedData = data.sort((a, b) => a - b);
return sortedData.map((value, i) => {
return {
x: i,
y: value,
};
});
} | static computeCumulativeFrequencies(data) {
const sortedData = data.sort((a, b) => a - b);
return sortedData.map((value, i) => {
return {
x: i,
y: value,
};
});
} |
JavaScript | plot(plotter) {
this.labelTitle_();
this.labelAxis_();
/* Other classes should not be able to change chartDimensions
* as then it will no longer reflect the chart's
* true dimensions.
*/
const dimensionsCopy = Object.assign({}, this.chartDimensions);
plotter.plot(this.graph_, this.chart_, this.legend_, dimensionsCopy);
} | plot(plotter) {
this.labelTitle_();
this.labelAxis_();
/* Other classes should not be able to change chartDimensions
* as then it will no longer reflect the chart's
* true dimensions.
*/
const dimensionsCopy = Object.assign({}, this.chartDimensions);
plotter.plot(this.graph_, this.chart_, this.legend_, dimensionsCopy);
} |
JavaScript | initChart_(graph, chart, chartDimensions) {
this.scaleForXAxis_ = this.createXAxisScale_(graph, chartDimensions);
this.scaleForYAxis_ = this.createYAxisScale_(graph, chartDimensions);
this.xAxisGenerator_ = d3.axisBottom(this.scaleForXAxis_);
this.yAxisGenerator_ = d3.axisLeft(this.scaleForYAxis_);
// Draw the x-axis.
chart.append('g')
.call(this.xAxisGenerator_)
.attr('transform', `translate(0, ${chartDimensions.height})`);
this.yAxisDrawing_ = chart.append('g')
.call(this.yAxisGenerator_);
} | initChart_(graph, chart, chartDimensions) {
this.scaleForXAxis_ = this.createXAxisScale_(graph, chartDimensions);
this.scaleForYAxis_ = this.createYAxisScale_(graph, chartDimensions);
this.xAxisGenerator_ = d3.axisBottom(this.scaleForXAxis_);
this.yAxisGenerator_ = d3.axisLeft(this.scaleForYAxis_);
// Draw the x-axis.
chart.append('g')
.call(this.xAxisGenerator_)
.attr('transform', `translate(0, ${chartDimensions.height})`);
this.yAxisDrawing_ = chart.append('g')
.call(this.yAxisGenerator_);
} |
JavaScript | plot(graph, chart, legend, chartDimensions) {
this.initChart_(graph, chart, chartDimensions);
const pathGenerator = d3.line()
.x(datum => this.scaleForXAxis_(datum.x))
.y(datum => this.scaleForYAxis_(datum.y))
.curve(d3.curveMonotoneX);
graph.dataSources.forEach(({ data, color, key }, index) => {
chart.selectAll('.dot')
.data(data)
.enter()
.append('circle')
.attr('cx', datum => this.scaleForXAxis_(datum.x))
.attr('cy', datum => this.scaleForYAxis_(datum.y))
.attr('r', 3)
.attr('fill', color)
.attr('class', 'line-dot')
.attr('clip-path', 'url(#plot-clip)');
chart.append('path')
.datum(data)
.attr('d', pathGenerator)
.attr('stroke', color)
.attr('fill', 'none')
.attr('stroke-width', 2)
.attr('data-legend', key)
.attr('class', 'line-plot')
.attr('clip-path', 'url(#plot-clip)');
legend.append('text')
.text(key)
.attr('y', index + 'em')
.attr('fill', color);
});
const zoom = d3.zoom();
this.setUpZoom_(zoom, chart, chartDimensions);
this.setUpZoomReset_(zoom, chart, chartDimensions);
} | plot(graph, chart, legend, chartDimensions) {
this.initChart_(graph, chart, chartDimensions);
const pathGenerator = d3.line()
.x(datum => this.scaleForXAxis_(datum.x))
.y(datum => this.scaleForYAxis_(datum.y))
.curve(d3.curveMonotoneX);
graph.dataSources.forEach(({ data, color, key }, index) => {
chart.selectAll('.dot')
.data(data)
.enter()
.append('circle')
.attr('cx', datum => this.scaleForXAxis_(datum.x))
.attr('cy', datum => this.scaleForYAxis_(datum.y))
.attr('r', 3)
.attr('fill', color)
.attr('class', 'line-dot')
.attr('clip-path', 'url(#plot-clip)');
chart.append('path')
.datum(data)
.attr('d', pathGenerator)
.attr('stroke', color)
.attr('fill', 'none')
.attr('stroke-width', 2)
.attr('data-legend', key)
.attr('class', 'line-plot')
.attr('clip-path', 'url(#plot-clip)');
legend.append('text')
.text(key)
.attr('y', index + 'em')
.attr('fill', color);
});
const zoom = d3.zoom();
this.setUpZoom_(zoom, chart, chartDimensions);
this.setUpZoomReset_(zoom, chart, chartDimensions);
} |
JavaScript | metrics() {
const metricsNames = [];
this.sampleArr.forEach(el => metricsNames.push(el.name));
return _.uniq(metricsNames);
} | metrics() {
const metricsNames = [];
this.sampleArr.forEach(el => metricsNames.push(el.name));
return _.uniq(metricsNames);
} |
JavaScript | stories() {
const reqMetrics = this.sampleArr
.filter(elem => elem.name === this.selected_metric);
const storiesByGuid = [];
reqMetrics.map(elem => storiesByGuid
.push(this.guidValue.get(elem.diagnostics.stories)[0]));
return Array.from(new Set(storiesByGuid));
} | stories() {
const reqMetrics = this.sampleArr
.filter(elem => elem.name === this.selected_metric);
const storiesByGuid = [];
reqMetrics.map(elem => storiesByGuid
.push(this.guidValue.get(elem.diagnostics.stories)[0]));
return Array.from(new Set(storiesByGuid));
} |
JavaScript | diagnostics() {
if (this.selected_story !== null && this.selected_metric !== null) {
const result = this.sampleArr
.filter(value => value.name === this.selected_metric &&
this.guidValue
.get(value.diagnostics.stories)[0] ===
this.selected_story);
const allDiagnostic = [];
result.map(val => allDiagnostic.push(Object.keys(val.diagnostics)));
return _.union.apply(this, allDiagnostic);
}
} | diagnostics() {
if (this.selected_story !== null && this.selected_metric !== null) {
const result = this.sampleArr
.filter(value => value.name === this.selected_metric &&
this.guidValue
.get(value.diagnostics.stories)[0] ===
this.selected_story);
const allDiagnostic = [];
result.map(val => allDiagnostic.push(Object.keys(val.diagnostics)));
return _.union.apply(this, allDiagnostic);
}
} |
JavaScript | target() {
if (this.selected_story !== null &&
this.selected_metric !== null &&
this.selected_diagnostic !== null) {
const result = this.sampleArr
.filter(value => value.name === this.selected_metric &&
this.guidValue
.get(value.diagnostics.stories)[0] ===
this.selected_story);
const content = new Map();
for (const val of result) {
const storyEl = this.guidValue.get(
val.diagnostics[this.selected_diagnostic]);
if (storyEl === undefined) {
continue;
}
const storyItem = storyEl[0];
if (content.has(storyItem)) {
const aux = content.get(storyItem);
content.set(storyItem, aux.concat(val.sampleValues));
} else {
content.set(storyItem, val.sampleValues);
}
}
/*
* Just for displaying data; will be removed.
* It's not possible to manipulate a map in origin format.
*/
const contentDisplay = [];
for (const [key, value] of content.entries()) {
const elem = { keyItem: key, valueItem: value };
contentDisplay.push(elem);
}
return contentDisplay;
}
return undefined;
} | target() {
if (this.selected_story !== null &&
this.selected_metric !== null &&
this.selected_diagnostic !== null) {
const result = this.sampleArr
.filter(value => value.name === this.selected_metric &&
this.guidValue
.get(value.diagnostics.stories)[0] ===
this.selected_story);
const content = new Map();
for (const val of result) {
const storyEl = this.guidValue.get(
val.diagnostics[this.selected_diagnostic]);
if (storyEl === undefined) {
continue;
}
const storyItem = storyEl[0];
if (content.has(storyItem)) {
const aux = content.get(storyItem);
content.set(storyItem, aux.concat(val.sampleValues));
} else {
content.set(storyItem, val.sampleValues);
}
}
/*
* Just for displaying data; will be removed.
* It's not possible to manipulate a map in origin format.
*/
const contentDisplay = [];
for (const [key, value] of content.entries()) {
const elem = { keyItem: key, valueItem: value };
contentDisplay.push(elem);
}
return contentDisplay;
}
return undefined;
} |
JavaScript | function visibleAll() {
document.getElementById('storyBtn').style.visibility = 'visible';
document.getElementById('storyTagsBtn').style.visibility = 'visible';
document.getElementById('storysetRepeatsBtn').style.visibility = 'visible';
document.getElementById('traceStartBtn').style.visibility = 'visible';
document.getElementById('traceUrlsBtn').style.visibility = 'visible';
document.getElementById('metricname').style.visibility = 'visible';
document.getElementById('storyname').style.visibility = 'visible';
document.getElementById('submit').style.visibility = 'visible';
} | function visibleAll() {
document.getElementById('storyBtn').style.visibility = 'visible';
document.getElementById('storyTagsBtn').style.visibility = 'visible';
document.getElementById('storysetRepeatsBtn').style.visibility = 'visible';
document.getElementById('traceStartBtn').style.visibility = 'visible';
document.getElementById('traceUrlsBtn').style.visibility = 'visible';
document.getElementById('metricname').style.visibility = 'visible';
document.getElementById('storyname').style.visibility = 'visible';
document.getElementById('submit').style.visibility = 'visible';
} |
JavaScript | function readSingleFile(e) {
const file = e.target.files[0];
if (!file) {
return;
}
/*
* Extract data from file and distribute it in some relevant structures:
* results for all guid-related( for now they are not
* divided in 3 parts depending on the type ) and
* all results with sample-value-related and
* map guid to value within the same structure
*/
const reader = new FileReader();
reader.onload = function(e) {
const contents = extractData(e.target.result);
const sampleArr = contents.sampleValueArray;
const guidValueInfo = contents.guidValueInfo;
app.sampleArr = sampleArr;
app.guidValue = guidValueInfo;
/*
* Data is displayed in a default format.
*/
// displayContents(sampleArr, guidValueInfo);
visibleAll();
/*
* Every button should be able to filter the information regarding
* one of the possibilities of choosing.
*/
document.getElementById('storyBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'stories');
}, false);
document.getElementById('storyTagsBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'storyTags');
}, false);
document.getElementById('storysetRepeatsBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'storysetRepeats');
}, false);
document.getElementById('traceStartBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'traceStart');
}, false);
document.getElementById('traceUrlsBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'traceUrls');
}, false);
};
reader.readAsText(file);
} | function readSingleFile(e) {
const file = e.target.files[0];
if (!file) {
return;
}
/*
* Extract data from file and distribute it in some relevant structures:
* results for all guid-related( for now they are not
* divided in 3 parts depending on the type ) and
* all results with sample-value-related and
* map guid to value within the same structure
*/
const reader = new FileReader();
reader.onload = function(e) {
const contents = extractData(e.target.result);
const sampleArr = contents.sampleValueArray;
const guidValueInfo = contents.guidValueInfo;
app.sampleArr = sampleArr;
app.guidValue = guidValueInfo;
/*
* Data is displayed in a default format.
*/
// displayContents(sampleArr, guidValueInfo);
visibleAll();
/*
* Every button should be able to filter the information regarding
* one of the possibilities of choosing.
*/
document.getElementById('storyBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'stories');
}, false);
document.getElementById('storyTagsBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'storyTags');
}, false);
document.getElementById('storysetRepeatsBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'storysetRepeats');
}, false);
document.getElementById('traceStartBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'traceStart');
}, false);
document.getElementById('traceUrlsBtn')
.addEventListener('click', function() {
displayContents(sampleArr, guidValueInfo, 'traceUrls');
}, false);
};
reader.readAsText(file);
} |
JavaScript | function forceUpdateAll() {
isRequestPending = false;
var rootInstances = getRootInstances(),
rootInstance;
for (var key in rootInstances) {
if (rootInstances.hasOwnProperty(key)) {
deepForceUpdate(rootInstances[key]);
}
}
} | function forceUpdateAll() {
isRequestPending = false;
var rootInstances = getRootInstances(),
rootInstance;
for (var key in rootInstances) {
if (rootInstances.hasOwnProperty(key)) {
deepForceUpdate(rootInstances[key]);
}
}
} |
JavaScript | function displayText(barHeight, text) {
if(barHeight < 20) {
return "";
} else {
return formatCount(text);
}
} | function displayText(barHeight, text) {
if(barHeight < 20) {
return "";
} else {
return formatCount(text);
}
} |
JavaScript | function astGoToNode(ast, branches) {
var node = ast;
if (branches == null) {
return node;
}
for (let branch of branches) {
node = node.children[branch];
}
return node;
} | function astGoToNode(ast, branches) {
var node = ast;
if (branches == null) {
return node;
}
for (let branch of branches) {
node = node.children[branch];
}
return node;
} |
JavaScript | function astMakeTrick(astTopSection, trickIndex) {
const headline2Index = trickIndex[0];
const headline3Index = trickIndex[1];
return {
headline_1 : astGoToNode(astTopSection, [0,0]).value,
headline_2 : astGoToNode(astTopSection, [headline2Index,0,0]).value,
headline_3 : astGoToNode(astTopSection, [headline2Index,
headline3Index,0,0]).value,
list : astMakeListItemBlock(
astGoToNode(astTopSection,[headline2Index,headline3Index]).children)
};
} | function astMakeTrick(astTopSection, trickIndex) {
const headline2Index = trickIndex[0];
const headline3Index = trickIndex[1];
return {
headline_1 : astGoToNode(astTopSection, [0,0]).value,
headline_2 : astGoToNode(astTopSection, [headline2Index,0,0]).value,
headline_3 : astGoToNode(astTopSection, [headline2Index,
headline3Index,0,0]).value,
list : astMakeListItemBlock(
astGoToNode(astTopSection,[headline2Index,headline3Index]).children)
};
} |
JavaScript | function astMakeTricks(ast) {
let tricks = [];
ast.children.forEach((astTopSection) => {
astTopSection.children.slice(1).forEach((headline2,headline2Index) => {
headline2.children.slice(1).forEach((headline3,headline3Index) => {
let trickIndex = [headline2Index + 1, headline3Index + 1];
tricks.push(astMakeTrick(astTopSection, trickIndex));
})
})
})
return tricks
} | function astMakeTricks(ast) {
let tricks = [];
ast.children.forEach((astTopSection) => {
astTopSection.children.slice(1).forEach((headline2,headline2Index) => {
headline2.children.slice(1).forEach((headline3,headline3Index) => {
let trickIndex = [headline2Index + 1, headline3Index + 1];
tricks.push(astMakeTrick(astTopSection, trickIndex));
})
})
})
return tricks
} |
JavaScript | function MarkupOrLink(props) {
const astNode = props.node;
let element;
switch (astNode.type) {
case 'text':
element = astNode.value;
break;
case 'link':
element = <a href={astNode.uri.raw}>{astNode.desc}</a>
break;
case 'strikeThrough':
element = <del>{astNode.children[0].value}</del>;
break;
case 'underline':
element = <span style={{textDecoration: 'underline'}}>
{astNode.children[0].value}
</span>;
break;
case 'bold':
element = <b>{astNode.children[0].value}</b>;
break;
case 'italic':
element = <i>{astNode.children[0].value}</i>;
break;
case 'code':
element = <code>{astNode.children[0].value}</code>;
break;
case 'verbatim':
element = <code>{astNode.children[0].value}</code>;
break;
default:
}
return element;
} | function MarkupOrLink(props) {
const astNode = props.node;
let element;
switch (astNode.type) {
case 'text':
element = astNode.value;
break;
case 'link':
element = <a href={astNode.uri.raw}>{astNode.desc}</a>
break;
case 'strikeThrough':
element = <del>{astNode.children[0].value}</del>;
break;
case 'underline':
element = <span style={{textDecoration: 'underline'}}>
{astNode.children[0].value}
</span>;
break;
case 'bold':
element = <b>{astNode.children[0].value}</b>;
break;
case 'italic':
element = <i>{astNode.children[0].value}</i>;
break;
case 'code':
element = <code>{astNode.children[0].value}</code>;
break;
case 'verbatim':
element = <code>{astNode.children[0].value}</code>;
break;
default:
}
return element;
} |
JavaScript | function inferPoints (node) {
const subtasks = node.children
.filter(n => n.type === 'project' || n.type === 'task')
if (subtasks.length === 0) return 1
return subtasks
.map(n => n.points)
.reduce((total, i) => total + i, 0)
} | function inferPoints (node) {
const subtasks = node.children
.filter(n => n.type === 'project' || n.type === 'task')
if (subtasks.length === 0) return 1
return subtasks
.map(n => n.points)
.reduce((total, i) => total + i, 0)
} |
JavaScript | function inferProgress (node) {
const subtasks = node.children
.filter(n => n.type === 'project' || n.type === 'task')
if (subtasks.length === 0) return 0
const total = inferPoints(node)
const points = subtasks
.map(n => n.progress * n.points)
.reduce((total, i) => total + i, 0)
return points / total
} | function inferProgress (node) {
const subtasks = node.children
.filter(n => n.type === 'project' || n.type === 'task')
if (subtasks.length === 0) return 0
const total = inferPoints(node)
const points = subtasks
.map(n => n.progress * n.points)
.reduce((total, i) => total + i, 0)
return points / total
} |
JavaScript | function encodeTiddlyLinkList(list)
{
if(list) {
var t,results = [];
for(t=0; t<list.length; t++)
results.push(encodeTiddlyLink(list[t]));
return results.join(" ");
} else {
return "";
}
} | function encodeTiddlyLinkList(list)
{
if(list) {
var t,results = [];
for(t=0; t<list.length; t++)
results.push(encodeTiddlyLink(list[t]));
return results.join(" ");
} else {
return "";
}
} |
JavaScript | async function checkOldLocks(bucket, locks = []) {
const fiveMinutesAgo = Date.now() - (5 * 60 * 1000);
const expiredLocks = locks.filter((lock) => lock.LastModified < fiveMinutesAgo);
await Promise.all(expiredLocks.map((lock) => deleteS3Object(bucket, lock.Key)));
return locks.length - expiredLocks.length;
} | async function checkOldLocks(bucket, locks = []) {
const fiveMinutesAgo = Date.now() - (5 * 60 * 1000);
const expiredLocks = locks.filter((lock) => lock.LastModified < fiveMinutesAgo);
await Promise.all(expiredLocks.map((lock) => deleteS3Object(bucket, lock.Key)));
return locks.length - expiredLocks.length;
} |
JavaScript | async function countLock(bucket, providerName) {
const s3Objects = await listS3ObjectsV2({
Bucket: bucket,
Prefix: `${lockPrefix}/${providerName}`
});
return checkOldLocks(bucket, s3Objects);
} | async function countLock(bucket, providerName) {
const s3Objects = await listS3ObjectsV2({
Bucket: bucket,
Prefix: `${lockPrefix}/${providerName}`
});
return checkOldLocks(bucket, s3Objects);
} |
JavaScript | async function handler(event) {
const { bucketList, s3Bucket, s3Key } = event;
if (!bucketList || !s3Bucket || !s3Key) {
throw new Error('A bucketlist and s3 bucket/key must be provided in the event');
}
const s3 = new AWS.S3();
const bucketMapPromises = event.bucketList.map(async (bucket) => ({
[bucket]: await getTeaBucketPath(bucket, process.env.TEA_API)
}));
const bucketMapObjects = await Promise.all(bucketMapPromises);
const bucketMap = bucketMapObjects.reduce(
(map, obj) => Object.assign(map, obj), {}
);
await s3.putObject({
Bucket: s3Bucket,
Key: s3Key,
Body: JSON.stringify(bucketMap)
}).promise();
console.log(`Wrote bucketmap ${JSON.stringify(bucketMap)} to ${s3Bucket}/${s3Key}`);
return bucketMap;
} | async function handler(event) {
const { bucketList, s3Bucket, s3Key } = event;
if (!bucketList || !s3Bucket || !s3Key) {
throw new Error('A bucketlist and s3 bucket/key must be provided in the event');
}
const s3 = new AWS.S3();
const bucketMapPromises = event.bucketList.map(async (bucket) => ({
[bucket]: await getTeaBucketPath(bucket, process.env.TEA_API)
}));
const bucketMapObjects = await Promise.all(bucketMapPromises);
const bucketMap = bucketMapObjects.reduce(
(map, obj) => Object.assign(map, obj), {}
);
await s3.putObject({
Bucket: s3Bucket,
Key: s3Key,
Body: JSON.stringify(bucketMap)
}).promise();
console.log(`Wrote bucketmap ${JSON.stringify(bucketMap)} to ${s3Bucket}/${s3Key}`);
return bucketMap;
} |
JavaScript | async aggregateActiveGranuleCollections() {
if (!this.client) {
this.client = await this.constructor.es();
}
// granules
const searchParams = this._buildSearch();
searchParams.size = 0;
delete searchParams.from;
searchParams.type = 'granule';
searchParams.body.aggs = {
collections: {
terms: {
field: 'collectionId'
}
}
};
const searchResults = await this.client.search(searchParams)
.then((response) => response.body);
return searchResults.aggregations.collections.buckets.map((b) => b.key);
} | async aggregateActiveGranuleCollections() {
if (!this.client) {
this.client = await this.constructor.es();
}
// granules
const searchParams = this._buildSearch();
searchParams.size = 0;
delete searchParams.from;
searchParams.type = 'granule';
searchParams.body.aggs = {
collections: {
terms: {
field: 'collectionId'
}
}
};
const searchResults = await this.client.search(searchParams)
.then((response) => response.body);
return searchResults.aggregations.collections.buckets.map((b) => b.key);
} |
JavaScript | async queryCollectionsWithActiveGranules() {
const collectionIds = await this.aggregateActiveGranuleCollections();
const searchParams = this._buildSearch();
searchParams.body.query = {
constant_score: {
filter: {
terms: {
_id: collectionIds
}
}
}
};
const res = await this.query(searchParams);
return res;
} | async queryCollectionsWithActiveGranules() {
const collectionIds = await this.aggregateActiveGranuleCollections();
const searchParams = this._buildSearch();
searchParams.body.query = {
constant_score: {
filter: {
terms: {
_id: collectionIds
}
}
}
};
const res = await this.query(searchParams);
return res;
} |
JavaScript | async function rerunRule({
prefix, ruleName, updateParams = {}, callback = invokeApi
}) {
return updateRule({
prefix,
ruleName,
updateParams: {
...updateParams,
action: 'rerun'
},
callback
});
} | async function rerunRule({
prefix, ruleName, updateParams = {}, callback = invokeApi
}) {
return updateRule({
prefix,
ruleName,
updateParams: {
...updateParams,
action: 'rerun'
},
callback
});
} |
JavaScript | async fetchItems() {
const results = await this.CMR.searchConcept(
this.type,
this.params,
this.format,
false
);
this.items = results;
this.params.page_num = (this.params.page_num) ? this.params.page_num + 1 : 1;
if (results.length === 0) this.items.push(null);
} | async fetchItems() {
const results = await this.CMR.searchConcept(
this.type,
this.params,
this.format,
false
);
this.items = results;
this.params.page_num = (this.params.page_num) ? this.params.page_num + 1 : 1;
if (results.length === 0) this.items.push(null);
} |
JavaScript | function storeFilesToS3(files) {
const putObjectParams = files.map((file) => ({
Bucket: file.bucket,
Key: file.key,
Body: randomString()
}));
return pMap(
putObjectParams,
(params) => awsServices.s3().putObject(params).promise(),
{ concurrency: 10 }
);
} | function storeFilesToS3(files) {
const putObjectParams = files.map((file) => ({
Bucket: file.bucket,
Key: file.key,
Body: randomString()
}));
return pMap(
putObjectParams,
(params) => awsServices.s3().putObject(params).promise(),
{ concurrency: 10 }
);
} |
JavaScript | function storeToDynamoDb(tableName, putRequests) {
// Break the requests into groups of 25
const putRequestsChunks = chunk(putRequests, 25);
const putRequestParams = putRequestsChunks.map((requests) => ({
RequestItems: {
[tableName]: requests
}
}));
return pMap(
putRequestParams,
(params) => awsServices.dynamodb().batchWriteItem(params).promise(),
{ concurrency: 1 }
);
} | function storeToDynamoDb(tableName, putRequests) {
// Break the requests into groups of 25
const putRequestsChunks = chunk(putRequests, 25);
const putRequestParams = putRequestsChunks.map((requests) => ({
RequestItems: {
[tableName]: requests
}
}));
return pMap(
putRequestParams,
(params) => awsServices.dynamodb().batchWriteItem(params).promise(),
{ concurrency: 1 }
);
} |
JavaScript | function navClasses() {
return (tree) => {
visit(tree, { type: 'element', tagName: 'a' }, (node) => {
node.properties.class = 'nav-' +
node.properties.href.replace('.html', '').replace(/\W+/g, '-');
});
};
} | function navClasses() {
return (tree) => {
visit(tree, { type: 'element', tagName: 'a' }, (node) => {
node.properties.class = 'nav-' +
node.properties.href.replace('.html', '').replace(/\W+/g, '-');
});
};
} |
JavaScript | function firstHeader() {
return (tree, file) => {
file.section = 'Index';
const heading = find(tree, { type: 'heading' });
if (heading) {
const text = find(heading, { type: 'text' });
if (text) file.section = text.value;
}
};
} | function firstHeader() {
return (tree, file) => {
file.section = 'Index';
const heading = find(tree, { type: 'heading' });
if (heading) {
const text = find(heading, { type: 'text' });
if (text) file.section = text.value;
}
};
} |
JavaScript | function preprocessText() {
return (tree) => {
visit(tree, null, (node) => {
if (node.type === 'text' && node.value) {
const value = linkJsTypeDocs(linkManPages(node.value));
if (value !== node.value) {
node.type = 'html';
node.value = value;
}
}
});
};
} | function preprocessText() {
return (tree) => {
visit(tree, null, (node) => {
if (node.type === 'text' && node.value) {
const value = linkJsTypeDocs(linkManPages(node.value));
if (value !== node.value) {
node.type = 'html';
node.value = value;
}
}
});
};
} |
JavaScript | function preprocessElements({ filename }) {
return (tree) => {
const STABILITY_RE = /(.*:)\s*(\d)([\s\S]*)/;
let headingIndex = -1;
let heading = null;
visit(tree, null, (node, index) => {
if (node.type === 'heading') {
headingIndex = index;
heading = node;
} else if (node.type === 'html' && common.isYAMLBlock(node.value)) {
node.value = parseYAML(node.value);
} else if (node.type === 'blockquote') {
const paragraph = node.children[0].type === 'paragraph' &&
node.children[0];
const text = paragraph && paragraph.children[0].type === 'text' &&
paragraph.children[0];
if (text && text.value.includes('Stability:')) {
const [, prefix, number, explication] =
text.value.match(STABILITY_RE);
const isStabilityIndex =
index - 2 === headingIndex || // General.
index - 3 === headingIndex; // With api_metadata block.
if (heading && isStabilityIndex) {
heading.stability = number;
headingIndex = -1;
heading = null;
}
// Do not link to the section we are already in.
const noLinking = filename.includes('documentation') &&
heading !== null && heading.children[0].value === 'Stability Index';
// Collapse blockquote and paragraph into a single node
node.type = 'paragraph';
node.children.shift();
node.children.unshift(...paragraph.children);
// Insert div with prefix and number
node.children.unshift({
type: 'html',
value: `<div class="api_stability api_stability_${number}">` +
(noLinking ? '' :
'<a href="documentation.html#documentation_stability_index">') +
`${prefix} ${number}${noLinking ? '' : '</a>'}`
.replace(/\n/g, ' ')
});
// Remove prefix and number from text
text.value = explication;
// close div
node.children.push({ type: 'html', value: '</div>' });
}
}
});
};
} | function preprocessElements({ filename }) {
return (tree) => {
const STABILITY_RE = /(.*:)\s*(\d)([\s\S]*)/;
let headingIndex = -1;
let heading = null;
visit(tree, null, (node, index) => {
if (node.type === 'heading') {
headingIndex = index;
heading = node;
} else if (node.type === 'html' && common.isYAMLBlock(node.value)) {
node.value = parseYAML(node.value);
} else if (node.type === 'blockquote') {
const paragraph = node.children[0].type === 'paragraph' &&
node.children[0];
const text = paragraph && paragraph.children[0].type === 'text' &&
paragraph.children[0];
if (text && text.value.includes('Stability:')) {
const [, prefix, number, explication] =
text.value.match(STABILITY_RE);
const isStabilityIndex =
index - 2 === headingIndex || // General.
index - 3 === headingIndex; // With api_metadata block.
if (heading && isStabilityIndex) {
heading.stability = number;
headingIndex = -1;
heading = null;
}
// Do not link to the section we are already in.
const noLinking = filename.includes('documentation') &&
heading !== null && heading.children[0].value === 'Stability Index';
// Collapse blockquote and paragraph into a single node
node.type = 'paragraph';
node.children.shift();
node.children.unshift(...paragraph.children);
// Insert div with prefix and number
node.children.unshift({
type: 'html',
value: `<div class="api_stability api_stability_${number}">` +
(noLinking ? '' :
'<a href="documentation.html#documentation_stability_index">') +
`${prefix} ${number}${noLinking ? '' : '</a>'}`
.replace(/\n/g, ' ')
});
// Remove prefix and number from text
text.value = explication;
// close div
node.children.push({ type: 'html', value: '</div>' });
}
}
});
};
} |
JavaScript | function componentMount() {
var _this2 = this;
_get(SParticleComponent.prototype.__proto__ || Object.getPrototypeOf(SParticleComponent.prototype), 'componentMount', this).call(this);
var lifetime = this.props.lifetime;
if (!lifetime) {
// get the animation properties
var animation = (0, _getAnimationProperties2.default)(this);
lifetime = animation.totalDuration;
}
// wait till the animation is finished to remove the particle from DOM
setTimeout(function () {
if (_this2.parentNode) {
_this2.parentNode.removeChild(_this2);
}
}, lifetime);
} | function componentMount() {
var _this2 = this;
_get(SParticleComponent.prototype.__proto__ || Object.getPrototypeOf(SParticleComponent.prototype), 'componentMount', this).call(this);
var lifetime = this.props.lifetime;
if (!lifetime) {
// get the animation properties
var animation = (0, _getAnimationProperties2.default)(this);
lifetime = animation.totalDuration;
}
// wait till the animation is finished to remove the particle from DOM
setTimeout(function () {
if (_this2.parentNode) {
_this2.parentNode.removeChild(_this2);
}
}, lifetime);
} |
JavaScript | static get defaultProps() {
return {
/**
* Specify the particle lifetime in ms. If not specified, will be auto-detected from his animation.
* @prop
* @type {Number}
*/
lifetime : null
};
} | static get defaultProps() {
return {
/**
* Specify the particle lifetime in ms. If not specified, will be auto-detected from his animation.
* @prop
* @type {Number}
*/
lifetime : null
};
} |
JavaScript | componentMount() {
super.componentMount();
let lifetime = this.props.lifetime;
if ( ! lifetime) {
// get the animation properties
const animation = __getAnimationProperties(this);
lifetime = animation.totalDuration;
}
// wait till the animation is finished to remove the particle from DOM
setTimeout(() => {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
}, lifetime);
} | componentMount() {
super.componentMount();
let lifetime = this.props.lifetime;
if ( ! lifetime) {
// get the animation properties
const animation = __getAnimationProperties(this);
lifetime = animation.totalDuration;
}
// wait till the animation is finished to remove the particle from DOM
setTimeout(() => {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
}, lifetime);
} |
JavaScript | function programRenameAjax(program_id, program_name_elem, original_program_name_elem, rename_button_elem) {
var program_name = program_name_elem[0].value;
var original_program_name = original_program_name_elem[0].value;
console.log("Renaming program ",program_id," to '",program_name,"', (Was '",original_program_name,"')")
$.ajax({
type: "POST",
url: "/pyxiebob/rename_program/",
data: JSON.stringify({
"program_id": program_id,
"program_name": program_name,
"original_program_name": original_program_name
}),
success: function (data) {
console.log("Rename successful.")
// We've successfully renamed the object, but need to recheck equality to make sure
// it's not changed since the submission.
original_program_name_elem[0].value = program_name;
if (program_name == program_name_elem[0].value) {
program_name_elem.removeClass('changed_name');
rename_button_elem.removeClass('changed_button');
} else {
console.log("Name changed since request, ",program_name," vs. ",program_name_elem[0].value);
program_name_elem.addClass('changed_name');
rename_button_elem.addClass('changed_button');
}
},
error: function(data) {
bootbox.alert("Something went wrong, could not rename the program");
}
});
} | function programRenameAjax(program_id, program_name_elem, original_program_name_elem, rename_button_elem) {
var program_name = program_name_elem[0].value;
var original_program_name = original_program_name_elem[0].value;
console.log("Renaming program ",program_id," to '",program_name,"', (Was '",original_program_name,"')")
$.ajax({
type: "POST",
url: "/pyxiebob/rename_program/",
data: JSON.stringify({
"program_id": program_id,
"program_name": program_name,
"original_program_name": original_program_name
}),
success: function (data) {
console.log("Rename successful.")
// We've successfully renamed the object, but need to recheck equality to make sure
// it's not changed since the submission.
original_program_name_elem[0].value = program_name;
if (program_name == program_name_elem[0].value) {
program_name_elem.removeClass('changed_name');
rename_button_elem.removeClass('changed_button');
} else {
console.log("Name changed since request, ",program_name," vs. ",program_name_elem[0].value);
program_name_elem.addClass('changed_name');
rename_button_elem.addClass('changed_button');
}
},
error: function(data) {
bootbox.alert("Something went wrong, could not rename the program");
}
});
} |
JavaScript | function checkIfAuthorizedChat(chatId) {
let authorizedChats = scriptProperties.getProperty('GruposAutorizados');
let authorizedChatsArray = JSON.parse(authorizedChats);
return authorizedChatsArray.indexOf(chatId) > -1;
} | function checkIfAuthorizedChat(chatId) {
let authorizedChats = scriptProperties.getProperty('GruposAutorizados');
let authorizedChatsArray = JSON.parse(authorizedChats);
return authorizedChatsArray.indexOf(chatId) > -1;
} |
JavaScript | function checkTelegramAuth(request) {
if(request['parameter'] && request['parameter']['token']) {
return request['parameter']['token'] === scriptProperties.getProperty('TelegramAPIAuthToken')
}
return false;
} | function checkTelegramAuth(request) {
if(request['parameter'] && request['parameter']['token']) {
return request['parameter']['token'] === scriptProperties.getProperty('TelegramAPIAuthToken')
}
return false;
} |
JavaScript | function handleSearchVideo(inlineQuery={"id":"5885869785744789","from":{"id":1370410,"is_bot":false,"first_name":"Manglaneso","username":"loMasBonitoDelMundo","language_code":"en"},"query":"searchVideo her","offset":""}) {
let searchQuery = replaceString('searchVideo ', '', inlineQuery['query']);
let answers = [];
let response = searchMulti(searchQuery=searchQuery)
for(let i in response['results']) {
let answer = {};
answer['type'] = 'photo';
answer['id'] = String(i);
answer['title'] = response['results'][i]['title'];
answer['thumb_url'] = imageBaseUrl + response['results'][i]['poster_path'];
answer['photo_url'] = imageBaseUrl + response['results'][i]['poster_path'];
answer['description'] = response['results'][i]['media_type'];
answer['parse_mode'] = 'HTML';
let template = HtmlService.createTemplateFromFile('TMDB/views/inlineQuerySearchResult');
let toTemplate = {
'title': response['results'][i]['title'],
'mediaType': response['results'][i]['media_type'],
'releaseDate': response['results'][i]['release_date'],
'voteAverage': response['results'][i]['vote_average'],
'originalLanguage': response['results'][i]['original_language'],
}
if(response['results'][i]['media_type'] === 'tv') {
toTemplate['tmdbUrl'] = tmdbBaseTvUrl + response['results'][i]['id'];
} else {
toTemplate['tmdbUrl'] = tmdbBaseUrl + response['results'][i]['id'];
}
template['data'] = toTemplate;
answer['caption'] = template.evaluate().getContent();
answers.push(answer);
}
telegramApi.answerInlineQuery(inlineQuery, answers, cacheTime=300);
} | function handleSearchVideo(inlineQuery={"id":"5885869785744789","from":{"id":1370410,"is_bot":false,"first_name":"Manglaneso","username":"loMasBonitoDelMundo","language_code":"en"},"query":"searchVideo her","offset":""}) {
let searchQuery = replaceString('searchVideo ', '', inlineQuery['query']);
let answers = [];
let response = searchMulti(searchQuery=searchQuery)
for(let i in response['results']) {
let answer = {};
answer['type'] = 'photo';
answer['id'] = String(i);
answer['title'] = response['results'][i]['title'];
answer['thumb_url'] = imageBaseUrl + response['results'][i]['poster_path'];
answer['photo_url'] = imageBaseUrl + response['results'][i]['poster_path'];
answer['description'] = response['results'][i]['media_type'];
answer['parse_mode'] = 'HTML';
let template = HtmlService.createTemplateFromFile('TMDB/views/inlineQuerySearchResult');
let toTemplate = {
'title': response['results'][i]['title'],
'mediaType': response['results'][i]['media_type'],
'releaseDate': response['results'][i]['release_date'],
'voteAverage': response['results'][i]['vote_average'],
'originalLanguage': response['results'][i]['original_language'],
}
if(response['results'][i]['media_type'] === 'tv') {
toTemplate['tmdbUrl'] = tmdbBaseTvUrl + response['results'][i]['id'];
} else {
toTemplate['tmdbUrl'] = tmdbBaseUrl + response['results'][i]['id'];
}
template['data'] = toTemplate;
answer['caption'] = template.evaluate().getContent();
answers.push(answer);
}
telegramApi.answerInlineQuery(inlineQuery, answers, cacheTime=300);
} |
JavaScript | function searchMulti(searchQuery='dogma') {
let apiKey = scriptProperties.getProperty('TmdbApiKey');
let url = `${baseUrl}${version}/search/multi?api_key=${apiKey}&query=${encodeURIComponent(searchQuery)}&include_adult=true&language=es-ES`
let options = {
method: 'GET',
muteHttpExceptions: false,
};
let res = UrlFetchApp.fetch(url, options);
return JSON.parse(res.getContentText());
} | function searchMulti(searchQuery='dogma') {
let apiKey = scriptProperties.getProperty('TmdbApiKey');
let url = `${baseUrl}${version}/search/multi?api_key=${apiKey}&query=${encodeURIComponent(searchQuery)}&include_adult=true&language=es-ES`
let options = {
method: 'GET',
muteHttpExceptions: false,
};
let res = UrlFetchApp.fetch(url, options);
return JSON.parse(res.getContentText());
} |
JavaScript | function searchMovie(searchQuery='Lebowski') {
let apiKey = scriptProperties.getProperty('TmdbApiKey');
let url = `${baseUrl}${version}/search/movie?api_key=${apiKey}&query=${encodeURIComponent(searchQuery)}&include_adult=true&language=es_ES`
let options = {
method: 'GET',
muteHttpExceptions: false,
};
let res = UrlFetchApp.fetch(url, options);
return JSON.parse(res.getContentText());
} | function searchMovie(searchQuery='Lebowski') {
let apiKey = scriptProperties.getProperty('TmdbApiKey');
let url = `${baseUrl}${version}/search/movie?api_key=${apiKey}&query=${encodeURIComponent(searchQuery)}&include_adult=true&language=es_ES`
let options = {
method: 'GET',
muteHttpExceptions: false,
};
let res = UrlFetchApp.fetch(url, options);
return JSON.parse(res.getContentText());
} |
JavaScript | function handlePokedex(msg) {
let pokemon = replaceString('/pokedex ', '', msg['text']);
getPokedex(msg, pokemon);
} | function handlePokedex(msg) {
let pokemon = replaceString('/pokedex ', '', msg['text']);
getPokedex(msg, pokemon);
} |
JavaScript | function loadPokedexJson() {
let jsonFile = DriveApp.getFileById(scriptProperties.getProperty('PokedexJsonId'));
let jsonBlob = jsonFile.getBlob();
return JSON.parse(jsonBlob.getDataAsString());
} | function loadPokedexJson() {
let jsonFile = DriveApp.getFileById(scriptProperties.getProperty('PokedexJsonId'));
let jsonBlob = jsonFile.getBlob();
return JSON.parse(jsonBlob.getDataAsString());
} |
JavaScript | function loadTypes() {
let jsonFile = DriveApp.getFileById(scriptProperties.getProperty('PokemonTypesConfigId'));
let jsonBlob = jsonFile.getBlob();
return JSON.parse(jsonBlob.getDataAsString());
} | function loadTypes() {
let jsonFile = DriveApp.getFileById(scriptProperties.getProperty('PokemonTypesConfigId'));
let jsonBlob = jsonFile.getBlob();
return JSON.parse(jsonBlob.getDataAsString());
} |
JavaScript | function isPerreteSubscribed(chatId) {
let perretesFolder = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID'));
let perreteFile = perretesFolder.getFilesByName(chatId);
return perreteFile.hasNext()
} | function isPerreteSubscribed(chatId) {
let perretesFolder = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID'));
let perreteFile = perretesFolder.getFilesByName(chatId);
return perreteFile.hasNext()
} |
JavaScript | function subscribeToPerretes(msg) {
if(isPerreteSubscribed(msg['chat']['id'])) {
telegramApi.sendMessage(msg, 'Este chat ya está suscrito a su ración de perretes diaria.', replyTo=true);
} else {
try {
let subscriptionFile = DriveApp.getFileById(SpreadsheetApp.create(String(msg['chat']['id']), 1, 1).getId());
// TODO: Cambiar la forma de gestionar la ubicación de los archivos
let rootFolder = DriveApp.getRootFolder();
let perretesFolder = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID'));
perretesFolder.addFile(subscriptionFile);
rootFolder.removeFile(subscriptionFile);
getPerrete(msg, caption='Gracias por suscribirse al servicio de perretes. A partir de ahora recibirás uno cada día. Además, aquí tienes el primero ;)')
} catch(e) {
telegramApi.sendMessage(msg, 'Ha ocurrido un error al suscribirse al servicio de perretes. :(', replyTo=true);
console.error('Perretes suscription error');
console.error(e);
}
}
} | function subscribeToPerretes(msg) {
if(isPerreteSubscribed(msg['chat']['id'])) {
telegramApi.sendMessage(msg, 'Este chat ya está suscrito a su ración de perretes diaria.', replyTo=true);
} else {
try {
let subscriptionFile = DriveApp.getFileById(SpreadsheetApp.create(String(msg['chat']['id']), 1, 1).getId());
// TODO: Cambiar la forma de gestionar la ubicación de los archivos
let rootFolder = DriveApp.getRootFolder();
let perretesFolder = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID'));
perretesFolder.addFile(subscriptionFile);
rootFolder.removeFile(subscriptionFile);
getPerrete(msg, caption='Gracias por suscribirse al servicio de perretes. A partir de ahora recibirás uno cada día. Además, aquí tienes el primero ;)')
} catch(e) {
telegramApi.sendMessage(msg, 'Ha ocurrido un error al suscribirse al servicio de perretes. :(', replyTo=true);
console.error('Perretes suscription error');
console.error(e);
}
}
} |
JavaScript | function unsubscribeFromPerretes(msg) {
if(isPerreteSubscribed(msg['chat']['id'])) {
try {
let perretesFolder = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID'));
let perreteFile = perretesFolder.getFilesByName(msg['chat']['id']);
perreteFile.next().setTrashed(true);
telegramApi.sendMessage(msg, 'Te echaré de menos :(', replyTo=true);
} catch(e) {
telegramApi.sendMessage(msg, 'Ha ocurrido un error desuscribiendote del servicio de perretes. Esto es una señal clarísima :)', replyTo=true);
console.error('Perretes unsubscription error');
console.error(e);
}
} else {
telegramApi.sendMessage(msg, 'No estás suscrito al servicio de Perretes.', replyTo=true);
}
} | function unsubscribeFromPerretes(msg) {
if(isPerreteSubscribed(msg['chat']['id'])) {
try {
let perretesFolder = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID'));
let perreteFile = perretesFolder.getFilesByName(msg['chat']['id']);
perreteFile.next().setTrashed(true);
telegramApi.sendMessage(msg, 'Te echaré de menos :(', replyTo=true);
} catch(e) {
telegramApi.sendMessage(msg, 'Ha ocurrido un error desuscribiendote del servicio de perretes. Esto es una señal clarísima :)', replyTo=true);
console.error('Perretes unsubscription error');
console.error(e);
}
} else {
telegramApi.sendMessage(msg, 'No estás suscrito al servicio de Perretes.', replyTo=true);
}
} |
JavaScript | function sendPerreteSubscription() {
console.info('Enviando perretes');
let perreteFiles = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID')).getFiles();
while(perreteFiles.hasNext()) {
let perreteFile = perreteFiles.next();
let msg = {'chat':{}};
msg['chat']['id'] = perreteFile.getName();
console.info('Enviando perrete al chat ' + msg['chat']['id']);
try {
getPerrete(msg, 'Aquí tienes tu perrete diario. 💜️')
} catch(e) {
console.error('Se ha intentado enviar un perrete por suscripción a un chat inaccesible: ' + msg['chat']['id']);
}
Utilities.sleep(500);
}
} | function sendPerreteSubscription() {
console.info('Enviando perretes');
let perreteFiles = DriveApp.getFolderById(scriptProperties.getProperty('PerreteSuscriptionsFolderID')).getFiles();
while(perreteFiles.hasNext()) {
let perreteFile = perreteFiles.next();
let msg = {'chat':{}};
msg['chat']['id'] = perreteFile.getName();
console.info('Enviando perrete al chat ' + msg['chat']['id']);
try {
getPerrete(msg, 'Aquí tienes tu perrete diario. 💜️')
} catch(e) {
console.error('Se ha intentado enviar un perrete por suscripción a un chat inaccesible: ' + msg['chat']['id']);
}
Utilities.sleep(500);
}
} |
JavaScript | function handleInlineLocation(inlineQuery) {
let address = replaceString('encontrar ', '', inlineQuery['query']);
let answers = [];
let geocoder = Maps.newGeocoder();
let response = geocoder.geocode(address);
for(let i in response['results']) {
let answer = {};
answer['type'] = 'location';
answer['id'] = String(i);
answer['title'] = response['results'][i]['formatted_address'];
answer['latitude'] = response['results'][i]['geometry']['location']['lat'];
answer['longitude'] = response['results'][i]['geometry']['location']['lng'];
answers.push(answer);
}
telegramApi.answerInlineQuery(inlineQuery, answers, cacheTime=300);
} | function handleInlineLocation(inlineQuery) {
let address = replaceString('encontrar ', '', inlineQuery['query']);
let answers = [];
let geocoder = Maps.newGeocoder();
let response = geocoder.geocode(address);
for(let i in response['results']) {
let answer = {};
answer['type'] = 'location';
answer['id'] = String(i);
answer['title'] = response['results'][i]['formatted_address'];
answer['latitude'] = response['results'][i]['geometry']['location']['lat'];
answer['longitude'] = response['results'][i]['geometry']['location']['lng'];
answers.push(answer);
}
telegramApi.answerInlineQuery(inlineQuery, answers, cacheTime=300);
} |
JavaScript | function handleProximaFiesta(msg) {
let filter = replaceString('/proximaFiesta ', '', msg['text']);
if(filter !== '/proximaFiesta') {
getNextFiesta(msg, filter);
} else {
getNextFiesta(msg);
}
} | function handleProximaFiesta(msg) {
let filter = replaceString('/proximaFiesta ', '', msg['text']);
if(filter !== '/proximaFiesta') {
getNextFiesta(msg, filter);
} else {
getNextFiesta(msg);
}
} |
JavaScript | function handleProximasFiestas(msg) {
let filter = replaceString('/proximasFiestas ', '', msg['text']);
if(filter !== '/proximasFiestas') {
getNextFiesta(msg, filter);
} else {
getNextFiesta(msg);
}
} | function handleProximasFiestas(msg) {
let filter = replaceString('/proximasFiestas ', '', msg['text']);
if(filter !== '/proximasFiestas') {
getNextFiesta(msg, filter);
} else {
getNextFiesta(msg);
}
} |
JavaScript | function handleTranslate(msg) {
let translateFrom;
let translateTo;
let translateText;
try {
if(msg.hasOwnProperty('reply_to_message')) {
let messageText = msg['text'];
messageText = replaceString('/translate ', '', messageText);
let params = messageText.split(',');
translateFrom = params[0];
translateTo = params[1];
translateText = msg['reply_to_message']['text'];
} else {
let messageText = msg['text'];
messageText = replaceString('/translate ', '', messageText);
let params = messageText.split(',');
translateFrom = params[params.length - 2];
translateTo = params[params.length - 1];
messageText = replaceString(',' + translateFrom, '', messageText);
messageText = replaceString(',' + translateTo, '', messageText);
translateText = messageText;
}
translate(msg, translateText, translateFrom, translateTo);
} catch(e) {
console.error('Error in formatting translate call');
console.error(e);
telegramApi.sendMessage(msg, 'Ya lo has roto.', replyTo=true);
}
} | function handleTranslate(msg) {
let translateFrom;
let translateTo;
let translateText;
try {
if(msg.hasOwnProperty('reply_to_message')) {
let messageText = msg['text'];
messageText = replaceString('/translate ', '', messageText);
let params = messageText.split(',');
translateFrom = params[0];
translateTo = params[1];
translateText = msg['reply_to_message']['text'];
} else {
let messageText = msg['text'];
messageText = replaceString('/translate ', '', messageText);
let params = messageText.split(',');
translateFrom = params[params.length - 2];
translateTo = params[params.length - 1];
messageText = replaceString(',' + translateFrom, '', messageText);
messageText = replaceString(',' + translateTo, '', messageText);
translateText = messageText;
}
translate(msg, translateText, translateFrom, translateTo);
} catch(e) {
console.error('Error in formatting translate call');
console.error(e);
telegramApi.sendMessage(msg, 'Ya lo has roto.', replyTo=true);
}
} |
JavaScript | function handleClick(msg) {
if(getRndInteger(0, 6) === 3) {
telegramApi.sendMessage(msg, '😵💥🔫 BAAANG', replyTo=true);
} else {
telegramApi.sendMessage(msg, '😛☁️🔫', replyTo=true);
}
} | function handleClick(msg) {
if(getRndInteger(0, 6) === 3) {
telegramApi.sendMessage(msg, '😵💥🔫 BAAANG', replyTo=true);
} else {
telegramApi.sendMessage(msg, '😛☁️🔫', replyTo=true);
}
} |
JavaScript | function isGateteSubscribed(chatId='-23232799') {
let gatetesFolder = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID'));
let gateteFile = gatetesFolder.getFilesByName(chatId);
return gateteFile.hasNext()
} | function isGateteSubscribed(chatId='-23232799') {
let gatetesFolder = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID'));
let gateteFile = gatetesFolder.getFilesByName(chatId);
return gateteFile.hasNext()
} |
JavaScript | function subscribeToGatetes(msg) {
if(isGateteSubscribed(msg['chat']['id'])) {
telegramApi.sendMessage(msg, 'Este chat ya está suscrito a su ración de gatetes diaria.', replyTo=true);
} else {
try {
let subscriptionFile = DriveApp.getFileById(SpreadsheetApp.create(String(msg['chat']['id']), 1, 1).getId());
let rootFolder = DriveApp.getRootFolder();
let gatetesFolder = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID'));
gatetesFolder.addFile(subscriptionFile);
rootFolder.removeFile(subscriptionFile);
getGatete(msg, caption='Gracias por suscribirse al servicio de gatetes. A partir de ahora recibirás uno cada día. Además, aquí tienes el primero ;)')
} catch(e) {
telegramApi.sendMessage(msg, 'Ha ocurrido un error al suscribirse al servicio de gatetes. :(', replyTo=true);
console.error('Gatetes suscription error');
console.error(e);
}
}
} | function subscribeToGatetes(msg) {
if(isGateteSubscribed(msg['chat']['id'])) {
telegramApi.sendMessage(msg, 'Este chat ya está suscrito a su ración de gatetes diaria.', replyTo=true);
} else {
try {
let subscriptionFile = DriveApp.getFileById(SpreadsheetApp.create(String(msg['chat']['id']), 1, 1).getId());
let rootFolder = DriveApp.getRootFolder();
let gatetesFolder = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID'));
gatetesFolder.addFile(subscriptionFile);
rootFolder.removeFile(subscriptionFile);
getGatete(msg, caption='Gracias por suscribirse al servicio de gatetes. A partir de ahora recibirás uno cada día. Además, aquí tienes el primero ;)')
} catch(e) {
telegramApi.sendMessage(msg, 'Ha ocurrido un error al suscribirse al servicio de gatetes. :(', replyTo=true);
console.error('Gatetes suscription error');
console.error(e);
}
}
} |
JavaScript | function unsubscribeFromGatetes(msg) {
if(isGateteSubscribed(msg['chat']['id'])) {
try {
let gatetesFolder = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID'));
let gateteFile = gatetesFolder.getFilesByName(msg['chat']['id']);
gateteFile.next().setTrashed(true);
telegramApi.sendMessage(msg, 'Te echaré de menos :(', replyTo=true);
} catch(e){
telegramApi.sendMessage(msg, 'Ha ocurrido un error desuscribiendote del servicio de gatetes. Esto es una señal clarísima :)', replyTo=true);
console.error('Gatetes unsubscription error');
console.error(e);
}
} else {
telegramApi.sendMessage(msg, 'No estás suscrito al servicio de gatetes.', replyTo=true);
}
} | function unsubscribeFromGatetes(msg) {
if(isGateteSubscribed(msg['chat']['id'])) {
try {
let gatetesFolder = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID'));
let gateteFile = gatetesFolder.getFilesByName(msg['chat']['id']);
gateteFile.next().setTrashed(true);
telegramApi.sendMessage(msg, 'Te echaré de menos :(', replyTo=true);
} catch(e){
telegramApi.sendMessage(msg, 'Ha ocurrido un error desuscribiendote del servicio de gatetes. Esto es una señal clarísima :)', replyTo=true);
console.error('Gatetes unsubscription error');
console.error(e);
}
} else {
telegramApi.sendMessage(msg, 'No estás suscrito al servicio de gatetes.', replyTo=true);
}
} |
JavaScript | function sendGateteSubscription() {
console.info('Enviando gatetes');
let gateteFiles = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID')).getFiles();
while(gateteFiles.hasNext()) {
let gateteFile = gateteFiles.next();
let msg = {'chat':{}};
msg['chat']['id'] = gateteFile.getName();
console.info('Enviando gatete al chat ' + msg['chat']['id']);
try {
getGatete(msg, 'Aquí tienes tu gatete diario. ❤️')
} catch(e) {
console.error('Se ha intentado enviar un gatete por suscripción a un chat inaccesible: ' + msg['chat']['id']);
}
Utilities.sleep(500);
}
} | function sendGateteSubscription() {
console.info('Enviando gatetes');
let gateteFiles = DriveApp.getFolderById(scriptProperties.getProperty('GateteSuscriptionsFolderID')).getFiles();
while(gateteFiles.hasNext()) {
let gateteFile = gateteFiles.next();
let msg = {'chat':{}};
msg['chat']['id'] = gateteFile.getName();
console.info('Enviando gatete al chat ' + msg['chat']['id']);
try {
getGatete(msg, 'Aquí tienes tu gatete diario. ❤️')
} catch(e) {
console.error('Se ha intentado enviar un gatete por suscripción a un chat inaccesible: ' + msg['chat']['id']);
}
Utilities.sleep(500);
}
} |
JavaScript | function initChatPoleSpreadsheet(chatId) {
let poleFolder = DriveApp.getFolderById(scriptProperties.getProperty('PolesFolderId'));
let rootFolder = DriveApp.getRootFolder();
let poleConfig = JSON.parse(scriptProperties.getProperty('PoleConfig'));
let ss = SpreadsheetApp.create(chatId);
var ssFile = DriveApp.getFileById(ss.getId());
let poleConfigJSON = {};
for(let i in poleConfig['names']) {
poleConfigJSON[poleConfig['names'][i]] = {
'priority': i,
'lastPoleador': '',
'lastDate': '1970-01-01'
}
let newSheet = ss.insertSheet(poleConfig['names'][i]);
newSheet.deleteColumns(3, newSheet.getMaxColumns() - 3);
newSheet.deleteRows(1, newSheet.getMaxRows() - 1);
}
let configSheet = ss.insertSheet('CONFIG', poleConfig['names'].length + 1);
configSheet.deleteColumns(1, configSheet.getMaxColumns() - 1);
configSheet.deleteRows(1, configSheet.getMaxRows() - 1);
configSheet.getRange(1,1).setValue(JSON.stringify(poleConfigJSON));
ss.deleteSheet(ss.getSheets()[0]);
poleFolder.addFile(ssFile);
rootFolder.removeFile(ssFile);
return ss;
} | function initChatPoleSpreadsheet(chatId) {
let poleFolder = DriveApp.getFolderById(scriptProperties.getProperty('PolesFolderId'));
let rootFolder = DriveApp.getRootFolder();
let poleConfig = JSON.parse(scriptProperties.getProperty('PoleConfig'));
let ss = SpreadsheetApp.create(chatId);
var ssFile = DriveApp.getFileById(ss.getId());
let poleConfigJSON = {};
for(let i in poleConfig['names']) {
poleConfigJSON[poleConfig['names'][i]] = {
'priority': i,
'lastPoleador': '',
'lastDate': '1970-01-01'
}
let newSheet = ss.insertSheet(poleConfig['names'][i]);
newSheet.deleteColumns(3, newSheet.getMaxColumns() - 3);
newSheet.deleteRows(1, newSheet.getMaxRows() - 1);
}
let configSheet = ss.insertSheet('CONFIG', poleConfig['names'].length + 1);
configSheet.deleteColumns(1, configSheet.getMaxColumns() - 1);
configSheet.deleteRows(1, configSheet.getMaxRows() - 1);
configSheet.getRange(1,1).setValue(JSON.stringify(poleConfigJSON));
ss.deleteSheet(ss.getSheets()[0]);
poleFolder.addFile(ssFile);
rootFolder.removeFile(ssFile);
return ss;
} |
JavaScript | function increaseUserRank(user, username, command, ss) {
let sheet = ss.getSheetByName(command);
//var data = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
let data = sheet.getRange('A1:C').getValues();
let count = 1;
let found = false;
for(let i in data) {
if(data[i][0] === user['id']) {
data[i][1] = username;
data[i][2] += 1;
sheet.getRange(parseInt(i) + 1, 1, 1, 3).setValues([data[i]]);
found = true;
}
}
if(!found) {
sheet.appendRow([user['id'], username, 1]);
}
} | function increaseUserRank(user, username, command, ss) {
let sheet = ss.getSheetByName(command);
//var data = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
let data = sheet.getRange('A1:C').getValues();
let count = 1;
let found = false;
for(let i in data) {
if(data[i][0] === user['id']) {
data[i][1] = username;
data[i][2] += 1;
sheet.getRange(parseInt(i) + 1, 1, 1, 3).setValues([data[i]]);
found = true;
}
}
if(!found) {
sheet.appendRow([user['id'], username, 1]);
}
} |
JavaScript | function convertCurrency(msg) {
try {
let params = msg['text'].toUpperCase().split(' ');
let amount = params[1];
let conversion = params[2] + '_' + params[3];
let convertEndpoint = '/api/v6/convert?q=' + conversion + '&compact= ultra&apiKey=' + scriptProperties.getProperty('CurrencyApiKey');
let data = UrlFetchApp.fetch(currencyUrlBase + convertEndpoint);
let JSONdata = JSON.parse(data.getContentText());
let result = amount * JSONdata['results'][conversion]['val'];
telegramApi.sendMessage(msg, result + ' ' + params[3], replyTo=false);
} catch(e) {
console.error('Error en convertCurrency');
console.error(e);
telegramApi.sendMessage(msg, 'No se ha podido realizar la conversion.', replyTo=true);
}
} | function convertCurrency(msg) {
try {
let params = msg['text'].toUpperCase().split(' ');
let amount = params[1];
let conversion = params[2] + '_' + params[3];
let convertEndpoint = '/api/v6/convert?q=' + conversion + '&compact= ultra&apiKey=' + scriptProperties.getProperty('CurrencyApiKey');
let data = UrlFetchApp.fetch(currencyUrlBase + convertEndpoint);
let JSONdata = JSON.parse(data.getContentText());
let result = amount * JSONdata['results'][conversion]['val'];
telegramApi.sendMessage(msg, result + ' ' + params[3], replyTo=false);
} catch(e) {
console.error('Error en convertCurrency');
console.error(e);
telegramApi.sendMessage(msg, 'No se ha podido realizar la conversion.', replyTo=true);
}
} |
JavaScript | function handlePole(msg) {
// Get a script lock, because we're about to modify a shared resource.
let lock = LockService.getScriptLock();
// Wait for up to 30 seconds for other processes to finish.
lock.waitLock(30000);
let poleConfig = JSON.parse(scriptProperties.getProperty('PoleConfig'));
if(!checkIfExcludedChat(msg, poleConfig)) {
let ss = getChatSpreadsheet(String(msg['chat']['id']));
if(ss == null) {
// No ha habido poles en esta conversación
ss = initChatPoleSpreadsheet(msg['chat']['id']);
}
let poleConfigSheet = ss.getSheetByName('CONFIG');
let poleConfigRange = poleConfigSheet.getRange(1, 1);
let poleConfigValues = JSON.parse(poleConfigRange.getValue());
let commandPriority = poleConfig['names'].indexOf(msg.text);
let today = new Date();
let lastDate = new Date(poleConfigValues[msg['text']]['lastDate']);
let username = getBestUsername(msg['from']);
if(commandPriority === 0) {
// Es la pole, vamos a ver si la de hoy ya se ha hecho
if(!isToday(poleConfigValues[msg['text']]['lastDate'])) {
// hay pole
// TODO: Place this logic into a function
let poleConfigConfiguration = poleConfig['configuration'][msg['text']];
poleConfigValues[msg['text']]['lastDate'] = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
poleConfigValues[msg['text']]['lastPoleador'] = msg['from']['id'];
poleConfigRange.setValue(JSON.stringify(poleConfigValues));
increaseUserRank(msg['from'], username, msg['text'], ss);
telegramApi.sendMessage(msg, `El ${poleConfigConfiguration['message']} @${username} ha hecho ${poleConfigConfiguration['gender']} ${msg['text']}`);
}
} else {
if(!isToday(poleConfigValues[msg.text]['lastDate'])) {
// No se ha hecho hoy, vamos a ver si se ha hecho la anterior
let previousCommand = poleConfig['names'][commandPriority - 1];
if(isToday(poleConfigValues[previousCommand]['lastDate'])) {
// Ya se ha hecho el comando anterior, así que podemos hacer el siguiente
if(!checkIfUserPoleo(msg['from']['id'], poleConfigValues)) {
// No hemos hecho nosotros ninguna pole anterior, así que la podemos hacer
let poleConfigConfiguration = poleConfig['configuration'][msg['text']];
poleConfigValues[msg['text']]['lastDate'] = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
poleConfigValues[msg['text']]['lastPoleador'] = msg['from']['id'];
poleConfigRange.setValue(JSON.stringify(poleConfigValues));
increaseUserRank(msg['from'], username, msg.text, ss);
telegramApi.sendMessage(msg, `El ${poleConfigConfiguration['message']} @${username} ha hecho ${poleConfigConfiguration['gender']} ${msg['text']}`);
}
}
}
}
}
// Release the lock so that other processes can continue.
lock.releaseLock();
} | function handlePole(msg) {
// Get a script lock, because we're about to modify a shared resource.
let lock = LockService.getScriptLock();
// Wait for up to 30 seconds for other processes to finish.
lock.waitLock(30000);
let poleConfig = JSON.parse(scriptProperties.getProperty('PoleConfig'));
if(!checkIfExcludedChat(msg, poleConfig)) {
let ss = getChatSpreadsheet(String(msg['chat']['id']));
if(ss == null) {
// No ha habido poles en esta conversación
ss = initChatPoleSpreadsheet(msg['chat']['id']);
}
let poleConfigSheet = ss.getSheetByName('CONFIG');
let poleConfigRange = poleConfigSheet.getRange(1, 1);
let poleConfigValues = JSON.parse(poleConfigRange.getValue());
let commandPriority = poleConfig['names'].indexOf(msg.text);
let today = new Date();
let lastDate = new Date(poleConfigValues[msg['text']]['lastDate']);
let username = getBestUsername(msg['from']);
if(commandPriority === 0) {
// Es la pole, vamos a ver si la de hoy ya se ha hecho
if(!isToday(poleConfigValues[msg['text']]['lastDate'])) {
// hay pole
// TODO: Place this logic into a function
let poleConfigConfiguration = poleConfig['configuration'][msg['text']];
poleConfigValues[msg['text']]['lastDate'] = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
poleConfigValues[msg['text']]['lastPoleador'] = msg['from']['id'];
poleConfigRange.setValue(JSON.stringify(poleConfigValues));
increaseUserRank(msg['from'], username, msg['text'], ss);
telegramApi.sendMessage(msg, `El ${poleConfigConfiguration['message']} @${username} ha hecho ${poleConfigConfiguration['gender']} ${msg['text']}`);
}
} else {
if(!isToday(poleConfigValues[msg.text]['lastDate'])) {
// No se ha hecho hoy, vamos a ver si se ha hecho la anterior
let previousCommand = poleConfig['names'][commandPriority - 1];
if(isToday(poleConfigValues[previousCommand]['lastDate'])) {
// Ya se ha hecho el comando anterior, así que podemos hacer el siguiente
if(!checkIfUserPoleo(msg['from']['id'], poleConfigValues)) {
// No hemos hecho nosotros ninguna pole anterior, así que la podemos hacer
let poleConfigConfiguration = poleConfig['configuration'][msg['text']];
poleConfigValues[msg['text']]['lastDate'] = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
poleConfigValues[msg['text']]['lastPoleador'] = msg['from']['id'];
poleConfigRange.setValue(JSON.stringify(poleConfigValues));
increaseUserRank(msg['from'], username, msg.text, ss);
telegramApi.sendMessage(msg, `El ${poleConfigConfiguration['message']} @${username} ha hecho ${poleConfigConfiguration['gender']} ${msg['text']}`);
}
}
}
}
}
// Release the lock so that other processes can continue.
lock.releaseLock();
} |
JavaScript | function checkIfUserPoleo(userId, poleConfigValues) {
for(let i in poleConfigValues) {
if(poleConfigValues[i]['lastPoleador'] === userId && isToday(poleConfigValues[i]['lastDate'])) {
return true;
}
}
return false;
} | function checkIfUserPoleo(userId, poleConfigValues) {
for(let i in poleConfigValues) {
if(poleConfigValues[i]['lastPoleador'] === userId && isToday(poleConfigValues[i]['lastDate'])) {
return true;
}
}
return false;
} |
JavaScript | function computeGlobalRank(poleConfig, data) {
let numLength = poleConfig['names'].length;
let globalRankObject = {};
for(let sheet in poleConfig['names']) {
let values = data[poleConfig['names'][sheet]]['sortedValues'];
for(let i in values) {
if(values[i][0] !== ''){
if(globalRankObject[values[i][0]]) {
globalRankObject[values[i][0]][values[i][1]] += values[i][2] * numLength
} else {
globalRankObject[values[i][0]] = {}
globalRankObject[values[i][0]][values[i][1]] = values[i][2] * numLength;
}
}
}
numLength -= 1;
}
let globalRankObjectValues = Object.values(globalRankObject);
let globalRank = [];
for(let user in globalRankObjectValues) {
globalRank.push(Object.entries(globalRankObjectValues[user])[0]);
}
globalRank.sort(compare);
return globalRank;
} | function computeGlobalRank(poleConfig, data) {
let numLength = poleConfig['names'].length;
let globalRankObject = {};
for(let sheet in poleConfig['names']) {
let values = data[poleConfig['names'][sheet]]['sortedValues'];
for(let i in values) {
if(values[i][0] !== ''){
if(globalRankObject[values[i][0]]) {
globalRankObject[values[i][0]][values[i][1]] += values[i][2] * numLength
} else {
globalRankObject[values[i][0]] = {}
globalRankObject[values[i][0]][values[i][1]] = values[i][2] * numLength;
}
}
}
numLength -= 1;
}
let globalRankObjectValues = Object.values(globalRankObject);
let globalRank = [];
for(let user in globalRankObjectValues) {
globalRank.push(Object.entries(globalRankObjectValues[user])[0]);
}
globalRank.sort(compare);
return globalRank;
} |
JavaScript | function polerank(msg) {
if(!checkIfExcludedChat(msg, poleConfig)) {
let poleConfig = JSON.parse(scriptProperties.getProperty('PoleConfig'));
let ss = getChatSpreadsheet(String(msg['chat']['id']));
if(ss) {
let toTemplate = {};
for(let sheet in poleConfig['names']) {
toTemplate[poleConfig['names'][sheet]] = {};
let values = ss.getSheetByName(poleConfig['names'][sheet]).getRange('A1:C').getValues();
values.sort(comparePolerank);
toTemplate[poleConfig['names'][sheet]]['sortedValues'] = values;
}
toTemplate['globalRank'] = computeGlobalRank(poleConfig, toTemplate);
let template = HtmlService.createTemplateFromFile('pole/views/poleTemplate');
template['data'] = toTemplate;
template['priority'] = poleConfig['names'];
telegramApi.sendMessage(msg, template.evaluate().getContent(), replyTo=true);
} else {
telegramApi.sendMessage(msg, 'No se ha hecho nunca la Pole en este chat', replyTo=true);
}
}
} | function polerank(msg) {
if(!checkIfExcludedChat(msg, poleConfig)) {
let poleConfig = JSON.parse(scriptProperties.getProperty('PoleConfig'));
let ss = getChatSpreadsheet(String(msg['chat']['id']));
if(ss) {
let toTemplate = {};
for(let sheet in poleConfig['names']) {
toTemplate[poleConfig['names'][sheet]] = {};
let values = ss.getSheetByName(poleConfig['names'][sheet]).getRange('A1:C').getValues();
values.sort(comparePolerank);
toTemplate[poleConfig['names'][sheet]]['sortedValues'] = values;
}
toTemplate['globalRank'] = computeGlobalRank(poleConfig, toTemplate);
let template = HtmlService.createTemplateFromFile('pole/views/poleTemplate');
template['data'] = toTemplate;
template['priority'] = poleConfig['names'];
telegramApi.sendMessage(msg, template.evaluate().getContent(), replyTo=true);
} else {
telegramApi.sendMessage(msg, 'No se ha hecho nunca la Pole en este chat', replyTo=true);
}
}
} |
JavaScript | function resetPolerank(msg) {
if(!checkIfExcludedChat(msg, poleConfig)) {
let ss = getChatSpreadsheet(String(msg['chat']['id']));
if(ss) {
DriveApp.getFileById(ss.getId()).setTrashed(true);
telegramApi.sendMessage(msg, 'Hecho!', replyTo=true);
} else {
telegramApi.sendMessage(msg, 'Ha habido un problema reseteando el ranking de este chat', replyTo=true);
}
}
} | function resetPolerank(msg) {
if(!checkIfExcludedChat(msg, poleConfig)) {
let ss = getChatSpreadsheet(String(msg['chat']['id']));
if(ss) {
DriveApp.getFileById(ss.getId()).setTrashed(true);
telegramApi.sendMessage(msg, 'Hecho!', replyTo=true);
} else {
telegramApi.sendMessage(msg, 'Ha habido un problema reseteando el ranking de este chat', replyTo=true);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.