Merge multiple HParams into one with scopes.
977166
def merge_unscoped_hparams(scopes_and_hparams):
  """"""
  merged_values = {}
  for (scope, hparams) in scopes_and_hparams:
    for key, value in six.iteritems(hparams.values()):
      scoped_key = "%s.%s" % (scope, key)
      merged_values[scoped_key] = value

  return hparam.HParams(**merged_values)
126844
def transform_params(param_node, scope_stack)
      param_node = param_node[1] if param_node[0] == :paren
      if param_node
        positional_1, optional, rest, positional_2, block = param_node[1..5]
        add_variable_list(positional_1, scope_stack, false) if positional_1
        if optional
          optional.each do |var, value|
            # MUST walk value first. (def foo(y=y); end) == (def foo(y=y()); end)
            transform_tree(value, scope_stack)
            add_variables_from_node(var, scope_stack, false)
          end
        end
        if rest && rest[1]
          add_variables_from_node(rest, scope_stack, false)
        end
        add_variable_list(positional_2, scope_stack, false) if positional_2
        add_variables_from_node(block, scope_stack, false) if block
      end
    end
758721
def _combine_ngrams(ngrams, joiner) -> str:
        """"""
        if isinstance(ngrams, str):
            return ngrams
        else:
            combined = joiner.join(ngrams)
            return combined
1085311
def _merge_unbound_var_dicts(src, dst):
  """"""
  for k, v in six.iteritems(src):
    if dst.get(k, v) != v:
      trace1 = ''.join(scopes.skip_common_stack_elements(v.stacktrace, dst[
          k].stacktrace))
      trace2 = ''.join(
          scopes.skip_common_stack_elements(dst[k].stacktrace, v.stacktrace))
      raise ValueError('Key conflict: %s\nDefined At:\n%s\nand\n%s' %
                       (k, trace1, trace2))
    else:
      dst[k] = v
550655
def _reverse_problem_hparams(p_hparams):
  """"""
  p = p_hparams

  # Swap modalities.
  # TODO(trandustin): Note this assumes target modalities have feature name
  # 'target', and each intended feature to swap has feature name 'input'.
  # In the future, remove need for this behavior.
  reversed_modality = {}
  for feature_name in p.modality:
    reversed_feature_name = feature_name.replace("target", "input")
    if "target" in feature_name and reversed_feature_name in p.modality:
      reversed_modality[feature_name] = p.modality[reversed_feature_name]
      reversed_modality[reversed_feature_name] = p.modality[feature_name]
    else:
      reversed_modality[feature_name] = p.modality[feature_name]

  p.modality = reversed_modality

  # Swap vocab sizes.
  reversed_vocab_size = {}
  for feature_name in p.vocab_size:
    reversed_feature_name = feature_name.replace("target", "input")
    if "target" in feature_name and reversed_feature_name in p.vocab_size:
      reversed_vocab_size[feature_name] = p.vocab_size[reversed_feature_name]
      reversed_vocab_size[reversed_feature_name] = p.vocab_size[feature_name]
    else:
      reversed_vocab_size[feature_name] = p.vocab_size[feature_name]

  p.vocab_size = reversed_vocab_size

  # Swap vocabularies.
  input_vocabulary = p.vocabulary.pop("inputs", None)
  target_vocabulary = p.vocabulary.pop("targets", None)
  if input_vocabulary is not None:
    p.vocabulary["targets"] = input_vocabulary
  if target_vocabulary is not None:
    p.vocabulary["inputs"] = target_vocabulary

  # Swap input/target space ids.
  input_space_id = p.input_space_id
  target_space_id = p.target_space_id
  if input_space_id is not None:
    p.target_space_id = input_space_id
  else:
    p.target_space_id = SpaceID.GENERIC
  if target_space_id is not None:
    p.input_space_id = target_space_id
  else:
    p.input_space_id = SpaceID.GENERIC

  # Mark that p was reversed.
  p.was_reversed = True
284449
def _merge(*args):
    """"""
    return re.compile(r'^' + r'[/-]'.join(args) + r'(?:\s+' + _dow + ')?$')
127293
def merge_parts(self, version_id=None, **kwargs):
        """"""
        self.file.update_checksum(**kwargs)
        with db.session.begin_nested():
            obj = ObjectVersion.create(
                self.bucket,
                self.key,
                _file_id=self.file_id,
                version_id=version_id
            )
            self.delete()
        return obj
557420
def _merge_maps(m1, m2):
    """"""
    return type(m1)(chain(m1.items(), m2.items()))
972145
function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}
949169
def with_params(self, params):
        
        return self.replace(params=_merge_maps(self.params, params))
376789
def merge_keyvals_into_map(keyvals, amap):

    """"""

    for kv in keyvals:
        k,v = kv.split('=')
        if k in amap:
            logger.warn('overwriting {0} with {1}'.format(k, v))
        amap[k] = v
515194
def variables(
            self,
            name=None,
            function=None,
            decl_type=None,
            header_dir=None,
            header_file=None,
            recursive=None,
            allow_empty=None):

        """"""
        return (
            self._find_multiple(
                self._impl_matchers[
                    scopedef_t.variable],
                name=name,
                function=function,
                decl_type=decl_type,
                header_dir=header_dir,
                header_file=header_file,
                recursive=recursive,
                allow_empty=allow_empty)
        )
871911
def _merge_multi_context(outputs, major_axis):
    
    rets = []
    for tensors, axis in zip(outputs, major_axis):
        if axis >= 0:
            # pylint: disable=no-member,protected-access
            if len(tensors) == 1:
                rets.append(tensors[0])
            else:
                # Concatenate if necessary
                rets.append(nd.concat(*[tensor.as_in_context(tensors[0].context)
                                        for tensor in tensors],
                                      dim=axis))
            # pylint: enable=no-member,protected-access
        else:
            # negative axis means the there is no batch_size axis, and all the
            # results should be the same on each device. We simply take the
            # first one, without checking they are actually the same
            rets.append(tensors[0])
    return rets
704389
def add_scopes(query, scope_param)
      scopes = []
      scopes.concat scope_param.split ':' unless scope_param.nil?
      scopes.concat params[:scopes] if params[:scopes].is_a?(Array)
      scopes.each do |scope|
        method, arg_string = scope.split(/(?<=[^\\])\(/)
        if !arg_string.nil?
          arg_string = arg_string.chop.gsub(/\\\\/, "\\backspace").gsub(/\\period/, '.')
          # split on non-escaped commas
          args = arg_string.split(/(?<=[^\\]),/).map(&:strip)
          # map escaped characters to normal values
          args = args.map {|arg| arg.gsub(/\\,/, ',')}.map {|arg| arg.gsub(/\\\(/, '(')}.map {|arg| arg.gsub(/\\backspace/, '\\')}
          query = query.send method.to_sym, *args
        else
          query = query.send method.to_sym
        end
      end
      query
    end
617710
def unpack_scope(cls, scope):
        """"""
        query = {}
        projection = {}
        options = {}

        if isinstance(scope, tuple):
            if len(scope) > 3:
                raise ValueError("Invalid scope")
            if len(scope) >= 1:
                query = scope[0]
            if len(scope) >= 2:
                projection = scope[1]
            if len(scope) == 3:
                options = scope[2]
        elif isinstance(scope, dict):
            query = scope
        else:
            raise ValueError("Invalid scope")

        return query, projection, options
596773
def _merge_raw(self, other):
        """"""
        if other is None:
            variables = OrderedDict(self.variables)
        else:
            # don't align because we already called xarray.align
            variables = expand_and_merge_variables(
                [self.variables, other.variables])
        return variables
439304
def _combine_core_aux_specs(self):
        """"""
        all_specs = []
        for core_dict in self._permute_core_specs():
            for aux_dict in self._permute_aux_specs():
                all_specs.append(_merge_dicts(core_dict, aux_dict))
        return all_specs