_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q59500
validation
function(yargs, classNames, packageName) { let pkg = null; packageName.split(".").forEach(seg => { if (pkg === null) { pkg = window[seg]; } else { pkg = pkg[seg]; } }); classNames.forEach(cmd => { require("../../../" + packageName.replace(/\./g, "/") + "/" + cmd); let data = pkg[cmd].getYargsCommand(); yargs.command(data); }); }
javascript
{ "resource": "" }
q59501
validation
function(msgId, ...args) { for (var i = 0; i < args.length; i++) { var arg = args[i]; if (typeof arg !== "string" && typeof arg !== "number" && arg !== null) { args[i] = String(arg); } } if (this.isMachineReadable()) { let str = "##" + msgId + ":" + JSON.stringify(args); console.log(str); } else { var writer = this.getWriter(); let str = this.decode(msgId, ...args); if (writer) { writer(str, msgId, ...args); } else { console.log(str); } } }
javascript
{ "resource": "" }
q59502
validation
function(msgId, ...args) { var msg = qx.tool.compiler.Console.MESSAGE_IDS[msgId]||msgId; var str = qx.lang.String.format(msg.message, args||[]); return str; }
javascript
{ "resource": "" }
q59503
validation
function(marker, showPosition) { var msg = qx.tool.compiler.Console.MESSAGE_IDS[marker.msgId]||marker.msgId; var str = ""; var pos = marker.pos; if (showPosition !== false && pos && pos.start && pos.start.line) { str += "[" + pos.start.line; if (pos.start.column) { str += "," + pos.start.column; } if (pos.end && pos.end.line && pos.end.line !== pos.start.line && pos.end.column !== pos.start.column) { str += " to " + pos.end.line; if (pos.end.column) { str += "," + pos.end.column; } } str += "] "; } str += qx.lang.String.format(msg.message, marker.args||[]); return str; }
javascript
{ "resource": "" }
q59504
validation
async function() { let apps = []; let argv = this.argv; let result = { target: argv.target, outputPath: argv.outputPath||null, locales: null, writeAllTranslations: argv.writeAllTranslations, environment: {}, applications: apps, libraries: argv.library||[], config: argv.configFile||"compile.json", continuous: argv.continuous, verbose: argv.verbose }; if (argv.set) { argv.set.forEach(function(kv) { var m = kv.match(/^([^=\s]+)(=(.+))?$/); if (m) { var key = m[1]; var value = m[3]; try { result.environment[key] = Function("\"use strict\";return (" + value + ")")(); } catch (error) { throw new Error("Failed to translate environment value '"+value+"' to a js datatype - "+error); } } else { throw new Error("Failed to parse environment setting commandline option '"+kv+"'"); } }); } if (argv.locale && argv.locale.length) { result.locales = argv.locale; } return result; }
javascript
{ "resource": "" }
q59505
validation
function() { return { command: "migrate [options]", desc: "migrates a qooxdoo application to the next major version", usage: "migrate", builder: { "verbose": { alias : "v", describe: "enables additional progress output to console", type: "boolean" } }, handler: function(argv) { return new qx.tool.cli.commands.Migrate(argv) .process() .catch(e => { console.error(e.stack || e.message); process.exit(1); }); } }; }
javascript
{ "resource": "" }
q59506
validation
function(type) { if (!type) { return null; } if (type.$$type == "Class") { return type; } if (type == "build") { return qx.tool.compiler.targets.BuildTarget; } if (type == "source") { return qx.tool.compiler.targets.SourceTarget; } if (type == "typescript") { throw new qx.tool.cli.Utils.UserError("Typescript targets are no longer supported - please use `typescript: true` in source target instead"); } if (type) { var targetClass; if (type.indexOf(".") < 0) { targetClass = qx.Class.getByName("qx.tool.compiler.targets." + type); } else { targetClass = qx.Class.getByName(type); } return targetClass; } return null; }
javascript
{ "resource": "" }
q59507
validation
function(callback) { var t = this; async.waterfall([ function readDb(callback) { fs.exists(t.__dbFilename, function(exists) { if (exists) { fs.readFile(t.__dbFilename, { encoding: "utf-8" }, callback); } else { callback(null, null); } }); }, function parseDb(data, callback) { t.__db = data && data.trim().length ? jsonlint.parse(data) : {}; callback(null, t.__db); } ], callback); }
javascript
{ "resource": "" }
q59508
scanDir
validation
function scanDir(rootDir, dir, resource, doNotCopy, callback) { // Get the list of files fs.readdir(dir, function(err, files) { if (err) { callback(err); return; } // and process each one async.forEach(files, function(file, callback) { var absFile = path.join(dir, file); fs.stat(absFile, function(err, stat) { if (err) { callback(err); return; } // Directory? recurse if (stat.isDirectory()) { scanDir(rootDir, absFile, resource, doNotCopy, callback); } else { var relFile = absFile.substring(rootDir.length + 1).replace(/\\/g, "/"); var fileInfo = resources[relFile]; delete unconfirmed[relFile]; if (!fileInfo) { fileInfo = resources[relFile] = {}; } fileInfo.doNotCopy = doNotCopy; fileInfo.resource = resource; t.__librariesByResourceUri[relFile] = library; var relDir = dir.substring(rootDir.length + 1).replace(/\\/g, "/"); t.__librariesByResourceFolderUri[relDir] = library; var tmp = ""; relDir.split("/").forEach(seg => { if (tmp.length) { tmp += "/"; } tmp += seg; t.__librariesByResourceFolderUri[tmp] = library; }); var handlers = t.__handlers.filter(handler => handler.matches(absFile)); if (!handlers.length) { callback(); return; } if (handlers.some(handler => handler.needsCompile(absFile, fileInfo, stat))) { fileInfo.mtime = stat.mtime; tasks.push({ fileInfo: fileInfo, absFile: absFile, library: library, handlers: handlers }); } callback(); } }); }, callback); }); }
javascript
{ "resource": "" }
q59509
validation
function(srcPaths) { var t = this; var db = this.__db; // Generate a lookup that maps the resource name to the meta file that // contains the composite var metas = {}; for (var libraryName in db.resources) { var libraryData = db.resources[libraryName]; for (var resourcePath in libraryData) { var fileInfo = libraryData[resourcePath]; if (!fileInfo.meta) { continue; } for (var altPath in fileInfo.meta) { metas[altPath] = resourcePath; } } } // Collect a list of assets var assets = []; var assetPaths = {}; function addAsset(library, resourceName) { if (assetPaths[resourceName] !== undefined) { return; } var libraryData = db.resources[library.getNamespace()]; var fileInfo = libraryData[resourceName]; if (fileInfo.doNotCopy === true) { return; } var asset = { libraryName: library.getNamespace(), filename: resourceName, fileInfo: fileInfo }; // Does this have meta data for a composite? var metaPath = metas[resourceName]; if (metaPath !== null) { var metaInfo = libraryData[metaPath]; if (metaInfo) { // Extract the fragment from the meta data for this particular resource var resMetaData = metaInfo.meta[resourceName]; fileInfo.composite = resMetaData[3]; fileInfo.x = resMetaData[4]; fileInfo.y = resMetaData[5]; if (!assetPaths[metaPath]) { srcPaths.push(metaPath); } } } assets.push(asset); assetPaths[resourceName] = assets.length - 1; } for (var i = 0; i < srcPaths.length; i++) { var srcPath = srcPaths[i]; var library = t.findLibraryForResource(srcPath); if (!library) { t.warn("Cannot find library for " + srcPath); continue; } var pos = srcPath.indexOf(":"); if (pos > -1) { srcPath = srcPath.substring(pos + 1); } libraryData = db.resources[library.getNamespace()]; pos = srcPath.indexOf("*"); if (pos > -1) { srcPath = srcPath.substring(0, pos); for (var resourceName in libraryData) { if (resourceName.substring(0, srcPath.length) == srcPath) { addAsset(library, resourceName); } } } else { fileInfo = libraryData[srcPath]; if (fileInfo && (fileInfo.doNotCopy !== true)) { addAsset(library, srcPath); } } } return assets; }
javascript
{ "resource": "" }
q59510
validation
async function(data) { let t = this; let result = {}; return new Promise((resolve, reject) => { async.forEach(data.libraries, function(path, cb) { t.__addLibrary(path, result, cb); }, function(err) { if (err) { reject(err); } else { resolve(result); } }); }); }
javascript
{ "resource": "" }
q59511
validation
function(rootDir, result, cb) { var lib = new qx.tool.compiler.app.Library(); lib.loadManifest(rootDir, function(err) { if (!err) { let s = lib.getNamespace(); let libs = s.split("."); result[libs[0]] = false; } return cb && cb(err, lib); }); }
javascript
{ "resource": "" }
q59512
validation
function(str) { if (str === null) { return null; } str = str.trim(); if (!str) { return null; } var ast = JsonToAst.parseToAst(str); var json = JsonToAst.astToObject(ast); return json; }
javascript
{ "resource": "" }
q59513
validation
async function(filename) { if (!await fs.existsAsync(filename)) { return null; } var data = await fs.readFileAsync(filename, "utf8"); try { return qx.tool.compiler.utils.Json.parseJson(data); } catch (ex) { throw new Error("Failed to load " + filename + ": " + ex); } }
javascript
{ "resource": "" }
q59514
validation
async function(filename, data) { if (!data) { if (await fs.existsAsync(filename)) { fs.unlinkAsync(filename); } } else { await fs.writeFileAsync(filename, JSON.stringify(data, null, 2), "utf8"); } }
javascript
{ "resource": "" }
q59515
validation
function(from, to) { return new Promise((resolve, reject) => { util.mkParentPath(to, function() { var rs = fs.createReadStream(from, { flags: "r", encoding: "binary" }); var ws = fs.createWriteStream(to, { flags: "w", encoding: "binary" }); rs.on("end", function() { resolve(); }); rs.on("error", reject); ws.on("error", reject); rs.pipe(ws); }); }); }
javascript
{ "resource": "" }
q59516
validation
function(filename) { return new Promise((resolve, reject) => { fs.stat(filename, function(err, stats) { if (err && err.code != "ENOENT") { reject(err); } else { resolve(err ? null : stats); } }); }); }
javascript
{ "resource": "" }
q59517
validation
function(filename) { return new Promise((resolve, reject) => { fs.unlink(filename, function(err) { if (err && err.code != "ENOENT") { reject(err); } else { resolve(); } }); }); }
javascript
{ "resource": "" }
q59518
validation
async function(filename, length) { if (await this.safeStat(filename) && length > 1) { var lastFile = null; for (var i = length; i > 0; i--) { var tmp = filename + "." + i; if (i == length) { await this.safeUnlink(tmp); } else if (await this.safeStat(tmp)) { await rename(tmp, lastFile); } lastFile = tmp; } await rename(filename, lastFile); } }
javascript
{ "resource": "" }
q59519
validation
function(name) { return new Promise((resolve, reject) => { rimraf(name, err => { if (err) { reject(err); } else { resolve(); } }); }); }
javascript
{ "resource": "" }
q59520
validation
function(dir) { var drivePrefix = ""; if (process.platform === "win32" && dir.match(/^[a-zA-Z]:/)) { drivePrefix = dir.substring(0, 2); dir = dir.substring(2); } dir = dir.replace(/\\/g, "/"); var segs = dir.split("/"); if (!segs.length) { return drivePrefix + dir; } var currentDir; var index; if (segs[0].length) { currentDir = ""; index = 0; } else { currentDir = "/"; index = 1; } function bumpToNext(nextSeg) { index++; if (currentDir.length && currentDir !== "/") { currentDir += "/"; } currentDir += nextSeg; return next(); } function next() { if (index == segs.length) { if (process.platform === "win32") { currentDir = currentDir.replace(/\//g, "\\"); } return Promise.resolve(drivePrefix + currentDir); } let nextSeg = segs[index]; if (nextSeg == "." || nextSeg == "..") { return bumpToNext(nextSeg); } return new Promise((resolve, reject) => { fs.readdir(currentDir.length == 0 ? "." : drivePrefix + currentDir, { encoding: "utf8" }, (err, files) => { if (err) { reject(err); return; } let nextLowerCase = nextSeg.toLowerCase(); let exact = false; let insensitive = null; for (let i = 0; i < files.length; i++) { if (files[i] === nextSeg) { exact = true; break; } if (files[i].toLowerCase() === nextLowerCase) { insensitive = files[i]; } } if (!exact && insensitive) { nextSeg = insensitive; } bumpToNext(nextSeg).then(resolve); }); }); } return new Promise((resolve, reject) => { fs.stat(drivePrefix + dir, err => { if (err) { if (err.code == "ENOENT") { resolve(drivePrefix + dir); } else { reject(err); } } else { next().then(resolve); } }); }); }
javascript
{ "resource": "" }
q59521
validation
function(args) { var opts; for (var i=0, l=args.length; i<l; i++) { if (args[i].indexOf("settings=") == 0) { opts = args[i].substr(9); break; } else if (args[i].indexOf("'settings=") == 0) { opts = /'settings\=(.*?)'/.exec(args[i])[1]; break; } } if (opts) { opts = opts.replace(/\\\{/g, "{").replace(/\\\}/g, "}"); opts = qx.lang.Json.parse(opts); for (var prop in opts) { var value = opts[prop]; if (typeof value == "string") { value = value.replace(/\$$/g, " "); } try { qx.core.Environment.add(prop, value); } catch(ex) { this.error("Unable to define command-line setting " + prop + ": " + ex); } } } }
javascript
{ "resource": "" }
q59522
ScaleColumns
validation
function ScaleColumns(colsByGroup, maxWidth, totalFlexGrow) { // calculate total width and flexgrow points for coulumns that can be resized angular.forEach(colsByGroup, (cols) => { cols.forEach((column) => { if (!column.canAutoResize){ maxWidth -= column.width; totalFlexGrow -= column.flexGrow; } else { column.width = 0; } }); }); var hasMinWidth = {} var remainingWidth = maxWidth; // resize columns until no width is left to be distributed do { let widthPerFlexPoint = remainingWidth / totalFlexGrow; remainingWidth = 0; angular.forEach(colsByGroup, (cols) => { cols.forEach((column, i) => { // if the column can be resize and it hasn't reached its minimum width yet if (column.canAutoResize && !hasMinWidth[i]){ let newWidth = column.width + column.flexGrow * widthPerFlexPoint; if (column.minWidth !== undefined && newWidth < column.minWidth){ remainingWidth += newWidth - column.minWidth; column.width = column.minWidth; hasMinWidth[i] = true; } else { column.width = newWidth; } } }); }); } while (remainingWidth !== 0); }
javascript
{ "resource": "" }
q59523
GetTotalFlexGrow
validation
function GetTotalFlexGrow(columns){ var totalFlexGrow = 0; for (let c of columns) { totalFlexGrow += c.flexGrow || 0; } return totalFlexGrow; }
javascript
{ "resource": "" }
q59524
ForceFillColumnWidths
validation
function ForceFillColumnWidths(allColumns, expectedWidth, startIdx){ var contentWidth = 0, columnsToResize = startIdx > -1 ? allColumns.slice(startIdx, allColumns.length).filter((c) => { return c.canAutoResize }) : allColumns.filter((c) => { return c.canAutoResize }); allColumns.forEach((c) => { if(!c.canAutoResize){ contentWidth += c.width; } else { contentWidth += (c.$$oldWidth || c.width); } }); var remainingWidth = expectedWidth - contentWidth, additionWidthPerColumn = remainingWidth / columnsToResize.length, exceedsWindow = contentWidth > expectedWidth; columnsToResize.forEach((column) => { if(exceedsWindow){ column.width = column.$$oldWidth || column.width; } else { if(!column.$$oldWidth){ column.$$oldWidth = column.width; } var newSize = column.$$oldWidth + additionWidthPerColumn; if(column.minWith && newSize < column.minWidth){ column.width = column.minWidth; } else if(column.maxWidth && newSize > column.maxWidth){ column.width = column.maxWidth; } else { column.width = newSize; } } }); }
javascript
{ "resource": "" }
q59525
PDU
validation
function PDU() { this.type = asn1ber.pduTypes.GetRequestPDU; this.reqid = 1; this.error = 0; this.errorIndex = 0; this.varbinds = [ new VarBind() ]; }
javascript
{ "resource": "" }
q59526
clearRequest
validation
function clearRequest(reqs, reqid) { var self = this; var entry = reqs[reqid]; if (entry) { if (entry.timeout) { clearTimeout(entry.timeout); } delete reqs[reqid]; } }
javascript
{ "resource": "" }
q59527
parseSingleOid
validation
function parseSingleOid(oid) { if (typeof oid !== 'string') { return oid; } if (oid[0] !== '.') { throw new Error('Invalid OID format'); } oid = oid.split('.') .filter(function (s) { return s.length > 0; }) .map(function (s) { return parseInt(s, 10); }); return oid; }
javascript
{ "resource": "" }
q59528
parseOids
validation
function parseOids(options) { if (options.oid) { options.oid = parseSingleOid(options.oid); } if (options.oids) { options.oids = options.oids.map(parseSingleOid); } }
javascript
{ "resource": "" }
q59529
defaults
validation
function defaults(targ, _defs) { [].slice.call(arguments, 1).forEach(function (def) { Object.keys(def).forEach(function (key) { if (!targ.hasOwnProperty(key)) { targ[key] = def[key]; } }); }); }
javascript
{ "resource": "" }
q59530
compareOids
validation
function compareOids (oidA, oidB) { var mlen, i; // The undefined OID, if there is any, is deemed lesser. if (typeof oidA === 'undefined' && typeof oidB !== 'undefined') { return 1; } else if (typeof oidA !== 'undefined' && typeof oidB === 'undefined') { return -1; } // Check each number part of the OIDs individually, and if there is any // position where one OID is larger than the other, return accordingly. // This will only check up to the minimum length of both OIDs. mlen = Math.min(oidA.length, oidB.length); for (i = 0; i < mlen; i++) { if (oidA[i] > oidB[i]) { return -1; } else if (oidB[i] > oidA[i]) { return 1; } } // If there is one OID that is longer than the other after the above comparison, // consider the shorter OID to be lesser. if (oidA.length > oidB.length) { return -1; } else if (oidB.length > oidA.length) { return 1; } else { // The OIDs are obviously equal. return 0; } }
javascript
{ "resource": "" }
q59531
Session
validation
function Session(options) { var self = this; self.options = options || {}; defaults(self.options, exports.defaultOptions); self.reqs = {}; self.socket = dgram.createSocket(self.options.family); self.socket.on('message', msgReceived.bind(self)); self.socket.on('close', function () { // Remove the socket so we don't try to send a message on // it when it's closed. self.socket = undefined; }); self.socket.on('error', function () { // Errors will be emitted here as well as on the callback to the send function. // We handle them there, so doing anything here is unnecessary. // But having no error handler trips up the test suite. }); // If exclusive is false (default), then cluster workers will use the same underlying handle, // allowing connection handling duties to be shared. // When exclusive is true, the handle is not shared, and attempted port sharing results in an error. self.socket.bind({ port: 0, //get a random port automatically exclusive: true // you should not share the same port, otherwise yours packages will be screwed up between workers }); }
javascript
{ "resource": "" }
q59532
inTree
validation
function inTree(root, oid) { var i; if (oid.length <= root.length) { return false; } for (i = 0; i < root.length; i++) { if (oid[i] !== root[i]) { return false; } } return true; }
javascript
{ "resource": "" }
q59533
wrapper
validation
function wrapper(type, contents) { var buf, len, i; // Get the encoded length of the contents len = lengthArray(contents.length); // Set up a buffer with the type and length bytes plus a straight copy of the content. buf = new Buffer(1 + contents.length + len.length); buf[0] = type; for (i = 1; i < len.length + 1; i++) { buf[i] = len[i - 1]; } contents.copy(buf, len.length + 1, 0); return buf; }
javascript
{ "resource": "" }
q59534
oidArray
validation
function oidArray(oid) { var bytes, i, val; // Enforce some minimum requirements on the OID. if (oid.length < 2) { throw new Error("Minimum OID length is two."); } else if (oid[0] > 2) { throw new Error("Invalid OID"); } else if (oid[0] == 0 && oid[1] > 39) { throw new Error("Invalid OID"); } else if (oid[0] == 1 && oid[1] > 39) { throw new Error("Invalid OID"); } else if (oid[0] == 2 && oid[1] > 79) { throw new Error("Invalid OID"); } // Calculate the first byte of the encoded OID according to the 'special' rule. bytes = [ 40 * oid[0] + oid[1] ]; // For the rest of the OID, encode each number individually and add the // resulting bytes to the buffer. for (i = 2; i < oid.length; i++) { val = oid[i]; if (val > 127) { bytes = bytes.concat(oidInt(val)); } else { bytes.push(val); } } return bytes; }
javascript
{ "resource": "" }
q59535
intArray
validation
function intArray(val) { var array = [], encVal = val, bytes; if (val === 0) { array.push(0); } else { if (val < 0) { bytes = Math.floor(1 + Math.log(-val) / LOG256); // Encode negatives as 32-bit two's complement. Let's hope that fits. encVal += Math.pow(2, 8 * bytes); } while (encVal > 0) { array.push(encVal % 256); encVal = parseInt(encVal / 256, 10); } } // Do not produce integers that look negative (high bit // of first byte set). if (val > 0 && array[array.length - 1] >= 0x80) { array.push(0); } return array.reverse(); }
javascript
{ "resource": "" }
q59536
insureFreshToken
validation
function insureFreshToken(conn, cb) { var rh = conn.requestHeaders; if (rh && rh.authorization && conn.user && rh.authorization.indexOf('Bearer ') === 0) { var stashedToken = tokenMgmt.currentToken(conn.user, conn.loginBaseUrl, conn.mgmtServer); if (tokenMgmt.isInvalidOrExpired(stashedToken)) { return conn.refreshToken(stashedToken, function(e, result){ if (e) { throw new Error('error refreshing token: ' + e ); } cb(merge(true, { headers: rh})); }); } else { cb(merge(true, { headers: rh})); } } else { cb(merge(true, { headers: rh})); } }
javascript
{ "resource": "" }
q59537
validation
function (arg) { var value = arg.value; var flag = arg.flag; var result = null; if (value) { value = Array.isArray(value) ? value : [value]; result = []; value.forEach(function (path) { result.push(flag); result.push(path); }); } return result; }
javascript
{ "resource": "" }
q59538
scaleSankeySize
validation
function scaleSankeySize(graph, margin) { var maxColumn = max(graph.nodes, function (node) { return node.column; }); var currentWidth = x1 - x0; var currentHeight = y1 - y0; var newWidth = currentWidth + margin.right + margin.left; var newHeight = currentHeight + margin.top + margin.bottom; var scaleX = currentWidth / newWidth; var scaleY = currentHeight / newHeight; x0 = x0 * scaleX + margin.left; x1 = margin.right == 0 ? x1 : x1 * scaleX; y0 = y0 * scaleY + margin.top; y1 = y1 * scaleY; graph.nodes.forEach(function (node) { node.x0 = x0 + node.column * ((x1 - x0 - dx) / maxColumn); node.x1 = node.x0 + dx; }); return scaleY; }
javascript
{ "resource": "" }
q59539
computeNodeDepths
validation
function computeNodeDepths(graph) { var nodes, next, x; for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) { nodes.forEach(function (node) { node.depth = x; node.sourceLinks.forEach(function (link) { if (next.indexOf(link.target) < 0 && !link.circular) { next.push(link.target); } }); }); } for (nodes = graph.nodes, next = [], x = 0; nodes.length; ++x, nodes = next, next = []) { nodes.forEach(function (node) { node.height = x; node.targetLinks.forEach(function (link) { if (next.indexOf(link.source) < 0 && !link.circular) { next.push(link.source); } }); }); } // assign column numbers, and get max value graph.nodes.forEach(function (node) { node.column = Math.floor(align.call(null, node, x)); }); }
javascript
{ "resource": "" }
q59540
sortLinkColumnAscending
validation
function sortLinkColumnAscending(link1, link2) { if (linkColumnDistance(link1) == linkColumnDistance(link2)) { return link1.circularLinkType == 'bottom' ? sortLinkSourceYDescending(link1, link2) : sortLinkSourceYAscending(link1, link2); } else { return linkColumnDistance(link2) - linkColumnDistance(link1); } }
javascript
{ "resource": "" }
q59541
selfLinking
validation
function selfLinking(link, id) { return getNodeID(link.source, id) == getNodeID(link.target, id); }
javascript
{ "resource": "" }
q59542
find
validation
function find (nodeById, id) { var node = nodeById.get(id) if (!node) throw new Error('missing: ' + id) return node }
javascript
{ "resource": "" }
q59543
computeNodeLinks
validation
function computeNodeLinks (graph) { graph.nodes.forEach(function (node, i) { node.index = i node.sourceLinks = [] node.targetLinks = [] }) var nodeById = map(graph.nodes, id) graph.links.forEach(function (link, i) { link.index = i var source = link.source var target = link.target if (typeof source !== 'object') { source = link.source = find(nodeById, source) } if (typeof target !== 'object') { target = link.target = find(nodeById, target) } source.sourceLinks.push(link) target.targetLinks.push(link) }) return graph }
javascript
{ "resource": "" }
q59544
linkAngle
validation
function linkAngle (link) { var adjacent = Math.abs(link.y1 - link.y0) var opposite = Math.abs(link.target.x0 - link.source.x1) return Math.atan(opposite / adjacent) }
javascript
{ "resource": "" }
q59545
circularLinksCross
validation
function circularLinksCross (link1, link2) { if (link1.source.column < link2.target.column) { return false } else if (link1.target.column > link2.source.column) { return false } else { return true } }
javascript
{ "resource": "" }
q59546
numberOfNonSelfLinkingCycles
validation
function numberOfNonSelfLinkingCycles (node, id) { var sourceCount = 0 node.sourceLinks.forEach(function (l) { sourceCount = l.circular && !selfLinking(l, id) ? sourceCount + 1 : sourceCount }) var targetCount = 0 node.targetLinks.forEach(function (l) { targetCount = l.circular && !selfLinking(l, id) ? targetCount + 1 : targetCount }) return sourceCount + targetCount }
javascript
{ "resource": "" }
q59547
onlyCircularLink
validation
function onlyCircularLink (link) { var nodeSourceLinks = link.source.sourceLinks var sourceCount = 0 nodeSourceLinks.forEach(function (l) { sourceCount = l.circular ? sourceCount + 1 : sourceCount }) var nodeTargetLinks = link.target.targetLinks var targetCount = 0 nodeTargetLinks.forEach(function (l) { targetCount = l.circular ? targetCount + 1 : targetCount }) if (sourceCount > 1 || targetCount > 1) { return false } else { return true } }
javascript
{ "resource": "" }
q59548
nodesOverlap
validation
function nodesOverlap (nodeA, nodeB) { // test if nodeA top partially overlaps nodeB if (nodeA.y0 > nodeB.y0 && nodeA.y0 < nodeB.y1) { return true } else if (nodeA.y1 > nodeB.y0 && nodeA.y1 < nodeB.y1) { // test if nodeA bottom partially overlaps nodeB return true } else if (nodeA.y0 < nodeB.y0 && nodeA.y1 > nodeB.y1) { // test if nodeA covers nodeB return true } else { return false } }
javascript
{ "resource": "" }
q59549
validation
function (options, callback) { if (!('headers' in options)) { options.headers = {}; } options.json = true; options.headers['User-Agent'] = Poloniex.USER_AGENT; options.strictSSL = Poloniex.STRICT_SSL; options.timeout = Poloniex.TIMEOUT; return new Promise(function (resolve, reject) { request(options, function (err, response, body) { // Empty response if (!err && (typeof body === 'undefined' || body === null)) { err = new Error('Empty response from remote server'); } if (err) { reject(err); } else { resolve(body); } if (typeof callback === 'function') { callback(err, body); } }); }); }
javascript
{ "resource": "" }
q59550
validation
function (command, parameters, callback) { if (typeof parameters === 'function') { callback = parameters; parameters = {}; } parameters || (parameters = {}); parameters.command = command; const options = { method: 'GET', url: PUBLIC_API_URL, qs: parameters }; options.qs.command = command; return this._request(options, callback); }
javascript
{ "resource": "" }
q59551
validation
function (command, parameters, callback) { if (typeof parameters === 'function') { callback = parameters; parameters = {}; } parameters || (parameters = {}); parameters.command = command; parameters.nonce = nonce(); const options = { method: 'POST', url: PRIVATE_API_URL, form: parameters, headers: this._getPrivateHeaders(parameters) }; return this._request(options, callback); }
javascript
{ "resource": "" }
q59552
spawnChildProcess
validation
function spawnChildProcess(bin, args, option) { const result = spawnCancelableChild(bin, args, option); return result.process; }
javascript
{ "resource": "" }
q59553
spawnCancelableChild
validation
function spawnCancelableChild(bin, args, option) { let innerCancel = null; let isCanceled = false; const canceller = function () { if (isCanceled) { return; } isCanceled = true; if (typeof innerCancel === 'function') { innerCancel(); } }; const process = new Promise(function(resolve, reject){ if (isCanceled) { reject(); return; } console.log('spawn: ' + bin + ' ' + args.join(' ')); const proc = childProcess.spawn(bin, args, option); innerCancel = function () { proc.kill('SIGINT'); }; proc.on('exit', function(status) { resolve(status); }); }); return { canceller, process, }; }
javascript
{ "resource": "" }
q59554
CasStrategy
validation
function CasStrategy(options, verify) { if (typeof options == 'function') { verify = options; options = undefined; } options = options || {}; if (!verify) { throw new TypeError('CasStrategy requires a verify callback'); } if (!options.casURL) { throw new TypeError('CasStrategy requires a casURL option'); } Strategy.call(this); this.name = 'cas'; this._verify = verify; this._passReqToCallback = options.passReqToCallback; this.casBaseUrl = options.casURL; this.casPgtUrl = options.pgtURL || undefined; this.casPropertyMap = options.propertyMap || {}; this.casSessionKey = options.sessionKey || 'cas'; this.cas = new CAS({ base_url: this.casBaseUrl, version: 2, external_pgt_url: this.casPgtUrl, ssl_cert: options.sslCert, ssl_key: options.sslKey, ssl_ca: options.sslCA }); }
javascript
{ "resource": "" }
q59555
PgtServer
validation
function PgtServer(casURL, pgtURL, serverCertificate, serverKey, serverCA) { var parsedURL = url.parse(pgtURL); var cas = new CAS({ base_url: casURL, version: 2.0, pgt_server: true, pgt_host: parsedURL.hostname, pgt_port: parsedURL.port, ssl_key: serverKey, ssl_cert: serverCertificate, ssl_ca: serverCA || null }); }
javascript
{ "resource": "" }
q59556
validation
function(element, link) { // Normalize the link parameter if(angular.isFunction(link)) { link = { post: link }; } var compiledContents; return { pre: (link && link.pre) ? link.pre : null, /** * Compiles and re-adds the contents */ post: function(scope, element, attrs, trvw) { // Compile our template if(!compiledContents) { compiledContents = $compile(trvw.getNodeTpl()); } // Add the compiled template compiledContents(scope, function(clone) { element.append(clone); }); // Call the post-linking function, if any if(link && link.post) { link.post.apply(null, arguments); } } }; }
javascript
{ "resource": "" }
q59557
validation
function(scope, element, attrs, trvw) { // Compile our template if(!compiledContents) { compiledContents = $compile(trvw.getNodeTpl()); } // Add the compiled template compiledContents(scope, function(clone) { element.append(clone); }); // Call the post-linking function, if any if(link && link.post) { link.post.apply(null, arguments); } }
javascript
{ "resource": "" }
q59558
validation
function(baseDir, importPath) { var parts = importPath.split('/'); var pathname = path.join(baseDir, importPath); if (parts[0] === 'node_modules') { // Gets all but the first element of array (i.e. node_modules). importPath = parts.slice(1).join('/'); } // Returns an array of all parent node_modules directories. var dirs = findNodeModules({ cwd: baseDir, relative: false }); _.each(dirs, function(dir) { if (fs.existsSync(path.join(dir, importPath))) { pathname = path.join(dir, importPath); return false; // Exits iteration by returning false. } }); return pathname; }
javascript
{ "resource": "" }
q59559
validation
function (options, callback) { if (_.isFunction(options) && !callback) { callback = options; options = {}; } options = _.clone(options); bootcode(function (err, code) { if (err) { return callback(err); } if (!code) { return callback(new Error('sandbox: bootcode missing!')); } options.bootCode = code; // assign the code in options PostmanSandbox.create(options, callback); }); }
javascript
{ "resource": "" }
q59560
extend
validation
function extend(klass, instance, override, methods) { var extendee = instance ? klass.prototype : klass; initializeClass(klass); iterateOverObject(methods, function(name, method) { var original = extendee[name]; var existed = hasOwnProperty(extendee, name); if(typeof override === 'function') { method = wrapNative(extendee[name], method, override); } if(override !== false || !extendee[name]) { defineProperty(extendee, name, method); } // If the method is internal to Sugar, then store a reference so it can be restored later. klass['SugarMethods'][name] = { instance: instance, method: method, original: original, existed: existed }; }); }
javascript
{ "resource": "" }
q59561
buildObjectInstanceMethods
validation
function buildObjectInstanceMethods(set, target) { extendSimilar(target, true, false, set, function(methods, name) { methods[name + (name === 'equal' ? 's' : '')] = function() { return object[name].apply(null, [this].concat(multiArgs(arguments))); } }); }
javascript
{ "resource": "" }
q59562
arrayEach
validation
function arrayEach(arr, fn, startIndex, loop) { var length, index, i; if(startIndex < 0) startIndex = arr.length + startIndex; i = isNaN(startIndex) ? 0 : startIndex; length = loop === true ? arr.length + i : arr.length; while(i < length) { index = i % arr.length; if(!(index in arr)) { return iterateOverSparseArray(arr, fn, i, loop); } else if(fn.call(arr, arr[index], index, arr) === false) { break; } i++; } }
javascript
{ "resource": "" }
q59563
collateStrings
validation
function collateStrings(a, b) { var aValue, bValue, aChar, bChar, aEquiv, bEquiv, index = 0, tiebreaker = 0; a = getCollationReadyString(a); b = getCollationReadyString(b); do { aChar = getCollationCharacter(a, index); bChar = getCollationCharacter(b, index); aValue = getCollationValue(aChar); bValue = getCollationValue(bChar); if(aValue === -1 || bValue === -1) { aValue = a.charCodeAt(index) || null; bValue = b.charCodeAt(index) || null; } aEquiv = aChar !== a.charAt(index); bEquiv = bChar !== b.charAt(index); if(aEquiv !== bEquiv && tiebreaker === 0) { tiebreaker = aEquiv - bEquiv; } index += 1; } while(aValue != null && bValue != null && aValue === bValue); if(aValue === bValue) return tiebreaker; return aValue < bValue ? -1 : 1; }
javascript
{ "resource": "" }
q59564
collectDateArguments
validation
function collectDateArguments(args, allowDuration) { var obj, arr; if(isObject(args[0])) { return args; } else if (isNumber(args[0]) && !isNumber(args[1])) { return [args[0]]; } else if (isString(args[0]) && allowDuration) { return [getDateParamsFromString(args[0]), args[1]]; } obj = {}; DateArgumentUnits.forEach(function(u,i) { obj[u.unit] = args[i]; }); return [obj]; }
javascript
{ "resource": "" }
q59565
getFormatMatch
validation
function getFormatMatch(match, arr) { var obj = {}, value, num; arr.forEach(function(key, i) { value = match[i + 1]; if(isUndefined(value) || value === '') return; if(key === 'year') { obj.yearAsString = value.replace(/'/, ''); } num = parseFloat(value.replace(/'/, '').replace(/,/, '.')); obj[key] = !isNaN(num) ? num : value.toLowerCase(); }); return obj; }
javascript
{ "resource": "" }
q59566
getWeekNumber
validation
function getWeekNumber(date) { date = date.clone(); var dow = callDateGet(date, 'Day') || 7; date.addDays(4 - dow).reset(); return 1 + floor(date.daysSince(date.clone().beginningOfYear()) / 7); }
javascript
{ "resource": "" }
q59567
formatDate
validation
function formatDate(date, format, relative, localeCode) { var adu, loc = getLocalization(localeCode), caps = regexp(/^[A-Z]/), value, shortcut; if(!date.isValid()) { return 'Invalid Date'; } else if(Date[format]) { format = Date[format]; } else if(isFunction(format)) { adu = getAdjustedUnitWithMonthFallback(date); format = format.apply(date, adu.concat(loc)); } if(!format && relative) { adu = adu || getAdjustedUnitWithMonthFallback(date); // Adjust up if time is in ms, as this doesn't // look very good for a standard relative date. if(adu[1] === 0) { adu[1] = 1; adu[0] = 1; } return loc.getRelativeFormat(adu); } format = format || 'long'; format = loc[format] || format; DateOutputFormats.forEach(function(dof) { format = format.replace(regexp('\\{('+dof.token+')(\\d)?\\}', dof.word ? 'i' : ''), function(m,t,d) { var val = dof.format(date, loc, d || 1, t), l = t.length, one = t.match(/^(.)\1+$/); if(dof.word) { if(l === 3) val = val.slice(0,3); if(one || t.match(caps)) val = simpleCapitalize(val); } else if(one && !dof.text) { val = (isNumber(val) ? padNumber(val, l) : val.toString()).slice(-l); } return val; }); }); return format; }
javascript
{ "resource": "" }
q59568
compareDate
validation
function compareDate(d, find, buffer, forceUTC) { var p, t, min, max, minOffset, maxOffset, override, capitalized, accuracy = 0, loBuffer = 0, hiBuffer = 0; p = getExtendedDate(find, null, null, forceUTC); if(buffer > 0) { loBuffer = hiBuffer = buffer; override = true; } if(!p.date.isValid()) return false; if(p.set && p.set.specificity) { DateUnits.forEach(function(u, i) { if(u.unit === p.set.specificity) { accuracy = u.multiplier(p.date, d - p.date) - 1; } }); capitalized = simpleCapitalize(p.set.specificity); if(p.set['edge'] || p.set['shift']) { p.date['beginningOf' + capitalized](); } if(p.set.specificity === 'month') { max = p.date.clone()['endOf' + capitalized]().getTime(); } if(!override && p.set['sign'] && p.set.specificity != 'millisecond') { // If the time is relative, there can occasionally be an disparity between the relative date // and "now", which it is being compared to, so set an extra buffer to account for this. loBuffer = 50; hiBuffer = -50; } } t = d.getTime(); min = p.date.getTime(); max = max || (min + accuracy); max = compensateForTimezoneTraversal(d, min, max); return t >= (min - loBuffer) && t <= (max + hiBuffer); }
javascript
{ "resource": "" }
q59569
validation
function (done) { var dependencies = [], addPackageToDependencies = function (pkg) { dependencies.push(pkg.name); }; this.bundler.on('package', addPackageToDependencies); return this.compile(function (err) { this.bundler.removeListener('package', addPackageToDependencies); return done(err, _.uniq(dependencies).sort()); }.bind(this)); }
javascript
{ "resource": "" }
q59570
Foscam
validation
function Foscam(config) { if (!config) { throw new Error('no config was supplied'); } this.username = config.username; this.password = config.password; this.address = config.host; this.port = config.port || 88; this.protocol = config.protocol || 'http'; this.rejectUnauthorizedCerts = 'rejectUnauthorizedCerts' in config ? config.rejectUnauthorizedCerts : true; this.baseUrl = this.protocol + '://' + this.address + ':' + this.port; this.url = this.baseUrl + '/cgi-bin/CGIProxy.fcgi'; this.streamUrl = this.baseUrl + '/cgi-bin/CGIStream.cgi'; this.rpClient = rp.defaults({ rejectUnauthorized: this.rejectUnauthorizedCerts, qs: { usr: this.username, pwd: this.password } }); }
javascript
{ "resource": "" }
q59571
put
validation
function put(point, data, octree, octant, depth) { let children = octant.children; let exists = false; let done = false; let i, l; if(octant.contains(point, octree.bias)) { if(children === null) { if(octant.points === null) { octant.points = []; octant.data = []; } else { for(i = 0, l = octant.points.length; !exists && i < l; ++i) { exists = octant.points[i].equals(point); } } if(exists) { octant.data[i - 1] = data; done = true; } else if(octant.points.length < octree.maxPoints || depth === octree.maxDepth) { octant.points.push(point.clone()); octant.data.push(data); ++octree.pointCount; done = true; } else { octant.split(); octant.redistribute(octree.bias); children = octant.children; } } if(children !== null) { ++depth; for(i = 0, l = children.length; !done && i < l; ++i) { done = put(point, data, octree, children[i], depth); } } } return done; }
javascript
{ "resource": "" }
q59572
fetch
validation
function fetch(point, octree, octant) { const children = octant.children; let result = null; let i, l; let points; if(octant.contains(point, octree.bias)) { if(children !== null) { for(i = 0, l = children.length; result === null && i < l; ++i) { result = fetch(point, octree, children[i]); } } else if(octant.points !== null) { points = octant.points; for(i = 0, l = points.length; result === null && i < l; ++i) { if(point.equals(points[i])) { result = octant.data[i]; } } } } return result; }
javascript
{ "resource": "" }
q59573
move
validation
function move(point, position, octree, octant, parent, depth) { const children = octant.children; let result = null; let i, l; let points; if(octant.contains(point, octree.bias)) { if(octant.contains(position, octree.bias)) { // The point and the new position both fall into the current octant. if(children !== null) { ++depth; for(i = 0, l = children.length; result === null && i < l; ++i) { result = move(point, position, octree, children[i], octant, depth); } } else if(octant.points !== null) { // No divergence - the point can be updated in place. points = octant.points; for(i = 0, l = points.length; i < l; ++i) { if(point.equals(points[i])) { // The point exists! Update its position. points[i].copy(position); result = octant.data[i]; break; } } } } else { // Retrieve the point and remove it. result = remove(point, octree, octant, parent); // Go back to the parent octant and add the updated point. put(position, result, octree, parent, depth - 1); } } return result; }
javascript
{ "resource": "" }
q59574
findPoints
validation
function findPoints(point, radius, skipSelf, octant, result) { const children = octant.children; let i, l; if(children !== null) { let child; for(i = 0, l = children.length; i < l; ++i) { child = children[i]; if(child.contains(point, radius)) { findPoints(point, radius, skipSelf, child, result); } } } else if(octant.points !== null) { const points = octant.points; const rSq = radius * radius; let p; for(i = 0, l = points.length; i < l; ++i) { p = points[i]; if(p.equals(point)) { if(!skipSelf) { result.push({ point: p.clone(), data: octant.data[i] }); } } else if(p.distanceToSquared(point) <= rSq) { result.push({ point: p.clone(), data: octant.data[i] }); } } } }
javascript
{ "resource": "" }
q59575
cull
validation
function cull(octant, region, result) { const children = octant.children; let i, l; b.min = octant.min; b.max = octant.max; if(region.intersectsBox(b)) { if(children !== null) { for(i = 0, l = children.length; i < l; ++i) { cull(children[i], region, result); } } else { result.push(octant); } } }
javascript
{ "resource": "" }
q59576
findOctantsByLevel
validation
function findOctantsByLevel(octant, level, depth, result) { const children = octant.children; let i, l; if(depth === level) { result.push(octant); } else if(children !== null) { ++depth; for(i = 0, l = children.length; i < l; ++i) { findOctantsByLevel(children[i], level, depth, result); } } }
javascript
{ "resource": "" }
q59577
findEntryOctant
validation
function findEntryOctant(tx0, ty0, tz0, txm, tym, tzm) { let entry = 0; // Find the entry plane. if(tx0 > ty0 && tx0 > tz0) { // YZ-plane. if(tym < tx0) { entry |= 2; } if(tzm < tx0) { entry |= 1; } } else if(ty0 > tz0) { // XZ-plane. if(txm < ty0) { entry |= 4; } if(tzm < ty0) { entry |= 1; } } else { // XY-plane. if(txm < tz0) { entry |= 4; } if(tym < tz0) { entry |= 2; } } return entry; }
javascript
{ "resource": "" }
q59578
findNextOctant
validation
function findNextOctant(currentOctant, tx1, ty1, tz1) { let min; let exit = 0; // Find the exit plane. if(tx1 < ty1) { min = tx1; exit = 0; // YZ-plane. } else { min = ty1; exit = 1; // XZ-plane. } if(tz1 < min) { exit = 2; // XY-plane. } return octantTable[currentOctant][exit]; }
javascript
{ "resource": "" }
q59579
raycastOctant
validation
function raycastOctant(octant, tx0, ty0, tz0, tx1, ty1, tz1, raycaster, intersects) { const children = octant.children; let currentOctant; let txm, tym, tzm; if(tx1 >= 0.0 && ty1 >= 0.0 && tz1 >= 0.0) { if(children === null) { // Leaf. intersects.push(octant); } else { // Compute means. txm = 0.5 * (tx0 + tx1); tym = 0.5 * (ty0 + ty1); tzm = 0.5 * (tz0 + tz1); currentOctant = findEntryOctant(tx0, ty0, tz0, txm, tym, tzm); do { /* The possibilities for the next node are passed in the same respective * order as the t-values. Hence, if the first value is found to be the * greatest, the fourth one will be returned. If the second value is the * greatest, the fifth one will be returned, etc. */ switch(currentOctant) { case 0: raycastOctant(children[flags], tx0, ty0, tz0, txm, tym, tzm, raycaster, intersects); currentOctant = findNextOctant(currentOctant, txm, tym, tzm); break; case 1: raycastOctant(children[flags ^ 1], tx0, ty0, tzm, txm, tym, tz1, raycaster, intersects); currentOctant = findNextOctant(currentOctant, txm, tym, tz1); break; case 2: raycastOctant(children[flags ^ 2], tx0, tym, tz0, txm, ty1, tzm, raycaster, intersects); currentOctant = findNextOctant(currentOctant, txm, ty1, tzm); break; case 3: raycastOctant(children[flags ^ 3], tx0, tym, tzm, txm, ty1, tz1, raycaster, intersects); currentOctant = findNextOctant(currentOctant, txm, ty1, tz1); break; case 4: raycastOctant(children[flags ^ 4], txm, ty0, tz0, tx1, tym, tzm, raycaster, intersects); currentOctant = findNextOctant(currentOctant, tx1, tym, tzm); break; case 5: raycastOctant(children[flags ^ 5], txm, ty0, tzm, tx1, tym, tz1, raycaster, intersects); currentOctant = findNextOctant(currentOctant, tx1, tym, tz1); break; case 6: raycastOctant(children[flags ^ 6], txm, tym, tz0, tx1, ty1, tzm, raycaster, intersects); currentOctant = findNextOctant(currentOctant, tx1, ty1, tzm); break; case 7: raycastOctant(children[flags ^ 7], txm, tym, tzm, tx1, ty1, tz1, raycaster, intersects); // Far top right octant. No other octants can be reached from here. currentOctant = 8; break; } } while(currentOctant < 8); } } }
javascript
{ "resource": "" }
q59580
deferred
validation
function deferred(options) { let args = null; const promise = new Promise((resolve, reject) => args = [resolve, reject, options]); promise.defer = function defer() { if (!args) throw new Error('defer has already been called'); const callback = callbackBuilder.apply(undefined, args); args = null; return callback; }; return promise; }
javascript
{ "resource": "" }
q59581
withTimeout
validation
function withTimeout(promise, delay, message) { let timeout; const timeoutPromise = new Promise((resolve, reject) => { // Instantiate the error here to capture a more useful stack trace. const error = message instanceof Error ? message : new Error(message || 'Operation timed out.'); timeout = setTimeout(reject, delay, error); }); return Promise.race([promise, timeoutPromise]).then((value) => { clearTimeout(timeout); return value; }, (err) => { clearTimeout(timeout); throw err; }); }
javascript
{ "resource": "" }
q59582
waitOn
validation
function waitOn(emitter, event, waitError) { if (waitError) { return new Promise((resolve, reject) => { function unbind() { emitter.removeListener('error', onError); emitter.removeListener(event, onEvent); } function onEvent(value) { unbind(); resolve(value); } function onError(err) { unbind(); reject(err); } emitter.on('error', onError); emitter.on(event, onEvent); }); } return new Promise((resolve) => emitter.once(event, resolve)); }
javascript
{ "resource": "" }
q59583
promisify
validation
function promisify(orig, options) { if (typeof orig !== 'function') { throw new TypeError('promisify requires a function'); } if (orig[kCustomPromisifiedSymbol]) { const fn = orig[kCustomPromisifiedSymbol]; if (typeof fn !== 'function') { throw new TypeError('The [util.promisify.custom] property must be a function'); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return fn; } function fn() { const args = toArray(arguments); return new Promise((resolve, reject) => { args.push(callbackBuilder(resolve, reject, options)); try { orig.apply(this, args); } catch (err) { reject(err); } }); } Object.setPrototypeOf(fn, Object.getPrototypeOf(orig)); Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true }); return Object.defineProperties(fn, getOwnPropertyDescriptors(orig)); }
javascript
{ "resource": "" }
q59584
promisifyMethod
validation
function promisifyMethod(obj, methodName, options) { if (!obj) { // This object could be anything, including a function, a real object, or an array. throw new TypeError('promisify.method requires a truthy value'); } return promisify(obj[methodName].bind(obj), options); }
javascript
{ "resource": "" }
q59585
promisifyMethods
validation
function promisifyMethods(obj, methodNames, options) { if (!obj) { // This object could be anything, including a function, a real object, or an array. throw new TypeError('promisify.methods requires a truthy value'); } const out = {}; for (let methodName of methodNames) { out[methodName] = promisify(obj[methodName].bind(obj), options); } return out; }
javascript
{ "resource": "" }
q59586
promisifyAll
validation
function promisifyAll(obj, options) { if (!obj) { // This object could be anything, including a function, a real object, or an array. throw new TypeError('promisify.all requires a truthy value'); } const out = {}; for (var name in obj) { if (typeof obj[name] === 'function') { out[name] = promisify(obj[name].bind(obj), options); } } return out; }
javascript
{ "resource": "" }
q59587
unpatchPromise
validation
function unpatchPromise() { for (let method of methods) { if (Promise.prototype[method.name] === method) { delete Promise.prototype[method.name]; } } }
javascript
{ "resource": "" }
q59588
asCheckedCallback
validation
function asCheckedCallback(promise, cb, useOwnMethod) { let called = false; if (useOwnMethod) { promise.asCallback(after); } else { asCallback(promise, after); } function after() { expect(called).toBeFalsy(); called = true; return cb.apply(this, arguments); } }
javascript
{ "resource": "" }
q59589
asCallback
validation
function asCallback(promise, cb) { promise.then((res) => cb(null, res), cb); }
javascript
{ "resource": "" }
q59590
sum
validation
function sum(arr, prop){ return arr.reduce(function(sum, obj){ return sum + obj.stats[prop]; }, 0); }
javascript
{ "resource": "" }
q59591
traverse
validation
function traverse(file) { file = master.resolve(file); fs.stat(file, function(err, stat){ if (!err) { if (stat.isDirectory()) { if (~exports.ignoreDirectories.indexOf(basename(file))) return; fs.readdir(file, function(err, files){ files.map(function(f){ return file + '/' + f; }).forEach(traverse); }); } else { watch(file); } } }); }
javascript
{ "resource": "" }
q59592
watch
validation
function watch(file) { if (!~extensions.indexOf(extname(file))) return; fs.watchFile(file, { interval: interval }, function(curr, prev){ if (curr.mtime > prev.mtime) { console.log(' \033[36mchanged\033[0m \033[90m- %s\033[0m', file); master.restartWorkers(signal); } }); }
javascript
{ "resource": "" }
q59593
installWatcher
validation
function installWatcher (startingFolder, callback) { bs.init({ server: config.commands.build.output, port: config.commands.build.port, ui: false, open: false, logLevel: 'silent' }) const watcher = createWatcher(path.join(startingFolder, '**/data.xml')) watcher.on('change', () => { callback() bs.reload() }) }
javascript
{ "resource": "" }
q59594
installDevelopmentWatcher
validation
function installDevelopmentWatcher (startingFolder, callback) { const buildFolder = config.commands.build.output // BrowserSync will watch for changes in the assets CSS. // It will also create a server with the build folder and the assets. bs.init({ server: [buildFolder, assets], port: config.commands.build.port, files: path.join(assets, '**/*.css'), ui: false, open: false }) // Meanwhile, the watcher will monitor changes in the templates // and the data files. // Then, when a change occurs, it will regenerate the site through // the provide callback. const templateFolder = path.join(assets, '**/*.html') const dataFolder = path.join(startingFolder, '**/data.xml') const watcher = createWatcher(templateFolder, dataFolder) watcher.on('change', () => { callback() bs.reload() }) }
javascript
{ "resource": "" }
q59595
findAllFiles
validation
function findAllFiles (baseDir, { ignoredFolders = [], maxDepth = undefined } = {}) { let list = [] function search (dir, depth) { fs.readdirSync(dir).forEach(file => { file = path.join(dir, file) // File or directory? Ok. // Otherwise, discard the file. let stat = fs.statSync(file) if (stat.isFile()) { list.push(file) } else if (stat.isDirectory()) { // The directory should be ignored? if (ignoredFolders.includes(path.basename(file))) { return } // Should we stop at this depth? if (maxDepth && (depth >= maxDepth)) { return } search(file, depth + 1) } }) } search(baseDir, 0) return list }
javascript
{ "resource": "" }
q59596
getElementHeight
validation
function getElementHeight (element) { var clone = element.cloneNode(true) clone.style.cssText = 'visibility: hidden; display: block; margin: -999px 0' var height = (element.parentNode.appendChild(clone)).clientHeight element.parentNode.removeChild(clone) return height }
javascript
{ "resource": "" }
q59597
getAbsolutePageUrl
validation
function getAbsolutePageUrl (dataFilePath, pageType) { const buildFolder = createAndGetBuildFolder() const pageFolder = getPageFolder(buildFolder, dataFilePath, pageType) const htmlFilePath = getHtmlFilePath(pageFolder) const relativePath = path.posix.relative(buildFolder, htmlFilePath) return path.posix.join(config.commands.build.baseUrl, relativePath) }
javascript
{ "resource": "" }
q59598
createThumbnails
validation
async function createThumbnails (target, images) { for (const x of images) { const imagePath = path.join(target, x) const thumbPath = path.join(target, `${x}.thumb.jpg`) try { // Background and flatten are for transparent PNGs/Gifs. // We force a white background here. await sharp(imagePath) .resize(450) .background({r: 255, g: 255, b: 255, alpha: 1}) .flatten() .jpeg() .toFile(thumbPath) } catch (e) { const msg = chalk.dim(`(${e.message})`) console.warn(`The '${chalk.bold(x)}' thumbnail has not been generated. ${msg}`) } } }
javascript
{ "resource": "" }
q59599
createTemplate
validation
function createTemplate (type, destination) { const templatePath = getTemplatePath(assets, type) if (!templatePath) { throw new Error('Missing template! Make sure your presskit has a "type" field (product/company)') } registerPartials(assets) registerHelpers(destination) const template = fs.readFileSync(templatePath, 'utf-8') return handlebars.compile(template) }
javascript
{ "resource": "" }