_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q63200
Connection
test
function Connection(socket, parent) { logger('new Connection to %s', parent.type); this.id = uuid(); this.socket = socket; this.parent = parent; this.responseHandlers = {}; if (this.parent.browser) { this.socket.onmessage = this.message.bind(this); this.socket.onclose = socketClosed.bind(this); this.socket.onerror = socketError.bind(this); } else { this.socket.on('message', this.message.bind(this)); this.socket.once('close', this.close.bind(this)); this.socket.once('error', this.close.bind(this)); } }
javascript
{ "resource": "" }
q63201
mark
test
function mark(type, attrs) { return function(...args) { let mark = type.create(takeAttrs(attrs, args)) let {nodes, tag} = flatten(type.schema, args, n => mark.type.isInSet(n.marks) ? n : n.mark(mark.addToSet(n.marks))) return {flat: nodes, tag} } }
javascript
{ "resource": "" }
q63202
serverRequest
test
function serverRequest(config) { var defer = $q.defer(); if (provider.debug) $log.info('$sails ' + config.method + ' ' + config.url, config.data || ''); if (config.timeout > 0) { $timeout(timeoutRequest, config.timeout); } else if (isPromiseLike(config.timeout)) { config.timeout.then(timeoutRequest); } socket['legacy_' + config.method.toLowerCase()](config.url, config.data, serverResponse); function timeoutRequest(){ serverResponse(null); } function serverResponse(result, jwr) { if (!jwr) { jwr = { body: result, headers: result.headers || {}, statusCode: result.statusCode || result.status || 0, error: (function() { if (this.statusCode < 200 || this.statusCode >= 400) { return this.body || this.statusCode; } })() }; } jwr.data = jwr.body; // $http compat jwr.status = jwr.statusCode; // $http compat jwr.socket = socket; jwr.url = config.url; jwr.method = config.method; jwr.config = config.config; if (jwr.error) { if (provider.debug) $log.warn('$sails response ' + jwr.statusCode + ' ' + config.url, jwr); defer.reject(jwr); } else { if (provider.debug) $log.info('$sails response ' + config.url, jwr); defer.resolve(jwr); } } return defer.promise; }
javascript
{ "resource": "" }
q63203
processBootStrap
test
function processBootStrap(file) { var data = fs.readFileSync(file).toString(); var idx = data.indexOf('bootstrap('); if (idx === -1) { return null; } else { idx+=10; } var odx1 = data.indexOf(',', idx); var odx2 = data.indexOf(')', idx); if (odx2 < odx1 && odx2 !== -1 || odx1 === -1) { odx1 = odx2; } if (odx1 === -1) { return null; } var componentRef = data.substring(idx, odx1); var exp = "import\\s+\\{("+componentRef+")\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]"; if (debugging) { console.log("Searching for", exp); } var result = function (r) { return { name: r[1], path: r[r.length - 1] }; }; //noinspection JSPotentiallyInvalidConstructorUsage var r = RegExp(exp, 'i').exec(data); if (r === null || r.length <= 1) { // check if using current style guide with spaces exp = "import\\s+\\{\\s+("+componentRef+")\\,\\s+([A-Z]{0,300})\\w+\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]"; if (debugging) { console.log("Searching for", exp); } r = RegExp(exp, 'i').exec(data); if (r === null || r.length <= 1) { // try just spaces with no angular cli style (, environment) etc. exp = "import\\s+\\{\\s+(" + componentRef + ")\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]"; if (debugging) { console.log("Searching for", exp); } r = RegExp(exp, 'i').exec(data); if (r !== null && r.length > 1) { return result(r); } } else { // angular cli return result(r); } return null; } return result(r); }
javascript
{ "resource": "" }
q63204
fixTsConfig
test
function fixTsConfig() { var tsConfig={}, tsFile = '../../tsconfig.json'; if (fs.existsSync(tsFile)) { tsConfig = require(tsFile); } if (!tsConfig.compilerOptions || !tsConfig.compilerOptions.typeRoots) { tsConfig.compilerOptions = { target: "es5", module: "commonjs", declaration: false, removeComments: true, noLib: false, emitDecoratorMetadata: true, experimentalDecorators: true, lib: [ "dom" ], sourceMap: true, pretty: true, allowUnreachableCode: false, allowUnusedLabels: false, noImplicitAny: false, noImplicitReturns: true, noImplicitUseStrict: false, noFallthroughCasesInSwitch: true, typeRoots: [ "node_modules/@types", "node_modules" ], types: [ "jasmine" ] }; } // See: https://github.com/NativeScript/nativescript-angular/issues/205 // tsConfig.compilerOptions.noEmitHelpers = false; // tsConfig.compilerOptions.noEmitOnError = false; if (!tsConfig.exclude) { tsConfig.exclude = []; } if (tsConfig.exclude.indexOf('node_modules') === -1) { tsConfig.exclude.push('node_modules'); } if (tsConfig.exclude.indexOf('platforms') === -1) { tsConfig.exclude.push('platforms'); } fs.writeFileSync(tsFile, JSON.stringify(tsConfig, null, 4), 'utf8'); }
javascript
{ "resource": "" }
q63205
fixRefFile
test
function fixRefFile() { var existingRef='', refFile = '../../references.d.ts'; if (fs.existsSync(refFile)) { existingRef = fs.readFileSync(refFile).toString(); } if (existingRef.indexOf('typescript/lib/lib.d.ts') === -1) { // has not been previously modified var fix = '/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />\n' + '/// <reference path="./node_modules/typescript/lib/lib.d.ts" />\n'; fs.writeFileSync(refFile, fix, 'utf8'); } }
javascript
{ "resource": "" }
q63206
fixNativeScriptPackage
test
function fixNativeScriptPackage() { var packageJSON = {}, packageFile = '../../package.json'; packageJSON.name = "NativeScriptApp"; packageJSON.version = "0.0.0"; // var AngularJSON = {}; if (fs.existsSync(packageFile)) { packageJSON = require(packageFile); } else { console.log("This should not happen, your are missing your package.json file!"); return; } // if (fs.existsSync('../angular2/package.json')) { // AngularJSON = require('../angular2/package.json'); // } else { // // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back // AngularJSON.peerDependencies = { // "es6-shim": "^0.35.0", // "reflect-metadata": "0.1.2", // "rxjs": "5.0.0-beta.6", // "zone.js": "^0.6.12" // }; // } packageJSON.nativescript['tns-ios'] = { version: "2.3.0" }; packageJSON.nativescript['tns-android'] = {version: "2.3.0" }; // Copy over all the Peer Dependencies // for (var key in AngularJSON.peerDependencies) { // if (AngularJSON.peerDependencies.hasOwnProperty(key)) { // packageJSON.dependencies[key] = AngularJSON.peerDependencies[key]; // } // } // TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template? if (!packageJSON.devDependencies) { packageJSON.devDependencies = {}; } packageJSON.devDependencies["@types/jasmine"] = "^2.5.35"; packageJSON.devDependencies["babel-traverse"] = "6.12.0"; packageJSON.devDependencies["babel-types"] = "6.11.1"; packageJSON.devDependencies.babylon = "6.8.4"; packageJSON.devDependencies.filewalker = "0.1.2"; packageJSON.devDependencies.lazy = "1.0.11"; // packageJSON.devDependencies["nativescript-dev-typescript"] = "^0.3.2"; packageJSON.devDependencies.typescript = "^2.0.2"; fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8'); }
javascript
{ "resource": "" }
q63207
fixAngularPackage
test
function fixAngularPackage() { var packageJSON = {}, packageFile = '../../../package.json'; if (fs.existsSync(packageFile)) { packageJSON = require(packageFile); } else { console.log("This should not happen, your are missing your main package.json file!"); return; } if (!packageJSON.scripts) { packageJSON.scripts = {}; } packageJSON.scripts["start.ios"] = "cd nativescript && tns emulate ios"; packageJSON.scripts["start.livesync.ios"] = "cd nativescript && tns livesync ios --emulator --watch"; packageJSON.scripts["start.android"] = "cd nativescript && tns emulate android"; packageJSON.scripts["start.livesync.android"] = "cd nativescript && tns livesync android --emulator --watch"; fs.writeFileSync(packageFile, JSON.stringify(packageJSON, null, 4), 'utf8'); }
javascript
{ "resource": "" }
q63208
fixMainFile
test
function fixMainFile(component) { var mainTS = '', mainFile = '../../app/main.ts'; if (fs.existsSync(mainFile)) { mainTS = fs.readFileSync(mainFile).toString(); } if (mainTS.indexOf('MagicService') === -1) { // has not been previously modified var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\n' + 'import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";\n' + 'import { NgModule } from "@angular/core";\n' + 'import { AppComponent } from "./app/app.component";\n' + '\n' + '@NgModule({\n' + ' declarations: [AppComponent],\n' + ' bootstrap: [AppComponent],\n' + ' imports: [NativeScriptModule],\n' + '})\n' + 'class AppComponentModule {}\n\n' + 'platformNativeScriptDynamic().bootstrapModule(AppComponentModule);'; fs.writeFileSync(mainFile, fix, 'utf8'); } }
javascript
{ "resource": "" }
q63209
fixGitIgnore
test
function fixGitIgnore(ignorePattern) { var fileString = '', ignoreFile = '../../../.gitignore'; if (fs.existsSync(ignoreFile)) { fileString = fs.readFileSync(ignoreFile).toString(); } if (fileString.indexOf(ignorePattern) === -1) { // has not been previously modified var fix = fileString + '\n' + ignorePattern; fs.writeFileSync(ignoreFile, fix, 'utf8'); } }
javascript
{ "resource": "" }
q63210
displayFinalHelp
test
function displayFinalHelp() { console.log("-------------- Welcome to the Magical World of NativeScript -----------------------------"); console.log("To finish, follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage"); console.log("After you have completed the steps in the usage guide, you can then:"); console.log(""); console.log("Run your app in the iOS Simulator with these options:"); console.log(" npm run start.ios"); console.log(" npm run start.livesync.ios"); console.log(""); console.log("Run your app in an Android emulator with these options:"); console.log(" npm run start.android"); console.log(" npm run start.livesync.android"); console.log("-----------------------------------------------------------------------------------------"); console.log(""); }
javascript
{ "resource": "" }
q63211
bind
test
function bind(func, thisObject, var_args) { var args = slice(arguments, 2); /** * @param {...} var_args */ function bound(var_args) { return InjectedScriptHost.callFunction(func, thisObject, concat(args, slice(arguments))); } bound.toString = function() { return "bound: " + toString(func); }; return bound; }
javascript
{ "resource": "" }
q63212
test
function(object, objectGroupName, forceValueType, generatePreview, columnNames, isTable, doNotBind, customObjectConfig) { try { return new InjectedScript.RemoteObject(object, objectGroupName, doNotBind, forceValueType, generatePreview, columnNames, isTable, undefined, customObjectConfig); } catch (e) { try { var description = injectedScript._describe(e); } catch (ex) { var description = "<failed to convert exception to string>"; } return new InjectedScript.RemoteObject(description); } }
javascript
{ "resource": "" }
q63213
test
function(callArgumentJson) { callArgumentJson = nullifyObjectProto(callArgumentJson); var objectId = callArgumentJson.objectId; if (objectId) { var parsedArgId = this._parseObjectId(objectId); if (!parsedArgId || parsedArgId["injectedScriptId"] !== injectedScriptId) throw "Arguments should belong to the same JavaScript world as the target object."; var resolvedArg = this._objectForId(parsedArgId); if (!this._isDefined(resolvedArg)) throw "Could not find object with given id"; return resolvedArg; } else if ("value" in callArgumentJson) { var value = callArgumentJson.value; if (callArgumentJson.type === "number" && typeof value !== "number") value = Number(value); return value; } return undefined; }
javascript
{ "resource": "" }
q63214
test
function(topCallFrame, callFrameId, functionObjectId, scopeNumber, variableName, newValueJsonString) { try { var newValueJson = /** @type {!RuntimeAgent.CallArgument} */ (InjectedScriptHost.eval("(" + newValueJsonString + ")")); var resolvedValue = this._resolveCallArgument(newValueJson); if (typeof callFrameId === "string") { var callFrame = this._callFrameForId(topCallFrame, callFrameId); if (!callFrame) return "Could not find call frame with given id"; callFrame.setVariableValue(scopeNumber, variableName, resolvedValue) } else { var parsedFunctionId = this._parseObjectId(/** @type {string} */ (functionObjectId)); var func = this._objectForId(parsedFunctionId); if (typeof func !== "function") return "Could not resolve function by id"; InjectedScriptHost.setFunctionVariableValue(func, scopeNumber, variableName, resolvedValue); } } catch (e) { return toString(e); } return undefined; }
javascript
{ "resource": "" }
q63215
validate
test
function validate(str) { let tj; if (typeof str === 'object') { tj = str; } else if (typeof str === 'string') { try { tj = jsonlint.parse(str); } catch (err) { return false; } } else { return false; } return tilejsonValidateObject.validate(tj); }
javascript
{ "resource": "" }
q63216
_loop2
test
function _loop2(_name) { var klass = resolve(associations[_name].klass); var data = associated[_name]; // clear association if (!data) { model[_name] = null; return "continue"; } if (associations[_name].type === 'hasOne') { var other = (typeof data === "undefined" ? "undefined" : _typeof(data)) === 'object' ? klass.load(data) : klass.local(data); model[_name] = other; } else if (associations[_name].type === 'hasMany') { var others = []; data.forEach(function (o) { others.push((typeof o === "undefined" ? "undefined" : _typeof(o)) === 'object' ? klass.load(o) : klass.local(o)); }); model[_name] = others; } }
javascript
{ "resource": "" }
q63217
handleErrors
test
function handleErrors(errors, data) { const message = errors[0].message; const error = new Error(`GraphQL Error: ${message}`); error.rawError = errors; error.rawData = data; throw error; }
javascript
{ "resource": "" }
q63218
zip
test
function zip(zipFile, srcList, dstPath) { if (!dstPath) { dstPath = false; } const output = fs.createWriteStream(zipFile); const archive = archiver('zip', { zlib: { level: 9 } // Sets the compression level. }); return new Promise((resolve, reject) => { output.on('close', function() { return resolve(); }); archive.on('warning', function(err) { if (err.code === 'ENOENT') { console.log(err); } else { return reject(err); } }); archive.on('error', function(err) { return reject(err); }); archive.pipe(output); srcList.forEach((src) => { const stat = fs.lstatSync(src); if (stat.isFile()) { archive.file(src); } else if (stat.isDirectory() || stat.isSymbolicLink()) { archive.directory(src, dstPath); } else { return reject(new Error('Invalid path')); } }); archive.finalize(); }); }
javascript
{ "resource": "" }
q63219
exec
test
function exec(cmd, verbose) { verbose = verbose === false ? verbose : true; const stdout = execSync(cmd); if (verbose) { console.log(stdout.toString()); } return stdout; }
javascript
{ "resource": "" }
q63220
fileToString
test
function fileToString(file) { try { const stat = fs.lstatSync(file); if (stat.isFile()) { const content = fs.readFileSync(file, 'utf8'); return content.toString(); } } catch (e) { if (!e.message.includes('ENOENT') && !e.message.includes('name too long, lstat')) { throw e; } } return file; }
javascript
{ "resource": "" }
q63221
mergeYamls
test
function mergeYamls(file1, file2) { const obj1 = yaml.safeLoad(fileToString(file1), { schema: yamlfiles.YAML_FILES_SCHEMA }); const obj2 = yaml.safeLoad(fileToString(file2), { schema: yamlfiles.YAML_FILES_SCHEMA }); return yaml.safeDump(merge({}, obj1, obj2)); }
javascript
{ "resource": "" }
q63222
loadKesOverride
test
function loadKesOverride(kesFolder, kesClass = 'kes.js') { let kesOverridePath = path.resolve(kesFolder, kesClass); let KesOverride; try { KesOverride = require(kesOverridePath); } catch (e) { // If the Kes override file exists, then the error occured when // trying to parse the file, so re-throw and prevent Kes from // going further. const fileExists = fs.existsSync(kesOverridePath); if (fileExists) { throw e; } console.log(`No Kes override found at ${kesOverridePath}, continuing`); } return KesOverride; }
javascript
{ "resource": "" }
q63223
determineKesClass
test
function determineKesClass(options, Kes) { let KesOverride; // If there is a kes class specified, use that const kesClass = get(options, 'kesClass'); if (kesClass) { KesOverride = loadKesOverride(process.cwd(), kesClass); } else { let kesFolder; // Check if there is kes.js in the kes folder if (options.kesFolder) { kesFolder = options.kesFolder; } else { kesFolder = path.join(process.cwd(), '.kes'); } KesOverride = loadKesOverride(kesFolder); // If the first Kes override didn't load, check if there is // a kes.js in the template folder. if (!KesOverride) { const template = get(options, 'template', '/path/to/nowhere'); kesFolder = path.join(process.cwd(), template); KesOverride = loadKesOverride(kesFolder); } } return KesOverride || Kes; }
javascript
{ "resource": "" }
q63224
failure
test
function failure(e) { if (e.message) { console.log(e.message); } else { console.log(e); } process.exit(1); }
javascript
{ "resource": "" }
q63225
getSystemBucket
test
function getSystemBucket(config) { let bucket = get(config, 'buckets.internal'); if (bucket && typeof bucket === 'string') { return bucket; } bucket = get(config, 'system_bucket'); if (bucket && typeof bucket === 'string') { return bucket; } return undefined; }
javascript
{ "resource": "" }
q63226
buildNestedCfs
test
function buildNestedCfs(config, KesClass, options) { const limit = pLimit(1); if (config.nested_templates) { const nested = config.nested_templates; console.log('Nested templates are found!'); const ps = Object.keys(nested).map((name) => limit(() => { console.log(`Compiling nested template for ${name}`); const newOptions = Object.assign({}, options); newOptions.cfFile = nested[name].cfFile; newOptions.configFile = nested[name].configFile; // no templates are used in nested stacks delete newOptions.template; delete newOptions.deployment; // use the parent stackname newOptions.stack = config.stack; newOptions.parent = config; const nestedConfig = new Config(newOptions); // get the bucket name from the parent if (!nestedConfig.bucket) { nestedConfig.bucket = utils.getSystemBucket(config); } // add nested deployment name nestedConfig.nested_cf_name = name; const kes = new KesClass(nestedConfig); return kes.uploadCF().then((uri) => { config.nested_templates[name].url = uri; }); })); return Promise.all(ps) .then(() => config) .catch(utils.failure); } return Promise.resolve(config); }
javascript
{ "resource": "" }
q63227
buildCf
test
function buildCf(options, cmd) { const KesClass = utils.determineKesClass(options, Kes); let parentConfig; try { parentConfig = new Config(options); } catch (e) { return Promise.reject(e); } return buildNestedCfs(parentConfig, KesClass, options).then((config) => { const kes = new KesClass(config); switch (cmd) { case 'create': deprecate('"kes cf create" command is deprecated. Use "kes cf deploy" instead'); return kes.createStack(); case 'update': deprecate('"kes cf update" command is deprecated. Use "kes cf deploy" instead'); return kes.updateStack(); case 'upsert': deprecate('"kes cf upsert" command is deprecated. Use "kes cf deploy" instead'); return kes.upsertStack(); case 'deploy': return kes.deployStack(); case 'validate': return kes.validateTemplate(); case 'compile': return kes.compileCF(); case 'delete': return kes.deleteStack(); default: console.log('Wrong choice. Accepted arguments: [create|update|upsert|deploy|validate|compile]'); } }); }
javascript
{ "resource": "" }
q63228
buildLambda
test
function buildLambda(options, cmd) { if (cmd) { const KesClass = utils.determineKesClass(options, Kes); const config = new Config(options); const kes = new KesClass(config); kes.updateSingleLambda(cmd).then(r => utils.success(r)).catch(e => utils.failure(e)); } else { utils.failure(new Error('Lambda name is missing')); } }
javascript
{ "resource": "" }
q63229
sendResponse
test
function sendResponse(event, context, responseStatus, responseData) { const responseBody = JSON.stringify({ Status: responseStatus, Reason: 'See the details in CloudWatch Log Stream: ' + context.logStreamName, PhysicalResourceId: context.logStreamName, StackId: event.StackId, RequestId: event.RequestId, LogicalResourceId: event.LogicalResourceId, Data: responseData }); console.log('RESPONSE BODY:\n', responseBody); const https = require('https'); const url = require('url'); const parsedUrl = url.parse(event.ResponseURL); const options = { hostname: parsedUrl.hostname, port: 443, path: parsedUrl.path, method: 'PUT', headers: { 'content-type': '', 'content-length': responseBody.length } }; console.log('SENDING RESPONSE...\n'); const request = https.request(options, function(response) { console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); // Tell AWS Lambda that the function execution is done context.done(); }); request.on('error', function(error) { console.log('sendResponse Error:' + error); // Tell AWS Lambda that the function execution is done context.done(); }); // write data to request body request.write(responseBody); request.end(); }
javascript
{ "resource": "" }
q63230
optionsToString
test
function optionsToString(options) { return Object.keys(options) .map(function processOption(key) { return key + "=" + options[key]; }) .join(","); }
javascript
{ "resource": "" }
q63231
assign
test
function assign(target) { var sources = Array.prototype.slice.call(arguments, 1); function assignArgument(previous, source) { Object.keys(source).forEach(function assignItem(key) { previous[key] = source[key]; // eslint-disable-line no-param-reassign }); return previous; } return sources.reduce(assignArgument, target); }
javascript
{ "resource": "" }
q63232
openPopupWithPost
test
function openPopupWithPost(url, postData, name, options) { var form = document.createElement("form"); var win; form.setAttribute("method", "post"); form.setAttribute("action", url); form.setAttribute("target", name); Object.keys(postData).forEach(function addFormItem(key) { var input = document.createElement("input"); input.type = "hidden"; input.name = key; input.value = postData[key]; form.appendChild(input); }); document.body.appendChild(form); win = window.open("/", name, options); win.document.write("Loading..."); form.submit(); document.body.removeChild(form); return win; }
javascript
{ "resource": "" }
q63233
popupExecute
test
function popupExecute(execute, url, name, options, callback) { var popupName = name || defaultPopupName(); var popupOptions = optionsResolveCentered(assign({}, defaultOptions, options)); var popupCallback = callback || function noop() {}; var optionsString = optionsToString(popupOptions); var win = execute(url, popupName, optionsString); var isMessageSent = false; var interval; function popupCallbackOnce(err, data) { if (!isMessageSent) { isMessageSent = true; popupCallback(err, data); } } function onMessage(message) { var data = message ? message.data : undefined; if (data) { popupCallbackOnce(undefined, data); window.removeEventListener("message", onMessage); } } window.addEventListener("message", onMessage, false); if (win) { interval = setInterval(function closePopupCallback() { if (win == null || win.closed) { setTimeout(function delayWindowClosing() { clearInterval(interval); popupCallbackOnce(new Error("Popup closed")); }, 500); } }, 100); } else { popupCallbackOnce(new Error("Popup blocked")); } return win; }
javascript
{ "resource": "" }
q63234
popup
test
function popup(url, name, options, callback) { return popupExecute(window.open, url, name, options, callback); }
javascript
{ "resource": "" }
q63235
popupWithPost
test
function popupWithPost(url, postData, name, options, callback) { function openWithPostData(popupUrl, popupName, optionsString) { return openPopupWithPost(popupUrl, postData, popupName, optionsString); } return popupExecute(openWithPostData, url, name, options, callback); }
javascript
{ "resource": "" }
q63236
getWrappingContentRange
test
function getWrappingContentRange(editor) { if (editor.somethingSelected()) { const sel = editor.listSelections().filter(sel => sel.anchor !== sel.head)[0]; if (sel) { return comparePos(sel.anchor, sel.head) < 0 ? { from: sel.anchor, to: sel.head } : { from: sel.head, to: sel.anchor }; } } // Nothing selected, find parent HTML node and return range for its content return getTagRangeForPos(editor, editor.getCursor()); }
javascript
{ "resource": "" }
q63237
betweenTags
test
function betweenTags(editor, range) { if (equalCursorPos(range.anchor, range.head)) { const cursor = range.anchor; const mode = editor.getModeAt(cursor); if (mode.name === 'xml') { const left = editor.getTokenAt(cursor); const right = editor.getTokenAt(Object.assign({}, cursor, { ch: cursor.ch + 1 })); return left.type === 'tag bracket' && left.string === '>' && right.type === 'tag bracket' && right.string === '</'; } } }
javascript
{ "resource": "" }
q63238
canExtract
test
function canExtract(editor, pos, config) { const tokenType = editor.getTokenTypeAt(pos); if (config.type === 'stylesheet') { return tokenType !== 'comment' && tokenType !== 'string'; } if (config.syntax === 'html') { return tokenType === null; } if (config.syntax === 'slim' || config.syntax === 'pug') { return tokenType === null || tokenType === 'tag' || (tokenType && /attribute/.test(tokenType)); } if (config.syntax === 'haml') { return tokenType === null || tokenType === 'attribute'; } if (config.syntax === 'jsx') { // JSX a bit tricky, delegate it to caller return true; } return false; }
javascript
{ "resource": "" }
q63239
getStylesheetCompletions
test
function getStylesheetCompletions(editor, pos, config) { const line = editor.getLine(pos.line).slice(0, pos.ch); const prefix = extractPrefix(line, /[\w-@$]/); if (prefix) { // Make sure that current position precedes element name (e.g. not attribute, // class, id etc.) const prefixRange = { from: { line: pos.line, ch: pos.ch - prefix.length }, to: pos }; if (config.options && config.options.property) { const lowerProp = config.options.property.toLowerCase(); // Find matching CSS property snippet for keyword completions const completion = getSnippetCompletions(editor, pos, config) .find(item => item.property && item.property === lowerProp); if (completion && completion.keywords.length) { return completion.keywords.map(kw => { return kw.key.indexOf(prefix) === 0 && new EmmetCompletion('value', editor, prefixRange, kw.key, kw.preview, kw.snippet); }).filter(Boolean); } } else { return getSnippetCompletions(editor, pos, config) .filter(completion => completion.key !== prefix && completion.key.indexOf(prefix) === 0) .map(completion => new EmmetCompletion('snippet', editor, prefixRange, completion.key, completion.preview, completion.snippet)); } } return []; }
javascript
{ "resource": "" }
q63240
getSnippetCompletions
test
function getSnippetCompletions(editor, pos, config) { const { type, syntax } = config; if (!editor.state.emmetCompletions) { editor.state.emmetCompletions = {}; } const cache = editor.state.emmetCompletions; if (!(syntax in cache)) { const registry = createSnippetsRegistry(type, syntax, config.snippets); cache[syntax] = type === 'stylesheet' ? getStylesheetSnippets(registry, config) : getMarkupSnippets(registry, config); } return cache[syntax]; }
javascript
{ "resource": "" }
q63241
getStylesheetSnippets
test
function getStylesheetSnippets(registry) { return convertToCSSSnippets(registry).map(snippet => { let preview = snippet.property; const keywords = snippet.keywords(); if (keywords.length) { preview += `: ${removeFields(keywords.join(' | '))}`; } else if (snippet.value) { preview += `: ${removeFields(snippet.value)}`; } return { key: snippet.key, value: snippet.value, snippet: snippet.key, property: snippet.property, keywords: keywords.map(kw => { const m = kw.match(/^[\w-]+/); return m && { key: m[0], preview: removeFields(kw), snippet: kw }; }).filter(Boolean), preview }; }); }
javascript
{ "resource": "" }
q63242
getMarkupSnippets
test
function getMarkupSnippets(registry, config) { return registry.all({ type: 'string' }).map(snippet => ({ key: snippet.key, value: snippet.value, preview: removeFields(expand(snippet.value, config)), snippet: snippet.key })); }
javascript
{ "resource": "" }
q63243
extractPrefix
test
function extractPrefix(str, match) { let offset = str.length; while (offset > 0) { if (!match.test(str[offset - 1])) { break; } offset--; } return str.slice(offset); }
javascript
{ "resource": "" }
q63244
isValidMarker
test
function isValidMarker(editor, marker) { const range = marker.find(); // No newlines inside abbreviation if (range.from.line !== range.to.line) { return false; } // Make sure marker contains valid abbreviation let text = editor.getRange(range.from, range.to); if (!text || /^\s|\s$/g.test(text)) { return false; } if (marker.model && marker.model.config.syntax === 'jsx' && text[0] === '<') { text = text.slice(1); } if (!marker.model || marker.model.abbreviation !== text) { // marker contents was updated, re-parse abbreviation try { marker.model = new Abbreviation(text, range, marker.model.config); if (!marker.model.valid(editor, true)) { marker.model = null; } } catch (err) { console.warn(err); marker.model = null; } } return Boolean(marker.model && marker.model.snippet); }
javascript
{ "resource": "" }
q63245
test
function (property) { var def = this._definition[property]; if (def.type === 'boolean') { // if it's a bool, just flip it this[property] = !this[property]; } else if (def && def.values) { // If it's a property with an array of values // skip to the next one looping back if at end. this[property] = arrayNext(def.values, this[property]); } else { throw new TypeError('Can only toggle properties that are type `boolean` or have `values` array.'); } return this; }
javascript
{ "resource": "" }
q63246
test
function (attr) { if (attr == null) return !!Object.keys(this._changed).length; if (has(this._derived, attr)) { return this._derived[attr].depList.some(function (dep) { return this.hasChanged(dep); }, this); } return has(this._changed, attr); }
javascript
{ "resource": "" }
q63247
test
function (propertyName) { if (!this._eventBubblingHandlerCache[propertyName]) { this._eventBubblingHandlerCache[propertyName] = function (name, model, newValue) { if (changeRE.test(name)) { this.trigger('change:' + propertyName + '.' + name.split(':')[1], model, newValue); } else if (name === 'change') { this.trigger('change', this); } }.bind(this); } return this._eventBubblingHandlerCache[propertyName]; }
javascript
{ "resource": "" }
q63248
createDerivedProperty
test
function createDerivedProperty(modelProto, name, definition) { var def = modelProto._derived[name] = { fn: isFunction(definition) ? definition : definition.fn, cache: (definition.cache !== false), depList: definition.deps || [] }; // add to our shared dependency list def.depList.forEach(function (dep) { modelProto._deps[dep] = union(modelProto._deps[dep] || [], [name]); }); // defined a top-level getter for derived names Object.defineProperty(modelProto, name, { get: function () { return this._getDerivedProperty(name); }, set: function () { throw new TypeError("`" + name + "` is a derived property, it can't be set directly."); } }); }
javascript
{ "resource": "" }
q63249
Image
test
function Image(image, address){ var at = this.attributes = image.attribs; this.name = path.basename(at.src, path.extname(at.src)); this.saveTo = path.dirname(require.main.filename) + "/"; this.extension = path.extname(at.src); this.address = url.resolve(address, at.src); this.fromAddress = address; }
javascript
{ "resource": "" }
q63250
shipitTask
test
function shipitTask(grunt) { 'use strict'; // Init shipit grunt.shipit = new Shipit(); grunt.registerTask('shipit', 'Shipit Task', function (env) { var config = grunt.config.get('shipit'); grunt.shipit.environment = env; // Support legacy options. if (!config.default && config.options) config.default = config.options; grunt.shipit .initConfig(config) .initialize(); }); }
javascript
{ "resource": "" }
q63251
injectTemplate
test
function injectTemplate (s, node, offset, id) { const t = node.src ? readSrc(id, node.src) : node.content // Compile template const compiled = compiler.compile(t) const renderFuncs = '\nrender: ' + toFunction(compiled.render) + ',' + '\nstaticRenderFns: [' + compiled.staticRenderFns.map(toFunction).join(',') + '],' s.appendLeft(offset, renderFuncs) return renderFuncs }
javascript
{ "resource": "" }
q63252
_defaultCheckSize
test
function _defaultCheckSize(size) { return function (raw) { if (raw.length < size) { return false; } this.buffer = raw.substr(size); return raw.substr(0, size); }; }
javascript
{ "resource": "" }
q63253
int64add5
test
function int64add5(dst, a, b, c, d, e) { var w0 = (a.l & 0xffff) + (b.l & 0xffff) + (c.l & 0xffff) + (d.l & 0xffff) + (e.l & 0xffff); var w1 = (a.l >>> 16) + (b.l >>> 16) + (c.l >>> 16) + (d.l >>> 16) + (e.l >>> 16) + (w0 >>> 16); var w2 = (a.h & 0xffff) + (b.h & 0xffff) + (c.h & 0xffff) + (d.h & 0xffff) + (e.h & 0xffff) + (w1 >>> 16); var w3 = (a.h >>> 16) + (b.h >>> 16) + (c.h >>> 16) + (d.h >>> 16) + (e.h >>> 16) + (w2 >>> 16); dst.l = (w0 & 0xffff) | (w1 << 16); dst.h = (w2 & 0xffff) | (w3 << 16); }
javascript
{ "resource": "" }
q63254
test
function (configFile, options) { DataStream.call(this); this.options = options || {}; var self = this; // apply config this.configFile = configFile; this.init(); // Bundles streams this.bundles = {}; // Let return instance before build this.buildConfig = this.compileConfig(configFile, self.options); this.makeEmptyStreamsUnreadable(this.buildConfig); var isFatalErrors = !this.isAllModulesExists(this.buildConfig); if (isFatalErrors) { this.readable = false; this.style.readable = false; this.sourceMap.readable = false; } else { this._initBundlesStreams(this.buildConfig.bundles); } process.nextTick(function () { if (!isFatalErrors) { if (configFile) { var buildResult = self.build(self.buildConfig); self.write(buildResult.source); self.style.write(buildResult.style); self.sourceMap.write(buildResult.sourceMap.toString()); self._streamBundles(buildResult.bundles); } else { self.log.write('lmd usage:\n\t ' + 'lmd'.blue + ' ' + 'config.lmd.js(on)'.green + ' [output.lmd.js]\n'); } } else { self.printFatalErrors(self.buildConfig); } self.closeStreams(); }); }
javascript
{ "resource": "" }
q63255
getSandboxMap
test
function getSandboxMap(ast) { var map = {}; walker.with_walkers({ // looking for first var with sandbox item; "var" : function (vars) { for (var i = 0, c = vars.length, varItem; i < c; i++) { varItem = vars[i]; if (varItem[0] === 'sandbox') { varItem[1][1].forEach(function (objectVar) { map[objectVar[0]] = objectVar[1][1]; }); throw 0; } } } }, function () { try { return walker.walk(ast); } catch (e) {} }); return map; }
javascript
{ "resource": "" }
q63256
breakSandbox
test
function breakSandbox(ast, replaceMap) { var sandboxName = ast[2][0] || 'sb'; var newAst = walker.with_walkers({ // lookup for dot // looking for this pattern // ["dot", ["name", "sb"], "require"] -> ["name", map["require"]] "dot" : function () { if (this[1] && this[1][0] === "name" && this[1][1] === sandboxName) { var sourceName = this[2]; return ["name", replaceMap[sourceName]]; } } }, function () { return walker.walk(ast); }); // remove IEFE's `sb` or whatever argument newAst[1][2] = []; return newAst; }
javascript
{ "resource": "" }
q63257
test
function () { if (isSandboxVariableWiped) { return; } for (var i = 0, c = this[1].length, varItem; i < c; i++) { varItem = this[1][i]; if (varItem[0] === 'sandbox') { isSandboxVariableWiped = true; this[1].splice(i, 1); return this; } } }
javascript
{ "resource": "" }
q63258
getEvents
test
function getEvents(ast) { var usage = {}, eventIndex = 0; walker.with_walkers({ // looking for first var with sandbox item; "call" : function () { if (this[1] && this[2][0]) { var functionName = this[1][1]; switch (functionName) { case "lmd_on": case "lmd_trigger": var eventName = this[2][0][1]; if (!usage[eventName]) { usage[eventName] = { on: 0, trigger: 0, eventIndex: eventIndex }; eventIndex++; } if (functionName === "lmd_on") { usage[eventName].on++; } else { usage[eventName].trigger++; } break; } } } }, function () { return walker.walk(ast); }); return usage; }
javascript
{ "resource": "" }
q63259
wipeLmdEvents
test
function wipeLmdEvents(ast) { var itemsToWipe = ['lmd_on', 'lmd_trigger', 'lmd_events']; return walker.with_walkers({ // wipe lmdEvents variables "var": function () { if (!itemsToWipe.length) { return; } for (var i = 0, c = this[1].length, varItem; i < c; i++) { varItem = this[1][i]; if (varItem) { var itemIndex = itemsToWipe.indexOf(varItem[0]); if (itemIndex !== -1) { itemsToWipe.splice(itemIndex, 1); this[1].splice(i, 1); i--; } } } } }, function () { return walker.walk(ast); }); }
javascript
{ "resource": "" }
q63260
test
function () { if (!itemsToWipe.length) { return; } for (var i = 0, c = this[1].length, varItem; i < c; i++) { varItem = this[1][i]; if (varItem) { var itemIndex = itemsToWipe.indexOf(varItem[0]); if (itemIndex !== -1) { itemsToWipe.splice(itemIndex, 1); this[1].splice(i, 1); i--; } } } }
javascript
{ "resource": "" }
q63261
test
function (optionName, isApply, isInline) { // /*if ($P.CSS || $P.JS || $P.ASYNC) {*/ var inlinePreprocessorBlock = isInline ? '/*if (' + optionName + ') {*/' : 'if (' + optionName + ') {', bracesCounter = 0, startIndex = lmd_js.indexOf(inlinePreprocessorBlock), startLength = inlinePreprocessorBlock.length, endIndex = startIndex + inlinePreprocessorBlock.length, endLength = isInline ? 5 : 1; if (startIndex === -1) { return false; } // lookup for own } while (lmd_js.length > endIndex) { if (lmd_js[endIndex] === '{') { bracesCounter++; } if (lmd_js[endIndex] === '}') { bracesCounter--; } // found! if (bracesCounter === -1) { if (isInline) { // step back endIndex -= 2; } else { // remove leading spaces from open part while (startIndex) { startIndex--; startLength++; if (lmd_js[startIndex] !== '\t' && lmd_js[startIndex] !== ' ') { startIndex++; startLength--; break; } } // remove leading spaces from close part while (endIndex) { endIndex--; endLength++; if (lmd_js[endIndex] !== '\t' && lmd_js[endIndex] !== ' ') { endIndex++; endLength--; break; } } // add front \n endLength++; startLength++; } if (isApply) { // wipe preprocessor blocks only // open lmd_js = lmd_js.substr(0, startIndex) + lmd_js.substr(startIndex + startLength); // close lmd_js = lmd_js.substr(0, endIndex - startLength) + lmd_js.substr(endIndex + endLength - startLength); if (!isInline) { // indent block back var blockForIndent = lmd_js.substr(startIndex, endIndex - startLength - startIndex); blockForIndent = blockForIndent .split('\n') .map(function (line) { return line.replace(/^\s{4}/, ''); }) .join('\n'); lmd_js = lmd_js.substr(0, startIndex) + blockForIndent + lmd_js.substr(endIndex - startLength); } } else { // wipe all lmd_js = lmd_js.substr(0, startIndex) + lmd_js.substr(endIndex + endLength); } break; } endIndex++; } return true; }
javascript
{ "resource": "" }
q63262
test
function (e) { if (isNotLoaded) { isNotLoaded = 0; // register or cleanup link.removeAttribute('id'); if (!e) { sb.trigger('*:request-error', moduleName, module); } callback(e ? sb.register(moduleName, link) : head.removeChild(link) && sb.undefined); // e === undefined if error } }
javascript
{ "resource": "" }
q63263
d3_layout_hierarchyRebind
test
function d3_layout_hierarchyRebind(object, hierarchy) { object.sort = d3.rebind(object, hierarchy.sort); object.children = d3.rebind(object, hierarchy.children); object.links = d3_layout_hierarchyLinks; object.value = d3.rebind(object, hierarchy.value); // If the new API is used, enabling inlining. object.nodes = function(d) { d3_layout_hierarchyInline = true; return (object.nodes = object)(d); }; return object; }
javascript
{ "resource": "" }
q63264
position
test
function position(row, u, rect, flush) { var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; if (u == rect.dx) { // horizontal subdivision if (flush || v > rect.dy) v = v ? rect.dy : 0; // over+underflow while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dy = v; x += o.dx = v ? round(o.area / v) : 0; } o.z = true; o.dx += rect.x + rect.dx - x; // rounding error rect.y += v; rect.dy -= v; } else { // vertical subdivision if (flush || v > rect.dx) v = v ? rect.dx : 0; // over+underflow while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dx = v; y += o.dy = v ? round(o.area / v) : 0; } o.z = false; o.dy += rect.y + rect.dy - y; // rounding error rect.x += v; rect.dx -= v; } }
javascript
{ "resource": "" }
q63265
test
function(classes) { var map = {}; function find(name, data) { var node = map[name], i; if (!node) { node = map[name] = data || {name: name, children: []}; if (name.length) { node.parent = find(""); node.parent.children.push(node); node.name = name; node.key = escapeId(name); } } return node; } classes.forEach(function(d) { find(d.name, d); }); return map[""]; }
javascript
{ "resource": "" }
q63266
stringify
test
function stringify(object) { var properties = []; for (var key in object) { if (object.hasOwnProperty(key)) { properties.push(quote(key) + ':' + getValue(object[key])); } } return "{" + properties.join(",") + "}"; }
javascript
{ "resource": "" }
q63267
countIf
test
function countIf() { var self = this, ret; if (self[0].start && analyzing.indexOf(self) < 0) { var decision = self[1]; var lineId = self[0].name + ':' + (self[0].start.line + lineOffset); self[1] = wrapCondition(decision, lineId); // We are adding new lines, make sure code blocks are actual blocks if (self[2] && self[2][0].start && self[2][0].start.value != "{") { self[2] = [ "block", [self[2]]]; } if (self[3] && self[3][0].start && self[3][0].start.value != "{") { self[3] = [ "block", [self[3]]]; } } ret = countLine.call(self); if (decision) { analyzing.pop(decision); } return ret; }
javascript
{ "resource": "" }
q63268
wrapCondition
test
function wrapCondition(decision, lineId, parentPos) { if (options.condition === false) { // condition coverage is disabled return decision; } if (isSingleCondition(decision)) { var pos = getPositionStart(decision, parentPos); var condId = lineId + ":" + pos; analyzing.push(decision); allConditions.push(condId); return ["call", ["dot", ["name", "require"], "coverage_condition"], [ [ "string", moduleName ], [ "string", condId], decision ] ]; } else { decision[2] = wrapCondition(decision[2], lineId, getPositionStart(decision, parentPos)); decision[3] = wrapCondition(decision[3], lineId, getPositionEnd(decision, parentPos)); return decision; } }
javascript
{ "resource": "" }
q63269
isSingleCondition
test
function isSingleCondition(decision) { if (decision[0].start && decision[0].name != "binary") { return true; } else if (decision[1] == "&&" || decision[1] == "||") { return false; } else { return true; } }
javascript
{ "resource": "" }
q63270
countLabel
test
function countLabel() { var ret; if (this[0].start && analyzing.indexOf(this) < 0) { var content = this[2]; if (content[0].name == "for" && content[4] && content[4].name != "block") { content[4] = [ "block", [content[4]]]; } analyzing.push(content); var ret = countLine.call(this); analyzing.pop(content); } return ret; }
javascript
{ "resource": "" }
q63271
giveNameToAnonymousFunction
test
function giveNameToAnonymousFunction () { var node = this; if (node[0].name == "var" || node[0].name == "object") { node[1].forEach(function (assignemt) { if (assignemt[1]) { if (assignemt[1][0].name === "function") { assignemt[1][0].anonymousName = assignemt[0]; } else if (assignemt[1][0].name === "conditional") { if (assignemt[1][2][0] && assignemt[1][2][0].name === "function") { assignemt[1][2][0].anonymousName = assignemt[0]; } if (assignemt[1][3][0] && assignemt[1][3][0].name === "function") { assignemt[1][3][0].anonymousName = assignemt[0]; } } } }); } else if (node[0].name == "assign" && node[1] === true) { if (node[3][0].name === "function") { node[3][0].anonymousName = getNameFromAssign(node); } else if (node[3][0] === "conditional") { if (node[3][2][0] && node[3][2][0].name === "function") { node[3][2][0].anonymousName = getNameFromAssign(node); } if (node[3][3][0] && node[3][3][0].name === "function") { node[3][3][0].anonymousName = getNameFromAssign(node); } } } }
javascript
{ "resource": "" }
q63272
wrapConditionals
test
function wrapConditionals () { if (options.condition === false) { // condition coverage is disabled return; } var self = this, ret; if (self[0].start && analyzing.indexOf(self) < 0) { analyzing.push(self); var lineId = self[0].name + ':' + (self[0].start.line + lineOffset); self[1] = wrapCondition(self[1], lineId); self[2] = walker.walk(self[2]); self[3] = walker.walk(self[3]); analyzing.pop(self); return self; } else if (self[1]) { self[1] = wrapCondition(self[1], lineId); } }
javascript
{ "resource": "" }
q63273
test
function (name, deps, module) { switch (arguments.length) { case 1: // define(function () {}) module = name; deps = name = sb.undefined; break; case 2: // define(['a', 'b'], function () {}) module = deps; deps = name; name = sb.undefined; break; case 3: // define('name', ['a', 'b'], function () {}) } if (typeof module !== "function") { amdModules[currentModule] = module; return; } var output = {'exports': {}}; if (!deps) { deps = ["require", "exports", "module"]; } for (var i = 0, c = deps.length; i < c; i++) { switch (deps[i]) { case "require": deps[i] = currentRequire; break; case "module": deps[i] = output; break; case "exports": deps[i] = output.exports; break; default: deps[i] = currentRequire && currentRequire(deps[i]); } } module = module.apply(this, deps) || output.exports; amdModules[currentModule] = module; }
javascript
{ "resource": "" }
q63274
stats_calculate_coverage
test
function stats_calculate_coverage(moduleName) { var stats = sb.trigger('*:stats-get', moduleName, null)[1], total, covered, lineId, lineNum, parts; var lineReport = {}; if (!stats.lines) { return; } stats.coverage = {}; covered = 0; total = stats.lines.length; for (lineId in stats.runLines) { if (stats.runLines[lineId] > 0) { covered++; } else { lineNum = lineId; if (!lineReport[lineNum]) { lineReport[lineNum] = {}; } lineReport[lineNum].lines = false; } } stats.coverage.lines = { total: total, covered: covered, percentage: 100.0 * (total ? covered / total : 1) }; covered = 0; total = stats.functions.length; for (lineId in stats.runFunctions) { if (stats.runFunctions[lineId] > 0) { covered++; } else { parts = lineId.split(':'); lineNum = parts[1]; if (!lineReport[lineNum]) { lineReport[lineNum] = {}; } if (!lineReport[lineNum].functions) { lineReport[lineNum].functions = []; } lineReport[lineNum].functions.push(parts[0]); } } stats.coverage.functions = { total:total, covered:covered, percentage:100.0 * (total ? covered / total : 1) }; covered = 0; total = stats.conditions.length; for (lineId in stats.runConditions) { if (stats.runConditions[lineId][1] > 0) { covered += 1; } if (stats.runConditions[lineId][1] === 0) { parts = lineId.split(':'); lineNum = parts[1]; if (!lineReport[lineNum]) { lineReport[lineNum] = {}; } if (!lineReport[lineNum].conditions) { lineReport[lineNum].conditions = []; } lineReport[lineNum].conditions.push(stats.runConditions[lineId]); } } stats.coverage.conditions = { total:total, covered:covered, percentage:100.0 * (total ? covered / total : 1) }; stats.coverage.report = lineReport; }
javascript
{ "resource": "" }
q63275
test
function (config, mixins) { if (Array.isArray(config.mixins) && Array.isArray(mixins)) { config.mixins.push.apply(config.mixins, mixins); return config; } return deepDestructableMerge(config, { mixins: mixins }); }
javascript
{ "resource": "" }
q63276
test
function (left, right) { for (var prop in right) { if (right.hasOwnProperty(prop)) { if (typeof left[prop] === "object") { deepDestructableMerge(left[prop], right[prop]); } else { left[prop] = right[prop]; } } } return left; }
javascript
{ "resource": "" }
q63277
test
function (config, configDir) { config = config || {}; if (typeof config.extends !== "string") { return config; } var parentConfig = tryExtend(readConfig(configDir, config.extends), configDir); return deepDestructableMerge(parentConfig, config); }
javascript
{ "resource": "" }
q63278
test
function (modulePath, dependsFileMask) { modulePath = [].concat(modulePath); return modulePath.map(function (modulePath) { var fileName = modulePath.replace(/^.*\/|\.[a-z0-9]+$/g, ''); return path.join(path.dirname(modulePath), dependsFileMask.replace('*', fileName)); }); }
javascript
{ "resource": "" }
q63279
test
function (configA, configB, flagsNames, isMasterConfig) { // Apply Flags flagsNames.forEach(function (optionsName) { // if master -> B if (typeof configB[optionsName] === "undefined") { return; } if (isMasterConfig) { configA[optionsName] = configB[optionsName]; } else { // if A literal B array -> B if (configB[optionsName] instanceof Array && !(configA[optionsName] instanceof Array) ) { configA[optionsName] = configB[optionsName]; } else if (configB[optionsName] instanceof Array && configA[optionsName] instanceof Array) { // if A array B array -> A concat B configA[optionsName] = configA[optionsName].concat(configB[optionsName]); } else { // if A literal B literal -> union // if A array B literal -> A configA[optionsName] = configA[optionsName] || configB[optionsName]; } // else {} } }); }
javascript
{ "resource": "" }
q63280
addPluginsFromBundles
test
function addPluginsFromBundles(resultConfig) { if (resultConfig.bundles) { var bundles = Object.keys(resultConfig.bundles), lmdPlugins = Object.keys(LMD_PLUGINS); // Apply flags from bundles bundles.forEach(function (bundleName) { mergeFlags(resultConfig, resultConfig.bundles[bundleName], lmdPlugins, false); }); // Set bundle plugin if (bundles.length) { resultConfig.bundle = true; } } }
javascript
{ "resource": "" }
q63281
test
function (code, options) { var exports = [], requires = [], bind = [], extra_exports = options.extra_exports, extra_require = options.extra_require, extra_bind = options.extra_bind, exportCode, bindModuleName; // add exports to the module end // extra_exports = {name: code, name: code} if (typeof extra_exports === "object") { for (var exportName in extra_exports) { exportCode = extra_exports[exportName]; exports.push(' ' + JSON.stringify(exportName) + ': ' + exportCode); } code += '\n\n/* added by builder */\nreturn {\n' + exports.join(',\n') + '\n};'; } else if (extra_exports) { // extra_exports = string code += '\n\n/* added by builder */\nreturn ' + extra_exports + ';'; } // change context of module (this) // and proxy return value // return function(){}.call({name: require('name')}); if (typeof extra_bind === "object") { for (var bindName in extra_bind) { bindModuleName = extra_bind[bindName]; bind.push(' ' + JSON.stringify(bindName) + ': require(' + JSON.stringify(bindModuleName) + ')'); } code = '\nreturn function(){\n\n' + code + '\n}.call({\n' + bind.join(',\n') + '\n});'; } else if (extra_bind) { // return function(){}.call(require('name')); code = '\nreturn function(){\n\n' + code + '\n}.call(require(' + JSON.stringify(extra_bind) + '));'; } // add require to the module start if (typeof extra_require === "object") { // extra_require = [name, name, name] if (extra_require instanceof Array) { for (var i = 0, c = extra_require.length, moduleName; i < c; i++) { moduleName = extra_require[i]; requires.push('require(' + JSON.stringify(moduleName) + ');'); } code = '/* added by builder */\n' + requires.join('\n') + '\n\n' + code; } else { // extra_require = {name: name, name: name} for (var localName in extra_require) { moduleName = extra_require[localName]; requires.push(localName + ' = require(' + JSON.stringify(moduleName) + ')'); } code = '/* added by builder */\nvar ' + requires.join(',\n ') + ';\n\n' + code; } } else if (extra_require) { // extra_require = string code = '/* added by builder */\nrequire(' + JSON.stringify(extra_require) + ');\n\n' + code; } return '(function (require) { /* wrapped by builder */\n' + code + '\n})'; }
javascript
{ "resource": "" }
q63282
test
function (code, moduleOptions, moduleType) { switch (moduleType) { case "3-party": // create lmd module from non-lmd module code = wrap3partyModule(code, moduleOptions); break; case "plain": // wrap plain module code = wrapPlainModule(code); break; case "amd": // AMD RequireJS code = wrapAmdModule(code); break; case "fd": case "fe": // wipe tail ; code = removeTailSemicolons(code); } return code; }
javascript
{ "resource": "" }
q63283
getModuleType
test
function getModuleType (code) { var ast; if (typeof code === "object") { ast = code; } else { try { JSON.parse(code); return "json"; } catch (e) {} try { ast = parser.parse(code); } catch (e) { return "string"; } } // Empty module if (ast.length === 2 && !ast[1].length && ast[0] === 'toplevel') return "plain"; // ["toplevel",[["defun","depA",["require"],[]]]] if (ast && ast.length === 2 && ast[1] && ast[1].length === 1 && ast[1][0][0] === "defun" ) { return "fd"; } // ["toplevel",[["stat",["function",null,["require"],[]]]]] if (ast && ast.length === 2 && ast[1] && ast[1].length === 1 && ast[1][0][0] === "stat" && ast[1][0][1] && ast[1][0][1][0] === "function" ) { return "fe"; } if (ast) { var isAmd = ast[1].every(function (ast) { return ast[0] === "stat" && ast[1][0] === "call" && ast[1][1][0] === "name" && ast[1][1][1] === "define"; }); if (isAmd) { return "amd"; } } return "plain"; }
javascript
{ "resource": "" }
q63284
d3_transform
test
function d3_transform(m) { var r0 = [m.a, m.b], r1 = [m.c, m.d], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)); this.translate = [m.e, m.f]; this.rotate = Math.atan2(m.b, m.a) * d3_transformDegrees; this.scale = [kx, ky || 0]; this.skew = ky ? kz / ky * d3_transformDegrees : 0; }
javascript
{ "resource": "" }
q63285
mousewheel
test
function mousewheel() { start.apply(this, arguments); if (!d3_behavior_zoomZooming) d3_behavior_zoomZooming = d3_behavior_zoomLocation(d3.svg.mouse(d3_behavior_zoomTarget)); d3_behavior_zoomTo(d3_behavior_zoomDelta() + xyz[2], d3.svg.mouse(d3_behavior_zoomTarget), d3_behavior_zoomZooming); }
javascript
{ "resource": "" }
q63286
d3_behavior_zoomDelta
test
function d3_behavior_zoomDelta() { // mousewheel events are totally broken! // https://bugs.webkit.org/show_bug.cgi?id=40441 // not only that, but Chrome and Safari differ in re. to acceleration! if (!d3_behavior_zoomDiv) { d3_behavior_zoomDiv = d3.select("body").append("div") .style("visibility", "hidden") .style("top", 0) .style("height", 0) .style("width", 0) .style("overflow-y", "scroll") .append("div") .style("height", "2000px") .node().parentNode; } var e = d3.event, delta; try { d3_behavior_zoomDiv.scrollTop = 1000; d3_behavior_zoomDiv.dispatchEvent(e); delta = 1000 - d3_behavior_zoomDiv.scrollTop; } catch (error) { delta = e.wheelDelta || (-e.detail * 5); } return delta * .005; }
javascript
{ "resource": "" }
q63287
test
function (data) { var config; // case data is argv string if (typeof data === "string") { // try to parse new version config = parseArgv(data); // its new config argv string if (Object.keys(config).length) { // translate short params to long one config.mode = config.mode || config.m; config.output = config.output || config.o; config.log = config.log || config.l; config.config = config.config || config.c; config['no-warn'] = config['no-warn'] || config['no-w']; config['source-map'] = config['source-map'] || config['sm']; config['source-map-root'] = config['source-map-root'] || config['sm-root']; config['source-map-www'] = config['source-map-www'] || config['sm-www']; config['source-map-inline'] = config['source-map-inline'] || config['sm-inline']; } else { // an old argv format, split argv and parse manually data = data.split(' '); // without mode if (availableModes.indexOf(data[2]) === -1) { config = { mode: 'main', config: data[2], output: data[3] }; } else { // with mode config = { mode: data[2], config: data[3], output: data[4] }; } } // case data is config object } else if (typeof config === "object") { // use as is config = data; // case else } else { // wut? throw new Error('Bad config data'); } config.mode = config.mode || 'main'; config.warn = !config['no-warn']; config.sourcemap = config['source-map'] || false; config.www_root = config['source-map-root'] || ""; config.sourcemap_www = config['source-map-www'] || ""; config.sourcemap_inline = config['source-map-inline'] || false; config.log = config.log || false; return config; }
javascript
{ "resource": "" }
q63288
parse
test
function parse (options, document, callback) { xml2js.parseString(document, { trim: true, normalizeTags: true, normalize: true }, function (err, result) { var source = options.source; if (!err) { // Process the url input, but break if base.input returns false. // In other words, _.find is looking for a non-falsy err. // For now, this can only happen if no outputDir is defined, // which is a fatal bad option problem and will happen immediately. _.find( // if the sitemap is malformed, just blow up result.urlset.url, function (urlNode) { // optionally ignore current urls by sitemap policy var url, process = !options.sitemapPolicy || !stillCurrent(urlNode, options); if (process) { // if sitemap is malformed, just blow up url = urlm.parse(urlNode.loc[0]); if (!base.input(_.extend({}, options, { protocol: url.protocol, auth: url.auth, hostname: url.hostname, port: url.port }), urlNode.loc[0]) ) { source = urlNode.loc[0]; err = base.generatorError(); } } return err; } ); } callback(common.prependMsgToErr(err, source, true)); }); }
javascript
{ "resource": "" }
q63289
convert
test
function convert(options, buffer, next, callback) { var gunzip = path.extname(options.source) === ".gz"; if (gunzip) { zlib.gunzip(buffer, function (err, result) { if (err) { callback(common.prependMsgToErr(err, options.source, true)); } else { next(options, result && result.toString(), callback); } }); } else { next(options, buffer.toString(), callback); } }
javascript
{ "resource": "" }
q63290
getUrl
test
function getUrl (options, parseFn, callback) { request({ url: options.source, encoding: null, timeout: options.timeout() // get the default timeout }, function (err, res, body) { var error = err || common.checkResponse(res, ["text/xml", "application/xml"]); if (error) { callback(common.prependMsgToErr(error, options.source, true)); } else { convert(options, body, parseFn, callback); } }); }
javascript
{ "resource": "" }
q63291
getFile
test
function getFile (options, parseFn, callback) { fs.readFile(options.source, function (err, data) { if (err) { callback(common.prependMsgToErr(err, options.source, true)); } else { convert(options, data, parseFn, callback); } }); }
javascript
{ "resource": "" }
q63292
test
function (error, message, quoteInput) { var result, prepend, empty = "", quote = "'"; if (error) { if (message) { prepend = quoteInput ? empty.concat(quote, message, quote) : message; } // Force Error instance, coerce given error to a string error = error instanceof Error ? error : new Error(empty + error); // If message supplied, prepend it error.message = prepend ? empty.concat(prepend, ": ", error.message) : error.message; result = error; } return result; }
javascript
{ "resource": "" }
q63293
test
function (res, mediaTypes) { var contentTypeOk, result = "status: '" + res.statusCode + "', GET failed."; mediaTypes = !Array.isArray(mediaTypes) ? [mediaTypes] : mediaTypes; if (res.statusCode === 200) { // if content-type exists, and media type found then contentTypeOk contentTypeOk = res.headers["content-type"] && // empty array and none found return true !mediaTypes.every(function(mediaType) { // flip -1 to 0 and NOT, so that true == NOT found, found stops loop w/false return !~res.headers["content-type"].indexOf(mediaType); }); result = contentTypeOk ? "" : "content-type not one of '"+mediaTypes.join(",")+"'"; } return result; }
javascript
{ "resource": "" }
q63294
nodeCall
test
function nodeCall (nodeFunc /* args... */) { var nodeArgs = Array.prototype.slice.call(arguments, 1); return new Promise(function (resolve, reject) { /** * Resolve a node callback */ function nodeResolver (err, value) { if (err) { reject(err); } else { resolve(value); } } nodeArgs.push(nodeResolver); nodeFunc.apply(nodeFunc, nodeArgs); }); }
javascript
{ "resource": "" }
q63295
prepareWrite
test
function prepareWrite (outputPath, callback) { var path = pathLib.parse(outputPath); var dir = pathLib.join(path.root, path.dir); mkdirp(dir, callback); }
javascript
{ "resource": "" }
q63296
parse
test
function parse (options, document, callback) { xml2js.parseString(document, { trim: true, normalizeTags: true, normalize: true }, function (err, result) { var sitemapUrls = []; var sitemapIndexOptions = Object.assign({}, options, { outputPath: undefined }); if (!err) { // Check if we should process each sitemap in the index. _.forEach( // if the sitemap index is malformed, just blow up result.sitemapindex.sitemap, function (sitemapNode) { // optionally ignore current sitemaps by sitemap policy var shouldProcess = !options.sitemapPolicy || !smLib.stillCurrent(sitemapNode, sitemapIndexOptions); if (shouldProcess) { // if sitemap index is malformed, just blow up sitemapUrls.push(sitemapNode.loc[0]); } } ); // Edge case message for clarity if (sitemapUrls.length === 0) { console.log("[*] No sitemaps qualified for processing"); } // Get all the sitemaps, parse them, and generate input for each Promise.all(sitemapUrls.map(function (sitemapUrl) { var sitemapOptions = Object.assign({}, options, { source: sitemapUrl, input: "sitemap", sitemapOutputDir: false, __sitemapIndex: sitemapIndexOptions }); console.log("[+] Loading the sitemap: '"+sitemapUrl+"'"); return nodeCall(smLib.getUrl, sitemapOptions, processSitemap); })) .then(function () { // Ignore the array of results to this function callback(); }) .catch(callback); } else { callback(err); } }); }
javascript
{ "resource": "" }
q63297
test
function (options, listener) { var opts = Object.assign({}, base.defaults(defaults), options); return base.run(opts, generateInput, listener); }
javascript
{ "resource": "" }
q63298
generateInput
test
function generateInput (options) { return nodeCall( fs.readFile, options.source ) .catch(function (err) { options._abort(err); }) .then(function (data) { var error; if (data) { data.toString().split('\n').every(function (line) { var page = line.replace(/^\s+|\s+$/g, ""); if (!base.input(options, page)) { error = common.prependMsgToErr(base.generatorError(), page, true); return false; } return true; }); if (error) { console.error(error); options._abort(error); } } base.EOI(textfile); }); }
javascript
{ "resource": "" }
q63299
generateInput
test
function generateInput (options) { var result = new Promise(function (resolve, reject) { var all; if (Array.isArray(options.source)) { all = options.source.every(function (sourceUrl) { var url = urlm.parse(sourceUrl); var opts = Object.assign({}, options, { protocol: url.protocol, auth: url.auth, hostname: url.hostname, port: url.port }); if (!base.input(opts, sourceUrl)) { reject( common.prependMsgToErr(base.generatorError(), sourceUrl, true) ); return false; } return true; }); if (all) { resolve(); } } else { reject(new Error("options.source must be an array")); } }); return result .catch(function (error) { options._abort(error); }) .then(function () { base.EOI(array); }); }
javascript
{ "resource": "" }