language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function addUser(id, info, welcome = true, callback = () => { }, retry = true, currentBuffer = 0, api = gapi) {
api.addUserToGroup(id, info.threadId, (err, data) => {
if (!err) {
updateGroupInfo(info.threadId, null, (err, info) => {
if (!err && welcome) {
if (info.names[id]) {
sendMessage(`Welcome to ${info.name}, ${info.names[id]}!`, info.threadId);
} else {
api.getUserInfo(id, (err, uinfo) => {
if (!err && uinfo.name) {
sendMessage(`${uinfo.name} will be added to ${info.name} pending admin approval.`, info.threadId);
}
});
}
}
});
callback();
} else if (err && (currentBuffer < config.addBufferLimit)) {
if (retry) {
addUser(id, info, welcome, callback, retry, (currentBuffer + 1));
} else {
callback(err);
}
} else {
callback(err);
}
});
} | function addUser(id, info, welcome = true, callback = () => { }, retry = true, currentBuffer = 0, api = gapi) {
api.addUserToGroup(id, info.threadId, (err, data) => {
if (!err) {
updateGroupInfo(info.threadId, null, (err, info) => {
if (!err && welcome) {
if (info.names[id]) {
sendMessage(`Welcome to ${info.name}, ${info.names[id]}!`, info.threadId);
} else {
api.getUserInfo(id, (err, uinfo) => {
if (!err && uinfo.name) {
sendMessage(`${uinfo.name} will be added to ${info.name} pending admin approval.`, info.threadId);
}
});
}
}
});
callback();
} else if (err && (currentBuffer < config.addBufferLimit)) {
if (retry) {
addUser(id, info, welcome, callback, retry, (currentBuffer + 1));
} else {
callback(err);
}
} else {
callback(err);
}
});
} |
JavaScript | function updateGroupInfo(threadId, message, callback = () => { }, api = gapi) {
getGroupInfo(threadId, (err, existingInfo) => {
if (!err) {
let isNew = false;
if (!existingInfo) {
const n = config.bot.names; // Bot name info
// Group not yet registered
isNew = true;
sendMessage(`Hello! I'm ${n.long}${n.short ? `, but you can call me ${n.short}` : ""}. Give me a moment to collect some information about this chat before you use any commands.`, threadId);
api.muteThread(threadId, -1); // Mute chat
// Add bot's nickname if available
api.changeNickname(n.short, threadId, config.bot.id); // Won't do anything if undefined
}
api.getThreadInfo(threadId, (err, data) => {
if (data) {
let info = existingInfo || {};
info.threadId = threadId;
info.lastMessage = message;
info.name = data.threadName || config.defaultTitle;
info.emoji = data.emoji;
info.color = data.color ? `#${data.color}` : null;
if (data.nicknames && data.nicknames[config.bot.id]) { // Don't add bot to nicknames list
delete data.nicknames[config.bot.id];
}
info.nicknames = data.nicknames || {};
info.admins = data.adminIDs ? data.adminIDs.map(u => u["id"]) : [];
if (isNew) {
// These properties only need to be initialized once
info.muted = true;
info.playlists = {};
info.aliases = {};
info.isGroup = data.isGroup;
}
api.getUserInfo(data.participantIDs, (err, userData) => {
if (!err) {
info.members = {};
info.names = {};
info.birthday = {};
for (let id in userData) {
if (userData.hasOwnProperty(id) && id != config.bot.id) { // Very important to not add bot to participants list
info.members[userData[id].name.toLowerCase()] = id;
info.names[id] = userData[id].name;
info.birthday[id] = userData[id].isBirthday;
}
}
// Set regex to search for member first names and any included aliases
const aliases = Object.keys(info.aliases).map((n) => {
return info.aliases[n];
});
const matches = Object.keys(info.members);
info.userRegExp = utils.getRegexFromMembers(matches.concat(aliases));
// Attempt to give chat a more descriptive name than "Unnamed chat" if possible
if (info.name == config.defaultTitle) {
let names = Object.keys(info.names).map((n) => {
return info.names[n];
});
info.name = names.join("/") || "Unnamed chat";
}
if (isNew) {
// Alert owner now that chat name is available
sendMessage(`Bot added to new chat: "${info.name}".`, config.owner.id);
}
}
setGroupInfo(info, (err) => {
if (!existingInfo) {
sendMessage(`All done! Use '${config.trigger} help' to see what I can do.`, threadId);
}
callback(err, info);
});
});
} else {
// Errors are logged here despite being a utility func b/c errors here are critical
console.log(new Error(`Thread info not found for ${threadId}`));
console.log(err);
callback(err);
}
});
} else {
console.log(err);
callback(err);
}
});
} | function updateGroupInfo(threadId, message, callback = () => { }, api = gapi) {
getGroupInfo(threadId, (err, existingInfo) => {
if (!err) {
let isNew = false;
if (!existingInfo) {
const n = config.bot.names; // Bot name info
// Group not yet registered
isNew = true;
sendMessage(`Hello! I'm ${n.long}${n.short ? `, but you can call me ${n.short}` : ""}. Give me a moment to collect some information about this chat before you use any commands.`, threadId);
api.muteThread(threadId, -1); // Mute chat
// Add bot's nickname if available
api.changeNickname(n.short, threadId, config.bot.id); // Won't do anything if undefined
}
api.getThreadInfo(threadId, (err, data) => {
if (data) {
let info = existingInfo || {};
info.threadId = threadId;
info.lastMessage = message;
info.name = data.threadName || config.defaultTitle;
info.emoji = data.emoji;
info.color = data.color ? `#${data.color}` : null;
if (data.nicknames && data.nicknames[config.bot.id]) { // Don't add bot to nicknames list
delete data.nicknames[config.bot.id];
}
info.nicknames = data.nicknames || {};
info.admins = data.adminIDs ? data.adminIDs.map(u => u["id"]) : [];
if (isNew) {
// These properties only need to be initialized once
info.muted = true;
info.playlists = {};
info.aliases = {};
info.isGroup = data.isGroup;
}
api.getUserInfo(data.participantIDs, (err, userData) => {
if (!err) {
info.members = {};
info.names = {};
info.birthday = {};
for (let id in userData) {
if (userData.hasOwnProperty(id) && id != config.bot.id) { // Very important to not add bot to participants list
info.members[userData[id].name.toLowerCase()] = id;
info.names[id] = userData[id].name;
info.birthday[id] = userData[id].isBirthday;
}
}
// Set regex to search for member first names and any included aliases
const aliases = Object.keys(info.aliases).map((n) => {
return info.aliases[n];
});
const matches = Object.keys(info.members);
info.userRegExp = utils.getRegexFromMembers(matches.concat(aliases));
// Attempt to give chat a more descriptive name than "Unnamed chat" if possible
if (info.name == config.defaultTitle) {
let names = Object.keys(info.names).map((n) => {
return info.names[n];
});
info.name = names.join("/") || "Unnamed chat";
}
if (isNew) {
// Alert owner now that chat name is available
sendMessage(`Bot added to new chat: "${info.name}".`, config.owner.id);
}
}
setGroupInfo(info, (err) => {
if (!existingInfo) {
sendMessage(`All done! Use '${config.trigger} help' to see what I can do.`, threadId);
}
callback(err, info);
});
});
} else {
// Errors are logged here despite being a utility func b/c errors here are critical
console.log(new Error(`Thread info not found for ${threadId}`));
console.log(err);
callback(err);
}
});
} else {
console.log(err);
callback(err);
}
});
} |
JavaScript | function sendFileFromUrl(url, path = "media/temp.jpg", message = "", threadId, api = gapi) {
request.head(url, (err, res, body) => {
// Download file and pass to chat API
if (!err) {
request(url).pipe(fs.createWriteStream(path)).on('close', (err, data) => {
if (!err) {
// Use API's official sendMessage here for callback functionality
sendMessage({
"body": message,
"attachment": fs.createReadStream(`${__dirname}/${path}`)
}, threadId, (err, data) => {
// Delete downloaded propic
fs.unlink(path);
});
} else {
sendMessage(url, threadId);
}
});
} else {
// Just send the description if photo can't be downloaded
sendMessage(message, threadId);
}
});
} | function sendFileFromUrl(url, path = "media/temp.jpg", message = "", threadId, api = gapi) {
request.head(url, (err, res, body) => {
// Download file and pass to chat API
if (!err) {
request(url).pipe(fs.createWriteStream(path)).on('close', (err, data) => {
if (!err) {
// Use API's official sendMessage here for callback functionality
sendMessage({
"body": message,
"attachment": fs.createReadStream(`${__dirname}/${path}`)
}, threadId, (err, data) => {
// Delete downloaded propic
fs.unlink(path);
});
} else {
sendMessage(url, threadId);
}
});
} else {
// Just send the description if photo can't be downloaded
sendMessage(message, threadId);
}
});
} |
JavaScript | function debugLog(msg) {
if (msg !== undefined && document.getElementById('debug-mode').checked==true) {
console.log(msg);
}
} | function debugLog(msg) {
if (msg !== undefined && document.getElementById('debug-mode').checked==true) {
console.log(msg);
}
} |
JavaScript | function fileSelected() {
// clear feedback block
resetUpload();
// get form files selection
var fileInput = document.getElementById('upload-tmpFiles');
// get feedback block
var feedBack = document.getElementById('feedBack');
// sum of the total size of files to upload
var sumFileSize = 0;
// loop through individual files contained in files selection
for (var i = 0, file; file = fileInput.files[i]; ++i) {
// determine and humanize file size of file
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toFixed(1) + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toFixed(0) + 'KB';
// add file size to total size
sumFileSize = sumFileSize + file.size;
// unique id to be applied to the <div> block
var fInc = 'file' + i.toString();
// string of text to be applied to the body of the <div> block
var fString = "";
fString = fString + (i+1).toString() + ': <code id="' + fInc + 'Name">' + file.name + '</code> ';
fString = fString + 'Size: <var id="' + fInc + 'Size">' + fileSize + '</var> ';
fString = fString + 'Type: <kbd id="' + fInc + 'Type">' + file.type + '</kbd>';
// append fString to existing feedBack block
feedBack.innerHTML = feedBack.innerHTML + '<div id="' + fInc + '">' + fString + '</div>'
}
// prepend files section count and total size to feedBack block
feedBack.innerHTML = '<p>' + i + ' files selected which are ' + (Math.round(sumFileSize * 100 / (1024 * 1024)) / 100).toFixed(1) + 'MB.</p>' + feedBack.innerHTML;
// enable feedBack block
feedBack.style = 'display: block;';
} | function fileSelected() {
// clear feedback block
resetUpload();
// get form files selection
var fileInput = document.getElementById('upload-tmpFiles');
// get feedback block
var feedBack = document.getElementById('feedBack');
// sum of the total size of files to upload
var sumFileSize = 0;
// loop through individual files contained in files selection
for (var i = 0, file; file = fileInput.files[i]; ++i) {
// determine and humanize file size of file
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toFixed(1) + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toFixed(0) + 'KB';
// add file size to total size
sumFileSize = sumFileSize + file.size;
// unique id to be applied to the <div> block
var fInc = 'file' + i.toString();
// string of text to be applied to the body of the <div> block
var fString = "";
fString = fString + (i+1).toString() + ': <code id="' + fInc + 'Name">' + file.name + '</code> ';
fString = fString + 'Size: <var id="' + fInc + 'Size">' + fileSize + '</var> ';
fString = fString + 'Type: <kbd id="' + fInc + 'Type">' + file.type + '</kbd>';
// append fString to existing feedBack block
feedBack.innerHTML = feedBack.innerHTML + '<div id="' + fInc + '">' + fString + '</div>'
}
// prepend files section count and total size to feedBack block
feedBack.innerHTML = '<p>' + i + ' files selected which are ' + (Math.round(sumFileSize * 100 / (1024 * 1024)) / 100).toFixed(1) + 'MB.</p>' + feedBack.innerHTML;
// enable feedBack block
feedBack.style = 'display: block;';
} |
JavaScript | function transferSpeed(loaded) {
var transferTimeSplit = new Date().getTime();
var tc = (transferTimeSplit - transferTimer) / 1000; // global var transferTimer is set in the xhr.onreadystatechange event.
var rate = '';
var speed = Math.round(loaded / tc); // loaded is a value of bytes
if(speed > 104858) {
speed = (speed/1048576);
rate = speed.toFixed(1) + ' Mibit/s'; // Mebibit per second
} else {
speed = (speed/1024);
rate = speed + ' Kibit/s'; // Kibibit per second
}
return rate;
} | function transferSpeed(loaded) {
var transferTimeSplit = new Date().getTime();
var tc = (transferTimeSplit - transferTimer) / 1000; // global var transferTimer is set in the xhr.onreadystatechange event.
var rate = '';
var speed = Math.round(loaded / tc); // loaded is a value of bytes
if(speed > 104858) {
speed = (speed/1048576);
rate = speed.toFixed(1) + ' Mibit/s'; // Mebibit per second
} else {
speed = (speed/1024);
rate = speed + ' Kibit/s'; // Kibibit per second
}
return rate;
} |
JavaScript | function formValidation(form) {
// clear feedback block
resetUpload();
// get form files selection
var fileInput = document.getElementById('upload-tmpFiles');
// get feedback block
var feedBack = document.getElementById('feedBack');
// if no files are selected notify the client.
if (fileInput.files.length == 0) {
feedBack.innerHTML = feedBack.innerHTML + '<li>Select at least one file for upload.</li>';
}
// you can add other form validations here ...
// if any validation errors exist display the notifications in the feedBack block
if (feedBack.innerHTML.length > 0) {
feedBack.style.display = "block";
feedBack.innerHTML = 'Please correct the following issues with your submission:<ul>' + feedBack.innerHTML + '</ul>';
return false;
} else {
return true;
}
} | function formValidation(form) {
// clear feedback block
resetUpload();
// get form files selection
var fileInput = document.getElementById('upload-tmpFiles');
// get feedback block
var feedBack = document.getElementById('feedBack');
// if no files are selected notify the client.
if (fileInput.files.length == 0) {
feedBack.innerHTML = feedBack.innerHTML + '<li>Select at least one file for upload.</li>';
}
// you can add other form validations here ...
// if any validation errors exist display the notifications in the feedBack block
if (feedBack.innerHTML.length > 0) {
feedBack.style.display = "block";
feedBack.innerHTML = 'Please correct the following issues with your submission:<ul>' + feedBack.innerHTML + '</ul>';
return false;
} else {
return true;
}
} |
JavaScript | membership(query, ctx) {
if (!ctx) return;
if (ctx && ctx.meta.userID) {
query.members = ctx.meta.userID;
} else {
query.public = true;
}
return query;
} | membership(query, ctx) {
if (!ctx) return;
if (ctx && ctx.meta.userID) {
query.members = ctx.meta.userID;
} else {
query.public = true;
}
return query;
} |
JavaScript | async clear(path=undefined) {
return new Promise(async (resolve, reject) => {
let listParams = {Bucket: this._bucket}
if (path !== undefined) listParams.Prefix = path;
while (true) {
// list objects
const listedObjects = await this._s3.listObjectsV2(listParams).promise();
if (listedObjects.Contents === undefined) {
return reject(new Error('Listing S3 returns no contents'));
}
if (listedObjects.Contents.length !== 0) {
await this._s3.deleteObjects({
Bucket: this._bucket,
Delete: {
Objects: listedObjects.Contents.map(obj => ({
Key: obj.Key
}))
}
}).promise();
}
if (!listedObjects.IsTruncated) return resolve();
}
});
} | async clear(path=undefined) {
return new Promise(async (resolve, reject) => {
let listParams = {Bucket: this._bucket}
if (path !== undefined) listParams.Prefix = path;
while (true) {
// list objects
const listedObjects = await this._s3.listObjectsV2(listParams).promise();
if (listedObjects.Contents === undefined) {
return reject(new Error('Listing S3 returns no contents'));
}
if (listedObjects.Contents.length !== 0) {
await this._s3.deleteObjects({
Bucket: this._bucket,
Delete: {
Objects: listedObjects.Contents.map(obj => ({
Key: obj.Key
}))
}
}).promise();
}
if (!listedObjects.IsTruncated) return resolve();
}
});
} |
JavaScript | function renderLicenseLink(license) {
///if/else statement
if (license === "") {
license = "";
} else {
license = "- [License](#license)\n";
}
return license;
} | function renderLicenseLink(license) {
///if/else statement
if (license === "") {
license = "";
} else {
license = "- [License](#license)\n";
}
return license;
} |
JavaScript | function renderLicenseSection(license) {
if (license !== "") {
licenseSection = `## License \n This project is licensed under the terms of the ${license} license. For more information please, refer to [https://choosealicense.com/]. `;
} else {
licenseSection = "";
}
return licenseSection;
} | function renderLicenseSection(license) {
if (license !== "") {
licenseSection = `## License \n This project is licensed under the terms of the ${license} license. For more information please, refer to [https://choosealicense.com/]. `;
} else {
licenseSection = "";
}
return licenseSection;
} |
JavaScript | function generateMarkdown(data) {
return `# ${data.title}
${renderLicenseBadge(data.license)}
## Description
${data.description}
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
${renderLicenseLink(data.license)}- [Contributing](#contributing)
- [Tests](#tests)
- [Questions](#questions)
## Installation
${data.installation}
## Usage
${data.usage}
${renderLicenseSection(data.license)}
## Contributing
${data.contributors}
## Tests
${data.test}
## Questions
Any Questions? Contact me! Github: ${data.github} Email: ${data.email}`;
} | function generateMarkdown(data) {
return `# ${data.title}
${renderLicenseBadge(data.license)}
## Description
${data.description}
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
${renderLicenseLink(data.license)}- [Contributing](#contributing)
- [Tests](#tests)
- [Questions](#questions)
## Installation
${data.installation}
## Usage
${data.usage}
${renderLicenseSection(data.license)}
## Contributing
${data.contributors}
## Tests
${data.test}
## Questions
Any Questions? Contact me! Github: ${data.github} Email: ${data.email}`;
} |
JavaScript | function writeToFile(fileName, data) {
//path- take a look at this one to bring in (Shipped Module)
//
fs.writeFile(fileName, data, (err) => {
err ? console.error(err) : console.log("Success!");
});
} | function writeToFile(fileName, data) {
//path- take a look at this one to bring in (Shipped Module)
//
fs.writeFile(fileName, data, (err) => {
err ? console.error(err) : console.log("Success!");
});
} |
JavaScript | addListeners() {
// Get all elements that are Skrolla-friendly
const elements = doc.querySelectorAll('[data-skrolla]');
// Add an event listener for each element
Array.prototype.forEach.call(elements, (element) => {
element.addEventListener('click', Events.onClick);
});
} | addListeners() {
// Get all elements that are Skrolla-friendly
const elements = doc.querySelectorAll('[data-skrolla]');
// Add an event listener for each element
Array.prototype.forEach.call(elements, (element) => {
element.addEventListener('click', Events.onClick);
});
} |
JavaScript | function serverFactory (factoryOptions) {
const options = {
host: process.env.HOST || "0.0.0.0",
port: process.env.PORT || "80",
keepComments: Boolean(process.env.KEEP_COMMENTS) || true,
beautify: Boolean(process.env.BEAUTIFY) || false,
minify: Boolean(process.env.MINIFY) || false,
validationLevel: process.env.VALIDATION_LEVEL || "soft", // choices: "strict", "soft", "skip"
maxBody: process.env.MAX_BODY || "1mb",
"mjml-version": pkg.dependencies.mjml, // requires launching through either npm or yarn, but not directly node,
authentication: {
enabled: Boolean(process.env.AUTH_ENABLED) || false,
type: process.env.AUTH_TYPE === "token" ? "token" : process.env.AUTH_TYPE === "basic" ? "basic" : "none",
basicAuth: {
username: process.env.BASIC_AUTH_USERNAME,
password: process.env.BASIC_AUTH_PASSWORD
},
token: {
secret: process.env.AUTH_TOKEN
}
},
...factoryOptions
};
const app = express();
// Parse request body to a buffer, as it might contain JSON but doesn't have to
app.use(express.raw({
type: () => true,
limit: options.maxBody
}));
// minimal JSON logging middleware
app.use(pino);
logger.info({ config: options }, "Parsed configuration");
// main API endpoint for mjml renderer
app.post("/v1/render", authentication(options.authentication), (req, res, next) => {
let mjmlText;
// attempt to parse JSON off of body
try {
// req.body is a Buffer, see express.raw()
mjmlText = JSON.parse(req.body.toString()).mjml;
} catch (err) {
mjmlText = req.body.toString();
}
let result;
const config = {
keepComments: options.keepComments,
beautify: options.beautify, // TODO(fibis): no longer supported in mjml ^4.0.0, see deprectation notice
minify: options.minify, // TODO(fibis): no longer supported in mjml ^4.0.0, see deprectation notice
validationLevel: options.validationLevel
};
try {
result = mjml(mjmlText, config);
} catch (err) {
req.log.error(err);
res.status(500).send({ message: "Failed to compile mjml", ...err });
next(err);
return;
}
const { html, errors } = result;
res.send({
html,
mjml: mjmlText,
mjml_version: options["mjml-version"],
errors
});
});
// Generic healthchecking endpoints
app.get(["/healthz", "/livez", "/readyz"], (_, res) => res.status(200).end());
return Object.assign(app, {
port: options.port,
host: options.host
});
} | function serverFactory (factoryOptions) {
const options = {
host: process.env.HOST || "0.0.0.0",
port: process.env.PORT || "80",
keepComments: Boolean(process.env.KEEP_COMMENTS) || true,
beautify: Boolean(process.env.BEAUTIFY) || false,
minify: Boolean(process.env.MINIFY) || false,
validationLevel: process.env.VALIDATION_LEVEL || "soft", // choices: "strict", "soft", "skip"
maxBody: process.env.MAX_BODY || "1mb",
"mjml-version": pkg.dependencies.mjml, // requires launching through either npm or yarn, but not directly node,
authentication: {
enabled: Boolean(process.env.AUTH_ENABLED) || false,
type: process.env.AUTH_TYPE === "token" ? "token" : process.env.AUTH_TYPE === "basic" ? "basic" : "none",
basicAuth: {
username: process.env.BASIC_AUTH_USERNAME,
password: process.env.BASIC_AUTH_PASSWORD
},
token: {
secret: process.env.AUTH_TOKEN
}
},
...factoryOptions
};
const app = express();
// Parse request body to a buffer, as it might contain JSON but doesn't have to
app.use(express.raw({
type: () => true,
limit: options.maxBody
}));
// minimal JSON logging middleware
app.use(pino);
logger.info({ config: options }, "Parsed configuration");
// main API endpoint for mjml renderer
app.post("/v1/render", authentication(options.authentication), (req, res, next) => {
let mjmlText;
// attempt to parse JSON off of body
try {
// req.body is a Buffer, see express.raw()
mjmlText = JSON.parse(req.body.toString()).mjml;
} catch (err) {
mjmlText = req.body.toString();
}
let result;
const config = {
keepComments: options.keepComments,
beautify: options.beautify, // TODO(fibis): no longer supported in mjml ^4.0.0, see deprectation notice
minify: options.minify, // TODO(fibis): no longer supported in mjml ^4.0.0, see deprectation notice
validationLevel: options.validationLevel
};
try {
result = mjml(mjmlText, config);
} catch (err) {
req.log.error(err);
res.status(500).send({ message: "Failed to compile mjml", ...err });
next(err);
return;
}
const { html, errors } = result;
res.send({
html,
mjml: mjmlText,
mjml_version: options["mjml-version"],
errors
});
});
// Generic healthchecking endpoints
app.get(["/healthz", "/livez", "/readyz"], (_, res) => res.status(200).end());
return Object.assign(app, {
port: options.port,
host: options.host
});
} |
JavaScript | function isInViewport(props) {
const { viewportRect, panelRect, actionRect } = props;
return ({ topOffset, leftOffset }) => {
const containerTop = actionRect.top + topOffset;
const containerLeft = actionRect.left + leftOffset;
const containerRight = containerLeft + panelRect.width;
const containerBottom = containerTop + panelRect.height;
const result =
containerLeft >= viewportRect.left &&
containerTop >= viewportRect.top &&
containerRight <= viewportRect.right &&
containerBottom <= viewportRect.bottom;
return result;
};
} | function isInViewport(props) {
const { viewportRect, panelRect, actionRect } = props;
return ({ topOffset, leftOffset }) => {
const containerTop = actionRect.top + topOffset;
const containerLeft = actionRect.left + leftOffset;
const containerRight = containerLeft + panelRect.width;
const containerBottom = containerTop + panelRect.height;
const result =
containerLeft >= viewportRect.left &&
containerTop >= viewportRect.top &&
containerRight <= viewportRect.right &&
containerBottom <= viewportRect.bottom;
return result;
};
} |
JavaScript | function renderOptions(props) {
const {
options = [],
getItemProps = itemProps => itemProps,
highlightedIndex,
selectedItem,
selectedItems = []
} = props;
const downshift = {
getItemProps,
highlightedIndex,
selectedItem,
selectedItems
};
const renderOption = createOptionRenderer(downshift);
return options.map(renderOption);
} | function renderOptions(props) {
const {
options = [],
getItemProps = itemProps => itemProps,
highlightedIndex,
selectedItem,
selectedItems = []
} = props;
const downshift = {
getItemProps,
highlightedIndex,
selectedItem,
selectedItems
};
const renderOption = createOptionRenderer(downshift);
return options.map(renderOption);
} |
JavaScript | function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier ||
expr.type === Syntax.MemberExpression ||
expr.type === Syntax.CallExpression ||
expr.type === Syntax.NewExpression;
} | function isLeftHandSide(expr) {
return expr.type === Syntax.Identifier ||
expr.type === Syntax.MemberExpression ||
expr.type === Syntax.CallExpression ||
expr.type === Syntax.NewExpression;
} |
JavaScript | function traceFunctionEntrance(traceName) {
return function (code) {
var tree,
functionList,
signature,
pos,
i;
tree = parse(code, { range: true });
functionList = [];
traverse(tree, function (node, path) {
var parent, name;
if (node.type === Syntax.FunctionDeclaration) {
functionList.push({
name: node.id.name,
range: node.range,
blockStart: node.body.range[0]
});
} else if (node.type === Syntax.FunctionExpression) {
parent = path[0];
if (parent.type === Syntax.AssignmentExpression) {
if (typeof parent.left.range !== 'undefined') {
functionList.push({
name: code.slice(parent.left.range[0],
parent.left.range[1] + 1),
range: node.range,
blockStart: node.body.range[0]
});
}
} else if (parent.type === Syntax.VariableDeclarator) {
functionList.push({
name: parent.id.name,
range: node.range,
blockStart: node.body.range[0]
});
} else if (parent.type === Syntax.CallExpression) {
functionList.push({
name: parent.id ? parent.id.name : '[Anonymous]',
range: node.range,
blockStart: node.body.range[0]
});
} else if (typeof parent.length === 'number') {
functionList.push({
name: parent.id ? parent.id.name : '[Anonymous]',
range: node.range,
blockStart: node.body.range[0]
});
} else if (typeof parent.key !== 'undefined') {
if (parent.key.type === 'Identifier') {
if (parent.value === node && parent.key.name) {
functionList.push({
name: parent.key.name,
range: node.range,
blockStart: node.body.range[0]
});
}
}
}
}
});
// Insert the instrumentation code from the last entry.
// This is to ensure that the range for each entry remains valid)
// (it won't shift due to some new inserting string before the range).
for (i = functionList.length - 1; i >= 0; i -= 1) {
signature = traceName + '(\'' + functionList[i].name + '\', ' +
'[' + functionList[i].range[0] + ', ' +
functionList[i].range[1] + ']);';
pos = functionList[i].blockStart + 1;
code = code.slice(0, pos) + '\n' + signature + code.slice(pos, code.length);
}
return code;
};
} | function traceFunctionEntrance(traceName) {
return function (code) {
var tree,
functionList,
signature,
pos,
i;
tree = parse(code, { range: true });
functionList = [];
traverse(tree, function (node, path) {
var parent, name;
if (node.type === Syntax.FunctionDeclaration) {
functionList.push({
name: node.id.name,
range: node.range,
blockStart: node.body.range[0]
});
} else if (node.type === Syntax.FunctionExpression) {
parent = path[0];
if (parent.type === Syntax.AssignmentExpression) {
if (typeof parent.left.range !== 'undefined') {
functionList.push({
name: code.slice(parent.left.range[0],
parent.left.range[1] + 1),
range: node.range,
blockStart: node.body.range[0]
});
}
} else if (parent.type === Syntax.VariableDeclarator) {
functionList.push({
name: parent.id.name,
range: node.range,
blockStart: node.body.range[0]
});
} else if (parent.type === Syntax.CallExpression) {
functionList.push({
name: parent.id ? parent.id.name : '[Anonymous]',
range: node.range,
blockStart: node.body.range[0]
});
} else if (typeof parent.length === 'number') {
functionList.push({
name: parent.id ? parent.id.name : '[Anonymous]',
range: node.range,
blockStart: node.body.range[0]
});
} else if (typeof parent.key !== 'undefined') {
if (parent.key.type === 'Identifier') {
if (parent.value === node && parent.key.name) {
functionList.push({
name: parent.key.name,
range: node.range,
blockStart: node.body.range[0]
});
}
}
}
}
});
// Insert the instrumentation code from the last entry.
// This is to ensure that the range for each entry remains valid)
// (it won't shift due to some new inserting string before the range).
for (i = functionList.length - 1; i >= 0; i -= 1) {
signature = traceName + '(\'' + functionList[i].name + '\', ' +
'[' + functionList[i].range[0] + ', ' +
functionList[i].range[1] + ']);';
pos = functionList[i].blockStart + 1;
code = code.slice(0, pos) + '\n' + signature + code.slice(pos, code.length);
}
return code;
};
} |
JavaScript | function addUser(projectId) {
const userName = document.getElementById("user-name").value
const userProjectList = document.getElementById("user-project-list")
const successElem = document.getElementById("add-user-success")
const errorElem = document.getElementById("add-user-error")
if(userName != ""){
httpRequest('PUT', `/projs/${projectId}/user/${userName}`, null, function(err, data) {
if(err) {
errorElem.innerText = err
successElem.setAttribute('hidden', 'true')
errorElem.removeAttribute('hidden')
} else {
successElem.innerText = data
successElem.removeAttribute('hidden')
errorElem.setAttribute('hidden', 'true')
userProjectList.innerHTML += '<li class="list-group-item">' + userName + '</li>'
}
})
}
} | function addUser(projectId) {
const userName = document.getElementById("user-name").value
const userProjectList = document.getElementById("user-project-list")
const successElem = document.getElementById("add-user-success")
const errorElem = document.getElementById("add-user-error")
if(userName != ""){
httpRequest('PUT', `/projs/${projectId}/user/${userName}`, null, function(err, data) {
if(err) {
errorElem.innerText = err
successElem.setAttribute('hidden', 'true')
errorElem.removeAttribute('hidden')
} else {
successElem.innerText = data
successElem.removeAttribute('hidden')
errorElem.setAttribute('hidden', 'true')
userProjectList.innerHTML += '<li class="list-group-item">' + userName + '</li>'
}
})
}
} |
JavaScript | function search(searchElemId, searchRelUrl, searchOutputElemId) {
const searchValue = document.getElementById(searchElemId).value
const outputElement = document.getElementById(searchOutputElemId)
httpRequest('GET', `/${searchRelUrl}?value=${searchValue}`, null, function(err, data) {
outputElement.innerHTML = data
})
} | function search(searchElemId, searchRelUrl, searchOutputElemId) {
const searchValue = document.getElementById(searchElemId).value
const outputElement = document.getElementById(searchOutputElemId)
httpRequest('GET', `/${searchRelUrl}?value=${searchValue}`, null, function(err, data) {
outputElement.innerHTML = data
})
} |
JavaScript | function ignoreVulnerability(projectId, vulnerabilityId) {
httpRequest('PUT', '/report/dependency/vulnerability/edit', JSON.stringify({projectId,vulnerabilityId}), function(err, data) {
const linkElement = document.getElementById(vulnerabilityId)
const buttonElement = document.getElementById(vulnerabilityId+'-btn')
if(linkElement.classList.contains('disabled-link')) {
linkElement.classList.remove('disabled-link')
buttonElement.classList.remove('btn-outline-success')
buttonElement.classList.add('btn-outline-danger')
buttonElement.innerText = 'Ignore vulnerability'
}
else {
linkElement.classList.add('disabled-link')
buttonElement.classList.remove('btn-outline-danger')
buttonElement.classList.add('btn-outline-success')
buttonElement.innerText = 'Consider vulnerability'
}
})
} | function ignoreVulnerability(projectId, vulnerabilityId) {
httpRequest('PUT', '/report/dependency/vulnerability/edit', JSON.stringify({projectId,vulnerabilityId}), function(err, data) {
const linkElement = document.getElementById(vulnerabilityId)
const buttonElement = document.getElementById(vulnerabilityId+'-btn')
if(linkElement.classList.contains('disabled-link')) {
linkElement.classList.remove('disabled-link')
buttonElement.classList.remove('btn-outline-success')
buttonElement.classList.add('btn-outline-danger')
buttonElement.innerText = 'Ignore vulnerability'
}
else {
linkElement.classList.add('disabled-link')
buttonElement.classList.remove('btn-outline-danger')
buttonElement.classList.add('btn-outline-success')
buttonElement.innerText = 'Consider vulnerability'
}
})
} |
JavaScript | function filterAffectedVersions(outputElemId, affectedVersions) {
const outputElem = document.getElementById(outputElemId)
if(affectedVersions.includes('&')) {
outputElem.innerHTML += '<li class="list-group-item">' + affectedVersions + '</li>'
} else {
const versions = affectedVersions.split(';')
versions.forEach(elem => outputElem.innerHTML += '<li class="list-group-item">' + elem + '</li>')
}
} | function filterAffectedVersions(outputElemId, affectedVersions) {
const outputElem = document.getElementById(outputElemId)
if(affectedVersions.includes('&')) {
outputElem.innerHTML += '<li class="list-group-item">' + affectedVersions + '</li>'
} else {
const versions = affectedVersions.split(';')
versions.forEach(elem => outputElem.innerHTML += '<li class="list-group-item">' + elem + '</li>')
}
} |
JavaScript | function _animateCells() {
_animateCells = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(inProgress, nodesToAnimate, startbtnText, algo) {
var count, cells, i, nodeCoordinates, x, y, num, cell, colorClass;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
count = 1;
(0, _timer.start)(startbtnText);
console.log("animation started");
inProgress = true;
toggleScreen(inProgress);
cells = document.getElementsByTagName("td");
i = 0;
case 7:
if (!(i < nodesToAnimate.length)) {
_context.next = 26;
break;
}
nodeCoordinates = nodesToAnimate[i][0];
x = nodeCoordinates.row;
y = nodeCoordinates.col;
num = x * _script.totalCols + y;
cell = cells[num];
colorClass = nodesToAnimate[i][1]; // success, visited or searching
// Wait until its time to animate
_context.next = 16;
return new Promise(function (resolve) {
return setTimeout(resolve, 5);
});
case 16:
if (!(cell.className == "start" || cell.className == "end")) {
_context.next = 21;
break;
}
if (cell.className == "end" && colorClass === "shortest") {
(0, _timer.start)(startbtnText);
console.log("End reached!");
}
return _context.abrupt("continue", 23);
case 21:
cell.className = colorClass;
case 22:
// Update count
if (colorClass == "shortest") {
count++;
countLength(count, algo);
}
case 23:
i++;
_context.next = 7;
break;
case 26:
nodesToAnimate = [];
inProgress = false;
toggleScreen(inProgress);
return _context.abrupt("return", new Promise(function (resolve) {
return resolve(true);
}));
case 30:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _animateCells.apply(this, arguments);
} | function _animateCells() {
_animateCells = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(inProgress, nodesToAnimate, startbtnText, algo) {
var count, cells, i, nodeCoordinates, x, y, num, cell, colorClass;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
count = 1;
(0, _timer.start)(startbtnText);
console.log("animation started");
inProgress = true;
toggleScreen(inProgress);
cells = document.getElementsByTagName("td");
i = 0;
case 7:
if (!(i < nodesToAnimate.length)) {
_context.next = 26;
break;
}
nodeCoordinates = nodesToAnimate[i][0];
x = nodeCoordinates.row;
y = nodeCoordinates.col;
num = x * _script.totalCols + y;
cell = cells[num];
colorClass = nodesToAnimate[i][1]; // success, visited or searching
// Wait until its time to animate
_context.next = 16;
return new Promise(function (resolve) {
return setTimeout(resolve, 5);
});
case 16:
if (!(cell.className == "start" || cell.className == "end")) {
_context.next = 21;
break;
}
if (cell.className == "end" && colorClass === "shortest") {
(0, _timer.start)(startbtnText);
console.log("End reached!");
}
return _context.abrupt("continue", 23);
case 21:
cell.className = colorClass;
case 22:
// Update count
if (colorClass == "shortest") {
count++;
countLength(count, algo);
}
case 23:
i++;
_context.next = 7;
break;
case 26:
nodesToAnimate = [];
inProgress = false;
toggleScreen(inProgress);
return _context.abrupt("return", new Promise(function (resolve) {
return resolve(true);
}));
case 30:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _animateCells.apply(this, arguments);
} |
JavaScript | function init(config) {
// TODO: Add support for other MSAL / B2C configuration
var msalConfig = {
auth: {
clientId: config.clientId,
authority: "https://login.microsoftonline.com/" + config.tenant,
redirectUri: config.redirectUri,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: false,
},
};
if (typeof config.scope === "string") {
tokenRequest.scopes = config.scope.split(" ");
} else {
tokenRequest.scopes = config.scope;
}
tokenRequest.prompt = config.prompt;
myMSALObj = new msal.PublicClientApplication(msalConfig);
} | function init(config) {
// TODO: Add support for other MSAL / B2C configuration
var msalConfig = {
auth: {
clientId: config.clientId,
authority: "https://login.microsoftonline.com/" + config.tenant,
redirectUri: config.redirectUri,
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: false,
},
};
if (typeof config.scope === "string") {
tokenRequest.scopes = config.scope.split(" ");
} else {
tokenRequest.scopes = config.scope;
}
tokenRequest.prompt = config.prompt;
myMSALObj = new msal.PublicClientApplication(msalConfig);
} |
JavaScript | async function login(refreshIfAvailable, onSuccess, onError) {
// Try to sign in silently
const account = getAccount();
if (account !== null) {
try {
// Silent acquisition only works if we the access token is either
// within its lifetime, or the refresh token can successfully be
// used to refresh it. This will throw if the access token can't
// be acquired.
const silentAuthResult = await myMSALObj.acquireTokenSilent({
scopes: tokenRequest.scopes,
prompt: "none",
account: account
});
authResult = silentAuthResult;
// Skip interactive login
onSuccess();
return;
} catch (error) {
console.log(error.message)
}
}
// Sign in with popup
try {
const interactiveAuthResult = await myMSALObj.loginPopup({
scopes: tokenRequest.scopes,
prompt: tokenRequest.prompt,
account: account
});
authResult = interactiveAuthResult;
onSuccess();
} catch (error) {
// rethrow
console.warn(error.message);
onError(error);
}
} | async function login(refreshIfAvailable, onSuccess, onError) {
// Try to sign in silently
const account = getAccount();
if (account !== null) {
try {
// Silent acquisition only works if we the access token is either
// within its lifetime, or the refresh token can successfully be
// used to refresh it. This will throw if the access token can't
// be acquired.
const silentAuthResult = await myMSALObj.acquireTokenSilent({
scopes: tokenRequest.scopes,
prompt: "none",
account: account
});
authResult = silentAuthResult;
// Skip interactive login
onSuccess();
return;
} catch (error) {
console.log(error.message)
}
}
// Sign in with popup
try {
const interactiveAuthResult = await myMSALObj.loginPopup({
scopes: tokenRequest.scopes,
prompt: tokenRequest.prompt,
account: account
});
authResult = interactiveAuthResult;
onSuccess();
} catch (error) {
// rethrow
console.warn(error.message);
onError(error);
}
} |
JavaScript | function GamesList() {
return (
<div className='cards'>
<h1>Les jeux</h1>
<div className='cards_container'>
<div className='cards_wrapper'>
<GameItem
src='images/lol-cover.jpg'
text='League of Legends'
label='MOBA'
path='/game/league-of-legends'
gridPlace="one"
/>
<GameItem
src='images/rocket-league-cover.jpg'
text='Rocket League'
label='Sport'
path='/game/rocket-league'
gridPlace="two"
/>
<GameItem
src='images/csgo-cover.jpg'
text='CS:GO'
label='Tir'
path='/game/cs-go'
gridPlace="three"
/>
<GameItem
src='images/valorant-cover.png'
text='Valorant'
label='Tir'
path='/game/valorant'
gridPlace=""
/>
<GameItem
src='images/hots-cover.jpg'
text='Heroes of the Storm'
label='MOBA'
path='/game/heroes-of-the-storm'
/>
<GameItem
src='images/haxball-cover.png'
text='Haxball'
label='Sport'
path='/game/haxball'
/>
<GameItem
src='images/slapshot-cover.jpg'
text='Slapshot'
label='Sport'
path='/game/slapshot'
/>
<GameItem
src='images/chess-cover.png'
text='Echecs'
label='Stratégie'
path='/game/chess'
gridPlace=""
/>
<GameItem
src='images/battlerite-cover.jpg'
text='Battlerite'
label='Arène'
path='/game/battlerite'
gridPlace=""
/>
<GameItem
src='images/slappyball-cover.jpg'
text='Slappyball'
label='Sport'
path='/game/slappyball'
gridPlace="two"
/>
</div>
</div>
</div>
);
} | function GamesList() {
return (
<div className='cards'>
<h1>Les jeux</h1>
<div className='cards_container'>
<div className='cards_wrapper'>
<GameItem
src='images/lol-cover.jpg'
text='League of Legends'
label='MOBA'
path='/game/league-of-legends'
gridPlace="one"
/>
<GameItem
src='images/rocket-league-cover.jpg'
text='Rocket League'
label='Sport'
path='/game/rocket-league'
gridPlace="two"
/>
<GameItem
src='images/csgo-cover.jpg'
text='CS:GO'
label='Tir'
path='/game/cs-go'
gridPlace="three"
/>
<GameItem
src='images/valorant-cover.png'
text='Valorant'
label='Tir'
path='/game/valorant'
gridPlace=""
/>
<GameItem
src='images/hots-cover.jpg'
text='Heroes of the Storm'
label='MOBA'
path='/game/heroes-of-the-storm'
/>
<GameItem
src='images/haxball-cover.png'
text='Haxball'
label='Sport'
path='/game/haxball'
/>
<GameItem
src='images/slapshot-cover.jpg'
text='Slapshot'
label='Sport'
path='/game/slapshot'
/>
<GameItem
src='images/chess-cover.png'
text='Echecs'
label='Stratégie'
path='/game/chess'
gridPlace=""
/>
<GameItem
src='images/battlerite-cover.jpg'
text='Battlerite'
label='Arène'
path='/game/battlerite'
gridPlace=""
/>
<GameItem
src='images/slappyball-cover.jpg'
text='Slappyball'
label='Sport'
path='/game/slappyball'
gridPlace="two"
/>
</div>
</div>
</div>
);
} |
JavaScript | function initDatabase() {
sqlInstance = (_databaseInstance) ?
$injector.invoke(_databaseInstance) :
$window.openDatabase(_databaseName, '1.0', 'database', 200000);
return sqlInstance;
} | function initDatabase() {
sqlInstance = (_databaseInstance) ?
$injector.invoke(_databaseInstance) :
$window.openDatabase(_databaseName, '1.0', 'database', 200000);
return sqlInstance;
} |
JavaScript | function initTables() {
var _this = this;
var tables = this.tables;
if(this.createPromise) { return this.createPromise; }
this.createPromise = this.createTables(_databaseSchema.defaultFields, tables)
.then(createSucceed);
return this.createPromise;
function createSucceed() {
var database = _this.getDatabase();
var currentVersion = localStorageService.get(DATABASE_VERSION_KEY) || 0;
$log.debug('[Storage] Create DB SUCCESS');
return (currentVersion && currentVersion < _databaseVersion) ?
sqlStorageMigrationService.updateManager(database, currentVersion)
.then(function() { return database; })
.catch(function (err) {
$log.error(err);
return database;
}) :
saveDatabaseVersion();
function saveDatabaseVersion() {
localStorageService.set(DATABASE_VERSION_KEY, _databaseVersion);
return database;
}
}
} | function initTables() {
var _this = this;
var tables = this.tables;
if(this.createPromise) { return this.createPromise; }
this.createPromise = this.createTables(_databaseSchema.defaultFields, tables)
.then(createSucceed);
return this.createPromise;
function createSucceed() {
var database = _this.getDatabase();
var currentVersion = localStorageService.get(DATABASE_VERSION_KEY) || 0;
$log.debug('[Storage] Create DB SUCCESS');
return (currentVersion && currentVersion < _databaseVersion) ?
sqlStorageMigrationService.updateManager(database, currentVersion)
.then(function() { return database; })
.catch(function (err) {
$log.error(err);
return database;
}) :
saveDatabaseVersion();
function saveDatabaseVersion() {
localStorageService.set(DATABASE_VERSION_KEY, _databaseVersion);
return database;
}
}
} |
JavaScript | function deleteDatas() {
var _this = this;
var tablesName = Object.keys(this.tables).map(function(tableKey) {
return _this.tables[tableKey].table_name;
});
// Databases
var queries = tablesName.map(function(tableName) {
var request = 'DROP TABLE IF EXISTS ' + tableName;
return _this.execute(request);
});
// Local Storage
localStorageService.clearAll();
return $q.all(queries).then(function(data) {
_this.createPromise = null;
$log.debug('[Storage] Drop DB SUCCESS');
return data;
});
} | function deleteDatas() {
var _this = this;
var tablesName = Object.keys(this.tables).map(function(tableKey) {
return _this.tables[tableKey].table_name;
});
// Databases
var queries = tablesName.map(function(tableName) {
var request = 'DROP TABLE IF EXISTS ' + tableName;
return _this.execute(request);
});
// Local Storage
localStorageService.clearAll();
return $q.all(queries).then(function(data) {
_this.createPromise = null;
$log.debug('[Storage] Drop DB SUCCESS');
return data;
});
} |
JavaScript | function install(Vue, { useAllComponents }) {
if (installed) {
console.warn('Not installed again: The library is already installed.')
return
}
installed = true
if (!useAllComponents) return
installComponents(Vue, components, {})
} | function install(Vue, { useAllComponents }) {
if (installed) {
console.warn('Not installed again: The library is already installed.')
return
}
installed = true
if (!useAllComponents) return
installComponents(Vue, components, {})
} |
JavaScript | function TriggerAdapter(trigger, rfs) {
var onRotate = function (triggerinfo) {
rfs.rotate(triggerinfo);
};
var onNewFile = function (data) {
trigger.newFile(data);
};
var onLogWrite = function (data) {
trigger.logWrite(data);
};
var onShutdown = function () {
trigger.shutdown();
trigger.removeListener('rotate', onRotate);
rfs.removeListener('newfile', onNewFile);
rfs.removeListener('logwrite', onLogWrite);
rfs.removeListener('shutdown', onShutdown);
}
trigger.on('rotate', onRotate);
rfs.on('newfile', onNewFile);
rfs.on('logwrite', onLogWrite);
rfs.on('shutdown', onShutdown);
return { onShutdown: onShutdown };
} | function TriggerAdapter(trigger, rfs) {
var onRotate = function (triggerinfo) {
rfs.rotate(triggerinfo);
};
var onNewFile = function (data) {
trigger.newFile(data);
};
var onLogWrite = function (data) {
trigger.logWrite(data);
};
var onShutdown = function () {
trigger.shutdown();
trigger.removeListener('rotate', onRotate);
rfs.removeListener('newfile', onNewFile);
rfs.removeListener('logwrite', onLogWrite);
rfs.removeListener('shutdown', onShutdown);
}
trigger.on('rotate', onRotate);
rfs.on('newfile', onNewFile);
rfs.on('logwrite', onLogWrite);
rfs.on('shutdown', onShutdown);
return { onShutdown: onShutdown };
} |
JavaScript | function InnerAuthProvider(props) {
const {
loginWithRedirect,
isAuthenticated: isAuthenticatedAuth0,
error: auth0Error,
isLoading,
getAccessTokenSilently,
logout: logoutAuth0,
} = useAuth0();
const [authState, dispatchAuthState] = useReducer(authReducer, initialState);
const fetchToken = async () => {
try {
dispatchAuthState({
type: actions.REQUEST_LOGIN,
});
const token = await getAccessTokenSilently({
audience: config.restApiEndpoint,
});
const restApiClient = new RestApiClient({ apiToken: token });
const userDetails = await restApiClient.getUserDetails();
dispatchAuthState({
type: actions.RECEIVE_LOGIN,
data: {
user: userDetails,
apiToken: token,
userAccessLevel: userDetails.access,
},
});
} catch (error) {
logger(error);
dispatchAuthState({
type: actions.RESET_LOGIN,
});
}
};
/**
* Disable Auth0 hooks when testing.
*/
if (!window.Cypress) {
/* eslint-disable react-hooks/rules-of-hooks */
useEffect(() => {
if (isLoading) return;
if (!isAuthenticatedAuth0) {
dispatchAuthState({ type: actions.RESET_LOGIN });
} else {
fetchToken();
}
}, [isLoading, isAuthenticatedAuth0, auth0Error]); // eslint-disable-line react-hooks/exhaustive-deps
} else {
useEffect(() => {
const localStorageAuthState = getLocalStorageItem('authState', 'json');
dispatchAuthState({
type: actions.LOAD_AUTH_STATE,
data: {
...initialState,
...localStorageAuthState,
isLoading: false,
},
});
return;
}, []);
}
// Remove welcome banner after auth is resolved
useEffect(() => {
if (authState.isLoading) return;
const banner = document.querySelector('#welcome-banner');
banner.classList.add('dismissed');
}, [authState?.isLoading]);
const value = {
...authState,
login: () => loginWithRedirect(),
logout: () => {
dispatchAuthState({
type: actions.RESET_LOGIN,
data: {
isLoggingOut: true,
},
});
logoutAuth0({
returnTo: window.location.origin,
});
},
};
return (
<AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>
);
} | function InnerAuthProvider(props) {
const {
loginWithRedirect,
isAuthenticated: isAuthenticatedAuth0,
error: auth0Error,
isLoading,
getAccessTokenSilently,
logout: logoutAuth0,
} = useAuth0();
const [authState, dispatchAuthState] = useReducer(authReducer, initialState);
const fetchToken = async () => {
try {
dispatchAuthState({
type: actions.REQUEST_LOGIN,
});
const token = await getAccessTokenSilently({
audience: config.restApiEndpoint,
});
const restApiClient = new RestApiClient({ apiToken: token });
const userDetails = await restApiClient.getUserDetails();
dispatchAuthState({
type: actions.RECEIVE_LOGIN,
data: {
user: userDetails,
apiToken: token,
userAccessLevel: userDetails.access,
},
});
} catch (error) {
logger(error);
dispatchAuthState({
type: actions.RESET_LOGIN,
});
}
};
/**
* Disable Auth0 hooks when testing.
*/
if (!window.Cypress) {
/* eslint-disable react-hooks/rules-of-hooks */
useEffect(() => {
if (isLoading) return;
if (!isAuthenticatedAuth0) {
dispatchAuthState({ type: actions.RESET_LOGIN });
} else {
fetchToken();
}
}, [isLoading, isAuthenticatedAuth0, auth0Error]); // eslint-disable-line react-hooks/exhaustive-deps
} else {
useEffect(() => {
const localStorageAuthState = getLocalStorageItem('authState', 'json');
dispatchAuthState({
type: actions.LOAD_AUTH_STATE,
data: {
...initialState,
...localStorageAuthState,
isLoading: false,
},
});
return;
}, []);
}
// Remove welcome banner after auth is resolved
useEffect(() => {
if (authState.isLoading) return;
const banner = document.querySelector('#welcome-banner');
banner.classList.add('dismissed');
}, [authState?.isLoading]);
const value = {
...authState,
login: () => loginWithRedirect(),
logout: () => {
dispatchAuthState({
type: actions.RESET_LOGIN,
data: {
isLoggingOut: true,
},
});
logoutAuth0({
returnTo: window.location.origin,
});
},
};
return (
<AuthContext.Provider value={value}>{props.children}</AuthContext.Provider>
);
} |
JavaScript | function withAuthenticationRequired(WrapperComponent, access) {
/* eslint-disable react-hooks/rules-of-hooks */
const {
isAuthenticated,
userAccessLevel,
isLoading,
isLoggingOut,
} = useAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated && !isLoggingOut) {
toasts.error('Please sign in to view this page.');
history.push('/');
} else if (isAuthenticated && access && access !== userAccessLevel) {
toasts.error('You do not have permission to view this page.');
history.push('/');
}
}, [isLoading, isAuthenticated, isLoggingOut, access, userAccessLevel]);
if (isLoading || !isAuthenticated || isLoggingOut) return;
return WrapperComponent;
/* eslint-enable react-hooks/rules-of-hooks */
} | function withAuthenticationRequired(WrapperComponent, access) {
/* eslint-disable react-hooks/rules-of-hooks */
const {
isAuthenticated,
userAccessLevel,
isLoading,
isLoggingOut,
} = useAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated && !isLoggingOut) {
toasts.error('Please sign in to view this page.');
history.push('/');
} else if (isAuthenticated && access && access !== userAccessLevel) {
toasts.error('You do not have permission to view this page.');
history.push('/');
}
}, [isLoading, isAuthenticated, isLoggingOut, access, userAccessLevel]);
if (isLoading || !isAuthenticated || isLoggingOut) return;
return WrapperComponent;
/* eslint-enable react-hooks/rules-of-hooks */
} |
JavaScript | initialize(bounds) {
this._shape = L.rectangle(bounds, { interactive: false }).addTo(this._map);
this._shape.setStyle({ fillOpacity: 0 });
this.onInitialize(this.getBbox(), this._shape);
} | initialize(bounds) {
this._shape = L.rectangle(bounds, { interactive: false }).addTo(this._map);
this._shape.setStyle({ fillOpacity: 0 });
this.onInitialize(this.getBbox(), this._shape);
} |
JavaScript | function onMouseUp() {
// Turn off the mousemove handler in all cases
// on the mouseUp action
this._shape.setStyle({ fillOpacity: 0 });
this._map.off('mousemove', onMouseMove, this);
// We need to enable dragging to get the
// cursor to remain consistent
this._map.dragging.enable();
// User has done a mouseUp action without actually drawing a bbox,
// In this case, we re-enable the mouseDown event to let the user
// draw again, keeping the user in AOI-drawing mode
if (!this._shape) {
this._map.on('mousedown', this._onMouseDown, this);
return;
}
this._map.off('mouseup', onMouseUp, this);
this.onDrawEnd(this.getBbox(), this._shape);
} | function onMouseUp() {
// Turn off the mousemove handler in all cases
// on the mouseUp action
this._shape.setStyle({ fillOpacity: 0 });
this._map.off('mousemove', onMouseMove, this);
// We need to enable dragging to get the
// cursor to remain consistent
this._map.dragging.enable();
// User has done a mouseUp action without actually drawing a bbox,
// In this case, we re-enable the mouseDown event to let the user
// draw again, keeping the user in AOI-drawing mode
if (!this._shape) {
this._map.on('mousedown', this._onMouseDown, this);
return;
}
this._map.off('mouseup', onMouseUp, this);
this.onDrawEnd(this.getBbox(), this._shape);
} |
JavaScript | function Table({ headers, data, renderRow, extraData, hoverable }) {
return (
<StyledTable hoverable={hoverable}>
<TableHeader>
<TableRow>
{headers.map((header) => (
<Subheading key={header} as='th'>
{header}
</Subheading>
))}
</TableRow>
</TableHeader>
<TableBody>{data.map((d, i) => renderRow(d, extraData, i))}</TableBody>
</StyledTable>
);
} | function Table({ headers, data, renderRow, extraData, hoverable }) {
return (
<StyledTable hoverable={hoverable}>
<TableHeader>
<TableRow>
{headers.map((header) => (
<Subheading key={header} as='th'>
{header}
</Subheading>
))}
</TableRow>
</TableHeader>
<TableBody>{data.map((d, i) => renderRow(d, extraData, i))}</TableBody>
</StyledTable>
);
} |
JavaScript | function FormGroupStructure(props) {
const {
id,
label,
labelHint,
className,
toolbarItems,
description,
helper,
children,
footerContent,
hint,
hideHeader,
} = props;
const hasToolbar = description || toolbarItems;
const descComp = description && (
<InfoButton
key={`info-button-${id}`}
id={`info-button-${id}`}
info={description}
useIcon='circle-information'
hideText
/>
);
// Because of a @devseed-ui/toolbar bug, there can't be null/undefined
// children on the toolbar.
const toolbar = (
<Toolbar size='small'>{[toolbarItems, descComp].filter(Boolean)}</Toolbar>
);
return (
<FormGroup className={className}>
<FormGroupHeader isHidden={hideHeader}>
<FormLabel htmlFor={id} optional={labelHint}>
{label}
</FormLabel>
{hasToolbar && toolbar}
</FormGroupHeader>
<FormGroupBody>
{children}
{(helper || hint) && <FormHelper>{helper || hint}</FormHelper>}
</FormGroupBody>
{footerContent && <FormGroupFooter>{footerContent}</FormGroupFooter>}
</FormGroup>
);
} | function FormGroupStructure(props) {
const {
id,
label,
labelHint,
className,
toolbarItems,
description,
helper,
children,
footerContent,
hint,
hideHeader,
} = props;
const hasToolbar = description || toolbarItems;
const descComp = description && (
<InfoButton
key={`info-button-${id}`}
id={`info-button-${id}`}
info={description}
useIcon='circle-information'
hideText
/>
);
// Because of a @devseed-ui/toolbar bug, there can't be null/undefined
// children on the toolbar.
const toolbar = (
<Toolbar size='small'>{[toolbarItems, descComp].filter(Boolean)}</Toolbar>
);
return (
<FormGroup className={className}>
<FormGroupHeader isHidden={hideHeader}>
<FormLabel htmlFor={id} optional={labelHint}>
{label}
</FormLabel>
{hasToolbar && toolbar}
</FormGroupHeader>
<FormGroupBody>
{children}
{(helper || hint) && <FormHelper>{helper || hint}</FormHelper>}
</FormGroupBody>
{footerContent && <FormGroupFooter>{footerContent}</FormGroupFooter>}
</FormGroup>
);
} |
JavaScript | function createNewAoi() {
dispatchMapState({
type: mapActionTypes.SET_MODE,
data: mapModes.CREATE_AOI_MODE,
});
setAoiRef(null);
setAoiBounds(null);
setAoiArea(null);
setAoiName(null);
setCurrentAoi(null);
//clear inference tiles
dispatchPredictions({
type: predictionActions.CLEAR_PREDICTION,
});
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RUN,
},
});
dispatchCurrentCheckpoint({
type: checkpointActions.CLEAR_SAMPLES,
});
} | function createNewAoi() {
dispatchMapState({
type: mapActionTypes.SET_MODE,
data: mapModes.CREATE_AOI_MODE,
});
setAoiRef(null);
setAoiBounds(null);
setAoiArea(null);
setAoiName(null);
setCurrentAoi(null);
//clear inference tiles
dispatchPredictions({
type: predictionActions.CLEAR_PREDICTION,
});
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RUN,
},
});
dispatchCurrentCheckpoint({
type: checkpointActions.CLEAR_SAMPLES,
});
} |
JavaScript | async function loadAoi(
project,
aoiObject,
aoiMatchesCheckpoint,
noLoadOnInst
) {
if (!aoiObject) {
return;
}
showGlobalLoadingMessage('Loading AOI');
const aoi = await restApiClient.get(
`project/${project.id}/aoi/${aoiObject.id}`
);
const [lonMin, latMin, lonMax, latMax] = tBbox(aoi.bounds);
const bounds = [
[latMin, lonMin],
[latMax, lonMax],
];
let area;
if (aoiRef) {
// Load existing AOI that was returned by the api
aoiRef.setBounds(bounds);
setAoiBounds(aoiRef.getBounds());
setAoiName(aoiObject.name);
if (predictions.isReady) {
dispatchPredictions({ type: predictionActions.CLEAR_PREDICTION });
}
} else {
// initializing map with first AOI
setAoiInitializer(bounds);
setAoiName(aoiObject.name);
}
area = areaFromBounds(tBbox(aoi.bounds));
setAoiArea(area);
if (!aoiMatchesCheckpoint) {
toasts.error(
'Tiles do not exist for this AOI and this checkpoint. Treating as geometry only'
);
setAoiName(aoiObject.name);
if (currentCheckpoint) {
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RUN,
},
});
setSessionStatusMode(sessionModes.PREDICTION_READY);
}
setCurrentAoi(null);
hideGlobalLoading();
} else {
setCurrentAoi(aoi);
// Only load AOI on instance if storage is true
if (currentInstance && !noLoadOnInst && aoiObject.storage) {
loadAoiOnInstance(aoi.id);
} else {
hideGlobalLoading();
}
if (currentCheckpoint) {
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RETRAIN,
},
});
dispatchCurrentCheckpoint({
type: checkpointActions.CLEAR_SAMPLES,
});
dispatchMapState({
type: mapActionTypes.SET_MODE,
data: mapModes.ADD_CLASS_SAMPLES,
});
}
}
dispatchCurrentCheckpoint({
type: checkpointActions.SET_AOI_CHECKED,
data: {
checkAoi: false,
},
});
return bounds;
} | async function loadAoi(
project,
aoiObject,
aoiMatchesCheckpoint,
noLoadOnInst
) {
if (!aoiObject) {
return;
}
showGlobalLoadingMessage('Loading AOI');
const aoi = await restApiClient.get(
`project/${project.id}/aoi/${aoiObject.id}`
);
const [lonMin, latMin, lonMax, latMax] = tBbox(aoi.bounds);
const bounds = [
[latMin, lonMin],
[latMax, lonMax],
];
let area;
if (aoiRef) {
// Load existing AOI that was returned by the api
aoiRef.setBounds(bounds);
setAoiBounds(aoiRef.getBounds());
setAoiName(aoiObject.name);
if (predictions.isReady) {
dispatchPredictions({ type: predictionActions.CLEAR_PREDICTION });
}
} else {
// initializing map with first AOI
setAoiInitializer(bounds);
setAoiName(aoiObject.name);
}
area = areaFromBounds(tBbox(aoi.bounds));
setAoiArea(area);
if (!aoiMatchesCheckpoint) {
toasts.error(
'Tiles do not exist for this AOI and this checkpoint. Treating as geometry only'
);
setAoiName(aoiObject.name);
if (currentCheckpoint) {
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RUN,
},
});
setSessionStatusMode(sessionModes.PREDICTION_READY);
}
setCurrentAoi(null);
hideGlobalLoading();
} else {
setCurrentAoi(aoi);
// Only load AOI on instance if storage is true
if (currentInstance && !noLoadOnInst && aoiObject.storage) {
loadAoiOnInstance(aoi.id);
} else {
hideGlobalLoading();
}
if (currentCheckpoint) {
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RETRAIN,
},
});
dispatchCurrentCheckpoint({
type: checkpointActions.CLEAR_SAMPLES,
});
dispatchMapState({
type: mapActionTypes.SET_MODE,
data: mapModes.ADD_CLASS_SAMPLES,
});
}
}
dispatchCurrentCheckpoint({
type: checkpointActions.SET_AOI_CHECKED,
data: {
checkAoi: false,
},
});
return bounds;
} |
JavaScript | function bboxIntersectsMapBounds(bbox, mapBounds) {
if (mapBounds) {
const mapBoundsPolygon = tBboxPolygon(
mapBounds
.toBBoxString()
.split(',')
.map((i) => Number(i))
);
return booleanIntersects(tBboxPolygon(bbox), mapBoundsPolygon);
}
return false;
} | function bboxIntersectsMapBounds(bbox, mapBounds) {
if (mapBounds) {
const mapBoundsPolygon = tBboxPolygon(
mapBounds
.toBBoxString()
.split(',')
.map((i) => Number(i))
);
return booleanIntersects(tBboxPolygon(bbox), mapBoundsPolygon);
}
return false;
} |
JavaScript | function filterComponentProps(Comp, filterProps = []) {
const isValidProp = (p) => !filterProps.includes(p);
return React.forwardRef((rawProps, ref) => {
const props = Object.keys(rawProps).reduce(
(acc, p) => (isValidProp(p) ? { ...acc, [p]: rawProps[p] } : acc),
{}
);
return <Comp ref={ref} {...props} />;
});
} | function filterComponentProps(Comp, filterProps = []) {
const isValidProp = (p) => !filterProps.includes(p);
return React.forwardRef((rawProps, ref) => {
const props = Object.keys(rawProps).reduce(
(acc, p) => (isValidProp(p) ? { ...acc, [p]: rawProps[p] } : acc),
{}
);
return <Comp ref={ref} {...props} />;
});
} |
JavaScript | async function fetchCheckpoint(projectId, checkpointId, mode, noCheck) {
try {
const checkpoint = await restApiClient.getCheckpoint(
projectId,
checkpointId
);
let _data = {};
if (mode) {
// Function is used from applyCheckpoint context
_data.mode =
mode || (currentCheckpoint && currentCheckpoint.mode) || null;
} else {
_data.analytics = null;
}
_data.checkAoi = noCheck ? false : true;
dispatchCurrentCheckpoint({
type: actions.RECEIVE_CHECKPOINT,
data: {
...checkpoint,
..._data,
},
});
} catch (error) {
logger(error);
toasts.error('Could not fetch checkpoint.');
}
} | async function fetchCheckpoint(projectId, checkpointId, mode, noCheck) {
try {
const checkpoint = await restApiClient.getCheckpoint(
projectId,
checkpointId
);
let _data = {};
if (mode) {
// Function is used from applyCheckpoint context
_data.mode =
mode || (currentCheckpoint && currentCheckpoint.mode) || null;
} else {
_data.analytics = null;
}
_data.checkAoi = noCheck ? false : true;
dispatchCurrentCheckpoint({
type: actions.RECEIVE_CHECKPOINT,
data: {
...checkpoint,
..._data,
},
});
} catch (error) {
logger(error);
toasts.error('Could not fetch checkpoint.');
}
} |
JavaScript | function GlobalLoadingProvider(props) {
[glState, setGlState] = useState(initialState);
const { revealed, message } = glState;
// Update the store min time.
MIN_TIME = props.minTime || MIN_TIME;
// Will be called on initial mount.
// Reset variables when this is mounted.
useEffect(() => {
globalLoadingMounted = true;
globalLoadingCount = 0;
return () => {
globalLoadingMounted = false;
};
}, []);
// Note:
// This check is necessary for this component to work when used with SSR.
// While react-portal will itself check if window is available, that is not
// enough to ensure that there aren't discrepancies between what the server
// renders and what the client renders, as the client *will* have access to
// the window. Therefore, we should only render the root level portal element
// once the component has actually mounted, as determined by a state variable.
if (!globalLoadingMounted) {
return null;
}
return createPortal(
<CSSTransition
in={revealed}
unmountOnExit
appear
classNames='overlay-loader'
timeout={{ enter: 300, exit: 300 }}
>
<GlobalLoadingWrapper
data-cy='global-loading'
className={props.className}
data-testid='global-loading'
>
<BodyUnscrollable />
<Spinner />
{message && <Message>{message}</Message>}
</GlobalLoadingWrapper>
</CSSTransition>,
document.body
);
} | function GlobalLoadingProvider(props) {
[glState, setGlState] = useState(initialState);
const { revealed, message } = glState;
// Update the store min time.
MIN_TIME = props.minTime || MIN_TIME;
// Will be called on initial mount.
// Reset variables when this is mounted.
useEffect(() => {
globalLoadingMounted = true;
globalLoadingCount = 0;
return () => {
globalLoadingMounted = false;
};
}, []);
// Note:
// This check is necessary for this component to work when used with SSR.
// While react-portal will itself check if window is available, that is not
// enough to ensure that there aren't discrepancies between what the server
// renders and what the client renders, as the client *will* have access to
// the window. Therefore, we should only render the root level portal element
// once the component has actually mounted, as determined by a state variable.
if (!globalLoadingMounted) {
return null;
}
return createPortal(
<CSSTransition
in={revealed}
unmountOnExit
appear
classNames='overlay-loader'
timeout={{ enter: 300, exit: 300 }}
>
<GlobalLoadingWrapper
data-cy='global-loading'
className={props.className}
data-testid='global-loading'
>
<BodyUnscrollable />
<Spinner />
{message && <Message>{message}</Message>}
</GlobalLoadingWrapper>
</CSSTransition>,
document.body
);
} |
JavaScript | function showGlobalLoading(options = {}) {
return new Promise((resolve) => {
const { count = 1, force, message = null } = options;
if (!globalLoadingMounted) {
throw new Error('<GlobalLoadingProvider /> component not mounted');
}
if (hideTimeout) {
clearTimeout(hideTimeout);
}
globalLoadingCount = force ? count : globalLoadingCount + count;
setGlState({
showTimestamp: Date.now(),
message,
revealed: true,
});
resolve();
});
} | function showGlobalLoading(options = {}) {
return new Promise((resolve) => {
const { count = 1, force, message = null } = options;
if (!globalLoadingMounted) {
throw new Error('<GlobalLoadingProvider /> component not mounted');
}
if (hideTimeout) {
clearTimeout(hideTimeout);
}
globalLoadingCount = force ? count : globalLoadingCount + count;
setGlState({
showTimestamp: Date.now(),
message,
revealed: true,
});
resolve();
});
} |
JavaScript | function hideGlobalLoading(options = {}) {
return new Promise((resolve) => {
const { count = 1, force } = options;
if (globalLoadingMounted === null) {
throw new Error('<GlobalLoading /> component not mounted');
}
const hide = () => {
setGlState({
...glState,
revealed: false,
});
resolve();
};
// Using 0 or negative numbers results in the loading being
// immediately dismissed.
if (count < 1) {
globalLoadingCount = 0;
return hide();
}
// Decrement counter by given amount without going below 0.
globalLoadingCount = Math.max(
0,
force ? count : globalLoadingCount - count
);
const time = glState.showTimestamp;
const diff = Date.now() - time;
if (diff >= MIN_TIME) {
if (globalLoadingCount === 0) return hide();
} else {
hideTimeout = setTimeout(() => {
if (globalLoadingCount === 0) return hide();
}, MIN_TIME - diff);
}
});
} | function hideGlobalLoading(options = {}) {
return new Promise((resolve) => {
const { count = 1, force } = options;
if (globalLoadingMounted === null) {
throw new Error('<GlobalLoading /> component not mounted');
}
const hide = () => {
setGlState({
...glState,
revealed: false,
});
resolve();
};
// Using 0 or negative numbers results in the loading being
// immediately dismissed.
if (count < 1) {
globalLoadingCount = 0;
return hide();
}
// Decrement counter by given amount without going below 0.
globalLoadingCount = Math.max(
0,
force ? count : globalLoadingCount - count
);
const time = glState.showTimestamp;
const diff = Date.now() - time;
if (diff >= MIN_TIME) {
if (globalLoadingCount === 0) return hide();
} else {
hideTimeout = setTimeout(() => {
if (globalLoadingCount === 0) return hide();
}, MIN_TIME - diff);
}
});
} |
JavaScript | function showGlobalLoadingMessage(message) {
return showGlobalLoading({
count: 1,
force: true,
message,
});
} | function showGlobalLoadingMessage(message) {
return showGlobalLoading({
count: 1,
force: true,
message,
});
} |
JavaScript | function GlobalLoading(props) {
useEffect(() => {
if (props.children) {
showGlobalLoadingMessage(props.children);
} else {
showGlobalLoading();
}
return () => {
hideGlobalLoading();
};
// The updating because of changing children is happening below.
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, []);
useEffect(() => {
if (props.children) {
showGlobalLoadingMessage(props.children);
}
}, [props.children]);
return null;
} | function GlobalLoading(props) {
useEffect(() => {
if (props.children) {
showGlobalLoadingMessage(props.children);
} else {
showGlobalLoading();
}
return () => {
hideGlobalLoading();
};
// The updating because of changing children is happening below.
/* eslint-disable-next-line react-hooks/exhaustive-deps */
}, []);
useEffect(() => {
if (props.children) {
showGlobalLoadingMessage(props.children);
}
}, [props.children]);
return null;
} |
JavaScript | function FormikInputSelect({
className,
description,
helper,
id,
inputSize,
inputVariation,
label,
labelHint,
name,
onBlur,
onChange,
options,
value,
disabled,
}) {
return (
<Field name={name}>
{({ field, meta }) => {
return (
<InputSelect
disabled={disabled}
id={id}
label={label}
labelHint={labelHint}
className={className}
inputSize={inputSize}
inputVariation={inputVariation}
description={description}
helper={
meta.touched && meta.error ? (
<FormHelperMessage invalid>{`${meta.error}`}</FormHelperMessage>
) : (
helper
)
}
options={options}
name={name}
invalid={!!meta.touched && !!meta.error}
onChange={onChange}
onBlur={onBlur}
{...field}
value={value}
/>
);
}}
</Field>
);
} | function FormikInputSelect({
className,
description,
helper,
id,
inputSize,
inputVariation,
label,
labelHint,
name,
onBlur,
onChange,
options,
value,
disabled,
}) {
return (
<Field name={name}>
{({ field, meta }) => {
return (
<InputSelect
disabled={disabled}
id={id}
label={label}
labelHint={labelHint}
className={className}
inputSize={inputSize}
inputVariation={inputVariation}
description={description}
helper={
meta.touched && meta.error ? (
<FormHelperMessage invalid>{`${meta.error}`}</FormHelperMessage>
) : (
helper
)
}
options={options}
name={name}
invalid={!!meta.touched && !!meta.error}
onChange={onChange}
onBlur={onBlur}
{...field}
value={value}
/>
);
}}
</Field>
);
} |
JavaScript | async function fetchJSON(url, options) {
let response;
options = options || {};
const format = options.format || 'json';
let data;
try {
response = await fetch(url, options);
if (format === 'json') {
data = await response.json();
} else if (format === 'binary') {
data = await response.arrayBuffer();
} else {
data = await response.text();
}
if (response.status >= 400) {
const err = new Error(data.message);
err.statusCode = response.status;
err.data = data;
throw err;
}
return { body: data, headers: response.headers };
} catch (error) {
error.statusCode = response ? response.status || null : null;
throw error;
}
} | async function fetchJSON(url, options) {
let response;
options = options || {};
const format = options.format || 'json';
let data;
try {
response = await fetch(url, options);
if (format === 'json') {
data = await response.json();
} else if (format === 'binary') {
data = await response.arrayBuffer();
} else {
data = await response.text();
}
if (response.status >= 400) {
const err = new Error(data.message);
err.statusCode = response.status;
err.data = data;
throw err;
}
return { body: data, headers: response.headers };
} catch (error) {
error.statusCode = response ? response.status || null : null;
throw error;
}
} |
JavaScript | function applyAoi() {
setMapMode(mapModes.BROWSE_MODE);
let bounds = aoiRef.getBounds();
setAoiBounds(bounds);
updateAoiName(bounds);
// When AOI is edited -> we go to run mode
if (currentCheckpoint) {
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RUN,
},
});
}
//Current AOI should only be set after AOI has been sent to the api
setCurrentAoi(null);
} | function applyAoi() {
setMapMode(mapModes.BROWSE_MODE);
let bounds = aoiRef.getBounds();
setAoiBounds(bounds);
updateAoiName(bounds);
// When AOI is edited -> we go to run mode
if (currentCheckpoint) {
dispatchCurrentCheckpoint({
type: checkpointActions.SET_CHECKPOINT_MODE,
data: {
mode: checkpointModes.RUN,
},
});
}
//Current AOI should only be set after AOI has been sent to the api
setCurrentAoi(null);
} |
JavaScript | function useFocus(delay = 0) {
const htmlElRef = useRef(null);
const setFocus = () => {
setTimeout(() => {
htmlElRef.current && htmlElRef.current.focus();
}, delay);
};
return [htmlElRef, setFocus];
} | function useFocus(delay = 0) {
const htmlElRef = useRef(null);
const setFocus = () => {
setTimeout(() => {
htmlElRef.current && htmlElRef.current.focus();
}, delay);
};
return [htmlElRef, setFocus];
} |
JavaScript | function updateAoiName(_aoiBounds, aoiList) {
const refBounds = _aoiBounds || aoiBounds;
if (!refBounds) {
logger(new Error('AOI bounds not defined', aoiBounds));
}
const bounds = [
refBounds.getWest(),
refBounds.getSouth(),
refBounds.getEast(),
refBounds.getNorth(),
];
showGlobalLoadingMessage('Geocoding AOI...');
reverseGeoCode(bounds).then((name) => {
let lastInstance;
aoiList
.sort((a, b) => {
if (a.name < b.name) return -1;
else if (a.name > b.name) return 1;
else return 0;
})
.forEach((a) => {
return (lastInstance = a.name.includes(name) ? a.name : lastInstance);
});
if (lastInstance) {
if (lastInstance.includes('#')) {
const [n, version] = lastInstance.split('#').map((w) => w.trim());
name = `${n} #${Number(version) + 1}`;
} else {
name = `${name} #${1}`;
}
}
setAoiName(name);
hideGlobalLoading();
});
} | function updateAoiName(_aoiBounds, aoiList) {
const refBounds = _aoiBounds || aoiBounds;
if (!refBounds) {
logger(new Error('AOI bounds not defined', aoiBounds));
}
const bounds = [
refBounds.getWest(),
refBounds.getSouth(),
refBounds.getEast(),
refBounds.getNorth(),
];
showGlobalLoadingMessage('Geocoding AOI...');
reverseGeoCode(bounds).then((name) => {
let lastInstance;
aoiList
.sort((a, b) => {
if (a.name < b.name) return -1;
else if (a.name > b.name) return 1;
else return 0;
})
.forEach((a) => {
return (lastInstance = a.name.includes(name) ? a.name : lastInstance);
});
if (lastInstance) {
if (lastInstance.includes('#')) {
const [n, version] = lastInstance.split('#').map((w) => w.trim());
name = `${n} #${Number(version) + 1}`;
} else {
name = `${name} #${1}`;
}
}
setAoiName(name);
hideGlobalLoading();
});
} |
JavaScript | async function reverseGeoCode(bbox) {
/*
if (!aoiBounds) {
console.error('defined bounds before reverse geocoding')
}*/
let center;
if (Array.isArray(bbox)) {
// Need to create a polygon
center = tCentroid(tBboxPolygon(bbox));
} else {
// Assume a polygon feature is provided
center = tCentroid(bbox);
}
const [lon, lat] = center.geometry.coordinates;
const address = await fetch(
`${config.bingSearchUrl}/Locations/${lat},${lon}?radius=${config.reverseGeocodeRadius}&includeEntityTypes=address,AdminDivision1,AdminDivision2, CountryRegion&key=${config.bingApiKey}`,
{
headers: {
'Content-Type': 'application/json',
},
mode: 'cors',
}
)
.then((res) => res.json())
.catch(() => {
toasts.error('Error querying address');
return null;
});
let name;
if (address && address.resourceSets[0].estimatedTotal) {
const result = address.resourceSets[0].resources[0];
const { entityType } = result;
switch (entityType) {
case 'Address':
name = result.address.locality;
break;
case 'AdminDivision1':
case 'AdminDivision2':
case 'CountryRegion':
name = result.name;
}
// Use first result if there are any
} else {
toasts.warn('AOI not geocodable, generic name used');
name = 'Area';
}
// else leave name undefined, should be set by user
return name;
} | async function reverseGeoCode(bbox) {
/*
if (!aoiBounds) {
console.error('defined bounds before reverse geocoding')
}*/
let center;
if (Array.isArray(bbox)) {
// Need to create a polygon
center = tCentroid(tBboxPolygon(bbox));
} else {
// Assume a polygon feature is provided
center = tCentroid(bbox);
}
const [lon, lat] = center.geometry.coordinates;
const address = await fetch(
`${config.bingSearchUrl}/Locations/${lat},${lon}?radius=${config.reverseGeocodeRadius}&includeEntityTypes=address,AdminDivision1,AdminDivision2, CountryRegion&key=${config.bingApiKey}`,
{
headers: {
'Content-Type': 'application/json',
},
mode: 'cors',
}
)
.then((res) => res.json())
.catch(() => {
toasts.error('Error querying address');
return null;
});
let name;
if (address && address.resourceSets[0].estimatedTotal) {
const result = address.resourceSets[0].resources[0];
const { entityType } = result;
switch (entityType) {
case 'Address':
name = result.address.locality;
break;
case 'AdminDivision1':
case 'AdminDivision2':
case 'CountryRegion':
name = result.name;
}
// Use first result if there are any
} else {
toasts.warn('AOI not geocodable, generic name used');
name = 'Area';
}
// else leave name undefined, should be set by user
return name;
} |
JavaScript | function decodeScalar(buf, message = 'Invalid scalar') {
const scalar = decodeInt(buf);
if (scalar.gte(ec.curve.n)) {
throw new RangeError(message);
}
return scalar;
} | function decodeScalar(buf, message = 'Invalid scalar') {
const scalar = decodeInt(buf);
if (scalar.gte(ec.curve.n)) {
throw new RangeError(message);
}
return scalar;
} |
JavaScript | function encodeUint32(num) {
if (num > MAX_UINT_32) {
throw RangeError('Value must not equal or exceed 2^32');
}
return new BN(num, 10).toArrayLike(Buffer, 'le', 4);
} | function encodeUint32(num) {
if (num > MAX_UINT_32) {
throw RangeError('Value must not equal or exceed 2^32');
}
return new BN(num, 10).toArrayLike(Buffer, 'le', 4);
} |
JavaScript | function buildProfileList(uuid, profiles = {}) {
const key = `skyblock_profiles:${uuid}`;
redis.get(key, (err, res) => {
if (err) {
return logger.error(`Failed getting profile list hash from redis: ${err}`);
}
const p = JSON.parse(res) || {};
// TODO - Mark old profiles
const updateQueue = Object.keys(profiles).filter(id => !(id in p));
if (updateQueue.length === 0) return;
async.each(updateQueue, (id, cb) => {
buildProfile(uuid, id, (err, profile) => {
p[id] = Object.assign(profiles[id], getStats(profile.members[uuid] || {}, profile.members));
cb();
});
}, () => redis.set(key, JSON.stringify(p), (err) => {
if (err) {
logger.error(err);
}
}));
});
} | function buildProfileList(uuid, profiles = {}) {
const key = `skyblock_profiles:${uuid}`;
redis.get(key, (err, res) => {
if (err) {
return logger.error(`Failed getting profile list hash from redis: ${err}`);
}
const p = JSON.parse(res) || {};
// TODO - Mark old profiles
const updateQueue = Object.keys(profiles).filter(id => !(id in p));
if (updateQueue.length === 0) return;
async.each(updateQueue, (id, cb) => {
buildProfile(uuid, id, (err, profile) => {
p[id] = Object.assign(profiles[id], getStats(profile.members[uuid] || {}, profile.members));
cb();
});
}, () => redis.set(key, JSON.stringify(p), (err) => {
if (err) {
logger.error(err);
}
}));
});
} |
JavaScript | insertion () {
for (let j = 0; j < this.data.length; j++) {
/*The next element to be compared in the array */
const key = this.data[j];
/*The previous element in the array */
let i = j - 1;
/*Chek through the array to see if all previous elements are greater than the curent lement [key] */
while (i > -1 && this.data[i] > key) {
this.data[i + 1] = this.data[i];
i -= 1;
}
/*Insert the element at the appropriate position within the array */
this.data[i + 1] = key;
}
} | insertion () {
for (let j = 0; j < this.data.length; j++) {
/*The next element to be compared in the array */
const key = this.data[j];
/*The previous element in the array */
let i = j - 1;
/*Chek through the array to see if all previous elements are greater than the curent lement [key] */
while (i > -1 && this.data[i] > key) {
this.data[i + 1] = this.data[i];
i -= 1;
}
/*Insert the element at the appropriate position within the array */
this.data[i + 1] = key;
}
} |
JavaScript | mergeSort(A, startIndex, endIndex) {
if (startIndex < endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
this.mergeSort(A, startIndex, middleIndex);
this.mergeSort(A, middleIndex + 1, endIndex);
this.merge(A, startIndex, middleIndex, endIndex);
}
} | mergeSort(A, startIndex, endIndex) {
if (startIndex < endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
this.mergeSort(A, startIndex, middleIndex);
this.mergeSort(A, middleIndex + 1, endIndex);
this.merge(A, startIndex, middleIndex, endIndex);
}
} |
JavaScript | selction() {
const n = this.data.length;
for (let i = 0; i < n; i += 1) {
let min= this.data[i];
for (let j = i; j < n; j += 1) {
if (this.data[j] < min){
min = this.data[j];
[this.data[i], this.data[j]] = [this.data[j], this.data[i]]; //swap the values
}
}
}
} | selction() {
const n = this.data.length;
for (let i = 0; i < n; i += 1) {
let min= this.data[i];
for (let j = i; j < n; j += 1) {
if (this.data[j] < min){
min = this.data[j];
[this.data[i], this.data[j]] = [this.data[j], this.data[i]]; //swap the values
}
}
}
} |
JavaScript | async function fetchRuntimeParameters(config, customRuntimeParameters) {
const runtimeParameters = Object.assign({}, customRuntimeParameters);
// Configure the log level
runtimeParameters.verbose = customRuntimeParameters.verbose || config.verbose || false;
// Copy lts and rtv runtime flag from custom parameters or the static config. Both are disabled by default.
runtimeParameters.lts = customRuntimeParameters.lts || config.lts || false;
runtimeParameters.rtv = customRuntimeParameters.rtv || config.rtv || false;
// Fetch the validator rules
runtimeParameters.validatorRules = config.validatorRules || (await validatorRules.fetch());
let {ampUrlPrefix, ampRuntimeVersion, ampRuntimeStyles, lts} = runtimeParameters;
// Use existing runtime version or fetch lts or latest
runtimeParameters.ampRuntimeVersion =
ampRuntimeVersion || (await config.runtimeVersion.currentVersion({ampUrlPrefix, lts}));
// Fetch runtime styles based on the runtime version
runtimeParameters.ampRuntimeStyles =
ampRuntimeStyles ||
(await fetchAmpRuntimeStyles_(config, ampUrlPrefix, runtimeParameters.ampRuntimeVersion));
return runtimeParameters;
} | async function fetchRuntimeParameters(config, customRuntimeParameters) {
const runtimeParameters = Object.assign({}, customRuntimeParameters);
// Configure the log level
runtimeParameters.verbose = customRuntimeParameters.verbose || config.verbose || false;
// Copy lts and rtv runtime flag from custom parameters or the static config. Both are disabled by default.
runtimeParameters.lts = customRuntimeParameters.lts || config.lts || false;
runtimeParameters.rtv = customRuntimeParameters.rtv || config.rtv || false;
// Fetch the validator rules
runtimeParameters.validatorRules = config.validatorRules || (await validatorRules.fetch());
let {ampUrlPrefix, ampRuntimeVersion, ampRuntimeStyles, lts} = runtimeParameters;
// Use existing runtime version or fetch lts or latest
runtimeParameters.ampRuntimeVersion =
ampRuntimeVersion || (await config.runtimeVersion.currentVersion({ampUrlPrefix, lts}));
// Fetch runtime styles based on the runtime version
runtimeParameters.ampRuntimeStyles =
ampRuntimeStyles ||
(await fetchAmpRuntimeStyles_(config, ampUrlPrefix, runtimeParameters.ampRuntimeVersion));
return runtimeParameters;
} |
JavaScript | function queueUpdateProgressBar() {
let currentWidth = parseInt(document.getElementById("loading-progress").style["width"]);
let barQueueLength = parseInt(document.getElementById("loading-progress").getAttribute("queueLength"));
let newWidth = (currentWidth + barQueueLength).toString();
if (newWidth && newWidth <= 100.0 && document.getElementById("loading-progress")) {
document.getElementById("loading-progress").style["width"] = newWidth+"%";
}
clearProgressMessage();
} | function queueUpdateProgressBar() {
let currentWidth = parseInt(document.getElementById("loading-progress").style["width"]);
let barQueueLength = parseInt(document.getElementById("loading-progress").getAttribute("queueLength"));
let newWidth = (currentWidth + barQueueLength).toString();
if (newWidth && newWidth <= 100.0 && document.getElementById("loading-progress")) {
document.getElementById("loading-progress").style["width"] = newWidth+"%";
}
clearProgressMessage();
} |
JavaScript | function streamUpdateProgressBar(chunkSize, totalSize, filename) {
let totalChunks = totalSize / chunkSize;
let barQueueLength = parseInt(document.getElementById("loading-progress").getAttribute("queueLength"));
let forThisQueueItem = ( barQueueLength * ( 1.0 / totalChunks ) );
let currentWidth = parseInt(document.getElementById("loading-progress").style["width"]);
let newWidth = (currentWidth + forThisQueueItem).toString();
if (newWidth && newWidth <= 100.0 && document.getElementById("loading-progress")) {
document.getElementById("loading-progress").style["width"] = newWidth+"%";
}
setProgressMessage("Loading " + filename);
} | function streamUpdateProgressBar(chunkSize, totalSize, filename) {
let totalChunks = totalSize / chunkSize;
let barQueueLength = parseInt(document.getElementById("loading-progress").getAttribute("queueLength"));
let forThisQueueItem = ( barQueueLength * ( 1.0 / totalChunks ) );
let currentWidth = parseInt(document.getElementById("loading-progress").style["width"]);
let newWidth = (currentWidth + forThisQueueItem).toString();
if (newWidth && newWidth <= 100.0 && document.getElementById("loading-progress")) {
document.getElementById("loading-progress").style["width"] = newWidth+"%";
}
setProgressMessage("Loading " + filename);
} |
JavaScript | function d3csvUpdateProgressBar(currentRow, totalRows, filename) {
let totalChunks = 10;
let oneTenth = Math.round(totalRows / totalChunks);
if( currentRow % oneTenth == 0 ) {
let barQueueLength = parseInt(document.getElementById("loading-progress").getAttribute("queueLength"));
let forThisQueueItem = ( barQueueLength * ( 1.0 / totalChunks ) );
let currentWidth = parseInt(document.getElementById("loading-progress").style["width"]);
let newWidth = (currentWidth + forThisQueueItem).toString();
if (newWidth && newWidth <= 100.0 && document.getElementById("loading-progress")) {
document.getElementById("loading-progress").style["width"] = newWidth+"%";
}
setProgressMessage("Loading " + filename);
}
} | function d3csvUpdateProgressBar(currentRow, totalRows, filename) {
let totalChunks = 10;
let oneTenth = Math.round(totalRows / totalChunks);
if( currentRow % oneTenth == 0 ) {
let barQueueLength = parseInt(document.getElementById("loading-progress").getAttribute("queueLength"));
let forThisQueueItem = ( barQueueLength * ( 1.0 / totalChunks ) );
let currentWidth = parseInt(document.getElementById("loading-progress").style["width"]);
let newWidth = (currentWidth + forThisQueueItem).toString();
if (newWidth && newWidth <= 100.0 && document.getElementById("loading-progress")) {
document.getElementById("loading-progress").style["width"] = newWidth+"%";
}
setProgressMessage("Loading " + filename);
}
} |
JavaScript | function handleViewSetup(data) {
// initializes loading bar
document.getElementById("UI").innerHTML = `<div id='loading_progress' class='card border-dark' style='height: 50vh;'>
<div class='card-header'><h3>ElectroLens</h3></div>
<div class='card-body'>
<div class='progress'>
<div class='progress-bar progress-bar-striped progress-bar-animated active' id='loading-progress' role='progressbar' style='width: 5%;'></div>
</div></div>
<div id='loading-message'></div></div>`;
const views = data.views;
const plotSetup = data.plotSetup;
initializeViewSetups(views, plotSetup);
document.getElementById("loading-progress").style["width"] = "10%";
main(views, plotSetup);
} | function handleViewSetup(data) {
// initializes loading bar
document.getElementById("UI").innerHTML = `<div id='loading_progress' class='card border-dark' style='height: 50vh;'>
<div class='card-header'><h3>ElectroLens</h3></div>
<div class='card-body'>
<div class='progress'>
<div class='progress-bar progress-bar-striped progress-bar-animated active' id='loading-progress' role='progressbar' style='width: 5%;'></div>
</div></div>
<div id='loading-message'></div></div>`;
const views = data.views;
const plotSetup = data.plotSetup;
initializeViewSetups(views, plotSetup);
document.getElementById("loading-progress").style["width"] = "10%";
main(views, plotSetup);
} |
JavaScript | function launch_web_auth_flow_and_store_access_token(auth_details,fn){
if(auth_details == null){
redirect_url = chrome.identity.getRedirectURL();
chrome.identity.launchWebAuthFlow(
{'url': sign_up_url + "?redirect_url="+ redirect_url + "oauth2", 'interactive': true},
function(redir) {
auth_token = $.url("?authentication_token",redir);
es = $.url("?es",redir);
set_auth_details(auth_token,es);
console.log("got auth details as:" );
console.log(auth_token);
console.log(es);
});
}
else{
console.log("auth details exist:" + auth_details);
}
} | function launch_web_auth_flow_and_store_access_token(auth_details,fn){
if(auth_details == null){
redirect_url = chrome.identity.getRedirectURL();
chrome.identity.launchWebAuthFlow(
{'url': sign_up_url + "?redirect_url="+ redirect_url + "oauth2", 'interactive': true},
function(redir) {
auth_token = $.url("?authentication_token",redir);
es = $.url("?es",redir);
set_auth_details(auth_token,es);
console.log("got auth details as:" );
console.log(auth_token);
console.log(es);
});
}
else{
console.log("auth details exist:" + auth_details);
}
} |
JavaScript | function add_authorization_headers(fn,xhr){
var auth_details = get_auth_details(function(auth_details){
console.log("the auth details are");
console.log(auth_details);
if(auth_details != null){
console.log("went to add the headers");
xhr.setRequestHeader("X-User-Es",auth_details[1]);
xhr.setRequestHeader("X-User-Token",auth_details[0]);
}
console.log("after adding the headers the xhr is");
console.log(xhr);
fn(xhr);
});
} | function add_authorization_headers(fn,xhr){
var auth_details = get_auth_details(function(auth_details){
console.log("the auth details are");
console.log(auth_details);
if(auth_details != null){
console.log("went to add the headers");
xhr.setRequestHeader("X-User-Es",auth_details[1]);
xhr.setRequestHeader("X-User-Token",auth_details[0]);
}
console.log("after adding the headers the xhr is");
console.log(xhr);
fn(xhr);
});
} |
JavaScript | function App() {
return (
<div className="App">
<header className="App-header">
<Nav />
</header>
<main>
<div className="about-me">
<About />
</div>
<div className="projects" id="projects">
<Projects />
</div>
</main>
<div className="contact" id="contact">
<Contact />
</div>
</div>
);
} | function App() {
return (
<div className="App">
<header className="App-header">
<Nav />
</header>
<main>
<div className="about-me">
<About />
</div>
<div className="projects" id="projects">
<Projects />
</div>
</main>
<div className="contact" id="contact">
<Contact />
</div>
</div>
);
} |
JavaScript | function createNavTree(edges) {
const items = edges.map(({ node }) => ({
url: node.fields.url,
isHomepage: node.fields.isHomepage,
title: node.frontmatter.title,
displayName: node.frontmatter.displayName,
pathChunks: getRelativePagePath(node.fileAbsolutePath).split('/'),
filename: path.basename(node.fileAbsolutePath),
}))
function buildRecursiveTree(pages) {
return pages.reduce((tree, page) => {
let { pathChunks, filename, url, title, isHomepage } = page
const displayName = page.displayName || title
// Remove the last node in the path chunks for root pages
if (isRootFile(filename)) {
pathChunks = pathChunks.slice(0, -1)
}
if (pathChunks.length === 0) {
return tree.concat({
title,
displayName,
url,
isHomepage,
})
} else {
const targetItems = pathChunks.reduce((acc, pathSegment, index) => {
const isLastSegment = index === pathChunks.length - 1
const existingNode = acc.find((node) => {
return node.segment === pathSegment
})
if (!existingNode) {
acc.push(
Object.assign(
{},
{
title: pathSegment,
segment: pathSegment,
displayName: unslugify(pathSegment),
},
isLastSegment
? {
title,
displayName,
url,
}
: {
items: [],
},
),
)
} else if (isLastSegment) {
existingNode.url = url
return existingNode
} else if (!existingNode.items) {
existingNode.items = []
}
const nextAcc = existingNode
? existingNode.items
: acc[acc.length - 1].items
return nextAcc
}, tree)
if (targetItems && Array.isArray(targetItems)) {
targetItems.push({
title,
pathSegment,
displayName,
url,
})
}
}
return tree
}, [])
}
return buildRecursiveTree(items)
} | function createNavTree(edges) {
const items = edges.map(({ node }) => ({
url: node.fields.url,
isHomepage: node.fields.isHomepage,
title: node.frontmatter.title,
displayName: node.frontmatter.displayName,
pathChunks: getRelativePagePath(node.fileAbsolutePath).split('/'),
filename: path.basename(node.fileAbsolutePath),
}))
function buildRecursiveTree(pages) {
return pages.reduce((tree, page) => {
let { pathChunks, filename, url, title, isHomepage } = page
const displayName = page.displayName || title
// Remove the last node in the path chunks for root pages
if (isRootFile(filename)) {
pathChunks = pathChunks.slice(0, -1)
}
if (pathChunks.length === 0) {
return tree.concat({
title,
displayName,
url,
isHomepage,
})
} else {
const targetItems = pathChunks.reduce((acc, pathSegment, index) => {
const isLastSegment = index === pathChunks.length - 1
const existingNode = acc.find((node) => {
return node.segment === pathSegment
})
if (!existingNode) {
acc.push(
Object.assign(
{},
{
title: pathSegment,
segment: pathSegment,
displayName: unslugify(pathSegment),
},
isLastSegment
? {
title,
displayName,
url,
}
: {
items: [],
},
),
)
} else if (isLastSegment) {
existingNode.url = url
return existingNode
} else if (!existingNode.items) {
existingNode.items = []
}
const nextAcc = existingNode
? existingNode.items
: acc[acc.length - 1].items
return nextAcc
}, tree)
if (targetItems && Array.isArray(targetItems)) {
targetItems.push({
title,
pathSegment,
displayName,
url,
})
}
}
return tree
}, [])
}
return buildRecursiveTree(items)
} |
JavaScript | calcularInformacionInicial(){
/** Se calcula el iva del producto */
var iva = (parseFloat(this.state.objArticulo.precio) * (1 + ((parseFloat(this.state.objConfiguracion.tasafinanciamiento) * parseInt(this.state.objConfiguracion.plazomaximo)) / parseFloat(100)))).toFixed(2);
//console.log("IVA: " + iva);
/** Se asigna el valor del precio al state */
this.asignarValorState('precio',iva,'cantidadArticulos');
/** Se asigna el importe al renglon */
this.asignarValorState('importe',(parseFloat(this.state.cantidadArticulos.precio) * parseInt(this.state.cantidadArticulos.cantidad)).toFixed(2),'cantidadArticulos');
/** Se asigna la cantidad al objeto state */
this.asignarValorState('cantidad',parseInt(this.state.cantidadArticulos.cantidad),'objArticulo');
/** Se regresa el objeto con los precios al onchange del props */
this.props.onChangeInput(this.state.objArticulo);
} | calcularInformacionInicial(){
/** Se calcula el iva del producto */
var iva = (parseFloat(this.state.objArticulo.precio) * (1 + ((parseFloat(this.state.objConfiguracion.tasafinanciamiento) * parseInt(this.state.objConfiguracion.plazomaximo)) / parseFloat(100)))).toFixed(2);
//console.log("IVA: " + iva);
/** Se asigna el valor del precio al state */
this.asignarValorState('precio',iva,'cantidadArticulos');
/** Se asigna el importe al renglon */
this.asignarValorState('importe',(parseFloat(this.state.cantidadArticulos.precio) * parseInt(this.state.cantidadArticulos.cantidad)).toFixed(2),'cantidadArticulos');
/** Se asigna la cantidad al objeto state */
this.asignarValorState('cantidad',parseInt(this.state.cantidadArticulos.cantidad),'objArticulo');
/** Se regresa el objeto con los precios al onchange del props */
this.props.onChangeInput(this.state.objArticulo);
} |
JavaScript | asignarValorState(campo,valor,objeto){
//Se crea el objeto que hara referncia al state
let Obj = this.state[objeto];
//Se crea el switch para entrar a las opciones
Obj[campo] = valor;
//Se realiza la actualizacion del state
this.setState({
objeto:Obj
})
} | asignarValorState(campo,valor,objeto){
//Se crea el objeto que hara referncia al state
let Obj = this.state[objeto];
//Se crea el switch para entrar a las opciones
Obj[campo] = valor;
//Se realiza la actualizacion del state
this.setState({
objeto:Obj
})
} |
JavaScript | onChange(target,propiedad,objeto){
if(target.value === ""){
/** Se asigna el valor al state */
this.asignarValorState('importe',0,objeto);
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
}else{
/** Validacion para que no pueda sobrepasar la cantidad maxima de la existencia */
if(parseInt(target.value) > parseInt(this.state.objArticulo.existencia)){
/** Se asigna el valor al state con el maximo permitido */
this.asignarValorState(propiedad,parseInt(this.state.objArticulo.existencia),objeto);
}else{
if(target.value === "0"){
/** Se asigna el valor al state */
this.asignarValorState(propiedad,1,objeto);
}else{
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
valorPattern = obtenerRegexPattern("numero");
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,parseInt(target.value),objeto);
}
}
/** Manda a llamar el metodo que realiza los calculos nuevamente */
this.calcularInformacionInicial();
}
} | onChange(target,propiedad,objeto){
if(target.value === ""){
/** Se asigna el valor al state */
this.asignarValorState('importe',0,objeto);
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
}else{
/** Validacion para que no pueda sobrepasar la cantidad maxima de la existencia */
if(parseInt(target.value) > parseInt(this.state.objArticulo.existencia)){
/** Se asigna el valor al state con el maximo permitido */
this.asignarValorState(propiedad,parseInt(this.state.objArticulo.existencia),objeto);
}else{
if(target.value === "0"){
/** Se asigna el valor al state */
this.asignarValorState(propiedad,1,objeto);
}else{
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
valorPattern = obtenerRegexPattern("numero");
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,parseInt(target.value),objeto);
}
}
/** Manda a llamar el metodo que realiza los calculos nuevamente */
this.calcularInformacionInicial();
}
} |
JavaScript | onClickEliminar(){
/** Se realiza el cambio del precio por el importe */
var importe = parseInt(this.state.cantidadArticulos.cantidad) * parseFloat(this.state.cantidadArticulos.precio);
/** Se asigna el nuevo valor del precio al objeto del renglon seleccionado */
this.asignarValorState('precio',importe,'objArticulo');
/** Se regresa el objeto */
this.props.onClickDelete(this.state.objArticulo);
} | onClickEliminar(){
/** Se realiza el cambio del precio por el importe */
var importe = parseInt(this.state.cantidadArticulos.cantidad) * parseFloat(this.state.cantidadArticulos.precio);
/** Se asigna el nuevo valor del precio al objeto del renglon seleccionado */
this.asignarValorState('precio',importe,'objArticulo');
/** Se regresa el objeto */
this.props.onClickDelete(this.state.objArticulo);
} |
JavaScript | componentDidMount(){
this.obtenerConteoArticulos();
/** Se asigna la informacion del modal para visualizarlo */
this.asignarValorState('mensaje','Cargando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se llama el metodo que obtendra la lista de clientes */
this.obtenerListadoArticulos();
} | componentDidMount(){
this.obtenerConteoArticulos();
/** Se asigna la informacion del modal para visualizarlo */
this.asignarValorState('mensaje','Cargando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se llama el metodo que obtendra la lista de clientes */
this.obtenerListadoArticulos();
} |
JavaScript | guardarArticulo(objetoArticulo){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Articulos/guardarArticulo',{
method:'POST',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
},body:JSON.stringify(objetoArticulo)
})
.then(res => res.json())
.then(Respuesta => {
/** Se limpia el state */
this.limpiarStateObjeto();
/** Se asigna la informacion del modal para ocultarlo */
this.asignarValorState('mensaje','','modalCargando');
this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se valida para determinar si se realizo el guardado correctamnte o no */
if(Respuesta.objetoStatus.codigoError.split(" ")[0] === "201"){
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'success','showMensaje');
/** Se llama el metodo que se encarga de obtener el total de registros */
this.obtenerConteoArticulos();
/** Se llama el metodo que obtendra el listado de los clientes */
this.obtenerListadoArticulos();
}else{
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'danger','showMensaje');
}
})
} | guardarArticulo(objetoArticulo){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Articulos/guardarArticulo',{
method:'POST',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
},body:JSON.stringify(objetoArticulo)
})
.then(res => res.json())
.then(Respuesta => {
/** Se limpia el state */
this.limpiarStateObjeto();
/** Se asigna la informacion del modal para ocultarlo */
this.asignarValorState('mensaje','','modalCargando');
this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se valida para determinar si se realizo el guardado correctamnte o no */
if(Respuesta.objetoStatus.codigoError.split(" ")[0] === "201"){
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'success','showMensaje');
/** Se llama el metodo que se encarga de obtener el total de registros */
this.obtenerConteoArticulos();
/** Se llama el metodo que obtendra el listado de los clientes */
this.obtenerListadoArticulos();
}else{
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'danger','showMensaje');
}
})
} |
JavaScript | obtenerConteoArticulos(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Articulos/countArticulos',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna el conteo */
this.asignarValorState('clavearticulo',Respuesta.conteoClave,'variablesVista');
//console.log(this.state.variablesVista);
})
} | obtenerConteoArticulos(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Articulos/countArticulos',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna el conteo */
this.asignarValorState('clavearticulo',Respuesta.conteoClave,'variablesVista');
//console.log(this.state.variablesVista);
})
} |
JavaScript | mostrarControlMensaje(mensaje,opcion,objeto){
//Se regresa como verdadero si cumplio con las validaciones
this.asignarValorState('colorHeader', opcion, objeto);
this.asignarValorState('mensajeBody', mensaje, objeto);
//Se muestra el mensaje de error adjunto el time out
this.setState({mostarModalMensaje:true},()=>{
window.setTimeout(()=>{
this.setState({mostarModalMensaje:false})
},3500)
});
} | mostrarControlMensaje(mensaje,opcion,objeto){
//Se regresa como verdadero si cumplio con las validaciones
this.asignarValorState('colorHeader', opcion, objeto);
this.asignarValorState('mensajeBody', mensaje, objeto);
//Se muestra el mensaje de error adjunto el time out
this.setState({mostarModalMensaje:true},()=>{
window.setTimeout(()=>{
this.setState({mostarModalMensaje:false})
},3500)
});
} |
JavaScript | limpiarStateObjeto(){
this.asignarValorState('id',0,'objArticulo');
this.asignarValorState('clavearticulo','','objArticulo');
this.asignarValorState('descripcion','','objArticulo');
this.asignarValorState('modelo','','objArticulo');
this.asignarValorState('precio',0,'objArticulo');
this.asignarValorState('existencia',0,'objArticulo');
} | limpiarStateObjeto(){
this.asignarValorState('id',0,'objArticulo');
this.asignarValorState('clavearticulo','','objArticulo');
this.asignarValorState('descripcion','','objArticulo');
this.asignarValorState('modelo','','objArticulo');
this.asignarValorState('precio',0,'objArticulo');
this.asignarValorState('existencia',0,'objArticulo');
} |
JavaScript | llenarValoresStates(objArticulo){
this.asignarValorState('id',objArticulo.id,'objArticulo');
this.asignarValorState('clavearticulo',objArticulo.clavearticulo,'objArticulo');
this.asignarValorState('descripcion',objArticulo.descripcion,'objArticulo');
this.asignarValorState('modelo',objArticulo.modelo,'objArticulo');
this.asignarValorState('precio',objArticulo.precio,'objArticulo');
this.asignarValorState('existencia',objArticulo.existencia,'objArticulo');
} | llenarValoresStates(objArticulo){
this.asignarValorState('id',objArticulo.id,'objArticulo');
this.asignarValorState('clavearticulo',objArticulo.clavearticulo,'objArticulo');
this.asignarValorState('descripcion',objArticulo.descripcion,'objArticulo');
this.asignarValorState('modelo',objArticulo.modelo,'objArticulo');
this.asignarValorState('precio',objArticulo.precio,'objArticulo');
this.asignarValorState('existencia',objArticulo.existencia,'objArticulo');
} |
JavaScript | function aplicaValidacion(control, valor,es_numero){
let color = "#E8E8E8";
let indicador = 1;
let comparacion = null;
comparacion = es_numero ? 0 : '';
//validacion para determinar si se proporciono toda la informacion necesaria
if(es_numero === true){
color = (parseInt(valor) === comparacion) ? "red" : color;
}else{
color = (valor === comparacion) ? "red" : color;
}
//color = (valor === comparacion) ? "red" : color;
document.getElementById(control).style.borderColor=color;
indicador = (color === "red") ? 1 : 0;
return indicador;
} | function aplicaValidacion(control, valor,es_numero){
let color = "#E8E8E8";
let indicador = 1;
let comparacion = null;
comparacion = es_numero ? 0 : '';
//validacion para determinar si se proporciono toda la informacion necesaria
if(es_numero === true){
color = (parseInt(valor) === comparacion) ? "red" : color;
}else{
color = (valor === comparacion) ? "red" : color;
}
//color = (valor === comparacion) ? "red" : color;
document.getElementById(control).style.borderColor=color;
indicador = (color === "red") ? 1 : 0;
return indicador;
} |
JavaScript | function validaStateVsPropObj(stateObj,propObj,opcion){
if(opcion === 'clientes'){
return (stateObj['nombre'] !== propObj['nombre'] || stateObj['appaterno'] !== propObj['appaterno'] ||
stateObj['apmaterno'] !== propObj['apmaterno'] || stateObj['rfc'] !== propObj['rfc']) ? true : false;
}else{
if(opcion === 'articulos'){
return (stateObj['descripcion'] !== propObj['descripcion'] || stateObj['modelo'] !== propObj['modelo'] ||
stateObj['precio'] !== propObj['precio'] || stateObj['existencia'] !== propObj['existencia']) ? true : false;
}else{
if(opcion === 'configuracion'){
return (stateObj['tasafinanciamiento'] !== propObj['tasafinanciamiento'] || stateObj['porcientoenganche'] !== propObj['porcientoenganche'] ||
stateObj['plazomaximo'] !== propObj['plazomaximo']) ? true : false;
}
}
}
} | function validaStateVsPropObj(stateObj,propObj,opcion){
if(opcion === 'clientes'){
return (stateObj['nombre'] !== propObj['nombre'] || stateObj['appaterno'] !== propObj['appaterno'] ||
stateObj['apmaterno'] !== propObj['apmaterno'] || stateObj['rfc'] !== propObj['rfc']) ? true : false;
}else{
if(opcion === 'articulos'){
return (stateObj['descripcion'] !== propObj['descripcion'] || stateObj['modelo'] !== propObj['modelo'] ||
stateObj['precio'] !== propObj['precio'] || stateObj['existencia'] !== propObj['existencia']) ? true : false;
}else{
if(opcion === 'configuracion'){
return (stateObj['tasafinanciamiento'] !== propObj['tasafinanciamiento'] || stateObj['porcientoenganche'] !== propObj['porcientoenganche'] ||
stateObj['plazomaximo'] !== propObj['plazomaximo']) ? true : false;
}
}
}
} |
JavaScript | componentWillMount(){
this.asignarValorState('id',this.props.objCliente.id,'objetoCliente');
if(this.props.objCliente.clavecliente === ''){
this.asignarValorState('clavecliente',this.props.claveCliente,'objetoCliente');
}else{
this.asignarValorState('clavecliente',this.props.objCliente.clavecliente,'objetoCliente');
}
this.asignarValorState('nombre',this.props.objCliente.nombre,'objetoCliente');
this.asignarValorState('appaterno',this.props.objCliente.appaterno,'objetoCliente');
this.asignarValorState('apmaterno',this.props.objCliente.apmaterno,'objetoCliente');
this.asignarValorState('rfc',this.props.objCliente.rfc,'objetoCliente');
} | componentWillMount(){
this.asignarValorState('id',this.props.objCliente.id,'objetoCliente');
if(this.props.objCliente.clavecliente === ''){
this.asignarValorState('clavecliente',this.props.claveCliente,'objetoCliente');
}else{
this.asignarValorState('clavecliente',this.props.objCliente.clavecliente,'objetoCliente');
}
this.asignarValorState('nombre',this.props.objCliente.nombre,'objetoCliente');
this.asignarValorState('appaterno',this.props.objCliente.appaterno,'objetoCliente');
this.asignarValorState('apmaterno',this.props.objCliente.apmaterno,'objetoCliente');
this.asignarValorState('rfc',this.props.objCliente.rfc,'objetoCliente');
} |
JavaScript | onChange(target,propiedad,objeto){
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
if(propiedad === 'rfc'){
valorPattern = obtenerRegexPattern("texto");
}else{
valorPattern = obtenerRegexPattern("nombres");
}
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
} | onChange(target,propiedad,objeto){
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
if(propiedad === 'rfc'){
valorPattern = obtenerRegexPattern("texto");
}else{
valorPattern = obtenerRegexPattern("nombres");
}
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
} |
JavaScript | validarInformacion(){
/** valida la informacion de los txt */
if(this.generaValidacionControles() === 0){
/** Se valida si se realizara un guardado o una actualizacion */
if(this.state.objetoCliente.id === 0){
/** Se realizara un guardado */
return true;
}else{
/** Se llama el metodo que se encargara de indicar si se modifico algo o no */
if(validaStateVsPropObj(this.state.objetoCliente,this.props.objCliente,'clientes')){
return true;
}else{
/** Se asignan los valores del mensaje */
this.mostrarControlMensaje("Se debe modificar al menos un campo para poder actualizar.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
}
}else{
this.mostrarControlMensaje("Debe proporcionar toda la información.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
} | validarInformacion(){
/** valida la informacion de los txt */
if(this.generaValidacionControles() === 0){
/** Se valida si se realizara un guardado o una actualizacion */
if(this.state.objetoCliente.id === 0){
/** Se realizara un guardado */
return true;
}else{
/** Se llama el metodo que se encargara de indicar si se modifico algo o no */
if(validaStateVsPropObj(this.state.objetoCliente,this.props.objCliente,'clientes')){
return true;
}else{
/** Se asignan los valores del mensaje */
this.mostrarControlMensaje("Se debe modificar al menos un campo para poder actualizar.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
}
}else{
this.mostrarControlMensaje("Debe proporcionar toda la información.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
} |
JavaScript | generaValidacionControles(){
let validacion = 0;
validacion = aplicaValidacion("txtNombre",this.state.objetoCliente.nombre,false);
validacion = aplicaValidacion("txtApPaterno",this.state.objetoCliente.appaterno,false);
validacion = aplicaValidacion("txtApMaterno",this.state.objetoCliente.apmaterno,false);
validacion = aplicaValidacion("txtRFC",this.state.objetoCliente.rfc,false);
return validacion;
} | generaValidacionControles(){
let validacion = 0;
validacion = aplicaValidacion("txtNombre",this.state.objetoCliente.nombre,false);
validacion = aplicaValidacion("txtApPaterno",this.state.objetoCliente.appaterno,false);
validacion = aplicaValidacion("txtApMaterno",this.state.objetoCliente.apmaterno,false);
validacion = aplicaValidacion("txtRFC",this.state.objetoCliente.rfc,false);
return validacion;
} |
JavaScript | ocultarDesocultarVentanas(valorVentVista,valorVentAddVenta){
/** Primer valor para ocultar o desocultar la ventana de vista tabla */
this.asignarValorState('ventanaTablaVentas',valorVentVista,'showModales');
/** Segundo valor para ocultar o desocultar la ventana de agregar venta*/
this.asignarValorState('ventanaAgregarVenta',valorVentAddVenta,'showModales');
} | ocultarDesocultarVentanas(valorVentVista,valorVentAddVenta){
/** Primer valor para ocultar o desocultar la ventana de vista tabla */
this.asignarValorState('ventanaTablaVentas',valorVentVista,'showModales');
/** Segundo valor para ocultar o desocultar la ventana de agregar venta*/
this.asignarValorState('ventanaAgregarVenta',valorVentAddVenta,'showModales');
} |
JavaScript | onClickAddVenta(){
/** Se oculta y desoculta las ventanas */
this.ocultarDesocultarVentanas(false,true);
/** Se oculta el boton de nueva venta */
//document.getElementById("divBotonVenta").style.display="none";
} | onClickAddVenta(){
/** Se oculta y desoculta las ventanas */
this.ocultarDesocultarVentanas(false,true);
/** Se oculta el boton de nueva venta */
//document.getElementById("divBotonVenta").style.display="none";
} |
JavaScript | obtenerListadoCientes(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Clientes/getAllClientesMapper',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna la informacion del modal para ocultarlo */
//this.asignarValorState('mensaje','','modalCargando');
//this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se asigna el listado al state */
this.setState({
listadoClientes:Respuesta.listadoClientesMapeados
})
})
} | obtenerListadoCientes(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Clientes/getAllClientesMapper',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna la informacion del modal para ocultarlo */
//this.asignarValorState('mensaje','','modalCargando');
//this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se asigna el listado al state */
this.setState({
listadoClientes:Respuesta.listadoClientesMapeados
})
})
} |
JavaScript | componentDidMount(){
this.obtenerConteoClientes();
/** Se asigna la informacion del modal para visualizarlo */
this.asignarValorState('mensaje','Cargando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se llama el metodo que obtendra la lista de clientes */
this.obtenerListadoClientes();
} | componentDidMount(){
this.obtenerConteoClientes();
/** Se asigna la informacion del modal para visualizarlo */
this.asignarValorState('mensaje','Cargando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se llama el metodo que obtendra la lista de clientes */
this.obtenerListadoClientes();
} |
JavaScript | guardarCliente(objetoCliente){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Clientes/guardarCliente',{
method:'POST',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
},body:JSON.stringify(objetoCliente)
})
.then(res => res.json())
.then(Respuesta => {
/** Se limpia el state */
this.limpiarStateObjeto();
/** Se asigna la informacion del modal para ocultarlo */
this.asignarValorState('mensaje','','modalCargando');
this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se valida para determinar si se realizo el guardado correctamnte o no */
if(Respuesta.objetoStatus.codigoError.split(" ")[0] === "201"){
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'success','showMensaje');
/** Se llama el metodo que se encarga de obtener el total de registros */
this.obtenerConteoClientes();
/** Se llama el metodo que obtendra el listado de los clientes */
this.obtenerListadoClientes();
}else{
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'danger','showMensaje');
}
})
} | guardarCliente(objetoCliente){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Clientes/guardarCliente',{
method:'POST',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
},body:JSON.stringify(objetoCliente)
})
.then(res => res.json())
.then(Respuesta => {
/** Se limpia el state */
this.limpiarStateObjeto();
/** Se asigna la informacion del modal para ocultarlo */
this.asignarValorState('mensaje','','modalCargando');
this.asignarValorState('mostrarModal',false,'modalCargando');
/** Se valida para determinar si se realizo el guardado correctamnte o no */
if(Respuesta.objetoStatus.codigoError.split(" ")[0] === "201"){
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'success','showMensaje');
/** Se llama el metodo que se encarga de obtener el total de registros */
this.obtenerConteoClientes();
/** Se llama el metodo que obtendra el listado de los clientes */
this.obtenerListadoClientes();
}else{
this.mostrarControlMensaje(Respuesta.objetoStatus.mensajeError,'danger','showMensaje');
}
})
} |
JavaScript | obtenerConteoClientes(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Clientes/countClientes',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna el conteo */
this.asignarValorState('clavecliente',Respuesta.conteoClave,'variablesVista');
//console.log(this.state.variablesVista);
})
} | obtenerConteoClientes(){
//Realizar la peticion para
fetch(Globales.Host + Globales.Name + Globales.Service + 'Clientes/countClientes',{
method:'GET',
headers:{
'Accept': 'application/json', 'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(Respuesta => {
/** Se asigna el conteo */
this.asignarValorState('clavecliente',Respuesta.conteoClave,'variablesVista');
//console.log(this.state.variablesVista);
})
} |
JavaScript | limpiarStateObjeto(){
this.asignarValorState('id',0,'objCliente');
this.asignarValorState('clavecliente','','objCliente');
this.asignarValorState('nombre','','objCliente');
this.asignarValorState('appaterno','','objCliente');
this.asignarValorState('apmaterno','','objCliente');
this.asignarValorState('rfc','','objCliente');
} | limpiarStateObjeto(){
this.asignarValorState('id',0,'objCliente');
this.asignarValorState('clavecliente','','objCliente');
this.asignarValorState('nombre','','objCliente');
this.asignarValorState('appaterno','','objCliente');
this.asignarValorState('apmaterno','','objCliente');
this.asignarValorState('rfc','','objCliente');
} |
JavaScript | llenarValoresStates(objCliente){
this.asignarValorState('id',objCliente.id,'objCliente');
this.asignarValorState('clavecliente',objCliente.clavecliente,'objCliente');
this.asignarValorState('nombre',objCliente.nombre,'objCliente');
this.asignarValorState('appaterno',objCliente.appaterno,'objCliente');
this.asignarValorState('apmaterno',objCliente.apmaterno,'objCliente');
this.asignarValorState('rfc',objCliente.rfc,'objCliente');
} | llenarValoresStates(objCliente){
this.asignarValorState('id',objCliente.id,'objCliente');
this.asignarValorState('clavecliente',objCliente.clavecliente,'objCliente');
this.asignarValorState('nombre',objCliente.nombre,'objCliente');
this.asignarValorState('appaterno',objCliente.appaterno,'objCliente');
this.asignarValorState('apmaterno',objCliente.apmaterno,'objCliente');
this.asignarValorState('rfc',objCliente.rfc,'objCliente');
} |
JavaScript | calcularInformacionMeses(){
/** Se calcula el valor de precio contado */
var precioContado = (parseFloat(this.props.objInformacionTotal.total) / (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseFloat(this.props.objConfiguracion.plazomaximo)) / parseInt(100)))).toFixed(2);
/** Se asigna el valor al state */
this.asignarValorState('preciocontado',precioContado,'informacionPagosMeses');
/** Se crean los calculos para cada tipo de pago */
this.calcularPagosMeses(3,precioContado);
this.calcularPagosMeses(6,precioContado);
this.calcularPagosMeses(9,precioContado);
this.calcularPagosMeses(12,precioContado);
} | calcularInformacionMeses(){
/** Se calcula el valor de precio contado */
var precioContado = (parseFloat(this.props.objInformacionTotal.total) / (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseFloat(this.props.objConfiguracion.plazomaximo)) / parseInt(100)))).toFixed(2);
/** Se asigna el valor al state */
this.asignarValorState('preciocontado',precioContado,'informacionPagosMeses');
/** Se crean los calculos para cada tipo de pago */
this.calcularPagosMeses(3,precioContado);
this.calcularPagosMeses(6,precioContado);
this.calcularPagosMeses(9,precioContado);
this.calcularPagosMeses(12,precioContado);
} |
JavaScript | calcularPagosMeses(totalMeses,precioContado){
var totalPagar = 0;
var importeAbono = 0;
var importeAhorro = 0;
/** Se realiza la validacion para saber que tipo de calculo se realizara */
if(parseInt(totalMeses) === parseInt(3)){
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(3)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(3)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar3meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono3meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro3meses',importeAhorro,'informacionPagosMeses');
}else{
if(parseInt(totalMeses) === parseInt(6)){
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(6)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(6)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar6meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono6meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro6meses',importeAhorro,'informacionPagosMeses');
}else{
if(parseInt(totalMeses) === parseInt(9)){
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(9)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(9)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar9meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono9meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro9meses',importeAhorro,'informacionPagosMeses');
}else{
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(12)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(12)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar12meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono12meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro12meses',importeAhorro,'informacionPagosMeses');
}
}
}
} | calcularPagosMeses(totalMeses,precioContado){
var totalPagar = 0;
var importeAbono = 0;
var importeAhorro = 0;
/** Se realiza la validacion para saber que tipo de calculo se realizara */
if(parseInt(totalMeses) === parseInt(3)){
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(3)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(3)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar3meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono3meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro3meses',importeAhorro,'informacionPagosMeses');
}else{
if(parseInt(totalMeses) === parseInt(6)){
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(6)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(6)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar6meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono6meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro6meses',importeAhorro,'informacionPagosMeses');
}else{
if(parseInt(totalMeses) === parseInt(9)){
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(9)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(9)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar9meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono9meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro9meses',importeAhorro,'informacionPagosMeses');
}else{
/** Se calcula el total a pagar para 3 meses */
totalPagar = (parseFloat(precioContado) * (parseInt(1) + ((parseFloat(this.props.objConfiguracion.tasafinanciamiento) * parseInt(12)) / parseInt(100)))).toFixed(2);
/** Se calcula el importe de abono para 3 meses */
importeAbono = (parseFloat(totalPagar) / parseInt(12)).toFixed(2);
/** Se calcula el importe ahorra para 3 meses */
importeAhorro = (parseFloat(this.props.objInformacionTotal.total) - parseFloat(totalPagar)).toFixed(2);
/** Se asignan los valores al state */
this.asignarValorState('totalpagar12meses',totalPagar,'informacionPagosMeses');
this.asignarValorState('importeabono12meses',importeAbono,'informacionPagosMeses');
this.asignarValorState('importeahorro12meses',importeAhorro,'informacionPagosMeses');
}
}
}
} |
JavaScript | onClickRadioButton(){
/** Se obtiene el valor que se selecciono */
var radio = document.getElementsByName('example');
/** Se recorre el arreglo de radio buttons */
for(var i=0; i<radio.length; i++){
if(radio[i].checked){
this.props.onClickRadioButton(radio[i].value);
}
}
} | onClickRadioButton(){
/** Se obtiene el valor que se selecciono */
var radio = document.getElementsByName('example');
/** Se recorre el arreglo de radio buttons */
for(var i=0; i<radio.length; i++){
if(radio[i].checked){
this.props.onClickRadioButton(radio[i].value);
}
}
} |
JavaScript | onChange(target,propiedad,objeto){
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
if(propiedad === 'tasafinanciamiento'){
valorPattern = obtenerRegexPattern("precio");
}else{
valorPattern = obtenerRegexPattern("numero");
}
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
} | onChange(target,propiedad,objeto){
/** Eliminar el espacio en blanco solo */
if(target.value.trim() === '' || target.value.trim() === null){
if(target.value.trim() === ''){
document.getElementById(target.id).value = target.value.replace(' ','');
}
/** Se asigna el color rojo para indicar que esta mal */
target.style.borderColor = 'red';
}else{
let valorPattern;
/** Se asigna el color default para indicar que esta bien */
target.style.borderColor = '#E8E8E8';
/** Se valida para determinar que pattern de validacion se obtendra */
if(propiedad === 'tasafinanciamiento'){
valorPattern = obtenerRegexPattern("precio");
}else{
valorPattern = obtenerRegexPattern("numero");
}
/** Se realiza el match para eliminar caracteres no permitidos */
if(target.value.match(valorPattern)){
document.getElementById(target.id).value = target.value.replace(valorPattern,'');
}
}
/** Se asigna el valor al state */
this.asignarValorState(propiedad,target.value,objeto);
} |
JavaScript | validarInformacion(){
if(this.generaValidacionControles() === 0){
/** Se valida si se realizara un guardado o una actualizacion */
if(this.state.objConfiguracion.id === 0){
/** Se realizara un guardado */
return true;
}else{
/** Se llama el metodo que se encargara de indicar si se modifico algo o no */
if(validaStateVsPropObj(this.state.objConfiguracion,this.state.objConfEditar,'configuracion')){
return true;
}else{
/** Se asignan los valores del mensaje */
this.mostrarControlMensaje("Se debe modificar al menos un campo para poder actualizar.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
}
}else{
this.mostrarControlMensaje("Debe proporcionar toda la información.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
} | validarInformacion(){
if(this.generaValidacionControles() === 0){
/** Se valida si se realizara un guardado o una actualizacion */
if(this.state.objConfiguracion.id === 0){
/** Se realizara un guardado */
return true;
}else{
/** Se llama el metodo que se encargara de indicar si se modifico algo o no */
if(validaStateVsPropObj(this.state.objConfiguracion,this.state.objConfEditar,'configuracion')){
return true;
}else{
/** Se asignan los valores del mensaje */
this.mostrarControlMensaje("Se debe modificar al menos un campo para poder actualizar.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
}
}else{
this.mostrarControlMensaje("Debe proporcionar toda la información.", 'danger', 'showMensaje');
/** Se regresa el valor de que no cumplio la condicion */
return false;
}
} |
JavaScript | onClickGuardar(){
if(this.validarInformacion()){
/** Se valida para determinar si se realiza un registro nuevo o actualizacion */
if(this.state.objConfiguracion.id === 0){
/** Se asigna el mensaje de carga */
this.asignarValorState('mensaje','Guardando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se realiza el guardado de la informacion */
this.guardarConfiguracion();
}else{
/** Se asigna el mensaje de carga */
this.asignarValorState('mensaje','Actualizando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se realiza la actualizacion de la informacion */
this.actualizarConfiguracion();
}
}
} | onClickGuardar(){
if(this.validarInformacion()){
/** Se valida para determinar si se realiza un registro nuevo o actualizacion */
if(this.state.objConfiguracion.id === 0){
/** Se asigna el mensaje de carga */
this.asignarValorState('mensaje','Guardando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se realiza el guardado de la informacion */
this.guardarConfiguracion();
}else{
/** Se asigna el mensaje de carga */
this.asignarValorState('mensaje','Actualizando','modalCargando');
this.asignarValorState('mostrarModal',true,'modalCargando');
/** Se realiza la actualizacion de la informacion */
this.actualizarConfiguracion();
}
}
} |
JavaScript | deshabilitarHabilitarInputs(valor){
/** Se deshabilitan o habilitan los inputs */
document.getElementById("txtTFinanciamiento").disabled = valor;
document.getElementById("txtEnganche").disabled = valor;
document.getElementById("txtPlazoMaximo").disabled = valor;
} | deshabilitarHabilitarInputs(valor){
/** Se deshabilitan o habilitan los inputs */
document.getElementById("txtTFinanciamiento").disabled = valor;
document.getElementById("txtEnganche").disabled = valor;
document.getElementById("txtPlazoMaximo").disabled = valor;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.