Walk through the supplied key handles and normalize them, while keeping
    the input format too (as value in a dictionary). The input format is
    used in AEAD filename paths.
189282
def keyhandles_fixup(args):
    
    new_handles = {}
    for val in args.key_handles:
        n = pyhsm.util.key_handle_to_int(val)
        new_handles[n] = val

    args.key_handles = new_handles
456227
def normalize_dictionary_values(dictionary):
    
    
    for key, val in dictionary.iteritems():
        if isinstance(val, dict):
            dictionary[key] = normalize_dictionary_values(val)
        elif isinstance(val, list):
            dictionary[key] = list(val)
        else:
            dictionary[key] = normalize_value(val)
    
    return dictionary
1251359
def _dict_prefix(self, key, value, i, dj=0, color=None, separator=":"):
        just = self._justify if i > 0 else dj
        key = cut(str(key), self._key_maxlen).rjust(just)
        key = colorize(key, color=color)
        pref = "{}{} {}".format(key, separator, value)
        """"""
        return pref
512996
function normalizeSR (input) {
  // The following WKIDs are known to proj4
  const knownWkids = [4326, 4269, 3857, 3785, 900913, 102113]
  let inputWkid

  // Search input for a wkid
  if (Number.isInteger(input) || Number.isInteger(Number(input))) inputWkid = Number(input)
  else if (/EPSG:/.test(input)) inputWkid = Number(input.match(/EPSG:(.*)/)[1])
  else if (input && (input.latestWkid || input.wkid)) inputWkid = input.latestWkid || input.wkid

  // When required input is undefined, return undefined
  if (!input || (_.isObject(input) && !inputWkid && !input.wkt)) return

  // 102100 is the old code for 3857 but not recognized for proj4
  if (inputWkid === 102100) inputWkid = 3857

  // If the input wkid is one of the set known to proj4, return it in an object
  if (knownWkids.includes(inputWkid)) return { wkid: inputWkid }

  // If here, WKID is not known to proj4, so we need its WKT spatial reference in order to do downstream reprojections.  First check in local lookup
  let wkt = wkidLookup[inputWkid]
  if (wkt) return { wkt }

  // If the wkid was not found in the local lookup, check the Esri lookups
  const esriResult = esriProjCodes.lookup(inputWkid)
  if (esriResult) {
    // Add the WKT to the local lookup so we don't need to scan the Esri lookups next time (we have a local lookup, because it will contain a smaller set of wkids than the Esri lookups)
    wkidLookup[inputWkid] = esriResult.wkt
    return { wkt: esriResult.wkt }
  }

  // If here and the inputWkid is defined without a wkt, the input was an unknown wkid without a wkt
  if (inputWkid && !input.wkt && process.env.NODE_ENV !== 'production') {
    console.log(`WARNING: An unknown spatial reference was detected: ${input}`)
  }

  // Input may already be or include a WKT spatial reference
  wkt = input.wkt || input

  // If wkt includes 'WGS_1984_Web_Mercator_Auxiliary_Sphere' return wkid 3857
  if (/WGS_1984_Web_Mercator_Auxiliary_Sphere/.test(wkt)) return { wkid: 3857 }

  try {
    wktParser(wkt)
    return { wkt }
  } catch (err) {
    if (process.env.NODE_ENV !== 'production') {
      console.log(`WARNING: An un-parseable WKT spatial reference was detected: ${wkt}`)
    }
  }
}
867373
function _keyPathNormalize(kp) {
    return new String(kp).replace(/\[([^\[\]]+)\]/g, function(m, k) {
        return '.' + k.replace(/^["']|["']$/g, '')
    })
}
1111614
def bind_env(self, *input_):
        
        if len(input_) == 0:
            return "bind_env missing key to bind to"

        key = input_[0].lower()

        if len(input_) == 1:
            env_key = self._merge_with_env_prefix(key)
        else:
            env_key = input_[1]

        self._env[key] = env_key

        if self._key_delimiter in key:
            parts = input_[0].split(self._key_delimiter)
            env_info = {
                "path": parts[1:-1],
                "final_key": parts[-1],
                "env_key": env_key
            }

            if self._env.get(parts[0]) is None:
                self._env[parts[0]] = [env_info]
            else:
                self._env[parts[0]].append(env_info)

        return None
559879
private void processKeyValue(Map<ConfigurationKey, Object> properties, String stringKey, Object value) {
        processKeyValue(properties, stringKey, value, false);
    }
1123169
function keyname(str) {
  return path.basename(path.normalize(str), path.extname(str));
}
902536
def extract_keypairs(lines, regexer):
    """"""
    updates = {}
    for line in lines:
        # for consistency we must match the replacer and strip whitespace / newlines
        match = regexer.match(line.strip())
        if not match:
            continue
        k_v = match.groupdict()
        updates[k_v[Constants.KEY_GROUP]] = k_v[Constants.VALUE_GROUP]
    return updates
498935
function handle1dkeys (keys, value, step, min, max) {
	step = step || 1;

	//up and right - increase by one
	if (keys[38] || keys[39]) {
		value = inc(value, step, 1);
	}

	//down and left - decrease by one
	if (keys[40] || keys[37]) {
		value = inc(value, step, -1);
	}

	//home - min
	if (keys[36]) {
		value = min;
	}

	//end - max
	if (keys[35]) {
		value = max;
	}

	//pageup
	if (keys[33]) {
		value = inc(value, step, PAGE);
	}

	//pagedown
	if (keys[34]) {
		value = inc(value, step, -PAGE);
	}

	return value;
}
77093
def clean_key_name(self):
        """"""
        key = self.cleaned_data['key_name']
        # Ensure key starts with prefix
        if not key.startswith(self.get_key_prefix()):
            raise forms.ValidationError('Key does not have required prefix.')
        # Ensure key exists
        if not self.get_upload_key():
            raise forms.ValidationError('Key does not exist.')
        return key
1248053
def normalize_value(value)
      unless value.is_a?(Hash)
        value = value.respond_to?(:to_ary) ? value.to_ary : value.to_str
      end

      # Handle unicode normalization
      if value.kind_of?(Array)
        value.map! { |val| Addressable::IDNA.unicode_normalize_kc(val) }
      elsif value.kind_of?(Hash)
        value = value.inject({}) { |acc, (k, v)|
          acc[Addressable::IDNA.unicode_normalize_kc(k)] =
            Addressable::IDNA.unicode_normalize_kc(v)
          acc
        }
      else
        value = Addressable::IDNA.unicode_normalize_kc(value)
      end
      value
    end
1153092
def _normalize_path(self, path):
        
        if type(path) is str:
            path = path.encode()
        path = path.split(b'\0')[0]

        if path[0:1] != self.pathsep:
            path = self.cwd + self.pathsep + path
        keys = path.split(self.pathsep)
        i = 0
        while i < len(keys):
            if keys[i] == b'':
                keys.pop(i)
            elif keys[i] == b'.':
                keys.pop(i)
            elif keys[i] == b'..':
                keys.pop(i)
                if i != 0:
                    keys.pop(i-1)
                    i -= 1
            else:
                i += 1
        return keys
1264985
function normalizeHeaderKey() {
  var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

  return key.replace(/\r?\n|\r/g, ' ') // no newlines in keys
  .trim().toLowerCase().replace(/^MIME\b|^[a-z]|-[a-z]/ig, function (c) {
    return c.toUpperCase();
  }); // use uppercase words, except MIME
}
731213
def _cleanup_new_key(self, key, size, axis):
        
        if _is_scalar(key):
            if key >= size or key < -size:
                msg = 'index {0} is out of bounds for axis {1} with' \
                      ' size {2}'.format(key, axis, size)
                raise IndexError(msg)
        elif isinstance(key, slice):
            pass
        elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'):
            if key.size > size:
                msg = 'too many boolean indices. Boolean index array ' \
                      'of size {0} is greater than axis {1} with ' \
                      'size {2}'.format(key.size, axis, size)
                raise IndexError(msg)
        elif isinstance(key, collections.Iterable) and \
                not isinstance(key, six.string_types):
            # Make sure we capture the values in case we've
            # been given a one-shot iterable, like a generator.
            key = tuple(key)
            for sub_key in key:
                if sub_key >= size or sub_key < -size:
                    msg = 'index {0} is out of bounds for axis {1}' \
                          ' with size {2}'.format(sub_key, axis, size)
                    raise IndexError(msg)
        else:
            raise TypeError('invalid key {!r}'.format(key))
        return key
768930
def _normalize_slice(self, key, clamp=False):
        """"""
        if key.start is None:
            start = 0
        else:
            start = (len(self) + key.start) if key.start < 0 else key.start
        if key.stop is None or key.stop == maxsize:
            stop = len(self) if clamp else None
        else:
            stop = (len(self) + key.stop) if key.stop < 0 else key.stop
        return slice(start, stop, key.step or 1)
442250
def _args_from_dict(ddata: Mapping[str, Any]):
        
        d_true_keys = {}
        # backwards compat
        uns_is_not_key = False
        valid_keys = []
        for keys in AnnData._H5_ALIASES.values():
            valid_keys += keys
        valid_keys += ['raw.X', 'raw.var', 'raw.varm', 'raw.cat']
        for key in ddata.keys():
            # if there is another key then the prdedefined
            # then we are reading the old format
            if key not in valid_keys:
                uns_is_not_key = True

        for true_key, keys in AnnData._H5_ALIASES.items():
            for key in keys:
                if key in ddata:
                    d_true_keys[true_key] = ddata[key]
                    if uns_is_not_key: del ddata[key]
                    break
            else:
                d_true_keys[true_key] = None

        # transform recarray to dataframe
        for true_key, keys in AnnData._H5_ALIASES_NAMES.items():
            if d_true_keys[true_key] is not None:
                for key in keys:
                    if key in d_true_keys[true_key].dtype.names:
                        d_true_keys[true_key] = pd.DataFrame.from_records(
                            d_true_keys[true_key], index=key)
                        break
                d_true_keys[true_key].index = d_true_keys[true_key].index.astype('U')
                # transform to unicode string
                # TODO: this is quite a hack
                for c in d_true_keys[true_key].columns:
                    if is_string_dtype(d_true_keys[true_key][c]):
                        d_true_keys[true_key][c] = pd.Index(
                            d_true_keys[true_key][c]).astype('U').values

        # these are the category fields
        k_to_delete = []
        items = (
            ddata.items() if uns_is_not_key
            else ddata['uns'].items() if 'uns' in ddata else []
        )
        for k, v in items:
            if k.endswith('_categories'):
                k_stripped = k.replace('_categories', '')
                if isinstance(v, (str, int)):  # fix categories with a single category
                    v = [v]
                for ann in ['obs', 'var']:
                    if k_stripped in d_true_keys[ann]:
                        d_true_keys[ann][k_stripped] = pd.Categorical.from_codes(
                            codes=d_true_keys[ann][k_stripped].values,
                            categories=v,
                        )
                k_to_delete.append(k)

        for k in k_to_delete:
            if uns_is_not_key:
                del ddata[k]
            else:
                del ddata['uns'][k]

        # assign the variables
        X = d_true_keys['X']
        obs = d_true_keys['obs']
        obsm = d_true_keys['obsm']
        var = d_true_keys['var']
        varm = d_true_keys['varm']
        layers = d_true_keys['layers']

        raw = None
        if 'raw.X' in ddata:
            raw = {}
            raw['X'] = ddata['raw.X']
            del ddata['raw.X']
            # get the dataframe
            raw['var'] = pd.DataFrame.from_records(
                ddata['raw.var'], index='index')
            del ddata['raw.var']
            raw['var'].index = raw['var'].index.astype('U')
            # transform to unicode string
            for c in raw['var'].columns:
                if is_string_dtype(raw['var'][c]):
                    raw['var'][c] = pd.Index(raw['var'][c]).astype('U').values
            # these are the category fields
            if 'raw.cat' in ddata:  # old h5ad didn't have that field
                for k, v in ddata['raw.cat'].items():
                    if k.endswith('_categories'):
                        k_stripped = k.replace('_categories', '')
                        if isinstance(v, (str, int)):  # fix categories with a single category
                            v = [v]
                        raw['var'][k_stripped] = pd.Categorical.from_codes(
                            codes=raw['var'][k_stripped].values,
                            categories=v)
                del ddata['raw.cat']
        if 'raw.varm' in ddata:
            raw['varm'] = ddata['raw.varm']
            del ddata['raw.varm']
        elif raw is not None:
            raw['varm'] = None

        # the remaining fields are the unstructured annotation
        uns = (
            ddata if uns_is_not_key
            else ddata['uns'] if 'uns' in ddata
            else {}
        )

        return X, obs, var, uns, obsm, varm, layers, raw