try loginWeb, catch the "not supported" message and fall back to couch
192209
function login (opener, prompter, opts) {
  validate('FFO', arguments)
  opts = ProfileConfig(opts)
  return loginWeb(opener, opts).catch(er => {
    if (er instanceof WebLoginNotSupported) {
      process.emit('log', 'verbose', 'web login not supported, trying couch')
      return prompter(opts.creds)
        .then(data => loginCouch(data.username, data.password, opts))
    } else {
      throw er
    }
  })
}
1284534
function MIDINotSupportedError(message) {
    Error.call(this);
    Error.captureStackTrace(this, this.constructor);

    this.name = this.constructor.name;
    this.message = message;
}
930446
function handleError(message, url, line) {
        // Ignore this error if it does not look like the rather vague cross origin error in Chrome
        // Chrome will print it to the console anyway
        if (!testCrossOriginError(message, url, line)) {
            if (previousErrorHandler) {
                return previousErrorHandler(message, url, line);
            }
            return;
        }

        // Show an error message
        window.alert("Oops! This application doesn't run in browsers yet.\n\nIt is built in HTML, but right now it runs as a desktop app so you can use it to edit local files. Please use the application shell in the following repo to run this application:\n\ngithub.com/adobe/brackets-shell");

        // Restore the original handler for later errors
        window.onerror = previousErrorHandler;
    }
234207
@SuppressWarnings("ACL.impersonate")
    private void loginAndTakeBack(StaplerRequest req, StaplerResponse rsp, User u) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session != null) {
            // avoid session fixation
            session.invalidate();
        }
        req.getSession(true);
        
        // ... and let him login
        Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1"));
        a = this.getSecurityComponents().manager.authenticate(a);
        SecurityContextHolder.getContext().setAuthentication(a);

        SecurityListener.fireLoggedIn(u.getId());

        // then back to top
        req.getView(this,"success.jelly").forward(req,rsp);
    }
944648
function _failHandler(e){
        $spin.hide()

        if(e.status === 400) alert(e.responseText || 'Bad request.')
        if(e.status === 401) alert(e.responseText || 'Unauthorized request.')
        if(e.status === 402) alert(e.responseText || 'Forbidden request.')
        if(e.status === 403) alert(e.responseText || 'Forbidden request.')
        if(e.status === 404) alert(e.responseText || 'Images were not found.')
        if(e.status === 405) alert(e.responseText || 'That method is not allowed.')
        if(e.status === 408) alert(e.responseText || 'The request timed out. Try again.')
        if(e.status === 500) alert(e.responseText || 'Something went really wrong.')
        
        postData = postUrl = ''
        
        cb & cb()

      }
471765
def _wait_until_connectable(self, timeout=30):
        """"""
        count = 0
        while not utils.is_connectable(self.profile.port):
            if self.process.poll() is not None:
                # Browser has exited
                raise WebDriverException(
                    "The browser appears to have exited "
                    "before we could connect. If you specified a log_file in "
                    "the FirefoxBinary constructor, check it for details.")
            if count >= timeout:
                self.kill()
                raise WebDriverException(
                    "Can't load the profile. Possible firefox version mismatch. "
                    "You must use GeckoDriver instead for Firefox 48+. Profile "
                    "Dir: %s If you specified a log_file in the "
                    "FirefoxBinary constructor, check it for details."
                    % (self.profile.path))
            count += 1
            time.sleep(1)
        return True
275211
function checkBasicSupport(client, metadata, properties) {
  try {
    const supported = client.issuer.token_endpoint_auth_methods_supported;
    if (!supported.includes(properties.token_endpoint_auth_method)) {
      if (supported.includes('client_secret_post')) {
        properties.token_endpoint_auth_method = 'client_secret_post';
      }
    }
  } catch (err) {}
}
290701
def _connection_failed(self, link_uri, msg):
        """"""
        print('Connection to %s failed: %s' % (link_uri, msg))
        self.is_connected = False
665087
private static void tryForceNotJava1()
	{
		String version = System.getProperty("java.version");

		// N.B. Log4j has issues with JVM versions written like "9" and "10"
		if (version != null && !version.startsWith("1."))
		{
			try
			{
				Class<Loader> loader = Loader.class;

				for (Field field : loader.getDeclaredFields())
				{
					if (field.getName().equals("java1"))
					{
						field.setAccessible(true);
						field.setBoolean(null, false);
					}
				}
			}
			catch (Throwable t)
			{
				// ignore, we must have been denied access. MDC may not work correctly due to log4j 1.2 limitations
			}
		}
	}
63889
async function connectUser(form) {
  if (!form.login.value || !form.password.value) {
    document.getElementById('login-errors').innerHTML += `<p>Login and password are required</p>`;
    return;
  }

  await client.setCredentials({ login: form.login.value, password: form.password.value });
  client
    .connect()
    .then(() => {
      displayMessage('Login success', 'Welcome to wonderful service', 'is-success');
      goTo('home');
    })
    .catch((e) => {
      displayMessage(
        'Login failed',
        'Your account is not validated, have you clicked on the link in the email ?',
        'is-warning'
      );
    });
}
1022736
def login_request(self, login_urls, is_retry=False):
        """"""
        try:
            login_url = login_urls.pop(0)
        except IndexError:
            _LOGGER.error("Could not login to blink servers.")
            return False

        _LOGGER.info("Attempting login with %s", login_url)

        response = api.request_login(self,
                                     login_url,
                                     self._username,
                                     self._password,
                                     is_retry=is_retry)
        try:
            if response.status_code != 200:
                response = self.login_request(login_urls)
            response = response.json()
            (self.region_id, self.region), = response['region'].items()

        except AttributeError:
            _LOGGER.error("Login API endpoint failed with response %s",
                          response,
                          exc_info=True)
            return False

        except KeyError:
            _LOGGER.warning("Could not extract region info.")
            self.region_id = 'piri'
            self.region = 'UNKNOWN'

        self._login_url = login_url
        return response
789920
private void checkIfUseDb(final DeviceProxy deviceProxy, final String origin) throws DevFailed {
        if (!deviceProxy.url.use_db) {
            Except.throw_non_db_exception("Api_NonDatabaseDevice", "Device " + name(deviceProxy)
                + " do not use database", "DeviceProxy(" + name(deviceProxy) + ")." + origin);
        }
    }
757936
def a_unable_to_connect(ctx):
    
    message = "{}{}".format(ctx.ctrl.before, ctx.ctrl.after)
    ctx.msg = message.strip().splitlines()[-1]
    ctx.device.last_error_msg = ctx.msg
    # ctx.msg = "{}{}".format(ctx.ctrl.before, ctx.ctrl.after)
    return False
380390
def http_exception(channel, title):
    

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Too much help",
        "{} is too helpful! Try trimming some of the help messages.".format(title),
        modulename=modulename
    )

    return gui
507164
public void setHTTPPort() throws InstallationFailedException {
        // Note this very significant assumption: this xpath will select exactly one connector
        Element httpConnector =
                (Element) getDocument()
                        .selectSingleNode(HTTP_CONNECTOR_XPATH);

        if (httpConnector == null) {
            throw new InstallationFailedException("Unable to set server.xml HTTP Port. XPath for Connector element failed.");
        }

        httpConnector.addAttribute("port", options
                .getValue(InstallOptions.TOMCAT_HTTP_PORT));
        httpConnector.addAttribute("enableLookups", "true"); // supports client dns/fqdn in xacml authz policies
        httpConnector.addAttribute("acceptCount", "100");
        httpConnector.addAttribute("maxThreads", "150");
        httpConnector.addAttribute("minSpareThreads", "25");
        httpConnector.addAttribute("maxSpareThreads", "75");
    }
1195732
def process_exception(self, request, exception):
        
        if isinstance(exception, (exceptions.NotAuthorized,
                                  exceptions.NotAuthenticated)):
            auth_url = settings.LOGIN_URL
            next_url = iri_to_uri(request.get_full_path())
            if next_url != auth_url:
                field_name = REDIRECT_FIELD_NAME
            else:
                field_name = None
            login_url = request.build_absolute_uri(auth_url)
            response = redirect_to_login(next_url, login_url=login_url,
                                         redirect_field_name=field_name)
            if isinstance(exception, exceptions.NotAuthorized):
                response.delete_cookie('messages')
                return shortcuts.render(request, 'not_authorized.html',
                                        status=403)

            if request.is_ajax():
                response_401 = http.HttpResponse(status=401)
                response_401['X-Horizon-Location'] = response['location']
                return response_401

            return response

        # If an internal "NotFound" error gets this far, return a real 404.
        if isinstance(exception, exceptions.NotFound):
            raise http.Http404(exception)

        if isinstance(exception, exceptions.Http302):
            # TODO(gabriel): Find a way to display an appropriate message to
            # the user *on* the login form...
            return shortcuts.redirect(exception.location)
300272
def get(self, url, instance, service_check_tags, run_check=False):
        ""
        self.log.debug('Fetching CouchDB stats at url: %s' % url)

        auth = None
        if 'user' in instance and 'password' in instance:
            auth = (instance['user'], instance['password'])

        # Override Accept request header so that failures are not redirected to the Futon web-ui
        request_headers = headers(self.agentConfig)
        request_headers['Accept'] = 'text/json'

        try:
            r = requests.get(
                url, auth=auth, headers=request_headers, timeout=int(instance.get('timeout', self.TIMEOUT))
            )
            r.raise_for_status()
            if run_check:
                self.service_check(
                    self.SERVICE_CHECK_NAME,
                    AgentCheck.OK,
                    tags=service_check_tags,
                    message='Connection to %s was successful' % url,
                )
        except requests.exceptions.Timeout as e:
            self.service_check(
                self.SERVICE_CHECK_NAME,
                AgentCheck.CRITICAL,
                tags=service_check_tags,
                message="Request timeout: {0}, {1}".format(url, e),
            )
            raise
        except requests.exceptions.HTTPError as e:
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e))
            raise
        except Exception as e:
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e))
            raise
        return r.json()