Stupidly simple function to fix any Items/Quantity disparities inside a
    DistributionConfig block before use. Since AWS only accepts JSON-encodable
    data types, this implementation is "good enough" for our purposes.
2048
def _fix_quantities(tree):
    '''
    
    '''
    if isinstance(tree, dict):
        tree = {k: _fix_quantities(v) for k, v in tree.items()}
        if isinstance(tree.get('Items'), list):
            tree['Quantity'] = len(tree['Items'])
            if not tree['Items']:
                tree.pop('Items')  # Silly, but AWS requires it....
        return tree
    elif isinstance(tree, list):
        return [_fix_quantities(t) for t in tree]
    else:
        return tree
1286284
function(widget_config, storage_name, item_name, value) {

		if (!(storage_name in widget_config)) widget_config[storage_name] = {};
		if (Lava.schema.DEBUG && (item_name in widget_config[storage_name])) Lava.t("Duplicate item in storage: " + item_name);
		widget_config[storage_name][item_name] = value;

	}
127341
function _normalize (json, limit) {
  var result = { total: parseInt(json['total_found'], 10), torrents: [] }

  // skip total_found key, or limit further
  var count = Math.min(Object.keys(json).length - 1, limit || 200)

  // convert object to array
  for (var i = 0; i < count; i++) {
    result.torrents[i] = {}
    Object.keys(json[i + 1]).forEach(function (key) {
      // rename some keys
      result.torrents[i][key.replace('torrent_', '')] = json[i + 1][key]
    })
    result.torrents[i].category = result.torrents[i].category.toLowerCase()
  }

  return result
}
681615
def fix_val(value):
    """"""
    if type(value) == bytes:
        return value

    if sys.version_info[0] == 2:
        return bytes(value)
    elif type(value) == str:
        return bytes(value, 'UTF-8')
    else:
        return bytes(str(value), 'ASCII')
697622
def _update_aws_include_relative_path(template_dict, original_root, new_root):
    

    for key, val in template_dict.items():
        if key == "Fn::Transform":
            if isinstance(val, dict) and val.get("Name") == "AWS::Include":
                path = val.get("Parameters", {}).get("Location", {})
                updated_path = _resolve_relative_to(path, original_root, new_root)
                if not updated_path:
                    # This path does not need to get updated
                    continue

                val["Parameters"]["Location"] = updated_path

        # Recurse through all dictionary values
        elif isinstance(val, dict):
            _update_aws_include_relative_path(val, original_root, new_root)
        elif isinstance(val, list):
            for item in val:
                if isinstance(item, dict):
                    _update_aws_include_relative_path(item, original_root, new_root)

    return template_dict
1105017
def _handle_dist_server(ds_type, repos_array):
    """"""
    if ds_type not in ("JDS", "CDP"):
        raise ValueError("Must be JDS or CDP")
    prompt = "Does your JSS use a %s? (Y|N): " % ds_type
    result = loop_until_valid_response(prompt)

    if result:
        repo_dict = ElementTree.SubElement(repos_array, "dict")
        repo_name_key = ElementTree.SubElement(repo_dict, "key")
        repo_name_key.text = "type"
        repo_name_string = ElementTree.SubElement(repo_dict, "string")
        repo_name_string.text = ds_type
133363
def fix_config(self, options):
        
        opt = "setup"
        if opt not in options:
            options[opt] = filters.Filter(classname="weka.filters.AllFilter")
        if opt not in self.help:
            self.help[opt] = "The filter to apply to the dataset (Filter)."

        opt = "keep_relationname"
        if opt not in options:
            options[opt] = False
        if opt not in self.help:
            self.help[opt] = "Whether to keep the original relation name (bool)."

        return super(Filter, self).fix_config(options)
1324948
function creds(done) {
  var configPath = './config.json';
  try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
  catch(e) {
    beep();
    console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
    process.exit();
  }
  done();
}
1199007
function buildIndicesUnfreeze (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [indices.unfreeze](https://www.elastic.co/guide/en/elasticsearch/reference/current/frozen.html) request
   *
   * @param {string} index - The name of the index to unfreeze
   * @param {time} timeout - Explicit operation timeout
   * @param {time} master_timeout - Specify timeout for connection to master
   * @param {boolean} ignore_unavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
   * @param {boolean} allow_no_indices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
   * @param {enum} expand_wildcards - Whether to expand wildcard expression to concrete indices that are open, closed or both.
   * @param {string} wait_for_active_shards - Sets the number of active shards to wait for before the operation returns.
   */

  const acceptedQuerystring = [
    'timeout',
    'master_timeout',
    'ignore_unavailable',
    'allow_no_indices',
    'expand_wildcards',
    'wait_for_active_shards'
  ]

  const snakeCase = {
    masterTimeout: 'master_timeout',
    ignoreUnavailable: 'ignore_unavailable',
    allowNoIndices: 'allow_no_indices',
    expandWildcards: 'expand_wildcards',
    waitForActiveShards: 'wait_for_active_shards'
  }

  return function indicesUnfreeze (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required parameters
    if (params['index'] == null) {
      const err = new ConfigurationError('Missing required parameter: index')
      return handleError(err, callback)
    }
    if (params.body != null) {
      const err = new ConfigurationError('This API does not require a body')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, index, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = 'POST'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    path = '/' + encodeURIComponent(index) + '/' + '_unfreeze'

    // build request object
    const request = {
      method,
      path,
      body: '',
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
248867
private void adjustQualityFromAccept(Map<String, Float> pFormatQuality, HttpServletRequest pRequest) {
        // Multiply all q factors with qs factors
        // No q=.. should be interpreted as q=1.0

        // Apache does some extras; if both explicit types and wildcards
        // (without qaulity factor) are present, */* is interpreted as
        // */*;q=0.01 and image/* is interpreted as image/*;q=0.02
        // See: http://httpd.apache.org/docs-2.0/content-negotiation.html

        String accept = getAcceptedFormats(pRequest);
        //System.out.println("Accept: " + accept);

        float anyImageFactor = getQualityFactor(accept, MIME_TYPE_IMAGE_ANY);
        anyImageFactor = (anyImageFactor == 1) ? 0.02f : anyImageFactor;

        float anyFactor = getQualityFactor(accept, MIME_TYPE_ANY);
        anyFactor = (anyFactor == 1) ? 0.01f : anyFactor;

        for (String format : pFormatQuality.keySet()) {
            //System.out.println("Trying format: " + format);

            String formatMIME = MIME_TYPE_IMAGE_PREFIX + format;
            float qFactor = getQualityFactor(accept, formatMIME);
            qFactor = (qFactor == 0f) ? Math.max(anyFactor, anyImageFactor) : qFactor;
            adjustQuality(pFormatQuality, format, qFactor);
        }
    }
824617
def fix_paths(project_data, rel_path, extensions):
    
    norm_func = lambda path : os.path.normpath(os.path.join(rel_path, path))
    for key in extensions:
        if type(project_data[key]) is dict:
            for k,v in project_data[key].items():
                project_data[key][k] = [norm_func(i) for i in v]
        elif type(project_data[key]) is list:
            project_data[key] = [norm_func(i) for i in project_data[key]]
        else:
            project_data[key] = norm_func(project_data[key])
293466
function compatibilityValuesRamp (datasource, column, args) {
  var values = args[0];
  var method = (args[1] || 'quantiles').toLowerCase();
  var numBuckets = values.getLength();
  return getRamp(datasource, column, numBuckets, method).then(compatibilityCreateRampFn(values));
}
489802
function buildUpdateByQuery (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [update_by_query](https://www.elastic.co/guide/en/elasticsearch/reference/master/docs-update-by-query.html) request
   *
   * @param {list} index - A comma-separated list of index names to search; use `_all` or empty string to perform the operation on all indices
   * @param {list} type - A comma-separated list of document types to search; leave empty to perform the operation on all types
   * @param {string} analyzer - The analyzer to use for the query string
   * @param {boolean} analyze_wildcard - Specify whether wildcard and prefix queries should be analyzed (default: false)
   * @param {enum} default_operator - The default operator for query string query (AND or OR)
   * @param {string} df - The field to use as default where no field prefix is given in the query string
   * @param {number} from - Starting offset (default: 0)
   * @param {boolean} ignore_unavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
   * @param {boolean} allow_no_indices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
   * @param {enum} conflicts - What to do when the update by query hits version conflicts?
   * @param {enum} expand_wildcards - Whether to expand wildcard expression to concrete indices that are open, closed or both.
   * @param {boolean} lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
   * @param {string} pipeline - Ingest pipeline to set on index requests made by this action. (default: none)
   * @param {string} preference - Specify the node or shard the operation should be performed on (default: random)
   * @param {string} q - Query in the Lucene query string syntax
   * @param {list} routing - A comma-separated list of specific routing values
   * @param {time} scroll - Specify how long a consistent view of the index should be maintained for scrolled search
   * @param {enum} search_type - Search operation type
   * @param {time} search_timeout - Explicit timeout for each search request. Defaults to no timeout.
   * @param {number} size - Number of hits to return (default: 10)
   * @param {list} sort - A comma-separated list of <field>:<direction> pairs
   * @param {list} _source - True or false to return the _source field or not, or a list of fields to return
   * @param {list} _source_excludes - A list of fields to exclude from the returned _source field
   * @param {list} _source_includes - A list of fields to extract and return from the _source field
   * @param {number} terminate_after - The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.
   * @param {list} stats - Specific 'tag' of the request for logging and statistical purposes
   * @param {boolean} version - Specify whether to return document version as part of a hit
   * @param {boolean} version_type - Should the document increment the version number (internal) on hit or not (reindex)
   * @param {boolean} request_cache - Specify if request cache should be used for this request or not, defaults to index level setting
   * @param {boolean} refresh - Should the effected indexes be refreshed?
   * @param {time} timeout - Time each individual bulk request should wait for shards that are unavailable.
   * @param {string} wait_for_active_shards - Sets the number of shard copies that must be active before proceeding with the update by query operation. Defaults to 1, meaning the primary shard only. Set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1)
   * @param {number} scroll_size - Size on the scroll request powering the update by query
   * @param {boolean} wait_for_completion - Should the request should block until the update by query operation is complete.
   * @param {number} requests_per_second - The throttle to set on this request in sub-requests per second. -1 means no throttle.
   * @param {number} slices - The number of slices this task should be divided into. Defaults to 1 meaning the task isn't sliced into subtasks.
   * @param {object} body - The search definition using the Query DSL
   */

  const acceptedQuerystring = [
    'analyzer',
    'analyze_wildcard',
    'default_operator',
    'df',
    'from',
    'ignore_unavailable',
    'allow_no_indices',
    'conflicts',
    'expand_wildcards',
    'lenient',
    'pipeline',
    'preference',
    'q',
    'routing',
    'scroll',
    'search_type',
    'search_timeout',
    'size',
    'sort',
    '_source',
    '_source_excludes',
    '_source_includes',
    'terminate_after',
    'stats',
    'version',
    'version_type',
    'request_cache',
    'refresh',
    'timeout',
    'wait_for_active_shards',
    'scroll_size',
    'wait_for_completion',
    'requests_per_second',
    'slices',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    analyzeWildcard: 'analyze_wildcard',
    defaultOperator: 'default_operator',
    ignoreUnavailable: 'ignore_unavailable',
    allowNoIndices: 'allow_no_indices',
    expandWildcards: 'expand_wildcards',
    searchType: 'search_type',
    searchTimeout: 'search_timeout',
    _sourceExcludes: '_source_excludes',
    _sourceIncludes: '_source_includes',
    terminateAfter: 'terminate_after',
    versionType: 'version_type',
    requestCache: 'request_cache',
    waitForActiveShards: 'wait_for_active_shards',
    scrollSize: 'scroll_size',
    waitForCompletion: 'wait_for_completion',
    requestsPerSecond: 'requests_per_second',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function updateByQuery (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required parameters
    if (params['index'] == null) {
      const err = new ConfigurationError('Missing required parameter: index')
      return handleError(err, callback)
    }

    // check required url components
    if (params['type'] != null && (params['index'] == null)) {
      const err = new ConfigurationError('Missing required parameter of the url: index')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, index, type, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = 'POST'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((index) != null && (type) != null) {
      path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + '_update_by_query'
    } else {
      path = '/' + encodeURIComponent(index) + '/' + '_update_by_query'
    }

    // build request object
    const request = {
      method,
      path,
      body: body || '',
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
412128
function createSizeFilters(output, key, value) {
  // Store parameters
  var data = output.sizeData = output.sizeData || {};
  data[key] = value;

  if (!('size' in data)) {
    // No size requested, keep original size
    return [];
  }

  // Try to match the different size string formats
  var fixedSize = data.size.match(/([0-9]+)x([0-9]+)/);
  var fixedWidth = data.size.match(/([0-9]+)x\?/);
  var fixedHeight = data.size.match(/\?x([0-9]+)/);
  var percentRatio = data.size.match(/\b([0-9]{1,3})%/);
  var width, height, aspect;

  if (percentRatio) {
    var ratio = Number(percentRatio[1]) / 100;
    return [{
      filter: 'scale',
      options: {
        w: 'trunc(iw*' + ratio + '/2)*2',
        h: 'trunc(ih*' + ratio + '/2)*2'
      }
    }];
  } else if (fixedSize) {
    // Round target size to multiples of 2
    width = Math.round(Number(fixedSize[1]) / 2) * 2;
    height = Math.round(Number(fixedSize[2]) / 2) * 2;

    aspect = width / height;

    if (data.pad) {
      return getScalePadFilters(width, height, aspect, data.pad);
    } else {
      // No autopad requested, rescale to target size
      return [{ filter: 'scale', options: { w: width, h: height }}];
    }
  } else if (fixedWidth || fixedHeight) {
    if ('aspect' in data) {
      // Specified aspect ratio
      width = fixedWidth ? fixedWidth[1] : Math.round(Number(fixedHeight[1]) * data.aspect);
      height = fixedHeight ? fixedHeight[1] : Math.round(Number(fixedWidth[1]) / data.aspect);

      // Round to multiples of 2
      width = Math.round(width / 2) * 2;
      height = Math.round(height / 2) * 2;

      if (data.pad) {
        return getScalePadFilters(width, height, data.aspect, data.pad);
      } else {
        // No autopad requested, rescale to target size
        return [{ filter: 'scale', options: { w: width, h: height }}];
      }
    } else {
      // Keep input aspect ratio

      if (fixedWidth) {
        return [{
          filter: 'scale',
          options: {
            w: Math.round(Number(fixedWidth[1]) / 2) * 2,
            h: 'trunc(ow/a/2)*2'
          }
        }];
      } else {
        return [{
          filter: 'scale',
          options: {
            w: 'trunc(oh*a/2)*2',
            h: Math.round(Number(fixedHeight[1]) / 2) * 2
          }
        }];
      }
    }
  } else {
    throw new Error('Invalid size specified: ' + data.size);
  }
}
680776
function fixMultisigOrder (input, transaction, vin, value, network) {
  if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return
  if (input.pubKeys.length === input.signatures.length) return

  network = network || networks.bitcoin
  var unmatched = input.signatures.concat()

  input.signatures = input.pubKeys.map(function (pubKey) {
    var keyPair = ECPair.fromPublicKeyBuffer(pubKey)
    var match

    // check for a signature
    unmatched.some(function (signature, i) {
      // skip if undefined || OP_0
      if (!signature) return false

      // TODO: avoid O(n) hashForSignature
      var parsed = ECSignature.parseScriptSignature(signature)
      var hash
      switch (network.coin) {
        case coins.BSV:
        case coins.BCH:
          hash = transaction.hashForCashSignature(vin, input.signScript, value, parsed.hashType)
          break
        case coins.BTG:
          hash = transaction.hashForGoldSignature(vin, input.signScript, value, parsed.hashType)
          break
        case coins.ZEC:
          if (value === undefined) {
            return false
          }
          hash = transaction.hashForZcashSignature(vin, input.signScript, value, parsed.hashType)
          break
        default:
          if (input.witness) {
            hash = transaction.hashForWitnessV0(vin, input.signScript, value, parsed.hashType)
          } else {
            hash = transaction.hashForSignature(vin, input.signScript, parsed.hashType)
          }
          break
      }

      // skip if signature does not match pubKey
      if (!keyPair.verify(hash, parsed.signature)) return false

      // remove matched signature from unmatched
      unmatched[i] = undefined
      match = signature

      return true
    })

    return match
  })
}
1148003
def normalize_options(options)
      options = options.dup

      options.tap do |opts|
        opts[:prefix] ||= "gridfs"
        opts[:prefix] = options[:prefix].gsub(/^\//, '')
        opts[:mapper] ||= lambda { |path| %r!^/#{options[:prefix]}/(.+)!.match(path)[1] }
      end
    end
861773
public static void assertJsonPartNotEquals(Object expected, Object fullJson, String path, Configuration configuration) {
        Diff diff = create(expected, fullJson, FULL_JSON, path, configuration);
        if (diff.similar()) {
            if (ROOT.equals(path)) {
                doFail("Expected different values but the values were equal.");
            } else {
                doFail(String.format("Expected different values in node \"%s\" but the values were equal.", path));
            }
        }
    }