Try to guess format of given bytestring.

    Args:
        inp: byte string to guess format of
    Returns:
        guessed format
196671
def _guess_fmt_from_bytes(inp):
    
    stripped = inp.strip()
    fmt = None
    ini_section_header_re = re.compile(b'^\[([\w-]+)\]')

    if len(stripped) == 0:
        # this can be anything, so choose yaml, for example
        fmt = 'yaml'
    else:
        if stripped.startswith(b'<'):
            fmt = 'xml'
        else:
            for l in stripped.splitlines():
                line = l.strip()
                # there are C-style comments in json5, but we don't auto-detect it,
                #  so it doesn't matter here
                if not line.startswith(b'#') and line:
                    break
            # json, ini or yaml => skip comments and then determine type
            if ini_section_header_re.match(line):
                fmt = 'ini'
            else:
                # we assume that yaml is superset of json
                # TODO: how do we figure out it's not yaml?
                fmt = 'yaml'

    return fmt
1166048
def guess_format(path):
    """"""
    for fmt in formats:
        if fmt.verify(path):
            return fmt.__name__
    else:
        msg = "Undefined file format: '{}'".format(path)
        raise UnknownFileFormatError(msg)
783933
def consult(string_in):
    
    # pylint: disable=eval-used
    # pylint: disable=too-many-branches
    # pylint: disable=too-many-statements

    # manually parse textual erlang data to avoid external dependencies
    list_out = []
    tuple_binary = False   # binaries become tuples of integers
    quoted_string = False  # strings become python string
    atom_string = False    # atoms become python string
    number = False
    whitespace = frozenset(('\n', '\t', ' '))
    i = 0
    while i < len(string_in):
        character = string_in[i]
        if character == ',':
            if atom_string:
                list_out.append('"')
                atom_string = False
            list_out.append(',')
            number = string_in[i + 1].isdigit()
        elif character == '{':
            list_out.append('(')
            number = string_in[i + 1].isdigit()
        elif character == '}':
            if atom_string:
                list_out.append('"')
                atom_string = False
            list_out.append(')')
            number = False
        elif character == '[':
            list_out.append('[')
            number = string_in[i + 1].isdigit()
        elif character == ']':
            if atom_string:
                list_out.append('"')
                atom_string = False
            list_out.append(']')
            number = False
        elif character == '<' and string_in[i + 1] == '<':
            list_out.append('(')
            tuple_binary = True
            i += 1
        elif character == '>' and string_in[i + 1] == '>':
            list_out.append(')')
            tuple_binary = False
            i += 1
        elif not quoted_string and not atom_string and character in whitespace:
            number = string_in[i + 1].isdigit()
        elif tuple_binary or number:
            list_out.append(character)
        elif character == '"':
            if quoted_string:
                quoted_string = False
            else:
                quoted_string = True
            list_out.append('"')
        elif character == "'":
            if atom_string:
                atom_string = False
            else:
                atom_string = True
            list_out.append('"')
        elif not quoted_string and not atom_string:
            atom_string = True
            list_out.append('"')
            list_out.append(character)
        else:
            list_out.append(character)
        i += 1
    return eval(''.join(list_out))
961459
def bytes2str_in_dicts(inp  # type: Union[MutableMapping[Text, Any], MutableSequence[Any], Any]
                      ):
    # type: (...) -> Union[Text, MutableSequence[Any], MutableMapping[Text, Any]]
    

    # if input is dict, recursively call for each value
    if isinstance(inp, MutableMapping):
        for k in inp:
            inp[k] = bytes2str_in_dicts(inp[k])
        return inp

    # if list, iterate through list and fn call
    # for all its elements
    if isinstance(inp, MutableSequence):
        for idx, value in enumerate(inp):
            inp[idx] = bytes2str_in_dicts(value)
            return inp

    # if value is bytes, return decoded string,
    elif isinstance(inp, bytes):
        return inp.decode('utf-8')

    # simply return elements itself
    return inp
879232
def _format_regular_value(self, str_in):
        # type: (Text) -> Text
        
        try:
            dt = datetime.strptime(str_in, self.format)
            return strftime(dt, DateSpec.OUTPUT_FORMAT)
        except ValueError as e:
            msg = "Unable to format date value '{}'. Reason: {}".format(str_in,
                                                                        e)
            e_new = InvalidEntryError(msg)
            e_new.field_spec = self
            raise_from(e_new, e)
843552
def bytes_from_string(value):
    
    BYTE_POWER = {
        'K': 1,
        'KB': 1,
        'M': 2,
        'MB': 2,
        'G': 3,
        'GB': 3,
        'T': 4,
        'TB': 4,
        'P': 5,
        'PB': 5,
    }
    if isinstance(value, six.string_types):
        value = six.text_type(value)
    else:
        msg = "Unable to interpret non-string value '%s' as bytes" % (value)
        raise ValueError(msg)
    matches = re.match("([0-9]+)([a-zA-Z]+)", value)
    if matches:
        size = int(matches.group(1)) * (1024 ** BYTE_POWER[matches.group(2)])
    else:
        # Assume that value passed in is bytes
        try:
            size = int(value)
        except ValueError:
            msg = "Unable to interpret string value '%s' as bytes" % (value)
            raise ValueError(msg)
    return size
197218
private String guessImageFormat(String contentType, String imagePath) throws IOException {

        String format = "png";

        if (contentType == null) {
            contentType = URLConnection.guessContentTypeFromName(imagePath);
        }

        if (contentType != null) {
            format = contentType.replaceFirst("^image/([^;]+)[;]?.*$", "$1");
        }
        else {
            int queryStringIndex = imagePath.indexOf('?');

            if (queryStringIndex != -1) {
                imagePath = imagePath.substring(0, queryStringIndex);
            }

            String[] pathTokens = imagePath.split("\\.");

            if (pathTokens.length > 1) {
                format = pathTokens[pathTokens.length - 1];
            }
        }

        return format;
    }
269043
def _input_optional(inp):
        
        if 'default' in inp.keys():
            return True

        typ = inp.get('type')
        if isinstance(typ, six.string_types):
            return typ.endswith('?')
        elif isinstance(typ, dict):
            # TODO: handle case where iput type is dict
            return False
        elif isinstance(typ, list):
            # The cwltool validation expands optional arguments to
            # [u'null', <type>]
            return bool(u'null' in typ)
        else:
            raise ValueError('Invalid input "{}"'.format(inp.get['id']))
591269
def guess_format(url):
    """"""
    import requests
    from requests.exceptions import InvalidSchema
    from rowgenerators import parse_url_to_dict

    parts = parse_url_to_dict(url)

    # Guess_type fails for root urls like 'http://civicknowledge.com'
    if parts.get('path'):
        type, encoding = mimetypes.guess_type(url)
    elif parts['scheme'] in ('http', 'https'):
        type, encoding = 'text/html', None  # Assume it is a root url
    else:
        type, encoding = None, None

    if type is None:
        try:
            r = requests.head(url, allow_redirects=False)
            type = r.headers['Content-Type']

            if ';' in type:
                type, encoding = [e.strip() for e in type.split(';')]

        except InvalidSchema:
            pass  # It's probably FTP

    return type, mime_map.get(type)
396870
def consume_input(self, inp):
        
        cur_state = sorted(
            self.states,
            key=attrgetter('initial'),
            reverse=True)[0]
        while len(inp) > 0:
            found = False
            for arc in cur_state.arcs:
                if self.isyms.find(arc.ilabel) == inp[0]:
                    cur_state = self[arc.nextstate]
                    inp = inp[1:]
                    found = True
                    break
            if not found:
                return False
        return cur_state.final != TropicalWeight(float('inf'))
123859
def guess_series(input_string):
    
    """
    float_finder = re.compile("([-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?)")
    return ([
        i for i in [
            _convert_to_float(j) for j in float_finder.findall(input_string)
        # Remove entires we couldn't convert to a sensible value.
        ] if i is not None and not math.isnan(i) and not math.isinf(i)
    ])
1245204
def guess(cls, *strings, **kwargs):
        '''
        
        '''
        license = None
        for string in strings:
            license = cls.guess_one(string)
            if license:
                break
        return license or kwargs.get('default')
313396
def make_compat_str(in_str):
    
    assert isinstance(in_str, (bytes, str, unicode))
    if not in_str:
        return unicode()

    # Chardet in Py2 works on str + bytes objects
    if IS_PY2 and isinstance(in_str, unicode):
        return in_str

    # Chardet in Py3 works on bytes objects
    if not IS_PY2 and not isinstance(in_str, bytes):
        return in_str

    # Detect the encoding now
    enc = chardet.detect(in_str)

    # Decode the object into a unicode object
    out_str = in_str.decode(enc['encoding'])

    # Cleanup: Sometimes UTF-16 strings include the BOM
    if enc['encoding'] == "UTF-16BE":
        # Remove byte order marks (BOM)
        if out_str.startswith('\ufeff'):
            out_str = out_str[1:]

    # Return the decoded string
    return out_str
794870
def _decode(value):
        
        if value.isdigit():
            return int(value)
        if isinstance(value, bytes):
            return value.decode('utf-8')
        else:
            return value
1229715
def decode_bytes(string):
    

    if is_string_type(type(string)):
        string = bytes(string, "utf-8")
    return base64.decodebytes(string)
829668
def quick_detect_encoding(string):
    
    assert isinstance(string, bytes)
    try:
        detected = cchardet.detect(string)
        if detected:
            return detected.get('encoding') or detect_encoding(string)
    except Exception as e:
        pass
    return detect_encoding(string)
412245
def _str(val):
    
    if str == bytes:
        if isinstance(val, str):
            return val
        else:
            return str(val)
    else:
        if isinstance(val, str):
            return val
        else:
            return str(val, 'ascii')