_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q17400
_itemsPerPage
train
function _itemsPerPage() { var itemsPerPage = 1, $items = self.$hintMenu.find("li"), $view = self.$hintMenu.find("ul.dropdown-menu"), itemHeight; if ($items.length !== 0) { itemHeight = $($items[0]).height(); if (itemHeight) { // round down to integer value itemsPerPage = Math.floor($view.height() / itemHeight); itemsPerPage = Math.max(1, Math.min(itemsPerPage, $items.length)); } } return itemsPerPage; }
javascript
{ "resource": "" }
q17401
stripQuotes
train
function stripQuotes(string) { if (string) { if (/^['"]$/.test(string.charAt(0))) { string = string.substr(1); } if (/^['"]$/.test(string.substr(-1, 1))) { string = string.substr(0, string.length - 1); } } return string; }
javascript
{ "resource": "" }
q17402
add
train
function add() { var root = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath), recentProjects = getRecentProjects(), index = recentProjects.indexOf(root); if (index !== -1) { recentProjects.splice(index, 1); } recentProjects.unshift(root); if (recentProjects.length > MAX_PROJECTS) { recentProjects = recentProjects.slice(0, MAX_PROJECTS); } PreferencesManager.setViewState("recentProjects", recentProjects); }
javascript
{ "resource": "" }
q17403
checkHovers
train
function checkHovers(pageX, pageY) { $dropdown.children().each(function () { var offset = $(this).offset(), width = $(this).outerWidth(), height = $(this).outerHeight(); if (pageX >= offset.left && pageX <= offset.left + width && pageY >= offset.top && pageY <= offset.top + height) { $(".recent-folder-link", this).triggerHandler("mouseenter"); } }); }
javascript
{ "resource": "" }
q17404
renderDelete
train
function renderDelete() { return $("<div id='recent-folder-delete' class='trash-icon'>&times;</div>") .mouseup(function (e) { // Don't let the click bubble upward. e.stopPropagation(); // Remove the project from the preferences. var recentProjects = getRecentProjects(), index = recentProjects.indexOf($(this).parent().data("path")), newProjects = [], i; for (i = 0; i < recentProjects.length; i++) { if (i !== index) { newProjects.push(recentProjects[i]); } } PreferencesManager.setViewState("recentProjects", newProjects); $(this).closest("li").remove(); checkHovers(e.pageX, e.pageY); if (newProjects.length === 1) { $dropdown.find(".divider").remove(); } }); }
javascript
{ "resource": "" }
q17405
selectNextItem
train
function selectNextItem(direction) { var $links = $dropdown.find("a"), index = $dropdownItem ? $links.index($dropdownItem) : (direction > 0 ? -1 : 0), $newItem = $links.eq((index + direction) % $links.length); if ($dropdownItem) { $dropdownItem.removeClass("selected"); } $newItem.addClass("selected"); $dropdownItem = $newItem; removeDeleteButton(); }
javascript
{ "resource": "" }
q17406
removeSelectedItem
train
function removeSelectedItem(e) { var recentProjects = getRecentProjects(), $cacheItem = $dropdownItem, index = recentProjects.indexOf($cacheItem.data("path")); // When focus is not on project item if (index === -1) { return false; } // remove project recentProjects.splice(index, 1); PreferencesManager.setViewState("recentProjects", recentProjects); checkHovers(e.pageX, e.pageY); if (recentProjects.length === 1) { $dropdown.find(".divider").remove(); } selectNextItem(+1); $cacheItem.closest("li").remove(); return true; }
javascript
{ "resource": "" }
q17407
keydownHook
train
function keydownHook(event) { var keyHandled = false; switch (event.keyCode) { case KeyEvent.DOM_VK_UP: selectNextItem(-1); keyHandled = true; break; case KeyEvent.DOM_VK_DOWN: selectNextItem(+1); keyHandled = true; break; case KeyEvent.DOM_VK_ENTER: case KeyEvent.DOM_VK_RETURN: if ($dropdownItem) { $dropdownItem.trigger("click"); } keyHandled = true; break; case KeyEvent.DOM_VK_BACK_SPACE: case KeyEvent.DOM_VK_DELETE: if ($dropdownItem) { removeSelectedItem(event); keyHandled = true; } break; } if (keyHandled) { event.stopImmediatePropagation(); event.preventDefault(); } return keyHandled; }
javascript
{ "resource": "" }
q17408
cleanupDropdown
train
function cleanupDropdown() { $("html").off("click", closeDropdown); $("#project-files-container").off("scroll", closeDropdown); $("#titlebar .nav").off("click", closeDropdown); $dropdown = null; MainViewManager.focusActivePane(); $(window).off("keydown", keydownHook); }
javascript
{ "resource": "" }
q17409
parsePath
train
function parsePath(path) { var lastSlash = path.lastIndexOf("/"), folder, rest; if (lastSlash === path.length - 1) { lastSlash = path.slice(0, path.length - 1).lastIndexOf("/"); } if (lastSlash >= 0) { rest = " - " + (lastSlash ? path.slice(0, lastSlash) : "/"); folder = path.slice(lastSlash + 1); } else { rest = "/"; folder = path; } return {path: path, folder: folder, rest: rest}; }
javascript
{ "resource": "" }
q17410
renderList
train
function renderList() { var recentProjects = getRecentProjects(), currentProject = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath), templateVars = { projectList : [], Strings : Strings }; recentProjects.forEach(function (root) { if (root !== currentProject) { templateVars.projectList.push(parsePath(root)); } }); return Mustache.render(ProjectsMenuTemplate, templateVars); }
javascript
{ "resource": "" }
q17411
showDropdown
train
function showDropdown(position) { // If the dropdown is already visible, just return (so the root click handler on html // will close it). if ($dropdown) { return; } Menus.closeAll(); $dropdown = $(renderList()) .css({ left: position.pageX, top: position.pageY }) .appendTo($("body")); PopUpManager.addPopUp($dropdown, cleanupDropdown, true); // TODO: should use capture, otherwise clicking on the menus doesn't close it. More fallout // from the fact that we can't use the Boostrap (1.4) dropdowns. $("html").on("click", closeDropdown); // Hide the menu if the user scrolls in the project tree. Otherwise the Lion scrollbar // overlaps it. // TODO: This duplicates logic that's already in ProjectManager (which calls Menus.close()). // We should fix this when the popup handling is centralized in PopupManager, as well // as making Esc close the dropdown. See issue #1381. $("#project-files-container").on("scroll", closeDropdown); // Note: PopUpManager will automatically hide the sidebar in other cases, such as when a // command is run, Esc is pressed, or the menu is focused. // Hacky: if we detect a click in the menubar, close ourselves. // TODO: again, we should have centralized popup management. $("#titlebar .nav").on("click", closeDropdown); _handleListEvents(); $(window).on("keydown", keydownHook); }
javascript
{ "resource": "" }
q17412
handleKeyEvent
train
function handleKeyEvent() { if (!$dropdown) { if (!SidebarView.isVisible()) { SidebarView.show(); } $("#project-dropdown-toggle").trigger("click"); $dropdown.focus(); $links = $dropdown.find("a"); // By default, select the most recent project (which is at the top of the list underneath Open Folder), // but if there are none, select Open Folder instead. $dropdownItem = $links.eq($links.length > 1 ? 1 : 0); $dropdownItem.addClass("selected"); // If focusing the dropdown caused a modal bar to close, we need to refocus the dropdown window.setTimeout(function () { $dropdown.focus(); }, 0); } }
javascript
{ "resource": "" }
q17413
_validateFrame
train
function _validateFrame(entry) { var deferred = new $.Deferred(), fileEntry = FileSystem.getFileForPath(entry.filePath); if (entry.inMem) { var indexInWS = MainViewManager.findInWorkingSet(entry.paneId, entry.filePath); // Remove entry if InMemoryFile is not found in Working set if (indexInWS === -1) { deferred.reject(); } else { deferred.resolve(); } } else { fileEntry.exists(function (err, exists) { if (!err && exists) { // Additional check to handle external modification and mutation of the doc text affecting markers if (fileEntry._hash !== entry._hash) { deferred.reject(); } else if (!entry._validateMarkers()) { deferred.reject(); } else { deferred.resolve(); } } else { deferred.reject(); } }); } return deferred.promise(); }
javascript
{ "resource": "" }
q17414
_navigateBack
train
function _navigateBack() { if (!jumpForwardStack.length) { if (activePosNotSynced) { currentEditPos = new NavigationFrame(EditorManager.getCurrentFullEditor(), {ranges: EditorManager.getCurrentFullEditor()._codeMirror.listSelections()}); jumpForwardStack.push(currentEditPos); } } var navFrame = jumpBackwardStack.pop(); // Check if the poped frame is the current active frame or doesn't have any valid marker information // if true, jump again if (navFrame && navFrame === currentEditPos) { jumpForwardStack.push(navFrame); _validateNavigationCmds(); CommandManager.execute(NAVIGATION_JUMP_BACK); return; } if (navFrame) { // We will check for the file existence now, if it doesn't exist we will jump back again // but discard the popped frame as invalid. _validateFrame(navFrame).done(function () { jumpForwardStack.push(navFrame); navFrame.goTo(); currentEditPos = navFrame; }).fail(function () { CommandManager.execute(NAVIGATION_JUMP_BACK); }).always(function () { _validateNavigationCmds(); }); } }
javascript
{ "resource": "" }
q17415
_navigateForward
train
function _navigateForward() { var navFrame = jumpForwardStack.pop(); if (!navFrame) { return; } // Check if the poped frame is the current active frame or doesn't have any valid marker information // if true, jump again if (navFrame === currentEditPos) { jumpBackwardStack.push(navFrame); _validateNavigationCmds(); CommandManager.execute(NAVIGATION_JUMP_FWD); return; } // We will check for the file existence now, if it doesn't exist we will jump back again // but discard the popped frame as invalid. _validateFrame(navFrame).done(function () { jumpBackwardStack.push(navFrame); navFrame.goTo(); currentEditPos = navFrame; }).fail(function () { _validateNavigationCmds(); CommandManager.execute(NAVIGATION_JUMP_FWD); }).always(function () { _validateNavigationCmds(); }); }
javascript
{ "resource": "" }
q17416
_initNavigationMenuItems
train
function _initNavigationMenuItems() { var menu = Menus.getMenu(Menus.AppMenuBar.NAVIGATE_MENU); menu.addMenuItem(NAVIGATION_JUMP_BACK, "", Menus.AFTER, Commands.NAVIGATE_PREV_DOC); menu.addMenuItem(NAVIGATION_JUMP_FWD, "", Menus.AFTER, NAVIGATION_JUMP_BACK); }
javascript
{ "resource": "" }
q17417
_initNavigationCommands
train
function _initNavigationCommands() { CommandManager.register(Strings.CMD_NAVIGATE_BACKWARD, NAVIGATION_JUMP_BACK, _navigateBack); CommandManager.register(Strings.CMD_NAVIGATE_FORWARD, NAVIGATION_JUMP_FWD, _navigateForward); commandJumpBack = CommandManager.get(NAVIGATION_JUMP_BACK); commandJumpFwd = CommandManager.get(NAVIGATION_JUMP_FWD); commandJumpBack.setEnabled(false); commandJumpFwd.setEnabled(false); KeyBindingManager.addBinding(NAVIGATION_JUMP_BACK, KeyboardPrefs[NAVIGATION_JUMP_BACK]); KeyBindingManager.addBinding(NAVIGATION_JUMP_FWD, KeyboardPrefs[NAVIGATION_JUMP_FWD]); _initNavigationMenuItems(); }
javascript
{ "resource": "" }
q17418
_captureFrame
train
function _captureFrame(editor) { // Capture the active position now if it was not captured earlier if ((activePosNotSynced || !jumpBackwardStack.length) && !jumpInProgress) { jumpBackwardStack.push(new NavigationFrame(editor, {ranges: editor._codeMirror.listSelections()})); } }
javascript
{ "resource": "" }
q17419
_backupLiveMarkers
train
function _backupLiveMarkers(frames, editor) { var index, frame; for (index in frames) { frame = frames[index]; if (frame.cm === editor._codeMirror) { frame._handleEditorDestroy(); } } }
javascript
{ "resource": "" }
q17420
_handleExternalChange
train
function _handleExternalChange(evt, doc) { if (doc) { _removeBackwardFramesForFile(doc.file); _removeForwardFramesForFile(doc.file); _validateNavigationCmds(); } }
javascript
{ "resource": "" }
q17421
_reinstateMarkers
train
function _reinstateMarkers(editor, frames) { var index, frame; for (index in frames) { frame = frames[index]; if (!frame.cm && frame.filePath === editor.document.file._path) { frame._reinstateMarkers(editor); } } }
javascript
{ "resource": "" }
q17422
_handleActiveEditorChange
train
function _handleActiveEditorChange(event, current, previous) { if (previous && previous._paneId) { // Handle only full editors previous.off("beforeSelectionChange", _recordJumpDef); _captureFrame(previous); _validateNavigationCmds(); } if (current && current._paneId) { // Handle only full editors activePosNotSynced = true; current.off("beforeSelectionChange", _recordJumpDef); current.on("beforeSelectionChange", _recordJumpDef); current.off("beforeDestroy", _handleEditorCleanup); current.on("beforeDestroy", _handleEditorCleanup); } }
javascript
{ "resource": "" }
q17423
repositionResizer
train
function repositionResizer(elementSize) { var resizerPosition = elementSize || 1; if (position === POSITION_RIGHT || position === POSITION_BOTTOM) { $resizer.css(resizerCSSPosition, resizerPosition); } }
javascript
{ "resource": "" }
q17424
_enqueueChange
train
function _enqueueChange(changedPath, stats) { _pendingChanges[changedPath] = stats; if (!_changeTimeout) { _changeTimeout = window.setTimeout(function () { if (_changeCallback) { Object.keys(_pendingChanges).forEach(function (path) { _changeCallback(path, _pendingChanges[path]); }); } _changeTimeout = null; _pendingChanges = {}; }, FILE_WATCHER_BATCH_TIMEOUT); } }
javascript
{ "resource": "" }
q17425
_fileWatcherChange
train
function _fileWatcherChange(evt, event, parentDirPath, entryName, statsObj) { var change; switch (event) { case "changed": // an existing file/directory was modified; stats are passed if available var fsStats; if (statsObj) { fsStats = new FileSystemStats(statsObj); } else { console.warn("FileWatcherDomain was expected to deliver stats for changed event!"); } _enqueueChange(parentDirPath + entryName, fsStats); break; case "created": case "deleted": // file/directory was created/deleted; fire change on parent to reload contents _enqueueChange(parentDirPath, null); break; default: console.error("Unexpected 'change' event:", event); } }
javascript
{ "resource": "" }
q17426
_mapError
train
function _mapError(err) { if (!err) { return null; } switch (err) { case appshell.fs.ERR_INVALID_PARAMS: return FileSystemError.INVALID_PARAMS; case appshell.fs.ERR_NOT_FOUND: return FileSystemError.NOT_FOUND; case appshell.fs.ERR_CANT_READ: return FileSystemError.NOT_READABLE; case appshell.fs.ERR_CANT_WRITE: return FileSystemError.NOT_WRITABLE; case appshell.fs.ERR_UNSUPPORTED_ENCODING: return FileSystemError.UNSUPPORTED_ENCODING; case appshell.fs.ERR_OUT_OF_SPACE: return FileSystemError.OUT_OF_SPACE; case appshell.fs.ERR_FILE_EXISTS: return FileSystemError.ALREADY_EXISTS; case appshell.fs.ERR_ENCODE_FILE_FAILED: return FileSystemError.ENCODE_FILE_FAILED; case appshell.fs.ERR_DECODE_FILE_FAILED: return FileSystemError.DECODE_FILE_FAILED; case appshell.fs.ERR_UNSUPPORTED_UTF16_ENCODING: return FileSystemError.UNSUPPORTED_UTF16_ENCODING; } return FileSystemError.UNKNOWN; }
javascript
{ "resource": "" }
q17427
showOpenDialog
train
function showOpenDialog(allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, callback) { appshell.fs.showOpenDialog(allowMultipleSelection, chooseDirectories, title, initialPath, fileTypes, _wrap(callback)); }
javascript
{ "resource": "" }
q17428
showSaveDialog
train
function showSaveDialog(title, initialPath, proposedNewFilename, callback) { appshell.fs.showSaveDialog(title, initialPath, proposedNewFilename, _wrap(callback)); }
javascript
{ "resource": "" }
q17429
stat
train
function stat(path, callback) { appshell.fs.stat(path, function (err, stats) { if (err) { callback(_mapError(err)); } else { var options = { isFile: stats.isFile(), mtime: stats.mtime, size: stats.size, realPath: stats.realPath, hash: stats.mtime.getTime() }; var fsStats = new FileSystemStats(options); callback(null, fsStats); } }); }
javascript
{ "resource": "" }
q17430
exists
train
function exists(path, callback) { stat(path, function (err) { if (err) { if (err === FileSystemError.NOT_FOUND) { callback(null, false); } else { callback(err); } return; } callback(null, true); }); }
javascript
{ "resource": "" }
q17431
mkdir
train
function mkdir(path, mode, callback) { if (typeof mode === "function") { callback = mode; mode = parseInt("0755", 8); } appshell.fs.makedir(path, mode, function (err) { if (err) { callback(_mapError(err)); } else { stat(path, function (err, stat) { callback(err, stat); }); } }); }
javascript
{ "resource": "" }
q17432
rename
train
function rename(oldPath, newPath, callback) { appshell.fs.rename(oldPath, newPath, _wrap(callback)); }
javascript
{ "resource": "" }
q17433
doReadFile
train
function doReadFile(stat) { if (stat.size > (FileUtils.MAX_FILE_SIZE)) { callback(FileSystemError.EXCEEDS_MAX_FILE_SIZE); } else { appshell.fs.readFile(path, encoding, function (_err, _data, encoding, preserveBOM) { if (_err) { callback(_mapError(_err)); } else { callback(null, _data, encoding, preserveBOM, stat); } }); } }
javascript
{ "resource": "" }
q17434
moveToTrash
train
function moveToTrash(path, callback) { appshell.fs.moveToTrash(path, function (err) { callback(_mapError(err)); }); }
javascript
{ "resource": "" }
q17435
watchPath
train
function watchPath(path, ignored, callback) { if (_isRunningOnWindowsXP) { callback(FileSystemError.NOT_SUPPORTED); return; } appshell.fs.isNetworkDrive(path, function (err, isNetworkDrive) { if (err || isNetworkDrive) { if (isNetworkDrive) { callback(FileSystemError.NETWORK_DRIVE_NOT_SUPPORTED); } else { callback(FileSystemError.UNKNOWN); } return; } _nodeDomain.exec("watchPath", path, ignored) .then(callback, callback); }); }
javascript
{ "resource": "" }
q17436
unwatchPath
train
function unwatchPath(path, ignored, callback) { _nodeDomain.exec("unwatchPath", path) .then(callback, callback); }
javascript
{ "resource": "" }
q17437
reloadDoc
train
function reloadDoc(doc) { var promise = FileUtils.readAsText(doc.file); promise.done(function (text, readTimestamp) { doc.refreshText(text, readTimestamp); }); promise.fail(function (error) { console.log("Error reloading contents of " + doc.file.fullPath, error); }); return promise; }
javascript
{ "resource": "" }
q17438
parsePersonString
train
function parsePersonString(obj) { if (typeof (obj) === "string") { var parts = _personRegex.exec(obj); // No regex match, so we just synthesize an object with an opaque name string if (!parts) { return { name: obj }; } else { var result = { name: parts[1] }; if (parts[2]) { result.email = parts[2]; } if (parts[3]) { result.url = parts[3]; } return result; } } else { // obj is not a string, so return as is return obj; } }
javascript
{ "resource": "" }
q17439
containsWords
train
function containsWords(wordlist, str) { var i; var matches = []; for (i = 0; i < wordlist.length; i++) { var re = new RegExp("\\b" + wordlist[i] + "\\b", "i"); if (re.exec(str)) { matches.push(wordlist[i]); } } return matches; }
javascript
{ "resource": "" }
q17440
findCommonPrefix
train
function findCommonPrefix(extractDir, callback) { fs.readdir(extractDir, function (err, files) { ignoredFolders.forEach(function (folder) { var index = files.indexOf(folder); if (index !== -1) { files.splice(index, 1); } }); if (err) { callback(err); } else if (files.length === 1) { var name = files[0]; if (fs.statSync(path.join(extractDir, name)).isDirectory()) { callback(null, name); } else { callback(null, ""); } } else { callback(null, ""); } }); }
javascript
{ "resource": "" }
q17441
validatePackageJSON
train
function validatePackageJSON(path, packageJSON, options, callback) { var errors = []; if (fs.existsSync(packageJSON)) { fs.readFile(packageJSON, { encoding: "utf8" }, function (err, data) { if (err) { callback(err, null, null); return; } var metadata; try { metadata = JSON.parse(data); } catch (e) { errors.push([Errors.INVALID_PACKAGE_JSON, e.toString(), path]); callback(null, errors, undefined); return; } // confirm required fields in the metadata if (!metadata.name) { errors.push([Errors.MISSING_PACKAGE_NAME, path]); } else if (!validateName(metadata.name)) { errors.push([Errors.BAD_PACKAGE_NAME, metadata.name]); } if (!metadata.version) { errors.push([Errors.MISSING_PACKAGE_VERSION, path]); } else if (!semver.valid(metadata.version)) { errors.push([Errors.INVALID_VERSION_NUMBER, metadata.version, path]); } // normalize the author if (metadata.author) { metadata.author = parsePersonString(metadata.author); } // contributors should be an array of people. // normalize each entry. if (metadata.contributors) { if (metadata.contributors.map) { metadata.contributors = metadata.contributors.map(function (person) { return parsePersonString(person); }); } else { metadata.contributors = [ parsePersonString(metadata.contributors) ]; } } if (metadata.engines && metadata.engines.brackets) { var range = metadata.engines.brackets; if (!semver.validRange(range)) { errors.push([Errors.INVALID_BRACKETS_VERSION, range, path]); } } if (options.disallowedWords) { ["title", "description", "name"].forEach(function (field) { var words = containsWords(options.disallowedWords, metadata[field]); if (words.length > 0) { errors.push([Errors.DISALLOWED_WORDS, field, words.toString(), path]); } }); } callback(null, errors, metadata); }); } else { if (options.requirePackageJSON) { errors.push([Errors.MISSING_PACKAGE_JSON, path]); } callback(null, errors, null); } }
javascript
{ "resource": "" }
q17442
extractAndValidateFiles
train
function extractAndValidateFiles(zipPath, extractDir, options, callback) { var unzipper = new DecompressZip(zipPath); unzipper.on("error", function (err) { // General error to report for problems reading the file callback(null, { errors: [[Errors.INVALID_ZIP_FILE, zipPath, err]] }); return; }); unzipper.on("extract", function (log) { findCommonPrefix(extractDir, function (err, commonPrefix) { if (err) { callback(err, null); return; } var packageJSON = path.join(extractDir, commonPrefix, "package.json"); validatePackageJSON(zipPath, packageJSON, options, function (err, errors, metadata) { if (err) { callback(err, null); return; } var mainJS = path.join(extractDir, commonPrefix, "main.js"), isTheme = metadata && metadata.theme; // Throw missing main.js file only for non-theme extensions if (!isTheme && !fs.existsSync(mainJS)) { errors.push([Errors.MISSING_MAIN, zipPath, mainJS]); } var npmOptions = ['--production']; if (options.proxy) { npmOptions.push('--proxy ' + options.proxy); } if (process.platform.startsWith('win')) { // On Windows force a 32 bit build until nodejs 64 bit is supported. npmOptions.push('--arch=ia32'); npmOptions.push('--npm_config_arch=ia32'); npmOptions.push('--npm_config_target_arch=ia32'); } performNpmInstallIfRequired(npmOptions, { errors: errors, metadata: metadata, commonPrefix: commonPrefix, extractDir: extractDir }, callback); }); }); }); unzipper.extract({ path: extractDir, filter: function (file) { return file.type !== "SymbolicLink"; } }); }
javascript
{ "resource": "" }
q17443
validate
train
function validate(path, options, callback) { options = options || {}; fs.exists(path, function (doesExist) { if (!doesExist) { callback(null, { errors: [[Errors.NOT_FOUND_ERR, path]] }); return; } temp.mkdir("bracketsPackage_", function _tempDirCreated(err, extractDir) { if (err) { callback(err, null); return; } extractAndValidateFiles(path, extractDir, options, callback); }); }); }
javascript
{ "resource": "" }
q17444
SelectionFold
train
function SelectionFold(cm, start) { if (!cm.somethingSelected()) { return; } var from = cm.getCursor("from"), to = cm.getCursor("to"); if (from.line === start.line) { return {from: from, to: to}; } }
javascript
{ "resource": "" }
q17445
_send
train
function _send(method, signature, varargs) { if (!_socket) { console.log("You must connect to the WebSocket before sending messages."); // FUTURE: Our current implementation closes and re-opens an inspector connection whenever // a new HTML file is selected. If done quickly enough, pending requests from the previous // connection could come in before the new socket connection is established. For now we // simply ignore this condition. // This race condition will go away once we support multiple inspector connections and turn // off auto re-opening when a new HTML file is selected. return (new $.Deferred()).reject().promise(); } var id, callback, args, i, params = {}, promise, msg; // extract the parameters, the callback function, and the message id args = Array.prototype.slice.call(arguments, 2); if (typeof args[args.length - 1] === "function") { callback = args.pop(); } else { var deferred = new $.Deferred(); promise = deferred.promise(); callback = function (result, error) { if (error) { deferred.reject(error); } else { deferred.resolve(result); } }; } id = _messageId++; // verify the parameters against the method signature // this also constructs the params object of type {name -> value} if (signature) { for (i in signature) { if (_verifySignature(args[i], signature[i])) { params[signature[i].name] = args[i]; } } } // Store message callback and send message msg = { method: method, id: id, params: params }; _messageCallbacks[id] = { callback: callback, message: msg }; _socket.send(JSON.stringify(msg)); return promise; }
javascript
{ "resource": "" }
q17446
_onError
train
function _onError(error) { if (_connectDeferred) { _connectDeferred.reject(); _connectDeferred = null; } exports.trigger("error", error); }
javascript
{ "resource": "" }
q17447
disconnect
train
function disconnect() { var deferred = new $.Deferred(), promise = deferred.promise(); if (_socket && (_socket.readyState === WebSocket.OPEN)) { _socket.onclose = function () { // trigger disconnect event _onDisconnect(); deferred.resolve(); }; promise = Async.withTimeout(promise, 5000); _socket.close(); } else { if (_socket) { delete _socket.onmessage; delete _socket.onopen; delete _socket.onclose; delete _socket.onerror; _socket = undefined; } deferred.resolve(); } return promise; }
javascript
{ "resource": "" }
q17448
connect
train
function connect(socketURL) { disconnect().done(function () { _socket = new WebSocket(socketURL); _socket.onmessage = _onMessage; _socket.onopen = _onConnect; _socket.onclose = _onDisconnect; _socket.onerror = _onError; }); }
javascript
{ "resource": "" }
q17449
connectToURL
train
function connectToURL(url) { if (_connectDeferred) { // reject an existing connection attempt _connectDeferred.reject("CANCEL"); } var deferred = new $.Deferred(); _connectDeferred = deferred; var promise = getDebuggableWindows(); promise.done(function onGetAvailableSockets(response) { var i, page; for (i in response) { page = response[i]; if (page.webSocketDebuggerUrl && page.url.indexOf(url) === 0) { connect(page.webSocketDebuggerUrl); // _connectDeferred may be resolved by onConnect or rejected by onError return; } } deferred.reject(FileError.ERR_NOT_FOUND); // Reject with a "not found" error }); promise.fail(function onFail(err) { deferred.reject(err); }); return deferred.promise(); }
javascript
{ "resource": "" }
q17450
showBusyIndicator
train
function showBusyIndicator(updateCursor) { if (!_init) { console.error("StatusBar API invoked before status bar created"); return; } if (updateCursor) { _busyCursor = true; $("*").addClass("busyCursor"); } $busyIndicator.addClass("spin"); }
javascript
{ "resource": "" }
q17451
addIndicator
train
function addIndicator(id, indicator, visible, style, tooltip, insertBefore) { if (!_init) { console.error("StatusBar API invoked before status bar created"); return; } indicator = indicator || window.document.createElement("div"); tooltip = tooltip || ""; style = style || ""; id = id.replace(_indicatorIDRegexp, "-") || ""; var $indicator = $(indicator); $indicator.attr("id", id); $indicator.attr("title", tooltip); $indicator.addClass("indicator"); $indicator.addClass(style); if (!visible) { $indicator.hide(); } // This code looks backwards because the DOM model is ordered // top-to-bottom but the UI view is ordered right-to-left. The concept // of "before" in the model is "after" in the view, and vice versa. if (insertBefore && $("#" + insertBefore).length > 0) { $indicator.insertAfter("#" + insertBefore); } else { // No positioning is provided, put on left end of indicators, but // to right of "busy" indicator (which is usually hidden). var $busyIndicator = $("#status-bar .spinner"); $indicator.insertBefore($busyIndicator); } }
javascript
{ "resource": "" }
q17452
updateIndicator
train
function updateIndicator(id, visible, style, tooltip) { if (!_init && !!brackets.test) { console.error("StatusBar API invoked before status bar created"); return; } var $indicator = $("#" + id.replace(_indicatorIDRegexp, "-")); if ($indicator) { if (visible) { $indicator.show(); } else { $indicator.hide(); } if (style) { $indicator.removeClass(); $indicator.addClass(style); } else { $indicator.removeClass(); $indicator.addClass("indicator"); } if (tooltip) { $indicator.attr("title", tooltip); } } }
javascript
{ "resource": "" }
q17453
updateScrollbars
train
function updateScrollbars(theme) { theme = theme || {}; if (prefs.get("themeScrollbars")) { var scrollbar = (theme.scrollbar || []).join(" "); $scrollbars.text(scrollbar || ""); } else { $scrollbars.text(""); } }
javascript
{ "resource": "" }
q17454
updateThemes
train
function updateThemes(cm) { var newTheme = prefs.get("theme"), cmTheme = (cm.getOption("theme") || "").replace(/[\s]*/, ""); // Normalize themes string // Check if the editor already has the theme applied... if (cmTheme === newTheme) { return; } // Setup current and further documents to get the new theme... CodeMirror.defaults.theme = newTheme; cm.setOption("theme", newTheme); }
javascript
{ "resource": "" }
q17455
getSelectedItem
train
function getSelectedItem() { // Prefer file tree context, then file tree selection, else use working set var selectedEntry = getFileTreeContext(); if (!selectedEntry) { selectedEntry = model.getSelected(); } if (!selectedEntry) { selectedEntry = MainViewManager.getCurrentlyViewedFile(); } return selectedEntry; }
javascript
{ "resource": "" }
q17456
setBaseUrl
train
function setBaseUrl(projectBaseUrl) { var context = _getProjectViewStateContext(); projectBaseUrl = model.setBaseUrl(projectBaseUrl); PreferencesManager.setViewState("project.baseUrl", projectBaseUrl, context); }
javascript
{ "resource": "" }
q17457
addWelcomeProjectPath
train
function addWelcomeProjectPath(path) { var welcomeProjects = ProjectModel._addWelcomeProjectPath(path, PreferencesManager.getViewState("welcomeProjects")); PreferencesManager.setViewState("welcomeProjects", welcomeProjects); }
javascript
{ "resource": "" }
q17458
_getFallbackProjectPath
train
function _getFallbackProjectPath() { var fallbackPaths = [], recentProjects = PreferencesManager.getViewState("recentProjects") || [], deferred = new $.Deferred(); // Build ordered fallback path array if (recentProjects.length > 1) { // *Most* recent project is the one that just failed to load, so use second most recent fallbackPaths.push(recentProjects[1]); } // Next is Getting Started project fallbackPaths.push(_getWelcomeProjectPath()); // Helper func for Async.firstSequentially() function processItem(path) { var deferred = new $.Deferred(), fileEntry = FileSystem.getDirectoryForPath(path); fileEntry.exists(function (err, exists) { if (!err && exists) { deferred.resolve(); } else { deferred.reject(); } }); return deferred.promise(); } // Find first path that exists Async.firstSequentially(fallbackPaths, processItem) .done(function (fallbackPath) { deferred.resolve(fallbackPath); }) .fail(function () { // Last resort is Brackets source folder which is guaranteed to exist deferred.resolve(FileUtils.getNativeBracketsDirectoryPath()); }); return deferred.promise(); }
javascript
{ "resource": "" }
q17459
openProject
train
function openProject(path) { var result = new $.Deferred(); // Confirm any unsaved changes first. We run the command in "prompt-only" mode, meaning it won't // actually close any documents even on success; we'll do that manually after the user also oks // the folder-browse dialog. CommandManager.execute(Commands.FILE_CLOSE_ALL, { promptOnly: true }) .done(function () { if (path) { // use specified path _loadProject(path, false).then(result.resolve, result.reject); } else { // Pop up a folder browse dialog FileSystem.showOpenDialog(false, true, Strings.CHOOSE_FOLDER, model.projectRoot.fullPath, null, function (err, files) { if (!err) { // If length == 0, user canceled the dialog; length should never be > 1 if (files.length > 0) { // Load the new project into the folder tree _loadProject(files[0]).then(result.resolve, result.reject); } else { result.reject(); } } else { _showErrorDialog(ERR_TYPE_OPEN_DIALOG, null, err); result.reject(); } }); } }) .fail(function () { result.reject(); }); // if fail, don't open new project: user canceled (or we failed to save its unsaved changes) return result.promise(); }
javascript
{ "resource": "" }
q17460
createNewItem
train
function createNewItem(baseDir, initialName, skipRename, isFolder) { baseDir = model.getDirectoryInProject(baseDir); if (skipRename) { if(isFolder) { return model.createAtPath(baseDir + initialName + "/"); } return model.createAtPath(baseDir + initialName); } return actionCreator.startCreating(baseDir, initialName, isFolder); }
javascript
{ "resource": "" }
q17461
deleteItem
train
function deleteItem(entry) { var result = new $.Deferred(); entry.moveToTrash(function (err) { if (!err) { DocumentManager.notifyPathDeleted(entry.fullPath); result.resolve(); } else { _showErrorDialog(ERR_TYPE_DELETE, entry.isDirectory, FileUtils.getFileErrorString(err), entry.fullPath); result.reject(err); } }); return result.promise(); }
javascript
{ "resource": "" }
q17462
_formatCountable
train
function _formatCountable(number, singularStr, pluralStr) { return StringUtils.format(number > 1 ? pluralStr : singularStr, number); }
javascript
{ "resource": "" }
q17463
_updateLanguageInfo
train
function _updateLanguageInfo(editor) { var doc = editor.document, lang = doc.getLanguage(); // Show the current language as button title languageSelect.$button.text(lang.getName()); }
javascript
{ "resource": "" }
q17464
_updateFileInfo
train
function _updateFileInfo(editor) { var lines = editor.lineCount(); $fileInfo.text(_formatCountable(lines, Strings.STATUSBAR_LINE_COUNT_SINGULAR, Strings.STATUSBAR_LINE_COUNT_PLURAL)); }
javascript
{ "resource": "" }
q17465
_updateIndentType
train
function _updateIndentType(fullPath) { var indentWithTabs = Editor.getUseTabChar(fullPath); $indentType.text(indentWithTabs ? Strings.STATUSBAR_TAB_SIZE : Strings.STATUSBAR_SPACES); $indentType.attr("title", indentWithTabs ? Strings.STATUSBAR_INDENT_TOOLTIP_SPACES : Strings.STATUSBAR_INDENT_TOOLTIP_TABS); $indentWidthLabel.attr("title", indentWithTabs ? Strings.STATUSBAR_INDENT_SIZE_TOOLTIP_TABS : Strings.STATUSBAR_INDENT_SIZE_TOOLTIP_SPACES); }
javascript
{ "resource": "" }
q17466
_toggleIndentType
train
function _toggleIndentType() { var current = EditorManager.getActiveEditor(), fullPath = current && current.document.file.fullPath; Editor.setUseTabChar(!Editor.getUseTabChar(fullPath), fullPath); _updateIndentType(fullPath); _updateIndentSize(fullPath); }
javascript
{ "resource": "" }
q17467
_changeIndentWidth
train
function _changeIndentWidth(fullPath, value) { $indentWidthLabel.removeClass("hidden"); $indentWidthInput.addClass("hidden"); // remove all event handlers from the input field $indentWidthInput.off("blur keyup"); // restore focus to the editor MainViewManager.focusActivePane(); var valInt = parseInt(value, 10); if (Editor.getUseTabChar(fullPath)) { if (!Editor.setTabSize(valInt, fullPath)) { return; // validation failed } } else { if (!Editor.setSpaceUnits(valInt, fullPath)) { return; // validation failed } } // update indicator _updateIndentSize(fullPath); // column position may change when tab size changes _updateCursorInfo(); }
javascript
{ "resource": "" }
q17468
_onActiveEditorChange
train
function _onActiveEditorChange(event, current, previous) { if (previous) { previous.off(".statusbar"); previous.document.off(".statusbar"); previous.document.releaseRef(); } if (!current) { StatusBar.hideAllPanes(); } else { var fullPath = current.document.file.fullPath; StatusBar.showAllPanes(); current.on("cursorActivity.statusbar", _updateCursorInfo); current.on("optionChange.statusbar", function () { _updateIndentType(fullPath); _updateIndentSize(fullPath); }); current.on("change.statusbar", function () { // async update to keep typing speed smooth window.setTimeout(function () { _updateFileInfo(current); }, 0); }); current.on("overwriteToggle.statusbar", _updateOverwriteLabel); current.document.addRef(); current.document.on("languageChanged.statusbar", function () { _updateLanguageInfo(current); }); _updateCursorInfo(null, current); _updateLanguageInfo(current); _updateEncodingInfo(current); _updateFileInfo(current); _initOverwriteMode(current); _updateIndentType(fullPath); _updateIndentSize(fullPath); } }
javascript
{ "resource": "" }
q17469
_populateLanguageDropdown
train
function _populateLanguageDropdown() { // Get all non-binary languages var languages = _.values(LanguageManager.getLanguages()).filter(function (language) { return !language.isBinary(); }); // sort dropdown alphabetically languages.sort(function (a, b) { return a.getName().toLowerCase().localeCompare(b.getName().toLowerCase()); }); languageSelect.items = languages; // Add option to top of menu for persisting the override languageSelect.items.unshift("---"); languageSelect.items.unshift(LANGUAGE_SET_AS_DEFAULT); }
javascript
{ "resource": "" }
q17470
_changeEncodingAndReloadDoc
train
function _changeEncodingAndReloadDoc(document) { var promise = document.reload(); promise.done(function (text, readTimestamp) { encodingSelect.$button.text(document.file._encoding); // Store the preferred encoding in the state var projectRoot = ProjectManager.getProjectRoot(), context = { location : { scope: "user", layer: "project", layerID: projectRoot.fullPath } }; var encoding = PreferencesManager.getViewState("encoding", context); encoding[document.file.fullPath] = document.file._encoding; PreferencesManager.setViewState("encoding", encoding, context); }); promise.fail(function (error) { console.log("Error reloading contents of " + document.file.fullPath, error); }); }
javascript
{ "resource": "" }
q17471
createFunctionList
train
function createFunctionList() { var doc = DocumentManager.getCurrentDocument(); if (!doc) { return; } var functionList = []; var docText = doc.getText(); var lines = docText.split("\n"); var functions = JSUtils.findAllMatchingFunctionsInText(docText, "*"); functions.forEach(function (funcEntry) { functionList.push(new FileLocation(null, funcEntry.nameLineStart, funcEntry.columnStart, funcEntry.columnEnd, funcEntry.label || funcEntry.name)); }); return functionList; }
javascript
{ "resource": "" }
q17472
rangeEqualsSelection
train
function rangeEqualsSelection(range, selection) { return range.from.line === selection.start.line && range.from.ch === selection.start.ch && range.to.line === selection.end.line && range.to.ch === selection.end.ch; }
javascript
{ "resource": "" }
q17473
isInViewStateSelection
train
function isInViewStateSelection(range, viewState) { if (!viewState || !viewState.selections) { return false; } return viewState.selections.some(function (selection) { return rangeEqualsSelection(range, selection); }); }
javascript
{ "resource": "" }
q17474
saveLineFolds
train
function saveLineFolds(editor) { var saveFolds = prefs.getSetting("saveFoldStates"); if (!editor || !saveFolds) { return; } var folds = editor._codeMirror._lineFolds || {}; var path = editor.document.file.fullPath; if (Object.keys(folds).length) { prefs.setFolds(path, folds); } else { prefs.setFolds(path, undefined); } }
javascript
{ "resource": "" }
q17475
collapseCurrent
train
function collapseCurrent() { var editor = EditorManager.getFocusedEditor(); if (!editor) { return; } var cm = editor._codeMirror; var cursor = editor.getCursorPos(), i; // Move cursor up until a collapsible line is found for (i = cursor.line; i >= 0; i--) { if (cm.foldCode(i)) { editor.setCursorPos(i); return; } } }
javascript
{ "resource": "" }
q17476
expandCurrent
train
function expandCurrent() { var editor = EditorManager.getFocusedEditor(); if (editor) { var cursor = editor.getCursorPos(), cm = editor._codeMirror; cm.unfoldCode(cursor.line); } }
javascript
{ "resource": "" }
q17477
expandAll
train
function expandAll() { var editor = EditorManager.getFocusedEditor(); if (editor) { var cm = editor._codeMirror; CodeMirror.commands.unfoldAll(cm); } }
javascript
{ "resource": "" }
q17478
setupGutterEventListeners
train
function setupGutterEventListeners(editor) { var cm = editor._codeMirror; $(editor.getRootElement()).addClass("folding-enabled"); cm.setOption("foldGutter", {onGutterClick: onGutterClick}); $(cm.getGutterElement()).on({ mouseenter: function () { if (prefs.getSetting("hideUntilMouseover")) { foldGutter.updateInViewport(cm); } else { $(editor.getRootElement()).addClass("over-gutter"); } }, mouseleave: function () { if (prefs.getSetting("hideUntilMouseover")) { clearGutter(editor); } else { $(editor.getRootElement()).removeClass("over-gutter"); } } }); }
javascript
{ "resource": "" }
q17479
removeGutters
train
function removeGutters(editor) { Editor.unregisterGutter(GUTTER_NAME); $(editor.getRootElement()).removeClass("folding-enabled"); CodeMirror.defineOption("foldGutter", false, null); }
javascript
{ "resource": "" }
q17480
onActiveEditorChanged
train
function onActiveEditorChanged(event, current, previous) { if (current && !current._codeMirror._lineFolds) { enableFoldingInEditor(current); } if (previous) { saveLineFolds(previous); } }
javascript
{ "resource": "" }
q17481
deinit
train
function deinit() { _isInitialized = false; KeyBindingManager.removeBinding(collapseKey); KeyBindingManager.removeBinding(expandKey); KeyBindingManager.removeBinding(collapseAllKey); KeyBindingManager.removeBinding(expandAllKey); KeyBindingManager.removeBinding(collapseAllKeyMac); KeyBindingManager.removeBinding(expandAllKeyMac); //remove menus Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuDivider(codeFoldingMenuDivider.id); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(COLLAPSE); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(EXPAND); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(COLLAPSE_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).removeMenuItem(EXPAND_ALL); EditorManager.off(".CodeFolding"); DocumentManager.off(".CodeFolding"); ProjectManager.off(".CodeFolding"); // Remove gutter & revert collapsed sections in all currently open editors Editor.forEveryEditor(function (editor) { CodeMirror.commands.unfoldAll(editor._codeMirror); }); removeGutters(); }
javascript
{ "resource": "" }
q17482
init
train
function init() { _isInitialized = true; foldCode.init(); foldGutter.init(); // Many CodeMirror modes specify which fold helper should be used for that language. For a few that // don't, we register helpers explicitly here. We also register a global helper for generic indent-based // folding, which cuts across all languages if enabled via preference. CodeMirror.registerGlobalHelper("fold", "selectionFold", function (mode, cm) { return prefs.getSetting("makeSelectionsFoldable"); }, selectionFold); CodeMirror.registerGlobalHelper("fold", "indent", function (mode, cm) { return prefs.getSetting("alwaysUseIndentFold"); }, indentFold); CodeMirror.registerHelper("fold", "handlebars", handlebarsFold); CodeMirror.registerHelper("fold", "htmlhandlebars", handlebarsFold); CodeMirror.registerHelper("fold", "htmlmixed", handlebarsFold); EditorManager.on("activeEditorChange.CodeFolding", onActiveEditorChanged); DocumentManager.on("documentRefreshed.CodeFolding", function (event, doc) { restoreLineFolds(doc._masterEditor); }); ProjectManager.on("beforeProjectClose.CodeFolding beforeAppClose.CodeFolding", saveBeforeClose); //create menus codeFoldingMenuDivider = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuDivider(); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND_ALL); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(COLLAPSE); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(EXPAND); //register keybindings KeyBindingManager.addBinding(COLLAPSE_ALL, [ {key: collapseAllKey}, {key: collapseAllKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(EXPAND_ALL, [ {key: expandAllKey}, {key: expandAllKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(COLLAPSE, collapseKey); KeyBindingManager.addBinding(EXPAND, expandKey); // Add gutters & restore saved expand/collapse state in all currently open editors Editor.registerGutter(GUTTER_NAME, CODE_FOLDING_GUTTER_PRIORITY); Editor.forEveryEditor(function (editor) { enableFoldingInEditor(editor); }); }
javascript
{ "resource": "" }
q17483
watchPrefsForChanges
train
function watchPrefsForChanges() { prefs.prefsObject.on("change", function (e, data) { if (data.ids.indexOf("enabled") > -1) { // Check if enabled state mismatches whether code-folding is actually initialized (can't assume // since preference change events can occur when the value hasn't really changed) var isEnabled = prefs.getSetting("enabled"); if (isEnabled && !_isInitialized) { init(); } else if (!isEnabled && _isInitialized) { deinit(); } } }); }
javascript
{ "resource": "" }
q17484
init
train
function init(domainManager) { if (!domainManager.hasDomain("fileWatcher")) { domainManager.registerDomain("fileWatcher", {major: 0, minor: 1}); } domainManager.registerCommand( "fileWatcher", "watchPath", watcherManager.watchPath, false, "Start watching a file or directory", [{ name: "path", type: "string", description: "absolute filesystem path of the file or directory to watch" }, { name: "ignored", type: "array", description: "list of path to ignore" }] ); domainManager.registerCommand( "fileWatcher", "unwatchPath", watcherManager.unwatchPath, false, "Stop watching a single file or a directory and it's descendants", [{ name: "path", type: "string", description: "absolute filesystem path of the file or directory to unwatch" }] ); domainManager.registerCommand( "fileWatcher", "unwatchAll", watcherManager.unwatchAll, false, "Stop watching all files and directories" ); domainManager.registerEvent( "fileWatcher", "change", [ {name: "event", type: "string"}, {name: "parentDirPath", type: "string"}, {name: "entryName", type: "string"}, {name: "statsObj", type: "object"} ] ); watcherManager.setDomainManager(domainManager); watcherManager.setWatcherImpl(watcherImpl); }
javascript
{ "resource": "" }
q17485
_write
train
function _write(filePath, json) { var result = $.Deferred(), _file = FileSystem.getFileForPath(filePath); if (_file) { var content = JSON.stringify(json); FileUtils.writeText(_file, content, true) .done(function () { result.resolve(); }) .fail(function (err) { result.reject(); }); } else { result.reject(); } return result.promise(); }
javascript
{ "resource": "" }
q17486
collectDuplicates
train
function collectDuplicates(value) { if (value == null || typeof value !== 'object') { return; } const metadata = metadataForVal.get(value); // Only consider duplicates with hashes longer than 2 (excludes [] and {}). if (metadata && metadata.value !== value && metadata.hash.length > 2) { metadata.isDuplicate = true; return; } if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { collectDuplicates(value[i]); } } else { for (const k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { collectDuplicates(value[k]); } } } }
javascript
{ "resource": "" }
q17487
printJSCode
train
function printJSCode(isDupedVar, depth, value) { if (value == null || typeof value !== 'object') { return JSON.stringify(value); } // Only use variable references at depth beyond the top level. if (depth !== '') { const metadata = metadataForVal.get(value); if (metadata && metadata.isDuplicate) { if (!metadata.varName) { const refCode = printJSCode(true, '', value); metadata.varName = 'v' + varDefs.length; varDefs.push(metadata.varName + ' = ' + refCode); } return '(' + metadata.varName + '/*: any*/)'; } } let str; let isEmpty = true; const depth2 = depth + ' '; if (Array.isArray(value)) { // Empty arrays can only have one inferred flow type and then conflict if // used in different places, this is unsound if we would write to them but // this whole module is based on the idea of a read only JSON tree. if (isDupedVar && value.length === 0) { return '([]/*: any*/)'; } str = '['; for (let i = 0; i < value.length; i++) { str += (isEmpty ? '\n' : ',\n') + depth2 + printJSCode(isDupedVar, depth2, value[i]); isEmpty = false; } str += isEmpty ? ']' : `\n${depth}]`; } else { str = '{'; for (const k in value) { if (value.hasOwnProperty(k) && value[k] !== undefined) { str += (isEmpty ? '\n' : ',\n') + depth2 + JSON.stringify(k) + ': ' + printJSCode(isDupedVar, depth2, value[k]); isEmpty = false; } } str += isEmpty ? '}' : `\n${depth}}`; } return str; }
javascript
{ "resource": "" }
q17488
mapModule
train
function mapModule(state, module) { var moduleMap = state.opts.map || {}; if (moduleMap.hasOwnProperty(module)) { return moduleMap[module]; } // Jest understands the haste module system, so leave modules intact. if (process.env.NODE_ENV === 'test') { return; } return './' + path.basename(module); }
javascript
{ "resource": "" }
q17489
cache
train
function cache (options) { if (is.bool(options)) { if (options) { // Default cache settings of 50MB, 20 files, 100 items return sharp.cache(50, 20, 100); } else { return sharp.cache(0, 0, 0); } } else if (is.object(options)) { return sharp.cache(options.memory, options.files, options.items); } else { return sharp.cache(); } }
javascript
{ "resource": "" }
q17490
extractChannel
train
function extractChannel (channel) { if (channel === 'red') { channel = 0; } else if (channel === 'green') { channel = 1; } else if (channel === 'blue') { channel = 2; } if (is.integer(channel) && is.inRange(channel, 0, 4)) { this.options.extractChannel = channel; } else { throw new Error('Cannot extract invalid channel ' + channel); } return this; }
javascript
{ "resource": "" }
q17491
_write
train
function _write (chunk, encoding, callback) { /* istanbul ignore else */ if (Array.isArray(this.options.input.buffer)) { /* istanbul ignore else */ if (is.buffer(chunk)) { if (this.options.input.buffer.length === 0) { const that = this; this.on('finish', function () { that.streamInFinished = true; }); } this.options.input.buffer.push(chunk); callback(); } else { callback(new Error('Non-Buffer data on Writable Stream')); } } else { callback(new Error('Unexpected data on Writable Stream')); } }
javascript
{ "resource": "" }
q17492
_flattenBufferIn
train
function _flattenBufferIn () { if (this._isStreamInput()) { this.options.input.buffer = Buffer.concat(this.options.input.buffer); } }
javascript
{ "resource": "" }
q17493
clone
train
function clone () { const that = this; // Clone existing options const clone = this.constructor.call(); clone.options = Object.assign({}, this.options); // Pass 'finish' event to clone for Stream-based input if (this._isStreamInput()) { this.on('finish', function () { // Clone inherits input data that._flattenBufferIn(); clone.options.bufferIn = that.options.bufferIn; clone.emit('finish'); }); } return clone; }
javascript
{ "resource": "" }
q17494
stats
train
function stats (callback) { const that = this; if (is.fn(callback)) { if (this._isStreamInput()) { this.on('finish', function () { that._flattenBufferIn(); sharp.stats(that.options, callback); }); } else { sharp.stats(this.options, callback); } return this; } else { if (this._isStreamInput()) { return new Promise(function (resolve, reject) { that.on('finish', function () { that._flattenBufferIn(); sharp.stats(that.options, function (err, stats) { if (err) { reject(err); } else { resolve(stats); } }); }); }); } else { return new Promise(function (resolve, reject) { sharp.stats(that.options, function (err, stats) { if (err) { reject(err); } else { resolve(stats); } }); }); } } }
javascript
{ "resource": "" }
q17495
toFile
train
function toFile (fileOut, callback) { if (!fileOut || fileOut.length === 0) { const errOutputInvalid = new Error('Missing output file path'); if (is.fn(callback)) { callback(errOutputInvalid); } else { return Promise.reject(errOutputInvalid); } } else { if (this.options.input.file === fileOut) { const errOutputIsInput = new Error('Cannot use same file for input and output'); if (is.fn(callback)) { callback(errOutputIsInput); } else { return Promise.reject(errOutputIsInput); } } else { this.options.fileOut = fileOut; return this._pipeline(callback); } } return this; }
javascript
{ "resource": "" }
q17496
toBuffer
train
function toBuffer (options, callback) { if (is.object(options)) { if (is.bool(options.resolveWithObject)) { this.options.resolveWithObject = options.resolveWithObject; } } return this._pipeline(is.fn(options) ? options : callback); }
javascript
{ "resource": "" }
q17497
jpeg
train
function jpeg (options) { if (is.object(options)) { if (is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { this.options.jpegQuality = options.quality; } else { throw new Error('Invalid quality (integer, 1-100) ' + options.quality); } } if (is.defined(options.progressive)) { this._setBooleanOption('jpegProgressive', options.progressive); } if (is.defined(options.chromaSubsampling)) { if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { this.options.jpegChromaSubsampling = options.chromaSubsampling; } else { throw new Error('Invalid chromaSubsampling (4:2:0, 4:4:4) ' + options.chromaSubsampling); } } const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; if (is.defined(trellisQuantisation)) { this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation); } if (is.defined(options.overshootDeringing)) { this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing); } const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans; if (is.defined(optimiseScans)) { this._setBooleanOption('jpegOptimiseScans', optimiseScans); if (optimiseScans) { this.options.jpegProgressive = true; } } const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; if (is.defined(optimiseCoding)) { this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); } const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; if (is.defined(quantisationTable)) { if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) { this.options.jpegQuantisationTable = quantisationTable; } else { throw new Error('Invalid quantisation table (integer, 0-8) ' + quantisationTable); } } } return this._updateFormatOut('jpeg', options); }
javascript
{ "resource": "" }
q17498
png
train
function png (options) { if (is.object(options)) { if (is.defined(options.progressive)) { this._setBooleanOption('pngProgressive', options.progressive); } if (is.defined(options.compressionLevel)) { if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) { this.options.pngCompressionLevel = options.compressionLevel; } else { throw new Error('Invalid compressionLevel (integer, 0-9) ' + options.compressionLevel); } } if (is.defined(options.adaptiveFiltering)) { this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); } if (is.defined(options.palette)) { this._setBooleanOption('pngPalette', options.palette); if (this.options.pngPalette) { if (is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) { this.options.pngQuality = options.quality; } else { throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality); } } const colours = options.colours || options.colors; if (is.defined(colours)) { if (is.integer(colours) && is.inRange(colours, 2, 256)) { this.options.pngColours = colours; } else { throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); } } if (is.defined(options.dither)) { if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { this.options.pngDither = options.dither; } else { throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); } } } } } return this._updateFormatOut('png', options); }
javascript
{ "resource": "" }
q17499
webp
train
function webp (options) { if (is.object(options) && is.defined(options.quality)) { if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { this.options.webpQuality = options.quality; } else { throw new Error('Invalid quality (integer, 1-100) ' + options.quality); } } if (is.object(options) && is.defined(options.alphaQuality)) { if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { this.options.webpAlphaQuality = options.alphaQuality; } else { throw new Error('Invalid webp alpha quality (integer, 0-100) ' + options.alphaQuality); } } if (is.object(options) && is.defined(options.lossless)) { this._setBooleanOption('webpLossless', options.lossless); } if (is.object(options) && is.defined(options.nearLossless)) { this._setBooleanOption('webpNearLossless', options.nearLossless); } return this._updateFormatOut('webp', options); }
javascript
{ "resource": "" }