Extract LDAP exception message
519241
def _get_ldap_msg(e):
        """"""
        msg = e
        if hasattr(e, 'message'):
            msg = e.message
            if 'desc' in e.message:
                msg = e.message['desc']
            elif hasattr(e, 'args'):
                msg = e.args[0]['desc']
        return msg
1309696
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) {
    StringBuilder builder = new StringBuilder();
    String permissionName = exceptionInfo.getViolatedPermissionName();
    String resourceType = exceptionInfo.getResourceType();
    String resourceId = exceptionInfo.getResourceId();
    builder.append("'");
    builder.append(permissionName);
    builder.append("' permission on resource '");
    builder.append((resourceId != null ? (resourceId+"' of type '") : "" ));
    builder.append(resourceType);
    builder.append("'");

    return builder.toString();
  }
278493
function ldapAssociateDrupalAccount($drupal_username) {

    if ($this->drupalAcctProvisionServer) {
      $prov_events = array(LDAP_USER_EVENT_LDAP_ASSOCIATE_DRUPAL_ACCT);
      $ldap_server = ldap_servers_get_servers($this->drupalAcctProvisionServer, 'enabled', TRUE);  // $ldap_user['sid']
      $account = user_load_by_name($drupal_username);
      $ldap_user = ldap_servers_get_user_ldap_data($drupal_username, $this->drupalAcctProvisionServer, 'ldap_user_prov_to_drupal');
      if (!$account) {
        watchdog(
          'ldap_user',
          'Failed to LDAP associate drupal account %drupal_username because account not found',
          array('%drupal_username' => $drupal_username),
          WATCHDOG_ERROR
        );
        return FALSE;
      }
      elseif (!$ldap_user) {
        watchdog(
          'ldap_user',
          'Failed to LDAP associate drupal account %drupal_username because corresponding LDAP entry not found',
          array('%drupal_username' => $drupal_username),
          WATCHDOG_ERROR
        );
        return FALSE;
      }
      else {
        $user_edit = array();
        $user_edit['data']['ldap_user']['init'] = array(
          'sid'  => $ldap_user['sid'],
          'dn'   => $ldap_user['dn'],
          'mail'   => $account->mail,
        );
        $ldap_user_puid = $ldap_server->userPuidFromLdapEntry($ldap_user['attr']);
        if ($ldap_user_puid) {
          $user_edit['ldap_user_puid'][LANGUAGE_NONE][0]['value'] = $ldap_user_puid; //
        }
        $user_edit['ldap_user_puid_property'][LANGUAGE_NONE][0]['value'] = $ldap_server->unique_persistent_attr;
        $user_edit['ldap_user_puid_sid'][LANGUAGE_NONE][0]['value'] = $ldap_server->sid;
        $user_edit['ldap_user_current_dn'][LANGUAGE_NONE][0]['value'] = $ldap_user['dn'];
        $account = user_save($account, $user_edit, 'ldap_user');
        return (boolean)$account;
      }
    }
    else {
      return FALSE;
    }
  }
1122411
private String getBinaryAttributes() {

        // Add binary settings for all octet string attributes.
        StringBuffer binaryAttrNamesBuffer = new StringBuffer();

        // Check the ldap data type of the extId attribute.
        Map<String, LdapAttribute> attrMap = iLdapConfigMgr.getAttributes();

        for (String attrName : attrMap.keySet()) {
            LdapAttribute attr = attrMap.get(attrName);
            if (LdapConstants.LDAP_ATTR_SYNTAX_OCTETSTRING.equalsIgnoreCase(attr.getSyntax())) {
                binaryAttrNamesBuffer.append(attr.getName()).append(" ");
            }
        }

        return binaryAttrNamesBuffer.toString().trim();
    }
287646
public static LdapException create(LdapResultCode resultCode, String message) {
        return new LdapException(resultCode, message, null);
    }
550411
def parse_error(output_dir):
    
    sys.stderr.seek(0)
    std_err = sys.stderr.read().decode('utf-8')
    err_file = os.path.join(output_dir, "eplusout.err")
    if os.path.isfile(err_file):
        with open(err_file, "r") as f:
            ep_err = f.read()
    else:
        ep_err = "<File not found>"
    message = "\r\n{std_err}\r\nContents of EnergyPlus error file at {err_file}\r\n{ep_err}".format(**locals())
    return message
755269
def from_exception(exc, uuid=None):
        
        if not isinstance(exc, Error):
            exc = Error(code=500, message=str(exc))

        return Result(
            uuid=exc.extra.get("uuid", uuid or random_uuid()),
            retcode=exc.code, stderr=exc.message,
            retval=dict(error=ErrorSchema().dump(exc))
        )
219385
def get_members(self):
        """"""
        res = self.__con__.search_s(
                self.__ldap_base_dn__,
                ldap.SCOPE_SUBTREE,
                "(memberof=%s)" % self.__dn__,
                ['uid'])

        ret = []
        for val in res:
            val = val[1]['uid'][0]
            try:
                ret.append(val.decode('utf-8'))
            except UnicodeDecodeError:
                ret.append(val)
            except KeyError:
                continue

        return [CSHMember(self.__lib__,
                result,
                uid=True)
                for result in ret]
1051342
public static LdapException create(ResultCode resultCode, String message) {
        return new LdapException(DefaultLdapResultCodeFactory.convertResultCode(resultCode), message, null);
    }
1138980
def _parse_ldap_criteria(ldap_filter, startidx=0, endidx=-1):
    # type: (str, int, int) -> LDAPCriteria
    
    comparators = "=<>~"
    if startidx < 0:
        raise ValueError(
            "Invalid string range start={0}, end={1}".format(startidx, endidx)
        )

    # Get the comparator
    escaped = False
    idx = startidx
    for char in ldap_filter[startidx:endidx]:
        if not escaped:
            if char == ESCAPE_CHARACTER:
                # Next character escaped
                escaped = True
            elif char in comparators:
                # Comparator found
                break
        else:
            # Escaped character ignored
            escaped = False
        idx += 1
    else:
        # Comparator never found
        raise ValueError(
            "Comparator not found in '{0}'".format(ldap_filter[startidx:endidx])
        )

    # The attribute name can be extracted directly
    attribute_name = ldap_filter[startidx:idx].strip()
    if not attribute_name:
        # Attribute name is missing
        raise ValueError(
            "Attribute name is missing in '{0}'".format(
                ldap_filter[startidx:endidx]
            )
        )

    comparator = _compute_comparator(ldap_filter, idx)
    if comparator is None:
        # Unknown comparator
        raise ValueError(
            "Unknown comparator in '{0}' - {1}\nFilter : {2}".format(
                ldap_filter[startidx:endidx], ldap_filter[idx], ldap_filter
            )
        )

    # Find the end of the comparator
    while ldap_filter[idx] in comparators:
        idx += 1

    # Skip spaces
    idx = _skip_spaces(ldap_filter, idx)

    # Extract the value
    value = ldap_filter[idx:endidx].strip()

    # Use the appropriate comparator if a joker is found in the filter value
    if value == "*":
        # Presence comparator
        comparator = _comparator_presence
    elif "*" in value:
        # Joker
        if comparator == _comparator_eq:
            comparator = _comparator_star
        elif comparator == _comparator_approximate:
            comparator = _comparator_approximate_star

    return LDAPCriteria(
        unescape_LDAP(attribute_name), unescape_LDAP(value), comparator
    )
1336563
function ErrorMsg()
	{
		if (!$this->_connectionID) return "No connection established";
		$errmsg = '';

		try {
			$errc = $this->_connectionID->Errors;
			if (!$errc) return "No Errors object found";
			if ($errc->Count == 0) return '';
			$err = $errc->Item($errc->Count-1);
			$errmsg = $err->Description;
		}catch(exception $e) {
		}
		return $errmsg;
	}
706437
def get(method, hmc, uri, uri_parms, logon_required):
        """"""
        query_str = uri_parms[0]
        try:
            console = hmc.consoles.lookup_by_oid(None)
        except KeyError:
            raise InvalidResourceError(method, uri)
        result_ldap_srv_defs = []
        filter_args = parse_query_parms(method, uri, query_str)
        for ldap_srv_def in console.ldap_server_definitions.list(filter_args):
            result_ldap_srv_def = {}
            for prop in ldap_srv_def.properties:
                if prop in ('element-uri', 'name', 'type'):
                    result_ldap_srv_def[prop] = ldap_srv_def.properties[prop]
            result_ldap_srv_defs.append(result_ldap_srv_def)
        return {'ldap-server-definitions': result_ldap_srv_defs}
1117639
def _get_user(self, username, attrs=ALL_ATTRS):
        """"""

        username = ldap.filter.escape_filter_chars(username)
        user_filter = self.user_filter_tmpl % {
            'username': self._uni(username)
        }
        r = self._search(self._byte_p2(user_filter), attrs, self.userdn)

        if len(r) == 0:
            return None

        # if NO_ATTR, only return the DN
        if attrs == NO_ATTR:
            dn_entry = r[0][0]
        # in other cases, return everything (dn + attributes)
        else:
            dn_entry = r[0]
        return dn_entry
574605
def _config(name, key=None, **kwargs):
    '''
    
    '''
    if key is None:
        key = name
    if name in kwargs:
        value = kwargs[name]
    else:
        value = __salt__['config.option']('ldap.{0}'.format(key))
    return salt.utils.data.decode(value, to_str=True)
1351459
def datetime_from_ldap(value):
    
    if not value:
        return None
    match = LDAP_DATETIME_RE.match(value)
    if not match:
        return None
    groups = match.groupdict()
    if groups['microsecond']:
        groups['microsecond'] = groups['microsecond'].ljust(6, '0')[:6]
    tzinfo = groups.pop('tzinfo')
    if tzinfo == 'Z':
        tzinfo = timezone.utc
    else:
        offset_mins = int(tzinfo[-2:]) if len(tzinfo) == 5 else 0
        offset = 60 * int(tzinfo[1:3]) + offset_mins
        if tzinfo[0] == '-':
            offset = - offset
        tzinfo = timezone.get_fixed_timezone(offset)
    kwargs = {k: int(v) for k, v in groups.items() if v is not None}
    kwargs['tzinfo'] = tzinfo
    return datetime.datetime(**kwargs)
362438
def get(self, ldap_dn):
        '''
        '''
        self.base_dn = ldap_dn
        self.sub_tree = BASE
        return self.first()
101764
def method_missing(method, *args, &block)
      attribute = Ldaptic.encode(method)
      if attribute[-1] == ?=
        attribute.chop!
        if may_must(attribute)
          return write_attribute(attribute, *args, &block)
        end
      elsif attribute[-1] == ??
        attribute.chop!
        if may_must(attribute)
          if args.empty?
            return !read_attribute(attribute).empty?
          else
            return args.flatten.any? {|arg| compare(attribute, arg)}
          end
        end
      elsif attribute =~ /\A(.*)-before-type-cast\z/ && may_must($1)
        return read_attribute($1, *args, &block)
      elsif may_must(attribute)
        return read_attribute(attribute, *args, &block).one
      end
      super(method, *args, &block)
    end