_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q21300 | train | function (cb) {
var self = this;
var dirs = ['classes', 'modules', 'files'];
if (self.options.dumpview) {
dirs.push('json');
}
var writeRedirect = function (dir, file, cb) {
Y.Files.exists(file, function (x) {
... | javascript | {
"resource": ""
} | |
q21301 | train | function (cb) {
var self = this;
Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function (err, opts) {
opts.meta.title = self.data.project.name;
opts.meta.projectRoot = './';
opts.meta.projectAssets = './assets';
opts.... | javascript | {
"resource": ""
} | |
q21302 | train | function (cb) {
var self = this,
stack = new Y.Parallel();
Y.log('Preparing index.html', 'info', 'builder');
self.renderIndex(stack.add(function (html, view) {
stack.html = html;
stack.view = view;
if (self.options.dump... | javascript | {
"resource": ""
} | |
q21303 | train | function (info, classItems, first) {
var self = this;
self._mergeCounter = (first) ? 0 : (self._mergeCounter + 1);
if (self._mergeCounter === 100) {
throw ('YUIDoc detected a loop extending class ' + info.name);
}
if (info.extends || info.uses... | javascript | {
"resource": ""
} | |
q21304 | train | function (cb, data, layout) {
var self = this;
Y.prepare([DEFAULT_THEME, themeDir], self.getProjectMeta(), function (err, opts) {
if (err) {
console.log(err);
}
if (!data.name) {
return;
}
... | javascript | {
"resource": ""
} | |
q21305 | train | function (cb) {
Y.log('Writing API Meta Data', 'info', 'builder');
var self = this;
this.renderAPIMeta(function (js) {
fs.writeFile(path.join(self.options.outdir, 'api.js'), js, Y.charset, cb);
});
} | javascript | {
"resource": ""
} | |
q21306 | train | function (cb) {
var opts = {
meta: {}
};
opts = this.populateClasses(opts);
opts = this.populateModules(opts);
['classes', 'modules'].forEach(function (id) {
opts.meta[id].forEach(function (v, k) {
opts.met... | javascript | {
"resource": ""
} | |
q21307 | train | function (cb) {
var self = this;
var starttime = (new Date()).getTime();
Y.log('Compiling Templates', 'info', 'builder');
this.mixExternal(function () {
self.makeDirs(function () {
Y.log('Copying Assets', 'info', 'builder');
... | javascript | {
"resource": ""
} | |
q21308 | parseMulti | train | function parseMulti(str, compare, arr) {
// TODO: add logic to deal with "0" values? Troublesome because the browser automatically appends a unit for some 0 values.
do {
// pull out the next value (ex. "20px", "12.4rad"):
var result = s.TRANSFORM_VALUE_RE.exec(str);
if (!result) { return arr; }
if (!arr... | javascript | {
"resource": ""
} |
q21309 | TweenGroup | train | function TweenGroup(paused, timeScale) {
this._tweens = [];
this.paused = paused;
this.timeScale = timeScale;
this.__onComplete = this._onComplete.bind(this);
} | javascript | {
"resource": ""
} |
q21310 | extractOriginHeaders_ | train | function extractOriginHeaders_(headers) {
const result = {
isSameOrigin: false,
};
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
const normalizedKey = key.toLowerCase();
// for same-origin requests where the Origin header is missing, AMP sets the amp-same-origin... | javascript | {
"resource": ""
} |
q21311 | isValidOrigin | train | async function isValidOrigin(origin, sourceOrigin) {
// This will fetch the caches from https://cdn.ampproject.org/caches.json the first time it's
// called. Subsequent calls will receive a cached version.
const officialCacheList = await caches.list();
// Calculate the cache specific origin
const ca... | javascript | {
"resource": ""
} |
q21312 | findMetaViewport | train | function findMetaViewport(head) {
for (let node = head.firstChild; node !== null; node = node.nextSibling) {
if (node.tagName === 'meta' && node.attribs.name === 'viewport') {
return node;
}
}
return null;
} | javascript | {
"resource": ""
} |
q21313 | oneBehindFetch | train | async function oneBehindFetch(input, init) {
let cachedResponse = cache.get(input);
if (!cachedResponse) {
cachedResponse = {
maxAge: Promise.resolve(MaxAge.zero()),
};
cache.set(input, cachedResponse);
}
const maxAge = await cachedResponse.maxAge;
if (!maxAge.isExpired()) {
// we have t... | javascript | {
"resource": ""
} |
q21314 | copyAndTransform | train | async function copyAndTransform(file, ampRuntimeVersion) {
const originalHtml = await readFile(file);
const ampFile = file.substring(1, file.length)
.replace('.html', '.amp.html');
const allTransformationsFile = file.substring(1, file.length)
.replace('.html', '.all.html');
const validTransformation... | javascript | {
"resource": ""
} |
q21315 | collectInputFiles | train | function collectInputFiles(pattern) {
return new Promise((resolve, reject) => {
glob(pattern, {root: SRC_DIR, nomount: true}, (err, files) => {
if (err) {
return reject(err);
}
resolve(files);
});
});
} | javascript | {
"resource": ""
} |
q21316 | setFSEventsListener | train | function setFSEventsListener(path, realPath, listener, rawEmitter) {
let watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path;
const parentPath = sysPath.dirname(watchPath);
let cont = FSEventsWatchers.get(watchPath);
// If we've accumulated a substantial number of paths that
// could have been c... | javascript | {
"resource": ""
} |
q21317 | createFsWatchInstance | train | function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path);
emitRaw(rawEvent, evPath, {watchedPath: path});
// emit based on events occurring for files from a directory's watcher in
// case the file's watcher misses it (an... | javascript | {
"resource": ""
} |
q21318 | abbr | train | function abbr(str) {
if (/total|overall/i.test(str)) return str.trim();
return str.replace(/\w+\s?/g, a => a[0]);
} | javascript | {
"resource": ""
} |
q21319 | validateMessageFormat | train | function validateMessageFormat(message) {
function validateTypeStructure(message) {
const typeParts = message.type.split('.'),
baseType = typeParts[0],
typeDepth = typeParts.length;
if (typeDepth > 2)
throw new Error(
'Message type has too many dot separated sections: ' + message.ty... | javascript | {
"resource": ""
} |
q21320 | write | train | function write(file, data) {
writeFileSync(file, data);
console.log(
`✓ ${relative(__dirname + "/../", file)} (${bytes(statSync(file).size)})`
);
} | javascript | {
"resource": ""
} |
q21321 | build | train | async function build(file) {
const { code, map, assets } = await ncc(file, options);
if (Object.keys(assets).length)
console.error("New unexpected assets are being emitted for", file);
const name = basename(file, ".js");
await mkdirp(resolve(DIST_DIR, name));
write(resolve(DIST_DIR, name, "index.js"), c... | javascript | {
"resource": ""
} |
q21322 | runSample | train | async function runSample(projectId = 'your-project-id') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// The text query request.... | javascript | {
"resource": ""
} |
q21323 | train | function() {
var self = this,
val = $.map(self.items(), function(item) {
return self.options.itemValue(item).toString();
});
self.$element.val(val, true);
if (self.options.triggerChange)
self.$element.trigger('change');
} | javascript | {
"resource": ""
} | |
q21324 | makeOptionItemFunction | train | function makeOptionItemFunction(options, key) {
if (typeof options[key] !== 'function') {
var propertyName = options[key];
options[key] = function(item) { return item[propertyName]; };
}
} | javascript | {
"resource": ""
} |
q21325 | keyCombinationInList | train | function keyCombinationInList(keyPressEvent, lookupList) {
var found = false;
$.each(lookupList, function (index, keyCombination) {
if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) {
found = true;
return false;
}
i... | javascript | {
"resource": ""
} |
q21326 | createClassComponent | train | function createClassComponent(ctor, displayName, opts) {
var cdu = createComponentDidUpdate(displayName, opts);
// the wrapper class extends the original class,
// and overwrites its `componentDidUpdate` method,
// to allow why-did-you-update to listen for updates.
// If the component had its own `componentD... | javascript | {
"resource": ""
} |
q21327 | createFunctionalComponent | train | function createFunctionalComponent(ctor, displayName, opts, ReactComponent) {
var cdu = createComponentDidUpdate(displayName, opts);
// We call the original function in the render() method,
// and implement `componentDidUpdate` for `why-did-you-update`
var WDYUFunctionalComponent = function (_ReactComponent) {... | javascript | {
"resource": ""
} |
q21328 | bindFunc | train | function bindFunc(obj, method, observer) {
const oldFn = obj[method]
obj[method] = function(target) {
if (observer) {
observer.call(this, target, {
[method]: true,
})
}
if (oldFn) {
oldFn.call(this, target)
}
}
} | javascript | {
"resource": ""
} |
q21329 | search | train | function search (query) {
if (!allowSearch) {
console.error('Assets for search still loading');
return;
}
var resultDocuments = [];
var results = index.search(query + '~2'); // fuzzy
for (var i=0; i < results.length; i++){
var result = results[i];
doc = documents[result.ref];
doc.summary ... | javascript | {
"resource": ""
} |
q21330 | isEqual | train | function isEqual (array1, array2) {
return array1.length === array2.length && array1.every(function (element, index) {
return element === array2[index];
});
} | javascript | {
"resource": ""
} |
q21331 | readCertificateDataFromFile | train | function readCertificateDataFromFile ({ keyFile, certFile, caFile }) {
let key, cert, ca;
if (keyFile) {
key = fs.readFileSync(keyFile);
}
if (certFile) {
cert = fs.readFileSync(certFile);
}
if (caFile) {
ca = fs.readFileSync(caFile);
}
return { key, cert, ca };
} | javascript | {
"resource": ""
} |
q21332 | walk | train | function walk(arr, key, fn) {
var l = arr.length,
children;
while (l--) {
children = arr[l][key];
if (children) {
walk(children, key, fn);
}
fn(arr[l]);
}
} | javascript | {
"resource": ""
} |
q21333 | run_table_cases | train | async function* run_table_cases(worker, data, test) {
console.log(`Benchmarking \`${test}\``);
try {
for (let x = 0; x < ITERATIONS + TOSS_ITERATIONS; x++) {
const start = performance.now();
const table = worker.table(data.slice ? data.slice() : data);
await table.siz... | javascript | {
"resource": ""
} |
q21334 | convert | train | async function convert(filename, options) {
let file;
if (filename) {
file = fs.readFileSync(filename).toString();
} else {
file = await read_stdin();
}
try {
file = JSON.parse(file);
} catch {}
let tbl = table(file);
let view = tbl.view();
let out;
option... | javascript | {
"resource": ""
} |
q21335 | host | train | async function host(filename, options) {
let files = [path.join(__dirname, "html")];
if (options.assets) {
files = [options.assets, ...files];
}
const server = new WebSocketHost({assets: files, port: options.port});
let file;
if (filename) {
file = fs.readFileSync(filename).toStr... | javascript | {
"resource": ""
} |
q21336 | train | async function(row, col, event) {
if (this.isTreeCol(col)) {
let isShift = false;
if (event.primitiveEvent.detail.primitiveEvent) {
isShift = !!event.primitiveEvent.detail.primitiveEvent.shiftKey; // typecast to boolean
}
let is_expanded = await th... | javascript | {
"resource": ""
} | |
q21337 | copyValues | train | function copyValues(origin, clone, elementSelector) {
var $originalElements = origin.find(elementSelector);
clone.find(elementSelector).each(function(index, item) {
$(item).val($originalElements.eq(index).val());
});
} | javascript | {
"resource": ""
} |
q21338 | setDocType | train | function setDocType($iframe, doctype){
var win, doc;
win = $iframe.get(0);
win = win.contentWindow || win.contentDocument || win;
doc = win.document || win.contentDocument || win;
doc.open();
doc.write(doctype);
... | javascript | {
"resource": ""
} |
q21339 | attachOnBeforePrintEvent | train | function attachOnBeforePrintEvent($iframe, beforePrintHandler) {
var win = $iframe.get(0);
win = win.contentWindow || win.contentDocument || win;
if (typeof beforePrintHandler === "function") {
if ('matchMedia' in win) {
win.ma... | javascript | {
"resource": ""
} |
q21340 | isSatisfiable | train | function isSatisfiable (comparators, options) {
var result = true
var remainingComparators = comparators.slice()
var testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every(function (otherComparator) {
return testComparator.inter... | javascript | {
"resource": ""
} |
q21341 | resizeImageBase64 | train | function resizeImageBase64 (successCallback, errorCallback, file, targetWidth, targetHeight) {
fileIO.readBufferAsync(file).done(function (buffer) {
var strBase64 = encodeToBase64String(buffer);
var imageData = 'data:' + file.contentType + ';base64,' + strBase64;
var image = new Image(); /*... | javascript | {
"resource": ""
} |
q21342 | orientationToRotation | train | function orientationToRotation (orientation) {
// VideoRotation enumerable and BitmapRotation enumerable have the same values
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.capture.videorotation.aspx
// https://msdn.microsoft.com/en-us/library/windows/apps/windows.graphic... | javascript | {
"resource": ""
} |
q21343 | train | function (picture) {
if (options.destinationType === Camera.DestinationType.FILE_URI || options.destinationType === Camera.DestinationType.NATIVE_URI) {
if (options.targetHeight > 0 && options.targetWidth > 0) {
resizeImage(successCallback, errorCallback, picture, options.targetWidth... | javascript | {
"resource": ""
} | |
q21344 | getProps | train | function getProps(componentProps, properties, indexes, suppressQuotes) {
// Make indexes ordered by ascending.
indexes.sort(function(a, b) {
return a - b;
});
const propertiesKeys = Object.keys(properties);
return indexes.map(i => {
const name = propertiesKeys[i];
const value = getPropValue(prope... | javascript | {
"resource": ""
} |
q21345 | getPropIndexes | train | function getPropIndexes(properties, max, filter) {
const indexes = [];
try {
let i = 0;
for (const name in properties) {
if (indexes.length >= max) {
return indexes;
}
// Type is specified in grip's "class" field and for primitive
// values use typeof.
const value = g... | javascript | {
"resource": ""
} |
q21346 | getPropValue | train | function getPropValue(property) {
let value = property;
if (typeof property === "object") {
const keys = Object.keys(property);
if (keys.includes("value")) {
value = property.value;
} else if (keys.includes("getterValue")) {
value = property.getterValue;
}
}
return value;
} | javascript | {
"resource": ""
} |
q21347 | oncePerAnimationFrame | train | function oncePerAnimationFrame(fn) {
let animationId = null;
let argsToPass = null;
return function(...args) {
argsToPass = args;
if (animationId !== null) {
return;
}
animationId = requestAnimationFrame(() => {
fn.call(this, ...argsToPass);
animationId = null;
argsToPass ... | javascript | {
"resource": ""
} |
q21348 | escapeString | train | function escapeString(str, escapeWhitespace) {
return `"${str.replace(escapeRegexp, (match, offset) => {
const c = match.charCodeAt(0);
if (c in escapeMap) {
if (!escapeWhitespace && (c === 9 || c === 0xa || c === 0xd)) {
return match[0];
}
return escapeMap[c];
}
if (c >= 0xd... | javascript | {
"resource": ""
} |
q21349 | getGripPreviewItems | train | function getGripPreviewItems(grip) {
if (!grip) {
return [];
}
// Promise resolved value Grip
if (grip.promiseState && grip.promiseState.value) {
return [grip.promiseState.value];
}
// Array Grip
if (grip.preview && grip.preview.items) {
return grip.preview.items;
}
// Node Grip
if (g... | javascript | {
"resource": ""
} |
q21350 | getGripType | train | function getGripType(object, noGrip) {
if (noGrip || Object(object) !== object) {
return typeof object;
}
if (object.type === "object") {
return object.class;
}
return object.type;
} | javascript | {
"resource": ""
} |
q21351 | isURL | train | function isURL(token) {
try {
if (!validProtocols.test(token)) {
return false;
}
new URL(token);
return true;
} catch (e) {
return false;
}
} | javascript | {
"resource": ""
} |
q21352 | interleave | train | function interleave(items, char) {
return items.reduce((res, item, index) => {
if (index !== items.length - 1) {
return res.concat(item, char);
}
return res.concat(item);
}, []);
} | javascript | {
"resource": ""
} |
q21353 | getBabelFrameIndexes | train | function getBabelFrameIndexes(frames) {
const startIndexes = frames.reduce((accumulator, frame, index) => {
if (
getFrameUrl(frame).match(/regenerator-runtime/i) &&
frame.displayName === "tryCatch"
) {
return [...accumulator, index];
}
return accumulator;
}, []);
const endIndexe... | javascript | {
"resource": ""
} |
q21354 | parseStackString | train | function parseStackString(stack) {
const res = [];
if (!stack) {
return res;
}
const isStacktraceALongString = isLongString(stack);
const stackString = isStacktraceALongString ? stack.initial : stack;
stackString.split("\n").forEach((frame, index, frames) => {
if (!frame) {
// Skip any blank... | javascript | {
"resource": ""
} |
q21355 | hasOwnProperty | train | function hasOwnProperty(value, key) {
if (value.hasOwnProperty && isFunction(value.hasOwnProperty)) {
return value.hasOwnProperty(key);
}
if (value.prototype && value.prototype.hasOwnProperty) {
return value.prototype.hasOwnProperty(key);
}
return false;
} | javascript | {
"resource": ""
} |
q21356 | addGroupToList | train | function addGroupToList(group, list) {
if (!group) {
return list;
}
if (group.length > 1) {
list.push(group);
} else {
list = list.concat(group);
}
return list;
} | javascript | {
"resource": ""
} |
q21357 | getEntries | train | function getEntries(props, entries, indexes) {
const { onDOMNodeMouseOver, onDOMNodeMouseOut, onInspectIconClick } = props;
// Make indexes ordered by ascending.
indexes.sort(function(a, b) {
return a - b;
});
return indexes.map((index, i) => {
const [key, entryValue] = entries[index];
const val... | javascript | {
"resource": ""
} |
q21358 | getEntriesIndexes | train | function getEntriesIndexes(entries, max, filter) {
return entries.reduce((indexes, [key, entry], i) => {
if (indexes.length < max) {
const value = entry && entry.value !== undefined ? entry.value : entry;
// Type is specified in grip's "class" field and for primitive
// values use typeof.
... | javascript | {
"resource": ""
} |
q21359 | createMozBuildFiles | train | function createMozBuildFiles() {
const builds = {};
getFiles()
.filter(file => file.match(/.js$/))
.filter(file => {
if (file.match(/\/workers\.js/)) {
return true;
}
// We exclude worker files because they are bundled and we include
// worker/index.js files because are requi... | javascript | {
"resource": ""
} |
q21360 | getLinkifiedElements | train | function getLinkifiedElements(text, cropLimit, openLink, isInContentPage) {
const halfLimit = Math.ceil((cropLimit - ELLIPSIS.length) / 2);
const startCropIndex = cropLimit ? halfLimit : null;
const endCropIndex = cropLimit ? text.length - halfLimit : null;
const items = [];
let currentIndex = 0;
let conte... | javascript | {
"resource": ""
} |
q21361 | getCroppedString | train | function getCroppedString(text, offset = 0, startCropIndex, endCropIndex) {
if (!startCropIndex) {
return text;
}
const start = offset;
const end = offset + text.length;
const shouldBeVisible = !(start >= startCropIndex && end <= endCropIndex);
if (!shouldBeVisible) {
return null;
}
const sho... | javascript | {
"resource": ""
} |
q21362 | globalizeDeclaration | train | function globalizeDeclaration(node, bindings) {
return node.declarations.map(declaration =>
t.expressionStatement(
t.assignmentExpression(
"=",
getAssignmentTarget(declaration.id, bindings),
declaration.init || t.unaryExpression("void", t.numericLiteral(0))
)
)
);
} | javascript | {
"resource": ""
} |
q21363 | globalizeAssignment | train | function globalizeAssignment(node, bindings) {
return t.assignmentExpression(
node.operator,
getAssignmentTarget(node.left, bindings),
node.right
);
} | javascript | {
"resource": ""
} |
q21364 | findExistingBreakpoint | train | function findExistingBreakpoint(state, generatedLocation) {
const breakpoints = getBreakpointsList(state);
return breakpoints.find(bp => {
return (
bp.generatedLocation.sourceUrl == generatedLocation.sourceUrl &&
bp.generatedLocation.line == generatedLocation.line &&
bp.generatedLocation.colu... | javascript | {
"resource": ""
} |
q21365 | getFunctionName | train | function getFunctionName(grip, props = {}) {
let { functionName } = props;
let name;
if (functionName) {
const end = functionName.length - 1;
functionName =
functionName.startsWith('"') && functionName.endsWith('"')
? functionName.substring(1, end)
: functionName;
}
if (
gr... | javascript | {
"resource": ""
} |
q21366 | getLocation | train | function getLocation(func) {
const location = { ...func.location };
// if the function has an identifier, start the block after it so the
// identifier is included in the "scope" of its parent
const identifierEnd = get(func, "identifier.loc.end");
if (identifierEnd) {
location.start = identifierEnd;
}
... | javascript | {
"resource": ""
} |
q21367 | train | function(props) {
const { object, defaultRep } = props;
const rep = getRep(object, defaultRep, props.noGrip);
return rep(props);
} | javascript | {
"resource": ""
} | |
q21368 | getRep | train | function getRep(object, defaultRep = Grip, noGrip = false) {
for (let i = 0; i < reps.length; i++) {
const rep = reps[i];
try {
// supportsObject could return weight (not only true/false
// but a number), which would allow to priorities templates and
// support better extensibility.
if... | javascript | {
"resource": ""
} |
q21369 | lastRelease | train | function lastRelease() {
const {stdout: branches} = exec(`git branch -a | grep 'origin/release'`)
const releases = branches.
split("\n")
.map(b => b.replace(/remotes\/origin\//, '').trim())
.filter(b => b.match(/^release-(\d+)$/))
const ordered = sortBy(releases, r => parseInt(/\d+/.exec(r)[0], 10) ... | javascript | {
"resource": ""
} |
q21370 | updateManifest | train | function updateManifest() {
const {stdout: branch} = exec(`git rev-parse --abbrev-ref HEAD`)
if (!branch.includes("release")) {
return;
}
console.log("[copy-assets] update assets manifest");
const last = lastRelease();
exec(`git cat-file -p ${last}:assets/module-manifest.json > assets/module-manifest... | javascript | {
"resource": ""
} |
q21371 | getRecordUpdateData | train | function getRecordUpdateData (msg) {
let data
try {
data = JSON.parse(msg.data[2])
} catch (error) {
return error
}
return data
} | javascript | {
"resource": ""
} |
q21372 | setGlobalConfigDirectory | train | function setGlobalConfigDirectory (argv, filePath) {
const customConfigPath =
argv.c ||
argv.config ||
filePath ||
process.env.DEEPSTREAM_CONFIG_DIRECTORY
const configPath = customConfigPath
? verifyCustomConfigPath(customConfigPath)
: getDefaultConfigPath()
global.deepstreamConfDi... | javascript | {
"resource": ""
} |
q21373 | setGlobalLibDirectory | train | function setGlobalLibDirectory (argv, config) {
const libDir =
argv.l ||
argv.libDir ||
(config.libDir && fileUtils.lookupConfRequirePath(config.libDir)) ||
process.env.DEEPSTREAM_LIBRARY_DIRECTORY
global.deepstreamLibDir = libDir
} | javascript | {
"resource": ""
} |
q21374 | extendConfig | train | function extendConfig (config, argv) {
const cliArgs = {}
let key
for (key in defaultOptions.get()) {
cliArgs[key] = argv[key]
}
if (argv.port) {
overrideEndpointOption('port', argv.port, 'websocket', config)
}
if (argv.host) {
overrideEndpointOption('host', argv.host, 'websocket', config)
... | javascript | {
"resource": ""
} |
q21375 | getDefaultConfigPath | train | function getDefaultConfigPath () {
let filePath
let i
let k
for (k = 0; k < DEFAULT_CONFIG_DIRS.length; k++) {
for (i = 0; i < SUPPORTED_EXTENSIONS.length; i++) {
filePath = DEFAULT_CONFIG_DIRS[k] + SUPPORTED_EXTENSIONS[i]
if (fileUtils.fileExistsSync(filePath)) {
return filePath
... | javascript | {
"resource": ""
} |
q21376 | replaceEnvironmentVariables | train | function replaceEnvironmentVariables (fileContent) {
const environmentVariable = new RegExp(/\${([^}]+)}/g)
// eslint-disable-next-line
fileContent = fileContent.replace(environmentVariable, (a, b) => process.env[b] || '')
return fileContent
} | javascript | {
"resource": ""
} |
q21377 | parseLogLevel | train | function parseLogLevel (logLevel) {
if (!/debug|info|warn|error|off/i.test(logLevel)) {
console.error('Log level must be one of the following (debug|info|warn|error|off)')
process.exit(1)
}
return logLevel.toUpperCase()
} | javascript | {
"resource": ""
} |
q21378 | parseInteger | train | function parseInteger (name, port) {
const portNumber = Number(port)
if (!portNumber) {
console.error(`Provided ${name} must be an integer`)
process.exit(1)
}
return portNumber
} | javascript | {
"resource": ""
} |
q21379 | parseBoolean | train | function parseBoolean (name, enabled) {
let isEnabled
if (typeof enabled === 'undefined' || enabled === 'true') {
isEnabled = true
} else if (typeof enabled !== 'undefined' && enabled === 'false') {
isEnabled = false
} else {
console.error(`Invalid argument for ${name}, please provide true or false`... | javascript | {
"resource": ""
} |
q21380 | handleForceWriteAcknowledgement | train | function handleForceWriteAcknowledgement (
socketWrapper, message, cacheResponse, storageResponse, error
) {
if (storageResponse && cacheResponse) {
socketWrapper.sendMessage(RECORD, C.ACTIONS.WRITE_ACKNOWLEDGEMENT, [
message.data[0],
[message.data[1]],
messageBuilder.typed(error)
], true)... | javascript | {
"resource": ""
} |
q21381 | sendRecord | train | function sendRecord (recordName, record, socketWrapper) {
socketWrapper.sendMessage(RECORD, C.ACTIONS.READ, [recordName, record._v, record._d])
} | javascript | {
"resource": ""
} |
q21382 | validateSubscriptionMessage | train | function validateSubscriptionMessage (socket, message) {
if (message.data && message.data.length === 1 && typeof message.data[0] === 'string') {
return true
}
socket.sendError(C.TOPIC.EVENT, C.EVENT.INVALID_MESSAGE_DATA, message.raw)
return false
} | javascript | {
"resource": ""
} |
q21383 | compileRuleset | train | function compileRuleset (path, rules) {
const ruleset = pathParser.parse(path)
ruleset.rules = {}
for (const ruleType in rules) {
ruleset.rules[ruleType] = ruleParser.parse(
rules[ruleType], ruleset.variables
)
}
return ruleset
} | javascript | {
"resource": ""
} |
q21384 | sendError | train | function sendError (
event, message, recordName, socketWrapper, onError, options, context, metaData
) {
options.logger.error(event, message, metaData)
if (socketWrapper) {
socketWrapper.sendError(C.TOPIC.RECORD, event, message)
}
if (onError) {
onError.call(context, event, message, recordName, socketW... | javascript | {
"resource": ""
} |
q21385 | onStorageResponse | train | function onStorageResponse (
error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData
) {
if (error) {
sendError(
C.EVENT.RECORD_LOAD_ERROR,
`error while loading ${recordName} from storage:${error.toString()}`,
recordName,
socketWrapper,
onError,
... | javascript | {
"resource": ""
} |
q21386 | onCacheResponse | train | function onCacheResponse (
error, record, recordName, socketWrapper, onComplete, onError, options, context, metaData
) {
if (error) {
sendError(
C.EVENT.RECORD_LOAD_ERROR,
`error while loading ${recordName} from cache:${error.toString()}`,
recordName,
socketWrapper,
onError,
... | javascript | {
"resource": ""
} |
q21387 | setValue | train | function setValue (root, path, value) {
const tokens = tokenize(path)
let node = root
let i
for (i = 0; i < tokens.length - 1; i++) {
const token = tokens[i]
if (node[token] !== undefined && typeof node[token] === 'object') {
node = node[token]
} else if (typeof tokens[i + 1] === 'number') {... | javascript | {
"resource": ""
} |
q21388 | tokenize | train | function tokenize (path) {
const tokens = []
const parts = path.split('.')
for (let i = 0; i < parts.length; i++) {
const part = parts[i].trim()
if (part.length === 0) {
continue
}
const arrayIndexes = part.split(SPLIT_REG_EXP)
tokens.push(arrayIndexes[0])
for (let j = 1; j < a... | javascript | {
"resource": ""
} |
q21389 | handleSSLProperties | train | function handleSSLProperties (config) {
const sslFiles = ['sslKey', 'sslCert', 'sslDHParams']
let key
let resolvedFilePath
let filePath
for (let i = 0; i < sslFiles.length; i++) {
key = sslFiles[i]
filePath = config[key]
if (!filePath) {
continue
}
resolvedFilePath = fileUtils.lookup... | javascript | {
"resource": ""
} |
q21390 | handleLogger | train | function handleLogger (config) {
const configOptions = (config.logger || {}).options
let Logger
if (config.logger == null || config.logger.name === 'default') {
Logger = DefaultLogger
} else {
Logger = resolvePluginClass(config.logger, 'logger')
}
if (configOptions instanceof Array) {
// Note: ... | javascript | {
"resource": ""
} |
q21391 | resolvePluginClass | train | function resolvePluginClass (plugin, type) {
// alias require to trick nexe from bundling it
const req = require
let requirePath
let pluginConstructor
if (plugin.path != null) {
requirePath = fileUtils.lookupLibRequirePath(plugin.path)
pluginConstructor = req(requirePath)
} else if (plugin.name != n... | javascript | {
"resource": ""
} |
q21392 | train | function (urlPath, outStream, callback) {
needle.get(`https://github.com${urlPath}`, {
follow_max: 5,
headers: { 'User-Agent': 'nodejs-client' }
}, (error, response) => {
if (error) {
return callback(error)
}
outStream.write(response.body)
outStream.end()
if (process.env.VERBOSE) {... | javascript | {
"resource": ""
} | |
q21393 | train | function (directory) {
try {
const content = fs.readFileSync(path.join(directory, CONFIG_EXAMPLE_FILE), 'utf8')
if (process.env.VERBOSE) {
console.log('You need to configure the connector in your deepstream configuration file')
}
if (!process.env.QUIET) {
console.log(`Example configuration... | javascript | {
"resource": ""
} | |
q21394 | resolvePrefixAndFile | train | function resolvePrefixAndFile (nonAbsoluteFilePath, prefix) {
// prefix is not absolute
if (path.parse(prefix).root === '') {
return path.resolve(process.cwd(), prefix, nonAbsoluteFilePath)
}
// prefix is absolute
return path.resolve(prefix, nonAbsoluteFilePath)
} | javascript | {
"resource": ""
} |
q21395 | getInvalidPackages | train | async function getInvalidPackages() {
const packages = (await new Project(__dirname).getPackages())
.filter(p => p.scripts.build) // Only packages that have a build target
.filter(p => isPf3
? p.location.indexOf('patternfly-3') !== -1 || commonPackages.indexOf(p.name) !== -1
: true) // Based off a... | javascript | {
"resource": ""
} |
q21396 | train | function() {
if(!mfp.isOpen) return;
_mfpTrigger(BEFORE_CLOSE_EVENT);
mfp.isOpen = false;
// for CSS3 animation
if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition ) {
mfp._addClassToMFP(REMOVING_CLASS);
setTimeout(function() {
mfp._close();
}, mfp.st.removalDelay);
} else {
m... | javascript | {
"resource": ""
} | |
q21397 | train | function() {
var item = mfp.items[mfp.index];
// Detach and perform modifications
mfp.contentContainer.detach();
if(mfp.content)
mfp.content.detach();
if(!item.parsed) {
item = mfp.parseEl( mfp.index );
}
var type = item.type;
_mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : ''... | javascript | {
"resource": ""
} | |
q21398 | train | function(newContent, type) {
mfp.content = newContent;
if(newContent) {
if(mfp.st.showCloseBtn && mfp.st.closeBtnInside &&
mfp.currTemplate[type] === true) {
// if there is no markup, we just append close button element inside
if(!mfp.content.find('.mfp-close').length) {
mfp.content.append(_get... | javascript | {
"resource": ""
} | |
q21399 | train | function(index) {
var item = mfp.items[index],
type;
if(item.tagName) {
item = { el: $(item) };
} else {
type = item.type;
item = { data: item, src: item.src };
}
if(item.el) {
var types = mfp.types;
// check for 'mfp-TYPE' class
for(var i = 0; i < types.length; i++) {
if( item.el.... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.