Commit 1fca2fa7 authored by Arnaud Fontaine's avatar Arnaud Fontaine

py3: cmp()-based comparison and sorting have been dropped (!1751).

key()-based sorting is now used instead, available since Python 2.4.
parent 4bcf4fbc
......@@ -50,9 +50,6 @@ def display(x):
display_cache[x] = display_funct(x)
return display_cache[x]
def sort(x,y):
return cmp(display(x), display(y))
def getItemList(category=None, portal_path=None, mirror=0, omit_filter=0,
simulation_state=None):
"""Returns a list of Account path items. """
......@@ -71,7 +68,7 @@ def getItemList(category=None, portal_path=None, mirror=0, omit_filter=0,
portal_type='Account',
base=0,
display_method=display,
sort_method=sort,
sort_key=display,
filter=filter_dict)
return item_list
......
if not portal_type:
portal_type = context.getPortalObject().getPortalAccountingMovementTypeList()
sort_dict = { 'income': 0,
'expense': -2,
'receivable': -2,
'payable': 0,
'collected_vat': -1,
'refundable_vat': -1 }
sort_dict = {
'bank': -3,
'income': 0,
'expense': -2,
'receivable': -2,
'payable': 0,
'collected_vat': -1,
'refundable_vat': -1,
}
def getAccountingTransactionLineSortKey(line):
return sort_dict.get(line.getId(), line.getIntIndex() or line.getIntId())
return sort_dict.get(line.getId(), (line.getIntIndex() or line.getIntId() or 0))
return sorted(context.contentValues(portal_type=portal_type, checked_permission="View"), key=getAccountingTransactionLineSortKey)
......@@ -48,6 +48,13 @@ whether this is really required.
from erp5.component.document.MovementGroup import MovementGroup
def _getSign(quantity):
if quantity == 0:
return 0
return 1 if quantity > 0 else -1
class QuantitySignMovementGroup(MovementGroup):
"""
The purpose of MovementGroup is to define how movements are grouped,
......@@ -59,7 +66,7 @@ class QuantitySignMovementGroup(MovementGroup):
def _getPropertyDict(self, movement, **kw):
property_dict = {}
quantity = movement.getQuantity()
property_dict['quantity_sign'] = cmp(quantity, 0)
property_dict['quantity_sign'] = _getSign(quantity)
return property_dict
def _separate(self, movement_list, **kw):
......@@ -68,7 +75,7 @@ class QuantitySignMovementGroup(MovementGroup):
tmp_list = [[], [], []] # -1:minus, 0:zero, 1:plus
for movement in movement_list:
tmp_list[cmp(movement.getQuantity(), 0)].append(movement)
tmp_list[_getSign(movement.getQuantity())].append(movement)
if len(tmp_list[1]):
if len(tmp_list[-1]):
return[
......
......@@ -36,6 +36,7 @@ from erp5.component.document.Amount import Amount
from erp5.component.module.MovementGroup import MovementGroupNode
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
from Products.ERP5Type.Utils import OrderableKey
from erp5.component.module.ExplanationCache import _getExplanationCache
from DateTime import DateTime
from Acquisition import aq_parent, aq_inner
......@@ -781,15 +782,16 @@ class BuilderMixin(XMLObject, Amount, Predicate):
for i in self.getPortalObject().portal_categories.collect_order_group.contentValues():
category_index_dict[i.getId()] = i.getIntIndex()
def sort_movement_group(a, b):
return cmp(category_index_dict.get(a.getCollectOrderGroup()),
category_index_dict.get(b.getCollectOrderGroup())) or \
cmp(a.getIntIndex(), b.getIntIndex())
def sort_movement_group_key(a):
return (
OrderableKey(category_index_dict.get(a.getCollectOrderGroup())),
OrderableKey(a.getIntIndex()),
)
if portal_type is None:
portal_type = self.getPortalMovementGroupTypeList()
movement_group_list = [x for x in self.contentValues(filter={'portal_type': portal_type}) \
if collect_order_group is None or collect_order_group == x.getCollectOrderGroup()]
return sorted(movement_group_list, sort_movement_group)
return sorted(movement_group_list, key=sort_movement_group_key)
# XXX category name is hardcoded.
def getDeliveryMovementGroupList(self, **kw):
......
......@@ -24,8 +24,5 @@ else:
or career.getStopDate() < to_date :
career_list.append(career)
def date_cmp(a, b):
return cmp(a.getStartDate(), b.getStartDate())
career_list.sort(date_cmp)
career_list.sort(key=lambda a: a.getStartDate())
return career_list
......@@ -90,11 +90,7 @@ for portal_type in portal_type_list:
obj['total'] = line_counter
append(obj)
# sort lines
def cmpType(a, b):
return cmp(a['document_type'], b['document_type'])
line_list.sort(cmpType)
line_list.sort(key=lambda a:a['document_type'])
# build stat line
obj = Object(uid="new_")
......
......@@ -31,9 +31,6 @@ dest_event_list = portal.portal_catalog(portal_type=event_type_list, default_des
event_list = list(source_event_list)+list(dest_event_list)
def sortDate(a, b):
return cmp(a.getStartDate(), b.getStartDate())
event_list.sort(sortDate)
event_list.sort(key=lambda a: a.getStartDate())
return event_list
......@@ -68,6 +68,7 @@ for item in item_list:
else:
sub_field_dict[item_key]['title'] = base_category
sub_field_values = sub_field_dict.values()
sub_field_values.sort(key=lambda d:d['int_index'])
return sub_field_values
return sorted(
sub_field_dict.values(),
key=lambda d: d['int_index']
)
......@@ -68,10 +68,7 @@ for person in person_value_list:
total=person_total,
**result_dict))
result_list.sort(lambda a,b: cmp(
a.person_career_reference or a.person_title,
b.person_career_reference or b.person_title))
result_list.sort(key=lambda r: (r.person_career_reference or '', r.person_title or ''))
request.set('total_time', total_time)
request.set('total_time_per_resource', total_time_per_resource)
......
......@@ -3,7 +3,7 @@ column_item_list = [ ('person_career_reference', 'Employee Number'),
non_translatable_column_item_list = context\
.PersonModule_getLeaveRequestReportListboxUntranslatableColumnList()
non_translatable_column_item_list.sort(lambda a,b: cmp(a[1], b[1]))
non_translatable_column_item_list.sort(key=lambda v: v[1])
column_item_list.extend(non_translatable_column_item_list)
column_item_list.append(('total', 'Total'))
......
......@@ -552,12 +552,12 @@ class BusinessConfiguration(Item):
"immediateReindexObject"])
# build
configuration_save_list = self.contentValues(portal_type='Configuration Save')
configuration_save_list.sort(lambda x, y: cmp(x.getIntIndex(x.getIntId()),
y.getIntIndex(y.getIntId())))
configuration_save_list.sort(key=lambda x: (x.getIntIndex(x.getIntId()) or 0))
for configuration_save in configuration_save_list:
# XXX: check which items are configure-able
configuration_item_list = configuration_save.contentValues()
configuration_item_list.sort(lambda x, y: cmp(x.getIntId(), y.getIntId()))
configuration_item_list.sort(key=lambda x: (x.getIntId() or 0))
for configurator_item in configuration_item_list:
configurator_item.activate(**kw).fixConsistency(
filter={"constraint_type":"configuration"})
......
......@@ -267,7 +267,7 @@ class TestTrashTool(ERP5TypeTestCase):
bc_path = base_category.getPath().split('/')[2:-1]
# check backup
backup_subobjects_ids = trash.backupObject(trashbin, bc_path, bc_id, save=1)
self.assertTrue(backup_subobjects_ids.keys().sort() == list(subobjects_ids).sort())
self.assertEqual(sorted(backup_subobjects_ids.keys()), sorted(subobjects_ids))
def stepBackupFolderObjectsWithSave(self, sequence=None, sequence_list=None, **kw):
"""
......@@ -297,7 +297,7 @@ class TestTrashTool(ERP5TypeTestCase):
bc_path = base_category.getPath().split('/')[1:-1]
# check backup
backup_subobjects_ids = trash.backupObject(trashbin, bc_path, bc_id, save=0)
self.assertTrue(backup_subobjects_ids.keys().sort() == list(subobjects_ids).sort())
self.assertEqual(sorted(backup_subobjects_ids.keys()), sorted(subobjects_ids))
def stepBackupObjectsWithKeepingSubobjects(self, sequence=None, sequence_list=None, **kw):
"""
......@@ -359,8 +359,8 @@ class TestTrashTool(ERP5TypeTestCase):
def stepCheckRestore(self, sequence=None, sequence_list=None, **kw):
bc_id = sequence.get('bc_id')
bc = self.portal.portal_categories[bc_id]
self.assertTrue(
sorted(bc.objectIds()) == sorted(sequence.get('category_id_list'))
self.assertEqual(
sorted(bc.objectIds()), sorted(sequence.get('category_id_list'))
)
self.assertEqual(
len(
......
......@@ -92,11 +92,7 @@ for r_event in event_list:
unassigned_dic[event.getSimulationState()]=unassigned_dic[event.getSimulationState()]+1
unassigned_dic['total']=unassigned_dic['total']+1
#Sort the result and add unassigned
def comparator(x, y):
if x['ticket_type'] == y['ticket_type']:
return cmp(x['ticket_title'], y['ticket_title'])
return cmp(x['ticket_type'], y['ticket_type'])
column_list.sort(comparator)
column_list.sort(key=lambda x: (x['ticket_type'], x['ticket_title']))
if unassigned_dic['total']>0: column_list.append(unassigned_dic)
#fill line_list that is returned to report
line_list = []
......
......@@ -12,12 +12,9 @@ def getCompactTitle(category):
title_list.reverse()
return '/'.join(title_list)
def compareTitle(a, b):
return cmp(a[1], b[1])
def getCompactChildItemList(context):
result = context.getCategoryChildItemList(display_method=getCompactTitle)
result.sort(compareTitle)
result.sort(key=lambda x: x[1])
return result
from Products.ERP5Type.Cache import CachingMethod
......
......@@ -58,7 +58,7 @@ def getRssDataAsDict(context, url, username=None, password=None):
entry_dict['updated_parsed'] = entry.get('updated_parsed', None)
result['items'].append(entry_dict)
# sort by date
result['items'] = sorted(result['items'], key=lambda k: k['updated_parsed'])
result['items'] = sorted(result['items'], key=lambda k: k['updated_parsed'] or ())
result['items'].reverse()
result['status'] = 0
return result
\ No newline at end of file
......@@ -28,6 +28,7 @@
import unittest
from DateTime import DateTime
from Products.ERP5Type.Utils import OrderableKey
from erp5.component.test.testBPMCore import TestBPMMixin
from six.moves import range
import six
......@@ -341,18 +342,18 @@ class TestMRPImplementation(TestMRPMixin):
reference = None
movement_list.append((sm.getTradePhase(), sm.getQuantity(),
reference, sm.getIndustrialPhaseList()))
movement_list.sort()
self.assertEqual(movement_list, sorted((
('mrp/manufacturing_step_0', -10.0, None, []),
movement_list.sort(key=lambda x: [OrderableKey(e) for e in x])
self.assertEqual(movement_list, [
('mrp/manufacturing_step_0', -30.0, None, []),
('mrp/manufacturing_step_0', -10.0, None, []),
('mrp/manufacturing_step_0', 10.0,
'pr/mrp/manufacturing_step_0', ['trade_phase/mrp/manufacturing_step_0']),
('mrp/manufacturing_step_1', -40.0, None, []),
('mrp/manufacturing_step_1', -10.0, None, []),
('mrp/manufacturing_step_1', -10.0,
'cr/mrp/manufacturing_step_1', ['trade_phase/mrp/manufacturing_step_0']),
('mrp/manufacturing_step_1', -10.0, None, []),
('mrp/manufacturing_step_1', -40.0, None, []),
('mrp/manufacturing_step_1', 10.0, 'pr', []),
)))
])
order.confirm()
# Build Manufacturing Order
......
......@@ -16,6 +16,4 @@ for (x,y) in selection_param_list:
active_process_list = [(y,x) for (x,y) in active_process_dict.items()]
active_process_list.sort(lambda x, y: cmp(x[1],y[1]), reverse=True )
return active_process_list
return sorted(active_process_list, key=lambda item: item[1], reverse=True)
......@@ -17,7 +17,7 @@ if active_process_path is None:
active_process_value = context.getPortalObject().restrictedTraverse(active_process_path)
result_list = [[x.method_id, x.result] for x in active_process_value.getResultList()]
result_list.sort()
result_list.sort(key=str)
for [method_id, result] in result_list:
safe_id = context.Base_getSafeIdFromString('result %s' % num)
......
......@@ -58,13 +58,7 @@ for inventory in portal.portal_simulation.getInventoryList(
request.set('total_price', total_price)
def sort_method(a, b):
employee_career_reference_diff = cmp(a.employee_career_reference,
b.employee_career_reference)
if employee_career_reference_diff:
return employee_career_reference_diff
return cmp(a.employee_title, b.employee_title)
object_list.sort(sort_method)
return object_list
return sorted(
object_list,
key=lambda o: (o.employee_career_reference or '', o.employee_title)
)
......@@ -112,21 +112,14 @@ request.set('base_total', base_total)
request.set('total', total)
sorted_inventory_list = []
sorted_inventory_list = inventory_list.values()
# sort by salary range, and add intermediate sums if needed
def sort_method(a, b):
salary_range_diff = cmp(a.salary_range, b.salary_range)
if salary_range_diff:
return salary_range_diff
employee_career_reference_diff = cmp(a.employee_career_reference,
b.employee_career_reference)
if employee_career_reference_diff:
return employee_career_reference_diff
return cmp(a.employee_title, b.employee_title)
sorted_inventory_list.sort(sort_method)
sorted_inventory_list = sorted(
inventory_list.values(),
key=lambda i: (
i.salary_range or '',
i.employee_career_reference or '',
i.employee_title or '',
))
i = 0
intermediate_base_total = 0
......
......@@ -10,12 +10,9 @@ from Products.ERP5Type.Utils import cartesianProduct
from Products.ERP5Type.Utils import ensure_list
from Products.ERP5Type.Message import translateString
def sortByIntIndex(a, b):
return cmp(a.getIntIndex(), b.getIntIndex())
portal_type_list = ['Pay Sheet Model Line']
sub_object_list = context.getInheritedObjectValueList(portal_type_list)
sub_object_list.sort(sortByIntIndex)
sub_object_list.sort(key=lambda x:x.getIntIndex())
model_line_list = sub_object_list
# remove editable model line
......@@ -118,37 +115,16 @@ if batch_mode:
return object_dict_list
# sort results
def sortByTitleAscending(x, y):
return cmp(x.getTitle(), y.getTitle())
def sortByTitleDescending(x, y):
return cmp(y.getTitle(), x.getTitle())
def sortByIntIndexAscending(x, y):
return cmp(x.getIntIndex(), y.getIntIndex())
def sortByIntIndexDescending(x, y):
return cmp(y.getIntIndex(), x.getIntIndex())
sortByDefaultSortMethod = sortByIntIndexAscending
if 'sort_on' in kw:
sort_on = kw['sort_on']
if sort_on[0][0] == 'title' and sort_on[0][1]=='ascending':
line_list.sort(sortByTitleAscending)
elif sort_on[0][0] == 'title' and sort_on[0][1]=='descending':
line_list.sort(sortByTitleDescending)
elif sort_on[0][0] == 'int_index' and sort_on[0][1]=='ascending':
line_list.sort(sortByIntIndexAscending)
elif sort_on[0][0] == 'int_index' and sort_on[0][1]=='descending':
line_list.sort(sortByIntIndexDescending)
if sort_on[0][0] == 'title':
line_list = sorted(line_list, key=lambda x: x.getTitle() or '', reverse=sort_on[0][1]=='ascending')
elif sort_on[0][0] == 'int_index':
line_list = sorted(line_list, key=lambda x: x.getIntIndex() or 0, reverse=sort_on[0][1]=='ascending')
else:
line_list.sort(sortByDefaultSortMethod)
line_list = sorted(line_list, key=lambda x: x.getIntIndex())
else:
line_list.sort(sortByDefaultSortMethod)
line_list = sorted(line_list, key=lambda x: x.getIntIndex())
#return pprint.pformat(line_list)
return line_list
......@@ -120,38 +120,12 @@ for paysheet_line in paysheet_line_list:
if 'no_slice' in object_dict:
line_list.append(paysheet_line.asContext(**object_dict['no_slice']))
# sort results
def sortByTitleAscending(x, y):
return cmp(x.getTitle(), y.getTitle())
def sortByTitleDescending(x, y):
return cmp(y.getTitle(), x.getTitle())
def sortByIntIndexAscending(x, y):
return cmp(x.getIntIndex(), y.getIntIndex())
def sortByIntIndexDescending(x, y):
return cmp(y.getIntIndex(), x.getIntIndex())
sortByDefaultSortMethod = sortByIntIndexAscending
reverse = False
sort_key = lambda l: (l.getIntIndex() or 0)
if 'sort_on' in kw:
sort_on = kw['sort_on']
if sort_on[0][0] == 'title' and sort_on[0][1]=='ascending':
line_list.sort(sortByTitleAscending)
elif sort_on[0][0] == 'title' and sort_on[0][1]=='descending':
line_list.sort(sortByTitleDescending)
elif sort_on[0][0] == 'int_index' and sort_on[0][1]=='ascending':
line_list.sort(sortByIntIndexAscending)
elif sort_on[0][0] == 'int_index' and sort_on[0][1]=='descending':
line_list.sort(sortByIntIndexDescending)
else:
line_list.sort(sortByDefaultSortMethod)
else:
line_list.sort(sortByDefaultSortMethod)
reverse = sort_on[0][1]=='descending'
if sort_on[0][0] == 'title':
sort_key = lambda l: (l.getTitle() or '')
return line_list
return sorted(line_list, key=sort_key, reverse=reverse)
......@@ -41,9 +41,7 @@ if depth == 0:
category_list = []
#i = 1
month_dict_list = month_dict.keys()
month_dict_list.sort()
for year, month in month_dict_list:
for year, month in sorted(month_dict.keys()):
category_list.append(here.getObject().asContext(title="%s - %s" % (year, month),
string_index="%s-%s" % (year, month),
))
......
......@@ -24,12 +24,6 @@ task_line_list = []
for task in task_list:
task_line_list.extend(task.contentValues(portal_type='Task Line'))
def sortTaskLine(a, b):
result = cmp(a.getStartDate(), b.getStartDate())
if result == 0:
result = cmp(a.getTitle(), b.getTitle())
return result
task_line_list.sort(sortTaskLine)
return task_line_list
return sorted(
task_line_list,
key=lambda tl: (tl.hasStartDate(), tl.getStartDate(), tl.getTitle()))
......@@ -40,12 +40,6 @@ for task in task_list:
task_line_list.extend(task.objectValues(portal_type=('Task Line', 'Task Report Line')))
def sortTaskLine(a, b):
result = cmp(a.getStartDate(), b.getStartDate())
if result == 0:
result = cmp(a.getTitle(), b.getTitle())
return result
task_line_list.sort(sortTaskLine)
return task_line_list
return sorted(
task_line_list,
key=lambda tl: (tl.getStartDate() is not None, tl.getStartDate(), tl.getTitle()))
......@@ -101,8 +101,7 @@ class SolverProcess(XMLObject, ActiveProcess):
if solver is None:
continue
solver_conviguration_dict = decision.getConfigurationPropertyDict()
configuration_mapping = solver_conviguration_dict.items()
configuration_mapping.sort() # Make sure the list is sorted in canonical way
configuration_mapping = sorted(solver_conviguration_dict.items()) # Make sure the list is sorted in canonical way
configuration_mapping = tuple(configuration_mapping)
for movement in decision.getDeliveryValueList():
# Detect incompatibilities
......
......@@ -29,40 +29,37 @@ def rank_method(trade_condition):
if destination_section:
destination_section_group = trade_condition.getDestinationSectionValue().getGroup()
if destination_section == context.getDestinationSection():
rank += 10
rank -= 10
else:
rank -= 2
rank += 2
destination = trade_condition.getDestination()
if destination:
if destination == context.getDestination():
rank += 10
rank -= 10
else:
rank -= 2
rank += 2
if trade_condition.getSourceSection():
rank += 1
rank -= 1
if destination_section_group:
source_section_group = trade_condition.getSourceSectionValue().getGroup()
if source_section_group:
if source_section_group.startswith(destination_section_group) \
or destination_section_group.startswith(source_section_group):
# trade conditions where both sections are in the same group must have high priority
rank += 20
rank -= 20
if trade_condition.getSource():
rank += 1
rank += len(trade_condition.getSpecialiseList())
rank -= 1
rank -= len(trade_condition.getSpecialiseList())
if trade_condition.getValidationState() == 'validated':
rank += 2
rank -= 2
return rank
def sort_method(a, b):
return -cmp(rank_method(a), rank_method(b))
while count > 0 and len(trade_condition_list) == 0:
count -= 1
trade_condition_list = context.portal_domains.searchPredicateList(
predicate_context, portal_type=trade_condition_portal_type_list,
tested_base_category_list=tested_base_category_list[:count],
sort_method=sort_method)
sort_key_method=rank_method)
keep_items = {}
if len(trade_condition_list ) == 0 :
......
......@@ -57,8 +57,6 @@ if active_process_path:
else:
raise ValueError("No active process found to process report")
def sortProduct(a, b):
return cmp(a['product'], b['product'])
period_counter_dict = {}
line_list = []
......@@ -132,7 +130,7 @@ if len(client_dict):
product_lines_list.append(obj)
# sort product list
product_lines_list.sort(sortProduct)
product_lines_list.sort(key=lambda p: p['product'])
extend(product_lines_list)
else:
# products
......@@ -169,7 +167,8 @@ else:
period_counter_dict['total amount'] = line_total_amount
append(obj)
line_list.sort(sortProduct)
line_list.sort(key=lambda p: p['product'])
obj = Object(uid="new_")
obj["client"] = 'Total'
......
......@@ -23,13 +23,10 @@ full_total_price = 0
worker_column_list = []
source_trade_dict = {}
def sortMovement(a, b):
return cmp(a.getRelativeUrl(), b.getRelativeUrl())
movement_type_list = context.getPortalMovementTypeList()
line_list = [x for x in context.getIndexableChildValueList() if x.getPortalType() in \
movement_type_list]
line_list.sort(sortMovement)
line_