_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q58400
toAbsoluteURL
validation
function toAbsoluteURL(url) { const a = document.createElement('a'); a.setAttribute('href', url); // <a href="hoge.html"> // @ts-ignore return a.cloneNode(false).href; // -> "http://example.com/hoge.html" }
javascript
{ "resource": "" }
q58401
normalize
validation
function normalize(node) { if (!(isElement(node) || isDocument(node) || isDocumentFragment(node))) { return; } if (!node.childNodes) { return; } var textRangeStart = -1; for (var i = node.childNodes.length - 1, n = void 0; i >= 0; i--) { n = node.childNodes[i]; if (isTextNode(n)) { if (textRangeStart === -1) { textRangeStart = i; } if (i === 0) { // collapse leading text nodes collapseTextRange(node, 0, textRangeStart); } } else { // recurse normalize(n); // collapse the range after this node if (textRangeStart > -1) { collapseTextRange(node, i + 1, textRangeStart); textRangeStart = -1; } } } }
javascript
{ "resource": "" }
q58402
getTextContent
validation
function getTextContent(node) { if (isCommentNode(node)) { return node.data || ''; } if (isTextNode(node)) { return node.value || ''; } var subtree = nodeWalkAll(node, isTextNode); return subtree.map(getTextContent).join(''); }
javascript
{ "resource": "" }
q58403
setTextContent
validation
function setTextContent(node, value) { if (isCommentNode(node)) { node.data = value; } else if (isTextNode(node)) { node.value = value; } else { var tn = newTextNode(value); tn.parentNode = node; node.childNodes = [tn]; } }
javascript
{ "resource": "" }
q58404
treeMap
validation
function treeMap(node, mapfn) { var results = []; nodeWalk(node, function(node) { results = results.concat(mapfn(node)); return false; }); return results; }
javascript
{ "resource": "" }
q58405
nodeWalk
validation
function nodeWalk(node, predicate, getChildNodes) { if (getChildNodes === void 0) { getChildNodes = module.exports.defaultChildNodes; } if (predicate(node)) { return node; } var match = null; var childNodes = getChildNodes(node); if (childNodes) { for (var i = 0; i < childNodes.length; i++) { match = nodeWalk(childNodes[i], predicate, getChildNodes); if (match) { break; } } } return match; }
javascript
{ "resource": "" }
q58406
nodeWalkAll
validation
function nodeWalkAll(node, predicate, matches, getChildNodes) { if (getChildNodes === void 0) { getChildNodes = module.exports.defaultChildNodes; } if (!matches) { matches = []; } if (predicate(node)) { matches.push(node); } var childNodes = getChildNodes(node); if (childNodes) { for (var i = 0; i < childNodes.length; i++) { nodeWalkAll(childNodes[i], predicate, matches, getChildNodes); } } return matches; }
javascript
{ "resource": "" }
q58407
nodeWalkAncestors
validation
function nodeWalkAncestors(node, predicate) { var parent = node.parentNode; if (!parent) { return undefined; } if (predicate(parent)) { return parent; } return nodeWalkAncestors(parent, predicate); }
javascript
{ "resource": "" }
q58408
query
validation
function query(node, predicate, getChildNodes) { if (getChildNodes === void 0) { getChildNodes = module.exports.defaultChildNodes; } var elementPredicate = AND(isElement, predicate); return nodeWalk(node, elementPredicate, getChildNodes); }
javascript
{ "resource": "" }
q58409
queryAll
validation
function queryAll(node, predicate, matches, getChildNodes) { if (getChildNodes === void 0) { getChildNodes = module.exports.defaultChildNodes; } var elementPredicate = AND(isElement, predicate); return nodeWalkAll(node, elementPredicate, matches, getChildNodes); }
javascript
{ "resource": "" }
q58410
insertNode
validation
function insertNode(parent, index, newNode, replace) { if (!parent.childNodes) { parent.childNodes = []; } var newNodes = []; var removedNode = replace ? parent.childNodes[index] : null; if (newNode) { if (isDocumentFragment(newNode)) { if (newNode.childNodes) { newNodes = Array.from(newNode.childNodes); newNode.childNodes.length = 0; } } else { newNodes = [newNode]; remove(newNode); } } if (replace) { removedNode = parent.childNodes[index]; } Array.prototype.splice.apply(parent.childNodes, [index, replace ? 1 : 0].concat(newNodes)); newNodes.forEach(function(n) { n.parentNode = parent; }); if (removedNode) { removedNode.parentNode = undefined; } }
javascript
{ "resource": "" }
q58411
removeNodeSaveChildren
validation
function removeNodeSaveChildren(node) { // We can't save the children if there's no parent node to provide // for them. var fosterParent = node.parentNode; if (!fosterParent) { return; } var children = (node.childNodes || []).slice(); for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; insertBefore(node.parentNode, node, child); } remove(node); }
javascript
{ "resource": "" }
q58412
getCode
validation
function getCode(filePath) { // take code from cache if available const cachedCode = esm.compiler.getCached(filePath); if (cachedCode) { return cachedCode; } if (!fs.existsSync(filePath)) { throw new Error(`File does not exist: ${filePath}`); } // otherwise read code from file and compile it const code = fs.readFileSync(filePath, 'utf-8'); return esm.compiler.compile(filePath, code); }
javascript
{ "resource": "" }
q58413
wrapTransitioningContext
validation
function wrapTransitioningContext(Comp) { return props => { return ( <TransitioningContext.Consumer> {context => <Comp context={context} {...props} />} </TransitioningContext.Consumer> ); }; }
javascript
{ "resource": "" }
q58414
split_linebreaks
validation
function split_linebreaks(s) { //return s.split(/\x0d\x0a|\x0a/); s = s.replace(acorn.allLineBreaks, '\n'); var out = [], idx = s.indexOf("\n"); while (idx !== -1) { out.push(s.substring(0, idx)); s = s.substring(idx + 1); idx = s.indexOf("\n"); } if (s.length) { out.push(s); } return out; }
javascript
{ "resource": "" }
q58415
onOutputError
validation
function onOutputError(err) { if (err.code === 'EACCES') { console.error(err.path + " is not writable. Skipping!"); } else { console.error(err); process.exit(0); } }
javascript
{ "resource": "" }
q58416
dasherizeShorthands
validation
function dasherizeShorthands(hash) { // operate in-place Object.keys(hash).forEach(function(key) { // each key value is an array var val = hash[key][0]; // only dasherize one-character shorthands if (key.length === 1 && val.indexOf('_') > -1) { hash[dasherizeFlag(val)] = val; } }); return hash; }
javascript
{ "resource": "" }
q58417
filterUnusedSelectors
validation
function filterUnusedSelectors(selectors, ignore, usedSelectors) { /* There are some selectors not supported for matching, like * :before, :after * They should be removed only if the parent is not found. * Example: '.clearfix:before' should be removed only if there * is no '.clearfix' */ return selectors.filter((selector) => { selector = dePseudify(selector); /* TODO: process @-rules */ if (selector[0] === '@') { return true; } for (let i = 0, len = ignore.length; i < len; ++i) { if (_.isRegExp(ignore[i]) && ignore[i].test(selector)) { return true; } if (ignore[i] === selector) { return true; } } return usedSelectors.indexOf(selector) !== -1; }); }
javascript
{ "resource": "" }
q58418
filterEmptyAtRules
validation
function filterEmptyAtRules(css) { /* Filter media queries with no remaining rules */ css.walkAtRules((atRule) => { if (atRule.name === 'media' && atRule.nodes.length === 0) { atRule.remove(); } }); }
javascript
{ "resource": "" }
q58419
filterUnusedRules
validation
function filterUnusedRules(pages, css, ignore, usedSelectors) { let ignoreNextRule = false, ignoreNextRulesStart = false, unusedRules = [], unusedRuleSelectors, usedRuleSelectors; /* Rule format: * { selectors: [ '...', '...' ], * declarations: [ { property: '...', value: '...' } ] * },. * Two steps: filter the unused selectors for each rule, * filter the rules with no selectors */ ignoreNextRule = false; css.walk((rule) => { if (rule.type === 'comment') { if (/^!?\s?uncss:ignore start\s?$/.test(rule.text)) { // ignore next rules while using comment `/* uncss:ignore start */` ignoreNextRulesStart = true; } else if (/^!?\s?uncss:ignore end\s?$/.test(rule.text)) { // until `/* uncss:ignore end */` was found ignoreNextRulesStart = false; } else if (/^!?\s?uncss:ignore\s?$/.test(rule.text)) { // ignore next rule while using comment `/* uncss:ignore */` ignoreNextRule = true; } } else if (rule.type === 'rule') { if (rule.parent.type === 'atrule' && _.endsWith(rule.parent.name, 'keyframes')) { // Don't remove animation keyframes that have selector names of '30%' or 'to' return; } if (ignoreNextRulesStart) { ignore = ignore.concat(rule.selectors); } else if (ignoreNextRule) { ignoreNextRule = false; ignore = ignore.concat(rule.selectors); } usedRuleSelectors = filterUnusedSelectors( rule.selectors, ignore, usedSelectors ); unusedRuleSelectors = rule.selectors.filter((selector) => usedRuleSelectors.indexOf(selector) < 0); if (unusedRuleSelectors && unusedRuleSelectors.length) { unusedRules.push({ type: 'rule', selectors: unusedRuleSelectors, position: rule.source }); } if (usedRuleSelectors.length === 0) { rule.remove(); } else { rule.selectors = usedRuleSelectors; } } }); /* Filter the @media rules with no rules */ filterEmptyAtRules(css); /* Filter unused @keyframes */ filterKeyframes(css, unusedRules); return css; }
javascript
{ "resource": "" }
q58420
parseUncssrc
validation
function parseUncssrc(filename) { let options = JSON.parse(fs.readFileSync(filename, 'utf-8')); /* RegExps can't be stored as JSON, therefore we need to parse them manually. * A string is a RegExp if it starts with '/', since that wouldn't be a valid CSS selector. */ options.ignore = options.ignore ? options.ignore.map(strToRegExp) : undefined; options.ignoreSheets = options.ignoreSheets ? options.ignoreSheets.map(strToRegExp) : undefined; return options; }
javascript
{ "resource": "" }
q58421
parsePaths
validation
function parsePaths(source, stylesheets, options) { return stylesheets.map((sheet) => { let sourceProtocol; const isLocalFile = sheet.substr(0, 5) === 'file:'; if (sheet.substr(0, 4) === 'http') { /* No need to parse, it's already a valid path */ return sheet; } /* Check if we are fetching over http(s) */ if (isURL(source) && !isLocalFile) { sourceProtocol = url.parse(source).protocol; if (sheet.substr(0, 2) === '//') { /* Use the same protocol we used for fetching this page. * Default to http. */ return sourceProtocol ? sourceProtocol + sheet : 'http:' + sheet; } return url.resolve(source, sheet); } /* We are fetching local files * Should probably report an error if we find an absolute path and * have no htmlroot specified. */ /* Fix the case when there is a query string or hash */ sheet = sheet.split('?')[0].split('#')[0]; /* Path already parsed by jsdom or user supplied local file */ if (isLocalFile) { sheet = url.parse(sheet).path.replace('%20', ' '); /* If on windows, remove first '/' */ sheet = isWindows() ? sheet.substring(1) : sheet; if (options.htmlroot) { return path.join(options.htmlroot, sheet); } sheet = path.relative(path.join(path.dirname(source)), sheet); } if (sheet[0] === '/' && options.htmlroot) { return path.join(options.htmlroot, sheet); } else if (isHTML(source)) { return path.join(options.csspath, sheet); } return path.join(path.dirname(source), options.csspath, sheet); }); }
javascript
{ "resource": "" }
q58422
readStylesheets
validation
function readStylesheets(files, outputBanner) { return Promise.all(files.map((filename) => { if (isURL(filename)) { return new Promise((resolve, reject) => { request({ url: filename, headers: { 'User-Agent': 'UnCSS' } }, (err, response, body) => { if (err) { return reject(err); } return resolve(body); }); }); } else if (fs.existsSync(filename)) { return new Promise((resolve, reject) => { fs.readFile(filename, 'utf-8', (err, contents) => { if (err) { return reject(err); } return resolve(contents); }); }); } throw new Error(`UnCSS: could not open ${path.join(process.cwd(), filename)}`); })).then((res) => { // res is an array of the content of each file in files (in the same order) if (outputBanner) { for (let i = 0, len = files.length; i < len; i++) { // We append a small banner to keep track of which file we are currently processing // super helpful for debugging const banner = `/*** uncss> filename: ${files[i].replace(/\\/g, '/')} ***/\n`; res[i] = banner + res[i]; } } return res; }); }
javascript
{ "resource": "" }
q58423
getHTML
validation
function getHTML(files, options) { if (_.isString(files)) { files = [files]; } files = _.flatten(files.map((file) => { if (!isURL(file) && !isHTML(file)) { return glob.sync(file); } return file; })); if (!files.length) { return Promise.reject(new Error('UnCSS: no HTML files found')); } // Save files for later reference. options.files = files; return Promise.all(files.map((file) => jsdom.fromSource(file, options))); }
javascript
{ "resource": "" }
q58424
processWithTextApi
validation
function processWithTextApi([options, pages, stylesheets]) { /* If we specified a raw string of CSS, add it to the stylesheets array */ if (options.raw) { if (_.isString(options.raw)) { stylesheets.push(options.raw); } else { throw new Error('UnCSS: options.raw - expected a string'); } } /* At this point, there isn't any point in running the rest of the task if: * - We didn't specify any stylesheet links in the options object * - We couldn't find any stylesheet links in the HTML itself * - We weren't passed a string of raw CSS in addition to, or to replace * either of the above */ if (!_.flatten(stylesheets).length) { throw new Error('UnCSS: no stylesheets found'); } /* OK, so we have some CSS to work with! * Three steps: * - Parse the CSS * - Remove the unused rules * - Return the optimized CSS as a string */ const cssStr = stylesheets.join(' \n'); let pcss, report; try { pcss = postcss.parse(cssStr); } catch (err) { /* Try and construct a helpful error message */ throw utility.parseErrorMessage(err, cssStr); } return uncss(pages, pcss, options.ignore).then(([css, rep]) => { let newCssStr = ''; postcss.stringify(css, (result) => { newCssStr += result; }); if (options.report) { report = { original: cssStr, selectors: rep }; } return [newCssStr, report]; }); }
javascript
{ "resource": "" }
q58425
init
validation
function init(files, options, callback) { if (_.isFunction(options)) { /* There were no options, this argument is actually the callback */ callback = options; options = {}; } else if (!_.isFunction(callback)) { throw new TypeError('UnCSS: expected a callback'); } /* Try and read options from the specified uncssrc file */ if (options.uncssrc) { try { /* Manually-specified options take precedence over uncssrc options */ options = _.merge(utility.parseUncssrc(options.uncssrc), options); } catch (err) { if (err instanceof SyntaxError) { callback(new SyntaxError('UnCSS: uncssrc file is invalid JSON.')); return; } callback(err); return; } } /* Assign default values to options, unless specified */ options = _.defaults(options, { csspath: '', ignore: [], media: [], timeout: 0, report: false, ignoreSheets: [], html: files, banner: true, // gulp-uncss parameters: raw: null, userAgent: 'uncss', inject: null }); process(options).then(([css, report]) => callback(null, css, report), callback); }
javascript
{ "resource": "" }
q58426
fromSource
validation
function fromSource(src, options) { const config = { features: { FetchExternalResources: ['script'], ProcessExternalResources: ['script'] }, virtualConsole: jsdom.createVirtualConsole().sendTo(console), userAgent: options.userAgent }; // The htmlroot option allows root-relative URLs (starting with a slash) // to be used for all resources. Without it, root-relative URLs are // looked up relative to file://, so will not be found. if (options.htmlroot) { config.resourceLoader = function(resource, callback) { // See whether raw attribute value is root-relative. const src = resource.element.getAttribute('src'); if (src.indexOf('/') === 0) { resource.url.pathname = path.join(options.htmlroot, src); } return resource.defaultFetch(callback); }; } if (options.inject) { config.onload = function(window) { if (typeof options.inject === 'function') { options.inject(window); } else { require(path.join(__dirname, options.inject))(window); } }; } return new Promise((resolve, reject) => { jsdom.env(src, config, (err, res) => { if (err) { return reject(err); } return resolve(res); }); }).then((result) => { return new Promise((resolve) => { setTimeout(() => resolve(result), options.timeout); }); }); }
javascript
{ "resource": "" }
q58427
getStylesheets
validation
function getStylesheets(window, options) { if (Array.isArray(options.media) === false) { options.media = [options.media]; } const media = _.union(['', 'all', 'screen'], options.media); const elements = window.document.querySelectorAll('link[rel="stylesheet"]'); return Array.prototype.map.call(elements, (link) => ({ href: link.getAttribute('href'), media: link.getAttribute('media') || '' })) .filter((sheet) => media.indexOf(sheet.media) !== -1) .map((sheet) => sheet.href); }
javascript
{ "resource": "" }
q58428
findAll
validation
function findAll(window, sels) { const document = window.document; // Unwrap noscript elements. const elements = document.getElementsByTagName('noscript'); Array.prototype.forEach.call(elements, (ns) => { const wrapper = document.createElement('div'); wrapper.innerHTML = ns.textContent; // Insert each child of the <noscript> as its sibling Array.prototype.forEach.call(wrapper.children, (child) => { ns.parentNode.insertBefore(child, ns); }); }); // Do the filtering. return sels.filter((selector) => { try { return document.querySelector(selector); } catch (e) { return true; } }); }
javascript
{ "resource": "" }
q58429
openDB
validation
function openDB(name, version, { blocked, upgrade, blocking } = {}) { const request = indexedDB.open(name, version); const openPromise = wrap(request); if (upgrade) { request.addEventListener('upgradeneeded', (event) => { upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction)); }); } if (blocked) request.addEventListener('blocked', () => blocked()); if (blocking) openPromise.then(db => db.addEventListener('versionchange', blocking)); return openPromise; }
javascript
{ "resource": "" }
q58430
deleteDB
validation
function deleteDB(name, { blocked } = {}) { const request = indexedDB.deleteDatabase(name); if (blocked) request.addEventListener('blocked', () => blocked()); return wrap(request).then(() => undefined); }
javascript
{ "resource": "" }
q58431
getCursorAdvanceMethods
validation
function getCursorAdvanceMethods() { return cursorAdvanceMethods || (cursorAdvanceMethods = [ IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey, ]); }
javascript
{ "resource": "" }
q58432
resolveOrReject
validation
function resolveOrReject(data) { if (data.filename) { console.warn(data); } if (!options.async) { head.removeChild(style); } }
javascript
{ "resource": "" }
q58433
validation
function(t) { return function() { var obj = Object.create(t.prototype); t.apply(obj, Array.prototype.slice.call(arguments, 0)); return obj; }; }
javascript
{ "resource": "" }
q58434
addReplacementIntoPath
validation
function addReplacementIntoPath(beginningPath, addPath, replacedElement, originalSelector) { var newSelectorPath, lastSelector, newJoinedSelector; // our new selector path newSelectorPath = []; // construct the joined selector - if & is the first thing this will be empty, // if not newJoinedSelector will be the last set of elements in the selector if (beginningPath.length > 0) { newSelectorPath = utils.copyArray(beginningPath); lastSelector = newSelectorPath.pop(); newJoinedSelector = originalSelector.createDerived(utils.copyArray(lastSelector.elements)); } else { newJoinedSelector = originalSelector.createDerived([]); } if (addPath.length > 0) { // /deep/ is a CSS4 selector - (removed, so should deprecate) // that is valid without anything in front of it // so if the & does not have a combinator that is "" or " " then // and there is a combinator on the parent, then grab that. // this also allows + a { & .b { .a & { ... though not sure why you would want to do that var combinator = replacedElement.combinator, parentEl = addPath[0].elements[0]; if (combinator.emptyOrWhitespace && !parentEl.combinator.emptyOrWhitespace) { combinator = parentEl.combinator; } // join the elements so far with the first part of the parent newJoinedSelector.elements.push(new Element( combinator, parentEl.value, replacedElement.isVariable, replacedElement._index, replacedElement._fileInfo )); newJoinedSelector.elements = newJoinedSelector.elements.concat(addPath[0].elements.slice(1)); } // now add the joined selector - but only if it is not empty if (newJoinedSelector.elements.length !== 0) { newSelectorPath.push(newJoinedSelector); } // put together the parent selectors after the join (e.g. the rest of the parent) if (addPath.length > 1) { var restOfPath = addPath.slice(1); restOfPath = restOfPath.map(function (selector) { return selector.createDerived(selector.elements, []); }); newSelectorPath = newSelectorPath.concat(restOfPath); } return newSelectorPath; }
javascript
{ "resource": "" }
q58435
addAllReplacementsIntoPath
validation
function addAllReplacementsIntoPath( beginningPath, addPaths, replacedElement, originalSelector, result) { var j; for (j = 0; j < beginningPath.length; j++) { var newSelectorPath = addReplacementIntoPath(beginningPath[j], addPaths, replacedElement, originalSelector); result.push(newSelectorPath); } return result; }
javascript
{ "resource": "" }
q58436
replaceParentSelector
validation
function replaceParentSelector(paths, context, inSelector) { // The paths are [[Selector]] // The first list is a list of comma separated selectors // The inner list is a list of inheritance separated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // var i, j, k, currentElements, newSelectors, selectorsMultiplied, sel, el, hadParentSelector = false, length, lastSelector; function findNestedSelector(element) { var maybeSelector; if (!(element.value instanceof Paren)) { return null; } maybeSelector = element.value.value; if (!(maybeSelector instanceof Selector)) { return null; } return maybeSelector; } // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [ [] ]; for (i = 0; (el = inSelector.elements[i]); i++) { // non parent reference elements just get added if (el.value !== '&') { var nestedSelector = findNestedSelector(el); if (nestedSelector != null) { // merge the current list of non parent selector elements // on to the current list of selectors to add mergeElementsOnToSelectors(currentElements, newSelectors); var nestedPaths = [], replaced, replacedNewSelectors = []; replaced = replaceParentSelector(nestedPaths, context, nestedSelector); hadParentSelector = hadParentSelector || replaced; // the nestedPaths array should have only one member - replaceParentSelector does not multiply selectors for (k = 0; k < nestedPaths.length; k++) { var replacementSelector = createSelector(createParenthesis(nestedPaths[k], el), el); addAllReplacementsIntoPath(newSelectors, [replacementSelector], el, inSelector, replacedNewSelectors); } newSelectors = replacedNewSelectors; currentElements = []; } else { currentElements.push(el); } } else { hadParentSelector = true; // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add mergeElementsOnToSelectors(currentElements, newSelectors); // loop through our current selectors for (j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length === 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements.push(new Element(el.combinator, '', el.isVariable, el._index, el._fileInfo)); } selectorsMultiplied.push(sel); } else { // and the parent selectors for (k = 0; k < context.length; k++) { // We need to put the current selectors // then join the last selector's elements on to the parents selectors var newSelectorPath = addReplacementIntoPath(sel, context[k], el, inSelector); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors mergeElementsOnToSelectors(currentElements, newSelectors); for (i = 0; i < newSelectors.length; i++) { length = newSelectors[i].length; if (length > 0) { paths.push(newSelectors[i]); lastSelector = newSelectors[i][length - 1]; newSelectors[i][length - 1] = lastSelector.createDerived(lastSelector.elements, inSelector.extendList); } } return hadParentSelector; }
javascript
{ "resource": "" }
q58437
validation
function (value, unit) { this.value = parseFloat(value); if (isNaN(this.value)) { throw new Error('Dimension is not a number.'); } this.unit = (unit && unit instanceof Unit) ? unit : new Unit(unit ? [unit] : undefined); this.setParent(this.unit, this); }
javascript
{ "resource": "" }
q58438
parseNode
validation
function parseNode(str, parseList, currentIndex, fileInfo, callback) { var result, returnNodes = []; var parser = parserInput; try { parser.start(str, false, function fail(msg, index) { callback({ message: msg, index: index + currentIndex }); }); for (var x = 0, p, i; (p = parseList[x]); x++) { i = parser.i; result = parsers[p](); if (result) { result._index = i + currentIndex; result._fileInfo = fileInfo; returnNodes.push(result); } else { returnNodes.push(null); } } var endInfo = parser.end(); if (endInfo.isFinished) { callback(null, returnNodes); } else { callback(true, null); } } catch (e) { throw new LessError({ index: e.index + currentIndex, message: e.message }, imports, fileInfo.filename); } }
javascript
{ "resource": "" }
q58439
validation
function (str, callback, additionalData) { var root, error = null, globalVars, modifyVars, ignored, preText = ''; globalVars = (additionalData && additionalData.globalVars) ? Parser.serializeVars(additionalData.globalVars) + '\n' : ''; modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + Parser.serializeVars(additionalData.modifyVars) : ''; if (context.pluginManager) { var preProcessors = context.pluginManager.getPreProcessors(); for (var i = 0; i < preProcessors.length; i++) { str = preProcessors[i].process(str, { context: context, imports: imports, fileInfo: fileInfo }); } } if (globalVars || (additionalData && additionalData.banner)) { preText = ((additionalData && additionalData.banner) ? additionalData.banner : '') + globalVars; ignored = imports.contentsIgnoredChars; ignored[fileInfo.filename] = ignored[fileInfo.filename] || 0; ignored[fileInfo.filename] += preText.length; } str = str.replace(/\r\n?/g, '\n'); // Remove potential UTF Byte Order Mark str = preText + str.replace(/^\uFEFF/, '') + modifyVars; imports.contents[fileInfo.filename] = str; // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { parserInput.start(str, context.chunkInput, function fail(msg, index) { throw new LessError({ index: index, type: 'Parse', message: msg, filename: fileInfo.filename }, imports); }); tree.Node.prototype.parse = this; root = new tree.Ruleset(null, this.parsers.primary()); tree.Node.prototype.rootNode = root; root.root = true; root.firstRoot = true; root.functionRegistry = functionRegistry.inherit(); } catch (e) { return callback(new LessError(e, imports, fileInfo.filename)); } // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occurred. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. var endInfo = parserInput.end(); if (!endInfo.isFinished) { var message = endInfo.furthestPossibleErrorMessage; if (!message) { message = 'Unrecognised input'; if (endInfo.furthestChar === '}') { message += '. Possibly missing opening \'{\''; } else if (endInfo.furthestChar === ')') { message += '. Possibly missing opening \'(\''; } else if (endInfo.furthestReachedEnd) { message += '. Possibly missing something'; } } error = new LessError({ type: 'Parse', message: message, index: endInfo.furthest, filename: fileInfo.filename }, imports); } var finish = function (e) { e = error || e || imports.error; if (e) { if (!(e instanceof LessError)) { e = new LessError(e, imports, fileInfo.filename); } return callback(e); } else { return callback(null, root); } }; if (context.processImports !== false) { new visitors.ImportVisitor(imports, finish) .run(root); } else { return finish(); } }
javascript
{ "resource": "" }
q58440
validation
function () { if (parserInput.commentStore.length) { var comment = parserInput.commentStore.shift(); return new(tree.Comment)(comment.text, comment.isLineComment, comment.index, fileInfo); } }
javascript
{ "resource": "" }
q58441
validation
function (forceEscaped) { var str, index = parserInput.i, isEscaped = false; parserInput.save(); if (parserInput.$char('~')) { isEscaped = true; } else if (forceEscaped) { parserInput.restore(); return; } str = parserInput.$quoted(); if (!str) { parserInput.restore(); return; } parserInput.forget(); return new(tree.Quoted)(str.charAt(0), str.substr(1, str.length - 2), isEscaped, index, fileInfo); }
javascript
{ "resource": "" }
q58442
validation
function () { var ch, name, index = parserInput.i; parserInput.save(); if (parserInput.currentChar() === '@' && (name = parserInput.$re(/^@@?[\w-]+/))) { ch = parserInput.currentChar(); if (ch === '(' || ch === '[' && !parserInput.prevChar().match(/^\s/)) { // this may be a VariableCall lookup var result = parsers.variableCall(name); if (result) { parserInput.forget(); return result; } } parserInput.forget(); return new(tree.Variable)(name, index, fileInfo); } parserInput.restore(); }
javascript
{ "resource": "" }
q58443
validation
function () { if (parserInput.peekNotNumeric()) { return; } var value = parserInput.$re(/^([+-]?\d*\.?\d+)(%|[a-z_]+)?/i); if (value) { return new(tree.Dimension)(value[1], value[2]); } }
javascript
{ "resource": "" }
q58444
validation
function () { var js, index = parserInput.i; parserInput.save(); var escape = parserInput.$char('~'); var jsQuote = parserInput.$char('`'); if (!jsQuote) { parserInput.restore(); return; } js = parserInput.$re(/^[^`]*`/); if (js) { parserInput.forget(); return new(tree.JavaScript)(js.substr(0, js.length - 1), Boolean(escape), index, fileInfo); } parserInput.restore('invalid javascript definition'); }
javascript
{ "resource": "" }
q58445
validation
function (parsedName) { var lookups, important, i = parserInput.i, inValue = !!parsedName, name = parsedName; parserInput.save(); if (name || (parserInput.currentChar() === '@' && (name = parserInput.$re(/^(@[\w-]+)(\(\s*\))?/)))) { lookups = this.mixin.ruleLookups(); if (!lookups && ((inValue && parserInput.$str('()') !== '()') || (name[2] !== '()'))) { parserInput.restore('Missing \'[...]\' lookup in variable call'); return; } if (!inValue) { name = name[1]; } if (lookups && parsers.important()) { important = true; } var call = new tree.VariableCall(name, i, fileInfo); if (!inValue && parsers.end()) { parserInput.forget(); return call; } else { parserInput.forget(); return new tree.NamespaceValue(call, lookups, important, i, fileInfo); } } parserInput.restore(); }
javascript
{ "resource": "" }
q58446
validation
function () { var name, params = [], match, ruleset, cond, variadic = false; if ((parserInput.currentChar() !== '.' && parserInput.currentChar() !== '#') || parserInput.peek(/^[^{]*\}/)) { return; } parserInput.save(); match = parserInput.$re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); if (match) { name = match[1]; var argInfo = this.args(false); params = argInfo.args; variadic = argInfo.variadic; // .mixincall("@{a}"); // looks a bit like a mixin definition.. // also // .mixincall(@a: {rule: set;}); // so we have to be nice and restore if (!parserInput.$char(')')) { parserInput.restore('Missing closing \')\''); return; } parserInput.commentStore.length = 0; if (parserInput.$str('when')) { // Guard cond = expect(parsers.conditions, 'expected condition'); } ruleset = parsers.block(); if (ruleset) { parserInput.forget(); return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { parserInput.restore(); } } else { parserInput.forget(); } }
javascript
{ "resource": "" }
q58447
validation
function () { var entities = this.entities; return this.comment() || entities.literal() || entities.variable() || entities.url() || entities.property() || entities.call() || entities.keyword() || this.mixin.call(true) || entities.javascript(); }
javascript
{ "resource": "" }
q58448
validation
function () { var index = parserInput.i, name, value, rules, nonVendorSpecificName, hasIdentifier, hasExpression, hasUnknown, hasBlock = true, isRooted = true; if (parserInput.currentChar() !== '@') { return; } value = this['import']() || this.plugin() || this.media(); if (value) { return value; } parserInput.save(); name = parserInput.$re(/^@[a-z-]+/); if (!name) { return; } nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = '@' + name.slice(name.indexOf('-', 2) + 1); } switch (nonVendorSpecificName) { case '@charset': hasIdentifier = true; hasBlock = false; break; case '@namespace': hasExpression = true; hasBlock = false; break; case '@keyframes': case '@counter-style': hasIdentifier = true; break; case '@document': case '@supports': hasUnknown = true; isRooted = false; break; default: hasUnknown = true; break; } parserInput.commentStore.length = 0; if (hasIdentifier) { value = this.entity(); if (!value) { error('expected ' + name + ' identifier'); } } else if (hasExpression) { value = this.expression(); if (!value) { error('expected ' + name + ' expression'); } } else if (hasUnknown) { value = this.permissiveValue(/^[{;]/); hasBlock = (parserInput.currentChar() === '{'); if (!value) { if (!hasBlock && parserInput.currentChar() !== ';') { error(name + ' rule is missing block or ending semi-colon'); } } else if (!value.value) { value = null; } } if (hasBlock) { rules = this.blockRuleset(); } if (rules || (!hasBlock && value && parserInput.$char(';'))) { parserInput.forget(); return new (tree.AtRule)(name, value, rules, index, fileInfo, context.dumpLineNumbers ? getDebugInfo(index) : null, isRooted ); } parserInput.restore('at-rule options not recognised'); }
javascript
{ "resource": "" }
q58449
validation
function () { var entities = this.entities, negate; if (parserInput.peek(/^-[@\$\(]/)) { negate = parserInput.$char('-'); } var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.property() || entities.call() || entities.quoted(true) || entities.colorKeyword() || entities.mixinLookup(); if (negate) { o.parensInOp = true; o = new(tree.Negative)(o); } return o; }
javascript
{ "resource": "" }
q58450
validation
function () { var entities = [], e, delim, index = parserInput.i; do { e = this.comment(); if (e) { entities.push(e); continue; } e = this.addition() || this.entity(); if (e) { entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here if (!parserInput.peek(/^\/[\/*]/)) { delim = parserInput.$char('/'); if (delim) { entities.push(new(tree.Anonymous)(delim, index)); } } } } while (e); if (entities.length > 0) { return new(tree.Expression)(entities); } }
javascript
{ "resource": "" }
q58451
validation
function (name, args, index, currentFileInfo) { this.name = name; this.args = args; this.calc = name === 'calc'; this._index = index; this._fileInfo = currentFileInfo; }
javascript
{ "resource": "" }
q58452
validation
function(less) { this.less = less; this.require = function(prefix) { prefix = path.dirname(prefix); return function(id) { var str = id.substr(0, 2); if (str === '..' || str === './') { return require(path.join(prefix, id)); } else { return require(id); } }; }; }
javascript
{ "resource": "" }
q58453
validation
function(less, context, rootFileInfo) { this.less = less; this.rootFilename = rootFileInfo.filename; this.paths = context.paths || []; // Search paths, when importing this.contents = {}; // map - filename to contents of all the files this.contentsIgnoredChars = {}; // map - filename to lines at the beginning of each file to ignore this.mime = context.mime; this.error = null; this.context = context; // Deprecated? Unused outside of here, could be useful. this.queue = []; // Files which haven't been imported yet this.files = {}; // Holds the imported parse trees. }
javascript
{ "resource": "" }
q58454
hasFakeRuleset
validation
function hasFakeRuleset(atRuleNode) { var bodyRules = atRuleNode.rules; return bodyRules.length === 1 && (!bodyRules[0].paths || bodyRules[0].paths.length === 0); }
javascript
{ "resource": "" }
q58455
bind
validation
function bind(func, thisArg) { var curryArgs = Array.prototype.slice.call(arguments, 2); return function() { var args = curryArgs.concat(Array.prototype.slice.call(arguments, 0)); return func.apply(thisArg, args); }; }
javascript
{ "resource": "" }
q58456
getNodeTransitions
validation
function getNodeTransitions(oldData, nextData) { const oldDataKeyed = oldData && getKeyedData(oldData); const nextDataKeyed = nextData && getKeyedData(nextData); return { entering: oldDataKeyed && getKeyedDataDifference(nextDataKeyed, oldDataKeyed), exiting: nextDataKeyed && getKeyedDataDifference(oldDataKeyed, nextDataKeyed) }; }
javascript
{ "resource": "" }
q58457
getInitialTransitionState
validation
function getInitialTransitionState(oldChildren, nextChildren) { let nodesWillExit = false; let nodesWillEnter = false; const getTransition = (oldChild, newChild) => { if (!newChild || oldChild.type !== newChild.type) { return {}; } const { entering, exiting } = getNodeTransitions(getChildData(oldChild), getChildData(newChild)) || {}; nodesWillExit = nodesWillExit || !!exiting; nodesWillEnter = nodesWillEnter || !!entering; return { entering: entering || false, exiting: exiting || false }; }; const getTransitionsFromChildren = (old, next) => { return old.map((child, idx) => { if (child && child.props && child.props.children && next[idx]) { return getTransitionsFromChildren( React.Children.toArray(old[idx].props.children), React.Children.toArray(next[idx].props.children) ); } // get Transition entering and exiting nodes return getTransition(child, next[idx]); }); }; const childrenTransitions = getTransitionsFromChildren( React.Children.toArray(oldChildren), React.Children.toArray(nextChildren) ); return { nodesWillExit, nodesWillEnter, childrenTransitions, // TODO: This may need to be refactored for the following situation. // The component receives new props, and the data provided // is a perfect match for the previous data and domain except // for new nodes. In this case, we wouldn't want a delay before // the new nodes appear. nodesShouldEnter: false }; }
javascript
{ "resource": "" }
q58458
omit
validation
function omit(originalObject, keys = []) { // code based on babel's _objectWithoutProperties const newObject = {}; for (const key in originalObject) { if (keys.indexOf(key) >= 0) { continue; } if (!Object.prototype.hasOwnProperty.call(originalObject, key)) { continue; } newObject[key] = originalObject[key]; } return newObject; }
javascript
{ "resource": "" }
q58459
createDomainFunction
validation
function createDomainFunction(getDomainFromDataFunction, formatDomainFunction) { getDomainFromDataFunction = isFunction(getDomainFromDataFunction) ? getDomainFromDataFunction : getDomainFromData; formatDomainFunction = isFunction(formatDomainFunction) ? formatDomainFunction : formatDomain; return (props, axis) => { const propsDomain = getDomainFromProps(props, axis); if (propsDomain) { return formatDomainFunction(propsDomain, props, axis); } const categories = Data.getCategories(props, axis); const domain = categories ? getDomainFromCategories(props, axis, categories) : getDomainFromDataFunction(props, axis); return domain ? formatDomainFunction(domain, props, axis) : undefined; }; }
javascript
{ "resource": "" }
q58460
formatDomain
validation
function formatDomain(domain, props, axis) { return cleanDomain(padDomain(domain, props, axis), props, axis); }
javascript
{ "resource": "" }
q58461
getDomainFromCategories
validation
function getDomainFromCategories(props, axis, categories) { categories = categories || Data.getCategories(props, axis); const { polar, startAngle = 0, endAngle = 360 } = props; if (!categories) { return undefined; } const minDomain = getMinFromProps(props, axis); const maxDomain = getMaxFromProps(props, axis); const stringArray = Collection.containsStrings(categories) ? Data.getStringsFromCategories(props, axis) : []; const stringMap = stringArray.length === 0 ? null : stringArray.reduce((memo, string, index) => { memo[string] = index + 1; return memo; }, {}); const categoryValues = stringMap ? categories.map((value) => stringMap[value]) : categories; const min = minDomain !== undefined ? minDomain : Collection.getMinValue(categoryValues); const max = maxDomain !== undefined ? maxDomain : Collection.getMaxValue(categoryValues); const categoryDomain = getDomainFromMinMax(min, max); return polar && axis === "x" && Math.abs(startAngle - endAngle) === 360 ? getSymmetricDomain(categoryDomain, categoryValues) : categoryDomain; }
javascript
{ "resource": "" }
q58462
getDomainFromData
validation
function getDomainFromData(props, axis, dataset) { dataset = dataset || Data.getData(props); const { polar, startAngle = 0, endAngle = 360 } = props; const minDomain = getMinFromProps(props, axis); const maxDomain = getMaxFromProps(props, axis); if (dataset.length < 1) { return minDomain !== undefined && maxDomain !== undefined ? getDomainFromMinMax(minDomain, maxDomain) : undefined; } const min = minDomain !== undefined ? minDomain : getExtremeFromData(dataset, axis, "min"); const max = maxDomain !== undefined ? maxDomain : getExtremeFromData(dataset, axis, "max"); const domain = getDomainFromMinMax(min, max); return polar && axis === "x" && Math.abs(startAngle - endAngle) === 360 ? getSymmetricDomain(domain, getFlatData(dataset, axis)) : domain; }
javascript
{ "resource": "" }
q58463
getDomainFromMinMax
validation
function getDomainFromMinMax(min, max) { const getSinglePointDomain = (val) => { // d3-scale does not properly resolve very small differences. // eslint-disable-next-line no-magic-numbers const verySmallNumber = val === 0 ? 2 * Math.pow(10, -10) : Math.pow(10, -10); const verySmallDate = 1; const minVal = val instanceof Date ? new Date(+val - verySmallDate) : +val - verySmallNumber; const maxVal = val instanceof Date ? new Date(+val + verySmallDate) : +val + verySmallNumber; return val === 0 ? [0, maxVal] : [minVal, maxVal]; }; return +min === +max ? getSinglePointDomain(max) : [min, max]; }
javascript
{ "resource": "" }
q58464
getDomainFromProps
validation
function getDomainFromProps(props, axis) { const minDomain = getMinFromProps(props, axis); const maxDomain = getMaxFromProps(props, axis); if (isPlainObject(props.domain) && props.domain[axis]) { return props.domain[axis]; } else if (Array.isArray(props.domain)) { return props.domain; } else if (minDomain !== undefined && maxDomain !== undefined) { return getDomainFromMinMax(minDomain, maxDomain); } return undefined; }
javascript
{ "resource": "" }
q58465
getDomainWithZero
validation
function getDomainWithZero(props, axis) { const propsDomain = getDomainFromProps(props, axis); if (propsDomain) { return propsDomain; } const dataset = Data.getData(props); const y0Min = dataset.reduce((min, datum) => (datum._y0 < min ? datum._y0 : min), Infinity); const ensureZero = (domain) => { if (axis === "x") { return domain; } const defaultMin = y0Min !== Infinity ? y0Min : 0; const maxDomainProp = getMaxFromProps(props, axis); const minDomainProp = getMinFromProps(props, axis); const max = maxDomainProp !== undefined ? maxDomainProp : Collection.getMaxValue(domain, defaultMin); const min = minDomainProp !== undefined ? minDomainProp : Collection.getMinValue(domain, defaultMin); return getDomainFromMinMax(min, max); }; const getDomainFunction = () => { return getDomainFromData(props, axis, dataset); }; const formatDomainFunction = (domain) => { return formatDomain(ensureZero(domain), props, axis); }; return createDomainFunction(getDomainFunction, formatDomainFunction)(props, axis); }
javascript
{ "resource": "" }
q58466
getMaxFromProps
validation
function getMaxFromProps(props, axis) { if (isPlainObject(props.maxDomain) && props.maxDomain[axis] !== undefined) { return props.maxDomain[axis]; } return typeof props.maxDomain === "number" ? props.maxDomain : undefined; }
javascript
{ "resource": "" }
q58467
getMinFromProps
validation
function getMinFromProps(props, axis) { if (isPlainObject(props.minDomain) && props.minDomain[axis] !== undefined) { return props.minDomain[axis]; } return typeof props.minDomain === "number" ? props.minDomain : undefined; }
javascript
{ "resource": "" }
q58468
getSymmetricDomain
validation
function getSymmetricDomain(domain, values) { const processedData = sortedUniq(values.sort((a, b) => a - b)); const step = processedData[1] - processedData[0]; return [domain[0], domain[1] + step]; }
javascript
{ "resource": "" }
q58469
isDomainComponent
validation
function isDomainComponent(component) { const getRole = (child) => { return child && child.type ? child.type.role : ""; }; let role = getRole(component); if (role === "portal") { const children = React.Children.toArray(component.props.children); role = children.length ? getRole(children[0]) : ""; } const whitelist = [ "area", "axis", "bar", "boxplot", "candlestick", "errorbar", "group", "line", "pie", "scatter", "stack", "voronoi" ]; return includes(whitelist, role); }
javascript
{ "resource": "" }
q58470
generateDataArray
validation
function generateDataArray(props, axis) { const propsDomain = isPlainObject(props.domain) ? props.domain[axis] : props.domain; const domain = propsDomain || Scale.getBaseScale(props, axis).domain(); const samples = props.samples || 1; const domainMax = Math.max(...domain); const domainMin = Math.min(...domain); const step = (domainMax - domainMin) / samples; const values = range(domainMin, domainMax, step); return last(values) === domainMax ? values : values.concat(domainMax); }
javascript
{ "resource": "" }
q58471
sortData
validation
function sortData(dataset, sortKey, sortOrder = "ascending") { if (!sortKey) { return dataset; } // Ensures previous VictoryLine api for sortKey prop stays consistent if (sortKey === "x" || sortKey === "y") { sortKey = `_${sortKey}`; } const order = sortOrder === "ascending" ? "asc" : "desc"; return orderBy(dataset, sortKey, order); }
javascript
{ "resource": "" }
q58472
getEventKey
validation
function getEventKey(key) { // creates a data accessor function // given a property key, path, array index, or null for identity. if (isFunction(key)) { return key; } else if (key === null || key === undefined) { return () => undefined; } // otherwise, assume it is an array index, property key or path (_.property handles all three) return property(key); }
javascript
{ "resource": "" }
q58473
addEventKeys
validation
function addEventKeys(props, data) { const hasEventKeyAccessor = !!props.eventKey; const eventKeyAccessor = getEventKey(props.eventKey); return data.map((datum) => { if (datum.eventKey !== undefined) { return datum; } else if (hasEventKeyAccessor) { const eventKey = eventKeyAccessor(datum); return eventKey !== undefined ? assign({ eventKey }, datum) : datum; } else { return datum; } }); }
javascript
{ "resource": "" }
q58474
createStringMap
validation
function createStringMap(props, axis) { const stringsFromAxes = getStringsFromAxes(props, axis); const stringsFromCategories = getStringsFromCategories(props, axis); const stringsFromData = getStringsFromData(props, axis); const allStrings = uniq([...stringsFromAxes, ...stringsFromCategories, ...stringsFromData]); return allStrings.length === 0 ? null : allStrings.reduce((memo, string, index) => { memo[string] = index + 1; return memo; }, {}); }
javascript
{ "resource": "" }
q58475
downsample
validation
function downsample(data, maxPoints, startingIndex = 0) { // ensures that the downampling of data while zooming looks good. const dataLength = getLength(data); if (dataLength > maxPoints) { // limit k to powers of 2, e.g. 64, 128, 256 // so that the same points will be chosen reliably, reducing flicker on zoom const k = Math.pow(2, Math.ceil(Math.log2(dataLength / maxPoints))); return data.filter( // ensure modulo is always calculated from same reference: i + startingIndex (d, i) => (i + startingIndex) % k === 0 ); } return data; }
javascript
{ "resource": "" }
q58476
formatData
validation
function formatData(dataset, props, expectedKeys) { const isArrayOrIterable = Array.isArray(dataset) || Immutable.isIterable(dataset); if (!isArrayOrIterable || getLength(dataset) < 1) { return []; } const defaultKeys = ["x", "y", "y0"]; expectedKeys = Array.isArray(expectedKeys) ? expectedKeys : defaultKeys; const stringMap = { x: expectedKeys.indexOf("x") !== -1 ? createStringMap(props, "x") : undefined, y: expectedKeys.indexOf("y") !== -1 ? createStringMap(props, "y") : undefined, y0: expectedKeys.indexOf("y0") !== -1 ? createStringMap(props, "y") : undefined }; const createAccessor = (name) => { return Helpers.createAccessor(props[name] !== undefined ? props[name] : name); }; const accessor = expectedKeys.reduce((memo, type) => { memo[type] = createAccessor(type); return memo; }, {}); const preformattedData = isEqual(expectedKeys, defaultKeys) && props.x === "_x" && props.y === "_y" && props.y0 === "_y0"; const data = preformattedData ? dataset : dataset.reduce((dataArr, datum, index) => { // eslint-disable-line complexity datum = parseDatum(datum); const fallbackValues = { x: index, y: datum }; const processedValues = expectedKeys.reduce((memo, type) => { const processedValue = accessor[type](datum); const value = processedValue !== undefined ? processedValue : fallbackValues[type]; if (value !== undefined) { if (typeof value === "string" && stringMap[type]) { memo[`${type}Name`] = value; memo[`_${type}`] = stringMap[type][value]; } else { memo[`_${type}`] = value; } } return memo; }, {}); const formattedDatum = assign({}, processedValues, datum); if (!isEmpty(formattedDatum)) { dataArr.push(formattedDatum); } return dataArr; }, []); const sortedData = sortData(data, props.sortKey, props.sortOrder); const cleanedData = cleanData(sortedData, props); return addEventKeys(props, cleanedData); }
javascript
{ "resource": "" }
q58477
generateData
validation
function generateData(props) { const xValues = generateDataArray(props, "x"); const yValues = generateDataArray(props, "y"); const values = xValues.map((x, i) => { return { x, y: yValues[i] }; }); return values; }
javascript
{ "resource": "" }
q58478
getCategories
validation
function getCategories(props, axis) { return props.categories && !Array.isArray(props.categories) ? props.categories[axis] : props.categories; }
javascript
{ "resource": "" }
q58479
getData
validation
function getData(props) { return props.data ? formatData(props.data, props) : formatData(generateData(props), props); }
javascript
{ "resource": "" }
q58480
getStringsFromAxes
validation
function getStringsFromAxes(props, axis) { const { tickValues, tickFormat } = props; let tickValueArray; if (!tickValues || (!Array.isArray(tickValues) && !tickValues[axis])) { tickValueArray = tickFormat && Array.isArray(tickFormat) ? tickFormat : []; } else { tickValueArray = tickValues[axis] || tickValues; } return tickValueArray.filter((val) => typeof val === "string"); }
javascript
{ "resource": "" }
q58481
getStringsFromCategories
validation
function getStringsFromCategories(props, axis) { if (!props.categories) { return []; } const categories = getCategories(props, axis); const categoryStrings = categories && categories.filter((val) => typeof val === "string"); return categoryStrings ? Collection.removeUndefined(categoryStrings) : []; }
javascript
{ "resource": "" }
q58482
getStringsFromData
validation
function getStringsFromData(props, axis) { const isArrayOrIterable = Array.isArray(props.data) || Immutable.isIterable(props.data); if (!isArrayOrIterable) { return []; } const key = props[axis] === undefined ? axis : props[axis]; const accessor = Helpers.createAccessor(key); // support immutable data const data = props.data.reduce((memo, d) => { memo.push(parseDatum(d)); return memo; }, []); const sortedData = sortData(data, props.sortKey, props.sortOrder); const dataStrings = sortedData .reduce((dataArr, datum) => { datum = parseDatum(datum); dataArr.push(accessor(datum)); return dataArr; }, []) .filter((datum) => typeof datum === "string"); // return a unique set of strings return dataStrings.reduce((prev, curr) => { if (curr !== undefined && curr !== null && prev.indexOf(curr) === -1) { prev.push(curr); } return prev; }, []); }
javascript
{ "resource": "" }
q58483
findAxisComponents
validation
function findAxisComponents(childComponents, predicate) { predicate = predicate || identity; const findAxes = (children) => { return children.reduce((memo, child) => { if (child.type && child.type.role === "axis" && predicate(child)) { return memo.concat(child); } else if (child.props && child.props.children) { return memo.concat(findAxes(React.Children.toArray(child.props.children))); } return memo; }, []); }; return findAxes(childComponents); }
javascript
{ "resource": "" }
q58484
getDomainFromData
validation
function getDomainFromData(props, axis) { const { polar, startAngle = 0, endAngle = 360 } = props; const tickValues = getTickArray(props); if (!Array.isArray(tickValues)) { return undefined; } const minDomain = Domain.getMinFromProps(props, axis); const maxDomain = Domain.getMaxFromProps(props, axis); const tickStrings = stringTicks(props); const ticks = tickValues.map((value) => +value); const defaultMin = tickStrings ? 1 : Collection.getMinValue(ticks); const defaultMax = tickStrings ? tickValues.length : Collection.getMaxValue(ticks); const min = minDomain !== undefined ? minDomain : defaultMin; const max = maxDomain !== undefined ? maxDomain : defaultMax; const initialDomain = Domain.getDomainFromMinMax(min, max); const domain = polar && axis === "x" && Math.abs(startAngle - endAngle) === 360 ? Domain.getSymmetricDomain(initialDomain, ticks) : initialDomain; if (isVertical(props) && !polar) { domain.reverse(); } return domain; }
javascript
{ "resource": "" }
q58485
getDomain
validation
function getDomain(props, axis) { const inherentAxis = getAxis(props); if (axis && axis !== inherentAxis) { return undefined; } return Domain.createDomainFunction(getDomainFromData)(props, inherentAxis); }
javascript
{ "resource": "" }
q58486
fillData
validation
function fillData(props, datasets) { const { fillInMissingData } = props; const xMap = datasets.reduce((prev, dataset) => { dataset.forEach((datum) => { prev[datum._x instanceof Date ? datum._x.getTime() : datum._x] = true; }); return prev; }, {}); const xKeys = keys(xMap).map((k) => +k); const xArr = orderBy(xKeys); return datasets.map((dataset) => { let indexOffset = 0; const isDate = dataset[0] && dataset[0]._x instanceof Date; const filledInData = xArr.map((x, index) => { x = +x; const datum = dataset[index - indexOffset]; if (datum) { const x1 = isDate ? datum._x.getTime() : datum._x; if (x1 === x) { return datum; } else { indexOffset++; const y = fillInMissingData ? 0 : null; x = isDate ? new Date(x) : x; return { x, y, _x: x, _y: y }; } } else { const y = fillInMissingData ? 0 : null; x = isDate ? new Date(x) : x; return { x, y, _x: x, _y: y }; } }); return filledInData; }); }
javascript
{ "resource": "" }
q58487
updateState
validation
function updateState() { history.replaceState( { left_top: split_left.scrollTop, right_top: split_right.scrollTop }, document.title ); }
javascript
{ "resource": "" }
q58488
_applyRemainingDefaultOptions
validation
function _applyRemainingDefaultOptions(opts) { opts.icon = opts.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', '¶', '❡', or '§'. opts.visible = opts.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always' & 'touch' opts.placement = opts.hasOwnProperty('placement') ? opts.placement : 'right'; // Also accepts 'left' opts.class = opts.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name. // Using Math.floor here will ensure the value is Number-cast and an integer. opts.truncate = opts.hasOwnProperty('truncate') ? Math.floor(opts.truncate) : 64; // Accepts any value that can be typecast to a number. }
javascript
{ "resource": "" }
q58489
_addBaselineStyles
validation
function _addBaselineStyles() { // We don't want to add global baseline styles if they've been added before. if (document.head.querySelector('style.anchorjs') !== null) { return; } var style = document.createElement('style'), linkRule = ' .anchorjs-link {' + ' opacity: 0;' + ' text-decoration: none;' + ' -webkit-font-smoothing: antialiased;' + ' -moz-osx-font-smoothing: grayscale;' + ' }', hoverRule = ' *:hover > .anchorjs-link,' + ' .anchorjs-link:focus {' + ' opacity: 1;' + ' }', anchorjsLinkFontFace = ' @font-face {' + ' font-family: "anchorjs-icons";' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above ' src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype");' + ' }', pseudoElContent = ' [data-anchorjs-icon]::after {' + ' content: attr(data-anchorjs-icon);' + ' }', firstStyleEl; style.className = 'anchorjs'; style.appendChild(document.createTextNode('')); // Necessary for Webkit. // We place it in the head with the other style tags, if possible, so as to // not look out of place. We insert before the others so these styles can be // overridden if necessary. firstStyleEl = document.head.querySelector('[rel="stylesheet"], style'); if (firstStyleEl === undefined) { document.head.appendChild(style); } else { document.head.insertBefore(style, firstStyleEl); } style.sheet.insertRule(linkRule, style.sheet.cssRules.length); style.sheet.insertRule(hoverRule, style.sheet.cssRules.length); style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length); style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length); }
javascript
{ "resource": "" }
q58490
getClaimValue
validation
function getClaimValue(entity, prop) { if (!entity.claims) return; if (!entity.claims[prop]) return; let value, c; for (let i = 0; i < entity.claims[prop].length; i++) { c = entity.claims[prop][i]; if (c.rank === 'deprecated') continue; if (c.mainsnak.snaktype !== 'value') continue; value = c.mainsnak.datavalue.value; if (c.rank === 'preferred') return value; // return immediately } return value; }
javascript
{ "resource": "" }
q58491
checkWikipedia
validation
function checkWikipedia(brands) { Object.keys(brands).forEach(k => { ['brand:wikipedia', 'operator:wikipedia'].forEach(t => { let wp = brands[k].tags[t]; if (wp && !/^[a-z_]{2,}:[^_]*$/.test(wp)) { _wrongFormat.push([k, wp, t]); } }); }); }
javascript
{ "resource": "" }
q58492
buildReverseIndex
validation
function buildReverseIndex(obj) { let warnCollisions = []; for (let k in obj) { checkAmbiguous(k); if (obj[k].match) { for (let i = obj[k].match.length - 1; i >= 0; i--) { let match = obj[k].match[i]; checkAmbiguous(match); if (rIndex[match]) { warnCollisions.push([rIndex[match], match]); warnCollisions.push([k, match]); } rIndex[match] = k; } } } if (warnCollisions.length) { console.warn(colors.yellow('\nWarning - match name collisions')); console.warn('To resolve these, make sure multiple entries do not contain the same "match" property.'); warnCollisions.forEach(w => console.warn( colors.yellow(' "' + w[0] + '"') + ' -> match? -> ' + colors.yellow('"' + w[1] + '"') )); } }
javascript
{ "resource": "" }
q58493
validation
function (KEY, exec) { var fn = (_core.Object || {})[KEY] || Object[KEY]; var exp = {}; exp[KEY] = exec(fn); _export(_export.S + _export.F * _fails(function () { fn(1); }), 'Object', exp); }
javascript
{ "resource": "" }
q58494
validation
function (it) { if (FREEZE && meta.NEED && isExtensible(it) && !_has(it, META)) setMeta(it); return it; }
javascript
{ "resource": "" }
q58495
isObject
validation
function isObject(obj) { // incase of arrow function and array return Object(obj) === obj && String(obj) === '[object Object]' && !isFunction(obj) && !isArray(obj); }
javascript
{ "resource": "" }
q58496
isNode$2
validation
function isNode$2(obj) { return !!((typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? obj instanceof Node : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.nodeType === 'number' && typeof obj.nodeName === 'string'); }
javascript
{ "resource": "" }
q58497
isElement
validation
function isElement(obj) { return !!((typeof HTMLElement === 'undefined' ? 'undefined' : _typeof(HTMLElement)) === 'object' ? obj instanceof HTMLElement : obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string'); }
javascript
{ "resource": "" }
q58498
isPosterityNode
validation
function isPosterityNode(parent, child) { if (!isNode$2(parent) || !isNode$2(child)) { return false; } while (child.parentNode) { child = child.parentNode; if (child === parent) { return true; } } return false; }
javascript
{ "resource": "" }
q58499
genTraversalHandler
validation
function genTraversalHandler(fn) { var setter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (target, key, value) { target[key] = value; }; // use recursive to move what in source to the target // if you do not provide a target, we will create a new target function recursiveFn(source, target, key) { if (isArray(source) || isObject(source)) { target = isPrimitive(target) ? isObject(source) ? {} : [] : target; for (var _key in source) { // $FlowFixMe: support computed key here setter(target, _key, recursiveFn(source[_key], target[_key], _key)); // target[key] = recursiveFn(source[key], target[key], key); } return target; } return fn(source, target, key); } return recursiveFn; }
javascript
{ "resource": "" }