def _custom_sorter(self, key1, key2): """Custom virtual columns sorter.""" col = self._col ascending = self._colSortFlag[col] real = self.get_real_col(col) item1 = self.itemDataMap[key1][real] item2 = self.itemDataMap[key2][real] # Internationalization of string sorting with locale module if isinstance(item1, str) and isinstance(item2, str): cmpVal = locale.strcoll(item1, item2) elif isinstance(item1, bytes) or isinstance(item2, bytes): cmpVal = locale.strcoll(str(item1), str(item2)) else: cmpVal = cmp(item1, item2) # If the items are equal, then pick something else to make the sort value unique if cmpVal == 0: cmpVal = cmp(*self.GetSecondarySortValues(col, key1, key2)) if ascending: return cmpVal else: return -cmpVal
def _compare_cities(city_xlated1, city_xlated2): """Compare two paris of cities and their translations.""" # if there are "cities" ending with numbers (like GMT+-X), we need to sort # them based on their numbers val1 = city_xlated1[1] val2 = city_xlated2[1] match1 = SPLIT_NUMBER_SUFFIX_RE.match(val1) match2 = SPLIT_NUMBER_SUFFIX_RE.match(val2) if match1 is None and match2 is None: # no +-X suffix, just compare the strings return locale_mod.strcoll(val1, val2) if match1 is None or match2 is None: # one with the +-X suffix, compare the prefixes if match1: prefix, _sign, _suffix = match1.groups() return locale_mod.strcoll(prefix, val2) else: prefix, _sign, _suffix = match2.groups() return locale_mod.strcoll(val1, prefix) # both have the +-X suffix prefix1, sign1, suffix1 = match1.groups() prefix2, sign2, suffix2 = match2.groups() if prefix1 == prefix2: # same prefixes, let signs determine return cmp(int(sign1 + suffix1), int(sign2 + suffix2)) else: # compare prefixes return locale_mod.strcoll(prefix1, prefix2)
def __ColumnSorter(self, key1, key2): col = self._col ascending = self._colSortFlag[col] item1 = self.itemDataMap[key1][col] item2 = self.itemDataMap[key2][col] #--- Internationalization of string sorting with locale module if isinstance(item1, six.text_type) and isinstance(item2, six.text_type): # both are unicode (py2) or str (py3) cmpVal = locale.strcoll(item1, item2) elif isinstance(item1, six.binary_type) or isinstance(item2, six.binary_type): # at least one is a str (py2) or byte (py3) cmpVal = locale.strcoll(str(item1), str(item2)) else: cmpVal = cmp(item1, item2) #--- # If the items are equal then pick something else to make the sort value unique if cmpVal == 0: cmpVal = cmp(*self.GetSecondarySortValues(col, key1, key2)) if ascending: return cmpVal else: return -cmpVal
def print_sorted(): pos1 = 0 pos2 = 0 # compare lines in each list and print to the right column while pos1 < len(lines1) and pos2 < len(lines2): if locale.strcoll(lines1[pos1], lines2[pos2]) == 0: if options.print_both: print(col3delimiter + lines1[pos1]) pos1 += 1 pos2 += 1 elif locale.strcoll(lines1[pos1], lines2[pos2]) > 0: if options.print_file_2: print(col2delimiter + lines2[pos2]) pos2 += 1 else: if options.print_file_1: print(lines1[pos1]) pos1 += 1 # print any remaining lines if pos1 < len(lines1) and options.print_file_1: for i in range(pos1, len(lines1)): print(lines1[i]) if pos2 < len(lines2) and options.print_file_2: for i in range(pos2, len(lines2)): print(lines2[i])
def compareSorted(self, suppress1, suppress2, suppress3): i = 0 j = 0 while i < len(self.lines1) and j < len(self.lines2): a = 0 b = 0 # if the line from FILE1 collates before FILE2, we print the line # from FILE1 and move to the next line in FILE1 if locale.strcoll(self.lines1[i], self.lines2[j]) < 0: self.printCol(self.lines1[i], 1, suppress1, suppress2, suppress3) i = i + 1 elif locale.strcoll(self.lines1[i], self.lines2[j]) > 0: self.printCol(self.lines2[j], 2, suppress1, suppress2, suppress3) j = j + 1 else: self.printCol(self.lines2[j], 3, suppress1, suppress2, suppress3) i = i + 1 j = j + 1 while i < len(self.lines1): self.printCol(self.lines1[i], 1, suppress1, suppress2, suppress3) i = i + 1 while j < len(self.lines2): self.printCol(self.lines2[j], 2, suppress1, suppress2, suppress3) j = j + 1
def test_strcoll(self): self.assertLess(locale.strcoll('a', 'b'), 0) self.assertEqual(locale.strcoll('a', 'a'), 0) self.assertGreater(locale.strcoll('b', 'a'), 0) # embedded null character self.assertRaises(ValueError, locale.strcoll, 'a\0', 'a') self.assertRaises(ValueError, locale.strcoll, 'a', 'a\0')
def __ColumnSorterRev(self, key1, key2):#copy from ColumnSorterMixin.__ColumnSorter col = self._col ascending = self._colSortFlag[col] item1 = self.itemDataMap[key1][col] item2 = self.itemDataMap[key2][col] #rev begin item1 = self.__revpath(item1) item2 = self.__revpath(item2) #rev end #--- Internationalization of string sorting with locale module if type(item1) == unicode and type(item2) == unicode: cmpVal = locale.strcoll(item1, item2) elif type(item1) == str or type(item2) == str: cmpVal = locale.strcoll(str(item1), str(item2)) else: cmpVal = cmp(item1, item2) #--- # If the items are equal then pick something else to make the sort value unique if cmpVal == 0: cmpVal = apply(cmp, self.GetSecondarySortValues(col, key1, key2)) if ascending: return cmpVal else: return -cmpVal
def __cmp__(self, other): try: if not locale.strcoll (self.label, other.label): return 0 else: return locale.strcoll (self.label, other.label) except: return - 1
def __init__(self): gtk.ListStore.__init__(self, int, str, str, float, bool, bool, str) self.db = DB.getInstance() self.set_sort_func(0, lambda m,i1,i2:locale.strcoll(str(m.get_value(i1,1)),str(m.get_value(i2,1)))) self.set_sort_func(1, lambda m,i1,i2:locale.strcoll(str(m.get_value(i1,2)),str(m.get_value(i2,2)))) self.set_sort_func(2, lambda m,i1,i2:cmp(int(m.get_value(i1,3)),int(m.get_value(i2,3)))) self.set_sort_func(3, lambda m,i1,i2:cmp(int(m.get_value(i1,4)),int(m.get_value(i2,4)))) self.set_sort_func(4, lambda m,i1,i2:cmp(int(m.get_value(i1,5)),int(m.get_value(i2,5)))) self.set_sort_column_id(0, gtk.SORT_ASCENDING) self.refresh()
def __cmp__(self, other): #Monthly hours attribute is excluded, because this #attribute varies form month to month try: if not locale.strcoll(self.label, other.label): return cmp (self.weekly_hours, other.weekly_hours) else: return locale.strcoll(self.label, other.label) except: return - 1
def apps_cmp(x, y): """ sort method for the applications """ # sort(key=locale.strxfrm) would be more efficient, but its # currently broken, see http://bugs.python.org/issue2481 if x.appname and y.appname: return locale.strcoll(x.appname, y.appname) elif x.appname: return locale.strcoll(x.appname, y.pkgname) elif y.appname: return locale.strcoll(x.pkgname, y.appname) else: return cmp(x.pkgname, y.pkgname)
def sort_konk(a, b): # Wir nehmen das Original zum sortieren (also das Tuple) a = a[1] b = b[1] if sort == 'rechts': return locale.strcoll(a[2], b[2]) elif sort == 'links': a, b = a[0].split(), b[0].split() if len(a) == 0: a.insert(0, ' ') if len(b) == 0: b.insert(0, ' ') return locale.strcoll(a[-1], b[-1]) else: return locale.strcoll(a[1], b[1])
def alusort(x, y): """ Método para ordenar los alumnos correctamente. Como usa la misma implementación del COLLATE para es_ES.UTF-8 (de la libc) que PostgreSQL hemos tenido que hacer un truco: sustituimos los espacios por otro caracter. El 0 parece funcionar correctamente. """ alux = x['alumno'] aluy = y['alumno'] repl = lambda x: x.replace(u'Á', 'A').replace(u'É', 'E').replace(u'Í', 'I').replace(u'Ó', 'O').replace(u'Ú', 'U').replace(' ', '0') res = locale.strcoll(repl(alux.persona.apellidos), repl(aluy.persona.apellidos)) if res != 0: return res res = locale.strcoll(repl(alux.persona.nombre), repl(aluy.persona.nombre)) return res
def strcoll(self, left, right): ml = min(len(left), len(right)) for i in xrange(ml): lv = 0 if left[i].islower(): lv = 1 rv = 0 if right[i].islower(): rv = 1 comp = lv - rv if comp != 0: return comp comp = locale.strcoll(left[i].lower(), right[i].lower()) if comp != 0: return comp if len(right) > ml: return 1 if len(left) > ml: return -1 return 0
def view_logs(): available_logs = [] for log in logs.get_available(): try: stat = os.stat(log.filename) except OSError: logger.warning("Could not stat %s, removing from available logs", log.filename) logs.remove_available(log.filename) continue dt = datetime.fromtimestamp(stat.st_atime) last_access = dt.strftime("%Y-%m-%d %H:%M:%S") dt = datetime.fromtimestamp(stat.st_mtime) last_modification = dt.strftime("%Y-%m-%d %H:%M:%S") available_logs.append({ "filename": log.filename, "size": stat.st_size, "last_access": last_access, "last_modification": last_modification }) available_logs.sort( cmp=lambda x1, x2: locale.strcoll(x1["filename"], x2["filename"])) return render_template("logs.html", page="logs", logs=available_logs, is_xhr=request.is_xhr)
def __sort_func(self, row_a, row_b): """ Sort rows @param row_a as SelectionListRow @param row_b as SelectionListRow """ a_index = row_a.id b_index = row_b.id # Static vs static if a_index < 0 and b_index < 0: return a_index < b_index # Static entries always on top elif b_index < 0: return True # Static entries always on top if a_index < 0: return False # String comparaison for non static else: if self.mask & SelectionListMask.ARTISTS: a = row_a.sortname b = row_b.sortname else: a = row_a.name b = row_b.name return strcoll(a, b)
def __sort_tags(self, child1, child2): """ Sort tags @param child1 as TagWidget @param child2 as TagWidget """ return strcoll(child1.label, child2.label)
def __ColumnSorter(self, itemData1, itemData2): """Allows custom compare functions, in self.colcmps.""" col = self._col ascending = self._colSortFlag[col] if col < len(self.enabled_columns): name = self.enabled_columns[col] else: name = self.column_order[0] itemData1 = self.TranslateItemData(itemData1) itemData2 = self.TranslateItemData(itemData2) item1 = self.itemData_to_row[itemData1][name] item2 = self.itemData_to_row[itemData2][name] column = self.columns[name] if column.comparator != None: # use custom cmp method cmpVal = column.comparator(item1, item2) elif isinstance(item1, str) or isinstance(item2, str): # Internationalization of string sorting with locale module cmpVal = locale.strcoll(unicode(item1), unicode(item2)) else: cmpVal = cmp(item1, item2) # If the items are equal then pick something else to make the sort value unique if cmpVal == 0: cmpVal = apply( cmp, self.GetSecondarySortValues(col, itemData1, itemData2)) if ascending: return cmpVal else: return -cmpVal
def __sort_items(self, model, itera, iterb, data): """ Sort model """ if self.__populating: return False a_index = model.get_value(itera, 0) b_index = model.get_value(iterb, 0) # Static vs static if a_index < 0 and b_index < 0: return a_index < b_index # Static entries always on top elif b_index < 0: return True # Static entries always on top if a_index < 0: return False # String comparaison for non static else: if self.__mask & SelectionListMask.ARTISTS: a = App().artists.get_sortname(a_index) b = App().artists.get_sortname(b_index) else: a = model.get_value(itera, 1) b = model.get_value(iterb, 1) return strcoll(a, b)
def __sort_items(self, model, itera, iterb, data): """ Sort model """ if not self.__updating: return False a_index = model.get_value(itera, 0) b_index = model.get_value(iterb, 0) # Static vs static if a_index < 0 and b_index < 0: return a_index < b_index # Static entries always on top elif b_index < 0: return True # Static entries always on top if a_index < 0: return False # String comparaison for non static else: if self.__is_artists: a = Lp().artists.get_sortname(a_index) b = Lp().artists.get_sortname(b_index) else: a = model.get_value(itera, 1) b = model.get_value(iterb, 1) return strcoll(a, b)
def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 # Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves merge_sort(L) # Sorting the first half merge_sort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if locale.strcoll(L[i][0], R[j][0]) < 0: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1
def projects_browse(request, project_set): """Page listing all projects""" items = [ make_project_list_item(project) for project in project_set.children ] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) table_fields = [ 'name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity' ] table = { 'id': 'projects', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items, } ctx = get_browser_context(request) ctx.update({ 'table': table, 'stats': jsonify(request.resource_obj.get_stats()), 'browser_extends': 'projects/all/base.html', }) response = render(request, 'browser/index.html', ctx) response.set_cookie('pootle-language', 'projects') return response
def __by_value(self, first, second): """ Method for sorting keys based on the values. """ fvalue = self.mapping[first] svalue = self.mapping[second] return locale.strcoll(fvalue, svalue)
def fill_tree_ctrl(self, root, tree): # print 'sorted:', [x.name for x in sorted(self.sublabels, cmp=lambda x,y: locale.strcoll(x.name, y.name))] for sub in sorted(self.sublabels, cmp=lambda x, y: locale.strcoll(x.name, y.name)): # print sub.name.encode('utf-8') newroot = tree.AppendItem(root, sub.name) sub.fill_tree_ctrl(newroot, tree)
def main(): # 在不同会话中重复这些操作会看到一些差别,系统非常清楚地指定了不同的区域.货币使用了合适的符号 # 并且日期和时间与UK版本有很大的区别. print(loc.setlocale(loc.LC_ALL, "")) # print(loc.currency(350)) # 这一句报错了 print(time.strftime("%x %X", time.localtime())) # 示例显示了字符串格式化指定器是如何同时为整数和浮点数工作的. print("{:n}".format(3.14159)) print("{:n}".format(42)) # locale.strcoll()字符串比较示例是非常有用的,因为它们在字符排序中采用了特定于区域的想法. # 如果第一个字符串有更"高"的值,返回值就是1,更低则返回-1,如果两个参数相同,则返回0 print(loc.strcoll("Spanish", "Inquisition")) print(loc.strcoll("Inquisition", "Spanish")) print(loc.strcoll("Spanish", "Spanish"))
def sort(self, column, sort_ascending=None): """ Sorts the internal container. Does not return anything. column: which column to use for sorting: if it is lower than 0, the elements are ordered in their natural order, if it is larger than the number of columns or None, no sorting is performed. sort_ascending: will sort ascending if set to true, descending if set to false. If it is set to none, the sorting order will be determined automatically """ if column == None: self.column = None self.sort_ascending = None return if sort_ascending == None: if column == None: self.sort_ascending = None elif self.column != column: self.sort_ascending = True else: self.sort_ascending = not self.sort_ascending else: self.sort_ascending = sort_ascending self.column = column if self.column < 0: self.elements.sort(reverse= not self.sort_ascending) elif self.column < len (self.data_class.HEADERS) and len (self.data_class.HEADERS): el = self.elements[0].as_data_list( )[self.column] #locale aware sorting if isinstance(el, str) or isinstance(el, unicode): self.elements.sort(cmp=lambda x, y: locale.strcoll(x.as_data_list()[self.column], y.as_data_list()[self.column]), reverse=not self.sort_ascending) else: self.elements.sort(cmp=lambda x, y: cmp(x.as_data_list()[self.column], y.as_data_list()[self.column]), reverse=not self.sort_ascending)
def projects_browse(request, project_set): """Page listing all projects""" items = [make_project_list_item(project) for project in project_set.children] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) table_fields = ['name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity'] table = { 'id': 'projects', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items, } ctx = get_browser_context(request) ctx.update({ 'table': table, 'stats': jsonify(request.resource_obj.get_stats()), 'browser_extends': 'projects/all/base.html', }) response = render(request, 'browser/index.html', ctx) response.set_cookie('pootle-language', 'projects') return response
def utSortObjsByLocaleAttr(self, p_list, p_attr, p_desc=1, p_locale=''): """Sort a list of objects by an attribute values based on locale""" if not p_locale: #normal sorting l_len = len(p_list) l_temp = map(None, map(getattr, p_list, (p_attr,)*l_len), xrange(l_len), p_list) l_temp.sort() if p_desc: l_temp.reverse() return map(operator.getitem, l_temp, (-1,)*l_len) else: #locale sorting based try: default_locale = locale.setlocale(locale.LC_ALL) try: #try to set for NT, WIN operating systems locale.setlocale(locale.LC_ALL, p_locale) except: #try to set for other operating system if p_locale == 'ar': p_locale = 'ar_DZ' else: p_locale = '%s_%s' % (p_locale, p_locale.upper()) locale.setlocale(locale.LC_ALL, p_locale) #sorting l_len = len(p_list) l_temp = map(None, map(getattr, p_list, (p_attr,)*l_len), xrange(l_len), p_list) l_temp.sort(lambda x, y: locale.strcoll(x[0], y[0])) if p_desc: l_temp.reverse() locale.setlocale(locale.LC_ALL, default_locale) return map(operator.getitem, l_temp, (-1,)*l_len) except: #in case of failure make a normal sorting locale.setlocale(locale.LC_ALL, default_locale) return self.utSortObjsByLocaleAttr(p_list, p_attr, p_desc)
def custom_compare(item1, item2): first_dash = item1[u"Cod"].find(u"-") second_dash = item1[u"Cod"].find(u"-", first_dash+1) p1 = item1[u"Cod"][first_dash+1:second_dash] first_dash = item2[u"Cod"].find(u"-") second_dash = item2[u"Cod"].find(u"-", first_dash+1) p2 = item2[u"Cod"][first_dash+1:second_dash] roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'IV': 4} if roman_numerals[p1] <> roman_numerals[p2]: return (roman_numerals[p1] < roman_numerals[p2]) if item1[u"Localitate"].find(u"muncipiul [[Sibiu") > -1 and \ item2[u"Localitate"].find(u"muncipiul [[Sibiu") == -1: return -1 if item1[u"Localitate"].find(u"muncipiul [[Sibiu") == -1 and \ item2[u"Localitate"].find(u"muncipiul [[Sibiu") > -1: return 1 cmp_village = locale.strcoll(item1[u"Localitate"], item2[u"Localitate"]) if cmp_village: return cmp_village last_dash = item1[u"Cod"].rfind(u"-") l1 = item1[u"Cod"][last_dash+1:] last_dash = item2[u"Cod"].rfind(u"-") l2 = item2[u"Cod"][last_dash+1:] return l1 < l2
def __ColumnSorter(self, itemData1, itemData2): """Allows custom compare functions, in self.colcmps.""" col = self._col ascending = self._colSortFlag[col] if col < len(self.enabled_columns): name = self.enabled_columns[col] else: name = self.column_order[0] itemData1 = self.TranslateItemData(itemData1) itemData2 = self.TranslateItemData(itemData2) item1 = self.itemData_to_row[itemData1][name] item2 = self.itemData_to_row[itemData2][name] column = self.columns[name] if column.comparator != None: # use custom cmp method cmpVal = column.comparator(item1, item2) elif isinstance(item1, str) or isinstance(item2, str): # Internationalization of string sorting with locale module cmpVal = locale.strcoll(unicode(item1), unicode(item2)) else: cmpVal = cmp(item1, item2) # If the items are equal then pick something else to make the sort value unique if cmpVal == 0: cmpVal = apply(cmp, self.GetSecondarySortValues(col, itemData1, itemData2)) if ascending: return cmpVal else: return -cmpVal
def get_items(request, model, get_last_action, name_func): items = [] if not check_permission('view', request): return items for item in model.iterator(): stats = item.getquickstats() stats = add_percentages(stats) lastact = get_last_action(item) items.append({ 'code': item.code, 'name': name_func(item.fullname), 'lastactivity': lastact, 'trans': stats["translatedsourcewords"], 'fuzzy': stats["fuzzysourcewords"], 'untrans': stats["untranslatedsourcewords"], 'total': stats["totalsourcewords"], 'transper': stats["translatedpercentage"], 'fuzzyper': stats["fuzzypercentage"], 'untransper': stats["untranslatedpercentage"], 'completed_title': _("%(percentage)d%% complete", {'percentage': stats['translatedpercentage']}), }) items.sort(lambda x, y: locale.strcoll(x['name'], y['name'])) return items
def get_items(request, model, get_last_action, name_func): items = [] if not check_permission('view', request): return items for item in model.objects.iterator(): stats = get_raw_stats(item) translated_percentage = stats['translated']['percentage'] items.append({ 'code': item.code, 'name': name_func(item.fullname), 'lastactivity': get_last_action(item), 'stats': stats, 'completed_title': _("%(percentage)d%% complete", {'percentage': translated_percentage}), }) items.sort(lambda x, y: locale.strcoll(x['name'], y['name'])) return items
def _sort_items(self, model, itera, iterb, data): """ Sort model """ if not self._updating: return False a_index = model.get_value(itera, 0) b_index = model.get_value(iterb, 0) # Static vs static if a_index < 0 and b_index < 0: return a_index < b_index # Static entries always on top elif b_index < 0: return True # Static entries always on top if a_index < 0: return False # String comparaison for non static else: if self._is_artists: a = Lp().artists.get_sortname(a_index) b = Lp().artists.get_sortname(b_index) else: a = model.get_value(itera, 1) b = model.get_value(iterb, 1) return strcoll(a, b)
def compare(self, sort): if sort == True: self.line1 = sorted(self.line1, key=locale.strxfrm) self.line2 = sorted(self.line2, key=locale.strxfrm) x = 0 while x < len(self.line1) and x < len(self.line2): cmp = locale.strcoll(self.line1[x], self.line2[x]) if cmp == 0: self.line3.append(self.line1[x]) self.line1[x] = space self.line2[x] = space elif cmp > 0: self.line1.insert(x, space) self.line3.append(space) else: self.line2.insert(x, space) self.line3.append(space) x += 1 if len(self.line1) > len(self.line3): y = len(self.line3) while y < len(self.line1): self.line3.append(space) self.line2.append(space) y += 1 elif len(self.line2) > len(self.line3): y = len(self.line3) while y < len(self.line2): self.line3.append(space) self.line1.append(space) y += 1
def get_items(request, model, get_last_action, name_func): items = [] if not check_permission("view", request): return items for item in model.objects.iterator(): stats = item.getquickstats() stats = add_percentages(stats) items.append( { "code": item.code, "name": name_func(item.fullname), "lastactivity": get_last_action(item), "trans": stats["translatedsourcewords"], "fuzzy": stats["fuzzysourcewords"], "untrans": stats["untranslatedsourcewords"], "total": stats["totalsourcewords"], "transper": stats["translatedpercentage"], "fuzzyper": stats["fuzzypercentage"], "untransper": stats["untranslatedpercentage"], "completed_title": _("%(percentage)d%% complete", {"percentage": stats["translatedpercentage"]}), } ) items.sort(lambda x, y: locale.strcoll(x["name"], y["name"])) return items
def __set_members(self): showhidden = self.__hidden_check.get_property('active') self.__members_model.clear() for name,member in sorted(inspect.getmembers(self.__obj), lambda a,b: locale.strcoll(a[0],b[0])): if not showhidden and name.startswith('_'): continue self.__members_model.append((name, member))
def humanize_street_list(self, sl): # We transform the string representing the squares list into a # Python list sl = [( street[0], [ map(int, x.split(',')) for x in street[1].split(';')[:-1] ] ) for street in sl] # Street prefixes are postfixed, a human readable label is # built to represent the list of squares, and the list is # alphabetically-sorted. prev_locale = locale.getlocale(locale.LC_COLLATE) locale.setlocale(locale.LC_COLLATE, self.i18n.language_code()) def _humanize_street_label(street): return (self.i18n.user_readable_street(street[0]), _user_readable_label(street[1])) try: sl = sorted(map(_humanize_street_label, sl), lambda x, y: locale.strcoll(x[0].lower(), y[0].lower())) finally: locale.setlocale(locale.LC_COLLATE, prev_locale) # Add the first letter of the street name as category sl = [(street[0][0], street[0], street[1]) for street in sl] return sl
def project_language_index(request, project_code): """page listing all languages added to project""" project = get_object_or_404(Project, code=project_code) request.permissions = get_matching_permissions(get_profile(request.user), project.directory) if not check_permission('view', request): raise PermissionDenied translation_projects = project.translationproject_set.all() items = [make_language_item(request, translation_project) for translation_project in translation_projects.iterator()] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) languagecount = len(translation_projects) totals = add_percentages(project.getquickstats()) average = totals['translatedpercentage'] topstats = gentopstats_project(project) templatevars = { 'project': { 'code': project.code, 'name': project.fullname, 'stats': ungettext('%(languages)d language, %(average)d%% translated', '%(languages)d languages, %(average)d%% translated', languagecount, {"languages": languagecount, "average": average}), }, 'description': project.description, 'adminlink': _('Admin'), 'languages': items, 'instancetitle': pagelayout.get_title(), 'topstats': topstats, 'statsheadings': get_stats_headings(), 'translationlegend': {'translated': _('Translations are complete'), 'fuzzy': _('Translations need to be checked (they are marked fuzzy)'), 'untranslated': _('Untranslated')}, } return render_to_response('project/project.html', templatevars, context_instance=RequestContext(request))
def test_message_5502(self): sort_index = random.randint(0, len(request_5502.fields) - 1) request_5502.sort_field = request_5502.fields[sort_index] request_5502.sort_method = message.SORT_ORDER_DESC m = self.client.send_and_receive(request_5502) self.assertEqual(m.msg_id, request_5502.msg_id) self.assertEqual(m.pid, request_5502.pid) self.assertEqual(m.fields, request_5502.fields) data = m.data for i in range(len(data) - 1): v, next_v = data[i][sort_index], data[i+1][sort_index] if isinstance(v, str): if sys.platform[0:5] != 'win32': locale.setlocale(locale.LC_COLLATE, 'zh_CN.GBK') self.assertGreaterEqual(locale.strcoll(v, next_v), 0) else: # not worked (python3.5 windows7) # locale.setlocale(locale.LC_COLLATE, ".936") # self.assertGreaterEqual(locale.strcoll(v, next_v), 0) pass else: # require as little as possible for the class, so we do not # use assertGreaterEqual to express v >= next_v self.assertFalse(v < next_v) locale.setlocale(locale.LC_COLLATE, '')
def view_logs(): available_logs = [] for log in logs.get_available(): try: stat = os.stat(log.filename) except OSError: logger.warning("Could not stat %s, removing from available logs", log.filename) logs.remove_available(log.filename) continue dt = datetime.fromtimestamp(stat.st_atime) last_access = dt.strftime("%Y-%m-%d %H:%M:%S") dt = datetime.fromtimestamp(stat.st_mtime) last_modification = dt.strftime("%Y-%m-%d %H:%M:%S") available_logs.append({ "filename": log.filename, "size": stat.st_size, "last_access": last_access, "last_modification": last_modification }) available_logs.sort(cmp=lambda x1, x2: locale.strcoll(x1["filename"], x2["filename"])) return render_template( "logs.html", page="logs", logs=available_logs, is_xhr=request.is_xhr )
def by_value(self, first, second): """ Method for sorting keys based on the values. """ fvalue = self.mapping[first] svalue = self.mapping[second] return locale.strcoll(fvalue, svalue)
def _update(self): logging.debug('Update the cloud') self.journal.save_old_day() def cmp_words((word1, _freq1), (word2, _freq2)): # TODO: Use key=locale.strxfrm in python3 return locale.strcoll(word1, word2)
def browse(request, project, dir_path, filename): """Languages browser for a given project.""" item_func = (make_xlanguage_item if dir_path or filename else make_language_item) items = [item_func(item) for item in request.resource_obj.get_children_for_user(request.profile)] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) table_fields = ['name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity'] table = { 'id': 'project', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items, } ctx = get_browser_context(request) ctx.update({ 'project': project, 'table': table, 'stats': jsonify(request.resource_obj.get_stats()), 'browser_extends': 'projects/base.html', }) return render(request, 'browser/index.html', ctx)
def default(self, o): name_repr = {} for name, member in sorted(inspect.getmembers(o), lambda a, b: locale.strcoll(a[0], b[0])): if name.startswith('_'): continue name_repr[name] = str(type(member)) return self.encode(name_repr)
def _rank_comparison(self, team1, team2): """Comparison for sorting by points, or by team name if points are tied.""" points1 = self.teams[team1] points2 = self.teams[team2] if points1 == points2: return locale.strcoll(team1, team2) else: return 1 if points1 < points2 else -1
def items(self): items = [ make_project_list_item(project) for project in self.object.children] items.sort( lambda x, y: locale.strcoll(x['title'], y['title'])) return items
def view_logs(): available_logs = current_service.get_logs() available_logs.sort( cmp=lambda x1, x2: locale.strcoll(x1['path'], x2['path'])) return render_template('logs.html', page='logs', logs=available_logs, is_xhr=request.is_xhr)
def __set_members(self): showhidden = self.__hidden_check.get_property('active') self.__members_model.clear() for name, member in sorted(inspect.getmembers(self.__obj), lambda a, b: locale.strcoll(a[0], b[0])): if not showhidden and name.startswith('_'): continue self.__members_model.append((name, member))
def custom_strcoll(a, b, last=sentinel): """strcoll that can handle a sentinel that is always last.""" if a is last: return 0 if a is b else 1 elif b is last: # a cannot also be sentinel b/c above logic return -1 else: # neither are sentinel return strcoll(a, b)
def test_view_projects_browse(client, request_users): user = request_users["user"] client.login(username=user.username, password=request_users["password"]) response = client.get(reverse("pootle-projects-browse")) assert response.cookies["pootle-language"].value == "projects" ctx = response.context request = response.wsgi_request user_projects = Project.accessible_by_user(request.user) user_projects = (Project.objects.for_user( request.user).filter(code__in=user_projects)) obj = ProjectSet(user_projects) items = [make_project_list_item(project) for project in obj.children] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) stats = obj.data_tool.get_stats(user=request.user) for item in items: if item["code"] in stats["children"]: item["stats"] = stats["children"][item["code"]] table_fields = [ 'name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity' ] table = { 'id': 'projects', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items } if request.user.is_superuser: url_action_continue = obj.get_translate_url(state='incomplete') url_action_fixcritical = obj.get_critical_url() url_action_review = obj.get_translate_url(state='suggestions') url_action_view_all = obj.get_translate_url(state='all') else: (url_action_continue, url_action_fixcritical, url_action_review, url_action_view_all) = [None] * 4 checks = ChecksDisplay(obj).checks_by_category stats = StatsDisplay(obj, stats=stats).stats del stats["children"] User = get_user_model() top_scorers = User.top_scorers(limit=10) assertions = dict(page="browse", pootle_path="/projects/", resource_path="", resource_path_parts=[], object=obj, table=table, browser_extends="projects/all/base.html", top_scorers=top_scorers, top_scorers_data=get_top_scorers_data(top_scorers, 10), translation_states=get_translation_states(obj), url_action_continue=url_action_continue, url_action_fixcritical=url_action_fixcritical, url_action_review=url_action_review, url_action_view_all=url_action_view_all, checks=checks, stats=stats) view_context_test(ctx, **assertions)
def _test_browse_view(project, request, response, kwargs): cookie_data = json.loads( unquote(response.cookies[SIDEBAR_COOKIE_NAME].value)) assert cookie_data["foo"] == "bar" assert "announcements_projects_%s" % project.code in cookie_data ctx = response.context kwargs["project_code"] = project.code resource_path = ("%(dir_path)s%(filename)s" % kwargs) project_path = ("%s/%s" % (kwargs["project_code"], resource_path)) if not (kwargs["dir_path"] or kwargs["filename"]): ob = project elif not kwargs["filename"]: ob = ProjectResource(Directory.objects.live().filter( pootle_path__regex="^/.*/%s$" % project_path), pootle_path="/projects/%s" % project_path) else: ob = ProjectResource(Store.objects.live().filter( pootle_path__regex="^/.*/%s$" % project_path), pootle_path="/projects/%s" % project_path) item_func = (make_xlanguage_item if (kwargs["dir_path"] or kwargs["filename"]) else make_language_item) items = [ item_func(item) for item in ob.get_children_for_user(request.user) ] items.sort(lambda x, y: locale.strcoll(x['title'], y['title'])) table_fields = [ 'name', 'progress', 'total', 'need-translation', 'suggestions', 'critical', 'last-updated', 'activity' ] table = { 'id': 'project', 'fields': table_fields, 'headings': get_table_headings(table_fields), 'items': items } assertions = dict( page="browse", project=project, browser_extends="projects/base.html", pootle_path="/projects/%s" % project_path, resource_path=resource_path, resource_path_parts=get_path_parts(resource_path), url_action_continue=ob.get_translate_url(state='incomplete'), url_action_fixcritical=ob.get_critical_url(), url_action_review=ob.get_translate_url(state='suggestions'), url_action_view_all=ob.get_translate_url(state='all'), translation_states=get_translation_states(ob), check_categories=get_qualitycheck_schema(ob), table=table, stats=jsonify(ob.get_stats())) sidebar = get_sidebar_announcements_context(request, (project, )) for k in ["has_sidebar", "is_sidebar_open", "announcements"]: assertions[k] = sidebar[0][k] view_context_test(ctx, **assertions)
def getCustomerWhoBought(array, category): arrayCategory = [] for i in range(0, len(array)): for j in range(0, len(array[i]["products"])): if locale.strcoll(array[i]['products'][j]["category"], category) == 0: arrayCategory.append(array[i]) return arrayCategory
def str_nocase_sort(model, iter1, iter2, data): """ Sort string column data with locale.strcoll which (allegedly) uses ISO 14651. """ v1 = model[iter1][data].lower() v2 = model[iter2][data].lower() return strcoll(v1, v2)
def column_compare(a, b): prefix = { 'pk': '0', 'fk': '1', } return locale.strcoll( prefix.get(a[2], '2') + a[1], prefix.get(b[2], '2') + b[1], )
def isInAlphabeticalOrder(list, marketCode): locale.setlocale(locale.LC_ALL, marketCode) current = list[0] for next in list[1:]: if locale.strcoll(current, next) == 1: return False current = next return True
def testSorted2(self): i = 0 while i < len(self.lines2): if i > 0: a = i - 1 if locale.strcoll(self.lines2[i], self.lines2[a]) < 0: return False i = i + 1 return True
def compare_records(a1, a2): for field in fields: f1 = a1.get(field) f2 = a2.get(field) if f1 and f2: compare_result = locale.strcoll(a1[field], a2[field]) if compare_result: return compare_result return 0
def sortedOutput(self): i, j = 0, 0 output = '' while i < len(self.lines1) and j < len(self.lines2): if locale.strcoll(self.lines1[i], self.lines2[j]) == 0: if self.sup3 == False: if self.sup1 == True and self.sup2 == True: output = output + self.lines1[i] + '\n' elif self.sup1 == False and self.sup2 == False: output = output + '\t\t' + self.lines1[i] + '\n' else: output = output + '\t' + self.lines1[i] + '\n' self.lines1 = self.lines1[1:] self.lines2 = self.lines2[1:] elif locale.strcoll(self.lines1[i], self.lines2[j]) < 0: if self.lines1[i] not in self.lines2: if self.sup1 == False: output = output + self.lines1[i] + '\n' self.lines1 = self.lines1[1:] elif locale.strcoll(self.lines1[i], self.lines2[j]) > 0: if self.lines2[j] not in self.lines1: if self.sup2 == False: if self.sup1 == False: output = output + '\t' + self.lines2[j] + '\n' else: output = output + self.lines2[j] + '\n' self.lines2 = self.lines2[1:] if len(self.lines1) > 0: if self.sup1 == False: for line1 in self.lines1: output = output + line1 + '\n' if len(self.lines2) > 0: if self.sup2 == False: if self.sup1 == False: for line2 in self.lines2: output = output + '\t' + line2 + '\n' else: for line2 in self.lines2: output = output + line2 + '\n' return output
def _compare_cities(city_xlated1, city_xlated2): """Compare two paris of cities and their translations.""" # if there are "cities" ending with numbers (like GMT+-X), we need to sort # them based on their numbers val1 = city_xlated1[1] val2 = city_xlated2[1] match1 = SPLIT_NUMBER_SUFFIX_RE.match(val1) match2 = SPLIT_NUMBER_SUFFIX_RE.match(val2) if match1 is None and match2 is None: # no +-X suffix, just compare the strings return locale_mod.strcoll(val1, val2) if match1 is None or match2 is None: # one with the +-X suffix, compare the prefixes if match1: prefix, _sign, _suffix = match1.groups() return locale_mod.strcoll(prefix, val2) else: prefix, _sign, _suffix = match2.groups() return locale_mod.strcoll(val1, prefix) # both have the +-X suffix prefix1, sign1, suffix1 = match1.groups() prefix2, sign2, suffix2 = match2.groups() if prefix1 == prefix2: # same prefixes, let signs determine def _cmp(a, b): if a < b: return -1 elif a > b: return 1 else: return 0 return _cmp(int(sign1 + suffix1), int(sign2 + suffix2)) else: # compare prefixes return locale_mod.strcoll(prefix1, prefix2)