_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
27
233k
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()...
javascript
{ "resource": "" }
q51401
sanitize
train
function sanitize(options, blacklist) { const opts = Object.assign({}, options); const defaults
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 po...
javascript
{ "resource": "" }
q51403
matchesFactory
train
function matchesFactory(test) { return matches function matches(node) { var key for (key in test) { if
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 {N...
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';
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: {},
javascript
{ "resource": "" }
q51407
Parser
train
function Parser(options) { this.options = merge({}, { headers: { included: false, downcase: true, upcase: true
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.del...
javascript
{ "resource": "" }
q51409
Subject
train
function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false,
javascript
{ "resource": "" }
q51410
BehaviorSubject
train
function BehaviorSubject(value) { __super__.call(this, subscribe); this.value =
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 = [];
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 rende...
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]') {
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 subty...
javascript
{ "resource": "" }
q51415
visualPad
train
function visualPad(str, num) { var needed = num - str.replace(remove_colors_re, '').length;
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) { ...
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(typ...
javascript
{ "resource": "" }
q51418
legacyify
train
function legacyify(record) { var clone = record.clone(); clone.isUnique = false;
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 = ...
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) { thr...
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
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 '/': ...
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...
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); ...
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, destination6...
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 }, r...
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,
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 (reque...
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 ...
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 ' +
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....
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
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 ' + ele...
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 {
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];
javascript
{ "resource": "" }
q51436
onlyOneFieldAttribute
train
function onlyOneFieldAttribute(fieldsList, keyword) { if (fieldsList.length > 1) { return Bluebird.reject(new BadRequestError(`"${keyword}" can contain
javascript
{ "resource": "" }
q51437
requireAttribute
train
function requireAttribute(filter, keyword, attribute) { if (!filter[attribute]) { return Bluebird.reject(new BadRequestError(`"${keyword}" requires the
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);
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
javascript
{ "resource": "" }
q51440
mustBeString
train
function mustBeString(filter, keyword, field) { if (typeof filter[field] !== 'string') {
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) {
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); ...
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) { ...
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))
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 { ...
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
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(r...
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)
javascript
{ "resource": "" }
q51449
remove
train
function remove (key) { if (typeof key !== 'string') { throw new Error('Invalid key provided for remove') }
javascript
{ "resource": "" }
q51450
isExpired
train
function isExpired (key) { const expireKey = `${expire}${key}` return storage .get(expireKey)
javascript
{ "resource": "" }
q51451
get
train
function get (key) { return isExpired(key).then(hasExpired => { if (hasExpired) { return remove(key).then(() => Promise.resolve(undefined))
javascript
{ "resource": "" }
q51452
flush
train
function flush () { return storage.keys().then(keys => { return storage.remove(
javascript
{ "resource": "" }
q51453
flushExpired
train
function flushExpired () { return storage.keys().then(keys => { const cacheKeys = keys.filter(key => key.indexOf(expire) === 0)
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 = {
javascript
{ "resource": "" }
q51455
train
function(settings){ //the root node this._currentElement = new Element("document"); this._topCandidate = null; this._origTitle = this._headerTitle = "";
javascript
{ "resource": "" }
q51456
canInclude
train
function canInclude(entry, opts) { if (!opts.include
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),
javascript
{ "resource": "" }
q51458
toFraction
train
function toFraction (value) { var integer = Math.floor(value); var decimal = value - integer; var key = n2f(decimal); var result = value;
javascript
{ "resource": "" }
q51459
dummyImgSrc
train
function dummyImgSrc (width, height, options) { if (!R.is(Number, width) || !R.is(Number, height)) { throw new Error('The "dummyImgSrc"
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) {
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) { th...
javascript
{ "resource": "" }
q51462
capitalizeWords
train
function capitalizeWords (str) { if (R.isNil(str)) { throw new Error('The "capitalizeWords" helper requires one argument.') }
javascript
{ "resource": "" }
q51463
replaceAll
train
function replaceAll (input, find, replace) { let regex
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) { ...
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
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, '-') //
javascript
{ "resource": "" }
q51467
concat
train
function concat () { var items = R.dropLast(1, arguments); if (!items.length) { throw new Error('The helper
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
javascript
{ "resource": "" }
q51469
toJSON
train
function toJSON (str) { str = str.toString(); try { return JSON.parse(str); } catch (e) { throw new Error(
javascript
{ "resource": "" }
q51470
capitalize
train
function capitalize (str) { if (R.isNil(str)) { throw new Error('The "capitalize" helper requires one argument.') }
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) {
javascript
{ "resource": "" }
q51472
defaultTo
train
function defaultTo () { var values = R.append('', R.dropLast(1, arguments));
javascript
{ "resource": "" }
q51473
train
function(iOstWSProvider) { const oThis = this; oThis.iOstWSProvider = iOstWSProvider; oThis.endPointUrl = iOstWSProvider.endPointUrl;
javascript
{ "resource": "" }
q51474
train
function(moduleName, logLevel) { var oThis = this; if (moduleName) { oThis.moduleNamePrefix = '[' +
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() + ...
javascript
{ "resource": "" }
q51476
train
function() { var oThis = this; var argsPassed = oThis._filterArgs(arguments); var args = [oThis.getPrefix(this.ERR_PRE)];
javascript
{ "resource": "" }
q51477
checkAvailability
train
function checkAvailability(fullGetterName) { if (composerMap.hasOwnProperty(fullGetterName) || shadowMap.hasOwnProperty(fullGetterName))
javascript
{ "resource": "" }
q51478
promiseSeries
train
function promiseSeries(items, iterator) { return items.reduce((iterable, name) => {
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, ...
javascript
{ "resource": "" }
q51480
require
train
function require(...names) { const unknown = names.filter(name => !options[name]); if (unknown.length > 0) { throw new MrmUndefinedOption(`Required
javascript
{ "resource": "" }
q51481
getConfigFromFile
train
function getConfigFromFile(directories, filename) { const filepath = tryFile(directories, filename);
javascript
{ "resource": "" }
q51482
tryFile
train
function tryFile(directories, filename) { return firstResult(directories, dir => { const filepath = path.resolve(dir, filename);
javascript
{ "resource": "" }
q51483
firstResult
train
function firstResult(items, fn) { for (const item of items) { if (!item) { continue; } const result = fn(item); if
javascript
{ "resource": "" }
q51484
train
function(RGBArray) { var hex = '#'; RGBArray.forEach(function(value) { if (value < 16) { hex += 0;
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 =...
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 op...
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) {
javascript
{ "resource": "" }
q51488
NodeContext
train
function NodeContext(msg, parent, nodeContext, serverName) { this.msgContext
javascript
{ "resource": "" }
q51489
train
function() { window.OPENSHIFT_CONFIG.api.k8s.resources = api.k8s; window.OPENSHIFT_CONFIG.api.openshift.resources = api.openshift;
javascript
{ "resource": "" }
q51490
ResourceGroupVersion
train
function ResourceGroupVersion(resource, group, version) { this.resource = resource; this.group =
javascript
{ "resource": "" }
q51491
normalizeResource
train
function normalizeResource(resource) { if (!resource) { return resource; } var i = resource.indexOf('/'); if (i === -1) { return resource.toLowerCase();
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...
javascript
{ "resource": "" }
q51493
train
function() { var user = userStore.getUser(); if (user) { $rootScope.user = user; authLogger.log('AuthService.withUser()', user);
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)) { ...
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 APIs...
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, applicatio...
javascript
{ "resource": "" }
q51497
train
function(id) { if (openQueue[id]) { delete openQueue[id]; } if (messageQueue[id]) { delete messageQueue[id]; }
javascript
{ "resource": "" }
q51498
train
function(params) { var keys = _.keysIn( _.pick( params, ['fieldSelector', 'labelSelector']) ).sort(); return _.reduce( keys, function(result,
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...
javascript
{ "resource": "" }