AWS employs a strict interpretation of [RFC 3986](http://tools.ietf.org/html/rfc3986#page-12). So, we must ensure all reserved characters listed in the spec are percent-encoded, and spaces are replaced with "+".
169751
function(param) {
            var percentEncoded = encodeURIComponent(param);

            // %-encode characters not handled by `encodeURIComponent` (to follow RFC 3986)
            percentEncoded = percentEncoded.replace(/[!'()]/g, escape);

            // %-encode characters not handled by `escape` (to follow RFC 3986)
            percentEncoded = percentEncoded.replace(/\*/g, "%2A");

            // replace percent-encoded spaces with a "+"
            return percentEncoded.replace(/%20/g, "+");
        }
276109
function fixedEncodeURIComponent (str) {
    return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
      return '%' + c.charCodeAt(0).toString(16);
    });
  }
594415
def percent_encode_non_ascii_headers(self, encoding='UTF-8'):
        
        def do_encode(m):
            return "*={0}''".format(encoding) + quote(to_native_str(m.group(1)))

        for index in range(len(self.headers) - 1, -1, -1):
            curr_name, curr_value = self.headers[index]
            try:
                # test if header is ascii encodable, no action needed
                curr_value.encode('ascii')
            except:
                new_value = self.ENCODE_HEADER_RX.sub(do_encode, curr_value)
                if new_value == curr_value:
                    new_value = quote(curr_value)

                self.headers[index] = (curr_name, new_value)
698490
function decode(s) {
    if (s) {
        s = s.toString().replace(re.pluses, '%20');
        s = decodeURIComponent(s);
    }
    return s;
  }
248486
public static String encodePath(String path) {
        // Any characters that are not one of the following are
        // percent-encoded (including spaces):
        // a-z A-Z 0-9 . - _ ~ ! $ &amp; ' ( ) * + , ; = : @ / %
        if (StringUtils.isBlank(path)) {
            return path;
        }
        StringBuilder sb = new StringBuilder();
        for (char ch : path.toCharArray()) {
            // Space to plus sign
            if (ch == ' ') {
                sb.append("%20");
                // Valid: keep it as is.
            } else if (CharUtils.isAsciiAlphanumeric(ch)
                    || ".-_~!$&'()*+,;=:@/%".indexOf(ch) != -1)  {
                sb.append(ch);
                // Invalid: encode it
            } else {
                byte[] bytes;
                bytes = Character.toString(ch).getBytes(StandardCharsets.UTF_8);
                for (byte b : bytes) {
                    sb.append('%');
                    int upper = (((int) b) >> 4) & 0xf;
                    sb.append(Integer.toHexString(
                            upper).toUpperCase(Locale.US));
                    int lower = ((int) b) & 0xf;
                    sb.append(Integer.toHexString(
                            lower).toUpperCase(Locale.US));
                }
            }
        }
        return sb.toString();
    }
377677
def normalize_password(text, encoding='utf-8'):
    '''
    '''
    path = percent_encode(text, encoding=encoding, encode_set=PASSWORD_ENCODE_SET)
    return uppercase_percent_encoding(path)
1370782
@SuppressWarnings("unchecked")
    private String encodeAttribute(String s, Charset charset) throws ErrorDataEncoderException {
        if (s == null) {
            return "";
        }
        try {
            String encoded = URLEncoder.encode(s, charset.name());
            if (encoderMode == EncoderMode.RFC3986) {
                for (Map.Entry<Pattern, String> entry : percentEncodings) {
                    String replacement = entry.getValue();
                    encoded = entry.getKey().matcher(encoded).replaceAll(replacement);
                }
            }
            return encoded;
        } catch (UnsupportedEncodingException e) {
            throw new ErrorDataEncoderException(charset.name(), e);
        }
    }
1082575
function quotedString(str) {
  return '"' + str
    .replace(/\\/g, '\\\\')
    .replace(/"/g, '\\"')
    .replace(/\n/g, '\\n')
    .replace(/\r/g, '\\r')
    .replace(/\u2028/g, '\\u2028')   // Per Ecma-262 7.3 + 7.8.4
    .replace(/\u2029/g, '\\u2029') + '"'
}
287327
function utf8ByteLength(str) {
  let s = str.length;
  let i;
  for (i = str.length - 1; i >= 0; i -= 1) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) {
      s += 1;
    } else if (code > 0x7ff && code <= 0xffff) {
      s += 2;
    }

    // trail surrogate
    if (code >= 0xDC00 && code <= 0xDFFF) {
      i -= 1;
    }
  }

  return s;
}
917870
def normalize_query(text, encoding='utf-8'):
    '''
    '''
    path = percent_encode_plus(text, encoding=encoding)
    return uppercase_percent_encoding(path)
88868
function b64DecodeUnicode(str) {
  // Going backwards: from bytestream, to percent-encoding, to original string.
  return decodeURIComponent(atob(str).split('').map(function (c) {
    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));
}
1242858
public static void parseQueryString( String str, Map res, String encoding )
    {

        // "Within the query string, the plus sign is reserved as
        // shorthand notation for a space. Therefore, real plus signs must
        // be encoded. This method was used to make query URIs easier to
        // pass in systems which did not allow spaces." -- RFC 1630
        int i = str.indexOf( '#' );
        if ( i > 0 )
        {
            str = str.substring( 0, i );
        }
        StringTokenizer st = new StringTokenizer( str.replace( '+', ' ' ), "&" );

        while ( st.hasMoreTokens() )
        {
            String qp = st.nextToken();
            String[] pair = qp.split( "=" );  // was String[] pair = StringUtils.split(qp, '=');
            //String s = unescape(pair[1], encoding);
            res.put( unescape( pair[0], encoding ), unescape( pair[1], encoding ) );
        }
    }
289069
function saslprep(input, opts = {}) {
  if (typeof input !== 'string') {
    throw new TypeError('Expected string.');
  }

  if (input.length === 0) {
    return '';
  }

  // 1. Map
  const mapped_input = toCodePoints(input)
    // 1.1 mapping to space
    .map(character => (mapping2space.get(character) ? 0x20 : character))
    // 1.2 mapping to nothing
    .filter(character => !mapping2nothing.get(character));

  // 2. Normalize
  const normalized_input = String.fromCodePoint
    .apply(null, mapped_input)
    .normalize('NFKC');

  const normalized_map = toCodePoints(normalized_input);

  // 3. Prohibit
  const hasProhibited = normalized_map.some(character =>
    prohibited_characters.get(character)
  );

  if (hasProhibited) {
    throw new Error(
      'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3'
    );
  }

  // Unassigned Code Points
  if (opts.allowUnassigned !== true) {
    const hasUnassigned = normalized_map.some(character =>
      unassigned_code_points.get(character)
    );

    if (hasUnassigned) {
      throw new Error(
        'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5'
      );
    }
  }

  // 4. check bidi

  const hasBidiRAL = normalized_map.some(character =>
    bidirectional_r_al.get(character)
  );

  const hasBidiL = normalized_map.some(character =>
    bidirectional_l.get(character)
  );

  // 4.1 If a string contains any RandALCat character, the string MUST NOT
  // contain any LCat character.
  if (hasBidiRAL && hasBidiL) {
    throw new Error(
      'String must not contain RandALCat and LCat at the same time,' +
        ' see https://tools.ietf.org/html/rfc3454#section-6'
    );
  }

  /**
   * 4.2 If a string contains any RandALCat character, a RandALCat
   * character MUST be the first character of the string, and a
   * RandALCat character MUST be the last character of the string.
   */

  const isFirstBidiRAL = bidirectional_r_al.get(
    getCodePoint(first(normalized_input))
  );
  const isLastBidiRAL = bidirectional_r_al.get(
    getCodePoint(last(normalized_input))
  );

  if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {
    throw new Error(
      'Bidirectional RandALCat character must be the first and the last' +
        ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6'
    );
  }

  return normalized_input;
}
717301
function (uri) {
  return encodeURIComponent(uri)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
}
262161
private boolean validCharacters(String value) {
        if (INVALID_CHARACTERS.contains(value)) {
            LOG.error("Flash key or value can not contain the following characters: spaces, |, & or :");
            return false;
        }

        return true;
    }
219188
function ecc200encode(&$t, &$tl, $s, $sl, $e) {
        // start in ASCII encoding mode
        $enc = 'a';
        $tp = 0;
        $sp = 0;
        $p = 0;
        $v = 0;
        $w = 0;

        $oldErrorReporting = error_reporting(0);

        //does not work, but is said to be optional, doesn't work in the JS code either because of a typo
        //        if ($e['encodingLength'] < $sl)
        //        {
        //            die("Encoding string too short");
        //            return 0;
        //        }

        // do the encoding
        while ($sp < $sl && $tp < $tl) {
            // suggest new encoding
            $newenc = $enc;
            if ($tl - $tp <= 1 && ($enc == 'c' || $enc == 't') || $tl - $tp <= 2 && $enc == 'x')
                // auto revert to ASCII
                $enc = 'a';
            //$this->debug("encoding: " + e.encoding);
            //$this->debug("encoding[sp]: " + e.encoding[sp]);
            $newenc = strtolower($e['encoding'][$sp]);
            switch ($newenc) {
                // encode character
                case 'c':
                    // C40
                case 't':
                    // Text
                case 'x': {
                    // X12
                    $out = array_fill(0, 6, 0);
                    $p = 0;
                    $s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_\232";
                    $s3 = "";
                    if ($newenc == 'c') {
                        $en = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                        $s3 = "`abcdefghijklmnopqrstuvwxyz{|}~\177";
                    }
                    if ($newenc == 't') {
                        $en = " 0123456789abcdefghijklmnopqrstuvwxyz";
                        $s3 = "`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\177";
                    }
                    if ($newenc == 'x')
                        $en = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\r*>";
                    do {
                        $c = $s{$sp++};
                        if ($c & 0x80) {
                            if ($newenc == 'x') {
                                die("Cannot encode char in X12: " . $c);
                                return 0;
                            }
                            $c = $c & 0x7f;
                            $out[$p++] = 1;
                            $out[$p++] = 30;
                        }
                        $w = strpos($en, $c);
                        if ($w !== false)
                            $out[$p++] = ($w + 3) % 40;
                        else {
                            if ($newenc == 'x') {
                                die("Cannot encode char in X12: " . $c);
                                return 0;
                            }
                            if (ord($c) < 32) {
                                // shift 1 XXX
                                $out[$p++] = 0;
                                $out[$p++] = $c;
                            } else {
                                $w = strpos($s2, $c);
                                if ($w !== false) {
                                    // shift 2
                                    $out[$p++] = 1;
                                    $out[$p++] = $w;
                                } else {
                                    $w = strpos($s3, $c);
                                    if ($w !== false) {
                                        $out[$p++] = 2;
                                        $out[$p++] = $w;
                                    } else {
                                        die("Should not happen. Could not encode: " . $c);
                                        return 0;
                                    }
                                }
                            }
                        }
                        if ($p == 2 && $tp + 2 == $tl && $sp == $sl)
                            // shift 1 $pad at end
                            $out[$p++] = 0;
                        while ($p >= 3) {
                            $v = $out[0] * 1600 + $out[1] * 40 + $out[2] + 1;
                            if ($enc != $newenc) {
                                if ($enc == 'c' || $enc == 't' || $enc == 'x')
                                    // escape C40/text/X12
                                    $t[$tp++] = 254;
                                elseif ($enc == 'x')
                                    // escape EDIFACT
                                    $t[$tp++] = 0x7C;
                                if ($newenc == 'c')
                                    $t[$tp++] = 230;
                                if ($newenc == 't')
                                    $t[$tp++] = 239;
                                if ($newenc == 'x')
                                    $t[$tp++] = 238;
                                $enc = $newenc;
                            }
                            $t[$tp++] = ($v >> 8);
                            $t[$tp++] = ($v & 0xFF);
                            $p -= 3;
                            $out[0] = $out[3];
                            $out[1] = $out[4];
                            $out[2] = $out[5];
                        }
                    } while ($p && $sp < $sl);
                }
                break;
                case 'e': {
                    // EDIFACT
                    $out = array_fill(0, 4, 0);
                    $p = 0;
                    if ($enc != $newenc) {
                        // can only be from C40/Text/X12
                        $t[$tp++] = 254;
                        $enc = 'a';
                    }
                    while ($sp < $sl && strtolower($e['encoding'][$sp]) == 'e' && $p < 4)
                        $out[$p++] = ord($s{$sp++});
                    if ($p < 4) {
                        $out[$p++] = 0x1F;
                        $enc = 'a';
                    }
                    // termination
                    $t[$tp] = (($s{0} & 0x3F) << 2);
                    $ttp = $tp++;
                    $t[$ttp] = $t[$ttp] | (($s{1} & 0x30) >> 4);
                    $t[$tp] = (($s{1} & 0x0F) << 4);
                    if ($p == 2)
                        $tp++;
                    else {
                        $ttp = $tp++;
                        $t[$ttp] = $t[$ttp] | (($s[2] & 0x3C) >> 2);
                        $t[$tp] = (($s{2} & 0x03) << 6);
                        $ttp = $tp++;
                        $t[$ttp] = $t[$ttp] | ($s{3} & 0x3F);
                    }
                }
                break;
                case 'a':
                    // ASCII
                    if ($enc != $newenc) {
                        if ($enc == 'c' || $enc == 't' || $enc == 'x')
                            // escape C40/text/X12
                            $t[$tp++] = 254;
                        else
                            // escape EDIFACT
                            $t[$tp++] = 0x7C;
                    }
                    $enc = 'a';
                    if ($sl - $sp >= 2 && $this->isDigit($s{$sp}) && $this->isDigit($s{$sp + 1})) {
                        $t[$tp++] = (ord($s{$sp}) - ord('0')) * 10 + ord($s{$sp + 1}) - ord('0') + 130;
                        $sp += 2;
                    } elseif (ord($s{$sp}) > 127) {
                        $t[$tp++] = 235;
                        $t[$tp++] = ord($s{$sp++}) - 127;
                    } else
                        $t[$tp++] = ord($s{$sp++}) + 1;
                    break;
                case 'b': {
                    // Binary
                    // how much to encode
                    $l = 0;
                    if ($encoding) {
                        for ($p = $sp; $p < $sl && strtolower($e['encoding'][$p]) == 'b'; $p++)
                            $l++;
                    }
                    // base256
                    $t[$tp++] = 231;
                    if ($l < 250)
                        $t[$tp++] = $l;
                    else {
                        $t[$tp++] = 249 + floor(l / 250);
                        $t[$tp++] = ($l % 250);
                    }
                    while ($l-- && $tp < $tl) {
                        // see annex H
                        $t[$tp] = ord($s{$sp++}) + ((($tp + 1) * 149) % 255) + 1;
                        $tp++;
                    }
                    // reverse to ASCII at end
                    $enc = 'a';
                }
                break;
                default:
                    die("Unknown encoding: " . $newenc);
                    // failed
                    return 0;
            }
        }
        if ($tp < $tl && $enc != 'a') {
            if ($enc == 'c' || $enc == 'x' || $enc == 't')
                // escape X12/C40/Text
                $t[$tp++] = 254;
            else
                // escape EDIFACT
                $t[$tp++] = 0x7C;
        }
        if ($tp < $tl)
            // $pad
            $t[$tp++] = 129;
        while ($tp < $tl) {
            // more $padding
            // see Annex H
            $v = 129 + ((($tp + 1) * 149) % 253) + 1;
            if ($v > 254)
                $v -= 254;
            $t[$tp++] = $v;
        }

        error_reporting($oldErrorReporting);

        if ($tp > $tl || $sp < $sl) // did not fit
            return 0;
        // OK
        return $tp;
    }
909623
function(s) {
      s = s.replace(/,/g, '\\,');
      s = escape(s);
      s = s.replace(/\+/g, '%2b');
      s = s.replace(/ /g, '+');
      return s;
    }