Python frozendict.frozendict() Examples
The following are 27
code examples of frozendict.frozendict().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
frozendict
, or try the search function
.
Example #1
Source File: graph_outputs.py From NeMo with Apache License 2.0 | 6 votes |
def tensors(self) -> Dict[str, "NmTensor"]: """ Property returns output tensors by extracting them on the fly from the bound outputs. Returns: Dictionary of tensors in the format (output-name: tensor). """ # Get the right output dictionary. d = self._manual_outputs if len(self._manual_outputs) > 0 else self._default_outputs output_tensors = {} # Get tensors by acessing the producer-ports. # At that point all keys (k) are unigue - we made sure of that during binding/__setitem__. for k, v in d.items(): producer_step = v.producer_step_module_port.step_number producer_port_name = v.producer_step_module_port.port_name # Find the right output tensor. tensor = self._tensors_ref[producer_step][producer_port_name] # Add it to the dictionary. output_tensors[k] = tensor # Return the result as an immutable dictionary, # so the user won't be able to modify its content by an accident! return frozendict(output_tensors)
Example #2
Source File: service.py From fabricio with MIT License | 6 votes |
def update_options(self): options = itertools.chain( ( (option, value) for option, value in self._update_options.items() ), self._other_options.items(), ) evaluated_options = ( (option, value(self) if callable(value) else value) for option, value in options ) return frozendict( ( (option, value) for option, value in evaluated_options if value is not None ), args=self.cmd, )
Example #3
Source File: base.py From fabricio with MIT License | 6 votes |
def _get_options(self, safe=False): options = itertools.chain( ( ( safe and option.safe_name or option.name or attr, getattr(self, attr), ) for attr, option in (self._safe_options if safe else self._options).items() ), (self._other_safe_options if safe else self._other_options).items(), ) evaluated_options = ( (option, value(self) if callable(value) else value) for option, value in options ) return frozendict( (option, value) for option, value in evaluated_options if value is not None )
Example #4
Source File: canonicaljson.py From python-canonicaljson with Apache License 2.0 | 6 votes |
def _default(obj): if type(obj) is frozendict: # fishing the protected dict out of the object is a bit nasty, # but we don't really want the overhead of copying the dict. return obj._dict raise TypeError('Object of type %s is not JSON serializable' % obj.__class__.__name__) # ideally we'd set ensure_ascii=False, but the ensure_ascii codepath is so # much quicker (assuming c speedups are enabled) that it's actually much # quicker to let it do that and then substitute back (it's about 2.5x faster). # # (in any case, simplejson's ensure_ascii doesn't get U+2028 and U+2029 right, # as per https://github.com/simplejson/simplejson/issues/206). #
Example #5
Source File: graph_outputs.py From NeMo with Apache License 2.0 | 6 votes |
def definitions(self) -> Dict[str, GraphOutput]: """ Property returns definitions of the output ports by extracting them on the fly from the bound outputs. ..info: This property actually returns a FrozenDict containing port definitions to indicate that port definitions SHOULD not be used during the actual binding. Returns: Dictionary of neural types associated with bound outputs. """ # Get the right output dictionary. d = self._manual_outputs if len(self._manual_outputs) > 0 else self._default_outputs # Extract port definitions (Neural Types) and return an immutable dictionary, # so the user won't be able to modify its content by an accident! return frozendict({k: v.ntype for k, v in d.items()})
Example #6
Source File: __init__.py From Comparative-Annotation-Toolkit with Apache License 2.0 | 6 votes |
def get_args(pipeline_args): args = tools.misc.HashableNamespace() args.genomes = list(pipeline_args.target_genomes) + [pipeline_args.ref_genome] args.out_dir = os.path.join(pipeline_args.out_dir, 'assemblyHub') args.hub_txt = os.path.join(args.out_dir, 'hub.txt') args.genomes_txt = os.path.join(args.out_dir, 'genomes.txt') args.groups_txt = os.path.join(args.out_dir, 'groups.txt') genome_files = frozendict({genome: GenomeFiles.get_args(pipeline_args, genome) for genome in args.genomes}) sizes = {} twobits = {} trackdbs = {} for genome, genome_file in genome_files.items(): sizes[genome] = (genome_file.sizes, os.path.join(args.out_dir, genome, 'chrom.sizes')) twobits[genome] = (genome_file.two_bit, os.path.join(args.out_dir, genome, '{}.2bit'.format(genome))) trackdbs[genome] = os.path.join(args.out_dir, genome, 'trackDb.txt') args.sizes = frozendict(sizes) args.twobits = frozendict(twobits) args.trackdbs = frozendict(trackdbs) args.hal = os.path.join(args.out_dir, os.path.basename(pipeline_args.hal)) return args
Example #7
Source File: actions.py From canute-ui with GNU General Public License v3.0 | 5 votes |
def set_dimensions(self, state, value): dimensions = frozendict(width=value[0], height=value[1]) return state.copy(dimensions=dimensions)
Example #8
Source File: test_canonicaljson.py From python-canonicaljson with Apache License 2.0 | 5 votes |
def test_frozen_dict(self): self.assertEqual( encode_canonical_json(frozendict({"a": 1})), b'{"a":1}', ) self.assertEqual( encode_pretty_printed_json(frozendict({"a": 1})), b'{\n "a": 1\n}')
Example #9
Source File: __init__.py From Comparative-Annotation-Toolkit with Apache License 2.0 | 5 votes |
def get_databases(pipeline_args): """wrapper for get_database() that provides all of the databases""" dbs = {genome: PipelineTask.get_database(pipeline_args, genome) for genome in pipeline_args.hal_genomes} return frozendict(dbs)
Example #10
Source File: widgets.py From esdc-ce with Apache License 2.0 | 5 votes |
def __init__(self, attrs=None): if self.default_attrs: # dict() converts default_attrs from frozendict to regular dict defaults = dict(self.default_attrs) if attrs: defaults.update(attrs) else: defaults = attrs super(_DefaultAttrsWidget, self).__init__(attrs=defaults) if self.default_class: self.attrs['class'] = (self.default_class + ' ' + self.attrs.get('class', '')).rstrip()
Example #11
Source File: user_group.py From esdc-ce with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): super(ZabbixUserGroupContainer, self).__init__(*args, **kwargs) self.users = set() # type: [ZabbixUserContainer] # noqa: F821 self.hostgroup_ids = set() # type: [int] self.superuser_group = False self.affected_users = frozendict({key: set() for key in self.AFFECTED_USERS})
Example #12
Source File: avro_schema.py From data_pipeline with Apache License 2.0 | 5 votes |
def to_cache_value(self): return { 'schema_id': self.schema_id, 'schema_json': frozendict(self.schema_json), 'topic_name': self.topic.name, 'base_schema_id': self.base_schema_id, 'status': self.status, 'primary_keys': self.primary_keys, 'note': frozendict(self.note.to_cache_value()) if self.note is not None else None, 'created_at': self.created_at, 'updated_at': self.updated_at }
Example #13
Source File: frozendict_json_encoder.py From data_pipeline with Apache License 2.0 | 5 votes |
def default(self, obj): if isinstance(obj, frozendict): return dict(obj) return json.JSONEncoder.default(self, obj)
Example #14
Source File: utility.py From canute-ui with GNU General Public License v3.0 | 5 votes |
def unfreeze(frozen): if type(frozen) is tuple or type(frozen) is list: return list(unfreeze(x) for x in frozen) elif type(frozen) is OrderedDict or type(frozen) is FrozenOrderedDict: return OrderedDict([(k, unfreeze(v)) for k, v in list(frozen.items())]) elif type(frozen) is dict or type(frozen) is frozendict: return {k: unfreeze(v) for k, v in list(frozen.items())} else: return frozen
Example #15
Source File: actions.py From canute-ui with GNU General Public License v3.0 | 5 votes |
def close_menu(self, state, value): books = state['user']['books'] # fully delete deleted bookmarks changed_books = OrderedDict() for filename in books: book = books[filename] bookmarks = tuple(bm for bm in book.bookmarks if bm != 'deleted') book = book._replace(bookmarks=bookmarks) changed_books[filename] = book bookmarks_menu = state['bookmarks_menu'] return state.copy(location='book', bookmarks_menu=bookmarks_menu.copy(page=0), home_menu_visible=False, go_to_page_selection='', help_menu=frozendict({'visible': False, 'page': 0}), user=state['user'].copy(books=FrozenOrderedDict(changed_books)))
Example #16
Source File: actions.py From canute-ui with GNU General Public License v3.0 | 5 votes |
def toggle_help_menu(self, state, _): visible = state['help_menu']['visible'] help_menu = frozendict(visible=not visible, page=0) return state.copy(help_menu=help_menu)
Example #17
Source File: genesig.py From pySCENIC with GNU General Public License v3.0 | 5 votes |
def union(self, other: Type['GeneSignature']) -> Type['GeneSignature']: """ Creates a new :class:`GeneSignature` instance which is the union of this signature and the other supplied signature. The weight associated with the genes in the intersection is the maximum of the weights in the composing signatures. :param other: The other :class:`GeneSignature`. :return: the new :class:`GeneSignature` instance. """ return self.copy(name="({} | {})".format(self.name, other.name) if self.name != other.name else self.name, gene2weight=frozendict(merge_with(max, self.gene2weight, other.gene2weight)))
Example #18
Source File: ResourceManager.py From datastories-semeval2017-task4 with MIT License | 5 votes |
def read_hashable(self): return frozendict(self.read())
Example #19
Source File: graph_inputs.py From NeMo with Apache License 2.0 | 5 votes |
def definitions(self) -> Dict[str, "NeuralType"]: """ Property returns definitions of the input ports by extracting them on the fly from list. ..info: This property actually returns a FrozenDict containing port definitions to indicate that port definitions SHOULD not be used during the actual binding. Returns: Dictionary of neural types associated with bound inputs. """ # Extract port definitions (Neural Types) from the inputs list. return frozendict({k: v.ntype for k, v in self._inputs.items()})
Example #20
Source File: genesig.py From pySCENIC with GNU General Public License v3.0 | 5 votes |
def convert(genes): # Genes supplied as dictionary. if isinstance(genes, Mapping): return frozendict(genes) # Genes supplied as iterable of (gene, weight) tuples. elif isinstance(genes, Iterable) and all(isinstance(n, tuple) for n in genes): return frozendict(genes) # Genes supplied as iterable of genes. elif isinstance(genes, Iterable) and all(isinstance(n, str) for n in genes): return frozendict(zip(genes, repeat(1.0)))
Example #21
Source File: __init__.py From platypush with MIT License | 5 votes |
def deep_freeze(x): if isinstance(x, str) or not hasattr(x, "__len__") : return x if hasattr(x, "keys") and hasattr(x, "values") : return frozendict({deep_freeze(k) : deep_freeze(v) for k,v in x.items()}) if hasattr(x, "__getitem__") : return tuple(map(deep_freeze, x)) return frozenset(map(deep_freeze,x)) # vim:sw=4:ts=4:et:
Example #22
Source File: fx.py From uchroma with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, driver): self._driver = driver self._available_fx = frozendict(self._load_fx())
Example #23
Source File: traits.py From uchroma with GNU Lesser General Public License v3.0 | 5 votes |
def validate(self, obj, value): return frozendict(super().validate(obj, value))
Example #24
Source File: test_traits.py From uchroma with GNU Lesser General Public License v3.0 | 5 votes |
def test_frozendict_init_write_once(): odict = OrderedDict() odict['test'] = 'best value ever' obj.popsicle = odict assert isinstance(obj.popsicle, frozendict) assert obj.popsicle is not None assert 'test' in obj.popsicle assert obj.popsicle['test'] == 'best value ever'
Example #25
Source File: genesig.py From pySCENIC with GNU General Public License v3.0 | 5 votes |
def intersection(self, other: Type['GeneSignature']) -> Type['GeneSignature']: """ Creates a new :class:`GeneSignature` instance which is the intersection of this signature and the supplied other signature. The weight associated with the genes in the intersection is the maximum of the weights in the composing signatures. :param other: The other :class:`GeneSignature`. :return: the new :class:`GeneSignature` instance. """ genes = set(self.gene2weight.keys()).intersection(set(other.gene2weight.keys())) return self.copy(name="({} & {})".format(self.name, other.name) if self.name != other.name else self.name, gene2weight=frozendict(keyfilter(lambda k: k in genes, merge_with(max, self.gene2weight, other.gene2weight))))
Example #26
Source File: genesig.py From pySCENIC with GNU General Public License v3.0 | 5 votes |
def difference(self, other: Type['GeneSignature']) -> Type['GeneSignature']: """ Creates a new :class:`GeneSignature` instance which is the difference of this signature and the supplied other signature. The weight associated with the genes in the difference are taken from this gene signature. :param other: The other :class:`GeneSignature`. :return: the new :class:`GeneSignature` instance. """ return self.copy(name="({} - {})".format(self.name, other.name) if self.name != other.name else self.name, gene2weight=frozendict(dissoc(dict(self.gene2weight), *other.genes)))
Example #27
Source File: initial_state.py From canute-ui with GNU General Public License v3.0 | 4 votes |
def read_user_state(path): global prev global manual current_book = manual_filename current_language = None book_files = utility.find_files(path, ('brf', 'pef')) config = config_loader.load() state_sources = ['sd_card_dir'] if config.has_option('files', 'additional_lib_1'): state_sources.append('additional_lib_1') if config.has_option('files', 'additional_lib_2'): state_sources.append('additional_lib_2') for state_source in state_sources: _dir = config.get('files', state_source) main_toml = os.path.join(path, _dir, USER_STATE_FILE) if os.path.exists(main_toml): main_state = toml.load(main_toml) if 'current_book' in main_state: current_book = main_state['current_book'] if not current_book == manual_filename: current_book = os.path.join(path, current_book) if 'current_language' in main_state: current_language = main_state['current_language'] break if not current_language or current_language == OLD_DEFAULT_LOCALE: current_language = DEFAULT_LOCALE.code install(current_language) manual = Manual.create() manual_toml = os.path.join(path, to_state_file(manual_filename)) if os.path.exists(manual_toml): t = toml.load(manual_toml) if 'current_page' in t: manual = manual._replace(page_number=t['current_page'] - 1) if 'bookmarks' in t: manual = manual._replace(bookmarks=tuple(sorted(manual.bookmarks + tuple( bm - 1 for bm in t['bookmarks'])))) books = OrderedDict({manual_filename: manual}) for book_file in book_files: toml_file = to_state_file(book_file) book = BookFile(filename=book_file, width=40, height=9) if os.path.exists(toml_file): t = toml.load(toml_file) if 'current_page' in t: book = book._replace(page_number=t['current_page'] - 1) if 'bookmarks' in t: book = book._replace(bookmarks=tuple(sorted(book.bookmarks + tuple( bm - 1 for bm in t['bookmarks'])))) books[book_file] = book books[cleaning_filename] = CleaningAndTesting.create() if current_book not in books: current_book = manual_filename user_state = frozendict(books=FrozenOrderedDict( books), current_book=current_book, current_language=current_language) prev = user_state return user_state.copy(books=user_state['books'])