language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function notify(selector, type, passdata) { if (!type) { passdata = selector._data_; type = selector._type_; selector = selector._selector_; } if (selector == FOCUS) { if (focus && focus._button_) { found(select("." + btnClass + "." + focusClass).node()); } else { var win = focus ? focus._window_ : parentWindow; crosstalk._send_(win, 7, { _selector_: selector, _type_: type, _data_: passdata }); } } else if (selector == SELF) { found(thisWindow); } else if (selector == PARENT) { crosstalk._send_(parentWindow, type, passdata); } else { var win = getData(selector)._window_; if (win) { crosstalk._send_(win, type, passdata); } else { found(selector); } } function found(obj) { message_handlers[type].call(obj, passdata); } }
function notify(selector, type, passdata) { if (!type) { passdata = selector._data_; type = selector._type_; selector = selector._selector_; } if (selector == FOCUS) { if (focus && focus._button_) { found(select("." + btnClass + "." + focusClass).node()); } else { var win = focus ? focus._window_ : parentWindow; crosstalk._send_(win, 7, { _selector_: selector, _type_: type, _data_: passdata }); } } else if (selector == SELF) { found(thisWindow); } else if (selector == PARENT) { crosstalk._send_(parentWindow, type, passdata); } else { var win = getData(selector)._window_; if (win) { crosstalk._send_(win, type, passdata); } else { found(selector); } } function found(obj) { message_handlers[type].call(obj, passdata); } }
JavaScript
function goBack() { var state; while (state = backstack.pop()) { if (state[0] != sceneName) { return gotoScene(state[0], state[1]); } } if (parentWindow) { crosstalk._send_(parentWindow, 5); } }
function goBack() { var state; while (state = backstack.pop()) { if (state[0] != sceneName) { return gotoScene(state[0], state[1]); } } if (parentWindow) { crosstalk._send_(parentWindow, 5); } }
JavaScript
function invoke(event) { var node; if ("src" in event) { node = first(iframeNodes, function(n) { // source window? return !event.src.search(n._path_ + "/"); }); } else { node = getData(this); event = new TriggerEvent(this, event._trigger_, event._data_); } var trigger = event.type, passdata = event.data, result = false; var n = node; while (n) { var act = n._actions_; if (act && act[trigger]) { executeAction.call(n._instance_.node(), { _command_: act[trigger], _event_: event }); result = true; break; } n = n._parent_; } if (!result) { if (parentWindow) { // bubble up crosstalk._send_(parentWindow, 4, event); } else { // this is top level, use fallbacks events.fallback.call(this, event); } } }
function invoke(event) { var node; if ("src" in event) { node = first(iframeNodes, function(n) { // source window? return !event.src.search(n._path_ + "/"); }); } else { node = getData(this); event = new TriggerEvent(this, event._trigger_, event._data_); } var trigger = event.type, passdata = event.data, result = false; var n = node; while (n) { var act = n._actions_; if (act && act[trigger]) { executeAction.call(n._instance_.node(), { _command_: act[trigger], _event_: event }); result = true; break; } n = n._parent_; } if (!result) { if (parentWindow) { // bubble up crosstalk._send_(parentWindow, 4, event); } else { // this is top level, use fallbacks events.fallback.call(this, event); } } }
JavaScript
function onLoad(path, callback) { if (path) { windowPath = path; selectAll("." + btnClass).each(function(n) { n._button_._path_ = path; }) pending_load_callback = callback; parentWindow = this.source; } if (iframeNodes.every(isNodeLoaded)) { if (!is_embedded || pending_load_callback) { crosstalk._sendAll_( iframeNodes, 1, function(n) { // make sub path return n._path_ = (windowPath ? windowPath + "/" : "") + n._id_; }, function() { // heard back from all if (pending_load_callback) { pending_load_callback(); } else { // set default focus proposeFocus(); } events.ready.call(this, { isMaster: !is_embedded }); } ); } } }
function onLoad(path, callback) { if (path) { windowPath = path; selectAll("." + btnClass).each(function(n) { n._button_._path_ = path; }) pending_load_callback = callback; parentWindow = this.source; } if (iframeNodes.every(isNodeLoaded)) { if (!is_embedded || pending_load_callback) { crosstalk._sendAll_( iframeNodes, 1, function(n) { // make sub path return n._path_ = (windowPath ? windowPath + "/" : "") + n._id_; }, function() { // heard back from all if (pending_load_callback) { pending_load_callback(); } else { // set default focus proposeFocus(); } events.ready.call(this, { isMaster: !is_embedded }); } ); } } }
JavaScript
function aspectRatioFill(srcWidth, srcHeight, maxWidth, maxHeight) { const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); // const output = { // width: srcWidth * ratio, // height: srcHeight * ratio // }; // return { // width: parseFloat(output.width.toFixed(0)), // height: parseFloat(output.height.toFixed(0)) // }; return { width: srcWidth * ratio, height: srcHeight * ratio }; }
function aspectRatioFill(srcWidth, srcHeight, maxWidth, maxHeight) { const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight); // const output = { // width: srcWidth * ratio, // height: srcHeight * ratio // }; // return { // width: parseFloat(output.width.toFixed(0)), // height: parseFloat(output.height.toFixed(0)) // }; return { width: srcWidth * ratio, height: srcHeight * ratio }; }
JavaScript
function applyRotationToDimensions({ width, height }, rotation) { if (rotation === 90 || rotation === 270) { return { width: height, height: width }; } return { width, height }; }
function applyRotationToDimensions({ width, height }, rotation) { if (rotation === 90 || rotation === 270) { return { width: height, height: width }; } return { width, height }; }
JavaScript
function generateSizesToRender( containerSize, imageSize, padding = 0, rotation = 0 ) { const handledImageSize = applyRotationToDimensions(imageSize, rotation); // console.log(handledImageSize); // This gets us an artboard to work with const artboardSize = aspectRatioFill( handledImageSize.width, handledImageSize.height, containerSize.width, containerSize.height ); // padding must be factored in to create the space the image has to fit in. // a new aspect ratio fill can be applied to preserve image aspect ratio. const availableImageSpace = { width: artboardSize.width - padding * 2, height: artboardSize.height - padding * 2 }; const imageSizeRendered = aspectRatioFill( handledImageSize.width, handledImageSize.height, availableImageSpace.width, availableImageSpace.height ); return { artboardSize, imageSizeRendered }; }
function generateSizesToRender( containerSize, imageSize, padding = 0, rotation = 0 ) { const handledImageSize = applyRotationToDimensions(imageSize, rotation); // console.log(handledImageSize); // This gets us an artboard to work with const artboardSize = aspectRatioFill( handledImageSize.width, handledImageSize.height, containerSize.width, containerSize.height ); // padding must be factored in to create the space the image has to fit in. // a new aspect ratio fill can be applied to preserve image aspect ratio. const availableImageSpace = { width: artboardSize.width - padding * 2, height: artboardSize.height - padding * 2 }; const imageSizeRendered = aspectRatioFill( handledImageSize.width, handledImageSize.height, availableImageSpace.width, availableImageSpace.height ); return { artboardSize, imageSizeRendered }; }
JavaScript
function process(data) { let buf = utils.convertToBuffer(data); if((buf === null) || (buf.length < MIN_DATA_LENGTH_BYTES)) { return null; } let frameType = buf.readUInt8(); switch(frameType) { case 0x00: return processEddystoneUID(buf); case 0x10: return processEddystoneURL(buf); case 0x20: return processEddystoneTLM(buf); } return null; }
function process(data) { let buf = utils.convertToBuffer(data); if((buf === null) || (buf.length < MIN_DATA_LENGTH_BYTES)) { return null; } let frameType = buf.readUInt8(); switch(frameType) { case 0x00: return processEddystoneUID(buf); case 0x10: return processEddystoneURL(buf); case 0x20: return processEddystoneTLM(buf); } return null; }
JavaScript
function processServiceData(uuid, data) { let buf = utils.convertToBuffer(data); uuid = utils.convertToUUID(uuid); if((uuid === null) || (buf === null) || (buf.length < MIN_DATA_LENGTH_BYTES)) { return null; } switch(uuid) { case 'ffe1': return minew.process(data); case 'feaa': return eddystone.process(data); case 'fd6f': return exposurenotification.process(data); } return null; }
function processServiceData(uuid, data) { let buf = utils.convertToBuffer(data); uuid = utils.convertToUUID(uuid); if((uuid === null) || (buf === null) || (buf.length < MIN_DATA_LENGTH_BYTES)) { return null; } switch(uuid) { case 'ffe1': return minew.process(data); case 'feaa': return eddystone.process(data); case 'fd6f': return exposurenotification.process(data); } return null; }
JavaScript
function process(data) { let buf = utils.convertToBuffer(data); if((buf === null) || (buf.length < MIN_DATA_LENGTH_BYTES)) { return null; } let frameType = buf.readUInt8(FRAME_TYPE_OFFSET); if(frameType !== MINEW_FRAME_TYPE) { return null; } let productModel = buf.readUInt8(PRODUCT_MODEL_OFFSET); switch(productModel) { case 0x01: return processTemperatureHumidity(buf); case 0x02: return processVisibleLight(buf); case 0x03: return processAcceleration(buf); case 0x08: return processInfo(buf); } return null; }
function process(data) { let buf = utils.convertToBuffer(data); if((buf === null) || (buf.length < MIN_DATA_LENGTH_BYTES)) { return null; } let frameType = buf.readUInt8(FRAME_TYPE_OFFSET); if(frameType !== MINEW_FRAME_TYPE) { return null; } let productModel = buf.readUInt8(PRODUCT_MODEL_OFFSET); switch(productModel) { case 0x01: return processTemperatureHumidity(buf); case 0x02: return processVisibleLight(buf); case 0x03: return processAcceleration(buf); case 0x08: return processInfo(buf); } return null; }
JavaScript
function processTemperatureHumidity(data) { let isInvalidLength = (data.length !== TEMPERATURE_HUMIDITY_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let temperature = utils.parseSigned88(data.subarray(TEMPERATURE_OFFSET, TEMPERATURE_OFFSET + 2)); let relativeHumidity = utils.parseSigned88(data.subarray(HUMIDITY_OFFSET, HUMIDITY_OFFSET + 2)); return { batteryPercentage: batteryPercentage, temperature: temperature, relativeHumidity: relativeHumidity, uri: MINEW_URI }; }
function processTemperatureHumidity(data) { let isInvalidLength = (data.length !== TEMPERATURE_HUMIDITY_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let temperature = utils.parseSigned88(data.subarray(TEMPERATURE_OFFSET, TEMPERATURE_OFFSET + 2)); let relativeHumidity = utils.parseSigned88(data.subarray(HUMIDITY_OFFSET, HUMIDITY_OFFSET + 2)); return { batteryPercentage: batteryPercentage, temperature: temperature, relativeHumidity: relativeHumidity, uri: MINEW_URI }; }
JavaScript
function processVisibleLight(data) { let isInvalidLength = (data.length !== VISIBLE_LIGHT_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let isVisibleLight = ((data.readUInt8(VISIBLE_LIGHT_OFFSET) & VISIBLE_LIGHT_MASK) === VISIBLE_LIGHT_MASK); return { batteryPercentage: batteryPercentage, isVisibleLight: isVisibleLight, uri: MINEW_URI }; }
function processVisibleLight(data) { let isInvalidLength = (data.length !== VISIBLE_LIGHT_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let isVisibleLight = ((data.readUInt8(VISIBLE_LIGHT_OFFSET) & VISIBLE_LIGHT_MASK) === VISIBLE_LIGHT_MASK); return { batteryPercentage: batteryPercentage, isVisibleLight: isVisibleLight, uri: MINEW_URI }; }
JavaScript
function processAcceleration(data) { let isInvalidLength = (data.length !== ACCELERATION_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let acceleration = [ utils.parseSigned88(data.subarray(ACC_X_OFFSET, ACC_X_OFFSET + 2)), utils.parseSigned88(data.subarray(ACC_Y_OFFSET, ACC_Y_OFFSET + 2)), utils.parseSigned88(data.subarray(ACC_Z_OFFSET, ACC_Z_OFFSET + 2)) ]; return { batteryPercentage: batteryPercentage, acceleration: acceleration, uri: MINEW_URI }; }
function processAcceleration(data) { let isInvalidLength = (data.length !== ACCELERATION_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let acceleration = [ utils.parseSigned88(data.subarray(ACC_X_OFFSET, ACC_X_OFFSET + 2)), utils.parseSigned88(data.subarray(ACC_Y_OFFSET, ACC_Y_OFFSET + 2)), utils.parseSigned88(data.subarray(ACC_Z_OFFSET, ACC_Z_OFFSET + 2)) ]; return { batteryPercentage: batteryPercentage, acceleration: acceleration, uri: MINEW_URI }; }
JavaScript
function processInfo(data) { let isInvalidLength = (data.length < MIN_INFO_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let name = data.toString('utf8', NAME_OFFSET); return { batteryPercentage: batteryPercentage, name: name, uri: MINEW_URI }; }
function processInfo(data) { let isInvalidLength = (data.length < MIN_INFO_FRAME_LENGTH); if(isInvalidLength) { return null; } let batteryPercentage = data.readUInt8(BATTERY_PERCENTAGE_OFFSET); let name = data.toString('utf8', NAME_OFFSET); return { batteryPercentage: batteryPercentage, name: name, uri: MINEW_URI }; }
JavaScript
function process(data) { let buf = utils.convertToBuffer(data); if((buf === null) || (buf.length !== EXPOSURE_NOTIFICATION_LENGTH)) { return null; } let rollingProximityIdentifier = buf.toString('hex', RPI_OFFSET, RPI_OFFSET + RPI_LENGTH); let version = ((buf.readUInt8(VERSION_OFFSET) & MAJOR_VERSION_MASK) >> 6) + '.' + ((buf.readUInt8(VERSION_OFFSET) & MINOR_VERSION_MASK) >> 4); let txPower = buf.readInt8(TX_POWER_OFFSET); return { rollingProximityIdentifier: rollingProximityIdentifier, version: version, txPower: txPower }; }
function process(data) { let buf = utils.convertToBuffer(data); if((buf === null) || (buf.length !== EXPOSURE_NOTIFICATION_LENGTH)) { return null; } let rollingProximityIdentifier = buf.toString('hex', RPI_OFFSET, RPI_OFFSET + RPI_LENGTH); let version = ((buf.readUInt8(VERSION_OFFSET) & MAJOR_VERSION_MASK) >> 6) + '.' + ((buf.readUInt8(VERSION_OFFSET) & MINOR_VERSION_MASK) >> 4); let txPower = buf.readInt8(TX_POWER_OFFSET); return { rollingProximityIdentifier: rollingProximityIdentifier, version: version, txPower: txPower }; }
JavaScript
function convertToUUID(data) { if(Buffer.isBuffer(data)) { return data.toString('hex'); } if(typeof data === 'string') { data = data.toLowerCase(); let isHex = /[0-9a-f]+/.test(data); if(isHex) { return data; } } return null; }
function convertToUUID(data) { if(Buffer.isBuffer(data)) { return data.toString('hex'); } if(typeof data === 'string') { data = data.toLowerCase(); let isHex = /[0-9a-f]+/.test(data); if(isHex) { return data; } } return null; }
JavaScript
function CommandUI() { var Views = require('../views'); var Collections = require('../models/collections'); var CommandViews = require('../views/commandViews'); var mainHelperBar = new Views.MainHelperBar(); var backgroundView = new Views.BackgroundView(); this.commandCollection = new Collections.CommandCollection(); this.commandBuffer = new Collections.CommandBuffer({ collection: this.commandCollection }); this.commandPromptView = new CommandViews.CommandPromptView({ el: $('#commandLineBar') }); this.commandLineHistoryView = new CommandViews.CommandLineHistoryView({ el: $('#commandLineHistory'), collection: this.commandCollection }); }
function CommandUI() { var Views = require('../views'); var Collections = require('../models/collections'); var CommandViews = require('../views/commandViews'); var mainHelperBar = new Views.MainHelperBar(); var backgroundView = new Views.BackgroundView(); this.commandCollection = new Collections.CommandCollection(); this.commandBuffer = new Collections.CommandBuffer({ collection: this.commandCollection }); this.commandPromptView = new CommandViews.CommandPromptView({ el: $('#commandLineBar') }); this.commandLineHistoryView = new CommandViews.CommandLineHistoryView({ el: $('#commandLineHistory'), collection: this.commandCollection }); }
JavaScript
renderGet () { console.log(this.getParams['id']) if(this.getParams['id']) { document.querySelector('body').style.overflow = 'hidden' this.$pictureContainer.innerHTML = returnGetPicture(this.data, this.getParams['id']) this.showPicture() this.pictureAnimation() this.picturePopup() } }
renderGet () { console.log(this.getParams['id']) if(this.getParams['id']) { document.querySelector('body').style.overflow = 'hidden' this.$pictureContainer.innerHTML = returnGetPicture(this.data, this.getParams['id']) this.showPicture() this.pictureAnimation() this.picturePopup() } }
JavaScript
function executeIfVersion (testVersion, func, args) { if (helper.versionCompare(helper.getDseVersion(), testVersion)) { func.apply(this, args); } }
function executeIfVersion (testVersion, func, args) { if (helper.versionCompare(helper.getDseVersion(), testVersion)) { func.apply(this, args); } }
JavaScript
function inside(centerOrShape, radius, unit) { if (centerOrShape instanceof geometry.Point) { validateUnit(unit); return new GeoP('inside', new Distance(centerOrShape, toDegrees(radius, unit))); } if (!(centerOrShape instanceof geometry.Polygon)) { throw new TypeError('geo.inside() only supports Polygons or Points with distance'); } return new GeoP('insideCartesian', centerOrShape); }
function inside(centerOrShape, radius, unit) { if (centerOrShape instanceof geometry.Point) { validateUnit(unit); return new GeoP('inside', new Distance(centerOrShape, toDegrees(radius, unit))); } if (!(centerOrShape instanceof geometry.Polygon)) { throw new TypeError('geo.inside() only supports Polygons or Points with distance'); } return new GeoP('insideCartesian', centerOrShape); }
JavaScript
function Distance(center, radius) { if(!(center instanceof geometry.Point)) { throw new TypeError('center must be an instanceof Point'); } if(isNaN(radius)) { throw new TypeError('radius must be a number'); } /** * Returns the center point. * @type {geometry.Point} */ this.center = center; /** * Returns the radius of the circle. * @type {Number} */ this.radius = radius; }
function Distance(center, radius) { if(!(center instanceof geometry.Point)) { throw new TypeError('center must be an instanceof Point'); } if(isNaN(radius)) { throw new TypeError('radius must be a number'); } /** * Returns the center point. * @type {geometry.Point} */ this.center = center; /** * Returns the radius of the circle. * @type {Number} */ this.radius = radius; }
JavaScript
function checkStatus(){ if(option1!=null && option2!=null){ document.getElementById('compareChoicesButton').removeAttribute('disabled') } }
function checkStatus(){ if(option1!=null && option2!=null){ document.getElementById('compareChoicesButton').removeAttribute('disabled') } }
JavaScript
function loadResults(type){ if(type=='sushi'){ document.getElementById("resultsLocCafe").style.display='none' document.getElementById("resultsLocSushi").style.display='block' window.sessionStorage.setItem("searchTerm",'sushi') } else{ document.getElementById("resultsLocSushi").style.display='none' document.getElementById("resultsLocCafe").style.display='block' window.sessionStorage.setItem("searchTerm",'cafe') } }
function loadResults(type){ if(type=='sushi'){ document.getElementById("resultsLocCafe").style.display='none' document.getElementById("resultsLocSushi").style.display='block' window.sessionStorage.setItem("searchTerm",'sushi') } else{ document.getElementById("resultsLocSushi").style.display='none' document.getElementById("resultsLocCafe").style.display='block' window.sessionStorage.setItem("searchTerm",'cafe') } }
JavaScript
function dijkstra(grid, startNode, finishNode) { const visitedNodesInOrder = []; startNode.distance = 0; const unvisitedNodes = getAllNodes(grid); while (!!unvisitedNodes.length) { // Should create the unvisited nodes by visiting the neighbors of the starting nodes. Then add more nodes sortNodesByDistance(unvisitedNodes); const closestNode = unvisitedNodes.shift(); // If we encounter a wall, we skip it. if (closestNode.isWall) continue; // If the closest node is at a distance of infinity, // we must be trapped and should therefore stop. if (closestNode.distance === Infinity) return visitedNodesInOrder; closestNode.isVisited = true; visitedNodesInOrder.push(closestNode); if (closestNode === finishNode) return visitedNodesInOrder; updateUnvisitedNeighbors(closestNode, grid); } }
function dijkstra(grid, startNode, finishNode) { const visitedNodesInOrder = []; startNode.distance = 0; const unvisitedNodes = getAllNodes(grid); while (!!unvisitedNodes.length) { // Should create the unvisited nodes by visiting the neighbors of the starting nodes. Then add more nodes sortNodesByDistance(unvisitedNodes); const closestNode = unvisitedNodes.shift(); // If we encounter a wall, we skip it. if (closestNode.isWall) continue; // If the closest node is at a distance of infinity, // we must be trapped and should therefore stop. if (closestNode.distance === Infinity) return visitedNodesInOrder; closestNode.isVisited = true; visitedNodesInOrder.push(closestNode); if (closestNode === finishNode) return visitedNodesInOrder; updateUnvisitedNeighbors(closestNode, grid); } }
JavaScript
async function processTemplateTree(node, targetPath, replacers) { if (node.children) { await processDirectory(node, targetPath, replacers); } else { await processFile(node, targetPath, replacers); } }
async function processTemplateTree(node, targetPath, replacers) { if (node.children) { await processDirectory(node, targetPath, replacers); } else { await processFile(node, targetPath, replacers); } }
JavaScript
function normalizeModuleName(name) { const normalized = name .split(' ') .map(part => part.toLowerCase()) .join('-'); const results = validate(normalized); if (!results['validForNewPackages']) { throw [].concat(results['errors'] || [], results['warnings'] || []); } return normalized; }
function normalizeModuleName(name) { const normalized = name .split(' ') .map(part => part.toLowerCase()) .join('-'); const results = validate(normalized); if (!results['validForNewPackages']) { throw [].concat(results['errors'] || [], results['warnings'] || []); } return normalized; }
JavaScript
function findTemplateBasedProjectRoot(startPath = process.cwd()) { if (path.resolve(startPath, '..') === path.resolve(startPath)) { return false; // reached root dir } const searchPath = path.resolve(startPath, projectIdentifierFileName); if ( fs.existsSync(searchPath) && fs.readFileSync(searchPath).toString().trim() === projectIdentifierFileContent.trim() ) { return path.dirname(searchPath); } else { return findTemplateBasedProjectRoot(path.resolve(startPath, '..')); } }
function findTemplateBasedProjectRoot(startPath = process.cwd()) { if (path.resolve(startPath, '..') === path.resolve(startPath)) { return false; // reached root dir } const searchPath = path.resolve(startPath, projectIdentifierFileName); if ( fs.existsSync(searchPath) && fs.readFileSync(searchPath).toString().trim() === projectIdentifierFileContent.trim() ) { return path.dirname(searchPath); } else { return findTemplateBasedProjectRoot(path.resolve(startPath, '..')); } }
JavaScript
async function compileReactApp() { // Disable the PREFLIGHT_CHECK as react-scripts, otherwise, aborts warning about multiple webpack versions. process.env.SKIP_PREFLIGHT_CHECK = 'true'; // craco, in the background, imports (and runs) the `react-scripts build` script. // Unfortunately, that script runs asynchronously and there's no nice way to detect completion. // To run tasks after compiling the React app in the right order, we therefore inject `console.log` // with a custom function. If `react-scripts` logs "Compiled successfully.", we know that the compilation is complete. const originalConsoleLog = console.log; /** * A promise that resolves when the injected `console.log` function got called with `'Compiled successfully.'` * @type {Promise<void>} */ const promise = new Promise(resolve => { console.log = (...message) => { originalConsoleLog(...message); // log the content to the actual console, as well if ( message[0] && message[0].includes && message[0].includes('Compiled successfully.') ) { // Set a timeout to allow for final messages to get printed before continuing // while 'Compiled successfully.' is the string that easiest to detect, a // few lines follow it in the log. setTimeout(resolve, 250); } }; }); // `build`, internally, overrides the require-cache to inject a custom config into `react-scripts`. // Then, it just imports (and thus, runs) the `react-scripts build` script. const { build } = require(`@craco/craco/lib/cra`); build({ // craco config reactScriptsVersion: 'react-scripts' }); await promise; // await completion of the build step // reset `console.log` override: console.log = originalConsoleLog; }
async function compileReactApp() { // Disable the PREFLIGHT_CHECK as react-scripts, otherwise, aborts warning about multiple webpack versions. process.env.SKIP_PREFLIGHT_CHECK = 'true'; // craco, in the background, imports (and runs) the `react-scripts build` script. // Unfortunately, that script runs asynchronously and there's no nice way to detect completion. // To run tasks after compiling the React app in the right order, we therefore inject `console.log` // with a custom function. If `react-scripts` logs "Compiled successfully.", we know that the compilation is complete. const originalConsoleLog = console.log; /** * A promise that resolves when the injected `console.log` function got called with `'Compiled successfully.'` * @type {Promise<void>} */ const promise = new Promise(resolve => { console.log = (...message) => { originalConsoleLog(...message); // log the content to the actual console, as well if ( message[0] && message[0].includes && message[0].includes('Compiled successfully.') ) { // Set a timeout to allow for final messages to get printed before continuing // while 'Compiled successfully.' is the string that easiest to detect, a // few lines follow it in the log. setTimeout(resolve, 250); } }; }); // `build`, internally, overrides the require-cache to inject a custom config into `react-scripts`. // Then, it just imports (and thus, runs) the `react-scripts build` script. const { build } = require(`@craco/craco/lib/cra`); build({ // craco config reactScriptsVersion: 'react-scripts' }); await promise; // await completion of the build step // reset `console.log` override: console.log = originalConsoleLog; }
JavaScript
async function runWebpackCompilerAsync(compiler) { await new Promise((resolve, reject) => { compiler.run((err, res) => { if (err) { return reject(err); } else if (res.compilation.errors && res.compilation.errors.length) { return reject(new Error(res.compilation.errors.join('\n\n'))); } if (res.compilation.warnings && res.compilation.warnings.length) { logger.warn('Compiled with warnings:'); for (let warning of res.compilation.warnings) { console.warn(warning); } } resolve(res); }); }); }
async function runWebpackCompilerAsync(compiler) { await new Promise((resolve, reject) => { compiler.run((err, res) => { if (err) { return reject(err); } else if (res.compilation.errors && res.compilation.errors.length) { return reject(new Error(res.compilation.errors.join('\n\n'))); } if (res.compilation.warnings && res.compilation.warnings.length) { logger.warn('Compiled with warnings:'); for (let warning of res.compilation.warnings) { console.warn(warning); } } resolve(res); }); }); }
JavaScript
function updateDependenciesObject(dependencies, packageNames, version) { if (typeof dependencies !== 'object' || Array.isArray(dependencies)) { throw new Error('The dependencies property has an invalid type.'); } return Object.keys(dependencies).reduce((accumulator, key) => { if (packageNames.includes(key)) { accumulator[key] = version; } else { accumulator[key] = dependencies[key]; } return accumulator; }, {}); }
function updateDependenciesObject(dependencies, packageNames, version) { if (typeof dependencies !== 'object' || Array.isArray(dependencies)) { throw new Error('The dependencies property has an invalid type.'); } return Object.keys(dependencies).reduce((accumulator, key) => { if (packageNames.includes(key)) { accumulator[key] = version; } else { accumulator[key] = dependencies[key]; } return accumulator; }, {}); }
JavaScript
function replacePackageVersions(packageJson, packageNames, version) { if (typeof packageJson !== 'object' || Array.isArray(packageJson)) { throw new Error('package.json has invalid type.'); } // update dependencies const newDependencies = 'dependencies' in packageJson ? updateDependenciesObject( packageJson.dependencies, packageNames, version ) : {}; // update devDependencies const newDevDependencies = 'devDependencies' in packageJson ? updateDependenciesObject( packageJson.devDependencies, packageNames, version ) : {}; return { ...packageJson, dependencies: newDependencies, devDependencies: newDevDependencies, version }; }
function replacePackageVersions(packageJson, packageNames, version) { if (typeof packageJson !== 'object' || Array.isArray(packageJson)) { throw new Error('package.json has invalid type.'); } // update dependencies const newDependencies = 'dependencies' in packageJson ? updateDependenciesObject( packageJson.dependencies, packageNames, version ) : {}; // update devDependencies const newDevDependencies = 'devDependencies' in packageJson ? updateDependenciesObject( packageJson.devDependencies, packageNames, version ) : {}; return { ...packageJson, dependencies: newDependencies, devDependencies: newDevDependencies, version }; }
JavaScript
function editPackageJson(packagePath, packageNames, version) { const packageJsonPath = path.join(packagePath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { console.warn('package.json does not exist in package:', packagePath); return; } // load package.json const packageJson = require(packageJsonPath); console.log('Replace versions for package:', packageJson.name); // edit it const newPackageJson = replacePackageVersions( packageJson, packageNames, version ); // and store them fs.writeFileSync( packageJsonPath, JSON.stringify(newPackageJson, null, '\t'), { encoding: 'utf-8' } ); }
function editPackageJson(packagePath, packageNames, version) { const packageJsonPath = path.join(packagePath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { console.warn('package.json does not exist in package:', packagePath); return; } // load package.json const packageJson = require(packageJsonPath); console.log('Replace versions for package:', packageJson.name); // edit it const newPackageJson = replacePackageVersions( packageJson, packageNames, version ); // and store them fs.writeFileSync( packageJsonPath, JSON.stringify(newPackageJson, null, '\t'), { encoding: 'utf-8' } ); }
JavaScript
function modifyFile(filePath, replacers) { const lines = fs .readFileSync(filePath, 'utf8') .toString() .split('\r\n') .join('\n') .split('\n'); for (let replacer of replacers) { const insertionMarkLineIndex = lines.findIndex(line => line.includes(replacer.needle) ); const newLines = [ lines[insertionMarkLineIndex].replace(replacer.needle, replacer.text) ]; if (replacer.position === INSERT_ABOVE) { newLines.push(lines[insertionMarkLineIndex]); } else if (replacer.position === INSERT_BELOW) { newLines.unshift(lines[insertionMarkLineIndex]); } else if (replacer.position !== REPLACE) { throw new Error( 'Internal Error: No valid position specified in replacer passed to modifyFile. ' + 'This is an internal error, and as a user, you should never get to see this. Somehow, something seems ' + 'to have mal-functioned. If you could report this (including the output) to the Telestion Team, ' + 'we would appreciate that a lot. Sorry, and thank you in advance.' ); } lines.splice(insertionMarkLineIndex, 1, ...newLines); } fs.writeFileSync(filePath, lines.join('\n')); }
function modifyFile(filePath, replacers) { const lines = fs .readFileSync(filePath, 'utf8') .toString() .split('\r\n') .join('\n') .split('\n'); for (let replacer of replacers) { const insertionMarkLineIndex = lines.findIndex(line => line.includes(replacer.needle) ); const newLines = [ lines[insertionMarkLineIndex].replace(replacer.needle, replacer.text) ]; if (replacer.position === INSERT_ABOVE) { newLines.push(lines[insertionMarkLineIndex]); } else if (replacer.position === INSERT_BELOW) { newLines.unshift(lines[insertionMarkLineIndex]); } else if (replacer.position !== REPLACE) { throw new Error( 'Internal Error: No valid position specified in replacer passed to modifyFile. ' + 'This is an internal error, and as a user, you should never get to see this. Somehow, something seems ' + 'to have mal-functioned. If you could report this (including the output) to the Telestion Team, ' + 'we would appreciate that a lot. Sorry, and thank you in advance.' ); } lines.splice(insertionMarkLineIndex, 1, ...newLines); } fs.writeFileSync(filePath, lines.join('\n')); }
JavaScript
async function prepareEnvironment() { logger.info('Reading configuration'); const config = await getConfig(); logger.success('Found configuration file at: ' + config['filepath']); logger.debug('Config', config); let projectRoot = path.dirname(config['filepath']); process.chdir(projectRoot); return { config: config['config'], projectRoot }; }
async function prepareEnvironment() { logger.info('Reading configuration'); const config = await getConfig(); logger.success('Found configuration file at: ' + config['filepath']); logger.debug('Config', config); let projectRoot = path.dirname(config['filepath']); process.chdir(projectRoot); return { config: config['config'], projectRoot }; }
JavaScript
function hasForbiddenMethod(node) { const properties = astUtil.getComponentProperties(node); return properties.find(property => { const name = astUtil.getPropertyName(property); return DEPRECATED_LIFECYCLE.indexOf(name) >= 0 || config.forbiddenMethods.indexOf(name) >= 0; }); }
function hasForbiddenMethod(node) { const properties = astUtil.getComponentProperties(node); return properties.find(property => { const name = astUtil.getPropertyName(property); return DEPRECATED_LIFECYCLE.indexOf(name) >= 0 || config.forbiddenMethods.indexOf(name) >= 0; }); }
JavaScript
function checkForViolation(node) { const property = hasForbiddenMethod(node); if ((utils.isES5Component(node) || utils.isES6Component(node)) && typeof property === 'object') { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has forbidden method ${astUtil.getPropertyName(property)}` }); } }
function checkForViolation(node) { const property = hasForbiddenMethod(node); if ((utils.isES5Component(node) || utils.isES6Component(node)) && typeof property === 'object') { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has forbidden method ${astUtil.getPropertyName(property)}` }); } }
JavaScript
function checkForViolation(node) { const expression = astUtil.getComponentProperties(node); if (expression.type === 'AssignmentExpression') { if (expression.left.type === 'MemberExpression') { // check if property of window is location if ( expression.left.object && expression.left.object.name === 'window' && expression.left.property && expression.left.property.name === 'location' && (expression.right.type === 'Literal' || expression.right.type === 'Identifier' || (expression.right.type === 'CallExpression' && expression.right.callee.type === 'Identifier' && config.wrapperName.indexOf(expression.right.callee.name) === -1)) ) { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has violation code(s) : XSS attack : ${astUtil.getPropertyName( expression.left )}` }); return; } // check if property of window is hash else if ( expression.left.object.object && expression.left.object.object.name === 'window' && expression.left.object.property && expression.left.object.property.name === 'location' && expression.left.property.name === 'hash' && (expression.right.type === 'Literal' || expression.right.type === 'Identifier' || (expression.right.type === 'CallExpression' && expression.right.callee.type === 'Identifier' && config.wrapperName.indexOf(expression.right.callee.name) === -1)) ) { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has violation code(s) : XSS attack : ${astUtil.getPropertyName( expression.left )}` }); return; } } } // check if property of window is location.assign else if ( expression.type === 'CallExpression' && expression.callee.object && expression.callee.object.object && expression.callee.object.object.name === 'window' && expression.callee.object.property.name === 'location' && expression.callee.property.name === 'assign' && (expression.arguments[0].type === 'Literal' || expression.arguments[0].type === 'Identifier' || (expression.arguments[0].type === 'CallExpression' && expression.arguments[0].callee.type === 'Identifier' && config.wrapperName.indexOf(expression.arguments[0].callee.name) === -1)) ) { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has violation code(s) : XSS attack : ${astUtil.getPropertyName( expression.callee )}` }); return; } return; }
function checkForViolation(node) { const expression = astUtil.getComponentProperties(node); if (expression.type === 'AssignmentExpression') { if (expression.left.type === 'MemberExpression') { // check if property of window is location if ( expression.left.object && expression.left.object.name === 'window' && expression.left.property && expression.left.property.name === 'location' && (expression.right.type === 'Literal' || expression.right.type === 'Identifier' || (expression.right.type === 'CallExpression' && expression.right.callee.type === 'Identifier' && config.wrapperName.indexOf(expression.right.callee.name) === -1)) ) { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has violation code(s) : XSS attack : ${astUtil.getPropertyName( expression.left )}` }); return; } // check if property of window is hash else if ( expression.left.object.object && expression.left.object.object.name === 'window' && expression.left.object.property && expression.left.object.property.name === 'location' && expression.left.property.name === 'hash' && (expression.right.type === 'Literal' || expression.right.type === 'Identifier' || (expression.right.type === 'CallExpression' && expression.right.callee.type === 'Identifier' && config.wrapperName.indexOf(expression.right.callee.name) === -1)) ) { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has violation code(s) : XSS attack : ${astUtil.getPropertyName( expression.left )}` }); return; } } } // check if property of window is location.assign else if ( expression.type === 'CallExpression' && expression.callee.object && expression.callee.object.object && expression.callee.object.object.name === 'window' && expression.callee.object.property.name === 'location' && expression.callee.property.name === 'assign' && (expression.arguments[0].type === 'Literal' || expression.arguments[0].type === 'Identifier' || (expression.arguments[0].type === 'CallExpression' && expression.arguments[0].callee.type === 'Identifier' && config.wrapperName.indexOf(expression.arguments[0].callee.name) === -1)) ) { context.report({ node: node, message: `ERROR - ${getNodeName(node)} has violation code(s) : XSS attack : ${astUtil.getPropertyName( expression.callee )}` }); return; } return; }
JavaScript
function successWrapper(result) { for (strFormat in scanFormats) { if (result.format === scanFormats[strFormat]) { success.call(null, resultFormats[strFormat], result.value); return; } } cancel.call(null); }
function successWrapper(result) { for (strFormat in scanFormats) { if (result.format === scanFormats[strFormat]) { success.call(null, resultFormats[strFormat], result.value); return; } } cancel.call(null); }
JavaScript
function onEachFeature(feature, layer) { layer.bindPopup("<h3>" + feature.properties.place + "</h3>" + "<hr>" + "<h3>" + feature.properties.mag + "</h3>" + "<hr>" + "<p>" + new Date(feature.properties.time) + "</p>"); }
function onEachFeature(feature, layer) { layer.bindPopup("<h3>" + feature.properties.place + "</h3>" + "<hr>" + "<h3>" + feature.properties.mag + "</h3>" + "<hr>" + "<p>" + new Date(feature.properties.time) + "</p>"); }
JavaScript
function addNewMarker (title, loc, content, array) { //Convert loc input to a latlng literal var location = { lat: loc.latitude, lng: loc.longitude, }; // Create a new infowindow. var infowindow = new google.maps.InfoWindow({ content: content, maxWidth: 300 }); // Create a marker. var marker = new google.maps.Marker({ position: location, map: map, title: title, animation: google.maps.Animation.DROP, info: infowindow }); // Click on the marker to open the info window. marker.addListener('click', function() { infowindow.open(map, marker); marker.setAnimation(4); }); marker.addListener('mouseover', function() { toggleBounceOn(marker); }); array.push(marker); }
function addNewMarker (title, loc, content, array) { //Convert loc input to a latlng literal var location = { lat: loc.latitude, lng: loc.longitude, }; // Create a new infowindow. var infowindow = new google.maps.InfoWindow({ content: content, maxWidth: 300 }); // Create a marker. var marker = new google.maps.Marker({ position: location, map: map, title: title, animation: google.maps.Animation.DROP, info: infowindow }); // Click on the marker to open the info window. marker.addListener('click', function() { infowindow.open(map, marker); marker.setAnimation(4); }); marker.addListener('mouseover', function() { toggleBounceOn(marker); }); array.push(marker); }
JavaScript
function clearMarkers (map) { for (var i = 0; i < yelpMarkers.length; i++) { yelpMarkers[i].setMap(null); yelpMarkers = []; } }
function clearMarkers (map) { for (var i = 0; i < yelpMarkers.length; i++) { yelpMarkers[i].setMap(null); yelpMarkers = []; } }
JavaScript
function filterMarkers () { for (var i = 0; i < markers.length; i++) { if (markers[i].title.toUpperCase().indexOf(term().toUpperCase()) > -1) { markers[i].setVisible(true); } else { markers[i].setVisible(false); } } for (var i = 0; i < yelpMarkers.length; i++) { if (yelpMarkers[i].title.toUpperCase().indexOf(term().toUpperCase()) > -1) { yelpMarkers[i].setVisible(true); } else { yelpMarkers[i].setVisible(false); } } }
function filterMarkers () { for (var i = 0; i < markers.length; i++) { if (markers[i].title.toUpperCase().indexOf(term().toUpperCase()) > -1) { markers[i].setVisible(true); } else { markers[i].setVisible(false); } } for (var i = 0; i < yelpMarkers.length; i++) { if (yelpMarkers[i].title.toUpperCase().indexOf(term().toUpperCase()) > -1) { yelpMarkers[i].setVisible(true); } else { yelpMarkers[i].setVisible(false); } } }
JavaScript
function zoomFav () { var location = { lat: this.coordinates.latitude, lng: this.coordinates.longitude, }; // Loop through array of markers for (var i = 0; i < markers.length; i++) { // Compare this DOM element to the markers. if (this.name == markers[i].title) { // Intiate the marker bounce. google.maps.event.trigger(markers[i], 'click'); toggleBounceOn(markers[i]); } } map.setZoom(12); map.setCenter(location); hideNav(); }
function zoomFav () { var location = { lat: this.coordinates.latitude, lng: this.coordinates.longitude, }; // Loop through array of markers for (var i = 0; i < markers.length; i++) { // Compare this DOM element to the markers. if (this.name == markers[i].title) { // Intiate the marker bounce. google.maps.event.trigger(markers[i], 'click'); toggleBounceOn(markers[i]); } } map.setZoom(12); map.setCenter(location); hideNav(); }
JavaScript
function zoomYelp () { var location = { lat: this.coordinates.latitude, lng: this.coordinates.longitude, }; // Loop through array of yelp markers for (var i = 0; i < yelpMarkers.length; i++) { // Compare this DOM element to the markers. if (this.name == yelpMarkers[i].title) { // Intiate the marker bounce. google.maps.event.trigger(yelpMarkers[i], 'click'); toggleBounceOn(yelpMarkers[i]); } } map.setZoom(12); map.setCenter(location); hideNav(); }
function zoomYelp () { var location = { lat: this.coordinates.latitude, lng: this.coordinates.longitude, }; // Loop through array of yelp markers for (var i = 0; i < yelpMarkers.length; i++) { // Compare this DOM element to the markers. if (this.name == yelpMarkers[i].title) { // Intiate the marker bounce. google.maps.event.trigger(yelpMarkers[i], 'click'); toggleBounceOn(yelpMarkers[i]); } } map.setZoom(12); map.setCenter(location); hideNav(); }
JavaScript
function zoomOut () { var location = {lat: 34.0686208, lng: -117.9389526}; map.setZoom(10); map.setCenter(location); }
function zoomOut () { var location = {lat: 34.0686208, lng: -117.9389526}; map.setZoom(10); map.setCenter(location); }
JavaScript
function toggleNav () { if (toggle === true) { hideNav(); } else if (toggle === false) { showNav(); } }
function toggleNav () { if (toggle === true) { hideNav(); } else if (toggle === false) { showNav(); } }
JavaScript
function selectFirstWordOfContentEdtiableDiv(element) { element.focus(); document.execCommand("selectAll", false, null); var sel = window.getSelection(); var range = sel.getRangeAt(0); console.log(range); range.setStart(sel.baseNode, 0); range.setEnd(sel.baseNode, 0); sel.modify("extend", "forward", "word"); }
function selectFirstWordOfContentEdtiableDiv(element) { element.focus(); document.execCommand("selectAll", false, null); var sel = window.getSelection(); var range = sel.getRangeAt(0); console.log(range); range.setStart(sel.baseNode, 0); range.setEnd(sel.baseNode, 0); sel.modify("extend", "forward", "word"); }
JavaScript
function resolveTsconfigPathsToAlias({ tsconfigPath = "./tsconfig.json", webpackConfigBasePath = __dirname } = {}) { const { paths } = require(tsconfigPath).compilerOptions; const aliases = {}; const getItemName = (alias) => path.resolve(webpackConfigBasePath, alias.replace("/*", "").replace("*", "")); paths && Object.keys(paths).forEach((item) => { const modifiedKey = item.replace("/*", ""); const aliasItems = paths[item]; const processedAliases = Array.isArray(aliasItems) ? aliasItems.map((alias) => getItemName(alias)) : getItemName(aliasItems); aliases[modifiedKey] = processedAliases; }); return aliases; }
function resolveTsconfigPathsToAlias({ tsconfigPath = "./tsconfig.json", webpackConfigBasePath = __dirname } = {}) { const { paths } = require(tsconfigPath).compilerOptions; const aliases = {}; const getItemName = (alias) => path.resolve(webpackConfigBasePath, alias.replace("/*", "").replace("*", "")); paths && Object.keys(paths).forEach((item) => { const modifiedKey = item.replace("/*", ""); const aliasItems = paths[item]; const processedAliases = Array.isArray(aliasItems) ? aliasItems.map((alias) => getItemName(alias)) : getItemName(aliasItems); aliases[modifiedKey] = processedAliases; }); return aliases; }
JavaScript
function sendNotification(title, options = {}) { if ( getCookie('domjudge_notify')!=1 ) return; // Check if we already sent this notification: var senttags = localStorage.getItem('domjudge_notifications_sent'); if ( senttags===null || senttags==='' ) { senttags = []; } else { senttags = senttags.split(','); } if ( options.tag!==null && senttags.indexOf(options.tag)>=0 ) { return; } var link = null; if ( typeof options.link !== 'undefined' ) { link = options.link; delete options.link; } options['icon'] = domjudge_base_url + '/apple-touch-icon.png'; var not = new Notification(title, options); if ( link!==null ) { not.onclick = function() { window.open(link); } } if ( options.tag!==null ) { senttags.push(options.tag); localStorage.setItem('domjudge_notifications_sent',senttags.join(',')); } }
function sendNotification(title, options = {}) { if ( getCookie('domjudge_notify')!=1 ) return; // Check if we already sent this notification: var senttags = localStorage.getItem('domjudge_notifications_sent'); if ( senttags===null || senttags==='' ) { senttags = []; } else { senttags = senttags.split(','); } if ( options.tag!==null && senttags.indexOf(options.tag)>=0 ) { return; } var link = null; if ( typeof options.link !== 'undefined' ) { link = options.link; delete options.link; } options['icon'] = domjudge_base_url + '/apple-touch-icon.png'; var not = new Notification(title, options); if ( link!==null ) { not.onclick = function() { window.open(link); } } if ( options.tag!==null ) { senttags.push(options.tag); localStorage.setItem('domjudge_notifications_sent',senttags.join(',')); } }
JavaScript
function postVerifyCommentToICAT(url, user, teamid, probid, submissionid) { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", url); form.setAttribute("hidden", true); // setting form target to a window named 'formresult' form.setAttribute("target", "formresult"); function addField(name, value) { var field = document.createElement("input"); field.setAttribute("name", name); field.setAttribute("id", name); field.setAttribute("value", value); form.appendChild(field); } var msg = document.getElementById("comment").value; addField("user", user); addField("priority", 1); addField("submission", submissionid); addField("text", "Team #t"+teamid+" on problem #p"+probid+": "+msg); document.body.appendChild(form); // creating the 'formresult' window prior to submitting the form window.open('about:blank', 'formresult'); form.submit(); }
function postVerifyCommentToICAT(url, user, teamid, probid, submissionid) { var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", url); form.setAttribute("hidden", true); // setting form target to a window named 'formresult' form.setAttribute("target", "formresult"); function addField(name, value) { var field = document.createElement("input"); field.setAttribute("name", name); field.setAttribute("id", name); field.setAttribute("value", value); form.appendChild(field); } var msg = document.getElementById("comment").value; addField("user", user); addField("priority", 1); addField("submission", submissionid); addField("text", "Team #t"+teamid+" on problem #p"+probid+": "+msg); document.body.appendChild(form); // creating the 'formresult' window prior to submitting the form window.open('about:blank', 'formresult'); form.submit(); }
JavaScript
createSVG(element) { const index = element.getAttribute('data-pie-index'); const json = JSON.parse(element.getAttribute('data-pie')); const options = { ...defaultOptions, ...json, index, ...this.globalObj }; const svg = createNSElement('svg'); const configSVG = { role: 'progressbar', width: options.size, height: options.size, viewBox: '0 0 100 100', 'aria-valuemin': '0', 'aria-valuemax': '100', }; setAttribute(svg, configSVG); // colorCircle if (options.colorCircle) { svg.appendChild(this.circle(options)); } // gradient if (options.lineargradient) { svg.appendChild(gradient(options)); } svg.appendChild(this.circle(options, 'top')); element.appendChild(svg); this.progress(svg, element, options); }
createSVG(element) { const index = element.getAttribute('data-pie-index'); const json = JSON.parse(element.getAttribute('data-pie')); const options = { ...defaultOptions, ...json, index, ...this.globalObj }; const svg = createNSElement('svg'); const configSVG = { role: 'progressbar', width: options.size, height: options.size, viewBox: '0 0 100 100', 'aria-valuemin': '0', 'aria-valuemax': '100', }; setAttribute(svg, configSVG); // colorCircle if (options.colorCircle) { svg.appendChild(this.circle(options)); } // gradient if (options.lineargradient) { svg.appendChild(gradient(options)); } svg.appendChild(this.circle(options, 'top')); element.appendChild(svg); this.progress(svg, element, options); }
JavaScript
function unsupported() { // Reference as exports.checkSupport so that we can stub it for testing. var result = exports.checkSupport(); function fallback(message, severity) { if (severity === annotator.notification.ERROR) { console.error(message); return; } console.log(message); } function notifyUser(app) { if (result.supported) { return; } var notify = app.registry.queryUtility('notifier') || fallback; var msg; msg = _t("Sorry, Annotator does not currently support your browser! "); msg += _t("Errors: "); msg += result.errors.join(", "); notify(msg); } return { start: notifyUser }; }
function unsupported() { // Reference as exports.checkSupport so that we can stub it for testing. var result = exports.checkSupport(); function fallback(message, severity) { if (severity === annotator.notification.ERROR) { console.error(message); return; } console.log(message); } function notifyUser(app) { if (result.supported) { return; } var notify = app.registry.queryUtility('notifier') || fallback; var msg; msg = _t("Sorry, Annotator does not currently support your browser! "); msg += _t("Errors: "); msg += result.errors.join(", "); notify(msg); } return { start: notifyUser }; }
JavaScript
function disableButtons(counter_max, counter_current) { $('#show-previous-image, #show-next-image') .show(); if (counter_max === counter_current) { $('#show-next-image') .hide(); } else if (counter_current === 1) { $('#show-previous-image') .hide(); } }
function disableButtons(counter_max, counter_current) { $('#show-previous-image, #show-next-image') .show(); if (counter_max === counter_current) { $('#show-next-image') .hide(); } else if (counter_current === 1) { $('#show-previous-image') .hide(); } }
JavaScript
function loadGallery(setIDs, setClickAttr) { let current_image, selector, counter = 0; $('#show-next-image, #show-previous-image') .click(function () { if ($(this) .attr('id') === 'show-previous-image') { current_image--; } else { current_image++; } selector = $('[data-image-id="' + current_image + '"]'); updateGallery(selector); }); function updateGallery(selector) { let $sel = selector; current_image = $sel.data('image-id'); $('#image-gallery-title') .text($sel.data('title')); $('#image-gallery-image') .attr('src', $sel.data('image')); disableButtons(counter, $sel.data('image-id')); } if (setIDs == true) { $('[data-image-id]') .each(function () { counter++; $(this) .attr('data-image-id', counter); }); } $(setClickAttr) .on('click', function () { updateGallery($(this)); }); }
function loadGallery(setIDs, setClickAttr) { let current_image, selector, counter = 0; $('#show-next-image, #show-previous-image') .click(function () { if ($(this) .attr('id') === 'show-previous-image') { current_image--; } else { current_image++; } selector = $('[data-image-id="' + current_image + '"]'); updateGallery(selector); }); function updateGallery(selector) { let $sel = selector; current_image = $sel.data('image-id'); $('#image-gallery-title') .text($sel.data('title')); $('#image-gallery-image') .attr('src', $sel.data('image')); disableButtons(counter, $sel.data('image-id')); } if (setIDs == true) { $('[data-image-id]') .each(function () { counter++; $(this) .attr('data-image-id', counter); }); } $(setClickAttr) .on('click', function () { updateGallery($(this)); }); }
JavaScript
function checkPropTypes( typeSpecs, values, location, componentName, getStack ) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName]( values, typeSpecName, componentName, location, null, ReactPropTypesSecret ); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if ( error instanceof Error && !(error.message in loggedTypeFailures) ) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } }
function checkPropTypes( typeSpecs, values, location, componentName, getStack ) { if (process.env.NODE_ENV !== 'production') { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName]( values, typeSpecName, componentName, location, null, ReactPropTypesSecret ); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if ( error instanceof Error && !(error.message in loggedTypeFailures) ) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } }
JavaScript
function toCssValue(value) { var ignoreImportant = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!Array.isArray(value)) return value; var cssValue = ''; // Support space separated values via `[['5px', '10px']]`. if (Array.isArray(value[0])) { for (var i = 0; i < value.length; i++) { if (value[i] === '!important') break; if (cssValue) cssValue += ', '; cssValue += join(value[i], ' '); } } else cssValue = join(value, ', '); // Add !important, because it was ignored. if (!ignoreImportant && value[value.length - 1] === '!important') { cssValue += ' !important'; } return cssValue; }
function toCssValue(value) { var ignoreImportant = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (!Array.isArray(value)) return value; var cssValue = ''; // Support space separated values via `[['5px', '10px']]`. if (Array.isArray(value[0])) { for (var i = 0; i < value.length; i++) { if (value[i] === '!important') break; if (cssValue) cssValue += ', '; cssValue += join(value[i], ' '); } } else cssValue = join(value, ', '); // Add !important, because it was ignored. if (!ignoreImportant && value[value.length - 1] === '!important') { cssValue += ' !important'; } return cssValue; }
JavaScript
function link(cssRules) { var map = this.options.sheet.renderer.getUnescapedKeysMap( this.index ); for (var i = 0; i < cssRules.length; i++) { var cssRule = cssRules[i]; var _key = this.options.sheet.renderer.getKey(cssRule); if (map[_key]) _key = map[_key]; var rule = this.map[_key]; if (rule) (0, _linkRule2['default'])(rule, cssRule); } }
function link(cssRules) { var map = this.options.sheet.renderer.getUnescapedKeysMap( this.index ); for (var i = 0; i < cssRules.length; i++) { var cssRule = cssRules[i]; var _key = this.options.sheet.renderer.getKey(cssRule); if (map[_key]) _key = map[_key]; var rule = this.map[_key]; if (rule) (0, _linkRule2['default'])(rule, cssRule); } }
JavaScript
function prop(name, value) { // It's a getter. if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed. if (this.style[name] === value) return this; value = this.options.jss.plugins.onChangeValue( value, name, this ); var isEmpty = value == null || value === false; var isDefined = name in this.style; // Value is empty and wasn't defined before. if (isEmpty && !isDefined) return this; // We are going to remove this value. var remove = isEmpty && isDefined; if (remove) delete this.style[name]; else this.style[name] = value; // Renderable is defined if StyleSheet option `link` is true. if (this.renderable) { if (remove) this.renderer.removeProperty(this.renderable, name); else this.renderer.setProperty(this.renderable, name, value); return this; } var sheet = this.options.sheet; if (sheet && sheet.attached) { (0, _warning2['default'])( false, 'Rule is not linked. Missing sheet option "link: true".' ); } return this; }
function prop(name, value) { // It's a getter. if (value === undefined) return this.style[name]; // Don't do anything if the value has not changed. if (this.style[name] === value) return this; value = this.options.jss.plugins.onChangeValue( value, name, this ); var isEmpty = value == null || value === false; var isDefined = name in this.style; // Value is empty and wasn't defined before. if (isEmpty && !isDefined) return this; // We are going to remove this value. var remove = isEmpty && isDefined; if (remove) delete this.style[name]; else this.style[name] = value; // Renderable is defined if StyleSheet option `link` is true. if (this.renderable) { if (remove) this.renderer.removeProperty(this.renderable, name); else this.renderer.setProperty(this.renderable, name, value); return this; } var sheet = this.options.sheet; if (sheet && sheet.attached) { (0, _warning2['default'])( false, 'Rule is not linked. Missing sheet option "link: true".' ); } return this; }
JavaScript
function toCss(selector, style) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var result = ''; if (!style) return result; var _options$indent = options.indent, indent = _options$indent === undefined ? 0 : _options$indent; var fallbacks = style.fallbacks; indent++; // Apply fallbacks first. if (fallbacks) { // Array syntax {fallbacks: [{prop: value}]} if (Array.isArray(fallbacks)) { for (var index = 0; index < fallbacks.length; index++) { var fallback = fallbacks[index]; for (var prop in fallback) { var value = fallback[prop]; if (value != null) { result += '\n' + indentStr( prop + ': ' + (0, _toCssValue2['default'])(value) + ';', indent ); } } } } else { // Object syntax {fallbacks: {prop: value}} for (var _prop in fallbacks) { var _value = fallbacks[_prop]; if (_value != null) { result += '\n' + indentStr( _prop + ': ' + (0, _toCssValue2['default'])(_value) + ';', indent ); } } } } for (var _prop2 in style) { var _value2 = style[_prop2]; if (_value2 != null && _prop2 !== 'fallbacks') { result += '\n' + indentStr( _prop2 + ': ' + (0, _toCssValue2['default'])(_value2) + ';', indent ); } } // Allow empty style in this case, because properties will be added dynamically. if (!result && !options.allowEmpty) return result; indent--; result = indentStr(selector + ' {' + result + '\n', indent) + indentStr('}', indent); return result; }
function toCss(selector, style) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var result = ''; if (!style) return result; var _options$indent = options.indent, indent = _options$indent === undefined ? 0 : _options$indent; var fallbacks = style.fallbacks; indent++; // Apply fallbacks first. if (fallbacks) { // Array syntax {fallbacks: [{prop: value}]} if (Array.isArray(fallbacks)) { for (var index = 0; index < fallbacks.length; index++) { var fallback = fallbacks[index]; for (var prop in fallback) { var value = fallback[prop]; if (value != null) { result += '\n' + indentStr( prop + ': ' + (0, _toCssValue2['default'])(value) + ';', indent ); } } } } else { // Object syntax {fallbacks: {prop: value}} for (var _prop in fallbacks) { var _value = fallbacks[_prop]; if (_value != null) { result += '\n' + indentStr( _prop + ': ' + (0, _toCssValue2['default'])(_value) + ';', indent ); } } } } for (var _prop2 in style) { var _value2 = style[_prop2]; if (_value2 != null && _prop2 !== 'fallbacks') { result += '\n' + indentStr( _prop2 + ': ' + (0, _toCssValue2['default'])(_value2) + ';', indent ); } } // Allow empty style in this case, because properties will be added dynamically. if (!result && !options.allowEmpty) return result; indent--; result = indentStr(selector + ' {' + result + '\n', indent) + indentStr('}', indent); return result; }
JavaScript
function findHigherSheet(registry, options) { for (var i = 0; i < registry.length; i++) { var sheet = registry[i]; if ( sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint ) { return sheet; } } return null; }
function findHigherSheet(registry, options) { for (var i = 0; i < registry.length; i++) { var sheet = registry[i]; if ( sheet.attached && sheet.options.index > options.index && sheet.options.insertionPoint === options.insertionPoint ) { return sheet; } } return null; }
JavaScript
function findHighestSheet(registry, options) { for (var i = registry.length - 1; i >= 0; i--) { var sheet = registry[i]; if ( sheet.attached && sheet.options.insertionPoint === options.insertionPoint ) { return sheet; } } return null; }
function findHighestSheet(registry, options) { for (var i = registry.length - 1; i >= 0; i--) { var sheet = registry[i]; if ( sheet.attached && sheet.options.insertionPoint === options.insertionPoint ) { return sheet; } } return null; }
JavaScript
function findPrevNode(options) { var registry = _sheets2['default'].registry; if (registry.length > 0) { // Try to insert before the next higher sheet. var sheet = findHigherSheet(registry, options); if (sheet) return sheet.renderer.element; // Otherwise insert after the last attached. sheet = findHighestSheet(registry, options); if (sheet) return sheet.renderer.element.nextElementSibling; } // Try to find a comment placeholder if registry is empty. var insertionPoint = options.insertionPoint; if (insertionPoint && typeof insertionPoint === 'string') { var comment = findCommentNode(insertionPoint); if (comment) return comment.nextSibling; // If user specifies an insertion point and it can't be found in the document - // bad specificity issues may appear. (0, _warning2['default'])( insertionPoint === 'jss', '[JSS] Insertion point "%s" not found.', insertionPoint ); } return null; }
function findPrevNode(options) { var registry = _sheets2['default'].registry; if (registry.length > 0) { // Try to insert before the next higher sheet. var sheet = findHigherSheet(registry, options); if (sheet) return sheet.renderer.element; // Otherwise insert after the last attached. sheet = findHighestSheet(registry, options); if (sheet) return sheet.renderer.element.nextElementSibling; } // Try to find a comment placeholder if registry is empty. var insertionPoint = options.insertionPoint; if (insertionPoint && typeof insertionPoint === 'string') { var comment = findCommentNode(insertionPoint); if (comment) return comment.nextSibling; // If user specifies an insertion point and it can't be found in the document - // bad specificity issues may appear. (0, _warning2['default'])( insertionPoint === 'jss', '[JSS] Insertion point "%s" not found.', insertionPoint ); } return null; }
JavaScript
function insertStyle(style, options) { var insertionPoint = options.insertionPoint; var prevNode = findPrevNode(options); if (prevNode) { var parentNode = prevNode.parentNode; if (parentNode) parentNode.insertBefore(style, prevNode); return; } // Works with iframes and any node types. if (insertionPoint && typeof insertionPoint.nodeType === 'number') { // https://stackoverflow.com/questions/41328728/force-casting-in-flow var insertionPointElement = insertionPoint; var _parentNode = insertionPointElement.parentNode; if (_parentNode) _parentNode.insertBefore( style, insertionPointElement.nextSibling ); else (0, _warning2['default'])( false, '[JSS] Insertion point is not in the DOM.' ); return; } getHead().insertBefore(style, prevNode); }
function insertStyle(style, options) { var insertionPoint = options.insertionPoint; var prevNode = findPrevNode(options); if (prevNode) { var parentNode = prevNode.parentNode; if (parentNode) parentNode.insertBefore(style, prevNode); return; } // Works with iframes and any node types. if (insertionPoint && typeof insertionPoint.nodeType === 'number') { // https://stackoverflow.com/questions/41328728/force-casting-in-flow var insertionPointElement = insertionPoint; var _parentNode = insertionPointElement.parentNode; if (_parentNode) _parentNode.insertBefore( style, insertionPointElement.nextSibling ); else (0, _warning2['default'])( false, '[JSS] Insertion point is not in the DOM.' ); return; } getHead().insertBefore(style, prevNode); }
JavaScript
function jssGlobal() { function onCreateRule(name, styles, options) { if (name === propKey) { return new GlobalContainerRule(name, styles, options); } if ( name[0] === '@' && name.substr(0, prefixKey.length) === prefixKey ) { return new GlobalPrefixedRule(name, styles, options); } var parent = options.parent; if (parent) { if ( parent.type === 'global' || parent.options.parent.type === 'global' ) { options.global = true; } } if (options.global) options.selector = name; return null; } function onProcessRule(rule) { if (rule.type !== 'style') return; handleNestedGlobalContainerRule(rule); handlePrefixedGlobalRule(rule); } return { onCreateRule: onCreateRule, onProcessRule: onProcessRule }; }
function jssGlobal() { function onCreateRule(name, styles, options) { if (name === propKey) { return new GlobalContainerRule(name, styles, options); } if ( name[0] === '@' && name.substr(0, prefixKey.length) === prefixKey ) { return new GlobalPrefixedRule(name, styles, options); } var parent = options.parent; if (parent) { if ( parent.type === 'global' || parent.options.parent.type === 'global' ) { options.global = true; } } if (options.global) options.selector = name; return null; } function onProcessRule(rule) { if (rule.type !== 'style') return; handleNestedGlobalContainerRule(rule); handlePrefixedGlobalRule(rule); } return { onCreateRule: onCreateRule, onProcessRule: onProcessRule }; }
JavaScript
function jssNested() { // Get a function to be used for $ref replacement. function getReplaceRef(container) { return function(match, key) { var rule = container.getRule(key); if (rule) return rule.selector; (0, _warning2.default)( false, '[JSS] Could not find the referenced rule %s in %s.', key, container.options.meta || container ); return key; }; } var hasAnd = function hasAnd(str) { return str.indexOf('&') !== -1; }; function replaceParentRefs(nestedProp, parentProp) { var parentSelectors = parentProp.split(separatorRegExp); var nestedSelectors = nestedProp.split(separatorRegExp); var result = ''; for (var i = 0; i < parentSelectors.length; i++) { var parent = parentSelectors[i]; for (var j = 0; j < nestedSelectors.length; j++) { var nested = nestedSelectors[j]; if (result) result += ', '; // Replace all & by the parent or prefix & with the parent. result += hasAnd(nested) ? nested.replace(parentRegExp, parent) : parent + ' ' + nested; } } return result; } function getOptions(rule, container, options) { // Options has been already created, now we only increase index. if (options) return _extends({}, options, { index: options.index + 1 }); var nestingLevel = rule.options.nestingLevel; nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1; return _extends({}, rule.options, { nestingLevel: nestingLevel, index: container.indexOf(rule) + 1 }); } function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; var container = rule.options.parent; var options = void 0; var replaceRef = void 0; for (var prop in style) { var isNested = hasAnd(prop); var isNestedConditional = prop[0] === '@'; if (!isNested && !isNestedConditional) continue; options = getOptions(rule, container, options); if (isNested) { var selector = replaceParentRefs( prop, rule.selector // Lazily create the ref replacer function just once for // all nested rules within the sheet. ); if (!replaceRef) replaceRef = getReplaceRef( container // Replace all $refs. ); selector = selector.replace(refRegExp, replaceRef); container.addRule( selector, style[prop], _extends({}, options, { selector: selector }) ); } else if (isNestedConditional) { container // Place conditional right after the parent rule to ensure right ordering. .addRule(prop, null, options) .addRule(rule.key, style[prop], { selector: rule.selector }); } delete style[prop]; } return style; } return { onProcessStyle: onProcessStyle }; }
function jssNested() { // Get a function to be used for $ref replacement. function getReplaceRef(container) { return function(match, key) { var rule = container.getRule(key); if (rule) return rule.selector; (0, _warning2.default)( false, '[JSS] Could not find the referenced rule %s in %s.', key, container.options.meta || container ); return key; }; } var hasAnd = function hasAnd(str) { return str.indexOf('&') !== -1; }; function replaceParentRefs(nestedProp, parentProp) { var parentSelectors = parentProp.split(separatorRegExp); var nestedSelectors = nestedProp.split(separatorRegExp); var result = ''; for (var i = 0; i < parentSelectors.length; i++) { var parent = parentSelectors[i]; for (var j = 0; j < nestedSelectors.length; j++) { var nested = nestedSelectors[j]; if (result) result += ', '; // Replace all & by the parent or prefix & with the parent. result += hasAnd(nested) ? nested.replace(parentRegExp, parent) : parent + ' ' + nested; } } return result; } function getOptions(rule, container, options) { // Options has been already created, now we only increase index. if (options) return _extends({}, options, { index: options.index + 1 }); var nestingLevel = rule.options.nestingLevel; nestingLevel = nestingLevel === undefined ? 1 : nestingLevel + 1; return _extends({}, rule.options, { nestingLevel: nestingLevel, index: container.indexOf(rule) + 1 }); } function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; var container = rule.options.parent; var options = void 0; var replaceRef = void 0; for (var prop in style) { var isNested = hasAnd(prop); var isNestedConditional = prop[0] === '@'; if (!isNested && !isNestedConditional) continue; options = getOptions(rule, container, options); if (isNested) { var selector = replaceParentRefs( prop, rule.selector // Lazily create the ref replacer function just once for // all nested rules within the sheet. ); if (!replaceRef) replaceRef = getReplaceRef( container // Replace all $refs. ); selector = selector.replace(refRegExp, replaceRef); container.addRule( selector, style[prop], _extends({}, options, { selector: selector }) ); } else if (isNestedConditional) { container // Place conditional right after the parent rule to ensure right ordering. .addRule(prop, null, options) .addRule(rule.key, style[prop], { selector: rule.selector }); } delete style[prop]; } return style; } return { onProcessStyle: onProcessStyle }; }
JavaScript
function camelCase() { function onProcessStyle(style) { if (Array.isArray(style)) { // Handle rules like @font-face, which can have multiple styles in an array for (var index = 0; index < style.length; index++) { style[index] = convertCase(style[index]); } return style; } return convertCase(style); } function onChangeValue(value, prop, rule) { var hyphenatedProp = (0, _hyphenateStyleName2['default'])(prop); // There was no camel case in place if (prop === hyphenatedProp) return value; rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above. return null; } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; }
function camelCase() { function onProcessStyle(style) { if (Array.isArray(style)) { // Handle rules like @font-face, which can have multiple styles in an array for (var index = 0; index < style.length; index++) { style[index] = convertCase(style[index]); } return style; } return convertCase(style); } function onChangeValue(value, prop, rule) { var hyphenatedProp = (0, _hyphenateStyleName2['default'])(prop); // There was no camel case in place if (prop === hyphenatedProp) return value; rule.prop(hyphenatedProp, value); // Core will ignore that property value we set the proper one above. return null; } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; }
JavaScript
function addCamelCasedVersion(obj) { var regExp = /(-[a-z])/g; var replace = function replace(str) { return str[1].toUpperCase(); }; var newObj = {}; for (var key in obj) { newObj[key] = obj[key]; newObj[key.replace(regExp, replace)] = obj[key]; } return newObj; }
function addCamelCasedVersion(obj) { var regExp = /(-[a-z])/g; var replace = function replace(str) { return str[1].toUpperCase(); }; var newObj = {}; for (var key in obj) { newObj[key] = obj[key]; newObj[key.replace(regExp, replace)] = obj[key]; } return newObj; }
JavaScript
function defaultUnit() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var camelCasedOptions = addCamelCasedVersion(options); function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; for (var prop in style) { style[prop] = iterate(prop, style[prop], camelCasedOptions); } return style; } function onChangeValue(value, prop) { return iterate(prop, value, camelCasedOptions); } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; }
function defaultUnit() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var camelCasedOptions = addCamelCasedVersion(options); function onProcessStyle(style, rule) { if (rule.type !== 'style') return style; for (var prop in style) { style[prop] = iterate(prop, style[prop], camelCasedOptions); } return style; } function onChangeValue(value, prop) { return iterate(prop, value, camelCasedOptions); } return { onProcessStyle: onProcessStyle, onChangeValue: onChangeValue }; }
JavaScript
function createMuiTheme() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$breakpoints = options.breakpoints, breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints, _options$mixins = options.mixins, mixinsInput = _options$mixins === void 0 ? {} : _options$mixins, _options$palette = options.palette, paletteInput = _options$palette === void 0 ? {} : _options$palette, shadowsInput = options.shadows, _options$typography = options.typography, typographyInput = _options$typography === void 0 ? {} : _options$typography, other = (0, _objectWithoutProperties2.default)(options, [ 'breakpoints', 'mixins', 'palette', 'shadows', 'typography' ]); var palette = (0, _createPalette.default)(paletteInput); var breakpoints = (0, _createBreakpoints.default)(breakpointsInput); var muiTheme = (0, _extends2.default)( { breakpoints: breakpoints, direction: 'ltr', mixins: (0, _createMixins.default)( breakpoints, _spacing.default, mixinsInput ), overrides: {}, // Inject custom styles palette: palette, props: {}, // Inject custom properties shadows: shadowsInput || _shadows.default, typography: (0, _createTypography.default)( palette, typographyInput ) }, (0, _deepmerge.default)( { shape: _shape.default, spacing: _spacing.default, transitions: _transitions.default, zIndex: _zIndex.default }, other, { isMergeableObject: _isPlainObject.default } ) ); process.env.NODE_ENV !== 'production' ? (0, _warning.default)( muiTheme.shadows.length === 25, 'Material-UI: the shadows array provided to createMuiTheme should support 25 elevations.' ) : void 0; return muiTheme; }
function createMuiTheme() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$breakpoints = options.breakpoints, breakpointsInput = _options$breakpoints === void 0 ? {} : _options$breakpoints, _options$mixins = options.mixins, mixinsInput = _options$mixins === void 0 ? {} : _options$mixins, _options$palette = options.palette, paletteInput = _options$palette === void 0 ? {} : _options$palette, shadowsInput = options.shadows, _options$typography = options.typography, typographyInput = _options$typography === void 0 ? {} : _options$typography, other = (0, _objectWithoutProperties2.default)(options, [ 'breakpoints', 'mixins', 'palette', 'shadows', 'typography' ]); var palette = (0, _createPalette.default)(paletteInput); var breakpoints = (0, _createBreakpoints.default)(breakpointsInput); var muiTheme = (0, _extends2.default)( { breakpoints: breakpoints, direction: 'ltr', mixins: (0, _createMixins.default)( breakpoints, _spacing.default, mixinsInput ), overrides: {}, // Inject custom styles palette: palette, props: {}, // Inject custom properties shadows: shadowsInput || _shadows.default, typography: (0, _createTypography.default)( palette, typographyInput ) }, (0, _deepmerge.default)( { shape: _shape.default, spacing: _spacing.default, transitions: _transitions.default, zIndex: _zIndex.default }, other, { isMergeableObject: _isPlainObject.default } ) ); process.env.NODE_ENV !== 'production' ? (0, _warning.default)( muiTheme.shadows.length === 25, 'Material-UI: the shadows array provided to createMuiTheme should support 25 elevations.' ) : void 0; return muiTheme; }
JavaScript
function clamp(value) { var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; process.env.NODE_ENV !== 'production' ? (0, _warning.default)( value >= min && value <= max, 'Material-UI: the value provided ' .concat(value, ' is out of range [') .concat(min, ', ') .concat(max, '].') ) : void 0; if (value < min) { return min; } if (value > max) { return max; } return value; }
function clamp(value) { var min = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var max = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; process.env.NODE_ENV !== 'production' ? (0, _warning.default)( value >= min && value <= max, 'Material-UI: the value provided ' .concat(value, ' is out of range [') .concat(min, ', ') .concat(max, '].') ) : void 0; if (value < min) { return min; } if (value > max) { return max; } return value; }
JavaScript
function recomposeColor(color) { var type = color.type; var values = color.values; if (type.indexOf('rgb') !== -1) { // Only convert the first 3 values to int (i.e. not alpha) values = values.map(function(n, i) { return i < 3 ? parseInt(n, 10) : n; }); } if (type.indexOf('hsl') !== -1) { values[1] = ''.concat(values[1], '%'); values[2] = ''.concat(values[2], '%'); } return ''.concat(color.type, '(').concat(values.join(', '), ')'); }
function recomposeColor(color) { var type = color.type; var values = color.values; if (type.indexOf('rgb') !== -1) { // Only convert the first 3 values to int (i.e. not alpha) values = values.map(function(n, i) { return i < 3 ? parseInt(n, 10) : n; }); } if (type.indexOf('hsl') !== -1) { values[1] = ''.concat(values[1], '%'); values[2] = ''.concat(values[2], '%'); } return ''.concat(color.type, '(').concat(values.join(', '), ')'); }
JavaScript
function initTokenState() { tokCurLine = options.line; tokPos = tokLineStart = 0; tokRegexpAllowed = true; metParenL = 0; inTemplate = false; skipSpace(); }
function initTokenState() { tokCurLine = options.line; tokPos = tokLineStart = 0; tokRegexpAllowed = true; metParenL = 0; inTemplate = false; skipSpace(); }
JavaScript
function finishToken(type, val, shouldSkipSpace) { tokEnd = tokPos; if (options.locations) tokEndLoc = new Position; tokType = type; if (shouldSkipSpace !== false) skipSpace(); tokVal = val; tokRegexpAllowed = type.beforeExpr; if (options.onToken) { options.onToken(getCurrentToken()); } }
function finishToken(type, val, shouldSkipSpace) { tokEnd = tokPos; if (options.locations) tokEndLoc = new Position; tokType = type; if (shouldSkipSpace !== false) skipSpace(); tokVal = val; tokRegexpAllowed = type.beforeExpr; if (options.onToken) { options.onToken(getCurrentToken()); } }
JavaScript
function Node() { this.type = null; this.start = tokStart; this.end = null; }
function Node() { this.type = null; this.start = tokStart; this.end = null; }
JavaScript
function startNodeFrom(other) { var node = new Node(); node.start = other.start; if (options.locations) { node.loc = new SourceLocation(); node.loc.start = other.loc.start; } if (options.ranges) node.range = [other.range[0], 0]; return node; }
function startNodeFrom(other) { var node = new Node(); node.start = other.start; if (options.locations) { node.loc = new SourceLocation(); node.loc.start = other.loc.start; } if (options.ranges) node.range = [other.range[0], 0]; return node; }
JavaScript
function eat(type) { if (tokType === type) { next(); return true; } else { return false; } }
function eat(type) { if (tokType === type) { next(); return true; } else { return false; } }
JavaScript
function checkPropClash(prop, propHash) { if (prop.computed) return; var key = prop.key, name; switch (key.type) { case "Identifier": name = key.name; break; case "Literal": name = String(key.value); break; default: return; } var kind = prop.kind || "init", other; if (has(propHash, name)) { other = propHash[name]; var isGetSet = kind !== "init"; if ((strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) raise(key.start, "Redefinition of property"); } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }
function checkPropClash(prop, propHash) { if (prop.computed) return; var key = prop.key, name; switch (key.type) { case "Identifier": name = key.name; break; case "Literal": name = String(key.value); break; default: return; } var kind = prop.kind || "init", other; if (has(propHash, name)) { other = propHash[name]; var isGetSet = kind !== "init"; if ((strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) raise(key.start, "Redefinition of property"); } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }
JavaScript
function parseTopLevel(program) { lastStart = lastEnd = tokPos; if (options.locations) lastEndLoc = new Position; inFunction = inGenerator = strict = null; labels = []; readToken(); var node = program || startNode(), first = true; if (!program) node.body = []; while (tokType !== _eof) { var stmt = parseStatement(); node.body.push(stmt); if (first && isUseStrict(stmt)) setStrict(true); first = false; } return finishNode(node, "Program"); }
function parseTopLevel(program) { lastStart = lastEnd = tokPos; if (options.locations) lastEndLoc = new Position; inFunction = inGenerator = strict = null; labels = []; readToken(); var node = program || startNode(), first = true; if (!program) node.body = []; while (tokType !== _eof) { var stmt = parseStatement(); node.body.push(stmt); if (first && isUseStrict(stmt)) setStrict(true); first = false; } return finishNode(node, "Program"); }
JavaScript
function parseForIn(node, init) { var type = tokType === _in ? "ForInStatement" : "ForOfStatement"; next(); node.left = init; node.right = parseExpression(); expect(_parenR); node.body = parseStatement(); labels.pop(); return finishNode(node, type); }
function parseForIn(node, init) { var type = tokType === _in ? "ForInStatement" : "ForOfStatement"; next(); node.left = init; node.right = parseExpression(); expect(_parenR); node.body = parseStatement(); labels.pop(); return finishNode(node, type); }
JavaScript
function parseVar(node, noIn, kind) { node.declarations = []; node.kind = kind; for (;;) { var decl = startNode(); decl.id = options.ecmaVersion >= 6 ? toAssignable(parseExprAtom()) : parseIdent(); checkLVal(decl.id, true); decl.init = eat(_eq) ? parseExpression(true, noIn) : (kind === _const.keyword ? unexpected() : null); node.declarations.push(finishNode(decl, "VariableDeclarator")); if (!eat(_comma)) break; } return node; }
function parseVar(node, noIn, kind) { node.declarations = []; node.kind = kind; for (;;) { var decl = startNode(); decl.id = options.ecmaVersion >= 6 ? toAssignable(parseExprAtom()) : parseIdent(); checkLVal(decl.id, true); decl.init = eat(_eq) ? parseExpression(true, noIn) : (kind === _const.keyword ? unexpected() : null); node.declarations.push(finishNode(decl, "VariableDeclarator")); if (!eat(_comma)) break; } return node; }
JavaScript
function parseMethod(isGenerator) { var node = startNode(); initFunction(node); parseFunctionParams(node); var allowExpressionBody; if (options.ecmaVersion >= 6) { node.generator = isGenerator; allowExpressionBody = true; } else { allowExpressionBody = false; } parseFunctionBody(node, allowExpressionBody); return finishNode(node, "FunctionExpression"); }
function parseMethod(isGenerator) { var node = startNode(); initFunction(node); parseFunctionParams(node); var allowExpressionBody; if (options.ecmaVersion >= 6) { node.generator = isGenerator; allowExpressionBody = true; } else { allowExpressionBody = false; } parseFunctionBody(node, allowExpressionBody); return finishNode(node, "FunctionExpression"); }
JavaScript
function parseArrowExpression(node, params) { initFunction(node); var defaults = node.defaults, hasDefaults = false; for (var i = 0, lastI = params.length - 1; i <= lastI; i++) { var param = params[i]; if (param.type === "AssignmentExpression" && param.operator === "=") { hasDefaults = true; params[i] = param.left; defaults.push(param.right); } else { toAssignable(param, i === lastI, true); defaults.push(null); if (param.type === "SpreadElement") { params.length--; node.rest = param.argument; break; } } } node.params = params; if (!hasDefaults) node.defaults = []; parseFunctionBody(node, true); return finishNode(node, "ArrowFunctionExpression"); }
function parseArrowExpression(node, params) { initFunction(node); var defaults = node.defaults, hasDefaults = false; for (var i = 0, lastI = params.length - 1; i <= lastI; i++) { var param = params[i]; if (param.type === "AssignmentExpression" && param.operator === "=") { hasDefaults = true; params[i] = param.left; defaults.push(param.right); } else { toAssignable(param, i === lastI, true); defaults.push(null); if (param.type === "SpreadElement") { params.length--; node.rest = param.argument; break; } } } node.params = params; if (!hasDefaults) node.defaults = []; parseFunctionBody(node, true); return finishNode(node, "ArrowFunctionExpression"); }
JavaScript
function parseFunctionBody(node, allowExpression) { var isExpression = allowExpression && tokType !== _braceL; if (isExpression) { node.body = parseExpression(true); node.expression = true; } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldInFunc = inFunction, oldInGen = inGenerator, oldLabels = labels; inFunction = true; inGenerator = node.generator; labels = []; node.body = parseBlock(true); node.expression = false; inFunction = oldInFunc; inGenerator = oldInGen; labels = oldLabels; } // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (strict || !isExpression && node.body.body.length && isUseStrict(node.body.body[0])) { var nameHash = {}; if (node.id) checkFunctionParam(node.id, nameHash); for (var i = 0; i < node.params.length; i++) checkFunctionParam(node.params[i], nameHash); if (node.rest) checkFunctionParam(node.rest, nameHash); } }
function parseFunctionBody(node, allowExpression) { var isExpression = allowExpression && tokType !== _braceL; if (isExpression) { node.body = parseExpression(true); node.expression = true; } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldInFunc = inFunction, oldInGen = inGenerator, oldLabels = labels; inFunction = true; inGenerator = node.generator; labels = []; node.body = parseBlock(true); node.expression = false; inFunction = oldInFunc; inGenerator = oldInGen; labels = oldLabels; } // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (strict || !isExpression && node.body.body.length && isUseStrict(node.body.body[0])) { var nameHash = {}; if (node.id) checkFunctionParam(node.id, nameHash); for (var i = 0; i < node.params.length; i++) checkFunctionParam(node.params[i], nameHash); if (node.rest) checkFunctionParam(node.rest, nameHash); } }
JavaScript
function parseExportSpecifiers() { var nodes = [], first = true; if (tokType === _star) { // export * from '...' var node = startNode(); next(); nodes.push(finishNode(node, "ExportBatchSpecifier")); } else { // export { x, y as z } [from '...'] expect(_braceL); while (!eat(_braceR)) { if (!first) { expect(_comma); if (options.allowTrailingCommas && eat(_braceR)) break; } else first = false; var node = startNode(); node.id = parseIdent(); if (tokType === _name && tokVal === "as") { next(); node.name = parseIdent(true); } else { node.name = null; } nodes.push(finishNode(node, "ExportSpecifier")); } } return nodes; }
function parseExportSpecifiers() { var nodes = [], first = true; if (tokType === _star) { // export * from '...' var node = startNode(); next(); nodes.push(finishNode(node, "ExportBatchSpecifier")); } else { // export { x, y as z } [from '...'] expect(_braceL); while (!eat(_braceR)) { if (!first) { expect(_comma); if (options.allowTrailingCommas && eat(_braceR)) break; } else first = false; var node = startNode(); node.id = parseIdent(); if (tokType === _name && tokVal === "as") { next(); node.name = parseIdent(true); } else { node.name = null; } nodes.push(finishNode(node, "ExportSpecifier")); } } return nodes; }
JavaScript
function parseImportSpecifiers() { var nodes = [], first = true; if (tokType === _star) { var node = startNode(); next(); if (tokType !== _name || tokVal !== "as") unexpected(); next(); node.name = parseIdent(); checkLVal(node.name, true); nodes.push(finishNode(node, "ImportBatchSpecifier")); return nodes; } if (tokType === _name) { // import defaultObj, { x, y as z } from '...' var node = startNode(); node.id = parseIdent(); checkLVal(node.id, true); node.name = null; node['default'] = true; nodes.push(finishNode(node, "ImportSpecifier")); if (!eat(_comma)) return nodes; } expect(_braceL); while (!eat(_braceR)) { if (!first) { expect(_comma); if (options.allowTrailingCommas && eat(_braceR)) break; } else first = false; var node = startNode(); node.id = parseIdent(true); if (tokType === _name && tokVal === "as") { next(); node.name = parseIdent(); } else { node.name = null; } checkLVal(node.name || node.id, true); node['default'] = false; nodes.push(finishNode(node, "ImportSpecifier")); } return nodes; }
function parseImportSpecifiers() { var nodes = [], first = true; if (tokType === _star) { var node = startNode(); next(); if (tokType !== _name || tokVal !== "as") unexpected(); next(); node.name = parseIdent(); checkLVal(node.name, true); nodes.push(finishNode(node, "ImportBatchSpecifier")); return nodes; } if (tokType === _name) { // import defaultObj, { x, y as z } from '...' var node = startNode(); node.id = parseIdent(); checkLVal(node.id, true); node.name = null; node['default'] = true; nodes.push(finishNode(node, "ImportSpecifier")); if (!eat(_comma)) return nodes; } expect(_braceL); while (!eat(_braceR)) { if (!first) { expect(_comma); if (options.allowTrailingCommas && eat(_braceR)) break; } else first = false; var node = startNode(); node.id = parseIdent(true); if (tokType === _name && tokVal === "as") { next(); node.name = parseIdent(); } else { node.name = null; } checkLVal(node.name || node.id, true); node['default'] = false; nodes.push(finishNode(node, "ImportSpecifier")); } return nodes; }
JavaScript
function parseYield() { var node = startNode(); next(); if (eat(_semi) || canInsertSemicolon()) { node.delegate = false; node.argument = null; } else { node.delegate = eat(_star); node.argument = parseExpression(true); } return finishNode(node, "YieldExpression"); }
function parseYield() { var node = startNode(); next(); if (eat(_semi) || canInsertSemicolon()) { node.delegate = false; node.argument = null; } else { node.delegate = eat(_star); node.argument = parseExpression(true); } return finishNode(node, "YieldExpression"); }
JavaScript
function parseComprehension(node, isGenerator) { node.blocks = []; while (tokType === _for) { var block = startNode(); next(); expect(_parenL); block.left = toAssignable(parseExprAtom()); checkLVal(block.left, true); if (tokType !== _name || tokVal !== "of") unexpected(); next(); // `of` property is here for compatibility with Esprima's AST // which also supports deprecated [for (... in ...) expr] block.of = true; block.right = parseExpression(); expect(_parenR); node.blocks.push(finishNode(block, "ComprehensionBlock")); } node.filter = eat(_if) ? parseParenExpression() : null; node.body = parseExpression(); expect(isGenerator ? _parenR : _bracketR); node.generator = isGenerator; return finishNode(node, "ComprehensionExpression"); }
function parseComprehension(node, isGenerator) { node.blocks = []; while (tokType === _for) { var block = startNode(); next(); expect(_parenL); block.left = toAssignable(parseExprAtom()); checkLVal(block.left, true); if (tokType !== _name || tokVal !== "of") unexpected(); next(); // `of` property is here for compatibility with Esprima's AST // which also supports deprecated [for (... in ...) expr] block.of = true; block.right = parseExpression(); expect(_parenR); node.blocks.push(finishNode(block, "ComprehensionBlock")); } node.filter = eat(_if) ? parseParenExpression() : null; node.body = parseExpression(); expect(isGenerator ? _parenR : _bracketR); node.generator = isGenerator; return finishNode(node, "ComprehensionExpression"); }
JavaScript
printMessage(message, className) { const messageWrapper = document.createElement('div'); messageWrapper.classList.add('text-center', 'alert', className); messageWrapper.appendChild(document.createTextNode(message)); // Insert into HTML document.querySelector('.primary').insertBefore(messageWrapper, addExpenseForm); // Clear the error setTimeout(function() { document.querySelector('.primary .alert').remove(); addExpenseForm.reset(); }, 3000); }
printMessage(message, className) { const messageWrapper = document.createElement('div'); messageWrapper.classList.add('text-center', 'alert', className); messageWrapper.appendChild(document.createTextNode(message)); // Insert into HTML document.querySelector('.primary').insertBefore(messageWrapper, addExpenseForm); // Clear the error setTimeout(function() { document.querySelector('.primary .alert').remove(); addExpenseForm.reset(); }, 3000); }
JavaScript
addExpenseToList(name, amount) { const expensesList = document.querySelector('#expenses ul'); // Create a li const li = document.createElement('li'); li.className = "list-group-item d-flex justify-content-between align-items-center"; // Create the template li.innerHTML = ` ${name} <span class="badge badge-primary badge-pill">$ ${amount}</span> `; // Insert into the HTML expensesList.appendChild(li); }
addExpenseToList(name, amount) { const expensesList = document.querySelector('#expenses ul'); // Create a li const li = document.createElement('li'); li.className = "list-group-item d-flex justify-content-between align-items-center"; // Create the template li.innerHTML = ` ${name} <span class="badge badge-primary badge-pill">$ ${amount}</span> `; // Insert into the HTML expensesList.appendChild(li); }
JavaScript
function resetAbstracts(selectedBoxIndex){ // console.log('box index: ' + selectedBoxIndex); $('.selectedBox').css('opacity', '0.3'); $('.selectedBox').css('cursor', 'default'); $('.selectedBox').removeClass('selectedBox'); $('.bottomItem' + selectedBoxIndex).find('.ratingText').remove(); $('.bottomItem' + selectedBoxIndex).find('.rating').remove(); $('.rating' + selectedBoxIndex).remove(); // Remove the rating system on the modal otherwise it will stack on each paper clicked - could probablyjust toggle hide on/off instead of adding/removing $('#testModal').find('.modal-footer #footerLeft').find('.ratingText').remove(); $('#testModal').find('.modal-footer #footerLeft').find('.rating').remove(); // Make the download buttons disabled again for the next paper $('#testModal').find('.modal-footer #footerRight a').attr('disabled', ''); $('#testModal').find('.modal-footer #footerRight a button').attr('disabled', ''); $('#testModal').find('.modal-footer #footerRight .btn-secondary').attr('disabled', ''); // Remove the onclick handler - don't let the paper to be clicked after it has been viewed once $('.item' + selectedBoxIndex).off('click'); }
function resetAbstracts(selectedBoxIndex){ // console.log('box index: ' + selectedBoxIndex); $('.selectedBox').css('opacity', '0.3'); $('.selectedBox').css('cursor', 'default'); $('.selectedBox').removeClass('selectedBox'); $('.bottomItem' + selectedBoxIndex).find('.ratingText').remove(); $('.bottomItem' + selectedBoxIndex).find('.rating').remove(); $('.rating' + selectedBoxIndex).remove(); // Remove the rating system on the modal otherwise it will stack on each paper clicked - could probablyjust toggle hide on/off instead of adding/removing $('#testModal').find('.modal-footer #footerLeft').find('.ratingText').remove(); $('#testModal').find('.modal-footer #footerLeft').find('.rating').remove(); // Make the download buttons disabled again for the next paper $('#testModal').find('.modal-footer #footerRight a').attr('disabled', ''); $('#testModal').find('.modal-footer #footerRight a button').attr('disabled', ''); $('#testModal').find('.modal-footer #footerRight .btn-secondary').attr('disabled', ''); // Remove the onclick handler - don't let the paper to be clicked after it has been viewed once $('.item' + selectedBoxIndex).off('click'); }
JavaScript
function find(key, array) { // The variable results needs var in this case (without 'var' a global variable is created) var results = []; for (var i = 0; i < array.length; i++) { if (array[i].indexOf(key) == 0) { results.push(i); } } return results; }
function find(key, array) { // The variable results needs var in this case (without 'var' a global variable is created) var results = []; for (var i = 0; i < array.length; i++) { if (array[i].indexOf(key) == 0) { results.push(i); } } return results; }
JavaScript
function mapp(num,i){ for(k=0;k<unikc[i].length;k++){ if(num==unikc[i][k]) return k; } }
function mapp(num,i){ for(k=0;k<unikc[i].length;k++){ if(num==unikc[i][k]) return k; } }
JavaScript
function transpose(a) { return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); }); }
function transpose(a) { return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); }); }
JavaScript
function eliminateDuplicates(arr) { var i, len=arr.length, out=[], obj={}; for (i=0;i<len;i++) { obj[arr[i]]=0; } for (i in obj) { out.push(i); } return out; }
function eliminateDuplicates(arr) { var i, len=arr.length, out=[], obj={}; for (i=0;i<len;i++) { obj[arr[i]]=0; } for (i in obj) { out.push(i); } return out; }
JavaScript
function checkD(a,b){ var flag=0; for(i=0;i<a.length;i++){ for(j=0;j<a.length;j++) { if(a[i] == b[j]) flag=1; } } return flag; }
function checkD(a,b){ var flag=0; for(i=0;i<a.length;i++){ for(j=0;j<a.length;j++) { if(a[i] == b[j]) flag=1; } } return flag; }
JavaScript
static from (block) { // Validate block 0 if (!(block && block instanceof Block)) { return new DnpError(ERR_NOTABLOCK[0], ERR_NOTABLOCK[1]) } if (block.length !== 8) { return new DnpError(ERR_BADBLOCKLENGTH[0], ERR_BADBLOCKLENGTH[1]) } let buffer = block.buffer if (buffer[0] !== 0x05 || buffer[1] !== 0x64) { return new DnpError(ERR_BADBLOCKSTART[0], ERR_BADBLOCKSTART[1]) } // Creates new instance return new LinkHeader({ block, buffer, _from: 'from' }) }
static from (block) { // Validate block 0 if (!(block && block instanceof Block)) { return new DnpError(ERR_NOTABLOCK[0], ERR_NOTABLOCK[1]) } if (block.length !== 8) { return new DnpError(ERR_BADBLOCKLENGTH[0], ERR_BADBLOCKLENGTH[1]) } let buffer = block.buffer if (buffer[0] !== 0x05 || buffer[1] !== 0x64) { return new DnpError(ERR_BADBLOCKSTART[0], ERR_BADBLOCKSTART[1]) } // Creates new instance return new LinkHeader({ block, buffer, _from: 'from' }) }
JavaScript
function check (block) { if (!block || block.length === undefined) { return new DnpError(ERR_NOTABLOCK[0], ERR_NOTABLOCK[1]) } const len = block.length if (len < 3) { // can't check crc on nothing return new DnpError(ERR_BADLENGTH[0], ERR_BADLENGTH[1]) } let crc1 = calculate(block.slice(0, len - 2)) let crc2 = (block[len - 1] << 8) + block[len - 2] return crc1 === crc2 ? ERR_OK : new DnpError(ERR_INVALIDCRC[0], ERR_INVALIDCRC[1]) }
function check (block) { if (!block || block.length === undefined) { return new DnpError(ERR_NOTABLOCK[0], ERR_NOTABLOCK[1]) } const len = block.length if (len < 3) { // can't check crc on nothing return new DnpError(ERR_BADLENGTH[0], ERR_BADLENGTH[1]) } let crc1 = calculate(block.slice(0, len - 2)) let crc2 = (block[len - 1] << 8) + block[len - 2] return crc1 === crc2 ? ERR_OK : new DnpError(ERR_INVALIDCRC[0], ERR_INVALIDCRC[1]) }
JavaScript
static from (buffer) { if (!buffer || buffer.length === undefined) { return new DnpError(ERR_NOTABUFFER[0], ERR_NOTABUFFER[1]) } // DNP3 blocks has at least one data byte and a maximum of 16 data bytes, plus 2 bytes of CRC if (buffer.length < 3 || buffer.length > 18) { return new DnpError(ERR_BADLENGTH[0], ERR_BADLENGTH[1]) } return new Block({ len: buffer.length - 2, buffer, _from: 'from' }) }
static from (buffer) { if (!buffer || buffer.length === undefined) { return new DnpError(ERR_NOTABUFFER[0], ERR_NOTABUFFER[1]) } // DNP3 blocks has at least one data byte and a maximum of 16 data bytes, plus 2 bytes of CRC if (buffer.length < 3 || buffer.length > 18) { return new DnpError(ERR_BADLENGTH[0], ERR_BADLENGTH[1]) } return new Block({ len: buffer.length - 2, buffer, _from: 'from' }) }
JavaScript
static from (buffer) { if (!buffer || buffer.length === undefined) { return new DnpError(ERR_NOTABUFFER[0], ERR_NOTABUFFER[1]) } // DNP3 frames has at least ten data bytes and are a maximum of 292 bytes length if (buffer.length < 10 || buffer.length > 292) { return new DnpError(ERR_BADLENGTH[0], ERR_BADLENGTH[1]) } return new Frame({ len: buffer.length, buffer, _from: 'from' }) }
static from (buffer) { if (!buffer || buffer.length === undefined) { return new DnpError(ERR_NOTABUFFER[0], ERR_NOTABUFFER[1]) } // DNP3 frames has at least ten data bytes and are a maximum of 292 bytes length if (buffer.length < 10 || buffer.length > 292) { return new DnpError(ERR_BADLENGTH[0], ERR_BADLENGTH[1]) } return new Frame({ len: buffer.length, buffer, _from: 'from' }) }
JavaScript
function validateEnvVariables() { // If no value has been assigned to our environment variables, set them up... if (!process.env.NODE_ENV) { process.env.NODE_ENV = config.ENV; } // Check to see if `process.env.NODE_ENV` is valid validateNodeEnvironment(); // For Express/Passport if (!process.env.SESSION_SECRET) process.env.SESSION_SECRET = config.SESSION_SECRET; if (!process.env.PORT) process.env.PORT = config.PORT; // Set the appropriate MongoDB URI validateMongoUri(); }
function validateEnvVariables() { // If no value has been assigned to our environment variables, set them up... if (!process.env.NODE_ENV) { process.env.NODE_ENV = config.ENV; } // Check to see if `process.env.NODE_ENV` is valid validateNodeEnvironment(); // For Express/Passport if (!process.env.SESSION_SECRET) process.env.SESSION_SECRET = config.SESSION_SECRET; if (!process.env.PORT) process.env.PORT = config.PORT; // Set the appropriate MongoDB URI validateMongoUri(); }