_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q62500
getTicks
test
function getTicks(ticks) { if (typeof ticks !== 'number'|| ticks >= _ticksInMs) { _ticks++; if (_ticks >= _ticksInMs) { _ticks = 0; } ticks = _ticks; } return ticks; }
javascript
{ "resource": "" }
q62501
getTimeWithTicks
test
function getTimeWithTicks(date, ticks) { if (!(date instanceof Date) || isNaN(date.getTime())) { // time with ticks for the current time date = new Date(); const time = date.getTime(); _ticksForCurrentTime++; if(_ticksForCurrentTime > _ticksInMs || time > _lastTimestamp) { _ticksForCurrentTime = 0; _lastTimestamp = time; } ticks = _ticksForCurrentTime; } return { time: date.getTime(), ticks: getTicks(ticks) }; }
javascript
{ "resource": "" }
q62502
generateBuffer
test
function generateBuffer(date, ticks, nodeId, clockId) { const timeWithTicks = getTimeWithTicks(date, ticks); nodeId = getNodeId(nodeId); clockId = getClockId(clockId); const buffer = utils.allocBufferUnsafe(16); //Positions 0-7 Timestamp writeTime(buffer, timeWithTicks.time, timeWithTicks.ticks); //Position 8-9 Clock clockId.copy(buffer, 8, 0); //Positions 10-15 Node nodeId.copy(buffer, 10, 0); //Version Byte: Time based //0001xxxx //turn off first 4 bits buffer[6] = buffer[6] & 0x0f; //turn on fifth bit buffer[6] = buffer[6] | 0x10; //IETF Variant Byte: 1.0.x //10xxxxxx //turn off first 2 bits buffer[8] = buffer[8] & 0x3f; //turn on first bit buffer[8] = buffer[8] | 0x80; return buffer; }
javascript
{ "resource": "" }
q62503
Encoder
test
function Encoder(protocolVersion, options) { this.encodingOptions = options.encoding || utils.emptyObject; defineInstanceMembers.call(this); this.setProtocolVersion(protocolVersion); setEncoders.call(this); if (this.encodingOptions.copyBuffer) { this.handleBuffer = handleBufferCopy; } else { this.handleBuffer = handleBufferRef; } }
javascript
{ "resource": "" }
q62504
numberOfLeadingZeros
test
function numberOfLeadingZeros(value) { if (value.equals(Long.ZERO)) { return 64; } let n = 1; let x = value.getHighBits(); if (x === 0) { n += 32; x = value.getLowBits(); } if (x >>> 16 === 0) { n += 16; x <<= 16; } if (x >>> 24 === 0) { n += 8; x <<= 8; } if (x >>> 28 === 0) { n += 4; x <<= 4; } if (x >>> 30 === 0) { n += 2; x <<= 2; } n -= x >>> 31; return n; }
javascript
{ "resource": "" }
q62505
Index
test
function Index(name, target, kind, options) { /** * Name of the index. * @type {String} */ this.name = name; /** * Target of the index. * @type {String} */ this.target = target; /** * A numeric value representing index kind (0: custom, 1: keys, 2: composite); * @type {Number} */ this.kind = typeof kind === 'string' ? getKindByName(kind) : kind; /** * An associative array containing the index options * @type {Object} */ this.options = options; }
javascript
{ "resource": "" }
q62506
test
function (key) { return _.sortBy(files, function (el) { return Number($(el).find('span[data-lint]').attr(key)) * -1; }); }
javascript
{ "resource": "" }
q62507
loadMode
test
function loadMode(cm) { var doc = cm.view.doc; cm.view.mode = CodeMirror.getMode(cm.options, cm.options.mode); doc.iter(0, doc.size, function(line) { line.stateAfter = null; }); cm.view.frontier = 0; startWorker(cm, 100); }
javascript
{ "resource": "" }
q62508
updateScrollbars
test
function updateScrollbars(d /* display */, docHeight) { var totalHeight = docHeight + 2 * paddingTop(d); d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); var needsH = d.scroller.scrollWidth > d.scroller.clientWidth; var needsV = scrollHeight > d.scroller.clientHeight; if (needsV) { d.scrollbarV.style.display = "block"; d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarV.firstChild.style.height = (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; } else d.scrollbarV.style.display = ""; if (needsH) { d.scrollbarH.style.display = "block"; d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; d.scrollbarH.firstChild.style.width = (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; } else d.scrollbarH.style.display = ""; if (needsH && needsV) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; } else d.scrollbarFiller.style.display = ""; if (mac_geLion && scrollbarWidth(d.measure) === 0) d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; }
javascript
{ "resource": "" }
q62509
restartBlink
test
function restartBlink(cm) { var display = cm.display; clearInterval(display.blinker); var on = true; display.cursor.style.visibility = display.otherCursor.style.visibility = ""; display.blinker = setInterval(function() { if (!display.cursor.offsetHeight) return; display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); }
javascript
{ "resource": "" }
q62510
coordsChar
test
function coordsChar(cm, x, y) { var doc = cm.view.doc; y += cm.display.viewOffset; if (y < 0) return {line: 0, ch: 0, outside: true}; var lineNo = lineAtHeight(doc, y); if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length}; if (x < 0) x = 0; for (;;) { var lineObj = getLine(doc, lineNo); var found = coordsCharInner(cm, lineObj, lineNo, x, y); var merged = collapsedSpanAtEnd(lineObj); if (merged && found.ch == lineRight(lineObj)) lineNo = merged.find().to.line; else return found; } }
javascript
{ "resource": "" }
q62511
updateDoc
test
function updateDoc(cm, from, to, newText, selUpdate, origin) { // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && removeReadOnlyRanges(cm.view.doc, from, to); if (split) { for (var i = split.length - 1; i >= 1; --i) updateDocInner(cm, split[i].from, split[i].to, [""], origin); if (split.length) return updateDocInner(cm, split[0].from, split[0].to, newText, selUpdate, origin); } else { return updateDocInner(cm, from, to, newText, selUpdate, origin); } }
javascript
{ "resource": "" }
q62512
setSelection
test
function setSelection(cm, anchor, head, bias, checkAtomic) { cm.view.goalColumn = null; var sel = cm.view.sel; // Skip over atomic spans. if (checkAtomic || !posEq(anchor, sel.anchor)) anchor = skipAtomic(cm, anchor, bias, checkAtomic != "push"); if (checkAtomic || !posEq(head, sel.head)) head = skipAtomic(cm, head, bias, checkAtomic != "push"); if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; sel.anchor = anchor; sel.head = head; var inv = posLess(head, anchor); sel.from = inv ? head : anchor; sel.to = inv ? anchor : head; cm.curOp.updateInput = true; cm.curOp.selectionChanged = true; }
javascript
{ "resource": "" }
q62513
highlightLine
test
function highlightLine(cm, line, state) { var mode = cm.view.mode, flattenSpans = cm.options.flattenSpans; var changed = !line.styles, pos = 0, curText = "", curStyle = null; var stream = new StringStream(line.text, cm.options.tabSize), st = line.styles || (line.styles = []); if (line.text == "" && mode.blankLine) mode.blankLine(state); while (!stream.eol()) { var style = mode.token(stream, state), substr = stream.current(); stream.start = stream.pos; if (!flattenSpans || curStyle != style) { if (curText) { changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1]; st[pos++] = curText; st[pos++] = curStyle; } curText = substr; curStyle = style; } else curText = curText + substr; // Give up when line is ridiculously long if (stream.pos > 5000) break; } if (curText) { changed = changed || pos >= st.length || curText != st[pos] || curStyle != st[pos+1]; st[pos++] = curText; st[pos++] = curStyle; } if (stream.pos > 5000) { st[pos++] = line.text.slice(stream.pos); st[pos++] = null; } if (pos != st.length) { st.length = pos; changed = true; } return changed; }
javascript
{ "resource": "" }
q62514
e_prop
test
function e_prop(e, prop) { var overridden = e.override && e.override.hasOwnProperty(prop); return overridden ? e.override[prop] : e[prop]; }
javascript
{ "resource": "" }
q62515
Flow
test
function Flow(opts) { /** * Supported by browser? * @type {boolean} */ this.support = ( typeof File !== 'undefined' && typeof Blob !== 'undefined' && typeof FileList !== 'undefined' && ( !!Blob.prototype.slice || !!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || false ) // slicing files support ); if (!this.support) { return ; } /** * Check if directory upload is supported * @type {boolean} */ this.supportDirectory = ( /Chrome/.test(window.navigator.userAgent) || /Firefox/.test(window.navigator.userAgent) || /Edge/.test(window.navigator.userAgent) ); /** * List of FlowFile objects * @type {Array.<FlowFile>} */ this.files = []; /** * Default options for flow.js * @type {Object} */ this.defaults = { chunkSize: 1024 * 1024, forceChunkSize: false, simultaneousUploads: 3, singleFile: false, fileParameterName: 'file', progressCallbacksInterval: 500, speedSmoothingFactor: 0.1, query: {}, headers: {}, withCredentials: false, preprocess: null, method: 'multipart', testMethod: 'GET', uploadMethod: 'POST', prioritizeFirstAndLastChunk: false, allowDuplicateUploads: false, target: '/', testChunks: true, generateUniqueIdentifier: null, maxChunkRetries: 0, chunkRetryInterval: null, permanentErrors: [404, 413, 415, 500, 501], successStatuses: [200, 201, 202], onDropStopPropagation: false, initFileFn: null, readFileFn: webAPIFileRead }; /** * Current options * @type {Object} */ this.opts = {}; /** * List of events: * key stands for event name * value array list of callbacks * @type {} */ this.events = {}; var $ = this; /** * On drop event * @function * @param {MouseEvent} event */ this.onDrop = function (event) { if ($.opts.onDropStopPropagation) { event.stopPropagation(); } event.preventDefault(); var dataTransfer = event.dataTransfer; if (dataTransfer.items && dataTransfer.items[0] && dataTransfer.items[0].webkitGetAsEntry) { $.webkitReadDataTransfer(event); } else { $.addFiles(dataTransfer.files, event); } }; /** * Prevent default * @function * @param {MouseEvent} event */ this.preventEvent = function (event) { event.preventDefault(); }; /** * Current options * @type {Object} */ this.opts = Flow.extend({}, this.defaults, opts || {}); }
javascript
{ "resource": "" }
q62516
test
function (event, fn) { if (event !== undefined) { event = event.toLowerCase(); if (fn !== undefined) { if (this.events.hasOwnProperty(event)) { arrayRemove(this.events[event], fn); } } else { delete this.events[event]; } } else { this.events = {}; } }
javascript
{ "resource": "" }
q62517
test
function (event, args) { // `arguments` is an object, not array, in FF, so: args = Array.prototype.slice.call(arguments); event = event.toLowerCase(); var preventDefault = false; if (this.events.hasOwnProperty(event)) { each(this.events[event], function (callback) { preventDefault = callback.apply(this, args.slice(1)) === false || preventDefault; }, this); } if (event != 'catchall') { args.unshift('catchAll'); preventDefault = this.fire.apply(this, args) === false || preventDefault; } return !preventDefault; }
javascript
{ "resource": "" }
q62518
test
function (event) { var $ = this; var queue = event.dataTransfer.items.length; var files = []; each(event.dataTransfer.items, function (item) { var entry = item.webkitGetAsEntry(); if (!entry) { decrement(); return ; } if (entry.isFile) { // due to a bug in Chrome's File System API impl - #149735 fileReadSuccess(item.getAsFile(), entry.fullPath); } else { readDirectory(entry.createReader()); } }); function readDirectory(reader) { reader.readEntries(function (entries) { if (entries.length) { queue += entries.length; each(entries, function(entry) { if (entry.isFile) { var fullPath = entry.fullPath; entry.file(function (file) { fileReadSuccess(file, fullPath); }, readError); } else if (entry.isDirectory) { readDirectory(entry.createReader()); } }); readDirectory(reader); } else { decrement(); } }, readError); } function fileReadSuccess(file, fullPath) { // relative path should not start with "/" file.relativePath = fullPath.substring(1); files.push(file); decrement(); } function readError(fileError) { throw fileError; } function decrement() { if (--queue == 0) { $.addFiles(files, event); } } }
javascript
{ "resource": "" }
q62519
test
function (file) { var custom = this.opts.generateUniqueIdentifier; if (typeof custom === 'function') { return custom(file); } // Some confusion in different versions of Firefox var relativePath = file.relativePath || file.webkitRelativePath || file.fileName || file.name; return file.size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''); }
javascript
{ "resource": "" }
q62520
test
function (preventEvents) { // In some cases (such as videos) it's really handy to upload the first // and last chunk of a file quickly; this let's the server check the file's // metadata and determine if there's even a point in continuing. var found = false; if (this.opts.prioritizeFirstAndLastChunk) { each(this.files, function (file) { if (!file.paused && file.chunks.length && file.chunks[0].status() === 'pending') { file.chunks[0].send(); found = true; return false; } if (!file.paused && file.chunks.length > 1 && file.chunks[file.chunks.length - 1].status() === 'pending') { file.chunks[file.chunks.length - 1].send(); found = true; return false; } }); if (found) { return found; } } // Now, simply look for the next, best thing to upload each(this.files, function (file) { if (!file.paused) { each(file.chunks, function (chunk) { if (chunk.status() === 'pending') { chunk.send(); found = true; return false; } }); } if (found) { return false; } }); if (found) { return true; } // The are no more outstanding chunks to upload, check is everything is done var outstanding = false; each(this.files, function (file) { if (!file.isComplete()) { outstanding = true; return false; } }); if (!outstanding && !preventEvents) { // All chunks have been uploaded, complete async(function () { this.fire('complete'); }, this); } return false; }
javascript
{ "resource": "" }
q62521
test
function (domNodes, isDirectory, singleFile, attributes) { if (domNodes instanceof Element) { domNodes = [domNodes]; } each(domNodes, function (domNode) { var input; if (domNode.tagName === 'INPUT' && domNode.type === 'file') { input = domNode; } else { input = document.createElement('input'); input.setAttribute('type', 'file'); // display:none - not working in opera 12 extend(input.style, { visibility: 'hidden', position: 'absolute', width: '1px', height: '1px' }); // for opera 12 browser, input must be assigned to a document domNode.appendChild(input); // https://developer.mozilla.org/en/using_files_from_web_applications) // event listener is executed two times // first one - original mouse click event // second - input.click(), input is inside domNode domNode.addEventListener('click', function() { input.click(); }, false); } if (!this.opts.singleFile && !singleFile) { input.setAttribute('multiple', 'multiple'); } if (isDirectory) { input.setAttribute('webkitdirectory', 'webkitdirectory'); } each(attributes, function (value, key) { input.setAttribute(key, value); }); // When new files are added, simply append them to the overall list var $ = this; input.addEventListener('change', function (e) { if (e.target.value) { $.addFiles(e.target.files, e); e.target.value = ''; } }, false); }, this); }
javascript
{ "resource": "" }
q62522
test
function (domNodes) { if (typeof domNodes.length === 'undefined') { domNodes = [domNodes]; } each(domNodes, function (domNode) { domNode.addEventListener('dragover', this.preventEvent, false); domNode.addEventListener('dragenter', this.preventEvent, false); domNode.addEventListener('drop', this.onDrop, false); }, this); }
javascript
{ "resource": "" }
q62523
test
function (domNodes) { if (typeof domNodes.length === 'undefined') { domNodes = [domNodes]; } each(domNodes, function (domNode) { domNode.removeEventListener('dragover', this.preventEvent); domNode.removeEventListener('dragenter', this.preventEvent); domNode.removeEventListener('drop', this.onDrop); }, this); }
javascript
{ "resource": "" }
q62524
test
function () { var uploading = false; each(this.files, function (file) { if (file.isUploading()) { uploading = true; return false; } }); return uploading; }
javascript
{ "resource": "" }
q62525
test
function () { var num = 0; var should = true; var simultaneousUploads = this.opts.simultaneousUploads; each(this.files, function (file) { each(file.chunks, function(chunk) { if (chunk.status() === 'uploading') { num++; if (num >= simultaneousUploads) { should = false; return false; } } }); }); // if should is true then return uploading chunks's length return should && num; }
javascript
{ "resource": "" }
q62526
test
function () { // Make sure we don't start too many uploads at once var ret = this._shouldUploadNext(); if (ret === false) { return; } // Kick off the queue this.fire('uploadStart'); var started = false; for (var num = 1; num <= this.opts.simultaneousUploads - ret; num++) { started = this.uploadNextChunk(true) || started; } if (!started) { async(function () { this.fire('complete'); }, this); } }
javascript
{ "resource": "" }
q62527
test
function (fileList, event) { var files = []; each(fileList, function (file) { // https://github.com/flowjs/flow.js/issues/55 if ((!ie10plus || ie10plus && file.size > 0) && !(file.size % 4096 === 0 && (file.name === '.' || file.fileName === '.'))) { var uniqueIdentifier = this.generateUniqueIdentifier(file); if (this.opts.allowDuplicateUploads || !this.getFromUniqueIdentifier(uniqueIdentifier)) { var f = new FlowFile(this, file, uniqueIdentifier); if (this.fire('fileAdded', f, event)) { files.push(f); } } } }, this); if (this.fire('filesAdded', files, event)) { each(files, function (file) { if (this.opts.singleFile && this.files.length > 0) { this.removeFile(this.files[0]); } this.files.push(file); }, this); this.fire('filesSubmitted', files, event); } }
javascript
{ "resource": "" }
q62528
test
function (file) { for (var i = this.files.length - 1; i >= 0; i--) { if (this.files[i] === file) { this.files.splice(i, 1); file.abort(); this.fire('fileRemoved', file); } } }
javascript
{ "resource": "" }
q62529
test
function (uniqueIdentifier) { var ret = false; each(this.files, function (file) { if (file.uniqueIdentifier === uniqueIdentifier) { ret = file; } }); return ret; }
javascript
{ "resource": "" }
q62530
test
function () { var sizeDelta = 0; var averageSpeed = 0; each(this.files, function (file) { if (!file.paused && !file.error) { sizeDelta += file.size - file.sizeUploaded(); averageSpeed += file.averageSpeed; } }); if (sizeDelta && !averageSpeed) { return Number.POSITIVE_INFINITY; } if (!sizeDelta && !averageSpeed) { return 0; } return Math.floor(sizeDelta / averageSpeed); }
javascript
{ "resource": "" }
q62531
test
function () { var timeSpan = Date.now() - this._lastProgressCallback; if (!timeSpan) { return ; } var smoothingFactor = this.flowObj.opts.speedSmoothingFactor; var uploaded = this.sizeUploaded(); // Prevent negative upload speed after file upload resume this.currentSpeed = Math.max((uploaded - this._prevUploadedSize) / timeSpan * 1000, 0); this.averageSpeed = smoothingFactor * this.currentSpeed + (1 - smoothingFactor) * this.averageSpeed; this._prevUploadedSize = uploaded; }
javascript
{ "resource": "" }
q62532
test
function (chunk, event, message) { switch (event) { case 'progress': if (Date.now() - this._lastProgressCallback < this.flowObj.opts.progressCallbacksInterval) { break; } this.measureSpeed(); this.flowObj.fire('fileProgress', this, chunk); this.flowObj.fire('progress'); this._lastProgressCallback = Date.now(); break; case 'error': this.error = true; this.abort(true); this.flowObj.fire('fileError', this, message, chunk); this.flowObj.fire('error', message, this, chunk); break; case 'success': if (this.error) { return; } this.measureSpeed(); this.flowObj.fire('fileProgress', this, chunk); this.flowObj.fire('progress'); this._lastProgressCallback = Date.now(); if (this.isComplete()) { this.currentSpeed = 0; this.averageSpeed = 0; this.flowObj.fire('fileSuccess', this, message, chunk); } break; case 'retry': this.flowObj.fire('fileRetry', this, chunk); break; } }
javascript
{ "resource": "" }
q62533
test
function (reset) { this.currentSpeed = 0; this.averageSpeed = 0; var chunks = this.chunks; if (reset) { this.chunks = []; } each(chunks, function (c) { if (c.status() === 'uploading') { c.abort(); this.flowObj.uploadNextChunk(); } }, this); }
javascript
{ "resource": "" }
q62534
test
function () { if (typeof this.flowObj.opts.initFileFn === "function") { this.flowObj.opts.initFileFn(this); } this.abort(true); this.error = false; // Rebuild stack of chunks from file this._prevProgress = 0; var round = this.flowObj.opts.forceChunkSize ? Math.ceil : Math.floor; var chunks = Math.max( round(this.size / this.flowObj.opts.chunkSize), 1 ); for (var offset = 0; offset < chunks; offset++) { this.chunks.push( new FlowChunk(this.flowObj, this, offset) ); } }
javascript
{ "resource": "" }
q62535
test
function () { if (this.error) { return 1; } if (this.chunks.length === 1) { this._prevProgress = Math.max(this._prevProgress, this.chunks[0].progress()); return this._prevProgress; } // Sum up progress across everything var bytesLoaded = 0; each(this.chunks, function (c) { // get chunk progress relative to entire file bytesLoaded += c.progress() * (c.endByte - c.startByte); }); var percent = bytesLoaded / this.size; // We don't want to lose percentages when an upload is paused this._prevProgress = Math.max(this._prevProgress, percent > 0.9999 ? 1 : percent); return this._prevProgress; }
javascript
{ "resource": "" }
q62536
test
function () { var outstanding = false; each(this.chunks, function (chunk) { var status = chunk.status(); if (status === 'pending' || status === 'uploading' || status === 'reading' || chunk.preprocessState === 1 || chunk.readState === 1) { outstanding = true; return false; } }); return !outstanding; }
javascript
{ "resource": "" }
q62537
test
function () { if (this.paused || this.error) { return 0; } var delta = this.size - this.sizeUploaded(); if (delta && !this.averageSpeed) { return Number.POSITIVE_INFINITY; } if (!delta && !this.averageSpeed) { return 0; } return Math.floor(delta / this.averageSpeed); }
javascript
{ "resource": "" }
q62538
webAPIFileRead
test
function webAPIFileRead(fileObj, startByte, endByte, fileType, chunk) { var function_name = 'slice'; if (fileObj.file.slice) function_name = 'slice'; else if (fileObj.file.mozSlice) function_name = 'mozSlice'; else if (fileObj.file.webkitSlice) function_name = 'webkitSlice'; chunk.readFinished(fileObj.file[function_name](startByte, endByte, fileType)); }
javascript
{ "resource": "" }
q62539
test
function () { // Set up request and listen for event this.xhr = new XMLHttpRequest(); this.xhr.addEventListener("load", this.testHandler, false); this.xhr.addEventListener("error", this.testHandler, false); var testMethod = evalOpts(this.flowObj.opts.testMethod, this.fileObj, this); var data = this.prepareXhrRequest(testMethod, true); this.xhr.send(data); }
javascript
{ "resource": "" }
q62540
test
function () { var preprocess = this.flowObj.opts.preprocess; var read = this.flowObj.opts.readFileFn; if (typeof preprocess === 'function') { switch (this.preprocessState) { case 0: this.preprocessState = 1; preprocess(this); return; case 1: return; } } switch (this.readState) { case 0: this.readState = 1; read(this.fileObj, this.startByte, this.endByte, this.fileObj.file.type, this); return; case 1: return; } if (this.flowObj.opts.testChunks && !this.tested) { this.test(); return; } this.loaded = 0; this.total = 0; this.pendingRetry = false; // Set up request and listen for event this.xhr = new XMLHttpRequest(); this.xhr.upload.addEventListener('progress', this.progressHandler, false); this.xhr.addEventListener("load", this.doneHandler, false); this.xhr.addEventListener("error", this.doneHandler, false); var uploadMethod = evalOpts(this.flowObj.opts.uploadMethod, this.fileObj, this); var data = this.prepareXhrRequest(uploadMethod, false, this.flowObj.opts.method, this.bytes); this.xhr.send(data); }
javascript
{ "resource": "" }
q62541
test
function (isTest) { if (this.readState === 1) { return 'reading'; } else if (this.pendingRetry || this.preprocessState === 1) { // if pending retry then that's effectively the same as actively uploading, // there might just be a slight delay before the retry starts return 'uploading'; } else if (!this.xhr) { return 'pending'; } else if (this.xhr.readyState < 4) { // Status is really 'OPENED', 'HEADERS_RECEIVED' // or 'LOADING' - meaning that stuff is happening return 'uploading'; } else { if (this.flowObj.opts.successStatuses.indexOf(this.xhr.status) > -1) { // HTTP 200, perfect // HTTP 202 Accepted - The request has been accepted for processing, but the processing has not been completed. return 'success'; } else if (this.flowObj.opts.permanentErrors.indexOf(this.xhr.status) > -1 || !isTest && this.retries >= this.flowObj.opts.maxChunkRetries) { // HTTP 413/415/500/501, permanent error return 'error'; } else { // this should never happen, but we'll reset and queue a retry // a likely case for this would be 503 service unavailable this.abort(); return 'pending'; } } }
javascript
{ "resource": "" }
q62542
test
function(method, isTest, paramsMethod, blob) { // Add data from the query options var query = evalOpts(this.flowObj.opts.query, this.fileObj, this, isTest); query = extend(query || {}, this.getParams()); var target = evalOpts(this.flowObj.opts.target, this.fileObj, this, isTest); var data = null; if (method === 'GET' || paramsMethod === 'octet') { // Add data from the query options var params = []; each(query, function (v, k) { params.push([encodeURIComponent(k), encodeURIComponent(v)].join('=')); }); target = this.getTarget(target, params); data = blob || null; } else { // Add data from the query options data = new FormData(); each(query, function (v, k) { data.append(k, v); }); if (typeof blob !== "undefined") data.append(this.flowObj.opts.fileParameterName, blob, this.fileObj.file.name); } this.xhr.open(method, target, true); this.xhr.withCredentials = this.flowObj.opts.withCredentials; // Add data from header options each(evalOpts(this.flowObj.opts.headers, this.fileObj, this, isTest), function (v, k) { this.xhr.setRequestHeader(k, v); }, this); return data; }
javascript
{ "resource": "" }
q62543
evalOpts
test
function evalOpts(data, args) { if (typeof data === "function") { // `arguments` is an object, not array, in FF, so: args = Array.prototype.slice.call(arguments); data = data.apply(null, args.slice(1)); } return data; }
javascript
{ "resource": "" }
q62544
each
test
function each(obj, callback, context) { if (!obj) { return ; } var key; // Is Array? // Array.isArray won't work, not only arrays can be iterated by index https://github.com/flowjs/ng-flow/issues/236# if (typeof(obj.length) !== 'undefined') { for (key = 0; key < obj.length; key++) { if (callback.call(context, obj[key], key) === false) { return ; } } } else { for (key in obj) { if (obj.hasOwnProperty(key) && callback.call(context, obj[key], key) === false) { return ; } } } }
javascript
{ "resource": "" }
q62545
createTable
test
function createTable() { tableName = arguments[0]; var fname = ''; var callback; if (arguments.length === 2) { callback = arguments[1]; fname = path.join(userData, tableName + '.json'); } else if (arguments.length === 3) { fname = path.join(arguments[1], arguments[0] + '.json'); callback = arguments[2]; } // Check if the file with the tablename.json exists let exists = fs.existsSync(fname); if (exists) { // The file exists, do not recreate the table/json file callback(false, tableName + '.json already exists!'); return; } else { // Create an empty object and pass an empty array as value let obj = new Object(); obj[tableName] = []; // Write the object to json file try { fs.writeFileSync(fname, JSON.stringify(obj, null, 2), (err) => { }) callback(true, "Success!") return; } catch (e) { callback(false, e.toString()); return; } } }
javascript
{ "resource": "" }
q62546
valid
test
function valid() { var fName = '' if (arguments.length == 2) { // Given the database name and location const dbName = arguments[0] const dbLocation = arguments[1] var fName = path.join(dbLocation, dbName + '.json') } else if (arguments.length == 1) { const dbName = arguments[0] fname = path.join(userData, dbName + '.json') } const content = fs.readFileSync(fName, 'utf-8') try { JSON.parse(content) } catch (e) { return false } return true }
javascript
{ "resource": "" }
q62547
insertTableContent
test
function insertTableContent() { let tableName = arguments[0]; var fname = ''; var callback; var tableRow; if (arguments.length === 3) { callback = arguments[2]; fname = path.join(userData, arguments[0] + '.json'); tableRow = arguments[1]; } else if (arguments.length === 4) { fname = path.join(arguments[1], arguments[0] + '.json'); callback = arguments[3]; tableRow = arguments[2]; } let exists = fs.existsSync(fname); if (exists) { // Table | json parsed let table = JSON.parse(fs.readFileSync(fname)); let date = new Date(); let id = date.getTime(); tableRow['id'] = id; table[tableName].push(tableRow); try { fs.writeFileSync(fname, JSON.stringify(table, null, 2), (err) => { }) callback(true, "Object written successfully!"); return; } catch (e) { callback(false, "Error writing object."); return; } } callback(false, "Table/json file doesn't exist!"); return; }
javascript
{ "resource": "" }
q62548
count
test
function count() { let tableName = arguments[0] let callback if (arguments.length === 2) { callback = arguments[1] getAll(tableName, (succ, data) => { if (succ) { callback(true, data.length) return } else { callback(false, data) return } }) } else if (arguments.length === 3) { callback = arguments[2] getAll(tableName, arguments[1], (succ, data) => { if (succ) { callback(true, data.length) return } else { callback(false, data) return } }) } else { callback(false,'Wrong number of arguments. Must be either 2 or 3 arguments including callback function.') return } }
javascript
{ "resource": "" }
q62549
updateRow
test
function updateRow() { let tableName = arguments[0]; var fname = ''; var where; var set; var callback; if (arguments.length === 4) { fname = path.join(userData, tableName + '.json'); where = arguments[1]; set = arguments[2]; callback = arguments[3]; } else if (arguments.length === 5) { fname = path.join(arguments[1], arguments[0] + '.json'); where = arguments[2]; set = arguments[3]; callback = arguments[4]; } let exists = fs.existsSync(fname); let whereKeys = Object.keys(where); let setKeys = Object.keys(set); if (exists) { let table = JSON.parse(fs.readFileSync(fname)); let rows = table[tableName]; let matched = 0; // Number of matched complete where clause let matchedIndex = 0; for (var i = 0; i < rows.length; i++) { for (var j = 0; j < whereKeys.length; j++) { // Test if there is a matched key with where clause and single row of table if (rows[i].hasOwnProperty(whereKeys[j])) { if (rows[i][whereKeys[j]] === where[whereKeys[j]]) { matched++; matchedIndex = i; } } } } if (matched === whereKeys.length) { // All field from where clause are present in this particular // row of the database table try { for (var k = 0; k < setKeys.length; k++) { // rows[i][setKeys[k]] = set[setKeys[k]]; rows[matchedIndex][setKeys[k]] = set[setKeys[k]]; } // Create a new object and pass the rows let obj = new Object(); obj[tableName] = rows; // Write the object to json file try { fs.writeFileSync(fname, JSON.stringify(obj, null, 2), (err) => { }) callback(true, "Success!") return; } catch (e) { callback(false, e.toString()); return; } callback(true, rows); } catch (e) { callback(false, e.toString()); return; } } else { callback(false, "Cannot find the specified record."); return; } } else { callback(false, 'Table file does not exist!'); return; } }
javascript
{ "resource": "" }
q62550
createHeaderGetter
test
function createHeaderGetter (str) { var name = str.toLowerCase() return function (req, res) { // set appropriate Vary header vary(res, str) // get header var header = req.headers[name] if (!header) { return undefined } // multiple headers get joined with comma by node.js core var index = header.indexOf(',') // return first value return index !== -1 ? header.substr(0, index).trim() : header.trim() } }
javascript
{ "resource": "" }
q62551
Param
test
function Param(name, shortName, process) { if (process == null) { process = cloudinary.Util.identity; } /** * The name of the parameter in snake_case * @member {string} Param#name */ this.name = name; /** * The name of the serialized form of the parameter * @member {string} Param#shortName */ this.shortName = shortName; /** * Manipulate origValue when value is called * @member {function} Param#process */ this.process = process; }
javascript
{ "resource": "" }
q62552
ArrayParam
test
function ArrayParam(name, shortName, sep, process) { if (sep == null) { sep = '.'; } this.sep = sep; ArrayParam.__super__.constructor.call(this, name, shortName, process); }
javascript
{ "resource": "" }
q62553
TransformationParam
test
function TransformationParam(name, shortName, sep, process) { if (shortName == null) { shortName = "t"; } if (sep == null) { sep = '.'; } this.sep = sep; TransformationParam.__super__.constructor.call(this, name, shortName, process); }
javascript
{ "resource": "" }
q62554
RangeParam
test
function RangeParam(name, shortName, process) { if (process == null) { process = this.norm_range_value; } RangeParam.__super__.constructor.call(this, name, shortName, process); }
javascript
{ "resource": "" }
q62555
Configuration
test
function Configuration(options) { if (options == null) { options = {}; } this.configuration = Util.cloneDeep(options); Util.defaults(this.configuration, DEFAULT_CONFIGURATION_PARAMS); }
javascript
{ "resource": "" }
q62556
Cloudinary
test
function Cloudinary(options) { var configuration; this.devicePixelRatioCache = {}; this.responsiveConfig = {}; this.responsiveResizeInitialized = false; configuration = new Configuration(options); this.config = function(newConfig, newValue) { return configuration.config(newConfig, newValue); }; /** * Use \<meta\> tags in the document to configure this Cloudinary instance. * @return {Cloudinary} this for chaining */ this.fromDocument = function() { configuration.fromDocument(); return this; }; /** * Use environment variables to configure this Cloudinary instance. * @return {Cloudinary} this for chaining */ this.fromEnvironment = function() { configuration.fromEnvironment(); return this; }; /** * Initialize configuration. * @function Cloudinary#init * @see Configuration#init * @return {Cloudinary} this for chaining */ this.init = function() { configuration.init(); return this; }; }
javascript
{ "resource": "" }
q62557
getMode
test
function getMode(env, argv) { // When running from parallel-webpack, grab the cli parameters argv = Object.keys(argv).length ? argv : require('minimist')(process.argv.slice(2)); var isProd = (argv.mode || env.mode) === 'production' || env === 'prod' || env.prod; return isProd ? 'production' : 'development'; }
javascript
{ "resource": "" }
q62558
resolveLodash
test
function resolveLodash(context, request, callback) { if (/^lodash\//.test(request)) { callback(null, { commonjs: request, commonjs2: request, amd: request, root: ['_', request.split('/')[1]] }); } else { callback(); } }
javascript
{ "resource": "" }
q62559
baseConfig
test
function baseConfig(name, mode) { const config = { name: `${name}-${mode}`, mode, output: { library: 'cloudinary', libraryTarget: 'umd', globalObject: "this", pathinfo: false }, optimization: { concatenateModules: true, moduleIds: 'named', usedExports: true, minimizer: [new TerserPlugin({ terserOptions: { mangle: { keep_classnames: true, reserved: reserved, ie8: true } }, })] }, resolve: { extensions: ['.js'] }, externals: [ { jquery: 'jQuery' } ], node: { Buffer: false, process: false }, devtool: "source-map", module: { rules: [ { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: {loader: 'babel-loader'} } ] }, plugins: [ new webpack.BannerPlugin({ banner: `/** * cloudinary-[name].js * Cloudinary's JavaScript library - Version ${version} * Copyright Cloudinary * see https://github.com/cloudinary/cloudinary_js * */`, // the banner as string or function, it will be wrapped in a comment raw: true, // if true, banner will not be wrapped in a comment entryOnly: true, // if true, the banner will only be added to the entry chunks }) ] }; let filename = `cloudinary-${name}`; if(mode === 'production') { filename += '.min';} const util = name.startsWith('jquery') ? 'jquery' : 'lodash'; const utilPath = path.resolve(__dirname, `src/util/${util}`); config.output.filename = `./${filename}.js`; config.entry = `./src/namespace/cloudinary-${name}.js`; config.resolve.alias = { "../util$": utilPath, "./util$": utilPath }; // Add reference to each lodash function as a separate module. if (name === 'core') { config.externals.push(resolveLodash); } config.plugins.push( new BundleAnalyzerPlugin({ analyzerMode: 'static', reportFilename: `./${filename}-visualizer.html`, openAnalyzer: false }) ); return config; }
javascript
{ "resource": "" }
q62560
finalizeResourceType
test
function finalizeResourceType(resourceType = "image", type = "upload", urlSuffix, useRootPath, shorten) { var options; resourceType = resourceType == null ? "image" : resourceType; type = type == null ? "upload" : type; if (isPlainObject(resourceType)) { options = resourceType; resourceType = options.resource_type; type = options.type; urlSuffix = options.url_suffix; useRootPath = options.use_root_path; shorten = options.shorten; } if (type == null) { type = 'upload'; } if (urlSuffix != null) { resourceType = SEO_TYPES[`${resourceType}/${type}`]; type = null; if (resourceType == null) { throw new Error(`URL Suffix only supported for ${Object.keys(SEO_TYPES).join(', ')}`); } } if (useRootPath) { if (resourceType === 'image' && type === 'upload' || resourceType === "images") { resourceType = null; type = null; } else { throw new Error("Root path only supported for image/upload"); } } if (shorten && resourceType === 'image' && type === 'upload') { resourceType = 'iu'; type = null; } return [resourceType, type].join("/"); }
javascript
{ "resource": "" }
q62561
Drag
test
function Drag(parent, options) { _classCallCheck(this, Drag); options = options || {}; var _this = _possibleConstructorReturn(this, (Drag.__proto__ || Object.getPrototypeOf(Drag)).call(this, parent)); _this.moved = false; _this.wheelActive = utils.defaults(options.wheel, true); _this.wheelScroll = options.wheelScroll || 1; _this.reverse = options.reverse ? 1 : -1; _this.clampWheel = options.clampWheel; _this.factor = options.factor || 1; _this.xDirection = !options.direction || options.direction === 'all' || options.direction === 'x'; _this.yDirection = !options.direction || options.direction === 'all' || options.direction === 'y'; _this.parseUnderflow(options.underflow || 'center'); _this.mouseButtons(options.mouseButtons); return _this; }
javascript
{ "resource": "" }
q62562
each
test
function each(object, fn) { keys(object).forEach(function (key) { return fn(object[key], key); }); }
javascript
{ "resource": "" }
q62563
reduce
test
function reduce(object, fn) { var initial = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return keys(object).reduce(function (accum, key) { return fn(accum, object[key], key); }, initial); }
javascript
{ "resource": "" }
q62564
isPlain
test
function isPlain(value) { return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object; }
javascript
{ "resource": "" }
q62565
logByType
test
function logByType(type, args) { var stringify = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : !!IE_VERSION && IE_VERSION < 11; var lvl = log.levels[level]; var lvlRegExp = new RegExp('^(' + lvl + ')$'); if (type !== 'log') { // Add the type to the front of the message when it's not "log". args.unshift(type.toUpperCase() + ':'); } // Add a clone of the args at this point to history. if (history) { history.push([].concat(args)); } // Add console prefix after adding to history. args.unshift('VIDEOJS:'); // If there's no console then don't try to output messages, but they will // still be stored in history. // // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist // when the module is executed. var fn = window.console && window.console[type]; // Bail out if there's no console or if this type is not allowed by the // current logging level. if (!fn || !lvl || !lvlRegExp.test(type)) { return; } // IEs previous to 11 log objects uselessly as "[object Object]"; so, JSONify // objects and arrays for those less-capable browsers. if (stringify) { args = args.map(function (a) { if (isObject(a) || Array.isArray(a)) { try { return JSON.stringify(a); } catch (x) { return String(a); } } // Cast to string before joining, so we get null and undefined explicitly // included in output (as we would in a modern console). return String(a); }).join(' '); } // Old IE versions do not allow .apply() for console methods (they are // reported as objects rather than functions). if (!fn.apply) { fn(args); } else { fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args); } }
javascript
{ "resource": "" }
q62566
createEl
test
function createEl() { var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var content = arguments[3]; var el = document.createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { log$1.warn(tsml(_templateObject, propName, val)); el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a // method for it. } else if (propName === 'textContent') { textContent(el, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { el.setAttribute(attrName, attributes[attrName]); }); if (content) { appendContent(el, content); } return el; }
javascript
{ "resource": "" }
q62567
addClass
test
function addClass(element, classToAdd) { if (element.classList) { element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if (!hasClass(element, classToAdd)) { element.className = (element.className + ' ' + classToAdd).trim(); } return element; }
javascript
{ "resource": "" }
q62568
toggleClass
test
function toggleClass(element, classToToggle, predicate) { // This CANNOT use `classList` internally because IE does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasClass(element, classToToggle); if (typeof predicate === 'function') { predicate = predicate(element, classToToggle); } if (typeof predicate !== 'boolean') { predicate = !has; } // If the necessary class operation matches the current state of the // element, no action is required. if (predicate === has) { return; } if (predicate) { addClass(element, classToToggle); } else { removeClass(element, classToToggle); } return element; }
javascript
{ "resource": "" }
q62569
getPointerPosition
test
function getPointerPosition(el, event) { var position = {}; var box = findPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; }
javascript
{ "resource": "" }
q62570
appendContent
test
function appendContent(el, content) { normalizeContent(content).forEach(function (node) { return el.appendChild(node); }); return el; }
javascript
{ "resource": "" }
q62571
getData
test
function getData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; }
javascript
{ "resource": "" }
q62572
hasData
test
function hasData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; }
javascript
{ "resource": "" }
q62573
removeData
test
function removeData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } }
javascript
{ "resource": "" }
q62574
_handleMultipleEvents
test
function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { // Call the event method for each one of the types fn(elem, type, callback); }); }
javascript
{ "resource": "" }
q62575
off
test
function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!hasData(elem)) { return; } var data = getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); } return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); }
javascript
{ "resource": "" }
q62576
one
test
function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || newGUID(); on(elem, type, func); }
javascript
{ "resource": "" }
q62577
autoSetup
test
function autoSetup() { // Protect against breakage in non-browser environments. if (!isReal()) { return; } // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop // through each list of elements to build up a new, combined list of elements. var vids = document.getElementsByTagName('video'); var audios = document.getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var _i = 0, _e = audios.length; _i < _e; _i++) { mediaEls.push(audios[_i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var _i2 = 0, _e2 = mediaEls.length; _i2 < _e2; _i2++) { var mediaEl = mediaEls[_i2]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of // 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. videojs$2(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }
javascript
{ "resource": "" }
q62578
autoSetupTimeout
test
function autoSetupTimeout(wait, vjs) { if (vjs) { videojs$2 = vjs; } window.setTimeout(autoSetup, wait); }
javascript
{ "resource": "" }
q62579
setTextContent
test
function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }
javascript
{ "resource": "" }
q62580
throttle
test
function throttle(fn, wait) { var last = Date.now(); var throttled = function throttled() { var now = Date.now(); if (now - last >= wait) { fn.apply(undefined, arguments); last = now; } }; return throttled; }
javascript
{ "resource": "" }
q62581
isValidEventType
test
function isValidEventType(type) { return ( // The regex here verifies that the `type` contains at least one non- // whitespace character. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length ); }
javascript
{ "resource": "" }
q62582
Component
test
function Component(player, options, ready) { classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = mergeOptions({}, this.options_); // Updated options with supplied options options = this.options_ = mergeOptions(this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } // Make this an evented object and use `el_`, if available, as its event bus evented(this, { eventBusKey: this.el_ ? 'el_' : null }); stateful(this, this.constructor.defaultState); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } }
javascript
{ "resource": "" }
q62583
rangeCheck
test
function rangeCheck(fnName, index, maxIndex) { if (typeof index !== 'number' || index < 0 || index > maxIndex) { throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is non-numeric or out of bounds (0-' + maxIndex + ').'); } }
javascript
{ "resource": "" }
q62584
getRange
test
function getRange(fnName, valueIndex, ranges, rangeIndex) { rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; }
javascript
{ "resource": "" }
q62585
createTimeRangesObj
test
function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; }
javascript
{ "resource": "" }
q62586
createTimeRanges
test
function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); }
javascript
{ "resource": "" }
q62587
TextTrackCueList
test
function TextTrackCueList(cues) { classCallCheck(this, TextTrackCueList); var list = this; // eslint-disable-line if (IS_IE8) { list = document.createElement('custom'); for (var prop in TextTrackCueList.prototype) { if (prop !== 'constructor') { list[prop] = TextTrackCueList.prototype[prop]; } } } TextTrackCueList.prototype.setCues_.call(list, cues); /** * @memberof TextTrackCueList * @member {number} length * The current number of `TextTrackCue`s in the TextTrackCueList. * @instance */ Object.defineProperty(list, 'length', { get: function get$$1() { return this.length_; } }); if (IS_IE8) { return list; } }
javascript
{ "resource": "" }
q62588
getFileExtension
test
function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }
javascript
{ "resource": "" }
q62589
loadTrack
test
function loadTrack(src, track) { var opts = { uri: src }; var crossOrigin = isCrossOrigin(src); if (crossOrigin) { opts.cors = crossOrigin; } xhr(opts, bind(this, function (err, response, responseBody) { if (err) { return log$1.error(err, response); } track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading // NOTE: this is only used for the alt/video.novtt.js build if (typeof window.WebVTT !== 'function') { if (track.tech_) { var loadHandler = function loadHandler() { return parseCues(responseBody, track); }; track.tech_.on('vttjsloaded', loadHandler); track.tech_.on('vttjserror', function () { log$1.error('vttjs failed to load, stopping trying to process ' + track.src); track.tech_.off('vttjsloaded', loadHandler); }); } } else { parseCues(responseBody, track); } })); }
javascript
{ "resource": "" }
q62590
constructColor
test
function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; }
javascript
{ "resource": "" }
q62591
checkVolumeSupport
test
function checkVolumeSupport(self, player) { // hide volume controls when they're not supported by the current tech if (player.tech_ && !player.tech_.featuresVolumeControl) { self.addClass('vjs-hidden'); } self.on(player, 'loadstart', function () { if (!player.tech_.featuresVolumeControl) { self.addClass('vjs-hidden'); } else { self.removeClass('vjs-hidden'); } }); }
javascript
{ "resource": "" }
q62592
parseOptionValue
test
function parseOptionValue(value, parser) { if (parser) { value = parser(value); } if (value && value !== 'none') { return value; } }
javascript
{ "resource": "" }
q62593
checkProgress
test
function checkProgress() { if (_this3.el_.currentTime > 0) { // Trigger durationchange for genuinely live video if (_this3.el_.duration === Infinity) { _this3.trigger('durationchange'); } _this3.off('timeupdate', checkProgress); } }
javascript
{ "resource": "" }
q62594
findFirstPassingTechSourcePair
test
function findFirstPassingTechSourcePair(outerArray, innerArray, tester) { var found = void 0; outerArray.some(function (outerChoice) { return innerArray.some(function (innerChoice) { found = tester(outerChoice, innerChoice); if (found) { return true; } }); }); return found; }
javascript
{ "resource": "" }
q62595
markPluginAsActive
test
function markPluginAsActive(player, name) { player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {}; player[PLUGIN_CACHE_KEY][name] = true; }
javascript
{ "resource": "" }
q62596
triggerSetupEvent
test
function triggerSetupEvent(player, hash, before) { var eventName = (before ? 'before' : '') + 'pluginsetup'; player.trigger(eventName, hash); player.trigger(eventName + ':' + hash.name, hash); }
javascript
{ "resource": "" }
q62597
createBasicPlugin
test
function createBasicPlugin(name, plugin) { var basicPluginWrapper = function basicPluginWrapper() { // We trigger the "beforepluginsetup" and "pluginsetup" events on the player // regardless, but we want the hash to be consistent with the hash provided // for advanced plugins. // // The only potentially counter-intuitive thing here is the `instance` in // the "pluginsetup" event is the value returned by the `plugin` function. triggerSetupEvent(this, { name: name, plugin: plugin, instance: null }, true); var instance = plugin.apply(this, arguments); markPluginAsActive(this, name); triggerSetupEvent(this, { name: name, plugin: plugin, instance: instance }); return instance; }; Object.keys(plugin).forEach(function (prop) { basicPluginWrapper[prop] = plugin[prop]; }); return basicPluginWrapper; }
javascript
{ "resource": "" }
q62598
createPluginFactory
test
function createPluginFactory(name, PluginSubClass) { // Add a `name` property to the plugin prototype so that each plugin can // refer to itself by name. PluginSubClass.prototype.name = name; return function () { triggerSetupEvent(this, { name: name, plugin: PluginSubClass, instance: null }, true); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var instance = new (Function.prototype.bind.apply(PluginSubClass, [null].concat([this].concat(args))))(); // The plugin is replaced by a function that returns the current instance. this[name] = function () { return instance; }; triggerSetupEvent(this, instance.getEventHash()); return instance; }; }
javascript
{ "resource": "" }
q62599
videojs
test
function videojs(id, options, ready) { var tag = void 0; // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { var players = videojs.getPlayers(); // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (players[id]) { // If options or ready function are passed, warn if (options) { log$1.warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { players[id].ready(ready); } return players[id]; } // Otherwise get element for ID tag = $('#' + id); // ID is a media element } else { tag = id; } // Check for a useable element // re: nodeName, could be a box div also if (!tag || !tag.nodeName) { throw new TypeError('The element or ID supplied is not valid. (videojs)'); } // Element may have a player attr referring to an already created player instance. // If so return that otherwise set up a new player below if (tag.player || Player.players[tag.playerId]) { return tag.player || Player.players[tag.playerId]; } options = options || {}; videojs.hooks('beforesetup').forEach(function (hookFunction) { var opts = hookFunction(tag, mergeOptions(options)); if (!isObject(opts) || Array.isArray(opts)) { log$1.error('please return an object in beforesetup hooks'); return; } options = mergeOptions(options, opts); }); var PlayerComponent = Component.getComponent('Player'); // If not, set up a new player var player = new PlayerComponent(tag, options, ready); videojs.hooks('setup').forEach(function (hookFunction) { return hookFunction(player); }); return player; }
javascript
{ "resource": "" }