Callback for uasort() that implements correct
locale-aware case-sensitive sorting
6669
protected function sort_folder_comparator($str1, $str2)
    {
        if ($this->sort_folder_collator === null) {
            $this->sort_folder_collator = false;

            // strcoll() does not work with UTF8 locale on Windows,
            // use Collator from the intl extension
            if (stripos(PHP_OS, 'win') === 0 && function_exists('collator_compare')) {
                $locale = $this->options['language'] ?: 'en_US';
                $this->sort_folder_collator = collator_create($locale) ?: false;
            }
        }

        $path1 = explode($this->delimiter, $str1);
        $path2 = explode($this->delimiter, $str2);

        foreach ($path1 as $idx => $folder1) {
            $folder2 = $path2[$idx];

            if ($folder1 === $folder2) {
                continue;
            }

            if ($this->sort_folder_collator) {
                return collator_compare($this->sort_folder_collator, $folder1, $folder2);
            }

            return strcoll($folder1, $folder2);
        }
    }
298637
function orderBy(array, sortPredicate, reverseOrder) {
  if (!isArrayLike(array)) {
    return array;
  }
  sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  sortPredicate = sortPredicate.map(function(predicate) {
    var descending = false;
    var get = predicate || value;
    if (isString(predicate)) {
      if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
        descending = predicate.charAt(0) == '-';
        predicate = predicate.substring(1);
      }
      if (predicate === '') {
        // Effectively no predicate was passed so we compare identity
        return reverseComparator(function(a, b) {
          return compare(a, b);
        }, descending);
      }
      get = $parse(predicate);
      if (get.constant) {
        var key = get();
        return reverseComparator(function(a, b) {
          return compare(a[key], b[key]);
        }, descending);
      }
    }
    return reverseComparator(function(a, b) {
      return compare(get(a),get(b));
    }, descending);
  });
  var arrayCopy = [];
  for (var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  return arrayCopy.sort(reverseComparator(comparator, reverseOrder));

  function comparator(o1, o2) {
    for (var i = 0; i < sortPredicate.length; i++) {
      var comp = sortPredicate[i](o1, o2);
      if (comp !== 0) break;
    }
    return comp;
  }
  function reverseComparator(comp, descending) {
    return descending
      ? function(a, b) {return comp(b,a);}
      : comp;
  }
  function compare(v1, v2) {
    var t1 = typeof v1;
    var t2 = typeof v2;
    if (t1 == t2) {
      if (isDate(v1) && isDate(v2)) {
        v1 = v1.valueOf();
        v2 = v2.valueOf();
      }
      if (t1 == "string") {
        v1 = v1.toLowerCase();
        v2 = v2.toLowerCase();
      }
      if (v1 === v2) return 0;
      return v1 < v2 ? -1 : 1;
    } else {
      return t1 < t2 ? -1 : 1;
    }
  }
}
159954
function sortJapanese(a, b) {
        a = normalize(a);
        b = normalize(b);
        if (a < b) {
            return -1;
        }
        if (a > b) {
            return 1;
        }
        return 0;
    }
1059348
function SortOrderComparator(sortOrder, options) {
        this.sortOrder = sortOrder;
        this.options = {
            casesensitive: false
        };
        if (options) {
            _.extend(this.options, options);
        }
        this.expressions = new Array(sortOrder.sortFields.length);
        for (var i = 0; i < this.expressions.length; ++i) {
            this.expressions[i] = new JsonPath_1.JsonPath(sortOrder.sortFields[i].name);
        }
    }
176751
function lookup(locale, format, obj) {
  if (!locale) throw new Error('missing required "locale" parameter');
  locale = locale.toLowerCase().replace('-', '_');
  format = format || 'cardinal';
  var p = obj[format];
  if (!p) throw new Error('unsupported format "' + format + '"');
  var fn = p[locale] || p[locale.split('_')[0]];
  if (fn) return fn;

  throw new Error('unsupported locale "' + locale + '"');
}
1075141
private static TreeMap<Double ,Set<String>> sortScoreMap(TreeMap<String, Double> scoreMap)
    {
        TreeMap<Double, Set<String>> result = new TreeMap<Double, Set<String>>(Collections.reverseOrder());
        for (Map.Entry<String, Double> entry : scoreMap.entrySet())
        {
            Set<String> sentenceSet = result.get(entry.getValue());
            if (sentenceSet == null)
            {
                sentenceSet = new HashSet<String>();
                result.put(entry.getValue(), sentenceSet);
            }
            sentenceSet.add(entry.getKey());
        }

        return result;
    }
80962
def sorted_nicely(l):
    
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(l, key = alphanum_key)
1008527
protected void updateLocaleNodeSorting() {

        // check if the locale nodes require sorting
        List<Locale> locales = new ArrayList<Locale>(m_locales);
        Collections.sort(locales, new Comparator<Locale>() {

            public int compare(Locale o1, Locale o2) {

                return o1.toString().compareTo(o2.toString());
            }
        });
        List<Element> localeNodes = new ArrayList<Element>(m_document.getRootElement().elements());
        boolean sortRequired = false;
        if (localeNodes.size() != locales.size()) {
            sortRequired = true;
        } else {
            int i = 0;
            for (Element el : localeNodes) {
                if (!locales.get(i).toString().equals(el.attributeValue("language"))) {
                    sortRequired = true;
                    break;
                }
                i++;
            }
        }

        if (sortRequired) {
            // do the actual node sorting, by removing the nodes first
            for (Element el : localeNodes) {
                m_document.getRootElement().remove(el);
            }

            Collections.sort(localeNodes, new Comparator<Object>() {

                public int compare(Object o1, Object o2) {

                    String locale1 = ((Element)o1).attributeValue("language");
                    String locale2 = ((Element)o2).attributeValue("language");
                    return locale1.compareTo(locale2);
                }
            });
            // re-adding the nodes in alphabetical order
            for (Element el : localeNodes) {
                m_document.getRootElement().add(el);
            }
        }
    }
720680
def sort(self, attribut, order=False):
        
        value_default = formats.ASSOCIATION[attribut][3]

        if type(value_default) is str:  # case insensitive sort
            get = lambda d : (d[attribut] or value_default).casefold()
        elif type(value_default) is dict: #can't sort dicts
            def get(d):
                u = d[attribut] or value_default
                return [str(u[i]) for i in sorted(u.keys())]
        else:
            get = lambda d : d[attribut] or value_default

        list.sort(self, key=get, reverse=order)
846389
function shortBubbleSort(array, comparatorFn) {
  const comparator = new Comparator(comparatorFn);
  const length = array.length - 1;
  let i = 0;

  for (i; i < length; i++) {
    const current = array[i];
    const next = array[i + 1];

    /**
     * If the current value if greater than the next:
     * - set current value to next value;
     * - and set next value to current value;
     * - then reset iterator counter to rescan for values to be sorted.
     */

    if (comparator.greaterThan(current, next)) {
      array[i + 1] = current;
      array[i] = next;
      i = -1;
    }
  }

  return array;
}
843809
def case_stmt_handle(self, loc, tokens):
        """"""
        if len(tokens) == 2:
            item, cases = tokens
            default = None
        elif len(tokens) == 3:
            item, cases, default = tokens
        else:
            raise CoconutInternalException("invalid case tokens", tokens)
        check_var = case_check_var + "_" + str(self.case_check_count)
        self.case_check_count += 1
        out = (
            match_to_var + " = " + item + "\n"
            + match_case_tokens(loc, cases[0], check_var, True)
        )
        for case in cases[1:]:
            out += (
                "if not " + check_var + ":\n" + openindent
                + match_case_tokens(loc, case, check_var, False) + closeindent
            )
        if default is not None:
            out += "if not " + check_var + default
        return out
395116
function(a, b) {
		var self = elFinder.prototype.naturalCompare;
		if (typeof self.loc == 'undefined') {
			self.loc = (navigator.userLanguage || navigator.browserLanguage || navigator.language || 'en-US');
		}
		if (typeof self.sort == 'undefined') {
			if ('11'.localeCompare('2', self.loc, {numeric: true}) > 0) {
				// Native support
				if (window.Intl && window.Intl.Collator) {
					self.sort = new Intl.Collator(self.loc, {numeric: true}).compare;
				} else {
					self.sort = function(a, b) {
						return a.localeCompare(b, self.loc, {numeric: true});
					};
				}
			} else {
				/*
				 * Edited for elFinder (emulates localeCompare() by numeric) by Naoki Sawada aka nao-pon
				 */
				/*
				 * Huddle/javascript-natural-sort (https://github.com/Huddle/javascript-natural-sort)
				 */
				/*
				 * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
				 * Author: Jim Palmer (based on chunking idea from Dave Koelle)
				 * http://opensource.org/licenses/mit-license.php
				 */
				self.sort = function(a, b) {
					var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
					sre = /(^[ ]*|[ ]*$)/g,
					dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
					hre = /^0x[0-9a-f]+$/i,
					ore = /^0/,
					syre = /^[\x01\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]/, // symbol first - (Naoki Sawada)
					i = function(s) { return self.sort.insensitive && (''+s).toLowerCase() || ''+s; },
					// convert all to strings strip whitespace
					// first character is "_", it's smallest - (Naoki Sawada)
					x = i(a).replace(sre, '').replace(/^_/, "\x01") || '',
					y = i(b).replace(sre, '').replace(/^_/, "\x01") || '',
					// chunk/tokenize
					xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
					yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
					// numeric, hex or date detection
					xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
					yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null,
					oFxNcL, oFyNcL,
					locRes = 0;

					// first try and sort Hex codes or Dates
					if (yD) {
						if ( xD < yD ) return -1;
						else if ( xD > yD ) return 1;
					}
					// natural sorting through split numeric strings and default strings
					for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {

						// find floats not starting with '0', string or 0 if not defined (Clint Priest)
						oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
						oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;

						// handle numeric vs string comparison - number < string - (Kyle Adams)
						// but symbol first < number - (Naoki Sawada)
						if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
							if (isNaN(oFxNcL) && (typeof oFxNcL !== 'string' || ! oFxNcL.match(syre))) {
								return 1;
							} else if (typeof oFyNcL !== 'string' || ! oFyNcL.match(syre)) {
								return -1;
							}
						}

						// use decimal number comparison if either value is string zero
						if (parseInt(oFxNcL, 10) === 0) oFxNcL = 0;
						if (parseInt(oFyNcL, 10) === 0) oFyNcL = 0;

						// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
						if (typeof oFxNcL !== typeof oFyNcL) {
							oFxNcL += '';
							oFyNcL += '';
						}

						// use locale sensitive sort for strings when case insensitive
						// note: localeCompare interleaves uppercase with lowercase (e.g. A,a,B,b)
						if (self.sort.insensitive && typeof oFxNcL === 'string' && typeof oFyNcL === 'string') {
							locRes = oFxNcL.localeCompare(oFyNcL, self.loc);
							if (locRes !== 0) return locRes;
						}

						if (oFxNcL < oFyNcL) return -1;
						if (oFxNcL > oFyNcL) return 1;
					}
					return 0;
				};
				self.sort.insensitive = true;
			}
		}
		return self.sort(a, b);
	}
732137
def auto_sort(parser, token):
    ""
    try:
        tag_name, queryset = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("{0} tag requires a single argument".format(token.contents.split()[0]))
    return SortedQuerysetNode(queryset)
808810
private static void checkSorted(int[] sorted) {
    for (int i = 0; i < sorted.length-1; i++) {
      if (sorted[i] > sorted[i+1]) {
        throw new RuntimeException("input must be sorted!");
      }
    }
  }
346934
function compareValue(aVal, bVal) {
  var cmp, i, collate;
  if (isString(aVal) && isString(bVal)) {
    collate = _arrayOptions('sortCollate');
    return collate(aVal, bVal);
  } else if (isArray(aVal) && isArray(bVal)) {
    if (aVal.length < bVal.length) {
      return -1;
    } else if (aVal.length > bVal.length) {
      return 1;
    } else {
      for(i = 0; i < aVal.length; i++) {
        cmp = compareValue(aVal[i], bVal[i]);
        if (cmp !== 0) {
          return cmp;
        }
      }
      return 0;
    }
  }
  return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
}
1021127
function typedArrayToUnicodeString(ua) {
    var binstr = Array.prototype.map.call(ua, function (ch) {
        return String.fromCharCode(ch);
    }).join('');
    var escstr = binstr.replace(/(.)/g, function (m, p) {
        var code = p.charCodeAt(p).toString(16).toUpperCase();
        if (code.length < 2) {
            code = '0' + code;
        }
        return '%' + code;
    });
    return decodeURIComponent(escstr);
}
1178823
private static void partialSort(
      final WordIterator[] a,
      final int maxChangedIndex,
      final int size,
      final Comparator<WordIterator> comp
  )
  {
    for (int i = maxChangedIndex; i >= 0; i--) {
      WordIterator it = a[i];
      for (int j = i + 1; j < size; j++) {
        WordIterator it2 = a[j];
        if (comp.compare(it, it2) <= 0) {
          break;
        }
        a[j - 1] = it2;
        a[j] = it;
      }
    }
  }