language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
static killWorker(worker) { logger.debug(`Killing Worker#${worker.id}.`); worker.__closing = true; // eslint-disable-line no-param-reassign const tryTerminate = signal => new Promise((resolve, reject) => { worker.once('exit', resolve); logger.silly(`Killing worker#${worker.id} with ${signal}`); try { worker.kill(signal); } catch (error) { reject(error); } }); return tryTerminate('SIGINT').timeout(Master.SIGINT_TIMEOUT) .catch(Promise.TimeoutError, () => { logger.warn(`Can't kill worker#${worker.id} kindly`); return tryTerminate('SIGTERM').timeout(Master.GIGTERM_TIMEOUT); }) .catch(Promise.TimeoutError, () => { logger.warn(`Can't kill worker#${worker.id} less kindly`); return tryTerminate('SIGKILL').timeout(Master.SIGKILL_TIMEOUT); }) .catch(Promise.TimeoutError, (error) => { logger.error(`Failed to kill Worker#${worker.id}: ${error.message}`); throw error; }) .catch((error) => { logger.warn(`kill throws error: ${error.message}`); throw error; }); }
static killWorker(worker) { logger.debug(`Killing Worker#${worker.id}.`); worker.__closing = true; // eslint-disable-line no-param-reassign const tryTerminate = signal => new Promise((resolve, reject) => { worker.once('exit', resolve); logger.silly(`Killing worker#${worker.id} with ${signal}`); try { worker.kill(signal); } catch (error) { reject(error); } }); return tryTerminate('SIGINT').timeout(Master.SIGINT_TIMEOUT) .catch(Promise.TimeoutError, () => { logger.warn(`Can't kill worker#${worker.id} kindly`); return tryTerminate('SIGTERM').timeout(Master.GIGTERM_TIMEOUT); }) .catch(Promise.TimeoutError, () => { logger.warn(`Can't kill worker#${worker.id} less kindly`); return tryTerminate('SIGKILL').timeout(Master.SIGKILL_TIMEOUT); }) .catch(Promise.TimeoutError, (error) => { logger.error(`Failed to kill Worker#${worker.id}: ${error.message}`); throw error; }) .catch((error) => { logger.warn(`kill throws error: ${error.message}`); throw error; }); }
JavaScript
static killAllWorkers() { logger.info('Killing all workers...'); return Promise.all(_.map(cluster.workers, Master.killWorker)) .then(() => { logger.info('All workers killed.'); }) .catch((error) => { logger.error(error); }); }
static killAllWorkers() { logger.info('Killing all workers...'); return Promise.all(_.map(cluster.workers, Master.killWorker)) .then(() => { logger.info('All workers killed.'); }) .catch((error) => { logger.error(error); }); }
JavaScript
static reloadWorker(worker) { logger.info(`Reloading Worker#${worker.id}.`); return Master.killWorker(worker) .then(() => Master.forkWorker()); }
static reloadWorker(worker) { logger.info(`Reloading Worker#${worker.id}.`); return Master.killWorker(worker) .then(() => Master.forkWorker()); }
JavaScript
static reloadAllWorkers() { logger.info('Restarting all workers...'); return Promise.each(_.values(cluster.workers), Master.reloadWorker) .then(() => { logger.info('All workers restarted.'); }); }
static reloadAllWorkers() { logger.info('Restarting all workers...'); return Promise.each(_.values(cluster.workers), Master.reloadWorker) .then(() => { logger.info('All workers restarted.'); }); }
JavaScript
static createFileListener(dir = '.') { logger.info(`Creating watcher for directory: ${dir}.`); // @note Listeners are created recursively, check amount of created listeners before commiting const options = { ignored: /(^|[/\\])\.|node_modules/, ignoreInitial: true }; const watcher = fileWatcher.watch(dir, options); watcher.on('ready', () => { logger.debug(`File watcher ready, watchers included: ${Object.keys(watcher.getWatched()).length}`); }); watcher.on('error', (error) => { logger.error(`Chokidar reported an error: ${error.message}`); logger.debug(error.stack); }); return watcher; }
static createFileListener(dir = '.') { logger.info(`Creating watcher for directory: ${dir}.`); // @note Listeners are created recursively, check amount of created listeners before commiting const options = { ignored: /(^|[/\\])\.|node_modules/, ignoreInitial: true }; const watcher = fileWatcher.watch(dir, options); watcher.on('ready', () => { logger.debug(`File watcher ready, watchers included: ${Object.keys(watcher.getWatched()).length}`); }); watcher.on('error', (error) => { logger.error(`Chokidar reported an error: ${error.message}`); logger.debug(error.stack); }); return watcher; }
JavaScript
static activateFileListener(watcher) { logger.info('Activating file listener, reloading workers automatically if changes detected.'); const masterFiles = [ path.join('app', 'master.js'), path.join('tools', 'logger'), path.join('tools', 'eventBus'), path.join('tools', 'cluster') ]; const listenedEvents = [ 'change', 'add', 'remove', 'unlinkDir', 'addDir' ]; watcher.on('all', (event, filePath) => { if (listenedEvents.indexOf(event) === -1) { logger.debug(`File event detected ${event}: ${filePath}`); } else if (masterFiles.indexOf(filePath) === -1) { logger.info('File changed, need to reload workers...'); eventBus.emit('workerRestartNeeded', `file changed: ${filePath}`); } else { logger.info(`Internal files (${filePath}) changed, the whole server needs to reset!`); eventBus.emit('systemRestartNeeded', `file changed: ${filePath}`); } }); }
static activateFileListener(watcher) { logger.info('Activating file listener, reloading workers automatically if changes detected.'); const masterFiles = [ path.join('app', 'master.js'), path.join('tools', 'logger'), path.join('tools', 'eventBus'), path.join('tools', 'cluster') ]; const listenedEvents = [ 'change', 'add', 'remove', 'unlinkDir', 'addDir' ]; watcher.on('all', (event, filePath) => { if (listenedEvents.indexOf(event) === -1) { logger.debug(`File event detected ${event}: ${filePath}`); } else if (masterFiles.indexOf(filePath) === -1) { logger.info('File changed, need to reload workers...'); eventBus.emit('workerRestartNeeded', `file changed: ${filePath}`); } else { logger.info(`Internal files (${filePath}) changed, the whole server needs to reset!`); eventBus.emit('systemRestartNeeded', `file changed: ${filePath}`); } }); }
JavaScript
function expectResult(res, targetStatus, targetBody) { if (!(targetBody instanceof Object) && targetBody !== undefined) { logger.error('[Test] Checks for non-object target bodies is not yet implemented'); process.exit(1); } expect(res).to.be.a('Object'); if (res.status === 300) { logger.error('[Test] 300 multiple choices points to an unclean DB'); process.exit(1); } expect(res.status).to.equal(targetStatus); if (targetBody !== undefined) { expect(res.body).to.be.instanceof(Object); expectObjectsToEqual(JSON.parse(JSON.stringify(res.body)), targetBody); } }
function expectResult(res, targetStatus, targetBody) { if (!(targetBody instanceof Object) && targetBody !== undefined) { logger.error('[Test] Checks for non-object target bodies is not yet implemented'); process.exit(1); } expect(res).to.be.a('Object'); if (res.status === 300) { logger.error('[Test] 300 multiple choices points to an unclean DB'); process.exit(1); } expect(res.status).to.equal(targetStatus); if (targetBody !== undefined) { expect(res.body).to.be.instanceof(Object); expectObjectsToEqual(JSON.parse(JSON.stringify(res.body)), targetBody); } }
JavaScript
static readFile(_file) { const file = _file; if (!_.isFunction(file.checksum)) { return Promise.reject(new TypeError('Provided file is not an instance of FileSchema.')); } if (!file.checksum()) { return Promise.reject(new Error('Could not resolve a checksum for the file.')); } logger.info(`Reading file ${file.name} (filename: ${file.checksum()}.${fileEnding}).`); return FileDB._readFile(file.checksum()) .then(FileDB._uncompress) .then((data) => { file.data = data; return file; }); }
static readFile(_file) { const file = _file; if (!_.isFunction(file.checksum)) { return Promise.reject(new TypeError('Provided file is not an instance of FileSchema.')); } if (!file.checksum()) { return Promise.reject(new Error('Could not resolve a checksum for the file.')); } logger.info(`Reading file ${file.name} (filename: ${file.checksum()}.${fileEnding}).`); return FileDB._readFile(file.checksum()) .then(FileDB._uncompress) .then((data) => { file.data = data; return file; }); }
JavaScript
static storeFile(file) { if (!_.isFunction(file.checksum)) { return Promise.reject(new TypeError('Provided file is not an instance of FileSchema.')); } if (!file.checksum()) { return Promise.reject(new Error('Could not resolve a checksum for the file.')); } const fileData = file.data; logger.info(`[${file.name}] storing file, filename: ${file.checksum()}.${fileEnding}.`); return FileDB._checkFilenameAvailability(file.checksum()).then((available) => { if (available) { return FileDB._compress(fileData).then((compressedData) => { const filename = file.checksum(); return FileDB._writeFile(filename, compressedData); }); } logger.warn('File already exists, no need to store a duplicate.'); return Promise.resolve(); }); }
static storeFile(file) { if (!_.isFunction(file.checksum)) { return Promise.reject(new TypeError('Provided file is not an instance of FileSchema.')); } if (!file.checksum()) { return Promise.reject(new Error('Could not resolve a checksum for the file.')); } const fileData = file.data; logger.info(`[${file.name}] storing file, filename: ${file.checksum()}.${fileEnding}.`); return FileDB._checkFilenameAvailability(file.checksum()).then((available) => { if (available) { return FileDB._compress(fileData).then((compressedData) => { const filename = file.checksum(); return FileDB._writeFile(filename, compressedData); }); } logger.warn('File already exists, no need to store a duplicate.'); return Promise.resolve(); }); }
JavaScript
static _checkFilenameAvailability(filename) { const filePath = FileDB._resolveFilePath(filename); logger.debug(`Checking if file exists in path: ${filePath}.`); return fs.exists(filePath).then((exists) => { if (exists) logger.debug(`File ${filename} already exists in path: ${filePath}.`); else logger.debug(`Path: ${filePath} is confirmed to be empty.`); // eslint-disable-line return !exists; }); }
static _checkFilenameAvailability(filename) { const filePath = FileDB._resolveFilePath(filename); logger.debug(`Checking if file exists in path: ${filePath}.`); return fs.exists(filePath).then((exists) => { if (exists) logger.debug(`File ${filename} already exists in path: ${filePath}.`); else logger.debug(`Path: ${filePath} is confirmed to be empty.`); // eslint-disable-line return !exists; }); }
JavaScript
static _readFile(filename) { const filePath = FileDB._resolveFilePath(filename); logger.debug(`Reading file from file system with path: ${filePath}.`); return fs.readFile(filePath).then((dataBuffer) => { logger.debug(`Read file (filename: ${filename} size: ${dataBuffer.size}).`); return dataBuffer; }).catch((error) => { const errorMessage = `Could not read file with path: ${filePath}, error: ${error.message}.`; logger.warn(errorMessage); throw error; }); }
static _readFile(filename) { const filePath = FileDB._resolveFilePath(filename); logger.debug(`Reading file from file system with path: ${filePath}.`); return fs.readFile(filePath).then((dataBuffer) => { logger.debug(`Read file (filename: ${filename} size: ${dataBuffer.size}).`); return dataBuffer; }).catch((error) => { const errorMessage = `Could not read file with path: ${filePath}, error: ${error.message}.`; logger.warn(errorMessage); throw error; }); }
JavaScript
static _writeFile(filename, data) { const filePath = FileDB._resolveFilePath(filename); // Ensure there is data to write if (!data) { const errorMessage = `Cannot write file, no data defined, received: ${data}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); } logger.debug(`Writing file to file system with path: ${filePath}.`); return fs.writeFile(filePath, data).then(() => { logger.debug(`Wrote file (filename: ${filename} size: ${data.length || '0'}).`); }).catch((error) => { const errorMessage = `Could not write data to path: ${filePath}, error: ${error.message}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); }); }
static _writeFile(filename, data) { const filePath = FileDB._resolveFilePath(filename); // Ensure there is data to write if (!data) { const errorMessage = `Cannot write file, no data defined, received: ${data}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); } logger.debug(`Writing file to file system with path: ${filePath}.`); return fs.writeFile(filePath, data).then(() => { logger.debug(`Wrote file (filename: ${filename} size: ${data.length || '0'}).`); }).catch((error) => { const errorMessage = `Could not write data to path: ${filePath}, error: ${error.message}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); }); }
JavaScript
static _compress(uncompressedData) { // Ensure there is data to write if (!uncompressedData) { const errorMessage = `Failed to compress, no data provided, received: ${uncompressedData}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); } return new Promise((resolve, reject) => { logger.debug(`Compressing data of size: ${uncompressedData.length}.`); zlib.gzip(uncompressedData, (error, compressedData) => { if (error) { const errorMessage = `Could not compress file, error with message: ${error.message}.`; logger.warn(errorMessage); return reject(errorMessage); } logger.verbose('Compress result:'); logger.verbose(` uncompressed size: ${uncompressedData.length}`); logger.verbose(` compressed size : ${compressedData.length}`); return resolve(compressedData); }); return undefined; }); }
static _compress(uncompressedData) { // Ensure there is data to write if (!uncompressedData) { const errorMessage = `Failed to compress, no data provided, received: ${uncompressedData}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); } return new Promise((resolve, reject) => { logger.debug(`Compressing data of size: ${uncompressedData.length}.`); zlib.gzip(uncompressedData, (error, compressedData) => { if (error) { const errorMessage = `Could not compress file, error with message: ${error.message}.`; logger.warn(errorMessage); return reject(errorMessage); } logger.verbose('Compress result:'); logger.verbose(` uncompressed size: ${uncompressedData.length}`); logger.verbose(` compressed size : ${compressedData.length}`); return resolve(compressedData); }); return undefined; }); }
JavaScript
static _uncompress(compressedData) { // Ensure there is data to write if (!compressedData) { const errorMessage = `Failed to uncompress, no data provided, received: ${compressedData}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); } return new Promise((resolve, reject) => { logger.debug(`Uncompressing data of size: ${compressedData.length}.`); zlib.gunzip(compressedData, (error, uncompressedData) => { if (error) { const errorMessage = `Could not uncompress, error with message: ${error.message}.`; logger.warn(errorMessage); return reject(errorMessage); } logger.verbose('Uncompress result:'); logger.verbose(` compressed size : ${compressedData.length}`); logger.verbose(` uncompressed size: ${uncompressedData.length}`); return resolve(uncompressedData.toString(usedEncoding)); }); return undefined; }); }
static _uncompress(compressedData) { // Ensure there is data to write if (!compressedData) { const errorMessage = `Failed to uncompress, no data provided, received: ${compressedData}.`; logger.warn(errorMessage); return Promise.reject(new Error(errorMessage)); } return new Promise((resolve, reject) => { logger.debug(`Uncompressing data of size: ${compressedData.length}.`); zlib.gunzip(compressedData, (error, uncompressedData) => { if (error) { const errorMessage = `Could not uncompress, error with message: ${error.message}.`; logger.warn(errorMessage); return reject(errorMessage); } logger.verbose('Uncompress result:'); logger.verbose(` compressed size : ${compressedData.length}`); logger.verbose(` uncompressed size: ${uncompressedData.length}`); return resolve(uncompressedData.toString(usedEncoding)); }); return undefined; }); }
JavaScript
static _resolveFilePath(filename) { if (!filename) { const errorMessage = `cannot resolve filename, no name provided, received: ${filename}`; logger.warn(errorMessage); throw new Error(errorMessage); } logger.verbose(`resolving filePath from filedb: ${filedb} and filename: ${filename} with ending: ${fileEnding}`); return path.join(filedb, `${filename}.${fileEnding}`); }
static _resolveFilePath(filename) { if (!filename) { const errorMessage = `cannot resolve filename, no name provided, received: ${filename}`; logger.warn(errorMessage); throw new Error(errorMessage); } logger.verbose(`resolving filePath from filedb: ${filedb} and filename: ${filename} with ending: ${fileEnding}`); return path.join(filedb, `${filename}.${fileEnding}`); }
JavaScript
router(req, res, next) { const resolveRoute = (router, reqParam, resParam, nextParam) => { router(reqParam, resParam, nextParam); }; const routers = this.addonRouters.map(addonRouter => resolveRoute.bind(this, addonRouter.router, req, res)); async.waterfall(routers, next); }
router(req, res, next) { const resolveRoute = (router, reqParam, resParam, nextParam) => { router(reqParam, resParam, nextParam); }; const routers = this.addonRouters.map(addonRouter => resolveRoute.bind(this, addonRouter.router, req, res)); async.waterfall(routers, next); }
JavaScript
removeRouter(addon) { for (let i = 0; i < this.addonRouters.length; i += 1) { if (this.addonRouters[i].addon.name === addon.name) { this.addonRouters.splice(i, 1); logger.debug(`Removed router for addon: ${addon.name}.`); return; } } logger.warn(`Could not find and remove router for addon: ${addon.name}.`); }
removeRouter(addon) { for (let i = 0; i < this.addonRouters.length; i += 1) { if (this.addonRouters[i].addon.name === addon.name) { this.addonRouters.splice(i, 1); logger.debug(`Removed router for addon: ${addon.name}.`); return; } } logger.warn(`Could not find and remove router for addon: ${addon.name}.`); }
JavaScript
static checkOrganization(oauth2, accessToken) { logger.debug('fetching list of organizations user belongs to.'); const {organization} = nconf.get('github'); if (!organization) { logger.warn('github organization is not configured - assuming anybody can login'); return Promise.resolve(); } logger.verbose('requesting organization information.'); const orgUrl = `${userApiUrl}/orgs`; return new Promise((resolve, reject) => { oauth2.get(orgUrl, accessToken, (error, body, res) => { if (error) { let message = 'cannot read organization'; try { const json = JSON.parse(error.data); message = json.message || message; } catch (parseError) { logger.debug('json parse error: ', parseError); } const err = new Error(message); err.statusCode = error.statusCode || 500; return reject(err); } try { logger.silly(`${orgUrl} - statusCode: ${res.statusCode}`); return resolve(JSON.parse(body)); } catch (parseError) { return reject(new Error(`Failed to parse user profile: ${parseError}`)); } }); }) .then((org) => { // Attempt to find the defined organization from a list of the users organizations const belongsOrg = _.find(org, {login: organization}); if (!belongsOrg) { logger.warn(`user not in ${organization} organization.`); throw new Error(`You do not have required access to ${organization}.`); } logger.verbose('user belongs to ' + `organization: ${organization} - OK`); return belongsOrg; }); }
static checkOrganization(oauth2, accessToken) { logger.debug('fetching list of organizations user belongs to.'); const {organization} = nconf.get('github'); if (!organization) { logger.warn('github organization is not configured - assuming anybody can login'); return Promise.resolve(); } logger.verbose('requesting organization information.'); const orgUrl = `${userApiUrl}/orgs`; return new Promise((resolve, reject) => { oauth2.get(orgUrl, accessToken, (error, body, res) => { if (error) { let message = 'cannot read organization'; try { const json = JSON.parse(error.data); message = json.message || message; } catch (parseError) { logger.debug('json parse error: ', parseError); } const err = new Error(message); err.statusCode = error.statusCode || 500; return reject(err); } try { logger.silly(`${orgUrl} - statusCode: ${res.statusCode}`); return resolve(JSON.parse(body)); } catch (parseError) { return reject(new Error(`Failed to parse user profile: ${parseError}`)); } }); }) .then((org) => { // Attempt to find the defined organization from a list of the users organizations const belongsOrg = _.find(org, {login: organization}); if (!belongsOrg) { logger.warn(`user not in ${organization} organization.`); throw new Error(`You do not have required access to ${organization}.`); } logger.verbose('user belongs to ' + `organization: ${organization} - OK`); return belongsOrg; }); }
JavaScript
static checkAdmin(oauth2, accessToken) { logger.debug('checking if the user is in the administrator team.'); logger.verbose('requesting list of teams where user is a member.'); const teamUrl = `${userApiUrl}/teams`; return new Promise((resolve, reject) => { oauth2.get(teamUrl, accessToken, (err, body, res) => { if (err) { return reject(new Error(`Failed to fetch user profile: ${teamUrl} ${err}`)); } try { logger.silly(`${teamUrl} - statusCode: ${res.statusCode}`); return resolve(JSON.parse(body)); } catch (ex) { return reject(new Error('Failed to parse user profile')); } }); }) .then((teams) => { logger.verbose(`response from: ${teamUrl} received - OK`); const {adminTeam, organization} = nconf.get('github'); // Attempt to find the correct admin team from list of teams the user belongs to const isAdmin = _.find(teams, team => (team.name === adminTeam && team.organization.login === organization)); logger.verbose(`user ${isAdmin ? 'belongs' : 'does not belong'} to admin team: ${adminTeam}`); return !!isAdmin; }); }
static checkAdmin(oauth2, accessToken) { logger.debug('checking if the user is in the administrator team.'); logger.verbose('requesting list of teams where user is a member.'); const teamUrl = `${userApiUrl}/teams`; return new Promise((resolve, reject) => { oauth2.get(teamUrl, accessToken, (err, body, res) => { if (err) { return reject(new Error(`Failed to fetch user profile: ${teamUrl} ${err}`)); } try { logger.silly(`${teamUrl} - statusCode: ${res.statusCode}`); return resolve(JSON.parse(body)); } catch (ex) { return reject(new Error('Failed to parse user profile')); } }); }) .then((teams) => { logger.verbose(`response from: ${teamUrl} received - OK`); const {adminTeam, organization} = nconf.get('github'); // Attempt to find the correct admin team from list of teams the user belongs to const isAdmin = _.find(teams, team => (team.name === adminTeam && team.organization.login === organization)); logger.verbose(`user ${isAdmin ? 'belongs' : 'does not belong'} to admin team: ${adminTeam}`); return !!isAdmin; }); }
JavaScript
static updateUsersGroup(user, groupname) { logger.debug('updating user\'s group to match current status.'); if (groupname !== 'admins') { logger.info(`removing user: ${user._id} from admins.`); return user.isAdmin() .then((isAdmin) => { if (isAdmin) { return user.removeFromGroup('admins'); } return user.save(); }); } else if (groupname === 'admins') { logger.info(`adding user: ${user._id} to admins.`); return user.addToGroup(groupname); } logger.verbose(`user is in the correct group: ${groupname}.`); return user.save(); }
static updateUsersGroup(user, groupname) { logger.debug('updating user\'s group to match current status.'); if (groupname !== 'admins') { logger.info(`removing user: ${user._id} from admins.`); return user.isAdmin() .then((isAdmin) => { if (isAdmin) { return user.removeFromGroup('admins'); } return user.save(); }); } else if (groupname === 'admins') { logger.info(`adding user: ${user._id} to admins.`); return user.addToGroup(groupname); } logger.verbose(`user is in the correct group: ${groupname}.`); return user.save(); }
JavaScript
paramCollection(req, res, next, collectionName) { const schema = this.schemas[collectionName]; if (schema) { req.Schema = schema; return next(); } return res.status(404).json({error: `No schema found with name: ${collectionName}`}); }
paramCollection(req, res, next, collectionName) { const schema = this.schemas[collectionName]; if (schema) { req.Schema = schema; return next(); } return res.status(404).json({error: `No schema found with name: ${collectionName}`}); }
JavaScript
function argumenFuncsContohDua() { // eslint-disable-next-line prefer-rest-params console.log('Contoh arguments di dalam fungsi biasa', arguments); // eslint-disable-next-line prefer-rest-params const nilaiArgumen = [...arguments]; console.log(nilaiArgumen); }
function argumenFuncsContohDua() { // eslint-disable-next-line prefer-rest-params console.log('Contoh arguments di dalam fungsi biasa', arguments); // eslint-disable-next-line prefer-rest-params const nilaiArgumen = [...arguments]; console.log(nilaiArgumen); }
JavaScript
function namaLengkap(first, last, ...gelars) { console.log('Nama depan', first); console.log('Nama belakang', last); console.log('Daftar gelar', gelars); }
function namaLengkap(first, last, ...gelars) { console.log('Nama depan', first); console.log('Nama belakang', last); console.log('Daftar gelar', gelars); }
JavaScript
function isValidasiPassword(username = '', password = '') { if (password.length < 8) { return false; } if (password.indexOf(' ') !== -1) { return false; } if (password.indexOf(username) !== -1) { return false; } return true; }
function isValidasiPassword(username = '', password = '') { if (password.length < 8) { return false; } if (password.indexOf(' ') !== -1) { return false; } if (password.indexOf(username) !== -1) { return false; } return true; }
JavaScript
function cekStatusRentang(nilaiAwal, nilaiAkhir) { return function(nilaiUji) { const isRentang = nilaiAwal <= nilaiUji && nilaiUji <= nilaiAkhir; return isRentang; }; }
function cekStatusRentang(nilaiAwal, nilaiAkhir) { return function(nilaiUji) { const isRentang = nilaiAwal <= nilaiUji && nilaiUji <= nilaiAkhir; return isRentang; }; }
JavaScript
function isArgValid (item,cb){ if (item !== undefined && item.indexOf('-') !== 0){ cb(true); }else{ cb(false); } }
function isArgValid (item,cb){ if (item !== undefined && item.indexOf('-') !== 0){ cb(true); }else{ cb(false); } }
JavaScript
function isPathValid(path){ fs.stat(path, function(err, stats){ if (err){ console.log('Error in path ' + '"' + path + '"'); process.exit(1); } if (stats.isFile()){ console.log("Error in path " + '"' + path + '"' + ". Should be a directory not a File."); process.exit(1); } }); }
function isPathValid(path){ fs.stat(path, function(err, stats){ if (err){ console.log('Error in path ' + '"' + path + '"'); process.exit(1); } if (stats.isFile()){ console.log("Error in path " + '"' + path + '"' + ". Should be a directory not a File."); process.exit(1); } }); }
JavaScript
function isFolderForTvShows(folder,cb){ tvshows.forEach(function(tvshow){ //Seperate words of tv show var tokens = tvshow.split(tvShowSeparators); var isTvShowInFolder = true; // Check if tokens are in folder tokens.forEach(function(word){ //If one word is not in folder name if(folder.toUpperCase().indexOf(word.toUpperCase()) === -1){ isTvShowInFolder = false; } }); if (isTvShowInFolder) //console.log(tvshow + ' / ' + folder + ' -> ' + isTvShowInFolder); cb(folder,tvshow); }); }
function isFolderForTvShows(folder,cb){ tvshows.forEach(function(tvshow){ //Seperate words of tv show var tokens = tvshow.split(tvShowSeparators); var isTvShowInFolder = true; // Check if tokens are in folder tokens.forEach(function(word){ //If one word is not in folder name if(folder.toUpperCase().indexOf(word.toUpperCase()) === -1){ isTvShowInFolder = false; } }); if (isTvShowInFolder) //console.log(tvshow + ' / ' + folder + ' -> ' + isTvShowInFolder); cb(folder,tvshow); }); }
JavaScript
function addEmployee() { const managersArr = []; function selectManager() { connection.promise().query("SELECT first_name, last_name FROM employee WHERE manager_id IS NULL", function(err, res) { if (err) throw err; for (var i = 0; i < res.length; i++) { managersArr.push(res[i].first_name + ' ' + res[i].last_name); } }) return managersArr; } const roleArr = []; function selectRole() { connection.promise().query("SELECT * FROM role", function(err, res) { if (err) throw err for (var i = 0; i < res.length; i++) { roleArr.push(res[i].title); } }) return roleArr; } inquirer.prompt([ { name: "firstname", type: "input", message: "Enter employee's first name." }, { name: "lastname", type: "input", message: "Enter employee's last name. " }, { name: "role", type: "list", message: "What is their role? ", choices: selectRole() }, { name: "manager", type: "list", message: "Whats their managers name?", choices: selectManager() } ]).then(function(answer) { let role = selectRole().indexOf(answer.role) + 1 let manager = selectManager().indexOf(answer.manager) + 1 connection.query("INSERT INTO employee SET ?", { first_name: answer.firstname, last_name: answer.lastname, role_id: role, manager_id: manager }, function(err) { if (err) throw err; }) console.table(answer.firstname + ' ' + answer.lastname + " has been added to the employees list!") promptReturn(); }) }
function addEmployee() { const managersArr = []; function selectManager() { connection.promise().query("SELECT first_name, last_name FROM employee WHERE manager_id IS NULL", function(err, res) { if (err) throw err; for (var i = 0; i < res.length; i++) { managersArr.push(res[i].first_name + ' ' + res[i].last_name); } }) return managersArr; } const roleArr = []; function selectRole() { connection.promise().query("SELECT * FROM role", function(err, res) { if (err) throw err for (var i = 0; i < res.length; i++) { roleArr.push(res[i].title); } }) return roleArr; } inquirer.prompt([ { name: "firstname", type: "input", message: "Enter employee's first name." }, { name: "lastname", type: "input", message: "Enter employee's last name. " }, { name: "role", type: "list", message: "What is their role? ", choices: selectRole() }, { name: "manager", type: "list", message: "Whats their managers name?", choices: selectManager() } ]).then(function(answer) { let role = selectRole().indexOf(answer.role) + 1 let manager = selectManager().indexOf(answer.manager) + 1 connection.query("INSERT INTO employee SET ?", { first_name: answer.firstname, last_name: answer.lastname, role_id: role, manager_id: manager }, function(err) { if (err) throw err; }) console.table(answer.firstname + ' ' + answer.lastname + " has been added to the employees list!") promptReturn(); }) }
JavaScript
function updateEmployee() { var employeeQuery =`SELECT employee.id, first_name, last_name, role.title FROM employee JOIN role ON employee.role_id = role.id`; connection.query(employeeQuery, function (err, res) { if (err) throw err; const employeeChoices = res.map(({ id, first_name, last_name }) => ({ value: id, name: `${first_name} ${last_name}` })); var roleQuery = `SELECT id, title FROM role` let roleChoices; connection.query(roleQuery, function (err, res) { if (err) throw err; roleChoices = res.map(({ id, title }) => ({ value: id + " " + title })); inquirer.prompt([ { type: "list", name: "employeeId", message: "Which employee do you want to set with the role?", choices: employeeChoices }, { type: "list", name: "roleId", message: "Which role do you want to update?", choices: roleChoices }, ]) .then(function (answer) { role = answer.roleId.split(" "); var query = `UPDATE employee SET role_id = ? WHERE id = ?` // when finished prompting, insert a new item into the db with that info connection.query(query, [role[0], answer.employeeId ], function (err, res) { if (err) throw err; promptReturn(); }); }); }); }) }
function updateEmployee() { var employeeQuery =`SELECT employee.id, first_name, last_name, role.title FROM employee JOIN role ON employee.role_id = role.id`; connection.query(employeeQuery, function (err, res) { if (err) throw err; const employeeChoices = res.map(({ id, first_name, last_name }) => ({ value: id, name: `${first_name} ${last_name}` })); var roleQuery = `SELECT id, title FROM role` let roleChoices; connection.query(roleQuery, function (err, res) { if (err) throw err; roleChoices = res.map(({ id, title }) => ({ value: id + " " + title })); inquirer.prompt([ { type: "list", name: "employeeId", message: "Which employee do you want to set with the role?", choices: employeeChoices }, { type: "list", name: "roleId", message: "Which role do you want to update?", choices: roleChoices }, ]) .then(function (answer) { role = answer.roleId.split(" "); var query = `UPDATE employee SET role_id = ? WHERE id = ?` // when finished prompting, insert a new item into the db with that info connection.query(query, [role[0], answer.employeeId ], function (err, res) { if (err) throw err; promptReturn(); }); }); }); }) }
JavaScript
function copyDate() { date = new Date(); year = date.getFullYear(); $("#copydate").html("<p>&copy; " + year + " WMTU 91.9 FM Houghton, Michigan Technological University</p>"); }
function copyDate() { date = new Date(); year = date.getFullYear(); $("#copydate").html("<p>&copy; " + year + " WMTU 91.9 FM Houghton, Michigan Technological University</p>"); }
JavaScript
function stream() { if ( stream_id == null || sound.state() == "unloaded" || sound.playing(stream_id) == false ) { console.log("\nPlaying stream...\n"); stream_id = sound.play(); $("#play_button").attr('style', 'background: black; color: #ffcd00;'); $("#play_button").html('&#x23F9;'); $(document).attr('title', 'WMTU 91.9 FM ▶️'); } else { console.log("\nStopping stream...\n"); stream_id = sound.stop(); sound.unload(); $("#play_button").removeAttr('style'); $("#play_button").html('&#x25B6;'); $(document).attr('title', 'WMTU 91.9 FM'); } }
function stream() { if ( stream_id == null || sound.state() == "unloaded" || sound.playing(stream_id) == false ) { console.log("\nPlaying stream...\n"); stream_id = sound.play(); $("#play_button").attr('style', 'background: black; color: #ffcd00;'); $("#play_button").html('&#x23F9;'); $(document).attr('title', 'WMTU 91.9 FM ▶️'); } else { console.log("\nStopping stream...\n"); stream_id = sound.stop(); sound.unload(); $("#play_button").removeAttr('style'); $("#play_button").html('&#x25B6;'); $(document).attr('title', 'WMTU 91.9 FM'); } }
JavaScript
function selectInputFile(selectedBtn, inputFile) { let selectBtn = $(selectedBtn), file = $(inputFile); selectBtn.on('click', function () { $(file).click(); $(file).on('change', function () { let fileName = this.files[0].name; selectBtn.text(fileName); let fileReader = new FileReader(); fileReader.onload = function () { $(file).next('img').attr('src', this.result); $(file).next('img').removeAttr('hidden'); } fileReader.readAsDataURL(this.files[0]) }) }) }
function selectInputFile(selectedBtn, inputFile) { let selectBtn = $(selectedBtn), file = $(inputFile); selectBtn.on('click', function () { $(file).click(); $(file).on('change', function () { let fileName = this.files[0].name; selectBtn.text(fileName); let fileReader = new FileReader(); fileReader.onload = function () { $(file).next('img').attr('src', this.result); $(file).next('img').removeAttr('hidden'); } fileReader.readAsDataURL(this.files[0]) }) }) }
JavaScript
function selectInputFile(selectedBtn, inputFile) { var selectBtn = $(selectedBtn), file = $(inputFile); selectBtn.on('click', function () { $(file).click(); $(file).on('change', function () { var fileName = this.files[0].name; selectBtn.text(fileName); var fileReader = new FileReader(); fileReader.onload = function () { $(file).next('img').attr('src', this.result); $(file).next('img').removeAttr('hidden'); }; fileReader.readAsDataURL(this.files[0]); }); }); }
function selectInputFile(selectedBtn, inputFile) { var selectBtn = $(selectedBtn), file = $(inputFile); selectBtn.on('click', function () { $(file).click(); $(file).on('change', function () { var fileName = this.files[0].name; selectBtn.text(fileName); var fileReader = new FileReader(); fileReader.onload = function () { $(file).next('img').attr('src', this.result); $(file).next('img').removeAttr('hidden'); }; fileReader.readAsDataURL(this.files[0]); }); }); }
JavaScript
startPtyProcess() { this.ptyProcess = pty.spawn(this.shell, [], { name: "xterm-color", cwd: process.env.HOME, // Which path should terminal start env: process.env // Pass environment variables }); // Add a "data" event listener. this.ptyProcess.on("data", data => { // Whenever terminal generates any data, send that output to socket.io client to display on UI this.sendToClient(data); }); }
startPtyProcess() { this.ptyProcess = pty.spawn(this.shell, [], { name: "xterm-color", cwd: process.env.HOME, // Which path should terminal start env: process.env // Pass environment variables }); // Add a "data" event listener. this.ptyProcess.on("data", data => { // Whenever terminal generates any data, send that output to socket.io client to display on UI this.sendToClient(data); }); }
JavaScript
function filter_list(l) { return l.filter(function (item) { return typeof item === 'number'; }); }
function filter_list(l) { return l.filter(function (item) { return typeof item === 'number'; }); }
JavaScript
function displayActions() { let attackAction = document.createElement("button") attackAction.id = "Attack_button" attackAction.innerText = "Attack" gameArea.appendChild(attackAction) attackAction.addEventListener("click", function() { playerTurn("attack") }) // let defendAction = document.createElement("button") // defendAction.innerText = "Defend" // gameArea.appendChild(defendAction) // defendAction.addEventListener("click", function() { // playerTurn("defend") // }) let healAction = document.createElement("button") healAction.id = "Heal_button" healAction.innerText = "Heal" gameArea.appendChild(healAction) healAction.addEventListener("click", function() { playerTurn("heal") }) let dialogueBox = document.createElement("div") dialogueBox.id = "Log_box" dialogueBox.innerText = "Choose your action" gameArea.appendChild(dialogueBox) }
function displayActions() { let attackAction = document.createElement("button") attackAction.id = "Attack_button" attackAction.innerText = "Attack" gameArea.appendChild(attackAction) attackAction.addEventListener("click", function() { playerTurn("attack") }) // let defendAction = document.createElement("button") // defendAction.innerText = "Defend" // gameArea.appendChild(defendAction) // defendAction.addEventListener("click", function() { // playerTurn("defend") // }) let healAction = document.createElement("button") healAction.id = "Heal_button" healAction.innerText = "Heal" gameArea.appendChild(healAction) healAction.addEventListener("click", function() { playerTurn("heal") }) let dialogueBox = document.createElement("div") dialogueBox.id = "Log_box" dialogueBox.innerText = "Choose your action" gameArea.appendChild(dialogueBox) }
JavaScript
function playerTurn(action) { switch (action) { case "heal": if (myHero.hp > myHero.maxHP - Math.floor(myHero.maxHP * .3)) { myHero.hp = myHero.maxHP } else { myHero.hp += Math.ceil(myHero.maxHP * .3) } refreshCard("player") updateText("You have healed") break; case "attack": myEnemy.hp = myEnemy.hp - myHero.attack refreshCard("enemy") updateText(`You attack the ${myEnemy.name}!`) // break; // case "defend": // console.log(`Enemy has defended`) } document.querySelector("#Attack_button").style.display = "none" document.querySelector("#Heal_button").style.display = "none" checkIfDead(myEnemy)//Passing the enemy to this function calls the enemies turn if the enemy is still alive }
function playerTurn(action) { switch (action) { case "heal": if (myHero.hp > myHero.maxHP - Math.floor(myHero.maxHP * .3)) { myHero.hp = myHero.maxHP } else { myHero.hp += Math.ceil(myHero.maxHP * .3) } refreshCard("player") updateText("You have healed") break; case "attack": myEnemy.hp = myEnemy.hp - myHero.attack refreshCard("enemy") updateText(`You attack the ${myEnemy.name}!`) // break; // case "defend": // console.log(`Enemy has defended`) } document.querySelector("#Attack_button").style.display = "none" document.querySelector("#Heal_button").style.display = "none" checkIfDead(myEnemy)//Passing the enemy to this function calls the enemies turn if the enemy is still alive }
JavaScript
function enemyTurn() { let enemyActions = ["attack", "miss", "heal"] let actions = enemyActions.length let i = Math.floor(Math.random() * actions) let action = enemyActions[i] switch (action) { case "heal": if (myEnemy.hp > myEnemy.maxHP - Math.floor(myEnemy.maxHP * .4)) { myEnemy.hp = myEnemy.maxHP } else { myEnemy.hp += Math.ceil(myEnemy.maxHP * .4) } refreshCard("enemy") updateText(`${myEnemy.name} has healed.`) break; case "attack": myHero.hp = myHero.hp - myEnemy.attack refreshCard("player") updateText(`${myEnemy.name} attacks you!`) break; case "miss": updateText(`${myEnemy.name} has missed...`) } checkIfDead(myHero) setTimeout( function() { document.querySelector("#Attack_button").style.display = "" document.querySelector("#Heal_button").style.display = "" }, 500) }
function enemyTurn() { let enemyActions = ["attack", "miss", "heal"] let actions = enemyActions.length let i = Math.floor(Math.random() * actions) let action = enemyActions[i] switch (action) { case "heal": if (myEnemy.hp > myEnemy.maxHP - Math.floor(myEnemy.maxHP * .4)) { myEnemy.hp = myEnemy.maxHP } else { myEnemy.hp += Math.ceil(myEnemy.maxHP * .4) } refreshCard("enemy") updateText(`${myEnemy.name} has healed.`) break; case "attack": myHero.hp = myHero.hp - myEnemy.attack refreshCard("player") updateText(`${myEnemy.name} attacks you!`) break; case "miss": updateText(`${myEnemy.name} has missed...`) } checkIfDead(myHero) setTimeout( function() { document.querySelector("#Attack_button").style.display = "" document.querySelector("#Heal_button").style.display = "" }, 500) }
JavaScript
function checkIfDead(character) { if (myHero.hp < 1) { setTimeout( function() { alert(`You have died. Game Over.`) }, 500) endgame() } if (myEnemy.hp < 1) { currentPlayer.score += myEnemy.points alert(`You defeated ${myEnemy.name} and earned ${myEnemy.points} points!`) document.getElementById("your_score").children.current_score.innerText = currentPlayer.score document.querySelector("#Attack_button").style.display = "" document.querySelector("#Heal_button").style.display = "" fetcher(ENEMY_URL, buildCards) drawNewEnemy(enemyCards) } else if (character === myEnemy){ refreshCard("player") setTimeout( function() { enemyTurn() }, 1000) } }
function checkIfDead(character) { if (myHero.hp < 1) { setTimeout( function() { alert(`You have died. Game Over.`) }, 500) endgame() } if (myEnemy.hp < 1) { currentPlayer.score += myEnemy.points alert(`You defeated ${myEnemy.name} and earned ${myEnemy.points} points!`) document.getElementById("your_score").children.current_score.innerText = currentPlayer.score document.querySelector("#Attack_button").style.display = "" document.querySelector("#Heal_button").style.display = "" fetcher(ENEMY_URL, buildCards) drawNewEnemy(enemyCards) } else if (character === myEnemy){ refreshCard("player") setTimeout( function() { enemyTurn() }, 1000) } }
JavaScript
function endgame() { while (gameArea.hasChildNodes()) { gameArea.removeChild(gameArea.firstChild) } let gameOver = document.createElement("h2") gameOver.innerText = "Game Over!" let yourScore = document.createElement("h3") yourScore.innerText = `Your Score: ${currentPlayer.score}` gameOver.appendChild(yourScore) if (currentPlayer.score > currentPlayer.top_score) { currentPlayer.top_score = currentPlayer.score currentPlayer.savePlayer() } let restart = document.createElement("button") restart.innerText = "Play again?" restart.addEventListener('click', function() { restartGame() }) gameOver.appendChild(restart) gameArea.appendChild(gameOver) }
function endgame() { while (gameArea.hasChildNodes()) { gameArea.removeChild(gameArea.firstChild) } let gameOver = document.createElement("h2") gameOver.innerText = "Game Over!" let yourScore = document.createElement("h3") yourScore.innerText = `Your Score: ${currentPlayer.score}` gameOver.appendChild(yourScore) if (currentPlayer.score > currentPlayer.top_score) { currentPlayer.top_score = currentPlayer.score currentPlayer.savePlayer() } let restart = document.createElement("button") restart.innerText = "Play again?" restart.addEventListener('click', function() { restartGame() }) gameOver.appendChild(restart) gameArea.appendChild(gameOver) }
JavaScript
function restartGame() { while (gameArea.hasChildNodes()) { gameArea.removeChild(gameArea.firstChild) } fetcher(ENEMY_URL, buildCards) fetcher(HERO_URL, buildCards) currentPlayer.score = 0 document.getElementById("your_score").children.current_score.innerText = currentPlayer.score startGame() }
function restartGame() { while (gameArea.hasChildNodes()) { gameArea.removeChild(gameArea.firstChild) } fetcher(ENEMY_URL, buildCards) fetcher(HERO_URL, buildCards) currentPlayer.score = 0 document.getElementById("your_score").children.current_score.innerText = currentPlayer.score startGame() }
JavaScript
function buildCards(URL) { if (URL[0].points) { enemyCards = [] } else { heroCards = [] } for(const character of URL) { if(character.points){ let enemy = new Enemy(character.id, character.name, character.hp, character.attack, character.points) enemyCards.push(enemy) } else { let hero = new Hero(character.id, character.name, character.hp, character.attack) heroCards.push(hero) } } }
function buildCards(URL) { if (URL[0].points) { enemyCards = [] } else { heroCards = [] } for(const character of URL) { if(character.points){ let enemy = new Enemy(character.id, character.name, character.hp, character.attack, character.points) enemyCards.push(enemy) } else { let hero = new Hero(character.id, character.name, character.hp, character.attack) heroCards.push(hero) } } }
JavaScript
function drawCard(cardDeck) { let totalCards = cardDeck.length let i = Math.floor(Math.random() * totalCards) let card = cardDeck[i] let characterDiv = document.createElement("div") characterDiv.className = "card" //Determines whether the card is for an enemy or a hero if (card instanceof Enemy) { myEnemy = card characterDiv.id = "enemy-card" characterDiv.style.backgroundColor = "gray" characterDiv.style.padding = "5px" } else { myHero = card characterDiv.id = "hero-card" characterDiv.style.backgroundColor = "teal" characterDiv.style.padding = "5px" } //Sets up a card object to appear as a div within the game area let char = document.createElement("h4") char.id = "name" char.class = "card-title" char.innerText = card.name characterDiv.appendChild(char) let charHP = document.createElement("p") charHP.className = "card-text" charHP.id = "hp" charHP.innerText = `HP: ${card.maxHP}` characterDiv.appendChild(charHP) let charHpBar = document.createElement("div") charHpBar.className = "progress" charHpBar.id = "progress" let barHealth = document.createElement("div") barHealth.id = "currentHP" barHealth.className = "progress-bar progress-bar-success" barHealth.style.width = `${(card.hp / card.maxHP) * 100}%` charHpBar.appendChild(barHealth) characterDiv.appendChild(charHpBar) let charImg = document.createElement("img") charImg.src = card.img charImg.className = "card-img-top" charImg.alt = "Custom image missing" characterDiv.appendChild(charImg) let charAtt = document.createElement("p") charAtt.className = "card-text" charAtt.id = "attack" charAtt.innerText = `Attack: ${card.attack}` characterDiv.appendChild(charAtt) gameArea.appendChild(characterDiv) }
function drawCard(cardDeck) { let totalCards = cardDeck.length let i = Math.floor(Math.random() * totalCards) let card = cardDeck[i] let characterDiv = document.createElement("div") characterDiv.className = "card" //Determines whether the card is for an enemy or a hero if (card instanceof Enemy) { myEnemy = card characterDiv.id = "enemy-card" characterDiv.style.backgroundColor = "gray" characterDiv.style.padding = "5px" } else { myHero = card characterDiv.id = "hero-card" characterDiv.style.backgroundColor = "teal" characterDiv.style.padding = "5px" } //Sets up a card object to appear as a div within the game area let char = document.createElement("h4") char.id = "name" char.class = "card-title" char.innerText = card.name characterDiv.appendChild(char) let charHP = document.createElement("p") charHP.className = "card-text" charHP.id = "hp" charHP.innerText = `HP: ${card.maxHP}` characterDiv.appendChild(charHP) let charHpBar = document.createElement("div") charHpBar.className = "progress" charHpBar.id = "progress" let barHealth = document.createElement("div") barHealth.id = "currentHP" barHealth.className = "progress-bar progress-bar-success" barHealth.style.width = `${(card.hp / card.maxHP) * 100}%` charHpBar.appendChild(barHealth) characterDiv.appendChild(charHpBar) let charImg = document.createElement("img") charImg.src = card.img charImg.className = "card-img-top" charImg.alt = "Custom image missing" characterDiv.appendChild(charImg) let charAtt = document.createElement("p") charAtt.className = "card-text" charAtt.id = "attack" charAtt.innerText = `Attack: ${card.attack}` characterDiv.appendChild(charAtt) gameArea.appendChild(characterDiv) }
JavaScript
function refreshCard(character) { if (character === "enemy") { let enemyCard = document.getElementById("enemy-card") enemyCard.children.hp.innerText = `HP: ${myEnemy.hp}` enemyCard.children.progress.firstChild.style.width = `${(myEnemy.hp / myEnemy.maxHP) * 100}%` } if (character === "player") { let heroCard = document.getElementById("hero-card") heroCard.children.hp.innerText = `HP: ${myHero.hp}` heroCard.children.progress.firstChild.style.width = `${(myHero.hp / myHero.maxHP) * 100}%` } }
function refreshCard(character) { if (character === "enemy") { let enemyCard = document.getElementById("enemy-card") enemyCard.children.hp.innerText = `HP: ${myEnemy.hp}` enemyCard.children.progress.firstChild.style.width = `${(myEnemy.hp / myEnemy.maxHP) * 100}%` } if (character === "player") { let heroCard = document.getElementById("hero-card") heroCard.children.hp.innerText = `HP: ${myHero.hp}` heroCard.children.progress.firstChild.style.width = `${(myHero.hp / myHero.maxHP) * 100}%` } }
JavaScript
function drawNewEnemy(characterList) { let totalCards = characterList.length let i = Math.floor(Math.random() * totalCards) let card = characterList[i] myEnemy = card //Updates the DOM enemy-card with new Enemy info let newEnemy = document.getElementById("enemy-card").children newEnemy[0].innerText = card.name newEnemy[1].innerText = `HP: ${card.hp}` newEnemy.progress.firstChild.style.width = `100%` newEnemy[3].src = card.img newEnemy[4].innerText = `Attack: ${card.attack}` }
function drawNewEnemy(characterList) { let totalCards = characterList.length let i = Math.floor(Math.random() * totalCards) let card = characterList[i] myEnemy = card //Updates the DOM enemy-card with new Enemy info let newEnemy = document.getElementById("enemy-card").children newEnemy[0].innerText = card.name newEnemy[1].innerText = `HP: ${card.hp}` newEnemy.progress.firstChild.style.width = `100%` newEnemy[3].src = card.img newEnemy[4].innerText = `Attack: ${card.attack}` }
JavaScript
function fetcher(URL, callback) { fetch(URL) .then(response => response.json()) .then(json => callback(json)) }
function fetcher(URL, callback) { fetch(URL) .then(response => response.json()) .then(json => callback(json)) }
JavaScript
function buildScoreboard() { let board = document.getElementById("scoreboard") let title = document.createElement('h3') title.innerText = `Top Scores` board.appendChild(title) for(let i = 0; i < 10; i++) { let user_score = document.createElement("li") user_score.innerText = "-" board.appendChild(user_score) } }
function buildScoreboard() { let board = document.getElementById("scoreboard") let title = document.createElement('h3') title.innerText = `Top Scores` board.appendChild(title) for(let i = 0; i < 10; i++) { let user_score = document.createElement("li") user_score.innerText = "-" board.appendChild(user_score) } }
JavaScript
function updateScore(scorelist) { let board = document.getElementById("scoreboard") let top_scores = [] //Adds anyone with a top_score attr that isn't null or empty and pushes to an array for(const user of scorelist.users) { if (user.top_score){ top_scores.push([user.username, user.top_score]) } } //Sorts the array by the highest score in descending order and updates the DOM top_scores.sort(function(a, b){return b[1]-a[1]}) for(let i = 1; i < 11; i++) { let user_score = board.childNodes if (top_scores[i - 1]){ user_score[i].innerText = `${top_scores[i - 1][0]}: ${top_scores[i -1][1]}` } } }
function updateScore(scorelist) { let board = document.getElementById("scoreboard") let top_scores = [] //Adds anyone with a top_score attr that isn't null or empty and pushes to an array for(const user of scorelist.users) { if (user.top_score){ top_scores.push([user.username, user.top_score]) } } //Sorts the array by the highest score in descending order and updates the DOM top_scores.sort(function(a, b){return b[1]-a[1]}) for(let i = 1; i < 11; i++) { let user_score = board.childNodes if (top_scores[i - 1]){ user_score[i].innerText = `${top_scores[i - 1][0]}: ${top_scores[i -1][1]}` } } }
JavaScript
function buildYourScore() { let board = document.getElementById("your_score") let title = document.createElement('h3') title.innerText = `Current Score` board.appendChild(title) let score = document.createElement('h4') score.id = "current_score" score.innerText = "0" board.appendChild(score) }
function buildYourScore() { let board = document.getElementById("your_score") let title = document.createElement('h3') title.innerText = `Current Score` board.appendChild(title) let score = document.createElement('h4') score.id = "current_score" score.innerText = "0" board.appendChild(score) }
JavaScript
function updateImage(result) { console.log(result); var countNumber = result["growth"]; var projectHTML = "<img src='../images/Cup" + countNumber + ".png' style='width:40%' ... />"; $('.sip-tracker').html(projectHTML); if (result["countMax"] == true) { alert("You've already reached your daily limit!"); } }
function updateImage(result) { console.log(result); var countNumber = result["growth"]; var projectHTML = "<img src='../images/Cup" + countNumber + ".png' style='width:40%' ... />"; $('.sip-tracker').html(projectHTML); if (result["countMax"] == true) { alert("You've already reached your daily limit!"); } }
JavaScript
function closeWin(s) { dir = exec("ps -ef | grep ./gl | grep -v grep | awk '{print $2}' | xargs kill ", function(err, stdout, stderr) { console.log(stderr); }); if (calWindow) calWindow.close(); status = s; size(); }
function closeWin(s) { dir = exec("ps -ef | grep ./gl | grep -v grep | awk '{print $2}' | xargs kill ", function(err, stdout, stderr) { console.log(stderr); }); if (calWindow) calWindow.close(); status = s; size(); }
JavaScript
function renameFiles(names) { const namesObject = {}; return names.map((name) => { const newName = (namesObject[name]) ? `${name}(${namesObject[name]++})` : name; namesObject[newName] = 1; return newName; }); }
function renameFiles(names) { const namesObject = {}; return names.map((name) => { const newName = (namesObject[name]) ? `${name}(${namesObject[name]++})` : name; namesObject[newName] = 1; return newName; }); }
JavaScript
function minesweeper(matrix) { let minefield = new Array(matrix.length) .fill(0) .map(() => new Array(matrix[0].length).fill(0)); matrix.forEach((row, rowIndex) => { row.forEach((item, columnIndex) => { if (item) { minefield = updateMinefieldWithNewMine(columnIndex, rowIndex, minefield); } }); }); return minefield; }
function minesweeper(matrix) { let minefield = new Array(matrix.length) .fill(0) .map(() => new Array(matrix[0].length).fill(0)); matrix.forEach((row, rowIndex) => { row.forEach((item, columnIndex) => { if (item) { minefield = updateMinefieldWithNewMine(columnIndex, rowIndex, minefield); } }); }); return minefield; }
JavaScript
function restore_options() { // Use default value seekStep = 6, autoView = 'focus' chrome.storage.sync.get({ seekStep: 5 }, function (items) { document.getElementById('seekStep').value = items.seekStep; }); }
function restore_options() { // Use default value seekStep = 6, autoView = 'focus' chrome.storage.sync.get({ seekStep: 5 }, function (items) { document.getElementById('seekStep').value = items.seekStep; }); }
JavaScript
function stat (reqPath) { return new Promise(function (resolve, reject) { fs.stat(path.join(ramlPath, reqPath), function (err, stat) { if (err) { if (err.code === 'ENOENT') { return reject(err.code); } return reject(err); // generate 500 } if (stat.isDirectory()) { return resolve(listDirectory(reqPath)); } if (stat.isFile()) { return resolve({ path: url.resolve('/', reqPath), name: path.basename(reqPath), type: 'file' }); } }); }); }
function stat (reqPath) { return new Promise(function (resolve, reject) { fs.stat(path.join(ramlPath, reqPath), function (err, stat) { if (err) { if (err.code === 'ENOENT') { return reject(err.code); } return reject(err); // generate 500 } if (stat.isDirectory()) { return resolve(listDirectory(reqPath)); } if (stat.isFile()) { return resolve({ path: url.resolve('/', reqPath), name: path.basename(reqPath), type: 'file' }); } }); }); }
JavaScript
function exit (err, cb, result){ if (!cb) { var code = (err) ? 1 : 0; setTimeout(function () { process.exit(code); }, 1000); } else { cb (err, result); } }
function exit (err, cb, result){ if (!cb) { var code = (err) ? 1 : 0; setTimeout(function () { process.exit(code); }, 1000); } else { cb (err, result); } }
JavaScript
function exit (code){ code = code || 0; setTimeout (function (){ process.exit (code); }, 1000); }
function exit (code){ code = code || 0; setTimeout (function (){ process.exit (code); }, 1000); }
JavaScript
function areInstancesReady (params, cb){ var ELB, EC2; ELB = params.AWS && new params.AWS.ELB(); if (ELB){ if (params.lbName){ console.log ("Checking that the new instances are ready. This might take a few minutes \n"); var dots = ''; function describeInstanceHealth (){ ELB.describeInstanceHealth({LoadBalancerName: params.lbName}, function( error, data) { if (error) { cb && cb (error);} // now check if the instances are ready else { var stateMap = {}; for (var i = 0; i < params.newInstances.length; ++i){ stateMap[params.newInstances[i].InstanceId] = false; } var readyCount = 0; var states = data.InstanceStates; for (i = 0; i < states.length; ++i){ if (states[i].State === "InService" && stateMap[states[i].InstanceId] === false){ stateMap[states[i]] = true; ++readyCount; } } // if Ready if (readyCount === params.newInstances.length){ console.log ("New Instances are in service"); cb && cb (null, params); } else { moveCursorUp (); dots += '.'; console.log (dots); setTimeout (describeInstanceHealth, 5000); } } }); } describeInstanceHealth (); } else { cb && cb ("LoadBalanceName not specified"); } } else { cb && cb ("AWS is not configured correctly"); } }
function areInstancesReady (params, cb){ var ELB, EC2; ELB = params.AWS && new params.AWS.ELB(); if (ELB){ if (params.lbName){ console.log ("Checking that the new instances are ready. This might take a few minutes \n"); var dots = ''; function describeInstanceHealth (){ ELB.describeInstanceHealth({LoadBalancerName: params.lbName}, function( error, data) { if (error) { cb && cb (error);} // now check if the instances are ready else { var stateMap = {}; for (var i = 0; i < params.newInstances.length; ++i){ stateMap[params.newInstances[i].InstanceId] = false; } var readyCount = 0; var states = data.InstanceStates; for (i = 0; i < states.length; ++i){ if (states[i].State === "InService" && stateMap[states[i].InstanceId] === false){ stateMap[states[i]] = true; ++readyCount; } } // if Ready if (readyCount === params.newInstances.length){ console.log ("New Instances are in service"); cb && cb (null, params); } else { moveCursorUp (); dots += '.'; console.log (dots); setTimeout (describeInstanceHealth, 5000); } } }); } describeInstanceHealth (); } else { cb && cb ("LoadBalanceName not specified"); } } else { cb && cb ("AWS is not configured correctly"); } }
JavaScript
function removeOldScaleGroups (params, cb){ var AUTO = params.AWS && new params.AWS.AutoScaling(); if (AUTO){ if (params.del){ console.log ("Removing old Scale Groups and Launch configurations"); async.eachSeries (params.AutoScalingInstances, function (instance, done) { if (instance.InstanceId === params.instanceId){ AUTO.deleteAutoScalingGroup ({AutoScalingGroupName:instance.AutoScalingGroupName, ForceDelete:true}, function (err, data){ AUTO.deleteLaunchConfiguration ({LaunchConfigurationName:instance.LaunchConfigurationName}, function (err, data){ done (); }); }); } else{ console.log ("Can't find Old Scale Group"); done (); } }, function (err){ cb && cb (err, params); }); } else { cb && cb (null, params); } } else {cb && cb ("AWS is not configured correctly");} }
function removeOldScaleGroups (params, cb){ var AUTO = params.AWS && new params.AWS.AutoScaling(); if (AUTO){ if (params.del){ console.log ("Removing old Scale Groups and Launch configurations"); async.eachSeries (params.AutoScalingInstances, function (instance, done) { if (instance.InstanceId === params.instanceId){ AUTO.deleteAutoScalingGroup ({AutoScalingGroupName:instance.AutoScalingGroupName, ForceDelete:true}, function (err, data){ AUTO.deleteLaunchConfiguration ({LaunchConfigurationName:instance.LaunchConfigurationName}, function (err, data){ done (); }); }); } else{ console.log ("Can't find Old Scale Group"); done (); } }, function (err){ cb && cb (err, params); }); } else { cb && cb (null, params); } } else {cb && cb ("AWS is not configured correctly");} }
JavaScript
function areInstancesReady (params, cb){ var ELB, EC2; ELB = params.AWS && new params.AWS.ELB(); if (ELB){ if (params.loadBalancerName){ console.log ("Checking that the new instances are ready. This might take a few minutes \n"); var dots = ''; function describeInstanceHealth (){ ELB.describeInstanceHealth({LoadBalancerName: params.loadBalancerName}, function( error, data) { if (error) { cb && cb (error);} // now check if the instances are ready else { var stateMap = {}; for (var i = 0; i < params.newInstances.length; ++i){ stateMap[params.newInstances[i].InstanceId] = false; } var readyCount = 0; var states = data.InstanceStates; for (i = 0; i < states.length; ++i){ if (states[i].State === "InService" && stateMap[states[i].InstanceId] === false){ stateMap[states[i]] = true; ++readyCount; } } // if Ready if (readyCount === params.newInstances.length){ console.log ("New Instances are in service"); cb && cb (null, params); } else { moveCursorUp (); dots += '.'; console.log (dots); setTimeout (describeInstanceHealth, 5000); } } }); } describeInstanceHealth (); } else { cb && cb ("LoadBalanceName not specified"); } } else { cb && cb ("AWS is not configured correctly"); } }
function areInstancesReady (params, cb){ var ELB, EC2; ELB = params.AWS && new params.AWS.ELB(); if (ELB){ if (params.loadBalancerName){ console.log ("Checking that the new instances are ready. This might take a few minutes \n"); var dots = ''; function describeInstanceHealth (){ ELB.describeInstanceHealth({LoadBalancerName: params.loadBalancerName}, function( error, data) { if (error) { cb && cb (error);} // now check if the instances are ready else { var stateMap = {}; for (var i = 0; i < params.newInstances.length; ++i){ stateMap[params.newInstances[i].InstanceId] = false; } var readyCount = 0; var states = data.InstanceStates; for (i = 0; i < states.length; ++i){ if (states[i].State === "InService" && stateMap[states[i].InstanceId] === false){ stateMap[states[i]] = true; ++readyCount; } } // if Ready if (readyCount === params.newInstances.length){ console.log ("New Instances are in service"); cb && cb (null, params); } else { moveCursorUp (); dots += '.'; console.log (dots); setTimeout (describeInstanceHealth, 5000); } } }); } describeInstanceHealth (); } else { cb && cb ("LoadBalanceName not specified"); } } else { cb && cb ("AWS is not configured correctly"); } }
JavaScript
function removeOldScaleGroups (params, cb){ var AUTO = params.AWS && new params.AWS.AutoScaling(); if (AUTO){ if (params.args.removeOldInstances){ console.log ("Removing old Scale Groups and Launch configurations"); async.eachSeries (params.AutoScalingInstances, function (instance, done) { if (instance.InstanceId === params.instanceId){ AUTO.deleteAutoScalingGroup ({AutoScalingGroupName:instance.AutoScalingGroupName, ForceDelete:true}, function (err, data){ AUTO.deleteLaunchConfiguration ({LaunchConfigurationName:instance.LaunchConfigurationName}, function (err, data){ done (); }); }); } else{ console.log ("Can't find Old Scale Group"); done (); } }, function (err){ cb && cb (err, params); }); } else { cb && cb (null, params); } } else {cb && cb ("AWS is not configured correctly");} }
function removeOldScaleGroups (params, cb){ var AUTO = params.AWS && new params.AWS.AutoScaling(); if (AUTO){ if (params.args.removeOldInstances){ console.log ("Removing old Scale Groups and Launch configurations"); async.eachSeries (params.AutoScalingInstances, function (instance, done) { if (instance.InstanceId === params.instanceId){ AUTO.deleteAutoScalingGroup ({AutoScalingGroupName:instance.AutoScalingGroupName, ForceDelete:true}, function (err, data){ AUTO.deleteLaunchConfiguration ({LaunchConfigurationName:instance.LaunchConfigurationName}, function (err, data){ done (); }); }); } else{ console.log ("Can't find Old Scale Group"); done (); } }, function (err){ cb && cb (err, params); }); } else { cb && cb (null, params); } } else {cb && cb ("AWS is not configured correctly");} }
JavaScript
function conditionString (str){ var open = String.fromCharCode(147); var close = String.fromCharCode(148); return str && str.replace(open,'"').replace(close,'"'); }
function conditionString (str){ var open = String.fromCharCode(147); var close = String.fromCharCode(148); return str && str.replace(open,'"').replace(close,'"'); }
JavaScript
async _loadProviders () { debug('loading providers') const { concurrency = os.cpus().length } = this._options const files = await globby( path.join(this._providersDir, '*.js'), { concurrency } ) const providers = files.map(path => { const Provider = require(path) return { priority: getPriority(path), provider: new Provider() } }) return providers.reduce(groupByPriority, {}) }
async _loadProviders () { debug('loading providers') const { concurrency = os.cpus().length } = this._options const files = await globby( path.join(this._providersDir, '*.js'), { concurrency } ) const providers = files.map(path => { const Provider = require(path) return { priority: getPriority(path), provider: new Provider() } }) return providers.reduce(groupByPriority, {}) }
JavaScript
function RecolectarDataGUI(){ NuevoEvento = { id: $('#idEvento').val(), title: $('#tituloModal').val(), start : $('#fechaModal').val()+" "+moment($('#horaModal').val(), 'hh:mmA').format('HH:mm:ss'), color : currColor, descripcion: $('#descripcionModal').val(), casos_id: $('#CasosModal').val(), comparendos_id: $('#ComparendosModal').val() }; return NuevoEvento; }
function RecolectarDataGUI(){ NuevoEvento = { id: $('#idEvento').val(), title: $('#tituloModal').val(), start : $('#fechaModal').val()+" "+moment($('#horaModal').val(), 'hh:mmA').format('HH:mm:ss'), color : currColor, descripcion: $('#descripcionModal').val(), casos_id: $('#CasosModal').val(), comparendos_id: $('#ComparendosModal').val() }; return NuevoEvento; }
JavaScript
function EnviarData(accion, objEvento){ $.ajax({ type: 'POST', url: baseurl+'Eventos/Acciones/'+accion, data: objEvento, success: function(msg){ var obj = JSON.parse(msg); if (obj.type == 'Success') { $('#calendar').fullCalendar('refetchEvents'); $("#modalForm").modal('toggle'); notificacion(); } else{ $('#calendar').fullCalendar('refetchEvents'); $("#modalForm").modal('toggle'); notificacion(); $.alert({ columnClass: 'medium', title: '<h4><b>Error!</b></h4>', content: '<h4>'+obj.msg+'</h4>', type: 'red', icon: 'fa fa-ban', buttons: { cancelar:{ text: 'OK', btnClass: 'btn-red', close: function(){} } } }); } } }); }
function EnviarData(accion, objEvento){ $.ajax({ type: 'POST', url: baseurl+'Eventos/Acciones/'+accion, data: objEvento, success: function(msg){ var obj = JSON.parse(msg); if (obj.type == 'Success') { $('#calendar').fullCalendar('refetchEvents'); $("#modalForm").modal('toggle'); notificacion(); } else{ $('#calendar').fullCalendar('refetchEvents'); $("#modalForm").modal('toggle'); notificacion(); $.alert({ columnClass: 'medium', title: '<h4><b>Error!</b></h4>', content: '<h4>'+obj.msg+'</h4>', type: 'red', icon: 'fa fa-ban', buttons: { cancelar:{ text: 'OK', btnClass: 'btn-red', close: function(){} } } }); } } }); }
JavaScript
function restaurar (){ $('#modalTitulo').attr("class", "form-group"); $('#tituloErrorModal').text(""); $('#modalHora').attr("class", "form-group"); $('#horaErrorModal').text(""); }
function restaurar (){ $('#modalTitulo').attr("class", "form-group"); $('#tituloErrorModal').text(""); $('#modalHora').attr("class", "form-group"); $('#horaErrorModal').text(""); }
JavaScript
set draggable(value) { let isDragging = false, elementLeft, elementTop; let onStartDrag = event => { if (event.target != this._elementRoot) return false; isDragging = true; let elementRect = this._elementRoot.getBoundingClientRect(); elementLeft = event.clientX - elementRect.left; elementTop = event.clientY - elementRect.top; this._position = { top: elementRect.top + 'px', left: elementRect.left + 'px' }; }; let onStopDrag = event => { isDragging = false; this._position = { top: this._elementRoot.style.top, left: this._elementRoot.style.left }; this.saveSession(); }; let onDragging = event => { if (!isDragging) return; let moveX = event.clientX - elementLeft, moveY = event.clientY - elementTop; this._elementRoot.style.left = moveX + 'px'; this._elementRoot.style.top = moveY + 'px'; event.preventDefault(); }; if (value) { this._draggable = true; this._elementRoot.classList.add('draggable'); document.addEventListener('mousedown', this._onStartDrag = onStartDrag); document.addEventListener('mouseup', this._onStopDrag = onStopDrag); document.addEventListener('mousemove', this._onDragging = onDragging); } else { this._draggable = false; this._elementRoot.classList.remove('draggable'); document.removeEventListener('mousedown', this._onStartDrag); document.removeEventListener('mouseup', this._onStopDrag); document.removeEventListener('mousemove', this._onDragging); } }
set draggable(value) { let isDragging = false, elementLeft, elementTop; let onStartDrag = event => { if (event.target != this._elementRoot) return false; isDragging = true; let elementRect = this._elementRoot.getBoundingClientRect(); elementLeft = event.clientX - elementRect.left; elementTop = event.clientY - elementRect.top; this._position = { top: elementRect.top + 'px', left: elementRect.left + 'px' }; }; let onStopDrag = event => { isDragging = false; this._position = { top: this._elementRoot.style.top, left: this._elementRoot.style.left }; this.saveSession(); }; let onDragging = event => { if (!isDragging) return; let moveX = event.clientX - elementLeft, moveY = event.clientY - elementTop; this._elementRoot.style.left = moveX + 'px'; this._elementRoot.style.top = moveY + 'px'; event.preventDefault(); }; if (value) { this._draggable = true; this._elementRoot.classList.add('draggable'); document.addEventListener('mousedown', this._onStartDrag = onStartDrag); document.addEventListener('mouseup', this._onStopDrag = onStopDrag); document.addEventListener('mousemove', this._onDragging = onDragging); } else { this._draggable = false; this._elementRoot.classList.remove('draggable'); document.removeEventListener('mousedown', this._onStartDrag); document.removeEventListener('mouseup', this._onStopDrag); document.removeEventListener('mousemove', this._onDragging); } }
JavaScript
function CrosswordCell(letter){ this.char = letter; // the actual letter for the cell on the crossword // If a word hits this cell going in the "across" direction, this will be a CrosswordCellNode this.across = null; // If a word hits this cell going in the "down" direction, this will be a CrosswordCellNode this.down = null; }
function CrosswordCell(letter){ this.char = letter; // the actual letter for the cell on the crossword // If a word hits this cell going in the "across" direction, this will be a CrosswordCellNode this.across = null; // If a word hits this cell going in the "down" direction, this will be a CrosswordCellNode this.down = null; }
JavaScript
function save({attributes}) { const {icon} = attributes; const attributesToStyle = (attributes) => { const { color, alignment, size, } = attributes; const alignmentMap = { center: "center", right: "flex-end" } const style = { 'color': color, 'justify-content': alignment && alignmentMap[alignment], 'font-size': size !== 16 && size } const iconStyle = Object.keys(style).reduce((object,key)=>( style[key] ? {...object, [key]: style[key]} : object ), {}) return iconStyle } const style = attributesToStyle(attributes); return ( <div className={'icon'} style={style}> <i className={icon}/> </div> ); }
function save({attributes}) { const {icon} = attributes; const attributesToStyle = (attributes) => { const { color, alignment, size, } = attributes; const alignmentMap = { center: "center", right: "flex-end" } const style = { 'color': color, 'justify-content': alignment && alignmentMap[alignment], 'font-size': size !== 16 && size } const iconStyle = Object.keys(style).reduce((object,key)=>( style[key] ? {...object, [key]: style[key]} : object ), {}) return iconStyle } const style = attributesToStyle(attributes); return ( <div className={'icon'} style={style}> <i className={icon}/> </div> ); }
JavaScript
function save({attributes}) { const attributesToStyle = (attributes) => { const { background, width, height, alignment, margin } = attributes; const alignmentMap = { center: "0 auto", right: "0 0 0 auto" } const style = { '--divider-background': background, '--divider-width': `${width}%`, '--divider-height': `${height}px`, 'margin': alignment && alignmentMap[alignment], 'margin-top': margin.top && `${margin.top}px`, 'margin-bottom': margin.bottom && `${margin.bottom}px` } const dividerStyle = Object.keys(style).reduce((object,key)=>( style[key] ? {...object, [key]: style[key]} : object ), {}) return dividerStyle } const style = attributesToStyle(attributes); return (<z-divider style={style}/>); }
function save({attributes}) { const attributesToStyle = (attributes) => { const { background, width, height, alignment, margin } = attributes; const alignmentMap = { center: "0 auto", right: "0 0 0 auto" } const style = { '--divider-background': background, '--divider-width': `${width}%`, '--divider-height': `${height}px`, 'margin': alignment && alignmentMap[alignment], 'margin-top': margin.top && `${margin.top}px`, 'margin-bottom': margin.bottom && `${margin.bottom}px` } const dividerStyle = Object.keys(style).reduce((object,key)=>( style[key] ? {...object, [key]: style[key]} : object ), {}) return dividerStyle } const style = attributesToStyle(attributes); return (<z-divider style={style}/>); }
JavaScript
function save({attributes}) { const attributesToStyle = (attributes) => { const { verticalAlignment, fullWidth, heightValue, heightUnit, textColor, backgroundColor, overlayColor, overlayOpacity, backgroundImageSrc, backgroundImageAttachment, backgroundImagePosition, backgroundImageSize, margin, marginDesktop, padding, paddingDesktop, } = attributes; const verticalAlignmentMap = { top: 'start', center: 'center', bottom: 'end' } const sectionBackground = fullWidth ? { 'background': `${backgroundImageSrc ? 'url('+backgroundImageSrc+')' : ''}${backgroundImageSrc && backgroundColor ? ', ' : ''}${backgroundColor ? backgroundColor : ''}`, 'background-position': backgroundImagePosition, 'background-size': backgroundImageSize, 'background-attachment': backgroundImageAttachment } : {} const contentBackground = fullWidth ? {} : { 'background': `${backgroundImageSrc ? 'url('+backgroundImageSrc+')' : ''}${backgroundImageSrc && backgroundColor ? ', ' : ''}${backgroundColor ? backgroundColor : ''}`, 'background-position': backgroundImagePosition, 'background-size': backgroundImageSize, 'background-attachment': backgroundImageAttachment } const section = { '--section-padding': Object.values(padding).some((val)=>(val > 0)) && `${padding.top}px ${padding.right}px ${padding.bottom}px ${padding.left}px`, '--section-desktop-padding': Object.values(paddingDesktop).some((val)=>(val > 0)) && `${paddingDesktop.top}px ${paddingDesktop.right}px ${paddingDesktop.bottom}px ${paddingDesktop.left}px`, '--section-margin': Object.values(margin).some((val)=>(val > 0)) && `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`, '--section-desktop-margin': Object.values(marginDesktop).some((val)=>(val > 0)) && `${marginDesktop.top}px ${marginDesktop.right}px ${marginDesktop.bottom}px ${marginDesktop.left}px`, '--section-color': textColor, '--section-overlay-background': overlayColor, '--section-overlay-opacity': `${overlayOpacity}%`, ...sectionBackground } const sectionStyle = Object.keys(section).reduce((object,key)=>( section[key] ? {...object, [key]: section[key]} : object ), {}) const content = { '--section-content-min-height': heightValue !== '0' && `${heightValue}${heightUnit}`, '--section-content-align-items': verticalAlignmentMap[verticalAlignment], ...contentBackground } const contentStyle = Object.keys(content).reduce((object,key)=>( content[key] ? {...object, [key]: content[key]} : object ), {}) const initial = { '--section-content-min-height': '100%', } return { ...initial, ...sectionStyle, ...contentStyle, } } const style = attributesToStyle(attributes); return ( <z-section tag={'div'} style={style}> <InnerBlocks.Content /> </z-section> ); }
function save({attributes}) { const attributesToStyle = (attributes) => { const { verticalAlignment, fullWidth, heightValue, heightUnit, textColor, backgroundColor, overlayColor, overlayOpacity, backgroundImageSrc, backgroundImageAttachment, backgroundImagePosition, backgroundImageSize, margin, marginDesktop, padding, paddingDesktop, } = attributes; const verticalAlignmentMap = { top: 'start', center: 'center', bottom: 'end' } const sectionBackground = fullWidth ? { 'background': `${backgroundImageSrc ? 'url('+backgroundImageSrc+')' : ''}${backgroundImageSrc && backgroundColor ? ', ' : ''}${backgroundColor ? backgroundColor : ''}`, 'background-position': backgroundImagePosition, 'background-size': backgroundImageSize, 'background-attachment': backgroundImageAttachment } : {} const contentBackground = fullWidth ? {} : { 'background': `${backgroundImageSrc ? 'url('+backgroundImageSrc+')' : ''}${backgroundImageSrc && backgroundColor ? ', ' : ''}${backgroundColor ? backgroundColor : ''}`, 'background-position': backgroundImagePosition, 'background-size': backgroundImageSize, 'background-attachment': backgroundImageAttachment } const section = { '--section-padding': Object.values(padding).some((val)=>(val > 0)) && `${padding.top}px ${padding.right}px ${padding.bottom}px ${padding.left}px`, '--section-desktop-padding': Object.values(paddingDesktop).some((val)=>(val > 0)) && `${paddingDesktop.top}px ${paddingDesktop.right}px ${paddingDesktop.bottom}px ${paddingDesktop.left}px`, '--section-margin': Object.values(margin).some((val)=>(val > 0)) && `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`, '--section-desktop-margin': Object.values(marginDesktop).some((val)=>(val > 0)) && `${marginDesktop.top}px ${marginDesktop.right}px ${marginDesktop.bottom}px ${marginDesktop.left}px`, '--section-color': textColor, '--section-overlay-background': overlayColor, '--section-overlay-opacity': `${overlayOpacity}%`, ...sectionBackground } const sectionStyle = Object.keys(section).reduce((object,key)=>( section[key] ? {...object, [key]: section[key]} : object ), {}) const content = { '--section-content-min-height': heightValue !== '0' && `${heightValue}${heightUnit}`, '--section-content-align-items': verticalAlignmentMap[verticalAlignment], ...contentBackground } const contentStyle = Object.keys(content).reduce((object,key)=>( content[key] ? {...object, [key]: content[key]} : object ), {}) const initial = { '--section-content-min-height': '100%', } return { ...initial, ...sectionStyle, ...contentStyle, } } const style = attributesToStyle(attributes); return ( <z-section tag={'div'} style={style}> <InnerBlocks.Content /> </z-section> ); }
JavaScript
function save({attributes}) { return ( <z-accordion multiple={attributes.multiple} first-open={attributes.firstOpen}> <InnerBlocks.Content /> </z-accordion> ); }
function save({attributes}) { return ( <z-accordion multiple={attributes.multiple} first-open={attributes.firstOpen}> <InnerBlocks.Content /> </z-accordion> ); }
JavaScript
function save({attributes}) { const {column} = attributes; return ( <div className={`z-column-${column}`}> <InnerBlocks.Content /> </div> ); }
function save({attributes}) { const {column} = attributes; return ( <div className={`z-column-${column}`}> <InnerBlocks.Content /> </div> ); }
JavaScript
function Edit({ attributes, setAttributes }) { function setTitle(value) { setAttributes({title: value}) } return ([ <div {...useBlockProps()}> <RichText key="editable" tagName="p" placeholder="Proszę podać tytuł bloku." value={attributes.title} onChange={setTitle}/> <InnerBlocks/> </div> ]); }
function Edit({ attributes, setAttributes }) { function setTitle(value) { setAttributes({title: value}) } return ([ <div {...useBlockProps()}> <RichText key="editable" tagName="p" placeholder="Proszę podać tytuł bloku." value={attributes.title} onChange={setTitle}/> <InnerBlocks/> </div> ]); }
JavaScript
function Edit({ attributes, setAttributes }) { const ALLOWED_BLOCKS = [ 'zhp/accordion-item' ]; function setMultiple(value) { setAttributes({multiple: value}) } function setFirstOpen(value) { setAttributes({firstOpen: value}) } return ([ <InspectorControls> <PanelBody title="Właściwości"> <ToggleControl label="Wiele zakładek" help={attributes.multiple ? 'Dozwolone jest otwieranie wielu zakładek.' : 'Przełącz, aby umożliwić otiweranie wielu zakładek.'} checked={attributes.multiple} onChange={setMultiple} /> <TextControl label="Otwarta zakładka" help="Wpisz tytuł zakładki, która powinna być otwarta po załadowaniu." value={attributes.firstOpen} onChange={setFirstOpen} /> </PanelBody> </InspectorControls>, <div {...useBlockProps()}> <InnerBlocks allowedBlocks={ALLOWED_BLOCKS} /> </div> ]); }
function Edit({ attributes, setAttributes }) { const ALLOWED_BLOCKS = [ 'zhp/accordion-item' ]; function setMultiple(value) { setAttributes({multiple: value}) } function setFirstOpen(value) { setAttributes({firstOpen: value}) } return ([ <InspectorControls> <PanelBody title="Właściwości"> <ToggleControl label="Wiele zakładek" help={attributes.multiple ? 'Dozwolone jest otwieranie wielu zakładek.' : 'Przełącz, aby umożliwić otiweranie wielu zakładek.'} checked={attributes.multiple} onChange={setMultiple} /> <TextControl label="Otwarta zakładka" help="Wpisz tytuł zakładki, która powinna być otwarta po załadowaniu." value={attributes.firstOpen} onChange={setFirstOpen} /> </PanelBody> </InspectorControls>, <div {...useBlockProps()}> <InnerBlocks allowedBlocks={ALLOWED_BLOCKS} /> </div> ]); }
JavaScript
function save({attributes}) { const {thumbnail, title, description, to, hasOverlay} = attributes const classes = { 'z-card--overlayed': hasOverlay, 'z-card--pictured': hasOverlay } const className = Object.keys(classes).reduce( (array, key) => (classes[key] ? [...array, key] : array), [] ) .join(' ') return ( <z-card to={to} title={title} description={description} thumbnail={thumbnail} className={className}/> ); }
function save({attributes}) { const {thumbnail, title, description, to, hasOverlay} = attributes const classes = { 'z-card--overlayed': hasOverlay, 'z-card--pictured': hasOverlay } const className = Object.keys(classes).reduce( (array, key) => (classes[key] ? [...array, key] : array), [] ) .join(' ') return ( <z-card to={to} title={title} description={description} thumbnail={thumbnail} className={className}/> ); }
JavaScript
function redraw() { for (let i = 0; i < points.length; i++) { let point = points[i]; ctx.lineWidth = point.width; ctx.strokeStyle = point.color; if (point.id == "md") { ctx.beginPath(); ctx.moveTo(point.x, point.y); } else { ctx.lineTo(point.x, point.y); ctx.stroke(); } } ctx.strokeStyle = currStrokeStyle; ctx.lineWidth = currLineWidth; console.log("calling redraw"); socket.emit("redraw", points); }
function redraw() { for (let i = 0; i < points.length; i++) { let point = points[i]; ctx.lineWidth = point.width; ctx.strokeStyle = point.color; if (point.id == "md") { ctx.beginPath(); ctx.moveTo(point.x, point.y); } else { ctx.lineTo(point.x, point.y); ctx.stroke(); } } ctx.strokeStyle = currStrokeStyle; ctx.lineWidth = currLineWidth; console.log("calling redraw"); socket.emit("redraw", points); }
JavaScript
function resetTimeout() { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }
function resetTimeout() { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }
JavaScript
decodeFromBytes(bc, options = {}, all = null) { const decoded = super.decodeFromBytes(bc); if (this[P_PROTOCOL_VERSION]>=5) { return new PayloadBuffer(decoded.payload, decoded.payloadtype); } else { return new PayloadBuffer(decoded.payload); } }
decodeFromBytes(bc, options = {}, all = null) { const decoded = super.decodeFromBytes(bc); if (this[P_PROTOCOL_VERSION]>=5) { return new PayloadBuffer(decoded.payload, decoded.payloadtype); } else { return new PayloadBuffer(decoded.payload); } }
JavaScript
async function verifySessionWithToken(jwtToken) { var { username = '' } = jwt.verify(jwtToken, plugin.settings.secret) || {}; var uid = await user.async.getUidByUsername(username); return uid === req.user.uid; }
async function verifySessionWithToken(jwtToken) { var { username = '' } = jwt.verify(jwtToken, plugin.settings.secret) || {}; var uid = await user.async.getUidByUsername(username); return uid === req.user.uid; }
JavaScript
function currentWeather(city) { var requestUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + APIKey + "&units=imperial"; fetch(requestUrl) // fetch (path to data) .then(function (response) { // turning that data into json for us to use return response.json(); }) .then(function (data) { console.log(data); // Putting name of city + current date in card var currentDate = moment().format("l"); cityNameEl.innerHTML = data.name + " " + currentDate; // console.log(data.weather[0].icon); Need this to add icon next to cityNameEl //Outputting selected data to corresponding html elements currentTempEl.innerHTML = "Temperature: " + data.main.temp; currentHumidityEl.innerHTML = "Humidity: " + data.main.humidity; currentWindEl.innerHTML = "Wind Speed: " + data.wind.speed; // Not in this data set, will need lat and long coordinates + another API currentUVel.innerHTML = "UV Index: "; //Saving the city's data to local storage and setting the key as the city name var City = { name: data.name, temp: data.main.temp, humidity: data.main.humidity, windSpeed: data.wind.speed, }; //Creating a button for each search item localStorage.setItem(City.name, JSON.stringify(City)); var entry = document.createElement("button"); entry.setAttribute("class", "btn btn-secondary col-3"); entry.setAttribute("id", City.name); entry.appendChild(document.createTextNode(City.name)); list.appendChild(entry); // entry.addEventListener("click", currentWeather(entry.id)); }); }
function currentWeather(city) { var requestUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + APIKey + "&units=imperial"; fetch(requestUrl) // fetch (path to data) .then(function (response) { // turning that data into json for us to use return response.json(); }) .then(function (data) { console.log(data); // Putting name of city + current date in card var currentDate = moment().format("l"); cityNameEl.innerHTML = data.name + " " + currentDate; // console.log(data.weather[0].icon); Need this to add icon next to cityNameEl //Outputting selected data to corresponding html elements currentTempEl.innerHTML = "Temperature: " + data.main.temp; currentHumidityEl.innerHTML = "Humidity: " + data.main.humidity; currentWindEl.innerHTML = "Wind Speed: " + data.wind.speed; // Not in this data set, will need lat and long coordinates + another API currentUVel.innerHTML = "UV Index: "; //Saving the city's data to local storage and setting the key as the city name var City = { name: data.name, temp: data.main.temp, humidity: data.main.humidity, windSpeed: data.wind.speed, }; //Creating a button for each search item localStorage.setItem(City.name, JSON.stringify(City)); var entry = document.createElement("button"); entry.setAttribute("class", "btn btn-secondary col-3"); entry.setAttribute("id", City.name); entry.appendChild(document.createTextNode(City.name)); list.appendChild(entry); // entry.addEventListener("click", currentWeather(entry.id)); }); }
JavaScript
function msgPageScript (data) { window.postMessage({ source: 'cancorder', isRecording: isRecording, isFinished: isFinished, sources: getCanvasNames() }, '*'); }
function msgPageScript (data) { window.postMessage({ source: 'cancorder', isRecording: isRecording, isFinished: isFinished, sources: getCanvasNames() }, '*'); }
JavaScript
function msgToolbarPopup (data) { browser.runtime.sendMessage({ source: 'cancorder', isRecording: isRecording, isFinished: isFinished, sources: getCanvasNames() }); }
function msgToolbarPopup (data) { browser.runtime.sendMessage({ source: 'cancorder', isRecording: isRecording, isFinished: isFinished, sources: getCanvasNames() }); }
JavaScript
function updateIcon (isReady, isRecording, isFinished) { var icon = ICON_DEFAULT; if (isRecording) { icon = ICON_RED; } else if (isFinished) { icon = ICON_GREEN; } else if (isReady) { icon = ICON_BLUE; } browser.browserAction.setIcon({ path: icon, tabId: currentTab.id }); }
function updateIcon (isReady, isRecording, isFinished) { var icon = ICON_DEFAULT; if (isRecording) { icon = ICON_RED; } else if (isFinished) { icon = ICON_GREEN; } else if (isReady) { icon = ICON_BLUE; } browser.browserAction.setIcon({ path: icon, tabId: currentTab.id }); }
JavaScript
function notify (msg) { if (msg.source !== 'cancorder') { return; } if (msg.sources) { canvasSourceField.options = []; msg.sources.map(function (source, idx) { canvasSourceField.options.add(new Option(source, idx)); }); } if ('isRecording' in msg) { isRecording = msg.isRecording; } }
function notify (msg) { if (msg.source !== 'cancorder') { return; } if (msg.sources) { canvasSourceField.options = []; msg.sources.map(function (source, idx) { canvasSourceField.options.add(new Option(source, idx)); }); } if ('isRecording' in msg) { isRecording = msg.isRecording; } }
JavaScript
async connect() { this.account = new VaultAccount({ logoUrl: REACT_APP_LOGO_URL, }); this.context = await Network.connect({ client: { environment: EnvironmentType.TESTNET }, account: this.account, context: { name: REACT_APP_CONTEXT_NAME } }); if (!this.context) { this.emit('authenticationCancelled'); return; } this.connected = true this.did = await this.account.did(); await this.initProfile(); this.emit('initialized'); }
async connect() { this.account = new VaultAccount({ logoUrl: REACT_APP_LOGO_URL, }); this.context = await Network.connect({ client: { environment: EnvironmentType.TESTNET }, account: this.account, context: { name: REACT_APP_CONTEXT_NAME } }); if (!this.context) { this.emit('authenticationCancelled'); return; } this.connected = true this.did = await this.account.did(); await this.initProfile(); this.emit('initialized'); }
JavaScript
function Table({ columns, data, updateMyData, skipPageReset }) { // For this example, we're using pagination to illustrate how to stop // the current page from resetting when our data changes // Otherwise, nothing is different here. const { getTableProps, getTableBodyProps, headerGroups, prepareRow, page, canPreviousPage, canNextPage, pageOptions, pageCount, gotoPage, nextPage, previousPage, setPageSize, state: { pageIndex, pageSize }, } = useTable( { columns, data, defaultColumn, // use the skipPageReset option to disable page resetting temporarily autoResetPage: !skipPageReset, // updateMyData isn't part of the API, but // anything we put into these options will // automatically be available on the instance. // That way we can call this function from our // cell renderer! updateMyData, initialState: { pageSize: 100 }, autoResetFilters: false, }, useFilters, usePagination ) const classes = useStyles() // Render the UI for your table return ( <> <table {...getTableProps()} className={classes.wrapper}> <thead> {headerGroups.map(headerGroup => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <th {...column.getHeaderProps()}> {column.render('Header')} {column.canFilter && column.Filter ? column.render('Filter') : ''} </th> ))} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {page.map((row, i) => { prepareRow(row) return ( <tr {...row.getRowProps()}> {row.cells.map(cell => { return <td {...cell.getCellProps()}>{cell.render('Cell')}</td> })} </tr> ) })} </tbody> </table> {data.length > pageSize && ( <div className='pagination'> <button type='button' onClick={() => gotoPage(0)} disabled={!canPreviousPage} title='First page'> {'<<'} </button>{' '} <button type='button' onClick={() => previousPage()} disabled={!canPreviousPage} title='Previous page' > {'<'} </button>{' '} <button type='button' onClick={() => nextPage()} disabled={!canNextPage} title='Next page'> {'>'} </button>{' '} <button type='button' onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage} title='Lasat page' > {'>>'} </button>{' '} <span> Page{' '} <strong> {pageIndex + 1} of {pageOptions.length} </strong>{' '} </span> <span> | Go to page:{' '} <input type='number' defaultValue={pageIndex + 1} onChange={e => { const _page = e.target.value ? Number(e.target.value) - 1 : 0 gotoPage(_page) }} style={{ width: '100px' }} /> </span>{' '} <select value={pageSize} onChange={e => { setPageSize(Number(e.target.value)) }} > {[100, 50, 20, 10].map(_pageSize => ( <option key={_pageSize} value={_pageSize}> Show {_pageSize} </option> ))} </select> </div> )} </> ) }
function Table({ columns, data, updateMyData, skipPageReset }) { // For this example, we're using pagination to illustrate how to stop // the current page from resetting when our data changes // Otherwise, nothing is different here. const { getTableProps, getTableBodyProps, headerGroups, prepareRow, page, canPreviousPage, canNextPage, pageOptions, pageCount, gotoPage, nextPage, previousPage, setPageSize, state: { pageIndex, pageSize }, } = useTable( { columns, data, defaultColumn, // use the skipPageReset option to disable page resetting temporarily autoResetPage: !skipPageReset, // updateMyData isn't part of the API, but // anything we put into these options will // automatically be available on the instance. // That way we can call this function from our // cell renderer! updateMyData, initialState: { pageSize: 100 }, autoResetFilters: false, }, useFilters, usePagination ) const classes = useStyles() // Render the UI for your table return ( <> <table {...getTableProps()} className={classes.wrapper}> <thead> {headerGroups.map(headerGroup => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <th {...column.getHeaderProps()}> {column.render('Header')} {column.canFilter && column.Filter ? column.render('Filter') : ''} </th> ))} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {page.map((row, i) => { prepareRow(row) return ( <tr {...row.getRowProps()}> {row.cells.map(cell => { return <td {...cell.getCellProps()}>{cell.render('Cell')}</td> })} </tr> ) })} </tbody> </table> {data.length > pageSize && ( <div className='pagination'> <button type='button' onClick={() => gotoPage(0)} disabled={!canPreviousPage} title='First page'> {'<<'} </button>{' '} <button type='button' onClick={() => previousPage()} disabled={!canPreviousPage} title='Previous page' > {'<'} </button>{' '} <button type='button' onClick={() => nextPage()} disabled={!canNextPage} title='Next page'> {'>'} </button>{' '} <button type='button' onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage} title='Lasat page' > {'>>'} </button>{' '} <span> Page{' '} <strong> {pageIndex + 1} of {pageOptions.length} </strong>{' '} </span> <span> | Go to page:{' '} <input type='number' defaultValue={pageIndex + 1} onChange={e => { const _page = e.target.value ? Number(e.target.value) - 1 : 0 gotoPage(_page) }} style={{ width: '100px' }} /> </span>{' '} <select value={pageSize} onChange={e => { setPageSize(Number(e.target.value)) }} > {[100, 50, 20, 10].map(_pageSize => ( <option key={_pageSize} value={_pageSize}> Show {_pageSize} </option> ))} </select> </div> )} </> ) }
JavaScript
expose(fnOrFns) { let mapping; if (typeof (fnOrFns) === 'function') { mapping = {}; mapping[fnOrFns.name] = fnOrFns; } else { mapping = fnOrFns; } Object.entries(mapping).forEach(([name, fn]) => { if (this._fns.hasOwnProperty(name)) throw `function '${name}' is already registered`; else this._fns[name] = fn; }); }
expose(fnOrFns) { let mapping; if (typeof (fnOrFns) === 'function') { mapping = {}; mapping[fnOrFns.name] = fnOrFns; } else { mapping = fnOrFns; } Object.entries(mapping).forEach(([name, fn]) => { if (this._fns.hasOwnProperty(name)) throw `function '${name}' is already registered`; else this._fns[name] = fn; }); }
JavaScript
go(shift) { if (shift !== 0) { let index = this.index + shift; if (index < 0 || index >= this.entries.length) { return Promise.reject(new OutOfHistoryException()); } this.index = index; this.trigger('popstate', this.current); } return Promise.resolve(this.current); }
go(shift) { if (shift !== 0) { let index = this.index + shift; if (index < 0 || index >= this.entries.length) { return Promise.reject(new OutOfHistoryException()); } this.index = index; this.trigger('popstate', this.current); } return Promise.resolve(this.current); }
JavaScript
indexOfState(state) { state = state || {}; let entries = this.entries.slice(0).reverse(); for (let i = 0, len = entries.length; i < len; i++) { if (entries[i].state.timestamp === state.timestamp) { return i; } } return -1; }
indexOfState(state) { state = state || {}; let entries = this.entries.slice(0).reverse(); for (let i = 0, len = entries.length; i < len; i++) { if (entries[i].state.timestamp === state.timestamp) { return i; } } return -1; }
JavaScript
async post( url, queryParams, payload, options, silent ) { try { const request = new Request( url.concat(AccessMapper.buildQueryParams(queryParams)), { body: JSON.stringify(payload), method: 'POST', headers: options?.headers, } ); if (!silent) { window.document.dispatchEvent(new CustomEvent('DeferredLoad.Push')); } const response = await this.performRequest(request); const accessResponse = await AccessMapper.mapResponse(response); if (!silent) { window.document.dispatchEvent(new CustomEvent('DeferredLoad.Remove')); } return Promise.resolve(accessResponse); } catch (error) { if (!silent) { window.document.dispatchEvent(new CustomEvent('DeferredLoad.Remove')); } return Promise.reject(error); } }
async post( url, queryParams, payload, options, silent ) { try { const request = new Request( url.concat(AccessMapper.buildQueryParams(queryParams)), { body: JSON.stringify(payload), method: 'POST', headers: options?.headers, } ); if (!silent) { window.document.dispatchEvent(new CustomEvent('DeferredLoad.Push')); } const response = await this.performRequest(request); const accessResponse = await AccessMapper.mapResponse(response); if (!silent) { window.document.dispatchEvent(new CustomEvent('DeferredLoad.Remove')); } return Promise.resolve(accessResponse); } catch (error) { if (!silent) { window.document.dispatchEvent(new CustomEvent('DeferredLoad.Remove')); } return Promise.reject(error); } }
JavaScript
function before (s3, bucket, keys, done) { createBucket(s3, bucket) .then(function () { return when.all( // Swallow deleteObject errors here incase the files don't yet exist keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function () {}); }) ) }).then(function () { done(); }); }
function before (s3, bucket, keys, done) { createBucket(s3, bucket) .then(function () { return when.all( // Swallow deleteObject errors here incase the files don't yet exist keys.map(function (key) { return deleteObject(s3, bucket, key).catch(function () {}); }) ) }).then(function () { done(); }); }
JavaScript
function uploadAndFetch (s3, stream, filename, bucket, key) { var deferred = when.defer(); exports.getFileStream(filename) .pipe(stream) .on("error", deferred.reject) .on("finish", function () { deferred.resolve(exports.getObject(s3, bucket, key)); }); return deferred.promise; }
function uploadAndFetch (s3, stream, filename, bucket, key) { var deferred = when.defer(); exports.getFileStream(filename) .pipe(stream) .on("error", deferred.reject) .on("finish", function () { deferred.resolve(exports.getObject(s3, bucket, key)); }); return deferred.promise; }
JavaScript
function S3UploadStream (s3, s3Ops, streamOps) { var uploader = new Uploader(s3, s3Ops); var stream = new UploadStream(uploader, streamOps); return stream; }
function S3UploadStream (s3, s3Ops, streamOps) { var uploader = new Uploader(s3, s3Ops); var stream = new UploadStream(uploader, streamOps); return stream; }
JavaScript
async function handleRequest(request) { const res = await fetch(request); return new HTMLRewriter() .on('title', new TitleHandler()) .on('meta', new DescriptionHandler()) .transform(res) // const { greet } = wasm_bindgen; // await wasm_bindgen(wasm) // const greeting = greet() // return new Response(greeting, {status: 200}) }
async function handleRequest(request) { const res = await fetch(request); return new HTMLRewriter() .on('title', new TitleHandler()) .on('meta', new DescriptionHandler()) .transform(res) // const { greet } = wasm_bindgen; // await wasm_bindgen(wasm) // const greeting = greet() // return new Response(greeting, {status: 200}) }
JavaScript
function changeContentHack(id, content) { var escaped = [/:/g, /\//g, /\\/g]; //may need more characters id = id.replace(/@/g, "@@"); for(var i = 0; i < escaped.length; i++){ id = id.replace(escaped[i], "@" + i + "_"); } id = options.transport.instrumentedFiles + '/' + id; fs.write(id, content, 'w'); networkRequest.changeUrl(prefix + id); }
function changeContentHack(id, content) { var escaped = [/:/g, /\//g, /\\/g]; //may need more characters id = id.replace(/@/g, "@@"); for(var i = 0; i < escaped.length; i++){ id = id.replace(escaped[i], "@" + i + "_"); } id = options.transport.instrumentedFiles + '/' + id; fs.write(id, content, 'w'); networkRequest.changeUrl(prefix + id); }
JavaScript
function translateQtTsFile(inputFileName, language) { console.log('******************************************************'); console.log(` Translate to '${language}'`); console.log(` ${inputFileName}`); console.log('******************************************************'); // Get project name from input filename. // Example: myproject_en.ts const pos = inputFileName.lastIndexOf('_'); const filextensionLength = inputFileName.length - pos; if (pos < 0 || filextensionLength < 6) { console.log( `*** Errror: Unexpected input file name format: "${inputFileName}"`); return; } // const outputFilename = `${inputFileName.substring(0, // pos)}_${language}_output.ts`; const outputFilename = `${inputFileName}`; fs.readFile(inputFileName, 'utf-8', function(err, data) { if (err) { throw err; } const doc = new xmldom().parseFromString(data, 'application/xml'); const tsElement = doc.getElementsByTagName('TS')[0]; // language="en_US" // language="es_ES"> // language="de_DE"> let targetLanguage = getAttributeByName(tsElement, 'language'); const pos = targetLanguage.indexOf('_'); if(pos > 0) { targetLanguage = targetLanguage.substring(0, pos); } console.log('targetLanguage:', targetLanguage); const promises = []; const contextList = doc.getElementsByTagName('context'); for (let i = 0; i < contextList.length; i += 1) { const context = contextList[i]; const messageList = context.getElementsByTagName('message'); for (let j = 0; j < messageList.length; j += 1) { const message = messageList[j]; promises.push(new Promise((resolve, reject) => { // Translate text from message/source message/translation messageTranslate( targetLanguage, doc, message, function(err, translation) { if (err > 0) { console.error(`** Error messageTranslate to '${language}' failed err:${err}`); reject(err); } else { resolve(); } }); })); } } // end for context // Set timeout if a translation fail to complete // promises.push(new Promise((resolve, reject) => setTimeout(() => reject(1), 1*60*1000))); // When all strings are translated, write the translations to file Promise.all(promises) .then(() => { const xml = new XMLSerializer().serializeToString(doc); fs.writeFile(outputFilename, xml, function(err) { if (err) { // console.log(err); return console.log(err); } }); }) .catch(err => console.log(`*** Error Promise.all writing : ${outputFilename}\n${err}`)); }); }
function translateQtTsFile(inputFileName, language) { console.log('******************************************************'); console.log(` Translate to '${language}'`); console.log(` ${inputFileName}`); console.log('******************************************************'); // Get project name from input filename. // Example: myproject_en.ts const pos = inputFileName.lastIndexOf('_'); const filextensionLength = inputFileName.length - pos; if (pos < 0 || filextensionLength < 6) { console.log( `*** Errror: Unexpected input file name format: "${inputFileName}"`); return; } // const outputFilename = `${inputFileName.substring(0, // pos)}_${language}_output.ts`; const outputFilename = `${inputFileName}`; fs.readFile(inputFileName, 'utf-8', function(err, data) { if (err) { throw err; } const doc = new xmldom().parseFromString(data, 'application/xml'); const tsElement = doc.getElementsByTagName('TS')[0]; // language="en_US" // language="es_ES"> // language="de_DE"> let targetLanguage = getAttributeByName(tsElement, 'language'); const pos = targetLanguage.indexOf('_'); if(pos > 0) { targetLanguage = targetLanguage.substring(0, pos); } console.log('targetLanguage:', targetLanguage); const promises = []; const contextList = doc.getElementsByTagName('context'); for (let i = 0; i < contextList.length; i += 1) { const context = contextList[i]; const messageList = context.getElementsByTagName('message'); for (let j = 0; j < messageList.length; j += 1) { const message = messageList[j]; promises.push(new Promise((resolve, reject) => { // Translate text from message/source message/translation messageTranslate( targetLanguage, doc, message, function(err, translation) { if (err > 0) { console.error(`** Error messageTranslate to '${language}' failed err:${err}`); reject(err); } else { resolve(); } }); })); } } // end for context // Set timeout if a translation fail to complete // promises.push(new Promise((resolve, reject) => setTimeout(() => reject(1), 1*60*1000))); // When all strings are translated, write the translations to file Promise.all(promises) .then(() => { const xml = new XMLSerializer().serializeToString(doc); fs.writeFile(outputFilename, xml, function(err) { if (err) { // console.log(err); return console.log(err); } }); }) .catch(err => console.log(`*** Error Promise.all writing : ${outputFilename}\n${err}`)); }); }
JavaScript
function onLostFocus(){ if(document.body.scrollHeight > 0){ scrollTo(0, 0); } }
function onLostFocus(){ if(document.body.scrollHeight > 0){ scrollTo(0, 0); } }
JavaScript
function sendEvent(category, action, label) { gtag('event', action, { 'event_category': category, 'event_label': label }); }
function sendEvent(category, action, label) { gtag('event', action, { 'event_category': category, 'event_label': label }); }