_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q18600
train
function(msgs){ var res = '[', msg; for(var i=0, l=msgs.length; i<l; i++) { if(i > 0) { res += ','; } msg = msgs[i]; if(typeof msg === 'string') { res += msg; } else { res += JSON.stringify(msg); } } res += ']'; return res; }
javascript
{ "resource": "" }
q18601
train
function(count, opts, cb) { this.count = count; this.cb = cb; var self = this; if (opts.timeout) { this.timerId = setTimeout(function() { self.cb(true); }, opts.timeout); } }
javascript
{ "resource": "" }
q18602
cached
train
function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) }
javascript
{ "resource": "" }
q18603
toObject
train
function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res }
javascript
{ "resource": "" }
q18604
genStaticKeys
train
function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') }
javascript
{ "resource": "" }
q18605
looseEqual
train
function looseEqual (a, b) { var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { return JSON.stringify(a) === JSON.stringify(b) } catch (e) { // possible circular reference return a === b } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } }
javascript
{ "resource": "" }
q18606
once
train
function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } }
javascript
{ "resource": "" }
q18607
simpleNormalizeChildren
train
function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children }
javascript
{ "resource": "" }
q18608
_toString
train
function _toString(val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) }
javascript
{ "resource": "" }
q18609
getEnterTargetState
train
function getEnterTargetState (el, stylesheet, startClass, endClass, activeClass, vm) { const targetState = {} const startState = stylesheet[startClass] const endState = stylesheet[endClass] const activeState = stylesheet[activeClass] // 1. fallback to element's default styling if (startState) { for (const key in startState) { targetState[key] = el.style[key] if ( process.env.NODE_ENV !== 'production' && targetState[key] == null && (!activeState || activeState[key] == null) && (!endState || endState[key] == null) ) { warn( `transition property "${key}" is declared in enter starting class (.${startClass}), ` + `but not declared anywhere in enter ending class (.${endClass}), ` + `enter active cass (.${activeClass}) or the element's default styling. ` + `Note in Weex, CSS properties need explicit values to be transitionable.` ) } } } // 2. if state is mixed in active state, extract them while excluding // transition properties if (activeState) { for (const key in activeState) { if (key.indexOf('transition') !== 0) { targetState[key] = activeState[key] } } } // 3. explicit endState has highest priority if (endState) { extend(targetState, endState) } return targetState }
javascript
{ "resource": "" }
q18610
train
function () { var total = this.stats.length return this.stats.map(function (stat, i) { var point = valueToPoint(stat.value, i, total) return point.x + ',' + point.y }).join(' ') }
javascript
{ "resource": "" }
q18611
valueToPoint
train
function valueToPoint (value, index, total) { var x = 0 var y = -value * 0.8 var angle = Math.PI * 2 / total * index var cos = Math.cos(angle) var sin = Math.sin(angle) var tx = x * cos - y * sin + 100 var ty = x * sin + y * cos + 100 return { x: tx, y: ty } }
javascript
{ "resource": "" }
q18612
assertType
train
function assertType (value, type) { var valid; var expectedType = getType(type); if (expectedType === 'String') { valid = typeof value === (expectedType = 'string'); } else if (expectedType === 'Number') { valid = typeof value === (expectedType = 'number'); } else if (expectedType === 'Boolean') { valid = typeof value === (expectedType = 'boolean'); } else if (expectedType === 'Function') { valid = typeof value === (expectedType = 'function'); } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } }
javascript
{ "resource": "" }
q18613
init
train
function init (cfg) { renderer.Document = cfg.Document; renderer.Element = cfg.Element; renderer.Comment = cfg.Comment; renderer.sendTasks = cfg.sendTasks; }
javascript
{ "resource": "" }
q18614
genModuleGetter
train
function genModuleGetter (instanceId) { var instance = instances[instanceId]; return function (name) { var nativeModule = modules[name] || []; var output = {}; var loop = function ( methodName ) { output[methodName] = function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var finalArgs = args.map(function (value) { return normalize(value, instance) }); renderer.sendTasks(instanceId + '', [{ module: name, method: methodName, args: finalArgs }], -1); }; }; for (var methodName in nativeModule) loop( methodName ); return output } }
javascript
{ "resource": "" }
q18615
normalize
train
function normalize (v, instance) { const type = typof(v) switch (type) { case 'undefined': case 'null': return '' case 'regexp': return v.toString() case 'date': return v.toISOString() case 'number': case 'string': case 'boolean': case 'array': case 'object': if (v instanceof renderer.Element) { return v.ref } return v case 'function': instance.callbacks[++instance.callbackId] = v return instance.callbackId.toString() default: return JSON.stringify(v) } }
javascript
{ "resource": "" }
q18616
setStreamType
train
function setStreamType(constraints, stream) { if (constraints.mandatory && constraints.mandatory.chromeMediaSource) { stream.isScreen = true; } else if (constraints.mozMediaSource || constraints.mediaSource) { stream.isScreen = true; } else if (constraints.video) { stream.isVideo = true; } else if (constraints.audio) { stream.isAudio = true; } }
javascript
{ "resource": "" }
q18617
xhr
train
function xhr(url, callback, data) { if (!window.XMLHttpRequest || !window.JSON) return; var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (callback && request.readyState == 4 && request.status == 200) { // server MUST return JSON text callback(JSON.parse(request.responseText)); } }; request.open('POST', url); var formData = new FormData(); // you're passing "message" parameter formData.append('message', data); request.send(formData); }
javascript
{ "resource": "" }
q18618
TextReceiver
train
function TextReceiver(connection) { var content = {}; function receive(data, userid, extra) { // uuid is used to uniquely identify sending instance var uuid = data.uuid; if (!content[uuid]) { content[uuid] = []; } content[uuid].push(data.message); if (data.last) { var message = content[uuid].join(''); if (data.isobject) { message = JSON.parse(message); } // latency detection var receivingTime = new Date().getTime(); var latency = receivingTime - data.sendingTime; var e = { data: message, userid: userid, extra: extra, latency: latency }; if (connection.autoTranslateText) { e.original = e.data; connection.Translator.TranslateText(e.data, function(translatedText) { e.data = translatedText; connection.onmessage(e); }); } else { connection.onmessage(e); } delete content[uuid]; } } return { receive: receive }; }
javascript
{ "resource": "" }
q18619
mergeProps
train
function mergeProps(mergein, mergeto) { for (var t in mergeto) { if (typeof mergeto[t] !== 'function') { mergein[t] = mergeto[t]; } } return mergein; }
javascript
{ "resource": "" }
q18620
WhammyVideo
train
function WhammyVideo(duration, quality) { this.frames = []; if (!duration) { duration = 1; } this.duration = 1000 / duration; this.quality = quality || 0.8; }
javascript
{ "resource": "" }
q18621
checkFrames
train
function checkFrames(frames) { if (!frames[0]) { postMessage({ error: 'Something went wrong. Maybe WebP format is not supported in the current browser.' }); return; } var width = frames[0].width, height = frames[0].height, duration = frames[0].duration; for (var i = 1; i < frames.length; i++) { duration += frames[i].duration; } return { duration: duration, width: width, height: height }; }
javascript
{ "resource": "" }
q18622
setCordovaAPIs
train
function setCordovaAPIs() { // if (DetectRTC.osName !== 'iOS') return; if (typeof cordova === 'undefined' || typeof cordova.plugins === 'undefined' || typeof cordova.plugins.iosrtc === 'undefined') return; var iosrtc = cordova.plugins.iosrtc; window.webkitRTCPeerConnection = iosrtc.RTCPeerConnection; window.RTCSessionDescription = iosrtc.RTCSessionDescription; window.RTCIceCandidate = iosrtc.RTCIceCandidate; window.MediaStream = iosrtc.MediaStream; window.MediaStreamTrack = iosrtc.MediaStreamTrack; navigator.getUserMedia = navigator.webkitGetUserMedia = iosrtc.getUserMedia; iosrtc.debug.enable('iosrtc*'); if (typeof iosrtc.selectAudioOutput == 'function') { iosrtc.selectAudioOutput(window.iOSDefaultAudioOutputDevice || 'speaker'); // earpiece or speaker } iosrtc.registerGlobals(); }
javascript
{ "resource": "" }
q18623
emberPlugin
train
function emberPlugin(Raven, Ember) { Ember = Ember || window.Ember; // quit if Ember isn't on the page if (!Ember) return; var _oldOnError = Ember.onerror; Ember.onerror = function EmberOnError(error) { Raven.captureException(error); if (typeof _oldOnError === 'function') { _oldOnError.call(this, error); } }; Ember.RSVP.on('error', function(reason) { if (reason instanceof Error) { Raven.captureException(reason, { extra: {context: 'Unhandled Promise error detected'} }); } else { Raven.captureMessage('Unhandled Promise error detected', {extra: {reason: reason}}); } }); }
javascript
{ "resource": "" }
q18624
AddPluginBrowserifyTransformer
train
function AddPluginBrowserifyTransformer() { var noop = function(chunk, _, cb) { cb(null, chunk); }; var append = function(cb) { cb(null, "\nrequire('../src/singleton').addPlugin(module.exports);"); }; return function(file) { return through(noop, /plugins/.test(file) ? append : undefined); }; }
javascript
{ "resource": "" }
q18625
Raven
train
function Raven() { this._hasJSON = !!(typeof JSON === 'object' && JSON.stringify); // Raven can run in contexts where there's no document (react-native) this._hasDocument = !isUndefined(_document); this._hasNavigator = !isUndefined(_navigator); this._lastCapturedException = null; this._lastData = null; this._lastEventId = null; this._globalServer = null; this._globalKey = null; this._globalProject = null; this._globalContext = {}; this._globalOptions = { // SENTRY_RELEASE can be injected by https://github.com/getsentry/sentry-webpack-plugin release: _window.SENTRY_RELEASE && _window.SENTRY_RELEASE.id, logger: 'javascript', ignoreErrors: [], ignoreUrls: [], whitelistUrls: [], includePaths: [], headers: null, collectWindowErrors: true, captureUnhandledRejections: true, maxMessageLength: 0, // By default, truncates URL values to 250 chars maxUrlLength: 250, stackTraceLimit: 50, autoBreadcrumbs: true, instrument: true, sampleRate: 1, sanitizeKeys: [] }; this._fetchDefaults = { method: 'POST', // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default // https://caniuse.com/#feat=referrer-policy // It doesn't. And it throw exception instead of ignoring this parameter... // REF: https://github.com/getsentry/raven-js/issues/1233 referrerPolicy: supportsReferrerPolicy() ? 'origin' : '' }; this._ignoreOnError = 0; this._isRavenInstalled = false; this._originalErrorStackTraceLimit = Error.stackTraceLimit; // capture references to window.console *and* all its methods first // before the console plugin has a chance to monkey patch this._originalConsole = _window.console || {}; this._originalConsoleMethods = {}; this._plugins = []; this._startTime = now(); this._wrappedBuiltIns = []; this._breadcrumbs = []; this._lastCapturedEvent = null; this._keypressTimeout; this._location = _window.location; this._lastHref = this._location && this._location.href; this._resetBackoff(); // eslint-disable-next-line guard-for-in for (var method in this._originalConsole) { this._originalConsoleMethods[method] = this._originalConsole[method]; } }
javascript
{ "resource": "" }
q18626
train
function() { TraceKit.report.uninstall(); this._detachPromiseRejectionHandler(); this._unpatchFunctionToString(); this._restoreBuiltIns(); this._restoreConsole(); Error.stackTraceLimit = this._originalErrorStackTraceLimit; this._isRavenInstalled = false; return this; }
javascript
{ "resource": "" }
q18627
train
function(ex, options) { options = objectMerge({trimHeadFrames: 0}, options ? options : {}); if (isErrorEvent(ex) && ex.error) { // If it is an ErrorEvent with `error` property, extract it to get actual Error ex = ex.error; } else if (isDOMError(ex) || isDOMException(ex)) { // If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers) // then we just extract the name and message, as they don't provide anything else // https://developer.mozilla.org/en-US/docs/Web/API/DOMError // https://developer.mozilla.org/en-US/docs/Web/API/DOMException var name = ex.name || (isDOMError(ex) ? 'DOMError' : 'DOMException'); var message = ex.message ? name + ': ' + ex.message : name; return this.captureMessage( message, objectMerge(options, { // neither DOMError or DOMException provide stack trace and we most likely wont get it this way as well // but it's barely any overhead so we may at least try stacktrace: true, trimHeadFrames: options.trimHeadFrames + 1 }) ); } else if (isError(ex)) { // we have a real Error object ex = ex; } else if (isPlainObject(ex)) { // If it is plain Object, serialize it manually and extract options // This will allow us to group events based on top-level keys // which is much better than creating new group when any key/value change options = this._getCaptureExceptionOptionsFromPlainObject(options, ex); ex = new Error(options.message); } else { // If none of previous checks were valid, then it means that // it's not a DOMError/DOMException // it's not a plain Object // it's not a valid ErrorEvent (one with an error property) // it's not an Error // So bail out and capture it as a simple message: return this.captureMessage( ex, objectMerge(options, { stacktrace: true, // if we fall back to captureMessage, default to attempting a new trace trimHeadFrames: options.trimHeadFrames + 1 }) ); } // Store the raw exception object for potential debugging and introspection this._lastCapturedException = ex; // TraceKit.report will re-raise any exception passed to it, // which means you have to wrap it in try/catch. Instead, we // can wrap it here and only re-raise if TraceKit.report // raises an exception different from the one we asked to // report on. try { var stack = TraceKit.computeStackTrace(ex); this._handleStackInfo(stack, options); } catch (ex1) { if (ex !== ex1) { throw ex1; } } return this; }
javascript
{ "resource": "" }
q18628
train
function(current) { var last = this._lastData; if ( !last || current.message !== last.message || // defined for captureMessage current.transaction !== last.transaction // defined for captureException/onerror ) return false; // Stacktrace interface (i.e. from captureMessage) if (current.stacktrace || last.stacktrace) { return isSameStacktrace(current.stacktrace, last.stacktrace); } else if (current.exception || last.exception) { // Exception interface (i.e. from captureException/onerror) return isSameException(current.exception, last.exception); } else if (current.fingerprint || last.fingerprint) { return Boolean(current.fingerprint && last.fingerprint) && JSON.stringify(current.fingerprint) === JSON.stringify(last.fingerprint) } return true; }
javascript
{ "resource": "" }
q18629
train
function(content) { // content.e = error // content.p = promise rejection // content.f = function call the Sentry if ( (content.e || content.p || (content.f && content.f.indexOf('capture') > -1) || (content.f && content.f.indexOf('showReportDialog') > -1)) && lazy ) { // We only want to lazy inject/load the sdk bundle if // an error or promise rejection occured // OR someone called `capture...` on the SDK injectSdk(onLoadCallbacks); } queue.data.push(content); }
javascript
{ "resource": "" }
q18630
generate
train
function generate(plugins, dest) { const pluginNames = plugins.map((plugin) => { return path.basename(plugin, '.js'); }); const pluginCombinations = combine(pluginNames); pluginCombinations.forEach((pluginCombination) => { fs.writeFileSync( path.resolve(dest, `${pluginCombination.join(',')}.js`), template(pluginCombination), ); }); }
javascript
{ "resource": "" }
q18631
Client
train
function Client(dsn, options) { if (dsn instanceof Client) return dsn; var ravenInstance = new Raven(); return ravenInstance.config.apply(ravenInstance, arguments); }
javascript
{ "resource": "" }
q18632
build
train
async function build(inputOptions, outputOptions) { const input = Object.assign( { plugins: [ commonjs(), // We can remove this plugin if there are no more CommonJS modules resolve(), // We need this plugin only to build the test script babel({ exclude: 'node_modules/**' }) ] }, inputOptions ); const output = Object.assign( { format: 'umd' }, outputOptions ); const bundle = await rollup(input); await bundle.write(output); }
javascript
{ "resource": "" }
q18633
ServerDetails
train
function ServerDetails(x) { if (!(this instanceof ServerDetails)) return new ServerDetails(x); const v = x.split(':'); this.hostname = (v[0].length > 0) ? v[0] : ''; this.port = (v.length > 1) ? Number(v[1]) : 80; }
javascript
{ "resource": "" }
q18634
propTypesDocsHandler
train
function propTypesDocsHandler(documentation, path) { const propTypesPath = getMemberValuePath(path, 'propTypes'); const docComment = getDocblock(propTypesPath.parent); const statementPattern = /@.*\:/; const info = {}; if (docComment) { const infoRaw = _.split(docComment, '\n'); _.forEach(infoRaw, (statement) => { if (statement && statementPattern.test(statement)) { const key = statement.match(statementPattern)[0].slice(1, -1); info[key] = statement.split(statementPattern)[1].trim(); } }); } documentation.set('propsInfo', info); }
javascript
{ "resource": "" }
q18635
flushQueue
train
function flushQueue() { var queued = WebInspector.log.queued; if (!queued) return; for (var i = 0; i < queued.length; ++i) logMessage(queued[i]); delete WebInspector.log.queued; }
javascript
{ "resource": "" }
q18636
flushQueueIfAvailable
train
function flushQueueIfAvailable() { if (!isLogAvailable()) return; clearInterval(WebInspector.log.interval); delete WebInspector.log.interval; flushQueue(); }
javascript
{ "resource": "" }
q18637
fixrefs
train
function fixrefs(scope, i) { // do children first; order shouldn't matter for (i = scope.children.length; --i >= 0;) fixrefs(scope.children[i]); for (i in scope.refs) if (HOP(scope.refs, i)) { // find origin scope and propagate the reference to origin for (var origin = scope.has(i), s = scope; s; s = s.parent) { s.refs[i] = origin; if (s === origin) break; } } }
javascript
{ "resource": "" }
q18638
getSize
train
async function getSize (files, opts) { if (typeof files === 'string') files = [files] if (!opts) opts = { } if (opts.webpack === false) { let sizes = await Promise.all(files.map(async file => { let bytes = await readFile(file, 'utf8') let result = { parsed: bytes.length } if (opts.running !== false) result.running = await getRunningTime(file) if (opts.gzip === false) { result.loading = getLoadingTime(result.parsed) } else { result.gzip = await gzipSize(bytes) result.loading = getLoadingTime(result.gzip) } return result })) return sizes.reduce(sumSize) } else { let config = getConfig(files, opts) let output = path.join( config.output.path || process.cwd(), config.output.filename) let size, running try { let stats = await runWebpack(config) if (opts.running !== false) running = await getRunningTime(output) if (stats.hasErrors()) { throw new Error(stats.toString('errors-only')) } if (opts.config && stats.stats) { size = stats.stats .map(stat => extractSize(stat.toJson(), opts)) .reduce(sumSize) } else { size = extractSize(stats.toJson(), opts) } } finally { if (config.output.path && !opts.output) { await del(config.output.path, { force: true }) } } let result = { parsed: size.parsed - WEBPACK_EMPTY_PROJECT_PARSED } if (opts.running !== false) result.running = running if (opts.config || opts.gzip === false) { result.loading = getLoadingTime(result.parsed) } else { result.gzip = size.gzip - WEBPACK_EMPTY_PROJECT_GZIP result.loading = getLoadingTime(result.gzip) } return result } }
javascript
{ "resource": "" }
q18639
getEventMetadata
train
function getEventMetadata({ event, payload }) { if (event === 'state') { return chalk.bold(payload.value); } if (event === 'instance-start' || event === 'instance-stop') { if (payload.dc != null) { return chalk.green(`(${payload.dc})`); } } return ''; }
javascript
{ "resource": "" }
q18640
stateString
train
function stateString(s) { switch (s) { case 'INITIALIZING': return chalk.yellow(s); case 'ERROR': return chalk.red(s); case 'READY': return s; default: return chalk.gray('UNKNOWN'); } }
javascript
{ "resource": "" }
q18641
filterUniqueApps
train
function filterUniqueApps() { const uniqueApps = new Set(); return function uniqueAppFilter([appName]) { if (uniqueApps.has(appName)) { return false; } uniqueApps.add(appName); return true; }; }
javascript
{ "resource": "" }
q18642
hashes
train
async function hashes(files) { const map = new Map(); await Promise.all( files.map(async name => { const data = await fs.promises.readFile(name); const h = hash(data); const entry = map.get(h); if (entry) { entry.names.push(name); } else { map.set(hash(data), { names: [name], data }); } }) ); return map; }
javascript
{ "resource": "" }
q18643
train
function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }
javascript
{ "resource": "" }
q18644
train
function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }
javascript
{ "resource": "" }
q18645
makeSingleQuery
train
function makeSingleQuery(allQuery, getMultipleError) { return (container, ...args) => { const els = allQuery(container, ...args) if (els.length > 1) { throw getMultipleElementsFoundError( getMultipleError(container, ...args), container, ) } return els[0] || null } }
javascript
{ "resource": "" }
q18646
makeGetAllQuery
train
function makeGetAllQuery(allQuery, getMissingError) { return (container, ...args) => { const els = allQuery(container, ...args) if (!els.length) { throw getElementError(getMissingError(container, ...args), container) } return els } }
javascript
{ "resource": "" }
q18647
makeFindQuery
train
function makeFindQuery(getter) { return (container, text, options, waitForElementOptions) => waitForElement( () => getter(container, text, options), waitForElementOptions, ) }
javascript
{ "resource": "" }
q18648
makeNormalizer
train
function makeNormalizer({trim, collapseWhitespace, normalizer}) { if (normalizer) { // User has specified a custom normalizer if ( typeof trim !== 'undefined' || typeof collapseWhitespace !== 'undefined' ) { // They've also specified a value for trim or collapseWhitespace throw new Error( 'trim and collapseWhitespace are not supported with a normalizer. ' + 'If you want to use the default trim and collapseWhitespace logic in your normalizer, ' + 'use "getDefaultNormalizer({trim, collapseWhitespace})" and compose that into your normalizer', ) } return normalizer } else { // No custom normalizer specified. Just use default. return getDefaultNormalizer({trim, collapseWhitespace}) } }
javascript
{ "resource": "" }
q18649
train
function(arrayOfWebPImages) { config.advertisement = []; var length = arrayOfWebPImages.length; for (var i = 0; i < length; i++) { config.advertisement.push({ duration: i, image: arrayOfWebPImages[i] }); } }
javascript
{ "resource": "" }
q18650
train
function() { if (mediaRecorder && typeof mediaRecorder.clearRecordedData === 'function') { mediaRecorder.clearRecordedData(); } mediaRecorder = null; setState('inactive'); self.blob = null; }
javascript
{ "resource": "" }
q18651
train
function() { var self = this; if (typeof indexedDB === 'undefined' || typeof indexedDB.open === 'undefined') { console.error('IndexedDB API are not available in this browser.'); return; } var dbVersion = 1; var dbName = this.dbName || location.href.replace(/\/|:|#|%|\.|\[|\]/g, ''), db; var request = indexedDB.open(dbName, dbVersion); function createObjectStore(dataBase) { dataBase.createObjectStore(self.dataStoreName); } function putInDB() { var transaction = db.transaction([self.dataStoreName], 'readwrite'); if (self.videoBlob) { transaction.objectStore(self.dataStoreName).put(self.videoBlob, 'videoBlob'); } if (self.gifBlob) { transaction.objectStore(self.dataStoreName).put(self.gifBlob, 'gifBlob'); } if (self.audioBlob) { transaction.objectStore(self.dataStoreName).put(self.audioBlob, 'audioBlob'); } function getFromStore(portionName) { transaction.objectStore(self.dataStoreName).get(portionName).onsuccess = function(event) { if (self.callback) { self.callback(event.target.result, portionName); } }; } getFromStore('audioBlob'); getFromStore('videoBlob'); getFromStore('gifBlob'); } request.onerror = self.onError; request.onsuccess = function() { db = request.result; db.onerror = self.onError; if (db.setVersion) { if (db.version !== dbVersion) { var setVersion = db.setVersion(dbVersion); setVersion.onsuccess = function() { createObjectStore(db); putInDB(); }; } else { putInDB(); } } else { putInDB(); } }; request.onupgradeneeded = function(event) { createObjectStore(event.target.result); }; }
javascript
{ "resource": "" }
q18652
train
function(config) { this.audioBlob = config.audioBlob; this.videoBlob = config.videoBlob; this.gifBlob = config.gifBlob; this.init(); return this; }
javascript
{ "resource": "" }
q18653
getLastNumber
train
function getLastNumber(str){ var retval=""; for (var i=str.length-1;i>=0;--i) if (str[i]>="0"&&str[i]<="9") retval=str[i]+retval; if (retval.length==0) return "0"; return retval; }
javascript
{ "resource": "" }
q18654
existing_stats
train
function existing_stats(stats_type, bucket){ matches = []; //typical case: one-off, fully qualified if (bucket in stats_type) { matches.push(bucket); } //special case: match a whole 'folder' (and subfolders) of stats if (bucket.slice(-2) == ".*") { var folder = bucket.slice(0,-1); for (var name in stats_type) { //check if stat is in bucket, ie~ name starts with folder if (name.substring(0, folder.length) == folder) { matches.push(name); } } } return matches; }
javascript
{ "resource": "" }
q18655
Metric
train
function Metric(key, value, ts) { var m = this; this.key = key; this.value = value; this.ts = ts; // return a string representation of this metric appropriate // for sending to the graphite collector. does not include // a trailing newline. this.toText = function() { return m.key + " " + m.value + " " + m.ts; }; this.toPickle = function() { return MARK + STRING + '\'' + m.key + '\'\n' + MARK + LONG + m.ts + 'L\n' + STRING + '\'' + m.value + '\'\n' + TUPLE + TUPLE + APPEND; }; }
javascript
{ "resource": "" }
q18656
Stats
train
function Stats() { var s = this; this.metrics = []; this.add = function(key, value, ts) { s.metrics.push(new Metric(key, value, ts)); }; this.toText = function() { return s.metrics.map(function(m) { return m.toText(); }).join('\n') + '\n'; }; this.toPickle = function() { var body = MARK + LIST + s.metrics.map(function(m) { return m.toPickle(); }).join('') + STOP; // The first four bytes of the graphite pickle format // contain the length of the rest of the payload. // We use Buffer because this is binary data. var buf = new Buffer(4 + body.length); buf.writeUInt32BE(body.length,0); buf.write(body,4); return buf; }; }
javascript
{ "resource": "" }
q18657
sk
train
function sk(key) { if (globalKeySanitize) { return key; } else { return key.replace(/\s+/g, '_') .replace(/\//g, '-') .replace(/[^a-zA-Z_\-0-9\.]/g, ''); } }
javascript
{ "resource": "" }
q18658
healthcheck
train
function healthcheck(node) { var ended = false; var node_id = node.host + ':' + node.port; var client = net.connect( {port: node.adminport, host: node.host}, function onConnect() { if (!ended) { client.write('health\r\n'); } } ); client.setTimeout(healthCheckInterval, function() { client.end(); markNodeAsUnhealthy(node_id); client.removeAllListeners('data'); ended = true; }); client.on('data', function(data) { if (ended) { return; } var health_status = data.toString(); client.end(); ended = true; if (health_status.indexOf('up') < 0) { markNodeAsUnhealthy(node_id); } else { markNodeAsHealthy(node_id); } }); client.on('error', function(e) { if (ended) { return; } if (e.code !== 'ECONNREFUSED' && e.code !== 'EHOSTUNREACH' && e.code !== 'ECONNRESET') { log('Error during healthcheck on node ' + node_id + ' with ' + e.code, 'ERROR'); } markNodeAsUnhealthy(node_id); }); }
javascript
{ "resource": "" }
q18659
train
function (sLink) { if (sLink[0] === "#") { sLink = document.location.href.substring(0,document.location.href.search("demoapps\.html")) + sLink; } return sLink; }
javascript
{ "resource": "" }
q18660
train
function(oOldOptions, oNewOptions) { var oMergedOptions = jQuery.extend({}, oOldOptions, oNewOptions); jQuery.each(oMergedOptions, function(key) { oMergedOptions[key] = oOldOptions[key] || oNewOptions[key]; // default merge strategy is inclusive OR }); return oMergedOptions; }
javascript
{ "resource": "" }
q18661
train
function(oChild1, oChild2) { var oGeometry1 = DOMUtil.getGeometry(oChild1); var oGeometry2 = DOMUtil.getGeometry(oChild2); var oPosition1 = oGeometry1 && oGeometry1.position; var oPosition2 = oGeometry2 && oGeometry2.position; if (oPosition1 && oPosition2) { var iBottom1 = oPosition1.top + oGeometry1.size.height; var iBottom2 = oPosition2.top + oGeometry2.size.height; if (oPosition1.top < oPosition2.top) { if (iBottom1 >= iBottom2 && oPosition2.left < oPosition1.left) { /* Example: +--------------+ +------+ | | | 2 | | 1 | +------+ | | +--------------+ Despites 1st overlay's top is above 2nd element, the order should be switched, since 2nd element is shorter and is more to the left */ return 1; } else { return -1; // do not switch order } } else if (oPosition1.top === oPosition2.top) { if (oPosition1.left === oPosition2.left) { // Give priority to smaller block by height or width if ( oGeometry1.size.height < oGeometry2.size.height || oGeometry1.size.width < oGeometry2.size.width ) { return -1; } else if ( oGeometry1.size.height > oGeometry2.size.height || oGeometry1.size.width > oGeometry2.size.width ) { return 1; } else { return 0; } } else if (oPosition1.left < oPosition2.left) { return -1; // order is correct } else { return 1; // switch order } } else if (iBottom1 <= iBottom2 && oPosition2.left > oPosition1.left) { // if (oPosition1.top > oPosition2.top) /* see picture above, but switch 1 and 2 - order is correct */ return -1; } else { /* Example: +--------------+ +------+ | 2 | | 1 | +--------------+ | | +------+ Since 1st overlay's both top and bottom coordinates are bellow in dom, then top and bottom of 2nd, they should be switched */ return 1; } } return 0; }
javascript
{ "resource": "" }
q18662
train
function() { var oViewModel = this.getModel("appView"), bPhoneSize = oViewModel.getProperty("/bPhoneSize"); // Version switch should not be shown on phone sizes or when no versions are found oViewModel.setProperty("/bShowVersionSwitchInHeader", !bPhoneSize && !!this._aNeoAppVersions); oViewModel.setProperty("/bShowVersionSwitchInMenu", bPhoneSize && !!this._aNeoAppVersions); }
javascript
{ "resource": "" }
q18663
train
function () { var that = this; if (!this._oFeedbackDialog) { this._oFeedbackDialog = new sap.ui.xmlfragment("feedbackDialogFragment", "sap.ui.documentation.sdk.view.FeedbackDialog", this); this._oView.addDependent(this._oFeedbackDialog); this._oFeedbackDialog.textInput = Fragment.byId("feedbackDialogFragment", "feedbackInput"); this._oFeedbackDialog.contextCheckBox = Fragment.byId("feedbackDialogFragment", "pageContext"); this._oFeedbackDialog.contextData = Fragment.byId("feedbackDialogFragment", "contextData"); this._oFeedbackDialog.ratingStatus = Fragment.byId("feedbackDialogFragment", "ratingStatus"); this._oFeedbackDialog.ratingStatus.value = 0; this._oFeedbackDialog.sendButton = Fragment.byId("feedbackDialogFragment", "sendButton"); this._oFeedbackDialog.ratingBar = [ { button : Fragment.byId("feedbackDialogFragment", "excellent"), status : "Excellent" }, { button : Fragment.byId("feedbackDialogFragment", "good"), status : "Good" }, { button : Fragment.byId("feedbackDialogFragment", "average"), status : "Average" }, { button : Fragment.byId("feedbackDialogFragment", "poor"), status : "Poor" }, { button : Fragment.byId("feedbackDialogFragment", "veryPoor"), status : "Very Poor" } ]; this._oFeedbackDialog.reset = function () { this.sendButton.setEnabled(false); this.textInput.setValue(""); this.contextCheckBox.setSelected(true); this.ratingStatus.setText(""); this.ratingStatus.setState("None"); this.ratingStatus.value = 0; this.contextData.setVisible(false); this.ratingBar.forEach(function(oRatingBarElement){ if (oRatingBarElement.button.getPressed()) { oRatingBarElement.button.setPressed(false); } }); }; this._oFeedbackDialog.updateContextData = function() { var sVersion = that._getUI5Version(), sUI5Distribution = that._getUI5Distribution(); if (this.contextCheckBox.getSelected()) { this.contextData.setValue("Location: " + that._getCurrentPageRelativeURL() + "\n" + sUI5Distribution + " Version: " + sVersion); } else { this.contextData.setValue(sUI5Distribution + " Version: " + sVersion); } }; this._oFeedbackDialog.updateContextData(); } this._oFeedbackDialog.updateContextData(); if (!this._oFeedbackDialog.isOpen()) { syncStyleClass("sapUiSizeCompact", this.getView(), this._oFeedbackDialog); this._oFeedbackDialog.open(); } }
javascript
{ "resource": "" }
q18664
train
function() { var data = {}; if (this._oFeedbackDialog.contextCheckBox.getSelected()) { data = { "texts": { "t1": this._oFeedbackDialog.textInput.getValue() }, "ratings":{ "r1": {"value" : this._oFeedbackDialog.ratingStatus.value} }, "context": {"page": this._getCurrentPageRelativeURL(), "attr1": this._getUI5Distribution() + ":" + sap.ui.version} }; } else { data = { "texts": { "t1": this._oFeedbackDialog.textInput.getValue() }, "ratings":{ "r1": {"value" : this._oFeedbackDialog.ratingStatus.value} }, "context": {"attr1": this._getUI5Distribution() + ":" + sap.ui.version} }; } // send feedback this._oFeedbackDialog.setBusyIndicatorDelay(0); this._oFeedbackDialog.setBusy(true); jQuery.ajax({ url: this.FEEDBACK_SERVICE_URL, type: "POST", contentType: "application/json", data: JSON.stringify(data) }). done( function () { MessageBox.success("Your feedback has been sent.", {title: "Thank you!"}); this._oFeedbackDialog.reset(); this._oFeedbackDialog.close(); this._oFeedbackDialog.setBusy(false); }.bind(this) ). fail( function (oRequest, sStatus, sError) { var sErrorDetails = sError; // + "\n" + oRequest.responseText; MessageBox.error("An error occurred sending your feedback:\n" + sErrorDetails, {title: "Sorry!"}); this._oFeedbackDialog.setBusy(false); }.bind(this) ); }
javascript
{ "resource": "" }
q18665
train
function(oEvent) { var that = this; var oPressedButton = oEvent.getSource(); that._oFeedbackDialog.ratingBar.forEach(function(oRatingBarElement) { if (oPressedButton !== oRatingBarElement.button) { oRatingBarElement.button.setPressed(false); } else { if (!oRatingBarElement.button.getPressed()) { setRatingStatus("None", "", 0); } else { switch (oRatingBarElement.status) { case "Excellent": setRatingStatus("Success", oRatingBarElement.status, 5); break; case "Good": setRatingStatus("Success", oRatingBarElement.status, 4); break; case "Average": setRatingStatus("None", oRatingBarElement.status, 3); break; case "Poor": setRatingStatus("Warning", oRatingBarElement.status, 2); break; case "Very Poor": setRatingStatus("Error", oRatingBarElement.status, 1); } } } }); function setRatingStatus(sState, sText, iValue) { that._oFeedbackDialog.ratingStatus.setState(sState); that._oFeedbackDialog.ratingStatus.setText(sText); that._oFeedbackDialog.ratingStatus.value = iValue; if (iValue) { that._oFeedbackDialog.sendButton.setEnabled(true); } else { that._oFeedbackDialog.sendButton.setEnabled(false); } } }
javascript
{ "resource": "" }
q18666
train
function(path){ // ##### BEGIN: MODIFIED BY SAP var dispatchFunction; // ##### END: MODIFIED BY SAP path = _makePath.apply(null, arguments); if(path !== _hash){ // we should store raw value // ##### BEGIN: MODIFIED BY SAP dispatchFunction = _registerChange(path); if (!hasher.raw) { path = _encodePath(path); } window.location.hash = '#' + path; dispatchFunction && dispatchFunction(); // ##### END: MODIFIED BY SAP } }
javascript
{ "resource": "" }
q18667
Doclet
train
function Doclet(comment) { this.comment = comment = unwrap(comment); this.tags = []; var m; var lastContent = 0; var lastTag = "description"; while ((m = rtag.exec(comment)) != null) { this._addTag(lastTag, comment.slice(lastContent, m.index)); lastTag = m[2]; lastContent = rtag.lastIndex; } this._addTag(lastTag, comment.slice(lastContent)); }
javascript
{ "resource": "" }
q18668
fnAppendBusyIndicator
train
function fnAppendBusyIndicator() { // Only append if busy state is still set if (!this.getBusy()) { return; } var $this = this.$(this._sBusySection); //If there is a pending delayed call to append the busy indicator, we can clear it now if (this._busyIndicatorDelayedCallId) { clearTimeout(this._busyIndicatorDelayedCallId); delete this._busyIndicatorDelayedCallId; } // if no busy section/control jquery instance could be retrieved -> the control is not part of the dom anymore // this might happen in certain scenarios when e.g. a dialog is closed faster than the busyIndicatorDelay if (!$this || $this.length === 0) { Log.warning("BusyIndicator could not be rendered. The outer control instance is not valid anymore."); return; } if (this._sBlockSection === this._sBusySection) { if (this._oBlockState) { BusyIndicatorUtils.addHTML(this._oBlockState, this.getBusyIndicatorSize()); BlockLayerUtils.toggleAnimationStyle(this._oBlockState, true); this._oBusyBlockState = this._oBlockState; } else { // BusyIndicator is the first blocking element created (and ) fnAddStandaloneBusyIndicator.call(this); } } else { // Standalone busy indicator fnAddStandaloneBusyIndicator.call(this); } }
javascript
{ "resource": "" }
q18669
fnAddStandaloneBlockLayer
train
function fnAddStandaloneBlockLayer () { this._oBlockState = BlockLayerUtils.block(this, this.getId() + "-blockedLayer", this._sBlockSection); jQuery(this._oBlockState.$blockLayer.get(0)).addClass("sapUiBlockLayerOnly"); }
javascript
{ "resource": "" }
q18670
fnAddStandaloneBusyIndicator
train
function fnAddStandaloneBusyIndicator () { this._oBusyBlockState = BlockLayerUtils.block(this, this.getId() + "-busyIndicator", this._sBusySection); BusyIndicatorUtils.addHTML(this._oBusyBlockState, this.getBusyIndicatorSize()); }
javascript
{ "resource": "" }
q18671
fnRemoveBusyIndicator
train
function fnRemoveBusyIndicator(bForceRemoval) { // removing all block layers is done upon rerendering and destroy of the control if (bForceRemoval) { fnRemoveAllBlockLayers.call(this); return; } var $this = this.$(this._sBusySection); $this.removeClass('sapUiLocalBusy'); //Unset the actual DOM Element´s 'aria-busy' $this.removeAttr('aria-busy'); if (this._sBlockSection === this._sBusySection) { if (!this.getBlocked() && !this.getBusy()) { // Remove shared block state & busy block state reference fnRemoveAllBlockLayers.call(this); } else if (this.getBlocked()) { // Hide animation in shared block layer BlockLayerUtils.toggleAnimationStyle(this._oBlockState || this._oBusyBlockState, false); this._oBlockState = this._oBusyBlockState; } else if (this._oBusyBlockState) { BlockLayerUtils.unblock(this._oBusyBlockState); delete this._oBusyBlockState; } } else if (this._oBusyBlockState) { // standalone busy block state BlockLayerUtils.unblock(this._oBusyBlockState); delete this._oBusyBlockState; } }
javascript
{ "resource": "" }
q18672
filterDuplicates
train
function filterDuplicates(/*ref*/ aMessages){ if (aMessages.length > 1) { for (var iIndex = 1; iIndex < aMessages.length; iIndex++) { if (aMessages[0].getCode() == aMessages[iIndex].getCode() && aMessages[0].getMessage() == aMessages[iIndex].getMessage()) { aMessages.shift(); // Remove outer error, since inner error is more detailed break; } } } }
javascript
{ "resource": "" }
q18673
toBuddhist
train
function toBuddhist(oGregorian) { var iEraStartYear = UniversalDate.getEraStartDate(CalendarType.Buddhist, 0).year, iYear = oGregorian.year - iEraStartYear + 1; // Before 1941 new year started on 1st of April if (oGregorian.year < 1941 && oGregorian.month < 3) { iYear -= 1; } if (oGregorian.year === null) { iYear = undefined; } return { year: iYear, month: oGregorian.month, day: oGregorian.day }; }
javascript
{ "resource": "" }
q18674
toGregorian
train
function toGregorian(oBuddhist) { var iEraStartYear = UniversalDate.getEraStartDate(CalendarType.Buddhist, 0).year, iYear = oBuddhist.year + iEraStartYear - 1; // Before 1941 new year started on 1st of April if (iYear < 1941 && oBuddhist.month < 3) { iYear += 1; } if (oBuddhist.year === null) { iYear = undefined; } return { year: iYear, month: oBuddhist.month, day: oBuddhist.day }; }
javascript
{ "resource": "" }
q18675
toGregorianArguments
train
function toGregorianArguments(aArgs) { var oBuddhist, oGregorian; oBuddhist = { year: aArgs[0], month: aArgs[1], day: aArgs[2] !== undefined ? aArgs[2] : 1 }; oGregorian = toGregorian(oBuddhist); aArgs[0] = oGregorian.year; return aArgs; }
javascript
{ "resource": "" }
q18676
train
function (oVersionInfo) { var bResult = false, sFrameworkInfo = ""; try { sFrameworkInfo = oVersionInfo.gav ? oVersionInfo.gav : oVersionInfo.name; bResult = sFrameworkInfo.indexOf('openui5') !== -1 ? true : false; } catch (e) { return bResult; } return bResult; }
javascript
{ "resource": "" }
q18677
train
function () { var that = this; var oInternalRulesPromise = new Promise(function (resolve) { if (that.bCanLoadInternalRules !== null) { resolve(that.bCanLoadInternalRules); return; } jQuery.ajax({ type: "HEAD", url: sInternalPingFilePath, success: function () { that.bCanLoadInternalRules = true; resolve(that.bCanLoadInternalRules); }, error: function() { that.bCanLoadInternalRules = false; resolve(that.bCanLoadInternalRules); } }); }); return oInternalRulesPromise; }
javascript
{ "resource": "" }
q18678
train
function(aRows, iField, oLD, oOptions, iLabelSize) { var iRemain = 0; var oRow; for (i = 0; i < aRows.length; i++) { if (iField >= aRows[i].first && iField <= aRows[i].last) { oRow = aRows[i]; break; } } if (!oLD) { oOptions.Size = Math.floor(oRow.availableCells / oRow.defaultFields); } if (iField === oRow.first && iField > 0) { oOptions.Break = true; if (iLabelSize > 0 && iLabelSize < iColumns && oOptions.Size <= iColumns - iLabelSize) { oOptions.Space = iLabelSize; } } if (iField === oRow.firstDefault) { // add remaining cells to first default field iRemain = oRow.availableCells - oRow.defaultFields * oOptions.Size; if (iRemain > 0) { oOptions.Size = oOptions.Size + iRemain; } } }
javascript
{ "resource": "" }
q18679
sanitizeHistorySensitive
train
function sanitizeHistorySensitive(blockOfProperties) { var elide = false; for (var i = 0, n = blockOfProperties.length; i < n-1; ++i) { var token = blockOfProperties[i]; if (':' === blockOfProperties[i+1]) { elide = !(cssSchema[token].cssPropBits & CSS_PROP_BIT_ALLOWED_IN_LINK); } if (elide) { blockOfProperties[i] = ''; } if (';' === token) { elide = false; } } return blockOfProperties.join(''); }
javascript
{ "resource": "" }
q18680
escapeAttrib
train
function escapeAttrib(s) { return ('' + s).replace(ampRe, '&amp;').replace(ltRe, '&lt;') .replace(gtRe, '&gt;').replace(quotRe, '&#34;'); }
javascript
{ "resource": "" }
q18681
htmlSplit
train
function htmlSplit(str) { // can't hoist this out of the function because of the re.exec loop. var re = /(<\/|<\!--|<[!?]|[&<>])/g; str += ''; if (splitWillCapture) { return str.split(re); } else { var parts = []; var lastPos = 0; var m; while ((m = re.exec(str)) !== null) { parts.push(str.substring(lastPos, m.index)); parts.push(m[0]); lastPos = m.index + m[0].length; } parts.push(str.substring(lastPos)); return parts; } }
javascript
{ "resource": "" }
q18682
sanitize
train
function sanitize(inputHtml, opt_naiveUriRewriter, opt_nmTokenPolicy) { var tagPolicy = makeTagPolicy(opt_naiveUriRewriter, opt_nmTokenPolicy); return sanitizeWithPolicy(inputHtml, tagPolicy); }
javascript
{ "resource": "" }
q18683
train
function (option) { option = option || {}; if (!BeaconRequest.isSupported()) { throw Error("Beacon API is not supported"); } if (typeof option.url !== "string") { throw Error("Beacon url must be valid"); } this._nMaxBufferLength = option.maxBufferLength || 10; this._aBuffer = []; this._sUrl = option.url; this.attachSendOnUnload(); }
javascript
{ "resource": "" }
q18684
train
function (sRule, bAsync) { var sCheckFunction = this.model.getProperty(sRule + "/check"); if (!sCheckFunction) { return; } // Check if a function is found var oMatch = sCheckFunction.match(/function[^(]*\(([^)]*)\)/); if (!oMatch) { return; } // Get the parameters of the function found and trim, then split by word. var aParams = oMatch[1].trim().split(/\W+/); // Add missing parameters to ensure the resolve function is passed on the correct position. aParams[0] = aParams[0] || "oIssueManager"; aParams[1] = aParams[1] || "oCoreFacade"; aParams[2] = aParams[2] || "oScope"; // If async add a fnResolve to the template else remove it. if (bAsync) { aParams[3] = aParams[3] || "fnResolve"; } else { aParams = aParams.slice(0, 3); } // Replace the current parameters with the new ones. var sNewCheckFunction = sCheckFunction.replace(/function[^(]*\(([^)]*)\)/, "function (" + aParams.join(", ") + ")"); this.model.setProperty(sRule + "/check", sNewCheckFunction); }
javascript
{ "resource": "" }
q18685
train
function (component, savedComponents) { for (var index = 0; index < savedComponents.length; index += 1) { if (savedComponents[index].text == component.text && savedComponents[index].selected) { return true; } } return false; }
javascript
{ "resource": "" }
q18686
train
function (oEvent) { var bShowRuleProperties = true, oSelectedRule = this.model.getProperty("/selectedRule"), bAdditionalRulesetsTab = oEvent.getParameter("selectedKey") === "additionalRulesets"; if (bAdditionalRulesetsTab || !oSelectedRule) { bShowRuleProperties = false; } // Ensure we don't make unnecessary requests. The requests will be made only // the first time the user clicks AdditionalRulesets tab. if (!this.bAdditionalRulesetsLoaded && bAdditionalRulesetsTab) { this.rulesViewContainer.setBusyIndicatorDelay(0); this.rulesViewContainer.setBusy(true); CommunicationBus.publish(channelNames.GET_NON_LOADED_RULE_SETS, { loadedRulesets: this._getLoadedRulesets() }); } this.getView().getModel().setProperty("/showRuleProperties", bShowRuleProperties); }
javascript
{ "resource": "" }
q18687
train
function (tempLib, treeTable) { var library, rule, oTempLibCopy, bSelected, aRules, iIndex, fnFilter = function (oRule) { return oRule.id === rule.id; }; for (var i in treeTable) { library = treeTable[i]; oTempLibCopy = treeTable[i].nodes; if (library.name !== Constants.TEMP_RULESETS_NAME) { continue; } //reset the model to add the temp rules treeTable[i].nodes = []; for (var ruleIndex in tempLib.rules) { rule = tempLib.rules[ruleIndex]; bSelected = oTempLibCopy[ruleIndex] !== undefined ? oTempLibCopy[ruleIndex].selected : true; // syncs selection of temporary rules from local storage if (this.tempRulesFromStorage) { aRules = this.tempRulesFromStorage.filter(fnFilter); if (aRules.length > 0) { bSelected = aRules[0].selected; iIndex = this.tempRulesFromStorage.indexOf(aRules[0]); this.tempRulesFromStorage.splice(iIndex, 1); if (bSelected === false) { library.selected = false; } } if (this.tempRulesFromStorage.length === 0) { this.tempRulesFromStorage.length = null; } } library.nodes.push({ name: rule.title, description: rule.description, id: rule.id, audiences: rule.audiences.toString(), categories: rule.categories.toString(), minversion: rule.minversion, resolution: rule.resolution, title: rule.title, selected: bSelected, libName: library.name, check: rule.check }); } this.model.setProperty("/treeModel", treeTable); return library; } }
javascript
{ "resource": "" }
q18688
train
function (tempRule, treeTable) { var ruleSource = this.model.getProperty("/editRuleSource"); for (var i in treeTable) { if (treeTable[i].name === Constants.TEMP_RULESETS_NAME) { for (var innerIndex in treeTable[i].nodes) { if (treeTable[i].nodes[innerIndex].id === ruleSource.id) { treeTable[i].nodes[innerIndex] = { name: tempRule.title, description: tempRule.description, id: tempRule.id, audiences: tempRule.audiences, categories: tempRule.categories, minversion: tempRule.minversion, resolution: tempRule.resolution, selected: treeTable[i].nodes[innerIndex].selected, title: tempRule.title, libName: treeTable[i].name, check: tempRule.check }; } } } } }
javascript
{ "resource": "" }
q18689
train
function () { var tempRules = Storage.getRules(), loadingFromAdditionalRuleSets = this.model.getProperty("/loadingAdditionalRuleSets"); if (tempRules && !loadingFromAdditionalRuleSets && !this.tempRulesLoaded) { this.tempRulesFromStorage = tempRules; this.tempRulesLoaded = true; tempRules.forEach(function (tempRule) { CommunicationBus.publish(channelNames.VERIFY_CREATE_RULE, RuleSerializer.serialize(tempRule)); }); this.persistedTempRulesCount = tempRules.length; } }
javascript
{ "resource": "" }
q18690
train
function (event) { var sPath = event.getSource().getBindingContext("treeModel").getPath(), sourceObject = this.treeTable.getBinding().getModel().getProperty(sPath), libs = this.model.getProperty("/libraries"); libs.forEach(function (lib, libIndex) { lib.rules.forEach(function (rule) { if (rule.id === sourceObject.id) { sourceObject.check = rule.check; } }); }); return sourceObject; }
javascript
{ "resource": "" }
q18691
train
function (aColumnsIds, bVisibilityValue) { var aColumns = this.treeTable.getColumns(); aColumns.forEach(function(oColumn) { oColumn.setVisible(!bVisibilityValue); aColumnsIds.forEach(function(sRuleId) { if (oColumn.sId.includes(sRuleId)) { oColumn.setVisible(bVisibilityValue); } }); }); }
javascript
{ "resource": "" }
q18692
train
function (oEvent) { var oColumn = oEvent.getParameter("column"), bNewVisibilityState = oEvent.getParameter("newVisible"); if (!this.model.getProperty("/persistingSettings")) { return; } oColumn.setVisible(bNewVisibilityState); this.persistVisibleColumns(); }
javascript
{ "resource": "" }
q18693
train
function(oModelReference, mParameter) { if (typeof mParameter == "string") { throw "Deprecated second argument: Adjust your invocation by passing an object with a property sAnnotationJSONDoc as a second argument instead"; } this._mParameter = mParameter; var that = this; /* * get access to OData model */ this._oActivatedWorkarounds = {}; if (oModelReference && oModelReference.aWorkaroundID) { for (var i = -1, sID; (sID = oModelReference.aWorkaroundID[++i]) !== undefined;) { this._oActivatedWorkarounds[sID] = true; } oModelReference = oModelReference.oModelReference; } // check proper usage if (!oModelReference || (!oModelReference.sServiceURI && !oModelReference.oModel)) { throw "Usage with oModelReference being an instance of Model.ReferenceByURI or Model.ReferenceByModel"; } //check if a model is given, or we need to create one from the service URI if (oModelReference.oModel) { this._oModel = oModelReference.oModel; // find out which model version we are running this._iVersion = AnalyticalVersionInfo.getVersion(this._oModel); checkForMetadata(); } else if (mParameter && mParameter.modelVersion === AnalyticalVersionInfo.V2) { // Check if the user wants a V2 model var V2ODataModel = sap.ui.requireSync("sap/ui/model/odata/v2/ODataModel"); this._oModel = new V2ODataModel(oModelReference.sServiceURI); this._iVersion = AnalyticalVersionInfo.V2; checkForMetadata(); } else { //default is V1 Model var ODataModel = sap.ui.requireSync("sap/ui/model/odata/ODataModel"); this._oModel = new ODataModel(oModelReference.sServiceURI); this._iVersion = AnalyticalVersionInfo.V1; checkForMetadata(); } if (this._oModel.getServiceMetadata() && this._oModel.getServiceMetadata().dataServices == undefined) { throw "Model could not be loaded"; } /** * Check if the metadata is already available, if not defere the interpretation of the Metadata */ function checkForMetadata() { // V2 supports asynchronous loading of metadata // we have to register for the MetadataLoaded Event in case, the data is not loaded already if (!that._oModel.getServiceMetadata()) { that._oModel.attachMetadataLoaded(processMetadata); } else { // metadata already loaded processMetadata(); } } /** * Kickstart the interpretation of the metadata, * either called directly if metadata is available, or deferred and then * executed via callback by the model during the metadata loaded event. */ function processMetadata () { //only interprete the metadata if the analytics model was not initialised yet if (that.bIsInitialized) { return; } //mark analytics model as initialized that.bIsInitialized = true; /* * add extra annotations if provided */ if (mParameter && mParameter.sAnnotationJSONDoc) { that.mergeV2Annotations(mParameter.sAnnotationJSONDoc); } that._interpreteMetadata(that._oModel.getServiceMetadata().dataServices); } }
javascript
{ "resource": "" }
q18694
processMetadata
train
function processMetadata () { //only interprete the metadata if the analytics model was not initialised yet if (that.bIsInitialized) { return; } //mark analytics model as initialized that.bIsInitialized = true; /* * add extra annotations if provided */ if (mParameter && mParameter.sAnnotationJSONDoc) { that.mergeV2Annotations(mParameter.sAnnotationJSONDoc); } that._interpreteMetadata(that._oModel.getServiceMetadata().dataServices); }
javascript
{ "resource": "" }
q18695
train
function(sName) { var oQueryResult = this._oQueryResultSet[sName]; // Everybody should have a second chance: // If the name was not fully qualified, check if it is in the default // container if (!oQueryResult && this._oDefaultEntityContainer) { var sQName = this._oDefaultEntityContainer.name + "." + sName; oQueryResult = this._oQueryResultSet[sQName]; } return oQueryResult; }
javascript
{ "resource": "" }
q18696
train
function(oSchema, sQTypeName) { var aEntitySet = []; for (var i = -1, oEntityContainer; (oEntityContainer = oSchema.entityContainer[++i]) !== undefined;) { for (var j = -1, oEntitySet; (oEntitySet = oEntityContainer.entitySet[++j]) !== undefined;) { if (oEntitySet.entityType == sQTypeName) { aEntitySet.push([ oEntityContainer, oEntitySet ]); } } } return aEntitySet; }
javascript
{ "resource": "" }
q18697
train
function(oModel, oEntityType, oEntitySet, oParameterization, oAssocFromParamsToResult) { this._oModel = oModel; this._oEntityType = oEntityType; this._oEntitySet = oEntitySet; this._oParameterization = oParameterization; this._oDimensionSet = {}; this._oMeasureSet = {}; // parse entity type for analytic semantics described by annotations var aProperty = oEntityType.getTypeDescription().property; var oAttributeForPropertySet = {}; for (var i = -1, oProperty; (oProperty = aProperty[++i]) !== undefined;) { if (oProperty.extensions == undefined) { continue; } for (var j = -1, oExtension; (oExtension = oProperty.extensions[++j]) !== undefined;) { if (!oExtension.namespace == odata4analytics.constants.SAP_NAMESPACE) { continue; } switch (oExtension.name) { case "aggregation-role": switch (oExtension.value) { case "dimension": { var oDimension = new odata4analytics.Dimension(this, oProperty); this._oDimensionSet[oDimension.getName()] = oDimension; break; } case "measure": { var oMeasure = new odata4analytics.Measure(this, oProperty); this._oMeasureSet[oMeasure.getName()] = oMeasure; break; } case "totaled-properties-list": this._oTotaledPropertyListProperty = oProperty; break; default: } break; case "attribute-for": { var oDimensionAttribute = new odata4analytics.DimensionAttribute(this, oProperty); var oKeyProperty = oDimensionAttribute.getKeyProperty(); oAttributeForPropertySet[oKeyProperty.name] = oDimensionAttribute; break; } default: } } } // assign dimension attributes to the respective dimension objects for ( var sDimensionAttributeName in oAttributeForPropertySet) { var oDimensionAttribute2 = oAttributeForPropertySet[sDimensionAttributeName]; oDimensionAttribute2.getDimension().addAttribute(oDimensionAttribute2); } // apply workaround for missing text properties if requested if (oModel._oActivatedWorkarounds.IdentifyTextPropertiesByName) { var aMatchedTextPropertyName = []; for ( var oDimName in this._oDimensionSet) { var oDimension2 = this._oDimensionSet[oDimName]; if (!oDimension2.getTextProperty()) { var oTextProperty = null; // order of matching is // significant! oTextProperty = oEntityType.findPropertyByName(oDimName + "Name"); if (!oTextProperty) { oTextProperty = oEntityType.findPropertyByName(oDimName + "Text"); } if (!oTextProperty) { oTextProperty = oEntityType.findPropertyByName(oDimName + "Desc"); } if (!oTextProperty) { oTextProperty = oEntityType.findPropertyByName(oDimName + "Description"); } if (oTextProperty) { // any match? oDimension2.setTextProperty(oTextProperty); // link // dimension // with text // property aMatchedTextPropertyName.push(oTextProperty.name); } } } // make sure that any matched text property is not exposed as // dimension (according to spec) for (var t = -1, sPropertyName; (sPropertyName = aMatchedTextPropertyName[++t]) !== undefined;) { delete this._oDimensionSet[sPropertyName]; } } }
javascript
{ "resource": "" }
q18698
train
function() { if (this._aDimensionNames) { return this._aDimensionNames; } this._aDimensionNames = []; for ( var sName in this._oDimensionSet) { this._aDimensionNames.push(this._oDimensionSet[sName].getName()); } return this._aDimensionNames; }
javascript
{ "resource": "" }
q18699
train
function() { if (this._aMeasureNames) { return this._aMeasureNames; } this._aMeasureNames = []; for ( var sName in this._oMeasureSet) { this._aMeasureNames.push(this._oMeasureSet[sName].getName()); } return this._aMeasureNames; }
javascript
{ "resource": "" }