_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q23100
doubletap
train
function doubletap(position, element, done) { touchTypes.tap(position, element, function() { setTimeout(function() { touchTypes.tap(position, element, done); }, 30); }); }
javascript
{ "resource": "" }
q23101
gesture
train
function gesture(position, element, done) { var gesture = { distanceX: config.randomizer.integer({ min: -100, max: 200 }), distanceY: config.randomizer.integer({ min: -100, max: 200 }), duration: config.randomizer.integer({ min: 20, max: 500 }) }; var touches = getTouches(position, 1, gesture.radius); triggerGesture(element, position, touches, gesture, function(touches) { done(touches, gesture); }); }
javascript
{ "resource": "" }
q23102
multitouch
train
function multitouch(position, element, done) { var points = config.randomizer.integer({ min: 2, max: config.maxTouches}); var gesture = { scale: config.randomizer.floating({ min: 0, max: 2 }), rotation: config.randomizer.natural({ min: -100, max: 100 }), radius: config.randomizer.integer({ min: 50, max: 200 }), distanceX: config.randomizer.integer({ min: -20, max: 20 }), distanceY: config.randomizer.integer({ min: -20, max: 20 }), duration: config.randomizer.integer({ min: 100, max: 1500 }) }; var touches = getTouches(position, points, gesture.radius); triggerGesture(element, position, touches, gesture, function(touches) { done(touches, gesture); }); }
javascript
{ "resource": "" }
q23103
parseOptions
train
function parseOptions (options) { var dbOptions = {} var config = { name: options.name, loglevel: options.loglevel, paths: { data: options.data, public: options.public }, plugins: options.plugins, app: options.app, inMemory: Boolean(options.inMemory), client: options.client } log.level = config.loglevel if (options.url) { config.url = options.url } if (options.adminPassword) { config.adminPassword = options.adminPassword } PouchDB.plugin(require('pouchdb-mapreduce')) options.dbUrl = createAuthDbUrl(log, options.dbUrlUsername, options.dbUrlPassword, options.dbUrl) if (options.dbUrl) { PouchDB.plugin(require('pouchdb-adapter-http')) dbOptions.prefix = options.dbUrl log.info('config', 'Storing all data in ' + options.dbUrl) } else if (options.inMemory) { PouchDB.plugin(require('pouchdb-adapter-memory')) config.inMemory = true log.info('config', 'Storing all data in memory only') } else { PouchDB.plugin(require(options.dbAdapter)) dbOptions.prefix = path.join(config.paths.data, 'data') + path.sep log.info('config', 'Storing all data in ' + dbOptions.prefix + ' using ' + options.dbAdapter) } config.PouchDB = PouchDB.defaults(dbOptions) return config }
javascript
{ "resource": "" }
q23104
_getMarkerSize
train
function _getMarkerSize(transform, mMax, lMax) { if (transform < mMax) { return SIZES.S; } else if (transform >= mMax && transform < lMax) { return SIZES.M; } else { return SIZES.L; } }
javascript
{ "resource": "" }
q23105
_computeMarkerId
train
function _computeMarkerId(highlight, transform, { maxZoom }) { const mMax = maxZoom / 4; const lMax = maxZoom / 2; const size = _getMarkerSize(transform, mMax, lMax); const highlighted = highlight ? HIGHLIGHTED : ""; const markerKey = _markerKeyBuilder(size, highlighted); return MARKERS[markerKey]; }
javascript
{ "resource": "" }
q23106
_memoizedComputeMarkerId
train
function _memoizedComputeMarkerId() { let cache = {}; return (highlight, transform, { maxZoom }) => { const cacheKey = `${highlight};${transform};${maxZoom}`; if (cache[cacheKey]) { return cache[cacheKey]; } const markerId = _computeMarkerId(highlight, transform, { maxZoom }); cache[cacheKey] = markerId; return markerId; }; }
javascript
{ "resource": "" }
q23107
smoothCurveRadius
train
function smoothCurveRadius(x1, y1, x2, y2) { const dx = x2 - x1; const dy = y2 - y1; return Math.sqrt(dx * dx + dy * dy); }
javascript
{ "resource": "" }
q23108
NodePO
train
function NodePO(id) { this.id = id; this.g = `#${this.id}`; this.path = `#${this.id} > path`; this.text = `#${this.id} > text`; this.image = `#${this.id} > image`; this.getPath = () => cy.get(this.path); this.getLabel = () => cy.get(this.text); this.getColor = () => cy.get(this.path).invoke("attr", "fill"); this.getFontSize = () => cy.get(this.text).invoke("attr", "font-size"); this.getFontWeight = () => cy.get(this.text).invoke("attr", "font-weight"); this.getImage = () => cy.get(this.image); this.getImageHref = () => cy.get(this.image).invoke("attr", "href"); this.getImageWidth = () => cy.get(this.image).invoke("attr", "width"); this.getImageHeight = () => cy.get(this.image).invoke("attr", "height"); this.getOpacity = () => cy.get(this.path).invoke("attr", "opacity"); }
javascript
{ "resource": "" }
q23109
buildSvgSymbol
train
function buildSvgSymbol(size = CONST.DEFAULT_NODE_SIZE, symbolTypeDesc = CONST.SYMBOLS.CIRCLE) { return d3Symbol() .size(() => size) .type(() => _convertTypeToD3Symbol(symbolTypeDesc))(); }
javascript
{ "resource": "" }
q23110
_getNodeOpacity
train
function _getNodeOpacity(node, highlightedNode, highlightedLink, config) { const highlight = node.highlighted || node.id === (highlightedLink && highlightedLink.source) || node.id === (highlightedLink && highlightedLink.target); const someNodeHighlighted = !!( highlightedNode || (highlightedLink && highlightedLink.source && highlightedLink.target) ); let opacity; if (someNodeHighlighted && config.highlightDegree === 0) { opacity = highlight ? config.node.opacity : config.highlightOpacity; } else if (someNodeHighlighted) { opacity = highlight ? config.node.opacity : config.highlightOpacity; } else { opacity = node.opacity || config.node.opacity; } return opacity; }
javascript
{ "resource": "" }
q23111
buildNodeProps
train
function buildNodeProps(node, config, nodeCallbacks = {}, highlightedNode, highlightedLink, transform) { const highlight = node.highlighted || (node.id === (highlightedLink && highlightedLink.source) || node.id === (highlightedLink && highlightedLink.target)); const opacity = _getNodeOpacity(node, highlightedNode, highlightedLink, config); let fill = node.color || config.node.color; if (highlight && config.node.highlightColor !== CONST.KEYWORDS.SAME) { fill = config.node.highlightColor; } let stroke = node.strokeColor || config.node.strokeColor; if (highlight && config.node.highlightStrokeColor !== CONST.KEYWORDS.SAME) { stroke = config.node.highlightStrokeColor; } let label = node[config.node.labelProperty] || node.id; if (typeof config.node.labelProperty === "function") { label = config.node.labelProperty(node); } let strokeWidth = node.strokeWidth || config.node.strokeWidth; if (highlight && config.node.highlightStrokeWidth !== CONST.KEYWORDS.SAME) { strokeWidth = config.node.highlightStrokeWidth; } const t = 1 / transform; const nodeSize = node.size || config.node.size; const fontSize = highlight ? config.node.highlightFontSize : config.node.fontSize; const dx = fontSize * t + nodeSize / 100 + 1.5; const svg = node.svg || config.node.svg; const fontColor = node.fontColor || config.node.fontColor; return { ...node, className: CONST.NODE_CLASS_NAME, cursor: config.node.mouseCursor, cx: (node && node.x) || "0", cy: (node && node.y) || "0", fill, fontColor, fontSize: fontSize * t, dx, fontWeight: highlight ? config.node.highlightFontWeight : config.node.fontWeight, id: node.id, label, onClickNode: nodeCallbacks.onClickNode, onRightClickNode: nodeCallbacks.onRightClickNode, onMouseOverNode: nodeCallbacks.onMouseOverNode, onMouseOut: nodeCallbacks.onMouseOut, opacity, renderLabel: config.node.renderLabel, size: nodeSize * t, stroke, strokeWidth: strokeWidth * t, svg, type: node.symbolType || config.node.symbolType, viewGenerator: node.viewGenerator || config.node.viewGenerator, overrideGlobalViewGenerator: !node.viewGenerator && node.svg, }; }
javascript
{ "resource": "" }
q23112
formMap
train
function formMap(k, v) { // customized props switch (k) { case "link.type": { return { type: "array", title: "link.type", items: { enum: Object.keys(LINE_TYPES), }, uniqueItems: true, }; } } return { title: k, type: typeof v, default: v, }; }
javascript
{ "resource": "" }
q23113
SandboxPO
train
function SandboxPO() { // whitelist checkbox inputs this.checkboxes = ["link.renderLabel", "node.renderLabel", "staticGraph", "collapsible", "directed"]; // actions this.fullScreenMode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(1)"); this.playGraph = () => cy.get(".container__graph > :nth-child(1) > :nth-child(2)").click(); this.pauseGraph = () => cy.get(".container__graph > :nth-child(1) > :nth-child(3)").click(); this.addNode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(5)").click(); this.removeNode = () => cy.get(".container__graph > :nth-child(1) > :nth-child(6)").click(); this.clickJsonTreeNodes = () => { cy.get(".container__graph-data") .contains("root") .scrollIntoView(); cy.get(".container__graph-data") .contains("nodes") .click(); }; // must be collapsed this.clickJsonTreeFirstNode = () => cy .get( ":nth-child(2) > .rejt-not-collapsed > .rejt-not-collapsed-list > :nth-child(1) > .rejt-collapsed > .rejt-collapsed-text" ) .click(); this.addJsonTreeFirstNodeProp = () => cy.get(":nth-child(2) > :nth-child(1) > .rejt-not-collapsed > :nth-child(4) > .rejt-plus-menu").click(); this.deleteJsonTreeFirstNodeProp = () => cy.get(".rejt-not-collapsed-list > :nth-child(2) > .rejt-minus-menu").click(); // element getters this.getFieldInput = field => this.checkboxes.includes(field) ? cy.contains(field).children("input") : cy.contains(field).siblings(".form-control"); this.getGraphNumbers = () => cy.get(".container__graph-info"); }
javascript
{ "resource": "" }
q23114
LinkPO
train
function LinkPO(index) { this.index = index; this.getLine = () => cy.get('path[class="link"]').then(lines => lines[this.index]); this.getStyle = () => this.getLine().invoke("attr", "style"); this.shouldHaveColor = color => this.getStyle().should("contain", `stroke: ${color};`); this.shouldHaveOpacity = opacity => this.getStyle().should("contain", `opacity: ${opacity};`); this.hasMarker = () => this.getLine() .invoke("attr", "marker-end") .should("contain", "url(#marker-"); this.getLabel = () => this.getLine().siblings(); }
javascript
{ "resource": "" }
q23115
_isPropertyNestedObject
train
function _isPropertyNestedObject(o, k) { return !!o && o.hasOwnProperty(k) && typeof o[k] === "object" && o[k] !== null && !isEmptyObject(o[k]); }
javascript
{ "resource": "" }
q23116
isDeepEqual
train
function isDeepEqual(o1, o2, _depth = 0) { let diffs = []; if (_depth === 0 && o1 === o2) { return true; } if ((isEmptyObject(o1) && !isEmptyObject(o2)) || (!isEmptyObject(o1) && isEmptyObject(o2))) { return false; } const o1Keys = Object.keys(o1); const o2Keys = Object.keys(o2); if (o1Keys.length !== o2Keys.length) { return false; } for (let k of o1Keys) { const nestedO = _isPropertyNestedObject(o1, k) && _isPropertyNestedObject(o2, k); if (nestedO && _depth < MAX_DEPTH) { diffs.push(isDeepEqual(o1[k], o2[k], _depth + 1)); } else { const r = (isEmptyObject(o1[k]) && isEmptyObject(o2[k])) || (o2.hasOwnProperty(k) && o2[k] === o1[k]); diffs.push(r); if (!r) { break; } } } return diffs.indexOf(false) === -1; }
javascript
{ "resource": "" }
q23117
deepClone
train
function deepClone(o, _clone = {}, _depth = 0) { // TODO: Handle invalid input o is null, undefined, empty object const oKeys = Object.keys(o); // TODO: handle arrays for (let k of oKeys) { const nested = _isPropertyNestedObject(o, k); _clone[k] = nested && _depth < MAX_DEPTH ? deepClone(o[k], {}, _depth + 1) : o[k]; } return _clone; }
javascript
{ "resource": "" }
q23118
merge
train
function merge(o1 = {}, o2 = {}, _depth = 0) { let o = {}; if (Object.keys(o1 || {}).length === 0) { return o2 && !isEmptyObject(o2) ? o2 : {}; } for (let k of Object.keys(o1)) { const nestedO = !!(o2[k] && typeof o2[k] === "object" && typeof o1[k] === "object" && _depth < MAX_DEPTH); if (nestedO) { const r = merge(o1[k], o2[k], _depth + 1); o[k] = o1[k].hasOwnProperty("length") && o2[k].hasOwnProperty("length") ? Object.keys(r).map(rk => r[rk]) : r; } else { o[k] = o2.hasOwnProperty(k) ? o2[k] : o1[k]; } } return o; }
javascript
{ "resource": "" }
q23119
pick
train
function pick(o, props = []) { return props.reduce((acc, k) => { if (o.hasOwnProperty(k)) { acc[k] = o[k]; } return acc; }, {}); }
javascript
{ "resource": "" }
q23120
antiPick
train
function antiPick(o, props = []) { const wanted = Object.keys(o).filter(k => !props.includes(k)); return pick(o, wanted); }
javascript
{ "resource": "" }
q23121
_initializeNodes
train
function _initializeNodes(graphNodes) { let nodes = {}; const n = graphNodes.length; for (let i = 0; i < n; i++) { const node = graphNodes[i]; node.highlighted = false; if (!node.hasOwnProperty("x")) { node.x = 0; } if (!node.hasOwnProperty("y")) { node.y = 0; } nodes[node.id.toString()] = node; } return nodes; }
javascript
{ "resource": "" }
q23122
_tagOrphanNodes
train
function _tagOrphanNodes(nodes, linksMatrix) { return Object.keys(nodes).reduce((acc, nodeId) => { const { inDegree, outDegree } = computeNodeDegree(nodeId, linksMatrix); const node = nodes[nodeId]; const taggedNode = inDegree === 0 && outDegree === 0 ? { ...node, _orphan: true } : node; acc[nodeId] = taggedNode; return acc; }, {}); }
javascript
{ "resource": "" }
q23123
_validateGraphData
train
function _validateGraphData(data) { if (!data.nodes || !data.nodes.length) { utils.throwErr("Graph", ERRORS.INSUFFICIENT_DATA); } const n = data.links.length; for (let i = 0; i < n; i++) { const l = data.links[i]; if (!data.nodes.find(n => n.id === l.source)) { utils.throwErr("Graph", `${ERRORS.INVALID_LINKS} - "${l.source}" is not a valid source node id`); } if (!data.nodes.find(n => n.id === l.target)) { utils.throwErr("Graph", `${ERRORS.INVALID_LINKS} - "${l.target}" is not a valid target node id`); } if (l && l.value !== undefined && typeof l.value !== "number") { utils.throwErr( "Graph", `${ERRORS.INVALID_LINK_VALUE} - found in link with source "${l.source}" and target "${l.target}"` ); } } }
javascript
{ "resource": "" }
q23124
checkForGraphConfigChanges
train
function checkForGraphConfigChanges(nextProps, currentState) { const newConfig = nextProps.config || {}; const configUpdated = newConfig && !utils.isEmptyObject(newConfig) && !utils.isDeepEqual(newConfig, currentState.config); const d3ConfigUpdated = newConfig && newConfig.d3 && !utils.isDeepEqual(newConfig.d3, currentState.config.d3); return { configUpdated, d3ConfigUpdated }; }
javascript
{ "resource": "" }
q23125
getCenterAndZoomTransformation
train
function getCenterAndZoomTransformation(d3Node, config) { if (!d3Node) { return; } const { width, height, focusZoom } = config; return ` translate(${width / 2}, ${height / 2}) scale(${focusZoom}) translate(${-d3Node.x}, ${-d3Node.y}) `; }
javascript
{ "resource": "" }
q23126
initializeGraphState
train
function initializeGraphState({ data, id, config }, state) { _validateGraphData(data); let graph; if (state && state.nodes) { graph = { nodes: data.nodes.map(n => state.nodes[n.id] ? Object.assign({}, n, utils.pick(state.nodes[n.id], NODE_PROPS_WHITELIST)) : Object.assign({}, n) ), links: data.links.map((l, index) => _mapDataLinkToD3Link(l, index, state && state.d3Links, config, state)), }; } else { graph = { nodes: data.nodes.map(n => Object.assign({}, n)), links: data.links.map(l => Object.assign({}, l)), }; } let newConfig = Object.assign({}, utils.merge(DEFAULT_CONFIG, config || {})); let links = _initializeLinks(graph.links, newConfig); // matrix of graph connections let nodes = _tagOrphanNodes(_initializeNodes(graph.nodes), links); const { nodes: d3Nodes, links: d3Links } = graph; const formatedId = id.replace(/ /g, "_"); const simulation = _createForceSimulation(newConfig.width, newConfig.height, newConfig.d3 && newConfig.d3.gravity); const { minZoom, maxZoom, focusZoom } = newConfig; if (focusZoom > maxZoom) { newConfig.focusZoom = maxZoom; } else if (focusZoom < minZoom) { newConfig.focusZoom = minZoom; } return { id: formatedId, config: newConfig, links, d3Links, nodes, d3Nodes, highlightedNode: "", simulation, newGraphElements: false, configUpdated: false, transform: 1, }; }
javascript
{ "resource": "" }
q23127
updateNodeHighlightedValue
train
function updateNodeHighlightedValue(nodes, links, config, id, value = false) { const highlightedNode = value ? id : ""; const node = Object.assign({}, nodes[id], { highlighted: value }); let updatedNodes = Object.assign({}, nodes, { [id]: node }); // when highlightDegree is 0 we want only to highlight selected node if (links[id] && config.highlightDegree !== 0) { updatedNodes = Object.keys(links[id]).reduce((acc, linkId) => { const updatedNode = Object.assign({}, updatedNodes[linkId], { highlighted: value }); return Object.assign(acc, { [linkId]: updatedNode }); }, updatedNodes); } return { nodes: updatedNodes, highlightedNode, }; }
javascript
{ "resource": "" }
q23128
train
function (uuids) { var guid = uuids[0] var sharedKey = uuids[1] if (!guid || !sharedKey || guid.length !== 36 || sharedKey.length !== 36) { throw 'Error generating wallet identifier' } return { guid: guid, sharedKey: sharedKey } }
javascript
{ "resource": "" }
q23129
train
function (uuids) { var walletJSON = { guid: uuids.guid, sharedKey: uuids.sharedKey, double_encryption: false, options: { pbkdf2_iterations: 5000, html5_notifications: false, fee_per_kb: 10000, logout_time: 600000 } } var createHdWallet = function (label) { label = label == null ? 'My Bitcoin Wallet' : label var mnemonic = BIP39.generateMnemonic(undefined, Blockchain.RNG.run.bind(Blockchain.RNG)) var hd = HDWallet.new(mnemonic) hd.newAccount(label) return hd } var createLegacyAddress = function (priv, label) { return priv ? Address.import(priv, label) : Address.new(label) } if (isHdWallet) { var hdJSON = createHdWallet(firstLabel).toJSON() hdJSON.accounts = hdJSON.accounts.map(function (a) { return a.toJSON() }) walletJSON.hd_wallets = [hdJSON] } else { winston.warn(warnings.CREATED_NON_HD) var firstAddress = createLegacyAddress(privateKey, firstLabel) walletJSON.keys = [firstAddress.toJSON()] } if (typeof secPass === 'string' && secPass.length) { walletJSON = JSON.parse(JSON.stringify(new Wallet(walletJSON).encrypt(secPass))) } return walletJSON }
javascript
{ "resource": "" }
q23130
train
function (wallet) { var data = JSON.stringify(wallet, null, 2) var enc = Blockchain.WalletCrypto.encryptWallet(data, password, wallet.options.pbkdf2_iterations, 2.0) var check = sha256(enc).toString('hex') // Throws if there is an encryption error Blockchain.WalletCrypto.decryptWallet(enc, password, function () {}, function () { throw 'Failed to confirm successful encryption when generating new wallet' }) var postData = { guid: wallet.guid, sharedKey: wallet.sharedKey, length: enc.length, payload: enc, checksum: check, method: 'insert', format: 'plain' } if (email) postData.email = email return Blockchain.API.securePost('wallet', postData).then(function () { if (isHdWallet) { var account = wallet.hd_wallets[0].accounts[0] return { guid: wallet.guid, address: account.xpub, label: account.label } } else { var firstKey = wallet.keys[0] return { guid: wallet.guid, address: firstKey.addr, label: firstKey.label, warning: warnings.CREATED_NON_HD } } }) }
javascript
{ "resource": "" }
q23131
fib
train
function fib(max) { var a = 0, b = 1; var results = []; while (b < max) { results.push(b); [a, b] = [b, a + b]; } return results; }
javascript
{ "resource": "" }
q23132
tree
train
function tree(list) { var n = list.length; if (n == 0) { return null; } var i = Math.floor(n / 2); return new Tree(list[i], tree(list.slice(0, i)), tree(list.slice(i + 1))); }
javascript
{ "resource": "" }
q23133
createArrayIterator
train
function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; }
javascript
{ "resource": "" }
q23134
traverse
train
function traverse(object, iterator, parent, parentProperty) { var key, child; if (iterator(object, parent, parentProperty) === false) return; for (key in object) { if (!object.hasOwnProperty(key)) continue; if (key == 'location' || key == 'type') continue; child = object[key]; if (typeof child == 'object' && child !== null) traverse(child, iterator, object, key); } }
javascript
{ "resource": "" }
q23135
__eval
train
function __eval(__source, __global, load) { // Hijack System.register to set declare function System.__curRegister = System.register; System.register = function(name, deps, declare) { // store the registered declaration as load.declare load.declare = typeof name == 'string' ? declare : deps; } eval('var __moduleName = "' + (load.name || '').replace('"', '\"') + '"; (function() { ' + __source + ' \n }).call(__global);'); System.register = System.__curRegister; delete System.__curRegister; }
javascript
{ "resource": "" }
q23136
wrapModule
train
function wrapModule(module, functions) { if (typeof module === 'string') module = require(module); if (!functions) { for (var k in module) { // HACK: wrap all functions with a fnSync variant. if (typeof module[k] === 'function' && typeof module[k + 'Sync'] === 'function') module[k] = wrapFunction(module[k]); } } else { for (var i = 0, k; i < functions.length; i++) { var k = functions[i]; module[k] = wrapFunction(module[k]); } } return module; }
javascript
{ "resource": "" }
q23137
printCompilerMsg
train
function printCompilerMsg(msg, file) { console.error('%s:%d:%d %s - %s', file || msg.file, msg.lineno + 1, msg.charno + 1, msg.type, msg.error); console.error('%s\n%s^', msg.line, Array(msg.charno + 1).join(' ')); }
javascript
{ "resource": "" }
q23138
mergedCompilerMsgLists
train
function mergedCompilerMsgLists(list1, list2) { var list = []; list1 = list1 || []; list2 = list2 || []; function lessThan(e1, e2) { if (e1.lineno < e2.lineno) return true; return e1.lineno === e2.lineno && e1.charno < e2.charno; } var i1 = 0, i2 = 0; while (true) { if (i1 >= list1.length) return list.concat(list2.slice(i2)); if (i2 >= list2.length) return list.concat(list1.slice(i1)); if (lessThan(list1[i1], list2[i2])) list.push(list1[i1++]); else list.push(list2[i2++]); } }
javascript
{ "resource": "" }
q23139
mkdirRecursive
train
function mkdirRecursive(dir) { var parts = path.normalize(dir).split(path.sep); dir = ''; for (var i = 0; i < parts.length; i++) { dir += parts[i] + path.sep; if (!existsSync(dir)) { fs.mkdirSync(dir, 0x1FD); // 0775 permissions } } }
javascript
{ "resource": "" }
q23140
removeCommonPrefix
train
function removeCommonPrefix(basedir, filedir) { var baseparts = basedir.split(path.sep); var fileparts = filedir.split(path.sep); var i = 0; while (i < fileparts.length && fileparts[i] === baseparts[i]) { i++; } return fileparts.slice(i).join(path.sep); }
javascript
{ "resource": "" }
q23141
scanTemplateStart
train
function scanTemplateStart(beginIndex) { if (isAtEnd()) { reportError('Unterminated template literal', beginIndex, index); return lastToken = createToken(END_OF_FILE, beginIndex); } return nextTemplateLiteralTokenShared(NO_SUBSTITUTION_TEMPLATE, TEMPLATE_HEAD); }
javascript
{ "resource": "" }
q23142
scanJsxToken
train
function scanJsxToken() { skipComments(); let beginIndex = index; switch (currentCharCode) { case 34: // " case 39: // ' return scanJsxStringLiteral(beginIndex, currentCharCode); case 62: // > next(); return createToken(CLOSE_ANGLE, beginIndex); // case 123: // { // case 125: // } } if (!isIdentifierStart(currentCharCode)) { return scanToken(); } next(); while (isIdentifierPart(currentCharCode) || currentCharCode === 45) { // '-' next(); } let value = input.slice(beginIndex, index); return new JsxIdentifierToken(getTokenRange(beginIndex), value); }
javascript
{ "resource": "" }
q23143
varNeedsInitializer
train
function varNeedsInitializer(tree, loopTree) { if (loopTree === null) return false; // Loop initializers for for-in/for-of must not have an initializer RHS. let type = loopTree.type; if (type !== FOR_IN_STATEMENT && type !== FOR_OF_STATEMENT) return true; return loopTree.initializer.declarations[0] !== tree; }
javascript
{ "resource": "" }
q23144
recursiveModuleCompile
train
function recursiveModuleCompile(fileNamesAndTypes, options) { var referrerName = options && options.referrer; var basePath = path.resolve('./') + '/'; basePath = basePath.replace(/\\/g, '/'); var elements = []; var loaderCompiler = new InlineLoaderCompiler(elements); var loader = new TraceurLoader(nodeLoader, basePath, loaderCompiler); function appendEvaluateModule(name) { var normalizedName = $traceurRuntime.ModuleStore.normalize(name, referrerName); // Create tree for $traceurRuntime.getModule('normalizedName'); var moduleModule = traceur.codegeneration.module; var tree = moduleModule.createModuleEvaluationStatement(normalizedName); elements.push(tree); } function loadInput(input) { var doEvaluateModule = false; var loadFunction = loader.import; var name = input.name; var optionsCopy = new Options(options); // Give each load a copy of options. if (input.type === 'script') { loadFunction = loader.loadAsScript; } else if (optionsCopy.modules === 'bootstrap') { doEvaluateModule = true; } var loadOptions = { referrerName: referrerName, metadata: { traceurOptions: optionsCopy, rootModule: input.rootModule && input.name } }; return loadFunction.call(loader, name, loadOptions).then(function() { if (doEvaluateModule) { appendEvaluateModule(name); } }); } return sequencePromises(fileNamesAndTypes, loadInput).then(function() { return loaderCompiler.toTree(); }); }
javascript
{ "resource": "" }
q23145
proceedToLocate
train
function proceedToLocate(loader, load) { proceedToFetch(loader, load, Promise.resolve() // 15.2.4.3.1 CallLocate .then(function() { return loader.loaderObj.locate({ name: load.name, metadata: load.metadata }); }) ); }
javascript
{ "resource": "" }
q23146
proceedToFetch
train
function proceedToFetch(loader, load, p) { proceedToTranslate(loader, load, p // 15.2.4.4.1 CallFetch .then(function(address) { // adjusted, see https://bugs.ecmascript.org/show_bug.cgi?id=2602 if (load.status != 'loading') return; load.address = address; return loader.loaderObj.fetch({ name: load.name, metadata: load.metadata, address: address }); }) ); }
javascript
{ "resource": "" }
q23147
addLoadToLinkSet
train
function addLoadToLinkSet(linkSet, load) { console.assert(load.status == 'loading' || load.status == 'loaded', 'loading or loaded on link set'); for (var i = 0, l = linkSet.loads.length; i < l; i++) if (linkSet.loads[i] == load) return; linkSet.loads.push(load); load.linkSets.push(linkSet); // adjustment, see https://bugs.ecmascript.org/show_bug.cgi?id=2603 if (load.status != 'loaded') { linkSet.loadingCount++; } var loader = linkSet.loader; for (var i = 0, l = load.dependencies.length; i < l; i++) { var name = load.dependencies[i].value; if (loader.modules[name]) continue; for (var j = 0, d = loader.loads.length; j < d; j++) { if (loader.loads[j].name != name) continue; addLoadToLinkSet(linkSet, loader.loads[j]); break; } } // console.log('add to linkset ' + load.name); // snapshot(linkSet.loader); }
javascript
{ "resource": "" }
q23148
updateLinkSetOnLoad
train
function updateLinkSetOnLoad(linkSet, load) { // console.log('update linkset on load ' + load.name); // snapshot(linkSet.loader); console.assert(load.status == 'loaded' || load.status == 'linked', 'loaded or linked'); linkSet.loadingCount--; if (linkSet.loadingCount > 0) return; // adjusted for spec bug https://bugs.ecmascript.org/show_bug.cgi?id=2995 var startingLoad = linkSet.startingLoad; // non-executing link variation for loader tracing // on the server. Not in spec. /***/ if (linkSet.loader.loaderObj.execute === false) { var loads = [].concat(linkSet.loads); for (var i = 0, l = loads.length; i < l; i++) { var load = loads[i]; load.module = load.kind == 'dynamic' ? { module: _newModule({}) } : { name: load.name, module: _newModule({}), evaluated: true }; load.status = 'linked'; finishLoad(linkSet.loader, load); } return linkSet.resolve(startingLoad); } /***/ var abrupt = doLink(linkSet); if (abrupt) return; console.assert(linkSet.loads.length == 0, 'loads cleared'); linkSet.resolve(startingLoad); }
javascript
{ "resource": "" }
q23149
finishLoad
train
function finishLoad(loader, load) { // add to global trace if tracing if (loader.loaderObj.trace) { if (!loader.loaderObj.loads) loader.loaderObj.loads = {}; var depMap = {}; load.dependencies.forEach(function(dep) { depMap[dep.key] = dep.value; }); loader.loaderObj.loads[load.name] = { name: load.name, deps: load.dependencies.map(function(dep){ return dep.key }), depMap: depMap, address: load.address, metadata: load.metadata, source: load.source, kind: load.kind }; } // if not anonymous, add to the module table if (load.name) { console.assert(!loader.modules[load.name], 'load not in module table'); loader.modules[load.name] = load.module; } var loadIndex = indexOf.call(loader.loads, load); if (loadIndex != -1) loader.loads.splice(loadIndex, 1); for (var i = 0, l = load.linkSets.length; i < l; i++) { loadIndex = indexOf.call(load.linkSets[i].loads, load); if (loadIndex != -1) load.linkSets[i].loads.splice(loadIndex, 1); } load.linkSets.splice(0, load.linkSets.length); }
javascript
{ "resource": "" }
q23150
linkDeclarativeModule
train
function linkDeclarativeModule(load, loads, loader) { if (load.module) return; var module = load.module = getOrCreateModuleRecord(load.name); var moduleObj = load.module.module; var registryEntry = load.declare.call(__global, function(name, value) { // NB This should be an Object.defineProperty, but that is very slow. // By disaling this module write-protection we gain performance. // It could be useful to allow an option to enable or disable this. // bulk export object if (typeof name == 'object') { for (var p in name) moduleObj[p] = name[p]; } // single export name / value pair else { moduleObj[name] = value; } for (var i = 0, l = module.importers.length; i < l; i++) { var importerModule = module.importers[i]; if (importerModule.setters) { var importerIndex = importerModule.dependencies.indexOf(module); if (importerIndex != -1) { var setter = importerModule.setters[importerIndex]; setter(moduleObj); } } } return value; }, {id: load.name}); // setup our setters and execution function load.module.setters = registryEntry.setters; load.module.execute = registryEntry.execute; // now link all the module dependencies // amending the depMap as we go for (var i = 0, l = load.dependencies.length; i < l; i++) { var depName = load.dependencies[i].value; var depModule = getOrCreateModuleRecord(depName); depModule.importers.push(module); // if not already a module in the registry, try and link it now if (!loader.modules[depName]) { // get the dependency load record for (var j = 0; j < loads.length; j++) { if (loads[j].name != depName) continue; // only link if already not already started linking (stops at circular / dynamic) if (!loads[j].module) linkDeclarativeModule(loads[j], loads, loader); } } console.assert(depModule, 'Dependency module not found!'); module.dependencies.push(depModule); // run the setter for this dependency if (module.setters[i]) module.setters[i](depModule.module); } load.status = 'linked'; }
javascript
{ "resource": "" }
q23151
evaluateLoadedModule
train
function evaluateLoadedModule(loader, load) { console.assert(load.status == 'linked', 'is linked ' + load.name); doEnsureEvaluated(load.module, [], loader); return load.module.module; }
javascript
{ "resource": "" }
q23152
ensureEvaluated
train
function ensureEvaluated(module, seen, loader) { if (module.evaluated || !module.dependencies) return; seen.push(module); var deps = module.dependencies; var err; for (var i = 0, l = deps.length; i < l; i++) { var dep = deps[i]; if (indexOf.call(seen, dep) == -1) { err = ensureEvaluated(dep, seen, loader); // stop on error, see https://bugs.ecmascript.org/show_bug.cgi?id=2996 if (err) return err + '\n in module ' + dep.name; } } if (module.failed) return new Error('Module failed execution.'); if (module.evaluated) return; module.evaluated = true; err = doExecute(module); if (err) module.failed = true; // spec variation // we don't create a new module here because it was created and ammended // we just disable further extensions instead if (Object.preventExtensions) Object.preventExtensions(module.module); module.execute = undefined; return err; }
javascript
{ "resource": "" }
q23153
train
function(key) { if (!this._loader.modules[key]) return; doEnsureEvaluated(this._loader.modules[key], [], this); return this._loader.modules[key].module; }
javascript
{ "resource": "" }
q23154
train
function(name, module) { if (!(module instanceof Module)) throw new TypeError('Set must be a module'); this._loader.modules[name] = { module: module }; }
javascript
{ "resource": "" }
q23155
createGetTemplateObject
train
function createGetTemplateObject(elements, getTemplateObject) { let cooked = []; let raw = []; let same = true; for (let i = 0; i < elements.length; i += 2) { let loc = elements[i].location; let str = elements[i].value.value; let cookedStr = toCookedString(str); let rawStr = toRawString(str); let cookedLiteral = createStringLiteralExpression(loc, cookedStr); cooked.push(cookedLiteral); if (cookedStr !== rawStr) { same = false; let rawLiteral = createStringLiteralExpression(loc, rawStr); raw.push(rawLiteral); } else { raw.push(cookedLiteral); } } maybeAddEmptyStringAtEnd(elements, cooked); let cookedLiteral = createArrayLiteral(cooked); let args = [cookedLiteral]; if (!same) { maybeAddEmptyStringAtEnd(elements, raw); let rawLiteral = createArrayLiteral(raw); args.unshift(rawLiteral); } return createCallExpression( getTemplateObject, createArgumentList(args)); }
javascript
{ "resource": "" }
q23156
maybeAddEmptyStringAtEnd
train
function maybeAddEmptyStringAtEnd(elements, items) { let length = elements.length; if (!length || elements[length - 1].type !== TEMPLATE_LITERAL_PORTION) { items.push(createStringLiteralExpression(null, '""')); } }
javascript
{ "resource": "" }
q23157
toCookedString
train
function toCookedString(s) { let sb = ['"']; let i = 0, k = 1, c, c2; while (i < s.length) { c = s[i++]; switch (c) { case '\\': c2 = s[i++]; switch (c2) { // Strip line continuation. case '\n': case '\u2028': case '\u2029': break; case '\r': // \ \r \n should be stripped as one if (s[i + 1] === '\n') { i++; } break; default: sb[k++] = c; sb[k++] = c2; } break; // Since we wrap the string in " we need to escape those. case '"': sb[k++] = '\\"'; break; // Whitespace case '\n': sb[k++] = '\\n'; break; // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> // for both TV and TRV. case '\r': if (s[i] === '\n') i++; sb[k++] = '\\n'; break; case '\t': sb[k++] = '\\t'; break; case '\f': sb[k++] = '\\f'; break; case '\b': sb[k++] = '\\b'; break; case '\u2028': sb[k++] = '\\u2028'; break; case '\u2029': sb[k++] = '\\u2029'; break; default: sb[k++] = c; } } sb[k++] = '"'; return sb.join(''); }
javascript
{ "resource": "" }
q23158
setDebugLevel
train
function setDebugLevel(level, printf) { var outLevel = 0; debug = debug2 = debug3 = debugTree = function() {}; switch (String(level)) { case '3': debug3 = printf; outLevel++; // fall through case '2': debugTree = function (fmt, tree) { printf(fmt, util.inspect(tree.toJSON(), false, 64)); }; debug2 = printf; outLevel++; // fall through case '1': debug = printf; outLevel++; // fall through default: return outLevel; } }
javascript
{ "resource": "" }
q23159
usePlugins
train
function usePlugins(core) { var installedPlugins = []; /** * @desc Register iro.js plugin * @param {Function} plugin = plugin constructor * @param {Object} pluginOptions = plugin options passed to constructor */ core.use = function(plugin, pluginOptions) { if ( pluginOptions === void 0 ) pluginOptions = {}; // Check that the plugin hasn't already been registered if (!(installedPlugins.indexOf(plugin) > -1)) { // Init plugin // TODO: consider collection of plugin utils, which are passed as a thrid param plugin(core, pluginOptions); // Register plugin installedPlugins.push(plugin); } }; core.installedPlugins = installedPlugins; return core; }
javascript
{ "resource": "" }
q23160
createClient
train
function createClient(wsdlUrl, options, cb) { if (!cb) { cb = options; options = {}; } if (this.errOnCreateClient) { return setTimeout(cb.bind(null, new Error('forced error on createClient'))); } var client = getStub(wsdlUrl); if (client) { resetStubbedMethods(client); setTimeout(cb.bind(null, null, client)); } else { setTimeout(cb.bind(null, new Error('no client stubbed for ' + wsdlUrl))); } }
javascript
{ "resource": "" }
q23161
createErroringStub
train
function createErroringStub(err) { return function() { this.args.forEach(function(argSet) { setTimeout(argSet[1].bind(null, err)); }); this.yields(err); }; }
javascript
{ "resource": "" }
q23162
createRespondingStub
train
function createRespondingStub(object, body) { return function() { this.args.forEach(function(argSet) { setTimeout(argSet[1].bind(null, null, object)); }); this.yields(null, object, body); }; }
javascript
{ "resource": "" }
q23163
registerClient
train
function registerClient(alias, urlToWsdl, clientStub) { aliasedClientStubs[alias] = clientStub; clientStubs[urlToWsdl] = clientStub; }
javascript
{ "resource": "" }
q23164
loadMode
train
function loadMode(cm) { cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); cm.doc.iter(function(line) { if (line.stateAfter) line.stateAfter = null; if (line.styles) line.styles = null; }); cm.doc.frontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) regChange(cm); }
javascript
{ "resource": "" }
q23165
setGuttersForLineNumbers
train
function setGuttersForLineNumbers(options) { var found = false; for (var i = 0; i < options.gutters.length; ++i) { if (options.gutters[i] == "CodeMirror-linenumbers") { if (options.lineNumbers) found = true; else options.gutters.splice(i--, 1); } } if (!found && options.lineNumbers) options.gutters.push("CodeMirror-linenumbers"); }
javascript
{ "resource": "" }
q23166
updateScrollbars
train
function updateScrollbars(cm) { var d = cm.display, docHeight = cm.doc.height; var totalHeight = docHeight + paddingVert(d); d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); var needsV = scrollHeight > (d.scroller.clientHeight + 1); if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; } else d.scrollbarV.style.display = ""; if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else d.scrollbarH.style.display = ""; if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; } else d.gutterFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; }
javascript
{ "resource": "" }
q23167
updateSelectionCursor
train
function updateSelectionCursor(cm) { var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); display.cursor.style.left = pos.left + "px"; display.cursor.style.top = pos.top + "px"; display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; display.cursor.style.display = ""; if (pos.other) { display.otherCursor.style.display = ""; display.otherCursor.style.left = pos.other.left + "px"; display.otherCursor.style.top = pos.other.top + "px"; display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } else { display.otherCursor.style.display = "none"; } }
javascript
{ "resource": "" }
q23168
operation
train
function operation(cm1, f) { return function() { var cm = cm1 || this, withOp = !cm.curOp; if (withOp) startOperation(cm); try { var result = f.apply(cm, arguments); } finally { if (withOp) endOperation(cm); } return result; }; }
javascript
{ "resource": "" }
q23169
unregister
train
function unregister() { for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} if (p) setTimeout(unregister, 5000); else off(window, "resize", onResize); }
javascript
{ "resource": "" }
q23170
clipPostChange
train
function clipPostChange(doc, change, pos) { if (!posLess(change.from, pos)) return clipPos(doc, pos); var diff = (change.text.length - 1) - (change.to.line - change.from.line); if (pos.line > change.to.line + diff) { var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); return clipToLen(pos, getLine(doc, preLine).text.length); } if (pos.line == change.to.line + diff) return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + getLine(doc, change.to.line).text.length - change.to.ch); var inside = pos.line - change.from.line; return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); }
javascript
{ "resource": "" }
q23171
train
function(pos) { if (posLess(pos, change.from)) return pos; if (!posLess(change.to, pos)) return end; var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) ch += end.ch - change.to.ch; return Pos(line, ch); }
javascript
{ "resource": "" }
q23172
extendSelection
train
function extendSelection(doc, pos, other, bias) { if (doc.sel.shift || doc.sel.extend) { var anchor = doc.sel.anchor; if (other) { var posBefore = posLess(pos, anchor); if (posBefore != posLess(other, anchor)) { anchor = pos; pos = other; } else if (posBefore != posLess(pos, other)) { pos = other; } } setSelection(doc, anchor, pos, bias); } else { setSelection(doc, pos, other || pos, bias); } if (doc.cm) doc.cm.curOp.userSelChange = true; }
javascript
{ "resource": "" }
q23173
setSelection
train
function setSelection(doc, anchor, head, bias, checkAtomic) { if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { var filtered = filterSelectionChange(doc, anchor, head); head = filtered.head; anchor = filtered.anchor; } var sel = doc.sel; sel.goalColumn = null; // Skip over atomic spans. if (checkAtomic || !posEq(anchor, sel.anchor)) anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); if (checkAtomic || !posEq(head, sel.head)) head = skipAtomic(doc, head, bias, checkAtomic != "push"); if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; sel.anchor = anchor; sel.head = head; var inv = posLess(head, anchor); sel.from = inv ? head : anchor; sel.to = inv ? anchor : head; if (doc.cm) doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = doc.cm.curOp.cursorActivity = true; signalLater(doc, "cursorActivity", doc); }
javascript
{ "resource": "" }
q23174
StringStream
train
function StringStream(string, tabSize) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; }
javascript
{ "resource": "" }
q23175
copyHistoryArray
train
function copyHistoryArray(events, newGroup) { for (var i = 0, copy = []; i < events.length; ++i) { var event = events[i], changes = event.changes, newChanges = []; copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, anchorAfter: event.anchorAfter, headAfter: event.headAfter}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m; newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } return copy; }
javascript
{ "resource": "" }
q23176
countColumn
train
function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) end = string.length; } for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); else ++n; } return n; }
javascript
{ "resource": "" }
q23177
updateWordCount
train
function updateWordCount() { var wordCount = document.getElementsByClassName('entry-word-count')[0], editorValue = editor.getValue(); if (editorValue.length) { wordCount.innerHTML = editorValue.match(/\S+/g).length + ' words'; } }
javascript
{ "resource": "" }
q23178
train
function (req, res, next) { if (req.query.return) { req.session.oauth2return = req.query.return; } next(); }
javascript
{ "resource": "" }
q23179
train
function (req, res) { req.session.loggedIn = true; if (config.oauth2.validateHostedDomain) { req.session.allowedDomain = config.oauth2.hostedDomain; } var redirect = req.session.oauth2return || '/'; delete req.session.oauth2return; res.redirect(redirect); }
javascript
{ "resource": "" }
q23180
cleanObjectStrings
train
function cleanObjectStrings (obj) { let cleanObj = {}; for (let field in obj) { if (obj.hasOwnProperty(field)) { cleanObj[cleanString(field, true)] = ('' + obj[field]).trim(); } } return cleanObj; }
javascript
{ "resource": "" }
q23181
slugToTitle
train
function slugToTitle (slug) { slug = slug.replace('.md', '').trim(); return _s.titleize(_s.humanize(path.basename(slug))); }
javascript
{ "resource": "" }
q23182
stripMeta
train
function stripMeta (markdownContent) { switch (true) { case _metaRegex.test(markdownContent): return markdownContent.replace(_metaRegex, '').trim(); case _metaRegexYaml.test(markdownContent): return markdownContent.replace(_metaRegexYaml, '').trim(); default: return markdownContent.trim(); } }
javascript
{ "resource": "" }
q23183
processMeta
train
function processMeta (markdownContent) { let meta = {}; let metaArr; let metaString; let metas; let yamlObject; switch (true) { case _metaRegex.test(markdownContent): metaArr = markdownContent.match(_metaRegex); metaString = metaArr ? metaArr[1].trim() : ''; if (metaString) { metas = metaString.match(/(.*): (.*)/ig); metas.forEach(item => { const parts = item.split(': '); if (parts[0] && parts[1]) { meta[cleanString(parts[0], true)] = parts[1].trim(); } }); } break; case _metaRegexYaml.test(markdownContent): metaArr = markdownContent.match(_metaRegexYaml); metaString = metaArr ? metaArr[1].trim() : ''; yamlObject = yaml.safeLoad(metaString); meta = cleanObjectStrings(yamlObject); break; default: // No meta information } return meta; }
javascript
{ "resource": "" }
q23184
processVars
train
function processVars (markdownContent, config) { if (config.variables && Array.isArray(config.variables)) { config.variables.forEach((v) => { markdownContent = markdownContent.replace(new RegExp('%' + v.name + '%', 'g'), v.content); }); } if (config.base_url) { markdownContent = markdownContent.replace(/%base_url%/g, config.base_url); } if (config.image_url) { markdownContent = markdownContent.replace(/%image_url%/g, config.image_url); } return markdownContent; }
javascript
{ "resource": "" }
q23185
create_meta_info
train
function create_meta_info (meta_title, meta_description, meta_sort) { var yamlDocument = {}; var meta_info_is_present = meta_title || meta_description || meta_sort; if (meta_info_is_present) { if (meta_title) { yamlDocument.Title = meta_title; } if (meta_description) { yamlDocument.Description = meta_description; } if (meta_sort) { yamlDocument.Sort = parseInt(meta_sort, 10); } return '---\n' + yaml.safeDump(yamlDocument) + '---\n'; } else { return '---\n---\n'; } }
javascript
{ "resource": "" }
q23186
cl_block
train
function cl_block(outs) { cl_hash(HSIZE); free_ent = ClearCode + 2; clear_flg = true; output(ClearCode, outs); }
javascript
{ "resource": "" }
q23187
flush_char
train
function flush_char(outs) { if (a_count > 0) { outs.writeByte(a_count); outs.writeBytes(accum, 0, a_count); a_count = 0; } }
javascript
{ "resource": "" }
q23188
isSimple
train
function isSimple(config) { return ( isObject(config) && !config.hasOwnProperty('linters') && intersection(Object.keys(defaultConfig), Object.keys(config)).length === 0 ) }
javascript
{ "resource": "" }
q23189
unknownValidationReporter
train
function unknownValidationReporter(config, option) { /** * If the unkonwn property is a glob this is probably * a typical mistake of mixing simple and advanced configs */ if (isGlob(option)) { // prettier-ignore const message = `You are probably trying to mix simple and advanced config formats. Adding ${chalk.bold(`"linters": { "${option}": ${JSON.stringify(config[option])} }`)} will fix it and remove this message.` return logUnknown(option, message, config[option]) } // If it is not glob pattern, simply notify of unknown value return logUnknown(option, '', config[option]) }
javascript
{ "resource": "" }
q23190
getConfig
train
function getConfig(sourceConfig, debugMode) { debug('Normalizing config') const config = defaultsDeep( {}, // Do not mutate sourceConfig!!! isSimple(sourceConfig) ? { linters: sourceConfig } : sourceConfig, defaultConfig ) // Check if renderer is set in sourceConfig and if not, set accordingly to verbose if (isObject(sourceConfig) && !sourceConfig.hasOwnProperty('renderer')) { config.renderer = debugMode ? 'verbose' : 'update' } return config }
javascript
{ "resource": "" }
q23191
validateConfig
train
function validateConfig(config) { debug('Validating config') const deprecatedConfig = { gitDir: "lint-staged now automatically resolves '.git' directory.", verbose: `Use the command line flag ${chalk.bold('--debug')} instead.` } const errors = [] try { schema.validateSync(config, { abortEarly: false, strict: true }) } catch (error) { error.errors.forEach(message => errors.push(formatError(message))) } if (isObject(config.linters)) { Object.keys(config.linters).forEach(key => { if ( (!isArray(config.linters[key]) || config.linters[key].some(item => !isString(item))) && !isString(config.linters[key]) ) { errors.push( createError(`linters[${key}]`, 'Should be a string or an array of strings', key) ) } }) } Object.keys(config) .filter(key => !defaultConfig.hasOwnProperty(key)) .forEach(option => { if (deprecatedConfig.hasOwnProperty(option)) { logDeprecation(option, deprecatedConfig[option]) return } unknownValidationReporter(config, option) }) if (errors.length) { throw new Error(errors.join('\n')) } return config }
javascript
{ "resource": "" }
q23192
execLinter
train
function execLinter(bin, args, execaOptions, pathsToLint) { const binArgs = args.concat(pathsToLint) debug('bin:', bin) debug('args: %O', binArgs) debug('opts: %o', execaOptions) return execa(bin, binArgs, { ...execaOptions }) }
javascript
{ "resource": "" }
q23193
makeErr
train
function makeErr(linter, result, context = {}) { // Indicate that some linter will fail so we don't update the index with formatting changes context.hasErrors = true // eslint-disable-line no-param-reassign const { stdout, stderr, killed, signal } = result if (killed || (signal && signal !== '')) { return throwError( `${symbols.warning} ${chalk.yellow(`${linter} was terminated with ${signal}`)}` ) } return throwError(dedent`${symbols.error} ${chalk.redBright( `${linter} found some errors. Please fix them and try committing again.` )} ${stdout} ${stderr} `) }
javascript
{ "resource": "" }
q23194
mod
train
function mod(n, m) { const q = n % m; return q < 0 ? q + m : q; }
javascript
{ "resource": "" }
q23195
applyRotationMatrix
train
function applyRotationMatrix(touch, axis) { const rotationMatrix = axisProperties.rotationMatrix[axis]; return { pageX: rotationMatrix.x[0] * touch.pageX + rotationMatrix.x[1] * touch.pageY, pageY: rotationMatrix.y[0] * touch.pageX + rotationMatrix.y[1] * touch.pageY, }; }
javascript
{ "resource": "" }
q23196
resolveFunc
train
function resolveFunc(value) { const name = value.split(',')[0].replace(/[\s\n\t]/g, ''); const fallback = (value.match(/(?:\s*,\s*){1}(.*)?/) || [])[1]; const match = settings.variables.hasOwnProperty(name) ? String(settings.variables[name]) : undefined; const replacement = match || (fallback ? String(fallback) : undefined); const unresolvedFallback = __recursiveFallback || value; if (!match) { settings.onWarning(`variable "${name}" is undefined`); } if (replacement && replacement !== 'undefined' && replacement.length > 0) { return resolveValue(replacement, settings, unresolvedFallback); } else { return `var(${unresolvedFallback})`; } }
javascript
{ "resource": "" }
q23197
getTimeStamp
train
function getTimeStamp() { return isBrowser && (window.performance || {}).now ? window.performance.now() : new Date().getTime(); }
javascript
{ "resource": "" }
q23198
shouldBailOut
train
function shouldBailOut(firstArg) { if ( firstArg === null || typeof firstArg !== 'object' || firstArg.behavior === undefined || firstArg.behavior === 'auto' || firstArg.behavior === 'instant' ) { // first argument is not an object/null // or behavior is auto, instant or undefined return true; } if (typeof firstArg === 'object' && firstArg.behavior === 'smooth') { // first argument is an object and behavior is smooth return false; } // throw error when behavior is not supported throw new TypeError( 'behavior member of ScrollOptions ' + firstArg.behavior + ' is not a valid value for enumeration ScrollBehavior.' ); }
javascript
{ "resource": "" }
q23199
hasScrollableSpace
train
function hasScrollableSpace(el, axis) { if (axis === 'Y') { return el.clientHeight + ROUNDING_TOLERANCE < el.scrollHeight; } if (axis === 'X') { return el.clientWidth + ROUNDING_TOLERANCE < el.scrollWidth; } }
javascript
{ "resource": "" }