Commit ce0fc93f authored by Kazuhiko Shiozaki's avatar Kazuhiko Shiozaki Committed by Jérome Perrin

py2/py3: modernize -f dict_six.

parent 42301657
from Products.ZSQLCatalog.SQLCatalog import SimpleQuery
from Products.PythonScripts.standard import Object
from ZTUtils import LazyFilter
import six
portal = context.getPortalObject()
portal_categories = portal.portal_categories
......@@ -42,7 +43,7 @@ src_list = []
def getInventoryList(node_uid=None, **kw):
if not node_uid and node_uid is not None:
return []
for key, value in inventory_params.iteritems():
for key, value in six.iteritems(inventory_params):
assert key not in kw, key
kw[key] = value
result = getInventoryList_(
......@@ -632,7 +633,7 @@ def getPaymentTitleFromUid(uid):
return title
line_list = []
for key, data in line_per_account.iteritems():
for key, data in six.iteritems(line_per_account):
node_relative_url = key[0]
mirror_section_uid = key[1]
payment_uid = key[2]
......
......@@ -9,6 +9,7 @@ What is expected with this script:
- In reality we probably also want that amount on vat line match invoice vat
amount, but we have ignored this.
"""
import six
line_list = context.getMovementList(
portal_type=context.getPortalAccountingMovementTypeList())
......@@ -41,7 +42,7 @@ receivable_type = account_type.asset.receivable
payable_type = account_type.liability.payable
asset_line = None
for line, account_type_list in account_type_dict.iteritems():
for line, account_type_list in six.iteritems(account_type_dict):
if receivable_type in account_type_list or payable_type in account_type_list:
if line.getSourceSection() == context.getSourceSection() and \
line.getDestinationSection() == context.getDestinationSection():
......
......@@ -6,6 +6,7 @@ from zExceptions import ExceptionFormatter, Unauthorized
from Products.CMFActivity.ActiveResult import ActiveResult
from zLOG import LOG, INFO
import six
def dumpWorkflowChain(self, ignore_default=False,
ignore_id_set=None, keep_order=False, batch_mode=False):
......@@ -92,7 +93,7 @@ def MessageCatalog_getMessageDict(self):
Get Localizer's MessageCatalog instance messages.
"""
d = {}
for k,v in self._messages.iteritems():
for k,v in six.iteritems(self._messages):
d[k] = v
return d
......@@ -102,7 +103,7 @@ def MessageCatalog_getNotTranslatedMessageDict(self):
"""
not_translated_message_dict = {}
messages = MessageCatalog_getMessageDict(self)
for k, v in messages.iteritems():
for k, v in six.iteritems(messages):
if not [x for x in v.values() if x]:
not_translated_message_dict[k] = v
return not_translated_message_dict
......
......@@ -60,7 +60,7 @@ mode_dict = {
}
if mode not in mode_dict:
return "Used Mode is not defined in the mode list %s" % mode_dict.keys()
return "Used Mode is not defined in the mode list %s" % list(mode_dict.keys())
# Check JSON Form
try:
......
......@@ -33,6 +33,7 @@ from Products.ERP5Type import Permissions, PropertySheet
from erp5.component.mixin.BuilderMixin import BuilderMixin
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
from Products.ERP5Type.CopySupport import CopyError, tryMethodCallWithTemporaryPermission
import six
class SimulatedDeliveryBuilder(BuilderMixin):
......@@ -202,7 +203,7 @@ class SimulatedDeliveryBuilder(BuilderMixin):
if property_dict in (None, {}):
return
delivery = self.getPortalObject().restrictedTraverse(delivery_relative_url)
for (prop, value) in property_dict.iteritems():
for (prop, value) in six.iteritems(property_dict):
delivery.setPropertyList(prop, value)
# Try to remove existing properties/categories from Movements that
......
......@@ -39,6 +39,7 @@ from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
from erp5.component.module.ExplanationCache import _getExplanationCache
from DateTime import DateTime
from Acquisition import aq_parent, aq_inner
import six
class CollectError(Exception): pass
class MatrixError(Exception): pass
......@@ -334,7 +335,7 @@ class BuilderMixin(XMLObject, Amount, Predicate):
edit_order = []
property_dict = {'edit_order': edit_order}
for d in property_dict_list:
for k,v in d.iteritems():
for k,v in six.iteritems(d):
if k in property_dict:
raise DuplicatedPropertyDictKeysError(k)
property_dict[k] = v
......
......@@ -33,7 +33,7 @@ for assignment in context.contentValues(portal_type='Assignment'):
# If we have multiple groups defined on assignments, this scripts does not
# try to guess, and fallback to the default career's group
if len(existing_group_set.keys()) == 1:
return existing_group_set.keys()[0]
return list(existing_group_set.keys())[0]
# no group found on open assignments, returns the default group
# (on a person document this is acquired on the default career's subordination)
......
......@@ -35,6 +35,7 @@ from Products.ERP5Type.Core.Predicate import Predicate
from Products.ERP5.mixin.variated import VariatedMixin
from Products.ERP5Type.Cache import transactional_cached
from ZTUtils import make_query
import six
class TempBudgetCell(object):
__allow_access_to_unprotected_subobjects__ = 1
......@@ -118,7 +119,7 @@ class BudgetLine(Predicate, XMLMatrix, VariatedMixin):
the value is the engaged budget.
"""
budget_dict = {k: v * -1
for k, v in self.getEngagedBudgetDict(**kw).iteritems()}
for k, v in six.iteritems(self.getEngagedBudgetDict(**kw))}
cell_key_list = self.getCellKeyList()
for cell_key in cell_key_list:
......
......@@ -38,6 +38,7 @@ from Acquisition import aq_base
from erp5.component.interface.IRule import IRule
from erp5.component.interface.IDivergenceController import IDivergenceController
from erp5.component.interface.IMovementCollectionUpdater import IMovementCollectionUpdater
import six
@zope.interface.implementer(IRule,
IDivergenceController,
......@@ -107,7 +108,7 @@ class LoyaltyTransactionRuleMovementGenerator(MovementGeneratorMixin):
# Only take loyalty trade model line
if amount.getResource() and [x for x in amount.getBaseApplicationList() if x in ['base_amount/loyalty_program/collect_point', 'base_amount/loyalty_program/using_point']]:
movement = input_movement.asContext(**{k: v
for k, v in amount.__dict__.iteritems()
for k, v in six.iteritems(amount.__dict__)
if k[0] != '_' and k != 'categories'})
base_category_set = set([x for x in amount.getBaseCategoryList() if x not in ('price_currency')])
movement._setCategoryMembership(base_category_set,
......
......@@ -33,6 +33,7 @@ from Products.ERP5Type.Utils import convertToUpperCase
from Products.ERP5Type.Utils import deprecated
from erp5.component.document.Coordinate import Coordinate
import six
class InternetProtocolAddress(Coordinate):
"""
......@@ -95,7 +96,7 @@ class InternetProtocolAddress(Coordinate):
self._setCoordinateText(coordinate_text)
kw_dict = self._splitCoordinateText(coordinate_text)
for name, value in kw_dict.iteritems():
for name, value in six.iteritems(kw_dict):
setter_name = 'set%s' % convertToUpperCase(name)
setter_method = getattr(self, setter_name)
setter_method(value)
......
......@@ -34,6 +34,7 @@ from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.XMLObject import XMLObject
from erp5.component.mixin.ConfiguratorItemMixin import ConfiguratorItemMixin
from erp5.component.interface.IConfiguratorItem import IConfiguratorItem
import six
class UnrestrictedStringIO(StringIO):
......@@ -149,7 +150,7 @@ class CategoriesSpreadsheetConfiguratorItem(ConfiguratorItemMixin, XMLObject):
category_path_dict = {item['path']: item
for item in cache[base_category_id]}
for path in category_path_dict.iterkeys():
for path in six.iterkeys(category_path_dict):
# the first item in this list is the base category itself, so we skip it.
if path == base_category_id:
continue
......
......@@ -32,6 +32,7 @@ from Products.ERP5Type import Permissions, PropertySheet
from Products.ERP5Type.XMLObject import XMLObject
from erp5.component.mixin.ConfiguratorItemMixin import ConfiguratorItemMixin
from erp5.component.interface.IConfiguratorItem import IConfiguratorItem
import six
@zope.interface.implementer(IConfiguratorItem)
......@@ -66,7 +67,7 @@ class SolverConfiguratorItem(ConfiguratorItemMixin, XMLObject):
property_dict = solver_property_dict.get(self.getId())
argument_dict = {}
for k, v in property_dict.iteritems():
for k, v in six.iteritems(property_dict):
if k not in ("content_list",) and k in self.showDict():
argument_dict[k] = v
......
......@@ -137,7 +137,7 @@ for i in range(len(ordered_items)):
# item is level-coherent, so keep it
if item_ok == True:
# add to the clean list
clean_data.append(current_item_data.values()[0])
clean_data.append(list(current_item_data.values())[0])
# add to the processed list of level
processed_level.append(current_item_level)
......
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
import six
class TestWorkflowMixin(ERP5TypeTestCase):
def getWorklistDocumentCountFromActionName(self, action_name):
......@@ -35,7 +36,7 @@ class TestWorkflowMixin(ERP5TypeTestCase):
selection_name = getattr(self, 'module_selection_name', None)
if selection_name is not None:
selection_parameter_dict = self.portal.portal_selections.getSelectionParamsFor(selection_name)
for parameter, value in url_parameter_dict.iteritems():
for parameter, value in six.iteritems(url_parameter_dict):
self.assertIn(parameter, selection_parameter_dict)
self.assertEqual(value, selection_parameter_dict[parameter])
......
......@@ -36,6 +36,7 @@ from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.Sequence import SequenceList
from Products.ERP5Type.tests.utils import createZODBPythonScript, FileUpload
from AccessControl.SecurityManagement import newSecurityManager
import six
class TestERP5Base(ERP5TypeTestCase):
......
......@@ -27,6 +27,7 @@ from IPython.core.pylabtools import print_figure
from IPython.core.display import _pngxy
from ipykernel.jsonutil import json_clean, encode_images
import threading
import six
display_data_wrapper_lock = threading.Lock()
# Well known unserializable types
......@@ -415,13 +416,13 @@ def Base_runJupyterCode(self, jupyter_code, old_notebook_context):
# Removing all the setup functions if user call environment.clearAll()
if environment_collector.clearAll():
keys = notebook_context ['setup'].keys()
keys = list(notebook_context ['setup'].keys())
for key in keys:
del notebook_context['setup'][key]
# Running all the setup functions that we got
failed_setup_key_list = []
for key, value in notebook_context['setup'].iteritems():
for key, value in six.iteritems(notebook_context['setup']):
try:
code = compile(value['code'], '<string>', 'exec')
exec(code, user_context, user_context)
......@@ -440,7 +441,7 @@ def Base_runJupyterCode(self, jupyter_code, old_notebook_context):
# Iterating over envinronment.define calls captured by the environment collector
# that are functions and saving them as setup functions.
for func_name, data in current_setup_dict.iteritems():
for func_name, data in six.iteritems(current_setup_dict):
setup_string = (
"%s\n"
"_result = %s()\n"
......@@ -455,7 +456,7 @@ def Base_runJupyterCode(self, jupyter_code, old_notebook_context):
# Iterating over envinronment.define calls captured by the environment collector
# that are simple variables and saving them in the setup.
for variable, value, in current_var_dict.iteritems():
for variable, value, in six.iteritems(current_var_dict):
setup_string = "%s = %s\n" % (variable, repr(value))
notebook_context['setup'][variable] = {
'func_name': variable,
......@@ -558,7 +559,7 @@ def canSerialize(obj):
if isinstance(obj, container_type_tuple):
if isinstance(obj, dict):
result_list = []
for key, value in obj.iteritems():
for key, value in six.iteritems(obj):
result_list.append(canSerialize(key))
result_list.append(canSerialize(value))
else:
......
......@@ -43,6 +43,7 @@ from erp5.component.module.WorkingCopy import \
from erp5.component.module.SubversionClient import newSubversionClient
from six import string_types as basestring
from six.moves import range
import six
# XXX This does not work with concurrent processes/threads accessing the
# same working copy...
......@@ -415,7 +416,7 @@ class BusinessTemplateWorkingCopy(BusinessTemplateFolder):
shutil.rmtree(x)
# Remove deleted files/dirs
self.client.remove([k for k, v in self.versioned_dict.iteritems()
self.client.remove([k for k, v in six.iteritems(self.versioned_dict)
if v is not None and self.versioned_dict[os.path.dirname(k)] is None])
# Add new files/dirs
self.client.add([x for x in self.added_set
......
from Products.PythonScripts.standard import html_quote
import six
portal = context.getPortalObject()
skin_folder = portal.portal_skins[original_skin_name]
new_skin_folder = portal.portal_skins[new_skin_name]
......@@ -41,7 +42,7 @@ for original_form in skin_folder.objectValues():
map(html_quote, ('[%s]' % key if T else key, str(old), str(new[key]))))
for T, old, new in ((0, original_value_dict, new_value_dict),
(1, original_value_tales, new_value_tales))
for key, old in old.iteritems()
for key, old in six.iteritems(old)
if old != new[key])
output_append("</table></blockquote><p>")
......
......@@ -3,6 +3,7 @@ Gets document properties discovered from the user who contributes / owns the doc
User would be usually the current user, but sometimes the name has to be given explicitly
if e.g. the doc is contributed by email, and the script is run by zope user.
"""
import six
assignment_dict = context.ERP5Site_getPersonAssignmentDict(user_name=user_name)
group_list = assignment_dict['group_list']
......@@ -15,7 +16,7 @@ if group_list:
#Get the highest levels groups of the assignments
##if group_list = ['g1', 'g1/g1.1', 'g1/g1.2'] returns ['g1']
##if group_list = ['g1/g1.1', 'g1/g1.2'] returns ['g1/g1.1', 'g1/g1.2']
highest_level_group_value = min(group_level_dict.itervalues())
highest_level_group_value = min(six.itervalues(group_level_dict))
highest_level_group_list = [k for k in group_level_dict if group_level_dict[k] == highest_level_group_value]
return {'group_list': highest_level_group_list}
......
......@@ -35,6 +35,7 @@ from Acquisition import Implicit
from BTrees.OOBTree import OOBTree
from warnings import warn
from six.moves import range
import six
ACTIVITY_GROUPING_COUNT = 200
......@@ -151,7 +152,7 @@ class UrlRegistryTool(BaseTool):
warn('context argument ignored', DeprecationWarning)
mapping = self._getMappingDict()
url_list = []
for url, stored_reference in mapping.iteritems():
for url, stored_reference in six.iteritems(mapping):
if reference == stored_reference:
url_list.append(url)
return url_list
......
......@@ -33,6 +33,7 @@ from Products.ERP5Type.TransactionalVariable import TransactionalResource
from Products.ERP5.mixin.timer_service import TimerServiceMixin
from AccessControl.SecurityManagement import newSecurityManager, \
getSecurityManager, setSecurityManager
import six
# TODO: Current API was designed to avoid compability issues in case it is
# reimplemented using https://pypi.python.org/pypi/pyinotify
......@@ -95,7 +96,7 @@ class InotifyTool(TimerServiceMixin, BaseTool):
update_state_dict[path] = new_state
events = [{'path': p, 'mask': IN_DELETE}
for p in set(state).difference(new_state)]
for p, m in new_state.iteritems():
for p, m in six.iteritems(new_state):
if p in state:
if m == state[p]:
continue
......
......@@ -30,6 +30,7 @@ from AccessControl import ClassSecurityInfo
from Products.ERP5Type import PropertySheet
from Products.ERP5Type.Permissions import AccessContentsInformation
from Products.ERP5Type.Base import Base
import six
try:
from spyne import MethodContext
except ImportError:
......@@ -65,7 +66,7 @@ class SOAPBinding(Base):
@classmethod
def getRegisteredServiceClassItemList(cls):
return sorted(('%s (%s)' % (v.__name__, v.__module__), k)
for k, v in cls._service_class_dict.iteritems())
for k, v in six.iteritems(cls._service_class_dict))
security.declarePrivate('getListItemUrl')
def getListItemUrl(self, *args):
......
......@@ -37,6 +37,7 @@ from erp5.component.mixin.MovementCollectionUpdaterMixin import \
from erp5.component.interface.IRule import IRule
from erp5.component.interface.IDivergenceController import IDivergenceController
from erp5.component.interface.IMovementCollectionUpdater import IMovementCollectionUpdater
import six
@zope.interface.implementer(IRule,
IDivergenceController,
......@@ -100,7 +101,7 @@ class TradeModelRuleMovementGenerator(MovementGeneratorMixin):
# FIXME: Is it the right way to have source/destination and other
# non-Amount properties set on the generated movement ?
movement = input_movement.asContext(**{k: v
for k, v in amount.__dict__.iteritems()
for k, v in six.iteritems(amount.__dict__)
if k[0] != '_' and k != 'categories'})
base_category_set = set(amount.getBaseCategoryList())
base_category_set.remove('price_currency') # XXX
......
......@@ -34,6 +34,7 @@ from Acquisition import aq_parent
from zLOG import LOG
from Products.ERP5Type.tests.Sequence import SequenceList
from erp5.component.test.testPackingList import TestPackingListMixin
import six
class TestInvoiceMixin(TestPackingListMixin):
"""Test methods for invoices
......@@ -1046,7 +1047,7 @@ class TestInvoiceMixin(TestPackingListMixin):
"""
rule_type = rule.getSpecialiseValue().getPortalType()
rule_def = rule_dict.get(rule_type, {})
for k, v in rule_def.iteritems():
for k, v in six.iteritems(rule_def):
if k == 'movement_type_list':
for movement in rule.objectValues():
if movement.getDeliveryValue() is not None:
......@@ -1067,7 +1068,7 @@ class TestInvoiceMixin(TestPackingListMixin):
# for each movement, we want to make sure that each rule is not
# instanciated more than once
if len(found_rule_dict):
self.assertEqual(set(found_rule_dict.itervalues()), {1})
self.assertEqual(set(six.itervalues(found_rule_dict)), {1})
elif k == 'parent_movement_type_list':
if rule.getParentValue().getDeliveryValue() is not None:
parent_type = rule.getParentValue().getDeliveryValue().getPortalType()
......
......@@ -34,6 +34,7 @@ from erp5.component.mixin.RuleMixin import RuleMixin
from erp5.component.mixin.MovementGeneratorMixin import MovementGeneratorMixin
from erp5.component.mixin.MovementCollectionUpdaterMixin import \
MovementCollectionUpdaterMixin
import six
class TransformationSimulationRule(RuleMixin, MovementCollectionUpdaterMixin):
"""
......@@ -138,7 +139,7 @@ class TransformationRuleMovementGenerator(MovementGeneratorMixin):
# FIXME: Is it the right way to have source/destination and other
# non-Amount properties set on the generated movement ?
movement = newMovement(amount.getCausality(), dict((k, v)
for k, v in amount.__dict__.iteritems()
for k, v in six.iteritems(amount.__dict__)
if k[0] != '_' and k != 'categories'))
base_category_set = set(amount.getBaseCategoryList())
base_category_set.remove('price_currency') # XXX
......
......@@ -5,6 +5,7 @@ If `portal_type` is provided, only return worklists that apply for this portal t
This script has proxy role, as only manager can access workflow configuration.
"""
from Products.ERP5Type.Message import translateString
import six
portal = context.getPortalObject()
query_dict = {}
......@@ -20,7 +21,7 @@ for worklist in workflow.getWorklistValueList():
continue
query_list = []
for key, value in identity_criterion_dict.iteritems():
for key, value in six.iteritems(identity_criterion_dict):
if key == workflow_state_var:
# instead of having {'validation_state': 'draft'}, we want to have
# {'translated_validation_state_title': 'Brouillon'}
......
......@@ -15,7 +15,7 @@ def getdoc(document, identifier):
document.getPath(),
)
)
return document.values()[0]
return list(document.values())[0]
return getattr(document, identifier)
exchange = portal.system_event_module.newContent(
......
......@@ -113,7 +113,7 @@ for model_line in model_line_list:
if batch_mode:
object_dict_list = [x.values()[0] for x in object_dict_list]
object_dict_list = [list(x.values())[0] for x in object_dict_list]
return object_dict_list
# sort results
......
......@@ -8,9 +8,9 @@ import base64
import datetime
import os
import time
import six
import requests
from Products.ERP5Type.Core.Workflow import ValidationFailed
import six
present = False
tz = None
......
......@@ -31,6 +31,7 @@
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions
from erp5.component.mixin.ConfigurablePropertySolverMixin import ConfigurablePropertySolverMixin
import six
class AcceptSolver(ConfigurablePropertySolverMixin):
"""Target solver that accepts the values from the decision on the prevision.
......@@ -84,7 +85,7 @@ class AcceptSolver(ConfigurablePropertySolverMixin):
# like recording the same values in other simulation movements
def _updateSimulationMovement(self, simulation_movement, value_dict,
activate_kw):
for property_id, value in value_dict.iteritems():
for property_id, value in six.iteritems(value_dict):
if not simulation_movement.isPropertyRecorded(property_id):
simulation_movement.recordProperty(property_id)
simulation_movement.setProperty(property_id, value)
......
......@@ -30,6 +30,7 @@
from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions
from erp5.component.mixin.ConfigurablePropertySolverMixin import ConfigurablePropertySolverMixin
import six
class AdoptSolver(ConfigurablePropertySolverMixin):
"""Target solver that adopts the values from the prevision on the decision.
......@@ -50,7 +51,7 @@ class AdoptSolver(ConfigurablePropertySolverMixin):
for simulation_movement in self.getDeliveryValueList():
delivery_dict.setdefault(simulation_movement.getDeliveryValue(),
[]).append(simulation_movement)
for movement, simulation_movement_list in delivery_dict.iteritems():
for movement, simulation_movement_list in six.iteritems(delivery_dict):
if activate_kw is not None:
movement.setDefaultActivateParameterDict(activate_kw)
for solved_property in solved_property_list:
......
......@@ -37,6 +37,7 @@ from erp5.component.mixin.ConfigurableMixin import ConfigurableMixin
from erp5.component.module.MovementCollectionDiff import _getPropertyAndCategoryList
from erp5.component.interface.ISolver import ISolver
from erp5.component.interface.IConfigurable import IConfigurable
import six
@zope.interface.implementer(ISolver,
IConfigurable,)
......@@ -77,7 +78,7 @@ class ItemListSplitSolver(SolverMixin, ConfigurableMixin, XMLObject):
delivery_dict.setdefault(simulation_movement.getDeliveryValue(),
[]).append(simulation_movement)
for movement, simulation_movement_list in delivery_dict.iteritems():
for movement, simulation_movement_list in six.iteritems(delivery_dict):
decision_aggregate_set = set(movement.getAggregateList())
split_list = []
for simulation_movement in simulation_movement_list:
......
......@@ -36,6 +36,7 @@ from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
from Products.ERP5Type.Message import translateString
from erp5.component.interface.ISolver import ISolver
from erp5.component.interface.IConfigurable import IConfigurable
import six
@zope.interface.implementer(ISolver,
IConfigurable,)
......@@ -71,7 +72,7 @@ class MovementSplitSolver(SolverMixin, ConfigurableMixin, XMLObject):
delivery_dict.setdefault(delivery, []).append(simulation_movement)
for delivery, split_simulation_movement_list \
in delivery_dict.iteritems():
in six.iteritems(delivery_dict):
# First, duplicate the whole delivery document including its
# sub objects.
old_delivery_url = delivery.getRelativeUrl()
......@@ -166,7 +167,7 @@ class MovementSplitSolver(SolverMixin, ConfigurableMixin, XMLObject):
delivery_error = total_quantity * delivery_ratio - quantity
simulation_movement.edit(delivery_ratio=delivery_ratio,
delivery_error=delivery_error)
for movement, quantity in quantity_dict.iteritems():
for movement, quantity in six.iteritems(quantity_dict):
movement.setQuantity(quantity)
assert delivery.getMovementList() and new_delivery.getMovementList()
......@@ -206,7 +207,7 @@ class MovementSplitSolver(SolverMixin, ConfigurableMixin, XMLObject):
if getattr(parent, 'setVariationCategoryList', None) is not None:
line_dict.setdefault(parent, []).extend(
movement.getVariationCategoryList())
for line, category_list in line_dict.iteritems():
for line, category_list in six.iteritems(line_dict):
line.setVariationCategoryList(sorted(set(category_list)))
_updateVariationCategoryList(delivery)
_updateVariationCategoryList(new_delivery)
......
......@@ -38,6 +38,7 @@ from erp5.component.mixin.ConfigurableMixin import ConfigurableMixin
from erp5.component.module.MovementCollectionDiff import _getPropertyAndCategoryList
from erp5.component.interface.ISolver import ISolver
from erp5.component.interface.IConfigurable import IConfigurable
import six
@zope.interface.implementer(ISolver,
IConfigurable,)
......@@ -83,7 +84,7 @@ class QuantitySplitSolver(SolverMixin, ConfigurableMixin, XMLObject):
for simulation_movement in self.getDeliveryValueList():
delivery_dict.setdefault(simulation_movement.getDeliveryValue(),
[]).append(simulation_movement)
for movement, simulation_movement_list in delivery_dict.iteritems():
for movement, simulation_movement_list in six.iteritems(delivery_dict):
decision_quantity = movement.getQuantity()
delivery_solver = self.getParentValue().newContent(
portal_type=configuration_dict['delivery_solver'],
......
......@@ -37,6 +37,7 @@ from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
from erp5.component.interface.IMovement import IMovement
from erp5.component.interface.ISolver import ISolver
from erp5.component.interface.IConfigurable import IConfigurable
import six
@zope.interface.implementer(ISolver,
IConfigurable,)
......
......@@ -31,6 +31,7 @@ from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet
from erp5.component.document.AcceptSolver import AcceptSolver
from erp5.component.interface.ISolver import ISolver
import six
@zope.interface.implementer(ISolver,)
class TradeModelSolver(AcceptSolver):
......@@ -96,7 +97,7 @@ class TradeModelSolver(AcceptSolver):
with self.defaultActivateParameterDict(activate_kw, True):
# Second, apply changes on invoice lines to simulation movements,
# then expand.
for movement, simulation_movement_list in delivery_dict.iteritems():
for movement, simulation_movement_list in six.iteritems(delivery_dict):
if movement in trade_model_related_movement_dict:
continue
for simulation_movement in simulation_movement_list:
......@@ -106,7 +107,7 @@ class TradeModelSolver(AcceptSolver):
if solved_property == 'quantity':
new_value *= simulation_movement.getDeliveryRatio()
value_dict[solved_property] = new_value
for property_id, value in value_dict.iteritems():
for property_id, value in six.iteritems(value_dict):
if not simulation_movement.isPropertyRecorded(property_id):
simulation_movement.recordProperty(property_id)
simulation_movement.setProperty(property_id, value)
......@@ -115,7 +116,7 @@ class TradeModelSolver(AcceptSolver):
# Third, adopt changes on trade model related lines.
# XXX non-linear case is not yet supported.
for movement, simulation_movement_list in \
trade_model_related_movement_dict.iteritems():
six.iteritems(trade_model_related_movement_dict):
for solved_property in solved_property_list:
if solved_property == 'quantity':
total_quantity = sum(x.getQuantity()
......
......@@ -32,6 +32,7 @@ from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet
from erp5.component.document.AcceptSolver import AcceptSolver
from erp5.component.interface.ISolver import ISolver
import six
@zope.interface.implementer(ISolver,)
class UnifySolver(AcceptSolver):
......@@ -105,7 +106,7 @@ class UnifySolver(AcceptSolver):
for simulation_movement in self.getDeliveryValueList():
delivery_dict.setdefault(simulation_movement.getDeliveryValue(),
set()).add(simulation_movement)
for movement, simulation_movement_set in delivery_dict.iteritems():
for movement, simulation_movement_set in six.iteritems(delivery_dict):
# get the movement that actually has the property to update
movement = self._getActualTargetMovement(movement, solved_property)
# and all other simulation movements we should also update
......
......@@ -169,7 +169,7 @@ class WebServiceRequest(XMLObject, ZopePageTemplate):
new_kw = kw.copy()
args = []
if self.getDestination():
for k,v in kw.iteritems():
for k,v in six.iteritems(kw):
new_key = site.getMappingFromProperty(self.getDestinationValue(), k)
new_kw.pop(k)
if new_key is None:
......
......@@ -20,6 +20,7 @@ from lxml import etree
from zLOG import LOG, ERROR
from DateTime import DateTime
from Products.ERP5Type.Cache import CachingMethod
import six
# Global variables
SEPARATOR = '\n'
......@@ -39,7 +40,7 @@ class TioSafeBrain(Explicit):
self.object_type = object_type
self.context = context
# save properties as attributes
for k,v in kw.iteritems():
for k,v in six.iteritems(kw):
# FIXME: '0000-00-00 00:00:00' is an error find in the Prestashop sync
if v is not None and v != '0000-00-00 00:00:00':
setattr(self, k.lower(), v)
......@@ -49,7 +50,7 @@ class TioSafeBrain(Explicit):
Update self properties with the one from
another brain
"""
for k,v in brain.__dict__.iteritems():
for k,v in six.iteritems(brain.__dict__):
setattr(self, k, v)
def _asXML(self):
......@@ -462,7 +463,7 @@ class Resource(TioSafeBrain):
category = etree.SubElement(element, 'category')
category.text = category_value
mapping.pop('category_list')
for k, v in mapping.iteritems():
for k, v in six.iteritems(mapping):
prop = etree.SubElement(element, k)
prop.text = v
......
......@@ -40,7 +40,7 @@ request= context.REQUEST
integration_site = context
if len(bad_destination_list) > 0:
status_message = "Impossible to update because of redundancy of %s." % repr({}.fromkeys(bad_destination_list).keys())
status_message = "Impossible to update because of redundancy of %s." % repr(list({}.fromkeys(bad_destination_list).keys()))
request.set('portal_status_message', status_message)
return getattr(context, request.form['dialog_id'])(listbox=listbox, kw=kw)
......
from Products.PythonScripts.standard import Object
from json import loads
import six
portal = context.getPortalObject()
......@@ -11,20 +12,20 @@ active_process_path = request.get('active_process')
def _addDict(global_dict, local_dict, only_amount=False):
if report_group_by == "both" and not only_amount:
# we have client -> product -> period -> amount
for local_title, local_product_dict in local_dict.iteritems():
for local_title, local_product_dict in six.iteritems(local_dict):
product_dict = global_dict.setdefault(local_title, {})
for local_product, local_period_dict in local_product_dict.iteritems():
for local_product, local_period_dict in six.iteritems(local_product_dict):
period_dict = product_dict.setdefault(local_product, {})
for period, local_amount_dict in local_period_dict.iteritems():
for period, local_amount_dict in six.iteritems(local_period_dict):
amount_dict = period_dict.setdefault(period, {'amount' : 0, 'quantity' : 0, 'quantity_unit' : ''})
amount_dict['amount'] = amount_dict['amount'] + local_amount_dict['amount']
amount_dict['quantity'] = amount_dict['quantity'] + local_amount_dict['quantity']
amount_dict['quantity_unit'] = local_amount_dict['quantity_unit']
else:
# We have client or product -> period -> amount
for local_title, local_period_dict in local_dict.iteritems():
for local_title, local_period_dict in six.iteritems(local_dict):
period_dict = global_dict.setdefault(local_title, {})
for period, local_amount_dict in local_period_dict.iteritems():
for period, local_amount_dict in six.iteritems(local_period_dict):
amount_dict = period_dict.setdefault(period, {'amount' : 0, 'quantity' : 0, 'quantity_unit' : ''})
amount_dict['amount'] = amount_dict['amount'] + local_amount_dict['amount']
if not only_amount:
......
import base64
import json
import six
portal = context.getPortalObject()
record = context
def byteify(string):
if isinstance(string, dict):
tmp = {}
for key, value in string.iteritems():
for key, value in six.iteritems(string):
tmp[byteify(key)] = byteify(value)
return tmp
elif isinstance(string, list):
......
import json
import six
portal = context.getPortalObject()
record = context
......@@ -6,7 +7,7 @@ record = context
def byteify(string):
if isinstance(string, dict):
tmp = {}
for key, value in string.iteritems():
for key, value in six.iteritems(string):
tmp[byteify(key)] = byteify(value)
return tmp
elif isinstance(string, list):
......
import six
portal = context.getPortalObject()
constraint_type_list = portal.getPortalConstraintTypeList()
......@@ -35,7 +36,7 @@ for property_sheet in portal.portal_property_sheets.objectValues():
constraint_type_per_id.setdefault(property_sheet_id, []).extend(type_list)
constraint_type_per_type = {}
for property_sheet_id, category_list in constraint_type_per_id.iteritems():
for property_sheet_id, category_list in six.iteritems(constraint_type_per_id):
for portal_type in property_sheet_by_type_dict.get(property_sheet_id, []):
constraint_type_per_type.setdefault(portal_type, set()).update(category_list)
......
import six
constraint_type_per_type, _ = context.Base_getConstraintTypeListPerPortalType()
constraint_type = filter_dict.get("constraint_type")
if not constraint_type:
......@@ -12,7 +13,7 @@ if filter_dict is None:
portal_type_list = []
append = portal_type_list.append
for portal_type, constraint_type_list in constraint_type_per_type.iteritems():
for portal_type, constraint_type_list in six.iteritems(constraint_type_per_type):
if constraint_type in constraint_type_list:
append(portal_type)
......
import re
import six
template_tool = context
bt5_per_title_dict = {}
......@@ -12,7 +13,7 @@ for bt5 in installed_bt5_list:
continue
bt5_per_title_dict[bt5_title] = bt5
resolved_list = template_tool.resolveBusinessTemplateListDependency(bt5_per_title_dict.iterkeys())
resolved_list = template_tool.resolveBusinessTemplateListDependency(six.iterkeys(bt5_per_title_dict))
pattern = re.compile(r"(?P<portal_type>.*)[| ]\|[| ](?P<workflow_id>.*)")
portal_type_dict = {}
......@@ -38,7 +39,7 @@ for _, bt5_id in resolved_list:
workflow_id_list.append(workflow_id)
error_list = []
for portal_type, workflow_chain in portal_type_dict.iteritems():
for portal_type, workflow_chain in six.iteritems(portal_type_dict):
portal_type_document = context.portal_types.getTypeInfo(portal_type)
workflow_chain_list = portal_type_document.getTypeWorkflowList()
expected_workflow_chain = sorted(workflow_chain)
......
......@@ -574,7 +574,7 @@ def generateReport():
DIAGRAM_PER_PAGE],
only_average=argument_namespace.only_average)
for suite_name, use_case_dict in use_case_dict.viewitems():
for suite_name, use_case_dict in six.viewitems(use_case_dict):
drawUseCasePerNumberOfUserPlot(
pdf,
"Scalability for %s with %d users" % (suite_name, nb_users),
......
......@@ -423,7 +423,7 @@ class FakeMovement:
"""
price_dict = self._getPriceDict()
if len(price_dict) == 1:
return price_dict.keys()[0]
return list(price_dict.keys())[0]
total_quantity = sum(price_dict.values())
return (total_quantity and
sum(price * quantity for price, quantity in price_dict.items())
......
......@@ -1539,7 +1539,7 @@ class SelectionTool( BaseTool, SimpleItem ):
def _getSelectionNameListFromContainer(self):
user_id = self._getUserId()
return list(set(self._getContainer().getSelectionNameList(user_id) +
self.getTemporarySelectionDict().keys()))
list(self.getTemporarySelectionDict().keys())))
def isAnonymous(self):
return self._getUserId() == 'Anonymous User'
......
......@@ -161,8 +161,64 @@ if WITH_LEGACY_WORKFLOW:
def canDoActionFor(self, ob, action, wf_id=None, guard_kw={}):
""" Check we can perform the given workflow action on 'ob'.
"""
if wf_id is None:
workflow_list = self.getWorkflowValueListFor(ob) or ()
chain_dict = {}
for portal_type, wf_id_list in six.iteritems(self._chains_by_type):
for wf_id in wf_id_list:
chain_dict.setdefault(wf_id, []).append(portal_type)
return chain_dict
security.declareProtected(Permissions.ManagePortal, 'getChainDict')
WorkflowTool.getChainDict = WorkflowTool_getChainDict
# Backward compatibility, as WorkflowMethod has been removed in CMFCore 2.2
from MethodObject import Method
class WorkflowMethod( Method ):
""" Wrap a method to workflow-enable it.
"""
_need__name__=1
def __init__(self, method, id=None, reindex=1):
self._m = method
if id is None:
id = method.__name__
self._id = id
# reindex ignored since workflows now perform the reindexing.
def __call__(self, instance, *args, **kw):
""" Invoke the wrapped method, and deal with the results.
"""
wf = getToolByName(instance, 'portal_workflow', None)
if wf is None or not hasattr(wf, 'wrapWorkflowMethod'):
# No workflow tool found.
try:
res = self._m(instance, *args, **kw)
except ObjectDeleted as ex:
res = ex.getResult()
else:
if hasattr(aq_base(instance), 'reindexObject'):
instance.reindexObject()
else:
res = wf.wrapWorkflowMethod(instance, self._id, self._m,
(instance,) + args, kw)
from Products.CMFCore import WorkflowCore
# BBB: WorkflowMethod has been removed from CMFCore 2
WorkflowCore.WorkflowAction = WorkflowMethod
# XXX: Kept here instead of ERP5Type.Tool.WorkflowTool because not used in
# erp5.git: is it used in projects?
security.declarePublic('canDoActionFor')
def canDoActionFor(self, ob, action, wf_id=None, guard_kw={}):
""" Check we can perform the given workflow action on 'ob'.
"""
if wf_id is None:
workflow_list = self.getWorkflowValueListFor(ob) or ()
else:
workflow = self._getOb(wf_id, None)
if workflow:
workflow_list = (workflow,)
else:
workflow = self._getOb(wf_id, None)
if workflow:
......
......@@ -460,8 +460,8 @@ class Field:
return obj.encode('utf-8')
return str(obj)
return ' '.join(map(getSearchSource,
(self.values.values()+self.tales.values()+
self.overrides.values())))
(list(self.values.values())+list(self.tales.values())+
list(self.overrides.values()))))
InitializeClass(Field)
......
......@@ -57,7 +57,7 @@ class ComplexQuery(Query):
self.logical_operator = kw.pop('logical_operator', 'and').lower()
assert self.logical_operator in ('and', 'or', 'not'), self.logical_operator
if kw:
raise TypeError('Unknown named arguments: %r' % (kw.keys(), ))
raise TypeError('Unknown named arguments: %r' % (list(kw.keys()), ))
query_list = []
append = query_list.append
extend = query_list.extend
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment