Unquote and fix hostname. Returns is_idn.
4598
def url_fix_host (urlparts):
    """"""
    if not urlparts[1]:
        urlparts[2] = urllib.unquote(urlparts[2])
        return False
    userpass, netloc = urllib.splituser(urlparts[1])
    if userpass:
        userpass = urllib.unquote(userpass)
    netloc, is_idn = idna_encode(urllib.unquote(netloc).lower())
    # a leading backslash in path causes urlsplit() to add the
    # path components up to the first slash to host
    # try to find this case...
    i = netloc.find("\\")
    if i != -1:
        # ...and fix it by prepending the misplaced components to the path
        comps = netloc[i:] # note: still has leading backslash
        if not urlparts[2] or urlparts[2] == '/':
            urlparts[2] = comps
        else:
            urlparts[2] = "%s%s" % (comps, urllib.unquote(urlparts[2]))
        netloc = netloc[:i]
    else:
        # a leading ? in path causes urlsplit() to add the query to the
        # host name
        i = netloc.find("?")
        if i != -1:
            netloc, urlparts[3] = netloc.split('?', 1)
        # path
        urlparts[2] = urllib.unquote(urlparts[2])
    if userpass:
        # append AT for easy concatenation
        userpass += "@"
    else:
        userpass = ""
    if urlparts[0] in default_ports:
        dport = default_ports[urlparts[0]]
        host, port = splitport(netloc, port=dport)
        if host.endswith("."):
            host = host[:-1]
        if port != dport:
            host = "%s:%d" % (host, port)
        netloc = host
    urlparts[1] = userpass+netloc
    return is_idn
703928
def quote(self, identifier, errors="strict"):
        
        if identifier is None:
            return None

        encodable = identifier.encode("utf-8", errors).decode("utf-8")

        nul_index = encodable.find("\x00")

        if nul_index >= 0:
            error = UnicodeEncodeError(
                "NUL-terminated utf-8",
                encodable,
                nul_index,
                nul_index + 1,
                "NUL not allowed"
            )
            error_handler = codecs.lookup_error(errors)
            replacement, _ = error_handler(error)
            encodable = encodable.replace("\x00", replacement)

        return "\"" + encodable.replace("\"", "\"\"") + "\""
220789
def cmd_extract_hostname(infile, check, verbose, jsonout):
    

    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')

    data = infile.read()

    result = extract_hostname(data)

    if check:
        logging.info('Checking against DNS...')
        for candidate in result:
            try:
                socket.getaddrinfo(candidate, None)
            except socket.gaierror:
                result.remove(candidate)

    if jsonout:
        print(json.dumps(result, indent=4))
    else:
        print('\n'.join(result))
573672
def unquote(value):
    
    if len(value) > 1 and value[0] == '"' and value[-1] == '"':
        value = value[1:-1].replace(r'\"', '"')
    return value
888871
@Override
    public String getHostnameForHostID(int hostId) {
        if (hostId == m_localHostId) {
            return CoreUtils.getHostnameOrAddress();
        }
        Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator();
        if (it.hasNext()) {
            ForeignHost fh = it.next();
            return fh.hostname();
        }
        return m_knownFailedHosts.get(hostId) != null ? m_knownFailedHosts.get(hostId) :
                "UNKNOWN";
    }
1156537
def hosting_devices_unassigned_from_cfg_agent(self, context, ids, host):
        
        self._host_notification(context,
                                'hosting_devices_unassigned_from_cfg_agent',
                                {'hosting_device_ids': ids}, host)
1281249
def is_valid_hostname(hostname):
    ''''''
    if not isinstance(hostname, str):
        raise TypeError('hostname must be a string')
    # strip exactly one dot from the right, if present
    if hostname and hostname[-1] == ".":
        hostname = hostname[:-1]
    if not hostname or len(hostname) > 253:
        return False
    labels = hostname.split('.')
    # the TLD must be not all-numeric
    if re.match(NUMERIC_REGEX, labels[-1]):
        return False
    return all(LABEL_REGEX.match(label) for label in labels)
235777
def patch_match_hostname():
    """"""


    _old_match_hostname = ssl.match_hostname

    def _new_match_hostname(cert, hostname):
        if hostname.endswith('.s3.amazonaws.com'):
            pos = hostname.find('.s3.amazonaws.com')
            hostname = hostname[:pos].replace('.', '') + hostname[pos:]
        return _old_match_hostname(cert, hostname)

    ssl.match_hostname = _new_match_hostname
203639
def _resolve_hostname(name):
    """"""
    if env.ssh_config is None:
        return name
    elif not os.path.exists(os.path.join("nodes", name + ".json")):
        resolved_name = env.ssh_config.lookup(name)['hostname']
        if os.path.exists(os.path.join("nodes", resolved_name + ".json")):
            name = resolved_name
    return name
347868
def fix_reference_name(name, blacklist=None):
    """"""
    name = "".join(re.split(r'[^0-9a-zA-Z_]', name))
    while name and not re.match(r'([a-zA-Z]+[0-9a-zA-Z_]*)$', name):
        if not re.match(r'[a-zA-Z]', name[0]):
            name = name[1:]
            continue
    name = str(name)
    if not name:
        name = "data"
    if blacklist is not None and name in blacklist:
        get_new_name = lambda index: name+('%03d' % index)
        index = 0
        while get_new_name(index) in blacklist:
            index += 1
        name = get_new_name(index)
    return name
1189078
def identify_id(id: str) -> bool:
    
    return re.match(r'^https?://', id, flags=re.IGNORECASE) is not None
154505
def _hostname_matches(self, hostname, entry):
        
        for h in entry.hostnames:
            if (
                h == hostname
                or h.startswith("|1|")
                and not hostname.startswith("|1|")
                and constant_time_bytes_eq(self.hash_host(hostname, h), h)
            ):
                return True
        return False
1319124
function parseDistinguishedName(dn) {
  log.trace('parseDistinguishedName(%s)', dn);
  if (! dn) return(dn);

  dn = dn.replace(/"/g, '\\"');
  return(dn.replace('\\,', '\\\\,'));
}
153562
def is_fqdn(hostname):
    

    compliant = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE)
    return "." in hostname and len(hostname) < 0xff and all(compliant.match(x) for x in hostname.rstrip(".").split("."))
412578
def cli(env, identifier):
    

    dh_mgr = SoftLayer.DedicatedHostManager(env.client)

    host_id = helpers.resolve_id(dh_mgr.resolve_ids, identifier, 'dedicated host')

    if not (env.skip_confirmations or formatting.no_going_back(host_id)):
        raise exceptions.CLIAbort('Aborted')

    table = formatting.Table(['id', 'server name', 'status'])

    result = dh_mgr.cancel_guests(host_id)

    if result:
        for status in result:
            table.add_row([
                status['id'],
                status['fqdn'],
                status['status']
            ])

        env.fout(table)
    else:
        click.secho('There is not any guest into the dedicated host %s' % host_id, fg='red')
155422
def host_name=(newname)
      return if newname == host_name
      raise JSS::InvalidDataError, 'names must be String' unless name.is_a? String
      @host_name = name
      @need_to_update = true
    end
42388
def host(self):
        
        raw = self.raw_host
        if raw is None:
            return None
        if "%" in raw:
            # Hack for scoped IPv6 addresses like
            # fe80::2%Проверка
            # presence of '%' sign means only IPv6 address, so idna is useless.
            return raw

        try:
            return idna.decode(raw.encode("ascii"))
        except UnicodeError:  # e.g. '::1'
            return raw.encode("ascii").decode("idna")