Clean and validate a sort order and direction from user params.
197044
def calculate_sort_name_and_direction(user_params = {})
      default_column, default_direction = (configuration[:default_sort_order] || "updated_at:desc").split(":")
      sort_name, direction = user_params['order'].to_s.split(":")
      unless sort_name.present? && configuration[:sort_orders][sort_name]
        sort_name = default_column
        direction = default_direction
      end

      [sort_name, direction == 'desc' ? 'desc' : 'asc']
    end
896586
public function prepareOrderParam() {

        if (isset($this->request['order']) and ! empty($this->request['order'])) {
            $paramOrder = $this->request['order'];
            $returnOrder = Array();
            if (strlen($paramOrder) > 3) {
                if (is_int(strpos($paramOrder, "[")) and is_int(strpos($paramOrder, "]"))) {
                    $matches2 = $matches = null;
                    preg_match_all("/\[[^\]].*?\]/", $paramOrder, $matches, PREG_PATTERN_ORDER);
                    preg_match_all('/\=(.+)/s', $paramOrder, $matches2);
                    $returnOrder[0]['indexColumn'] = str_replace("]", '', str_replace("[", '', $matches[0][0]));
                    $returnOrder[0]['valueColumn'] = str_replace("=", '', $matches2[1][0]);
                }
            }
            return $returnOrder;
        } else {
            return null;
        }
    }
188714
function sortQueryresults(matches, order) {
  const orderArray = order.split(',').map(k => {
    let dir = 'asc';
    let key = k;

    if (k.charAt(0) === '-') {
      key = k.substring(1);
      dir = 'desc';
    }

    return [item => deserializeQueryParam(item[key]), dir];
  });

  const keys = orderArray.map(_.first);
  const orders = orderArray.map(_.last);

  return _.orderBy(matches, keys, orders);
}
1010768
def apply_ordering_to_scope(scope, user_params)
      sort_name, direction = calculate_sort_name_and_direction(user_params)
      order = configuration[:sort_orders].fetch(sort_name, {})[:value]

      ordered_scope = case order
        when Proc
          fresh_helper_instance.instance_exec(scope, direction, &order)
        when nil
          scope
        else
          scope.reorder(order.to_s + " " + direction)
      end

      fallback_deterministic_sort = assemble_primary_key_sort(scope)
      # Chain on a tiebreaker sort to ensure deterministic ordering of multiple pages of data

      if fallback_deterministic_sort
        ordered_scope.order(fallback_deterministic_sort)
      else
        ordered_scope
      end
    end
615723
def _filter_parameters(parameters):
    """"""
    if not parameters:
        return None
    return OrderedDict(
        (param, value) for param, value in six.iteritems(parameters) if param not in IGNORED_PARAMS
    )
477784
def validate(self, input_parameters, context):
        """"""
        errors = {}

        for key, type_handler in self.input_transformations.items():
            if self.raise_on_invalid:
                if key in input_parameters:
                    input_parameters[key] = self.initialize_handler(
                        type_handler,
                        input_parameters[key],
                        context=context
                    )
            else:
                try:
                    if key in input_parameters:
                        input_parameters[key] = self.initialize_handler(
                            type_handler,
                            input_parameters[key],
                            context=context
                        )
                except InvalidTypeData as error:
                    errors[key] = error.reasons or str(error.message)
                except Exception as error:
                    if hasattr(error, 'args') and error.args:
                        errors[key] = error.args[0]
                    else:
                        errors[key] = str(error)
        for require in self.required:
            if not require in input_parameters:
                errors[require] = "Required parameter '{}' not supplied".format(require)
        if not errors and getattr(self, 'validate_function', False):
            errors = self.validate_function(input_parameters)
        return errors
506980
public static void validate(OrderBy<?> orderBy,
                                ListExpressionValidation validation,
                                boolean ignoreUnknown) {
        if (orderBy == null) return;
        Iterator<Property> it = orderBy.getProperties().iterator();
        while (it.hasNext()) {
            validation.validate(it.next().getProperty());
            if (ignoreUnknown && !validation.lastValid()) {
                it.remove();
            }
        }
    }
206244
def _validated(self, data):
        """"""
        errors = []
        for sub in self.schemas:
            try:
                return sub(data)
            except NotValid as ex:
                errors.extend(ex.args)

        raise NotValid(' and '.join(errors))
883487
protected static function _normalizeParams(array &$params) {
		array_walk($params, function(&$value, $key) {
			if (!is_array($value)) {
				$value = array(
					'field' => $key,
					'direction' => $value
				);
			} elseif (is_array($value) && !isset($value['field'])) {
				$value['field'] = $key;
			}

			if (!empty($value['order'])) {
				$value['direction'] = $value['order'];
				unset($value['order']);
			}
		});
	}
1121130
def clean(self, value):
        """"""

        for parameter_obj in self.types:
            try:
                return parameter_obj.clean(value)
            except ParameterNotValidError:
                continue

        raise ParameterNotValidError
1456
def _post_clean(self):
        
        super(NgModelFormMixin, self)._post_clean()
        if self._errors and self.prefix:
            self._errors = ErrorDict((self.add_prefix(name), value) for name, value in self._errors.items())
984078
def sort_key_process(request, sort_key='sort'):
    
    current = request.GET.get(sort_key)
    current_reversed = False
    current_param = None
    if current:
        mo = re.match(r'^(-?)(\w+)$', current)    # exclude first "-" (if exist)
        if mo:
            current_reversed = mo.group(1) == '-'
            current_param = mo.group(2)

    return current_param, current_reversed
1230976
def order_items(params={})
      order_items = get("/orders/#{id}/order_items")
      if order_items
        order_items["order_items"].map { |data| FetchAppAPI::OrderItem.new(data) }
      end
    end
398643
def clean(self, value):
        """"""

        if isinstance(value, six.string_types):
            return value
        elif isinstance(value, numbers.Number):
            return str(value)

        raise ParameterNotValidError
65697
protected function sortParams(): void
    {
        $sorted = [];
        foreach ($this->params as $paramName => $paramSet) {
            if (0 != strlen($paramSet->prefix)) {
                $sorted[$paramName] = $paramSet;
            }
        }
        foreach ($this->params as $paramName => $paramSet) {
            if (0 == strlen($paramSet->prefix)) {
                $sorted[$paramName] = $paramSet;
            }
        }
        $this->params = $sorted;
    }
669529
def sort_order=(sort_order)
      validator = EnumAttributeValidator.new('String', ["DESC", "ASC"])
      unless validator.valid?(sort_order)
        fail ArgumentError, "invalid value for 'sort_order', must be one of #{validator.allowable_values}."
      end
      @sort_order = sort_order
    end
755188
def prepare_sorting_fields(self):
        
        if self.sorting_parameter_name in self.request.query_params:
            # Extract sorting parameter from query string
            self._sorting_fields = [
                _.strip() for _ in self.request.query_params.get(self.sorting_parameter_name).split(',')
            ]

        if self._sorting_fields:
            # Create a list of sorting parameters. Each parameter is a tuple: (field:str, descending:bool)
            self._sorting_fields = [
                (self.sorting_fields_map.get(field.lstrip('-'), field.lstrip('-')), field[0] == '-')
                for field in self._sorting_fields
            ]