Extract the *order_by*, *per_page*, and *page* parameters from
    `query_dict` (a Django QueryDict), and return a dict suitable for
    instantiating a preconfigured Table object.
163588
def extract(query_dict, prefix=""):
    

    strs = ['order_by']
    ints = ['per_page', 'page']

    extracted = { }

    for key in (strs + ints):
        if (prefix + key) in query_dict:
            val = query_dict.get(prefix + key)

            extracted[key] = (val
                if not key in ints
                else int(val))

    return extracted
407573
def list_parameters(self, parameter_type=None, page_size=None):
        
        params = {'details': True}

        if parameter_type is not None:
            params['type'] = parameter_type
        if page_size is not None:
            params['limit'] = page_size

        return pagination.Iterator(
            client=self._client,
            path='/mdb/{}/parameters'.format(self._instance),
            params=params,
            response_class=mdb_pb2.ListParametersResponse,
            items_key='parameter',
            item_mapper=Parameter,
        )
862621
def _get_query_params(self):
        
        result = {}
        if self.next_page_token is not None:
            result[self._PAGE_TOKEN] = self.next_page_token
        if self.max_results is not None:
            result[self._MAX_RESULTS] = self.max_results - self.num_results
        result.update(self.extra_params)
        return result
67140
def _query(self, query_str, query_args=None, **query_options):
        
        ret = True
        # http://stackoverflow.com/questions/6739355/dictcursor-doesnt-seem-to-work-under-psycopg2
        connection = query_options.get('connection', None)
        with self.connection(connection) as connection:
            cur = connection.cursor()
            ignore_result = query_options.get('ignore_result', False)
            count_result = query_options.get('count_result', False)
            one_result = query_options.get('fetchone', query_options.get('one_result', False))
            cursor_result = query_options.get('cursor_result', False)

            try:
                if query_args:
                    self.log("{}{}{}", query_str, os.linesep, query_args)
                    cur.execute(query_str, query_args)
                else:
                    self.log(query_str)
                    cur.execute(query_str)

                if cursor_result:
                    ret = cur

                elif not ignore_result:
                    if one_result:
                        ret = self._normalize_result_dict(cur.fetchone())
                    elif count_result:
                        ret = cur.rowcount
                    else:
                        ret = self._normalize_result_list(cur.fetchall())

            except Exception as e:
                self.log(e)
                raise

            return ret
837117
def query(self):
        
        ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True))
        return MultiDictProxy(ret)
1344083
def get(self, table='', start=0, limit=0, order=None, where=None):
        
        parameters = {}

        args = ['start', 'limit', 'order', 'where']
        for arg in args:
            if arg in locals() and locals()[arg]:
                parameters[arg] = locals()[arg]

        response = self._client.session.get(
            '{url}/{table}'.format(
                url=self.endpoint_url, table=table
            ),
            params=parameters
        )
        return self.process_response(response)
95894
def from_dict(cls, entity_cls, adict):
        """"""
        invalid_req = InvalidRequestObject()

        # Extract the pagination parameters from the input
        page = int(adict.pop('page', 1))
        per_page = int(adict.pop(
            'per_page', getattr(active_config, 'PER_PAGE', 10)))
        order_by = adict.pop('order_by', ())

        # Check for invalid request conditions
        if page < 0:
            invalid_req.add_error('page', 'is invalid')

        if invalid_req.has_errors:
            return invalid_req

        # Do we need to pop out random?
        # adict.pop('random', None)

        return cls(entity_cls, page, per_page, order_by, adict)
1044364
def query_helper(request,namespace, docid, configuration=None):
    """"""
    flatargs = {
        'customslicesize': request.POST.get('customslicesize',settings.CONFIGURATIONS[configuration].get('customslicesize','50')), #for pagination of search results
    }
    #stupid compatibility stuff
    if sys.version < '3':
        if hasattr(request, 'body'):
            data = json.loads(unicode(request.body,'utf-8')) #pylint: disable=undefined-variable
        else: #older django
            data = json.loads(unicode(request.raw_post_data,'utf-8')) #pylint: disable=undefined-variable
    else:
        if hasattr(request, 'body'):
            data = json.loads(str(request.body,'utf-8'))
        else: #older django
            data = json.loads(str(request.raw_post_data,'utf-8'))

    if not data['queries']:
        return HttpResponseForbidden("No queries to run")

    for query in data['queries']:
        #get document selector and check it doesn't violate the namespace
        docselector, query = getdocumentselector(query)
        if not docselector:
            return HttpResponseForbidden("Query does not start with a valid document selector (USE keyword)!")
        elif docselector[0] != namespace:
            return HttpResponseForbidden("Query would affect a different namespace than your current one, forbidden!")

        if query != "GET" and query[:4] != "CQL " and query[:4] != "META":
            #parse query on this end to catch syntax errors prior to sending, should be fast enough anyway
            #first resolve variables to dummies (real ones will be handled server-side) as it won't be valid FQL otherwise
            query = query.replace("$FOLIADOCSERVE_PROCESSOR", "PROCESSOR name \"foliadocserve\"")
            query = query.replace("$FLAT_PROCESSOR", "PROCESSOR name \"FLAT\" version \"" + VERSION + "\" host \"" + request.get_host() + "\" src \"" + request.build_absolute_uri("/") + "\"") #also another instance in comm.py
            try:
                query = fql.Query(query)
            except fql.SyntaxError as e:
                return HttpResponseForbidden("FQL Syntax Error: " + str(e))
            needwritepermission = query.declarations or query.action and query.action.action != "SELECT"
        else:
            needwritepermission = False

    if configuration != "pub":
        if needwritepermission and not flat.users.models.haswritepermission(request.user.username, namespace, request):
            return HttpResponseForbidden("Permission denied, no write access")

    query = "\n".join(data['queries']) #throw all queries on a big pile to transmit
    try:
        d = flat.comm.query(request, query,**flatargs)
    except Exception as e:
        if sys.version < '3':
            errmsg = docserveerror(e)['fatalerror_text']
            return HttpResponseForbidden("FoLiA Document Server error: ".encode('utf-8') + errmsg.encode('utf-8'))
        else:
            return HttpResponseForbidden("FoLiA Document Server error: " + docserveerror(e)['fatalerror_text'])
    return HttpResponse(json.dumps(d).encode('utf-8'), content_type='application/json')
577179
def parse_pagination_dict(cls, response_obj):
        

        pagination_dict = {}

        cls.update_dict_id_field_from_response_field(
            pagination_dict,
            cls._FIELD_OLDER_ID,
            response_obj,
            cls._FIELD_OLDER_URL,
            client.Pagination.PARAM_OLDER_ID
        )
        cls.update_dict_id_field_from_response_field(
            pagination_dict,
            cls._FIELD_NEWER_ID,
            response_obj,
            cls._FIELD_NEWER_URL,
            client.Pagination.PARAM_NEWER_ID
        )
        cls.update_dict_id_field_from_response_field(
            pagination_dict,
            cls._FIELD_FUTURE_ID,
            response_obj,
            cls._FIELD_FUTURE_URL,
            client.Pagination.PARAM_NEWER_ID
        )

        return pagination_dict
426613
def slice(self, order_by='pk', n=None):
        
        if n is not None and n < 0:
            raise ValueError('slice parameter cannot be negative')
        
        queryset = self.order_by(order_by)
        
        if n is None:
            return queryset[0]
        else:
            return queryset[0:n]
98846
def _query(self, request, filter=None):
        
        limit = None
        offset = None
        if 'maxfeatures' in request.params:
            limit = int(request.params['maxfeatures'])
        if 'limit' in request.params:
            limit = int(request.params['limit'])
        if 'offset' in request.params:
            offset = int(request.params['offset'])
        if filter is None:
            filter = create_filter(request, self.mapped_class, self.geom_attr)
        query = self.Session().query(self.mapped_class)
        if filter is not None:
            query = query.filter(filter)
        order_by = self._get_order_by(request)
        if order_by is not None:
            query = query.order_by(order_by)
        query = query.limit(limit).offset(offset)
        return query.all()
972146
def _get_query(self, order=None, filters=None):
        
        order = self._get_order(order)
        return self.posts.all().order_by(order)
1043900
def pages_to_json(queryset):
    
    # selection may be in the wrong order, and order matters
    queryset = queryset.order_by('tree_id', 'lft')
    return simplejson.dumps(
        {JSON_PAGE_EXPORT_NAME: JSON_PAGE_EXPORT_VERSION,
            'pages': [page.dump_json_data() for page in queryset]},
        indent=JSON_PAGE_EXPORT_INDENT, sort_keys=True)
851575
def django_pre_2_0_table_context(
        request,
        table,
        links=None,
        paginate_by=None,
        page=None,
        extra_context=None,
        paginator=None,
        show_hits=False,
        hit_label='Items'):
    
    if extra_context is None:  # pragma: no cover
        extra_context = {}

    assert table.data is not None

    links, grouped_links = evaluate_and_group_links(links, table=table)

    base_context = {
        'links': links,
        'grouped_links': grouped_links,
        'table': table,
    }

    if paginate_by:
        try:
            paginate_by = int(request.GET.get('page_size', paginate_by))
        except ValueError:  # pragma: no cover
            pass
        if paginator is None:
            paginator = Paginator(table.data, paginate_by)
            object_list = None
        else:  # pragma: no cover
            object_list = table.data
        if not page:
            page = request.GET.get('page', 1)
        try:
            page = int(page)
            if page < 1:  # pragma: no cover
                page = 1
            if page > paginator.num_pages:  # pragma: no cover
                page = paginator.num_pages
            if object_list is None:
                table.data = paginator.page(page).object_list
        except (InvalidPage, ValueError):  # pragma: no cover
            if page == 1:
                table.data = []
            else:
                raise Http404

        base_context.update({
            'request': request,
            'is_paginated': paginator.num_pages > 1,
            'results_per_page': paginate_by,
            'has_next': paginator.num_pages > page,
            'has_previous': page > 1,
            'page_size': paginate_by,
            'page': page,
            'next': page + 1,
            'previous': page - 1,
            'pages': paginator.num_pages,
            'hits': paginator.count,
            'show_hits': show_hits,
            'hit_label': hit_label})
    else:  # pragma: no cover
        base_context.update({
            'is_paginated': False})

    base_context.update(extra_context)
    return base_context
797721
def get_parameters_as_dictionary(self, query_string):
        
        pairs = (x.split('=', 1) for x in query_string.split('&'))
        return dict((k, unquote(v)) for k, v in pairs)
1344916
def make_query(self, *args, **kwargs):
        
        query = Q()  # initial is an empty query
        query_dict = self._build_query_dict(self.cleaned_data)
        if 'negate' in self.cleaned_data and self.cleaned_data['negate']:
            query = query & ~Q(**query_dict)
        else:
            query = query & Q(**query_dict)
        return query
650349
def get_context_data(self, **kwargs):
        
        #noinspection PyUnresolvedReferences
        query_str           = self.request.GET.get('q', None)
        queryset            = kwargs.pop('object_list', self.object_list)
        context_object_name = self.get_context_object_name(queryset)

        # Build the context dictionary.
        context = {
            'ordering':     self.get_ordering(),
            'query_string': query_str,
            'is_searching': bool(query_str),
        }

        # Add extra variables to context for non-AJAX requests.
        #noinspection PyUnresolvedReferences
        if not self.request.is_ajax() or kwargs.get('force_search', False):
            context.update({
                'search_form':  self.get_search_form(),
                'popular_tags': self.model.popular_tags()
            })

        if context_object_name is not None:
            context[context_object_name] = queryset

        # Update context with any additional keyword arguments.
        context.update(kwargs)

        return super(IndexView, self).get_context_data(**context)