Evaluate the query observer.

        :param return_emitted: True if the emitted diffs should be returned (testing only)
179142
async def evaluate(self):
        

        @database_sync_to_async
        def remove_subscribers():
            models.Observer.subscribers.through.objects.filter(
                observer_id=self.id
            ).delete()

        @database_sync_to_async
        def get_subscriber_sessions():
            return list(
                models.Observer.subscribers.through.objects.filter(observer_id=self.id)
                .distinct('subscriber_id')
                .values_list('subscriber_id', flat=True)
            )

        try:
            settings = get_queryobserver_settings()

            start = time.time()
            # Evaluate the observer
            added, changed, removed = await database_sync_to_async(self._evaluate)()
            duration = time.time() - start

            # Log slow observers.
            if duration > settings['warnings']['max_processing_time']:
                self._warning("Slow observed viewset", duration=duration)

            # Remove subscribers of really slow observers.
            if duration > settings['errors']['max_processing_time']:
                logger.error(
                    "Removing subscribers to extremely slow observed viewset ({})".format(
                        self._get_logging_id()
                    ),
                    extra=self._get_logging_extra(duration=duration),
                )
                await remove_subscribers()

            if self._meta.change_detection == Options.CHANGE_DETECTION_POLL:
                # Register poller.
                await get_channel_layer().send(
                    CHANNEL_MAIN,
                    {
                        'type': TYPE_POLL,
                        'observer': self.id,
                        'interval': self._meta.poll_interval,
                    },
                )

            message = {
                'type': TYPE_ITEM_UPDATE,
                'observer': self.id,
                'primary_key': self._meta.primary_key,
                'added': added,
                'changed': changed,
                'removed': removed,
            }

            # Only generate notifications in case there were any changes.
            if added or changed or removed:
                for session_id in await get_subscriber_sessions():
                    await get_channel_layer().group_send(
                        GROUP_SESSIONS.format(session_id=session_id), message
                    )

        except Exception:
            logger.exception(
                "Error while evaluating observer ({})".format(self._get_logging_id()),
                extra=self._get_logging_extra(),
            )
416394
def commitreturn(self, cursor, qstring, vals=()):
    ""
    cursor.execute(qstring, vals)
    return cursor.fetchall()[0]
968708
async def _observe(self, api_command):
        """"""
        duration = api_command.observe_duration
        url = api_command.url(self._host)
        err_callback = api_command.err_callback

        msg = Message(code=Code.GET, uri=url, observe=duration)

        # Note that this is necessary to start observing
        pr, r = await self._get_response(msg)

        api_command.result = _process_output(r)

        def success_callback(res):
            api_command.result = _process_output(res)

        def error_callback(ex):
            err_callback(ex)

        ob = pr.observation
        ob.register_callback(success_callback)
        ob.register_errback(error_callback)
        self._observations_err_callbacks.append(ob.error)
668209
def true_false_returns(func):
    

    @functools.wraps(func)
    def _execute(*args, **kwargs):
        """Executes function, if error returns False, else True

        :param args: args of function
        :param kwargs: extra args of function
        :param *args: args
        :param **kwargs: extra args
        :return: True iff ok, else False
        """

        try:
            func(*args, **kwargs)
            return True
        except:
            return False

    return _execute
1091899
def _vispy_emit_match_andor_record(self, record):
        """"""
        test = record.getMessage()
        match = self._vispy_match
        if (match is None or re.search(match, test) or
                re.search(match, _get_vispy_caller())):
            if self._vispy_emit_record:
                fmt_rec = self._vispy_formatter.format(record)
                self._vispy_emit_list.append(fmt_rec)
            if self._vispy_print_msg:
                return logging.StreamHandler.emit(self, record)
            else:
                return
179229
def check(self, version):  # Ignore PyDocStyleBear
        

        def _compare_spec(spec):
            if len(spec) == 1:
                spec = ("=", spec[0])

            token = Tokens.operators.index(spec[0])
            comparison = compare_version(version, spec[1])
            if token in [Tokens.EQ1, Tokens.EQ2]:
                return comparison == 0
            elif token == Tokens.GT:
                return comparison == 1
            elif token == Tokens.LT:
                return comparison == -1
            elif token == Tokens.GTE:
                return comparison >= 0
            elif token == Tokens.LTE:
                return comparison <= 0
            elif token == Tokens.NEQ:
                return comparison != 0
            else:
                raise ValueError("Invalid comparison token")

        results, intermediaries = False, False
        for spec in self.spec:
            if isinstance(spec, list):
                intermediary = True
                for sub in spec:
                    intermediary &= _compare_spec(sub)
                intermediaries |= intermediary
            elif isinstance(spec, tuple):
                results |= _compare_spec(spec)

        return results or intermediaries
43820
def _emitHMM(self, token_type, past_states, past_emissions):
        
        assert token_type in self.emissions
        return utils.weighted_choice(self.emissions[token_type].items())
716699
def do_retval(self, arg):
        
        locals = self.get_locals(self.curframe)
        if '__return__' in locals:
            self.message(bdb.safe_repr(locals['__return__']))
        else:
            self.error('Not yet returned!')
633116
def execute(self, query):
        
        c = self.conn.cursor()
        result = c.execute(query)
        for i in result:
            yield i
1038436
def _observe(self, api_command):
        """"""
        path = api_command.path
        duration = api_command.observe_duration
        if duration <= 0:
            raise ValueError("Observation duration has to be greater than 0.")
        url = api_command.url(self._host)
        err_callback = api_command.err_callback

        command = (self._base_command('get')
                   + ['-s', str(duration), '-B', str(duration), url])

        kwargs = {
            'stdout': subprocess.PIPE,
            'stderr': subprocess.DEVNULL,
            'universal_newlines': True
        }
        try:
            proc = subprocess.Popen(command, **kwargs)
        except subprocess.CalledProcessError as err:
            raise RequestError(
                'Error executing request: %s'.format(err)) from None

        output = ''
        open_obj = 0
        start = time()

        for data in iter(lambda: proc.stdout.read(1), ''):
            if data == '\n':
                _LOGGER.debug('Observing stopped for %s after %.1fs',
                              path, time() - start)
                err_callback(RequestError("Observing stopped."))
                break

            if data == '{':
                open_obj += 1
            elif data == '}':
                open_obj -= 1

            output += data

            if open_obj == 0:
                api_command.result = _process_output(output)
                output = ''
1179932
def returner(ret):
    '''
    
    '''
    serv = _get_serv(ret)
    pipeline = serv.pipeline(transaction=False)
    minion, jid = ret['id'], ret['jid']
    pipeline.hset('ret:{0}'.format(jid), minion, salt.utils.json.dumps(ret))
    pipeline.expire('ret:{0}'.format(jid), _get_ttl())
    pipeline.set('{0}:{1}'.format(minion, ret['fun']), jid)
    pipeline.sadd('minions', minion)
    pipeline.execute()
132091
def _verifyReturnToArgs(query):
        
        message = Message.fromPostArgs(query)
        return_to = message.getArg(OPENID_NS, 'return_to')

        if return_to is None:
            raise ProtocolError('Response has no return_to')

        parsed_url = urlparse(return_to)
        rt_query = parsed_url[4]
        parsed_args = cgi.parse_qsl(rt_query)

        for rt_key, rt_value in parsed_args:
            try:
                value = query[rt_key]
                if rt_value != value:
                    format = ("parameter %s value %r does not match "
                              "return_to's value %r")
                    raise ProtocolError(format % (rt_key, value, rt_value))
            except KeyError:
                format = "return_to parameter %s absent from query %r"
                raise ProtocolError(format % (rt_key, query))

        # Make sure all non-OpenID arguments in the response are also
        # in the signed return_to.
        bare_args = message.getArgs(BARE_NS)
        for pair in bare_args.iteritems():
            if pair not in parsed_args:
                raise ProtocolError("Parameter %s not in return_to URL" % (pair[0],))
974586
def returner(ret):
    '''
    
    '''
    conn = _get_conn(ret)
    cur = conn.cursor()
    sql = '''INSERT INTO salt_returns
            (fun, jid, retval, id, success, full_ret)
            VALUES (?, ?, ?, ?, ?, ?)'''
    cur.execute(
        sql, (
            ret['fun'],
            ret['jid'],
            salt.utils.json.dumps(ret['return']),
            ret['id'],
            ret['success'],
            salt.utils.json.dumps(ret)
        )
    )
    _close_conn(conn)
512339
def visit_Return(self, node: ast.Return) -> Any:  # pylint: disable=no-self-use
        """"""
        raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node)))
1113147
def emit(self, record):
        
        # if we've already processed this record, ignore it
        if record in self._recordQueue:
            return
        
        if self._activeLevels and not record.levelno in self._activeLevels:
            return
        
        name = record.name
        lvl = self.loggerLevel(name)
        
        # don't process this log
        if lvl > record.levelno:
            return
        
        self._recordQueue.insert(0, record)
        self._recordQueue = self._recordQueue[:10]
        
        # emit the change
        super(XLoggerWidgetHandler, self).emit(record)
772551
def execute(self, result=None):
        
        try:
            return self.unsafe_execute(result=result)
        except Exception as exc:
            return self._onerror(Result.from_exception(exc, uuid=self.uuid))
903265
def relicResult(relicFunc, resultType, *args):
    
    result = None

    # If there is a return type, it becomes the first parameter.
    if resultType is not None:
        result = resultType()
        args = (result,) + args

    # Pass all parameters byref
    params = [byref(x) for x in list(args)]

    # Call the function and return our result.
    relicFunc(*params)
    return result