本文整理汇总了Python中frozenset函数的典型用法代码示例。如果您正苦于以下问题:Python frozenset函数的具体用法?Python frozenset怎么用?Python frozenset使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了frozenset函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: editBonding
def editBonding(self, bond, _netinfo):
"""
Modifies the bond so that the bond in the system ends up with the
same slave and options configuration that are requested. Makes a
best effort not to interrupt connectivity.
"""
nicsToSet = frozenset(nic.name for nic in bond.slaves)
currentNics = frozenset(_netinfo.getNicsForBonding(bond.name))
nicsToAdd = nicsToSet
nicsToRemove = currentNics
if bond.areOptionsApplied():
nicsToAdd -= currentNics
nicsToRemove -= nicsToSet
for nic in nicsToRemove:
slave = Nic(nic, self, _netinfo=_netinfo)
self.configApplier.removeBondSlave(bond, slave)
slave.remove()
if not bond.areOptionsApplied():
self.configApplier.ifdown(bond)
self.configApplier.addBondOptions(bond)
for slave in bond.slaves:
if slave.name in nicsToAdd:
self.configApplier.addBondSlave(bond, slave)
self.configApplier.ifup(bond)
self.runningConfig.setBonding(
bond.name, {'options': bond.options,
'nics': [slave.name for slave in bond.slaves],
'switch': 'legacy'})
示例2: izipstrict
def izipstrict(*args):
"""
XXX broken! this function does not always raise the error it claims to
implement; it needs a layer of counters to see how much was used from each
iterable....
Returns a generator very like the itertools izip function. The arguments
are treated like arguments to izip. Unlike izip this function ensures that
all the iterators finished after the same number of items. It raises a
StrictError if not all the ierators have finished.
If StrictError is raised, in addition to a human-readable message, the
exception will have attributes 'finished', 'unfinished' and 'values', all
tuples corresponding respectively to the indices in the argument list of the
iterators that had finished, the indices of the iterators that had not
finished, and the initial yields from those unfinished iterators. Note that
process of getting each initial yield can itself finish iterators in the
unfinished set.
>>> tuple(izipstrict(xrange(5), xrange(5)))
((0, 0), (1, 1), (2, 2), (3, 3), (4, 4))
Uncaught error
>>> tuple(izipstrict(xrange(5), xrange(4), xrange(1,6), xrange(4)))
Traceback (most recent call last):
...
StrictError: out of 4 iterators, 2 were unfinished: at argument indices (0, 2)
Caught error and attributes
>>> try: tuple(izipstrict(xrange(5), xrange(4), xrange(1,6), xrange(4)))
... except StrictError, e: print e.finished, e.unfinished, e.values
(1, 3) (0, 2) (4, 5)
"""
nexts = tuple(iter(arg).next for arg in args)
finished = list()
build = list()
build_append = build.append
while True:
del build[:]
for index, next in enumerate(nexts):
try:
build_append(next())
except StopIteration:
finished.append(index)
if finished and build:
unfinished = tuple(sorted(frozenset(xrange(len(nexts))) - frozenset(finished)))
assert len(unfinished) == len(build)
err = StrictError("out of %d iterators, %d were unfinished: at argument indices %s"
% (len(nexts), len(unfinished), tuple(unfinished)))
err.finished = tuple(finished)
err.unfinished = unfinished
err.values = tuple(build)
raise err
if build:
yield tuple(build)
else:
assert len(finished) == len(nexts)
raise StopIteration
示例3: test_exclude_related
def test_exclude_related(self):
"""Test for specifying excluded columns on related models."""
date = datetime.date(1999, 12, 31)
person = self.Person(name='Test', age=10, other=20, birth_date=date)
computer = self.Computer(name='foo', vendor='bar', buy_date=date)
self.session.add(person)
person.computers.append(computer)
self.session.commit()
exclude = frozenset(['name', 'age', 'computers', 'computers.id',
'computers.name'])
self.manager.create_api(self.Person, exclude_columns=exclude)
exclude = frozenset(['name', 'age', 'computers.id', 'computers.name'])
self.manager.create_api(self.Person, url_prefix='/api2',
exclude_columns=exclude)
response = self.app.get('/api/person/%s' % person.id)
person_dict = loads(response.data)
for column in 'name', 'age', 'computers':
assert column not in person_dict
for column in 'id', 'other', 'birth_date':
assert column in person_dict
response = self.app.get('/api2/person/%s' % person.id)
person_dict = loads(response.data)
assert 'computers' in person_dict
for column in 'id', 'name':
assert column not in person_dict['computers'][0]
for column in 'vendor', 'owner_id', 'buy_date':
assert column in person_dict['computers'][0]
示例4: CheckPrereq
def CheckPrereq(self):
owned_groups = frozenset(self.owned_locks(locking.LEVEL_NODEGROUP))
assert self.group_uuid in owned_groups
# Check if locked instances are still correct
owned_instance_names = frozenset(self.owned_locks(locking.LEVEL_INSTANCE))
if self.op.conflicts_check:
CheckNodeGroupInstances(self.cfg, self.group_uuid, owned_instance_names)
self.netparams = {
constants.NIC_MODE: self.network_mode,
constants.NIC_LINK: self.network_link,
}
objects.NIC.CheckParameterSyntax(self.netparams)
self.group = self.cfg.GetNodeGroup(self.group_uuid)
#if self.network_mode == constants.NIC_MODE_BRIDGED:
# _CheckNodeGroupBridgesExist(self, self.network_link, self.group_uuid)
self.connected = False
if self.network_uuid in self.group.networks:
self.LogWarning("Network '%s' is already mapped to group '%s'" %
(self.network_name, self.group.name))
self.connected = True
# check only if not already connected
elif self.op.conflicts_check:
pool = network.AddressPool(self.cfg.GetNetwork(self.network_uuid))
_NetworkConflictCheck(
self, lambda nic: pool.Contains(nic.ip), "connect to",
[instance_info for (_, instance_info) in
self.cfg.GetMultiInstanceInfoByName(owned_instance_names)])
示例5: force_trace_widths
def force_trace_widths(board):
microstrip_layers = frozenset(('1_top', '6_bot'))
stripline_layers = frozenset(('3_inner', '4_inner'))
se_50_microstrip_width = '0.1778'
se_50_stripline_width = '0.1651'
diff_90_microstrip_width = '0.127'
diff_90_stripline_width = '0.127'
for element in board:
if element[0] == 'segment':
segment = OrderedDict([(v[0], v[1:]) for v in element[1:]])
assert len(segment['net']) == 1
net_name = net_by_number[int(segment['net'][0])]
assert len(segment['layer']) == 1
layer = segment['layer'][0]
new_width = None
if net_name in nets_by_net_class['50_se']:
if layer in microstrip_layers:
new_width = [se_50_microstrip_width]
if layer in stripline_layers:
new_width = [se_50_stripline_width]
elif net_name in nets_by_net_class['90_diff']:
if layer in microstrip_layers:
new_width = [diff_90_microstrip_width]
if layer in stripline_layers:
new_width = [diff_90_stripline_width]
if new_width:
segment['width'] = new_width
new_elements = [[a] + b for a, b in segment.items()]
element[1:] = new_elements
示例6: mincoverages_upto_maxk__defi
def mincoverages_upto_maxk__defi(m, q, dontcares, maxk, counters, mincov):
# In deficiency counter mode we act on all deficient ktuples
# and reduce their deficiency, if appropriate.
endk = maxk + 1
minc = [0] * endk
_append_new_defi_position(counters, m, q, mincov)
shift = m - q # put the q-gram into the window at the rightmost shift
sdc = list(range(shift)) + [d+shift for d in dontcares]
sdcset = frozenset(sdc)
D = len(sdc)
for k in range(1, endk):
# iterate over deficient tuples or over k-tuples with all dontcares?
ck = counters[k]
if k*len(ck) <= binom(D, k):
# iterate over keys
if k == 1:
to_reduce = [i for i in ck if i in sdcset]
else:
to_reduce = [dt for dt in ck if frozenset(dt) <= sdcset]
else:
# iterate over k-tuples from sdc
combos = combinations(sdc, k) if k > 1 else sdc
to_reduce = [dt for dt in combos if dt in ck]
# decrement all items of counters[k] in to_reduce
for key in to_reduce:
if ck[key] > 1:
ck[key] -= 1
else:
del ck[key]
# compute minimum coverage for each k = 1..maxk
minc[k] = mincov - (max(ck.values()) if len(ck) > 0 else 0)
return minc, counters
示例7: __init__
def __init__(self, prefix, channels, subdirs=(), specs_to_add=(), specs_to_remove=()):
"""
Args:
prefix (str):
The conda prefix / environment location for which the :class:`Solver`
is being instantiated.
channels (Sequence[:class:`Channel`]):
A prioritized list of channels to use for the solution.
subdirs (Sequence[str]):
A prioritized list of subdirs to use for the solution.
specs_to_add (Set[:class:`MatchSpec`]):
The set of package specs to add to the prefix.
specs_to_remove (Set[:class:`MatchSpec`]):
The set of package specs to remove from the prefix.
"""
self.prefix = prefix
self.channels = IndexedSet(Channel(c) for c in channels or context.channels)
self.subdirs = tuple(s for s in subdirs or context.subdirs)
self.specs_to_add = frozenset(MatchSpec.merge(s for s in specs_to_add))
self.specs_to_remove = frozenset(MatchSpec.merge(s for s in specs_to_remove))
assert all(s in context.known_subdirs for s in self.subdirs)
self._index = None
self._r = None
self._prepared = False
示例8: test_blankpattern
def test_blankpattern(self):
# Make sure when tuple or something has no values no regex is generated.
# Fixes bug #661354
test_locale = _strptime.LocaleTime()
test_locale.timezone = (frozenset(), frozenset())
self.assertEqual(_strptime.TimeRE(test_locale).pattern("%Z"), '',
"with timezone == ('',''), TimeRE().pattern('%Z') != ''")
示例9: get_partitions
def get_partitions(tree):
"""
Get all of the partitions implied by a tree.
Each positive branch implies a partition.
Each partition is a frozenset of two frozensets of leaf names.
The return value is the set of these partitions.
Note that the word 'partition' is a python keyword,
so the word 'part' will be used here instead.
@param tree: a tree object
@return: the set of partitions implied by the tree.
"""
# map a directed branch id to the set of leaf names in its subtree
d = _get_branch_id_to_leaf_name_set(tree)
# for each branch in the tree get the frozenset of leaf names on each end of the branch
parts = set()
for node in tree.gen_non_root_nodes():
parent = node.get_parent()
directed_branches = (node.get_directed_branch_to(parent), parent.get_directed_branch_to(node))
branch_length = directed_branches[0].get_branch_length()
for dbranch in directed_branches:
assert dbranch.get_branch_length() == branch_length
if branch_length > 0:
leaf_sets = [d[id(dbranch)] for dbranch in directed_branches]
part = frozenset(frozenset(leaf_set) for leaf_set in leaf_sets)
parts.add(part)
# return the set of partitions
return parts
示例10: test_metanode__properties
def test_metanode__properties():
node = MetaNode()
assert_equal(node.input_files, frozenset())
assert_equal(node.output_files, frozenset())
assert_equal(node.executables, frozenset())
assert_equal(node.auxiliary_files, frozenset())
assert_equal(node.requirements, frozenset())
示例11: _get_autounmask_changes
def _get_autounmask_changes(self, pkg):
needed_use_config_change = self.depgraph._dynamic_config._needed_use_config_changes.get(pkg)
if needed_use_config_change is None:
return frozenset()
use, changes = needed_use_config_change
return frozenset(changes.keys())
示例12: test_metanode__nodes
def test_metanode__nodes():
subnodes = [Node(), Node()]
dependencies = [Node(), Node()]
node = MetaNode(subnodes=iter(subnodes),
dependencies=iter(dependencies))
assert_equal(node.subnodes, frozenset(subnodes))
assert_equal(node.dependencies, frozenset(dependencies))
示例13: test_constructor__requirements
def test_constructor__requirements():
node = Node(requirements = id)
assert_equal(node.requirements, frozenset([id]))
node = Node(requirements = [id])
assert_equal(node.requirements, frozenset([id]))
node = Node(requirements = [id, str])
assert_equal(node.requirements, frozenset([id, str]))
示例14: test_change_mapping
def test_change_mapping(self):
""" Test using multiple input datasets, like if you were calculating a change. """
with mock.patch('cwsl.core.pattern_dataset.PatternDataSet.glob_fs') as mock_glob:
fake_file_1 = '/a/fake/file_1956_red.nc'
fake_file_2 = '/a/fake/file_1981_red.nc'
mock_glob.return_value = [fake_file_1, fake_file_2]
first_pattern_ds = PatternDataSet("/a/fake/file_%date%_%colour%.nc",
set([Constraint('date', ['1956'])]))
second_pattern_ds = PatternDataSet("/a/fake/file_%date%_%colour%.nc",
set([Constraint('date', ['1981'])]))
# Overwrite the valid combinations for these mock datasets.
first_pattern_ds.valid_combinations = set([frozenset([Constraint('colour', ['red']),
Constraint('date', ['1956'])])])
second_pattern_ds.valid_combinations = set([frozenset([Constraint('colour', ['red']),
Constraint('date', ['1981'])])])
the_process_unit = ProcessUnit([first_pattern_ds, second_pattern_ds],
"/a/final/output/file_%start_date%_%end_date%_%colour%.txt",
'echo', map_dict={'start_date': ('date', 0),
'end_date': ('date', 1)})
ds_result = the_process_unit.execute(simulate=True)
outfiles = [file_thing for file_thing in ds_result.files]
self.assertEqual(len(outfiles), 1)
expected_string = self.script_header + "mkdir -p /a/final/output\necho /a/fake/file_1956_red.nc /a/fake/file_1981_red.nc /a/final/output/file_1956_1981_red.txt\n"
self.assertEqual(expected_string, the_process_unit.scheduler.job.to_str())
示例15: test_creation
def test_creation():
metaedge_tuples = [
('compound', 'disease', 'indication', 'both'),
('disease', 'gene', 'association', 'both'),
('compound', 'gene', 'target', 'both'),
]
metanode_ids = 'compound', 'disease', 'gene'
metagraph = graph.MetaGraph.from_edge_tuples(metaedge_tuples)
# check that nodes got added to metagraph_node_dict
assert frozenset(metagraph.node_dict) == frozenset(metanode_ids)
for metanode in metagraph.node_dict.values():
assert isinstance(metanode, graph.MetaNode)
# check that metanode.get_id() and hash(metanode) are working as expected
for metanode_id in metanode_ids:
metanode = metagraph.node_dict[metanode_id]
assert metanode.identifier == metanode_id
assert metanode.get_id() == metanode_id
assert hash(metanode) == hash(metanode_id)
g = graph.Graph(metagraph)
ms = g.add_node('disease', 'DOID:2377', 'multiple sclerosis')
assert ms.metanode.identifier == 'disease'
assert ms.identifier == 'DOID:2377'
assert ms.name == 'multiple sclerosis'
with pytest.raises(KeyError):
# misordered args
g.add_node('DOID:2377', 'multiple sclerosis', 'disease')