Convert mappings to namedtuples recursively.
5494
def mapper(mapping, _nt_name='NT'):
    
    if isinstance(mapping, Mapping) and not isinstance(mapping, AsDict):
        for key, value in list(mapping.items()):
            mapping[key] = mapper(value)
        return namedtuple_wrapper(_nt_name, **mapping)
    elif isinstance(mapping, list):
        return [mapper(item) for item in mapping]
    return mapping
947201
def mapping_of(cls):
    """"""
    def mapper(data):
        if not isinstance(data, Mapping):
            raise TypeError(
                "data must be a mapping, not %s"
                % type(data).__name__)
        return {
            key: cls(value)
            for key, value in data.items()
        }
    return mapper
1374102
def zip_namedtuple(nt_list):
    
    if not nt_list:
        return dict()
    if not isinstance(nt_list, list):
        nt_list = [nt_list]
    for nt in nt_list:
        assert type(nt) == type(nt_list[0])
    ret = {k : [v] for k, v in nt_list[0]._asdict().items()}
    for nt in nt_list[1:]:
        for k, v in nt._asdict().items():
            ret[k].append(v)
    return ret
1027819
private void initializeNamesNodesMaps(Tree t) {
    for (Tree node : t.subTreeList()) {
      Matcher m = namePattern.matcher(node.label().value());
      if (m.find()) {
        namesToNodes.put(m.group(1),node);
        nodesToNames.put(node,m.group(1));
        node.label().setValue(m.replaceFirst(""));
      }
      Matcher m1 = escapedNameChar.matcher(node.label().value());
      node.label().setValue(m1.replaceAll(nameIntroducingChar));
    }
  }
1131677
def fresh(t, non_generic):
    

    mappings = {}  # A mapping of TypeVariables to TypeVariables

    def freshrec(tp):
        p = prune(tp)
        if isinstance(p, TypeVariable):
            if is_generic(p, non_generic):
                if p not in mappings:
                    mappings[p] = TypeVariable()
                return mappings[p]
            else:
                return p
        elif isinstance(p, dict):
            return p  # module
        elif isinstance(p, Collection):
            return Collection(*[freshrec(x) for x in p.types])
        elif isinstance(p, Scalar):
            return Scalar([freshrec(x) for x in p.types])
        elif isinstance(p, TypeOperator):
            return TypeOperator(p.name, [freshrec(x) for x in p.types])
        elif isinstance(p, MultiType):
            return MultiType([freshrec(x) for x in p.types])
        else:
            assert False, "missing freshrec case {}".format(type(p))

    return freshrec(t)
586739
def mapping_fields(mapping, parent=[]):
    
    rtn_obj = {}
    for key, value in mapping.items():
        new_key = parent + [key]
        new_key = ".".join(new_key)
        rtn_obj.update({new_key: value.get('type')})
        if value.get('properties'):
            rtn_obj.update(mapping_fields(value['properties'], [new_key]))
        elif value.get('fields'):
            rtn_obj.update(mapping_fields(value['fields'], [new_key]))
            rtn_obj[new_key] = [rtn_obj[new_key]] + \
                    list(value['fields'].keys())
    return rtn_obj
472200
private static ImmutableMap<IRI, VocabularyEntry> extractVocabulary(@Nonnull Mapping mapping) {
		return mapping.getRDFAtomPredicates().stream()
				.filter(p -> p instanceof TriplePredicate)
				.map(p -> (TriplePredicate) p)
				.findFirst()
				.map(p -> extractTripleVocabulary(mapping, p)
						.collect(ImmutableCollectors.toMap(e -> e.name, e -> e)))
				.orElseGet(ImmutableMap::of);
    }
1246825
def infer_typing_namedtuple(node, context=None):
    """"""
    # This is essentially a namedtuple with different arguments
    # so we extract the args and infer a named tuple.
    try:
        func = next(node.func.infer())
    except InferenceError:
        raise UseInferenceDefault

    if func.qname() != "typing.NamedTuple":
        raise UseInferenceDefault

    if len(node.args) != 2:
        raise UseInferenceDefault

    if not isinstance(node.args[1], (nodes.List, nodes.Tuple)):
        raise UseInferenceDefault

    names = []
    for elt in node.args[1].elts:
        if not isinstance(elt, (nodes.List, nodes.Tuple)):
            raise UseInferenceDefault
        if len(elt.elts) != 2:
            raise UseInferenceDefault
        names.append(elt.elts[0].as_string())

    typename = node.args[0].as_string()
    if names:
        field_names = "({},)".format(",".join(names))
    else:
        field_names = "''"
    node = extract_node(
        "namedtuple({typename}, {fields})".format(typename=typename, fields=field_names)
    )
    return infer_named_tuple(node, context)
484387
def from_mapping(cls, mapping):
        
        group = cls()
        for name, value in mapping.items():
            if name.startswith('_'):
                continue
            group[name] = Parameter(
                name=name,
                value=value,
                constraint=Parameter.constraint_from_type(value),
            )
        return group
243873
def _remap_fields(cls, kwargs):
        """"""
        mapped = {}
        for key in kwargs:
            if key in cls._remap:
                mapped[cls._remap[key]] = kwargs[key]
            else:
                mapped[key] = kwargs[key]
        return mapped
88863
function normalizeMappings(mappings) {
        if (Array.isArray(mappings)) {
            return mappings.reduce(function (normalizedMappings, key) {
                normalizedMappings[key] = key;

                return normalizedMappings;
            }, {});
        }

        return mappings;
    }
690286
def get_namedtuple(cls, field_mappings, name="Record"):
    """"""
    return namedtuple(name, [fm.destination_name for fm in field_mappings])
721910
def to_namedtuple(self):
        
        keys = filter(lambda x: not x.startswith("_"), self.__dict__)
        opt_nt = namedtuple(self.__class__.__name__, keys)
        filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys))

        return opt_nt(**filtered_dict)
949117
def flatten_dict(d,
                 parent_key='', sep='.',
                 ignore_under_prefixed=True,
                 mark_value=True):
    '''
    
    '''
    items = {}
    for k in d:
        if ignore_under_prefixed and k.startswith('__'): continue
        v = d[k]
        if mark_value and k.startswith('_') and not k.startswith('__'):
            v = MarkValue(repr(v))

        new_key = sep.join((parent_key, k)) if parent_key else k
        if isinstance(v, collections.MutableMapping):
            items.update(flatten_dict(v, new_key, sep=sep,
                                        ignore_under_prefixed=True,
                                        mark_value=True)
                            )
        else:
            items[new_key] = v

    return items
329497
def mapping_to_frozenset(mapping):
    

    aggregation = {}

    for key, value in mapping.items():
        if isinstance(value, Mapping):
            aggregation[key] = mapping_to_frozenset(value)
        elif isinstance(value, Sequence):
            value = list(value)
            for i, item in enumerate(value):
                if isinstance(item, Mapping):
                    value[i] = mapping_to_frozenset(item)
            aggregation[key] = tuple(value)
        elif isinstance(value, Set):
            aggregation[key] = frozenset(value)
        else:
            aggregation[key] = value

    return frozenset(aggregation.items())
445853
def map_with(*names)
      [self, *names.map { |name| mappers[name] }]
        .reduce { |a, e| composite_class.new(a, e) }
    end
347847
def map_nested(function, data_struct, dict_only=False, map_tuple=False):
  """"""

  # Could add support for more exotic data_struct, like OrderedDict
  if isinstance(data_struct, dict):
    return {
        k: map_nested(function, v, dict_only, map_tuple)
        for k, v in data_struct.items()
    }
  elif not dict_only:
    types = [list]
    if map_tuple:
      types.append(tuple)
    if isinstance(data_struct, tuple(types)):
      mapped = [map_nested(function, v, dict_only, map_tuple)
                for v in data_struct]
      if isinstance(data_struct, list):
        return mapped
      else:
        return tuple(mapped)
  # Singleton
  return function(data_struct)