Wraps the main routine. Is callable from other code without fear of it
calling System.exit(..).
188395
public static int mainWithReturnCode(String args[]) {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
        // Initialize parameter defaults
        String serverList = "localhost";
        int port = 21212;
        String user = "";
        String password = "";
        String credentials = "";
        String kerberos = "";
        FileReader fr = null;
        List<String> queries = null;
        String ddlFileText = "";
        String sslConfigFile = null;
        boolean enableSSL = false;

        // Parse out parameters
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.startsWith("--servers=")) {
                serverList = extractArgInput(arg);
                if (serverList == null) return -1;
            }
            else if (arg.startsWith("--port=")) {
                String portStr = extractArgInput(arg);
                if (portStr == null) return -1;
                port = Integer.valueOf(portStr);
            }
            else if (arg.startsWith("--user=")) {
                user = extractArgInput(arg);
                if (user == null) return -1;
            }
            else if (arg.startsWith("--password=")) {
                password = extractArgInput(arg);
                if (password == null) return -1;
            }
            else if (arg.startsWith("--credentials")) {
                credentials = extractArgInput(arg);
                if (credentials == null) return -1;
            }
            else if (arg.startsWith("--kerberos=")) {
                kerberos = extractArgInput(arg);
                if (kerberos == null) return -1;
            }
            else if (arg.startsWith("--kerberos")) {
                kerberos = "VoltDBClient";
            }
            else if (arg.startsWith("--query=")) {
                List<String> argQueries = SQLLexer.splitStatements(arg.substring(8)).getCompletelyParsedStmts();
                if (!argQueries.isEmpty()) {
                    if (queries == null) {
                        queries = argQueries;
                    }
                    else {
                        queries.addAll(argQueries);
                    }
                }
            }
            else if (arg.startsWith("--output-format=")) {
                String formatName = extractArgInput(arg);
                if (formatName == null) return -1;
                formatName = formatName.toLowerCase();
                if (formatName.equals("fixed")) {
                    m_outputFormatter = new SQLCommandOutputFormatterDefault();
                }
                else if (formatName.equals("csv")) {
                    m_outputFormatter = new SQLCommandOutputFormatterCSV();
                }
                else if (formatName.equals("tab")) {
                    m_outputFormatter = new SQLCommandOutputFormatterTabDelimited();
                }
                else {
                    printUsage("Invalid value for --output-format");
                    return -1;
                }
            }
            else if (arg.startsWith("--stop-on-error=")) {
                String optionName = extractArgInput(arg);
                if (optionName == null) return -1;
                optionName = optionName.toLowerCase();
                if (optionName.equals("true")) {
                    m_stopOnError = true;
                }
                else if (optionName.equals("false")) {
                    m_stopOnError = false;
                }
                else {
                    printUsage("Invalid value for --stop-on-error");
                    return -1;
                }
            }
            else if (arg.startsWith("--ddl-file=")) {
                String ddlFilePath = extractArgInput(arg);
                if (ddlFilePath == null) return -1;
                try {
                    File ddlJavaFile = new File(ddlFilePath);
                    Scanner scanner = new Scanner(ddlJavaFile);
                    ddlFileText = scanner.useDelimiter("\\Z").next();
                    scanner.close();
                } catch (FileNotFoundException e) {
                    printUsage("DDL file not found at path:" + ddlFilePath);
                    return -1;
                }
            }
            else if (arg.startsWith("--query-timeout=")) {
                m_hasBatchTimeout = true;
                String batchTimeoutStr = extractArgInput(arg);
                if (batchTimeoutStr == null) return -1;
                m_batchTimeout = Integer.valueOf(batchTimeoutStr);
            }

            // equals check starting here
            else if (arg.equals("--output-skip-metadata")) {
                m_outputShowMetadata = false;
            }
            else if (arg.startsWith("--ssl=")) {
                enableSSL = true;
                sslConfigFile = extractArgInput(arg);
                if (sslConfigFile == null) return -1;
            }
            else if (arg.startsWith("--ssl")) {
                enableSSL = true;
                sslConfigFile = null;
            }
            else if (arg.equals("--debug")) {
                m_debug = true;
            }
            else if (arg.equals("--help")) {
                printHelp(System.out); // Print readme to the screen
                System.out.println("\n\n");
                printUsage();
                return -1;
            }
            else if (arg.equals("--no-version-check")) {
                m_versionCheck = false; // Disable new version phone home check
            }
            else if ((arg.equals("--usage")) || (arg.equals("-?"))) {
                printUsage();
                return -1;
            }
            else {
                printUsage("Invalid Parameter: " + arg);
                return -1;
            }
        }

        // Split server list
        String[] servers = serverList.split(",");

        // Phone home to see if there is a newer version of VoltDB
        if (m_versionCheck) {
            openURLAsync();
        }

        // read username and password from txt file
        if (credentials != null && !credentials.trim().isEmpty()) {
            Properties props = MiscUtils.readPropertiesFromCredentials(credentials);
            user = props.getProperty("username");
            password = props.getProperty("password");
        }

        try
        {
            // If we need to prompt the user for a password, do so.
            password = CLIConfig.readPasswordIfNeeded(user, password, "Enter password: ");
        }
        catch (IOException ex)
        {
            printUsage("Unable to read password: " + ex);
        }

        // Create connection
        ClientConfig config = new ClientConfig(user, password, null);
        if (enableSSL) {
            if (sslConfigFile != null && !sslConfigFile.trim().isEmpty()) {
                config.setTrustStoreConfigFromPropertyFile(sslConfigFile);
            } else {
                config.setTrustStoreConfigFromDefault();
            }
            config.enableSSL();
        }
        config.setProcedureCallTimeout(0);  // Set procedure all to infinite timeout, see ENG-2670
        try {
            // if specified enable kerberos
            if (!kerberos.isEmpty()) {
                config.enableKerberosAuthentication(kerberos);
            }
            m_client = getClient(config, servers, port);
        } catch (Exception exc) {
            System.err.println(exc.getMessage());
            return -1;
        }

        try {
            if (! ddlFileText.equals("")) {
                // fast DDL Loader mode
                // System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile);
                m_client.callProcedure("@AdHoc", ddlFileText);
                return m_exitCode;
            }

            // Load system procedures
            loadSystemProcedures();

            // Load user stored procs
            loadStoredProcedures(Procedures, Classlist);

            // Removed code to prevent Ctrl-C from exiting. The original code is visible
            // in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20.

            m_interactive = true;
            if (queries != null && !queries.isEmpty()) {
                // If queries are provided via command line options run them in
                // non-interactive mode.
                //TODO: Someday we should honor batching.
                m_interactive = false;
                for (String query : queries) {
                    executeStatement(query, null, 0);
                }
            }
            // This test for an interactive environment is mostly
            // reliable. See stackoverflow.com/questions/1403772.
            // It accurately detects when data is piped into the program
            // but it fails to distinguish the case when data is ONLY piped
            // OUT of the command -- that's a possible but very strange way
            // to run an interactive session, so it's OK that we don't support
            // it. Instead, in that edge case, we fall back to non-interactive
            // mode but IN THAT MODE, we wait on and process user input as if
            // from a slow pipe. Strange, but acceptable, and preferable to the
            // check used here in the past (System.in.available() > 0)
            // which would fail in the opposite direction, when a 0-length
            // file was piped in, showing an interactive greeting and prompt
            // before quitting.
            if (System.console() == null && m_interactive) {
                m_interactive = false;
                executeNoninteractive();
            }
            if (m_interactive) {
                // Print out welcome message
                System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port);
                interactWithTheUser();
            }
        }
        catch (SQLCmdEarlyExitException e) {
            return m_exitCode;
        }
        catch (Exception x) {
            try { stopOrContinue(x); } catch (SQLCmdEarlyExitException e) { return m_exitCode; }
        }
        finally {
            try { m_client.close(); } catch (Exception x) { }
        }
        // Processing may have been continued after one or more errors.
        // Reflect them in the exit code.
        // This might be a little unconventional for an interactive session,
        // but it's also likely to be ignored in that case, so "no great harm done".
        //* enable to debug */ System.err.println("Exiting with code " + m_exitCode);
        return m_exitCode;
    }
150348
def main(argv=None):
    
    # Exit code
    exit_code = 0

    # First, we change main() to take an optional 'argv'
    # argument, which allows us to call it from the interactive
    # Python prompt
    if argv is None:
        argv = sys.argv

    try:
        # Bootstrap
        init(argv)

        # Perform the actual backup job
        make_backup_files()

    except Exception as e:
        # ... and if everything else fails
        _handle_except(e)
        exit_code = 1
    finally:
        # All cleanup actions are taken from here
        shutdown()
        return exit_code
482345
def _exit_handling(self):
        

        def close_asyncio_loop():
            loop = None
            try:
                loop = asyncio.get_event_loop()
            except AttributeError:
                pass
            if loop is not None:
                loop.close()

        atexit.register(close_asyncio_loop)
824802
def system_exit_exception_handler(*args):
    

    reporter = Reporter()
    reporter.Footer_label.setText(
        "The severity of this exception is critical, <b>{0}</b> cannot continue and will now close!".format(
            Constants.application_name))

    base_exception_handler(*args)

    foundations.core.exit(1)

    return True
1110222
def do_exit(self, arg_list: List[str]) -> bool:
        
        # If an argument was provided
        if arg_list:
            try:
                self.exit_code = int(arg_list[0])
            except ValueError:
                self.perror("{} isn't a valid integer exit code".format(arg_list[0]))
                self.exit_code = -1

        self._should_quit = True
        return self._STOP_AND_EXIT
932785
def run(self):
        
        while self.status != 'EXIT':
            print(self.process_input(self.get_input()))
        
        print('Bye')
911959
def run(self, accept_unrecognized_args=False):
        

        self.__parse_args(accept_unrecognized_args)
        self.__parse_config()
        self.__process_username_password()
        self.__finish_initializing()

        exit_status = 0

        try:
            yield self
        except ExitedCleanly:
            pass
        except (Exception, KeyboardInterrupt) as e:
            # Run any method a library or caller might have registered.
            for base in type(e).mro():
                if base in self.exceptions:
                    self.exceptions[base](e)
                    break
            else:
                self.log.exception(e)

            exit_status = os.EX_SOFTWARE
        finally:
            logging.shutdown()

        sys.exit(exit_status)
1271954
def main(args):
    
    start = time.time()
    output = get(args)
    _safe_exit(start, output)
57819
def execute(self):
        
        # Ensure that we have commands registered
        if not self.commands or self._parser is None:
            raise NotImplementedError(
                "No commands registered with this program!"
            )

        # Handle input from the command line
        args = self.parser.parse_args()                # Parse the arguments

        try:

            handle_default_args(args)                  # Handle the default args

            if not hasattr(args, 'func'):              # Handle no subcommands
                self.parser.print_help()
                self.exit(0)

            msg = args.func(args)                      # Call the default function
            msg = "{}\n".format(msg) if msg else ''    # Format the message
            self.exit(0, msg)                          # Exit cleanly with message

        except Exception as e:
            if hasattr(args, 'traceback') and args.traceback:
                traceback.print_exc()

            msg = color.format(str(e), color.RED)
            self.exit(1, msg)
976349
def __exitfunction(self):
        '''
        
        '''
        if self._hook.exit_code is None and self._hook.exception is None:
            print("Check did not exit! You should call an exit code method.")
            sys.stdout.flush()
            os._exit(1)
        elif self._hook.exception:
            print("Check failed to run: %s, %s" %
                  (sys.last_type, traceback.format_tb(sys.last_traceback)))
            sys.stdout.flush()
            os._exit(2)
32115
function handleExit (canCancel, signal, code) {
	var i = 0,
		sub;

	while ((sub = subs[i++])) {
		if (sub[0].call(sub[1], canCancel, signal, code) === false && canCancel) {
			return;
		}
	}

	if (canCancel) {
		process.exit(code);
	}
}
404824
function () {
  var args = Array.prototype.slice.call(arguments);
  console.error();
  console.error.apply(console, [" "].concat(args));
  console.error();
  process.exit(1); // eslint-disable-line no-process-exit
}
223372
def main():
    """"""

    cleanup_and_exit = sys.exit # Function to do cleanup and exit before the import.
    exit_code = 0

    # Imports are done here inside the try block so some ugly (and useless)
    # traceback info is avoided on user's ^C (KeyboardInterrupt, EOFError on Windows).
    try:
        from . import external_program_calls as ex # Creates tmp dir as side effect.
        cleanup_and_exit = ex.cleanup_and_exit # Switch to the real one, deletes temp dir.

        from . import main_pdfCropMargins # Imports external_program_calls, don't do first.
        main_pdfCropMargins.main_crop() # Run the actual program.

    except (KeyboardInterrupt, EOFError): # Windows raises EOFError on ^C.
        print("\nGot a KeyboardInterrupt, cleaning up and exiting...\n",
              file=sys.stderr)

    except SystemExit:
        exit_code = sys.exc_info()[1]
        print()

    except:
        # Echo back the unexpected error so the user can see it.
        print("\nCaught an unexpected exception in the pdfCropMargins program.",
                                                               file=sys.stderr)
        print("Unexpected error: ", sys.exc_info()[0], file=sys.stderr)
        print("Error message   : ", sys.exc_info()[1], file=sys.stderr)
        print()
        exit_code = 1
        import traceback
        max_traceback_length = 30
        traceback.print_tb(sys.exc_info()[2], limit=max_traceback_length)
        # raise # Re-raise the error.

    finally:
        # Some people like to hit multiple ^C chars, which kills cleanup.
        # Call cleanup again each time.
        for i in range(30): # Give up after 30 tries.
            try:
                cleanup_and_exit(exit_code)
            except (KeyboardInterrupt, EOFError):
                continue
613787
def handle_command_exit_code(self, code):
        
        ca = self.call_args
        exc_class = get_exc_exit_code_would_raise(code, ca["ok_code"],
                ca["piped"])
        if exc_class:
            exc = exc_class(self.ran, self.process.stdout, self.process.stderr,
                    ca["truncate_exc"])
            raise exc
1048891
def exit(self, code=0, message=None):
        

        ## If we have a parser, use it to exit
        if self._parser:
            if code > 0:
                self.parser.error(message)
            else:
                self.parser.exit(code, message)

        ## Else we are exiting before parser creation
        else:
            if message is not None:
                if code > 0:
                    sys.stderr.write(message)
                else:
                    sys.stdout.write(message)
            sys.exit(code)

        ## If we're here we didn't exit for some reason?
        raise Exception("Unable to exit the %s" % self.__class__.__name__)
1131914
def console_main():
    """"""
    cmd = main(check=False)
    if cmd is not None:
        sys.exit(cmd.returncode)
1063129
void wrapAndRun (Runnable runnable) { // PM90834 added method
      if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINEST)) { 
          logger.entering(CLASS_NAME,"wrapAndRun",runnable);
      }

      try {
          this.popContextData();

          if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINEST)) {
              logger.logp(Level.FINEST, CLASS_NAME, "wrapAndRun", "run with context class loader: " + Thread.currentThread().getContextClassLoader());
          }

          runnable.run();
      } finally {
          try {
              this.resetContextData();
          }finally {
              if (runnable instanceof CompleteRunnable) {
                  asyncContext.notifyITransferContextCompleteState();
              }

              if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINEST)) { 
                  logger.exiting(CLASS_NAME,"wrapAndRun",runnable);
              }
          }
      }
  }