_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q51400
interpolate
train
function interpolate(str, context) { const opts = { ...context.options }; let val = opts.apiurl + str.replace(/:([\w_]+)/g, (m, key) => { opts.params = union(opts.params, key); let val = get(opts, key); if (val !== void 0) { return val; } return key; }); if (opts.method.toLowerCase() === 'get' && opts.paged !== false) { const obj = url.parse(val); const query = obj.query ? qs.parse(obj.query) : {}; const noquery = omit(obj, ['query', 'search']); noquery.query = noquery.search = qs.stringify(Object.assign({ per_page: 100 }, opts.query, query)); val = url.format(noquery); } val += /\?/.test(val) ? '&' : '?'; val += (new Date()).getTime(); return val; }
javascript
{ "resource": "" }
q51401
sanitize
train
function sanitize(options, blacklist) { const opts = Object.assign({}, options); const defaults = ['apiurl', 'token', 'username', 'password', 'placeholders', 'bearer']; const keys = union([], defaults, blacklist); return omit(opts, keys); }
javascript
{ "resource": "" }
q51402
is
train
function is(test, node, index, parent, context) { var hasParent = parent !== null && parent !== undefined var hasIndex = index !== null && index !== undefined var check = convert(test) if ( hasIndex && (typeof index !== 'number' || index < 0 || index === Infinity) ) { throw new Error('Expected positive finite index or child node') } if (hasParent && (!is(null, parent) || !parent.children)) { throw new Error('Expected parent node') } if (!node || !node.type || typeof node.type !== 'string') { return false } if (hasParent !== hasIndex) { throw new Error('Expected both parent and index') } return Boolean(check.call(context, node, index, parent)) }
javascript
{ "resource": "" }
q51403
matchesFactory
train
function matchesFactory(test) { return matches function matches(node) { var key for (key in test) { if (node[key] !== test[key]) { return false } } return true } }
javascript
{ "resource": "" }
q51404
ElementRect
train
function ElementRect(element) { _classCallCheck(this, ElementRect); this._element = element; /** * Returns the width of the current element. * * @type {Number} */ this.width = this.boundingRect.width; /** * Returns the height of the current element. * * @type {Number} */ this.height = this.boundingRect.height; /** * Returns the size (the biggest side) of the current element. * * @type {number} */ this.size = Math.max(this.width, this.height); return this; }
javascript
{ "resource": "" }
q51405
translate
train
function translate(messageObj) { // Default to English if we don't have this message, or don't support this // language at all var language = messageObj.language && this[messageObj.language] && this[messageObj.language][messageObj.messageKey] ? messageObj.language : 'en'; var rv = this[language][messageObj.messageKey]; if (messageObj.messageParam) { rv = rv.replace('%s', messageObj.messageParam); } return rv; }
javascript
{ "resource": "" }
q51406
Renderer
train
function Renderer(options) { var defaults = { headers: { included: true, downcase: true, upcase: true }, delimiter: 'tab', decimalSign: 'comma', outputDataType: 'json', columnDelimiter: "\t", rowDelimiter: '\n', inputHeader: {}, outputHeader: {}, dataSelect: {}, outputText: '', newline: '\n', indent: ' ', commentLine: '//', commentLineEnd: '', tableName: 'converter', useUnderscores: true, includeWhiteSpace: true, useTabsForIndent: false }; this.options = merge({}, defaults, options); if (this.options.includeWhiteSpace) { this.options.newline = '\n'; } else { this.options.indent = ''; this.options.newline = ''; } }
javascript
{ "resource": "" }
q51407
Parser
train
function Parser(options) { this.options = merge({}, { headers: { included: false, downcase: true, upcase: true }, delimiter: 'tab', decimalSign: 'comma' }, options); }
javascript
{ "resource": "" }
q51408
toArray
train
function toArray(str, options) { var opts = extend({delim: ','}, options); // Create a regular expression to parse the CSV values. var re = new RegExp( // Delimiters. '(\\' + opts.delim + '|\\n|^)' + // Quoted fields. '(?:"([^"]*(?:""[^"]*)*)"|' + // Standard fields. '([^"\\' + opts.delim + '\\n]*))', 'gi'); // Create an array to hold our data. Give the array // a default empty first row. var arr = [[]]; // Create an array to hold our individual pattern // matching groups. var match = null; var value; // Keep looping over the regular expression matches // until we can no longer find a match. while (match = re.exec(str)) { // Get the delimiter that was found. var matchedDelim = match[1]; // Check to see if the given delimiter has a length // (is not the start of string) and if it matches // field delimiter. If it does not, then we can expect // this delimiter to be a row delimiter. if (matchedDelim.length && (matchedDelim != opts.delim)) { // Since we have reached a new row of data, // add an empty row to our data array. arr.push([]); } // Now that we have our delimiter out of the way, // let's check to see which kind of value we // captured (quoted or unquoted). if (match[2]) { // We found a quoted value. When we capture // this value, unescape any double quotes. value = match[2].replace(/""/g, '"'); } else { // We found a non-quoted value. value = match[3]; } // Now that we have our value string, let's add // it to the data array. arr[arr.length - 1].push(value); } // Return the parsed data. return arr; }
javascript
{ "resource": "" }
q51409
Subject
train
function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; }
javascript
{ "resource": "" }
q51410
BehaviorSubject
train
function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; }
javascript
{ "resource": "" }
q51411
ReplaySubject
train
function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); }
javascript
{ "resource": "" }
q51412
toy
train
function toy(frag, cb) { const canvas = document.body.appendChild(document.createElement('canvas')) const gl = context(canvas, render) const shader = Shader(gl, vert, frag) const fitter = fit(canvas) render.update = update render.resize = fitter render.shader = shader render.canvas = canvas render.gl = gl window.addEventListener('resize', fitter, false) return render function render() { const width = gl.drawingBufferWidth const height = gl.drawingBufferHeight gl.viewport(0, 0, width, height) shader.bind() cb(gl, shader) triangle(gl) } function update(frag) { shader.update(vert, frag) } }
javascript
{ "resource": "" }
q51413
stringify
train
function stringify(val) { if (typeof val === 'string') return JSON.stringify(val.toLowerCase()); if (Array.isArray(val)) return '[' + val.map(stringify) + ']'; if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && '' + val === '[object Object]') { var str = Object.keys(val).sort().map(function (key) { return stringify(key) + ':' + stringify(val[key]); }).join(','); return '{' + str + '}'; } return JSON.stringify(val); }
javascript
{ "resource": "" }
q51414
Browser
train
function Browser(type, options = {}) { if (!(this instanceof Browser)) return new Browser(type, options); EventEmitter.call(this); // convert argument ServiceType to validate it (might throw) const serviceType = (type instanceof ServiceType) ? type : new ServiceType(type); // can't search for multiple subtypes at the same time if (serviceType.subtypes.length > 1) { throw new Error('Too many subtypes. Can only browse one at a time.'); } this._id = serviceType.toString(); debug(`Creating new browser for "${this._id}"`); this._resolvers = {}; // active service resolvers (when browsing services) this._serviceTypes = {}; // active service types (when browsing service types) this._protocol = serviceType.protocol; this._serviceName = serviceType.name; this._subtype = serviceType.subtypes[0]; this._isWildcard = serviceType.isEnumerator; this._domain = options.domain || 'local.'; this._maintain = ('maintain' in options) ? options.maintain : true; this._resolve = ('resolve' in options) ? options.resolve : true; this._interface = NetworkInterface.get(options.interface); this._state = STATE.STOPPED; // emitter used to stop child queries instead of holding onto a reference // for each one this._offswitch = new EventEmitter(); }
javascript
{ "resource": "" }
q51415
visualPad
train
function visualPad(str, num) { var needed = num - str.replace(remove_colors_re, '').length; return needed > 0 ? str + ' '.repeat(needed) : str; }
javascript
{ "resource": "" }
q51416
alignRecords
train
function alignRecords() { var colWidths = []; var result = void 0; // Get max size for each column (have to look at all records) for (var _len2 = arguments.length, groups = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { groups[_key2] = arguments[_key2]; } result = groups.map(function (records) { return records.map(function (record) { // break record into parts var parts = record.toParts(); parts.forEach(function (part, i) { var len = part.replace(remove_colors_re, '').length; if (!colWidths[i]) colWidths[i] = 0; if (len > colWidths[i]) colWidths[i] = len; }); return parts; }); }); // Add padding: result = result.map(function (records) { return records.map(function (recordParts) { return recordParts.map(function (part, i) { return visualPad(part, colWidths[i]); }).join(' '); }); }); return result; }
javascript
{ "resource": "" }
q51417
Advertisement
train
function Advertisement(type, port, options = {}) { if (!(this instanceof Advertisement)) { return new Advertisement(type, port, options); } EventEmitter.call(this); // convert argument ServiceType to validate it (might throw) const serviceType = (!(type instanceof ServiceType)) ? new ServiceType(type) : type; // validate other inputs (throws on invalid) validate.port(port); if (options.txt) validate.txt(options.txt); if (options.name) validate.label(options.name, 'Instance'); if (options.host) validate.label(options.host, 'Hostname'); this.serviceName = serviceType.name; this.protocol = serviceType.protocol; this.subtypes = (options.subtypes) ? options.subtypes : serviceType.subtypes; this.port = port; this.instanceName = options.name || misc.hostname(); this.hostname = options.host || misc.hostname(); this.txt = options.txt || {}; // Domain notes: // 1- link-local only, so this is the only possible value // 2- "_domain" used instead of "domain" because "domain" is an instance var // in older versions of EventEmitter. Using "domain" messes up `this.emit()` this._domain = 'local'; this._id = misc.fqdn(this.instanceName, this.serviceName, this.protocol, 'local'); debug(`Creating new advertisement for "${this._id}" on ${port}`); this.state = STATE.STOPPED; this._interface = NetworkInterface.get(options.interface); this._defaultAddresses = null; this._hostnameResponder = null; this._serviceResponder = null; }
javascript
{ "resource": "" }
q51418
legacyify
train
function legacyify(record) { var clone = record.clone(); clone.isUnique = false; clone.ttl = 10; return clone; }
javascript
{ "resource": "" }
q51419
loadJSSequentially
train
function loadJSSequentially (aList, finished) { if (aList.length === 0) { console.log('Finished loadJSSequentially.') if (finished) { finished() } return } let item = aList.shift() let newScript = document.createElement('script') let url = null let shouldSkip = null let loaded = null if (typeof item === 'object') { ({ url, shouldSkip, loaded } = item) if (shouldSkip()) { console.log('Skipped loading', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) if (loaded) { loaded() } loadJSSequentially(aList, finished) } else { newScript.onload = () => { console.log('Loaded:', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) if (loaded) { loaded() } loadJSSequentially(aList, finished) } } } else if (typeof item === 'string') { url = item newScript.onload = () => { console.log('Loaded:', url) console.timeEnd(`\tLoading time of "${url}"\n\t`) loadJSSequentially(aList, finished) } } newScript.src = url document.head.appendChild(newScript) console.time(`\tLoading time of "${url}"\n\t`) }
javascript
{ "resource": "" }
q51420
WfI18n
train
function WfI18n (translation = {}, fallback = null, locale = 'en') { this.translation = translation this.locale = locale this.fallback = fallback this.t = (key) => { let result = this.translation[this.locale] if (!result) { result = this.translation[this.fallback] } if (!result) { throw new WfException(`Translation for locale "${this.locale}" not found.`) } const keys = key.split('.') if (keys.length === 0) { throw new WfException('Empty translation key.') } for (let i = 0; i < keys.length; i++) { result = result[keys[i]] if (!result) { setTimeout(() => { throw new WfException(`Translation for key "${key}" not found.`) }) return key } } return result } return { t: this.t } }
javascript
{ "resource": "" }
q51421
Bot
train
function Bot(options) { this.base_url = 'https://api.telegram.org/'; this.id = ''; this.first_name = ''; this.username = ''; this.token = options.token; this.offset = options.offset ? options.offset : 0; this.interval = options.interval ? options.interval : 500; this.webhook = options.webhook ? options.webhook : false; this.parseCommand = options.parseCommand ? options.parseCommand : true; this.maxAttempts = options.maxAttempts ? options.maxAttempts : 5; this.polling = false; this.pollingRequest = null; this.analytics = null; this.timeout = options.timeout ? options.timeout : 60; //specify in seconds // define the messageType's this.NORMAL_MESSAGE = 1; this.EDITED_MESSAGE = 2; }
javascript
{ "resource": "" }
q51422
transformPath
train
function transformPath (bgp, group, options) { let i = 0 var queryChange = false var ret = [bgp, null, []] while (i < bgp.length && !queryChange) { var curr = bgp[i] if (typeof curr.predicate !== 'string' && curr.predicate.type === 'path') { switch (curr.predicate.pathType) { case '/': ret = pathSeq(bgp, curr, i, group, ret[2], options) if (ret[1] != null) { queryChange = true } break case '^': ret = pathInv(bgp, curr, i, group, ret[2], options) if (ret[1] != null) { queryChange = true } break case '|': ret = pathAlt(bgp, curr, i, group, ret[2], options) queryChange = true break case '!': ret = pathNeg(bgp, curr, i, group, ret[2], options) queryChange = true break default: break } } i++ } return ret }
javascript
{ "resource": "" }
q51423
xivelyPost
train
function xivelyPost(feedId, streamId, apiKey, currentValue) { var dataPoint = { "version":"1.0.0", "datastreams" : [ { "id" : streamId, "current_value" : currentValue }, ] }; var requestUrl = "https://api.xively.com/v2/feeds/" + feedId; var options = { url: requestUrl, headers: { "X-ApiKey" : apiKey, "Content-Type": "application/json", "Accept": "*/*", "User-Agent": "nodejs" }, body: JSON.stringify(dataPoint) }; return requestPut(options); }
javascript
{ "resource": "" }
q51424
_lookupByNodeIdentifier
train
function _lookupByNodeIdentifier(nodeIdentifier, timeoutMs) { // if the address is cached, return that if (cachedNodes[nodeIdentifier]) { return rx.of({ destination64: cachedNodes[nodeIdentifier]}); } if (debug) { console.log("Looking up", nodeIdentifier); } return _localCommand("DN", timeoutMs, nodeIdentifier).pipe( rx.operators.catchError(function() { return rx.throwError(new Error("Node not found")); }), rx.operators.map(_extractDestination64), rx.operators.tap(function(address64) { cachedNodes[nodeIdentifier] = address64; }), rx.operators.map(function(address64) { return { destination64: address64 }; }) ); }
javascript
{ "resource": "" }
q51425
_remoteCommand
train
function _remoteCommand(command, destination64, destination16, timeoutMs, commandParameter, broadcast) { var frame = { type: xbee_api.constants.FRAME_TYPE.REMOTE_AT_COMMAND_REQUEST, command: command, commandParameter: commandParameter, destination64: destination64, destination16: destination16 }, responseStream; if (debug) { console.log("Sending", command, "to", destination64, "with parameter", commandParameter || []); } responseStream = _sendFrameStreamResponse(frame, timeoutMs, xbee_api.constants.FRAME_TYPE.REMOTE_COMMAND_RESPONSE).pipe( rx.operators.flatMap(function(frame) { if (frame.commandStatus === xbee_api.constants.COMMAND_STATUS.REMOTE_CMD_TRANS_FAILURE) { // if there was a remote command transmission failure, throw error return rx.throwError(new Error(xbee_api.constants.COMMAND_STATUS[frame.commandStatus])); } // any other response is returned return rx.of(frame); }) ); if (broadcast) { return responseStream; } else { // if not broadcast, there can be only one response packet return responseStream.pipe(rx.operators.take(1)); } }
javascript
{ "resource": "" }
q51426
_remoteTransmit
train
function _remoteTransmit(destination64, destination16, data, timeoutMs) { var frame = { data: data, type: xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_REQUEST, destination64: destination64, destination16: destination16 }, responseFrameType = xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_STATUS; if (module === "802.15.4") { responseFrameType = xbee_api.constants.FRAME_TYPE.TX_STATUS; frame.type = destination64 ? xbee_api.constants.FRAME_TYPE.TX_REQUEST_64 : xbee_api.constants.FRAME_TYPE.TX_REQUEST_16; } if (debug) { console.log("Sending '" + data + "' to", destination64 || destination16); } return _sendFrameStreamResponse(frame, timeoutMs, responseFrameType).pipe( rx.operators.take(1), rx.operators.flatMap(function(frame) { if (frame.deliveryStatus === xbee_api.constants.DELIVERY_STATUS.SUCCESS) { return rx.of(true); } // if not OK, throw error return rx.throwError(new Error(xbee_api.constants.DELIVERY_STATUS[frame.deliveryStatus])); }) ); }
javascript
{ "resource": "" }
q51427
getResults
train
function getResults( form, url, callback ){ var formData = new FormData( form ); var request = new XMLHttpRequest(); request.open("POST", url); request.send(formData); request.onload = function(e) { if (request.status == 200) { callback(null, JSON.parse(request.responseText)); } else { callback("Error " + request.status + ' - ' + request.responseText, null); } }; }
javascript
{ "resource": "" }
q51428
buildOptions
train
function buildOptions(request, callback) { let options = {}; let err = null; if (request.payload.html !== undefined) { options.html = request.payload.html.trim(); } if (request.payload.baseUrl !== undefined) { options.baseUrl = request.payload.baseUrl.trim(); } if (request.payload.filters !== undefined) { if (request.payload.filters.indexOf(',') > -1) { options.filters = trimArray(request.payload.filters.split(',')) } else { options.filters = trimArray(request.payload.filters) } if (options.filters.length === 0) { delete options.filters; } } if (request.payload.dateFormat !== undefined) { options.dateFormat = request.payload.dateFormat; } if (request.payload.textFormat !== undefined) { options.textFormat = request.payload.textFormat; } if (request.payload.overlappingVersions !== undefined) { options.overlappingVersions = request.payload.overlappingVersions } if (request.payload.impliedPropertiesByVersion !== undefined) { options.impliedPropertiesByVersion = request.payload.impliedPropertiesByVersion } if (request.payload.parseLatLonGeo !== undefined) { options.parseLatLonGeo = request.payload.parseLatLonGeo } if (request.payload.url !== undefined) { Request(request.payload.url, function (error, response, body) { err = error; if(!err && response && response.statusCode === 200){ options.html = body; callback(null, options); }else{ callback(err, null); } }); }else{ callback(err, options); } }
javascript
{ "resource": "" }
q51429
normalizeMessagePlaceholders
train
function normalizeMessagePlaceholders(descriptor, messageIds) { const message = typeof descriptor.messageId === 'string' ? messageIds[descriptor.messageId] : descriptor.message; if (!descriptor.data) { return { message, data: typeof descriptor.messageId === 'string' ? {} : null, }; } const normalizedData = Object.create(null); const interpolatedMessage = message.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, term) => { if (term in descriptor.data) { normalizedData[term] = descriptor.data[term]; return descriptor.data[term]; } return fullMatch; }); return { message: interpolatedMessage, data: Object.freeze(normalizedData), }; }
javascript
{ "resource": "" }
q51430
classOf
train
function classOf (obj) { const class2type = {} 'Boolean Number String Function Array Date RegExp Object tips'.split(' ') .forEach((e, i) => { class2type['[object ' + e + ']'] = e.toLowerCase() }) if (obj == null) { return String(obj) } return typeof obj === 'object' || typeof obj === 'function' ? class2type[ class2type.toString.call(obj) ] || 'object' : typeof obj }
javascript
{ "resource": "" }
q51431
install
train
function install (Vue, options = {}) { options.lang = options.lang || 'zh_cn' Object.assign(validator, options.validators) Object.assign(lang[options.lang], options.messages) try { const directive = new Directive(Vue, { mode: options.mode, errorIcon: options.errorIcon, errorClass: options.errorClass || null, errorForm: options.errorForm, validators: validator, messages: lang[options.lang] }) directive.install(Vue) } catch (e) { console.error(`${e}\nfrom v-verify`) } }
javascript
{ "resource": "" }
q51432
add
train
function add(message) { if (!message.order || // no keep order needed message.inProcess) {// or already in process return false; // should continue } var queue = this.getQueue(message.context); queue.unshift(message); // FIFO message.pointId = this.pipe._id; var moreInQueue = queue.length > 1; message.inProcess = !moreInQueue; return moreInQueue; }
javascript
{ "resource": "" }
q51433
train
function(elementId, apiController, direction) { if (elementId == pgwSlider.currentSlide) { return false; } var element = pgwSlider.data[elementId - 1]; if (typeof element == 'undefined') { throw new Error('PgwSlider - The element ' + elementId + ' is undefined'); return false; } if (typeof direction == 'undefined') { direction = 'left'; } // Before slide if (typeof pgwSlider.config.beforeSlide == 'function') { pgwSlider.config.beforeSlide(elementId); } if (typeof pgwSlider.plugin.find('.ps-caption').fadeOut == 'function') { pgwSlider.plugin.find('.ps-caption, .ps-prev, .ps-next').fadeOut(pgwSlider.config.transitionDuration / 2); } else { pgwSlider.plugin.find('.ps-caption, .ps-prev, .ps-next').hide(); } // Choose the transition effect if (pgwSlider.config.transitionEffect == 'sliding') { slideElement(element, direction); } else { fadeElement(element); } // Reset interval to avoid a half interval after an API control if (typeof apiController != 'undefined' && pgwSlider.config.autoSlide) { activateInterval(); } return true; }
javascript
{ "resource": "" }
q51434
destroy
train
function destroy(foPairs, index, collection, operand) { if (foPairs[index][collection].size === 1) { if (containsOne(foPairs[index])) { delete foPairs[index]; } else { delete foPairs[index][collection]; } }else { foPairs[index][collection].delete(operand); } }
javascript
{ "resource": "" }
q51435
evalFilter
train
function evalFilter(filters, results, pos = {value: 0}) { const key = Object.keys(filters)[0]; if (['and', 'or', 'not'].indexOf(key) === -1 || filters._isLeaf) { pos.value++; return results[pos.value - 1]; } if (key === 'not') { return !evalFilter(filters[key], results, pos); } return filters[key].reduce((p, c) => { const r = evalFilter(c, results, pos); if (p === null) { return r; } return key === 'and' ? p && r : p || r; }, null); }
javascript
{ "resource": "" }
q51436
onlyOneFieldAttribute
train
function onlyOneFieldAttribute(fieldsList, keyword) { if (fieldsList.length > 1) { return Bluebird.reject(new BadRequestError(`"${keyword}" can contain only one attribute`)); } return Bluebird.resolve(fieldsList); }
javascript
{ "resource": "" }
q51437
requireAttribute
train
function requireAttribute(filter, keyword, attribute) { if (!filter[attribute]) { return Bluebird.reject(new BadRequestError(`"${keyword}" requires the following attribute: ${attribute}`)); } return Bluebird.resolve(); }
javascript
{ "resource": "" }
q51438
mustBeNonEmptyObject
train
function mustBeNonEmptyObject(filter, keyword) { if (!filter || typeof filter !== 'object' || Array.isArray(filter)) { return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`)); } const fields = Object.keys(filter); if (fields.length === 0) { return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`)); } return Bluebird.resolve(fields); }
javascript
{ "resource": "" }
q51439
mustBeScalar
train
function mustBeScalar(filter, keyword, field) { if (filter[field] instanceof Object || filter[field] === undefined) { return Bluebird.reject(new BadRequestError(`"${field}" in "${keyword}" must be either a string, a number, a boolean or null`)); } return Bluebird.resolve(); }
javascript
{ "resource": "" }
q51440
mustBeString
train
function mustBeString(filter, keyword, field) { if (typeof filter[field] !== 'string') { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be a string`)); } return Bluebird.resolve(); }
javascript
{ "resource": "" }
q51441
mustBeNonEmptyArray
train
function mustBeNonEmptyArray(filter, keyword, field) { if (!Array.isArray(filter[field])) { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be an array`)); } if (filter[field].length === 0) { return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" cannot be empty`)); } return Bluebird.resolve(); }
javascript
{ "resource": "" }
q51442
storeGeoshape
train
function storeGeoshape(index, type, id, shape) { switch (type) { case 'geoBoundingBox': index.addBoundingBox(id, shape.bottom, shape.left, shape.top, shape.right ); break; case 'geoDistance': index.addCircle(id, shape.lat, shape.lon, shape.distance); break; case 'geoDistanceRange': index.addAnnulus(id, shape.lat, shape.lon, shape.to, shape.from); break; case 'geoPolygon': index.addPolygon(id, shape); break; default: break; } }
javascript
{ "resource": "" }
q51443
convertGeopoint
train
function convertGeopoint (point) { const t = typeof point; if (!point || (t !== 'string' && t !== 'object')) { return null; } // Format: "lat, lon" or "geohash" if (t === 'string') { return fromString(point); } // Format: [lat, lon] if (Array.isArray(point)) { if (point.length === 2) { return toCoordinate(point[0], point[1]); } return null; } const camelCased = geoLocationToCamelCase(point); // Format: { lat, lon } if (camelCased.hasOwnProperty('lat') && camelCased.hasOwnProperty('lon')) { return toCoordinate(camelCased.lat, camelCased.lon); } if (camelCased.latLon) { // Format: { latLon: [lat, lon] } if (Array.isArray(camelCased.latLon)) { if (camelCased.latLon.length === 2) { return toCoordinate(camelCased.latLon[0], camelCased.latLon[1]); } return null; } // Format: { latLon: { lat, lon } } if (typeof camelCased.latLon === 'object' && camelCased.latLon.hasOwnProperty('lat') && camelCased.latLon.hasOwnProperty('lon')) { return toCoordinate(camelCased.latLon.lat, camelCased.latLon.lon); } if (typeof camelCased.latLon === 'string') { return fromString(camelCased.latLon); } } return null; }
javascript
{ "resource": "" }
q51444
fromString
train
function fromString(str) { let tmp = str.match(regexLatLon), converted = null; // Format: "latitude, longitude" if (tmp !== null) { converted = toCoordinate(tmp[1], tmp[2]); } // Format: "<geohash>" else if (regexGeohash.test(str)) { tmp = geohash.decode(str); converted = toCoordinate(tmp.latitude, tmp.longitude); } return converted; }
javascript
{ "resource": "" }
q51445
geoLocationToCamelCase
train
function geoLocationToCamelCase (obj) { const converted = {}, keys = Object.keys(obj); let i; // NOSONAR for(i = 0; i < keys.length; i++) { const k = keys[i], idx = ['lat_lon', 'top_left', 'bottom_right'].indexOf(k); if (idx === -1) { converted[k] = obj[k]; } else { converted[k .split('_') .map((v,j) => j === 0 ? v : v.charAt(0).toUpperCase() + v.substring(1)) .join('')] = obj[k]; } } return converted; }
javascript
{ "resource": "" }
q51446
convertDistance
train
function convertDistance (distance) { let cleaned, converted; // clean up to ensure node-units will be able to convert it // for instance: "3 258,55 Ft" => "3258.55 ft" cleaned = distance .replace(/[-\s]/g, '') .replace(/,/g, '.') .toLowerCase() .replace(/([0-9])([a-z])/, '$1 $2'); try { converted = units.convert(cleaned + ' to m'); } catch (e) { throw new BadRequestError(`unable to parse distance value "${distance}"`); } return converted; }
javascript
{ "resource": "" }
q51447
dateAdd
train
function dateAdd (date, interval, units) { let result = new Date(date) switch (interval.toLowerCase()) { case 'year': result.setFullYear(result.getFullYear() + units) break case 'quarter': result.setMonth(result.getMonth() + 3 * units) break case 'month': result.setMonth(result.getMonth() + units) break case 'week': result.setDate(result.getDate() + 7 * units) break case 'day': result.setDate(result.getDate() + units) break case 'hour': result.setTime(result.getTime() + units * 3600000) break case 'minute': result.setTime(result.getTime() + units * 60000) break case 'second': result.setTime(result.getTime() + units * 1000) break default: result = undefined break } return result }
javascript
{ "resource": "" }
q51448
set
train
function set (key, value, time = 60) { let expireTime const cacheKey = `${prefix}${key}` const expireKey = `${expire}${key}` if (typeof time === 'number') { expireTime = dateAdd(Date.now(), 'minute', time) } else if (time !== null && typeof time === 'object' && time.interval && time.units) { expireTime = dateAdd(Date.now(), time.interval, time.units) } else { throw new Error('Invalid time provided for set') } return storage.set(expireKey, expireTime).then(() => storage.set(cacheKey, value)) }
javascript
{ "resource": "" }
q51449
remove
train
function remove (key) { if (typeof key !== 'string') { throw new Error('Invalid key provided for remove') } const keys = [`${prefix}${key}`, `${expire}${key}`] return storage.remove(keys) }
javascript
{ "resource": "" }
q51450
isExpired
train
function isExpired (key) { const expireKey = `${expire}${key}` return storage .get(expireKey) .then(time => Promise.resolve(Date.now() >= new Date(time).getTime(), time)) }
javascript
{ "resource": "" }
q51451
get
train
function get (key) { return isExpired(key).then(hasExpired => { if (hasExpired) { return remove(key).then(() => Promise.resolve(undefined)) } else { return storage.get(`${prefix}${key}`) } }) }
javascript
{ "resource": "" }
q51452
flush
train
function flush () { return storage.keys().then(keys => { return storage.remove( keys.filter(key => key.indexOf(prefix) === 0 || key.indexOf(expire) === 0) ) }) }
javascript
{ "resource": "" }
q51453
flushExpired
train
function flushExpired () { return storage.keys().then(keys => { const cacheKeys = keys.filter(key => key.indexOf(expire) === 0) return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length)))) }) }
javascript
{ "resource": "" }
q51454
train
function(tagName, parent){ this.name = tagName; this.parent = parent; this.attributes = {}; this.children = []; this.tagScore = 0; this.attributeScore = 0; this.totalScore = 0; this.elementData = ""; this.info = { textLength: 0, linkLength: 0, commas: 0, density: 0, tagCount: {} }; this.isCandidate = false; }
javascript
{ "resource": "" }
q51455
train
function(settings){ //the root node this._currentElement = new Element("document"); this._topCandidate = null; this._origTitle = this._headerTitle = ""; this._scannedLinks = {}; if(settings) this._processSettings(settings); }
javascript
{ "resource": "" }
q51456
canInclude
train
function canInclude(entry, opts) { if (!opts.include || !opts.include.length) return true; return !entry.isDirectory(); }
javascript
{ "resource": "" }
q51457
genCircles
train
function genCircles(width, height, N = 500) { const minR = 1; const maxR = Math.sqrt(width * height / N) * 0.5; return [...Array(N)].map((_, idx) => ({ id: idx, x: Math.round(Math.random() * width), y: Math.round(Math.random() * height), r: Math.max(minR, Math.round(Math.random() * maxR)) })); }
javascript
{ "resource": "" }
q51458
toFraction
train
function toFraction (value) { var integer = Math.floor(value); var decimal = value - integer; var key = n2f(decimal); var result = value; if (vulgarities.hasOwnProperty(key)) { result = integer + vulgarities[key]; } return result; }
javascript
{ "resource": "" }
q51459
dummyImgSrc
train
function dummyImgSrc (width, height, options) { if (!R.is(Number, width) || !R.is(Number, height)) { throw new Error('The "dummyImgSrc" helper must be passed two numeric dimensions.'); } var result = encode(create(width, height, options.hash)); return new Handlebars.SafeString(result); }
javascript
{ "resource": "" }
q51460
randomItem
train
function randomItem () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper "randomItem" must be passed at least one argument.'); } if (items.length === 1) { items = R.is(Array, items[0]) ? items[0] : [items[0]]; } return items[Math.floor(Math.random() * items.length)]; }
javascript
{ "resource": "" }
q51461
compare
train
function compare (left, operator, right, options) { var result; if (arguments.length < 3) { throw new Error('The "compare" helper needs two arguments.'); } if (options === undefined) { options = right; right = operator; operator = '==='; } if (operators[operator] === undefined) { throw new Error('The "compare" helper needs a valid operator.') } result = operators[operator](left, right); if (R.isNil(options.fn)) { return result; } return result ? options.fn(this) : options.inverse(this); }
javascript
{ "resource": "" }
q51462
capitalizeWords
train
function capitalizeWords (str) { if (R.isNil(str)) { throw new Error('The "capitalizeWords" helper requires one argument.') } if (!R.is(String, str)) { str = str.toString(); } return Capitalize.words(str); }
javascript
{ "resource": "" }
q51463
replaceAll
train
function replaceAll (input, find, replace) { let regex = new RegExp(find, 'g'); return input.toString().replace(regex, replace); }
javascript
{ "resource": "" }
q51464
around
train
function around (items, center, padding, block) { var result = ''; var options = (block && block.hash) ? R.merge(defaults, block.hash) : R.clone(defaults); var max, start, end; center = parseFloat(center) + options.offset; padding = parseFloat(padding); max = padding * 2 + 1; if (items.length > max) { start = center - padding; end = center + padding + 1; if (start < 0) { end -= start; start = 0; } if (end > items.length) { start -= end - items.length; end = items.length; } items = items.slice(start, end); } for (var item in items) { result += block.fn(items[item]); } return result; }
javascript
{ "resource": "" }
q51465
average
train
function average (arr, options) { var isArray = Array.isArray(arr); var key = options.hash.key; var sum; if (!isArray) { throw new Error('The helper "average" must be passed an Array.'); } if (key) { arr = arr.map(function (item) { return item[key]; }); } sum = arr.reduce(function (prev, current) { return prev + current; }); return sum / arr.length; }
javascript
{ "resource": "" }
q51466
toSlug
train
function toSlug (str) { return str .toString() .toLowerCase() .replace(/\s+/g, '-') // Replace spaces with - .replace(/[^\w\-]+/g, '-') // Remove all non-word chars .replace(/\-\-+/g, '-') // Replace multiple - with single - .replace(/^-+/, '') // Trim - from start of text .replace(/-+$/, ''); // Trim - from end of text }
javascript
{ "resource": "" }
q51467
concat
train
function concat () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper "concat" must be passed at least one argument.'); } return items.join(''); }
javascript
{ "resource": "" }
q51468
iterate
train
function iterate (num, block) { return R.times(function (i) { var data = block.data ? R.merge( Handlebars.createFrame(block.data), { index: i, count: i + 1} ) : null; return block.fn(i, {data: data}); }, num).join(''); }
javascript
{ "resource": "" }
q51469
toJSON
train
function toJSON (str) { str = str.toString(); try { return JSON.parse(str); } catch (e) { throw new Error( 'The "toJSON" helper must be passed a valid JSON string.' ); } }
javascript
{ "resource": "" }
q51470
capitalize
train
function capitalize (str) { if (R.isNil(str)) { throw new Error('The "capitalize" helper requires one argument.') } if (!R.is(String, str)) { str = str.toString(); } return Capitalize(str); }
javascript
{ "resource": "" }
q51471
math
train
function math (left, operator, right, options) { if (arguments.length < 3) { throw new Error('The "math" helper needs at least two arguments.'); } if (options === undefined) { options = right; right = undefined; } left = parseFloat(left); right = parseFloat(right); if (operators[operator] === undefined) { throw new Error ('The "math" helper needs a valid operator.'); } return operators[operator](left, right); }
javascript
{ "resource": "" }
q51472
defaultTo
train
function defaultTo () { var values = R.append('', R.dropLast(1, arguments)); return R.head(R.reject(R.isNil, values)); }
javascript
{ "resource": "" }
q51473
train
function(iOstWSProvider) { const oThis = this; oThis.iOstWSProvider = iOstWSProvider; oThis.endPointUrl = iOstWSProvider.endPointUrl; oThis.notificationCallbacks = iOstWSProvider.notificationCallbacks; const options = iOstWSProvider.options; Object.assign(oThis, options); oThis.reconnect(); }
javascript
{ "resource": "" }
q51474
train
function(moduleName, logLevel) { var oThis = this; if (moduleName) { oThis.moduleNamePrefix = '[' + moduleName + ']'; } oThis.setLogLevel(logLevel); }
javascript
{ "resource": "" }
q51475
train
function(requestUrl, requestType) { const oThis = this, d = new Date(), dateTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds(), message = "Started '" + requestType + "' '" + requestUrl + "' at " + dateTime; oThis.info(message); }
javascript
{ "resource": "" }
q51476
train
function() { var oThis = this; var argsPassed = oThis._filterArgs(arguments); var args = [oThis.getPrefix(this.ERR_PRE)]; args = args.concat(Array.prototype.slice.call(argsPassed)); args.push(this.CONSOLE_RESET); console.log.apply(console, args); }
javascript
{ "resource": "" }
q51477
checkAvailability
train
function checkAvailability(fullGetterName) { if (composerMap.hasOwnProperty(fullGetterName) || shadowMap.hasOwnProperty(fullGetterName)) { console.trace('Duplicate Getter Method name', fullGetterName); throw 'Duplicate Getter Method Name '; } }
javascript
{ "resource": "" }
q51478
promiseSeries
train
function promiseSeries(items, iterator) { return items.reduce((iterable, name) => { return iterable.then(() => iterator(name)); }, Promise.resolve()); }
javascript
{ "resource": "" }
q51479
getConfigGetter
train
function getConfigGetter(options) { /** * Return a config value. * * @param {string} prop * @param {any} [defaultValue] * @return {any} */ function config(prop, defaultValue) { console.warn( 'Warning: calling config as a function is deprecated. Use config.values() instead' ); return get(options, prop, defaultValue); } /** * Return an object with all config values. * * @return {Object} */ function values() { return options; } /** * Mark config options as required. * * @param {string[]} names... * @return {Object} this */ function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, { unknown, }); } return config; } /** * Set default values. * * @param {Object} defaultOptions * @return {any} */ function defaults(defaultOptions) { options = Object.assign({}, defaultOptions, options); return config; } config.require = require; config.defaults = defaults; config.values = values; return config; }
javascript
{ "resource": "" }
q51480
require
train
function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, { unknown, }); } return config; }
javascript
{ "resource": "" }
q51481
getConfigFromFile
train
function getConfigFromFile(directories, filename) { const filepath = tryFile(directories, filename); if (!filepath) { return {}; } return require(filepath); }
javascript
{ "resource": "" }
q51482
tryFile
train
function tryFile(directories, filename) { return firstResult(directories, dir => { const filepath = path.resolve(dir, filename); return fs.existsSync(filepath) ? filepath : undefined; }); }
javascript
{ "resource": "" }
q51483
firstResult
train
function firstResult(items, fn) { for (const item of items) { if (!item) { continue; } const result = fn(item); if (result) { return result; } } return undefined; }
javascript
{ "resource": "" }
q51484
train
function(RGBArray) { var hex = '#'; RGBArray.forEach(function(value) { if (value < 16) { hex += 0; } hex += value.toString(16); }); return hex; }
javascript
{ "resource": "" }
q51485
train
function(H, S, L) { H /= 360; var q = L < 0.5 ? L * (1 + S) : L + S - L * S; var p = 2 * L - q; return [H + 1/3, H, H - 1/3].map(function(color) { if(color < 0) { color++; } if(color > 1) { color--; } if(color < 1/6) { color = p + (q - p) * 6 * color; } else if(color < 0.5) { color = q; } else if(color < 2/3) { color = p + (q - p) * 6 * (2/3 - color); } else { color = p; } return Math.round(color * 255); }); }
javascript
{ "resource": "" }
q51486
train
function(options) { options = options || {}; var LS = [options.lightness, options.saturation].map(function(param) { param = param || [0.35, 0.5, 0.65]; // note that 3 is a prime return isArray(param) ? param.concat() : [param]; }); this.L = LS[0]; this.S = LS[1]; if (typeof options.hue === 'number') { options.hue = {min: options.hue, max: options.hue}; } if (typeof options.hue === 'object' && !isArray(options.hue)) { options.hue = [options.hue]; } if (typeof options.hue === 'undefined') { options.hue = []; } this.hueRanges = options.hue.map(function (range) { return { min: typeof range.min === 'undefined' ? 0 : range.min, max: typeof range.max === 'undefined' ? 360: range.max }; }); this.hash = options.hash || BKDRHash; }
javascript
{ "resource": "" }
q51487
compose
train
function compose() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return function (arg0) { return (0, _array.reduceRight)(function (value, fn) { return fn(value); }, arg0, args); }; }
javascript
{ "resource": "" }
q51488
NodeContext
train
function NodeContext(msg, parent, nodeContext, serverName) { this.msgContext = new mustache.Context(msg, parent); this.nodeContext = nodeContext; this.serverName = serverName; }
javascript
{ "resource": "" }
q51489
train
function() { window.OPENSHIFT_CONFIG.api.k8s.resources = api.k8s; window.OPENSHIFT_CONFIG.api.openshift.resources = api.openshift; window.OPENSHIFT_CONFIG.apis.groups = apis; if (API_DISCOVERY_ERRORS.length) { window.OPENSHIFT_CONFIG.apis.API_DISCOVERY_ERRORS = API_DISCOVERY_ERRORS; } next(); }
javascript
{ "resource": "" }
q51490
ResourceGroupVersion
train
function ResourceGroupVersion(resource, group, version) { this.resource = resource; this.group = group; this.version = version; return this; }
javascript
{ "resource": "" }
q51491
normalizeResource
train
function normalizeResource(resource) { if (!resource) { return resource; } var i = resource.indexOf('/'); if (i === -1) { return resource.toLowerCase(); } return resource.substring(0, i).toLowerCase() + resource.substring(i); }
javascript
{ "resource": "" }
q51492
train
function(includeClusterScoped) { var kinds = []; var rejectedKinds = _.map(Constants.AVAILABLE_KINDS_BLACKLIST, function(kind) { return _.isString(kind) ? { kind: kind, group: '' } : kind; }); // ignore the legacy openshift kinds, these have been migrated to api groups _.each(_.pickBy(API_CFG, function(value, key) { return key !== 'openshift'; }), function(api) { _.each(api.resources.v1, function(resource) { if (resource.namespaced || includeClusterScoped) { // Exclude subresources and any rejected kinds if (_.includes(resource.name, '/') || _.find(rejectedKinds, { kind: resource.kind, group: '' })) { return; } kinds.push({ kind: resource.kind, group: '' }); } }); }); // Kinds under api groups _.each(APIS_CFG.groups, function(group) { // Use the console's default version first, and the server's preferred version second var preferredVersion = defaultVersion[group.name] || group.preferredVersion; _.each(group.versions[preferredVersion].resources, function(resource) { // Exclude subresources and any rejected kinds if (_.includes(resource.name, '/') || _.find(rejectedKinds, {kind: resource.kind, group: group.name})) { return; } if(excludeKindFromAPIGroupList(group.name, resource.kind)) { return; } if (resource.namespaced || includeClusterScoped) { kinds.push({ kind: resource.kind, group: group.name }); } }); }); return _.uniqBy(kinds, function(value) { return value.group + "/" + value.kind; }); }
javascript
{ "resource": "" }
q51493
train
function() { var user = userStore.getUser(); if (user) { $rootScope.user = user; authLogger.log('AuthService.withUser()', user); return $q.when(user); } else { authLogger.log('AuthService.withUser(), calling startLogin()'); return this.startLogin(); } }
javascript
{ "resource": "" }
q51494
train
function(config) { // Requests that don't require auth can continue if (!AuthService.requestRequiresAuth(config)) { // console.log("No auth required", config.url); return config; } // If we could add auth info, we can continue if (AuthService.addAuthToRequest(config)) { // console.log("Auth added", config.url); return config; } // We should have added auth info, but couldn't // If we were specifically told not to trigger a login, return if (config.auth && config.auth.triggerLogin === false) { return config; } // 1. Set up a deferred and remember this config, so we can add auth info and resume once login is complete var deferred = $q.defer(); pendingRequestConfigs.push([deferred, config, 'request']); // 2. Start the login flow AuthService.startLogin(); // 3. Return the deferred's promise return deferred.promise; }
javascript
{ "resource": "" }
q51495
train
function(projectName, forceRefresh) { var deferred = $q.defer(); currentProject = projectName; var projectRules = cachedRulesByProject.get(projectName); var rulesResource = "selfsubjectrulesreviews"; if (!projectRules || projectRules.forceRefresh || forceRefresh) { // Check if APIserver contains 'selfsubjectrulesreviews' resource. If not switch to permissive mode. if (APIService.apiInfo(rulesResource)) { // If a request is already in flight, return the promise for that request. if (inFlightRulesRequests[projectName]) { return inFlightRulesRequests[projectName]; } Logger.log("AuthorizationService, loading user rules for " + projectName + " project"); inFlightRulesRequests[projectName] = deferred.promise; var resourceGroupVersion = { kind: "SelfSubjectRulesReview", apiVersion: "v1" }; DataService.create(rulesResource, null, resourceGroupVersion, {namespace: projectName}).then( function(data) { var normalizedData = normalizeRules(data.status.rules); var canUserAddToProject = canAddToProjectCheck(data.status.rules); cachedRulesByProject.put(projectName, {rules: normalizedData, canAddToProject: canUserAddToProject, forceRefresh: false, cacheTimestamp: _.now() }); deferred.resolve(); }, function() { permissiveMode = true; deferred.resolve(); }).finally(function() { delete inFlightRulesRequests[projectName]; }); } else { Logger.log("AuthorizationService, resource 'selfsubjectrulesreviews' is not part of APIserver. Switching into permissive mode."); permissiveMode = true; deferred.resolve(); } } else { // Using cached data. Logger.log("AuthorizationService, using cached rules for " + projectName + " project"); if ((_.now() - projectRules.cacheTimestamp) >= 600000) { projectRules.forceRefresh = true; } deferred.resolve(); } return deferred.promise; }
javascript
{ "resource": "" }
q51496
train
function(serviceInstance, application, serviceClass, parameters) { var parametersSecretName; if (!_.isEmpty(parameters)) { parametersSecretName = generateSecretName(serviceInstance.metadata.name + '-bind-parameters-'); } var newBinding = makeBinding(serviceInstance, application, parametersSecretName); var context = { namespace: serviceInstance.metadata.namespace }; var promise = DataService.create(serviceBindingsVersion, null, newBinding, context); if (!parametersSecretName) { return promise; } // Create the secret as well if the binding has parameters. return promise.then(function(binding) { var parametersSecret = makeParametersSecret(parametersSecretName, parameters, binding); return DataService.create(secretsVersion, null, parametersSecret, context).then(function() { return binding; }); }); }
javascript
{ "resource": "" }
q51497
train
function(id) { if (openQueue[id]) { delete openQueue[id]; } if (messageQueue[id]) { delete messageQueue[id]; } if (closeQueue[id]) { delete closeQueue[id]; } if (errorQueue[id]) { delete errorQueue[id]; } }
javascript
{ "resource": "" }
q51498
train
function(params) { var keys = _.keysIn( _.pick( params, ['fieldSelector', 'labelSelector']) ).sort(); return _.reduce( keys, function(result, key, i) { return result + key + '=' + encodeURIComponent(params[key]) + ((i < (keys.length-1)) ? '&' : ''); }, '?'); }
javascript
{ "resource": "" }
q51499
train
function(objects, filterFields, keywords) { if (_.isEmpty(keywords)) { return []; } var results = []; _.each(objects, function(object) { // Keep a score for matches, weighted by field. var score = 0; _.each(keywords, function(regex) { var matchesKeyword = false; _.each(filterFields, function(field) { var value = _.get(object, field.path); if (!value) { return; } if (regex.test(value)) { // For each matching keyword, add the field weight to the score. score += field.weight; matchesKeyword = true; } }); if (!matchesKeyword) { // We've missed a keyword. Set score to 0 and short circuit the loop. score = 0; return false; } }); if (score > 0) { results.push({ object: object, score: score }); } }); // Sort first by score, then by display name for items that have the same score. var orderedResult = _.orderBy(results, ['score', displayName], ['desc', 'asc']); return _.map(orderedResult, 'object'); }
javascript
{ "resource": "" }