_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q7200
train
function(scopes) { console.log('iamInterface.group.addScopes', scopes); corbel.validate.value('id', this.id); return this.request({ url: this._buildUriWithDomain(this.uri, this.id) + '/scope', method: corbel.request.method.PUT, data: scopes, withAuth: true }); }
javascript
{ "resource": "" }
q7201
train
function(email) { console.log('iamInterface.email.availability', email); corbel.validate.value('email', email); return this.request({ url: this._buildUriWithDomain(this.uri, email), method: corbel.request.method.HEAD }).then( function() { return false; }, function(response) { if (response.status === 404) { return true; } else { return Promise.reject(response); } } ); }
javascript
{ "resource": "" }
q7202
train
function(srcType, srcId, destType, destId) { var urlBase = this.driver.config.getCurrentEndpoint(corbel.Resources.moduleName, this._buildPort(this.driver.config)); var domain = this.driver.config.get(corbel.Iam.IAM_DOMAIN, 'unauthenticated'); var customDomain = this.driver.config.get(corbel.Domain.CUSTOM_DOMAIN, domain); this.driver.config.set(corbel.Domain.CUSTOM_DOMAIN, undefined); var uri = urlBase + customDomain + '/resource/' + srcType; if (srcId) { uri += '/' + srcId; if (destType) { uri += '/' + destType; if (destId) { uri += ';r=' + destType + '/' + destId; } } } return uri; }
javascript
{ "resource": "" }
q7203
train
function(destId, relationData, options) { options = this.getDefaultOptions(options); corbel.validate.value('destId', destId); var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), data: relationData, method: corbel.request.method.PUT, contentType: options.dataType, Accept: options.dataType }); return this.request(args); }
javascript
{ "resource": "" }
q7204
train
function(relationData, options) { options = this.getDefaultOptions(options); var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType), data: relationData, method: corbel.request.method.POST, contentType: options.dataType, Accept: options.dataType }); return this.request(args); }
javascript
{ "resource": "" }
q7205
train
function(destId, pos, options) { corbel.validate.value('destId', destId); var positionStartId = destId.indexOf('/'); if (positionStartId !== -1) { destId = destId.substring(positionStartId + 1); } options = this.getDefaultOptions(options); var args = corbel.utils.extend(options, { url: this.buildUri(this.type, this.srcId, this.destType, destId), contentType: 'application/json', data: { '_order': '$pos(' + pos + ')' }, method: corbel.request.method.PUT }); return this.request(args); }
javascript
{ "resource": "" }
q7206
train
function(data, options) { options = this.getDefaultOptions(options); var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.POST, contentType: options.dataType, Accept: options.dataType, data: data }); return this.request(args).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7207
train
function(data, options) { options = this.getDefaultOptions(options); var args = corbel.utils.extend(options, { url: this.buildUri(this.type), method: corbel.request.method.PUT, contentType: options.dataType, Accept: options.dataType, data: data }); return this.request(args); }
javascript
{ "resource": "" }
q7208
train
function(acl) { var args = { url: this.buildUri(this.type, this.id), method: corbel.request.method.PUT, data: acl, Accept: 'application/corbel.acl+json' }; return this.request(args); }
javascript
{ "resource": "" }
q7209
train
function() { console.log('oauthInterface.authorization.dialog'); var that = this; return this.request({ url: this._buildUri(this.uri + '/authorize'), method: corbel.request.method.GET, dataType: 'text', withCredentials: true, query: corbel.utils.toURLEncoded(this.params.data), noRedirect: true, contentType: corbel.Oauth._URL_ENCODED }) .then(function(res) { var params = { url: corbel.Services.getLocation(res), withCredentials: true }; return that.request(params); }); }
javascript
{ "resource": "" }
q7210
train
function(username, password, setCookie, redirect) { console.log('oauthInterface.authorization.login', username + ':' + password); if (username) { this.params.data.username = username; } if (password) { this.params.data.password = password; } this.params.withCredentials = true; var that = this; // make request, generate oauth cookie, then redirect manually return this.request({ url: this._buildUri(this.uri + '/authorize'), method: corbel.request.method.POST, data: this.params.data, contentType: this.params.contentType, noRedirect: redirect ? redirect : true }) .then(function(res) { if (corbel.Services.getLocation(res)) { var req = { url: corbel.Services.getLocation(res) }; if (setCookie) { req.headers = { RequestCookie: 'true' }; req.withCredentials = true; } return that.request(req).then(function(response) { var accessToken = response.data.accessToken || response.data.query.code; that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); that.driver.config.set(corbel.Iam.IAM_DOMAIN, corbel.jwt.decode(accessToken).domainId); if (that.params.jwt) { that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, corbel.jwt.decode(that.params.jwt).scope); } if (that.params.claims) { if (that.params.claims.scope) { that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.params.claims.scope); } else { that.driver.config.set(corbel.Iam.IAM_TOKEN_SCOPES, that.driver.config.get('scopes', '')); } } return response; }); } else { return res.data; } }); }
javascript
{ "resource": "" }
q7211
train
function() { console.log('oauthInterface.authorization.signOut'); delete this.params.data; return this.request({ url: this._buildUri(this.uri + '/signout'), method: corbel.request.method.GET, withCredentials: true }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7212
train
function(user) { console.log('oauthInterface.user.create', user); return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, headers: { Authorization: 'Basic ' + this.getSerializer()(this.clientId + ':' + this.clientSecret) }, dataType: 'text', data: user }) .then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7213
train
function(notification) { console.log('notificationsInterface.notification.sendNotification', notification); this.uri += '/send'; return this.request({ url: this.buildUri(this.uri), method: corbel.request.method.POST, data: notification }); }
javascript
{ "resource": "" }
q7214
train
function(couponIds) { console.log('ecInterface.order.prepare'); corbel.validate.value('id', this.id); return this.request({ url: this._buildUri(this.uri, this.id, '/prepare'), method: corbel.request.method.POST, data: couponIds }); }
javascript
{ "resource": "" }
q7215
train
function(data) { console.log('ecInterface.order.checkout'); if (!data.paymentMethodIds) { return Promise.reject(new Error('paymentMethodIds lists needed')); } if (!data.paymentMethodIds.length) { return Promise.reject(new Error('One payment method is needed at least')); } corbel.validate.value('id', this.id); return this.request({ method: corbel.request.method.POST, url: this._buildUri(this.uri, this.id, '/checkout'), data: data }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7216
train
function(product) { console.log('ecInterface.product.create', product); return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: product }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7217
train
function(eventData) { if (!eventData) { throw new Error('Send event require data'); } console.log('evciInterface.publish', eventData); corbel.validate.value('eventType', this.eventType); return this.request({ url: this._buildUri(this.uri, this.eventType), method: corbel.request.method.POST, data: eventData }).then(function(res) { return res; }); }
javascript
{ "resource": "" }
q7218
train
function(id) { var resource = new corbel.Borrow.BorrowBuilder(id); resource.driver = this.driver; return resource; }
javascript
{ "resource": "" }
q7219
train
function(id) { var lender = new corbel.Borrow.LenderBuilder(id); lender.driver = this.driver; return lender; }
javascript
{ "resource": "" }
q7220
train
function(id) { var user = new corbel.Borrow.UserBuilder(id); user.driver = this.driver; return user; }
javascript
{ "resource": "" }
q7221
train
function(license) { console.log('borrowInterface.resource.addLicense', license); corbel.validate.value('id', this.id); return this.request({ url: this._buildUri(this.uri, this.id, 'license'), method: corbel.request.method.POST, data: license }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7222
train
function() { console.log('borrowInterface.user.getAllLoans', this.id); return this.request({ url: this._buildUri(this.uri, this.id, 'loan'), method: corbel.request.method.GET }); }
javascript
{ "resource": "" }
q7223
train
function(lender) { console.log('borrowInterface.lender.update'); return this.request({ url: this._buildUri(this.uri, this.id), method: corbel.request.method.PUT, data: lender }); }
javascript
{ "resource": "" }
q7224
train
function(id) { var phraseBuilder = new corbel.CompoSR.PhraseBuilder(id); phraseBuilder.driver = this.driver; return phraseBuilder; }
javascript
{ "resource": "" }
q7225
train
function() { var requestBuilder = new corbel.CompoSR.RequestBuilder(Array.prototype.slice.call(arguments)); requestBuilder.driver = this.driver; return requestBuilder; }
javascript
{ "resource": "" }
q7226
train
function(params) { corbel.validate.value('id', this.id); var options = params ? corbel.utils.clone(params) : {}; var args = corbel.utils.extend(options, { url: this._buildUriWithDomain(this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null }); return this.request(args); }
javascript
{ "resource": "" }
q7227
train
function(driver) { this.driver = driver; return function(id) { driver.config.set(corbel.Domain.CUSTOM_DOMAIN, id); return driver; }; }
javascript
{ "resource": "" }
q7228
FunctionCall
train
function FunctionCall( fn , isAsync , thisArg , ... args ) { this.function = fn ; this.isAsync = isAsync ; this.this = thisArg ; this.args = args ; this.hasThrown = false ; this.error = undefined ; this.return = undefined ; try { this.return = this.function.call( this.this || null , ... this.args ) ; } catch ( error ) { this.hasThrown = true ; this.error = error ; } if ( this.isAsync ) { if ( this.hasThrown ) { this.promise = Promise.resolve() ; } else { this.promise = Promise.resolve( this.return ) .then( value => this.return = value , error => { this.hasThrown = true ; this.error = error ; } ) ; } } }
javascript
{ "resource": "" }
q7229
train
function (commandName, fn) { var config = this.config; config.commands = config.commands || {}; config.commands[commandName] = fn; }
javascript
{ "resource": "" }
q7230
WPCOMUnpublished
train
function WPCOMUnpublished( token, reqHandler ) { if ( ! ( this instanceof WPCOMUnpublished ) ) { return new WPCOMUnpublished( token, reqHandler ); } WPCOM.call( this, token, reqHandler ); }
javascript
{ "resource": "" }
q7231
toUrl
train
function toUrl(mId) { const parsed = parse(mId); let url = parsed.bareId; if (url[0] !== '/' && !url.match(/^https?:\/\//)) url = _baseUrl + url; if (!parsed.ext) { // no known ext, add .js url += '.js'; } return url; }
javascript
{ "resource": "" }
q7232
runtimeReq
train
function runtimeReq(mId) { const parsed = parse(mId); return _fetch(parsed.cleanId) .then(response => { // ensure default user space define.switchToUserSpace(); for (let i = 0, len = _translators.length; i < len; i++) { const result = _translators[i](parsed, response); if (result && typeof result.then === 'function') return result; } throw new Error(`no runtime translator to handle ${parsed.cleanId}`); }) .then(() => { if (userSpace.has(parsed.cleanId)) return userSpace.req(parsed.cleanId); throw new Error(`module "${parsed.cleanId}" is missing from url "${toUrl(mId)}"`); }) .catch(err => { console.error(`could not load module "${parsed.cleanId}" from remote`); // eslint-disable-line no-console throw err; }); }
javascript
{ "resource": "" }
q7233
userReqFromBundle
train
function userReqFromBundle(mId) { const possibleIds = nodejsIds(mId); const bundleName = Object.keys(_bundles).find(bn => { const {nameSpace, user} = _bundles[bn]; return possibleIds.some(d => { if (nameSpace) { const parsed = parse(d); if (parsed.bareId.slice(0, nameSpace.length + 1) === nameSpace + '/') { d = parsed.prefix + parsed.bareId.slice(nameSpace.length + 1); } } if (user.hasOwnProperty(d)) return true; const p = parse(d); // For module with unknown plugin prefix, try bareId. // This relies on dumber bundler's default behaviour, it write in bundle config // both 'foo.html' and 'text!foo.html'. if (p.prefix) return user.hasOwnProperty(p.bareId); }); }); if (bundleName) { return loadBundle(bundleName) .then(() => { if (userSpace.has(mId)) return userSpace.req(mId); // mId is not directly defined in the bundle, it could be // behind a customised plugin or ext plugin. const tried = tryPlugin(mId, userSpace); if (tried) return tried; throw new Error(`module "${mId}" is missing from bundle "${bundleName}"`); }); } }
javascript
{ "resource": "" }
q7234
packageReqFromBundle
train
function packageReqFromBundle(mId) { const possibleIds = nodejsIds(mId); const bundleName = Object.keys(_bundles).find(bn => possibleIds.some(d => { const pack = _bundles[bn].package; if (pack.hasOwnProperty(d)) return true; const p = parse(d); // For module with unknown plugin prefix, try bareId. // This relies on dumber bundler's default behaviour, it write in bundle config // both 'foo.html' and 'text!foo.html'. if (p.prefix) return pack.hasOwnProperty(p.bareId); }) ); if (bundleName) { return loadBundle(bundleName) .then(() => { if (packageSpace.has(mId)) return packageSpace.req(mId); const tried = tryPlugin(mId, packageSpace); if (tried) return tried; throw new Error(`module "${mId}" is missing from bundle "${bundleName}"`); }); } const err = new Error(`no bundle for module "${mId}"`); err.__unkown = mId; throw err; }
javascript
{ "resource": "" }
q7235
loadBundle
train
function loadBundle(bundleName) { if (!_bundleLoad[bundleName]) { const mappedBundleName = _paths[bundleName] || bundleName; const url = toUrl(mappedBundleName); const {nameSpace} = _bundles[bundleName] || {}; let job; // I really hate this. // Use script tag, not fetch, only to support sourcemaps. // And I don't know how to mock it up, so __skip_script_load_test if (!define.__skip_script_load_test && isBrowser && // no name space or browser has support of document.currentScript (!nameSpace || 'currentScript' in _global.document)) { job = new Promise((resolve, reject) => { const script = document.createElement('script'); if (nameSpace) { script.setAttribute('data-namespace', nameSpace); } script.type = 'text/javascript'; script.charset = 'utf-8'; script.async = true; script.addEventListener('load', resolve); script.addEventListener('error', reject); script.src = url; // If the script is cached, IE10 executes the script body and the // onload handler synchronously here. That's a spec violation, // so be sure to do this asynchronously. if (document.documentMode === 10) { setTimeout(() => { document.head.appendChild(script); }); } else { document.head.appendChild(script); } }); } if (!job) { // in nodejs or web worker // or need name space in browser doesn't support document.currentScipt job = _fetch(mappedBundleName) .then(response => response.text()) .then(text => { // ensure default user space // the bundle itself may switch to package space in middle of the file switchToUserSpace(); if (!nameSpace) { (new Function(text)).call(_global); } else { const wrapped = function(id, deps, cb) { nameSpacedDefine(nameSpace, id, deps, cb); }; wrapped.amd = define.amd; wrapped.switchToUserSpace = switchToUserSpace; wrapped.switchToPackageSpace = switchToPackageSpace; const f = new Function('define', text); f.call(_global, wrapped); } }); } _bundleLoad[bundleName] = job; } return _bundleLoad[bundleName]; }
javascript
{ "resource": "" }
q7236
nameSpacedDefine
train
function nameSpacedDefine(nameSpace, id, deps, callback) { // only add name space for modules in user space // also skip any ext: plugin (a dumber-module-loader feature) if (currentSpace === userSpace && id.slice(0, 4) !== 'ext:') { const parsed = parse(id); userSpace.define(parsed.prefix + nameSpace + '/' + parsed.bareId, deps, callback); } else { currentSpace.define(id, deps, callback); } }
javascript
{ "resource": "" }
q7237
requireFunc
train
function requireFunc() { if (typeof arguments[0] === 'string') { const dep = arguments[0]; const got = defined(dep); if (got) return got.val; throw new Error(`commonjs dependency "${dep}" is not prepared.`); } return requirejs.apply(null, arguments); }
javascript
{ "resource": "" }
q7238
loadWasm
train
function loadWasm(name, req, load) { req(['raw!' + name], response => { response.arrayBuffer().then(buffer => WebAssembly.instantiate(buffer, /*importObject*/) ) .then( obj => { load(obj.instance.exports); }, load.error ); }); }
javascript
{ "resource": "" }
q7239
config
train
function config(opts) { if (!opts) return; if (opts.baseUrl) _baseUrl = parse(opts.baseUrl).bareId + '/'; if (opts.paths) { Object.keys(opts.paths).forEach(path => { let alias = opts.paths[path]; _paths[cleanPath(path)] = cleanPath(alias); }); } if (opts.bundles) { Object.keys(opts.bundles).forEach(bundleName => { const spaces = opts.bundles[bundleName]; if (Array.isArray(spaces)) { _bundles[bundleName] = { user: arrayToHash(spaces), package: arrayToHash([]) }; } else { _bundles[bundleName] = { nameSpace: spaces.nameSpace || null, user: arrayToHash(spaces.user || []), package: arrayToHash(spaces.package || []) }; } }); } }
javascript
{ "resource": "" }
q7240
train
function () { var name, index = i; if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.currentFileInfo); } }
javascript
{ "resource": "" }
q7241
validateComponent
train
function validateComponent(def, name) { let e = 'Invalid component definition: ' + name; // Check that it's an object if (typeof def !== 'object' && def !== null && def !== undefined) { throw new Error(e + ' must be an object, null or undefined'); } // Check that is object has a setup function if (!(def.setup instanceof Function)) { throw new Error(e + ' is missing setup function'); } // If requires is defined, then we check that it's an array of strings if (def.requires) { if (!(def.requires instanceof Array)) { throw new Error(e + ' if present, requires must be array'); } // Check that all entries in def.requires are strings if (!def.requires.every(entry => typeof entry === 'string')) { throw new Error(e + ' all items in requires must be strings'); } } }
javascript
{ "resource": "" }
q7242
renderGraph
train
function renderGraph(componentDirectory, sortedComponents) { let dot = [ '// This graph shows all dependencies for this loader.', '// You might find http://www.webgraphviz.com/ useful!', '', 'digraph G {', ]; for (let component of sortedComponents) { dot.push(util.format(' "%s"', component)); let def = componentDirectory[component] || {}; for (let dep of def.requires || []) { dot.push(util.format(' "%s" -> "%s" [dir=back]', dep, component)); } } dot.push('}'); return dot.join('\n'); }
javascript
{ "resource": "" }
q7243
load
train
function load(target) { if (!loaded[target]) { var def = componentDirectory[target]; // Initialize component, this won't cause an infinite loop because // we've already check that the componentDirectory is a DAG let requires = def.requires || []; return loaded[target] = Promise.all(requires.map(load)).then(deps => { let ctx = {}; for (let i = 0; i < deps.length; i++) { ctx[def.requires[i]] = deps[i]; } return new Promise((resolve, reject) => { try { resolve(def.setup.call(null, ctx)); } catch (err) { reject(err); } }).catch(function(err) { debug(`error while loading component '${target}': ${err}`); throw err; }); }); } return loaded[target]; }
javascript
{ "resource": "" }
q7244
train
function (element) { var self = this; var $el = self.$el; // 隐藏当然不包含了 // 隐藏当然不包含了 if (!self.get('visible') || !$el) { return false; } if ($el && ($el[0] === element || $el.contains(element))) { return true; } var children = self.get('children'); for (var i = 0, count = children.length; i < count; i++) { var child = children[i]; if (child.containsElement && child.containsElement(element)) { return true; } } return false; }
javascript
{ "resource": "" }
q7245
afterHighlightedItemChange
train
function afterHighlightedItemChange(e) { if (e.target.isMenu) { var el = this.el, menuItem = e.newVal; el.setAttribute('aria-activedescendant', menuItem && menuItem.el.id || ''); } }
javascript
{ "resource": "" }
q7246
train
function (v, e) { var self = this; self.callSuper(v, e); // sync // sync if (!e) { return; } if (e.fromMouse) { return; } if (v && !e.fromKeyboard) { showMenu.call(self); } else if (!v) { hideMenu.call(self); } }
javascript
{ "resource": "" }
q7247
train
function (e) { var self = this, menu = self.get('menu'), menuChildren, menuChild, hasKeyboardControl_ = menu.get('visible'), keyCode = e.keyCode; if (!hasKeyboardControl_) { // right if (keyCode === KeyCode.RIGHT) { showMenu.call(self); menuChildren = menu.get('children'); if (menuChild = menuChildren[0]) { menuChild.set('highlighted', true, { data: { fromKeyboard: 1 } }); } } else if (keyCode === KeyCode.ENTER) { // enter as click return self.handleClickInternal(e); } else { return undefined; } } else if (!menu.handleKeyDownInternal(e)) { // The menu has control and the key hasn't yet been handled, on left arrow // we turn off key control. // left if (keyCode === KeyCode.LEFT) { // refresh highlightedItem of parent menu self.set('highlighted', false); self.set('highlighted', true, { data: { fromKeyboard: 1 } }); } else { return undefined; } } return true; }
javascript
{ "resource": "" }
q7248
forEach
train
function forEach(callback, thisArg = UNDEFINED, defaultReturn = UNDEFINED) { const savedReturn = BREAK.clearDefault(defaultReturn); const iMax = this.length; let result = thisArg; for (let i = 0; i < iMax; i++) { const value = this[i]; const returned = callback.call(thisArg, value, i, this); if (returned === BREAK) { result = BREAK.returned; break; } } BREAK.restoreDefault(savedReturn); return result; }
javascript
{ "resource": "" }
q7249
SiteWordAdsTOS
train
function SiteWordAdsTOS( sid, wpcom ) { if ( ! ( this instanceof SiteWordAdsTOS ) ) { return new SiteWordAdsTOS( sid, wpcom ); } this._sid = sid; this.wpcom = wpcom; }
javascript
{ "resource": "" }
q7250
train
function (a, override) { var b = a.slice(); if (override) { b.reverse(); } var i = 0, n, item; while (i < b.length) { item = b[i]; while ((n = util.lastIndexOf(item, b)) !== i) { b.splice(n, 1); } i += 1; } if (override) { b.reverse(); } return b; }
javascript
{ "resource": "" }
q7251
train
function (r, varArgs) { var args = util.makeArray(arguments), len = args.length - 2, i = 1, proto, arg, ov = args[len], wl = args[len + 1]; args[1] = varArgs; if (!util.isArray(wl)) { ov = wl; wl = undef; len++; } if (typeof ov !== 'boolean') { ov = undef; len++; } for (; i < len; i++) { arg = args[i]; if (proto = arg.prototype) { arg = util.mix({}, proto, true, removeConstructor); } util.mix(r.prototype, arg, ov, wl); } return r; }
javascript
{ "resource": "" }
q7252
train
function (id, fn) { id = (id + EMPTY).match(RE_ID_STR)[1]; var retryCount = 1; var timer = util.later(function () { if (++retryCount > POLL_RETIRES) { timer.cancel(); return; } var node = doc.getElementById(id); if (node) { fn(node); timer.cancel(); } }, POLL_INTERVAL, true); }
javascript
{ "resource": "" }
q7253
getUrlForRouter
train
function getUrlForRouter(urlStr) { urlStr = urlStr || location.href; var uri = url.parse(urlStr); if (!globalConfig.useHash && supportHistoryPushState) { return uri.pathname.substr(globalConfig.urlRoot.length) + (uri.search || ''); } else { return utils.getHash(urlStr); } }
javascript
{ "resource": "" }
q7254
train
function (fragment, urlRoot) { return location.protocol + '//' + location.host + this.removeEndSlash(urlRoot) + this.addStartSlash(fragment); }
javascript
{ "resource": "" }
q7255
saveBoxed
train
function saveBoxed(onDoneCallback = UNDEFINED) { const boxed = this.boxed; if (boxed) { const modified = boxed[boxedImmutable.BOXED_GET_THIS].valueOfModified(); if (modified !== UNDEFINED) { this.boxed = UNDEFINED; if (this.saveState) { return this.saveState(modified, boxed, onDoneCallback); } else { throw new TypeError("Save State Not Supported on this instance, saveState callback not provided"); } } } else if (onDoneCallback) { onDoneCallback(); } }
javascript
{ "resource": "" }
q7256
cancelBoxed
train
function cancelBoxed() { const boxed = this.boxed; this.boxed = UNDEFINED; return boxed && boxed[boxedImmutable.BOXED_GET_THIS].unboxedDelta(); }
javascript
{ "resource": "" }
q7257
train
function (target, prop, receiver) { if (isBoxedState(target)) { if (prop === BOXED_GET_THIS) return target; if (prop === target.saveBoxedProp) return target.saveBoxed; if (prop === target.cancelBoxedProp) return target.cancelBoxed; if (prop === target.boxOptionsProp) return target.boxOptions; return target.getBoxed()[prop]; } throw new TypeError("BoxedStateHandler: IllegalArgument expected BoxedState target"); }
javascript
{ "resource": "" }
q7258
Layer
train
function Layer(name, fn) { this.length = fn.length; this.name = name; this.fn = fn; }
javascript
{ "resource": "" }
q7259
Supply
train
function Supply(provider, options) { if (!this) return new Supply(provider, options); options = options || {}; this.provider = provider || this; this.layers = []; this.length = 0; if ('function' === typeof this.initialize) { this.initialize(options); } }
javascript
{ "resource": "" }
q7260
next
train
function next(err, done) { var layer = supply.layers[i++]; if (err || done || !layer) { return fn(err, !!done); } if (layer.length > length) { return layer.fn.apply(supply.provider, args.concat(next)); } else { dollars.catch(function catching() { return layer.fn.apply(supply.provider, args); }, next); } }
javascript
{ "resource": "" }
q7261
Angle
train
function Angle(value, parameters) { abstractions.Element.call(this, utilities.types.ANGLE, parameters); // analyze the value if (value === undefined) value = 0; // default value if (!isFinite(value)) { throw new utilities.Exception({ $module: '/bali/elements/Angle', $procedure: '$Angle', $exception: '$invalidParameter', $parameter: value.toString(), $text: '"An invalid angle value was passed to the constructor."' }); } if (parameters) { const units = parameters.getParameter('$units'); if (units && units.toString() === '$degrees') { // convert degrees to radians value = utilities.precision.quotient(utilities.precision.product(value, Math.PI), 180); } } // lock onto pi if appropriate value = utilities.precision.lockOnAngle(value); // normalize the value to the range (-pi..pi] const twoPi = utilities.precision.product(Math.PI, 2); if (value < -twoPi || value > twoPi) { value = utilities.precision.remainder(value, twoPi); // make in the range (-2pi..2pi) } if (value > Math.PI) { value = utilities.precision.difference(value, twoPi); // make in the range (-pi..pi] } else if (value <= -Math.PI) { value = utilities.precision.sum(value, twoPi); // make in the range (-pi..pi] } if (value === -0) value = 0; // normalize to positive zero // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7262
bench
train
function bench(callback){ conn.connect(function(err, keyspace){ if(err){ throw(err); } console.time('Helenus ' + times + ' writes'); function cb(err, results){ if(err){ console.log('Error encountered at: ' + completed); throw(err); } completed += 1; if(completed === times){ console.timeEnd('Helenus ' + times + ' writes') ; conn.close(); callback(); } } /** * lets run a test for writes */ for(; i < times; i += 1){ vals = ['Column'+i, i.toString(16), (i % 100).toString(16)]; conn.cql(cqlInsert, vals, { gzip:true }, cb); } }); }
javascript
{ "resource": "" }
q7263
Pattern
train
function Pattern(value, parameters) { abstractions.Element.call(this, utilities.types.PATTERN, parameters); value = value || '^none$'; // the default value matches nothing if (typeof value === 'string') value = new RegExp(value); // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7264
run
train
function run(key, selfie) { if (!options[key]) return; if ('string' === typeof options[key]) options[key] = options[key].split(split); if ('function' === typeof options[key]) return options[key].call(selfie); for (var i = 0, type, what; i < options[key].length; i++) { what = options[key][i]; type = typeof what; if ('function' === type) { what.call(selfie); } else if ('string' === type && 'function' === typeof selfie[what]) { selfie[what](); } } }
javascript
{ "resource": "" }
q7265
Association
train
function Association(key, value) { abstractions.Composite.call(this, utilities.types.ASSOCIATION); key = this.convert(key); value = this.convert(value); // access to this component's attributes is tightly controlled this.getKey = function() { return key; }; this.getValue = function() { return value; }; this.setValue = function(newValue) { newValue = this.convert(newValue); const oldValue = value; value = newValue; return oldValue; }; return this; }
javascript
{ "resource": "" }
q7266
train
function(credentials, mocha) { var that = this; this._connection = new taskcluster.PulseConnection(credentials); this._listeners = null; this._promisedMessages = null; // **Note**, the before(), beforeEach(9, afterEach() and after() functions // below are mocha hooks. Ie. they are called by mocha, that is also the // reason that `PulseTestReceiver` only works in the context of a mocha test. if (!mocha) { mocha = require('mocha'); } // Before all tests we ask the pulseConnection to connect, why not it offers // slightly better performance, and we want tests to run fast mocha.before(function() { return that._connection.connect(); }); // Before each test we create list of listeners and mapping from "name" to // promised messages mocha.beforeEach(function() { that._listeners = []; that._promisedMessages = {}; }); // After each test we clean-up all the listeners created mocha.afterEach(function() { // Because listener is created with a PulseConnection they only have an // AMQP channel each, and not a full TCP connection, hence, .close() // should be pretty fast too. Also unnecessary as they get clean-up when // the PulseConnection closes eventually... But it's nice to keep things // clean, errors are more likely to surface at the right test this way. return Promise.all(that._listeners.map(function(listener) { listener.close(); })).then(function() { that._listeners = null; that._promisedMessages = null; }); }); // After all tests we close the PulseConnection, as we haven't named any of // the queues, they are all auto-delete queues and will be deleted if they // weren't cleaned up in `afterEach()` mocha.after(function() { return that._connection.close().then(function() { that._connection = null; }); }); }
javascript
{ "resource": "" }
q7267
vNumber
train
function vNumber(func, type, str, range) { let success = true; let checkType = true; let errmsg; // 先验证类型 if (!func(str)) { errmsg = localData.em_type({ desc, str, type, }); checkType = false; success = false; } // 再验证类型范围 // if (range && range.min === undefined) { // range.min = 0; // } if (range && (range.min === undefined || range.min < -NUMBER_MAX)) { range.min = -NUMBER_MAX; } if (range && (range.max === undefined || range.max > NUMBER_MAX)) { range.max = NUMBER_MAX; } if (success && checkType && range && (range.min !== undefined || range.max !== undefined)) { if (range && range.min !== undefined && range.min > Number(str)) { success = false; } if (success && range && range.max !== undefined && range.max < Number(str)) { success = false; } if (!success) { errmsg = localData.em_minmax({ desc, type, opDesc: 'value', minOp : '>=', min : range.min, maxOp : '<=', max : range.max, }); } } return { success, errmsg }; }
javascript
{ "resource": "" }
q7268
Percent
train
function Percent(value, parameters) { abstractions.Element.call(this, utilities.types.PERCENT, parameters); value = value || 0; // the default value // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7269
train
function(name, value, timestamp, ttl){ /** * The name of the column, can be any type, for composites use Array */ this.name = name; /** * The value of the column */ this.value = value; /** * The timestamp of the value * @default {Date} new Date(); */ this.timestamp = timestamp || new Date(); /** * The ttl for the column */ this.ttl = ttl; }
javascript
{ "resource": "" }
q7270
train
function (queueDef) { if (isString(queueDef)) { return true } if (isObject(queueDef) && isString(queueDef.name)) { return true } return false }
javascript
{ "resource": "" }
q7271
train
function (queues, name) { var result = queues.filter(function (queue) { return queue.name === name }) return result.length > 0 }
javascript
{ "resource": "" }
q7272
formatLines
train
function formatLines(string, indentation) { indentation = indentation ? indentation : ''; var formatted = ''; const length = string.length; if (length > LINE_WIDTH) { for (var index = 0; index < length; index += LINE_WIDTH) { formatted += EOL + indentation; formatted += string.substring(index, index + LINE_WIDTH); } formatted += EOL; } else { formatted += string; } return formatted; }
javascript
{ "resource": "" }
q7273
train
function (progressListener) { var self = this, listeners = self[PROMISE_PROGRESS_LISTENERS]; if (listeners === false) { return self; } if (!listeners) { listeners = self[PROMISE_PROGRESS_LISTENERS] = []; } listeners.push(progressListener); return self; }
javascript
{ "resource": "" }
q7274
train
function (callback) { return when(this, function (value) { return callback(value, true); }, function (reason) { return callback(reason, false); }); }
javascript
{ "resource": "" }
q7275
when
train
function when(value, fulfilled, rejected) { var defer = new Defer(), done = 0; // wrap user's callback to catch exception // wrap user's callback to catch exception function _fulfilled(value) { try { return fulfilled ? fulfilled.call(this, value) : // propagate value; } catch (e) { // can not use logger.error // must expose to user // print stack info for firefox/chrome logError(e.stack || e); return new Reject(e); } } function _rejected(reason) { try { return rejected ? // error recovery rejected.call(this, reason) : // propagate new Reject(reason); } catch (e) { // print stack info for firefox/chrome logError(e.stack || e); return new Reject(e); } } function finalFulfill(value) { if (done) { logger.error('already done at fulfilled'); return; } if (value instanceof Promise) { logger.error('assert.not(value instanceof Promise) in when'); return; } done = 1; defer.resolve(_fulfilled.call(this, value)); } if (value instanceof Promise) { promiseWhen(value, finalFulfill, function (reason) { if (done) { logger.error('already done at rejected'); return; } done = 1; // _reject may return non-Reject object for error recovery // _reject may return non-Reject object for error recovery defer.resolve(_rejected.call(this, reason)); }); } else { finalFulfill(value); } // chained and leveled // wait for value's resolve // chained and leveled // wait for value's resolve return defer.promise; }
javascript
{ "resource": "" }
q7276
_fulfilled
train
function _fulfilled(value) { try { return fulfilled ? fulfilled.call(this, value) : // propagate value; } catch (e) { // can not use logger.error // must expose to user // print stack info for firefox/chrome logError(e.stack || e); return new Reject(e); } }
javascript
{ "resource": "" }
q7277
train
function (promises) { var count = promises.length; if (!count) { return null; } var defer = new Defer(); for (var i = 0; i < promises.length; i++) { /*jshint loopfunc:true*/ (function (promise, i) { when(promise, function (value) { promises[i] = value; if (--count === 0) { // if all is resolved // then resolve final returned promise with all value defer.resolve(promises); } }, function (r) { // if any one is rejected // then reject final return promise with first reason defer.reject(r); }); }(promises[i], i)); } return defer.promise; }
javascript
{ "resource": "" }
q7278
train
function (generatorFunc) { return function () { var generator = generatorFunc.apply(this, arguments); function doAction(action, arg) { var result; // in case error on first // in case error on first try { result = generator[action](arg); } catch (e) { return new Reject(e); } if (result.done) { return result.value; } return when(result.value, next, throwEx); } function next(v) { return doAction('next', v); } function throwEx(e) { return doAction('throw', e); } return next(); }; }
javascript
{ "resource": "" }
q7279
Version
train
function Version(value, parameters) { abstractions.Element.call(this, utilities.types.VERSION, parameters); value = value || [1]; // the default value if (value.indexOf(0) >= 0) { throw new utilities.Exception({ $module: '/bali/elements/Version', $procedure: '$Version', $exception: '$invalidParameter', $parameter: value.toString(), $text: '"An invalid version value was passed to the constructor."' }); } // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7280
Tag
train
function Tag(value, parameters) { abstractions.Element.call(this, utilities.types.TAG, parameters); value = value || 20; // the default number of bytes var bytes, numberOfBytes, hash; switch (typeof value) { case 'number': numberOfBytes = value; bytes = utilities.random.bytes(value); value = utilities.codex.base32Encode(bytes); break; case 'string': bytes = utilities.codex.base32Decode(value); numberOfBytes = bytes.length; break; } hash = utilities.codex.bytesToInteger(bytes); // the first four bytes work perfectly // since this element is immutable the attributes must be read-only this.getSize = function() { return numberOfBytes; }; this.getValue = function() { return value; }; this.getHash = function() { return hash; }; return this; }
javascript
{ "resource": "" }
q7281
train
function (msg, cat, logger) { if ('@DEBUG@') { var matched = 1; if (logger) { var list, i, l, level, minLevel, maxLevel, reg; cat = cat || 'debug'; level = loggerLevel[cat] || loggerLevel.debug; if ((list = config.includes)) { matched = 0; for (i = 0; i < list.length; i++) { l = list[i]; reg = l.logger; maxLevel = loggerLevel[l.maxLevel] || loggerLevel.error; minLevel = loggerLevel[l.minLevel] || loggerLevel.debug; if (minLevel <= level && maxLevel >= level && logger.match(reg)) { matched = 1; break; } } } else if ((list = config.excludes)) { matched = 1; for (i = 0; i < list.length; i++) { l = list[i]; reg = l.logger; maxLevel = loggerLevel[l.maxLevel] || loggerLevel.error; minLevel = loggerLevel[l.minLevel] || loggerLevel.debug; if (minLevel <= level && maxLevel >= level && logger.match(reg)) { matched = 0; break; } } } if (matched) { msg = logger + ': ' + msg; } } /*global console*/ if (matched) { if (typeof console !== 'undefined' && console.log) { console[cat && console[cat] ? cat : 'log'](msg); } return msg; } } return undefined; }
javascript
{ "resource": "" }
q7282
train
function (name, cfg) { var module = mods[name]; if (!module) { name = normalizeName(name); module = mods[name]; } if (module) { mix(module, cfg); // module definition changes requires if (cfg && cfg.requires) { module.setRequiresModules(cfg.requires); } return module; } // 防止 cfg 里有 tag,构建 fullpath 需要 mods[name] = module = new Loader.Module(mix({ name: name }, cfg)); return module; }
javascript
{ "resource": "" }
q7283
train
function () { var self = this; if (!self.url) { self.url = Utils.normalizeSlash(S.Config.resolveModFn(self)); } return self.url; }
javascript
{ "resource": "" }
q7284
cssPoll
train
function cssPoll() { for (var url in monitors) { var callbackObj = monitors[url], node = callbackObj.node; if (isCssLoaded(node, url)) { if (callbackObj.callback) { callbackObj.callback.call(node); } delete monitors[url]; } } if (Utils.isEmptyObject(monitors)) { logger.debug('clear css poll timer'); timer = 0; } else { timer = setTimeout(cssPoll, CSS_POLL_INTERVAL); } }
javascript
{ "resource": "" }
q7285
train
function (moduleName) { var requiresModule = createModule(moduleName); var mods = requiresModule.getNormalizedModules(); Utils.each(mods, function (m) { m.undef(); }); }
javascript
{ "resource": "" }
q7286
SiteWordAdsEarnings
train
function SiteWordAdsEarnings( sid, wpcom ) { if ( ! ( this instanceof SiteWordAdsEarnings ) ) { return new SiteWordAdsEarnings( sid, wpcom ); } this._sid = sid; this.wpcom = wpcom; }
javascript
{ "resource": "" }
q7287
_raco
train
function _raco (iter, args, callback, opts) { var self = this var trycatch = true var isYieldable = true var yielded = false var nothrow = !!opts.nothrow /** * internal callback stepper * * @param {object} err - callback error object * @param {...*} val - callback value(s) */ function step (err, val) { if (iter) { // generator step yielded = false isYieldable = false var state if (trycatch) { try { if (nothrow) state = iter.next(slice.call(arguments)) else state = err ? iter.throw(err) : iter.next(val) } catch (err) { iter = null // catch err, break iteration return step(err) } } else { if (nothrow) state = iter.next(slice.call(arguments)) else state = err ? iter.throw(err) : iter.next(val) } if (state && state.done) iter = null yielded = true isYieldable = yieldable.call(self, state.value, step, opts) if (!isYieldable && opts.yieldable) { isYieldable = opts.yieldable.call(self, state.value, step) } // next if generator returned non-yieldable if (!isYieldable && !iter) next(null, state.value) } else if (callback) { callback.apply(self, arguments) callback = null } } /** * next, callback stepper with nextTick * * @param {object} err - callback error object * @param {...*} val - callback value(s) */ function next () { var args = slice.call(arguments) if (!isYieldable) { // only handle callback if not yieldable if (iter && yielded) { // no need defer when yielded step.apply(self, args) } else { // need next tick if not defered process.nextTick(function () { step.apply(self, args) }) } } else { step(new Error('Callback on yieldable is prohibited')) } } // prepend or append next arg if (args) opts.prepend ? args.unshift(next) : args.push(next) else args = [next] if (!isGenerator(iter)) iter = iter.apply(self, args) if (callback) { // callback mode step() } else if (opts.Promise) { // return promise if callback not exists return new opts.Promise(function (resolve, reject) { callback = function (err, val) { if (err) reject(err) else resolve(val) } step() }) } else { // callback and promise not exists, // no try catch wrap trycatch = false callback = noop step() } }
javascript
{ "resource": "" }
q7288
step
train
function step (err, val) { if (iter) { // generator step yielded = false isYieldable = false var state if (trycatch) { try { if (nothrow) state = iter.next(slice.call(arguments)) else state = err ? iter.throw(err) : iter.next(val) } catch (err) { iter = null // catch err, break iteration return step(err) } } else { if (nothrow) state = iter.next(slice.call(arguments)) else state = err ? iter.throw(err) : iter.next(val) } if (state && state.done) iter = null yielded = true isYieldable = yieldable.call(self, state.value, step, opts) if (!isYieldable && opts.yieldable) { isYieldable = opts.yieldable.call(self, state.value, step) } // next if generator returned non-yieldable if (!isYieldable && !iter) next(null, state.value) } else if (callback) { callback.apply(self, arguments) callback = null } }
javascript
{ "resource": "" }
q7289
next
train
function next () { var args = slice.call(arguments) if (!isYieldable) { // only handle callback if not yieldable if (iter && yielded) { // no need defer when yielded step.apply(self, args) } else { // need next tick if not defered process.nextTick(function () { step.apply(self, args) }) } } else { step(new Error('Callback on yieldable is prohibited')) } }
javascript
{ "resource": "" }
q7290
raco
train
function raco (genFn, opts) { if (!isGeneratorFunction(genFn)) { if (isFunction(genFn)) throw new Error('Generator function required') else if (!isGenerator(genFn)) return factory(genFn) } opts = Object.assign({}, _opts, opts) opts.Promise = null return _raco.call(this, genFn, null, null, opts) }
javascript
{ "resource": "" }
q7291
columnParent
train
function columnParent(cf, column) { var args = { column_family: cf.name }; if (cf.isSuper && column) args.super_column = cf.columnMarshaller.serialize(column); return new ttype.ColumnParent(args); }
javascript
{ "resource": "" }
q7292
columnPath
train
function columnPath(cf, column, subcolumn) { var args = { column_family: cf.name }; if (column) args.column = cf.columnMarshaller.serialize(column); if (cf.isSuper && subcolumn) args.subcolumn = cf.subcolumnMarshaller.serialize(subcolumn); return new ttype.ColumnPath(args); }
javascript
{ "resource": "" }
q7293
normalizeParameters
train
function normalizeParameters(list) { list = _.toArray(list); return _.reduce(list, function(args, value, index) { if (_.isObject(value) && !Array.isArray(value)) { var options = args.options, timestamp = value.timestamp, consistency = value.consistency || value.consistencyLevel; if (_.isDate(timestamp)) options.timestamp = timestamp; if (consistency) options.consistency = consistency; _.defaults(options, value); } else if (index < 2) args[index ? 'subcolumn' : 'column'] = value; return args; }, { key: list.shift(), options: { timestamp: new Date(), consistency: DEFAULT_WRITE_CONSISTENCY } }); }
javascript
{ "resource": "" }
q7294
train
function() { var stable = []; for (var i=0;i<physicsSimulators.length; i++) { stable.push(physicsSimulators[i].step()); } // Check if all simulators are stable //console.log(stable); for (i=0;i<stable.length;i++) { if (!stable[i]) { return false } } return true; }
javascript
{ "resource": "" }
q7295
train
function (nodeId) { var layer = getLayer(nodeId); var body = getInitializedBody(nodeId); body.pos.z = layer * interLayerDistance; return body.pos; }
javascript
{ "resource": "" }
q7296
train
function() { graph.off('changed', onGraphChanged); for (var i=0;i<physicsSimulators.length; i++) { physicsSimulators[i].off('stable', onStableChanged); } }
javascript
{ "resource": "" }
q7297
train
function (tplContent, name) { if (tplContent) { var ret; try { ret = parser.parse(tplContent, name); } catch (err) { var e; if (err instanceof Error) { e = err; } else { e = new Error(err); } var errorStr = 'XTemplate error '; e.stack = errorStr + e.stack; e.message = errorStr + e.message; throw e; } return ret; } else { return { statements: [] }; } }
javascript
{ "resource": "" }
q7298
Queue
train
function Queue(parameters) { parameters = parameters || new composites.Parameters(new Catalog()); if (!parameters.getParameter('$type')) parameters.setParameter('$type', '/bali/collections/Queue/v1'); abstractions.Collection.call(this, utilities.types.QUEUE, parameters); // the capacity and array are private attributes so methods that use it are // defined in the constructor var capacity = 1024; // default capacity if (parameters) { const value = parameters.getParameter('$capacity', 2); if (value) capacity = value.toNumber(); } const array = []; this.acceptVisitor = function(visitor) { visitor.visitQueue(this); }; this.toArray = function() { return array.slice(); // copy the array }; this.getSize = function() { return array.length; }; this.addItem = function(item) { if (array.length < capacity) { item = this.convert(item); array.push(item); return true; } throw new utilities.Exception({ $module: '/bali/collections/Queue', $procedure: '$addItem', $exception: '$resourceLimit', $capacity: capacity, $text: '"The queue has reached its maximum capacity."' }); }; this.removeItem = function() { if (array.length > 0) return array.splice(0, 1)[0]; // remove the first item in the array }; this.getHead = function() { return array[0]; }; this.deleteAll = function() { array.splice(0); }; return this; }
javascript
{ "resource": "" }
q7299
train
function (type, code) { $sgCodeTitles.removeClass('sg-code-title-active'); switch (type) { case 'e': $sgCodeTitleHtml.addClass('sg-code-title-active'); break; case 'm': $sgCodeTitleMustache.addClass('sg-code-title-active'); break; } $sgCodeFill.removeClass().addClass('language-markup'); $sgCodeFill.html(code); window.Prism.highlightElement($sgCodeFill[0]); if (codeViewer.copyOnInit) { codeViewer.selectCode(); codeViewer.copyOnInit = false; } }
javascript
{ "resource": "" }