_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3
values | text stringlengths 52 373k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q64000 | buildCommands | test | function buildCommands (commands) {
var result = [];
commands.forEach(function (command) {
result.push([
command.name,
command.desc || ''
]);
});
return table(result);
} | javascript | {
"resource": ""
} |
q64001 | Router | test | function Router(options) {
const logPrefix = topLogPrefix + 'Router() - ';
const that = this;
let defaultRouteFound = false;
that.options = options || {};
if (! that.options.paths) {
that.options.paths = {
'controller': {
'path': 'controllers',
'exts': 'js'
},
'static': {
'path': 'pu... | javascript | {
"resource": ""
} |
q64002 | getDefaultPortByProtocol | test | function getDefaultPortByProtocol (rawProtocol) {
// port-numbers expect no trailing colon
const protocol = rawProtocol.endsWith(':')
? rawProtocol.slice(0, -1)
: rawProtocol
// e.g. mailto has no port associated
// example return value:
// { port: 80, protocol: 'tcp', description: 'World Wide Web HT... | javascript | {
"resource": ""
} |
q64003 | clearScripts | test | function clearScripts(node){
var rslt = {};
for(var key in node){
var val = node[key];
if(_.isString(val)){
if(val.trim()) rslt[key] = "...";
}
else{
var childScripts = clearScripts(val);
if(!_.isEmpty(childScripts)) rslt[key] = childScripts;
... | javascript | {
"resource": ""
} |
q64004 | test | function(obj, array){
if(!Array.prototype.indexOf){
for(var i=0; i<array.length; i++){
if(array[i]===obj){
return i;
}
}
return -1;
}
else {
return array.indexOf(obj);
}
} | javascript | {
"resource": ""
} | |
q64005 | getElementValues | test | function getElementValues(nodeList, initialScope) {
const valueList = []
for (let i = 0; i < nodeList.length; ++i) {
const elementNode = nodeList[i]
if (elementNode == null) {
valueList.length = i + 1
} else if (elementNode.type === "SpreadElement") {
const argu... | javascript | {
"resource": ""
} |
q64006 | getStaticValueR | test | function getStaticValueR(node, initialScope) {
if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
return operations[node.type](node, initialScope)
}
return null
} | javascript | {
"resource": ""
} |
q64007 | isModifiedGlobal | test | function isModifiedGlobal(variable) {
return (
variable == null ||
variable.defs.length !== 0 ||
variable.references.some(r => r.isWrite())
)
} | javascript | {
"resource": ""
} |
q64008 | config | test | function config(ext) {
return {
input: "src/index.js",
output: {
file: `index${ext}`,
format: ext === ".mjs" ? "es" : "cjs",
sourcemap: true,
sourcemapFile: `index${ext}.map`,
strict: true,
banner: `/*! @author Toru Nagashima <h... | javascript | {
"resource": ""
} |
q64009 | isEscaped | test | function isEscaped(str, index) {
let escaped = false
for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
escaped = !escaped
}
return escaped
} | javascript | {
"resource": ""
} |
q64010 | replaceS | test | function replaceS(matcher, str, replacement) {
const chunks = []
let index = 0
/** @type {RegExpExecArray} */
let match = null
/**
* @param {string} key The placeholder.
* @returns {string} The replaced string.
*/
function replacer(key) {
switch (key) {
case ... | javascript | {
"resource": ""
} |
q64011 | replaceF | test | function replaceF(matcher, str, replace) {
const chunks = []
let index = 0
for (const match of matcher.execAll(str)) {
chunks.push(str.slice(index, match.index))
chunks.push(String(replace(...match, match.index, match.input)))
index = match.index + match[0].length
}
chunks.p... | javascript | {
"resource": ""
} |
q64012 | send | test | function send(msg) {
switch(ps.readyState) {
case 0: // CONNECTING
setTimeout(function () { send(msg); }, 1000);
break;
case 2: // CLOSING
case 3: // CLOSED
_event('dev', 'pubsub - reconnect: send() - closing/closed state');
connect();
setTimeout(function ()... | javascript | {
"resource": ""
} |
q64013 | parseMessage | test | function parseMessage(data) {
switch (data.topic) {
// https://dev.twitch.tv/docs/v5/guides/PubSub/
case 'channel-bits-events-v1.' + state.channel_id:
bits();
break;
// https://discuss.dev.twitch.tv/t/in-line-broadcaster-chat-mod-logs/7281/12
case 'chat_moderator_actions.' + ... | javascript | {
"resource": ""
} |
q64014 | JWT | test | function JWT(secret, options) {
this.token = '';
this.payload = {};
this.secret = secret;
this.options = options;
this.valid = false;
this.expired = false;
this.stale = true;
} | javascript | {
"resource": ""
} |
q64015 | test | function(payload) {
payload.stales = Date.now() + this.options.stales;
this.payload = payload;
this.token = utils.sign(this.payload, this.secret, this.options.signOptions);
this.valid = true;
this.expired = false;
this.stale = false;
return this;... | javascript | {
"resource": ""
} | |
q64016 | test | function(res) {
if (this.options.cookies) {
res.cookie(this.options.cookie, this.token, this.options.cookieOptions);
}
return this;
} | javascript | {
"resource": ""
} | |
q64017 | test | function() {
return {
token: this.token,
payload: this.payload,
valid: this.valid,
expired: this.expired,
stale: this.stale
};
} | javascript | {
"resource": ""
} | |
q64018 | test | function(token) {
this.token = token || '';
try {
this.payload = utils.verify(this.token, this.secret, this.options.verifyOptions);
this.valid = true;
} catch (err) {
this.payload = utils.decode(this.token) || {};
if (err.name == 'TokenExp... | javascript | {
"resource": ""
} | |
q64019 | test | function(secret, options) {
if (!secret) {
throw new ReferenceError('secret must be defined');
}
if (typeof secret == 'string') {
var _secret = secret;
secret = function(req) {return _secret};
}
options = options || {};
... | javascript | {
"resource": ""
} | |
q64020 | test | function() {
return function(req, res, next) {
var jwt = req[this.options.reqProperty] || {};
if (!jwt.valid) {
next(new JWTExpressError('JWT is invalid'));
} else {
next();
}
}.bind(this);
} | javascript | {
"resource": ""
} | |
q64021 | setupComponent | test | function setupComponent (fixture, options) {
// tear down any existing component instance
if (this.component) {
this.component.teardown();
this.$node.remove();
}
if (fixture instanceof jQuery || typeof fixture === 'string') {
// use the fixture to create component root node
this... | javascript | {
"resource": ""
} |
q64022 | describeModuleFactory | test | function describeModuleFactory (modulePath, specDefinitions) {
return function () {
beforeEach(function (done) {
this.module = null;
var requireCallback = function (module) {
this.module = module;
done();
}.bind(this);
require([modulePath], requireCallback... | javascript | {
"resource": ""
} |
q64023 | consul | test | function consul (options, resilient) {
defineResilientOptions(params, options)
return {
// Incoming traffic middleware
'in': function inHandler (err, res, next) {
if (err) return next()
// resilient.js sometimes calls the middleware function more than once, with the out... | javascript | {
"resource": ""
} |
q64024 | inHandler | test | function inHandler (err, res, next) {
if (err) return next()
// resilient.js sometimes calls the middleware function more than once, with the output
// of the previous invokation; checking here the type of the items in the response to
// only call `mapServers` with service objec... | javascript | {
"resource": ""
} |
q64025 | outHandler | test | function outHandler (options, next) {
options.params = options.params || {}
if (params.datacenter) {
options.params.dc = params.datacenter
}
if (params.onlyHealthy) {
options.params.passing = true
}
if (params.tag) {
opti... | javascript | {
"resource": ""
} |
q64026 | test | function(categoryId, event) {
event.preventDefault();
this.refs.scroller.prepareAnimationSync();
this.setState({
mode: 'single',
selected: categoryId,
previousScrollPosition: this.refs.scroller.scrollTop,
}, function() {
this.refs.scroller.animateAndResetScroll(0, 0);
});
} | javascript | {
"resource": ""
} | |
q64027 | test | function(event) {
event.preventDefault();
this.setState({
mode: 'all',
selected: null,
}, function() {
this.refs.scroller.animateAndResetScroll(0, this.state.previousScrollPosition);
});
} | javascript | {
"resource": ""
} | |
q64028 | Service | test | function Service(displayName, UUID, subtype) {
if (!UUID) throw new Error("Services must be created with a valid UUID.");
this.displayName = displayName;
this.UUID = UUID;
this.subtype = subtype;
this.iid = null; // assigned later by our containing Accessory
this.characteristics = [];
this.optionalCha... | javascript | {
"resource": ""
} |
q64029 | Characteristic | test | function Characteristic(displayName, UUID, props) {
this.displayName = displayName;
this.UUID = UUID;
this.iid = null; // assigned by our containing Service
this.value = null;
this.props = props || {
format : null,
unit : null,
minValue: null,
maxValue: null,
minStep : null,
per... | javascript | {
"resource": ""
} |
q64030 | migrateDatabase | test | function migrateDatabase(nativeDatabase, nativeTransaction, schemaDescriptors,
currentVersion) {
let descriptorsToProcess = schemaDescriptors.filter((descriptor) => {
return descriptor.version > currentVersion
})
if (!descriptorsToProcess.length) {
return PromiseSync.resolve(undefined)
}
ret... | javascript | {
"resource": ""
} |
q64031 | migrateDatabaseVersion | test | function migrateDatabaseVersion(nativeDatabase, nativeTransaction,
descriptor) {
let fetchPromise
if (descriptor.fetchBefore && descriptor.fetchBefore.length) {
let fetcher = new RecordFetcher()
let objectStores = normalizeFetchBeforeObjectStores(descriptor.fetchBefore)
fetchPromise = fetcher.fetchR... | javascript | {
"resource": ""
} |
q64032 | normalizeFetchBeforeObjectStores | test | function normalizeFetchBeforeObjectStores(objectStores) {
return objectStores.map((objectStore) => {
if (typeof objectStore === "string") {
return {
objectStore,
preprocessor: record => record
}
} else if (!objectStore.preprocessor) {
return {
objectStore: objectStore... | javascript | {
"resource": ""
} |
q64033 | checkSchemaDescriptorTypes | test | function checkSchemaDescriptorTypes(schemaDescriptors) {
let onlyPlainObjects = schemaDescriptors.every((descriptor) => {
return descriptor.constructor === Object
})
if (onlyPlainObjects) {
return
}
if (!(schemaDescriptors[0] instanceof DatabaseSchema)) {
throw new TypeError("The schema descrip... | javascript | {
"resource": ""
} |
q64034 | list | test | function list(storage, keyRange, filter, direction, unique, pageSize,
storageFactory) {
return new Promise((resolve, reject) => {
let items = []
storage.createCursorFactory(keyRange, direction)((cursor) => {
if (!filter || filter(cursor.record, cursor.primaryKey, cursor.key)) {
if (items.le... | javascript | {
"resource": ""
} |
q64035 | normalizeCompoundObjectKey | test | function normalizeCompoundObjectKey(keyPaths, key) {
let normalizedKey = []
keyPaths.forEach((keyPath) => {
let keyValue = key
keyPath.split(".").forEach((fieldName) => {
if (!keyValue.hasOwnProperty(fieldName)) {
throw new Error(`The ${keyPath} key path is not defined in the ` +
... | javascript | {
"resource": ""
} |
q64036 | iterateCursor | test | function iterateCursor(request, cursorConstructor, recordCallback) {
return new PromiseSync((resolve, reject) => {
let traversedRecords = 0
let canIterate = true
request.onerror = () => reject(request.error)
request.onsuccess = () => {
if (!canIterate) {
console.warn("Cursor iterati... | javascript | {
"resource": ""
} |
q64037 | handleCursorIteration | test | function handleCursorIteration(request, cursorConstructor, recordCallback,
reject) {
let iterationRequested = false
let cursor = new cursorConstructor(request, () => {
iterationRequested = true
}, (subRequest) => {
return PromiseSync.resolve(subRequest).catch((error) => {
reject(error)
thr... | javascript | {
"resource": ""
} |
q64038 | fetchAllRecords | test | function fetchAllRecords(transaction, objectStores) {
return PromiseSync.all(objectStores.map((descriptor) => {
return fetchRecords(
transaction.getObjectStore(descriptor.objectStore),
descriptor.preprocessor
)
})).then((fetchedRecords) => {
let recordsMap = {}
for (let i = 0; i < o... | javascript | {
"resource": ""
} |
q64039 | fetchRecords | test | function fetchRecords(objectStore, preprocessor) {
return new PromiseSync((resolve, reject) => {
let records = []
objectStore.openCursor(null, CursorDirection.NEXT, (cursor) => {
let primaryKey = cursor.primaryKey
if (primaryKey instanceof Object) {
Object.freeze(primaryKey)
}
... | javascript | {
"resource": ""
} |
q64040 | writeFileP | test | function writeFileP (outputPath, data, cb) {
outputPath = abs(outputPath);
let dirname = path.dirname(outputPath);
mkdirp(dirname, err => {
if (err) { return cb(err); }
let str = data;
if (typpy(data, Array) || typpy(data, Object)) {
str = JSON.stringify(data, null, 2);
... | javascript | {
"resource": ""
} |
q64041 | runTransaction | test | function runTransaction(transaction, objectStoreNames, transactionOperations) {
let callbackArguments = objectStoreNames.map((objectStoreName) => {
return transaction.getObjectStore(objectStoreName)
})
callbackArguments.push(() => transaction.abort())
let resultPromise = transactionOperations(...callback... | javascript | {
"resource": ""
} |
q64042 | toNativeCursorDirection | test | function toNativeCursorDirection(direction, unique) {
if (typeof direction === "string") {
if (CURSOR_DIRECTIONS.indexOf(direction.toUpperCase()) === -1) {
throw new Error("When using a string as cursor direction, use NEXT " +
`or PREVIOUS, ${direction} provided`);
}
} else {
direction =... | javascript | {
"resource": ""
} |
q64043 | createIndex | test | function createIndex(objectStore, indexSchema) {
let indexNames = Array.from(objectStore.indexNames)
if (indexNames.indexOf(indexSchema.name) !== -1) {
return
}
objectStore.createIndex(indexSchema.name, indexSchema.keyPath, {
unique: indexSchema.unique,
multiEntry: indexSchema.multiEntry
})
} | javascript | {
"resource": ""
} |
q64044 | fetchNextPage | test | function fetchNextPage(storageFactory, keyRange, cursorDirection, unique,
firstPrimaryKey, filter, pageSize) {
let storage = storageFactory()
let nextItems = []
return new Promise((resolve, reject) => {
let idb = idbProvider()
let cursorFactory = storage.createCursorFactory(
keyRange,
cu... | javascript | {
"resource": ""
} |
q64045 | executeEventListeners | test | function executeEventListeners(listeners, ...parameters) {
listeners.forEach((listener) => {
try {
listener.apply(null, parameters)
} catch (error) {
console.error("An event listener threw an error", error)
}
})
} | javascript | {
"resource": ""
} |
q64046 | resolve | test | function resolve(instance, newState, value) {
if (instance[FIELDS.state] !== STATE.PENDING) {
return
}
instance[FIELDS.state] = newState
instance[FIELDS.value] = value
let listeners
if (newState === STATE.RESOLVED) {
listeners = instance[FIELDS.fulfillListeners]
} else {
listeners = inst... | javascript | {
"resource": ""
} |
q64047 | runQuery | test | function runQuery(cursorFactory, filter, comparator, offset, limit, callback) {
let records = []
let recordIndex = -1
return cursorFactory((cursor) => {
if (!filter && offset && ((recordIndex + 1) < offset)) {
recordIndex = offset - 1
cursor.advance(offset)
return
}
let primary... | javascript | {
"resource": ""
} |
q64048 | insertSorted | test | function insertSorted(records, record, primaryKey, comparator) {
let index = findInsertIndex(records, record, comparator)
records.splice(index, 0, {
record,
primaryKey
})
} | javascript | {
"resource": ""
} |
q64049 | findInsertIndex | test | function findInsertIndex(records, record, comparator) {
if (!records.length) {
return 0
}
if (records.length === 1) {
let comparison = comparator(records[0].record, record)
return (comparison > 0) ? 0 : 1
}
let comparison = comparator(records[0].record, record)
if (comparison > 0) {
re... | javascript | {
"resource": ""
} |
q64050 | prepareQuery | test | function prepareQuery(thisStorage, filter, order) {
order = normalizeKeyPath(order)
let expectedSortingDirection = order[0].charAt(0) === "!"
let canSortingBeOptimized
canSortingBeOptimized = canOptimizeSorting(expectedSortingDirection, order)
let storages = new Map()
storages.set(normalizeKeyPath(thi... | javascript | {
"resource": ""
} |
q64051 | prepareSortingOptimization | test | function prepareSortingOptimization(storages, simplifiedOrderFieldPaths) {
let idb = idbProvider()
for (let [keyPath, storageAndScore] of storages) {
let keyPathSlice = keyPath.slice(0, simplifiedOrderFieldPaths.length)
if (idb.cmp(keyPathSlice, simplifiedOrderFieldPaths) === 0) {
storageAndScore.scor... | javascript | {
"resource": ""
} |
q64052 | prepareFilteringOptimization | test | function prepareFilteringOptimization(storages, filter) {
if (filter instanceof Function) {
for (let [keyPath, storageAndScore] of storages) {
storageAndScore.filter = filter
}
return
}
for (let [keyPath, storageAndScore] of storages) {
let normalizedFilter = normalizeFilter(filter, keyPat... | javascript | {
"resource": ""
} |
q64053 | chooseStorageForQuery | test | function chooseStorageForQuery(storages, order, simplifiedOrderFieldPaths,
canSortingBeOptimized, expectedSortingDirection) {
let sortedStorages = Array.from(storages.values())
sortedStorages.sort((storage1, storage2) => {
return storage2.score - storage1.score
})
let chosenStorageDetails = sortedStora... | javascript | {
"resource": ""
} |
q64054 | prepareOrderingSpecificationForQuery | test | function prepareOrderingSpecificationForQuery(order, keyPath) {
if (order === null) {
order = CursorDirection.NEXT
}
let isCursorDirection = ((typeof order === "string") &&
(CURSOR_DIRECTIONS.indexOf(order.toUpperCase()) > -1)) ||
(CURSOR_DIRECTIONS.indexOf(order) > -1)
if (isCursorDirection ... | javascript | {
"resource": ""
} |
q64055 | openConnection | test | function openConnection(databaseName, sortedSchemaDescriptors) {
let version = sortedSchemaDescriptors.slice().pop().version
let request = NativeDBAccessor.indexedDB.open(databaseName, version)
return new Promise((resolve, reject) => {
let wasBlocked = false
let upgradeTriggered = false
let mi... | javascript | {
"resource": ""
} |
q64056 | handleConnectionError | test | function handleConnectionError(event, error, wasBlocked, upgradeTriggered,
reject, migrationPromiseRejector) {
if (wasBlocked || upgradeTriggered) {
event.preventDefault()
return
}
reject(request.error)
migrationPromiseRejector(request.error)
} | javascript | {
"resource": ""
} |
q64057 | executeMigrationListeners | test | function executeMigrationListeners(databaseName, oldVersion, newVersion,
completionPromise) {
for (let listener of migrationListeners) {
try {
listener(databaseName, oldVersion, newVersion, completionPromise)
} catch (e) {
console.warn("A schema migration event listener threw an error", e);
... | javascript | {
"resource": ""
} |
q64058 | splitFilteringObject | test | function splitFilteringObject(filter, filterFieldPaths, storageKeyPath) {
let fieldsToOptimize = {}
let fieldsToCompile = {}
filterFieldPaths.forEach((fieldPath) => {
let value = getFieldValue(filter, fieldPath)
if (storageKeyPath.indexOf(fieldPath) > -1) {
setFieldValue(fieldsToOptimize, fieldPath... | javascript | {
"resource": ""
} |
q64059 | getFieldPaths | test | function getFieldPaths(object, stopOnKeyRange = true) {
let fieldPaths = []
fieldPaths.containsKeyRange = false
generateFieldPaths(object, [])
return fieldPaths
function generateFieldPaths(object, parts) {
Object.keys(object).some((fieldName) => {
let value = object[fieldName]
if (stopOnKeyR... | javascript | {
"resource": ""
} |
q64060 | setFieldValue | test | function setFieldValue(object, fieldPath, value) {
let parts = fieldPath.split(".")
let done = []
let currentObject = object
while (parts.length) {
let field = parts.shift()
if (!parts.length) {
if (currentObject.hasOwnProperty(field)) {
throw new Error(`The ${fieldPath} field seems to b... | javascript | {
"resource": ""
} |
q64061 | getFieldValue | test | function getFieldValue(object, fieldPath) {
if (!fieldPath) {
return object
}
let currentObject = object
fieldPath.split(".").forEach((fieldName) => {
if (!currentObject.hasOwnProperty(fieldName)) {
throw new Error(`The field path ${fieldPath} does not exist in the ` +
"provided object"... | javascript | {
"resource": ""
} |
q64062 | upgradeSchema | test | function upgradeSchema(nativeDatabase, nativeTransaction, descriptors) {
let objectStoreNames = Array.from(nativeDatabase.objectStoreNames)
let newObjectStoreNames = descriptors.map((objectStore) => {
return objectStore.name
})
objectStoreNames.forEach((objectStoreName) => {
if (newObjectStoreNames.inde... | javascript | {
"resource": ""
} |
q64063 | container | test | function container(width, height, position, elem) {
return new Element(new ContainerElement(position, elem)
, width, height)
} | javascript | {
"resource": ""
} |
q64064 | mainSection | test | function mainSection(state) {
var todos = state.todos
var route = state.route
return h("section.main", { hidden: todos.length === 0 }, [
toggleAllPool.change(h("input#toggle-all.toggle-all", {
type: "checkbox",
checked: todos.every(function (todo) {
return to... | javascript | {
"resource": ""
} |
q64065 | Client | test | function Client() {
EventEmitter.call(this);
this.debug = true; //false
this.socket = dgram.createSocket('udp4');
this.isSocketBound = false;
this.devices = {};
this.port = constants.DREAMSCREEN_PORT;
this.discoveryTimer = null;
this.messageHandlers = [];
this.messageHandlerTimeout... | javascript | {
"resource": ""
} |
q64066 | Light | test | function Light(constr) {
this.client = constr.client;
this.ipAddress = constr.ipAddress;
this.serialNumber = constr.serialNumber;
this.productId = constr.productId; //devicetype
this.lastSeen = constr.lastSeen;
this.isReachable = constr.isReachable;
this.name = constr.nam... | javascript | {
"resource": ""
} |
q64067 | plainText | test | function plainText(content) {
var textSize = getTextSize(content)
return new Element(new TextElement("left", content)
, textSize.width, textSize.height)
} | javascript | {
"resource": ""
} |
q64068 | test | function(json) {
var output = '[<ul class="array collapsible">';
var hasContents = false;
for ( var prop in json ) {
hasContents = true;
output += '<li>';
output += this.valueToHTML(json[prop]);
output += '</li>';
}
output += '</ul>]';
if ( ! hasConte... | javascript | {
"resource": ""
} | |
q64069 | test | function(error, data, uri) {
// var output = '<div id="error">' +
// this.stringbundle.GetStringFromName('errorParsing') + '</div>';
// output += '<h1>' +
// this.stringbundle.GetStringFromName('docContents') + ':</h1>';
var output = '<div id="error">Error parsing JSON: ' +... | javascript | {
"resource": ""
} | |
q64070 | write | test | function write(chunk, encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding
encoding = null
}
if (ended) {
throw new Error('Did not expect `write` after `end`')
}
chunks.push((chunk || '').toString(encoding || 'utf8'))
if (callback) {
callback... | javascript | {
"resource": ""
} |
q64071 | end | test | function end() {
write.apply(null, arguments)
ended = true
processor.process(chunks.join(''), done)
return true
function done(err, file) {
var messages = file ? file.messages : []
var length = messages.length
var index = -1
chunks = null
// Trigger messages as war... | javascript | {
"resource": ""
} |
q64072 | cleanup | test | function cleanup() {
emitter.removeListener('data', ondata)
emitter.removeListener('end', onend)
emitter.removeListener('error', onerror)
emitter.removeListener('end', cleanup)
emitter.removeListener('close', cleanup)
dest.removeListener('error', onerror)
dest.removeListener('... | javascript | {
"resource": ""
} |
q64073 | onerror | test | function onerror(err) {
var handlers = emitter._events.error
cleanup()
// Cannot use `listenerCount` in node <= 0.12.
if (!handlers || handlers.length === 0 || handlers === onerror) {
throw err // Unhandled stream error in pipe.
}
} | javascript | {
"resource": ""
} |
q64074 | clean | test | function clean(root, name) {
const blacklist = ['.git', 'node_modules'];
for (const item of blacklist) {
const pathToItem = path.join(root, item);
if (fs.pathExistsSync(pathToItem)) {
fs.removeSync(pathToItem);
console.log(`${chalk.dim.redBright(item)} has been removed from ${chalk.yellow(name)}... | javascript | {
"resource": ""
} |
q64075 | ls | test | function ls() {
const vault = path.join(os.homedir(), '.snap');
const list = shell.ls(vault);
if (!list.length) {
console.log("\nIt seems you don't have anything saved...");
console.log(`You can run ${chalk.yellow('snap save')} to save a directory or Git repo for future use!`);
console.log(`Run ${chal... | javascript | {
"resource": ""
} |
q64076 | sessionData | test | function sessionData(req, res, session, cb){
const now = new Date();
if(session.continued)
return cb(null, req, res, session);
async.parallelLimit([
getIp,
getLocation,
getSystem
], 2,
function(err){
cb(err, this.req, this.res, this.... | javascript | {
"resource": ""
} |
q64077 | newRequest | test | function newRequest(req, res, session, cb){
const now = new Date();
const request = {
_id: `r${crypto.randomBytes(16).toString('hex')}${Date.now()}`,
host: req.hostname,
url: req.url,
method: req.method,
referrer: req.get('Referrer') || req.get('Referer')
};
//... | javascript | {
"resource": ""
} |
q64078 | test | function(packet) {
this.updatePayload = function(packet) {
this.p_previous = this.p;
this.p = packet.payload;
this.changed = this.p_previous != this.p;
this.retained = packet.retain;
this.lastChange = this.currentChange;
this.currentChange = new Date();
};
this.changedFromTo = function(from, to) {
ret... | javascript | {
"resource": ""
} | |
q64079 | test | function(){
this.date = new Date();
this.getHours = function() {
return this.date.getHours();
};
this.getMinutes = function() {
return this.date.getMinutes();
};
this.hoursIsBetween = function(a, b) {
if(a <= b) return this.date.getHours() >= a && this.date.getHours() <=b;
... | javascript | {
"resource": ""
} | |
q64080 | test | function(req, cb) {
req = request.normalizeRequest(req);
var page;
try {
page = this.createPageForRequest(req);
} catch(err) {
if (cb)
return cb(err)
else
throw err;
}
var needData = typeof page.fetchData === 'function' && !this.state.request.data;
if (re... | javascript | {
"resource": ""
} | |
q64081 | create | test | function create (format, options) {
const ogrFormat = ogrFormats[format]
// shapefiles cannot be streamed out of ogr2ogr
const output = format === 'zip' ? `${options.path || '.'}/${options.name}` : '/vsistdout/'
const input = options.input || 'layer.vrt'
let cmd = ['--config', 'SHAPE_ENCODING', 'UTF-8', '-f'... | javascript | {
"resource": ""
} |
q64082 | csvParams | test | function csvParams (cmd, options) {
cmd.push('-lco', 'WRITE_BOM=YES')
const hasPointGeom = options.geometry === 'POINT'
const fields = options.fields.join('|').toLowerCase().split('|')
const hasXY = fields.indexOf('x') > -1 && fields.indexOf('y') > -1
if (hasPointGeom && !hasXY) cmd = cmd.concat(['-lco', 'GEO... | javascript | {
"resource": ""
} |
q64083 | shapefileParams | test | function shapefileParams (cmd, options) {
// make sure geometries are still written even if the first is null
if (options.geometry !== 'NONE') cmd.push('-nlt', options.geometry.toUpperCase())
cmd.push('-fieldmap', 'identity')
if (!options.ignoreShpLimit) cmd.push('-lco', '2GB_LIMIT=yes')
if (options.srs) cmd.... | javascript | {
"resource": ""
} |
q64084 | watcherFn | test | function watcherFn(schemaFilepath, watchInterval, reinitBabelRelayPlugin, prevMtime) {
try {
let stats;
try {
stats = fs.statSync(schemaFilepath);
} catch (e) {
// no problem
}
if (stats) {
if (!prevMtime) prevMtime = stats.mtime;
if (stats.mtime.getTime() !== prevMtime.get... | javascript | {
"resource": ""
} |
q64085 | AkamaiPurge | test | function AkamaiPurge(username, password, objects, options) {
var auth = {},
requestBody = {},
requestOptions;
// Ensure options exist and are the right type
if (options === undefined || !lodash.isPlainObject(options)) {
options = {};
}
// Prepare authentication
auth.username = username;
auth... | javascript | {
"resource": ""
} |
q64086 | test | function () {
// Apply the modifier to the current `options`
options = lodash.assign(options, modifier);
// Create new wrapper function.
var AkamaiPurgeChain = function AkamaiPurgeChain (username, password, objects) {
return AkamaiPurge(username, password, objects, options);
... | javascript | {
"resource": ""
} | |
q64087 | Mock | test | function Mock(mount, options) {
// convert to absolute path
this.mount = mount;
this.options = options || {};
this.options.params = this.options.params === undefined ? true : this.options.params;
this.locator = new Locator(mount);
debug('mount at %s', this.mount);
} | javascript | {
"resource": ""
} |
q64088 | forEach | test | function forEach (object, block, context) {
if (object) {
let resolve = Object; // default
if (object instanceof Function) {
// functions have a "length" property
resolve = Function;
} else if (object.forEach instanceof Function) {
// the object implements a custom forEach method so use that
object.f... | javascript | {
"resource": ""
} |
q64089 | test | function(target, source) {
var skeys = _.keys(source);
_.each(skeys, function(skey) {
if (!target[skey]) {
target[skey] = source[skey];
}
});
return target;
} | javascript | {
"resource": ""
} | |
q64090 | createObject | test | function createObject(proto, args) {
var instance = Object.create(proto);
if (instance.$meta.constructors) {
instance.$meta.constructors.forEach(function(constructor) {
constructor.apply(instance, args);
});
}
return instance;
} | javascript | {
"resource": ""
} |
q64091 | mergeProperty | test | function mergeProperty(destination, source, property) {
if (source[property] instanceof Array) {
mergeAsArray(destination, source, property);
}
else if (isPrimitive(source[property]) || !isLiteral(source[property])) {
overrideIfNotExists(destination, source, property);
}
else {
... | javascript | {
"resource": ""
} |
q64092 | mergeAsArray | test | function mergeAsArray(destination, source, property) {
destination[property] = source[property].concat(destination[property] || []);
} | javascript | {
"resource": ""
} |
q64093 | mergeAsObject | test | function mergeAsObject(destination, source, property) {
destination[property] = destination[property] || {};
merge(destination[property], source[property]);
} | javascript | {
"resource": ""
} |
q64094 | mixin | test | function mixin(instance, mixins) {
mixins.forEach(function(Mixin) {
mix(instance, Mixin);
});
return instance;
} | javascript | {
"resource": ""
} |
q64095 | mkdirp | test | function mkdirp(dir, made) {
var mode = 0777 & (~process.umask());
if (!made) made = null;
dir = path.resolve(dir);
try {
fs.mkdirSync(dir, mode);
made = made || dir;
} catch (err0) {
switch (err0.code) {
case 'ENOENT':
made = mkdirp(path.dirname(dir), made);
mkdirp(dir, ma... | javascript | {
"resource": ""
} |
q64096 | test | function(identifier, target, cb) {
var systemId = _sr.findSystem(identifier);
if (!systemId) { logger.error(ERR_NOSYSID); return cb(new Error(ERR_NOSYSID)); }
fetchTarget(systemId, target, function(err, target) {
if (err) { return cb(err); }
logger.info({ systemId: systemId, target: target }, 'g... | javascript | {
"resource": ""
} | |
q64097 | test | function(user, name, namespace, cwd, cb) {
logger.info('create system name: ' + name + ', namespace: ' + namespace + ', cwd: ' + cwd);
_sr.createSystem(user, namespace, name, cwd, cb);
} | javascript | {
"resource": ""
} | |
q64098 | test | function(user, path, cwd, cb) {
logger.info('link system: ' + path + ', ' + cwd);
_sr.linkSystem(user, path, cwd, cb);
} | javascript | {
"resource": ""
} | |
q64099 | test | function(identifier, revisionId, out, cb) {
logger.info('list containers: ' + identifier);
var systemId = _sr.findSystem(identifier);
var containers = {};
if (!systemId) { return cb(new Error(ERR_NOSYSID)); }
_builder.loadTargets(systemId, revisionId, function(err, targets) {
if (err) { return... | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.