_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q20500
event
train
function event(eventName, callingFunction) { if (typeof eventName !== 'string') { self.showError(self.errCodes.DEVELOPER_ERR, callingFunction + " called without a string as the first argument"); throw "developer error"; } if (!allowedEvents[eventName]) { self.showError(self.errCodes.DEVELOPER_ERR, callingFunction + " called with a bad event name = " + eventName); throw "developer error"; } }
javascript
{ "resource": "" }
q20501
disconnectBody
train
function disconnectBody() { var key; self.loggingOut = true; offersPending = {}; acceptancePending = {}; self.disconnecting = true; closedChannel = self.webSocket; if( stillAliveTimer ) { clearTimeout(stillAliveTimer); stillAliveTimer = null; } if (self.webSocketConnected) { if (!preallocatedSocketIo) { self.webSocket.close(); } self.webSocketConnected = false; } self.hangupAll(); if (roomOccupantListener) { for (key in lastLoggedInList) { if (lastLoggedInList.hasOwnProperty(key)) { roomOccupantListener(key, {}, false); } } } lastLoggedInList = {}; self.emitEvent("roomOccupant", {}); self.roomData = {}; self.roomJoin = {}; self.loggingOut = false; self.myEasyrtcid = null; self.disconnecting = false; oldConfig = {}; }
javascript
{ "resource": "" }
q20502
train
function() { var alteredData = findDeltas(oldConfig, newConfig); // // send all the configuration information that changes during the session // if (alteredData) { logDebug("cfg=" + JSON.stringify(alteredData.added)); if (self.webSocket) { sendSignalling(null, "setUserCfg", {setUserCfg: alteredData.added}, null, null); } } oldConfig = newConfig; }
javascript
{ "resource": "" }
q20503
checkIceGatheringState
train
function checkIceGatheringState(otherPeer) { console.log("entered checkIceGatheringState"); if( peerConns[otherPeer] && peerConns[otherPeer].pc && peerConns[otherPeer].pc.iceGatheringState ) { if( peerConns[otherPeer].pc.iceGatheringState === "complete" ) { self.sendPeerMessage(otherPeer, "iceGatheringDone", {}); console.log("sent iceGatherDone message to ", otherPeer); } else { setTimeout( function() { checkIceGatheringState(otherPeer); }, 500); } } else { console.log("checkIceGatherState: leaving"); // peer left, ignore } }
javascript
{ "resource": "" }
q20504
validateVideoIds
train
function validateVideoIds(monitorVideoId, videoIds) { var i; // verify that video ids were not typos. if (monitorVideoId && !document.getElementById(monitorVideoId)) { easyrtc.showError(easyrtc.errCodes.DEVELOPER_ERR, "The monitor video id passed to easyApp was bad, saw " + monitorVideoId); return false; } for (i in videoIds) { if (!videoIds.hasOwnProperty(i)) { continue; } var name = videoIds[i]; if (!document.getElementById(name)) { easyrtc.showError(easyrtc.errCodes.DEVELOPER_ERR, "The caller video id '" + name + "' passed to easyApp was bad."); return false; } } return true; }
javascript
{ "resource": "" }
q20505
connect
train
function connect() { easyrtc.enableDebug(false); easyrtc.enableDataChannels(true); easyrtc.enableVideo(false); easyrtc.enableAudio(false); easyrtc.enableVideoReceive(false); easyrtc.enableAudioReceive(false); easyrtc.setDataChannelOpenListener(openListener); easyrtc.setDataChannelCloseListener(closeListener); easyrtc.setPeerListener(addToConversation); easyrtc.setRoomOccupantListener(convertListToButtons); easyrtc.connect("easyrtc.dataMessaging", loginSuccess, loginFailure); }
javascript
{ "resource": "" }
q20506
onAccessApproved
train
function onAccessApproved(sourceId) { pending = false; // if "cancel" button is clicked if(!sourceId || !sourceId.length) { return port.postMessage('PermissionDeniedError'); } // "ok" button is clicked; share "sourceId" with the // content-script which will forward it to the webpage port.postMessage({ chromeMediaSourceId: sourceId }); }
javascript
{ "resource": "" }
q20507
portOnMessageHanlder
train
function portOnMessageHanlder(message) { if(message === 'get-sourceId' && !pending) { pending = true; chrome.desktopCapture.chooseDesktopMedia(session, port.sender.tab, onAccessApproved); } }
javascript
{ "resource": "" }
q20508
fillBar
train
function fillBar() { var arr = [] for (var i=0; i<servers.length; i++) { arr.push(Math.round(Math.random()*10)) } bar.setData({titles: servers, data: arr}) }
javascript
{ "resource": "" }
q20509
getMaxY
train
function getMaxY() { if (self.options.maxY) { return self.options.maxY; } var max = -Infinity; for(let i = 0; i < data.length; i++) { if (data[i].y.length) { var current = _.max(data[i].y, parseFloat); if (current > max) { max = current; } } } return max + (max - self.options.minY) * 0.2; }
javascript
{ "resource": "" }
q20510
drawLine
train
function drawLine(values, style, minY) { style = style || {} var color = self.options.style.line c.strokeStyle = style.line || color c.moveTo(0, 0) c.beginPath(); c.lineTo(getXPixel(0), getYPixel(values[0], minY)); for(var k = 1; k < values.length; k++) { c.lineTo(getXPixel(k), getYPixel(values[k], minY)); } c.stroke(); }
javascript
{ "resource": "" }
q20511
train
function(ev) { this.count = this.count || 0; if (this.count >= 256 || rng_pptr >= rng_psize) { if (window.removeEventListener) window.removeEventListener("mousemove", onMouseMoveListener, false); else if (window.detachEvent) window.detachEvent("onmousemove", onMouseMoveListener); return; } try { var mouseCoordinates = ev.x + ev.y; rng_pool[rng_pptr++] = mouseCoordinates & 255; this.count += 1; } catch (e) { // Sometimes Firefox will deny permission to access event properties for some reason. Ignore. } }
javascript
{ "resource": "" }
q20512
hashUnique
train
function hashUnique(a) { var table={},i=0,j=0,l=a.length,x; for (;i<l;i++) { x=a[i]; if (table.hasOwnProperty(x)) continue; table[x]=1; a[j++]=x; } a.length=j; return a; }
javascript
{ "resource": "" }
q20513
parseCharset
train
function parseCharset(charset /*:String*/) { charset=charset.split(''); var chars=[],ranges=[], exclude = charset[0]==='^' && charset.length > 1 && charset.shift(); charset.forEach(function (c) { if (chars[0]=='-' && chars.length>1) {//chars=['-','a'],c=='z' if (chars[1] > c ) // z-a is invalid throw new Error('Charset range out of order:'+chars[1]+'-'+c+'!'); ranges.push(chars[1]+c); chars.splice(0,2); } else chars.unshift(c); }); ranges=ranges.concat(chars); //convert exclude to include return exclude?negate(ranges):classify(ranges).ranges; }
javascript
{ "resource": "" }
q20514
toPrint
train
function toPrint(s,isRaw) { var ctrl=/[\x00-\x1F\x7F-\x9F]/,unicode=/[\u009F-\uFFFF]/; s=s.split('').map(function (c) { if (!isRaw && printEscapeMap.hasOwnProperty(c)) return printEscapeMap[c]; else if (unicode.test(c)) return '\\u'+('00'+ord(c).toString(16).toUpperCase()).slice(-4); else if (ctrl.test(c)) return '\\x'+("0"+ord(c).toString(16).toUpperCase()).slice(-2); return c; }).join(''); return s; }
javascript
{ "resource": "" }
q20515
endChoice
train
function endChoice(stack) { if (stack._parentChoice) { var choice=stack._parentChoice; delete stack._parentChoice; delete stack._parentGroup; delete stack.groupCounter; var parentStack=choice._parentStack; delete choice._parentStack; return parentStack; } return stack; }
javascript
{ "resource": "" }
q20516
structure
train
function structure(a) { a.accepts=a.accepts.split(','); var ts=a.trans, i=ts.length,t,s,from,to; while (i--) { t=ts[i]; s=t[0].split('>'); from=s[0].split(','); to=s[1].split(','); ts[i]={from:from,to:to,charset:t[1],action:t[2],assert:t[3]}; } a.compact=false; return a; }
javascript
{ "resource": "" }
q20517
train
function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }
javascript
{ "resource": "" }
q20518
AsyncInvokeLater
train
function AsyncInvokeLater(fn, receiver, arg) { ASSERT(arguments.length === 3); this._lateQueue.push(fn, receiver, arg); this._queueTick(); }
javascript
{ "resource": "" }
q20519
_drainQueueStep
train
function _drainQueueStep(queue) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); } else { var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }
javascript
{ "resource": "" }
q20520
insert
train
function insert(item, msecs) { item._idleStart = Timer.now(); item._idleTimeout = msecs; if (msecs < 0) return; var list; if (lists[msecs]) { list = lists[msecs]; } else { list = new Timer(); list.start(msecs, 0); L.init(list); lists[msecs] = list; list.msecs = msecs; list[kOnTimeout] = listOnTimeout; } L.append(list, item); assert(!L.isEmpty(list)); // list is not empty }
javascript
{ "resource": "" }
q20521
dummyP
train
function dummyP(n) { return function lifted() { var deferred = Promise.pending(); timers.setTimeout(nodeback, deferred, global.asyncTime || 100); return deferred.promise; } }
javascript
{ "resource": "" }
q20522
train
function( src, fileName ) { var ast = parse(src, fileName); walk.simple(ast, { ExpressionStatement: function( node ) { if( node.expression.type !== 'CallExpression' ) { return; } var start = node.start; var end = node.end; node = node.expression; var callee = node.callee; if( callee.name === "CONSTANT" && callee.type === "Identifier" ) { if( node.arguments.length !== 2 ) { throw new Error( "Exactly 2 arguments must be passed to CONSTANT\n" + src.substring(start, end) ); } if( node.arguments[0].type !== "Identifier" ) { throw new Error( "Can only define identifier as a constant\n" + src.substring(start, end) ); } var args = node.arguments; var name = args[0]; var nameStr = name.name; var expr = args[1]; var e = eval; constants[nameStr] = { identifier: name, value: e(nodeToString(expr)) }; walk.simple( expr, { Identifier: function( node ) { ignore.push(node); } }); global[nameStr] = constants[nameStr].value; } } }); }
javascript
{ "resource": "" }
q20523
train
function( src, fileName ) { var results = []; var identifiers = []; var ast = parse(src, fileName); walk.simple(ast, { Identifier: function( node ) { identifiers.push( node ); } }); for( var i = 0, len = identifiers.length; i < len; ++i ) { var id = identifiers[i]; if( ignore.indexOf(id) > -1 ) { continue; } var constant = constants[id.name]; if( constant === void 0 ) { continue; } if( constant.identifier === id ) { continue; } results.push( new ConstantReplacement( constant.value, id.start, id.end ) ); } return convertSrc( src, results ); }
javascript
{ "resource": "" }
q20524
validateListFromOptions
train
function validateListFromOptions (opts, name) { if (opts.all) return Array.from(supported[name].values()) let list = opts[name] if (!list) { if (name === 'arch') { list = hostArch() } else { list = process[name] } } else if (list === 'all') { return Array.from(supported[name].values()) } if (!Array.isArray(list)) { if (typeof list === 'string') { list = list.split(/,\s*/) } else { return unsupportedListOption(name, list, supported[name]) } } const officialElectronPackages = usingOfficialElectronPackages(opts) for (let value of list) { if (officialElectronPackages && !supported[name].has(value)) { return unsupportedListOption(name, value, supported[name]) } } return list }
javascript
{ "resource": "" }
q20525
train
function(reason) { log(qq.format("Failed to determine blob name for ID {} - {}", id, reason), "error"); promise.failure({error: reason}); }
javascript
{ "resource": "" }
q20526
handleNameUpdate
train
function handleNameUpdate(newFilenameInputEl, fileId) { var newName = newFilenameInputEl.value, origExtension; if (newName !== undefined && qq.trimStr(newName).length > 0) { origExtension = getOriginalExtension(fileId); if (origExtension !== undefined) { newName = newName + "." + origExtension; } spec.onSetName(fileId, newName); } spec.onEditingStatusChange(fileId, false); }
javascript
{ "resource": "" }
q20527
registerInputBlurHandler
train
function registerInputBlurHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() { handleNameUpdate(inputEl, fileId); }); }
javascript
{ "resource": "" }
q20528
registerInputEnterKeyHandler
train
function registerInputEnterKeyHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) { var code = event.keyCode || event.which; if (code === 13) { handleNameUpdate(inputEl, fileId); } }); }
javascript
{ "resource": "" }
q20529
getFilesInDirectory
train
function getFilesInDirectory(entry, reader, accumEntries, existingPromise) { var promise = existingPromise || new qq.Promise(), dirReader = reader || entry.createReader(); dirReader.readEntries( function readSuccess(entries) { var newEntries = accumEntries ? accumEntries.concat(entries) : entries; if (entries.length) { setTimeout(function() { // prevent stack overflow, however unlikely getFilesInDirectory(entry, dirReader, newEntries, promise); }, 0); } else { promise.success(newEntries); } }, promise.failure ); return promise; }
javascript
{ "resource": "" }
q20530
addCallbacks
train
function addCallbacks(transformedOpts, newUploaderInstance) { var callbacks = transformedOpts.callbacks = {}; $.each(newUploaderInstance._options.callbacks, function(prop, nonJqueryCallback) { var name, callbackEventTarget; name = /^on(\w+)/.exec(prop)[1]; name = name.substring(0, 1).toLowerCase() + name.substring(1); callbackEventTarget = $el; callbacks[prop] = function() { var originalArgs = Array.prototype.slice.call(arguments), transformedArgs = [], nonJqueryCallbackRetVal, jqueryEventCallbackRetVal; $.each(originalArgs, function(idx, arg) { transformedArgs.push(maybeWrapInJquery(arg)); }); nonJqueryCallbackRetVal = nonJqueryCallback.apply(this, originalArgs); try { jqueryEventCallbackRetVal = callbackEventTarget.triggerHandler(name, transformedArgs); } catch (error) { qq.log("Caught error in Fine Uploader jQuery event handler: " + error.message, "error"); } /*jshint -W116*/ if (nonJqueryCallbackRetVal != null) { return nonJqueryCallbackRetVal; } return jqueryEventCallbackRetVal; }; }); newUploaderInstance._options.callbacks = callbacks; }
javascript
{ "resource": "" }
q20531
maybeWrapInJquery
train
function maybeWrapInJquery(val) { var transformedVal = val; // If the command is returning an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object /*jshint -W116*/ if (val != null && typeof val === "object" && (val.nodeType === 1 || val.nodeType === 9) && val.cloneNode) { transformedVal = $(val); } return transformedVal; }
javascript
{ "resource": "" }
q20532
train
function(id, loaded, total) { updateTotalProgress(id, loaded, total); perFileProgress[id] = {loaded: loaded, total: total}; }
javascript
{ "resource": "" }
q20533
examineEvent
train
function examineEvent(target, event) { if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); // We only allow users to change filenames of files that have been submitted but not yet uploaded. if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); qq.preventDefault(event); inheritedInternalApi.handleFilenameEdit(fileId, target, true); } } }
javascript
{ "resource": "" }
q20534
getDirEntryCount
train
function getDirEntryCount(app1Start, littleEndian) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) { if (littleEndian) { return promise.success(parseLittleEndian(hex)); } else { promise.success(parseInt(hex, 16)); } }); return promise; }
javascript
{ "resource": "" }
q20535
getIfd
train
function getIfd(app1Start, dirEntries) { var offset = app1Start + 20, bytes = dirEntries * 12; return qq.readBlobToHex(fileOrBlob, offset, bytes); }
javascript
{ "resource": "" }
q20536
getTagValues
train
function getTagValues(littleEndian, dirEntries) { var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {}; qq.each(dirEntries, function(idx, entry) { var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength; if (tagsToFindIdx >= 0) { tagName = TAG_INFO[id].name; tagValLength = TAG_INFO[id].bytes; tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength * 2)); vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16); tagsToFind.splice(tagsToFindIdx, 1); } if (tagsToFind.length === 0) { return false; } }); return vals; }
javascript
{ "resource": "" }
q20537
handleCompleteRequestComplete
train
function handleCompleteRequestComplete(id, xhr, isError) { var promise = pendingCompleteRequests[id], domParser = new DOMParser(), bucket = options.getBucket(id), key = options.getKey(id), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), bucketEls = responseDoc.getElementsByTagName("Bucket"), keyEls = responseDoc.getElementsByTagName("Key"); delete pendingCompleteRequests[id]; options.log(qq.format("Complete response status {}, body = {}", xhr.status, xhr.responseText)); // If the base requester has determine this a failure, give up. if (isError) { options.log(qq.format("Complete Multipart Upload request for {} failed with status {}.", id, xhr.status), "error"); } else { // Make sure the correct bucket and key has been specified in the XML response from AWS. if (bucketEls.length && keyEls.length) { if (bucketEls[0].textContent !== bucket) { isError = true; options.log(qq.format("Wrong bucket in response to Complete Multipart Upload request for {}.", id), "error"); } // TODO Compare key name from response w/ expected key name if AWS ever fixes the encoding of key names in this response. } else { isError = true; options.log(qq.format("Missing bucket and/or key in response to Complete Multipart Upload request for {}.", id), "error"); } } if (isError) { promise.failure("Problem combining the file parts!", xhr); } else { promise.success({}, xhr); } }
javascript
{ "resource": "" }
q20538
train
function(id, uploadId, etagEntries) { var promise = new qq.Promise(), body = getCompleteRequestBody(etagEntries); getHeaders(id, uploadId, body).then(function(headers, endOfUrl) { options.log("Submitting S3 complete multipart upload request for " + id); pendingCompleteRequests[id] = promise; delete headers["Content-Type"]; requester.initTransport(id) .withPath(endOfUrl) .withHeaders(headers) .withPayload(body) .send(); }, promise.failure); return promise; }
javascript
{ "resource": "" }
q20539
train
function() { var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; log(qq.format("Attempting to determine if {} can be rendered in this browser", name)); log("First pass: check type attribute of blob object."); if (this.isPreviewableSync()) { log("Second pass: check for magic bytes in file header."); qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) { qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) { if (isIdentifiable(bytes, hex)) { // Safari is the only supported browser that can deal with TIFFs natively, // so, if this is a TIFF and the UA isn't Safari, declare this file "non-previewable". if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) { previewable = true; identifier.success(mime); } return false; } }); log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT")); if (!previewable) { identifier.failure(); } }, function() { log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser."); identifier.failure(); }); } else { identifier.failure(); } return identifier; }
javascript
{ "resource": "" }
q20540
train
function(id, xhr, chunkIdx) { var response = upload.response.parse(id, xhr), etag; if (response.success) { etag = xhr.getResponseHeader("ETag"); if (!handler._getPersistableData(id).etags) { handler._getPersistableData(id).etags = []; } handler._getPersistableData(id).etags.push({part: chunkIdx + 1, etag: etag}); } }
javascript
{ "resource": "" }
q20541
train
function(awsParams) { xhr.open("POST", url, true); qq.obj2FormData(awsParams, formData); // AWS requires the file field be named "file". formData.append("file", fileOrBlob); promise.success(formData); }
javascript
{ "resource": "" }
q20542
train
function(awsResponseXml) { var parser = new DOMParser(), parsedDoc = parser.parseFromString(awsResponseXml, "application/xml"), errorEls = parsedDoc.getElementsByTagName("Error"), errorDetails = {}, codeEls, messageEls; if (errorEls.length) { codeEls = parsedDoc.getElementsByTagName("Code"); messageEls = parsedDoc.getElementsByTagName("Message"); if (messageEls.length) { errorDetails.message = messageEls[0].textContent; } if (codeEls.length) { errorDetails.code = codeEls[0].textContent; } return errorDetails; } }
javascript
{ "resource": "" }
q20543
train
function(id, uploadId) { getHeaders(id, uploadId).then(function(headers, endOfUrl) { options.log("Submitting S3 Abort multipart upload request for " + id); requester.initTransport(id) .withPath(endOfUrl) .withHeaders(headers) .send(); }); }
javascript
{ "resource": "" }
q20544
train
function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) { var promiseToReturn = new qq.Promise(), fileOrUrl, options; if (this._imageGenerator) { fileOrUrl = this._thumbnailUrls[fileId]; options = { customResizeFunction: customResizeFunction, maxSize: maxSize > 0 ? maxSize : null, scale: maxSize > 0 }; // If client-side preview generation is possible // and we are not specifically looking for the image URl returned by the server... if (!fromServer && qq.supportedFeatures.imagePreviews) { fileOrUrl = this.getFile(fileId); } /* jshint eqeqeq:false,eqnull:true */ if (fileOrUrl == null) { promiseToReturn.failure({container: imgOrCanvas, error: "File or URL not found."}); } else { this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then( function success(modifiedContainer) { promiseToReturn.success(modifiedContainer); }, function failure(container, reason) { promiseToReturn.failure({container: container, error: reason || "Problem generating thumbnail"}); } ); } } else { promiseToReturn.failure({container: imgOrCanvas, error: "Missing image generator module"}); } return promiseToReturn; }
javascript
{ "resource": "" }
q20545
train
function(id) { var uploadDataEntry = this.getUploads({id: id}), parentId = null; if (uploadDataEntry) { if (uploadDataEntry.parentId !== undefined) { parentId = uploadDataEntry.parentId; } } return parentId; }
javascript
{ "resource": "" }
q20546
train
function(spec) { var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button; function allowMultiple() { if (qq.supportedFeatures.ajaxUploading) { // Workaround for bug in iOS7+ (see #1039) if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) { return false; } if (spec.multiple === undefined) { return self._options.multiple; } return spec.multiple; } return false; } button = new qq.UploadButton({ acceptFiles: acceptFiles, element: spec.element, focusClass: this._options.classes.buttonFocus, folders: spec.folders, hoverClass: this._options.classes.buttonHover, ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash, multiple: allowMultiple(), name: this._options.request.inputName, onChange: function(input) { self._onInputChange(input); }, title: spec.title == null ? this._options.text.fileInputTitle : spec.title }); this._disposeSupport.addDisposer(function() { button.dispose(); }); self._buttons.push(button); return button; }
javascript
{ "resource": "" }
q20547
train
function(buttonOrFileInputOrFile) { var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile; // We want the reference file/blob here if this is a proxy (a file that will be generated on-demand later) if (fileBlobOrInput instanceof qq.BlobProxy) { fileBlobOrInput = fileBlobOrInput.referenceBlob; } // If the item is a `Blob` it will never be associated with a button or drop zone. if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) { if (qq.isFile(fileBlobOrInput)) { return fileBlobOrInput.qqButtonId; } else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") { return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } inputs = fileBlobOrInput.getElementsByTagName("input"); qq.each(inputs, function(idx, input) { if (input.getAttribute("type") === "file") { fileInput = input; return false; } }); if (fileInput) { return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } } }
javascript
{ "resource": "" }
q20548
train
function() { if (this._options.camera.ios && qq.ios()) { var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options; // If we are not targeting the default button, it is an "extra" button if (buttonId && buttonId !== this._defaultButtonId) { optionRoot = this._extraButtonSpecs[buttonId]; } // Camera access won't work in iOS if the `multiple` attribute is present on the file input optionRoot.multiple = false; // update the options if (optionRoot.validation.acceptFiles === null) { optionRoot.validation.acceptFiles = acceptIosCamera; } else { optionRoot.validation.acceptFiles += "," + acceptIosCamera; } // update the already-created button qq.each(this._buttons, function(idx, button) { if (button.getButtonId() === buttonId) { button.setMultiple(optionRoot.multiple); button.setAcceptFiles(optionRoot.acceptFiles); return false; } }); } }
javascript
{ "resource": "" }
q20549
train
function(spec) { var button = this._createUploadButton({ accept: spec.validation.acceptFiles, allowedExtensions: spec.validation.allowedExtensions, element: spec.element, folders: spec.folders, multiple: spec.multiple, title: spec.fileInputTitle }); this._extraButtonSpecs[button.getButtonId()] = spec; }
javascript
{ "resource": "" }
q20550
train
function(id) { var buttonId; if (qq.supportedFeatures.ajaxUploading) { buttonId = this._handler.getFile(id).qqButtonId; } else { buttonId = this._getButtonId(this._handler.getInput(id)); } if (buttonId) { this._buttonIdsForFileIds[id] = buttonId; } }
javascript
{ "resource": "" }
q20551
train
function(fileWrapper, validationDescriptor) { var self = this, file = (function() { if (fileWrapper.file instanceof qq.BlobProxy) { return fileWrapper.file.referenceBlob; } return fileWrapper.file; }()), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise(); validityChecker.then( function() {}, function() { self._fileOrBlobRejected(fileWrapper.id, name); }); if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) { this._itemError("typeError", name, file); return validityChecker.failure(); } if (!this._options.validation.allowEmpty && size === 0) { this._itemError("emptyError", name, file); return validityChecker.failure(); } if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) { this._itemError("sizeError", name, file); return validityChecker.failure(); } if (size > 0 && size < validationBase.minSizeLimit) { this._itemError("minSizeError", name, file); return validityChecker.failure(); } if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) { new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then( validityChecker.success, function(errorCode) { self._itemError(errorCode + "ImageError", name, file); validityChecker.failure(); } ); } else { validityChecker.success(); } return validityChecker; }
javascript
{ "resource": "" }
q20552
train
function(sizes) { "use strict"; sizes = qq.extend([], sizes); return sizes.sort(function(a, b) { if (a.maxSize > b.maxSize) { return 1; } if (a.maxSize < b.maxSize) { return -1; } return 0; }); }
javascript
{ "resource": "" }
q20553
train
function(originalImage, scaledImageDataUri, log) { "use strict"; var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = ""; reader.onload = function() { originalImageDataUri = reader.result; insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri)); }; reader.onerror = function() { log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error"); insertionEffort.failure(); }; reader.readAsDataURL(originalImage); return insertionEffort; }
javascript
{ "resource": "" }
q20554
maybeUploadOnSubmit
train
function maybeUploadOnSubmit(formEl) { var nativeSubmit = formEl.submit; // Intercept and squelch submit events. qq(formEl).attach("submit", function(event) { event = event || window.event; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } validateForm(formEl, nativeSubmit) && startUpload(); }); // The form's `submit()` function may be called instead (i.e. via jQuery.submit()). // Intercept that too. formEl.submit = function() { validateForm(formEl, nativeSubmit) && startUpload(); }; }
javascript
{ "resource": "" }
q20555
train
function(spec) { var status = spec.status || qq.status.SUBMITTING, id = data.push({ name: spec.name, originalName: spec.name, uuid: spec.uuid, size: spec.size == null ? -1 : spec.size, status: status, file: spec.file }) - 1; if (spec.batchId) { data[id].batchId = spec.batchId; if (byBatchId[spec.batchId] === undefined) { byBatchId[spec.batchId] = []; } byBatchId[spec.batchId].push(id); } if (spec.proxyGroupId) { data[id].proxyGroupId = spec.proxyGroupId; if (byProxyGroupId[spec.proxyGroupId] === undefined) { byProxyGroupId[spec.proxyGroupId] = []; } byProxyGroupId[spec.proxyGroupId].push(id); } data[id].id = id; byUuid[spec.uuid] = id; if (byStatus[status] === undefined) { byStatus[status] = []; } byStatus[status].push(id); spec.onBeforeStatusChange && spec.onBeforeStatusChange(id); uploaderProxy.onStatusChange(id, null, status); return id; }
javascript
{ "resource": "" }
q20556
train
function(name) { if (qq.azure.util._paramNameMatchesAzureParameter(name)) { return name; } else { return qq.azure.util.AZURE_PARAM_PREFIX + name; } }
javascript
{ "resource": "" }
q20557
handleInputFocus
train
function handleInputFocus(target, event) { if (spec.templating.isEditInput(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); inheritedInternalApi.handleFilenameEdit(fileId, target); } } }
javascript
{ "resource": "" }
q20558
draw
train
function draw(fileOrBlob, container, options) { var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, // jshint eqnull:true orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() { container.onerror = null; container.onload = null; log("Could not render preview, file may be too large!", "error"); drawPreview.failure(container, "Browser cannot render image!"); }; identifier.isPreviewable().then( function(mime) { // If options explicitly specify that Orientation is not desired, // replace the orient task with a dummy promise that "succeeds" immediately. var dummyExif = { parse: function() { return new qq.Promise().success(); } }, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler); if (registerThumbnailRenderedListener(container, drawPreview)) { exif.parse().then( function(exif) { var orientation = exif && exif.Orientation; mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, orientation: orientation, mime: mime, resize: options.customResizeFunction }); }, function(failureMsg) { log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg)); mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, mime: mime, resize: options.customResizeFunction }); } ); } }, function() { log("Not previewable"); drawPreview.failure(container, "Not previewable"); } ); return drawPreview; }
javascript
{ "resource": "" }
q20559
train
function (nBytes) { var words = []; for (var i = 0; i < nBytes; i += 4) { words.push((Math.random() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); }
javascript
{ "resource": "" }
q20560
train
function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }
javascript
{ "resource": "" }
q20561
train
function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; }
javascript
{ "resource": "" }
q20562
train
function(endpoint) { var patterns = [ //bucket in domain /^(?:https?:\/\/)?([a-z0-9.\-_]+)\.s3(?:-[a-z0-9\-]+)?\.amazonaws\.com/i, //bucket in path /^(?:https?:\/\/)?s3(?:-[a-z0-9\-]+)?\.amazonaws\.com\/([a-z0-9.\-_]+)/i, //custom domain /^(?:https?:\/\/)?([a-z0-9.\-_]+)/i ], bucket; qq.each(patterns, function(idx, pattern) { var match = pattern.exec(endpoint); if (match) { bucket = match[1]; return false; } }); return bucket; }
javascript
{ "resource": "" }
q20563
train
function(name) { if (qq.indexOf(qq.s3.util.UNPREFIXED_PARAM_NAMES, name) >= 0) { return name; } return qq.s3.util.AWS_PARAM_PREFIX + name; }
javascript
{ "resource": "" }
q20564
train
function(policy, minSize, maxSize) { var adjustedMinSize = minSize < 0 ? 0 : minSize, // Adjust a maxSize of 0 to the largest possible integer, since we must specify a high and a low in the request adjustedMaxSize = maxSize <= 0 ? 9007199254740992 : maxSize; if (minSize > 0 || maxSize > 0) { policy.conditions.push(["content-length-range", adjustedMinSize.toString(), adjustedMaxSize.toString()]); } }
javascript
{ "resource": "" }
q20565
train
function(iframe) { var doc = iframe.contentDocument || iframe.contentWindow.document, queryString = doc.location.search, match = /bucket=(.+)&key=(.+)&etag=(.+)/.exec(queryString); if (match) { return { bucket: match[1], key: match[2], etag: match[3].replace(/%22/g, "") }; } }
javascript
{ "resource": "" }
q20566
getCorsAjaxTransport
train
function getCorsAjaxTransport() { var xhrOrXdr; if (window.XMLHttpRequest || window.ActiveXObject) { xhrOrXdr = qq.createXhrInstance(); if (xhrOrXdr.withCredentials === undefined) { xhrOrXdr = new XDomainRequest(); // Workaround for XDR bug in IE9 - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment xhrOrXdr.onload = function() {}; xhrOrXdr.onerror = function() {}; xhrOrXdr.ontimeout = function() {}; xhrOrXdr.onprogress = function() {}; } } return xhrOrXdr; }
javascript
{ "resource": "" }
q20567
dequeue
train
function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; delete requestData[id]; queue.splice(i, 1); if (queue.length >= max && i < max) { nextId = queue[max - 1]; sendRequest(nextId); } }
javascript
{ "resource": "" }
q20568
train
function(optXhr) { if (cacheBuster && qq.indexOf(["GET", "DELETE"], options.method) >= 0) { params.qqtimestamp = new Date().getTime(); } return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload); }
javascript
{ "resource": "" }
q20569
train
function() { var self = this, additionalOptions = { aclStore: this._aclStore, getBucket: qq.bind(this._determineBucket, this), getHost: qq.bind(this._determineHost, this), getKeyName: qq.bind(this._determineKeyName, this), iframeSupport: this._options.iframeSupport, objectProperties: this._options.objectProperties, signature: this._options.signature, clockDrift: this._options.request.clockDrift, // pass size limit validation values to include in the request so AWS enforces this server-side validation: { minSizeLimit: this._options.validation.minSizeLimit, maxSizeLimit: this._options.validation.sizeLimit } }; // We assume HTTP if it is missing from the start of the endpoint string. qq.override(this._endpointStore, function(super_) { return { get: function(id) { var endpoint = super_.get(id); if (endpoint.indexOf("http") < 0) { return "http://" + endpoint; } return endpoint; } }; }); // Some param names should be lower case to avoid signature mismatches qq.override(this._paramsStore, function(super_) { return { get: function(id) { var oldParams = super_.get(id), modifiedParams = {}; qq.each(oldParams, function(name, val) { var paramName = name; if (qq.indexOf(qq.s3.util.CASE_SENSITIVE_PARAM_NAMES, paramName) < 0) { paramName = paramName.toLowerCase(); } modifiedParams[paramName] = qq.isFunction(val) ? val() : val; }); return modifiedParams; } }; }); additionalOptions.signature.credentialsProvider = { get: function() { return self._currentCredentials; }, onExpired: function() { var updateCredentials = new qq.Promise(), callbackRetVal = self._options.callbacks.onCredentialsExpired(); if (qq.isGenericPromise(callbackRetVal)) { callbackRetVal.then(function(credentials) { try { self.setCredentials(credentials); updateCredentials.success(); } catch (error) { self.log("Invalid credentials returned from onCredentialsExpired callback! (" + error.message + ")", "error"); updateCredentials.failure("onCredentialsExpired did not return valid credentials."); } }, function(errorMsg) { self.log("onCredentialsExpired callback indicated failure! (" + errorMsg + ")", "error"); updateCredentials.failure("onCredentialsExpired callback failed."); }); } else { self.log("onCredentialsExpired callback did not return a promise!", "error"); updateCredentials.failure("Unexpected return value for onCredentialsExpired."); } return updateCredentials; } }; return qq.FineUploaderBasic.prototype._createUploadHandler.call(this, additionalOptions, "s3"); }
javascript
{ "resource": "" }
q20570
train
function(keynameFunc, id, successCallback, failureCallback) { var self = this, onSuccess = function(keyname) { successCallback(keyname); }, onFailure = function(reason) { self.log(qq.format("Failed to retrieve key name for {}. Reason: {}", id, reason || "null"), "error"); failureCallback(reason); }, keyname = keynameFunc.call(this, id); if (qq.isGenericPromise(keyname)) { keyname.then(onSuccess, onFailure); } /*jshint -W116*/ else if (keyname == null) { onFailure(); } else { onSuccess(keyname); } }
javascript
{ "resource": "" }
q20571
train
function(id, onSuccessCallback) { var additionalMandatedParams = { key: this.getKey(id), bucket: this.getBucket(id) }; return qq.FineUploaderBasic.prototype._onSubmitDelete.call(this, id, onSuccessCallback, additionalMandatedParams); }
javascript
{ "resource": "" }
q20572
train
function(id, chunkIdx, response, xhr) { var chunkData = handler._getChunkData(id, chunkIdx); handler._getFileState(id).attemptingResume = false; delete handler._getFileState(id).temp.chunkProgress[chunkIdx]; handler._getFileState(id).loaded += chunkData.size; options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr); }
javascript
{ "resource": "" }
q20573
train
function(id) { var size = options.getSize(id), name = options.getName(id); log("All chunks have been uploaded for " + id + " - finalizing...."); handler.finalizeChunks(id).then( function(response, xhr) { log("Finalize successful for " + id); var normaizedResponse = upload.normalizeResponse(response, true); options.onProgress(id, name, size, size); handler._maybeDeletePersistedChunkData(id); upload.cleanup(id, normaizedResponse, xhr); }, function(response, xhr) { var normalizedResponse = upload.normalizeResponse(response, false); log("Problem finalizing chunks for file ID " + id + " - " + normalizedResponse.error, "error"); if ( normalizedResponse.reset || (xhr && options.chunking.success.resetOnStatus.indexOf(xhr.status) >= 0) ) { chunked.reset(id); } if (!options.onAutoRetry(id, name, normalizedResponse, xhr)) { upload.cleanup(id, normalizedResponse, xhr); } } ); }
javascript
{ "resource": "" }
q20574
train
function(errorMessage) { var errorResponse = {}; if (errorMessage) { errorResponse.error = errorMessage; } log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error"); options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null); upload.maybeSendDeferredFiles(id); connectionManager.free(id); }
javascript
{ "resource": "" }
q20575
train
function(originalResponse, successful) { var response = originalResponse; // The passed "response" param may not be a response at all. // It could be a string, detailing the error, for example. if (!qq.isObject(originalResponse)) { response = {}; if (qq.isString(originalResponse) && !successful) { response.error = originalResponse; } } response.success = successful; return response; }
javascript
{ "resource": "" }
q20576
train
function() { var waitingOrConnected = connectionManager.getWaitingOrConnected(), i; // ensure files are cancelled in reverse order which they were added // to avoid a flash of time where a queued file begins to upload before it is canceled if (waitingOrConnected.length) { for (i = waitingOrConnected.length - 1; i >= 0; i--) { controller.cancel(waitingOrConnected[i]); } } connectionManager.reset(); }
javascript
{ "resource": "" }
q20577
train
function(id) { if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) { connectionManager.free(id); handler.moveInProgressToRemaining(id); return true; } return false; }
javascript
{ "resource": "" }
q20578
isChrome14OrHigher
train
function isChrome14OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined; }
javascript
{ "resource": "" }
q20579
isCrossOriginXhrSupported
train
function isCrossOriginXhrSupported() { if (window.XMLHttpRequest) { var xhr = qq.createXhrInstance(); //Commonly accepted test for XHR CORS support. return xhr.withCredentials !== undefined; } return false; }
javascript
{ "resource": "" }
q20580
train
function(id, toBeSigned) { var params = toBeSigned, signatureConstructor = toBeSigned.signatureConstructor, signatureEffort = new qq.Promise(), queryParams; if (options.signatureSpec.version === 4) { queryParams = {v4: true}; } if (credentialsProvider.get().secretKey && qq.CryptoJS) { if (credentialsProvider.get().expiration.getTime() > Date.now()) { determineSignatureClientSide(id, toBeSigned, signatureEffort); } // If credentials are expired, ask for new ones before attempting to sign request else { credentialsProvider.onExpired().then(function() { determineSignatureClientSide(id, toBeSigned, signatureEffort, credentialsProvider.get().accessKey, credentialsProvider.get().sessionToken); }, function(errorMsg) { options.log("Attempt to update expired credentials apparently failed! Unable to sign request. ", "error"); signatureEffort.failure("Unable to sign request - expired credentials."); }); } } else { options.log("Submitting S3 signature request for " + id); if (signatureConstructor) { signatureConstructor.getToSign(id).then(function(signatureArtifacts) { params = {headers: signatureArtifacts.stringToSignRaw}; requester.initTransport(id) .withParams(params) .withQueryParams(queryParams) .send(); }, function (err) { options.log("Failed to construct signature. ", "error"); signatureEffort.failure("Failed to construct signature."); }); } else { requester.initTransport(id) .withParams(params) .withQueryParams(queryParams) .send(); } pendingSignatures[id] = { promise: signatureEffort, signatureConstructor: signatureConstructor }; } return signatureEffort; }
javascript
{ "resource": "" }
q20581
train
function(id) { // If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }
javascript
{ "resource": "" }
q20582
train
function(id, name, loaded, total) { this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (total === 0 || Math.round(loaded / total * 100) === 100) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.hideProgress(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); // If ~last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); } }
javascript
{ "resource": "" }
q20583
handleInitiateRequestComplete
train
function handleInitiateRequestComplete(id, xhr, isError) { var promise = pendingInitiateRequests[id], domParser = new DOMParser(), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), uploadIdElements, messageElements, uploadId, errorMessage, status; delete pendingInitiateRequests[id]; // The base ajax requester may declare the request to be a failure based on status code. if (isError) { status = xhr.status; messageElements = responseDoc.getElementsByTagName("Message"); if (messageElements.length > 0) { errorMessage = messageElements[0].textContent; } } // If the base ajax requester has not declared this a failure, make sure we can retrieve the uploadId from the response. else { uploadIdElements = responseDoc.getElementsByTagName("UploadId"); if (uploadIdElements.length > 0) { uploadId = uploadIdElements[0].textContent; } else { errorMessage = "Upload ID missing from request"; } } // Either fail the promise (passing a descriptive error message) or declare it a success (passing the upload ID) if (uploadId === undefined) { if (errorMessage) { options.log(qq.format("Specific problem detected initiating multipart upload request for {}: '{}'.", id, errorMessage), "error"); } else { options.log(qq.format("Unexplained error with initiate multipart upload request for {}. Status code {}.", id, status), "error"); } promise.failure("Problem initiating upload request.", xhr); } else { options.log(qq.format("Initiate multipart upload request successful for {}. Upload ID is {}", id, uploadId)); promise.success(uploadId, xhr); } }
javascript
{ "resource": "" }
q20584
expungeFile
train
function expungeFile(id) { delete detachLoadEvents[id]; // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe. // In that case, terminate the timer waiting for a message from the loaded iframe // and stop listening for any more messages coming from this iframe. if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { // To cancel request set src to something else. We use src="javascript:false;" // because it doesn't trigger ie6 prompt on https /* jshint scripturl:true */ iframe.setAttribute("src", "javascript:false;"); qq(iframe).remove(); } }
javascript
{ "resource": "" }
q20585
initIframeForUpload
train
function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; }
javascript
{ "resource": "" }
q20586
train
function(id, fileInput) { super_.add(id, {input: fileInput}); fileInput.setAttribute("name", inputName); // remove file input from DOM if (fileInput.parentNode) { qq(fileInput).remove(); } }
javascript
{ "resource": "" }
q20587
train
function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }
javascript
{ "resource": "" }
q20588
train
function(id, chunkIdx) { var fileState = handler._getFileState(id); if (fileState) { delete fileState.temp.cachedChunks[chunkIdx]; } }
javascript
{ "resource": "" }
q20589
train
function(id, responseParser) { var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx); if (responseParser) { return new qq.Promise().success(responseParser(xhr), xhr); } return new qq.Promise().success({}, xhr); }
javascript
{ "resource": "" }
q20590
train
function(id) { var localStorageId; if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); if (localStorageId && localStorage.getItem(localStorageId)) { localStorage.removeItem(localStorageId); return true; } } return false; }
javascript
{ "resource": "" }
q20591
train
function(id, optChunkIdx, xhr, optAjaxRequester) { var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp; tempState.xhrs = tempState.xhrs || {}; tempState.ajaxRequesters = tempState.ajaxRequesters || {}; tempState.xhrs[xhrsId] = xhr; if (optAjaxRequester) { tempState.ajaxRequesters[xhrsId] = optAjaxRequester; } return xhr; }
javascript
{ "resource": "" }
q20592
train
function() { var expirationDays = resume.recordsExpireIn; handler._iterateResumeRecords(function(key, uploadData) { var expirationDate = new Date(uploadData.lastUpdated); // transform updated date into expiration date expirationDate.setDate(expirationDate.getDate() + expirationDays); if (expirationDate.getTime() <= Date.now()) { log("Removing expired resume record with key " + key); localStorage.removeItem(key); } }); }
javascript
{ "resource": "" }
q20593
routePath
train
function routePath (route) { if (!route) return '' return route.path || (route.regexp && route.regexp.source) || '' }
javascript
{ "resource": "" }
q20594
getPathFromRequest
train
function getPathFromRequest (req, useBase, usePathAsTransactionName) { // Static serving route if (req[symbols.staticFile]) { return 'static file' } var path = getStackPath(req) var route = routePath(req.route) if (route) { return path ? join([ path, route ]) : route } if (useBase) { return path } // Enable usePathAsTransactionName config if (usePathAsTransactionName) { const parsed = parseUrl(req) return parsed && parsed.pathname } }
javascript
{ "resource": "" }
q20595
activator
train
function activator (fn) { var fallback = function () { var args var cbIdx = arguments.length - 1 if (typeof arguments[cbIdx] === 'function') { args = Array(arguments.length) for (var i = 0; i < arguments.length - 1; i++) { args[i] = arguments[i] } args[cbIdx] = ins.bindFunction(arguments[cbIdx]) } return fn.apply(this, args || arguments) } // Preserve function length for small arg count functions. switch (fn.length) { case 1: return function (cb) { if (arguments.length !== 1) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, cb) } case 2: return function (a, cb) { if (arguments.length !== 2) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, cb) } case 3: return function (a, b, cb) { if (arguments.length !== 3) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, cb) } case 4: return function (a, b, c, cb) { if (arguments.length !== 4) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, cb) } case 5: return function (a, b, c, d, cb) { if (arguments.length !== 5) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, d, cb) } case 6: return function (a, b, c, d, e, cb) { if (arguments.length !== 6) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, d, e, cb) } default: return fallback } }
javascript
{ "resource": "" }
q20596
wrapInitPromise
train
function wrapInitPromise (original) { return function wrappedInitPromise () { var command = this var cb = this.callback if (typeof cb === 'function') { this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { var span = command[spanSym] if (span && !span.ended) span.end() return cb.apply(this, arguments) }) } return original.apply(this, arguments) } }
javascript
{ "resource": "" }
q20597
wrapCreateServer
train
function wrapCreateServer (original) { return function wrappedCreateServer (options, handler) { var server = original.apply(this, arguments) shimmer.wrap(server.constructor.prototype, 'emit', wrapEmit) wrappedCreateServer[symbols.unwrap]() return server } }
javascript
{ "resource": "" }
q20598
getCulprit
train
function getCulprit (frames) { if (frames.length === 0) return var filename = frames[0].filename var fnName = frames[0].function for (var n = 0; n < frames.length; n++) { if (!frames[n].library_frame) { filename = frames[n].filename fnName = frames[n].function break } } return filename ? fnName + ' (' + filename + ')' : fnName }
javascript
{ "resource": "" }
q20599
linux
train
function linux(canary) { let installations = []; // Look into the directories where .desktop are saved on gnome based distro's const desktopInstallationFolders = [ path.join(require('os').homedir(), '.local/share/applications/'), '/usr/share/applications/', ]; desktopInstallationFolders.forEach(folder => { installations = installations.concat(findChromeExecutables(folder)); }); // Look for google-chrome(-stable) & chromium(-browser) executables by using the which command const executables = [ 'google-chrome-stable', 'google-chrome', 'chromium-browser', 'chromium', ]; executables.forEach(executable => { try { const chromePath = execFileSync('which', [executable], {stdio: 'pipe'}).toString().split(newLineRegex)[0]; if (canAccess(chromePath)) installations.push(chromePath); } catch (e) { // Not installed. } }); if (!installations.length) throw new Error('The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.'); const priorities = [ {regex: /chrome-wrapper$/, weight: 51}, {regex: /google-chrome-stable$/, weight: 50}, {regex: /google-chrome$/, weight: 49}, {regex: /chromium-browser$/, weight: 48}, {regex: /chromium$/, weight: 47}, ]; if (process.env.CHROME_PATH) priorities.unshift({regex: new RegExp(`${process.env.CHROME_PATH}`), weight: 101}); return sort(uniq(installations.filter(Boolean)), priorities)[0]; }
javascript
{ "resource": "" }