>>> sort_key(('name', ('ROUTE', 'URL')))
    -3
162010
def sort_key(x):
    
    name, (r, u) = x
    return - len(u) + u.count('}') * 100
153462
def sort_by_key(self, keys=None):
        
        keys = keys or self.key_on
        keys = keys if isinstance(keys, (list, tuple)) else [keys]
        for key in reversed(keys):
            reverse, key = (True, key[1:]) if key[0] == '-' else (False, key)
            self.table.sort(key=lambda row: row[key], reverse=reverse)
1340334
def sort_url(sort_on)
      url_params = @@params.clone
      if url_params.has_key? TableBuilder.params_sort_table
        if url_params[TableBuilder.params_sort_table].has_key? sort_on
          url_params[TableBuilder.params_sort_table][sort_on] = inverse_sorting(sort_on)
          return url_for(url_params)
        end
        url_params[TableBuilder.params_sort_table].delete sort_on
      end
      url_params[TableBuilder.params_sort_table] = { sort_on => :asc }
      url_for(url_params)
    end
297346
def order_by(self, key):
        
        if key is None:
            raise NullArgumentError(u"No key for sorting given")
        kf = [OrderingDirection(key, reverse=False)]
        return SortedEnumerable3(kf, self._data)
756524
def p_route(self, p):
        """"""
        p[0] = AstRouteDef(self.path, p.lineno(1), p.lexpos(1), p[2], p[3], p[5], *p[4])
        if len(p) > 7:
            p[0].set_doc(p[8])
            if p[9]:
                keys = set()
                for attr in p[9]:
                    if attr.name in keys:
                        msg = "Attribute '%s' defined more than once." % attr.name
                        self.errors.append((msg, attr.lineno, attr.path))
                    keys.add(attr.name)
                p[0].set_attrs(p[9])
80900
def sort(self, key, *get_patterns,
             by=None, offset=None, count=None,
             asc=None, alpha=False, store=None):
        """"""
        args = []
        if by is not None:
            args += [b'BY', by]
        if offset is not None and count is not None:
            args += [b'LIMIT', offset, count]
        if get_patterns:
            args += sum(([b'GET', pattern] for pattern in get_patterns), [])
        if asc is not None:
            args += [asc is True and b'ASC' or b'DESC']
        if alpha:
            args += [b'ALPHA']
        if store is not None:
            args += [b'STORE', store]
        return self.execute(b'SORT', key, *args)
1333573
def sort_order(options = {})
      [[prefix, last].compact.join(' '), suffix, options[:initials] ? initials : first].compact.join(', ')
    end
472447
def result_sort_key(response_item):
    
    code, snippet = response_item

    snippet_length = len(snippet)
    freq = search_freq.get(code, 0)
    beta = 0.05
    score = math.log(freq * 0.05 + 1) / (snippet_length + 1)

    return score
924339
def order_by(self, sort_key=None):
        
        if sort_key is not None:
            sort_attr = re.match(r'(-)?(.*)$', sort_key).group(2)
            if sort_attr not in self._valid_sort_attrs:
                raise ClientValidationError("Invalid ordering attribute: %s" % sort_key)

        q = self._clone()
        q._order_by = sort_key
        return q
1339755
def route(route_str):  # decorator param
    

    def ilog(elapsed):
        # statistic
        last_stat = _routes_stat.get(route_str, {"count": 0, "min": sys.maxint, "max": 0, "avg": 0})
        last_count = last_stat["count"]
        _routes_stat[route_str] = {
            "count": last_count + 1,
            "min": min(elapsed, last_stat["min"]),
            "max": max(elapsed, last_stat["max"]),
            "avg": (last_count * last_stat["avg"] + elapsed) / (last_count + 1)
        }
        # log.debug('Route Time: {0} took {1} ms'.format(route_str, elapsed))

    def wrapper(f):  # decorated function
        @wraps(f)
        def wrapped_func(*args, **kwargs):  # params of function
            self = args[0]
            method, url = route_str.split(" ")

            def defaults_dict():
                f_args, varargs, keywords, defaults = inspect.getargspec(f)
                defaults = defaults or []
                return dict(zip(f_args[-len(defaults):], defaults))

            defs = defaults_dict()

            route_args = dict(defs.items() + kwargs.items())

            def get_destination_url():
                try:
                    return url.format(**route_args)
                except KeyError as e:
                    # KeyError in format have a message with key
                    raise AttributeError("Define {0} as named argument for route.".format(e))

            destination_url = self.base_url + get_destination_url()
            f(*args, **kwargs)  # generally this is "pass"

            bypass_args = dict([
                                   (param, route_args[param]) for param in
                                   ["data", "json", "cookies", "auth", "files", "content_type", "params"] if
                                   param in route_args
                                   ])

            # add json content type for:
            # - unless files are sent
            # - private that ends with .json
            # - all public api with POST/PUT method, meaning have basic auth
            # - json parameter is present
            if "files" not in bypass_args and (destination_url.endswith('.json') or "json" in route_args or (
                            "auth" in bypass_args and method in ["POST", "PUT"])):
                bypass_args['headers'] = {'Content-Type': 'application/json'}

            if "content_type" in bypass_args and bypass_args['content_type'] == "yaml":
                del bypass_args["content_type"]
                bypass_args['headers'] = {'Content-Type': 'application/x-yaml'}

            start = time.time()
            try:
                response = self._session.request(method, destination_url, verify=self.verify_ssl, **bypass_args)
            except requests.ConnectionError:
                log.info('ConnectionError caught. Trying again: \n %s:%s ' % (method, destination_url))
                import traceback
                def log_exception(exc_class, exc, tb):
                    log.info('Got exception: %s' % exc)
                    log.info('Class: %s' % exc_class)
                    log.info('Trace: %s' % traceback.format_tb(tb))
                    log.error('Got exception while executing: %s' % exc)

                log_exception(*sys.exc_info())
                time.sleep(2)
                response = self._session.request(method, destination_url, verify=self.verify_ssl, **bypass_args)

            end = time.time()
            elapsed = int((end - start) * 1000.0)
            ilog(elapsed)

            if self.verify_codes:
                if response.status_code is not 200:
                    msg = "Route {0} {1} returned code={2} and error: {3}".format(method,
                                                                                  get_destination_url(),
                                                                                  response.status_code,
                                                                                  response.text)
                    if response.status_code in api_http_code_errors.keys():
                        raise api_http_code_errors[response.status_code](msg)
                    else:
                        log.debug(response.text)
                        log.debug(response.request.body)
                        raise ApiError(msg)
            return response

        return wrapped_func

    return wrapper
1207406
protected function sortRoutes()
    {
        //TODO store the first preordering set in cache, it need to order just one time
        $routes = array();
        foreach ($this->routes as $i => $item) {
            $this->routes[$i]['patCount'] = count(explode('/', $item->getPattern()));
            $this->routes[$i]['reqCount'] = count($item->getRequirements());
            $this->routes[$i]['varCount'] = count($item->getVars());
            $this->routes[$i]['pop'] = trim(array_pop(explode('/', $item->getPattern())));
        }

        $list = $this->routes;
        // first, order by separator number '/'
        usort($list, function ($a, $b)
        {
            if ($b['patCount'] == $a['patCount']) {
                return 0;
            }

            return $b['patCount'] < $a['patCount'] ? 1 : -1;
        });

        $n = count($list);
        for ($i = 1; $i < $n; $i++) {
            $j= $i - 1;
            while (
                $j>=0 && $list[$j]['patCount'] == $list[$i]['patCount'] &&
                $list[$j]['varCount'] > $list[$i]['varCount']
            ) {
                $this->swapValues($list[$j+1],$list[$j]);
                $j--;
            }
        }

        for ($i = 1; $i < $n; $i++) {
            $j= $i - 1;
            while (
                $j>=0 && $list[$j]['patCount'] == $list[$i]['patCount'] &&
                $list[$j]['varCount'] >= $list[$i]['varCount'] && $list[$j]['reqCount'] < $list[$i]['reqCount']
            ) {
                $this->swapValues($list[$j+1],$list[$j]);
                $j--;
            }
        }

        $this->routes = $list;
    }
293003
def _route(self, attr, args, kwargs, **fkwargs):
        
        return self.cluster.hosts.keys()
127416
def handle_json_GET_routes(self, params):
    """"""
    schedule = self.server.schedule
    result = []
    for r in schedule.GetRouteList():
      result.append( (r.route_id, r.route_short_name, r.route_long_name) )
    result.sort(key = lambda x: x[1:3])
    return result
905952
def sort(key=None, reverse=False, buffersize=None):
    

    return SortComponent(key=key, reverse=reverse, buffersize=buffersize)
235897
def _get_order_by(self, request):
        
        attr = request.params.get('sort', request.params.get('order_by'))
        if attr is None or not hasattr(self.mapped_class, attr):
            return None
        if request.params.get('dir', '').upper() == 'DESC':
            return desc(getattr(self.mapped_class, attr))
        else:
            return asc(getattr(self.mapped_class, attr))
436228
def _recSortKey(r):
        
        return r.seqname, r.start, -r.end, r.type
962643
def p_jsonpath_sort(self, p):
        "'"
        sort = _iterable.SortedThis(p[3])
        p[0] = jsonpath_rw.Child(p[1], sort)