Generate a docstring of numpy type.
182709
def _generate_numpy_doc(self, func_info):
        """"""
        numpy_doc = ''

        arg_names = func_info.arg_name_list
        arg_types = func_info.arg_type_list
        arg_values = func_info.arg_value_list

        if len(arg_names) > 0 and arg_names[0] == 'self':
            del arg_names[0]
            del arg_types[0]
            del arg_values[0]

        indent1 = func_info.func_indent + self.code_editor.indent_chars
        indent2 = func_info.func_indent + self.code_editor.indent_chars * 2

        numpy_doc += '\n{}\n'.format(indent1)

        if len(arg_names) > 0:
            numpy_doc += '\n{}Parameters'.format(indent1)
            numpy_doc += '\n{}----------\n'.format(indent1)

        arg_text = ''
        for arg_name, arg_type, arg_value in zip(arg_names, arg_types,
                                                 arg_values):
            arg_text += '{}{} : '.format(indent1, arg_name)
            if arg_type:
                arg_text += '{}'.format(arg_type)
            else:
                arg_text += 'TYPE'

            if arg_value:
                arg_text += ', optional'

            arg_text += '\n{}DESCRIPTION.'.format(indent2)

            if arg_value:
                arg_value = arg_value.replace(self.quote3, self.quote3_other)
                arg_text += ' The default is {}.'.format(arg_value)

            arg_text += '\n'

        numpy_doc += arg_text

        if func_info.raise_list:
            numpy_doc += '\n{}Raises'.format(indent1)
            numpy_doc += '\n{}------'.format(indent1)
            for raise_type in func_info.raise_list:
                numpy_doc += '\n{}{}'.format(indent1, raise_type)
                numpy_doc += '\n{}DESCRIPTION.'.format(indent2)
            numpy_doc += '\n'

        numpy_doc += '\n'
        if func_info.has_yield:
            header = '{0}Yields\n{0}------\n'.format(indent1)
        else:
            header = '{0}Returns\n{0}-------\n'.format(indent1)

        return_type_annotated = func_info.return_type_annotated
        if return_type_annotated:
            return_section = '{}{}{}'.format(header, indent1,
                                             return_type_annotated)
            return_section += '\n{}DESCRIPTION.'.format(indent2)
        else:
            return_element_type = indent1 + '{return_type}\n' + indent2 + \
                'DESCRIPTION.'
            placeholder = return_element_type.format(return_type='TYPE')
            return_element_name = indent1 + '{return_name} : ' + \
                placeholder.lstrip()

            try:
                return_section = self._generate_docstring_return_section(
                    func_info.return_value_in_body, header,
                    return_element_name, return_element_type, placeholder,
                    indent1)
            except (ValueError, IndexError):
                return_section = '{}{}None.'.format(header, indent1)

        numpy_doc += return_section
        numpy_doc += '\n\n{}{}'.format(indent1, self.quote3)

        return numpy_doc
427843
def format_doc(fun):
    """"""
    SEPARATOR = '============================='
    func = cvloop.functions.__dict__[fun]

    doc_lines = ['{}'.format(l).strip() for l in func.__doc__.split('\n')]
    if hasattr(func, '__init__'):
        doc_lines.append(SEPARATOR)
        doc_lines += ['{}'.format(l).strip() for l in
                      func.__init__.__doc__.split('\n')]

    mod_lines = []
    argblock = False
    returnblock = False
    for line in doc_lines:
        if line == SEPARATOR:
            mod_lines.append('\n#### `{}.__init__(...)`:\n\n'.format(fun))
        elif 'Args:' in line:
            argblock = True
            if GENERATE_ARGS:
                mod_lines.append('**{}**\n'.format(line))
        elif 'Returns:' in line:
            returnblock = True
            mod_lines.append('\n**{}**'.format(line))
        elif not argblock and not returnblock:
            mod_lines.append('{}\n'.format(line))
        elif argblock and not returnblock and ':' in line:
            if GENERATE_ARGS:
                mod_lines.append('- *{}:* {}\n'.format(
                    *line.split(':')))
        elif returnblock:
            mod_lines.append(line)
        else:
            mod_lines.append('{}\n'.format(line))
    return mod_lines
1124632
def _int_doc(cls):
    """"""
    def __init__(self, value=None, **kwargs):
        if value is not None:
            kwargs['value'] = value
        super(cls, self).__init__(**kwargs)

    __init__.__doc__ = _int_doc_t
    cls.__init__ = __init__
    return cls
1224065
def doctype (self, data):
        
        data = data.encode(self.encoding, "ignore")
        self.fd.write("<!DOCTYPE%s>" % data)
140645
def generate_docs(self, clspath, more_content):
        """"""
        obj = import_class(clspath)
        sourcename = 'docstring of %s' % clspath
        all_options = []
        indent = '    '
        config = obj.get_required_config()

        if config.options:
            # Go through options and figure out relevant information
            for option in config:
                if 'namespace' in self.options:
                    namespaced_key = self.options['namespace'] + '_' + option.key
                else:
                    namespaced_key = option.key

                if 'case' in self.options:
                    if self.options['case'] == 'upper':
                        namespaced_key = namespaced_key.upper()
                    elif self.options['case'] == 'lower':
                        namespaced_key = namespaced_key.lower()

                all_options.append({
                    'key': namespaced_key,
                    'parser': qualname(option.parser),
                    'doc': option.doc,
                    'default': option.default,
                })

        if 'hide-classname' not in self.options:
            modname, clsname = split_clspath(clspath)
            component_name = clspath
            component_index = clsname
        else:
            component_name = 'Configuration'
            component_index = 'Configuration'

        if all_options:
            # Add index entries for options first so they link to the right
            # place; we do it this way so that we don't have to make options a
            # real object type and then we don't get to use TypedField
            # formatting
            self.add_line('.. index::', sourcename)
            for option in all_options:
                self.add_line('   single: %s; (%s)' % (option['key'], component_index), sourcename)
            self.add_line('', '')

        # Add the classname or 'Configuration'
        self.add_line('.. everett:component:: %s' % component_name, sourcename)
        self.add_line('', sourcename)

        # Add the docstring if there is one and if show-docstring
        if 'show-docstring' in self.options:
            docstring_attr = self.options['show-docstring'] or '__doc__'
            docstring = getattr(obj, docstring_attr, None)
            if docstring:
                docstringlines = prepare_docstring(docstring, ignore=1)
                for i, line in enumerate(docstringlines):
                    self.add_line(indent + line, sourcename, i)
                self.add_line('', '')

        # Add content from the directive if there was any
        if more_content:
            for line, src in zip(more_content.data, more_content.items):
                self.add_line(indent + line, src[0], src[1])
            self.add_line('', '')

        if all_options:
            # Now list the options
            sourcename = 'class definition'

            for option in all_options:
                self.add_line(
                    '%s:option %s %s:' % (indent, option['parser'], option['key']),
                    sourcename
                )
                self.add_line('%s    %s' % (indent, option['doc']), sourcename)
                if option['default'] is not NO_VALUE:
                    self.add_line('', '')
                    self.add_line(
                        '%s    Defaults to ``%r``.' % (indent, option['default']),
                        sourcename
                    )
                self.add_line('', '')
437991
def get_type_string(item):
    """"""
    if isinstance(item, DataFrame):
        return "DataFrame"
    if isinstance(item, Index):
        return type(item).__name__
    if isinstance(item, Series):
        return "Series"
    found = re.findall(r"<(?:type|class) '(\S*)'>",
                       to_text_string(type(item)))
    if found:
        return found[0]
586527
def _prepare_docstrings():
    """"""
    if config.USEAUTODOC:
        source = inspect.getsource(Options)
        docstrings = source.split('"""')[3::2]
        attributes = [line.strip().split()[0] for line in source.split('\n')
                      if '_Option(' in line]
        for attribute, docstring in zip(attributes, docstrings):
            Options.__dict__[attribute].__doc__ = docstring
629246
def encode_numpy(array):
    '''

    '''
    return {'data' : base64.b64encode(array.data).decode('utf8'),
            'type' : array.dtype.name,
            'shape': array.shape}
932563
def Shape(docs, drop=0.0):
    """"""
    ids = numpy.zeros((sum(len(doc) for doc in docs),), dtype="i")
    i = 0
    for doc in docs:
        for token in doc:
            ids[i] = token.shape
            i += 1
    return ids, None
743924
def _fix_tbit_dtype(self, array, colnums):
        
        descr = array.dtype.descr
        for i, colnum in enumerate(colnums):
            npy_type, isvar, istbit = self._get_tbl_numpy_dtype(colnum)
            if (istbit):
                coldescr = list(descr[i])
                coldescr[1] = '?'
                descr[i] = tuple(coldescr)

        return array.view(descr)
598179
def _generate_namespace_types(self, namespace, jazzy_cfg):
        """"""
        ns_name = fmt_public_name(namespace.name)
        output_path = os.path.join('ApiObjects', ns_name)
        output_path_headers = os.path.join(output_path, 'Headers')

        for data_type in namespace.linearize_data_types():
            class_name = fmt_class_prefix(data_type)

            if self.args.documentation:
                append_to_jazzy_category_dict(jazzy_cfg, ns_name, class_name)
                append_to_jazzy_category_dict(
                    jazzy_cfg, 'Serializers', '{}Serializer'.format(class_name))

            if is_struct_type(data_type):
                # struct header
                file_path = os.path.join(output_path_headers,
                                         class_name + '.h')
                with self.output_to_relative_path(file_path):
                    self.emit_raw(base_file_comment)
                    self._generate_struct_class_h(data_type)
            elif is_union_type(data_type):

                if self.args.documentation:
                    append_to_jazzy_category_dict(
                        jazzy_cfg, 'Tags', '{}Tag'.format(fmt_class_prefix(data_type)))
                # union header
                file_path = os.path.join(output_path_headers,
                                         class_name + '.h')
                with self.output_to_relative_path(file_path):
                    self.emit_raw(base_file_comment)
                    self._generate_union_class_h(data_type)
            else:
                raise TypeError('Can\'t handle type %r' % type(data_type))

        file_path = os.path.join(
            output_path,
            'DB{}Objects.m'.format(fmt_camel_upper(namespace.name)))
        with self.output_to_relative_path(file_path):
            self.emit_raw(base_file_comment)

            description = '/// Arguments, results, and errors for the `{}` namespace.'.format(
                fmt_camel_upper(namespace.name))
            self.emit(description)

            if self.args.exclude_from_analysis:
                self.emit()
                self.emit('#ifndef __clang_analyzer__')

            for data_type in namespace.linearize_data_types():
                if is_struct_type(data_type):
                    # struct implementation
                    self._generate_struct_class_m(data_type)
                elif is_union_type(data_type):
                    # union implementation
                    self._generate_union_class_m(data_type)

            if self.args.exclude_from_analysis:
                self.emit('#endif')
790306
def get_py_dtype(np_dtype):
    '''
    
    '''
    if np_dtype.type == np.object_:
        return object
    elif hasattr(np_dtype.type(0), 'item'):
        return type(np_dtype.type(0).item())
    else:
        return type(np_dtype.type(0))
105746
def _generate_docstring_return_section(self, return_vals, header,
                                           return_element_name,
                                           return_element_type,
                                           placeholder, indent):
        """"""
        # If all return values are None, return none
        non_none_vals = [return_val for return_val in return_vals
                         if return_val and return_val != 'None']
        if not non_none_vals:
            return header + indent + 'None.'

        # Get only values with matching brackets that can be cleaned up
        non_none_vals = [return_val.strip(' ()\t\n').rstrip(',')
                         for return_val in non_none_vals]
        non_none_vals = [re.sub('([\"\'])(?:(?=(\\\\?))\\2.)*?\\1',
                                '"string"', return_val)
                         for return_val in non_none_vals]
        unambiguous_vals = []
        for return_val in non_none_vals:
            try:
                cleaned_val = self.find_top_level_bracket_locations(return_val)
            except IndexError:
                continue
            unambiguous_vals.append(cleaned_val)
        if not unambiguous_vals:
            return header + placeholder

        # If remaining are a mix of tuples and not, return single placeholder
        single_vals, tuple_vals = [], []
        for return_val in unambiguous_vals:
            (tuple_vals.append(return_val) if ',' in return_val
             else single_vals.append(return_val))
        if single_vals and tuple_vals:
            return header + placeholder

        # If return values are tuples of different length, return a placeholder
        if tuple_vals:
            num_elements = [return_val.count(',') + 1
                            for return_val in tuple_vals]
            if num_elements.count(num_elements[0]) != len(num_elements):
                return header + placeholder
            num_elements = num_elements[0]
        else:
            num_elements = 1

        # If all have the same len but some ambiguous return that placeholders
        if len(unambiguous_vals) != len(non_none_vals):
            return header + '\n'.join(
                [placeholder for __ in range(num_elements)])

        # Handle tuple (or single) values position by position
        return_vals_grouped = zip(*[
            [return_element.strip() for return_element in
             return_val.split(',')]
            for return_val in unambiguous_vals])
        return_elements_out = []
        for return_vals_group in return_vals_grouped:
            return_elements_out.append(
                self.parse_return_elements(return_vals_group,
                                           return_element_name,
                                           return_element_type,
                                           placeholder))

        return header + '\n'.join(return_elements_out)
1204643
def _prepare_default_dtype(src_array, dtype):
    """"""
    if dtype is None:
        if isinstance(src_array, (NDArray, np.ndarray)):
            dtype = src_array.dtype
        elif spsp and isinstance(src_array, spsp.csr.csr_matrix):
            dtype = src_array.dtype
        else:
            dtype = mx_real_t
    return dtype
446814
def inherit_docstrings(cls):
    
    @functools.wraps(cls)
    def _inherit_docstrings(cls):
        if not isinstance(cls, (type, colorise.compat.ClassType)):
            raise RuntimeError("Type is not a class")

        for name, value in colorise.compat.iteritems(vars(cls)):
            if isinstance(getattr(cls, name), types.MethodType):
                if not getattr(value, '__doc__', None):
                    for base in cls.__bases__:
                        basemethod = getattr(base, name, None)

                        if basemethod and getattr(base, '__doc__', None):
                            value.__doc__ = basemethod.__doc__

        return cls

    return _inherit_docstrings(cls)
142554
def _from_python_type(self, obj, field, pytype):
        """"""
        json_schema = {
            'title': field.attribute or field.name,
        }

        for key, val in TYPE_MAP[pytype].items():
            json_schema[key] = val

        if field.dump_only:
            json_schema['readonly'] = True

        if field.default is not missing:
            json_schema['default'] = field.default

        # NOTE: doubled up to maintain backwards compatibility
        metadata = field.metadata.get('metadata', {})
        metadata.update(field.metadata)

        for md_key, md_val in metadata.items():
            if md_key == 'metadata':
                continue
            json_schema[md_key] = md_val

        if isinstance(field, fields.List):
            json_schema['items'] = self._get_schema_for_field(
                obj, field.container
            )
        return json_schema
1183517
def np2gdal_dtype(d):
    
    dt_dict = gdal_array.codes        
    if isinstance(d, (np.ndarray, np.generic)):
        d = d.dtype
    #This creates dtype from another built-in type
    #d = np.dtype(d)
    if isinstance(d, np.dtype):
        if d.name == 'int8':
            gdal_dt = 1
        elif d.name == 'bool':
            #Write out as Byte
            gdal_dt = 1 
        else:
            gdal_dt = list(dt_dict.keys())[list(dt_dict.values()).index(d)]
    else:
        print("Input must be NumPy array or NumPy dtype")
        gdal_dt = None
    return gdal_dt