Issue #2974 - Part 6: Adapt dict

2to3 . --fix dict -wpn

Py2 dict was a list by default, the iterator versions
were switched around to be the default.
This lets you have the old behavior. Mechanical.

Ref: PEP 3106
https://peps.python.org/pep-3106/
This commit is contained in:
Jeremy Andrews committed 2026-03-04 13:56:53 -06:00
1 parent 112c119477
commit 8c0f0ccdcf
422 files changed
+1180 -1180

No files matched your search

@@ -43,7 +43,7 @@ def readConfig(configfile, keys=[], required=[]):
execfile(configfile, c)
for k in keys:
c = c[k]
items = c.keys()
items = list(c.keys())
err = False
for key in required:
if key not in items:
+1 -1
View File
@@ -335,7 +335,7 @@ def bootstrap(topsrcdir, mozilla_dir=None):
# always load local repository configuration
mach.settings_paths.append(mozilla_dir)
for category, meta in CATEGORIES.items():
for category, meta in list(CATEGORIES.items()):
mach.define_category(category, meta['short'], meta['long'],
meta['priority'])
+1 -1
View File
@@ -70,7 +70,7 @@ def sleep(args):
values = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}
for a in args:
multiplier = 1
for k, v in values.iteritems():
for k, v in values.items():
if a.endswith(k):
a = a[:-1]
multiplier = v
+5 -5
View File
@@ -447,7 +447,7 @@ class Variables(object):
self.parent = parent
def readfromenvironment(self, env):
for k, v in env.iteritems():
for k, v in env.items():
self.set(k, self.FLAVOR_RECURSIVE, self.SOURCE_ENVIRONMENT, v)
def get(self, name, expand=True):
@@ -547,7 +547,7 @@ class Variables(object):
self.set(k, flavor, source, value)
def __iter__(self):
for k, (flavor, source, value, valueexp) in self._map.iteritems():
for k, (flavor, source, value, valueexp) in self._map.items():
yield k, flavor, source, value
def __contains__(self, item):
@@ -1678,7 +1678,7 @@ class Makefile(object):
self.variables.set('MAKECMDGOALS', Variables.FLAVOR_SIMPLE,
Variables.SOURCE_AUTOMATIC, ' '.join(targets))
for vname, val in implicit.variables.iteritems():
for vname, val in implicit.variables.items():
self.variables.set(vname,
Variables.FLAVOR_SIMPLE,
Variables.SOURCE_IMPLICIT, val)
@@ -1753,7 +1753,7 @@ class Makefile(object):
self._vpath = [e for e in re.split('[%s\s]+' % os.pathsep,
value.resolvestr(self, self.variables, ['VPATH'])) if e != '']
targets = list(self._targets.itervalues())
targets = list(self._targets.values())
for t in targets:
t.explicit = True
for r in t.rules:
@@ -1824,7 +1824,7 @@ class Makefile(object):
def getsubenvironment(self, variables):
env = dict(self.env)
for vname, v in self.exportedvars.iteritems():
for vname, v in self.exportedvars.items():
if v:
flavor, source, val = variables.get(vname)
if val is None:
+2 -2
View File
@@ -108,7 +108,7 @@ _alltokens = re.compile(r'''\\*\# | # hash mark preceeded by any number of backs
:: |
(?:\$(?:$|[\(\{](?:%s)\s+|.)) | # dollar sign followed by EOF, a function keyword with whitespace, or any character
:(?![\\/]) | # colon followed by anything except a slash (Windows path detection)
[=#{}();,|'"]''' % '|'.join(functions.functionmap.iterkeys()), re.VERBOSE)
[=#{}();,|'"]''' % '|'.join(iter(functions.functionmap.keys())), re.VERBOSE)
def iterdata(d, offset, tokenlist, it):
"""
@@ -336,7 +336,7 @@ _conditionkeywords = {
'ifndef': ifndef
}
_conditiontokens = tuple(_conditionkeywords.iterkeys())
_conditiontokens = tuple(_conditionkeywords.keys())
_conditionre = re.compile(r'(%s)(?:$|\s+)' % '|'.join(_conditiontokens))
_directivestokenlist = _conditiontokens + \
+3 -3
View File
@@ -28,7 +28,7 @@ def tokens2re(tokens):
# which matches the pattern and captures it in a named match group.
# The group names and patterns come are given as a dict in the function
# argument.
nonescaped = r'(?<!\\)(?:%s)' % '|'.join('(?P<%s>%s)' % (name, value) for name, value in tokens.iteritems())
nonescaped = r'(?<!\\)(?:%s)' % '|'.join('(?P<%s>%s)' % (name, value) for name, value in tokens.items())
# The final pattern matches either the above pattern, or an escaped
# backslash, captured in the "escape" match group.
return re.compile('(?:%s|%s)' % (nonescaped, r'(?P<escape>\\\\)'))
@@ -115,7 +115,7 @@ class ClineSplitter(list):
self._push(self.cline[:m.start()])
self.cline = self.cline[m.end():]
match = dict([(name, value) for name, value in m.groupdict().items() if value])
match = dict([(name, value) for name, value in list(m.groupdict().items()) if value])
if 'quote' in match:
# " or ' start a quoted string
if match['quote'] == '"':
@@ -166,7 +166,7 @@ class ClineSplitter(list):
raise Exception, 'Unterminated quoted string in command'
self._push(self.cline[:m.start()])
self.cline = self.cline[m.end():]
match = dict([(name, value) for name, value in m.groupdict().items() if value])
match = dict([(name, value) for name, value in list(m.groupdict().items()) if value])
if 'quote' in match:
# a double quote ends the quoted string, so go back to
# unquoted parsing
+1 -1
View File
@@ -138,7 +138,7 @@ class MostUsedCache(object):
return item.o
def verify(self):
for k, v in self.d.iteritems():
for k, v in self.d.items():
if v.o:
assert v in self.active
else:
+1 -1
View File
@@ -4,7 +4,7 @@ import re
from cStringIO import StringIO
def multitest(cls):
for name in cls.testdata.iterkeys():
for name in cls.testdata.keys():
def m(self, name=name):
return self.runSingle(*self.testdata[name])
+3 -3
View File
@@ -5,7 +5,7 @@ import logging
from cStringIO import StringIO
def multitest(cls):
for name in cls.testdata.iterkeys():
for name in cls.testdata.keys():
def m(self, name=name):
return self.runSingle(*self.testdata[name])
@@ -217,7 +217,7 @@ class MakeSyntaxTest(TestBase):
else:
self.assertEqual(type(a), getattr(pymake.functions, e['type']),
"compareRecursive: %s" % (ipath,))
for k, v in e.iteritems():
for k, v in e.items():
if k == 'type':
pass
elif k[0] == '[':
@@ -264,7 +264,7 @@ class VariableTest(TestBase):
m = pymake.data.Makefile()
stmts.execute(m)
for k, v in self.expected.iteritems():
for k, v in self.expected.items():
flavor, source, val = m.variables.get(k)
if val is None:
self.assertEqual(val, v, 'variable named %s' % k)
+1 -1
View File
@@ -144,7 +144,7 @@ for makefile in makefiles:
if sys.platform in data:
d['returncode'] = data[sys.platform]
elif key == 'environment':
for k, v in data.iteritems():
for k, v in data.items():
d['env'][k] = v
elif key == 'grep-for':
d['grepfor'] = data
+2 -2
View File
@@ -90,7 +90,7 @@ def readConfig(configfile, keys=[], required=[]):
execfile(configfile, c)
for k in keys:
c = c[k]
items = c.keys()
items = list(c.keys())
err = False
for key in required:
if key not in items:
@@ -137,7 +137,7 @@ def getReleaseName(product, version, buildNumber):
def getRepoMatchingBranch(branch, sourceRepositories):
for sr in sourceRepositories.values():
for sr in list(sourceRepositories.values()):
if branch in sr['path']:
return sr
return None
+1 -1
View File
@@ -578,7 +578,7 @@ def adjust_paths(dest, **paths):
config.add_section('paths')
changed = False
for path_name, path_value in paths.items():
for path_name, path_value in list(paths.items()):
if (not config.has_option('paths', path_name) or
config.get('paths', path_name) != path_value):
changed = True
+1 -1
View File
@@ -275,7 +275,7 @@ def check_style():
edges[inclname] = set()
# Process all the JS files.
for filename in js_names.keys():
for filename in list(js_names.keys()):
inclname = js_names[filename]
file_kind = FileKind.get(filename)
if file_kind == FileKind.C or file_kind == FileKind.CPP or \
+2 -2
View File
@@ -95,12 +95,12 @@ def count_lines():
"""Keep track of the amount of times individual lines occur, in order to
prioritize the errors which occur most frequently."""
counts = {}
for string,count in blacklist.items():
for string,count in list(blacklist.items()):
for line in string.split("\n"):
counts[line] = counts.get(line, 0) + count
lines = []
for k,v in counts.items():
for k,v in list(counts.items()):
lines.append("{0:6}: {1}".format(v, k))
lines.sort()
+1 -1
View File
@@ -140,7 +140,7 @@ class MockedOpen(object):
'''
def __init__(self, files = {}):
self.files = {}
for name, content in files.iteritems():
for name, content in files.items():
self.files[normcase(os.path.abspath(name))] = content
def __call__(self, name, mode = 'r'):
+2 -2
View File
@@ -136,10 +136,10 @@ class TestExtensiveStored(unittest.TestCase):
self.failIf(badEntry, badEntry)
zlist = zf.namelist()
zlist.sort()
vlist = self.ref.keys()
vlist = list(self.ref.keys())
vlist.sort()
self.assertEqual(zlist, vlist)
for leaf, content in self.ref.iteritems():
for leaf, content in self.ref.items():
zcontent = zf.read(leaf)
self.assertEqual(content, zcontent)
+3 -3
View File
@@ -45,11 +45,11 @@ def config_status(config):
sanitized_config = {}
sanitized_config['substs'] = {
k: sanitized_bools(v) for k, v in config.iteritems()
k: sanitized_bools(v) for k, v in config.items()
if k not in ('DEFINES', 'non_global_defines', 'TOPSRCDIR', 'TOPOBJDIR')
}
sanitized_config['defines'] = {
k: sanitized_bools(v) for k, v in config['DEFINES'].iteritems()
k: sanitized_bools(v) for k, v in config['DEFINES'].items()
}
sanitized_config['non_global_defines'] = config['non_global_defines']
sanitized_config['topsrcdir'] = config['TOPSRCDIR']
@@ -71,7 +71,7 @@ def config_status(config):
''') % {'python': config['PYTHON'], 'encoding': encoding})
# A lot of the build backend code is currently expecting byte
# strings and breaks in subtle ways with unicode strings. (bug 1296508)
for k, v in sanitized_config.iteritems():
for k, v in sanitized_config.items():
fh.write('%s = encode(%s, encoding)\n' % (k, indented_repr(v)))
fh.write("__all__ = ['topobjdir', 'topsrcdir', 'defines', "
"'non_global_defines', 'substs', 'mozconfig']")
+8 -8
View File
@@ -9728,7 +9728,7 @@ class CGEnum(CGThing):
name=ENUM_ENTRY_VARIABLE_NAME,
count=self.nEnumStrings(),
entries=''.join('{"%s", %d},\n' % (val, len(val))
for val in self.enum.values()))))
for val in list(self.enum.values())))))
toJSValue = CGEnumToJSValue(enum)
self.cgThings = CGList([strings, toJSValue], "\n")
@@ -9736,7 +9736,7 @@ class CGEnum(CGThing):
return self.enum.identifier.name + "Values"
def nEnumStrings(self):
return len(self.enum.values()) + 1
return len(list(self.enum.values())) + 1
def declare(self):
decl = fill(
@@ -9747,7 +9747,7 @@ class CGEnum(CGThing):
};
""",
name=self.enum.identifier.name,
enums=",\n".join(map(getEnumValueName, self.enum.values())) + ",\n")
enums=",\n".join(map(getEnumValueName, list(self.enum.values()))) + ",\n")
strings = CGNamespace(self.stringsNamespace(),
CGGeneric(declare="extern const EnumEntry %s[%d];\n"
% (ENUM_ENTRY_VARIABLE_NAME, self.nEnumStrings())))
@@ -13658,7 +13658,7 @@ class ForwardDeclarationBuilder:
if self.decls:
decls.append(CGList([CGClassForwardDeclare(cname, isStruct)
for cname, isStruct in sorted(self.decls)]))
for namespace, child in sorted(self.children.iteritems()):
for namespace, child in sorted(self.children.items()):
decls.append(CGNamespace(namespace, child._build(atTopLevel=False), declareOnly=True))
cg = CGList(decls, "\n")
@@ -14008,10 +14008,10 @@ class CGBindingRoot(CGThing):
# Add header includes.
bindingHeaders = [header
for header, include in bindingHeaders.iteritems()
for header, include in bindingHeaders.items()
if include]
bindingDeclareHeaders = [header
for header, include in bindingDeclareHeaders.iteritems()
for header, include in bindingDeclareHeaders.items()
if include]
curr = CGHeaders(descriptors,
@@ -14619,7 +14619,7 @@ class CGBindingImplClass(CGClass):
(returnType, args),
descriptor.getExtendedAttributes(op)))
# Sort things by name so we get stable ordering in the output.
ops = descriptor.operations.items()
ops = list(descriptor.operations.items())
ops.sort(key=lambda x: x[0])
for name, op in ops:
appendSpecialOperation(name, op)
@@ -16969,7 +16969,7 @@ class GlobalGenRoots():
@staticmethod
def UnionConversions(config):
unionTypes = []
for l in config.unionsPerFilename.itervalues():
for l in config.unionsPerFilename.values():
unionTypes.extend(l)
unionTypes.sort(key=lambda u: u.name)
headers, unions = UnionConversions(unionTypes,
+1 -1
View File
@@ -169,7 +169,7 @@ class Configuration(DescriptorProvider):
# Collect up our filters, because we may have a webIDLFile filter that
# we always want to apply first.
tofilter = []
for key, val in filters.iteritems():
for key, val in filters.items():
if key == 'webIDLFile':
# Special-case this part to make it fast, since most of our
# getDescriptors calls are conditioned on a webIDLFile. We may
+6 -6
View File
@@ -99,7 +99,7 @@ class WebIDLCodegenManagerState(dict):
self['version'] = state['version']
self['global_depends'] = state['global_depends']
for k, v in state['webidls'].items():
for k, v in list(state['webidls'].items()):
self['webidls'][k] = v
# Sets are converted to lists for serialization because JSON
@@ -111,7 +111,7 @@ class WebIDLCodegenManagerState(dict):
"""Dump serialized state to a file handle."""
normalized = deepcopy(self)
for k, v in self['webidls'].items():
for k, v in list(self['webidls'].items()):
# Convert sets to lists because JSON doesn't support sets.
normalized['webidls'][k]['outputs'] = sorted(v['outputs'])
normalized['webidls'][k]['inputs'] = sorted(v['inputs'])
@@ -296,7 +296,7 @@ class WebIDLCodegenManager(LoggingMixin):
if self._make_deps_path:
mk = Makefile()
codegen_rule = mk.create_rule([self._make_deps_target])
codegen_rule.add_dependencies(global_hashes.keys())
codegen_rule.add_dependencies(list(global_hashes.keys()))
codegen_rule.add_dependencies(self._input_paths)
with FileAvoidWrite(self._make_deps_path) as fh:
@@ -382,7 +382,7 @@ class WebIDLCodegenManager(LoggingMixin):
# Now we move on to the input files.
old_hashes = {v['filename']: v['sha1']
for v in self._state['webidls'].values()}
for v in list(self._state['webidls'].values())}
old_filenames = set(old_hashes.keys())
new_filenames = self._input_paths
@@ -403,7 +403,7 @@ class WebIDLCodegenManager(LoggingMixin):
# Inherit dependencies from previous run. The full set of dependencies
# is associated with each record, so we don't need to perform any fancy
# graph traversal.
for v in self._state['webidls'].values():
for v in list(self._state['webidls'].values()):
if any(dep for dep in v['inputs'] if dep in changed_inputs):
changed_inputs.add(v['filename'])
@@ -512,7 +512,7 @@ class WebIDLCodegenManager(LoggingMixin):
return True, current_hashes
# Compare hashes.
for f, sha1 in current_hashes.items():
for f, sha1 in list(current_hashes.items()):
if sha1 != self._state['global_depends'][f]:
return True, current_hashes
+4 -4
View File
@@ -1515,7 +1515,7 @@ class IDLInterfaceOrNamespace(IDLObjectWithScope, IDLExposureMixins):
assert len(naviProp) == 1
assert isinstance(naviProp, list)
assert len(naviProp[0]) != 0
conditionExtendedAttributes = self._extendedAttrDict.viewkeys() & IDLInterfaceOrNamespace.conditionExtendedAttributes
conditionExtendedAttributes = self._extendedAttrDict.keys() & IDLInterfaceOrNamespace.conditionExtendedAttributes
attr = IDLAttribute(self.location,
IDLUnresolvedIdentifier(BuiltinLocation("<auto-generated-identifier>"), naviProp[0]),
IDLUnresolvedType(self.location, IDLUnresolvedIdentifier(self.location, self.identifier.name)),
@@ -3249,7 +3249,7 @@ integerTypeSizes = {
def matchIntegerValueToType(value):
for type, extremes in integerTypeSizes.items():
for type, extremes in list(integerTypeSizes.items()):
(min, max) = extremes
if value <= max and value >= min:
return BuiltinTypes[type]
@@ -3328,7 +3328,7 @@ class IDLValue(IDLObject):
elif self.type.isString() and type.isEnum():
# Just keep our string, but make sure it's a valid value for this enum
enum = type.unroll().inner
if self.value not in enum.values():
if self.value not in list(enum.values()):
raise WebIDLError("'%s' is not a valid default value for enum %s"
% (self.value, enum.identifier.name),
[location, enum.location])
@@ -5261,7 +5261,7 @@ class Tokenizer(object):
"ReadableStream": "READABLESTREAM",
}
tokens.extend(keywords.values())
tokens.extend(list(keywords.values()))
def t_error(self, t):
raise WebIDLError("Unrecognized Input",
+1 -1
View File
@@ -26,7 +26,7 @@ def WebIDLTest(parser, harness):
enum = results[0]
harness.check(enum.identifier.QName(), "::TestEnum", "Enum has the right QName")
harness.check(enum.identifier.name, "TestEnum", "Enum has the right name")
harness.check(enum.values(), ["", "foo", "bar"], "Enum has the right values")
harness.check(list(enum.values()), ["", "foo", "bar"], "Enum has the right values")
iface = results[1]
+1 -1
View File
@@ -58,7 +58,7 @@ def writeFiles(files):
dirp, leaf = path.rsplit('/', 1)
pathmap.setdefault(dirp, []).append(leaf)
for k, v in pathmap.items():
for k, v in list(pathmap.items()):
with open(k + '/mochitest.ini', 'w') as fh:
result = writeBuildFiles.substManifest('parseFailures.py', v, [])
fh.write(result)
@@ -75,7 +75,7 @@ class YouTubePuppeteer(VideoPuppeteer):
'BUFFERING': 3,
'CUED': 5
}
_yt_player_state_name = {v: k for k, v in _yt_player_state.items()}
_yt_player_state_name = {v: k for k, v in list(_yt_player_state.items())}
_time_pattern = re.compile('(?P<minute>\d+):(?P<second>\d+)')
def __init__(self, marionette, url, autostart=True, **kwargs):
+1 -1
View File
@@ -45,7 +45,7 @@ def run_external_media_test(tests, testtype=None, topsrcdir=None, **kwargs):
args = Namespace(tests=tests)
for k, v in kwargs.iteritems():
for k, v in kwargs.items():
setattr(args, k, v)
parser.verify_usage(args)
+3 -3
View File
@@ -22,7 +22,7 @@ def compute_sum(data):
out = ([],[])
for i in data:
if i[0] not in last_values.keys():
if i[0] not in list(last_values.keys()):
last_values[i[0]] = 0
last_values[i[0]] = float(i[3])
print(last_values)
@@ -76,7 +76,7 @@ for tupl in data:
name = tupl[0]
if tupl[1] != 0:
name = name+tupl[1]
if name not in final_data.keys():
if name not in list(final_data.keys()):
final_data[name] = ([], [])
# sanity-check values
if float(tupl[3]) < 10*1000:
@@ -89,7 +89,7 @@ for tupl in data:
pprint(final_data)
fig = plt.figure()
for i in final_data.keys():
for i in list(final_data.keys()):
plt.plot(final_data[i][0], final_data[i][1], label=i)
plt.legend()
@@ -39,7 +39,7 @@ def load_with_override(override_path):
results = load_forward_table(map_path)
overrides = load_json(override_path)
for k, v in overrides.iteritems():
for k, v in overrides.items():
results[k] = v
return results
@@ -141,7 +141,7 @@ def do_format(format_data):
'depthStencil': macro_prefix + 'DS'
}
for format_name, format_support in sorted(format_data.iteritems()):
for format_name, format_support in sorted(format_data.items()):
always_supported = set()
never_supported = set()
@@ -152,7 +152,7 @@ def do_format(format_data):
fl_10_0_check_10_1_supported = set()
fl_10_0_check_11_0_supported = set()
for json_flag, support in format_support.iteritems():
for json_flag, support in format_support.items():
d3d_flag = [json_flag_to_d3d[json_flag]]
@@ -158,8 +158,8 @@ def get_swizzle_format_id(internal_format, angle_format):
raise ValueError('no bits information for determining swizzleformat for format: ' + internal_format)
bits = angle_format['bits']
max_component_bits = max(bits.itervalues())
channels_different = not all([component_bits == bits.itervalues().next() for component_bits in bits.itervalues()])
max_component_bits = max(bits.values())
channels_different = not all([component_bits == iter(bits.values()).next() for component_bits in bits.values()])
# The format itself can be used for swizzles if it can be accessed as a render target and
# sampled and the bit count for all 4 channels is the same.
@@ -261,7 +261,7 @@ def json_to_table_data(internal_format, format_name, prefix, json):
"condition": prefix,
}
for k, v in json.iteritems():
for k, v in json.items():
parsed[k] = v
# Derived values.
@@ -280,15 +280,15 @@ def parse_json_angle_format_case(format_name, angle_format, json_data):
support_test = None
fallback = None
for k, v in angle_format.iteritems():
for k, v in angle_format.items():
if k == "FL10Plus":
assert support_test is None
support_test = "OnlyFL10Plus(deviceCaps)"
for k2, v2 in v.iteritems():
for k2, v2 in v.items():
supported_case[k2] = v2
elif k == "FL9_3":
split = True
for k2, v2 in v.iteritems():
for k2, v2 in v.items():
unsupported_case[k2] = v2
elif k == "supportTest":
assert support_test is None
@@ -312,7 +312,7 @@ def parse_json_angle_format_case(format_name, angle_format, json_data):
def parse_json_into_switch_angle_format_string(json_map, json_data):
table_data = ''
for internal_format, format_name in sorted(json_map.iteritems()):
for internal_format, format_name in sorted(json_map.items()):
if format_name not in json_data:
continue
@@ -183,7 +183,7 @@ def json_to_table_data(format_id, json, angle_to_gl):
"id": format_id,
}
for k, v in json.iteritems():
for k, v in json.items():
parsed[k] = v
if "glInternalFormat" not in parsed:
@@ -227,7 +227,7 @@ def gen_enum_string(all_angle):
gl_to_angle = angle_format.load_forward_table('angle_format_map.json')
angle_to_gl = angle_format.load_inverse_table('angle_format_map.json')
json_data = angle_format.load_json('angle_format_data.json')
all_angle = angle_to_gl.keys()
all_angle = list(angle_to_gl.keys())
angle_format_cases = parse_json_into_angle_format_switch_string(
all_angle, json_data, angle_to_gl)
@@ -107,7 +107,7 @@ def get_load_func(func_name, type_functions):
snippet += "{\n"
snippet += " switch (type)\n"
snippet += " {\n"
for gl_type, load_function in sorted(type_functions.iteritems()):
for gl_type, load_function in sorted(type_functions.items()):
snippet += " case " + gl_type + ":\n"
requiresConversion = str('LoadToNative<' not in load_function).lower()
snippet += " return LoadImageFunctionInfo(" + load_function + ", " + requiresConversion + ");\n"
@@ -127,13 +127,13 @@ def get_unknown_load_func(angle_to_type_map, internal_format):
def parse_json(json_data):
table_data = ''
load_functions_data = ''
for internal_format, angle_to_type_map in sorted(json_data.iteritems()):
for internal_format, angle_to_type_map in sorted(json_data.items()):
s = ' '
table_data += s + 'case ' + internal_format + ':\n'
do_switch = len(angle_to_type_map) > 1 or angle_to_type_map.keys()[0] != angle_format_unknown
do_switch = len(angle_to_type_map) > 1 or list(angle_to_type_map.keys())[0] != angle_format_unknown
if do_switch:
table_data += s + '{\n'
@@ -142,7 +142,7 @@ def parse_json(json_data):
table_data += s + '{\n'
s += ' '
for angle_format, type_functions in sorted(angle_to_type_map.iteritems()):
for angle_format, type_functions in sorted(angle_to_type_map.items()):
if angle_format == angle_format_unknown:
continue
@@ -154,7 +154,7 @@ def parse_json(json_data):
table_data += s + ' return ' + func_name + ';\n'
if angle_format_unknown in angle_to_type_map:
for gl_type, load_function in angle_to_type_map[angle_format_unknown].iteritems():
for gl_type, load_function in angle_to_type_map[angle_format_unknown].items():
if gl_type not in type_functions:
type_functions[gl_type] = load_function
+1 -1
View File
@@ -186,7 +186,7 @@ class GLDatabase:
headerFile = GLConstHeader(f)
headerFile.formatFileBegin()
constNames = self.consts.keys()
constNames = list(self.consts.keys())
constNames.sort()
for lib in GLDatabase.LIBS:
+6 -6
View File
@@ -66,13 +66,13 @@ def print_joining_table(f):
values[u] = value
short_value = {}
for value in sorted (set ([v for v in values.values ()] + ['JOINING_TYPE_X'])):
for value in sorted (set ([v for v in list(values.values ())] + ['JOINING_TYPE_X'])):
short = ''.join(x[0] for x in value.split('_')[2:])
assert short not in short_value.values()
assert short not in list(short_value.values())
short_value[value] = short
print ()
for value,short in short_value.items():
for value,short in list(short_value.items()):
print ("#define %s %s" % (short, value))
uu = sorted(values.keys())
@@ -149,7 +149,7 @@ def print_joining_table(f):
print (" return X;")
print ("}")
print ()
for value,short in short_value.items():
for value,short in list(short_value.items()):
print ("#undef %s" % (short))
print ()
@@ -217,7 +217,7 @@ def print_shaping_table(f):
print ("static const uint16_t shaping_table[][4] =")
print ("{")
keys = shapes.keys ()
keys = list(shapes.keys ())
min_u, max_u = min (keys), max (keys)
for u in range (min_u, max_u + 1):
s = [shapes[u][shape] if u in shapes and shape in shapes[u] else 0
@@ -234,7 +234,7 @@ def print_shaping_table(f):
ligas_2 = {}
ligas_3 = {}
ligas_mark_2 = {}
for key in ligatures.keys ():
for key in list(ligatures.keys ()):
for shape in ligatures[key]:
c = ligatures[key][shape]
if len(key) == 3:
+1 -1
View File
@@ -57,7 +57,7 @@ print ()
print ('#include "hb-unicode.hh"')
print ()
for typ, s in ranges.items():
for typ, s in list(ranges.items()):
if typ != "Extended_Pictographic": continue
arr = dict()
+11 -11
View File
@@ -68,13 +68,13 @@ for i, f in enumerate (files):
defaults = ('Other', 'Not_Applicable', 'No_Block')
combined = {}
for i,d in enumerate (unicode_data):
for u,v in d.items ():
for u,v in list(d.items ()):
if i == 2 and not u in combined:
continue
if not u in combined:
combined[u] = list (defaults)
combined[u][i] = v
combined = {k:v for k,v in combined.items() if k in ALLOWED_SINGLES or v[2] in ALLOWED_BLOCKS}
combined = {k:v for k,v in list(combined.items()) if k in ALLOWED_SINGLES or v[2] in ALLOWED_BLOCKS}
# Convert categories & positions types
@@ -432,18 +432,18 @@ def position_to_category(pos):
defaults = (category_map[defaults[0]], position_map[defaults[1]], defaults[2])
indic_data = {}
for k, (cat, pos, block) in combined.items():
for k, (cat, pos, block) in list(combined.items()):
cat = category_map[cat]
pos = position_map[pos]
indic_data[k] = (cat, pos, block)
for k,new_cat in category_overrides.items():
for k,new_cat in list(category_overrides.items()):
(cat, pos, _) = indic_data.get(k, defaults)
indic_data[k] = (new_cat, pos, unicode_data[2][k])
# We only expect position for certain types
positioned_categories = ('CM', 'SM', 'RS', 'H', 'M', 'MPst')
for k, (cat, pos, block) in indic_data.items():
for k, (cat, pos, block) in list(indic_data.items()):
if cat not in positioned_categories:
pos = 'END'
indic_data[k] = (cat, pos, block)
@@ -454,7 +454,7 @@ for k, (cat, pos, block) in indic_data.items():
consonant_categories = ('C', 'CS', 'Ra','CM', 'V', 'PLACEHOLDER', 'DOTTEDCIRCLE')
matra_categories = ('M', 'MPst')
smvd_categories = ('SM', 'VD', 'A', 'Symbol')
for k, (cat, pos, block) in indic_data.items():
for k, (cat, pos, block) in list(indic_data.items()):
if cat in consonant_categories:
pos = 'BASE_C'
elif cat in matra_categories:
@@ -466,13 +466,13 @@ for k, (cat, pos, block) in indic_data.items():
pos = 'SMVD';
indic_data[k] = (cat, pos, block)
for k,new_pos in position_overrides.items():
for k,new_pos in list(position_overrides.items()):
(cat, pos, _) = indic_data.get(k, defaults)
indic_data[k] = (cat, new_pos, unicode_data[2][k])
values = [{_: 1} for _ in defaults]
for vv in indic_data.values():
for vv in list(indic_data.values()):
for i,v in enumerate(vv):
values[i][v] = values[i].get (v, 0) + 1
@@ -513,7 +513,7 @@ for shaper in categories:
print ('#include "hb-ot-shaper-%s-machine.hh"' % shaper)
print ()
done = {}
for shaper, shaper_cats in categories.items():
for shaper, shaper_cats in list(categories.items()):
print ('/* %s */' % shaper)
for cat in shaper_cats:
v = shaper[0].upper()
@@ -554,7 +554,7 @@ all_shorts = [{},{}]
# Add some of the values, to make them more readable, and to avoid duplicates
for i in range (2):
for v,s in short[i].items ():
for v,s in list(short[i].items ()):
all_shorts[i][s] = v
what = ["OT", "POS"]
@@ -666,7 +666,7 @@ print (" {")
pages = set ([u>>page_bits for u in starts+ends+list (singles.keys ())])
for p in sorted(pages):
print (" case 0x%0Xu:" % p)
for u,d in singles.items ():
for u,d in list(singles.items ()):
if p != u>>page_bits: continue
print (" if (unlikely (u == 0x%04Xu)) return _(%s,%s);" % (u, short[0][d[0]], short[1][d[1]]))
for (start,end) in zip (starts, ends):
+8 -8
View File
@@ -405,7 +405,7 @@ class OpenTypeRegistryParser (HTMLParser):
with open (filename, encoding='utf-8') as f:
self.feed (f.read ())
expect (self.header)
for tag, iso_codes in self.to_bcp_47.items ():
for tag, iso_codes in list(self.to_bcp_47.items ()):
for iso_code in iso_codes:
self.from_bcp_47[iso_code].add (tag)
@@ -483,7 +483,7 @@ class OpenTypeRegistryParser (HTMLParser):
first_time = self.from_bcp_47_uninherited is None
if first_time:
self.from_bcp_47_uninherited = dict (self.from_bcp_47)
for macrolanguage, languages in dict (bcp_47.macrolanguages).items ():
for macrolanguage, languages in list(dict (bcp_47.macrolanguages).items ()):
ot_macrolanguages = {
ot_macrolanguage for ot_macrolanguage in self.from_bcp_47_uninherited.get (macrolanguage, set ())
}
@@ -521,7 +521,7 @@ class OpenTypeRegistryParser (HTMLParser):
def sort_languages (self):
"""Sort the values of ``from_bcp_47`` in ascending rank order."""
for language, tags in self.from_bcp_47.items ():
for language, tags in list(self.from_bcp_47.items ()):
self.from_bcp_47[language] = sorted (tags,
key=lambda t: (self.ranks[t] + rank_delta (language, t), t))
@@ -642,10 +642,10 @@ class BCP47Parser (object):
def remove_extra_macrolanguages (self):
"""Make every language have at most one macrolanguage."""
inverted = collections.defaultdict (list)
for macrolanguage, languages in self.macrolanguages.items ():
for macrolanguage, languages in list(self.macrolanguages.items ()):
for language in languages:
inverted[language].append (macrolanguage)
for language, macrolanguages in inverted.items ():
for language, macrolanguages in list(inverted.items ()):
if len (macrolanguages) > 1:
macrolanguages.sort (key=lambda ml: len (self.macrolanguages[ml]))
biggest_macrolanguage = macrolanguages.pop ()
@@ -1008,7 +1008,7 @@ def print_subtag_matches (subtag, string, new_line):
complex_tags = collections.defaultdict (list)
for initial, group in itertools.groupby ((lt_tags for lt_tags in [
(LanguageTag (language), tags)
for language, tags in sorted (ot.from_bcp_47.items (),
for language, tags in sorted (list(ot.from_bcp_47.items ()),
key=lambda i: (-len (i[0]), i[0]))
] if lt_tags[0].is_complex ()),
key=lambda lt_tags: lt_tags[0].get_group ()):
@@ -1160,7 +1160,7 @@ def verify_disambiguation_dict ():
global bcp_47
global disambiguation
global ot
for ot_tag, bcp_47_tags in ot.to_bcp_47.items ():
for ot_tag, bcp_47_tags in list(ot.to_bcp_47.items ()):
if ot_tag == DEFAULT_LANGUAGE_SYSTEM:
primary_tags = []
else:
@@ -1194,7 +1194,7 @@ def verify_disambiguation_dict ():
different_bcp_47_tags = sorted (t for t in bcp_47_tags if not same_tag (t, ot.from_bcp_47.get (t)))
if different_bcp_47_tags and disambiguation[ot_tag] == different_bcp_47_tags[0] and '-' not in disambiguation[ot_tag]:
del disambiguation[ot_tag]
for ot_tag in disambiguation.keys ():
for ot_tag in list(disambiguation.keys ()):
expect (ot_tag in ot.to_bcp_47, 'unknown OT tag: %s' % ot_tag)
verify_disambiguation_dict ()
+3 -3
View File
@@ -51,15 +51,15 @@ dm = {i:tuple(int(v, 16) for v in u['dm'].split()) for i,u in enumerate(ucd)
if u['dm'] != '#' and u['dt'] == 'can' and not (0xAC00 <= i < 0xAC00+11172)}
ce = {i for i,u in enumerate(ucd) if u['Comp_Ex'] == 'Y'}
assert not any(v for v in dm.values() if len(v) not in (1,2))
dm1 = sorted(set(v for v in dm.values() if len(v) == 1))
assert not any(v for v in list(dm.values()) if len(v) not in (1,2))
dm1 = sorted(set(v for v in list(dm.values()) if len(v) == 1))
assert all((v[0] >> 16) in (0,2) for v in dm1)
dm1_p0_array = ['0x%04Xu' % (v[0] & 0xFFFF) for v in dm1 if (v[0] >> 16) == 0]
dm1_p2_array = ['0x%04Xu' % (v[0] & 0xFFFF) for v in dm1 if (v[0] >> 16) == 2]
dm1_order = {v:i+1 for i,v in enumerate(dm1)}
dm2 = sorted((v+(i if i not in ce and not ccc[i] else 0,), v)
for i,v in dm.items() if len(v) == 2)
for i,v in list(dm.items()) if len(v) == 2)
filt = lambda v: ((v[0] & 0xFFFFF800) == 0x0000 and
(v[1] & 0xFFFFFF80) == 0x0300 and
+8 -8
View File
@@ -86,13 +86,13 @@ for i,v in enumerate (defaults):
values[i][v] = values[i].get (v, 0) + 1
combined = {}
for i,d in enumerate (unicode_data):
for u,v in d.items ():
for u,v in list(d.items ()):
if not u in combined:
if i >= 4:
continue
combined[u] = list (defaults)
combined[u][i] = v
combined = {k: v for k, v in combined.items() if v[6] not in DISABLED_SCRIPTS}
combined = {k: v for k, v in list(combined.items()) if v[6] not in DISABLED_SCRIPTS}
property_names = [
@@ -350,8 +350,8 @@ use_positions = {
def map_to_use(data):
out = {}
items = use_mapping.items()
for U, (UISC, UIPC, AJT, UDI, UGC, UBlock, _) in data.items():
items = list(use_mapping.items())
for U, (UISC, UIPC, AJT, UDI, UGC, UBlock, _) in list(data.items()):
# Resolve Indic_Syllabic_Category
@@ -381,7 +381,7 @@ def map_to_use(data):
pos_mapping = use_positions.get(USE, None)
if pos_mapping:
values = [k for k,v in pos_mapping.items() if v and UIPC in v]
values = [k for k,v in list(pos_mapping.items()) if v and UIPC in v]
assert len(values) == 1, "%s %s %s %s %s %s %s %s" % (hex(U), UIPC, USE, UISC, UDI, UGC, AJT, values)
USE = USE + values[0]
@@ -459,7 +459,7 @@ for k,v in sorted(use_mapping.items()):
print ("#define %s USE(%s) /* %s */" % (k, k, v.__name__[3:]))
for k,v in sorted(use_positions.items()):
if not v: continue
for suf in v.keys():
for suf in list(v.keys()):
tag = k + suf
print ("#define %s USE(%s)" % (tag, tag))
print ('#pragma GCC diagnostic pop')
@@ -467,7 +467,7 @@ print ("")
import packTab
data = {u:v[0] for u,v in use_data.items()}
data = {u:v[0] for u,v in list(use_data.items())}
DEFAULT = 5
COMPACT = 9
@@ -498,7 +498,7 @@ for k in sorted(use_mapping.keys()):
print ("#undef %s" % k)
for k,v in sorted(use_positions.items()):
if not v: continue
for suf in v.keys():
for suf in list(v.keys()):
tag = k + suf
print ("#undef %s" % tag)
print ()
+2 -2
View File
@@ -110,7 +110,7 @@ class ConstraintSet (object):
cases = collections.defaultdict (set)
for first, rest in sorted (self._c.items ()):
cases[rest.__str__ (index + 1, depth + 2)].add (first)
for body, labels in sorted (cases.items (), key=lambda b_ls: sorted (b_ls[1])[0]):
for body, labels in sorted (list(cases.items ()), key=lambda b_ls: sorted (b_ls[1])[0]):
for i, cp in enumerate (sorted (labels)):
if i % 4 == 0:
s.append (self._indent (depth + 1))
@@ -205,7 +205,7 @@ print (' unsigned int count = buffer->len;')
print (' switch ((unsigned) buffer->props.script)')
print (' {')
for script, constraints in sorted (constraints.items (), key=lambda s_c: script_order[s_c[0]]):
for script, constraints in sorted (list(constraints.items ()), key=lambda s_c: script_order[s_c[0]]):
print((' case HB_SCRIPT_{}:'.format (script.upper ())))
print (' for (buffer->idx = 0; buffer->idx + 1 < count && buffer->successful;)')
print (' {')
+1 -1
View File
@@ -31,7 +31,7 @@ for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
for key, val in list(generator_flags.items()):
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
+2 -2
View File
@@ -174,7 +174,7 @@ def generate_platform_sources():
sources[plat] = set(v.replace('../', 'skia/') for v in json.load(f));
f.close()
return dict(sources.items() + generate_opt_sources().items())
return dict(list(sources.items()) + list(generate_opt_sources().items()))
def generate_separated_sources(platform_sources):
@@ -281,7 +281,7 @@ def generate_separated_sources(platform_sources):
'gpu': set()
})
for plat in platform_sources.keys():
for plat in list(platform_sources.keys()):
for value in platform_sources[plat]:
if isblacklisted(value):
continue
@@ -398,7 +398,7 @@ class ResourceFilterInfo(object):
new_requests = []
i = 0
for rules, filter_files in unique_rules.items():
for rules, filter_files in list(unique_rules.items()):
base_filter_file = filter_files[0]
new_requests += [
PrintFileRequest(
@@ -451,7 +451,7 @@ def _apply_resource_filters(all_requests, config, io):
# Add the filter generation requests to the beginning so that by default
# they are made before genrb gets run (order is required by windirect)
new_requests = []
for filter_info in collected.values():
for filter_info in list(collected.values()):
new_requests += filter_info.make_requests()
new_requests += all_requests
return new_requests
@@ -106,7 +106,7 @@ class AbstractExecutionRequest(AbstractRequest):
def _del_at(self, i):
del self.input_files[i]
for _, v in self.format_with.items():
for _, v in list(self.format_with.items()):
if isinstance(v, list):
assert len(v) == len(self.input_files) + 1
del v[i]
@@ -177,7 +177,7 @@ class RepeatedExecutionRequest(AbstractExecutionRequest):
super(RepeatedExecutionRequest, self)._del_at(i)
del self.output_files[i]
del self.specific_dep_files[i]
for _, v in self.repeat_with.items():
for _, v in list(self.repeat_with.items()):
if isinstance(v, list):
del v[i]
@@ -222,7 +222,7 @@ class RepeatedOrSingleExecutionRequest(AbstractExecutionRequest):
def _del_at(self, i):
super(RepeatedOrSingleExecutionRequest, self)._del_at(i)
del self.output_files[i]
for _, v in self.repeat_with.items():
for _, v in list(self.repeat_with.items()):
if isinstance(v, list):
del v[i]
@@ -46,7 +46,7 @@ def get_local_dirname(dirname):
return LOCAL_DIRNAME_SUBSTITUTIONS[variable] + dirname[sep_idx:]
print(
"Error: Local directory must be absolute, or relative to one of: " +
(", ".join("$%s" % v for v in LOCAL_DIRNAME_SUBSTITUTIONS.keys())),
(", ".join("$%s" % v for v in list(LOCAL_DIRNAME_SUBSTITUTIONS.keys()))),
file=sys.stderr
)
exit(1)
@@ -77,7 +77,7 @@ def repeated_execution_request_looper(request):
# dictionary of lists to list of dictionaries:
ld = [
dict(list(zip(request.repeat_with, t)))
for t in zip(*request.repeat_with.values())
for t in zip(*list(request.repeat_with.values()))
]
if not ld:
# No special options given in repeat_with
+1 -1
View File
@@ -15,7 +15,7 @@ def main(header, propFile):
if len(parts) == 2 and len(parts[0]) > 0:
mappings[parts[0].strip()] = parts[1].strip()
keys = mappings.keys()
keys = list(mappings.keys())
keys.sort()
header.write("// This is a generated file. Please do not edit.\n")
+1 -1
View File
@@ -412,7 +412,7 @@ class Entry:
"optaddarg" :
self._optaddarg and ", const %s value" % self._ctype or ""
}
for (k, v) in extradict.items():
for (k, v) in list(extradict.items()):
mapping[k] = v
return mapping
+1 -1
View File
@@ -1730,7 +1730,7 @@ class _GenerateProtocolCode(ipdl.ast.Visitor):
transitions.append(ifsametrigger)
msgToTransitions[msgid] = transitions
for msgid, transitions in msgToTransitions.iteritems():
for msgid, transitions in msgToTransitions.items():
block = Block()
block.addstmts(transitions +[ StmtBreak() ])
msgswitch.addcase(CaseLabel(msgid), block)
+6 -6
View File
@@ -1581,7 +1581,7 @@ class Process:
self.spawn.add(spawn)
def iteredges(self):
for edgelist in self.edges.itervalues():
for edgelist in self.edges.values():
for edge in edgelist:
yield edge
@@ -1690,7 +1690,7 @@ class ProcessGraph:
@classmethod
def iterbridges(cls):
for edges in cls.bridges.itervalues():
for edges in cls.bridges.values():
for bridge in edges:
yield bridge
@@ -1711,7 +1711,7 @@ class ProcessGraph:
@classmethod
def iteropens(cls):
for edges in cls.opens.itervalues():
for edges in cls.opens.values():
for opens in edges:
yield opens
@@ -1885,11 +1885,11 @@ class CheckProcessGraph(TcheckVisitor):
for edge in process.iteredges():
print(' ', edge)
print('Bridges')
for bridgeList in ProcessGraph.bridges.itervalues():
for bridgeList in ProcessGraph.bridges.values():
for bridge in bridgeList:
print(' ', bridge)
print('Opens')
for opensList in ProcessGraph.opens.itervalues():
for opensList in ProcessGraph.opens.values():
for opens in opensList:
print(' ', opens)
@@ -2140,7 +2140,7 @@ direction as trigger |t|'''
root.loc,
"when starting from state `%s', actors of protocol `%s' cannot be deleted", root.state.name, p.name)
for ts in p.states.itervalues():
for ts in p.states.values():
if ts.state is not State.DEAD and ts.state not in allvisited:
self.error(ts.loc,
"unreachable state `%s' in protocol `%s'",
+1 -1
View File
@@ -132,7 +132,7 @@ def messages(jsmsg):
def get_config_defines(buildconfig):
# Collect defines equivalent to ACDEFINES and add MOZ_DEBUG_DEFINES.
env = {key: value for key, value in buildconfig.defines.iteritems()
env = {key: value for key, value in buildconfig.defines.items()
if key not in buildconfig.non_global_defines}
for define in buildconfig.substs['MOZ_DEBUG_DEFINES']:
env[define] = 1
+39 -39
View File
@@ -64,7 +64,7 @@ def writeMappingsVar(println, mapping, name, description, source, url):
println(u"")
writeMappingHeader(println, description, source, url)
println(u"var {0} = {{".format(name))
for (key, value) in sorted(mapping.items(), key=itemgetter(0)):
for (key, value) in sorted(list(mapping.items()), key=itemgetter(0)):
println(u' "{0}": "{1}",'.format(key, value))
println(u"};")
@@ -103,7 +103,7 @@ bool js::intl::LanguageTag::{0}({1} {2}) {{
# Sort the subtags by length. That enables using an optimized comparator
# for the binary search, which only performs a single |memcmp| for multiple
# of two subtag lengths.
mappings_keys = mappings.keys() if type(mappings) == dict else mappings
mappings_keys = list(mappings.keys()) if type(mappings) == dict else mappings
for (length, subtags) in groupby(sorted(mappings_keys, key=len), len):
# Omit the length check if the current length is the maximum length.
if length != tag_maxlength:
@@ -198,7 +198,7 @@ void js::intl::LanguageTag::performComplexLanguageMappings() {
# Merge duplicate language entries.
language_aliases = {}
for (deprecated_language, (language, script, region)) in (
sorted(complex_language_mappings.items(), key=itemgetter(0))
sorted(list(complex_language_mappings.items()), key=itemgetter(0))
):
key = (language, script, region)
if key not in language_aliases:
@@ -208,7 +208,7 @@ void js::intl::LanguageTag::performComplexLanguageMappings() {
first_language = True
for (deprecated_language, (language, script, region)) in (
sorted(complex_language_mappings.items(), key=itemgetter(0))
sorted(list(complex_language_mappings.items()), key=itemgetter(0))
):
key = (language, script, region)
if deprecated_language in language_aliases[key]:
@@ -265,7 +265,7 @@ void js::intl::LanguageTag::performComplexRegionMappings() {
# Merge duplicate region entries.
region_aliases = {}
for (deprecated_region, (default, non_default_replacements)) in (
sorted(complex_region_mappings.items(), key=itemgetter(0))
sorted(list(complex_region_mappings.items()), key=itemgetter(0))
):
key = hash_key(default, non_default_replacements)
if key not in region_aliases:
@@ -275,7 +275,7 @@ void js::intl::LanguageTag::performComplexRegionMappings() {
first_region = True
for (deprecated_region, (default, non_default_replacements)) in (
sorted(complex_region_mappings.items(), key=itemgetter(0))
sorted(list(complex_region_mappings.items()), key=itemgetter(0))
):
key = hash_key(default, non_default_replacements)
if deprecated_region in region_aliases[key]:
@@ -380,7 +380,7 @@ bool js::intl::LanguageTag::performVariantMappings(JSContext* cx) {
first_variant = True
for (deprecated_variant, (type, replacement)) in (
sorted(variant_mappings.items(), key=itemgetter(0))
sorted(list(variant_mappings.items()), key=itemgetter(0))
):
if_kind = u"if" if first_variant else u"else if"
first_variant = False
@@ -498,7 +498,7 @@ bool js::intl::LanguageTag::updateGrandfatheredMappings(JSContext* cx) {
is_first = True
for (tag, modern) in sorted(grandfathered_mappings.items(), key=itemgetter(0)):
for (tag, modern) in sorted(list(grandfathered_mappings.items()), key=itemgetter(0)):
tag_match = re_unicode_locale_id.match(tag)
assert tag_match is not None
@@ -823,12 +823,12 @@ def readSupplementalData(core_file):
complex_region_mappings_final = {}
for (deprecated_region, replacements) in complex_region_mappings.items():
for (deprecated_region, replacements) in list(complex_region_mappings.items()):
# Find all likely subtag entries which don't already contain a region
# subtag and whose target region is in the list of replacement regions.
region_likely_subtags = [(from_language, from_script, to_region)
for ((from_language, from_script, from_region),
(_, _, to_region)) in likely_subtags.items()
(_, _, to_region)) in list(likely_subtags.items())
if from_region is None and to_region in replacements]
# The first replacement entry is the default region.
@@ -1152,7 +1152,7 @@ static bool IsCanonicallyCasedTransformType(mozilla::Span<const char> type) {
"const LanguageSubtag&", "language",
"IsStructurallyValidLanguageTag",
"IsCanonicallyCasedLanguageTag",
complex_language_mappings.keys(), language_maxlength,
list(complex_language_mappings.keys()), language_maxlength,
"Language subtags with complex mappings.", source, url)
writeMappingsBinarySearch(println, "regionMapping",
"RegionSubtag&", "region",
@@ -1164,7 +1164,7 @@ static bool IsCanonicallyCasedTransformType(mozilla::Span<const char> type) {
"const RegionSubtag&", "region",
"IsStructurallyValidRegionTag",
"IsCanonicallyCasedRegionTag",
complex_region_mappings.keys(), region_maxlength,
list(complex_region_mappings.keys()), region_maxlength,
"Region subtags with complex mappings.", source, url)
writeComplexLanguageTagMappings(println, complex_language_mappings,
@@ -1282,17 +1282,17 @@ def writeCLDRLanguageTagLikelySubtagsTest(println, data, url):
return to_canonical
# |likely_subtags| contains non-canonicalized tags, so canonicalize it first.
likely_subtags_canonical = {k: likely_canonical(k, v) for (k, v) in likely_subtags.items()}
likely_subtags_canonical = {k: likely_canonical(k, v) for (k, v) in list(likely_subtags.items())}
# Add test data for |Intl.Locale.prototype.maximize()|.
writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in likely_subtags_canonical.items()},
writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in list(likely_subtags_canonical.items())},
"maxLikelySubtags", "Extracted from likelySubtags.xml.", source, url)
# Use the maximalized tags as the input for the remove likely-subtags test.
minimized = {tag: removeLikelySubtags(tag) for tag in likely_subtags_canonical.values()}
minimized = {tag: removeLikelySubtags(tag) for tag in list(likely_subtags_canonical.values())}
# Add test data for |Intl.Locale.prototype.minimize()|.
writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in minimized.items()},
writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in list(minimized.items())},
"minLikelySubtags", "Extracted from likelySubtags.xml.", source, url)
println(u"""
@@ -1435,13 +1435,13 @@ class TzDataFile:
def validateTimeZones(zones, links):
""" Validate the zone and link entries. """
linkZones = set(links.viewkeys())
linkZones = set(links.keys())
intersect = linkZones.intersection(zones)
if intersect:
raise RuntimeError("Links also present in zones: %s" % intersect)
zoneNames = set(z.name for z in zones)
linkTargets = set(links.viewvalues())
linkTargets = set(links.values())
if not linkTargets.issubset(zoneNames):
raise RuntimeError("Link targets not found: %s" % linkTargets.difference(zoneNames))
@@ -1507,7 +1507,7 @@ def readIANATimeZones(tzdataDir, ignoreBackzone, ignoreFactory):
# Merge with backzone data.
if not ignoreBackzone:
zones |= backzones
links = {name: target for name, target in links.iteritems() if name not in backzones}
links = {name: target for name, target in links.items() if name not in backzones}
links.update(backlinks)
validateTimeZones(zones, links)
@@ -1644,7 +1644,7 @@ def readICUTimeZonesFromZoneInfo(icuTzDir):
elif name == namesKey:
tzNames.extend(value)
links = dict((Zone(tzNames[zone]), tzNames[target]) for (zone, target) in tzLinks.iteritems())
links = dict((Zone(tzNames[zone]), tzNames[target]) for (zone, target) in tzLinks.items())
zones = set([Zone(v) for v in tzNames if Zone(v) not in links])
validateTimeZones(zones, links)
@@ -1673,7 +1673,7 @@ def readICUTimeZones(icuDir, icuTzDir, ignoreFactory):
# Remove any outdated ICU links.
for links in (zoneinfoLinks, typesLinks):
for zone in otherICULegacyLinks().keys():
for zone in list(otherICULegacyLinks().keys()):
if zone not in links:
raise KeyError("Can't remove non-existent link from '%s'" % zone)
del links[zone]
@@ -1685,7 +1685,7 @@ def readICUTimeZones(icuDir, icuTzDir, ignoreFactory):
if notFoundInZoneInfo64:
raise RuntimeError("Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64)
notFoundInZoneInfo64 = [zone for zone in typesLinks.iterkeys() if not inZoneInfo64(zone)]
notFoundInZoneInfo64 = [zone for zone in typesLinks.keys() if not inZoneInfo64(zone)]
if notFoundInZoneInfo64:
raise RuntimeError("Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64)
@@ -1697,8 +1697,8 @@ def readICUTimeZones(icuDir, icuTzDir, ignoreFactory):
(zone for zone in typesZones)
))
icuLinks = dict(chain(
((zone, target) for (zone, target) in zoneinfoLinks.iteritems() if zone not in typesZones),
((zone, target) for (zone, target) in typesLinks.iteritems())
((zone, target) for (zone, target) in zoneinfoLinks.items() if zone not in typesZones),
((zone, target) for (zone, target) in typesLinks.items())
))
return (icuZones, icuLinks)
@@ -1723,7 +1723,7 @@ def readICULegacyZones(icuDir):
# A handful of non-IANA zones/links are not in icuzones and must be added
# manually so that we won't invoke ICU with them.
for (zone, target) in otherICULegacyLinks().items():
for (zone, target) in list(otherICULegacyLinks().items()):
if zone in links:
if links[zone] != target:
raise KeyError(
@@ -1813,23 +1813,23 @@ def findIncorrectICULinks(ianaZones, ianaLinks, icuZones, icuLinks):
isICUZone = lambda zone: zone in icuZones
# All links should be present in ICU.
missingTimeZones = [zone for zone in ianaLinks.iterkeys() if not isICUTimeZone(zone)]
missingTimeZones = [zone for zone in ianaLinks.keys() if not isICUTimeZone(zone)]
if missingTimeZones:
raise RuntimeError("Not all zones are present in ICU, did you forget "
"to run intl/update-tzdata.sh? %s" % missingTimeZones)
# Links which are only present in ICU?
additionalTimeZones = [zone for zone in icuLinks.iterkeys() if not isIANATimeZone(zone)]
additionalTimeZones = [zone for zone in icuLinks.keys() if not isIANATimeZone(zone)]
if additionalTimeZones:
raise RuntimeError("Additional links present in ICU, did you forget "
"to run intl/update-tzdata.sh? %s" % additionalTimeZones)
result = chain(
# IANA links which have a different target in ICU.
((zone, target, icuLinks[zone]) for (zone, target) in ianaLinks.iteritems() if isICULink(zone) and target != icuLinks[zone]),
((zone, target, icuLinks[zone]) for (zone, target) in ianaLinks.items() if isICULink(zone) and target != icuLinks[zone]),
# IANA links which are zones in ICU.
((zone, target, zone.name) for (zone, target) in ianaLinks.iteritems() if isICUZone(zone))
((zone, target, zone.name) for (zone, target) in ianaLinks.items() if isICUZone(zone))
)
# Remove unnecessary UTC mappings.
@@ -1851,7 +1851,7 @@ def processTimeZones(tzdataDir, icuDir, icuTzDir, version, ignoreBackzone, ignor
# Remove all egacy ICU time zones.
icuZones = {zone for zone in icuZones if zone not in legacyZones}
icuLinks = {
zone: target for (zone, target) in icuLinks.items() if zone not in legacyLinks
zone: target for (zone, target) in list(icuLinks.items()) if zone not in legacyLinks
}
incorrectZones = findIncorrectICUZones(ianaZones, ianaLinks, icuZones, icuLinks, ignoreBackzone)
@@ -1919,7 +1919,7 @@ def processTimeZones(tzdataDir, icuDir, icuTzDir, version, ignoreBackzone, ignor
def updateBackzoneLinks(tzdataDir, links):
(backzoneZones, backzoneLinks) = readIANAFiles(tzdataDir, ["backzone"])
(stableZones, updatedLinks, updatedZones) = partition(
links.iteritems(),
iter(links.items()),
# Link not changed in backzone.
lambda (zone, target): zone not in backzoneLinks and zone not in backzoneZones,
# Link has a new target.
@@ -1981,7 +1981,7 @@ def generateTzDataTestBackwardLinks(tzdataDir, version, ignoreBackzone, testDir)
testDir, version,
"timeZone_backward_links.js",
u"// Link names derived from IANA Time Zone Database, backward file.",
links.iteritems()
iter(links.items())
)
def generateTzDataTestNotBackwardLinks(tzdataDir, version, ignoreBackzone, testDir):
@@ -1995,7 +1995,7 @@ def generateTzDataTestNotBackwardLinks(tzdataDir, version, ignoreBackzone, testD
testDir, version,
"timeZone_notbackward_links.js",
u"// Link names derived from IANA Time Zone Database, excluding backward file.",
links.iteritems()
iter(links.items())
)
def generateTzDataTestBackzone(tzdataDir, version, ignoreBackzone, testDir):
@@ -2056,7 +2056,7 @@ def generateTzDataTestBackzoneLinks(tzdataDir, version, ignoreBackzone, testDir)
testDir, version,
"timeZone_backzone_links.js",
comment + u"// Backzone links derived from IANA Time Zone Database.",
((zone, target if not ignoreBackzone else links[zone]) for (zone, target) in backlinks.iteritems())
((zone, target if not ignoreBackzone else links[zone]) for (zone, target) in backlinks.items())
)
def generateTzDataTests(tzdataDir, version, ignoreBackzone, testDir):
@@ -2146,8 +2146,8 @@ static inline bool Is{0}Type(
linear_search_max_length = 4
needs_binary_search = any(len(replacements.items()) > linear_search_max_length
for replacements in mapping.values())
needs_binary_search = any(len(list(replacements.items())) > linear_search_max_length
for replacements in list(mapping.values()))
if needs_binary_search:
println(u"""
@@ -2220,7 +2220,7 @@ const char* js::intl::LanguageTag::replace{0}ExtensionType(
# Merge duplicate keys.
key_aliases = {}
for (key, replacements) in sorted(mapping.items(), key=itemgetter(0)):
for (key, replacements) in sorted(list(mapping.items()), key=itemgetter(0)):
hash_key = to_hash_key(replacements)
if hash_key not in key_aliases:
key_aliases[hash_key] = []
@@ -2228,7 +2228,7 @@ const char* js::intl::LanguageTag::replace{0}ExtensionType(
key_aliases[hash_key].append(key)
first_key = True
for (key, replacements) in sorted(mapping.items(), key=itemgetter(0)):
for (key, replacements) in sorted(list(mapping.items()), key=itemgetter(0)):
hash_key = to_hash_key(replacements)
if key in key_aliases[hash_key]:
continue
@@ -2242,7 +2242,7 @@ const char* js::intl::LanguageTag::replace{0}ExtensionType(
{} ({}) {{""".format(if_kind, cond).strip("\n"))
first_key = False
replacements = sorted(replacements.items(), key=itemgetter(0))
replacements = sorted(list(replacements.items()), key=itemgetter(0))
if len(replacements) > linear_search_max_length:
types = [t for (t, _) in replacements]
@@ -194,7 +194,7 @@ def generate_source_and_headers(generate_osx=True, generate_ios=True):
build_target(desktop64_platform, platform_headers)
mkdir_p('darwin_common/include')
for header_name, tag_tuples in platform_headers.iteritems():
for header_name, tag_tuples in platform_headers.items():
basename, suffix = os.path.splitext(header_name)
with open(os.path.join('darwin_common/include', header_name), 'w') as header:
for tag_tuple in tag_tuples:
+1 -1
View File
@@ -274,7 +274,7 @@ def run_command(command, check=False, **kwargs):
# Add in environment variable settings for this variant. Normally used to
# modify the flags passed to the shell or to set the GC zeal mode.
for k, v in variant.get('env', {}).items():
for k, v in list(variant.get('env', {}).items()):
env[k] = v.format(
DIR=DIR.scripts,
TOOLTOOL_CHECKOUT=DIR.tooltool,
+2 -2
View File
@@ -87,11 +87,11 @@ def run_tests(tests, test_dir):
print('fail')
return dict((filename, dict(TMax=TMax, TAvg=TAvg, MMax=MMax, MAvg=MAvg, SMax=SMax, SAvg=SAvg))
for filename, (TMax, TAvg, MMax, MAvg, SMax, SAvg) in bench_map.iteritems())
for filename, (TMax, TAvg, MMax, MAvg, SMax, SAvg) in bench_map.items())
def compare(current, baseline):
percent_speedups = []
for key, current_result in current.iteritems():
for key, current_result in current.items():
try:
baseline_result = baseline[key]
except KeyError:
+4 -4
View File
@@ -44,12 +44,12 @@ def print_command(command, outfile=None, env=None):
if env:
changed = {}
e = os.environ
for key,value in env.items():
for key,value in list(env.items()):
if (key not in e) or (e[key] != value):
changed[key] = value
if changed:
outputs = []
for key, value in changed.items():
for key, value in list(changed.items()):
if key in e and e[key] in value:
start = value.index(e[key])
end = start + len(e[key])
@@ -184,7 +184,7 @@ def run_job(name, config):
else:
with open(stdout_filename, 'w') as output:
subprocess.check_call(command, stdout=output, env=env(config))
for (temp, final) in temp_map.items():
for (temp, final) in list(temp_map.items()):
try:
os.rename(temp, final)
except OSError:
@@ -232,7 +232,7 @@ for default in defaults:
data = config.copy()
for k,v in vars(args).items():
for k,v in list(vars(args).items()):
if v is not None:
data[k] = v
+2 -2
View File
@@ -21,14 +21,14 @@ class Body(dict):
# Indexes
self['Line2Points'] = defaultdict(list)
for point, line in self['Points'].items():
for point, line in list(self['Points'].items()):
self['Line2Points'][line].append(point)
self['SrcPoint2Edges'] = defaultdict(list)
for edge in self['Edges']:
src, dst = edge['Index']
self['SrcPoint2Edges'][src].append(edge)
self['Line2Edges'] = defaultdict(list)
for (src, edges) in self['SrcPoint2Edges'].items():
for (src, edges) in list(self['SrcPoint2Edges'].items()):
line = self['Points'][src]
self['Line2Edges'][line].extend(edges)
+2 -2
View File
@@ -80,7 +80,7 @@ def split_list_per_column(reserved_word_list, column):
per_column = column_dict.setdefault(word[column], [])
per_column.append(item)
return sorted(column_dict.items(), key=lambda (char, word): ord(char))
return sorted(list(column_dict.items()), key=lambda (char, word): ord(char))
def generate_letter_switch(opt, unprocessed_columns, reserved_word_list,
columns=None):
@@ -161,7 +161,7 @@ def split_list_per_length(reserved_word_list):
per_length = length_dict.setdefault(len(word), [])
per_length.append(item)
return sorted(length_dict.items(), key=lambda (length, word): length)
return sorted(list(length_dict.items()), key=lambda (length, word): length)
def generate_switch(opt, reserved_word_list):
assert(len(reserved_word_list) != 0);
+1 -1
View File
@@ -178,7 +178,7 @@ class jsvalTypeCache(object):
# the i'th magic value.
d = gdb.types.make_enum_dict(gdb.lookup_type('JSWhyMagic'))
self.magic_names = list(range(max(d.values()) + 1))
for (k,v) in d.items(): self.magic_names[v] = k
for (k,v) in list(d.items()): self.magic_names[v] = k
# Choose an unboxing scheme for this architecture.
self.boxer = Punbox if cache.void_ptr_t.sizeof == 8 else Nunbox
+1 -1
View File
@@ -107,7 +107,7 @@ def clear_module_printers(module_name):
# should remove. (It's not safe to delete entries from a dictionary
# while we're iterating over it.)
to_delete = []
for (k, v) in d.items():
for (k, v) in list(d.items()):
if v.__module__ == module_name:
to_delete.append(k)
remove_from_subprinter_list(v)
+2 -2
View File
@@ -80,7 +80,7 @@ def split_list_per_column(keyword_list, column):
per_column = column_dict.setdefault(keyword[column], [])
per_column.append(item)
return sorted(column_dict.items(), key=lambda (char, keyword): ord(char))
return sorted(list(column_dict.items()), key=lambda (char, keyword): ord(char))
def generate_letter_switch(opt, unprocessed_columns, keyword_list,
columns=None):
@@ -161,7 +161,7 @@ def split_list_per_length(keyword_list):
per_length = length_dict.setdefault(len(keyword), [])
per_length.append(item)
return sorted(length_dict.items(), key=lambda (length, keyword): length)
return sorted(list(length_dict.items()), key=lambda (length, keyword): length)
def generate_switch(opt, keyword_list):
assert(len(keyword_list) != 0);
+1 -1
View File
@@ -15,7 +15,7 @@ def avg(seq):
def compare(current, baseline):
percent_speedups = []
for key, current_result in current.iteritems():
for key, current_result in current.items():
try:
baseline_result = baseline[key]
except KeyError:
+1 -1
View File
@@ -567,7 +567,7 @@ def process_test_results(results, num_tests, pb, options):
sys.stdout.write(res.err)
if options.check_output:
if res.test.path in output_dict.keys():
if res.test.path in list(output_dict.keys()):
if output_dict[res.test.path] != res.out:
pb.message("FAIL - OUTPUT DIFFERS {}".format(res.test.relpath_tests))
else:
+1 -1
View File
@@ -199,7 +199,7 @@ def _emit_manifest_at(location, relative, test_gen, depth):
filename = os.path.join(location, 'jstests.list')
manifest = []
numTestFiles = 0
for k, test_list in manifests.iteritems():
for k, test_list in manifests.items():
fullpath = os.path.join(location, k)
if os.path.isdir(fullpath):
manifest.append("include " + k + "/jstests.list")
+1 -1
View File
@@ -131,7 +131,7 @@ class ResultsSink:
dev_label = self.LABELS[tup][1]
if self.options.check_output:
if output.test.path in self.output_dict.keys():
if output.test.path in list(self.output_dict.keys()):
if self.output_dict[output.test.path] != output:
self.counts['FAIL'] += 1
self.print_automation_result(
+3 -3
View File
@@ -50,7 +50,7 @@ def get_jitflags(variant, **kwargs):
return JITFLAGS[variant]
def valid_jitflags():
return JITFLAGS.keys()
return list(JITFLAGS.keys())
def get_environment_overlay(js_shell):
"""
@@ -81,7 +81,7 @@ def get_environment_overlay(js_shell):
def change_env(env_overlay):
# Apply the overlaid environment and record the current state.
prior_env = {}
for key, val in env_overlay.items():
for key, val in list(env_overlay.items()):
prior_env[key] = os.environ.get(key, None)
if 'PATH' in key and key in os.environ:
os.environ[key] = '{}{}{}'.format(val, os.pathsep, os.environ[key])
@@ -94,7 +94,7 @@ def change_env(env_overlay):
finally:
# Restore the prior environment.
for key, val in prior_env.items():
for key, val in list(prior_env.items()):
if val is not None:
os.environ[key] = val
else:
+2 -2
View File
@@ -96,7 +96,7 @@ def parsemark(filepaths, fbench, stfu=False):
print('Parsemarking {}...'.format(filename))
bench_map[filename] = fbench(filepath)
print('{')
for i, (filename, (avg, stddev)) in enumerate(bench_map.iteritems()):
for i, (filename, (avg, stddev)) in enumerate(bench_map.items()):
assert '"' not in filename
fmt = ' {:30s}: {{"average_ms": {:6.2f}, "stddev_ms": {:6.2f}}}'
if i != len(bench_map) - 1:
@@ -105,7 +105,7 @@ def parsemark(filepaths, fbench, stfu=False):
print(fmt.format(filename_str, avg, stddev))
print('}')
return dict((filename, dict(average_ms=avg, stddev_ms=stddev))
for filename, (avg, stddev) in bench_map.iteritems())
for filename, (avg, stddev) in bench_map.items())
def main():
+11 -11
View File
@@ -527,10 +527,10 @@ def process_special_casing(special_casing, table, index):
return upper
def ascii(char_dict):
return ifilter(lambda ch: ch <= 0x7f, char_dict.iterkeys())
return ifilter(lambda ch: ch <= 0x7f, iter(char_dict.keys()))
def latin1(char_dict):
return ifilter(lambda ch: ch <= 0xff, char_dict.iterkeys())
return ifilter(lambda ch: ch <= 0xff, iter(char_dict.keys()))
def is_empty(iterable):
return not any(True for _ in iterable)
@@ -567,11 +567,11 @@ def process_special_casing(special_casing, table, index):
assert all(ch != lowerCase(ch) for ch in [0x0130, 0x03A3])
# Ensure Azeri, Lithuanian, and Turkish are the only languages with conditional case mappings.
assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_tolower.iterkeys()))
assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_toupper.iterkeys()))
assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_tolower.keys()))
assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_toupper.keys()))
# Maximum case mapping length is three characters.
itervals = lambda d: d.itervalues()
itervals = lambda d: iter(d.values())
assert max(imap(len, chain(
itervals(unconditional_tolower),
itervals(unconditional_toupper),
@@ -732,7 +732,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
assert unconditional_toupper, "|unconditional_toupper| is not empty"
# Sorted list of code units with special upper case mappings.
code_list = sorted(unconditional_toupper.iterkeys())
code_list = sorted(unconditional_toupper.keys())
# Fail-fast if the input character isn't a special casing character.
println(' if ({})'.format(out_range(code_list[0], code_list[-1])))
@@ -787,7 +787,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
println('{')
println(' switch(ch) {')
for (code, converted) in sorted(unconditional_toupper.iteritems(), key=itemgetter(0)):
for (code, converted) in sorted(iter(unconditional_toupper.items()), key=itemgetter(0)):
println(' case {}: return {}; // {}'.format(hexlit(code), len(converted),
codepoint_table.name(code)))
println(' }')
@@ -804,7 +804,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println
println('{')
println(' switch(ch) {')
for (code, converted) in sorted(unconditional_toupper.iteritems(), key=itemgetter(0)):
for (code, converted) in sorted(iter(unconditional_toupper.items()), key=itemgetter(0)):
println(' case {}: // {}'.format(hexlit(code), codepoint_table.name(code)))
for ch in converted:
println(' elements[(*index)++] = {}; // {}'.format(hexlit(ch),
@@ -1072,7 +1072,7 @@ def make_unicode_file(version,
println('bool')
println('js::unicode::{}(uint32_t codePoint)'.format(name))
println('{')
for (from_code, to_code) in int_ranges(group_set.keys()):
for (from_code, to_code) in int_ranges(list(group_set.keys())):
println(' if (codePoint >= 0x{:X} && codePoint <= 0x{:X}) // {} .. {}'.format(from_code,
to_code,
codepoint_table.name(from_code),
@@ -1117,7 +1117,7 @@ def make_unicode_file(version,
# If the following assert fails, it means space character is added to
# non-BMP area. In that case the following code should be uncommented
# and the corresponding code should be added to frontend.
assert len(non_bmp_space_set.keys()) == 0
assert len(list(non_bmp_space_set.keys())) == 0
write_supplemental_identifier_method('IsIdentifierStartNonBMP', non_bmp_id_start_set,
println)
@@ -1304,7 +1304,7 @@ def make_irregexp_tables(version,
println(' return {};'.format(consequent(casefolded)))
println(' }')
println('')
for (ch, casemapped_chars) in casemap_for_latin1.iteritems():
for (ch, casemapped_chars) in casemap_for_latin1.items():
for casemapped in casemapped_chars:
println(' // "{}" case maps to "{}".'.format(char_name(casemapped),
char_name(ch)))
+1 -1
View File
@@ -34,7 +34,7 @@ for line in sys.stdin:
sys.stdout.write('digraph g {\n')
for olist in classdict.itervalues():
for olist in classdict.values():
for line in olist:
sys.stdout.write(line)
+1 -1
View File
@@ -339,7 +339,7 @@ def main():
listfile.write("\ndefault-preferences {0}\n\n".format(defaultPreferences))
lastDefaultPreferences = defaultPreferences
key = 1
while not test[key] in gTestFlags.keys() and key < len(test):
while not test[key] in list(gTestFlags.keys()) and key < len(test):
key = key + 1
testType = test[key - 1]
testFlags = gTestFlags[test[key]]
+1 -1
View File
@@ -254,7 +254,7 @@ class ReftestArgumentsParser(argparse.ArgumentParser):
return
for test_path in options.tests:
for manifest_file, suite in manifests.iteritems():
for manifest_file, suite in manifests.items():
if os.path.exists(os.path.join(test_path, manifest_file)):
options.suite = suite
return
+1 -1
View File
@@ -194,7 +194,7 @@ class ReftestResolver(object):
manifests[manifest] = set()
manifests[manifest].add(filter_str)
for key in manifests.iterkeys():
for key in manifests.keys():
if None in manifests[key]:
manifests[key] = None
else:
+2 -2
View File
@@ -37,12 +37,12 @@ class ProfileConfigParser(ConfigParser.RawConfigParser):
def write(self, fp):
if self._defaults:
fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
for (key, value) in self._defaults.items():
for (key, value) in list(self._defaults.items()):
fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
for (key, value) in list(self._sections[section].items()):
if key == "__name__":
continue
if (value is not None) or (self._optcre == self.OPTCRE):
+6 -6
View File
@@ -491,9 +491,9 @@ class DataTable(object):
# dictionary).
# NOTE: this way of differentiating might create ambiguity. See docs.
if (len(table_description) != 1 or
(isinstance(table_description.keys()[0], types.StringTypes) and
isinstance(table_description.values()[0], tuple) and
len(table_description.values()[0]) < 4)):
(isinstance(list(table_description.keys())[0], types.StringTypes) and
isinstance(list(table_description.values())[0], tuple) and
len(list(table_description.values())[0]) < 4)):
# This is the most inner dictionary. Parsing types.
columns = []
# We sort the items, equivalent to sort the keys since they are unique
@@ -509,11 +509,11 @@ class DataTable(object):
columns.append(parsed_col)
return columns
# This is an outer dictionary, must have at most one key.
parsed_col = DataTable.ColumnTypeParser(table_description.keys()[0])
parsed_col = DataTable.ColumnTypeParser(list(table_description.keys())[0])
parsed_col["depth"] = depth
parsed_col["container"] = "dict"
return ([parsed_col] +
DataTable.TableDescriptionParser(table_description.values()[0],
DataTable.TableDescriptionParser(list(table_description.values())[0],
depth=depth + 1))
@property
@@ -622,7 +622,7 @@ class DataTable(object):
return
# We have a dictionary in an inner depth level.
if not data.keys():
if not list(data.keys()):
# In case this is an empty dictionary, we add a record with the columns
# filled only until this point.
self.__data.append(prev_col_values)
@@ -90,12 +90,12 @@ class StructInfo():
def update_struct_item_list(self):
# Collect all struct_items from struct_name_dic and typedef_name_dic
# Compute child_decl_map for each struct item.
for struct_name in self.struct_name_dic.keys():
for struct_name in list(self.struct_name_dic.keys()):
struct_item = self.struct_name_dic[struct_name]
struct_item.compute_child_decl_map(self)
self.struct_item_list.append(struct_item)
for typedef_name in self.typedef_name_dic.keys():
for typedef_name in list(self.typedef_name_dic.keys()):
struct_item = self.typedef_name_dic[typedef_name]
if struct_item.struct_name not in self.struct_name_dic:
struct_item.compute_child_decl_map(self)
+4 -4
View File
@@ -512,7 +512,7 @@ _ALT_TOKEN_REPLACEMENT = {
# False positives include C-style multi-line comments and multi-line strings
# but those have always been troublesome for cpplint.
_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
r'[ =()](' + ('|'.join(list(_ALT_TOKEN_REPLACEMENT.keys()))) + r')(?=[ (]|$)')
# These constants define types of headers for use with
@@ -952,7 +952,7 @@ class _CppLintState(object):
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
for category, count in self.errors_by_category.items():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stdout.write('Total errors found: %d\n' % self.error_count)
@@ -4622,7 +4622,7 @@ def _GetTextInside(text, start_pattern):
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(matching_punctuation.itervalues())
closing_punctuation = set(matching_punctuation.values())
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
@@ -5570,7 +5570,7 @@ def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
# include_dict is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = include_dict.keys()
header_keys = list(include_dict.keys())
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
+1 -1
View File
@@ -105,7 +105,7 @@ def main(argv=None):
# Run each affected file through cpplint
lint_failed = False
for filename, affected_lines in file_affected_line_map.iteritems():
for filename, affected_lines in file_affected_line_map.items():
if filename.split(".")[-1] not in ("c", "h", "cc"):
continue
@@ -236,7 +236,7 @@ def remap(metric):
for (m, img) in data:
fname = "%s/%s_%s" % (output_dir, m, img)
fig = go.Figure()
for method in sorted(data[(m, img)].keys(), key=pos):
for method in sorted(list(data[(m, img)].keys()), key=pos):
vals = data[(m, img)][method]
zvals = list(zip(*sorted(vals)))
if not zvals:
@@ -77,7 +77,7 @@ def CheckMeta(dec, ref):
if isinstance(ref, dict):
if not isinstance(dec, dict):
return Failure("Malformed metadata file")
for k, v in ref.items():
for k, v in list(ref.items()):
if k in TEST_KEYS:
continue
if k not in dec:
@@ -232,7 +232,7 @@ def BuildCleaner(args):
with open(os.path.join(args.src_dir, 'lib/CMakeLists.txt'), 'r') as f:
cmake_text = f.read()
version = {'major_version': '', 'minor_version': '', 'patch_version': ''}
for var in version.keys():
for var in list(version.keys()):
cmake_var = f'JPEGXL_{var.upper()}'
# TODO(eustas): use `cmake -L`
# Regexp:
@@ -232,7 +232,7 @@ def PrintStats(stats):
for objstat in stats:
bin_size = 0
ram_size = 0
for kind, size in objstat.size_map.items():
for kind, size in list(objstat.size_map.items()):
if kind in BIN_SIZE:
bin_size += size
if kind in RAM_SIZE:
@@ -263,7 +263,7 @@ def PrintStackStats(tgt_stack_sizes, top_entries=20):
if not tgt_stack_sizes:
return
print(' Stack Symbol name')
for i, (name, size) in zip(itertools.count(), tgt_stack_sizes.items()):
for i, (name, size) in zip(itertools.count(), list(tgt_stack_sizes.items())):
if top_entries > 0 and i >= top_entries:
break
print('%8d %s' % (size, name))
@@ -304,7 +304,7 @@ def SizeStats(args):
# Cache of symbols of a target.
syms = {}
# Load the symbols from the all targets and its deps.
all_deps = set(tgts.keys()).union(*[set(tgt.deps) for tgt in tgts.values()])
all_deps = set(tgts.keys()).union(*[set(tgt.deps) for tgt in list(tgts.values())])
for entry in all_deps:
fn = os.path.join(args.build_dir,
tgts[entry].filename if entry in tgts else entry)
@@ -396,7 +396,7 @@ def SizeStats(args):
# Check the maximum stack size.
exit_code = 0
if args.max_stack:
for name, size in tgt_stack_sizes.items():
for name, size in list(tgt_stack_sizes.items()):
if size > args.max_stack:
print('Error: %s exceeds stack limit: %d vs %d' % (
name, size, args.max_stack),
@@ -124,7 +124,7 @@ if __name__ == "__main__":
print(f'Processing template {name}')
path = source_path.joinpath(name)
text = path.read_text().strip()
for key, value in substitutes.items():
for key, value in list(substitutes.items()):
text = text.replace(key, value)
#text = uglify(text, name)
output_path.joinpath(name).write_text(text)
+4 -4
View File
@@ -512,7 +512,7 @@ _ALT_TOKEN_REPLACEMENT = {
# False positives include C-style multi-line comments and multi-line strings
# but those have always been troublesome for cpplint.
_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
r'[ =()](' + ('|'.join(list(_ALT_TOKEN_REPLACEMENT.keys()))) + r')(?=[ (]|$)')
# These constants define types of headers for use with
@@ -952,7 +952,7 @@ class _CppLintState(object):
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
for category, count in self.errors_by_category.items():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stdout.write('Total errors found: %d\n' % self.error_count)
@@ -4622,7 +4622,7 @@ def _GetTextInside(text, start_pattern):
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(matching_punctuation.itervalues())
closing_punctuation = set(matching_punctuation.values())
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
@@ -5570,7 +5570,7 @@ def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
# include_dict is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = include_dict.keys()
header_keys = list(include_dict.keys())
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
+1 -1
View File
@@ -103,7 +103,7 @@ def main(argv=None):
# Run each affected file through cpplint
lint_failed = False
for filename, affected_lines in file_affected_line_map.items():
for filename, affected_lines in list(file_affected_line_map.items()):
if filename.split(".")[-1] not in ("c", "h", "cc"):
continue
if filename.startswith("third_party"):
@@ -110,7 +110,7 @@ def _RunCommand(command, working_dir=None, ignore_exit_code=False,
logging.debug('CMD: %s CWD: %s', ' '.join(command), working_dir)
env = os.environ.copy()
if extra_env:
assert all(isinstance(value, str) for value in extra_env.values())
assert all(isinstance(value, str) for value in list(extra_env.values()))
logging.debug('extra env: %s', extra_env)
env.update(extra_env)
p = subprocess.Popen(command,
@@ -195,7 +195,7 @@ def GetMatchingDepsEntries(depsentry_dict, dir_path):
A list of DepsEntry objects.
"""
result = []
for path, depsentry in depsentry_dict.items():
for path, depsentry in list(depsentry_dict.items()):
if path == dir_path:
result.append(depsentry)
else:
@@ -210,7 +210,7 @@ def BuildDepsentryDict(deps_dict):
result = {}
def AddDepsEntries(deps_subdict):
for path, deps_url_spec in deps_subdict.items():
for path, deps_url_spec in list(deps_subdict.items()):
if isinstance(deps_url_spec, dict):
if deps_url_spec.get('dep_type') == 'cipd':
continue
@@ -245,7 +245,7 @@ def CalculateChangedDeps(libyuv_deps, new_cr_deps):
result = []
libyuv_entries = BuildDepsentryDict(libyuv_deps)
new_cr_entries = BuildDepsentryDict(new_cr_deps)
for path, libyuv_deps_entry in libyuv_entries.items():
for path, libyuv_deps_entry in list(libyuv_entries.items()):
if path in DONT_AUTOROLL_THESE:
continue
cr_deps_entry = new_cr_entries.get(path)
@@ -138,7 +138,7 @@ def main(base_dir, adb_cmd='adb'):
except:
logging.exception('Unexpected exception in main.')
finally:
for process, _ in devices.itervalues():
for process, _ in devices.values():
if process:
try:
process.terminate()
@@ -106,7 +106,7 @@ def GetDeviceLogs(log_filenames, logger):
"""
device_logs = []
for device, device_files in log_filenames.iteritems():
for device, device_files in log_filenames.items():
logger.debug('%s: %s', device, str(device_files))
device_file_lines = []
for cur_file in device_files:
@@ -991,7 +991,7 @@ class AndroidCommands(object):
for pid in pid_list:
usage_dict_per_pid, smaps_per_pid = self.GetMemoryUsageForPid(pid)
smaps[pid] = smaps_per_pid
for (key, value) in usage_dict_per_pid.items():
for (key, value) in list(usage_dict_per_pid.items()):
usage_dict[key] += value
return usage_dict, smaps
@@ -129,7 +129,7 @@ class ApkInfo(object):
def GetAnnotatedTests(self, annotation_filter_list):
"""Returns a list of all tests that match the given annotation filters."""
return [test for test, annotations in self._GetAnnotationMap().iteritems()
return [test for test, annotations in self._GetAnnotationMap().items()
if self._IsTestMethod(test) and self._AnnotationsMatchFilters(
annotation_filter_list, annotations)]
@@ -52,7 +52,7 @@ class AnnotatedFunctions(object):
List of all annotations for this function.
"""
return [annotation
for annotation, tests in AnnotatedFunctions._ANNOTATED.iteritems()
for annotation, tests in AnnotatedFunctions._ANNOTATED.items()
if qualified_function_name in tests]
@@ -165,7 +165,7 @@ class AbstractRpcServer(object):
req = urllib2.Request(url, data=data)
if self.host_override:
req.add_header("Host", self.host_override)
for key, value in self.extra_headers.iteritems():
for key, value in self.extra_headers.items():
req.add_header(key, value)
return req
@@ -698,7 +698,7 @@ class VersionControlSystem(object):
patches = dict()
[patches.setdefault(v, k) for k, v in patch_list]
for filename in patches.keys():
for filename in list(patches.keys()):
base_content, new_content, is_binary, status = files[filename]
file_id_str = patches.get(filename)
if file_id_str.find("nobase") != -1:
@@ -1324,7 +1324,7 @@ def RealMain(argv, data=None):
# Send a hash of all the base file so the server can determine if a copy
# already exists in an earlier patchset.
base_hashes = ""
for file, info in files.iteritems():
for file, info in files.items():
if not info[0] is None:
checksum = md5.new(info[0]).hexdigest()
if base_hashes:
@@ -241,7 +241,7 @@ class Subprocess:
# Changes made by os.environ.clear are not inheritable by child
# processes until Python 2.6. To produce inheritable changes we have
# to delete environment items with the del statement.
for key in dest.keys():
for key in list(dest.keys()):
del dest[key]
dest.update(src)
@@ -97,7 +97,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase):
self.assertEquals(
len(expected_children), len(actual_children),
'number of child elements differ in element ' + actual_node.tagName)
for child_id, child in expected_children.iteritems():
for child_id, child in expected_children.items():
self.assert_(child_id in actual_children,
'<%s> is not in <%s> (in element %s)' %
(child_id, actual_children, actual_node.tagName))
@@ -433,7 +433,7 @@ def ConvertVCMacrosToMSBuild(s):
'$(PlatformName)': '$(Platform)',
'$(SafeInputName)': '%(Filename)',
}
for old, new in replace_map.iteritems():
for old, new in replace_map.items():
s = s.replace(old, new)
s = FixVCMacroSlashes(s)
return s
@@ -453,10 +453,10 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr):
dictionaries of settings and their values.
"""
msbuild_settings = {}
for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems():
for msvs_tool_name, msvs_tool_settings in msvs_settings.items():
if msvs_tool_name in _msvs_to_msbuild_converters:
msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name]
for msvs_setting, msvs_value in msvs_tool_settings.iteritems():
for msvs_setting, msvs_value in msvs_tool_settings.items():
if msvs_setting in msvs_tool:
# Invoke the translation function.
try:
@@ -513,7 +513,7 @@ def _ValidateSettings(validators, settings, stderr):
for tool_name in settings:
if tool_name in validators:
tool_validators = validators[tool_name]
for setting, value in settings[tool_name].iteritems():
for setting, value in settings[tool_name].items():
if setting in tool_validators:
try:
tool_validators[setting](value)
@@ -91,7 +91,7 @@ class Writer(object):
if environment and isinstance(environment, dict):
env_list = ['%s="%s"' % (key, val)
for (key,val) in environment.iteritems()]
for (key,val) in environment.items()]
environment = ' '.join(env_list)
else:
environment = ''
@@ -135,7 +135,7 @@ class Writer(object):
def WriteIfChanged(self):
"""Writes the user file."""
configs = ['Configurations']
for config, spec in sorted(self.configurations.iteritems()):
for config, spec in sorted(self.configurations.items()):
configs.append(spec)
content = ['VisualStudioUserFile',
@@ -236,7 +236,7 @@ def InsertLargePdbShims(target_list, target_dicts, vars):
# Set up the shim to output its PDB to the same location as the final linker
# target.
for config_name, config in shim_dict.get('configurations').iteritems():
for config_name, config in shim_dict.get('configurations').items():
pdb_path = _GetPdbPath(target_dict, config_name, vars)
# A few keys that we don't want to propagate.
@@ -92,7 +92,7 @@ def Load(build_files, format, default_variables={},
# These parameters are passed in order (as opposed to by key)
# because ActivePython cannot handle key parameters to __import__.
generator = __import__(generator_name, globals(), locals(), generator_name)
for (key, val) in generator.generator_default_variables.items():
for (key, val) in list(generator.generator_default_variables.items()):
default_variables.setdefault(key, val)
# Give the generator the opportunity to set additional variables based on
@@ -210,7 +210,7 @@ def RegenerateFlags(options):
# We always want to ignore the environment when regenerating, to avoid
# duplicate or changed flags in the environment at the time of regeneration.
flags = ['--ignore-environment']
for name, metadata in options._regeneration_metadata.iteritems():
for name, metadata in options._regeneration_metadata.items():
opt = metadata['opt']
value = getattr(options, name)
value_predicate = metadata['type'] == 'path' and FixPath or Noop
@@ -493,7 +493,7 @@ def gyp_main(args):
if options.generator_flags:
gen_flags += options.generator_flags
generator_flags = NameValueListToDict(gen_flags)
if DEBUG_GENERAL in gyp.debug.keys():
if DEBUG_GENERAL in list(gyp.debug.keys()):
DebugOutput(DEBUG_GENERAL, "generator_flags: %s", generator_flags)
# Generate all requested formats (use a set in case we got one format request
@@ -526,7 +526,7 @@ def gyp_main(args):
generator.GenerateOutput(flat_list, targets, data, params)
if options.configs:
valid_configs = targets[flat_list[0]]['configurations'].keys()
valid_configs = list(targets[flat_list[0]]['configurations'].keys())
for conf in options.configs:
if conf not in valid_configs:
raise GypError('Invalid config specified via --build: %s' % conf)
@@ -23,7 +23,7 @@ class TestTopologicallySorted(unittest.TestCase):
def GetEdge(node):
return tuple(graph[node])
self.assertEqual(
gyp.common.TopologicallySorted(graph.keys(), GetEdge),
gyp.common.TopologicallySorted(list(graph.keys()), GetEdge),
['a', 'c', 'd', 'b'])
def test_Cycle(self):
@@ -38,7 +38,7 @@ class TestTopologicallySorted(unittest.TestCase):
return tuple(graph[node])
self.assertRaises(
gyp.common.CycleError, gyp.common.TopologicallySorted,
graph.keys(), GetEdge)
list(graph.keys()), GetEdge)
class TestGetFlavor(unittest.TestCase):
@@ -79,7 +79,7 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0):
# Optionally in second position is a dictionary of the attributes.
rest = specification[1:]
if rest and isinstance(rest[0], dict):
for at, val in sorted(rest[0].iteritems()):
for at, val in sorted(rest[0].items()):
xml_parts.append(' %s="%s"' % (at, _XmlEscape(val, attr=True)))
rest = rest[1:]
if rest:
@@ -143,7 +143,7 @@ _xml_escape_map = {
_xml_escape_re = re.compile(
"(%s)" % "|".join(map(re.escape, _xml_escape_map.keys())))
"(%s)" % "|".join(map(re.escape, list(_xml_escape_map.keys()))))
def _XmlEscape(value, attr=False):
@@ -410,7 +410,7 @@ def _GetUnqualifiedToTargetMapping(all_targets, to_find):
if not to_find:
return {}, []
to_find = set(to_find)
for target_name in all_targets.keys():
for target_name in list(all_targets.keys()):
extracted = gyp.common.ParseQualifiedTarget(target_name)
if len(extracted) > 1 and extracted[1] in to_find:
to_find.remove(extracted[1])
@@ -669,7 +669,7 @@ class TargetCalculator(object):
assert self.is_build_impacted();
# Compile targets are found by searching up from changed targets.
# Reset the visited status for _GetBuildTargets.
for target in self._name_to_target.itervalues():
for target in self._name_to_target.values():
target.visited = False
supplied_targets = _LookupTargets(self._supplied_target_names_no_all(),
@@ -979,7 +979,7 @@ def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use,
# XCode settings
xcode_settings = config.get('xcode_settings', {})
for xcode_setting, xcode_value in xcode_settings.viewitems():
for xcode_setting, xcode_value in xcode_settings.items():
SetTargetProperty(output, cmake_target_name,
"XCODE_ATTRIBUTE_%s" % xcode_setting, xcode_value,
'' if isinstance(xcode_value, str) else ' ')
@@ -1230,7 +1230,7 @@ def GenerateOutput(target_list, target_dicts, data, params):
GenerateOutputForConfig(target_list, target_dicts, data,
params, user_config)
else:
config_names = target_dicts[target_list[0]]['configurations'].keys()
config_names = list(target_dicts[target_list[0]]['configurations'].keys())
if params['parallel']:
try:
pool = multiprocessing.Pool(len(config_names))
@@ -34,7 +34,7 @@ for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
for key, val in list(generator_flags.items()):
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
Loaded 100 of 422 files, more files were not shown because too many files have changed in this diff. Show more