Check whether `s_indices` and `a_indices` are sorted in
    lexicographic order.

    Parameters
    ----------
    s_indices, a_indices : ndarray(ndim=1)

    Returns
    -------
    bool
        Whether `s_indices` and `a_indices` are sorted.
339580
def _has_sorted_sa_indices(s_indices, a_indices):
    
    L = len(s_indices)
    for i in range(L-1):
        if s_indices[i] > s_indices[i+1]:
            return False
        if s_indices[i] == s_indices[i+1]:
            if a_indices[i] >= a_indices[i+1]:
                return False
    return True
44985
def get_value_index(self, indices):
        
        size = self['size'] if self.get('size') else self['dimension']['size']
        ndims = len(size)
        mult = 1
        num = 0
        for idx, dim in enumerate(size):
            mult *= size[ndims - idx] if (idx > 0) else 1
            num += mult * indices[ndims - idx - 1]
        return num
1228047
def _get_indexers_coords_and_indexes(self, indexers):
        
        from .dataarray import DataArray

        coord_list = []
        indexes = OrderedDict()
        for k, v in indexers.items():
            if isinstance(v, DataArray):
                v_coords = v.coords
                if v.dtype.kind == 'b':
                    if v.ndim != 1:  # we only support 1-d boolean array
                        raise ValueError(
                            '{:d}d-boolean array is used for indexing along '
                            'dimension {!r}, but only 1d boolean arrays are '
                            'supported.'.format(v.ndim, k))
                    # Make sure in case of boolean DataArray, its
                    # coordinate also should be indexed.
                    v_coords = v[v.values.nonzero()[0]].coords

                coord_list.append({d: v_coords[d].variable for d in v.coords})
                indexes.update(v.indexes)

        # we don't need to call align() explicitly or check indexes for
        # alignment, because merge_variables already checks for exact alignment
        # between dimension coordinates
        coords = merge_variables(coord_list)
        assert_coordinate_consistent(self, coords)

        # silently drop the conflicted variables.
        attached_coords = OrderedDict(
            (k, v) for k, v in coords.items() if k not in self._variables
        )
        attached_indexes = OrderedDict(
            (k, v) for k, v in indexes.items() if k not in self._variables
        )
        return attached_coords, attached_indexes
406639
def dimension_sort(odict, kdims, vdims, key_index):
    
    sortkws = {}
    ndims = len(kdims)
    dimensions = kdims+vdims
    indexes = [(dimensions[i], int(i not in range(ndims)),
                    i if i in range(ndims) else i-ndims)
                for i in key_index]
    cached_values = {d.name: [None]+list(d.values) for d in dimensions}

    if len(set(key_index)) != len(key_index):
        raise ValueError("Cannot sort on duplicated dimensions")
    else:
       sortkws['key'] = lambda x: tuple(cached_values[dim.name].index(x[t][d])
                                        if dim.values else x[t][d]
                                        for i, (dim, t, d) in enumerate(indexes))
    if sys.version_info.major == 3:
        return python2sort(odict.items(), **sortkws)
    else:
        return sorted(odict.items(), **sortkws)
1229714
def _check_min_max_indices(self, min_index=None, max_index=None):
        
        min_index = min_index or 0
        max_index = max_index or len(self)
        if min_index < 0:
            self.log_exc(u"min_index is negative", None, True, ValueError)
        if max_index > len(self):
            self.log_exc(u"max_index is bigger than the number of intervals in the list", None, True, ValueError)
        return min_index, max_index
1242713
def reorder_indices(self, indices_order):
        ''
        # allow mixed index syntax like int
        indices_order, single = convert_index_to_keys(self.indices, indices_order)
        old_indices = force_list(self.indices.keys())

        if indices_order == old_indices: # no changes
            return

        if set(old_indices) != set(indices_order):
            raise KeyError('Keys in the new order do not match existing keys')

#        if len(old_indices) == 0: # already return since indices_order must equal to old_indices
#            return

        # must have more than 1 index to reorder
        new_idx = [old_indices.index(i) for i in indices_order]
        # reorder items
        items = [map(i.__getitem__, new_idx) for i in self.items()]
        self.clear(True)
        _MI_init(self, items, indices_order)
1051766
def looks_like_index(series, index_names=('Unnamed: 0', 'pk', 'index', '')):
    
    if series.name in index_names:
        return True
    if (series == series.index.values).all():
        return True
    if (series == np.arange(len(series))).all():
        return True
    if (
        (series.index == np.arange(len(series))).all() and
        str(series.dtype).startswith('int') and
        (series.count() == len(series))
    ):
        return True
    return False
481806
def _make_indices(self, Ns):
        '''  '''
        N_new = int(Ns * self.n_splits)

        test = [np.full(N_new, False) for i in range(self.n_splits)]
        for i in range(self.n_splits):
            test[i][np.arange(Ns * i, Ns * (i + 1))] = True
        train = [np.logical_not(test[i]) for i in range(self.n_splits)]

        test = [np.arange(N_new)[test[i]] for i in range(self.n_splits)]
        train = [np.arange(N_new)[train[i]] for i in range(self.n_splits)]

        cv = list(zip(train, test))
        return cv
393237
def indices(db=None):
    '''
    
    '''
    cur = _connect(db)

    if not cur:
        return False

    cur.execute(
        "SELECT name FROM sqlite_master WHERE type='index' ORDER BY name;"
    )
    rows = cur.fetchall()
    return rows
784299
def hidden_indices(self):
        """"""
        return tuple(sorted(set(self.micro_indices) -
                            set(self.output_indices)))
643215
def nDims(self):
        
        result = self._index.ndim
        assert result == 1, "Expected index to be 1D, got: {}D".format(result)
        return result
366263
def _is_partial_index(gbi_file):
    
    with open(gbi_file) as in_handle:
        for i, _ in enumerate(in_handle):
            if i > 2:
                return False
    return True
1192834
function compareIndex(nodeA, nodeB) {
  var indexA = nodeA && nodeA.sortIndex;
  var indexB = nodeB && nodeB.sortIndex;
  if (!indexA && !indexB) {
    return 0;
  }
  else if (Boolean(indexA) !== Boolean(indexB)) {
    return indexA ? +1 : indexB ? -1 : 0;
  }
  else {
    return indexA - indexB;
  }
}
63393
def filtered(self, indices):
        
        if indices is None or len(indices) == len(self):
            return self
        new = object.__new__(self.__class__)
        indices = numpy.uint32(sorted(indices))
        new.array = self.array[indices]
        new.complete = self.complete
        return new
567308
def more_than_one_index(s, brackets=2):
    '''
    
    '''
    start = 0
    brackets_num = 0
    while start != -1 and brackets_num < brackets:
        start = s.find("[", start)
        if start == -1:
            break
        start = s.find("]", start)
        brackets_num += 1
    if start != -1:
        return True
    return False
512330
def _get_index_nd(self, key):
        """"""
        def _is_advanced_index(index):
            """The definition of advanced index here includes integers as well, while
            integers are considered as basic index type when the key contains only
            slices and integers."""
            return not isinstance(index, py_slice)

        if isinstance(key, (NDArray, np.ndarray, list, integer_types, py_slice)):
            key = (key,)

        assert isinstance(key, tuple),\
            'index=%s must be a NDArray, or np.ndarray, or list, or tuple ' \
            ' type to use advanced indexing, received type=%s' % (str(key), str(type(key)))

        assert len(key) > 0, "Cannot slice with empty indices"
        shape = self.shape
        assert len(shape) >= len(key),\
            "Slicing dimensions exceeds array dimensions, %d vs %d" % (len(key), len(shape))
        indices = []
        dtype = 'int32'  # index data type passed to gather_nd op
        need_broadcast = (len(key) != 1)
        advanced_indices = []  # include list, NDArray, np.ndarray, integer
        basic_indices = []  # include only slices
        advanced_index_bshape = None  # final advanced index shape
        for i, idx_i in enumerate(key):
            is_advanced_index = True
            if isinstance(idx_i, (np.ndarray, list, tuple)):
                idx_i = array(idx_i, ctx=self.context, dtype=dtype)
                advanced_indices.append(i)
            elif isinstance(idx_i, py_slice):
                start, stop, step = _get_index_range(idx_i.start, idx_i.stop, shape[i], idx_i.step)
                idx_i = arange(start, stop, step, ctx=self.context, dtype=dtype)
                basic_indices.append(i)
                is_advanced_index = False
            elif isinstance(idx_i, integer_types):
                start, stop, step = _get_index_range(idx_i, idx_i+1, shape[i], 1)
                idx_i = arange(start, stop, step, ctx=self.context, dtype=dtype)
                advanced_indices.append(i)
            elif isinstance(idx_i, NDArray):
                if dtype != idx_i.dtype:
                    idx_i = idx_i.astype(dtype)
                advanced_indices.append(i)
            else:
                raise IndexError('Indexing NDArray with index=%s of type=%s is not supported'
                                 % (str(key), str(type(key))))
            if is_advanced_index:
                if advanced_index_bshape is None:
                    advanced_index_bshape = idx_i.shape
                elif advanced_index_bshape != idx_i.shape:
                    need_broadcast = True
                    advanced_index_bshape = _get_broadcast_shape(advanced_index_bshape, idx_i.shape)
            indices.append(idx_i)

        # Get final index shape for gather_nd. See the following reference
        # for determining the output array shape.
        # https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#combining-advanced-and-basic-indexing  # pylint: disable=line-too-long
        if len(advanced_indices) == 0:
            raise ValueError('Advanced index tuple must contain at least one of the following types:'
                             ' list, tuple, NDArray, np.ndarray, integer, received index=%s' % key)
        # determine the output array's shape by checking whether advanced_indices are all adjacent
        # or separated by slices
        advanced_indices_adjacent = True
        for i in range(0, len(advanced_indices)-1):
            if advanced_indices[i] + 1 != advanced_indices[i+1]:
                advanced_indices_adjacent = False
                break

        index_bshape_list = []  # index broadcasted shape
        if advanced_indices_adjacent:
            for i in range(0, advanced_indices[0]):
                index_bshape_list.extend(indices[i].shape)
                if not need_broadcast and indices[i].shape != advanced_index_bshape:
                    need_broadcast = True
            index_bshape_list.extend(advanced_index_bshape)
            for i in range(advanced_indices[-1]+1, len(indices)):
                if not need_broadcast and indices[i].shape != advanced_index_bshape:
                    need_broadcast = True
                index_bshape_list.extend(indices[i].shape)
        else:
            index_bshape_list.extend(advanced_index_bshape)
            for i in basic_indices:
                index_bshape_list.extend(indices[i].shape)
                if not need_broadcast and indices[i].shape != advanced_index_bshape:
                    need_broadcast = True
        index_bshape = tuple(index_bshape_list)

        # Need to broadcast all ndarrays in indices to the final shape.
        # For example, suppose an array has shape=(5, 6, 7, 8) and
        # key=(slice(1, 5), [[1, 2]], slice(2, 5), [1]).
        # Since key[1] and key[3] are two advanced indices here and they are
        # separated by basic indices key[0] and key[2], the output shape
        # is (1, 2, 4, 3), where the first two elements come from the shape
        # that key[1] and key[3] should broadcast to, which is (1, 2), and
        # the last two elements come from the shape of two basic indices.
        # In order to broadcast all basic and advanced indices to the output shape,
        # we need to reshape them based on their axis. For example, to broadcast key[0],
        # with shape=(4,), we first need to reshape it into (1, 1, 4, 1), and then
        # broadcast the reshaped array to (1, 2, 4, 3); to broadcast key[1], we first
        # reshape it into (1, 2, 1, 1), then broadcast the reshaped array to (1, 2, 4, 3).
        if need_broadcast:
            broadcasted_indices = []
            idx_rshape = [1] * len(index_bshape)
            if advanced_indices_adjacent:
                advanced_index_bshape_start = advanced_indices[0]  # start index of advanced_index_bshape in index_shape
                advanced_index_bshape_stop = advanced_index_bshape_start + len(advanced_index_bshape)
                for i, idx in enumerate(key):
                    if _is_advanced_index(idx):
                        k = advanced_index_bshape_stop
                        # find the reshaped shape for indices[i]
                        for dim_size in indices[i].shape[::-1]:
                            k -= 1
                            idx_rshape[k] = dim_size
                    else:
                        if i < advanced_indices[0]:  # slice is on the left side of advanced indices
                            idx_rshape[i] = indices[i].shape[0]
                        elif i > advanced_indices[-1]:  # slice is on the right side of advanced indices
                            idx_rshape[i-len(key)] = indices[i].shape[0]
                        else:
                            raise ValueError('basic index i=%d cannot be between advanced index i=%d and i=%d'
                                             % (i, advanced_indices[0], advanced_indices[-1]))
                    # broadcast current index to the final shape
                    broadcasted_indices.append(indices[i].reshape(tuple(idx_rshape)).broadcast_to(index_bshape))
                    # reset idx_rshape to ones
                    for j, _ in enumerate(idx_rshape):
                        idx_rshape[j] = 1
            else:
                basic_index_offset = len(advanced_index_bshape)
                for i, idx in enumerate(key):
                    if _is_advanced_index(idx):
                        k = len(advanced_index_bshape)
                        for dim_size in indices[i].shape[::-1]:
                            k -= 1
                            idx_rshape[k] = dim_size
                    else:
                        idx_rshape[basic_index_offset] = indices[i].shape[0]
                        basic_index_offset += 1
                    # broadcast current index to the final shape
                    broadcasted_indices.append(indices[i].reshape(tuple(idx_rshape)).broadcast_to(index_bshape))
                    # reset idx_rshape to ones
                    for j, _ in enumerate(idx_rshape):
                        idx_rshape[j] = 1

            indices = broadcasted_indices
        return op.stack(*indices)
451941
def _indexes(arr):
    
    myarr = np.array(arr)
    if myarr.ndim == 1:
        return list(range(len(myarr)))
    elif myarr.ndim == 2:
        return tuple(itertools.product(list(range(arr.shape[0])),
                                       list(range(arr.shape[1]))))
    else:
        raise NotImplementedError('Only supporting arrays of dimension 1 and 2 as yet.')