_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49700
LogEvent
train
function LogEvent(timestamp, level, messageTemplate, properties, error) { this.timestamp = timestamp; this.level = level; this.messageTemplate = messageTemplate; this.properties = properties || {}; this.error = error || null; }
javascript
{ "resource": "" }
q49701
MessageTemplate
train
function MessageTemplate(messageTemplate) { if (messageTemplate === null || !messageTemplate.length) { throw new Error('Argument "messageTemplate" is required.'); } this.raw = messageTemplate; this.tokens = this.tokenize(messageTemplate); }
javascript
{ "resource": "" }
q49702
Logger
train
function Logger(pipeline, suppressErrors) { this.suppressErrors = true; this.pipeline = pipeline; this.suppressErrors = typeof suppressErrors === 'undefined' || suppressErrors; }
javascript
{ "resource": "" }
q49703
ImNotTouchingYou
train
function ImNotTouchingYou(element, parent, lrOnly, tbOnly, ignoreBottom) { return OverlapArea(element, parent, lrOnly, tbOnly, ignoreBottom) === 0; }
javascript
{ "resource": "" }
q49704
GetDimensions
train
function GetDimensions(elem, test){ elem = elem.length ? elem[0] : elem; if (elem === window || elem === document) { throw new Error("I'm sorry, Dave. I'm afraid I can't do that."); } var rect = elem.getBoundingClientRect(), parRect = elem.parentNode.getBoundingClientRect(), winRect = document.body.getBoundingClientRect(), winY = window.pageYOffset, winX = window.pageXOffset; return { width: rect.width, height: rect.height, offset: { top: rect.top + winY, left: rect.left + winX }, parentDims: { width: parRect.width, height: parRect.height, offset: { top: parRect.top + winY, left: parRect.left + winX } }, windowDims: { width: winRect.width, height: winRect.height, offset: { top: winY, left: winX } } } }
javascript
{ "resource": "" }
q49705
hideHandler
train
function hideHandler( e ) { var inContainer = moduleFilter.contains( e.target ); if ( e.keyCode === 27 || !inContainer ) { if ( e.keyCode === 27 && inContainer ) { moduleSearch.focus(); } dropDown.style.display = "none"; removeEvent( document, "click", hideHandler ); removeEvent( document, "keydown", hideHandler ); moduleSearch.value = ""; searchInput(); } }
javascript
{ "resource": "" }
q49706
searchInput
train
function searchInput() { var i, item, searchText = moduleSearch.value.toLowerCase(), listItems = dropDownList.children; for ( i = 0; i < listItems.length; i++ ) { item = listItems[ i ]; if ( !searchText || item.textContent.toLowerCase().indexOf( searchText ) > -1 ) { item.style.display = ""; } else { item.style.display = "none"; } } }
javascript
{ "resource": "" }
q49707
emCalc
train
function emCalc(em) { return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em; }
javascript
{ "resource": "" }
q49708
indent
train
function indent(extra) { if (!this.multiline) { return ""; } var chr = this.indentChar; if (this.HTML) { chr = chr.replace(/\t/g, " ").replace(/ /g, "&#160;"); } return new Array(this.depth + (extra || 0)).join(chr); }
javascript
{ "resource": "" }
q49709
on
train
function on(eventName, callback) { if (objectType(eventName) !== "string") { throw new TypeError("eventName must be a string when registering a listener"); } else if (!inArray(eventName, SUPPORTED_EVENTS)) { var events = SUPPORTED_EVENTS.join(", "); throw new Error("\"" + eventName + "\" is not a valid event; must be one of: " + events + "."); } else if (objectType(callback) !== "function") { throw new TypeError("callback must be a function when registering a listener"); } if (!LISTENERS[eventName]) { LISTENERS[eventName] = []; } // Don't register the same callback more than once if (!inArray(callback, LISTENERS[eventName])) { LISTENERS[eventName].push(callback); } }
javascript
{ "resource": "" }
q49710
registerLoggingCallbacks
train
function registerLoggingCallbacks(obj) { var i, l, key, callbackNames = ["begin", "done", "log", "testStart", "testDone", "moduleStart", "moduleDone"]; function registerLoggingCallback(key) { var loggingCallback = function loggingCallback(callback) { if (objectType(callback) !== "function") { throw new Error("QUnit logging methods require a callback function as their first parameters."); } config.callbacks[key].push(callback); }; return loggingCallback; } for (i = 0, l = callbackNames.length; i < l; i++) { key = callbackNames[i]; // Initialize key collection of logging callback if (objectType(config.callbacks[key]) === "undefined") { config.callbacks[key] = []; } obj[key] = registerLoggingCallback(key); } }
javascript
{ "resource": "" }
q49711
done
train
function done() { var storage = config.storage; ProcessingQueue.finished = true; var runtime = now() - config.started; var passed = config.stats.all - config.stats.bad; emit("runEnd", globalSuite.end(true)); runLoggingCallbacks("done", { passed: passed, failed: config.stats.bad, total: config.stats.all, runtime: runtime }); // Clear own storage items if all tests passed if (storage && config.stats.bad === 0) { for (var i = storage.length - 1; i >= 0; i--) { var key = storage.key(i); if (key.indexOf("qunit-test-") === 0) { storage.removeItem(key); } } } }
javascript
{ "resource": "" }
q49712
internalStop
train
function internalStop(test) { test.semaphore += 1; config.blocking = true; // Set a recovery timeout, if so configured. if (defined.setTimeout) { var timeoutDuration = void 0; if (typeof test.timeout === "number") { timeoutDuration = test.timeout; } else if (typeof config.testTimeout === "number") { timeoutDuration = config.testTimeout; } if (typeof timeoutDuration === "number" && timeoutDuration > 0) { clearTimeout(config.timeout); config.timeout = setTimeout(function () { pushFailure("Test took longer than " + timeoutDuration + "ms; test timed out.", sourceFromStacktrace(2)); internalRecover(test); }, timeoutDuration); } } var released = false; return function resume() { if (released) { return; } released = true; test.semaphore -= 1; internalStart(test); }; }
javascript
{ "resource": "" }
q49713
internalStart
train
function internalStart(test) { // If semaphore is non-numeric, throw error if (isNaN(test.semaphore)) { test.semaphore = 0; pushFailure("Invalid value on test.semaphore", sourceFromStacktrace(2)); return; } // Don't start until equal number of stop-calls if (test.semaphore > 0) { return; } // Throw an Error if start is called more often than stop if (test.semaphore < 0) { test.semaphore = 0; pushFailure("Tried to restart test while already started (test's semaphore was 0 already)", sourceFromStacktrace(2)); return; } // Add a slight delay to allow more assertions etc. if (defined.setTimeout) { if (config.timeout) { clearTimeout(config.timeout); } config.timeout = setTimeout(function () { if (test.semaphore > 0) { return; } if (config.timeout) { clearTimeout(config.timeout); } begin(); }, 13); } else { begin(); } }
javascript
{ "resource": "" }
q49714
onError
train
function onError(error) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (config.current) { if (config.current.ignoreGlobalErrors) { return true; } pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args)); } else { test("global failure", extend(function () { pushFailure.apply(undefined, [error.message, error.fileName + ":" + error.lineNumber].concat(args)); }, { validTest: true })); } return false; }
javascript
{ "resource": "" }
q49715
storeFixture
train
function storeFixture() { // Avoid overwriting user-defined values if (hasOwn.call(config, "fixture")) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { config.fixture = fixture.innerHTML; } }
javascript
{ "resource": "" }
q49716
resetFixture
train
function resetFixture() { if (config.fixture == null) { return; } var fixture = document.getElementById("qunit-fixture"); if (fixture) { fixture.innerHTML = config.fixture; } }
javascript
{ "resource": "" }
q49717
train
function (lang, elt) { var data = lang_data[lang]; if (!data) { data = lang_data[lang] = {}; } // Look for additional dependencies defined on the <code> or <pre> tags var deps = elt.getAttribute('data-dependencies'); if (!deps && elt.parentNode && elt.parentNode.tagName.toLowerCase() === 'pre') { deps = elt.parentNode.getAttribute('data-dependencies'); } if (deps) { deps = deps.split(/\s*,\s*/g); } else { deps = []; } loadLanguages(deps, function () { loadLanguage(lang, function () { Prism.highlightElement(elt); }); }); }
javascript
{ "resource": "" }
q49718
train
function (langs, success, error) { if (typeof langs === 'string') { langs = [langs]; } var i = 0; var l = langs.length; var f = function () { if (i < l) { loadLanguage(langs[i], function () { i++; f(); }, function () { error && error(langs[i]); }); } else if (i === l) { success && success(langs); } }; f(); }
javascript
{ "resource": "" }
q49719
train
function (lang, success, error) { var load = function () { var force = false; // Do we want to force reload the grammar? if (lang.indexOf('!') >= 0) { force = true; lang = lang.replace('!', ''); } var data = lang_data[lang]; if (!data) { data = lang_data[lang] = {}; } if (success) { if (!data.success_callbacks) { data.success_callbacks = []; } data.success_callbacks.push(success); } if (error) { if (!data.error_callbacks) { data.error_callbacks = []; } data.error_callbacks.push(error); } if (!force && Prism.languages[lang]) { languageSuccess(lang); } else if (!force && data.error) { languageError(lang); } else if (force || !data.loading) { data.loading = true; var src = getLanguagePath(lang); script(src, function () { data.loading = false; languageSuccess(lang); }, function () { data.loading = false; data.error = true; languageError(lang); }); } }; var dependencies = lang_dependencies[lang]; if(dependencies && dependencies.length) { loadLanguages(dependencies, load); } else { load(); } }
javascript
{ "resource": "" }
q49720
train
function (lang) { if (lang_data[lang] && lang_data[lang].success_callbacks && lang_data[lang].success_callbacks.length) { lang_data[lang].success_callbacks.forEach(function (f) { f(lang); }); } }
javascript
{ "resource": "" }
q49721
train
function (lang) { if (lang_data[lang] && lang_data[lang].error_callbacks && lang_data[lang].error_callbacks.length) { lang_data[lang].error_callbacks.forEach(function (f) { f(lang); }); } }
javascript
{ "resource": "" }
q49722
train
function(plugin, name) { // Object key to use when adding to global Foundation object // Examples: Foundation.Reveal, Foundation.OffCanvas var className = (name || functionName(plugin)); // Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin // Examples: data-reveal, data-off-canvas var attrName = hyphenate(className); // Add to the Foundation object and the plugins list (for reflowing) this._plugins[attrName] = this[className] = plugin; }
javascript
{ "resource": "" }
q49723
train
function (func, delay) { var timer = null; return function () { var context = this, args = arguments; if (timer === null) { timer = setTimeout(function () { func.apply(context, args); timer = null; }, delay); } }; }
javascript
{ "resource": "" }
q49724
functionName
train
function functionName(fn) { if (Function.prototype.name === undefined) { var funcNameRegex = /function\s([^(]{1,})\(/; var results = (funcNameRegex).exec((fn).toString()); return (results && results.length > 1) ? results[1].trim() : ""; } else if (fn.prototype === undefined) { return fn.constructor.name; } else { return fn.prototype.constructor.name; } }
javascript
{ "resource": "" }
q49725
GetYoDigits
train
function GetYoDigits(length, namespace){ length = length || 6; return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1) + (namespace ? `-${namespace}` : ''); }
javascript
{ "resource": "" }
q49726
ResponsiveAccordionTabs
train
function ResponsiveAccordionTabs(element, options) { _classCallCheck(this, ResponsiveAccordionTabs); this.$element = $(element); this.options = $.extend({}, this.$element.data(), options); this.rules = this.$element.data('responsive-accordion-tabs'); this.currentMq = null; this.currentPlugin = null; if (!this.$element.attr('id')) { this.$element.attr('id', Foundation.GetYoDigits(6, 'responsiveaccordiontabs')); }; this._init(); this._events(); Foundation.registerPlugin(this, 'ResponsiveAccordionTabs'); }
javascript
{ "resource": "" }
q49727
advance
train
function advance() { const start = now(); config.depth = ( config.depth || 0 ) + 1; while ( config.queue.length && !config.blocking ) { const elapsedTime = now() - start; if ( !defined.setTimeout || config.updateRate <= 0 || elapsedTime < config.updateRate ) { if ( priorityCount > 0 ) { priorityCount--; } config.queue.shift()(); } else { setTimeout( advance, 13 ); break; } } config.depth--; if ( !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } }
javascript
{ "resource": "" }
q49728
addToQueue
train
function addToQueue( callback, prioritize, seed ) { if ( prioritize ) { config.queue.splice( priorityCount++, 0, callback ); } else if ( seed ) { if ( !unitSampler ) { unitSampler = unitSamplerGenerator( seed ); } // Insert into a random position after all prioritized items const index = Math.floor( unitSampler() * ( config.queue.length - priorityCount + 1 ) ); config.queue.splice( priorityCount + index, 0, callback ); } else { config.queue.push( callback ); } }
javascript
{ "resource": "" }
q49729
unitSamplerGenerator
train
function unitSamplerGenerator( seed ) { // 32-bit xorshift, requires only a nonzero seed // http://excamera.com/sphinx/article-xorshift.html let sample = parseInt( generateHash( seed ), 16 ) || -1; return function() { sample ^= sample << 13; sample ^= sample >>> 17; sample ^= sample << 5; // ECMAScript has no unsigned number type if ( sample < 0 ) { sample += 0x100000000; } return sample / 0x100000000; }; }
javascript
{ "resource": "" }
q49730
loadLanguage
train
function loadLanguage (lang) { // at first we need to fetch all dependencies for the main language // Note: we need to do this, even if the main language already is loaded (just to be sure..) // // We load an array of all dependencies and call recursively this function on each entry // // dependencies is now an (possibly empty) array of loading-promises var dependencies = getDependenciesOfLanguage(lang).map(loadLanguage); // We create a promise, which will resolve, as soon as all dependencies are loaded. // They need to be fully loaded because the main language may extend them. return Promise.all(dependencies) .then(function () { // If the main language itself isn't already loaded, load it now // and return the newly created promise (we chain the promises). // If the language is already loaded, just do nothing - the next .then() // will immediately be called if (!Prism.languages[lang]) { return new Promise(function (resolve) { $u.script('components/prism-' + lang + '.js', resolve); }); } }); }
javascript
{ "resource": "" }
q49731
getMultipleSelectors
train
function getMultipleSelectors(selector) { if (Array.isArray(selector)) { var section_selector = selector[0].selector; var real_selector = selector[1].selector; return [section_selector, real_selector]; } else { return selector; } }
javascript
{ "resource": "" }
q49732
assertion
train
function assertion(selector, attribute, regexp) { var _this = this; var msg = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; this.message = msg; if (!this.message) { this.message = _util2.default.format('Testing if element <%s> has attribute <%s> that matches %s', selector, attribute, regexp.toString()); } this.expected = regexp; this.pass = function (value) { return _this.expected.test(value); }; this.value = function (result) { if (result.value.error) { console.error(result.value); return ""; } return result.value; }; this.command = function (callback) { return _this.api.getAttribute(selector, attribute, callback); }; }
javascript
{ "resource": "" }
q49733
shouldAnimate
train
function shouldAnimate () { // Don’t animate while dragging if (pointerIsDown) return false const finished = current === target && Math.abs(currentSpeed) < 0.5 return !finished }
javascript
{ "resource": "" }
q49734
update
train
function update () { const bestSpeed = (target - current) * springK currentSpeed = linearlyApproach(currentSpeed, bestSpeed, acceleration) current += currentSpeed if (Math.abs(current - target) < 0.1) { current = target } }
javascript
{ "resource": "" }
q49735
linearlyApproach
train
function linearlyApproach (current, target, delta) { if (Math.abs(current - target) < delta) { return target } else if (current < target) { return current + delta } else { return current - delta } }
javascript
{ "resource": "" }
q49736
getProjection
train
function getProjection () { let projection = current let speed = currentSpeed for (let i = 0; i < 600; i++) { const targetSpeed = speed * (1 - springK) speed = linearlyApproach(speed, targetSpeed, acceleration) projection += speed } return projection }
javascript
{ "resource": "" }
q49737
getTargetAngle
train
function getTargetAngle (projection, flipped) { const offset = flipped ? 180 : 0 return Math.round((projection - offset - 1) / 360) * 360 + offset }
javascript
{ "resource": "" }
q49738
getAllTags
train
function getAllTags(version, cwd, repo, cb) { var str = 'git for-each-ref --format="%(tag)" --sort=\'*authordate\' refs/tags | sed \'1!G;h;$!d\''; exec(str, {cwd: cwd}, function (err, stdout, stderr) { var output = ''; if (err) { return cb(err); } var stdoutAsString = stdout.toString('utf8'); // Get the latest tag var lastTag = stdoutAsString.split('\n')[0]; getTagDate(lastTag, function (err, tagDateAsString) { if (err) { return cb(err); } output += format('## [%s] -%s\n\n', version, tagDateAsString); output += '### Fixed\n\n'; var str = 'git --no-pager log --pretty="format:- [] %%s (\\`%%an\\`)%%n https://github.com/%s/commit/%H" "%s..HEAD"'; str = format(str, repo, lastTag); exec(str, {cwd: cwd}, function (err, stdout, stderr) { if (err) { return cb(err); } output += stdout; return cb(null, output); }); }); }); }
javascript
{ "resource": "" }
q49739
runChromeDevTools
train
function runChromeDevTools(context) { var data = fs.readFileSync(AUDIT_FILE, 'utf-8'); data = data + ' var configuration = new axs.AuditConfiguration(' + JSON.stringify(context.config.chromeA11YDevTools.auditConfiguration) + '); return axs.Audit.run(configuration);'; var elementPromises = [], elementStringLength = 200; function trimText(text) { if (text.length > elementStringLength) { return text.substring(0, elementStringLength / 2) + ' ... ' + text.substring(text.length - elementStringLength / 2); } else { return text; } } var testHeader = 'Chrome A11Y - '; return browser.executeScriptWithDescription(data, 'a11y developer tool rules').then(function(results) { var audit = results.map(function(result) { var DOMElements = result.elements; if (DOMElements !== undefined) { DOMElements.forEach(function(elem) { // get elements from WebDriver, add to promises array elementPromises.push( elem.getAttribute('outerHTML').then(function(text) { return { code: result.rule.code, list: trimText(text) }; }, function(reason){ return { code: result.rule.code, list: reason }; }) ); }); result.elementCount = DOMElements.length; } return result; }); // Wait for element names to be fetched return q.all(elementPromises).then(function(elementFailures) { return audit.forEach(function(result, index) { if (result.result === 'FAIL') { var label = result.elementCount === 1 ? ' element ' : ' elements '; if (result.rule.severity !== 'Warning' || context.config.chromeA11YDevTools.treatWarningsAsFailures) { result.warning = false; } else { result.warning = true; result.rule.heading = '\x1b[33m(WARNING) ' + result.rule.heading + ' (' + result.elementCount + label + 'failed)'; } result.output = '\n\t\t' + result.elementCount + label + 'failed:'; // match elements returned via promises // by their failure codes elementFailures.forEach(function(element, index) { if (element.code === result.rule.code) { result.output += '\n\t\t' + elementFailures[index].list; } }); result.output += '\n\n\t\t' + result.rule.url; (result.warning ? context.addWarning : context.addFailure)( result.output, {specName: testHeader + result.rule.heading}); } else { context.addSuccess({specName: testHeader + result.rule.heading}); } }); }); }); }
javascript
{ "resource": "" }
q49740
train
function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); }
javascript
{ "resource": "" }
q49741
train
function (msg, src) { /* globals console */ if (TinCan.DEBUG && typeof console !== "undefined" && console.log) { src = src || this.LOG_SRC || "TinCan"; console.log("TinCan." + src + ": " + msg); } }
javascript
{ "resource": "" }
q49742
train
function (stmt, callback) { this.log("sendStatement"); // would prefer to use .bind instead of 'self' var self = this, lrs, statement = this.prepareStatement(stmt), rsCount = this.recordStores.length, i, results = [], callbackWrapper, callbackResults = [] ; if (rsCount > 0) { /* if there is a callback that is a function then we need to wrap that function with a function that becomes the new callback that reduces a closure count of the requests that don't have allowFail set to true and when that number hits zero then the original callback is executed */ if (typeof callback === "function") { callbackWrapper = function (err, xhr) { var args; self.log("sendStatement - callbackWrapper: " + rsCount); if (rsCount > 1) { rsCount -= 1; callbackResults.push( { err: err, xhr: xhr } ); } else if (rsCount === 1) { callbackResults.push( { err: err, xhr: xhr } ); args = [ callbackResults, statement ]; callback.apply(this, args); } else { self.log("sendStatement - unexpected record store count: " + rsCount); } }; } for (i = 0; i < rsCount; i += 1) { lrs = this.recordStores[i]; results.push( lrs.saveStatement(statement, { callback: callbackWrapper }) ); } } else { this.log("[warning] sendStatement: No LRSs added yet (statement not sent)"); if (typeof callback === "function") { callback.apply(this, [ null, statement ]); } } return { statement: statement, results: results }; }
javascript
{ "resource": "" }
q49743
train
function (stmtId, callback, cfg) { this.log("getStatement"); var lrs; cfg = cfg || {}; cfg.params = cfg.params || {}; if (this.recordStores.length > 0) { // // for statements (for now) we only need to read from the first LRS // in the future it may make sense to get all from all LRSes and // compare to remove duplicates or allow inspection of them for differences? // // TODO: make this the first non-allowFail LRS but for now it should // be good enough to make it the first since we know the LMS provided // LRS is the first // lrs = this.recordStores[0]; return lrs.retrieveStatement(stmtId, { callback: callback, params: cfg.params }); } this.log("[warning] getStatement: No LRSs added yet (statement not retrieved)"); }
javascript
{ "resource": "" }
q49744
train
function (stmtId, callback) { this.log("getVoidedStatement"); var lrs; if (this.recordStores.length > 0) { // // for statements (for now) we only need to read from the first LRS // in the future it may make sense to get all from all LRSes and // compare to remove duplicates or allow inspection of them for differences? // // TODO: make this the first non-allowFail LRS but for now it should // be good enough to make it the first since we know the LMS provided // LRS is the first // lrs = this.recordStores[0]; return lrs.retrieveVoidedStatement(stmtId, { callback: callback }); } this.log("[warning] getVoidedStatement: No LRSs added yet (statement not retrieved)"); }
javascript
{ "resource": "" }
q49745
train
function (stmts, callback) { this.log("sendStatements"); var self = this, lrs, statements = [], rsCount = this.recordStores.length, i, results = [], callbackWrapper, callbackResults = [] ; if (stmts.length === 0) { if (typeof callback === "function") { callback.apply(this, [ null, statements ]); } } else { for (i = 0; i < stmts.length; i += 1) { statements.push( this.prepareStatement(stmts[i]) ); } if (rsCount > 0) { /* if there is a callback that is a function then we need to wrap that function with a function that becomes the new callback that reduces a closure count of the requests that don't have allowFail set to true and when that number hits zero then the original callback is executed */ if (typeof callback === "function") { callbackWrapper = function (err, xhr) { var args; self.log("sendStatements - callbackWrapper: " + rsCount); if (rsCount > 1) { rsCount -= 1; callbackResults.push( { err: err, xhr: xhr } ); } else if (rsCount === 1) { callbackResults.push( { err: err, xhr: xhr } ); args = [ callbackResults, statements ]; callback.apply(this, args); } else { self.log("sendStatements - unexpected record store count: " + rsCount); } }; } for (i = 0; i < rsCount; i += 1) { lrs = this.recordStores[i]; results.push( lrs.saveStatements(statements, { callback: callbackWrapper }) ); } } else { this.log("[warning] sendStatements: No LRSs added yet (statements not sent)"); if (typeof callback === "function") { callback.apply(this, [ null, statements ]); } } } return { statements: statements, results: results }; }
javascript
{ "resource": "" }
q49746
train
function (prop, lang) { var langDict = this[prop], key; if (typeof lang !== "undefined" && typeof langDict[lang] !== "undefined") { return langDict[lang]; } if (typeof langDict.und !== "undefined") { return langDict.und; } if (typeof langDict["en-US"] !== "undefined") { return langDict["en-US"]; } for (key in langDict) { if (langDict.hasOwnProperty(key)) { return langDict[key]; } } return ""; }
javascript
{ "resource": "" }
q49747
train
function (cfg) { this.log("sendRequest"); var fullUrl = this.endpoint + cfg.url, headers = {}, prop ; // respect absolute URLs passed in if (cfg.url.indexOf("http") === 0) { fullUrl = cfg.url; } // add extended LMS-specified values to the params if (this.extended !== null) { cfg.params = cfg.params || {}; for (prop in this.extended) { if (this.extended.hasOwnProperty(prop)) { // don't overwrite cfg.params values that have already been added to the request with our extended params if (! cfg.params.hasOwnProperty(prop)) { if (this.extended[prop] !== null) { cfg.params[prop] = this.extended[prop]; } } } } } // consolidate headers headers.Authorization = this.auth; if (this.version !== "0.9") { headers["X-Experience-API-Version"] = this.version; } for (prop in cfg.headers) { if (cfg.headers.hasOwnProperty(prop)) { headers[prop] = cfg.headers[prop]; } } return this._makeRequest(fullUrl, headers, cfg); }
javascript
{ "resource": "" }
q49748
train
function (cfg) { this.log("about"); var requestCfg, requestResult, callbackWrapper; cfg = cfg || {}; requestCfg = { url: "about", method: "GET", params: {} }; if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err === null) { result = TinCan.About.fromJSON(xhr.responseText); } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); if (callbackWrapper) { return; } if (requestResult.err === null) { requestResult.xhr = TinCan.About.fromJSON(requestResult.xhr.responseText); } return requestResult; }
javascript
{ "resource": "" }
q49749
train
function (stmt, cfg) { this.log("saveStatement"); var requestCfg = { url: "statements", headers: {} }, versionedStatement, requestAttachments = [], boundary, i; cfg = cfg || {}; try { versionedStatement = stmt.asVersion( this.version ); } catch (ex) { if (this.allowFail) { this.log("[warning] statement could not be serialized in version (" + this.version + "): " + ex); if (typeof cfg.callback !== "undefined") { cfg.callback(null, null); return; } return { err: null, xhr: null }; } this.log("[error] statement could not be serialized in version (" + this.version + "): " + ex); if (typeof cfg.callback !== "undefined") { cfg.callback(ex, null); return; } return { err: ex, xhr: null }; } if (versionedStatement.hasOwnProperty("attachments") && stmt.hasAttachmentWithContent()) { boundary = this._getBoundary(); requestCfg.headers["Content-Type"] = "multipart/mixed; boundary=" + boundary; for (i = 0; i < stmt.attachments.length; i += 1) { if (stmt.attachments[i].content !== null) { requestAttachments.push(stmt.attachments[i]); } } try { requestCfg.data = this._getMultipartRequestData(boundary, versionedStatement, requestAttachments); } catch (ex) { if (this.allowFail) { this.log("[warning] multipart request data could not be created (attachments probably not supported): " + ex); if (typeof cfg.callback !== "undefined") { cfg.callback(null, null); return; } return { err: null, xhr: null }; } this.log("[error] multipart request data could not be created (attachments probably not supported): " + ex); if (typeof cfg.callback !== "undefined") { cfg.callback(ex, null); return; } return { err: ex, xhr: null }; } } else { requestCfg.headers["Content-Type"] = "application/json"; requestCfg.data = JSON.stringify(versionedStatement); } if (stmt.id !== null) { requestCfg.method = "PUT"; requestCfg.params = { statementId: stmt.id }; } else { requestCfg.method = "POST"; } if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49750
train
function (stmtId, cfg) { this.log("retrieveStatement"); var requestCfg, requestResult, callbackWrapper, lrs = this; cfg = cfg || {}; cfg.params = cfg.params || {}; requestCfg = { url: "statements", method: "GET", params: { statementId: stmtId } }; if (cfg.params.attachments) { requestCfg.params.attachments = true; requestCfg.expectMultipart = true; } if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err === null) { result = lrs._processGetStatementResult(xhr, cfg.params); } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); if (! callbackWrapper) { requestResult.statement = null; if (requestResult.err === null) { requestResult.statement = lrs._processGetStatementResult(requestResult.xhr, cfg.params); } } return requestResult; }
javascript
{ "resource": "" }
q49751
train
function (cfg) { this.log("queryStatements"); var requestCfg, requestResult, callbackWrapper, lrs = this; cfg = cfg || {}; cfg.params = cfg.params || {}; // // if they misconfigured (possibly due to version mismatches) the // query then don't try to send a request at all, rather than give // them invalid results // try { requestCfg = this._queryStatementsRequestCfg(cfg); if (cfg.params.attachments) { requestCfg.expectMultipart = true; } } catch (ex) { this.log("[error] Query statements failed - " + ex); if (typeof cfg.callback !== "undefined") { cfg.callback(ex, {}); } return { err: ex, statementsResult: null }; } if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr, parsedResponse, boundary, statements, attachmentMap = {}, i; if (err === null) { if (! cfg.params.attachments) { result = TinCan.StatementsResult.fromJSON(xhr.responseText); } else { boundary = xhr.getResponseHeader("Content-Type").split("boundary=")[1]; parsedResponse = lrs._parseMultipart(boundary, xhr.response); statements = JSON.parse(parsedResponse[0].body); for (i = 1; i < parsedResponse.length; i += 1) { attachmentMap[parsedResponse[i].headers["X-Experience-API-Hash"]] = parsedResponse[i].body; } lrs._assignAttachmentContent(statements.statements, attachmentMap); result = new TinCan.StatementsResult({ statements: statements.statements }); for (i = 0; i < result.statements.length; i += 1) { if (! (result.statements[i] instanceof TinCan.Statement)) { result.statements[i] = new TinCan.Statement(result.statements[i]); } } } } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); requestResult.config = requestCfg; if (! callbackWrapper) { requestResult.statementsResult = null; if (requestResult.err === null) { requestResult.statementsResult = TinCan.StatementsResult.fromJSON(requestResult.xhr.responseText); } } return requestResult; }
javascript
{ "resource": "" }
q49752
train
function (cfg) { this.log("moreStatements: " + cfg.url); var requestCfg, requestResult, callbackWrapper, parsedURL, serverRoot; cfg = cfg || {}; // to support our interface (to support IE) we need to break apart // the more URL query params so that the request can be made properly later parsedURL = TinCan.Utils.parseURL(cfg.url, { allowRelative: true }); // Respect a more URL that is relative to either the server root // or endpoint (though only the former is allowed in the spec) serverRoot = TinCan.Utils.getServerRoot(this.endpoint); if (parsedURL.path.indexOf("/statements") === 0){ parsedURL.path = this.endpoint.replace(serverRoot, "") + parsedURL.path; this.log("converting non-standard more URL to " + parsedURL.path); } // The more relative URL might not start with a slash, add it if not if (parsedURL.path.indexOf("/") !== 0) { parsedURL.path = "/" + parsedURL.path; } requestCfg = { method: "GET", // For arbitrary more URLs to work, we need to make the URL absolute here url: serverRoot + parsedURL.path, params: parsedURL.params }; if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err === null) { result = TinCan.StatementsResult.fromJSON(xhr.responseText); } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); requestResult.config = requestCfg; if (! callbackWrapper) { requestResult.statementsResult = null; if (requestResult.err === null) { requestResult.statementsResult = TinCan.StatementsResult.fromJSON(requestResult.xhr.responseText); } } return requestResult; }
javascript
{ "resource": "" }
q49753
train
function (key, cfg) { this.log("retrieveState"); var requestParams = {}, requestCfg = {}, requestResult, callbackWrapper, requestHeaders, self = this; requestHeaders = cfg.requestHeaders || {}; requestParams = { stateId: key, activityId: cfg.activity.id }; if (this.version === "0.9") { requestParams.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestParams.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if ((typeof cfg.registration !== "undefined") && (cfg.registration !== null)) { if (this.version === "0.9") { requestParams.registrationId = cfg.registration; } else { requestParams.registration = cfg.registration; } } requestCfg = { url: "activities/state", method: "GET", params: requestParams, ignore404: true, headers: requestHeaders }; if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err === null) { if (xhr.status === 404) { result = null; } else { result = new TinCan.State( { id: key, contents: xhr.responseText } ); if (typeof xhr.getResponseHeader !== "undefined" && xhr.getResponseHeader("ETag") !== null && xhr.getResponseHeader("ETag") !== "") { result.etag = xhr.getResponseHeader("ETag"); } else { // // either XHR didn't have getResponseHeader (probably cause it is an IE // XDomainRequest object which doesn't) or not populated by LRS so create // the hash ourselves // // the LRS is responsible for quoting the Etag value so we need to mimic // that behavior here as well // result.etag = "\"" + TinCan.Utils.getSHA1String(xhr.responseText) + "\""; } if (typeof xhr.contentType !== "undefined") { // most likely an XDomainRequest which has .contentType, // for the ones that it supports result.contentType = xhr.contentType; } else if (typeof xhr.getResponseHeader !== "undefined" && xhr.getResponseHeader("Content-Type") !== null && xhr.getResponseHeader("Content-Type") !== "") { result.contentType = xhr.getResponseHeader("Content-Type"); } if (TinCan.Utils.isApplicationJSON(result.contentType)) { try { result.contents = JSON.parse(result.contents); } catch (ex) { self.log("retrieveState - failed to deserialize JSON: " + ex); } } } } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); if (! callbackWrapper) { requestResult.state = null; if (requestResult.err === null && requestResult.xhr.status !== 404) { requestResult.state = new TinCan.State( { id: key, contents: requestResult.xhr.responseText } ); if (typeof requestResult.xhr.getResponseHeader !== "undefined" && requestResult.xhr.getResponseHeader("ETag") !== null && requestResult.xhr.getResponseHeader("ETag") !== "") { requestResult.state.etag = requestResult.xhr.getResponseHeader("ETag"); } else { // // either XHR didn't have getResponseHeader (probably cause it is an IE // XDomainRequest object which doesn't) or not populated by LRS so create // the hash ourselves // // the LRS is responsible for quoting the Etag value so we need to mimic // that behavior here as well // requestResult.state.etag = "\"" + TinCan.Utils.getSHA1String(requestResult.xhr.responseText) + "\""; } if (typeof requestResult.xhr.contentType !== "undefined") { // most likely an XDomainRequest which has .contentType // for the ones that it supports requestResult.state.contentType = requestResult.xhr.contentType; } else if (typeof requestResult.xhr.getResponseHeader !== "undefined" && requestResult.xhr.getResponseHeader("Content-Type") !== null && requestResult.xhr.getResponseHeader("Content-Type") !== "") { requestResult.state.contentType = requestResult.xhr.getResponseHeader("Content-Type"); } if (TinCan.Utils.isApplicationJSON(requestResult.state.contentType)) { try { requestResult.state.contents = JSON.parse(requestResult.state.contents); } catch (ex) { this.log("retrieveState - failed to deserialize JSON: " + ex); } } } } return requestResult; }
javascript
{ "resource": "" }
q49754
train
function (cfg) { this.log("retrieveStateIds"); var requestParams = {}, requestCfg, requestHeaders, requestResult, callbackWrapper; cfg = cfg || {}; requestHeaders = cfg.requestHeaders || {}; requestParams.activityId = cfg.activity.id; if (this.version === "0.9") { requestParams.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestParams.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if ((typeof cfg.registration !== "undefined") && (cfg.registration !== null)) { if (this.version === "0.9") { requestParams.registrationId = cfg.registration; } else { requestParams.registration = cfg.registration; } } requestCfg = { url: "activities/state", method: "GET", params: requestParams, headers: requestHeaders, ignore404: true }; if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err !== null) { cfg.callback(err, result); return; } if (xhr.status === 404) { result = []; } else { try { result = JSON.parse(xhr.responseText); } catch (ex) { err = "Response JSON parse error: " + ex; } } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } if (typeof cfg.since !== "undefined") { requestCfg.params.since = cfg.since; } requestResult = this.sendRequest(requestCfg); if (! callbackWrapper) { requestResult.profileIds = null; if (requestResult.err !== null) { return requestResult; } if (requestResult.xhr.status === 404) { requestResult.profileIds = []; } else { try { requestResult.profileIds = JSON.parse(requestResult.xhr.responseText); } catch (ex) { requestResult.err = "retrieveStateIds - JSON parse error: " + ex; } } } return requestResult; }
javascript
{ "resource": "" }
q49755
train
function (key, val, cfg) { this.log("saveState"); var requestParams, requestCfg, requestHeaders; requestHeaders = cfg.requestHeaders || {}; if (typeof cfg.contentType === "undefined") { cfg.contentType = "application/octet-stream"; } requestHeaders["Content-Type"] = cfg.contentType; if (typeof val === "object" && TinCan.Utils.isApplicationJSON(cfg.contentType)) { val = JSON.stringify(val); } if (typeof cfg.method === "undefined" || cfg.method !== "POST") { cfg.method = "PUT"; } requestParams = { stateId: key, activityId: cfg.activity.id }; if (this.version === "0.9") { requestParams.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestParams.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if ((typeof cfg.registration !== "undefined") && (cfg.registration !== null)) { if (this.version === "0.9") { requestParams.registrationId = cfg.registration; } else { requestParams.registration = cfg.registration; } } requestCfg = { url: "activities/state", method: cfg.method, params: requestParams, data: val, headers: requestHeaders }; if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } if (typeof cfg.lastSHA1 !== "undefined" && cfg.lastSHA1 !== null) { requestCfg.headers["If-Match"] = cfg.lastSHA1; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49756
train
function (key, cfg) { this.log("dropState"); var requestParams, requestCfg, requestHeaders; requestHeaders = cfg.requestHeaders || {}; requestParams = { activityId: cfg.activity.id }; if (this.version === "0.9") { requestParams.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestParams.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if (key !== null) { requestParams.stateId = key; } if ((typeof cfg.registration !== "undefined") && (cfg.registration !== null)) { if (this.version === "0.9") { requestParams.registrationId = cfg.registration; } else { requestParams.registration = cfg.registration; } } requestCfg = { url: "activities/state", method: "DELETE", params: requestParams, headers: requestHeaders }; if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49757
train
function (activityId, cfg) { this.log("retrieveActivity"); var requestCfg = {}, requestResult, callbackWrapper, requestHeaders; requestHeaders = cfg.requestHeaders || {}; requestCfg = { url: "activities", method: "GET", params: { activityId: activityId }, ignore404: true, headers: requestHeaders }; if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err === null) { // // a 404 really shouldn't happen because the LRS can dynamically // build the response based on what has been passed to it, but // don't have the client fail in the condition that it does, because // we can do the same thing // if (xhr.status === 404) { result = new TinCan.Activity( { id: activityId } ); } else { result = TinCan.Activity.fromJSON(xhr.responseText); } } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); if (! callbackWrapper) { requestResult.activity = null; if (requestResult.err === null) { if (requestResult.xhr.status === 404) { requestResult.activity = new TinCan.Activity( { id: activityId } ); } else { requestResult.activity = TinCan.Activity.fromJSON(requestResult.xhr.responseText); } } } return requestResult; }
javascript
{ "resource": "" }
q49758
train
function (cfg) { this.log("retrieveActivityProfileIds"); var requestCfg, requestHeaders, requestResult, callbackWrapper; cfg = cfg || {}; requestHeaders = cfg.requestHeaders || {}; requestCfg = { url: "activities/profile", method: "GET", params: { activityId: cfg.activity.id }, headers: requestHeaders, ignore404: true }; if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err !== null) { cfg.callback(err, result); return; } if (xhr.status === 404) { result = []; } else { try { result = JSON.parse(xhr.responseText); } catch (ex) { err = "Response JSON parse error: " + ex; } } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } if (typeof cfg.since !== "undefined") { requestCfg.params.since = cfg.since; } requestResult = this.sendRequest(requestCfg); if (! callbackWrapper) { requestResult.profileIds = null; if (requestResult.err !== null) { return requestResult; } if (requestResult.xhr.status === 404) { requestResult.profileIds = []; } else { try { requestResult.profileIds = JSON.parse(requestResult.xhr.responseText); } catch (ex) { requestResult.err = "retrieveActivityProfileIds - JSON parse error: " + ex; } } } return requestResult; }
javascript
{ "resource": "" }
q49759
train
function (key, val, cfg) { this.log("saveActivityProfile"); var requestCfg, requestHeaders; requestHeaders = cfg.requestHeaders || {}; if (typeof cfg.contentType === "undefined") { cfg.contentType = "application/octet-stream"; } requestHeaders["Content-Type"] = cfg.contentType; if (typeof cfg.method === "undefined" || cfg.method !== "POST") { cfg.method = "PUT"; } if (typeof val === "object" && TinCan.Utils.isApplicationJSON(cfg.contentType)) { val = JSON.stringify(val); } requestCfg = { url: "activities/profile", method: cfg.method, params: { profileId: key, activityId: cfg.activity.id }, data: val, headers: requestHeaders }; if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } if (typeof cfg.lastSHA1 !== "undefined" && cfg.lastSHA1 !== null) { requestCfg.headers["If-Match"] = cfg.lastSHA1; } else { requestCfg.headers["If-None-Match"] = "*"; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49760
train
function (key, cfg) { this.log("dropActivityProfile"); var requestParams, requestCfg, requestHeaders; requestHeaders = cfg.requestHeaders || {}; requestParams = { profileId: key, activityId: cfg.activity.id }; requestCfg = { url: "activities/profile", method: "DELETE", params: requestParams, headers: requestHeaders }; if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49761
train
function (key, cfg) { this.log("retrieveAgentProfile"); var requestCfg = {}, requestResult, callbackWrapper, requestHeaders, self = this; requestHeaders = cfg.requestHeaders || {}; requestCfg = { method: "GET", params: { profileId: key }, ignore404: true, headers: requestHeaders }; if (this.version === "0.9") { requestCfg.url = "actors/profile"; requestCfg.params.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestCfg.url = "agents/profile"; requestCfg.params.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if (typeof cfg.callback !== "undefined") { callbackWrapper = function (err, xhr) { var result = xhr; if (err === null) { if (xhr.status === 404) { result = null; } else { result = new TinCan.AgentProfile( { id: key, agent: cfg.agent, contents: xhr.responseText } ); if (typeof xhr.getResponseHeader !== "undefined" && xhr.getResponseHeader("ETag") !== null && xhr.getResponseHeader("ETag") !== "") { result.etag = xhr.getResponseHeader("ETag"); } else { // // either XHR didn't have getResponseHeader (probably cause it is an IE // XDomainRequest object which doesn't) or not populated by LRS so create // the hash ourselves // // the LRS is responsible for quoting the Etag value so we need to mimic // that behavior here as well // result.etag = "\"" + TinCan.Utils.getSHA1String(xhr.responseText) + "\""; } if (typeof xhr.contentType !== "undefined") { // most likely an XDomainRequest which has .contentType // for the ones that it supports result.contentType = xhr.contentType; } else if (typeof xhr.getResponseHeader !== "undefined" && xhr.getResponseHeader("Content-Type") !== null && xhr.getResponseHeader("Content-Type") !== "") { result.contentType = xhr.getResponseHeader("Content-Type"); } if (TinCan.Utils.isApplicationJSON(result.contentType)) { try { result.contents = JSON.parse(result.contents); } catch (ex) { self.log("retrieveAgentProfile - failed to deserialize JSON: " + ex); } } } } cfg.callback(err, result); }; requestCfg.callback = callbackWrapper; } requestResult = this.sendRequest(requestCfg); if (! callbackWrapper) { requestResult.profile = null; if (requestResult.err === null && requestResult.xhr.status !== 404) { requestResult.profile = new TinCan.AgentProfile( { id: key, agent: cfg.agent, contents: requestResult.xhr.responseText } ); if (typeof requestResult.xhr.getResponseHeader !== "undefined" && requestResult.xhr.getResponseHeader("ETag") !== null && requestResult.xhr.getResponseHeader("ETag") !== "") { requestResult.profile.etag = requestResult.xhr.getResponseHeader("ETag"); } else { // // either XHR didn't have getResponseHeader (probably cause it is an IE // XDomainRequest object which doesn't) or not populated by LRS so create // the hash ourselves // // the LRS is responsible for quoting the Etag value so we need to mimic // that behavior here as well // requestResult.profile.etag = "\"" + TinCan.Utils.getSHA1String(requestResult.xhr.responseText) + "\""; } if (typeof requestResult.xhr.contentType !== "undefined") { // most likely an XDomainRequest which has .contentType // for the ones that it supports requestResult.profile.contentType = requestResult.xhr.contentType; } else if (typeof requestResult.xhr.getResponseHeader !== "undefined" && requestResult.xhr.getResponseHeader("Content-Type") !== null && requestResult.xhr.getResponseHeader("Content-Type") !== "") { requestResult.profile.contentType = requestResult.xhr.getResponseHeader("Content-Type"); } if (TinCan.Utils.isApplicationJSON(requestResult.profile.contentType)) { try { requestResult.profile.contents = JSON.parse(requestResult.profile.contents); } catch (ex) { this.log("retrieveAgentProfile - failed to deserialize JSON: " + ex); } } } } return requestResult; }
javascript
{ "resource": "" }
q49762
train
function (key, val, cfg) { this.log("saveAgentProfile"); var requestCfg, requestHeaders; requestHeaders = cfg.requestHeaders || {}; if (typeof cfg.contentType === "undefined") { cfg.contentType = "application/octet-stream"; } requestHeaders["Content-Type"] = cfg.contentType; if (typeof cfg.method === "undefined" || cfg.method !== "POST") { cfg.method = "PUT"; } if (typeof val === "object" && TinCan.Utils.isApplicationJSON(cfg.contentType)) { val = JSON.stringify(val); } requestCfg = { method: cfg.method, params: { profileId: key }, data: val, headers: requestHeaders }; if (this.version === "0.9") { requestCfg.url = "actors/profile"; requestCfg.params.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestCfg.url = "agents/profile"; requestCfg.params.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } if (typeof cfg.lastSHA1 !== "undefined" && cfg.lastSHA1 !== null) { requestCfg.headers["If-Match"] = cfg.lastSHA1; } else { requestCfg.headers["If-None-Match"] = "*"; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49763
train
function (key, cfg) { this.log("dropAgentProfile"); var requestParams, requestCfg, requestHeaders; requestHeaders = cfg.requestHeaders || {}; requestParams = { profileId: key }; requestCfg = { method: "DELETE", params: requestParams, headers: requestHeaders }; if (this.version === "0.9") { requestCfg.url = "actors/profile"; requestParams.actor = JSON.stringify(cfg.agent.asVersion(this.version)); } else { requestCfg.url = "agents/profile"; requestParams.agent = JSON.stringify(cfg.agent.asVersion(this.version)); } if (typeof cfg.callback !== "undefined") { requestCfg.callback = cfg.callback; } return this.sendRequest(requestCfg); }
javascript
{ "resource": "" }
q49764
train
function () { this.log("hasAttachmentWithContent"); var i; if (this.attachments === null) { return false; } for (i = 0; i < this.attachments.length; i += 1) { if (this.attachments[i].content !== null) { return true; } } return false; }
javascript
{ "resource": "" }
q49765
train
function(token) { if (Array.isArray(token)) { var tokens = /**@type {!Array.<number>}*/(token); while (tokens.length) this.tokens.push(tokens.pop()); } else { this.tokens.push(token); } }
javascript
{ "resource": "" }
q49766
train
function(token) { if (Array.isArray(token)) { var tokens = /**@type {!Array.<number>}*/(token); while (tokens.length) this.tokens.unshift(tokens.shift()); } else { this.tokens.unshift(token); } }
javascript
{ "resource": "" }
q49767
TextDecoder
train
function TextDecoder(label, options) { // Web IDL conventions if (!(this instanceof TextDecoder)) throw TypeError('Called as a function. Did you forget \'new\'?'); label = label !== undefined ? String(label) : DEFAULT_ENCODING; options = ToDictionary(options); // A TextDecoder object has an associated encoding, decoder, // stream, ignore BOM flag (initially unset), BOM seen flag // (initially unset), error mode (initially replacement), and do // not flush flag (initially unset). /** @private */ this._encoding = null; /** @private @type {?Decoder} */ this._decoder = null; /** @private @type {boolean} */ this._ignoreBOM = false; /** @private @type {boolean} */ this._BOMseen = false; /** @private @type {string} */ this._error_mode = 'replacement'; /** @private @type {boolean} */ this._do_not_flush = false; // 1. Let encoding be the result of getting an encoding from // label. var encoding = getEncoding(label); // 2. If encoding is failure or replacement, throw a RangeError. if (encoding === null || encoding.name === 'replacement') throw RangeError('Unknown encoding: ' + label); if (!decoders[encoding.name]) { throw Error('Decoder not present.' + ' Did you forget to include encoding-indexes.js?'); } // 3. Let dec be a new TextDecoder object. var dec = this; // 4. Set dec's encoding to encoding. dec._encoding = encoding; // 5. If options's fatal member is true, set dec's error mode to // fatal. if (Boolean(options['fatal'])) dec._error_mode = 'fatal'; // 6. If options's ignoreBOM member is true, set dec's ignore BOM // flag. if (Boolean(options['ignoreBOM'])) dec._ignoreBOM = true; // For pre-ES5 runtimes: if (!Object.defineProperty) { this.encoding = dec._encoding.name.toLowerCase(); this.fatal = dec._error_mode === 'fatal'; this.ignoreBOM = dec._ignoreBOM; } // 7. Return dec. return dec; }
javascript
{ "resource": "" }
q49768
serializeStream
train
function serializeStream(stream) { // 1. Let token be the result of reading from stream. // (Done in-place on array, rather than as a stream) // 2. If encoding is UTF-8, UTF-16BE, or UTF-16LE, and ignore // BOM flag and BOM seen flag are unset, run these subsubsteps: if (includes(['UTF-8', 'UTF-16LE', 'UTF-16BE'], this._encoding.name) && !this._ignoreBOM && !this._BOMseen) { if (stream.length > 0 && stream[0] === 0xFEFF) { // 1. If token is U+FEFF, set BOM seen flag. this._BOMseen = true; stream.shift(); } else if (stream.length > 0) { // 2. Otherwise, if token is not end-of-stream, set BOM seen // flag and append token to stream. this._BOMseen = true; } else { // 3. Otherwise, if token is not end-of-stream, append token // to output. // (no-op) } } // 4. Otherwise, return output. return codePointsToString(stream); }
javascript
{ "resource": "" }
q49769
TextEncoder
train
function TextEncoder(label, options) { // Web IDL conventions if (!(this instanceof TextEncoder)) throw TypeError('Called as a function. Did you forget \'new\'?'); options = ToDictionary(options); // A TextEncoder object has an associated encoding and encoder. /** @private */ this._encoding = null; /** @private @type {?Encoder} */ this._encoder = null; // Non-standard /** @private @type {boolean} */ this._do_not_flush = false; /** @private @type {string} */ this._fatal = Boolean(options['fatal']) ? 'fatal' : 'replacement'; // 1. Let enc be a new TextEncoder object. var enc = this; // 2. Set enc's encoding to UTF-8's encoder. if (Boolean(options['NONSTANDARD_allowLegacyEncoding'])) { // NONSTANDARD behavior. label = label !== undefined ? String(label) : DEFAULT_ENCODING; var encoding = getEncoding(label); if (encoding === null || encoding.name === 'replacement') throw RangeError('Unknown encoding: ' + label); if (!encoders[encoding.name]) { throw Error('Encoder not present.' + ' Did you forget to include encoding-indexes.js?'); } enc._encoding = encoding; } else { // Standard behavior. enc._encoding = getEncoding('utf-8'); if (label !== undefined && 'console' in global) { console.warn('TextEncoder constructor called with encoding label, ' + 'which is ignored.'); } } // For pre-ES5 runtimes: if (!Object.defineProperty) this.encoding = enc._encoding.name.toLowerCase(); // 3. Return enc. return enc; }
javascript
{ "resource": "" }
q49770
UTF8Encoder
train
function UTF8Encoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007f)) return code_point; // 3. Set count and offset based on the range code point is in: var count, offset; // U+0080 to U+07FF, inclusive: if (inRange(code_point, 0x0080, 0x07FF)) { // 1 and 0xC0 count = 1; offset = 0xC0; } // U+0800 to U+FFFF, inclusive: else if (inRange(code_point, 0x0800, 0xFFFF)) { // 2 and 0xE0 count = 2; offset = 0xE0; } // U+10000 to U+10FFFF, inclusive: else if (inRange(code_point, 0x10000, 0x10FFFF)) { // 3 and 0xF0 count = 3; offset = 0xF0; } // 4.Let bytes be a byte sequence whose first byte is (code // point >> (6 × count)) + offset. var bytes = [(code_point >> (6 * count)) + offset]; // 5. Run these substeps while count is greater than 0: while (count > 0) { // 1. Set temp to code point >> (6 × (count − 1)). var temp = code_point >> (6 * (count - 1)); // 2. Append to bytes 0x80 | (temp & 0x3F). bytes.push(0x80 | (temp & 0x3F)); // 3. Decrease count by one. count -= 1; } // 6. Return bytes bytes, in order. return bytes; }; }
javascript
{ "resource": "" }
q49771
SingleByteDecoder
train
function SingleByteDecoder(index, options) { var fatal = options.fatal; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream, return finished. if (bite === end_of_stream) return finished; // 2. If byte is an ASCII byte, return a code point whose value // is byte. if (isASCIIByte(bite)) return bite; // 3. Let code point be the index code point for byte − 0x80 in // index single-byte. var code_point = index[bite - 0x80]; // 4. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 5. Return a code point whose value is code point. return code_point; }; }
javascript
{ "resource": "" }
q49772
GB18030Decoder
train
function GB18030Decoder(options) { var fatal = options.fatal; // gb18030's decoder has an associated gb18030 first, gb18030 // second, and gb18030 third (all initially 0x00). var /** @type {number} */ gb18030_first = 0x00, /** @type {number} */ gb18030_second = 0x00, /** @type {number} */ gb18030_third = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and gb18030 first, gb18030 // second, and gb18030 third are 0x00, return finished. if (bite === end_of_stream && gb18030_first === 0x00 && gb18030_second === 0x00 && gb18030_third === 0x00) { return finished; } // 2. If byte is end-of-stream, and gb18030 first, gb18030 // second, or gb18030 third is not 0x00, set gb18030 first, // gb18030 second, and gb18030 third to 0x00, and return error. if (bite === end_of_stream && (gb18030_first !== 0x00 || gb18030_second !== 0x00 || gb18030_third !== 0x00)) { gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; decoderError(fatal); } var code_point; // 3. If gb18030 third is not 0x00, run these substeps: if (gb18030_third !== 0x00) { // 1. Let code point be null. code_point = null; // 2. If byte is in the range 0x30 to 0x39, set code point to // the index gb18030 ranges code point for (((gb18030 first − // 0x81) × 10 + gb18030 second − 0x30) × 126 + gb18030 third − // 0x81) × 10 + byte − 0x30. if (inRange(bite, 0x30, 0x39)) { code_point = indexGB18030RangesCodePointFor( (((gb18030_first - 0x81) * 10 + (gb18030_second - 0x30)) * 126 + (gb18030_third - 0x81)) * 10 + bite - 0x30); } // 3. Let buffer be a byte sequence consisting of gb18030 // second, gb18030 third, and byte, in order. var buffer = [gb18030_second, gb18030_third, bite]; // 4. Set gb18030 first, gb18030 second, and gb18030 third to // 0x00. gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; // 5. If code point is null, prepend buffer to stream and // return error. if (code_point === null) { stream.prepend(buffer); return decoderError(fatal); } // 6. Return a code point whose value is code point. return code_point; } // 4. If gb18030 second is not 0x00, run these substeps: if (gb18030_second !== 0x00) { // 1. If byte is in the range 0x81 to 0xFE, set gb18030 third // to byte and return continue. if (inRange(bite, 0x81, 0xFE)) { gb18030_third = bite; return null; } // 2. Prepend gb18030 second followed by byte to stream, set // gb18030 first and gb18030 second to 0x00, and return error. stream.prepend([gb18030_second, bite]); gb18030_first = 0x00; gb18030_second = 0x00; return decoderError(fatal); } // 5. If gb18030 first is not 0x00, run these substeps: if (gb18030_first !== 0x00) { // 1. If byte is in the range 0x30 to 0x39, set gb18030 second // to byte and return continue. if (inRange(bite, 0x30, 0x39)) { gb18030_second = bite; return null; } // 2. Let lead be gb18030 first, let pointer be null, and set // gb18030 first to 0x00. var lead = gb18030_first; var pointer = null; gb18030_first = 0x00; // 3. Let offset be 0x40 if byte is less than 0x7F and 0x41 // otherwise. var offset = bite < 0x7F ? 0x40 : 0x41; // 4. If byte is in the range 0x40 to 0x7E or 0x80 to 0xFE, // set pointer to (lead − 0x81) × 190 + (byte − offset). if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) pointer = (lead - 0x81) * 190 + (bite - offset); // 5. Let code point be null if pointer is null and the index // code point for pointer in index gb18030 otherwise. code_point = pointer === null ? null : indexCodePointFor(pointer, index('gb18030')); // 6. If code point is null and byte is an ASCII byte, prepend // byte to stream. if (code_point === null && isASCIIByte(bite)) stream.prepend(bite); // 7. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 8. Return a code point whose value is code point. return code_point; } // 6. If byte is an ASCII byte, return a code point whose value // is byte. if (isASCIIByte(bite)) return bite; // 7. If byte is 0x80, return code point U+20AC. if (bite === 0x80) return 0x20AC; // 8. If byte is in the range 0x81 to 0xFE, set gb18030 first to // byte and return continue. if (inRange(bite, 0x81, 0xFE)) { gb18030_first = bite; return null; } // 9. Return error. return decoderError(fatal); }; }
javascript
{ "resource": "" }
q49773
GB18030Encoder
train
function GB18030Encoder(options, gbk_flag) { var fatal = options.fatal; // gb18030's decoder has an associated gbk flag (initially unset). /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is an ASCII code point, return a byte whose // value is code point. if (isASCIICodePoint(code_point)) return code_point; // 3. If code point is U+E5E5, return error with code point. if (code_point === 0xE5E5) return encoderError(code_point); // 4. If the gbk flag is set and code point is U+20AC, return // byte 0x80. if (gbk_flag && code_point === 0x20AC) return 0x80; // 5. Let pointer be the index pointer for code point in index // gb18030. var pointer = indexPointerFor(code_point, index('gb18030')); // 6. If pointer is not null, run these substeps: if (pointer !== null) { // 1. Let lead be floor(pointer / 190) + 0x81. var lead = floor(pointer / 190) + 0x81; // 2. Let trail be pointer % 190. var trail = pointer % 190; // 3. Let offset be 0x40 if trail is less than 0x3F and 0x41 otherwise. var offset = trail < 0x3F ? 0x40 : 0x41; // 4. Return two bytes whose values are lead and trail + offset. return [lead, trail + offset]; } // 7. If gbk flag is set, return error with code point. if (gbk_flag) return encoderError(code_point); // 8. Set pointer to the index gb18030 ranges pointer for code // point. pointer = indexGB18030RangesPointerFor(code_point); // 9. Let byte1 be floor(pointer / 10 / 126 / 10). var byte1 = floor(pointer / 10 / 126 / 10); // 10. Set pointer to pointer − byte1 × 10 × 126 × 10. pointer = pointer - byte1 * 10 * 126 * 10; // 11. Let byte2 be floor(pointer / 10 / 126). var byte2 = floor(pointer / 10 / 126); // 12. Set pointer to pointer − byte2 × 10 × 126. pointer = pointer - byte2 * 10 * 126; // 13. Let byte3 be floor(pointer / 10). var byte3 = floor(pointer / 10); // 14. Let byte4 be pointer − byte3 × 10. var byte4 = pointer - byte3 * 10; // 15. Return four bytes whose values are byte1 + 0x81, byte2 + // 0x30, byte3 + 0x81, byte4 + 0x30. return [byte1 + 0x81, byte2 + 0x30, byte3 + 0x81, byte4 + 0x30]; }; }
javascript
{ "resource": "" }
q49774
Big5Decoder
train
function Big5Decoder(options) { var fatal = options.fatal; // big5's decoder has an associated big5 lead (initially 0x00). var /** @type {number} */ big5_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and big5 lead is not 0x00, set // big5 lead to 0x00 and return error. if (bite === end_of_stream && big5_lead !== 0x00) { big5_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and big5 lead is 0x00, return // finished. if (bite === end_of_stream && big5_lead === 0x00) return finished; // 3. If big5 lead is not 0x00, let lead be big5 lead, let // pointer be null, set big5 lead to 0x00, and then run these // substeps: if (big5_lead !== 0x00) { var lead = big5_lead; var pointer = null; big5_lead = 0x00; // 1. Let offset be 0x40 if byte is less than 0x7F and 0x62 // otherwise. var offset = bite < 0x7F ? 0x40 : 0x62; // 2. If byte is in the range 0x40 to 0x7E or 0xA1 to 0xFE, // set pointer to (lead − 0x81) × 157 + (byte − offset). if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) pointer = (lead - 0x81) * 157 + (bite - offset); // 3. If there is a row in the table below whose first column // is pointer, return the two code points listed in its second // column // Pointer | Code points // --------+-------------- // 1133 | U+00CA U+0304 // 1135 | U+00CA U+030C // 1164 | U+00EA U+0304 // 1166 | U+00EA U+030C switch (pointer) { case 1133: return [0x00CA, 0x0304]; case 1135: return [0x00CA, 0x030C]; case 1164: return [0x00EA, 0x0304]; case 1166: return [0x00EA, 0x030C]; } // 4. Let code point be null if pointer is null and the index // code point for pointer in index big5 otherwise. var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('big5')); // 5. If code point is null and byte is an ASCII byte, prepend // byte to stream. if (code_point === null && isASCIIByte(bite)) stream.prepend(bite); // 6. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 7. Return a code point whose value is code point. return code_point; } // 4. If byte is an ASCII byte, return a code point whose value // is byte. if (isASCIIByte(bite)) return bite; // 5. If byte is in the range 0x81 to 0xFE, set big5 lead to // byte and return continue. if (inRange(bite, 0x81, 0xFE)) { big5_lead = bite; return null; } // 6. Return error. return decoderError(fatal); }; }
javascript
{ "resource": "" }
q49775
Big5Encoder
train
function Big5Encoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is an ASCII code point, return a byte whose // value is code point. if (isASCIICodePoint(code_point)) return code_point; // 3. Let pointer be the index big5 pointer for code point. var pointer = indexBig5PointerFor(code_point); // 4. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 5. Let lead be floor(pointer / 157) + 0x81. var lead = floor(pointer / 157) + 0x81; // 6. If lead is less than 0xA1, return error with code point. if (lead < 0xA1) return encoderError(code_point); // 7. Let trail be pointer % 157. var trail = pointer % 157; // 8. Let offset be 0x40 if trail is less than 0x3F and 0x62 // otherwise. var offset = trail < 0x3F ? 0x40 : 0x62; // Return two bytes whose values are lead and trail + offset. return [lead, trail + offset]; }; }
javascript
{ "resource": "" }
q49776
EUCJPDecoder
train
function EUCJPDecoder(options) { var fatal = options.fatal; // euc-jp's decoder has an associated euc-jp jis0212 flag // (initially unset) and euc-jp lead (initially 0x00). var /** @type {boolean} */ eucjp_jis0212_flag = false, /** @type {number} */ eucjp_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and euc-jp lead is not 0x00, set // euc-jp lead to 0x00, and return error. if (bite === end_of_stream && eucjp_lead !== 0x00) { eucjp_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and euc-jp lead is 0x00, return // finished. if (bite === end_of_stream && eucjp_lead === 0x00) return finished; // 3. If euc-jp lead is 0x8E and byte is in the range 0xA1 to // 0xDF, set euc-jp lead to 0x00 and return a code point whose // value is 0xFF61 + byte − 0xA1. if (eucjp_lead === 0x8E && inRange(bite, 0xA1, 0xDF)) { eucjp_lead = 0x00; return 0xFF61 + bite - 0xA1; } // 4. If euc-jp lead is 0x8F and byte is in the range 0xA1 to // 0xFE, set the euc-jp jis0212 flag, set euc-jp lead to byte, // and return continue. if (eucjp_lead === 0x8F && inRange(bite, 0xA1, 0xFE)) { eucjp_jis0212_flag = true; eucjp_lead = bite; return null; } // 5. If euc-jp lead is not 0x00, let lead be euc-jp lead, set // euc-jp lead to 0x00, and run these substeps: if (eucjp_lead !== 0x00) { var lead = eucjp_lead; eucjp_lead = 0x00; // 1. Let code point be null. var code_point = null; // 2. If lead and byte are both in the range 0xA1 to 0xFE, set // code point to the index code point for (lead − 0xA1) × 94 + // byte − 0xA1 in index jis0208 if the euc-jp jis0212 flag is // unset and in index jis0212 otherwise. if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { code_point = indexCodePointFor( (lead - 0xA1) * 94 + (bite - 0xA1), index(!eucjp_jis0212_flag ? 'jis0208' : 'jis0212')); } // 3. Unset the euc-jp jis0212 flag. eucjp_jis0212_flag = false; // 4. If byte is not in the range 0xA1 to 0xFE, prepend byte // to stream. if (!inRange(bite, 0xA1, 0xFE)) stream.prepend(bite); // 5. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 6. Return a code point whose value is code point. return code_point; } // 6. If byte is an ASCII byte, return a code point whose value // is byte. if (isASCIIByte(bite)) return bite; // 7. If byte is 0x8E, 0x8F, or in the range 0xA1 to 0xFE, set // euc-jp lead to byte and return continue. if (bite === 0x8E || bite === 0x8F || inRange(bite, 0xA1, 0xFE)) { eucjp_lead = bite; return null; } // 8. Return error. return decoderError(fatal); }; }
javascript
{ "resource": "" }
q49777
ISO2022JPEncoder
train
function ISO2022JPEncoder(options) { var fatal = options.fatal; // iso-2022-jp's encoder has an associated iso-2022-jp encoder // state which is one of ASCII, Roman, and jis0208 (initially // ASCII). /** @enum */ var states = { ASCII: 0, Roman: 1, jis0208: 2 }; var /** @type {number} */ iso2022jp_state = states.ASCII; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream and iso-2022-jp encoder // state is not ASCII, prepend code point to stream, set // iso-2022-jp encoder state to ASCII, and return three bytes // 0x1B 0x28 0x42. if (code_point === end_of_stream && iso2022jp_state !== states.ASCII) { stream.prepend(code_point); iso2022jp_state = states.ASCII; return [0x1B, 0x28, 0x42]; } // 2. If code point is end-of-stream and iso-2022-jp encoder // state is ASCII, return finished. if (code_point === end_of_stream && iso2022jp_state === states.ASCII) return finished; // 3. If ISO-2022-JP encoder state is ASCII or Roman, and code // point is U+000E, U+000F, or U+001B, return error with U+FFFD. if ((iso2022jp_state === states.ASCII || iso2022jp_state === states.Roman) && (code_point === 0x000E || code_point === 0x000F || code_point === 0x001B)) { return encoderError(0xFFFD); } // 4. If iso-2022-jp encoder state is ASCII and code point is an // ASCII code point, return a byte whose value is code point. if (iso2022jp_state === states.ASCII && isASCIICodePoint(code_point)) return code_point; // 5. If iso-2022-jp encoder state is Roman and code point is an // ASCII code point, excluding U+005C and U+007E, or is U+00A5 // or U+203E, run these substeps: if (iso2022jp_state === states.Roman && ((isASCIICodePoint(code_point) && code_point !== 0x005C && code_point !== 0x007E) || (code_point == 0x00A5 || code_point == 0x203E))) { // 1. If code point is an ASCII code point, return a byte // whose value is code point. if (isASCIICodePoint(code_point)) return code_point; // 2. If code point is U+00A5, return byte 0x5C. if (code_point === 0x00A5) return 0x5C; // 3. If code point is U+203E, return byte 0x7E. if (code_point === 0x203E) return 0x7E; } // 6. If code point is an ASCII code point, and iso-2022-jp // encoder state is not ASCII, prepend code point to stream, set // iso-2022-jp encoder state to ASCII, and return three bytes // 0x1B 0x28 0x42. if (isASCIICodePoint(code_point) && iso2022jp_state !== states.ASCII) { stream.prepend(code_point); iso2022jp_state = states.ASCII; return [0x1B, 0x28, 0x42]; } // 7. If code point is either U+00A5 or U+203E, and iso-2022-jp // encoder state is not Roman, prepend code point to stream, set // iso-2022-jp encoder state to Roman, and return three bytes // 0x1B 0x28 0x4A. if ((code_point === 0x00A5 || code_point === 0x203E) && iso2022jp_state !== states.Roman) { stream.prepend(code_point); iso2022jp_state = states.Roman; return [0x1B, 0x28, 0x4A]; } // 8. If code point is U+2212, set it to U+FF0D. if (code_point === 0x2212) code_point = 0xFF0D; // 9. Let pointer be the index pointer for code point in index // jis0208. var pointer = indexPointerFor(code_point, index('jis0208')); // 10. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 11. If iso-2022-jp encoder state is not jis0208, prepend code // point to stream, set iso-2022-jp encoder state to jis0208, // and return three bytes 0x1B 0x24 0x42. if (iso2022jp_state !== states.jis0208) { stream.prepend(code_point); iso2022jp_state = states.jis0208; return [0x1B, 0x24, 0x42]; } // 12. Let lead be floor(pointer / 94) + 0x21. var lead = floor(pointer / 94) + 0x21; // 13. Let trail be pointer % 94 + 0x21. var trail = pointer % 94 + 0x21; // 14. Return two bytes whose values are lead and trail. return [lead, trail]; }; }
javascript
{ "resource": "" }
q49778
ShiftJISDecoder
train
function ShiftJISDecoder(options) { var fatal = options.fatal; // shift_jis's decoder has an associated shift_jis lead (initially // 0x00). var /** @type {number} */ shiftjis_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and shift_jis lead is not 0x00, // set shift_jis lead to 0x00 and return error. if (bite === end_of_stream && shiftjis_lead !== 0x00) { shiftjis_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and shift_jis lead is 0x00, // return finished. if (bite === end_of_stream && shiftjis_lead === 0x00) return finished; // 3. If shift_jis lead is not 0x00, let lead be shift_jis lead, // let pointer be null, set shift_jis lead to 0x00, and then run // these substeps: if (shiftjis_lead !== 0x00) { var lead = shiftjis_lead; var pointer = null; shiftjis_lead = 0x00; // 1. Let offset be 0x40, if byte is less than 0x7F, and 0x41 // otherwise. var offset = (bite < 0x7F) ? 0x40 : 0x41; // 2. Let lead offset be 0x81, if lead is less than 0xA0, and // 0xC1 otherwise. var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1; // 3. If byte is in the range 0x40 to 0x7E or 0x80 to 0xFC, // set pointer to (lead − lead offset) × 188 + byte − offset. if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) pointer = (lead - lead_offset) * 188 + bite - offset; // 4. Let code point be null, if pointer is null, and the // index code point for pointer in index jis0208 otherwise. var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('jis0208')); // 5. If code point is null and pointer is in the range 8836 // to 10528, return a code point whose value is 0xE000 + // pointer − 8836. if (code_point === null && pointer !== null && inRange(pointer, 8836, 10528)) return 0xE000 + pointer - 8836; // 6. If code point is null and byte is an ASCII byte, prepend // byte to stream. if (code_point === null && isASCIIByte(bite)) stream.prepend(bite); // 7. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 8. Return a code point whose value is code point. return code_point; } // 4. If byte is an ASCII byte or 0x80, return a code point // whose value is byte. if (isASCIIByte(bite) || bite === 0x80) return bite; // 5. If byte is in the range 0xA1 to 0xDF, return a code point // whose value is 0xFF61 + byte − 0xA1. if (inRange(bite, 0xA1, 0xDF)) return 0xFF61 + bite - 0xA1; // 6. If byte is in the range 0x81 to 0x9F or 0xE0 to 0xFC, set // shift_jis lead to byte and return continue. if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) { shiftjis_lead = bite; return null; } // 7. Return error. return decoderError(fatal); }; }
javascript
{ "resource": "" }
q49779
ShiftJISEncoder
train
function ShiftJISEncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is an ASCII code point or U+0080, return a // byte whose value is code point. if (isASCIICodePoint(code_point) || code_point === 0x0080) return code_point; // 3. If code point is U+00A5, return byte 0x5C. if (code_point === 0x00A5) return 0x5C; // 4. If code point is U+203E, return byte 0x7E. if (code_point === 0x203E) return 0x7E; // 5. If code point is in the range U+FF61 to U+FF9F, return a // byte whose value is code point − 0xFF61 + 0xA1. if (inRange(code_point, 0xFF61, 0xFF9F)) return code_point - 0xFF61 + 0xA1; // 6. If code point is U+2212, set it to U+FF0D. if (code_point === 0x2212) code_point = 0xFF0D; // 7. Let pointer be the index shift_jis pointer for code point. var pointer = indexShiftJISPointerFor(code_point); // 8. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 9. Let lead be floor(pointer / 188). var lead = floor(pointer / 188); // 10. Let lead offset be 0x81, if lead is less than 0x1F, and // 0xC1 otherwise. var lead_offset = (lead < 0x1F) ? 0x81 : 0xC1; // 11. Let trail be pointer % 188. var trail = pointer % 188; // 12. Let offset be 0x40, if trail is less than 0x3F, and 0x41 // otherwise. var offset = (trail < 0x3F) ? 0x40 : 0x41; // 13. Return two bytes whose values are lead + lead offset and // trail + offset. return [lead + lead_offset, trail + offset]; }; }
javascript
{ "resource": "" }
q49780
EUCKRDecoder
train
function EUCKRDecoder(options) { var fatal = options.fatal; // euc-kr's decoder has an associated euc-kr lead (initially 0x00). var /** @type {number} */ euckr_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and euc-kr lead is not 0x00, set // euc-kr lead to 0x00 and return error. if (bite === end_of_stream && euckr_lead !== 0) { euckr_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and euc-kr lead is 0x00, return // finished. if (bite === end_of_stream && euckr_lead === 0) return finished; // 3. If euc-kr lead is not 0x00, let lead be euc-kr lead, let // pointer be null, set euc-kr lead to 0x00, and then run these // substeps: if (euckr_lead !== 0x00) { var lead = euckr_lead; var pointer = null; euckr_lead = 0x00; // 1. If byte is in the range 0x41 to 0xFE, set pointer to // (lead − 0x81) × 190 + (byte − 0x41). if (inRange(bite, 0x41, 0xFE)) pointer = (lead - 0x81) * 190 + (bite - 0x41); // 2. Let code point be null, if pointer is null, and the // index code point for pointer in index euc-kr otherwise. var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('euc-kr')); // 3. If code point is null and byte is an ASCII byte, prepend // byte to stream. if (pointer === null && isASCIIByte(bite)) stream.prepend(bite); // 4. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 5. Return a code point whose value is code point. return code_point; } // 4. If byte is an ASCII byte, return a code point whose value // is byte. if (isASCIIByte(bite)) return bite; // 5. If byte is in the range 0x81 to 0xFE, set euc-kr lead to // byte and return continue. if (inRange(bite, 0x81, 0xFE)) { euckr_lead = bite; return null; } // 6. Return error. return decoderError(fatal); }; }
javascript
{ "resource": "" }
q49781
EUCKREncoder
train
function EUCKREncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is an ASCII code point, return a byte whose // value is code point. if (isASCIICodePoint(code_point)) return code_point; // 3. Let pointer be the index pointer for code point in index // euc-kr. var pointer = indexPointerFor(code_point, index('euc-kr')); // 4. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 5. Let lead be floor(pointer / 190) + 0x81. var lead = floor(pointer / 190) + 0x81; // 6. Let trail be pointer % 190 + 0x41. var trail = (pointer % 190) + 0x41; // 7. Return two bytes whose values are lead and trail. return [lead, trail]; }; }
javascript
{ "resource": "" }
q49782
convertCodeUnitToBytes
train
function convertCodeUnitToBytes(code_unit, utf16be) { // 1. Let byte1 be code unit >> 8. var byte1 = code_unit >> 8; // 2. Let byte2 be code unit & 0x00FF. var byte2 = code_unit & 0x00FF; // 3. Then return the bytes in order: // utf-16be flag is set: byte1, then byte2. if (utf16be) return [byte1, byte2]; // utf-16be flag is unset: byte2, then byte1. return [byte2, byte1]; }
javascript
{ "resource": "" }
q49783
UTF16Decoder
train
function UTF16Decoder(utf16_be, options) { var fatal = options.fatal; var /** @type {?number} */ utf16_lead_byte = null, /** @type {?number} */ utf16_lead_surrogate = null; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and either utf-16 lead byte or // utf-16 lead surrogate is not null, set utf-16 lead byte and // utf-16 lead surrogate to null, and return error. if (bite === end_of_stream && (utf16_lead_byte !== null || utf16_lead_surrogate !== null)) { return decoderError(fatal); } // 2. If byte is end-of-stream and utf-16 lead byte and utf-16 // lead surrogate are null, return finished. if (bite === end_of_stream && utf16_lead_byte === null && utf16_lead_surrogate === null) { return finished; } // 3. If utf-16 lead byte is null, set utf-16 lead byte to byte // and return continue. if (utf16_lead_byte === null) { utf16_lead_byte = bite; return null; } // 4. Let code unit be the result of: var code_unit; if (utf16_be) { // utf-16be decoder flag is set // (utf-16 lead byte << 8) + byte. code_unit = (utf16_lead_byte << 8) + bite; } else { // utf-16be decoder flag is unset // (byte << 8) + utf-16 lead byte. code_unit = (bite << 8) + utf16_lead_byte; } // Then set utf-16 lead byte to null. utf16_lead_byte = null; // 5. If utf-16 lead surrogate is not null, let lead surrogate // be utf-16 lead surrogate, set utf-16 lead surrogate to null, // and then run these substeps: if (utf16_lead_surrogate !== null) { var lead_surrogate = utf16_lead_surrogate; utf16_lead_surrogate = null; // 1. If code unit is in the range U+DC00 to U+DFFF, return a // code point whose value is 0x10000 + ((lead surrogate − // 0xD800) << 10) + (code unit − 0xDC00). if (inRange(code_unit, 0xDC00, 0xDFFF)) { return 0x10000 + (lead_surrogate - 0xD800) * 0x400 + (code_unit - 0xDC00); } // 2. Prepend the sequence resulting of converting code unit // to bytes using utf-16be decoder flag to stream and return // error. stream.prepend(convertCodeUnitToBytes(code_unit, utf16_be)); return decoderError(fatal); } // 6. If code unit is in the range U+D800 to U+DBFF, set utf-16 // lead surrogate to code unit and return continue. if (inRange(code_unit, 0xD800, 0xDBFF)) { utf16_lead_surrogate = code_unit; return null; } // 7. If code unit is in the range U+DC00 to U+DFFF, return // error. if (inRange(code_unit, 0xDC00, 0xDFFF)) return decoderError(fatal); // 8. Return code point code unit. return code_unit; }; }
javascript
{ "resource": "" }
q49784
UTF16Encoder
train
function UTF16Encoder(utf16_be, options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+FFFF, return the // sequence resulting of converting code point to bytes using // utf-16be encoder flag. if (inRange(code_point, 0x0000, 0xFFFF)) return convertCodeUnitToBytes(code_point, utf16_be); // 3. Let lead be ((code point − 0x10000) >> 10) + 0xD800, // converted to bytes using utf-16be encoder flag. var lead = convertCodeUnitToBytes( ((code_point - 0x10000) >> 10) + 0xD800, utf16_be); // 4. Let trail be ((code point − 0x10000) & 0x3FF) + 0xDC00, // converted to bytes using utf-16be encoder flag. var trail = convertCodeUnitToBytes( ((code_point - 0x10000) & 0x3FF) + 0xDC00, utf16_be); // 5. Return a byte sequence of lead followed by trail. return lead.concat(trail); }; }
javascript
{ "resource": "" }
q49785
XUserDefinedDecoder
train
function XUserDefinedDecoder(options) { var fatal = options.fatal; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.<number>)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream, return finished. if (bite === end_of_stream) return finished; // 2. If byte is an ASCII byte, return a code point whose value // is byte. if (isASCIIByte(bite)) return bite; // 3. Return a code point whose value is 0xF780 + byte − 0x80. return 0xF780 + bite - 0x80; }; }
javascript
{ "resource": "" }
q49786
XUserDefinedEncoder
train
function XUserDefinedEncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.<number>)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1.If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is an ASCII code point, return a byte whose // value is code point. if (isASCIICodePoint(code_point)) return code_point; // 3. If code point is in the range U+F780 to U+F7FF, return a // byte whose value is code point − 0xF780 + 0x80. if (inRange(code_point, 0xF780, 0xF7FF)) return code_point - 0xF780 + 0x80; // 4. Return error with code point. return encoderError(code_point); }; }
javascript
{ "resource": "" }
q49787
exchangeLR
train
function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; }
javascript
{ "resource": "" }
q49788
train
function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }
javascript
{ "resource": "" }
q49789
train
function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }
javascript
{ "resource": "" }
q49790
validateOptions
train
function validateOptions (options) { if (typeof options.apiKey !== 'string') { throw new Error('You must provide a valid API key to upload sourcemaps to Bugsnag.') } if (typeof options.sourceMap !== 'string') { throw new Error('You must provide a path to the source map you want to upload.') } if (options.addWildcardPrefix && !options.stripProjectRoot) { options.stripProjectRoot = true } if (options.uploadSources && !options.projectRoot) { throw new Error('You must provide a project root when uploading sources. ' + 'The project root is used to generate relative paths to the sources.') } if (options.stripProjectRoot && !options.projectRoot) { throw new Error('You must provide a project root when stripping the root ' + 'path from the source map.') } if (options.projectRoot && !path.isAbsolute(options.projectRoot)) { options.projectRoot = path.resolve(options.projectRoot) } return options }
javascript
{ "resource": "" }
q49791
stripProjectRoot
train
function stripProjectRoot (projectRoot, filePath) { if (typeof filePath === 'string') { // Check whether the path is an posix absolute file, otherwise check whether it's a // win32 valid absolute file. The order is important here because win32 treats posix // absolute paths as absolute, but posix doesn't do the same for win32. const p = path.posix.isAbsolute(filePath) ? path.posix : path.win32.isAbsolute(filePath) ? path.win32 : null if (p) { const relative = p.relative(projectRoot, filePath) if (relative.indexOf('.') !== 0) { return relative } } } return filePath }
javascript
{ "resource": "" }
q49792
readFileJSON
train
function readFileJSON (path) { return new Promise((resolve, reject) => { fs.readFile(path, (err, data) => { if (err) { reject(err) return } try { const json = JSON.parse(String(data)) resolve(json) } catch (err) { reject(err) } }) }) }
javascript
{ "resource": "" }
q49793
transformSourcesMap
train
function transformSourcesMap (options) { return ( readFileJSON(options.sourceMap) .then(sourceMap => ( mapSources(sourceMap, path => { const relativePath = stripProjectRoot(options.projectRoot, path) return doesFileExist(path).then(exists => { if (exists && options.uploadSources) { if (path.indexOf('node_modules') !== -1) { if (options.uploadNodeModules) { options.sources[relativePath] = path } } else { options.sources[relativePath] = path } } return relativePath }) }) )) .then(sourceMap => { // Replace the sourceMap option with a buffer of the modified sourcemap. const tempMap = path.join(options.tempDir, path.basename(options.sourceMap)) fs.writeFileSync(tempMap, JSON.stringify(sourceMap)) // FIXME find out why passing a Buffer instead of a fs.ReadStream throws "maxFieldsSize 2097152 exceeded" options.sourceMap = tempMap return options }) .catch(err => { if (err.name === 'SyntaxError') { throw new Error(`Source map file was not valid JSON (${options.sourceMap})`) } if (err.code === 'ENOENT') { throw new Error(`Source map file does not exist (${options.sourceMap})`) } throw new Error(`Source map file could not be read (doesn't exist or isn't valid JSON).`) }) ) }
javascript
{ "resource": "" }
q49794
transformOptions
train
function transformOptions (options) { if (options.codeBundleId && options.appVersion) { delete options.appVersion } if (options.addWildcardPrefix && options.minifiedUrl) { if (options.minifiedUrl.indexOf('://') === -1 && options.minifiedUrl[0] !== '*') { options.minifiedUrl = '*' + options.minifiedUrl } } if (options.stripProjectRoot) { options.tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bugsnag-sourcemaps')) return transformSourcesMap(options) } return options }
javascript
{ "resource": "" }
q49795
sendRequest
train
function sendRequest (args) { // { options, formData } const options = args.options const formData = args.formData return request(options.endpoint, formData).then(() => options) }
javascript
{ "resource": "" }
q49796
cleanupTempFiles
train
function cleanupTempFiles (options) { return new Promise((resolve, reject) => { if (options.tempDir) { if (path.dirname(options.sourceMap) === options.tempDir) { fs.unlinkSync(options.sourceMap) } fs.rmdir(options.tempDir, (err) => { if (err) { reject(err) } else { resolve() }; }) } else { resolve() } }) }
javascript
{ "resource": "" }
q49797
upload
train
function upload (options, callback) { const promise = ( Promise.resolve(options) .then(applyDefaults) .then(validateOptions) .then(opts => { options = opts return options }) .then(transformOptions) .then(prepareRequest) .then(sendRequest) .catch(err => { return cleanupTempFiles(options) .then(() => Promise.reject(err)) }) .then(cleanupTempFiles) ) if (callback) { promise .then(message => callback(null, message)) .catch(err => callback(err, null)) } return promise }
javascript
{ "resource": "" }
q49798
createWriteHead
train
function createWriteHead (prevWriteHead, listener) { var fired = false // return function with core name and argument list return function writeHead (statusCode) { // set headers from arguments var args = setWriteHeadHeaders.apply(this, arguments) // fire listener if (!fired) { fired = true listener.call(this) // pass-along an updated status code if (typeof args[0] === 'number' && this.statusCode !== args[0]) { args[0] = this.statusCode args.length = 1 } } return prevWriteHead.apply(this, args) } }
javascript
{ "resource": "" }
q49799
onHeaders
train
function onHeaders (res, listener) { if (!res) { throw new TypeError('argument res is required') } if (typeof listener !== 'function') { throw new TypeError('argument listener must be a function') } res.writeHead = createWriteHead(res.writeHead, listener) }
javascript
{ "resource": "" }