Django queryset.extra() is used here to add decryption sql to query.
177135
def get_queryset(self, *args, **kwargs):
        """"""
        select_sql = {}
        encrypted_fields = []
        for f in self.model._meta.get_fields_with_model():
            field = f[0]
            if isinstance(field, PGPMixin):
                select_sql[field.name] = self.get_decrypt_sql(field).format(
                    field.model._meta.db_table,
                    field.name,
                    settings.PGPFIELDS_PRIVATE_KEY,
                )
                encrypted_fields.append(field.name)
        return super(PGPEncryptedManager, self).get_queryset(
            *args, **kwargs).defer(*encrypted_fields).extra(select=select_sql)
1348430
def create_new_values(self):
        
        model = self.queryset.model
        pks = []
        extra_create_kwargs = self.extra_create_kwargs()
        for value in self._new_values:
            create_kwargs = {self.create_field: value}
            create_kwargs.update(extra_create_kwargs)
            new_item = self.create_item(**create_kwargs)
            pks.append(new_item.pk)
        return model.objects.filter(pk__in=pks)
1227139
def _filter_or_exclude_querysets(self, negate, **kwargs):
        
        # Ensure negate is a boolean.
        negate = bool(negate)

        for kwarg, value in kwargs.items():
            parts = kwarg.split(LOOKUP_SEP)

            # Ensure this is being used to filter QuerySets.
            if parts[0] != '#':
                raise ValueError("Keyword '%s' is not a valid keyword to filter over, "
                                 "it must begin with '#'." % kwarg)

            # Don't allow __ multiple times.
            if len(parts) > 2:
                raise ValueError("Keyword '%s' must not contain multiple "
                                 "lookup seperators." % kwarg)

            # The actual lookup is the second part.
            try:
                lookup = parts[1]
            except IndexError:
                lookup = 'exact'

            # Math operators that all have the same logic.
            LOOKUP_TO_OPERATOR = {
                'exact': eq,
                'iexact': eq,
                'gt': gt,
                'gte': ge,
                'lt': lt,
                'lte': le,
            }
            try:
                operator = LOOKUP_TO_OPERATOR[lookup]

                # These expect integers, this matches the logic in
                # IntegerField.get_prep_value(). (Essentially treat the '#'
                # field as an IntegerField.)
                if value is not None:
                    value = int(value)

                self._queryset_idxs = filter(lambda i: operator(i, value) != negate, self._queryset_idxs)
                continue
            except KeyError:
                # It wasn't one of the above operators, keep trying.
                pass

            # Some of these seem to get handled as bytes.
            if lookup in ('contains', 'icontains'):
                value = six.text_type(value)
                self._queryset_idxs = filter(lambda i: (value in six.text_type(i)) != negate, self._queryset_idxs)

            elif lookup == 'in':
                self._queryset_idxs = filter(lambda i: (i in value) != negate, self._queryset_idxs)

            elif lookup in ('startswith', 'istartswith'):
                value = six.text_type(value)
                self._queryset_idxs = filter(lambda i: six.text_type(i).startswith(value) != negate, self._queryset_idxs)

            elif lookup in ('endswith', 'iendswith'):
                value = six.text_type(value)
                self._queryset_idxs = filter(lambda i: six.text_type(i).endswith(value) != negate, self._queryset_idxs)

            elif lookup == 'range':
                # Inclusive include.
                start, end = value
                self._queryset_idxs = filter(lambda i: (start <= i <= end) != negate, self._queryset_idxs)

            else:
                # Any other field lookup is not supported, e.g. date, year, month,
                # day, week_day, hour, minute, second, isnull, search, regex, and
                # iregex.
                raise ValueError("Unsupported lookup '%s'" % lookup)

        # Convert back to a list on Python 3.
        self._queryset_idxs = list(self._queryset_idxs)

        # Finally, keep only the QuerySets we care about!
        self._querysets = [self._querysets[i] for i in self._queryset_idxs]
568498
def build_filtered_queryset(self, query, **kwargs):
        
        # Take the basic queryset
        qs = self.get_queryset()
        # filter it via the query conditions
        qs = qs.filter(self.get_queryset_filters(query))
        return self.build_extra_filtered_queryset(qs, **kwargs)
599990
def inject_extra_args(callback, request, kwargs):
    ''''''
    # TODO: this is a temporary pach, should be managed via honouring the
    # mimetype in the request header....
    annots = dict(callback.__annotations__)
    del annots['return']
    for param_name, (param_type, _) in annots.items():
        if param_type == Ptypes.path:
            continue  # Already parsed by werkzeug
        elif param_type == Ptypes.body:
            value = getattr(request, PTYPE_TO_REQUEST_PROPERTY[param_type])
            # TODO: The JSON conversion should be dependant from request
            # header type, really...
            value = json.loads(value.decode('utf-8'))
        else:
            get = lambda attr: getattr(request, attr).get(param_name, None)
            value = get(PTYPE_TO_REQUEST_PROPERTY[param_type])
        if value is not None:
            kwargs[param_name] = value
971972
def validate_extra_context(ctx, param, value):
    """"""
    for s in value:
        if '=' not in s:
            raise click.BadParameter(
                'EXTRA_CONTEXT should contain items of the form key=value; '
                "'{}' doesn't match that form".format(s)
            )

    # Convert tuple -- e.g.: (u'program_name=foobar', u'startsecs=66')
    # to dict -- e.g.: {'program_name': 'foobar', 'startsecs': '66'}
    return collections.OrderedDict(s.split('=', 1) for s in value) or None
51103
def extra_value(index, convert = false)
      return nil if index < 1 || index > 5
      val = send "extra_#{index}_value"
      if convert
        case extra_type(index)
          when 'boolean'
            BarkestCore::BooleanParser.parse_for_boolean_column(val)
          when 'integer'
            BarkestCore::NumberParser.parse_for_int_column(val)
          when 'float'
            BarkestCore::NumberParser.parse_for_float_column(val)
          else
            val.to_s
        end
      end
    end
37172
def query_sum(queryset, field):
    
    return queryset.aggregate(s=models.functions.Coalesce(models.Sum(field), 0))['s']
358644
def _filter_extras(dm):
        
        for extra in list(filter(None, dm)):
            new_extra = extra
            reqs = dm.pop(extra)
            new_extra, _, marker = extra.partition(':')
            fails_marker = marker and (
                invalid_marker(marker)
                or not evaluate_marker(marker)
            )
            if fails_marker:
                reqs = []
            new_extra = safe_extra(new_extra) or None

            dm.setdefault(new_extra, []).extend(reqs)
        return dm
1337420
def extra_context(self, request, context):
        """"""
        if settings.PAGE_EXTRA_CONTEXT:
            context.update(settings.PAGE_EXTRA_CONTEXT())
221943
function querystring(query) {
  var parser = /([^=?&]+)=?([^&]*)/g
    , result = {}
    , part;

  while (part = parser.exec(query)) {
    var key = decode(part[1])
      , value = decode(part[2]);

    //
    // Prevent overriding of existing properties. This ensures that build-in
    // methods like `toString` or __proto__ are not overriden by malicious
    // querystrings.
    //
    if (key in result) continue;
    result[key] = value;
  }

  return result;
}
603465
public static String queryEncode(String query, Charset charset) {
    return encodeReserved(query, FragmentType.QUERY, charset);

    /* spaces will be encoded as 'plus' symbols here, we want them pct-encoded */
    // return encoded.replaceAll("\\+", "%20");
  }
535617
def queryset(self, request, queryset):
        
        if self.value() is not None:
            if self.value() > 0:
                return queryset.filter(parent_process_id=self.value())
707926
@SuppressWarnings("unchecked")
    public static Map<String, Object> normaliseAndValidateQuery(Map<String, Object> query) throws QueryException{
        boolean isWildCard = false;
        if (query.isEmpty()) {
            isWildCard = true;
        }

        // First expand the query to include a leading compound predicate
        // if there isn't one already.
        query = addImplicitAnd(query);

        // At this point we will have a single entry map, key AND or OR,
        // forming the compound predicate.
        String compoundOperator = (String) query.keySet().toArray()[0];
        List<Object> predicates = new ArrayList<Object>();
        if (query.get(compoundOperator) instanceof List) {
            // Next make sure all the predicates have an operator -- the EQ
            // operator is implicit and we need to add it if there isn't one.
            // Take
            //     [ {"field1": "mike"}, ... ]
            // and make
            //     [ {"field1": { "$eq": "mike"} }, ... ]
            predicates = addImplicitEq((List<Object>) query.get(compoundOperator));

            // Then all shorthand operators like $ne, if present, need to be converted
            // to their logical longhand equivalent.
            // Take
            //     [ { "field1": { "$ne": "mike"} }, ... ]
            // and make
            //     [ { "field1": { "$not" : { "$eq": "mike"} } }, ... ]
            predicates = handleShortHandOperators(predicates);

            // Now in the event that extraneous $not operators exist in the query,
            // these operators must be compressed down to the their logical equivalent.
            // Take
            //     [ { "field1": { "$not" : { $"not" : { "$eq": "mike"} } } }, ... ]
            // and make
            //     [ { "field1": { "$eq": "mike"} }, ... ]
            predicates = compressMultipleNotOperators(predicates);

            // Here we ensure that all non-whole number arguments included in a $mod
            // clause are truncated.  This provides for consistent behavior between
            // the SQL engine and the unindexed matcher.
            // Take
            //     [ { "field1": { "$mod" : [ 2.6, 1.7] } }, ... ]
            // and make
            //     [ { "field1": { "$mod" : [ 2, 1 ] } }, ... ]
            predicates = truncateModArguments(predicates);
        }

        Map<String, Object> selector = new HashMap<String, Object>();
        selector.put(compoundOperator, predicates);
        if (!isWildCard) {
            validateSelector(selector);
        }

        return selector;
    }
742815
def _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning,
                    ignore_duplicate_updates=True, return_untouched=False):
    
    model = queryset.model

    # Use all fields except pk unless the uniqueness constraint is the pk field
    all_fields = [
        field for field in model._meta.fields
        if field.column != model._meta.pk.name or not field.auto_created
    ]

    all_field_names = [field.column for field in all_fields]
    returning = returning if returning is not True else [f.column for f in model._meta.fields]
    all_field_names_sql = ', '.join([_quote(field) for field in all_field_names])

    # Convert field names to db column names
    unique_fields = [
        model._meta.get_field(unique_field)
        for unique_field in unique_fields
    ]
    update_fields = [
        model._meta.get_field(update_field)
        for update_field in update_fields
    ]

    unique_field_names_sql = ', '.join([
        _quote(field.column) for field in unique_fields
    ])
    update_fields_sql = ', '.join([
        '{0} = EXCLUDED.{0}'.format(_quote(field.column))
        for field in update_fields
    ])

    row_values, sql_args = _get_values_for_rows(model_objs, all_fields)

    return_sql = 'RETURNING ' + _get_return_fields_sql(returning, return_status=True) if returning else ''
    ignore_duplicates_sql = ''
    if ignore_duplicate_updates:
        ignore_duplicates_sql = (
            ' WHERE ({update_fields_sql}) IS DISTINCT FROM ({excluded_update_fields_sql}) '
        ).format(
            update_fields_sql=', '.join(
                '{0}.{1}'.format(model._meta.db_table, _quote(field.column))
                for field in update_fields
            ),
            excluded_update_fields_sql=', '.join(
                'EXCLUDED.' + _quote(field.column)
                for field in update_fields
            )
        )

    on_conflict = (
        'DO UPDATE SET {0} {1}'.format(update_fields_sql, ignore_duplicates_sql) if update_fields else 'DO NOTHING'
    )

    if return_untouched:
        row_values_sql = ', '.join([
            '(\'{0}\', {1})'.format(i, row_value[1:-1])
            for i, row_value in enumerate(row_values)
        ])
        sql = (
            ' WITH input_rows("temp_id_", {all_field_names_sql}) AS ('
            '     VALUES {row_values_sql}'
            ' ), ins AS ( '
            '     INSERT INTO {table_name} ({all_field_names_sql})'
            '     SELECT {all_field_names_sql} FROM input_rows ORDER BY temp_id_'
            '     ON CONFLICT ({unique_field_names_sql}) {on_conflict} {return_sql}'
            ' )'
            ' SELECT DISTINCT ON ({table_pk_name}) * FROM ('
            '     SELECT status_, {return_fields_sql}'
            '     FROM   ins'
            '     UNION  ALL'
            '     SELECT \'n\' AS status_, {aliased_return_fields_sql}'
            '     FROM input_rows'
            '     JOIN {table_name} c USING ({unique_field_names_sql})'
            ' ) as results'
            ' ORDER BY results."{table_pk_name}", CASE WHEN(status_ = \'n\') THEN 1 ELSE 0 END;'
        ).format(
            all_field_names_sql=all_field_names_sql,
            row_values_sql=row_values_sql,
            table_name=model._meta.db_table,
            unique_field_names_sql=unique_field_names_sql,
            on_conflict=on_conflict,
            return_sql=return_sql,
            table_pk_name=model._meta.pk.name,
            return_fields_sql=_get_return_fields_sql(returning),
            aliased_return_fields_sql=_get_return_fields_sql(returning, alias='c')
        )
    else:
        row_values_sql = ', '.join(row_values)
        sql = (
            ' INSERT INTO {table_name} ({all_field_names_sql})'
            ' VALUES {row_values_sql}'
            ' ON CONFLICT ({unique_field_names_sql}) {on_conflict} {return_sql}'
        ).format(
            table_name=model._meta.db_table,
            all_field_names_sql=all_field_names_sql,
            row_values_sql=row_values_sql,
            unique_field_names_sql=unique_field_names_sql,
            on_conflict=on_conflict,
            return_sql=return_sql
        )

    return sql, sql_args
830538
def ko(queryset, field_names=None):
    

    try:
        koDataString = ko_data(queryset, field_names)
        koModelString = ko_model(queryset[0].__class__.__name__, field_names, data=True)
        koBindingsString = ko_bindings(queryset[0])

        koString = koDataString + '\n' + koModelString + '\n' + koBindingsString

        return koString
    except Exception as e:
        logger.error(e)
        return ''
358043
public void aggregateQueryStringParams(String additionalQueryString, boolean setQS)
    {
        // 321485
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
            logger.logp(Level.FINE, CLASS_NAME,"aggregateQueryStringParams", "entry qs --> " + additionalQueryString + " set --> " + String.valueOf(setQS));
        }
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }
        QSListItem tmpQS = null;
        SRTServletRequestThreadData reqData = SRTServletRequestThreadData.getInstance();        
        if (reqData.getParameters() == null)
        {
            if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))   //306998.15
                logger.logp(Level.FINE, CLASS_NAME,"aggregateQueryStringParams", "The paramater stack is currently null");
            // Begin 258025, Part 2
            LinkedList queryStringList = SRTServletRequestThreadData.getInstance().getQueryStringList();
            if (queryStringList == null || queryStringList.isEmpty())
            {
                if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))  //306998.15
                    logger.logp(Level.FINE, CLASS_NAME,"aggregateQueryStringParams", "The queryStringList is empty");
                if (queryStringList == null)
                   queryStringList = new LinkedList();

                if (getQueryString()!=null){
                    if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))  //306998.15
                        logger.logp(Level.FINE, CLASS_NAME,"aggregateQueryStringParams", "getQueryString will be added first in the QSList wih value->"+getQueryString());
                    tmpQS = new QSListItem(getQueryString(), null);
                    queryStringList.add(tmpQS);
                }
                SRTServletRequestThreadData.getInstance().setQueryStringList(queryStringList);

            }
            // End 258025, Part 2
            if (additionalQueryString !=null){
                tmpQS = new QSListItem(additionalQueryString, null);
                queryStringList.add(tmpQS);
            }
            
       }
        if (setQS){
            setQueryString(additionalQueryString);
        }

        // if _parameters is not null, then this is part of a forward or include...add the additional query parms
        // if _parameters is null, then the string will be parsed if needed
        if (reqData.getParameters() != null && additionalQueryString != null)
        {
            Hashtable parameters = RequestUtils.parseQueryString(additionalQueryString, getReaderEncoding(true));
            // end 249841, 256836
            String[] valArray;
            for (Enumeration e = parameters.keys(); e.hasMoreElements();)
            {
                String key = (String) e.nextElement();
                String[] newVals = (String[]) parameters.get(key);

                // Check to see if a parameter with the key already exists
                // and prepend the values since QueryString takes precedence
                //
                if (reqData.getParameters().containsKey(key))
                {
                    String[] oldVals = (String[]) reqData.getParameters().get(key);
                    Vector v = new Vector();

                    for (int i = 0; i < newVals.length; i++)
                    {
                        v.add(newVals[i]);
                    }

                    for (int i = 0; i < oldVals.length; i++)
                    {
                        // 249841, do not check to see if values already exist
                        v.add(oldVals[i]);
                    }

                    valArray = new String[v.size()];
                    v.toArray(valArray);

                    reqData.getParameters().put(key, valArray);
                }
                else
                {
                    reqData.getParameters().put(key, newVals);
                }
            }
        }
    }