_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q15400
|
addonsManager_getSearchFilterValue
|
train
|
function addonsManager_getSearchFilterValue(aSpec) {
var spec = aSpec || { };
var filter = spec.filter;
if (!filter)
throw new Error(arguments.callee.name + ": Search filter not specified.");
return filter.getNode().value;
}
|
javascript
|
{
"resource": ""
}
|
q15401
|
addonsManager_waitForSearchFilter
|
train
|
function addonsManager_waitForSearchFilter(aSpec) {
var spec = aSpec || { };
var filter = spec.filter;
var timeout = (spec.timeout == undefined) ? TIMEOUT : spec.timeout;
if (!filter)
throw new Error(arguments.callee.name + ": Search filter not specified.");
// TODO: restore after 1.5.1 has landed
// var self = this;
//
// mozmill.utils.waitFor(function () {
// return self.selectedSearchFilter.getNode() == filter.getNode();
// }, timeout, 100, "Search filter '" + filter.getNode().value + "' has been set");
mozmill.utils.waitForEval("subject.self.selectedSearchFilter.getNode() == subject.aFilter.getNode()",
timeout, 100,
{self: this, aFilter: filter});
}
|
javascript
|
{
"resource": ""
}
|
q15402
|
addonsManager_getSearchResults
|
train
|
function addonsManager_getSearchResults() {
var filterValue = this.getSearchFilterValue({
filter: this.selectedSearchFilter
});
switch (filterValue) {
case "local":
return this.getAddons({attribute: "status", value: "installed"});
case "remote":
return this.getAddons({attribute: "remote", value: "true"});
default:
throw new Error(arguments.callee.name + ": Unknown search filter '" +
filterValue + "' selected");
}
}
|
javascript
|
{
"resource": ""
}
|
q15403
|
addonsManager_waitForSearchFinished
|
train
|
function addonsManager_waitForSearchFinished(aSpec) {
var spec = aSpec || { };
var timeout = (spec.timeout == undefined) ? TIMEOUT_SEARCH : spec.timeout;
// TODO: restore after 1.5.1 has landed
// var self = this;
//
// mozmill.utils.waitFor(function () {
// return self.isSearching == false;
// }, timeout, 100, "Search has been finished");
mozmill.utils.waitForEval("subject.isSearching == false",
timeout, 100, this);
}
|
javascript
|
{
"resource": ""
}
|
q15404
|
addToWhiteList
|
train
|
function addToWhiteList(aDomain) {
pm.add(utils.createURI(aDomain),
"install",
Ci.nsIPermissionManager.ALLOW_ACTION);
}
|
javascript
|
{
"resource": ""
}
|
q15405
|
train
|
function(
pattern, opt_dateIntervalSymbols, opt_dateTimeSymbols) {
asserts.assert(goog.isDef(pattern), 'Pattern must be defined.');
asserts.assert(
goog.isDef(opt_dateIntervalSymbols) ||
goog.isDef(dateIntervalSymbols.getDateIntervalSymbols()),
'goog.i18n.DateIntervalSymbols or explicit symbols must be defined');
asserts.assert(
goog.isDef(opt_dateTimeSymbols) || goog.isDef(DateTimeSymbols),
'goog.i18n.DateTimeSymbols or explicit symbols must be defined');
/**
* DateIntervalSymbols object that contains locale data required by the
* formatter.
* @private @const {!dateIntervalSymbols.DateIntervalSymbols}
*/
this.dateIntervalSymbols_ =
opt_dateIntervalSymbols || dateIntervalSymbols.getDateIntervalSymbols();
/**
* DateTimeSymbols object that contain locale data required by the formatter.
* @private @const {!DateTimeSymbolsType}
*/
this.dateTimeSymbols_ = opt_dateTimeSymbols || DateTimeSymbols;
/**
* Date interval pattern to use.
* @private @const {!dateIntervalSymbols.DateIntervalPatternMap}
*/
this.intervalPattern_ = this.getIntervalPattern_(pattern);
/**
* Keys of the available date interval patterns. Used to lookup the key that
* contains a specific pattern letter (e.g. for ['Myd', 'hms'], the key that
* contains 'y' is 'Myd').
* @private @const {!Array<string>}
*/
this.intervalPatternKeys_ = object.getKeys(this.intervalPattern_);
// Remove the default pattern's key ('_') from intervalPatternKeys_. Is not
// necesary when looking up for a key: when no key is found it will always
// default to the default pattern.
array.remove(this.intervalPatternKeys_, DEFAULT_PATTERN_KEY_);
/**
* Default fallback pattern to use.
* @private @const {string}
*/
this.fallbackPattern_ =
this.dateIntervalSymbols_.FALLBACK || DEFAULT_FALLBACK_PATTERN_;
// Determine which date should be used with each part of the interval
// pattern.
var indexOfFirstDate = this.fallbackPattern_.indexOf(FIRST_DATE_PLACEHOLDER_);
var indexOfSecondDate =
this.fallbackPattern_.indexOf(SECOND_DATE_PLACEHOLDER_);
if (indexOfFirstDate < 0 || indexOfSecondDate < 0) {
throw new Error('Malformed fallback interval pattern');
}
/**
* True if the first date provided should be formatted with the first pattern
* of the interval pattern.
* @private @const {boolean}
*/
this.useFirstDateOnFirstPattern_ = indexOfFirstDate <= indexOfSecondDate;
/**
* Map that stores a Formatter_ object per calendar field. Formatters will be
* instanced on demand and stored on this map until required again.
* @private @const {!Object<string, !Formatter_>}
*/
this.formatterMap_ = {};
}
|
javascript
|
{
"resource": ""
}
|
|
q15406
|
train
|
function(
firstPattern, secondPattern, dateTimeSymbols, useFirstDateOnFirstPattern) {
/**
* Formatter_ to format the first part of the date interval.
* @private {!DateTimeFormat}
*/
this.firstPartFormatter_ = new DateTimeFormat(firstPattern, dateTimeSymbols);
/**
* Formatter_ to format the second part of the date interval.
* @private {!DateTimeFormat}
*/
this.secondPartFormatter_ =
new DateTimeFormat(secondPattern, dateTimeSymbols);
/**
* Specifies if the first or the second date should be formatted by the
* formatter of the first or second part of the date interval.
* @private {boolean}
*/
this.useFirstDateOnFirstPattern_ = useFirstDateOnFirstPattern;
}
|
javascript
|
{
"resource": ""
}
|
|
q15407
|
train
|
function(
dateTimePattern, fallbackPattern, dateTimeSymbols) {
/**
* Date time pattern used to format the dates.
* @private {string}
*/
this.dateTimePattern_ = dateTimePattern;
/**
* Date time formatter used to format the dates.
* @private {!DateTimeFormat}
*/
this.dateTimeFormatter_ =
new DateTimeFormat(dateTimePattern, dateTimeSymbols);
/**
* Fallback interval pattern.
* @private {string}
*/
this.fallbackPattern_ = fallbackPattern;
}
|
javascript
|
{
"resource": ""
}
|
|
q15408
|
toMap
|
train
|
function toMap(hash) {
let m = new Map;
for (let key in hash) {
if (hash.hasOwnProperty(key)) {
m.set(key, hash[key]);
}
}
return m;
}
|
javascript
|
{
"resource": ""
}
|
q15409
|
preferencesDialog_close
|
train
|
function preferencesDialog_close(saveChanges) {
saveChanges = (saveChanges == undefined) ? false : saveChanges;
var button = this.getElement({type: "button", subtype: (saveChanges ? "accept" : "cancel")});
this._controller.click(button);
}
|
javascript
|
{
"resource": ""
}
|
q15410
|
engineManager_editKeyword
|
train
|
function engineManager_editKeyword(name, handler)
{
// Select the search engine
this.selectedEngine = name;
// Setup the modal dialog handler
md = new modalDialog.modalDialog(this._controller.window);
md.start(handler);
var button = this.getElement({type: "engine_button", subtype: "edit"});
this._controller.click(button);
md.waitForDialog();
}
|
javascript
|
{
"resource": ""
}
|
q15411
|
engineManager_moveUpEngine
|
train
|
function engineManager_moveUpEngine(name) {
this.selectedEngine = name;
var index = this.selectedIndex;
var button = this.getElement({type: "engine_button", subtype: "up"});
this._controller.click(button);
this._controller.waitForEval("subject.manager.selectedIndex == subject.oldIndex - 1", TIMEOUT, 100,
{manager: this, oldIndex: index});
}
|
javascript
|
{
"resource": ""
}
|
q15412
|
engineManager_removeEngine
|
train
|
function engineManager_removeEngine(name) {
this.selectedEngine = name;
var button = this.getElement({type: "engine_button", subtype: "remove"});
this._controller.click(button);
this._controller.waitForEval("subject.manager.selectedEngine != subject.removedEngine", TIMEOUT, 100,
{manager: this, removedEngine: name});
}
|
javascript
|
{
"resource": ""
}
|
q15413
|
searchBar_checkSearchResultPage
|
train
|
function searchBar_checkSearchResultPage(searchTerm) {
// Retrieve the URL which is used for the currently selected search engine
var targetUrl = this._bss.currentEngine.getSubmission(searchTerm, null).uri;
var currentUrl = this._controller.tabs.activeTabWindow.document.location.href;
// Check if pure domain names are identical
var domainName = targetUrl.host.replace(/.+\.(\w+)\.\w+$/gi, "$1");
var index = currentUrl.indexOf(domainName);
this._controller.assertJS("subject.URLContainsDomain == true",
{URLContainsDomain: currentUrl.indexOf(domainName) != -1});
// Check if search term is listed in URL
this._controller.assertJS("subject.URLContainsText == true",
{URLContainsText: currentUrl.toLowerCase().indexOf(searchTerm.toLowerCase()) != -1});
}
|
javascript
|
{
"resource": ""
}
|
q15414
|
searchBar_clear
|
train
|
function searchBar_clear()
{
var activeElement = this._controller.window.document.activeElement;
var searchInput = this.getElement({type: "searchBar_input"});
var cmdKey = utils.getEntity(this.getDtds(), "selectAllCmd.key");
this._controller.keypress(searchInput, cmdKey, {accelKey: true});
this._controller.keypress(searchInput, 'VK_DELETE', {});
if (activeElement)
activeElement.focus();
}
|
javascript
|
{
"resource": ""
}
|
q15415
|
searchBar_focus
|
train
|
function searchBar_focus(event)
{
var input = this.getElement({type: "searchBar_input"});
switch (event.type) {
case "click":
this._controller.click(input);
break;
case "shortcut":
if (mozmill.isLinux) {
var cmdKey = utils.getEntity(this.getDtds(), "searchFocusUnix.commandkey");
} else {
var cmdKey = utils.getEntity(this.getDtds(), "searchFocus.commandkey");
}
this._controller.keypress(null, cmdKey, {accelKey: true});
break;
default:
throw new Error(arguments.callee.name + ": Unknown element type - " + event.type);
}
// Check if the search bar has the focus
var activeElement = this._controller.window.document.activeElement;
this._controller.assertJS("subject.isFocused == true",
{isFocused: input.getNode() == activeElement});
}
|
javascript
|
{
"resource": ""
}
|
q15416
|
train
|
function(searchTerm) {
var suggestions = [ ];
var popup = this.getElement({type: "searchBar_autoCompletePopup"});
var treeElem = this.getElement({type: "searchBar_suggestions"});
// Enter search term and wait for the popup
this.type(searchTerm);
this._controller.waitForEval("subject.popup.state == 'open'", TIMEOUT, 100,
{popup: popup.getNode()});
this._controller.waitForElement(treeElem, TIMEOUT);
// Get all suggestions
var tree = treeElem.getNode();
this._controller.waitForEval("subject.tree.view != null", TIMEOUT, 100,
{tree: tree});
for (var i = 0; i < tree.view.rowCount; i ++) {
suggestions.push(tree.view.getCellText(i, tree.columns.getColumnAt(0)));
}
// Close auto-complete popup
this._controller.keypress(popup, "VK_ESCAPE", {});
this._controller.waitForEval("subject.popup.state == 'closed'", TIMEOUT, 100,
{popup: popup.getNode()});
return suggestions;
}
|
javascript
|
{
"resource": ""
}
|
|
q15417
|
searchBar_openEngineManager
|
train
|
function searchBar_openEngineManager(handler)
{
this.enginesDropDownOpen = true;
var engineManager = this.getElement({type: "engine_manager"});
// Setup the modal dialog handler
md = new modalDialog.modalDialog(this._controller.window);
md.start(handler);
// XXX: Bug 555347 - Process any outstanding events before clicking the entry
this._controller.sleep(0);
this._controller.click(engineManager);
md.waitForDialog();
this._controller.assert(function () {
return this.enginesDropDownOpen == false;
}, "The search engine drop down menu has been closed", this);
}
|
javascript
|
{
"resource": ""
}
|
q15418
|
searchBar_search
|
train
|
function searchBar_search(data)
{
var searchBar = this.getElement({type: "searchBar"});
this.type(data.text);
switch (data.action) {
case "returnKey":
this._controller.keypress(searchBar, 'VK_RETURN', {});
break;
case "goButton":
default:
this._controller.click(this.getElement({type: "searchBar_goButton"}));
break;
}
this._controller.waitForPageLoad();
this.checkSearchResultPage(data.text);
}
|
javascript
|
{
"resource": ""
}
|
q15419
|
XNode
|
train
|
function XNode(type, name, opt_value, opt_owner) {
this.attributes = [];
this.childNodes = [];
XNode.init.call(this, type, name, opt_value, opt_owner);
}
|
javascript
|
{
"resource": ""
}
|
q15420
|
addNewerLanguageTranspilationCheck
|
train
|
function addNewerLanguageTranspilationCheck(modeName, isSupported) {
if (transpilationRequiredForAllLaterModes) {
requiresTranspilation[modeName] = true;
} else if (isSupported()) {
requiresTranspilation[modeName] = false;
} else {
requiresTranspilation[modeName] = true;
transpilationRequiredForAllLaterModes = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q15421
|
clickTreeCell
|
train
|
function clickTreeCell(controller, tree, rowIndex, columnIndex, eventDetails)
{
tree = tree.getNode();
var selection = tree.view.selection;
selection.select(rowIndex);
tree.treeBoxObject.ensureRowIsVisible(rowIndex);
// get cell coordinates
var x = {}, y = {}, width = {}, height = {};
var column = tree.columns[columnIndex];
tree.treeBoxObject.getCoordsForCellItem(rowIndex, column, "text",
x, y, width, height);
controller.sleep(0);
EventUtils.synthesizeMouse(tree.body, x.value + 4, y.value + 4,
eventDetails, tree.ownerDocument.defaultView);
controller.sleep(0);
}
|
javascript
|
{
"resource": ""
}
|
q15422
|
softwareUpdate
|
train
|
function softwareUpdate() {
this._controller = null;
this._wizard = null;
this._aus = Cc["@mozilla.org/updates/update-service;1"].
getService(Ci.nsIApplicationUpdateService);
this._ums = Cc["@mozilla.org/updates/update-manager;1"].
getService(Ci.nsIUpdateManager);
this._vc = Cc["@mozilla.org/xpcom/version-comparator;1"].
getService(Ci.nsIVersionComparator);
}
|
javascript
|
{
"resource": ""
}
|
q15423
|
softwareUpdate_assertUpdateApplied
|
train
|
function softwareUpdate_assertUpdateApplied(updateData) {
// Get the information from the last update
var info = updateData.updates[updateData.updateIndex];
// The upgraded version should be identical with the version given by
// the update and we shouldn't have run a downgrade
var check = this._vc.compare(info.build_post.version, info.build_pre.version);
this._controller.assert(function() {
return check >= 0;
}, "The version number of the upgraded build is higher or equal.");
// The build id should be identical with the one from the update
this._controller.assert(function() {
return info.build_post.buildid == info.patch.buildid;
}, "The build id is equal to the build id of the update.");
// An upgrade should not change the builds locale
this._controller.assert(function() {
return info.build_post.locale == info.build_pre.locale;
}, "The locale of the updated build is identical to the original locale.");
}
|
javascript
|
{
"resource": ""
}
|
q15424
|
softwareUpdate_closeDialog
|
train
|
function softwareUpdate_closeDialog() {
if (this._controller) {
this._controller.keypress(null, "VK_ESCAPE", {});
this._controller.sleep(500);
this._controller = null;
this._wizard = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q15425
|
softwareUpdate_download
|
train
|
function softwareUpdate_download(channel, waitForFinish, timeout) {
waitForFinish = waitForFinish ? waitForFinish : true;
// Check that the correct channel has been set
this._controller.assert(function() {
return channel == this.channel;
}, "The current update channel is identical to the specified one.", this);
// Click the next button
var next = this.getElement({type: "button", subtype: "next"});
this._controller.click(next);
// Wait for the download page - if it fails the update was already cached
try {
this.waitForWizardPage(WIZARD_PAGES.downloading);
if (waitForFinish)
this.waitforDownloadFinished(timeout);
} catch (ex) {
this.waitForWizardPage(WIZARD_PAGES.finished);
}
}
|
javascript
|
{
"resource": ""
}
|
q15426
|
softwareUpdate_openDialog
|
train
|
function softwareUpdate_openDialog(browserController) {
// XXX: After Firefox 4 has been released and we do not have to test any
// beta release anymore uncomment out the following code
// With version >= 4.0b7pre the update dialog is reachable from within the
// about window now.
var appVersion = utils.appInfo.version;
if (this._vc.compare(appVersion, "4.0b7pre") >= 0) {
// XXX: We can't open the about window, otherwise a parallel download of
// the update will let us fallback to a complete one all the time
// Open the about window and check the update button
//var aboutItem = new elementslib.Elem(browserController.menus.helpMenu.aboutName);
//browserController.click(aboutItem);
//
//utils.handleWindow("type", "Browser:About", function(controller) {
// // XXX: Bug 599290 - Check for updates has been completely relocated
// // into the about window. We can't check the in-about ui yet.
// var updateButton = new elementslib.ID(controller.window.document,
// "checkForUpdatesButton");
// //controller.click(updateButton);
// controller.waitForElement(updateButton, gTimeout);
//});
// For now just call the old ui until we have support for the about window.
var updatePrompt = Cc["@mozilla.org/updates/update-prompt;1"].
createInstance(Ci.nsIUpdatePrompt);
updatePrompt.checkForUpdates();
} else {
// For builds <4.0b7pre
updateItem = new elementslib.Elem(browserController.menus.helpMenu.checkForUpdates);
browserController.click(updateItem);
}
this.waitForDialogOpen(browserController);
}
|
javascript
|
{
"resource": ""
}
|
q15427
|
softwareUpdate_waitForCheckFinished
|
train
|
function softwareUpdate_waitForCheckFinished(timeout) {
timeout = timeout ? timeout : gTimeoutUpdateCheck;
this._controller.waitFor(function() {
return this.currentPage != WIZARD_PAGES.checking;
}, "Check for updates has been completed.", timeout, null, this);
}
|
javascript
|
{
"resource": ""
}
|
q15428
|
softwareUpdate_waitForDialogOpen
|
train
|
function softwareUpdate_waitForDialogOpen(browserController) {
this._controller = utils.handleWindow("type", "Update:Wizard",
null, true);
this._wizard = this.getElement({type: "wizard"});
this._controller.waitFor(function() {
return this.currentPage != WIZARD_PAGES.dummy;
}, "Dummy wizard page has been made invisible.", undefined, undefined, this);
this._controller.window.focus();
}
|
javascript
|
{
"resource": ""
}
|
q15429
|
softwareUpdate_waitForDownloadFinished
|
train
|
function softwareUpdate_waitForDownloadFinished(timeout) {
timeout = timeout ? timeout : gTimeoutUpdateDownload;
var progress = this.getElement({type: "download_progress"});
this._controller.waitFor(function() {
return progress.getNode().value == 100;
}, "Update has been finished downloading.", timeout);
this.waitForWizardPage(WIZARD_PAGES.finished);
}
|
javascript
|
{
"resource": ""
}
|
q15430
|
getCanonicalPath
|
train
|
function getCanonicalPath(path) {
path = path.replace(/\//g, '\\');
path = path.replace(/\\\\/g, '\\');
return path;
}
|
javascript
|
{
"resource": ""
}
|
q15431
|
checkResponse
|
train
|
function checkResponse(data) {
if (data && typeof data.error === 'string') {
let ctor = ERROR_CODE_TO_TYPE.get(data.error) || WebDriverError;
throw new ctor(data.message);
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q15432
|
throwDecodedError
|
train
|
function throwDecodedError(data) {
if (isErrorResponse(data)) {
let ctor = ERROR_CODE_TO_TYPE.get(data.error) || WebDriverError;
let err = new ctor(data.message);
// TODO(jleyba): remove whichever case is excluded from the final W3C spec.
if (typeof data.stacktrace === 'string') {
err.remoteStacktrace = data.stacktrace;
} else if (typeof data.stackTrace === 'string') {
err.remoteStacktrace = data.stackTrace;
}
throw err;
}
throw new WebDriverError('Unknown error: ' + JSON.stringify(data));
}
|
javascript
|
{
"resource": ""
}
|
q15433
|
checkLegacyResponse
|
train
|
function checkLegacyResponse(responseObj) {
// Handle the legacy Selenium error response format.
if (responseObj
&& typeof responseObj === 'object'
&& typeof responseObj['status'] === 'number'
&& responseObj['status'] !== 0) {
let status = responseObj['status'];
let ctor = LEGACY_ERROR_CODE_TO_TYPE.get(status) || WebDriverError;
let value = responseObj['value'];
if (!value || typeof value !== 'object') {
throw new ctor(value + '');
} else {
let message = value['message'] + '';
if (ctor !== UnexpectedAlertOpenError) {
throw new ctor(message);
}
let text = '';
if (value['alert'] && typeof value['alert']['text'] === 'string') {
text = value['alert']['text'];
}
throw new UnexpectedAlertOpenError(message, text);
}
}
return responseObj;
}
|
javascript
|
{
"resource": ""
}
|
q15434
|
train
|
function(commandRequest) {
//decodeURIComponent doesn't strip plus signs
var processed = commandRequest.replace(/\+/g, "%20");
// strip trailing spaces
var processed = processed.replace(/\s+$/, "");
var vars = processed.split("&");
var cmdArgs = new Object();
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
cmdArgs[pair[0]] = pair[1];
}
var cmd = cmdArgs['cmd'];
var arg1 = cmdArgs['1'];
if (null == arg1) arg1 = "";
arg1 = decodeURIComponent(arg1);
var arg2 = cmdArgs['2'];
if (null == arg2) arg2 = "";
arg2 = decodeURIComponent(arg2);
if (cmd == null) {
throw new Error("Bad command request: " + commandRequest);
}
return new SeleniumCommand(cmd, arg1, arg2);
}
|
javascript
|
{
"resource": ""
}
|
|
q15435
|
escapeCss
|
train
|
function escapeCss(css) {
if (typeof css !== 'string') {
throw new TypeError('input must be a string');
}
let ret = '';
const n = css.length;
for (let i = 0; i < n; i++) {
const c = css.charCodeAt(i);
if (c == 0x0) {
throw new InvalidCharacterError();
}
if ((c >= 0x0001 && c <= 0x001F)
|| c == 0x007F
|| (i == 0 && c >= 0x0030 && c <= 0x0039)
|| (i == 1 && c >= 0x0030 && c <= 0x0039
&& css.charCodeAt(0) == 0x002D)) {
ret += '\\' + c.toString(16) + ' ';
continue;
}
if (i == 0 && c == 0x002D && n == 1) {
ret += '\\' + css.charAt(i);
continue;
}
if (c >= 0x0080
|| c == 0x002D // -
|| c == 0x005F // _
|| (c >= 0x0030 && c <= 0x0039) // [0-9]
|| (c >= 0x0041 && c <= 0x005A) // [A-Z]
|| (c >= 0x0061 && c <= 0x007A)) { // [a-z]
ret += css.charAt(i);
continue;
}
ret += '\\' + css.charAt(i);
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q15436
|
check
|
train
|
function check(locator) {
if (locator instanceof By || typeof locator === 'function') {
return locator;
}
if (locator
&& typeof locator === 'object'
&& typeof locator.using === 'string'
&& typeof locator.value === 'string') {
return new By(locator.using, locator.value);
}
for (let key in locator) {
if (locator.hasOwnProperty(key) && By.hasOwnProperty(key)) {
return By[key](locator[key]);
}
}
throw new TypeError('Invalid locator');
}
|
javascript
|
{
"resource": ""
}
|
q15437
|
getFailureMessage
|
train
|
function getFailureMessage(exceptionMessage) {
var msg = 'Snapsie failed: ';
if (exceptionMessage) {
if (exceptionMessage ==
"Automation server can't create object") {
msg += 'Is it installed? Does it have permission to run '
+ 'as an add-on? See http://snapsie.sourceforge.net/';
}
else {
msg += exceptionMessage;
}
}
else {
msg += 'Undocumented error';
}
return msg;
}
|
javascript
|
{
"resource": ""
}
|
q15438
|
nodeGlobalRequire
|
train
|
function nodeGlobalRequire(file) {
vm.runInThisContext.call(global, fs.readFileSync(file), file);
}
|
javascript
|
{
"resource": ""
}
|
q15439
|
aboutSessionRestore_getRestoreState
|
train
|
function aboutSessionRestore_getRestoreState(element) {
var tree = this.tabList.getNode();
return tree.view.getCellValue(element.listIndex, tree.columns.getColumnAt(0));
}
|
javascript
|
{
"resource": ""
}
|
q15440
|
aboutSessionRestore_getTabs
|
train
|
function aboutSessionRestore_getTabs(window) {
var tabs = [ ];
var tree = this.tabList.getNode();
// Add entries when they are tabs (no container)
var ii = window.listIndex + 1;
while (ii < tree.view.rowCount && !tree.view.isContainer(ii)) {
tabs.push({
index: tabs.length,
listIndex : ii,
restore: tree.view.getCellValue(ii, tree.columns.getColumnAt(0)),
title: tree.view.getCellText(ii, tree.columns.getColumnAt(2))
});
ii++;
}
return tabs;
}
|
javascript
|
{
"resource": ""
}
|
q15441
|
aboutSessionRestore_getWindows
|
train
|
function aboutSessionRestore_getWindows() {
var windows = [ ];
var tree = this.tabList.getNode();
for (var ii = 0; ii < tree.view.rowCount; ii++) {
if (tree.view.isContainer(ii)) {
windows.push({
index: windows.length,
listIndex : ii,
open: tree.view.isContainerOpen(ii),
restore: tree.view.getCellValue(ii, tree.columns.getColumnAt(0)),
title: tree.view.getCellText(ii, tree.columns.getColumnAt(2))
});
}
}
return windows;
}
|
javascript
|
{
"resource": ""
}
|
q15442
|
aboutSessionRestore_toggleRestoreState
|
train
|
function aboutSessionRestore_toggleRestoreState(element) {
var state = this.getRestoreState(element);
widgets.clickTreeCell(this._controller, this.tabList, element.listIndex, 0, {});
this._controller.sleep(0);
this._controller.assertJS("subject.newState != subject.oldState",
{newState : this.getRestoreState(element), oldState : state});
}
|
javascript
|
{
"resource": ""
}
|
q15443
|
undoClosedTab
|
train
|
function undoClosedTab(controller, event)
{
var count = sessionStoreService.getClosedTabCount(controller.window);
switch (event.type) {
case "menu":
throw new Error("Menu gets build dynamically and cannot be accessed.");
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "tabCmd.commandkey");
controller.keypress(null, cmdKey, {accelKey: true, shiftKey: true});
break;
}
if (count > 0)
controller.assertJS("subject.newTabCount < subject.oldTabCount",
{
newTabCount : sessionStoreService.getClosedTabCount(controller.window),
oldTabCount : count
});
}
|
javascript
|
{
"resource": ""
}
|
q15444
|
undoClosedWindow
|
train
|
function undoClosedWindow(controller, event)
{
var count = sessionStoreService.getClosedWindowCount(controller.window);
switch (event.type) {
case "menu":
throw new Error("Menu gets build dynamically and cannot be accessed.");
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "newNavigatorCmd.key");
controller.keypress(null, cmdKey, {accelKey: true, shiftKey: true});
break;
}
if (count > 0)
controller.assertJS("subject.newWindowCount < subject.oldWindowCount",
{
newWindowCount : sessionStoreService.getClosedWindowCount(controller.window),
oldWindowCount : count
});
}
|
javascript
|
{
"resource": ""
}
|
q15445
|
pushBack
|
train
|
function pushBack(t) {
goog.labs.format.csv.assertToken_(t);
goog.asserts.assert(goog.isNull(pushBackToken));
pushBackToken = t;
}
|
javascript
|
{
"resource": ""
}
|
q15446
|
readQuotedField
|
train
|
function readQuotedField() {
// We've already consumed the first quote by the time we get here.
var start = index;
var end = null;
for (var token = nextToken(); token != EOF; token = nextToken()) {
if (token == '"') {
end = index - 1;
token = nextToken();
// Two double quotes in a row. Keep scanning.
if (token == '"') {
end = null;
continue;
}
// End of field. Break out.
if (token == delimiter || token == EOF || token == NEWLINE) {
if (token == NEWLINE) {
pushBack(token);
}
break;
}
if (!opt_ignoreErrors) {
// Ignoring errors here means keep going in current field after
// closing quote. E.g. "ab"c,d splits into abc,d
throw new goog.labs.format.csv.ParseError(
text, index - 1,
'Unexpected character "' + token + '" after quote mark');
} else {
// Fall back to reading the rest of this field as unquoted.
// Note: the rest is guaranteed not start with ", as that case is
// eliminated above.
var prefix = '"' + text.substring(start, index);
var suffix = readField();
if (suffix == EOR) {
pushBack(NEWLINE);
return prefix;
} else {
return prefix + suffix;
}
}
}
}
if (goog.isNull(end)) {
if (!opt_ignoreErrors) {
throw new goog.labs.format.csv.ParseError(
text, text.length - 1, 'Unexpected end of text after open quote');
} else {
end = text.length;
}
}
// Take substring, combine double quotes.
return text.substring(start, end).replace(/""/g, '"');
}
|
javascript
|
{
"resource": ""
}
|
q15447
|
readField
|
train
|
function readField() {
var start = index;
var didSeeComma = sawComma;
sawComma = false;
var token = nextToken();
if (token == EMPTY) {
return EOR;
}
if (token == EOF || token == NEWLINE) {
if (didSeeComma) {
pushBack(EMPTY);
return '';
}
return EOR;
}
// This is the beginning of a quoted field.
if (token == '"') {
return readQuotedField();
}
while (true) {
// This is the end of line or file.
if (token == EOF || token == NEWLINE) {
pushBack(token);
break;
}
// This is the end of record.
if (token == delimiter) {
sawComma = true;
break;
}
if (token == '"' && !opt_ignoreErrors) {
throw new goog.labs.format.csv.ParseError(
text, index - 1, 'Unexpected quote mark');
}
token = nextToken();
}
var returnString = (token == EOF) ?
text.substring(start) : // Return to end of file.
text.substring(start, index - 1);
return returnString.replace(/[\r\n]+/g, ''); // Squash any CRLFs.
}
|
javascript
|
{
"resource": ""
}
|
q15448
|
readRecord
|
train
|
function readRecord() {
if (index >= text.length) {
return EOF;
}
var record = [];
for (var field = readField(); field != EOR; field = readField()) {
record.push(field);
}
return record;
}
|
javascript
|
{
"resource": ""
}
|
q15449
|
train
|
function( data ) {
if ( data && /\S/.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval )
script.appendChild( document.createTextNode( data ) );
else
script.text = data;
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15450
|
num
|
train
|
function num(elem, prop) {
return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
|
javascript
|
{
"resource": ""
}
|
q15451
|
train
|
function( event, data, elem, bubbling ) {
// Event object or event type
var type = event.type || event;
if( !bubbling ){
event = typeof event === "object" ?
// jQuery.Event object
event[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( this.global[type] )
jQuery.each( jQuery.cache, function(){
if ( this.events && this.events[type] )
jQuery.event.trigger( event, data, this.handle.elem );
});
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
return undefined;
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray(data);
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = jQuery.data(elem, "handle");
if ( handle )
handle.apply( elem, data );
// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
event.result = false;
// Trigger the native events (except for clicks on links)
if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
this.triggered = true;
try {
elem[ type ]();
// prevent IE from throwing an error for some hidden elements
} catch (e) {}
}
this.triggered = false;
if ( !event.isPropagationStopped() ) {
var parent = elem.parentNode || elem.ownerDocument;
if ( parent )
jQuery.event.trigger(event, data, parent, true);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15452
|
train
|
function(isTimeout){
// The request was aborted, clear the interval and decrement jQuery.active
if (xhr.readyState == 0) {
if (ival) {
// clear poll interval
clearInterval(ival);
ival = null;
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
requestDone = true;
// clear poll interval
if (ival) {
clearInterval(ival);
ival = null;
}
status = isTimeout == "timeout" ? "timeout" :
!jQuery.httpSuccess( xhr ) ? "error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
"success";
if ( status == "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch(e) {
status = "parsererror";
}
}
// Make sure that the request was successful or notmodified
if ( status == "success" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes;
try {
modRes = xhr.getResponseHeader("Last-Modified");
} catch(e) {} // swallow exception thrown by FF if header is not available
if ( s.ifModified && modRes )
jQuery.lastModified[s.url] = modRes;
// JSONP handles its own success callback
if ( !jsonp )
success();
} else
jQuery.handleError(s, xhr, status);
// Fire the complete handlers
complete();
if ( isTimeout )
xhr.abort();
// Stop memory leaks
if ( s.async )
xhr = null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15453
|
train
|
function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol == "file:" ||
( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
} catch(e){}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q15454
|
isBookmarkInFolder
|
train
|
function isBookmarkInFolder(uri, folderId)
{
var ids = bookmarksService.getBookmarkIdsForURI(uri, {});
for (let i = 0; i < ids.length; i++) {
if (bookmarksService.getFolderIdForItem(ids[i]) == folderId)
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q15455
|
restoreDefaultBookmarks
|
train
|
function restoreDefaultBookmarks() {
// Set up the observer -- we're only checking for success here, so we'll simply
// time out and throw on failure. It makes the code much clearer than handling
// finished state and success state separately.
var importSuccessful = false;
var importObserver = {
observe: function (aSubject, aTopic, aData) {
if (aTopic == TOPIC_BOOKMARKS_RESTORE_SUCCESS) {
importSuccessful = true;
}
}
}
observerService.addObserver(importObserver, TOPIC_BOOKMARKS_RESTORE_SUCCESS, false);
try {
// Fire off the import
var bookmarksURI = utils.createURI(BOOKMARKS_RESOURCE);
var importer = Cc["@mozilla.org/browser/places/import-export-service;1"].
getService(Ci.nsIPlacesImportExportService);
importer.importHTMLFromURI(bookmarksURI, true);
// Wait for it to be finished--the observer above will flip this flag
mozmill.utils.waitFor(function () {
return importSuccessful;
}, "Default bookmarks have finished importing", BOOKMARKS_TIMEOUT);
}
finally {
// Whatever happens, remove the observer afterwards
observerService.removeObserver(importObserver, TOPIC_BOOKMARKS_RESTORE_SUCCESS);
}
}
|
javascript
|
{
"resource": ""
}
|
q15456
|
load
|
train
|
function load(path) {
return io.read(path).then(data => {
let zip = new Zip;
return zip.z_.loadAsync(data).then(() => zip);
});
}
|
javascript
|
{
"resource": ""
}
|
q15457
|
unzip
|
train
|
function unzip(src, dst) {
return load(src).then(zip => {
let promisedDirs = new Map;
let promises = [];
zip.z_.forEach((relPath, file) => {
let p;
if (file.dir) {
p = createDir(relPath);
} else {
let dirname = path.dirname(relPath);
if (dirname === '.') {
p = writeFile(relPath, file);
} else {
p = createDir(dirname).then(() => writeFile(relPath, file));
}
}
promises.push(p);
});
return Promise.all(promises).then(() => dst);
function createDir(dir) {
let p = promisedDirs.get(dir);
if (!p) {
p = io.mkdirp(path.join(dst, dir));
promisedDirs.set(dir, p);
}
return p;
}
function writeFile(relPath, file) {
return file.async('nodebuffer')
.then(buffer => io.write(path.join(dst, relPath), buffer));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q15458
|
headersToString
|
train
|
function headersToString(headers) {
let ret = [];
headers.forEach(function(value, name) {
ret.push(`${name.toLowerCase()}: ${value}`);
});
return ret.join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q15459
|
getTabsWithURL
|
train
|
function getTabsWithURL(aUrl) {
var tabs = [ ];
var uri = utils.createURI(aUrl, null, null);
var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
getService(Ci.nsIWindowMediator);
var winEnum = wm.getEnumerator("navigator:browser");
// Iterate through all windows
while (winEnum.hasMoreElements()) {
var window = winEnum.getNext();
// Don't check windows which are about to close or don't have gBrowser set
if (window.closed || !("gBrowser" in window))
continue;
// Iterate through all tabs in the current window
var browsers = window.gBrowser.browsers;
for (var i = 0; i < browsers.length; i++) {
var browser = browsers[i];
if (browser.currentURI.equals(uri)) {
tabs.push({
controller : new mozmill.controller.MozMillController(window),
index : i
});
}
}
}
return tabs;
}
|
javascript
|
{
"resource": ""
}
|
q15460
|
tabBrowser_closeAllTabs
|
train
|
function tabBrowser_closeAllTabs()
{
while (this._controller.tabs.length > 1) {
this.closeTab({type: "menu"});
}
this._controller.open("about:blank");
this._controller.waitForPageLoad();
}
|
javascript
|
{
"resource": ""
}
|
q15461
|
tabBrowser_closeTab
|
train
|
function tabBrowser_closeTab(aEvent) {
var event = aEvent || { };
var type = (event.type == undefined) ? "menu" : event.type;
// Disable tab closing animation for default behavior
prefs.preferences.setPref(PREF_TABS_ANIMATE, false);
// Add event listener to wait until the tab has been closed
var self = { closed: false };
function checkTabClosed() { self.closed = true; }
this._controller.window.addEventListener("TabClose", checkTabClosed, false);
switch (type) {
case "closeButton":
var button = this.getElement({type: "tabs_tabCloseButton",
subtype: "tab", value: this.getTab()});
this._controller.click(button);
break;
case "menu":
var menuitem = new elementslib.Elem(this._controller.menus['file-menu'].menu_close);
this._controller.click(menuitem);
break;
case "middleClick":
var tab = this.getTab(event.index);
this._controller.middleClick(tab);
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "closeCmd.key");
this._controller.keypress(null, cmdKey, {accelKey: true});
break;
default:
throw new Error(arguments.callee.name + ": Unknown event type - " + type);
}
try {
this._controller.waitForEval("subject.tab.closed == true", TIMEOUT, 100,
{tab: self});
} finally {
this._controller.window.removeEventListener("TabClose", checkTabClosed, false);
prefs.preferences.clearUserPref(PREF_TABS_ANIMATE);
}
}
|
javascript
|
{
"resource": ""
}
|
q15462
|
tabBrowser_getTab
|
train
|
function tabBrowser_getTab(index) {
if (index === undefined)
index = this.selectedIndex;
return this.getElement({type: "tabs_tab", subtype: "index", value: index});
}
|
javascript
|
{
"resource": ""
}
|
q15463
|
tabBrowser_getTabPanelElement
|
train
|
function tabBrowser_getTabPanelElement(tabIndex, elemString)
{
var index = tabIndex ? tabIndex : this.selectedIndex;
var elemStr = elemString ? elemString : "";
// Get the tab panel and check if an element has to be fetched
var panel = this.getElement({type: "tabs_tabPanel", subtype: "tab", value: this.getTab(index)});
var elem = new elementslib.Lookup(this._controller.window.document, panel.expression + elemStr);
return elem;
}
|
javascript
|
{
"resource": ""
}
|
q15464
|
tabBrowser_openTab
|
train
|
function tabBrowser_openTab(aEvent) {
var event = aEvent || { };
var type = (event.type == undefined) ? "menu" : event.type;
// Disable tab closing animation for default behavior
prefs.preferences.setPref(PREF_TABS_ANIMATE, false);
// Add event listener to wait until the tab has been opened
var self = { opened: false };
function checkTabOpened() { self.opened = true; }
this._controller.window.addEventListener("TabOpen", checkTabOpened, false);
switch (type) {
case "menu":
var menuitem = new elementslib.Elem(this._controller.menus['file-menu'].menu_newNavigatorTab);
this._controller.click(menuitem);
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "tabCmd.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true});
break;
case "newTabButton":
var newTabButton = this.getElement({type: "tabs_newTabButton"});
this._controller.click(newTabButton);
break;
case "tabStrip":
var tabStrip = this.getElement({type: "tabs_strip"});
// RTL-locales need to be treated separately
if (utils.getEntity(this.getDtds(), "locale.dir") == "rtl") {
// XXX: Workaround until bug 537968 has been fixed
this._controller.click(tabStrip, 100, 3);
// Todo: Calculate the correct x position
this._controller.doubleClick(tabStrip, 100, 3);
} else {
// XXX: Workaround until bug 537968 has been fixed
this._controller.click(tabStrip, tabStrip.getNode().clientWidth - 100, 3);
// Todo: Calculate the correct x position
this._controller.doubleClick(tabStrip, tabStrip.getNode().clientWidth - 100, 3);
}
break;
default:
throw new Error(arguments.callee.name + ": Unknown event type - " + type);
}
try {
this._controller.waitForEval("subject.tab.opened == true", TIMEOUT, 100,
{tab: self});
} finally {
this._controller.window.removeEventListener("TabOpen", checkTabOpened, false);
prefs.preferences.clearUserPref(PREF_TABS_ANIMATE);
}
}
|
javascript
|
{
"resource": ""
}
|
q15465
|
tabBrowser_waitForTabPanel
|
train
|
function tabBrowser_waitForTabPanel(tabIndex, elemString) {
// Get the specified tab panel element
var tabPanel = this.getTabPanelElement(tabIndex, elemString);
// Get the style information for the tab panel element
var style = this._controller.window.getComputedStyle(tabPanel.getNode(), null);
// Wait for the top margin to be 0px - ie. has stopped animating
// XXX: A notification bar starts at a negative pixel margin and drops down
// to 0px. This creates a race condition where a test may click
// before the notification bar appears at it's anticipated screen location
this._controller.waitFor(function () {
return style.marginTop == '0px';
}, "Expected notification bar to be visible: '" + elemString + "' ");
}
|
javascript
|
{
"resource": ""
}
|
q15466
|
replacerDemuxer
|
train
|
function replacerDemuxer(
match, flags, width, dotp, precision, type, offset, wholeString) {
// The % is too simple and doesn't take an argument.
if (type == '%') {
return '%';
}
// Try to get the actual value from parent function.
var value = args.shift();
// If we didn't get any arguments, fail.
if (typeof value == 'undefined') {
throw Error('[goog.string.format] Not enough arguments');
}
// Patch the value argument to the beginning of our type specific call.
arguments[0] = value;
return goog.string.format.demuxes_[type].apply(null, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q15467
|
getText
|
train
|
function getText(element) {
var text = "";
var isRecentFirefox = (browserVersion.isFirefox && browserVersion.firefoxVersion >= "1.5");
if (isRecentFirefox || browserVersion.isKonqueror || browserVersion.isSafari || browserVersion.isOpera) {
text = getTextContent(element);
} else if (element.textContent) {
text = element.textContent;
} else if (element.innerText) {
text = element.innerText;
}
text = normalizeNewlines(text);
text = normalizeSpaces(text);
return text.trim();
}
|
javascript
|
{
"resource": ""
}
|
q15468
|
normalizeSpaces
|
train
|
function normalizeSpaces(text)
{
// IE has already done this conversion, so doing it again will remove multiple nbsp
if (browserVersion.isIE)
{
return text;
}
// Replace multiple spaces with a single space
// TODO - this shouldn't occur inside PRE elements
text = text.replace(/\ +/g, " ");
// Replace with a space
var nbspPattern = new RegExp(String.fromCharCode(160), "g");
if (browserVersion.isSafari) {
return replaceAll(text, String.fromCharCode(160), " ");
} else {
return text.replace(nbspPattern, " ");
}
}
|
javascript
|
{
"resource": ""
}
|
q15469
|
setText
|
train
|
function setText(element, text) {
if (element.textContent != null) {
element.textContent = text;
} else if (element.innerText != null) {
element.innerText = text;
}
}
|
javascript
|
{
"resource": ""
}
|
q15470
|
AssertionArguments
|
train
|
function AssertionArguments(args) {
if (args.length == 2) {
this.comment = "";
this.expected = args[0];
this.actual = args[1];
} else {
this.comment = args[0] + "; ";
this.expected = args[1];
this.actual = args[2];
}
}
|
javascript
|
{
"resource": ""
}
|
q15471
|
o2s
|
train
|
function o2s(obj) {
var s = "";
for (key in obj) {
var line = key + "->" + obj[key];
line.replace("\n", " ");
s += line + "\n";
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q15472
|
getTimeoutTime
|
train
|
function getTimeoutTime(timeout) {
var now = new Date().getTime();
var timeoutLength = parseInt(timeout);
if (isNaN(timeoutLength)) {
throw new SeleniumError("Timeout is not a number: '" + timeout + "'");
}
return now + timeoutLength;
}
|
javascript
|
{
"resource": ""
}
|
q15473
|
hasJavascriptHref
|
train
|
function hasJavascriptHref(element) {
if (getTagName(element) != 'a') {
return false;
}
if (element.getAttribute('onclick')) {
return false;
}
if (! element.href) {
return false;
}
if (! /\s*javascript:/i.test(element.href)) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q15474
|
XPathEngine
|
train
|
function XPathEngine() {
// public
this.doc = null;
/**
* Returns whether the current runtime environment supports the use of this
* engine. Needs override.
*/
this.isAvailable = function() { return false; };
/**
* Sets the document to be used for evaluation. Always returns the current
* engine object so as to be chainable.
*/
this.setDocument = function(newDocument) {
this.doc = newDocument;
return this;
};
/**
* Returns a possibly-empty list of nodes. Needs override.
*/
this.selectNodes = function(xpath, contextNode, namespaceResolver) {
return [];
};
/**
* Returns a single node, or null if no nodes were selected. This default
* implementation simply returns the first result of selectNodes(), or
* null.
*/
this.selectSingleNode = function(xpath, contextNode, namespaceResolver) {
var nodes = this.selectNodes(xpath, contextNode, namespaceResolver);
return (nodes.length > 0 ? nodes[0] : null);
};
/**
* Returns the number of matching nodes. This default implementation simply
* returns the length of the result of selectNodes(), which should be
* adequate for most sub-implementations.
*/
this.countNodes = function(xpath, contextNode, namespaceResolver) {
return this.selectNodes(xpath, contextNode, namespaceResolver).length;
};
/**
* An optimization; likely to be a no-op for many implementations. Always
* returns the current engine object so as to be chainable.
*/
this.setIgnoreAttributesWithoutValue = function(ignore) { return this; };
}
|
javascript
|
{
"resource": ""
}
|
q15475
|
BoundedCache
|
train
|
function BoundedCache(newMaxSize) {
var maxSize = newMaxSize;
var map = {};
var size = 0;
var counter = -1;
/**
* Adds a key-value pair to the cache. If the cache is at its size limit,
* the least-recently used entry is evicted.
*/
this.put = function(key, value) {
if (map[key]) {
// entry already exists
map[key] = { usage: ++counter, value: value };
}
else {
map[key] = { usage: ++counter, value: value };
++size;
if (size > maxSize) {
// remove the least recently used item
var minUsage = counter;
var keyToRemove = key;
for (var key in map) {
if (map[key].usage < minUsage) {
minUsage = map[key].usage;
keyToRemove = key;
}
}
this.remove(keyToRemove);
}
}
};
/**
* Returns a cache item by its key, and updates its use status.
*/
this.get = function(key) {
if (map[key]) {
map[key].usage = ++counter;
return map[key].value;
}
return null;
};
/**
* Removes a cache item by its key.
*/
this.remove = function(key) {
if (map[key]) {
delete map[key];
--size;
if (size == 0) {
counter = -1;
}
}
}
/**
* Clears all entries in the cache.
*/
this.clear = function() {
map = {};
size = 0;
counter = -1;
};
}
|
javascript
|
{
"resource": ""
}
|
q15476
|
isXPathValid
|
train
|
function isXPathValid(xpath, node) {
var contextNode = mirror.getReflection();
return (engine.setDocument(mirror.getReflection())
.selectSingleNode(xpath, contextNode, namespaceResolver) === node);
}
|
javascript
|
{
"resource": ""
}
|
q15477
|
isDetached
|
train
|
function isDetached(node) {
while (node = node.parentNode) {
if (node.nodeType == 11) {
// it's a document fragment; we're detached (IE)
return true;
}
else if (node.nodeType == 9) {
// it's a normal document; we're attached
return false;
}
}
// we didn't find a document; we're detached (most other browsers)
return true;
}
|
javascript
|
{
"resource": ""
}
|
q15478
|
getEngineFor
|
train
|
function getEngineFor(inDocument) {
if (allowNativeXPath &&
nativeEngine.setDocument(inDocument).isAvailable()) {
return nativeEngine;
}
var currentEngine = engines[currentEngineName];
if (currentEngine &&
currentEngine.setDocument(inDocument).isAvailable()) {
return currentEngine;
}
return engines[defaultEngineName].setDocument(inDocument);
}
|
javascript
|
{
"resource": ""
}
|
q15479
|
dispatch
|
train
|
function dispatch(methodName, inDocument, xpath, contextNode, namespaceResolver) {
xpath = preprocess(xpath);
if (! contextNode) {
contextNode = inDocument;
}
var result = getEngineFor(inDocument)
.setIgnoreAttributesWithoutValue(ignoreAttributesWithoutValue)
[methodName](xpath, contextNode, namespaceResolver);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q15480
|
eval_xpath
|
train
|
function eval_xpath(xpath, inDocument, opts)
{
if (! opts) {
var opts = {};
}
var contextNode = opts.contextNode
? opts.contextNode : inDocument;
var namespaceResolver = opts.namespaceResolver
? opts.namespaceResolver : null;
var xpathLibrary = opts.xpathLibrary
? opts.xpathLibrary : null;
var allowNativeXpath = (opts.allowNativeXpath != undefined)
? opts.allowNativeXpath : true;
var ignoreAttributesWithoutValue = (opts.ignoreAttributesWithoutValue != undefined)
? opts.ignoreAttributesWithoutValue : true;
var returnOnFirstMatch = (opts.returnOnFirstMatch != undefined)
? opts.returnOnFirstMatch : false;
if (! eval_xpath.xpathEvaluator) {
eval_xpath.xpathEvaluator = new XPathEvaluator();
}
var xpathEvaluator = eval_xpath.xpathEvaluator;
xpathEvaluator.setCurrentEngine(xpathLibrary);
xpathEvaluator.setAllowNativeXPath(allowNativeXpath);
xpathEvaluator.setIgnoreAttributesWithoutValue(ignoreAttributesWithoutValue);
if (returnOnFirstMatch) {
var singleNode = xpathEvaluator.selectSingleNode(inDocument, xpath,
contextNode, namespaceResolver);
var results = (singleNode ? [ singleNode ] : []);
}
else {
var results = xpathEvaluator.selectNodes(inDocument, xpath, contextNode,
namespaceResolver);
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q15481
|
eval_css
|
train
|
function eval_css(locator, inDocument) {
var results = [];
try {
window.Sizzle(locator, inDocument, results);
} catch (ignored) {
// Presumably poor formatting
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q15482
|
are_equal
|
train
|
function are_equal(a1, a2)
{
if (typeof(a1) != typeof(a2))
return false;
switch(typeof(a1)) {
case 'object':
// arrays
if (a1.length) {
if (a1.length != a2.length)
return false;
for (var i = 0; i < a1.length; ++i) {
if (!are_equal(a1[i], a2[i]))
return false
}
}
// associative arrays
else {
var keys = {};
for (var key in a1) {
keys[key] = true;
}
for (var key in a2) {
keys[key] = true;
}
for (var key in keys) {
if (!are_equal(a1[key], a2[key]))
return false;
}
}
return true;
default:
return a1 == a2;
}
}
|
javascript
|
{
"resource": ""
}
|
q15483
|
clone
|
train
|
function clone(orig) {
var copy;
switch(typeof(orig)) {
case 'object':
copy = (orig.length) ? [] : {};
for (var attr in orig) {
copy[attr] = clone(orig[attr]);
}
break;
default:
copy = orig;
break;
}
return copy;
}
|
javascript
|
{
"resource": ""
}
|
q15484
|
parse_kwargs
|
train
|
function parse_kwargs(kwargs)
{
var args = new Object();
var pairs = kwargs.split(/,/);
for (var i = 0; i < pairs.length;) {
if (i > 0 && pairs[i].indexOf('=') == -1) {
// the value string contained a comma. Glue the parts back together.
pairs[i-1] += ',' + pairs.splice(i, 1)[0];
}
else {
++i;
}
}
for (var i = 0; i < pairs.length; ++i) {
var splits = pairs[i].split(/=/);
if (splits.length == 1) {
continue;
}
var key = splits.shift();
var value = splits.join('=');
args[key.trim()] = value.trim();
}
return args;
}
|
javascript
|
{
"resource": ""
}
|
q15485
|
to_kwargs
|
train
|
function to_kwargs(args, sortedKeys)
{
var s = '';
if (!sortedKeys) {
var sortedKeys = keys(args).sort();
}
for (var i = 0; i < sortedKeys.length; ++i) {
var k = sortedKeys[i];
if (args[k] != undefined) {
if (s) {
s += ', ';
}
s += k + '=' + args[k];
}
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q15486
|
is_ancestor
|
train
|
function is_ancestor(node, target)
{
while (target.parentNode) {
target = target.parentNode;
if (node == target)
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q15487
|
train
|
function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
// Set display property to block for height/width animations
if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) {
this.elem.style.display = "block";
}
}
|
javascript
|
{
"resource": ""
}
|
|
q15488
|
locationBar_clear
|
train
|
function locationBar_clear() {
this.focus({type: "shortcut"});
this._controller.keypress(this.urlbar, "VK_DELETE", {});
this._controller.waitForEval("subject.value == ''",
TIMEOUT, 100, this.urlbar.getNode());
}
|
javascript
|
{
"resource": ""
}
|
q15489
|
locationBar_focus
|
train
|
function locationBar_focus(event) {
switch (event.type) {
case "click":
this._controller.click(this.urlbar);
break;
case "shortcut":
var cmdKey = utils.getEntity(this.getDtds(), "openCmd.commandkey");
this._controller.keypress(null, cmdKey, {accelKey: true});
break;
default:
throw new Error(arguments.callee.name + ": Unkown event type - " + event.type);
}
// Wait until the location bar has been focused
this._controller.waitForEval("subject.getAttribute('focused') == 'true'",
TIMEOUT, 100, this.urlbar.getNode());
}
|
javascript
|
{
"resource": ""
}
|
q15490
|
locationBar_getNotificationElement
|
train
|
function locationBar_getNotificationElement(aType, aLookupString)
{
var lookup = '/id("' + aType + '")';
lookup = aLookupString ? lookup + aLookupString : lookup;
// Get the notification and fetch the child element if wanted
return this.getElement({type: "notification_element", subtype: lookup});
}
|
javascript
|
{
"resource": ""
}
|
q15491
|
locationBar_toggleAutocompletePopup
|
train
|
function locationBar_toggleAutocompletePopup() {
var dropdown = this.getElement({type: "historyDropMarker"});
var stateOpen = this.autoCompleteResults.isOpened;
this._controller.click(dropdown);
this._controller.waitForEval("subject.isOpened == " + stateOpen,
TIMEOUT, 100, this.autoCompleteResults);
}
|
javascript
|
{
"resource": ""
}
|
q15492
|
preferencesDialog_close
|
train
|
function preferencesDialog_close(saveChanges) {
saveChanges = (saveChanges == undefined) ? false : saveChanges;
if (mozmill.isWindows) {
var button = this.getElement({type: "button", subtype: (saveChanges ? "accept" : "cancel")});
this._controller.click(button);
} else {
this._controller.keypress(null, 'w', {accelKey: true});
}
}
|
javascript
|
{
"resource": ""
}
|
q15493
|
preferences_getPref
|
train
|
function preferences_getPref(prefName, defaultValue, defaultBranch,
interfaceType) {
try {
branch = defaultBranch ? this.defaultPrefBranch : this.prefBranch;
// If interfaceType has been set, handle it differently
if (interfaceType != undefined) {
return branch.getComplexValue(prefName, interfaceType);
}
switch (typeof defaultValue) {
case ('boolean'):
return branch.getBoolPref(prefName);
case ('string'):
return branch.getCharPref(prefName);
case ('number'):
return branch.getIntPref(prefName);
default:
return undefined;
}
} catch(e) {
return defaultValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q15494
|
preferences_setPref
|
train
|
function preferences_setPref(prefName, value, interfaceType) {
try {
switch (typeof value) {
case ('boolean'):
this.prefBranch.setBoolPref(prefName, value);
break;
case ('string'):
this.prefBranch.setCharPref(prefName, value);
break;
case ('number'):
this.prefBranch.setIntPref(prefName, value);
break;
default:
this.prefBranch.setComplexValue(prefName, interfaceType, value);
}
} catch(e) {
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q15495
|
openPreferencesDialog
|
train
|
function openPreferencesDialog(controller, callback, launcher) {
if(!controller)
throw new Error("No controller given for Preferences Dialog");
if(typeof callback != "function")
throw new Error("No callback given for Preferences Dialog");
if (mozmill.isWindows) {
// Preference dialog is modal on windows, set up our callback
var prefModal = new modalDialog.modalDialog(controller.window);
prefModal.start(callback);
}
// Launch the preference dialog
if (launcher) {
launcher();
} else {
mozmill.getPreferencesController();
}
if (mozmill.isWindows) {
prefModal.waitForDialog();
} else {
// Get the window type of the preferences window depending on the application
var prefWindowType = null;
switch (mozmill.Application) {
case "Thunderbird":
prefWindowType = "Mail:Preferences";
break;
default:
prefWindowType = "Browser:Preferences";
}
utils.handleWindow("type", prefWindowType, callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q15496
|
map
|
train
|
async function map(array, fn, self = undefined) {
const v = await Promise.resolve(array);
if (!Array.isArray(v)) {
throw TypeError('not an array');
}
const arr = /** @type {!Array} */(v);
const n = arr.length;
const values = new Array(n);
for (let i = 0; i < n; i++) {
if (i in arr) {
values[i] = await Promise.resolve(fn.call(self, arr[i], i, arr));
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q15497
|
filter
|
train
|
async function filter(array, fn, self = undefined) {
const v = await Promise.resolve(array);
if (!Array.isArray(v)) {
throw TypeError('not an array');
}
const arr = /** @type {!Array} */(v);
const n = arr.length;
const values = [];
let valuesLength = 0;
for (let i = 0; i < n; i++) {
if (i in arr) {
let value = arr[i];
let include = await fn.call(self, value, i, arr);
if (include) {
values[valuesLength++] = value;
}
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
q15498
|
xbDebugApplyFunction
|
train
|
function xbDebugApplyFunction(funcname, funcref, thisref, argumentsref)
{
var rv;
if (!funcref)
{
alert('xbDebugApplyFunction: funcref is null');
}
if (typeof(funcref.apply) != 'undefined')
return funcref.apply(thisref, argumentsref);
var applyexpr = 'thisref.xbDebug_orig_' + funcname + '(';
var i;
for (i = 0; i < argumentsref.length; i++)
{
applyexpr += 'argumentsref[' + i + '],';
}
if (argumentsref.length > 0)
{
applyexpr = applyexpr.substring(0, applyexpr.length - 1);
}
applyexpr += ')';
return eval(applyexpr);
}
|
javascript
|
{
"resource": ""
}
|
q15499
|
xpathCollectDescendants
|
train
|
function xpathCollectDescendants(nodelist, node, opt_tagName) {
if (opt_tagName && node.getElementsByTagName) {
copyArray(nodelist, node.getElementsByTagName(opt_tagName));
return;
}
for (var n = node.firstChild; n; n = n.nextSibling) {
nodelist.push(n);
xpathCollectDescendants(nodelist, n);
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.