Create a range filter.

    :param field: Field name.
    :param start_date_math: Starting date.
    :param end_date_math: Ending date.
    :param kwargs: Addition arguments passed to the Range query.
    :returns: Function that returns the Range query.
345485
def range_filter(field, start_date_math=None, end_date_math=None, **kwargs):
    
    def inner(values):
        if len(values) != 1 or values[0].count('--') != 1 or values[0] == '--':
            raise RESTValidationError(
                errors=[FieldError(field, 'Invalid range format.')])

        range_ends = values[0].split('--')
        range_args = dict()

        ineq_opers = [{'strict': 'gt', 'nonstrict': 'gte'},
                      {'strict': 'lt', 'nonstrict': 'lte'}]
        date_maths = [start_date_math, end_date_math]

        # Add the proper values to the dict
        for (range_end, strict, opers,
             date_math) in zip(range_ends, ['>', '<'], ineq_opers, date_maths):

            if range_end != '':
                # If first char is '>' for start or '<' for end
                if range_end[0] == strict:
                    dict_key = opers['strict']
                    range_end = range_end[1:]
                else:
                    dict_key = opers['nonstrict']

                if date_math:
                    range_end = '{0}||{1}'.format(range_end, date_math)

                range_args[dict_key] = range_end

        args = kwargs.copy()
        args.update(range_args)

        return Range(**{field: args})

    return inner
569564
def where_ends_with(self, field_name, value):
        
        if field_name is None:
            raise ValueError("None field_name is invalid")

        field_name = Query.escape_if_needed(field_name)
        self._add_operator_if_needed()
        self.negate_if_needed(field_name)

        self.last_equality = {field_name: value}
        token = _Token(field_name=field_name, token="endsWith", value=self.add_query_parameter(value))
        token.write = self.rql_where_write(token)
        self._where_tokens.append(token)

        return self
413652
def get_queryset(self):
        
        kwargs = {}
        if self.ends_at:
            kwargs.update({'%s__lt' % self.date_field: self.ends_at})
        return super(BeforeMixin, self).get_queryset().filter(**kwargs)
1356919
def datedif(ctx, start_date, end_date, unit):
    
    start_date = conversions.to_date(start_date, ctx)
    end_date = conversions.to_date(end_date, ctx)
    unit = conversions.to_string(unit, ctx).lower()

    if start_date > end_date:
        raise ValueError("Start date cannot be after end date")

    if unit == 'y':
        return relativedelta(end_date, start_date).years
    elif unit == 'm':
        delta = relativedelta(end_date, start_date)
        return 12 * delta.years + delta.months
    elif unit == 'd':
        return (end_date - start_date).days
    elif unit == 'md':
        return relativedelta(end_date, start_date).days
    elif unit == 'ym':
        return relativedelta(end_date, start_date).months
    elif unit == 'yd':
        return (end_date - start_date.replace(year=end_date.year)).days

    raise ValueError("Invalid unit value: %s" % unit)
546021
def as_dates(self):
        
        new_start = self.start.date() if self.start and isinstance(self.start, datetime.datetime) else self.start
        new_end = self.end.date() if self.end and isinstance(self.end, datetime.datetime) else self.end
        return DateRange(new_start, new_end, CLOSED_CLOSED)
975515
def range_return(request, items):
    
    if ('Range' in request.headers):
        range = parse_range_header(request.headers['Range'])
    elif 'X-Range' in request.headers:
        range = parse_range_header(request.headers['X-Range'])
    else:
        range = {
            'start': 0,
            'finish': MAX_NUMBER_ITEMS - 1,
            'count': MAX_NUMBER_ITEMS
        }
    filtered = items[range['start']:range['finish'] + 1]
    if len(filtered) < range['count']:
        # Something was stripped, deal with it
        range['count'] = len(filtered)
        range['finish'] = range['start'] + range['count'] - 1
    if range['finish'] - range['start'] + 1 >= MAX_NUMBER_ITEMS:
        range['finish'] = range['start'] + MAX_NUMBER_ITEMS - 1
        filtered = items[range['start']:range['finish'] + 1]

    request.response.headers['Content-Range'] = 'items %d-%d/%d' % (range['start'], range['finish'], len(items))
    request.response.headers['X-Content-Range'] = request.response.headers['Content-Range']
    return filtered
1009354
def _create_filter(self, condition):
        
        # "Normal" comparison operators?
        comparison = re.match(r"^(%s)(<[>=]?|>=?|!=|~)(.*)$" % self.ident_re, condition)
        if comparison:
            name, comparison, values = comparison.groups()
            if values and values[0] in "+-":
                raise FilterError("Comparison operator cannot be followed by '%s' in '%s'" % (values[0], condition))
            values = self.COMPARISON_OPS[comparison] % values
        else:
            # Split name from value(s)
            try:
                name, values = condition.split('=', 1)
            except ValueError:
                if self.default_field:
                    name, values = self.default_field, condition
                else:
                    raise FilterError("Field name missing in '%s' (expected '=')" % condition)

        # Try to find field definition
        field = self.lookup(name)
        if not field:
            raise FilterError("Unknown field %r in %r" % (name, condition))
        if field.get("matcher") is None:
            raise FilterError("Field %r cannot be used as a filter" % (name,))

        # Make filters from values (split on commas outside of /…/)
        filters = []
        split_values = re.findall(r'(!?/[^/]*/|[^,]+)(?:,|$)', values) if values else ['']
        if not split_values:
            raise FilterError("Internal Error: Cannot split %r into match values" % (values,))

        for value in split_values:
            wrapper = None
            if value.startswith('!'):
                wrapper = NegateFilter
                value = value[1:]
            field_matcher = field["matcher"](name, value)
            filters.append(wrapper(field_matcher) if wrapper else field_matcher)

        # Return filters
        return CompoundFilterAny(filters) if len(filters) > 1 else filters[0]
122962
def _init_date_range(self, start_date=None, end_date=None):
        """"""
        self.end_date = end_date
        self.start_date = start_date
        if self.end_date is None:
            today = now_utc().date()
            end_date = self.event.end_dt.date()
            self.end_date = end_date if end_date < today else today
        if self.start_date is None:
            self.start_date = self.end_date - timedelta(days=ReportBase.default_report_interval)
342791
def filter_model_items(index_instance, model_items, model_name, start_date, end_date):
    ''' '''
    if index_instance.updated_field is None:
        logger.warning("No updated date field found for {} - not restricting with start and end date".format(model_name))
    else:
        if start_date:
            model_items = model_items.filter(**{'{}__gte'.format(index_instance.updated_field): __str_to_tzdate__(start_date)})
        if end_date:
            model_items = model_items.filter(**{'{}__lte'.format(index_instance.updated_field): __str_to_tzdate__(end_date)})

    return model_items
928489
public Query range(String start, String end) {
    return range(wrapKey(start), wrapKey(end));
  }
483311
def _term_query(self, term, field_name, field_type, stemmed=True):
        
        constructor = '{prefix}{term}'

        # construct the prefix to be used.
        prefix = ''
        if field_name:
            prefix = TERM_PREFIXES['field'] + field_name.upper()
            term = _to_xapian_term(term)

        if field_name in (ID, DJANGO_ID, DJANGO_CT):
            # to ensure the value is serialized correctly.
            if field_name == DJANGO_ID:
                term = int(term)
            term = _term_to_xapian_value(term, field_type)
            return xapian.Query('%s%s' % (TERM_PREFIXES[field_name], term))

        # we construct the query dates in a slightly different way
        if field_type == 'datetime':
            date, time = term.split()
            return xapian.Query(xapian.Query.OP_AND_MAYBE,
                                constructor.format(prefix=prefix, term=date),
                                constructor.format(prefix=prefix, term=time)
                                )

        # only use stem if field is text or "None"
        if field_type not in ('text', None):
            stemmed = False

        unstemmed_term = constructor.format(prefix=prefix, term=term)
        if stemmed:
            stem = xapian.Stem(self.backend.language)
            stemmed_term = 'Z' + constructor.format(prefix=prefix, term=stem(term).decode('utf-8'))

            return xapian.Query(xapian.Query.OP_OR,
                                xapian.Query(stemmed_term),
                                xapian.Query(unstemmed_term)
                                )
        else:
            return xapian.Query(unstemmed_term)
631274
def dates(date_range)
      if date_range.is_a? String

        # assume the user knows what she is doing if passed a string
        @query[:params][:date] = date_range
      elsif date_range.is_a? Range
        start = date_range.first
        last = date_range.last
        @query[:params][:date] = "#{start.strftime("%YM%m")}:#{last.strftime("%YM%m")}"
      end
      self
    end
586998
def get_value_filter(self, filter_value):
        '''
        
        '''
        self.validate_parameter(filter_value)
        f, t = self._ranges[filter_value]
        limits = {}
        # lt and gte to ensure non-overlapping ranges
        if f is not None:
            limits['gte'] = f
        if t is not None:
            limits['lt'] = t

        return Q('range', **{
            self._params['field']: limits
        })
919464
public void setTimeRange(String fieldName, Date startTime, Date endTime) {
		this.where += " and " + fieldName + ">=? and " + fieldName + "<=?";
		this.getParam().setDate(startTime);
		this.getParam().setDate(endTime);
	}
408142
def date_range_for_webtrends(cls, start_at=None, end_at=None):
        
        if start_at and end_at:
            start_date = cls.parse_standard_date_string_to_date(
                start_at)
            end_date = cls.parse_standard_date_string_to_date(
                end_at)
            return [(
                cls.parse_date_for_query(start_date),
                cls.parse_date_for_query(end_date))]
        else:
            return [("current_hour-1", "current_hour-1")]
907888
def query(self, start_date=None, end_date=None, ndays=None, metrics=[], dimensions=[], filters=None, segment=None, sort=[], start_index=1, max_results=10):
        
        if start_date:
            start_date = start_date
        elif getattr(self.args, 'start-date'):
            start_date = getattr(self.args, 'start-date')
        elif self.config.get('start-date', None):
            start_date = self.config['start-date']
        else:
            start_date = '2005-01-01'

        if end_date:
            end_date = end_date
        elif getattr(self.args, 'end-date'):
            end_date = getattr(self.args, 'end-date')
        elif self.config.get('end-date', None):
            end_date = self.config['end-date']
        elif ndays:
            end_date = self._ndays(start_date, ndays)
        elif self.args.ndays:
            end_date = self._ndays(start_date, self.args.ndays)
        elif self.config.get('ndays', None):
            end_date = self._ndays(start_date, self.config['ndays'])
        else:
            end_date = 'today' 

        if self.args.domain:
            domain = self.args.domain
        elif self.config.get('domain', None):
            domain = self.config['domain']
        else:
            domain = None

        if domain:
            domain_filter = 'ga:hostname==%s' % domain

            if filters:
                filters = '%s;%s' % (domain_filter, filters)
            else:
                filters = domain_filter

        if self.args.prefix:
            prefix = self.args.prefix
        elif self.config.get('prefix', None):
            prefix = self.config['prefix']
        else:
            prefix = None

        if prefix:
            prefix_filter = 'ga:pagePath=~^%s' % prefix 
                
            if filters:
                filters = '%s;%s' % (prefix_filter, filters)
            else:
                filters = prefix_filter

        return self.service.data().ga().get(
            ids='ga:' + self.config['property-id'],
            start_date=start_date,
            end_date=end_date,
            metrics=','.join(metrics) or None,
            dimensions=','.join(dimensions) or None,
            filters=filters,
            segment=segment,
            sort=','.join(sort) or None,
            start_index=str(start_index),
            max_results=str(max_results)
        ).execute()
690652
def filter_from_url_arg(model_cls, query, arg, query_operator=and_,
                        arg_types=None):
    

    fields = arg.split(',')
    mapper = class_mapper(model_cls)

    if not arg_types:
        arg_types = {}

    exprs = []
    joins = set()
    for expr in fields:
        if expr == "":
            continue

        e_mapper = mapper
        e_model_cls = model_cls

        operator = None
        method = None
        for op in operator_order:
            if op in expr:
                operator = op
                method = operator_to_method[op]
                break

        if operator is None:
            raise Exception('No operator in expression "{0}".'.format(expr))

        (column_names, value) = expr.split(operator)

        column_names = column_names.split('__')
        value = value.strip()

        for column_name in column_names:
            if column_name in arg_types:
                typed_value = arg_types[column_name](value)
            else:
                typed_value = value

            if column_name in e_mapper.relationships:
                joins.add(column_name)
                e_model_cls = e_mapper.attrs[column_name].mapper.class_
                e_mapper = class_mapper(e_model_cls)

        if hasattr(e_model_cls, column_name):
            column = getattr(e_model_cls, column_name)
            exprs.append(getattr(column, method)(typed_value))
        else:
            raise Exception('Invalid property {0} in class {1}.'.format(column_name, e_model_cls))

    return query.join(*joins).filter(query_operator(*exprs))