Escape a string to let it go in an LDAP filter

    :param ldap_string: The string to escape
    :return: The protected string
189798
def escape_LDAP(ldap_string):
    # type: (str) -> str
    # pylint: disable=C0103
    
    if not ldap_string:
        # No content
        return ldap_string

    # Protect escape character previously in the string
    assert is_string(ldap_string)
    ldap_string = ldap_string.replace(
        ESCAPE_CHARACTER, ESCAPE_CHARACTER + ESCAPE_CHARACTER
    )

    # Leading space
    if ldap_string.startswith(" "):
        ldap_string = "\\ {0}".format(ldap_string[1:])

    # Trailing space
    if ldap_string.endswith(" "):
        ldap_string = "{0}\\ ".format(ldap_string[:-1])

    # Escape other characters
    for escaped in ESCAPED_CHARACTERS:
        ldap_string = ldap_string.replace(escaped, ESCAPE_CHARACTER + escaped)

    return ldap_string
1217873
def _get_anon_bind(self):
        
        r = self._search(
            'cn=config',
            '(objectClass=*)',
            ['nsslapd-allow-anonymous-access'],
            scope=ldap.SCOPE_BASE
        )
        dn, attrs = r[0]
        state = attrs.get('nsslapd-allow-anonymous-access')[0].decode('utf-8', 'ignore')
        if state in ['on', 'off', 'rootdse']:
            r = state
        else:
            r = None
        self._anon_bind = r
1331254
protected final String escapeLDAPSearchFilter(String filter) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < filter.length(); i++) {
      char curChar = filter.charAt(i);
        switch (curChar) {
          case '\\':
            sb.append("\\5c");
            break;
          case '*':
            sb.append("\\2a");
            break;
          case '(':
            sb.append("\\28");
            break;
          case ')':
            sb.append("\\29");
            break;
          case '\u0000':
            sb.append("\\00");
            break;
          default:
            sb.append(curChar);
        }
    }
    return sb.toString();
  }
633360
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
        
        for k, v in dictionary.iteritems():
            if isinstance(v, datetime.datetime):
                v = v.strftime(datetime_format)

            if isinstance(v, basestring):
                v = CoyoteDb.db_escape(str(v))
                v = '"{}"'.format(v)

            if v is True:
                v = 1

            if v is False:
                v = 0

            if v is None:
                v = 'NULL'

            dictionary[k] = v
356892
public static function paranoid($string, $allowed = array())
	{
		$allow = null;
		if (!empty($allowed))
		{
			foreach ($allowed as $value)
			{
				$allow .= "\\$value";
			}
		}

		if (!is_array($string))
		{
			return preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
		}

		$cleaned = array();
		foreach ($string as $key => $clean)
		{
			$cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean);
		}

		return $cleaned;
	}
463785
private static function escape( $string )
	{
		$replace	= array(
			'\\'	=> '\\\\',
			'"'	=> '\"',
			'/'	=> '\/',
			"\b"	=> '\b',
			"\f"	=> '\f',
			"\n"	=> '\n',
			"\r"	=> '\r',
			"\t"	=> '\t',
			"\u"	=> '\u'
			);
		$string	= str_replace( array_keys( $replace ), array_values( $replace ), $string );
		return $string;
	}
671090
def escape(self, string):
        
        html_entities = {"&": "&amp;", '<': '&lt;', '>': '&gt;'}
        return HTML("".join(html_entities.get(c, c) for c in string))
1194475
def escape_string(self, value):
        
        if isinstance(value, EscapedString):
            return value.formatted(self._escaper)
        return self._escaper(value)
602585
def escape(string)
      return "" unless string
      str = string.b
      str.gsub!(/&/n, '&amp;')
      str.gsub!(/\"/n, '&quot;')
      str.gsub!(/>/n, '&gt;')
      str.gsub!(/</n, '&lt;')
      str.force_encoding(string.encoding)
    end
881184
private static String unescape(String string) {
    return StringUtils.unEscapeString(string, StringUtils.ESCAPE_CHAR, 
                                      charsToEscape);
  }
708457
def escape_string(self, string):
        """"""
        if self.quote:
            quote = self.quote
        else:
            found = QUOTE_REGEX.search(string)
            quote = STRING_QUOTES[found.group()] if found else next(iter(STRING_QUOTES))

        for match, seq in ESCAPE_SUBS.items():
            if match == quote or match not in STRING_QUOTES:
                string = string.replace(match, seq)

        return f'{quote}{string}{quote}'
267136
@Trivial
    private String getString(boolean isOctet, Object ldapValue) {
        if (isOctet) {
            return LdapHelper.getOctetString((byte[]) ldapValue);
        } else {
            return ldapValue.toString();
        }
    }
645394
def sqlalchemy_escape(val, escape_char, special_chars):
    
    if sys.version_info[:2] >= (3, 0):
        assert isinstance(val, str)
    else:
        assert isinstance(val, basestring)
    result = []
    for c in val:
        if c in special_chars + escape_char:
            result.extend(escape_char + c)
        else:
            result.extend(c)
    return ''.join(result)
493614
def p_encaps_list_string(p):
    ''
    if p[1] == '':
        p[0] = p[2].decode('string_escape')
    else:
        p[0] = ast.BinaryOp('.', p[1], p[2].decode('string_escape'),
                            lineno=p.lineno(2))
183597
def escape(str):
    """"""
    out = ''
    for char in str:
        if char in '\\ ':
            out += '\\'
        out += char
    return out
506643
function ldap_slashes($str){
        $illegal=array("(",")","#"); // the + character has problems too, but it's an illegal character
        
        $legal=array();
        foreach ($illegal as $id => $char){ $legal[$id]="\\".$char; } //make up the array of legal chars
        
        $str=str_replace($illegal,$legal,$str); //replace them
        return ($str);
    }
1041140
def escape(self, varname, value):
        
        f = self.escape_funcs.get(varname)
        return f(value) if f else value