Handler to allow process to be remotely debugged.
545532
def remote_debug(sig,frame):
    """"""
    def _raiseEx(ex):
        """Raise specified exception in the remote process"""
        _raiseEx.ex = ex
    _raiseEx.ex = None
    
    try:
        # Provide some useful functions.
        locs = {'_raiseEx' : _raiseEx}
        locs.update(frame.f_locals)  # Unless shadowed.
        globs = frame.f_globals
        
        pid = os.getpid()  # Use pipe name based on pid
        pipe = NamedPipe(pipename(pid))
    
        old_stdout, old_stderr = sys.stdout, sys.stderr
        txt = ''
        pipe.put("Interrupting process at following point:\n" + 
               ''.join(traceback.format_stack(frame)) + ">>> ")
        
        try:
            while pipe.is_open() and _raiseEx.ex is None:
                line = pipe.get()
                if line is None: continue # EOF
                txt += line
                try:
                    code = codeop.compile_command(txt)
                    if code:
                        sys.stdout = six.StringIO()
                        sys.stderr = sys.stdout
                        six.exec_(code, globs, locs)
                        txt = ''
                        pipe.put(sys.stdout.getvalue() + '>>> ')
                    else:
                        pipe.put('... ')
                except:
                    txt='' # May be syntax err.
                    sys.stdout = six.StringIO()
                    sys.stderr = sys.stdout
                    traceback.print_exc()
                    pipe.put(sys.stdout.getvalue() + '>>> ')
        finally:
            sys.stdout = old_stdout # Restore redirected output.
            sys.stderr = old_stderr
            pipe.close()

    except Exception:  # Don't allow debug exceptions to propogate to real program.
        traceback.print_exc()
        
    if _raiseEx.ex is not None: raise _raiseEx.ex
612051
def __cleanup_breakpoint(self, event, bp):
        ""
        try:
            process = event.get_process()
            thread  = event.get_thread()
            bp.disable(process, thread) # clear the debug regs / trap flag
        except Exception:
            pass
        bp.set_condition(True)  # break possible circular reference
        bp.set_action(None)
68500
def debug(self, *debugReqs):
        """"""
        return self._client.send(debug=sc2api_pb2.RequestDebug(debug=debugReqs))
274452
def runserver(ctx, conf, port, foreground):
    """"""
    config = read_config(conf)

    debug = config['conf'].get('debug', False)
    click.echo('Debug mode {0}.'.format('on' if debug else 'off'))

    port = port or config['conf']['server']['port']

    app_settings = {
        'debug': debug,
        'auto_reload': config['conf']['server'].get('auto_reload', False),
    }
    handlers_settings = __create_handler_settings(config)

    if foreground:
        click.echo('Requested mode: foreground')
        start_app(port, app_settings, handlers_settings)
    else:
        click.echo('Requested mode: background')
        # subprocess.call([sys.executable, 'yourscript.py'], env=os.environ.copy())
        raise NotImplementedError
1108763
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):
    
    atexit.register(close_port, port)
    try:
        log("Starting a remote python debugger session on %s:%s" % (addr,
                                                                    port))
        open_port(port)
        debugger = Rpdb(addr=addr, port=port)
        debugger.set_trace(sys._getframe().f_back)
    except Exception:
        _error("Cannot start a remote debug session on %s:%s" % (addr,
                                                                 port))
661028
def DEBUG(msg, *args, **kwargs):
    """"""
    logger = getLogger("DEBUG")
    if len(logger.handlers) == 0:
        logger.addHandler(StreamHandler())
    logger.propagate = False
    logger.setLevel(logging.DEBUG)
    logger.DEV(msg, *args, **kwargs)
91632
def debug(request, message, extra_tags='', fail_silently=False, async=False):
    """"""
    if ASYNC and async:
        messages.debug(_get_user(request), message)
    else:
        add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
                    fail_silently=fail_silently)
482527
function(brk) {
		hooks.enableHooks(
			brk,
			function(module, port) {
				grunt.log.ok('Debugging forked process %s on port %d', module, port);
			}
		);
	}
908960
async def debug(self, conn_id, name, cmd_args):
        

        progress_callback = functools.partial(_on_progress, self, 'debug', conn_id)

        resp = await self._execute(self._adapter.debug_sync, conn_id, name, cmd_args, progress_callback)
        _raise_error(conn_id, 'send_rpc', resp)

        return resp.get('return_value')
1155507
def nl_valid_handler_debug(msg, arg):
    """"""
    ofd = arg or _LOGGER.debug
    ofd('-- Debug: Unhandled Valid message: ' + print_header_content(nlmsg_hdr(msg)))
    return NL_OK
183998
def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)
151459
def hook(self, debug, pid):
        
        label = "%s!%s" % (self.__modName, self.__procName)
        try:
            hook = self.__hook[pid]
        except KeyError:
            try:
                aProcess = debug.system.get_process(pid)
            except KeyError:
                aProcess = Process(pid)
            hook = Hook(self.__preCB, self.__postCB,
                        self.__paramCount, self.__signature,
                        aProcess.get_arch() )
            self.__hook[pid] = hook
        hook.hook(debug, pid, label)
45347
def cli_main(pid, include_greenlet, debugger, verbose):
    '''
    '''
    try:
        print_stack(pid, include_greenlet, debugger, verbose)
    except DebuggerNotFound as e:
        click.echo('DebuggerNotFound: %s' % e.args[0], err=True)
        click.get_current_context().exit(1)
1356321
def remote_run(cmd, instance_name, detach=False, retries=1):
  """"""
  if detach:
    cmd = SCREEN.format(command=cmd)
  args = SSH.format(instance_name=instance_name).split()
  args.append(cmd)
  for i in range(retries + 1):
    try:
      if i > 0:
        tf.logging.info("Retry %d for %s", i, args)
      return sp.check_call(args)
    except sp.CalledProcessError as e:
      if i == retries:
        raise e
339127
function debug(cmd) {
        // start node in debug mode
        childProcess = childProcess || require("child_process");

        var PATH_CWD = process.cwd();

        // splice out allume command
        process.argv.splice(0, 1);

        // find debug argument
        var debugIdx = -1;
        for (var a in process.argv) {
            if (process.argv[a] == "--debug") {
                debugIdx = a;
            }
            process.argv[a] = process.argv[a].replace(/"/g, "\"");
        }
        if (debugIdx >= 0) {
            process.argv.splice(debugIdx, 1);
        }
        if (!cmd["--debug"].port) {
            process.argv.splice(0, 0, "--debug-brk");
            //process.argv.splice(0, 0, "--inspect");
        }
        else {
            if (debugIdx >= 0) {
                process.argv.splice(debugIdx, 1);
            }
            process.argv.splice(0, 0, "--debug-brk=" + cmd["--debug"].port);
            //process.argv.splice(0, 0, "--inspect=" + cmd["--debug"].port);
        }
    

        var ls = childProcess.spawn("node", process.argv, {"cwd": PATH_CWD});

        ls.stdout.on("data", function(data) {
            console.log(data.toString().trim());
        });

        ls.stderr.on("data", function(data) {
            console.error(data.toString().trim());
        });

        return;
    }
857207
def enable_console_debug_logging():  # pragma no cover (Function useful only outside test environment)
    

    logger = logging.getLogger("github")
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler())
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv