Apply a datetime filter against the contributors's line item queryset.
500337
def line_items(self):
        """"""
        if self._line_items is None:
            self._line_items = self.contributor.line_items.filter(
                payment_date__range=(self.start, self.end)
            )
        return self._line_items
244091
public ModelAdapter<Model, Item> withItemFilter(ItemFilter<Model, Item> itemFilter) {
        this.mItemFilter = itemFilter;
        return this;
    }
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)
833668
def feed(self, from_date=None, from_offset=None, category=None,
             latest_items=None, arthur_items=None, filter_classified=None):
        

        if self.fetch_archive:
            items = self.perceval_backend.fetch_from_archive()
            self.feed_items(items)
            return
        elif arthur_items:
            items = arthur_items
            self.feed_items(items)
            return

        if from_date and from_offset:
            raise RuntimeError("Can't not feed using from_date and from_offset.")

        # We need to filter by repository to support several repositories
        # in the same raw index
        filters_ = [get_repository_filter(self.perceval_backend,
                    self.get_connector_name())]

        # Check if backend supports from_date
        signature = inspect.signature(self.perceval_backend.fetch)

        last_update = None
        if 'from_date' in signature.parameters:
            if from_date:
                last_update = from_date
            else:
                self.last_update = self.get_last_update_from_es(filters_=filters_)
                last_update = self.last_update

            logger.info("Incremental from: %s", last_update)

        offset = None
        if 'offset' in signature.parameters:
            if from_offset:
                offset = from_offset
            else:
                offset = self.elastic.get_last_offset("offset", filters_=filters_)

            if offset is not None:
                logger.info("Incremental from: %i offset", offset)
            else:
                logger.info("Not incremental")

        params = {}
        # category and filter_classified params are shared
        # by all Perceval backends
        if category is not None:
            params['category'] = category
        if filter_classified is not None:
            params['filter_classified'] = filter_classified

        # latest items, from_date and offset cannot be used together,
        # thus, the params dictionary is filled with the param available
        # and Perceval is executed
        if latest_items:
            params['latest_items'] = latest_items
            items = self.perceval_backend.fetch(**params)
        elif last_update:
            last_update = last_update.replace(tzinfo=None)
            params['from_date'] = last_update
            items = self.perceval_backend.fetch(**params)
        elif offset is not None:
            params['offset'] = offset
            items = self.perceval_backend.fetch(**params)
        else:
            items = self.perceval_backend.fetch(**params)

        self.feed_items(items)
        self.update_items()
1208384
def filter(cls, **items):
        '''
        
        '''
        client = cls._new_api_client(subpath='/search')
        items_dict = dict((k, v) for k, v in list(items.items()))
        json_data = json.dumps(items_dict, sort_keys=True, indent=4)
        return client.make_request(cls, 'post', post_data=json_data)
19874
def filter_published(self, queryset):
        """"""
        if settings.PAGE_USE_SITE_ID:
            queryset = queryset.filter(sites=global_settings.SITE_ID)

        queryset = queryset.filter(status=self.model.PUBLISHED)

        if settings.PAGE_SHOW_START_DATE:
            queryset = queryset.filter(publication_date__lte=get_now())

        if settings.PAGE_SHOW_END_DATE:
            queryset = queryset.filter(
                Q(publication_end_date__gt=get_now()) |
                Q(publication_end_date__isnull=True)
            )

        return queryset
354687
def load_with_datetime(pairs):
    """"""
    d = {}
    for k, v in pairs:
        if isinstance(v, basestring):
            try:
                d[k] = dateutil.parser.parse(v)
            except ValueError:
                d[k] = v
        else:
            d[k] = v             
    return d
1104687
private void filter(Predicate<TreeItem<S>> predicate) {
        if (task != null) {
            task.cancel(false);
        }
        task = threadPool.schedule(filterRunnable, 200, TimeUnit.MILLISECONDS);
    }
1112895
def filter_to_dmql(filter_dict):
        """"""

        if not isinstance(filter_dict, (dict, collections.OrderedDict)):
            raise TypeError('Expected a dictionary type buy got {} instead.'.format(type(filter_dict)))

        def is_date_time_type(val):
            """Returns True if the value is a datetime"""
            return isinstance(val, (datetime.datetime, datetime.date, datetime.time))

        def evaluate_datetime(val):
            """Converts the datetime object into the RETS expected format"""
            date_format = '%Y-%m-%d'
            time_format = '%H:%M:%S'
            datetime_format = '{}T{}'.format(date_format, time_format)

            if isinstance(val, datetime.datetime):
                evaluated = val.strftime(datetime_format)
            elif isinstance(val, datetime.date):
                evaluated = val.strftime(date_format)
            elif isinstance(val, datetime.time):
                evaluated = val.strftime(time_format)
            else:
                evaluated = val

            return evaluated

        def evaluate_operators(key_dict):
            """Turns the custom filter operators into the expected RETS query"""
            allowed_operators = ['$gte', '$lte', '$contains', '$begins', '$ends', '$in', '$nin', '$neq']

            # If key not in allowed_operators, assume it is a field name with the and operation.
            if not all(op in allowed_operators for op in key_dict.keys()):
                raise ValueError("You have supplied an invalid operator. "
                                 "Please provide one of the following {}".format(allowed_operators))

            # We can have a single operator key, or the combination of gte/lte
            keys = key_dict.keys()
            string = ''

            # Search between two numbers or two dates
            if len(keys) == 2 and all(k in ['$gte', '$lte'] for k in keys):
                if all(is_date_time_type(key_dict[v]) for v in keys):
                    # comparing dates
                    string = '{}-{}'.format(evaluate_datetime(key_dict['$gte']), evaluate_datetime(key_dict['$lte']))
                else:
                    # comparing numbers
                    try:
                        float(key_dict['$gte'])
                        float(key_dict['$lte'])
                    except ValueError:
                        raise ValueError("$gte and $lte expect numeric or datetime values")
                    string = '{:.2f}-{:.2f}'.format(key_dict['$gte'], key_dict['$lte'])

            # Using a single operator key
            elif len(keys) == 1:
                if '$gte' in key_dict:
                    if is_date_time_type(key_dict['$gte']):
                        string = '{}+'.format(evaluate_datetime(key_dict['$gte']))
                    else:
                        try:
                            float(key_dict['$gte'])
                        except ValueError:
                            raise ValueError("$gte expects a numeric value or a datetime object")
                        string = '{:.2f}+'.format(key_dict['$gte'])

                elif '$lte' in key_dict:
                    if is_date_time_type(key_dict['$lte']):
                        string = '{}-'.format(evaluate_datetime(key_dict['$lte']))
                    else:
                        try:
                            float(key_dict['$lte'])
                        except ValueError:
                            raise ValueError("$lte expects a numeric value or a datetime object")
                        string = '{:.2f}-'.format(key_dict['$lte'])

                elif '$in' in key_dict:
                    if not isinstance(key_dict['$in'], list):
                        raise ValueError("$in expects a list of strings")
                    key_dict['$in'] = [evaluate_datetime(v) for v in key_dict['$in']]
                    if not all(isinstance(v, string_types) for v in key_dict['$in']):
                        raise ValueError("$in expects a list of strings")
                    options = ','.join(key_dict['$in'])
                    string = '{}'.format(options)

                elif '$nin' in key_dict:
                    if not isinstance(key_dict['$nin'], list):
                        raise ValueError("$nin expects a list of strings")
                    key_dict['$nin'] = [evaluate_datetime(v) for v in key_dict['$nin']]
                    if not all(isinstance(v, string_types) for v in key_dict['$nin']):
                        raise ValueError("$nin expects a list of strings")
                    options = ','.join(key_dict['$nin'])
                    string = '~{}'.format(options)

                elif '$contains' in key_dict:
                    if not isinstance(key_dict['$contains'], string_types):
                        raise ValueError("$contains expects a string.")
                    string = '*{}*'.format(key_dict['$contains'])

                elif '$begins' in key_dict:
                    if not isinstance(key_dict['$begins'], string_types):
                        raise ValueError("$begins expects a string.")
                    string = '{}*'.format(key_dict['$begins'])

                elif '$ends' in key_dict:
                    if not isinstance(key_dict['$ends'], string_types):
                        raise ValueError("$ends expects a string.")
                    string = '*{}'.format(key_dict['$ends'])

                elif '$neq' in key_dict:
                    string = '~{}'.format(key_dict['$neq'])

            else:
                # Provided too many or too few operators
                raise ValueError("Please supply $gte and $lte for getting values between numbers or 1 of {}".format(
                    allowed_operators))

            return string

        dmql_search_filters = []

        for filt, value in filter_dict.items():
            dmql_string = '({}='.format(filt)
            if isinstance(value, dict):
                # Applying an operator. This will need to be recursive because of the or possibility
                dmql_string += evaluate_operators(key_dict=value)
            else:
                # Simle equals statement
                dmql_string += '{}'.format(evaluate_datetime(value))
            dmql_string += ')'
            dmql_search_filters.append(dmql_string)

        search_string = ','.join(dmql_search_filters)
        # Converts the filter dictionary to dmqp string
        logger.debug("Filter returned the following DMQL: {}".format(search_string))
        return search_string
752583
def get_last_date(self, field, filters_=[]):
        '''
            
        '''

        last_date = self.get_last_item_field(field, filters_=filters_)

        return last_date
1337072
def get_list_filter(self, request):
        
        list_filter = super(VersionedAdmin, self).get_list_filter(request)
        return list(list_filter) + [('version_start_date', DateTimeFilter),
                                    IsCurrentFilter]
851017
def build_dated_queryset(self):
        
        qs = self.get_dated_queryset()
        years = self.get_date_list(qs)
        [self.build_year(dt) for dt in years]
1354285
def getComponentFilters(self,component,event=None,dateTime=None):
        '''
        
        '''

        # Limit to the staff member or staff category specified by the rule.
        if component.staffMember:
            filters = Q(pk=component.staffMember.pk)
        else:
            filters = Q(eventstaffmember__category=component.staffCategory)

        # Handle 'Always' and 'EventOnly' rules first, because they do not require an analysis of intervals.
        if component.admissionRule == 'EventOnly' and event:
            # Skip the analysis of intervals and include only those who are staffed for the event.
            return Q(filters & Q(eventstaffmember__event=event))
        elif component.admissionRule in ['Always','EventOnly']:
            # If 'Always' or no event is specified, include all associated staff
            return Q(filters)

        # Start with the event occurrence intervals, or with the specified time.
        if event:
            intervals = [(x.startTime,x.endTime) for x in event.eventoccurrence_set.all()]
        elif dateTime:
            intervals = [(dateTime,dateTime)]
        else:
            raise ValueError(_('Must provide either an event or a datetime to get interval queries.'))

        if component.admissionRule == 'Day':
            # The complete days of each event occurrence
            intervals = [
                (self.getDayStart(x[0]),self.getDayStart(x[1]) + timedelta(days=1)) for x in intervals
            ]
        elif component.admissionRule == 'Week':
            # The complete weeks of each event occurrence
            intervals = [
                (
                    self.getDayStart(x[0]) - timedelta(days=x[0].weekday()),
                    self.getDayStart(x[1]) - timedelta(days=x[1].weekday() - 7)
                ) for x in intervals
            ]
        elif component.admissionRule == 'Month':
            # The complete month of each event occurrence
            intervals = [
                (
                    self.getDayStart(x[0]).replace(day=1),
                    self.getDayStart(x[1]).replace(day=1) + relativedelta(months=1)
                ) for x in intervals
            ]
        elif component.admissionRule == 'Year':
            # The complete years of each event occurrence
            intervals = [
                (
                    self.getDayStart(x[0]).replace(month=1,day=1),
                    self.getDayStart(x[1]).replace(year=x[1].year + 1,month=1,day=1)
                ) for x in intervals
            ]
        else:
            # This is a failsafe that will always evaluate as False.
            return Q(pk__isnull=True)

        # Use intervaltree to create the most parsimonious set of intervals for this interval
        # and then filter on those intervals
        intervals = [sorted(x) for x in intervals]
        tree = IntervalTree.from_tuples(intervals)
        tree.merge_overlaps()

        # Since we are OR appending, start with something that is always False.
        intervalFilters = Q(pk__isnull=True)

        for item in tree.items():
            intervalFilters = intervalFilters | Q(
                Q(eventstaffmember__event__eventoccurrence__endTime__gte=item[0]) &
                Q(eventstaffmember__event__eventoccurrence__startTime__lte=item[1])
            )

        return Q(filters & intervalFilters)
789597
def exclude(self, *args, **kwargs) -> "QuerySet":
        
        return self._filter_or_exclude(negate=True, *args, **kwargs)
818972
def sanitize_date(publication_date: str) -> str:
    """"""
    if re1.search(publication_date):
        return datetime.strptime(publication_date, '%Y %b %d').strftime('%Y-%m-%d')

    if re2.search(publication_date):
        return datetime.strptime(publication_date, '%Y %b').strftime('%Y-%m-01')

    if re3.search(publication_date):
        return publication_date + "-01-01"

    if re4.search(publication_date):
        return datetime.strptime(publication_date[:-4], '%Y %b').strftime('%Y-%m-01')

    s = re5.search(publication_date)

    if s:
        year, season = s.groups()
        return '{}-{}-01'.format(year, season_map[season])

    s = re6.search(publication_date)

    if s:
        return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d')

    s = re7.search(publication_date)

    if s:
        return datetime.strptime(publication_date, '%Y %b %d-{}'.format(s.groups()[0])).strftime('%Y-%m-%d')
1311155
def apply_filters(query, args):
    
    pre_joins = []
    for querystring_key, filter_value in args.items(multi=True):
        if querystring_key in filter_registry:
            cls_inst = filter_registry[querystring_key]
            query = cls_inst.apply_filter(query, args, pre_joins)
        elif querystring_key in PaginationKeys._value_list:
            pass
        else:
            raise InvalidQueryString(querystring_key, filter_value)
    return query
1036658
def validate_a_time_filter(self, value):
        
        if value:
            try:
                utils.parse_datetime_range(value)
            except Exception as e:
                raise serializers.ValidationError(e.message)

        return value