Return scripting action when a response begins.
175845
def consult_pre_response_hook(self, item_session: ItemSession) -> Actions:
        ''''''
        try:
            return self.hook_dispatcher.call(
                PluginFunctions.handle_pre_response,
                item_session
            )
        except HookDisconnected:
            return Actions.NORMAL
1300584
def action(self, *action_names):
        """"""
        def action_wrapper(decorated):

            @functools.wraps(decorated)
            def wrapper(argv):
                kwargs = dict(arg.split('=') for arg in argv)
                try:
                    return decorated(**kwargs)
                except TypeError as e:
                    if decorated.__doc__:
                        e.args += (decorated.__doc__,)
                    raise

            self.register_action(decorated.__name__, wrapper)
            if '_' in decorated.__name__:
                self.register_action(
                    decorated.__name__.replace('_', '-'), wrapper)

            return wrapper

        return action_wrapper
646710
def respond_to_action_responses
      if !respond_to_performed? && action_responses.any?
        respond_to do |responder|
          action_responses.each {|response| instance_exec(responder, &response) }
        end
      end
    end
122790
def action(func):
    """"""
    @wraps(func)
    def call_action(*args, **kwargs):
        """Wrap the function with logger debug."""
        try:
            ctx = kwargs['ctx']
        except KeyError:
            ctx = None

        if ctx is None:
            try:
                ctx = args[-1]
            except IndexError:
                ctx = None
        if ctx:
            if func.__doc__ is None:
                ctx.device.chain.connection.log("A={}".format(func.__name__))
            else:
                ctx.device.chain.connection.log("A={}".format(func.__doc__.split('\n', 1)[0]))
        return func(*args, **kwargs)
    return call_action
95708
def on_log(request, page_name):
    """"""
    page = Page.query.filter_by(name=page_name).first()
    if page is None:
        return page_missing(request, page_name, False)
    return Response(generate_template("action_log.html", page=page))
255776
def process_action(ctx, param, value):
    """"""
    actions = current_app.extensions['invenio-access'].actions
    if value not in actions:
        raise click.BadParameter('Action "%s" is not registered.', value)
    return actions[value]
1257845
def call(self, method, args={}, retry=False, retry_policy=None,
             ticket=None, **props):
        """"""
        ticket = ticket or uuid()
        reply_q = self.get_reply_queue(ticket)
        self.cast(method, args, declare=[reply_q], reply_to=ticket, **props)
        return self.AsyncResult(ticket, self)
307745
def respond(self, obj):
        """"""

        # Get the callback argument if JSONP is allowed
        callback = self.get_argument("callback", None) if oz.settings["allow_jsonp"] else None

        # We're pretty strict with what callback names are allowed, just in case
        if callback and not CALLBACK_VALIDATOR.match(callback):
            raise oz.json_api.ApiError("Invalid callback identifier - only functions with ASCII characters are allowed")

        # Provide the response in a different manner depending on whether a
        # JSONP callback is specified
        json = escape.json_encode(obj)

        if callback:
            self.set_header("Content-Type", "application/javascript; charset=UTF-8")
            self.finish("%s(%s)" % (callback, json))
        else:
            self.set_header("Content-Type", "application/json; charset=UTF-8")
            self.finish(json)
859330
def begin_script(self):
        """"""

        if self.remote_bridge.status in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.VALIDATED, BRIDGE_STATUS.EXECUTING):
            return [1]  #FIXME: Return correct error here

        self.remote_bridge.status = BRIDGE_STATUS.WAITING
        self.remote_bridge.error = 0
        self.remote_bridge.script_error = None
        self.remote_bridge.parsed_script = None

        self._device.script = bytearray()

        return [0]
776797
def main():
    """"""

    # Hack to make user code available for import
    sys.path.append(".")

    # Run the specified action
    oz.initialize()
    retr = optfn.run(list(oz._actions.values()))

    if retr == optfn.ERROR_RETURN_CODE:
        sys.exit(-1)
    elif retr == None:
        sys.exit(0)
    elif isinstance(retr, int):
        sys.exit(retr)
    else:
        raise Exception("Unexpected return value from action: %s" % retr)
934523
async def handler(event):
    """"""
    q1 = event.pattern_match.group(1)
    q2 = urllib.parse.quote(q1)
    await asyncio.wait([
        event.delete(),
        event.respond(DOCS.format(q1, q2), reply_to=event.reply_to_msg_id)
    ])
153622
def execute(self, *args, **kwargs):
        """"""
        timeout = kwargs.pop("timeout", -1)
        run_async = kwargs.pop("run_async", False)
        self._is_running = True
        result = None
        if self._action_lock.acquire(False):
            self._state = ACTION_PENDING
            self._action_event = threading.Event()
            self.spine.send_command("kervi_action_" + self._action_id, *args, **kwargs)

            if not run_async:
                if self._action_event.wait(timeout):
                    self._state = ACTION_FAILED
                    raise TimeoutError("Timeout in call to action: " + self._action_id)
                self._action_event = None
                result = self._last_result
            else:
                self._action_lock.release()

        else:
            if not self._action_lock.acquire(True, timeout):
                return None
            self._action_lock.release()
            return result
555204
def _script_reload(script, input, output):
    """"""
    input = [Path(entry).expand().abspath() for entry in input]
    output = Path(output).expand().abspath()
    cmd = 'python3 {0} {1} {2}'.format(script, ' '.join(input), output)
    event_handler = RunScriptChangeHandler(cmd)
    event_handler.run()  # run always once
    observer = Observer()
    path = script.dirname().expand().abspath()
    click.secho('watch: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    for entry in input:
        entry = entry.dirname().expand().abspath()
        click.secho('watch: {0}'.format(entry), fg='blue')
        observer.schedule(event_handler, entry, recursive=True)
    path = Path(__file__).parent / 'qface'
    click.secho('watch: {0}'.format(path), fg='blue')
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
578497
async def handler(event):
    """"""
    await asyncio.wait([
        event.delete(),
        event.respond(
            LEARN_PYTHON, reply_to=event.reply_to_msg_id, link_preview=False)
    ])
793027
function onData(rawData){

        // strip delimiter sequence from array
        const input = rawData.toString(_encoding);

        // response data object - default no response data
        const data = {
            echo: input,
            response: null
        };

        // response found ? split echo and response
        const splitIndex = input.indexOf('\n');
        if (splitIndex > 0){
            data.echo = input.substr(0, splitIndex).trim();
            data.response = input.substr(splitIndex + 1).trim();
        }

        // process waiting for input ?
        if (_waitingForInput !== null){
            const resolver = _waitingForInput;
            _waitingForInput = null;
            resolver(data);
        }else{
            _inputbuffer.push(data);
        }
    }
807197
def _EnsureRequesterStarted(self):
    """"""
    if not self._analyzer_started:
      self._analyzer.start()
      self._analyzer_started = True
228607
def OnApply(self, event):
        """"""

        # See if we have valid python
        try:
            ast.parse(self.macros)
        except:
            # Grab the traceback and print it for the user
            s = StringIO()
            e = exc_info()
            # usr_tb will more than likely be none because ast throws
            #   SytnaxErrorsas occurring outside of the current
            #   execution frame
            usr_tb = get_user_codeframe(e[2]) or None
            print_exception(e[0], e[1], usr_tb, None, s)
            post_command_event(self.parent, self.MacroErrorMsg,
                               err=s.getvalue())
            success = False
        else:
            self.result_ctrl.SetValue('')
            post_command_event(self.parent, self.MacroReplaceMsg,
                               macros=self.macros)
            post_command_event(self.parent, self.MacroExecuteMsg)
            success = True

        event.Skip()
        return success