Returns a dictionary containing the calculations (aggregation)
        over the current queryset

        If args is present the expression is passed as a kwarg using
        the Aggregate object's default alias.
341498
def aggregate(self, *args, **kwargs):
        
        obj = self._clone()
        obj._facets = [] #reset facets
        from django.db.models import Avg, Max, Min

        for arg in args:
            if isinstance(arg, (Avg, Max, Min)):

                field, djfield = self._django_to_es_field(arg.lookup)
                if not djfield:
                    obj = obj.annotate(field)
                from pyes.facets import StatisticalFacet

                obj = obj.annotate(StatisticalFacet(field, field))
        facets = obj.get_facets()
        #collecting results
        result = {}
        for name, values in facets.items():
            for k, v in values.items():
                if k.startswith("_"):
                    continue
                result[u'%s__%s' % (name, k)] = v

        return result
686993
def _calc_cost(self, *args, **kwargs):
        

        return np.sum([op.cost(*args, **kwargs) for op in self._operators])
1226862
def get_queryset(self, **kwargs):
        
        queryset = self.derive_queryset(**kwargs)

        return self.order_queryset(queryset)
215304
def parse_kwargs(kwargs):
    
    
    d = defaultdict(list)
    for k, v in ((k.lstrip('-'), v) for k,v in (a.split('=') for a in kwargs)):
        d[k].append(v)

    ret = {}
    for k, v in d.items():
        # replace single item lists with just the item.
        if len(v) == 1 and type(v) is list:
            ret[k] = v[0]
        else:
            ret[k] = v
    return ret
971866
def assoc(cls, ops, kwargs):
    
    expanded = [(o,) if not isinstance(o, cls) else o.operands for o in ops]
    return sum(expanded, ()), kwargs
1122661
def aggregate(self):
        
        from nefertari.elasticsearch import ES
        aggregations_params = self.pop_aggregations_params()
        if self.view._auth_enabled:
            self.check_aggregations_privacy(aggregations_params)
        self.stub_wrappers()

        return ES(self.view.Model.__name__).aggregate(
            _aggregations_params=aggregations_params,
            **self._query_params)
1154933
def totals(self):
        
        def agg(d):
            keys = ['g','a','p','pm','pn','pim','s','ab','ms','ht','gv','tk','bs']
            res = { k: 0 for k in keys }
            res['fo'] = { 'won': 0, 'total': 0 }
            for _, v in d.items():
                for k in keys:
                    res[k] += v[k]
                for fi in res['fo'].keys():
                    res['fo'][fi] += v['fo'][fi]
            return res
            
        return self.__apply_to_both(agg)
1180183
def get_terms(self, field=None):
        

        if not field:
            raise AttributeError("Please provide field to apply aggregation to!")
        agg = A("terms", field=field, size=self.size, order={"_count": "desc"})
        self.aggregations['terms_' + field] = agg
        return self
753575
def extract_kwargs(names:Collection[str], kwargs:KWArgs):
    ""
    new_kwargs = {}
    for arg_name in names:
        if arg_name in kwargs:
            arg_val = kwargs.pop(arg_name)
            new_kwargs[arg_name] = arg_val
    return new_kwargs, kwargs
1181662
def _aggop(self, query):
        
        if isinstance(query.select, list):
            # RETURN SINGLE OBJECT WITH AGGREGATES
            for s in query.select:
                if s.aggregate not in aggregates:
                    Log.error("Expecting all columns to have an aggregate: {{select}}", select=s)

            selects = FlatList()
            for s in query.select:
                selects.append(sql_alias(aggregates[s.aggregate].replace("{{code}}", s.value),quote_column(s.name)))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
            """, {
                "selects": SQL(",\n".join(selects)),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.filter)
            })

            return sql, lambda sql: self.db.column(sql)[0]  # RETURNING SINGLE OBJECT WITH AGGREGATE VALUES
        else:
            # RETURN SINGLE VALUE
            s0 = query.select
            if s0.aggregate not in aggregates:
                Log.error("Expecting all columns to have an aggregate: {{select}}", select=s0)

            select = sql_alias(aggregates[s0.aggregate].replace("{{code}}", s0.value) , quote_column(s0.name))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
            """, {
                "selects": SQL(select),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where)
            })

            def post(sql):
                result = self.db.column_query(sql)
                return result[0][0]

            return sql, post
1128164
def get_kwargs(self):
        """"""
        return {k: v for k, v in vars(self).items() if k not in self._ignored}
599402
def process_kwargs(obj, kwargs):
    '''
    
    '''
    with Modules() as m:
        kwargs = m.kwargs(obj, kwargs)
    return kwargs
371259
def get_aggregation(self, name):
        '''
        
        '''
        agg = self.aggregations[name]
        if 'buckets' in agg:
            return agg['buckets']
        else:
            return agg
1235291
def _user_object_converter(cls):
    # type: (Type[Any]) -> _AggregateConverter
    """"""
    def _from_dict(dict_value):
        try:
            object_value = cls(**dict_value)
        except TypeError:
            # Constructor does not support keyword arguments, try setting each
            # field individually.
            object_value = cls()
            for field_name, field_value in dict_value.items():
                setattr(object_value, field_name, field_value)

        return object_value

    def _to_dict(value):
        if value:
            return value.__dict__

        return {}

    return _AggregateConverter(from_dict=_from_dict, to_dict=_to_dict)
1325765
def process_filter_args(cls, kwargs):
    

    output = {}

    for key, value in kwargs.items():
        if '__' in key:
            prop, operator = key.rsplit('__')
            operator = OPERATOR_TABLE[operator]
        else:
            prop = key
            operator = '='

        if prop not in cls.defined_properties(rels=False):
            raise ValueError("No such property {0} on {1}".format(prop, cls.__name__))

        property_obj = getattr(cls, prop)
        if isinstance(property_obj, AliasProperty):
            prop = property_obj.aliased_to()
            deflated_value = getattr(cls, prop).deflate(value)
        else:
            # handle special operators
            if operator == _SPECIAL_OPERATOR_IN:
                if not isinstance(value, tuple) and not isinstance(value, list):
                    raise ValueError('Value must be a tuple or list for IN operation {0}={1}'.format(key, value))
                deflated_value = [property_obj.deflate(v) for v in value]
            elif operator == _SPECIAL_OPERATOR_ISNULL:
                if not isinstance(value, bool):
                    raise ValueError('Value must be a bool for isnull operation on {0}'.format(key))
                operator = 'IS NULL' if value else 'IS NOT NULL'
                deflated_value = None
            elif operator in _REGEX_OPERATOR_TABLE.values():
                deflated_value = property_obj.deflate(value)
                if not isinstance(deflated_value, basestring):
                    raise ValueError('Must be a string value for {0}'.format(key))
                if operator in _STRING_REGEX_OPERATOR_TABLE.values():
                    deflated_value = re.escape(deflated_value)
                deflated_value = operator.format(deflated_value)
                operator = _SPECIAL_OPERATOR_REGEX
            else:
                deflated_value = property_obj.deflate(value)

        # map property to correct property name in the database
        db_property = cls.defined_properties(rels=False)[prop].db_property or prop

        output[db_property] = (operator, deflated_value)

    return output
475897
def _parse_args(args, cls):
    
    
    d = _create_djset(args, cls)
    
    key_value_pair = args.get('<key>=<value>')
    key = args.get('<key>')
    func = None
    if args.get('add') and key_value_pair:
        fargs = tuple(args.get('<key>=<value>').split('='))
        if fargs[1]:
            func = d.set
    elif args.get('remove') and key:
        func = d.remove
        fargs = (args.get('<key>'),)
    kwargs = {'glob': args.get('--global')}
    if func:
        return func, fargs, kwargs
    else:
        return None, None, None
1085810
def resolve_kw(self, kwargs):
        
        resolved = {}
        for key, value in kwargs.items():
            split = key.split('_', 1)
            if len(split) > 1:
                key = split[1]
            resolved[key] = value
        return resolved