Normalize JSON/YAML derived values as they pertain
    to Vault resources and comparison operations
188812
def normalize_val(val):
    
    if is_unicode(val) and val.isdigit():
        return int(val)
    elif isinstance(val, list):
        return ','.join(val)
    elif val is None:
        return ''

    return val
641017
function normalizeDispense(value) {
    var tokens = value.split(' ');
    var result;
    if (tokens.length === 4 && tokens[1] === 'Every') {
        result = {
            "doseQuantity": {
                "value": tokens[0]
            },
            "timing": {
                "repeat": {
                    "durationUnits": tokens[3]
                }
            }
        };
    } else {
        result = {
            "timing": {
                "repeat": {
                    "durationUnits": value
                }
            }
        };
    }
    return result;
}
989918
def loads_json_or_yaml(file_path, content):
    
    if os.path.splitext(file_path)[1] == ".json":
        return json.loads(content)
    else:
        return inginious.common.custom_yaml.load(content)
299288
def generate
      if @yaml.has_key?("version")
        @yaml = @yaml.fetch("services")
      end

      # Generate JSON for our containers.
      containers = @yaml.map do |name, fields|
        # Skip this service if we've been given a list to emit, and
        # this service isn't on the list.
        begin
          mount_points = (fields["volumes"] || []).map do |v|
            host, container, ro = v.split(':')
            {
              "sourceVolume" => path_to_vol_name(host),
              "containerPath" => container,
              "readOnly" => (ro == "ro")
            }
          end

          json = {
            "name" => name,
            "image" => fields.fetch("image"),
            # Default to a tiny guaranteed CPU share.  Currently, 2 is the
            # smallest meaningful value, and various ECS tools will round
            # smaller numbers up.
            "cpu" => fields["cpu_shares"] || 2,
            "memory" => mem_limit_to_mb(fields.fetch("mem_limit")),
            "links" => fields["links"] || [],
            "portMappings" =>
              (fields["ports"] || []).map {|pm| port_mapping(pm) },
            "essential" => true,
            "environment" => environment(fields["environment"] || {}),
            "mountPoints" => mount_points,
            "volumesFrom" => [],
            "dockerLabels" => fields.fetch("labels", {}),
          }
          if fields.has_key?("entrypoint")
            json["entryPoint"] = command_line(fields.fetch("entrypoint"))
          end
          if fields.has_key?("command")
            json["command"] = command_line(fields.fetch("command"))
          end
          if fields.has_key?("privileged")
            json["privileged"] = fields.fetch("privileged")
          end
          if fields.has_key?("ulimits")
            json["ulimits"] = fields.fetch("ulimits").map do |name, limits|
              case limits
              when Hash
                softLimit = limits.fetch("soft")
                hardLimit = limits.fetch("hard")
              else
                softLimit = limits
                hardLimit = limits
              end
              { "name" => name,
                "softLimit" => softLimit,
                "hardLimit" => hardLimit }
            end
          end
          json

        rescue KeyError => e
          # This makes it a lot easier to localize errors a bit.
          raise ContainerKeyError.new("#{e.message} processing container \"#{name}\"")
        end
      end

      # Generate our top-level volume declarations.
      volumes = @yaml.map do |name, fields|
        (fields["volumes"] || []).map {|v| v.split(':')[0] }
      end.flatten.sort.uniq.map do |host_path|
        {
          "name" => path_to_vol_name(host_path),
          "host" => { "sourcePath" => host_path }
        }
      end

      # Return our final JSON.
      {
        "family" => @family,
        "containerDefinitions" => containers,
        "volumes" => volumes
      }
    end
170636
function normalizeAssets(clientLibPath, assets) {

  var list = assets;

  // transform object to array
  if (!_.isArray(assets)) {
    list = [];
    _.keys(assets).forEach(function (assetKey) {
      var assetItem = assets[assetKey];

      // check/transform short version
      if (_.isArray(assetItem)) {
        assetItem = {
          files: assetItem
        };
      }
      if (!assetItem.base) {
        assetItem.base = assetKey;
      }
      assetItem.type = assetKey;
      list.push(assetItem);
    });
  }

  // transform files to scr-dest mapping
  list.forEach(function (asset) {

    var mapping = [];
    var flatName = typeof asset.flatten !== "boolean" ? true : asset.flatten;
    var assetPath = path.posix.join(clientLibPath, asset.base);
    var globOptions = {};
    if (asset.cwd) {
      globOptions.cwd = asset.cwd;
    }

    asset.files.forEach(function (file) {
      var fileItem = file;

      // convert simple syntax to object
      if (_.isString(file)) {
        fileItem = {
          src: file
        };
      }

      // no magic pattern -> default behaviour
      if (!glob.hasMagic(fileItem.src)) {

        // determine default dest
        if (!fileItem.dest) {
          fileItem.dest = path.posix.basename(file);
        }

        // generate full path
        fileItem.dest = path.posix.join(assetPath, fileItem.dest);
        mapping.push(fileItem);
      }

      // resolve magic pattern
      else {
        var files = glob.sync(fileItem.src, globOptions);
        var hasCwd = !!globOptions.cwd;
        var dest = fileItem.dest ? path.posix.join(assetPath, fileItem.dest) : assetPath;

        files.forEach(function (resolvedFile) {

          // check 'flatten' option -> strip dir name
          var destFile = flatName ? path.posix.basename(resolvedFile) : resolvedFile;

          var item = {
            src: resolvedFile,
            dest: path.posix.join(dest, destFile)
          };

          // check "cwd" option -> rebuild path, because it was stripped by glob.sync()
          if (hasCwd) {
            item.src = path.posix.join(globOptions.cwd, resolvedFile);
          }

          mapping.push(item);
        });
      }
    });

    asset.files = mapping;
  });

  return list;
}
736481
def options
      Hash[*Vault::Configurable.keys.map do |key|
        [key, instance_variable_get(:"@#{key}")]
      end.flatten]
    end
742288
def normalize_yaml(yaml):
    
    if isinstance(yaml, list):
        # Normalize the roles YAML data
        normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD'))
                           for x in yaml]
    else:
        # Extract the project names from the roles YAML and create a list of
        # tuples.
        projects = [x[:-9] for x in yaml.keys() if x.endswith('git_repo')]
        normalized_yaml = []
        for project in projects:
            repo_url = yaml['{0}_git_repo'.format(project)]
            commit_sha = yaml['{0}_git_install_branch'.format(project)]
            normalized_yaml.append((project, repo_url, commit_sha))

    return normalized_yaml
272041
def normalize_params(params):
    """"""
    # Collect a set of all fields
    fields = set()
    for p in params:
        fields.update(p)
    fields = sorted(fields)

    params2 = list(pluck(fields, params, MISSING))
    # Non-basic types (including MISSING) are unique to their id
    tokens = [
        tuple(x if isinstance(x, (int, float, str)) else id(x) for x in p)
        for p in params2
    ]

    return fields, tokens, params2
1021375
function normalizeTypeDescriptors(types) {
  let [requestType, successType, failureType] = types;

  if (typeof requestType === 'string' || typeof requestType === 'symbol') {
    requestType = { type: requestType };
  }

  if (typeof successType === 'string' || typeof successType === 'symbol') {
    successType = { type: successType };
  }
  successType = {
    payload: (action, state, res) => getJSON(res),
    ...successType
  };

  if (typeof failureType === 'string' || typeof failureType === 'symbol') {
    failureType = { type: failureType };
  }
  failureType = {
    payload: (action, state, res) =>
      getJSON(res).then(json => new ApiError(res.status, res.statusText, json)),
    ...failureType
  };

  return [requestType, successType, failureType];
}
1334615
function createValueOperator(vault, value) {
	// figure out what operation we should be doing for this vault

	var operation = value.getOperationForVault(vault);
	if (!operation) {
		return;
	}

	// check if this value can be stored in this vault, by pulling out the API for this topic

	var topicApi = configuration.getTopicApi(value.topic, vault.name);
	if (!topicApi) {
		logger.verbose('No topic API for topic', value.topic, 'on vault', vault.name);
		return;
	}

	// get the function that will execute this operation on this vault

	if (typeof vault.archive[operation] !== 'function') {
		throw new Error('Operation ' + operation + ' not supported on vault ' + vault.name);
	}

	// create a function that will execute this operation

	return function (cb) {
		logger.verbose('Running operation', operation, 'for topic', value.topic, 'on vault', vault.name);

		// errors are passed into the 2nd argument of the callback, because mutation operations are best-effort, and an
		// error case should never prevent other mutations from happening.

		try {
			var startTime = process.hrtime();

			vault.archive[operation](topicApi, value, function (error) {
				if (error) {
					var context = {
						index: value.index,
						operation: operation,
						topic: value.topic,
						vault: vault.name
					};

					logger.alert.data(context).log(error);

					exports.emit('vaultError', vault.name, operation);
				} else {
					exports.emit('operation', vault.name, operation, process.hrtime(startTime));
				}

				cb(null, error);
			});
		} catch (error) {
			var context = {
				index: value.index,
				operation: operation,
				topic: value.topic,
				vault: vault.name
			};

			logger.alert.data(context).log(error);

			setImmediate(cb, null, error);
		}
	};
}
495132
function normalizeInject (options, vm) {
  const inject = options.inject;
  if (!inject) return
  const normalized = options.inject = {};
  if (Array.isArray(inject)) {
    for (let i = 0; i < inject.length; i++) {
      normalized[inject[i]] = { from: inject[i] };
    }
  } else if (isPlainObject(inject)) {
    for (const key in inject) {
      const val = inject[key];
      normalized[key] = isPlainObject(val)
        ? extend({ from: key }, val)
        : { from: val };
    }
  } else {
    warn(
      `Invalid value for option "inject": expected an Array or an Object, ` +
      `but got ${toRawType(inject)}.`,
      vm
    );
  }
}
359782
def set_(key, value, profile=None):
    '''
    
    '''
    if '?' in key:
        __utils__['versions.warn_until'](
            'Neon',
            (
                'Using ? to seperate between the path and key for vault has been deprecated '
                'and will be removed in {version}.  Please just use a /.'
            ),
        )
        path, key = key.split('?')
    else:
        path, key = key.rsplit('/', 1)

    try:
        url = 'v1/{0}'.format(path)
        data = {key: value}
        response = __utils__['vault.make_request'](
            'POST',
            url,
            profile,
            json=data)

        if response.status_code != 204:
            response.raise_for_status()
        return True
    except Exception as e:
        log.error('Failed to write secret! %s: %s', type(e).__name__, e)
        raise salt.exceptions.CommandExecutionError(e)
675849
function(value)
	{
		value = value + '';
		var len = YamlEscaper.escapees.length;
		var maxlen = YamlEscaper.escaped.length;
		var esc = YamlEscaper.escaped;
		for (var i = 0; i < len; ++i)
			if ( i >= maxlen ) esc.push('');

		var ret = '';		
		ret = value.replace(new RegExp(YamlEscaper.escapees.join('|'),'g'), function(str){
			for(var i = 0; i < len; ++i){
				if( str == YamlEscaper.escapees[i] )
					return esc[i];
			}
		});
		return '"' + ret + '"'; 
	}
1318915
function normalize(result) {
  return {
    relevance: result.relevance || 0,
    language: result.language || null,
    value: result.value || []
  }
}
389527
function normalize(value, callback) {
  if (!value) {
    return [];
  }

  if (!Array.isArray(value)) {
    value = [ value ];
  }

  return value.map(callback);
}
1104504
function normalizeParams(params) {
        if (params && params.constructor !== Array && typeof params === 'object') {
            params = _.mapKeys(params, function (value, key) {
                return ':' + _.trimStart(key, ':');
            });
        }
        return params;
    }
439945
def _normalize_json_search_response(self, json):
        
        result = {}
        if 'facet_counts' in json:
            result['facet_counts'] = json[u'facet_counts']
        if 'grouped' in json:
            result['grouped'] = json[u'grouped']
        if 'stats' in json:
            result['stats'] = json[u'stats']
        if u'response' in json:
            result['num_found'] = json[u'response'][u'numFound']
            result['max_score'] = float(json[u'response'][u'maxScore'])
            docs = []
            for doc in json[u'response'][u'docs']:
                resdoc = {}
                if u'_yz_rk' in doc:
                    # Is this a Riak 2.0 result?
                    resdoc = doc
                else:
                    # Riak Search 1.0 Legacy assumptions about format
                    resdoc[u'id'] = doc[u'id']
                    if u'fields' in doc:
                        for k, v in six.iteritems(doc[u'fields']):
                            resdoc[k] = v
                docs.append(resdoc)
            result['docs'] = docs
        return result