_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q27000
addMiter
train
function addMiter (v, coordCurr, normPrev, normNext, miter_len_sq, isBeginning, context) { var miterVec = createMiterVec(normPrev, normNext); // Miter limit: if miter join is too sharp, convert to bevel instead if (Vector.lengthSq(miterVec) > miter_len_sq) { addJoin(JOIN_TYPE.bevel, v, coordCurr, ...
javascript
{ "resource": "" }
q27001
addJoin
train
function addJoin(join_type, v, coordCurr, normPrev, normNext, isBeginning, context) { var miterVec = createMiterVec(normPrev, normNext); var isClockwise = (normNext[0] * normPrev[1] - normNext[1] * normPrev[0] > 0); if (context.texcoord_index != null) { zero_v[1] = v; one_v[1] = v; } ...
javascript
{ "resource": "" }
q27002
indexPairs
train
function indexPairs(num_pairs, context){ var vertex_elements = context.vertex_data.vertex_elements; var num_vertices = context.vertex_data.vertex_count; var offset = num_vertices - 2 * num_pairs - 2; for (var i = 0; i < num_pairs; i++){ vertex_elements.push(offset + 2 * i + 2); vertex_e...
javascript
{ "resource": "" }
q27003
addCap
train
function addCap (coord, v, normal, type, isBeginning, context) { var neg_normal = Vector.neg(normal); var has_texcoord = (context.texcoord_index != null); switch (type){ case CAP_TYPE.square: var tangent; // first vertex on the lineString if (isBeginning){ tangent = ...
javascript
{ "resource": "" }
q27004
trianglesPerArc
train
function trianglesPerArc (angle, width) { if (angle < 0) { angle = -angle; } var numTriangles = (width > 2 * MIN_FAN_WIDTH) ? Math.log2(width / MIN_FAN_WIDTH) : 1; return Math.ceil(angle / Math.PI * numTriangles); }
javascript
{ "resource": "" }
q27005
permuteLine
train
function permuteLine(line, startIndex){ var newLine = []; for (let i = 0; i < line.length; i++){ var index = (i + startIndex) % line.length; // skip the first (repeated) index if (index !== 0) { newLine.push(line[index]); } } newLine.push(newLine[0]); retu...
javascript
{ "resource": "" }
q27006
collapseLeadingSlashes
train
function collapseLeadingSlashes (str) { for (var i = 0; i < str.length; i++) { if (str.charCodeAt(i) !== 0x2f /* / */) { break } } return i > 1 ? '/' + str.substr(i) : str }
javascript
{ "resource": "" }
q27007
createRedirectDirectoryListener
train
function createRedirectDirectoryListener () { return function redirect (res) { if (this.hasTrailingSlash()) { this.error(404) return } // get original URL var originalUrl = parseUrl.original(this.req) // append trailing slash originalUrl.path = null originalUrl.pathname = col...
javascript
{ "resource": "" }
q27008
yolo
train
async function yolo( input, model, { classProbThreshold = DEFAULT_CLASS_PROB_THRESHOLD, iouThreshold = DEFAULT_IOU_THRESHOLD, filterBoxesThreshold = DEFAULT_FILTER_BOXES_THRESHOLD, yoloAnchors = YOLO_ANCHORS, maxBoxes = DEFAULT_MAX_BOXES, width: widthPx = DEFAULT_INPUT_DIM, height: hei...
javascript
{ "resource": "" }
q27009
redirect
train
function redirect(url) { // unset headers const { res } = this; res .getHeaderNames() .filter(name => !name.match(/^access-control-|vary|x-amz-/i)) .forEach(name => res.removeHeader(name)); this.set("Location", url); // status if (!statuses.redirect[this.status]) this.status = 302; if (this...
javascript
{ "resource": "" }
q27010
onerror
train
async function onerror(err) { // don't do anything if there is no error. // this allows you to pass `this.onerror` // to node-style callbacks. if (null == err) return; if (!(err instanceof Error)) err = new Error(format("non-error thrown: %j", err)); let headerSent = false; if (this.headerSent || !t...
javascript
{ "resource": "" }
q27011
getStringToSign
train
function getStringToSign(canonicalRequest) { return [ canonicalRequest.method, canonicalRequest.contentMD5, canonicalRequest.contentType, canonicalRequest.timestamp, ...canonicalRequest.amzHeaders, canonicalRequest.querystring ? `${canonicalRequest.uri}?${canonicalRequest.querystring}` ...
javascript
{ "resource": "" }
q27012
calculateSignature
train
function calculateSignature(stringToSign, signingKey, algorithm) { const signature = createHmac(algorithm, signingKey); signature.update(stringToSign, "utf8"); return signature.digest("base64"); }
javascript
{ "resource": "" }
q27013
onerror
train
function onerror(err) { // don't do anything if there is no error. // this allows you to pass `this.onerror` // to node-style callbacks. if (null == err) return; if (!(err instanceof Error)) err = new Error(format("non-error thrown: %j", err)); let headerSent = false; if (this.headerSent || !this.wr...
javascript
{ "resource": "" }
q27014
Shopify
train
function Shopify(options) { if (!(this instanceof Shopify)) return new Shopify(options); if ( !options || !options.shopName || !options.accessToken && (!options.apiKey || !options.password) || options.accessToken && (options.apiKey || options.password) ) { throw new Error('Missing or invalid o...
javascript
{ "resource": "" }
q27015
listenersById
train
function listenersById(state = {}, { type, path, payload }) { switch (type) { case actionTypes.SET_LISTENER: return { ...state, [payload.name]: { name: payload.name, path, }, }; case actionTypes.UNSET_LISTENER: return omit(state, [payload.name]); ...
javascript
{ "resource": "" }
q27016
allListeners
train
function allListeners(state = [], { type, payload }) { switch (type) { case actionTypes.SET_LISTENER: return [...state, payload.name]; case actionTypes.UNSET_LISTENER: return state.filter(name => name !== payload.name); default: return state; } }
javascript
{ "resource": "" }
q27017
addDoc
train
function addDoc(array = [], action) { const { meta, payload } = action; if (!meta.subcollections || meta.storeAs) { return [ ...array.slice(0, payload.ordered.newIndex), { id: meta.doc, ...payload.data }, ...array.slice(payload.ordered.newIndex), ]; } // Add doc to subcollection by mo...
javascript
{ "resource": "" }
q27018
removeDoc
train
function removeDoc(array, action) { // Update is at doc level (not subcollection level) if (!action.meta.subcollections || action.meta.storeAs) { // Remove doc from collection array return reject(array, { id: action.meta.doc }); // returns a new array } // Update is at subcollection level const subcol...
javascript
{ "resource": "" }
q27019
arrayToStr
train
function arrayToStr(key, value) { if (isString(value) || isNumber(value)) return `${key}=${value}`; if (isString(value[0])) return `${key}=${value.join(':')}`; if (value && value.toString) return `${key}=${value.toString()}`; return value.map(val => arrayToStr(key, val)); }
javascript
{ "resource": "" }
q27020
pickQueryParams
train
function pickQueryParams(obj) { return [ 'where', 'orderBy', 'limit', 'startAfter', 'startAt', 'endAt', 'endBefore', ].reduce((acc, key) => (obj[key] ? { ...acc, [key]: obj[key] } : acc), {}); }
javascript
{ "resource": "" }
q27021
docChangeEvent
train
function docChangeEvent(change, originalMeta = {}) { const meta = { ...cloneDeep(originalMeta), path: change.doc.ref.path }; if (originalMeta.subcollections && !originalMeta.storeAs) { meta.subcollections[0] = { ...meta.subcollections[0], doc: change.doc.id }; } else { meta.doc = change.doc.id; } retu...
javascript
{ "resource": "" }
q27022
createWithFirebaseAndDispatch
train
function createWithFirebaseAndDispatch(firebase, dispatch) { return func => (...args) => func.apply(firebase, [firebase, dispatch, ...args]); }
javascript
{ "resource": "" }
q27023
train
function (diffX, diffY) { if (diffX === 0 && diffY === -1) return EasyStar.TOP else if (diffX === 1 && diffY === -1) return EasyStar.TOP_RIGHT else if (diffX === 1 && diffY === 0) return EasyStar.RIGHT else if (diffX === 1 && diffY === 1) return EasyStar.BOTTOM_RIGHT else if (dif...
javascript
{ "resource": "" }
q27024
getTouches
train
function getTouches(touches) { return Array.prototype.slice.call(touches).map(function (touch) { return { left: touch.pageX, top: touch.pageY }; }); }
javascript
{ "resource": "" }
q27025
getComputedTranslate
train
function getComputedTranslate(obj) { var result = { translateX: 0, translateY: 0, translateZ: 0, scaleX: 1, scaleY: 1, offsetX: 0, offsetY: 0 }; var offsetX = 0, offsetY = 0; if (!global.getComputedStyle ...
javascript
{ "resource": "" }
q27026
startHandler
train
function startHandler(evt) { startHandlerOriginal.call(this, evt); // must be a picture, only one picture!! var node = this.els[1].querySelector('img:first-child'); var device = this.deviceEvents; if (device.hasTouch && node !== null) { IN_SCALE_MODE = true; ...
javascript
{ "resource": "" }
q27027
moveHandler
train
function moveHandler(evt) { if (IN_SCALE_MODE) { var result = 0; var node = zoomNode; var device = this.deviceEvents; if (device.hasTouch) { if (evt.targetTouches.length === 2) { node.style.webkitTransitionDuration = '0'; ...
javascript
{ "resource": "" }
q27028
handleDoubleTap
train
function handleDoubleTap(evt) { var zoomFactor = zoomFactor || 2; var node = zoomNode; var pos = getPosition(node); currentScale = currentScale == 1 ? zoomFactor : 1; node.style.webkitTransform = generateTranslate(0, 0, 0, currentScale); if (currentScale != 1) node.style....
javascript
{ "resource": "" }
q27029
endHandler
train
function endHandler(evt) { if (IN_SCALE_MODE) { var result = 0; if (gesture === 2) {//双手指 resetImage(evt); result = 2; } else if (gesture == 1) {//放大拖拽 resetImage(evt); result = 1; } else if (gesture ...
javascript
{ "resource": "" }
q27030
valueInViewScope
train
function valueInViewScope(node, value, tag) { var min, max; var pos = getPosition(node); viewScope = { start: {left: pos.left, top: pos.top}, end: {left: pos.left + node.clientWidth, top: pos.top + node.clientHeight} }; var str = tag == 1 ? 'left' : 'top';...
javascript
{ "resource": "" }
q27031
_A
train
function _A(a) { return Array.prototype.slice.apply(a, Array.prototype.slice.call(arguments, 1)); }
javascript
{ "resource": "" }
q27032
detectPlatform
train
function detectPlatform(platform) { var name = platform.toLowerCase(); var prefix = "", suffix = ""; // Detect NuGet/Squirrel.Windows files if (name == 'releases' || hasSuffix(name, '.nupkg')) return platforms.WINDOWS_32; // Detect prefix: osx, widnows or linux if (_.contains(name, 'win') ...
javascript
{ "resource": "" }
q27033
satisfiesPlatform
train
function satisfiesPlatform(platform, list) { if (_.contains(list, platform)) return true; // By default, user 32bits version if (_.contains(list+'_32', platform)) return true; return false; }
javascript
{ "resource": "" }
q27034
resolveForVersion
train
function resolveForVersion(version, platformID, opts) { opts = _.defaults(opts || {}, { // Order for filetype filePreference: ['.exe', '.dmg', '.deb', '.rpm', '.tgz', '.tar.gz', '.zip', '.nupkg'], wanted: null }); // Prepare file prefs if (opts.wanted) opts.filePreference = _.un...
javascript
{ "resource": "" }
q27035
mergeForVersions
train
function mergeForVersions(versions, opts) { opts = _.defaults(opts || {}, { includeTag: true }); return _.chain(versions) .reduce(function(prev, version) { if (!version.notes) return prev; // Include tag as title if (opts.includeTag) { pr...
javascript
{ "resource": "" }
q27036
hashPrerelease
train
function hashPrerelease(s) { if (_.isString(s[0])) { return (_.indexOf(CHANNELS, s[0]) + 1) * CHANNEL_MAGINITUDE + (s[1] || 0); } else { return s[0]; } }
javascript
{ "resource": "" }
q27037
normVersion
train
function normVersion(tag) { var parts = new semver.SemVer(tag); var prerelease = ""; if (parts.prerelease && parts.prerelease.length > 0) { prerelease = hashPrerelease(parts.prerelease); } return [ parts.major, parts.minor, parts.patch ].join('.') + (prerelease?...
javascript
{ "resource": "" }
q27038
toSemver
train
function toSemver(tag) { var parts = tag.split('.'); var version = parts.slice(0, 3).join('.'); var prerelease = Number(parts[3]); // semver == windows version if (!prerelease) return version; var channelId = Math.floor(prerelease/CHANNEL_MAGINITUDE); var channel = CHANNELS[channelId - 1];...
javascript
{ "resource": "" }
q27039
generateRELEASES
train
function generateRELEASES(entries) { return _.map(entries, function(entry) { var filename = entry.filename; if (!filename) { filename = [ entry.app, entry.version, entry.isDelta? 'delta.nupkg' : 'full.nupkg' ].join('-'); ...
javascript
{ "resource": "" }
q27040
normalizeVersion
train
function normalizeVersion(release) { // Ignore draft if (release.draft) return null; var downloadCount = 0; var releasePlatforms = _.chain(release.assets) .map(function(asset) { var platform = platforms.detect(asset.name); if (!platform) return null; downloa...
javascript
{ "resource": "" }
q27041
compareVersions
train
function compareVersions(v1, v2) { if (semver.gt(v1.tag, v2.tag)) { return -1; } if (semver.lt(v1.tag, v2.tag)) { return 1; } return 0; }
javascript
{ "resource": "" }
q27042
execute
train
function execute(args, live, silent) { const env = Object.assign({}, process.env); return new Promise((resolve, reject) => { if (live === true) { const pid = childProcess.spawn(getPath(), args, { env, stdio: ['inherit', silent ? 'pipe' : 'inherit', 'inherit'], }); pid.on('exit'...
javascript
{ "resource": "" }
q27043
getSetJ
train
function getSetJ(h, lw, phi, dec, n, M, L) { var w = hourAngle(h, phi, dec), a = approxTransit(w, lw, n); return solarTransitJ(a, M, L); }
javascript
{ "resource": "" }
q27044
getLimitedLinksMetadata
train
function getLimitedLinksMetadata (limitedLinks) { return limitedLinks.map((link, index) => { if (link === ELLIPSES && limitedLinks[index - 1] === 0) { return 'left-ellipses' } else if (link === ELLIPSES && limitedLinks[index - 1] !== 0) { return 'right-ellipses' } return link }) }
javascript
{ "resource": "" }
q27045
findDelegate
train
function findDelegate(start) { let frag = start; let delegate, el; out: while (frag) { // find next element el = 0; while (!el && frag) { if (frag.owner.type === ELEMENT) el = frag.owner; if (frag.owner.ractive && frag.owner.ractive.delegate === false) break out; frag = frag.parent ...
javascript
{ "resource": "" }
q27046
variants
train
function variants(name, initial) { const map = initial ? initStars : bubbleStars; if (map[name]) return map[name]; const parts = name.split('.'); const result = []; let base = false; // initial events the implicit namespace of 'this' if (initial) { parts.unshift('this'); base = true; } // u...
javascript
{ "resource": "" }
q27047
transpile
train
function transpile(src, options) { return buble.transform(src, { target: { ie: 9 }, transforms: { modules: false } }); }
javascript
{ "resource": "" }
q27048
replacePlaceholders
train
function replacePlaceholders(src, options) { return Object.keys(placeholders).reduce((out, placeholder) => { return out.replace(new RegExp(`${placeholder}`, 'g'), placeholders[placeholder]); }, src); }
javascript
{ "resource": "" }
q27049
decomposeSyllable
train
function decomposeSyllable(codePoint) { const sylSIndex = codePoint - SBASE; const sylTIndex = sylSIndex % TCOUNT; return String.fromCharCode(LBASE + sylSIndex / NCOUNT) + String.fromCharCode(VBASE + (sylSIndex % NCOUNT) / TCOUNT) + ((sylTIndex > 0) ? String.fromCharCode(TBASE + sylTIndex) : ''); }
javascript
{ "resource": "" }
q27050
groupArray
train
function groupArray(array, fn) { var ret = {}; for (var ii = 0; ii < array.length; ii++) { var result = fn.call(array, array[ii], ii); if (!ret[result]) { ret[result] = []; } ret[result].push(array[ii]); } return ret; }
javascript
{ "resource": "" }
q27051
compare
train
function compare(name, version, query, normalizer) { // check for exact match with no version if (name === query) { return true; } // check for non-matching names if (!query.startsWith(name)) { return false; } // full comparison with version let range = query.slice(name.length); if (version)...
javascript
{ "resource": "" }
q27052
getElementPosition
train
function getElementPosition(element) { const rect = getElementRect(element); return { x: rect.left, y: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; }
javascript
{ "resource": "" }
q27053
checkOrExpression
train
function checkOrExpression(range, version) { const expressions = range.split(orRegex); if (expressions.length > 1) { return expressions.some(range => VersionRange.contains(range, version)); } else { range = expressions[0].trim(); return checkRangeExpression(range, version); } }
javascript
{ "resource": "" }
q27054
zeroPad
train
function zeroPad(array, length) { for (let i = array.length; i < length; i++) { array[i] = '0'; } }
javascript
{ "resource": "" }
q27055
compare
train
function compare(a, b) { invariant(typeof a === typeof b, '"a" and "b" must be of the same type'); if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } }
javascript
{ "resource": "" }
q27056
compareComponents
train
function compareComponents(a, b) { const [aNormalized, bNormalized] = normalizeVersions(a, b); for (let i = 0; i < bNormalized.length; i++) { const result = compareNumeric(aNormalized[i], bNormalized[i]); if (result) { return result; } } return 0; }
javascript
{ "resource": "" }
q27057
hiraganaToKatakana
train
function hiraganaToKatakana(str) { if (!hasKana(str)) { return str; } return str.split('').map(charCodeToKatakana).join(''); }
javascript
{ "resource": "" }
q27058
isKanaWithTrailingLatin
train
function isKanaWithTrailingLatin(str) { REGEX_IS_KANA_WITH_TRAILING_LATIN = REGEX_IS_KANA_WITH_TRAILING_LATIN || new RegExp('^' + '[' + R_KANA + ']+' + '[' + R_LATIN + ']' + '$'); return REGEX_IS_KANA_WITH_TRAILING_LATIN.test(str); }
javascript
{ "resource": "" }
q27059
getDocumentScrollElement
train
function getDocumentScrollElement(doc) { doc = doc || document; if (doc.scrollingElement) { return doc.scrollingElement; } return !isWebkit && doc.compatMode === 'CSS1Compat' ? doc.documentElement : doc.body; }
javascript
{ "resource": "" }
q27060
printWarning
train
function printWarning(format, ...args) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, () => args[argIndex++]); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you ca...
javascript
{ "resource": "" }
q27061
concatAllArray
train
function concatAllArray(array) { var ret = []; for (var ii = 0; ii < array.length; ii++) { var value = array[ii]; if (Array.isArray(value)) { push.apply(ret, value); } else if (value != null) { throw new TypeError( 'concatAllArray: All items in the array must be an array or null, ' +...
javascript
{ "resource": "" }
q27062
train
function(element, className) { invariant( !/\s/.test(className), 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ); if (className) { if (element.classList) { element.classList.add(className); } else if (!CSSCore.hasCla...
javascript
{ "resource": "" }
q27063
train
function(element, className) { invariant( !/\s/.test(className), 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className ); if (className) { if (element.classList) { element.classList.remove(className); } else if (CSSCore.h...
javascript
{ "resource": "" }
q27064
train
function(element, className, bool) { return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className); }
javascript
{ "resource": "" }
q27065
createArrayFromMixed
train
function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } }
javascript
{ "resource": "" }
q27066
getElementRect
train
function getElementRect(elem) { const docElem = elem.ownerDocument.documentElement; // FF 2, Safari 3 and Opera 9.5- do not support getBoundingClientRect(). // IE9- will throw if the element is not in the document. if (!('getBoundingClientRect' in elem) || !containsNode(docElem, elem)) { return { lef...
javascript
{ "resource": "" }
q27067
train
function(node) { if (!node) { return null; } var ownerDocument = node.ownerDocument; while (node && node !== ownerDocument.body) { if (_isNodeScrollable(node, 'overflow') || _isNodeScrollable(node, 'overflowY') || _isNodeScrollable(node, 'overflowX')) { return nod...
javascript
{ "resource": "" }
q27068
mapModule
train
function mapModule(state, module) { var moduleMap = state.opts.map || {}; if (moduleMap.hasOwnProperty(module)) { return moduleMap[module]; } // Jest understands the haste module system, so leave modules intact. if (process.env.NODE_ENV !== 'test') { var modulePrefix = state.opts.prefix; if (modul...
javascript
{ "resource": "" }
q27069
transformTypeImport
train
function transformTypeImport(path, state) { var source = path.get('source'); if (source.type === 'StringLiteral') { var module = mapModule(state, source.node.value); if (module) { source.replaceWith(t.stringLiteral(module)); } } }
javascript
{ "resource": "" }
q27070
phpEscape
train
function phpEscape(s) { var result = '"'; for (let cp of UnicodeUtils.getCodePoints(s)) { let special = specialEscape[cp]; if (special !== undefined) { result += special; } else if (cp >= 0x20 && cp <= 0x7e) { result += String.fromCodePoint(cp); } else if (cp <= 0xFFFF) { result +=...
javascript
{ "resource": "" }
q27071
jsEscape
train
function jsEscape(s) { var result = '"'; for (var i = 0; i < s.length; i++) { let cp = s.charCodeAt(i); let special = specialEscape[cp]; if (special !== undefined) { result += special; } else if (cp >= 0x20 && cp <= 0x7e) { result += String.fromCodePoint(cp); } else { result +=...
javascript
{ "resource": "" }
q27072
getBrowserVersion
train
function getBrowserVersion(version) { if (!version) { return { major: '', minor: '', }; } var parts = version.split('.'); return { major: parts[0], minor: parts[1], }; }
javascript
{ "resource": "" }
q27073
getCodePoints
train
function getCodePoints(str) { const codePoints = []; for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) { codePoints.push(str.codePointAt(pos)); } return codePoints; }
javascript
{ "resource": "" }
q27074
train
function (version) { var that = this; var createValidators = function (spec, validatorsMap) { return _.reduce(validatorsMap, function (result, schemas, schemaName) { result[schemaName] = helpers.createJsonValidator(schemas); return result; }, {}); }; var fixSchemaId = function (schemaName) ...
javascript
{ "resource": "" }
q27075
csurf
train
function csurf (options) { var opts = options || {} // get cookie options var cookie = getCookieOptions(opts.cookie) // get session options var sessionKey = opts.sessionKey || 'session' // get value getter var value = opts.value || defaultValue // token repo var tokens = new Tokens(opts) // ign...
javascript
{ "resource": "" }
q27076
defaultValue
train
function defaultValue (req) { return (req.body && req.body._csrf) || (req.query && req.query._csrf) || (req.headers['csrf-token']) || (req.headers['xsrf-token']) || (req.headers['x-csrf-token']) || (req.headers['x-xsrf-token']) }
javascript
{ "resource": "" }
q27077
getCookieOptions
train
function getCookieOptions (options) { if (options !== true && typeof options !== 'object') { return undefined } var opts = Object.create(null) // defaults opts.key = '_csrf' opts.path = '/' if (options && typeof options === 'object') { for (var prop in options) { var val = options[prop] ...
javascript
{ "resource": "" }
q27078
getIgnoredMethods
train
function getIgnoredMethods (methods) { var obj = Object.create(null) for (var i = 0; i < methods.length; i++) { var method = methods[i].toUpperCase() obj[method] = true } return obj }
javascript
{ "resource": "" }
q27079
getSecret
train
function getSecret (req, sessionKey, cookie) { // get the bag & key var bag = getSecretBag(req, sessionKey, cookie) var key = cookie ? cookie.key : 'csrfSecret' if (!bag) { throw new Error('misconfigured csrf') } // return secret from bag return bag[key] }
javascript
{ "resource": "" }
q27080
getSecretBag
train
function getSecretBag (req, sessionKey, cookie) { if (cookie) { // get secret from cookie var cookieKey = cookie.signed ? 'signedCookies' : 'cookies' return req[cookieKey] } else { // get secret from session return req[sessionKey] } }
javascript
{ "resource": "" }
q27081
setCookie
train
function setCookie (res, name, val, options) { var data = Cookie.serialize(name, val, options) var prev = res.getHeader('set-cookie') || [] var header = Array.isArray(prev) ? prev.concat(data) : [prev, data] res.setHeader('set-cookie', header) }
javascript
{ "resource": "" }
q27082
setSecret
train
function setSecret (req, res, sessionKey, val, cookie) { if (cookie) { // set secret on cookie var value = val if (cookie.signed) { value = 's:' + sign(val, req.secret) } setCookie(res, cookie.key, value, cookie) } else { // set secret on session req[sessionKey].csrfSecret = val ...
javascript
{ "resource": "" }
q27083
verifyConfiguration
train
function verifyConfiguration (req, sessionKey, cookie) { if (!getSecretBag(req, sessionKey, cookie)) { return false } if (cookie && cookie.signed && !req.secret) { return false } return true }
javascript
{ "resource": "" }
q27084
train
function (message) { receiveQueue.push(message); //reason I need this setTmeout is to return this function as fast as //possible to release the native side thread. setTimeout(function () { var message = receiveQueue.pop(); callFunc(WebViewBridge.onMessage, message); }, 15);...
javascript
{ "resource": "" }
q27085
train
function (message) { if ('string' !== typeof message) { callFunc(WebViewBridge.onError, "message is type '" + typeof message + "', and it needs to be string"); return; } //we queue the messages to make sure that native can collects all of them in one shot. sendQueue.push(message...
javascript
{ "resource": "" }
q27086
main
train
function main(argv) { try { shell.mkdir('-p', 'docs') shell.pushd('-q', 'docs') handleErrorCode(shell.exec('npm init -y')) handleErrorCode(shell.exec('npm install docusaurus-init')) handleErrorCode(shell.exec('docusaurus-init')) shell.mv('docs-examples-from-docusaurus/', 'docs') shell.mv('...
javascript
{ "resource": "" }
q27087
attach
train
function attach() { const container = this.options.container; if (container instanceof HTMLElement) { const style = window.getComputedStyle(container); if (style.position === 'static') { container.style.position = 'relative'; } } container.addEventListener('scroll'...
javascript
{ "resource": "" }
q27088
off
train
function off(event, selector, handler) { const enterCallbacks = Object.keys(this.trackedElements[selector].enter || {}); const leaveCallbacks = Object.keys(this.trackedElements[selector].leave || {}); if ({}.hasOwnProperty.call(this.trackedElements, selector)) { if (handler) { if (this....
javascript
{ "resource": "" }
q27089
destroy
train
function destroy() { this.options.container.removeEventListener('scroll', this._scroll); window.removeEventListener('resize', this._scroll); this.attached = false; }
javascript
{ "resource": "" }
q27090
on
train
function on(event, selector, callback) { const allowed = ['enter', 'leave']; if (!event) throw new Error('No event given. Choose either enter or leave'); if (!selector) throw new Error('No selector to track'); if (allowed.indexOf(event) < 0) throw new Error(`${event} event is not supported`); if (...
javascript
{ "resource": "" }
q27091
debouncedScroll
train
function debouncedScroll() { let timeout; return () => { clearTimeout(timeout); timeout = setTimeout(() => { scrollHandler(this.trackedElements, this.options); }, this.options.debounce); }; }
javascript
{ "resource": "" }
q27092
inContainer
train
function inContainer(el, options = { tolerance: 0, container: '' }) { if (!el) { throw new Error('You should specify the element you want to test'); } if (typeof el === 'string') { el = document.querySelector(el); } if (typeof options === 'string') { options = { ...
javascript
{ "resource": "" }
q27093
observeDOM
train
function observeDOM(obj, callback) { const MutationObserver = window.MutationObserver || window.WebKitMutationObserver; /* istanbul ignore else */ if (MutationObserver) { const obs = new MutationObserver(callback); obs.observe(obj, { childList: true, subtree: true ...
javascript
{ "resource": "" }
q27094
OnScreen
train
function OnScreen(options = { tolerance: 0, debounce: 100, container: window }) { this.options = {}; this.trackedElements = {}; Object.defineProperties(this.options, { container: { configurable: false, enumerable: false, get() { let container; ...
javascript
{ "resource": "" }
q27095
inViewport
train
function inViewport(el, options = { tolerance: 0 }) { if (!el) { throw new Error('You should specify the element you want to test'); } if (typeof el === 'string') { el = document.querySelector(el); } const elRect = el.getBoundingClientRect(); return ( // Check bottom b...
javascript
{ "resource": "" }
q27096
deployFIFSRegistrar
train
function deployFIFSRegistrar(deployer, tld) { var rootNode = getRootNodeFromTLD(tld); // Deploy the ENS first deployer.deploy(ENS) .then(() => { // Deploy the FIFSRegistrar and bind it with ENS return deployer.deploy(FIFSRegistrar, ENS.address, rootNode.namehash); }) .then(function() { ...
javascript
{ "resource": "" }
q27097
lookup
train
async function lookup(words) { const index = new Index(); const hits = await index.lookup(words); index.quit(); words.forEach((word, i) => { console.log(`hits for "${word}":`, hits[i].join(', ')); }); return hits; }
javascript
{ "resource": "" }
q27098
extractDescription
train
function extractDescription(texts) { let document = ''; texts.forEach(text => { document += text.description || ''; }); return document.toLowerCase(); }
javascript
{ "resource": "" }
q27099
extractDescriptions
train
async function extractDescriptions(filename, index, response) { if (response.textAnnotations.length) { const words = extractDescription(response.textAnnotations); await index.add(filename, words); } else { console.log(`${filename} had no discernable text.`); await index.setContainsNoText(filename); ...
javascript
{ "resource": "" }