_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q27400
clientCoreData
train
function clientCoreData(opt) { var self = { __TYPE__ : MessageType.CS_CORE, rdpVersion : new type.UInt32Le(VERSION.RDP_VERSION_5_PLUS), desktopWidth : new type.UInt16Le(1280), desktopHeight : new type.UInt16Le(800), colorDepth : new type.UInt16Le(ColorDepth.RNS_UD_COLOR_8BPP), sasSequence : new type.UInt16Le(Sequence.RNS_UD_SAS_DEL), kbdLayout : new type.UInt32Le(KeyboardLayout.FRENCH), clientBuild : new type.UInt32Le(3790), clientName : new type.BinaryString(new Buffer('node-rdpjs\x00\x00\x00\x00\x00\x00', 'ucs2'), { readLength : new type.CallableValue(32) }), keyboardType : new type.UInt32Le(KeyboardType.IBM_101_102_KEYS), keyboardSubType : new type.UInt32Le(0), keyboardFnKeys : new type.UInt32Le(12), imeFileName : new type.BinaryString(new Buffer(Array(64 + 1).join('\x00')), { readLength : new type.CallableValue(64), optional : true }), postBeta2ColorDepth : new type.UInt16Le(ColorDepth.RNS_UD_COLOR_8BPP, { optional : true }), clientProductId : new type.UInt16Le(1, { optional : true }), serialNumber : new type.UInt32Le(0, { optional : true }), highColorDepth : new type.UInt16Le(HighColor.HIGH_COLOR_24BPP, { optional : true }), supportedColorDepths : new type.UInt16Le(Support.RNS_UD_15BPP_SUPPORT | Support.RNS_UD_16BPP_SUPPORT | Support.RNS_UD_24BPP_SUPPORT | Support.RNS_UD_32BPP_SUPPORT, { optional : true }), earlyCapabilityFlags : new type.UInt16Le(CapabilityFlag.RNS_UD_CS_SUPPORT_ERRINFO_PDU, { optional : true }), clientDigProductId : new type.BinaryString(new Buffer(Array(64 + 1).join('\x00')), { optional : true, readLength : new type.CallableValue(64) }), connectionType : new type.UInt8(0, { optional : true }), pad1octet : new type.UInt8(0, { optional : true }), serverSelectedProtocol : new type.UInt32Le(0, { optional : true }) }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27401
settings
train
function settings(blocks, opt) { var self = { blocks : blocks || new type.Factory(function(s) { self.blocks = new type.Component([]); // read until end of stream while(s.availableLength() > 0) { self.blocks.obj.push(block().read(s)); } }), }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27402
readConferenceCreateResponse
train
function readConferenceCreateResponse(s) { per.readChoice(s); if(!per.readObjectIdentifier(s, t124_02_98_oid)) { throw new error.ProtocolError('NODE_RDP_PROTOCOL_T125_GCC_BAD_OBJECT_IDENTIFIER_T124'); } per.readLength(s); per.readChoice(s); per.readInteger16(s, 1001); per.readInteger(s); per.readEnumerates(s); per.readNumberOfSet(s); per.readChoice(s); if (!per.readOctetStream(s, h221_sc_key, 4)) { throw new error.ProtocolError('NODE_RDP_PROTOCOL_T125_GCC_BAD_H221_SC_KEY'); } length = per.readLength(s); serverSettings = settings(null, { readLength : new type.CallableValue(length) }); // Object magic return serverSettings.read(s).obj.blocks.obj.map(function(e) { return e.obj.data; }); }
javascript
{ "resource": "" }
q27403
readConferenceCreateRequest
train
function readConferenceCreateRequest (s) { per.readChoice(s); if (!per.readObjectIdentifier(s, t124_02_98_oid)) { throw new error.ProtocolError('NODE_RDP_PROTOCOL_T125_GCC_BAD_H221_SC_KEY'); } per.readLength(s); per.readChoice(s); per.readSelection(s); per.readNumericString(s, 1); per.readPadding(s, 1); if (per.readNumberOfSet(s) !== 1) { throw new error.ProtocolError('NODE_RDP_PROTOCOL_T125_GCC_BAD_SET'); } if (per.readChoice(s) !== 0xc0) { throw new error.ProtocolError('NODE_RDP_PROTOCOL_T125_GCC_BAD_CHOICE'); } per.readOctetStream(s, h221_cs_key, 4); length = per.readLength(s); var clientSettings = settings(null, { readLength : new type.CallableValue(length) }); // Object magic return clientSettings.read(s).obj.blocks.obj.map(function(e) { return e.obj.data; }); }
javascript
{ "resource": "" }
q27404
certBlob
train
function certBlob() { var self = { cbCert : new type.UInt32Le(function() { return self.abCert.size(); }), abCert : new type.BinaryString(null, { readLength : new type.CallableValue(function() { return self.cbCert.value; }) }) }; return new type.Component(self); }
javascript
{ "resource": "" }
q27405
x509CertificateChain
train
function x509CertificateChain() { var self = { __TYPE__ : CertificateType.CERT_CHAIN_VERSION_2, NumCertBlobs : new type.UInt32Le(), CertBlobArray : new type.Factory(function(s) { self.CertBlobArray = new type.Component([]); for(var i = 0; i < self.NumCertBlobs.value; i++) { self.CertBlobArray.obj.push(certBlob().read(s)); } }), padding : new type.BinaryString(null, { readLength : new type.CallableValue(function() { return 8 + 4 * self.NumCertBlobs.value; }) }), /** * @return {object} {n : modulus{bignum}, e : publicexponent{integer} */ getPublicKey : function(){ var cert = x509.X509Certificate().decode(new type.Stream(self.CertBlobArray.obj[self.CertBlobArray.obj.length - 1].obj.abCert.value), asn1.ber); var publikeyStream = new type.Stream(cert.value.tbsCertificate.value.subjectPublicKeyInfo.value.subjectPublicKey.toBuffer()); var asn1PublicKey = x509.RSAPublicKey().decode(publikeyStream, asn1.ber); return rsa.publicKey(asn1PublicKey.value.modulus.value, asn1PublicKey.value.publicExponent.value); } }; return new type.Component(self); }
javascript
{ "resource": "" }
q27406
MCS
train
function MCS(transport, recvOpCode, sendOpCode) { this.transport = transport; this.recvOpCode = recvOpCode; this.sendOpCode = sendOpCode; this.channels = [{id : Channel.MCS_GLOBAL_CHANNEL, name : 'global'}]; this.channels.find = function(callback) { for(var i in this) { if(callback(this[i])) return this[i]; }; }; // bind events var self = this; this.transport.on('close', function () { self.emit('close'); }).on('error', function (err) { self.emit('error', err); }); }
javascript
{ "resource": "" }
q27407
Client
train
function Client(transport) { MCS.call(this, transport, DomainMCSPDU.SEND_DATA_INDICATION, DomainMCSPDU.SEND_DATA_REQUEST); // channel context automata this.channelsConnected = 0; // init gcc information this.clientCoreData = gcc.clientCoreData(); this.clientNetworkData = gcc.clientNetworkData(new type.Component([])); this.clientSecurityData = gcc.clientSecurityData(); // must be readed from protocol this.serverCoreData = null; this.serverSecurityData = null; this.serverNetworkData = null; var self = this; this.transport.on('connect', function(s) { self.connect(s); }); }
javascript
{ "resource": "" }
q27408
Server
train
function Server (transport) { MCS.call(this, transport, DomainMCSPDU.SEND_DATA_REQUEST, DomainMCSPDU.SEND_DATA_INDICATION); // must be readed from protocol this.clientCoreData = null; this.clientNetworkData = null; this.clientSecurityData = null; // init gcc information this.serverCoreData = gcc.serverCoreData(); this.serverSecurityData = gcc.serverSecurityData(); this.serverNetworkData = gcc.serverNetworkData(new type.Component([])); var self = this; this.transport.on('connect', function (selectedProtocol) { self.serverCoreData.obj.clientRequestedProtocol.value = selectedProtocol; }).once('data', function (s) { self.recvConnectInitial(s); }); }
javascript
{ "resource": "" }
q27409
TPKT
train
function TPKT(transport) { this.transport = transport; // wait 2 bytes this.transport.expect(2); // next state is receive header var self = this; this.transport.once('data', function(s) { self.recvHeader(s); }).on('close', function() { self.emit('close'); }).on('error', function (err) { self.emit('error', err); }); }
javascript
{ "resource": "" }
q27410
licenseBinaryBlob
train
function licenseBinaryBlob(blobType) { blobType = blobType || BinaryBlobType.BB_ANY_BLOB; var self = { wBlobType : new type.UInt16Le(blobType, { constant : (blobType === BinaryBlobType.BB_ANY_BLOB)?false:true }), wBlobLen : new type.UInt16Le(function() { return self.blobData.size(); }), blobData : new type.BinaryString(null, { readLength : new type.CallableValue(function() { return self.wBlobLen.value; })}) }; return new type.Component(self); }
javascript
{ "resource": "" }
q27411
licensingErrorMessage
train
function licensingErrorMessage(opt) { var self = { __TYPE__ : MessageType.ERROR_ALERT, dwErrorCode : new type.UInt32Le(), dwStateTransition : new type.UInt32Le(), blob : licenseBinaryBlob(BinaryBlobType.BB_ANY_BLOB) }; return new type.Component(self, opt); }
javascript
{ "resource": "" }
q27412
productInformation
train
function productInformation() { var self = { dwVersion : new type.UInt32Le(), cbCompanyName : new type.UInt32Le(function() { return self.pbCompanyName.size(); }), // may contain "Microsoft Corporation" from server microsoft pbCompanyName : new type.BinaryString(new Buffer('Microsoft Corporation', 'ucs2'), { readLength : new type.CallableValue(function() { return self.cbCompanyName.value; })}), cbProductId : new type.UInt32Le(function() { return self.pbProductId.size(); }), // may contain "A02" from microsoft license server pbProductId : new type.BinaryString(new Buffer('A02', 'ucs2'), { readLength : new type.CallableValue(function() { return self.cbProductId.value; })}) }; return new type.Component(self); }
javascript
{ "resource": "" }
q27413
licensePacket
train
function licensePacket(message) { var self = { bMsgtype : new type.UInt8(function() { return self.licensingMessage.obj.__TYPE__; }), flag : new type.UInt8(Preambule.PREAMBLE_VERSION_3_0), wMsgSize : new type.UInt16Le(function() { return new type.Component(self).size(); }), licensingMessage : message || new type.Factory(function(s) { switch(self.bMsgtype.value) { case MessageType.ERROR_ALERT: self.licensingMessage = licensingErrorMessage({ readLength : new type.CallableValue(function() { return self.wMsgSize.value - 4; })}).read(s); break; case MessageType.LICENSE_REQUEST: self.licensingMessage = serverLicenseRequest({ readLength : new type.CallableValue(function() { return self.wMsgSize.value - 4; })}).read(s); break; case MessageType.NEW_LICENSE_REQUEST: self.licensingMessage = clientNewLicenseRequest({ readLength : new type.CallableValue(function() { return self.wMsgSize.value - 4; })}).read(s); break; case MessageType.PLATFORM_CHALLENGE: self.licensingMessage = serverPlatformChallenge({ readLength : new type.CallableValue(function() { return self.wMsgSize.value - 4; })}).read(s); break; case MessageType.PLATFORM_CHALLENGE_RESPONSE: self.licensingMessage = clientPLatformChallengeResponse({ readLength : new type.CallableValue(function() { return self.wMsgSize.value - 4; })}).read(s); break; default: log.error('unknown license message type ' + self.bMsgtype.value); } }) }; return new type.Component(self); }
javascript
{ "resource": "" }
q27414
requireProxy
train
function requireProxy(path) { reset(); currentModule.require = nodeRequire; return nodeRequire.call(currentModule, path); // node's require only works when "this" points to the module }
javascript
{ "resource": "" }
q27415
getImportGlobalsSrc
train
function getImportGlobalsSrc(ignore) { var key, value, src = "", globalObj = typeof global === "undefined"? window: global; ignore = ignore || []; // global itself can't be overridden because it's the only reference to our real global objects ignore.push("global"); // ignore 'module', 'exports' and 'require' on the global scope, because otherwise our code would // shadow the module-internal variables // @see https://github.com/jhnns/rewire-webpack/pull/6 ignore.push("module", "exports", "require"); for (key in globalObj) { /* jshint forin: false */ if (ignore.indexOf(key) !== -1) { continue; } value = globalObj[key]; // key may be an invalid variable name (e.g. 'a-b') try { eval("var " + key + ";"); src += "var " + key + " = global." + key + "; "; } catch(e) {} } return src; }
javascript
{ "resource": "" }
q27416
detectStrictMode
train
function detectStrictMode(src) { var singleLine; var multiLine; while ((singleLine = singleLineComment.test(src)) || (multiLine = multiLineComment.test(src))) { if (singleLine) { src = src.replace(singleLineComment, ""); } if (multiLine) { src = src.replace(multiLineComment, ""); } } return strictMode.test(src); }
javascript
{ "resource": "" }
q27417
internalRewire
train
function internalRewire(parentModulePath, targetPath) { var targetModule, prelude, appendix, src; // Checking params if (typeof targetPath !== "string") { throw new TypeError("Filename must be a string"); } // Resolve full filename relative to the parent module targetPath = Module._resolveFilename(targetPath, parentModulePath); // Create testModule as it would be created by require() targetModule = new Module(targetPath, parentModulePath); // We prepend a list of all globals declared with var so they can be overridden (without changing original globals) prelude = getImportGlobalsSrc(); // Wrap module src inside IIFE so that function declarations do not clash with global variables // @see https://github.com/jhnns/rewire/issues/56 prelude += "(function () { "; // We append our special setter and getter. appendix = "\n" + getDefinePropertySrc(); // End of IIFE appendix += "})();"; // Check if the module uses the strict mode. // If so we must ensure that "use strict"; stays at the beginning of the module. src = fs.readFileSync(targetPath, "utf8"); if (detectStrictMode(src) === true) { prelude = ' "use strict"; ' + prelude; } moduleEnv.inject(prelude, appendix); moduleEnv.load(targetModule); return targetModule.exports; }
javascript
{ "resource": "" }
q27418
train
function () { return _.map(groceries, item => { const object = { id: item.id, name: item.name, departmentsCount: item.departments.length } delete object.departments // @TODO ???? return object }) }
javascript
{ "resource": "" }
q27419
train
function () { const departments = [] // @TODO this is an example what should be updated. loooooks so bad and unreadable _.forEach(_.range(0, groceries.length), value => departments.push(..._.map(groceries[value]['departments'])) ) return departments }
javascript
{ "resource": "" }
q27420
createTreeListener
train
function createTreeListener({ handler, restPath }) { const newHandler = function treeListener(changeEvent) { const extendedChangeEvent = { restPath, ...changeEvent }; const { previousValue, value } = changeEvent; // removes listener for all branches of the path on old object if (previousValue && typeof previousValue === 'object') { removeTreeListener(previousValue, restPath, handler); } // adds listener for all branches of "restPath" path on newly assigned object if (value && typeof value === 'object') { addTreeListener(value, restPath, handler); } // call original handler handler.call(this, extendedChangeEvent); }; newHandler._callback = handler; return newHandler; }
javascript
{ "resource": "" }
q27421
defaultUpdateFunction
train
function defaultUpdateFunction(instance, data) { if (instance.isMatreshkaArray) { instance.recreate(data); } else if (instance.isMatreshkaObject) { instance.setData(data, { replaceData: true }); } else { // for other objects just extend them with given data nofn.assign(instance, data); } }
javascript
{ "resource": "" }
q27422
createInstantiateMediator
train
function createInstantiateMediator({ UsedClass, updateFunction }) { return function mediator(value, previousValue, key, object) { if (previousValue instanceof UsedClass) { updateFunction.call(object, previousValue, value, key); return previousValue; } return new UsedClass(value, object, key); }; }
javascript
{ "resource": "" }
q27423
shift
train
function shift(arr, index) { for (let i = index; i < arr.length; i++) { arr[i] = arr[i + 1]; } delete arr[arr.length - 1]; arr.length -= 1; }
javascript
{ "resource": "" }
q27424
pullByValue
train
function pullByValue(arr, value) { for (let i = 0; i < arr.length; i++) { if (arr[i] === value) { shift(arr, i); return value; } } return undefined; }
javascript
{ "resource": "" }
q27425
pullByIndex
train
function pullByIndex(arr, index) { if (index < arr.length) { const value = arr[index]; shift(arr, index); return value; } return undefined; }
javascript
{ "resource": "" }
q27426
getNotListedKeys
train
function getNotListedKeys(inObject, fromObject) { const result = []; nofn.forOwn(inObject, (_, key) => { if (!(key in fromObject)) { result.push(key); } }); return result; }
javascript
{ "resource": "" }
q27427
createBindingHandlers
train
function createBindingHandlers({ fullEventName, domEventHandler, selector }) { return { bindHandler(evt = {}) { const { node } = evt; if (node) { dom.$(node).on(fullEventName, selector, domEventHandler); } }, unbindHandler(evt = {}) { const { node } = evt; if (node) { dom.$(node).off(fullEventName, selector, domEventHandler); } } }; }
javascript
{ "resource": "" }
q27428
changeHandler
train
function changeHandler(eventOptions = {}) { const { key, silent } = eventOptions; const def = defs.get(this); if (key && key in def.keys && !silent) { triggerOne(this, 'set', eventOptions); triggerOne(this, 'modify', eventOptions); } }
javascript
{ "resource": "" }
q27429
createMediator
train
function createMediator({ object, propDef, key, mediator }) { return function propMediator(value) { // args: value, previousValue, key, object itself return mediator.call(object, value, propDef.value, key, object); }; }
javascript
{ "resource": "" }
q27430
is
train
function is(node, selector) { return (node.matches || node.webkitMatchesSelector || node.mozMatchesSelector || node.msMatchesSelector || node.oMatchesSelector).call(node, selector); }
javascript
{ "resource": "" }
q27431
delegateHandler
train
function delegateHandler(evt, selector, handler) { const scopeSelector = `[${randomID}="${randomID}"] `; const splittedSelector = selector.split(','); let matching = ''; for (let i = 0; i < splittedSelector.length; i++) { const sel = splittedSelector[i]; matching += `${i === 0 ? '' : ','}${scopeSelector}${sel},${scopeSelector}${sel} *`; } this.setAttribute(randomID, randomID); if (is(evt.target, matching)) { handler.call(this, evt); } this.removeAttribute(randomID); }
javascript
{ "resource": "" }
q27432
createItemMediator
train
function createItemMediator({ arr, mediator }) { return function itemMediator(value, index) { // args: value, old value, index, array itself return mediator.call(arr, value, index, arr); }; }
javascript
{ "resource": "" }
q27433
modelItemMediator
train
function modelItemMediator(item, index) { const { Model } = this; // if an item is already instance of Model if (item instanceof Model) { return item; } let itemData; if (item && typeof item.toJSON === 'function') { // if item is not falsy and if it has toJSON method // then retrieve instance data by this method itemData = item.toJSON(false); } else { // if not then use an item as its data itemData = item; } return new Model(itemData, this, index); }
javascript
{ "resource": "" }
q27434
percentage
train
function percentage(target, context) { if (target.slice(-1) === "%" || context.slice(-1) === "%") { throw new Error(`Cannot calculate percentage; one or more units appear to be %. Units must be rem or px.`); } if (target.slice(-1) !== context.slice(-1)) { throw new Error("Cannot calculate percentage; units do not appear to match."); } const unit = target.slice(-1) === "x" ? "px" : "rem"; const numbers = _getNumbers([target, context], "static", unit); const result = numbers.reduce((a, b) => a / b) * 100; return _affixValue(result, "fluid"); }
javascript
{ "resource": "" }
q27435
gutter
train
function gutter( math = settings.math, columns = settings.columns, multiplier = 1 ) { const gutterWidth = _calculateGutter(multiplier); const containerWidth = _updateContext( typeof columns === "string" ? parseInt(columns, 10) : columns ); if (math === "static") { return _staticCalculation(gutterWidth); } if (math === "fluid") { return _percent(gutterWidth, containerWidth); } return false; }
javascript
{ "resource": "" }
q27436
visuallyHidden
train
function visuallyHidden(focusable) { const focusableStyles = { clip: "auto", clipPath: "none", height: "auto", margin: 0, overflow: "visible", position: "static", whiteSpace: "inherit", width: "auto", }; return Object.assign({}, { border: 0, clipPath: "inset(50%)", display: "inline-block", height: "1px", margin: "-1px", overflow: "hidden", padding: 0, whiteSpace: "nowrap", width: "1px", }, focusable === "focusable" ? { ":active": focusableStyles, ":focus": focusableStyles, } : {}); }
javascript
{ "resource": "" }
q27437
blueLink
train
function blueLink() { return { color: colors.linkPrimary, textDecoration: "none", transition: `color ${timing.fast} ease-in-out`, ":hover": { color: colors.linkPrimaryHover, }, ":active": { color: colors.linkPrimaryHover, }, ":focus": Object.assign({}, outline(), { color: colors.linkPrimaryHover, }), }; }
javascript
{ "resource": "" }
q27438
underlinedLink
train
function underlinedLink(linkColor = colors.textPrimary) { const underlineOffset = 2; const underlineWeight = 1; const backgroundColor = colors.bgPrimary; const underlineColor = rgba(linkColor, 0.4); return { color: linkColor, position: "relative", textDecoration: "none", transition: `color ${timing.fast} ease`, // Draw the underline with a background gradient backgroundImage: `linear-gradient( to top, transparent, transparent ${underlineOffset}px, ${underlineColor} ${underlineOffset}px, ${underlineColor} ${(underlineOffset + underlineWeight)}px, transparent ${(underlineOffset + underlineWeight)}px )`, // Create breaks in the underline textShadow: `-1px -1px 0 ${backgroundColor}, 1px -1px 0 ${backgroundColor}, -1px 1px 0 ${backgroundColor}, 1px 1px 0 ${backgroundColor}`, }; }
javascript
{ "resource": "" }
q27439
config
train
function config(mode = 'production', assetDirs = [], moduleDirs = [], outputDir = false) { const context = resolve(__dirname, '../../../node_modules'); const entry = _entry(Utils.castArray(assetDirs)); const output = outputDir ? { filename: '[name].js', path: outputDir } : {}; const removeFiles = _removeFiles(entry); const resolveModules = Utils.concat([context], moduleDirs); const devtool = mode === 'development' ? 'source-map' : false; return { mode, context, entry, output, devtool, module: { rules: [ { test: /\.s[ac]ss$/, use: [ { loader: MiniCssExtractPlugin.loader }, { loader: 'css-loader', options: { url: false, sourceMap: true } }, { loader: 'sass-loader', options: { implementation: sass, sourceMap: true } }, { loader: 'resolve-url-loader' }, ], }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css', }), new RemoveFilesPlugin({ files: removeFiles, }), ], resolve: { modules: resolveModules, }, }; }
javascript
{ "resource": "" }
q27440
_removeFiles
train
function _removeFiles(entry) { return Utils.reduce(entry, (memo, value, key) => { if (value[0].match(/\.pack\.s[ac]ss/)) { memo.push(`${key}.js`); } return memo; }, []); }
javascript
{ "resource": "" }
q27441
_updatePjson
train
function _updatePjson(siteId) { pjson.vapid.site = siteId; writePkg.sync(pjsonPath, pjson); }
javascript
{ "resource": "" }
q27442
_generateManifest
train
function _generateManifest(siteChecksums, presignedPosts) { return Utils.reduce(siteChecksums, (memo, checksum, path) => { /* eslint-disable-next-line no-param-reassign */ memo[path] = presignedPosts[path].digest; return memo; }, {}); }
javascript
{ "resource": "" }
q27443
_checksums
train
function _checksums(dir) { const checksums = {}; glob.sync(resolve(dir, '**/!(*.pack.+(s[ac]ss|js))'), { mark: true }).forEach((file) => { if (Utils.endsWith(file, '/')) { return; } const relativePath = relative(dir, file); checksums[relativePath] = Utils.checksum(file); }); return checksums; }
javascript
{ "resource": "" }
q27444
_getPresignedPosts
train
async function _getPresignedPosts(siteId, checksums) { const endpoint = url.resolve(apiURL, `/sites/${siteId}/presigned_posts`); const body = { checksums }; const response = await got.post(endpoint, { body, json: true, headers: _bearer() }); return response.body.presignedPosts; }
javascript
{ "resource": "" }
q27445
_uploadFiles
train
async function _uploadFiles(dir, presignedPosts) { const promises = []; const limit = pLimit(5); let uploaded = false; Object.keys(presignedPosts).forEach(async (path) => { const { post } = presignedPosts[path]; if (!post) { Logger.tagged('exists', path, 'blue'); } else { const filePath = resolve(dir, path); const form = new FormData(); Utils.forEach(post.fields, (value, key) => { form.append(key, value); }); form.append('file', fs.createReadStream(filePath)); const promise = limit(() => got.post(post.url, { body: form }).then(() => { Logger.tagged('upload', path); })); promises.push(promise); uploaded = true; } }); await Promise.all(promises); return uploaded; }
javascript
{ "resource": "" }
q27446
_updateSite
train
async function _updateSite(siteId, tree, manifest, content) { const endpoint = url.resolve(apiURL, `/sites/${siteId}`); const body = { tree, content, manifest }; const response = await got.post(endpoint, { body, json: true, headers: _bearer() }); return response.body.site; }
javascript
{ "resource": "" }
q27447
_compileAssets
train
async function _compileAssets(wwwDir, tmpDir) { const nodeDir = resolve(wwwDir, '../node_modules'); const moduleDirs = (function _moduleDirs() { const dirs = [wwwDir]; if (fs.existsSync(nodeDir)) dirs.push(nodeDir); return dirs; }()); const config = webPackConfig('production', tmpDir, moduleDirs, tmpDir); if (Utils.isEmpty(config.entry)) return; const compiler = Webpack(config); await new Promise((_resolve, _reject) => { compiler.run((err, stats) => { if (stats.hasErrors()) { _reject(new Error('Failed to compile assets')); } _resolve(); }); }); }
javascript
{ "resource": "" }
q27448
addData
train
function addData(element, key, value) { if (value === undefined) { return element && element.h5s && element.h5s.data && element.h5s.data[key]; } else { element.h5s = element.h5s || {}; element.h5s.data = element.h5s.data || {}; element.h5s.data[key] = value; } }
javascript
{ "resource": "" }
q27449
train
function (config) { if (typeof config !== 'object') { throw new Error('You must provide a valid configuration object to the config setter.'); } // combine config with default var mergedConfig = Object.assign({}, config); // add config to map this._config = new Map(Object.entries(mergedConfig)); }
javascript
{ "resource": "" }
q27450
train
function (draggedElement, elementOffset, event) { return { element: draggedElement, posX: event.pageX - elementOffset.left, posY: event.pageY - elementOffset.top }; }
javascript
{ "resource": "" }
q27451
_throttle
train
function _throttle (fn, threshold) { var _this = this; if (threshold === void 0) { threshold = 250; } // check function if (typeof fn !== 'function') { throw new Error('You must provide a function as the first argument for throttle.'); } // check threshold if (typeof threshold !== 'number') { throw new Error('You must provide a number as the second argument for throttle.'); } var lastEventTimestamp = null; return function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i - 0] = arguments[_i]; } var now = Date.now(); if (lastEventTimestamp === null || now - lastEventTimestamp >= threshold) { lastEventTimestamp = now; fn.apply(_this, args); } }; }
javascript
{ "resource": "" }
q27452
train
function (items) { removeEventListener(items, 'dragstart'); removeEventListener(items, 'dragend'); removeEventListener(items, 'dragover'); removeEventListener(items, 'dragenter'); removeEventListener(items, 'drop'); removeEventListener(items, 'mouseenter'); removeEventListener(items, 'mouseleave'); }
javascript
{ "resource": "" }
q27453
train
function (draggedItem, sortable) { var ditem = draggedItem; if (store(sortable).getConfig('copy') === true) { ditem = draggedItem.cloneNode(true); addAttribute(ditem, 'aria-copied', 'true'); draggedItem.parentElement.appendChild(ditem); ditem.style.display = 'none'; ditem.oldDisplay = draggedItem.style.display; } return ditem; }
javascript
{ "resource": "" }
q27454
findDragElement
train
function findDragElement(sortableElement, element) { var options = addData(sortableElement, 'opts'); var items = _filter(sortableElement.children, options.items); var itemlist = items.filter(function (ele) { return ele.contains(element); }); return itemlist.length > 0 ? itemlist[0] : element; }
javascript
{ "resource": "" }
q27455
train
function (sortableElement) { var opts = addData(sortableElement, 'opts') || {}; var items = _filter(sortableElement.children, opts.items); var handles = _getHandles(items, opts.handle); // remove event handlers & data from sortable removeEventListener(sortableElement, 'dragover'); removeEventListener(sortableElement, 'dragenter'); removeEventListener(sortableElement, 'drop'); // remove event data from sortable _removeSortableData(sortableElement); // remove event handlers & data from items removeEventListener(handles, 'mousedown'); _removeItemEvents(items); _removeItemData(items); }
javascript
{ "resource": "" }
q27456
train
function (sortableElement) { var opts = addData(sortableElement, 'opts'); var items = _filter(sortableElement.children, opts.items); var handles = _getHandles(items, opts.handle); addAttribute(sortableElement, 'aria-dropeffect', 'move'); addData(sortableElement, '_disabled', 'false'); addAttribute(handles, 'draggable', 'true'); // @todo: remove this fix // IE FIX for ghost // can be disabled as it has the side effect that other events // (e.g. click) will be ignored if (opts.disableIEFix === false) { var spanEl = (document || window.document).createElement('span'); if (typeof spanEl.dragDrop === 'function') { addEventListener(handles, 'mousedown', function () { if (items.indexOf(this) !== -1) { this.dragDrop(); } else { var parent = this.parentElement; while (items.indexOf(parent) === -1) { parent = parent.parentElement; } parent.dragDrop(); } }); } } }
javascript
{ "resource": "" }
q27457
train
function (sortableElement) { var opts = addData(sortableElement, 'opts'); var items = _filter(sortableElement.children, opts.items); var handles = _getHandles(items, opts.handle); addAttribute(sortableElement, 'aria-dropeffect', 'none'); addData(sortableElement, '_disabled', 'true'); addAttribute(handles, 'draggable', 'false'); removeEventListener(handles, 'mousedown'); }
javascript
{ "resource": "" }
q27458
train
function (e) { var element = e.target; var sortableElement = element.isSortable === true ? element : findSortable(element); element = findDragElement(sortableElement, element); if (!dragging || !_listsConnected(sortableElement, dragging.parentElement) || addData(sortableElement, '_disabled') === 'true') { return; } var options = addData(sortableElement, 'opts'); if (parseInt(options.maxItems) && _filter(sortableElement.children, addData(sortableElement, 'items')).length >= parseInt(options.maxItems) && dragging.parentElement !== sortableElement) { return; } e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = store(sortableElement).getConfig('copy') === true ? 'copy' : 'move'; debouncedDragOverEnter(sortableElement, element, e.pageY); }
javascript
{ "resource": "" }
q27459
find
train
function find(params = {}) { const name = params.type; if (Utils.has(availableDirectives, name)) { return new availableDirectives[name](params); } // Only show warning if someone explicity enters a bad name if (name) { Logger.warn(`Directive type '${name}' does not exist. Falling back to 'text'`); } /* eslint-disable-next-line new-cap */ return new availableDirectives.text(params); }
javascript
{ "resource": "" }
q27460
getProjectName
train
function getProjectName(protoPath) { var cordovaConfigPath = path.join(protoPath, 'config.xml'), content = fs.readFileSync(cordovaConfigPath, 'utf-8'); return /<name>([\s\S]*)<\/name>/mi.exec(content)[1].trim(); }
javascript
{ "resource": "" }
q27461
getOffsetWidth
train
function getOffsetWidth(el) { var rect = el.getBoundingClientRect(); return rect.width || rect.right - rect.left; }
javascript
{ "resource": "" }
q27462
columnNum
train
function columnNum(){ var count; var $headerColumns = $header.find(opts.headerCellSelector); if(existingColGroup){ count = $tableColGroup.find('col').length; } else { count = 0; $headerColumns.each(function () { count += parseInt(($(this).attr('colspan') || 1), 10); }); } if(count !== lastColumnCount){ lastColumnCount = count; var cells = [], cols = [], psuedo = [], content; for(var x = 0; x < count; x++){ content = $headerColumns.eq(x).text(); cells.push('<th class="floatThead-col" aria-label="'+content+'"/>'); cols.push('<col/>'); psuedo.push( $('<fthtd>').css({ 'display': 'table-cell', 'height': 0, 'width': 'auto' }) ); } cols = cols.join(''); cells = cells.join(''); if(createElements){ $fthRow.empty(); $fthRow.append(psuedo); $fthCells = $fthRow.find('fthtd'); } $sizerRow.html(cells); $sizerCells = $sizerRow.find("th"); if(!existingColGroup){ $tableColGroup.html(cols); } $tableCells = $tableColGroup.find('col'); $floatColGroup.html(cols); $headerCells = $floatColGroup.find("col"); } return count; }
javascript
{ "resource": "" }
q27463
calculateScrollBarSize
train
function calculateScrollBarSize(){ //this should happen after the floating table has been positioned if($scrollContainer.length){ if(opts.support && opts.support.perfectScrollbar && $scrollContainer.data().perfectScrollbar){ scrollbarOffset = {horizontal:0, vertical:0}; } else { if($scrollContainer.css('overflow-x') == 'scroll'){ scrollbarOffset.horizontal = scrollbarWidth; } else { var sw = $scrollContainer.width(), tw = tableWidth($table, $fthCells); var offsetv = sh < th ? scrollbarWidth : 0; scrollbarOffset.horizontal = sw - offsetv < tw ? scrollbarWidth : 0; } if($scrollContainer.css('overflow-y') == 'scroll'){ scrollbarOffset.vertical = scrollbarWidth; } else { var sh = $scrollContainer.height(), th = $table.height(); var offseth = sw < tw ? scrollbarWidth : 0; scrollbarOffset.vertical = sh - offseth < th ? scrollbarWidth : 0; } } } }
javascript
{ "resource": "" }
q27464
train
function (options, callback) { // build dataSource based with options var resp = { count: data.repeater.listData.length, items: [], page: options.pageIndex }; // get start and end limits for JSON var i, l; resp.pages = Math.ceil(resp.count / (options.pageSize || 50)); i = options.pageIndex * (options.pageSize || 50); l = i + (options.pageSize || 50); l = (l <= resp.count) ? l : resp.count; resp.start = i + 1; resp.end = l; // setup columns for list view resp.columns = [ { label: 'Common Name', property: 'commonName', sortable: true, width: 600 }, { label: 'Latin Name', property: 'latinName', sortable: true, width: 600 }, { label: 'Appearance', property: 'appearance', sortable: true }, { label: 'Sound', property: 'sound', sortable: true } ]; // add sample items to datasource for (i; i < l; i++) { // from data.js resp.items.push(data.repeater.listData[i]); } resp.items = sort(resp.items, options.sortProperty, options.sortDirection); // call and simulate latency setTimeout(function () { callback(resp); }, loadDelays[Math.floor(Math.random() * 4)]); }
javascript
{ "resource": "" }
q27465
train
function (options, callback) { var sampleImageCategories = ['abstract', 'animals', 'business', 'cats', 'city', 'food', 'nature', 'technics', 'transport']; var numItems = 200; // build dataSource based with options var resp = { count: numItems, items: [], pages: (Math.ceil(numItems / (options.pageSize || 30))), page: options.pageIndex }; // get start and end limits for JSON var i, l; i = options.pageIndex * (options.pageSize || 30); l = i + (options.pageSize || 30); resp.start = i + 1; resp.end = l; // add sample items to datasource for (i; i < l; i++) { resp.items.push({ name: ('Thumbnail ' + (i + 1)), src: 'http://lorempixel.com/65/65/' + sampleImageCategories[Math.floor(Math.random() * 9)] + '/?_=' + i }); } // call and simulate latency setTimeout(function () { callback(resp); }, loadDelays[Math.floor(Math.random() * 4)]); }
javascript
{ "resource": "" }
q27466
train
function(...args) { const cacheKey = keySelector(...args); if (isValidCacheKey(cacheKey)) { let cacheResponse = cache.get(cacheKey); if (cacheResponse === undefined) { cacheResponse = selectorCreator(...funcs); cache.set(cacheKey, cacheResponse); } return cacheResponse(...args); } console.warn( `[re-reselect] Invalid cache key "${cacheKey}" has been returned by keySelector function.` ); return undefined; }
javascript
{ "resource": "" }
q27467
compressJS
train
function compressJS() { let tasks = []; Object.keys(config.tasks).forEach((key) => { let val = config.tasks[key]; tasks.push(gulp.src(val.src) .pipe(plumber({ errorHandler: handleErrors })) .pipe(uglify()) .pipe(rename(config.rename)) .pipe(gulp.dest(val.dest))); }); return merge(tasks); }
javascript
{ "resource": "" }
q27468
watchTask
train
function watchTask() { gulp.watch(config.watchers.static, copyStaticFiles); gulp.watch(config.watchers.css, gulp.series(lintCSS, compileSass)); gulp.watch(config.watchers.js, gulp.series(lintJS, concatJS, copyJS)); gulp.watch(config.watchers.drizzle, drizzleTask); }
javascript
{ "resource": "" }
q27469
compressCSS
train
function compressCSS() { let tasks = []; Object.keys(config.tasks).forEach((key) => { let val = config.tasks[key]; tasks.push(gulp.src(val.src) .pipe(cleanCSS({processImport: false})) .pipe(rename(config.rename)) .pipe(gulp.dest(val.dest))); }); return merge(tasks); }
javascript
{ "resource": "" }
q27470
initEmailForm
train
function initEmailForm() { var newsletterForm = document.getElementById('newsletter-form'); var submitButton = document.getElementById('newsletter-submit'); var formDetails = document.getElementById('newsletter-details'); var emailField = document.querySelector('.mzp-js-email-field'); var formExpanded = window.getComputedStyle(formDetails).display === 'none' ? false : true; function emailFormShowDetails() { if (!formExpanded) { formDetails.style.display = 'block'; formExpanded = true; } } emailField.addEventListener('focus', function() { emailFormShowDetails(); }); submitButton.addEventListener('click', function(e) { if (!formExpanded) { e.preventDefault(); emailFormShowDetails(); } }); newsletterForm.addEventListener('submit', function(e) { if (!formExpanded) { e.preventDefault(); emailFormShowDetails(); } }); }
javascript
{ "resource": "" }
q27471
copyJS
train
function copyJS() { let tasks = []; Object.keys(config).forEach((key) => { let val = config[key]; tasks.push(gulp.src(val.src).pipe(gulp.dest(val.dest))); }); return merge(tasks); }
javascript
{ "resource": "" }
q27472
concatJS
train
function concatJS() { let tasks = []; Object.keys(config).forEach((key) => { let val = config[key]; tasks.push(gulp.src(val.src) .pipe(plumber({ errorHandler: handleErrors })) .pipe(concat(key + '.js')) .pipe(gulp.dest(val.dest))); }); return merge(tasks); }
javascript
{ "resource": "" }
q27473
stripColons
train
function stripColons (str) { var colonIndex = str.indexOf(':'); if (colonIndex > -1) { // :emoji: (http://www.emoji-cheat-sheet.com/) if (colonIndex === str.length - 1) { str = str.substring(0, colonIndex); return stripColons(str); } else { str = str.substr(colonIndex + 1); return stripColons(str); } } return str; }
javascript
{ "resource": "" }
q27474
train
function() { if (!this.resolved) { throw new Error('Future must resolve before value is ready'); } else if (this.error) { // Link the stack traces up var error = this.error; var localStack = {}; Error.captureStackTrace(localStack, Future.prototype.get); var futureStack = Object.getOwnPropertyDescriptor(error, 'futureStack'); if (!futureStack) { futureStack = Object.getOwnPropertyDescriptor(error, 'stack'); if (futureStack) { Object.defineProperty(error, 'futureStack', futureStack); } } if (futureStack && futureStack.get) { Object.defineProperty(error, 'stack', { get: function() { var stack = futureStack.get.apply(error); if (stack) { stack = stack.split('\n'); return [stack[0]] .concat(localStack.stack.split('\n').slice(1)) .concat(' - - - - -') .concat(stack.slice(1)) .join('\n'); } else { return localStack.stack; } }, set: function(stack) { Object.defineProperty(error, 'stack', { value: stack, configurable: true, enumerable: false, writable: true, }); }, configurable: true, enumerable: false, }); } throw error; } else { return this.value; } }
javascript
{ "resource": "" }
q27475
train
function(value) { if (this.resolved) { throw new Error('Future resolved more than once'); } this.value = value; this.resolved = true; var callbacks = this.callbacks; if (callbacks) { delete this.callbacks; for (var ii = 0; ii < callbacks.length; ++ii) { try { var ref = callbacks[ii]; if (ref[1]) { ref[1](value); } else { ref[0](undefined, value); } } catch(ex) { // console.log('Resolve cb threw', String(ex.stack || ex.message || ex)); process.nextTick(function() { throw(ex); }); } } } }
javascript
{ "resource": "" }
q27476
train
function(error) { if (this.resolved) { throw new Error('Future resolved more than once'); } else if (!error) { throw new Error('Must throw non-empty error'); } this.error = error; this.resolved = true; var callbacks = this.callbacks; if (callbacks) { delete this.callbacks; for (var ii = 0; ii < callbacks.length; ++ii) { try { var ref = callbacks[ii]; if (ref[1]) { ref[0].throw(error); } else { ref[0](error); } } catch(ex) { // console.log('Resolve cb threw', String(ex.stack || ex.message || ex)); process.nextTick(function() { throw(ex); }); } } } }
javascript
{ "resource": "" }
q27477
train
function(arg1, arg2) { if (this.resolved) { if (arg2) { if (this.error) { arg1.throw(this.error); } else { arg2(this.value); } } else { arg1(this.error, this.value); } } else { (this.callbacks = this.callbacks || []).push([arg1, arg2]); } return this; }
javascript
{ "resource": "" }
q27478
train
function(futures) { this.resolve(function(err) { if (!err) { return; } if (futures instanceof Array) { for (var ii = 0; ii < futures.length; ++ii) { futures[ii].throw(err); } } else { futures.throw(err); } }); return this; }
javascript
{ "resource": "" }
q27479
train
function() { var that = this; return new Promise(function(resolve, reject) { that.resolve(function(err, val) { if (err) { reject(err); } else { resolve(val); } }); }); }
javascript
{ "resource": "" }
q27480
FiberFuture
train
function FiberFuture(fn, context, args) { this.fn = fn; this.context = context; this.args = args; this.started = false; var that = this; process.nextTick(function() { if (!that.started) { that.started = true; Fiber(function() { try { that.return(fn.apply(context, args)); } catch(e) { that.throw(e); } }).run(); } }); }
javascript
{ "resource": "" }
q27481
afterBuild
train
function afterBuild() { var targetPath = path.join(__dirname, 'build', debug ? 'Debug' : 'Release', 'fibers.node'); var installPath = path.join(__dirname, 'bin', modPath, 'fibers.node'); try { fs.mkdirSync(path.join(__dirname, 'bin', modPath)); } catch (ex) {} try { fs.statSync(targetPath); } catch (ex) { console.error('Build succeeded but target not found'); process.exit(1); } fs.renameSync(targetPath, installPath); console.log('Installed in `'+ installPath+ '`'); if (process.versions.electron) { process.nextTick(function() { require('electron').app.quit(); }); } }
javascript
{ "resource": "" }
q27482
isArray
train
function isArray (arr) { return Array.isArray ? Array.isArray(arr) : Object.prototype.toString.call(arr) === '[object Array]' }
javascript
{ "resource": "" }
q27483
train
function (info) { return Object.keys(info).reduce(function (escaped, key) { var ref = info.__dangerouslyDisableSanitizers; var isDisabled = ref && ref.indexOf(key) > -1; var val = info[key]; escaped[key] = val; if (key === '__dangerouslyDisableSanitizers') { return escaped } if (!isDisabled) { if (typeof val === 'string') { escaped[key] = escapeHTML(val); } else if (index$2$1(val)) { escaped[key] = escape(val); } else if (isArray(val)) { escaped[key] = val.map(escape); } else { escaped[key] = val; } } else { escaped[key] = val; } return escaped }, {}); }
javascript
{ "resource": "" }
q27484
VueMeta
train
function VueMeta (Vue, options) { if ( options === void 0 ) options = {}; // set some default options var defaultOptions = { keyName: VUE_META_KEY_NAME, attribute: VUE_META_ATTRIBUTE, ssrAttribute: VUE_META_SERVER_RENDERED_ATTRIBUTE, tagIDKeyName: VUE_META_TAG_LIST_ID_KEY_NAME }; // combine options options = index(defaultOptions, options); // bind the $meta method to this component instance Vue.prototype.$meta = _$meta(options); // store an id to keep track of DOM updates var batchID = null; // watch for client side component updates Vue.mixin({ beforeCreate: function beforeCreate () { // Add a marker to know if it uses metaInfo if (typeof this.$options[options.keyName] !== 'undefined') { this._hasMetaInfo = true; } // coerce function-style metaInfo to a computed prop so we can observe // it on creation if (typeof this.$options[options.keyName] === 'function') { if (typeof this.$options.computed === 'undefined') { this.$options.computed = {}; } this.$options.computed.$metaInfo = this.$options[options.keyName]; } }, created: function created () { var this$1 = this; // if computed $metaInfo exists, watch it for updates & trigger a refresh // when it changes (i.e. automatically handle async actions that affect metaInfo) // credit for this suggestion goes to [Sébastien Chopin](https://github.com/Atinux) if (this.$metaInfo) { this.$watch('$metaInfo', function () { // batch potential DOM updates to prevent extraneous re-rendering batchID = batchUpdate(batchID, function () { return this$1.$meta().refresh(); }); }); } }, activated: function activated () { var this$1 = this; if (this._hasMetaInfo) { // batch potential DOM updates to prevent extraneous re-rendering batchID = batchUpdate(batchID, function () { return this$1.$meta().refresh(); }); } }, deactivated: function deactivated () { var this$1 = this; if (this._hasMetaInfo) { // batch potential DOM updates to prevent extraneous re-rendering batchID = batchUpdate(batchID, function () { return this$1.$meta().refresh(); }); } }, beforeMount: function beforeMount () { var this$1 = this; // batch potential DOM updates to prevent extraneous re-rendering if (this._hasMetaInfo) { batchID = batchUpdate(batchID, function () { return this$1.$meta().refresh(); }); } }, destroyed: function destroyed () { var this$1 = this; // do not trigger refresh on the server side if (this.$isServer) { return } // re-render meta data when returning from a child component to parent if (this._hasMetaInfo) { // Wait that element is hidden before refreshing meta tags (to support animations) var interval = setInterval(function () { if (this$1.$el.offsetParent !== null) { return } clearInterval(interval); batchID = batchUpdate(batchID, function () { return this$1.$meta().refresh(); }); }, 50); } } }); }
javascript
{ "resource": "" }
q27485
encodeURIComponentPretty
train
function encodeURIComponentPretty (str) { return encodeURI(str).replace(/[\/?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) }
javascript
{ "resource": "" }
q27486
ansiHTML
train
function ansiHTML (text) { // Returns the text if the string has no ANSI escape code. if (!_regANSI.test(text)) { return text } // Cache opened sequence. var ansiCodes = [] // Replace with markup. var ret = text.replace(/\033\[(\d+)*m/g, function (match, seq) { var ot = _openTags[seq] if (ot) { // If current sequence has been opened, close it. if (!!~ansiCodes.indexOf(seq)) { // eslint-disable-line no-extra-boolean-cast ansiCodes.pop() return '</span>' } // Open tag. ansiCodes.push(seq) return ot[0] === '<' ? ot : '<span style="' + ot + ';">' } var ct = _closeTags[seq] if (ct) { // Pop sequence ansiCodes.pop() return ct } return '' }) // Make sure tags are closed. var l = ansiCodes.length ;(l > 0) && (ret += Array(l + 1).join('</span>')) return ret }
javascript
{ "resource": "" }
q27487
race$1
train
function race$1(entries) { /*jshint validthis:true */ var Constructor = this; if (!isArray(entries)) { return new Constructor(function (_, reject) { return reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function (resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } }
javascript
{ "resource": "" }
q27488
arrayEachRight
train
function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; }
javascript
{ "resource": "" }
q27489
arrayEvery
train
function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; }
javascript
{ "resource": "" }
q27490
baseFindKey
train
function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; }
javascript
{ "resource": "" }
q27491
baseIndexOfWith
train
function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; }
javascript
{ "resource": "" }
q27492
charsStartIndex
train
function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; }
javascript
{ "resource": "" }
q27493
charsEndIndex
train
function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; }
javascript
{ "resource": "" }
q27494
setToPairs
train
function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; }
javascript
{ "resource": "" }
q27495
lazyClone
train
function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; }
javascript
{ "resource": "" }
q27496
arraySampleSize
train
function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); }
javascript
{ "resource": "" }
q27497
baseConforms
train
function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; }
javascript
{ "resource": "" }
q27498
baseConformsTo
train
function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; }
javascript
{ "resource": "" }
q27499
baseFill
train
function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; }
javascript
{ "resource": "" }