_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q52800
startLine
train
function startLine (e) { e.preventDefault(); strokes = that.strokes; sketching = true; that.undos = []; var cursor = getCursorRelativeToCanvas(e); strokes.push({ points: [cursor], color: opts.line.color, size: getLineSizeRelativeToCanvas(opts.line.size), cap: opts.line.cap, join: opts.line.join, miterLimit: opts.line.miterLimit }); }
javascript
{ "resource": "" }
q52801
resolveFilename
train
function resolveFilename(fileName, cwd = process.cwd()) { try { const parent = new Module(); // eslint-disable-next-line no-underscore-dangle parent.paths = Module._nodeModulePaths(cwd); // eslint-disable-next-line no-underscore-dangle return Module._resolveFilename(fileName, parent); } catch (error) { if (error.code === "MODULE_NOT_FOUND") { console.warn(format("babel-plugin-direct-import: %s", error.message)); return null; } throw error; } }
javascript
{ "resource": "" }
q52802
handleError
train
function handleError(err) { let errMsg = err; if (err instanceof Object) { errMsg = err.message || err.error || JSON.stringify(err); } printColumns(chalk.red('Error: ' + errMsg)); printColumns( chalk.white( "If you can't settle this, please open an issue at:" + EOL + chalk.cyan(pkg.bugs.url) ) ); process.exit(1); }
javascript
{ "resource": "" }
q52803
printColumns
train
function printColumns(heading, data) { const columns = columnify(data, {}); const spacer = EOL + EOL; process.stdout.write(heading); process.stdout.write(spacer); if (columns) { process.stdout.write(columns); process.stdout.write(spacer); } }
javascript
{ "resource": "" }
q52804
getUserRules
train
function getUserRules(cosmiconfig) { const userConfig = cosmiconfig.config; const configPath = cosmiconfig.filepath; return ( Promise.resolve() // Handle `extends` .then(() => { // If `extends` is defined, use stylelint's extends resolver if (!_.isEmpty(userConfig.extends)) { // We need this to fetch and merge all `extends` from the provided config // This will also merge the `rules` on top of the `extends` rules const linter = stylelint.createLinter(); // stylelint used cosmiconfig v4 at version 9, bumped to v5 somewhere 9.x // So we pass both arguments to `load`, works in both versions return linter._extendExplorer.load(configPath, configPath); } }) .then(extendedConfig => { const finalConfig = extendedConfig ? extendedConfig.config : userConfig; rules.userRulesNames = _.sortedUniq(_.keys(finalConfig.rules)); }) ); }
javascript
{ "resource": "" }
q52805
findDeprecatedStylelintRules
train
function findDeprecatedStylelintRules() { if (!argv.deprecated && !argv.unused) { return Promise.resolve(); } const isDeprecatedPromises = _.map(rules.stylelintAll, isDDeprecated); return Promise.all(isDeprecatedPromises).then(rulesIsDeprecated => { rules.stylelintDeprecated = _.filter( rules.stylelintAll, (rule, index) => rulesIsDeprecated[index] ); // Don't remove, just for testing deprecated rules matching if (argv.testDeprecated) { rules.stylelintDeprecated.push('color-hex-case', 'color-hex-length'); } if (argv.unused) { rules.stylelintNoDeprecated = _.difference(rules.stylelintAll, rules.stylelintDeprecated); } return rules.stylelintDeprecated; }); }
javascript
{ "resource": "" }
q52806
printUserCurrent
train
function printUserCurrent() { if (!argv.current) { return; } const heading = chalk.blue.underline('CURRENT: Currently configured user rules:'); const rulesToPrint = _.map(rules.userRulesNames, rule => { return { rule, url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`) }; }); printColumns(heading, rulesToPrint); }
javascript
{ "resource": "" }
q52807
printAllAvailable
train
function printAllAvailable() { if (!argv.available) { return; } const heading = chalk.blue.underline('AVAILABLE: All available stylelint rules:'); const rulesToPrint = _.map(rules.stylelintAll, rule => { return { rule, url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`) }; }); printColumns(heading, rulesToPrint); }
javascript
{ "resource": "" }
q52808
printConfiguredUnavailable
train
function printConfiguredUnavailable() { if (!argv.invalid) { return; } const configuredUnavailable = _.difference(rules.userRulesNames, rules.stylelintAll); if (!configuredUnavailable.length) { return; } const heading = chalk.red.underline('INVALID: Configured rules that are no longer available:'); const rulesToPrint = _.map(configuredUnavailable, rule => { return { rule: chalk.redBright(rule) }; }); printColumns(heading, rulesToPrint); }
javascript
{ "resource": "" }
q52809
printUserDeprecated
train
function printUserDeprecated() { if (!argv.deprecated) { return; } const userDeprecated = _.intersection(rules.stylelintDeprecated, rules.userRulesNames); if (!userDeprecated.length) { return; } const heading = chalk.red.underline('DEPRECATED: Configured rules that are deprecated:'); const rulesToPrint = _.map(userDeprecated, rule => { return { rule: chalk.redBright(rule), url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`) }; }); printColumns(heading, rulesToPrint); }
javascript
{ "resource": "" }
q52810
printUserUnused
train
function printUserUnused() { if (!argv.unused) { return; } const userUnconfigured = _.difference(rules.stylelintNoDeprecated, rules.userRulesNames); let heading; if (!userUnconfigured.length) { heading = chalk.green('All rules are up-to-date!'); printColumns(heading); return; } const rulesToPrint = _.map(userUnconfigured, rule => { return { rule, url: chalk.cyan(`https://stylelint.io/user-guide/rules/${rule}/`) }; }); heading = chalk.blue.underline('UNUSED: Available rules that are not configured:'); printColumns(heading, rulesToPrint); }
javascript
{ "resource": "" }
q52811
printTimingAndExit
train
function printTimingAndExit(startTime) { const execTime = time() - startTime; printColumns(chalk.green(`Finished in: ${execTime.toFixed()}ms`)); process.exit(0); }
javascript
{ "resource": "" }
q52812
resolveModule
train
function resolveModule(module) { debug("resolveModule", module); const presetName = module; if (path.isAbsolute(presetName)) { return [getPresetName(module), module]; } try { // Try the naive way return [presetName, require.resolve(module)]; } catch (e) { // Try a more advanced way return [presetName, resolve.sync(process.cwd() + "/node_modules", module)]; } }
javascript
{ "resource": "" }
q52813
getPresetName
train
function getPresetName(file) { const packageJson = findUp.sync("package.json", { cwd: path.dirname(file) }); if (packageJson) { return require(packageJson).name || file; } return file; }
javascript
{ "resource": "" }
q52814
getOverrides
train
function getOverrides() { const configPath = path.join(process.cwd(), "crafty.config.js"); if (fs.existsSync(configPath)) { return require(configPath); } console.log(`No crafty.config.js found in '${process.cwd()}', proceeding...`); return {}; }
javascript
{ "resource": "" }
q52815
sortFiles
train
function sortFiles(files) { const modules = []; const assets = []; let isAssets = false; for (var i in files) { const row = files[i]; if (row[0] == "size" && row[2] == "asset") { isAssets = true; } if (row[0] == "size" || row[0] == "") { continue; } if (isAssets) { assets.push(row); } else { modules.push(row); } } const final = []; if (modules.length) { final.push(["size", "name", "module", "status"]); final.push(...modules.sort((a, b) => a[1] - b[1])); } if (modules.length && assets.length) { final.push(["", "", "", ""]); } if (assets.length) { final.push(["size", "name", "asset", "status"]); final.push( ...assets.sort((a, b) => { if (a[2] < b[2]) return -1; if (a[2] > b[2]) return 1; return 0; }) ); } // Replacing the file sizes in output log // to have predictable snapshot output // when testing Crafty. As webpack seems // to create differences in various environments // without differences in the actual output's size if (process.env.TESTING_CRAFTY) { return final.map(item => { if (item[0] != "" && item[0] != "size") { item[0] = 1000; } return item; }); } return final; }
javascript
{ "resource": "" }
q52816
updateMouse
train
function updateMouse(e) { input.mouse.clientX = e.clientX; input.mouse.clientY = e.clientY; input.mouse.buttons = e.buttons; if (e.type === 'mouseleave') input.mouse.mouseOnDocument = false; else input.mouse.mouseOnDocument = true; }
javascript
{ "resource": "" }
q52817
updateHybridMouse
train
function updateHybridMouse(e) { if (input.touch.recentTouch || input.touch.touchOnScreen) return; updateMouse(e); }
javascript
{ "resource": "" }
q52818
handleNotifyNext
train
function handleNotifyNext(e) { if (notifyOfNextSubs[e.type].length === 0) return; e.persist = blankFunction; const reNotifyOfNext = []; const reNotifyOfNextIDs = {}; notifyOfNextSubs[e.type].forEach(sub => { if (sub.callback(e) === 'reNotifyOfNext') { reNotifyOfNextIDs[sub.id] = reNotifyOfNext.push(sub) - 1; } }); notifyOfNextSubs[e.type] = reNotifyOfNext; subsIDs[e.type] = reNotifyOfNextIDs; }
javascript
{ "resource": "" }
q52819
setupEvent
train
function setupEvent(element, eType, handler, capture) { notifyOfNextSubs[eType] = []; subsIDs[eType] = {}; element.addEventListener( eType, handler, passiveEventSupport ? { capture, // don't set click listener as passive because syntheticClick may call preventDefault passive: eType !== 'click', } : capture, ); }
javascript
{ "resource": "" }
q52820
exists
train
function exists(fileOrDir) { let stats; try { stats = statSync(fileOrDir); return stats.isFile() || stats.isDirectory(); } catch (err) { return false; } }
javascript
{ "resource": "" }
q52821
findFileLocation
train
function findFileLocation(file) { let location = './'; while (true) { if (exists(location + file)) { break; } else if (exists(location + 'package.json') || location === '/') { // Assumption is that reaching the app root folder or the system '/' marks the end of the search throw new Error(`Failed to find file "${file}" within the project`); } // Go one level up location = path.resolve('../' + location) + '/'; } return location; }
javascript
{ "resource": "" }
q52822
drawLoop
train
function drawLoop () { ctx.clearRect(0, 0, canvas.width, canvas.height) var centerX = canvas.width / 2 var centerY = canvas.height / 2 // draw circle ctx.beginPath() ctx.arc(centerX, centerY, 100, 0, 2 * Math.PI, false) ctx.fillStyle = 'yellow' ctx.fill() // draw three oscilloscopes in different positions and colors ctx.strokeStyle = 'lime' scope.draw(ctx, 0, 0, centerX, centerY) ctx.strokeStyle = 'cyan' scope.draw(ctx, centerX, 0, centerX, centerY) ctx.strokeStyle = 'red' scope.draw(ctx, 0, centerY, null, centerY) window.requestAnimationFrame(drawLoop) }
javascript
{ "resource": "" }
q52823
ToggleAnimation
train
function ToggleAnimation (AppState) { var state = AppState.get() if ( state.currentAnimation[0] === animationDictionary.bend[0] && state.currentAnimation[1] === animationDictionary.bend[1] ) { state.currentAnimation = animationDictionary.jump } else { state.currentAnimation = animationDictionary.bend } AppState.set(state) }
javascript
{ "resource": "" }
q52824
compactXML
train
function compactXML (res, xml) { var txt = Object.keys(xml.attributes).length === 0 && xml.children.length === 0 var r = {} if (!res[xml.name]) res[xml.name] = [] if (txt) { r = xml.content || '' } else { r.$ = xml.attributes r._ = xml.content || '' xml.children.forEach(function (ch) { compactXML(r, ch) }) } res[xml.name].push(r) return res }
javascript
{ "resource": "" }
q52825
parseJoints
train
function parseJoints (node, parentJointName, accumulator) { accumulator = accumulator || {} node.forEach(function (joint) { accumulator[joint.$.sid] = accumulator[joint.$.sid] || {} // The bind pose of the matrix. We don't make use of this right now, but you would // use it to render a model in bind pose. Right now we only render the model based on // their animated joint positions, so we ignore this bind pose data accumulator[joint.$.sid].jointMatrix = joint.matrix[0]._.split(' ').map(Number) accumulator[joint.$.sid].parent = parentJointName if (joint.node) { parseJoints(joint.node, joint.$.sid, accumulator) } }) return accumulator }
javascript
{ "resource": "" }
q52826
createSandbox
train
function createSandbox(filename, socket) { var self = new EventEmitter; var listeners = new WeakMap; self.addEventListener = function (type, listener) { if (!listeners.has(listener)) { var facade = function (event) { if (!event.canceled) listener.apply(this, arguments); }; listeners.set(listener, facade); self.on(type, facade); } }; self.removeEventListener = function (type, listener) { self.removeListener(type, listeners.get(listener)); }; self.__filename = filename; self.__dirname = path.dirname(filename); self.postMessage = function postMessage(data) { message(socket, data); }; self.console = console; self.process = process; self.Buffer = Buffer; self.clearImmediate = clearImmediate; self.clearInterval = clearInterval; self.clearTimeout = clearTimeout; self.setImmediate = setImmediate; self.setInterval = setInterval; self.setTimeout = setTimeout; self.module = module; self.global = self; self.self = self; self.require = function (file) { switch (true) { case file === 'workway': return self.workway; case /^[./]/.test(file): file = path.resolve(self.__dirname, file); default: return require(file); } }; return self; }
javascript
{ "resource": "" }
q52827
error
train
function error(socket, err) { socket.emit(SECRET + ':error', { message: err.message, stack: cleanedStack(err.stack) }); }
javascript
{ "resource": "" }
q52828
findPluginPath
train
function findPluginPath(command) { if (command && /^\w+$/.test(command)) { try { return resolve.sync('nowa-' + command, { paths: moduleDirs }); } catch (e) { console.log(''); console.log(' ' + chalk.green.bold(command) + ' command is not installed.'); console.log(' You can try to install it by ' + chalk.blue.bold('nowa install ' + command) + '.'); console.log(''); } } }
javascript
{ "resource": "" }
q52829
loadDefaultOpts
train
function loadDefaultOpts(startDir, configFile) { try { return require(path.join(startDir, configFile)).options || {}; } catch (e) { var dir = path.dirname(startDir); if (dir === startDir) { return {}; } return loadDefaultOpts(dir, configFile); } }
javascript
{ "resource": "" }
q52830
explainSync
train
function explainSync (options) { options = new JsdocOptions(options) const ExplainSync = require('./lib/explain-sync') const command = new ExplainSync(options, exports.cache) return command.execute() }
javascript
{ "resource": "" }
q52831
explain
train
function explain (options) { options = new JsdocOptions(options) const Explain = require('./lib/explain') const command = new Explain(options, exports.cache) return command.execute() }
javascript
{ "resource": "" }
q52832
renderSync
train
function renderSync (options) { options = new JsdocOptions(options) const RenderSync = require('./lib/render-sync') const command = new RenderSync(options) return command.execute() }
javascript
{ "resource": "" }
q52833
addEvent
train
function addEvent(el, e, callback, capture) { if (el.addEventListener) { el.addEventListener(e, callback, capture || false); } else if (el.attachEvent) { el.attachEvent('on' + e, callback); } }
javascript
{ "resource": "" }
q52834
hasClass
train
function hasClass(el, className) { if (!el || !className) { return; } return (new RegExp('(^|\\s)' + className + '(\\s|$)').test(el.className)); }
javascript
{ "resource": "" }
q52835
removeClass
train
function removeClass(el, className) { if (!el || !className) { return; } el.className = el.className.replace(new RegExp('(?:^|\\s)' + className + '(?!\\S)'), ''); return el; }
javascript
{ "resource": "" }
q52836
getAttr
train
function getAttr(obj, attr) { if (!obj || !isset(obj)) { return false; } var ret; if (obj.getAttribute) { ret = obj.getAttribute(attr); } else if (obj.getAttributeNode) { ret = obj.getAttributeNode(attr).value; } if (isset(ret) && ret !== '') { return ret; } return false; }
javascript
{ "resource": "" }
q52837
clckHlpr
train
function clckHlpr(i) { addEvent(i, 'click', function (e) { stopPropagation(e); preventDefault(e); currGroup = getAttr(i, _const_dataattr + '-group') || false; currThumbnail = i; openBox(i, false, false, false); }, false); }
javascript
{ "resource": "" }
q52838
getByGroup
train
function getByGroup(group) { var arr = []; for (var i = 0; i < CTX.thumbnails.length; i++) { if (getAttr(CTX.thumbnails[i], _const_dataattr + '-group') === group) { arr.push(CTX.thumbnails[i]); } } return arr; }
javascript
{ "resource": "" }
q52839
getPos
train
function getPos(thumbnail, group) { var arr = getByGroup(group); for (var i = 0; i < arr.length; i++) { // compare elements if (getAttr(thumbnail, 'src') === getAttr(arr[i], 'src') && getAttr(thumbnail, _const_dataattr + '-index') === getAttr(arr[i], _const_dataattr + '-index') && getAttr(thumbnail, _const_dataattr) === getAttr(arr[i], _const_dataattr)) { return i; } } }
javascript
{ "resource": "" }
q52840
preload
train
function preload() { if (!currGroup) { return; } var prev = new Image(); var next = new Image(); var pos = getPos(currThumbnail, currGroup); if (pos === (currImages.length - 1)) { // last image in group, preload first image and the one before prev.src = getAttr(currImages[currImages.length - 1], _const_dataattr) || currImages[currImages.length - 1].src; next.src = getAttr(currImages[0].src, _const_dataattr) || currImages[0].src; } else if (pos === 0) { // first image in group, preload last image and the next one prev.src = getAttr(currImages[currImages.length - 1], _const_dataattr) || currImages[currImages.length - 1].src; next.src = getAttr(currImages[1], _const_dataattr) || currImages[1].src; } else { // in between, preload prev & next image prev.src = getAttr(currImages[pos - 1], _const_dataattr) || currImages[pos - 1].src; next.src = getAttr(currImages[pos + 1], _const_dataattr) || currImages[pos + 1].src; } }
javascript
{ "resource": "" }
q52841
startAnimation
train
function startAnimation() { if (isIE8) { return; } // stop any already running animations stopAnimation(); var fnc = function () { addClass(CTX.box, _const_class_prefix + '-loading'); if (!isIE9 && typeof CTX.opt.loadingAnimation === 'number') { var index = 0; animationInt = setInterval(function () { addClass(animationChildren[index], _const_class_prefix + '-active'); setTimeout(function () { removeClass(animationChildren[index], _const_class_prefix + '-active'); }, CTX.opt.loadingAnimation); index = index >= animationChildren.length ? 0 : index += 1; }, CTX.opt.loadingAnimation); } }; // set timeout to not show loading animation on fast connections animationTimeout = setTimeout(fnc, 500); }
javascript
{ "resource": "" }
q52842
stopAnimation
train
function stopAnimation() { if (isIE8) { return; } // hide animation-element removeClass(CTX.box, _const_class_prefix + '-loading'); // stop animation if (!isIE9 && typeof CTX.opt.loadingAnimation !== 'string' && CTX.opt.loadingAnimation) { clearInterval(animationInt); // do not use animationChildren.length here due to IE8/9 bugs for (var i = 0; i < animationChildren.length; i++) { removeClass(animationChildren[i], _const_class_prefix + '-active'); } } }
javascript
{ "resource": "" }
q52843
initControls
train
function initControls() { if (!nextBtn) { // create & append next-btn nextBtn = document.createElement('span'); addClass(nextBtn, _const_class_prefix + '-next'); // add custom images if (CTX.opt.nextImg) { var nextBtnImg = document.createElement('img'); nextBtnImg.setAttribute('src', CTX.opt.nextImg); nextBtn.appendChild(nextBtnImg); } else { addClass(nextBtn, _const_class_prefix + '-no-img'); } addEvent(nextBtn, 'click', function (e) { stopPropagation(e); // prevent closing of lightbox CTX.next(); }, false); CTX.box.appendChild(nextBtn); } addClass(nextBtn, _const_class_prefix + '-active'); if (!prevBtn) { // create & append next-btn prevBtn = document.createElement('span'); addClass(prevBtn, _const_class_prefix + '-prev'); // add custom images if (CTX.opt.prevImg) { var prevBtnImg = document.createElement('img'); prevBtnImg.setAttribute('src', CTX.opt.prevImg); prevBtn.appendChild(prevBtnImg); } else { addClass(prevBtn, _const_class_prefix + '-no-img'); } addEvent(prevBtn, 'click', function (e) { stopPropagation(e); // prevent closing of lightbox CTX.prev(); }, false); CTX.box.appendChild(prevBtn); } addClass(prevBtn, _const_class_prefix + '-active'); }
javascript
{ "resource": "" }
q52844
repositionControls
train
function repositionControls() { if (CTX.opt.responsive && nextBtn && prevBtn) { var btnTop = (getHeight() / 2) - (nextBtn.offsetHeight / 2); nextBtn.style.top = btnTop + 'px'; prevBtn.style.top = btnTop + 'px'; } }
javascript
{ "resource": "" }
q52845
resolveSrcString
train
function resolveSrcString(srcProperty) { if (Array.isArray(srcProperty)) { // handle multiple tag replacement return Promise.all(srcProperty.map(function (item) { return resolveSrcString(item); })); } else if (isStream(srcProperty)) { return new Promise(function (resolve, reject) { var strings = []; srcProperty.pipe(buffer()) .on('data', function (file) { strings.push(file.contents.toString()); }) .on('error', function(error) { reject(error); this.end(); }) .once('end', function () { resolve(strings); }); }); } else { return Promise.resolve(srcProperty); } }
javascript
{ "resource": "" }
q52846
type
train
function type(value) { let valueType = typeof value; if (Array.isArray(value)) { valueType = 'array'; } else if (value instanceof Date) { valueType = 'date'; } else if (value === null) { valueType = 'null'; } return valueType; }
javascript
{ "resource": "" }
q52847
Template
train
function Template(fn, parameters) { // Paul Brewer Dec 2017 add deduplication call, use only key property to eliminate Object.assign(fn, { parameters: dedupe(parameters, item => item.key) }); return fn; }
javascript
{ "resource": "" }
q52848
parseObject
train
function parseObject(object) { const children = Object.keys(object).map(key => ({ keyTemplate: parseString(key), valueTemplate: parse(object[key]) })); const templateParameters = children.reduce( (parameters, child) => parameters.concat(child.valueTemplate.parameters, child.keyTemplate.parameters), [] ); const templateFn = context => { return children.reduce((newObject, child) => { newObject[child.keyTemplate(context)] = child.valueTemplate(context); return newObject; }, {}); }; return Template(templateFn, templateParameters); }
javascript
{ "resource": "" }
q52849
parseArray
train
function parseArray(array) { const templates = array.map(parse); const templateParameters = templates.reduce( (parameters, template) => parameters.concat(template.parameters), [] ); const templateFn = context => templates.map(template => template(context)); return Template(templateFn, templateParameters); }
javascript
{ "resource": "" }
q52850
asBuffer
train
function asBuffer(data, encoding) { let result = data; if (!isNullOrUndefined(result)) { if ('object' !== typeof result) { // handle as string encoding = normalizeString(encoding); if (!encoding) { encoding = 'utf8'; } result = new Buffer(toStringSafe(result), encoding); } } return result; }
javascript
{ "resource": "" }
q52851
createSimplePromiseCompletedAction
train
function createSimplePromiseCompletedAction(resolve, reject) { return (err, result) => { if (err) { if (reject) { reject(err); } } else { if (resolve) { resolve(result); } } }; }
javascript
{ "resource": "" }
q52852
normalizeString
train
function normalizeString(val, normalizer) { if (!normalizer) { normalizer = (str) => str.toLowerCase().trim(); } return normalizer(toStringSafe(val)); }
javascript
{ "resource": "" }
q52853
readSocket
train
function readSocket(socket, numberOfBytes) { return new Promise((resolve, reject) => { let completed = createSimplePromiseCompletedAction(resolve, reject); try { let buff = socket.read(numberOfBytes); if (null === buff) { socket.once('readable', function () { readSocket(socket, numberOfBytes).then((b) => { completed(null, b); }, (err) => { completed(err); }); }); } else { completed(null, buff); } } catch (e) { completed(e); } }); }
javascript
{ "resource": "" }
q52854
listen
train
function listen(port, cb) { return new Promise((resolve, reject) => { let completed = ssocket_helpers.createSimplePromiseCompletedAction(resolve, reject); try { let serverToClient; let server = Net.createServer((connectionWithClient) => { try { if (cb) { cb(null, createServer(connectionWithClient)); } } catch (e) { if (cb) { cb(e); } } }); let isListening = false; server.once('error', (err) => { if (!isListening && err) { completed(err); } }); server.on('listening', () => { isListening = true; completed(null, server); }); server.listen(port); } catch (e) { completed(e); } }); }
javascript
{ "resource": "" }
q52855
read
train
async function read(filename, options = undefined) { const {encoding, flag, ...opts} = normalizeOptions(options) if (!isNumber(filename)) { filename = await normalizePath(base, filename) opts.filename = filename } const content = await fs.readFile(filename, {encoding, flag}) return yaml.load(content, opts) }
javascript
{ "resource": "" }
q52856
write
train
async function write(filename, object, options = undefined) { const {encoding, flag, ...opts} = normalizeOptions(options) if (!isNumber(filename)) { filename = toAbsolute(base, filename) opts.filename = filename } await fs.writeFile(filename, yaml.dump(object, opts), {encoding, flag}) }
javascript
{ "resource": "" }
q52857
exposeBundles
train
function exposeBundles(b){ b.add("./" + packageConfig.main, {expose: packageConfig.name }); if(packageConfig.sniper !== undefined && packageConfig.sniper.exposed !== undefined){ for(var i=0; i<packageConfig.sniper.exposed.length; i++){ b.require(packageConfig.sniper.exposed[i]); } } }
javascript
{ "resource": "" }
q52858
mkdirSync
train
function mkdirSync(root, mode) { if (typeof root !== 'string') { throw new Error('missing root'); } var chunks = root.split(path.sep); // split in chunks var chunk; if (path.isAbsolute(root) === true) { // build from absolute path chunk = chunks.shift(); // remove "/" or C:/ if (!chunk) { // add "/" chunk = path.sep; } } else { chunk = path.resolve(); // build with relative path } return mkdirSyncRecursive(chunk, chunks, mode); }
javascript
{ "resource": "" }
q52859
rmdir
train
function rmdir(root, callback) { if (typeof root !== 'string') { throw new Error('missing root'); } else if (typeof callback !== 'function') { throw new Error('missing callback'); } var chunks = root.split(path.sep); // split in chunks var chunk = path.resolve(root); // build absolute path // remove "/" from head and tail if (chunks[0] === '') { chunks.shift(); } if (chunks[chunks.length - 1] === '') { chunks.pop(); } return rmdirRecursive(chunk, chunks, callback); }
javascript
{ "resource": "" }
q52860
rmdirSync
train
function rmdirSync(root) { if (typeof root !== 'string') { throw new Error('missing root'); } var chunks = root.split(path.sep); // split in chunks var chunk = path.resolve(root); // build absolute path // remove "/" from head and tail if (chunks[0] === '') { chunks.shift(); } if (chunks[chunks.length - 1] === '') { chunks.pop(); } return rmdirSyncRecursive(chunk, chunks); }
javascript
{ "resource": "" }
q52861
mkdirSyncRecursive
train
function mkdirSyncRecursive(root, chunks, mode) { var chunk = chunks.shift(); if (!chunk) { return; } var root = path.join(root, chunk); if (fs.existsSync(root) === true) { // already done return mkdirSyncRecursive(root, chunks, mode); } var err = fs.mkdirSync(root, mode); return err ? err : mkdirSyncRecursive(root, chunks, mode); // let's magic }
javascript
{ "resource": "" }
q52862
rmdirRecursive
train
function rmdirRecursive(root, chunks, callback) { var chunk = chunks.pop(); if (!chunk) { return callback(null); } var pathname = path.join(root, '..'); // backtrack return fs.exists(root, function(exists) { if (exists === false) { // already done return rmdirRecursive(root, chunks, callback); } return fs.rmdir(root, function(err) { if (err) { return callback(err); } return rmdirRecursive(pathname, chunks, callback); // let's magic }); }); }
javascript
{ "resource": "" }
q52863
rmdirSyncRecursive
train
function rmdirSyncRecursive(root, chunks) { var chunk = chunks.pop(); if (!chunk) { return; } var pathname = path.join(root, '..'); // backtrack if (fs.existsSync(root) === false) { // already done return rmdirSyncRecursive(root, chunks); } var err = fs.rmdirSync(root); return err ? err : rmdirSyncRecursive(pathname, chunks); // let's magic }
javascript
{ "resource": "" }
q52864
interval
train
function interval(prop) { // create a function that will use the intervals to check the group by property return function(intervals) { // create custom labels to use for the resulting object keys var labels = intervals.reduce(function(acc, val, i) { var min = val; var max = (intervals[i + 1] && intervals[i + 1] - 1) || '*'; acc[val] = min + ' - ' + max; return acc; }, {}); // create a function that does the grouping for each item return function(item) { // value to group by var val = item[prop]; // if the value falls between the interval range, return it // as an array to make the interval value the key being grouped by return intervals.filter(function(int, i) { var min = int; var max = intervals[i+1] || Infinity; return min <= val && val < max; }).map(function(int) { return labels[int]; }); }; }; }
javascript
{ "resource": "" }
q52865
inferSiderbars
train
function inferSiderbars () { // You will need to update this config when directory was added or removed. const sidebars = [ // { title: 'JavaScript', dirname: 'javascript' }, // { title: 'CSS', dirname: 'css' }, ] return sidebars.map(({ title, dirname }) => { const dirpath = path.resolve(__dirname, '../' + dirname) return { title, collapsable: false, children: fs .readdirSync(dirpath) .filter(item => item.endsWith('.md') && fs.statSync(path.join(dirpath, item)).isFile()) .map(item => dirname + '/' + item.replace(/(README)?(.md)$/, '')) } }) }
javascript
{ "resource": "" }
q52866
getBuildingConfigs
train
function getBuildingConfigs (target) { return target.map(({ dirname, name, version, entry, outDir, styleFilename }) => { return formats.map(format => { return { inputOptions: getInputOptions({ entry, outDir, styleFilename }), outputOptions: getOutputOptions({ outDir, name, version, format }) } }) }).reduce((prev, next) => prev.concat(next)) }
javascript
{ "resource": "" }
q52867
save
train
function save(str) { let result = {}; console.log('Writing data...'); str.split(/\r?\n/g) .filter(line => line.length && line[0] !== '#') .forEach(line => { if (line.split(';').length < 2) return; let [ src, dst ] = line.split(';').slice(0, 2).map(s => s.trim()); src = String.fromCodePoint(parseInt(src, 16)); dst = dst .replace(/\s+/g, ' ') .split(' ') .map(code => !code ? '' : String.fromCodePoint(parseInt(code, 16))) .join(''); result[src] = dst; }); fs.writeFileSync(SAVE_PATH, JSON.stringify(result, null, ' ')); console.log('Done!'); }
javascript
{ "resource": "" }
q52868
restartProcessing
train
function restartProcessing (q) { logger('restartProcessing') setTimeout(function randomRestart () { queueProcess.restart(q) }, Math.floor(Math.random() * 1000)) }
javascript
{ "resource": "" }
q52869
unicodeStringToTypedArray
train
function unicodeStringToTypedArray(s) { var escstr = encodeURIComponent(s); var binstr = escstr.replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); }); var ua = new Uint8Array(binstr.length); Array.prototype.forEach.call(binstr, function (ch, i) { ua[i] = ch.charCodeAt(0); }); return ua; }
javascript
{ "resource": "" }
q52870
typedArrayToUnicodeString
train
function typedArrayToUnicodeString(ua) { var binstr = Array.prototype.map.call(ua, function (ch) { return String.fromCharCode(ch); }).join(''); var escstr = binstr.replace(/(.)/g, function (m, p) { var code = p.charCodeAt(p).toString(16).toUpperCase(); if (code.length < 2) { code = '0' + code; } return '%' + code; }); return decodeURIComponent(escstr); }
javascript
{ "resource": "" }
q52871
setup
train
function setup(config, options) { const rule = config.module.rule("svg"); // Find the svg rule /* * Let's use the file loader option defaults for the svg loader again. Otherwise * we'll have to set our own and it's no longer consistent with the changing * vue-cli. */ const fileLoaderOptions = rule.use("file-loader").get("options"); // Get the file loader options options.external = _.merge(fileLoaderOptions, options.external); // Make sure we save the file loader options // Use file loader options for sprite name options.sprite = _.merge( { spriteFilename: fileLoaderOptions.name }, options.sprite ); rule.uses.clear(); // Clear out existing uses of the svg rule const query = parseResourceQuery(options); // Get the resource queries rule .oneOf("inline") .resourceQuery(query.inline) .use("vue-svg-loader") .loader("vue-svg-loader") .options(options.inline); rule .oneOf("sprite") .resourceQuery(query.sprite) .use("svg-sprite-loader") .loader("svg-sprite-loader") .options(options.sprite); rule .oneOf("data") .resourceQuery(query.data) .use("url-loader") .loader("url-loader") .options(options.data); rule .oneOf("external") .use("file-loader") .loader("file-loader") .options(options.external); }
javascript
{ "resource": "" }
q52872
parseResourceQuery
train
function parseResourceQuery(options) { const query = {}; for (option in options) { if (!options[option].resourceQuery) continue; // Skip if no query query[option] = options[option].resourceQuery; // Get the query delete options[option].resourceQuery; // Delete the field (to prevent passing it as a loader option) } return query; }
javascript
{ "resource": "" }
q52873
slideTo
train
function slideTo(newPos, immediate) { // Align items if (itemNav && dragging.released) { var tempRel = getRelatives(newPos), isDetached = newPos > pos.start && newPos < pos.end; if (centeredNav) { if (isDetached) { newPos = items[tempRel.centerItem].center; } if (forceCenteredNav) { self.activate(tempRel.centerItem, 1); } } else if (isDetached) { newPos = items[tempRel.firstItem].start; } } // Handle overflowing position limits if (!dragging.released && dragging.source === 'slidee' && o.elasticBounds) { if (newPos > pos.end) { newPos = pos.end + (newPos - pos.end) / 6; } else if (newPos < pos.start) { newPos = pos.start + (newPos - pos.start) / 6; } } else { newPos = within(newPos, pos.start, pos.end); } // Update the animation object animation.start = +new Date(); animation.time = 0; animation.from = pos.cur; animation.to = newPos; animation.delta = newPos - pos.cur; animation.immediate = immediate; // Attach animation destination pos.dest = newPos; // Reset next cycle timeout resetCycle(); // Synchronize states updateRelatives(); updateNavButtonsState(); syncPagesbar(); // Render the animation if (newPos !== pos.cur) { trigger('change'); if (!renderID) { render(); } } }
javascript
{ "resource": "" }
q52874
render
train
function render() { // If first render call, wait for next animationFrame if (!renderID) { renderID = rAF(render); if (dragging.released) { trigger('moveStart'); } return; } // If immediate repositioning is requested, SLIDEE is being dragged, or animation duration would take // less than 2 frames, don't animate if (animation.immediate || (!dragging.released ? dragging.source === 'slidee' : o.speed < 33)) { pos.cur = animation.to; } // Use tweesing for animations without known end point else if (!dragging.released && dragging.source === 'handle') { pos.cur += (animation.to - pos.cur) * o.syncFactor; } // Use tweening for basic animations with known end point else { animation.time = Math.min(+new Date() - animation.start, o.speed); pos.cur = animation.from + animation.delta * jQuery.easing[o.easing](animation.time/o.speed, animation.time, 0, 1, o.speed); } // If there is nothing more to render (animation reached the end, or dragging has been released), // break the rendering loop, otherwise request another animation frame if (animation.to === Math.round(pos.cur) && (!dragging.released || animation.time >= o.speed)) { pos.cur = pos.dest; renderID = 0; } else { renderID = rAF(render); } trigger('move'); // Update SLIDEE position if (!parallax) { if (transform) { $slidee[0].style[transform] = gpuAcceleration + (o.horizontal ? 'translateX' : 'translateY') + '(' + (-pos.cur) + 'px)'; } else { $slidee[0].style[o.horizontal ? 'left' : 'top'] = -Math.round(pos.cur) + 'px'; } } // When animation reached the end, and dragging is not active, trigger moveEnd if (!renderID && dragging.released) { trigger('moveEnd'); } syncScrollbar(); }
javascript
{ "resource": "" }
q52875
syncScrollbar
train
function syncScrollbar() { if ($handle) { hPos.cur = pos.start === pos.end ? 0 : (((!dragging.released && dragging.source === 'handle') ? pos.dest : pos.cur) - pos.start) / (pos.end - pos.start) * hPos.end; hPos.cur = within(Math.round(hPos.cur), hPos.start, hPos.end); if (last.hPos !== hPos.cur) { last.hPos = hPos.cur; if (transform) { $handle[0].style[transform] = gpuAcceleration + (o.horizontal ? 'translateX' : 'translateY') + '(' + hPos.cur + 'px)'; } else { $handle[0].style[o.horizontal ? 'left' : 'top'] = hPos.cur + 'px'; } } } }
javascript
{ "resource": "" }
q52876
syncPagesbar
train
function syncPagesbar() { if ($pages[0] && last.page !== rel.activePage) { last.page = rel.activePage; $pages.removeClass(o.activeClass).eq(rel.activePage).addClass(o.activeClass); } }
javascript
{ "resource": "" }
q52877
to
train
function to(location, item, immediate) { // Optional arguments logic if (typeof item === 'boolean') { immediate = item; item = undefined; } if (item === undefined) { slideTo(pos[location]); } else { // You can't align items to sides of the frame // when centered navigation type is enabled if (centeredNav && location !== 'center') { return; } var itemPos = self.getPos(item); if (itemPos) { slideTo(itemPos[location], immediate); } } }
javascript
{ "resource": "" }
q52878
getIndex
train
function getIndex(item) { return isNumber(item) ? within(item, 0, items.length - 1) : item === undefined ? -1 : $items.index(item); }
javascript
{ "resource": "" }
q52879
getRelatives
train
function getRelatives(slideePos) { slideePos = within(isNumber(slideePos) ? slideePos : pos.dest, pos.start, pos.end); var relatives = {}, centerOffset = forceCenteredNav ? 0 : frameSize / 2; // Determine active page if (!parallax) { for (var p = 0, pl = pages.length; p < pl; p++) { if (slideePos >= pos.end || p === pages.length - 1) { relatives.activePage = pages.length - 1; break; } if (slideePos <= pages[p] + centerOffset) { relatives.activePage = p; break; } } } // Relative item indexes if (itemNav) { var first = false, last = false, center = false; // From start for (var i = 0, il = items.length; i < il; i++) { // First item if (first === false && slideePos <= items[i].start) { first = i; } // Centered item if (center === false && slideePos - items[i].size / 2 <= items[i].center) { center = i; } // Last item if (i === items.length - 1 || (last === false && slideePos < items[i + 1].end)) { last = i; } // Terminate if all are assigned if (last !== false) { break; } } // Safe assignment, just to be sure the false won't be returned relatives.firstItem = isNumber(first) ? first : 0; relatives.centerItem = isNumber(center) ? center : relatives.firstItem; relatives.lastItem = isNumber(last) ? last : relatives.centerItem; } return relatives; }
javascript
{ "resource": "" }
q52880
updateNavButtonsState
train
function updateNavButtonsState() { // Item navigation if (itemNav) { var isFirst = rel.activeItem === 0, isLast = rel.activeItem >= items.length - 1, itemsButtonState = isFirst ? 'first' : isLast ? 'last' : 'middle'; if (last.itemsButtonState !== itemsButtonState) { last.itemsButtonState = itemsButtonState; if ($prevButton.is('button,input')) { $prevButton.prop('disabled', isFirst); } if ($nextButton.is('button,input')) { $nextButton.prop('disabled', isLast); } $prevButton[isFirst ? 'removeClass' : 'addClass'](o.disabledClass); $nextButton[isLast ? 'removeClass' : 'addClass'](o.disabledClass); } } // Page navigation if ($pages[0]) { var isStart = pos.dest <= pos.start, isEnd = pos.dest >= pos.end, pagesButtonState = isStart ? 'first' : isEnd ? 'last' : 'middle'; // Update paging buttons only if there has been a change in their state if (last.pagesButtonState !== pagesButtonState) { last.pagesButtonState = pagesButtonState; if ($prevPageButton.is('button,input')) { $prevPageButton.prop('disabled', isStart); } if ($nextPageButton.is('button,input')) { $nextPageButton.prop('disabled', isEnd); } $prevPageButton[isStart ? 'removeClass' : 'addClass'](o.disabledClass); $nextPageButton[isEnd ? 'removeClass' : 'addClass'](o.disabledClass); } } }
javascript
{ "resource": "" }
q52881
handleToSlidee
train
function handleToSlidee(handlePos) { return Math.round(within(handlePos, hPos.start, hPos.end) / hPos.end * (pos.end - pos.start)) + pos.start; }
javascript
{ "resource": "" }
q52882
dragInit
train
function dragInit(event) { var isTouch = event.type === 'touchstart', source = event.data.source, isSlidee = source === 'slidee'; // Ignore other than left mouse button if (isTouch || event.which <= 1) { stopDefault(event); // Update a dragging object dragging.source = source; dragging.$source = $(event.target); dragging.init = 0; dragging.released = 0; dragging.touch = isTouch; dragging.initLoc = (isTouch ? event.originalEvent.touches[0] : event)[o.horizontal ? 'pageX' : 'pageY']; dragging.initPos = isSlidee ? pos.cur : hPos.cur; dragging.start = +new Date(); dragging.time = 0; dragging.path = 0; dragging.pathMin = isSlidee ? -dragging.initLoc : -hPos.cur; dragging.pathMax = isSlidee ? document[o.horizontal ? 'width' : 'height'] - dragging.initLoc : hPos.end - hPos.cur; // Add dragging class (isSlidee ? $slidee : $handle).addClass(o.draggedClass); // Bind dragging events $doc.on(isTouch ? dragTouchEvents : dragMouseEvents, dragHandler); } }
javascript
{ "resource": "" }
q52883
dragHandler
train
function dragHandler(event) { dragging.released = event.type === 'mouseup' || event.type === 'touchend'; dragging.path = within( (dragging.touch ? event.originalEvent[dragging.released ? 'changedTouches' : 'touches'][0] : event)[o.horizontal ? 'pageX' : 'pageY'] - dragging.initLoc, dragging.pathMin, dragging.pathMax ); // Initialization if (!dragging.init && (Math.abs(dragging.path) > (dragging.touch ? 50 : 10) || dragging.source === 'handle')) { dragging.init = 1; if (dragging.source === 'slidee') { ignoreNextClick = 1; } // Pause ongoing cycle self.pause(1); // Disable click actions on source element, as they are unwelcome when dragging dragging.$source.on('click', function disableAction(event) { stopDefault(event, 1); if (dragging.source === 'slidee') { ignoreNextClick = 0; } dragging.$source.off('click', disableAction); }); // Trigger moveStart event trigger('moveStart'); } // Proceed when initialized if (dragging.init) { stopDefault(event); // Adjust path with a swing on mouse release if (dragging.released && dragging.source === 'slidee' && o.speed > 33) { dragging.path += dragging.path * 200 / (+new Date() - dragging.start); } slideTo(dragging.source === 'slidee' ? Math.round(dragging.initPos - dragging.path) : handleToSlidee(dragging.initPos + dragging.path)); } // Cleanup and trigger :moveEnd event on release if (dragging.released) { $doc.off(dragging.touch ? dragTouchEvents : dragMouseEvents, dragHandler); (dragging.source === 'slidee' ? $slidee : $handle).removeClass(o.draggedClass); // Account for item snapping position adjustment. if (pos.cur === pos.dest) { trigger('moveEnd'); } } }
javascript
{ "resource": "" }
q52884
trigger
train
function trigger(name, arg1, arg2, arg3, arg4) { // Common arguments for events switch (name) { case 'active': arg2 = arg1; arg1 = $items; break; case 'activePage': arg2 = arg1; arg1 = pages; break; default: arg4 = arg1; arg1 = pos; arg2 = $items; arg3 = rel; } if (callbacks[name]) { for (var i = 0, l = callbacks[name].length; i < l; i++) { callbacks[name][i].call(frame, arg1, arg2, arg3, arg4); } } if (o.domEvents && !parallax) { $frame.trigger(pluginName + ':' + name, [arg1, arg2, arg3, arg4]); } }
javascript
{ "resource": "" }
q52885
stopDefault
train
function stopDefault(event, noBubbles) { event = event || w.event; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } if (noBubbles) { if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } } }
javascript
{ "resource": "" }
q52886
shouldReplace
train
function shouldReplace(svg, cssPath, newCssContent) { try { fs.accessSync(svg.path, fs.constants ? fs.constants.R_OK : fs.R_OK); fs.accessSync(cssPath, fs.constants ? fs.constants.R_OK : fs.R_OK); } catch(e) { return true; } const oldSvg = fs.readFileSync(svg.path).toString(); const newSvg = svg.contents.toString(); const oldCss = fs.readFileSync(cssPath).toString(); const svgDifferent = oldSvg !== newSvg; // returns true if new SVG is different const cssDifferent = oldCss !== newCssContent; // returns true if new SCSS is different // only rerender if svgs or scss are different return svgDifferent || cssDifferent ? true : false; }
javascript
{ "resource": "" }
q52887
train
function(expr, msg, negatedMsg, expected, showDiff){ var msg = this.negate ? negatedMsg : msg , ok = this.negate ? !expr : expr , obj = this.obj; if (ok) return; var err = new AssertionError({ message: msg.call(this) , actual: obj , expected: expected , stackStartFunction: this.assert , negated: this.negate }); err.showDiff = showDiff; throw err; }
javascript
{ "resource": "" }
q52888
train
function(val, desc){ this.assert( eql(val, this.obj) , function(){ return 'expected ' + this.inspect + ' to equal ' + i(val) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not equal ' + i(val) + (desc ? " | " + desc : "") } , val , true); return this; }
javascript
{ "resource": "" }
q52889
train
function(val, desc){ this.assert( val.valueOf() === this.obj , function(){ return 'expected ' + this.inspect + ' to equal ' + i(val) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not equal ' + i(val) + (desc ? " | " + desc : "") } , val); return this; }
javascript
{ "resource": "" }
q52890
train
function(type, desc){ this.assert( type == typeof this.obj , function(){ return 'expected ' + this.inspect + ' to be a ' + type + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' not to be a ' + type + (desc ? " | " + desc : "") }) return this; }
javascript
{ "resource": "" }
q52891
train
function(constructor, desc){ var name = constructor.name; this.assert( this.obj instanceof constructor , function(){ return 'expected ' + this.inspect + ' to be an instance of ' + name + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' not to be an instance of ' + name + (desc ? " | " + desc : "") }); return this; }
javascript
{ "resource": "" }
q52892
train
function(n, desc){ this.assert( this.obj > n , function(){ return 'expected ' + this.inspect + ' to be above ' + n + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to be below ' + n + (desc ? " | " + desc : "") }); return this; }
javascript
{ "resource": "" }
q52893
train
function(regexp, desc){ this.assert( regexp.exec(this.obj) , function(){ return 'expected ' + this.inspect + ' to match ' + regexp + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' not to match ' + regexp + (desc ? " | " + desc : "") }); return this; }
javascript
{ "resource": "" }
q52894
train
function(n, desc){ this.obj.should.have.property('length'); var len = this.obj.length; this.assert( n == len , function(){ return 'expected ' + this.inspect + ' to have a length of ' + n + ' but got ' + len + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have a length of ' + len + (desc ? " | " + desc : "") }); return this; }
javascript
{ "resource": "" }
q52895
train
function(name, val, desc){ if (this.negate && undefined !== val) { if (undefined === this.obj[name]) { throw new Error(this.inspect + ' has no property ' + i(name) + (desc ? " | " + desc : "")); } } else { this.assert( undefined !== this.obj[name] , function(){ return 'expected ' + this.inspect + ' to have a property ' + i(name) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have a property ' + i(name) + (desc ? " | " + desc : "") }); } if (undefined !== val) { this.assert( val === this.obj[name] , function(){ return 'expected ' + this.inspect + ' to have a property ' + i(name) + ' of ' + i(val) + ', but got ' + i(this.obj[name]) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have a property ' + i(name) + ' of ' + i(val) + (desc ? " | " + desc : "") }); } this.obj = this.obj[name]; return this; }
javascript
{ "resource": "" }
q52896
train
function(name, desc){ this.assert( this.obj.hasOwnProperty(name) , function(){ return 'expected ' + this.inspect + ' to have own property ' + i(name) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not have own property ' + i(name) + (desc ? " | " + desc : "") }); this.obj = this.obj[name]; return this; }
javascript
{ "resource": "" }
q52897
train
function(obj, desc){ this.assert( this.obj.some(function(item) { return eql(obj, item); }) , function(){ return 'expected ' + this.inspect + ' to include an object equal to ' + i(obj) + (desc ? " | " + desc : "") } , function(){ return 'expected ' + this.inspect + ' to not include an object equal to ' + i(obj) + (desc ? " | " + desc : "") }); return this; }
javascript
{ "resource": "" }
q52898
train
function(obj){ console.warn('should.contain() is deprecated, use should.include()'); this.obj.should.be.an.instanceof(Array); this.assert( ~this.obj.indexOf(obj) , function(){ return 'expected ' + this.inspect + ' to contain ' + i(obj) } , function(){ return 'expected ' + this.inspect + ' to not contain ' + i(obj) }); return this; }
javascript
{ "resource": "" }
q52899
train
function(field, val){ this.obj.should .have.property('headers').and .have.property(field.toLowerCase(), val); return this; }
javascript
{ "resource": "" }