Implementation of orthogonal indexing with slices and ints.
557375
def oindex(a, selection):
    """"""
    selection = replace_ellipsis(selection, a.shape)
    drop_axes = tuple([i for i, s in enumerate(selection) if is_integer(s)])
    selection = ix_(selection, a.shape)
    result = a[selection]
    if drop_axes:
        result = result.squeeze(axis=drop_axes)
    return result
629148
def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None):
        

        allow_fill = fill_tuple is not None

        sl_type, slobj, sllen = _preprocess_slice_or_indexer(
            slice_or_indexer, self.shape[0], allow_fill=allow_fill)

        if self._is_single_block:
            blk = self.blocks[0]

            if sl_type in ('slice', 'mask'):
                return [blk.getitem_block(slobj, new_mgr_locs=slice(0, sllen))]
            elif not allow_fill or self.ndim == 1:
                if allow_fill and fill_tuple[0] is None:
                    _, fill_value = maybe_promote(blk.dtype)
                    fill_tuple = (fill_value, )

                return [blk.take_nd(slobj, axis=0,
                                    new_mgr_locs=slice(0, sllen),
                                    fill_tuple=fill_tuple)]

        if sl_type in ('slice', 'mask'):
            blknos = self._blknos[slobj]
            blklocs = self._blklocs[slobj]
        else:
            blknos = algos.take_1d(self._blknos, slobj, fill_value=-1,
                                   allow_fill=allow_fill)
            blklocs = algos.take_1d(self._blklocs, slobj, fill_value=-1,
                                    allow_fill=allow_fill)

        # When filling blknos, make sure blknos is updated before appending to
        # blocks list, that way new blkno is exactly len(blocks).
        #
        # FIXME: mgr_groupby_blknos must return mgr_locs in ascending order,
        # pytables serialization will break otherwise.
        blocks = []
        for blkno, mgr_locs in libinternals.get_blkno_placements(blknos,
                                                                 self.nblocks,
                                                                 group=True):
            if blkno == -1:
                # If we've got here, fill_tuple was not None.
                fill_value = fill_tuple[0]

                blocks.append(self._make_na_block(placement=mgr_locs,
                                                  fill_value=fill_value))
            else:
                blk = self.blocks[blkno]

                # Otherwise, slicing along items axis is necessary.
                if not blk._can_consolidate:
                    # A non-consolidatable block, it's easy, because there's
                    # only one item and each mgr loc is a copy of that single
                    # item.
                    for mgr_loc in mgr_locs:
                        newblk = blk.copy(deep=True)
                        newblk.mgr_locs = slice(mgr_loc, mgr_loc + 1)
                        blocks.append(newblk)

                else:
                    blocks.append(blk.take_nd(blklocs[mgr_locs.indexer],
                                              axis=0, new_mgr_locs=mgr_locs,
                                              fill_tuple=None))

        return blocks
1025226
def indexed(cls, dataset, selection):
        
        selected = list(selection.keys())
        all_scalar = all((not isinstance(sel, (tuple, slice, set, list))
                          and not callable(sel)) for sel in selection.values())
        all_kdims = all(d in selected for d in dataset.kdims)
        return all_scalar and all_kdims
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)
286430
def _set_nd_basic_indexing(self, key, value):
        """"""
        shape = self.shape
        if isinstance(key, integer_types):
            if key < 0:
                key += shape[0]
            if key < 0 or key >= shape[0]:
                if key < 0:
                    key -= shape[0]
                raise IndexError('index %d is out of bounds for axis 0 with size %d'
                                 % (key, shape[0]))
            key = py_slice(key, key+1)  # key must be >= 0 here

        if isinstance(key, py_slice):
            assign_to_self = key.step is None or key.step == 1
            assign_to_self &= key.start is None or key.start == 0
            assign_to_self &= key.stop is None or key.stop == shape[0]
            if assign_to_self:  # trivial case, assign value to self
                if isinstance(value, NDArray):
                    if value.handle is not self.handle:
                        if value.shape != shape:
                            value = value.broadcast_to(shape)
                        value.copyto(self)
                elif isinstance(value, numeric_types):
                    _internal._full(shape=shape, ctx=self.context,
                                    dtype=self.dtype, value=float(value), out=self)
                elif isinstance(value, (np.ndarray, np.generic)):
                    if isinstance(value, np.generic) or value.shape != shape:
                        value = np.broadcast_to(value, shape)
                    self._sync_copyfrom(value)
                else:  # value might be a list or a tuple
                    value_nd = self._prepare_value_nd(value, shape)
                    value_nd.copyto(self)
                return
            else:  # non-trivial case, use _slice_assign or _slice_assign_scalar
                key = (key,)

        assert isinstance(key, tuple), "key=%s must be a tuple of slices and integers" % str(key)

        assert len(key) <= len(shape), "Indexing dimensions exceed array dimensions, %d vs %d"\
                                       % (len(key), len(shape))
        begin = []
        end = []
        steps = []
        oshape = []  # output shape of slice using key
        vshape = []  # value shape of data[key]
        for i, slice_i in enumerate(key):
            dim_size = 1
            if isinstance(slice_i, py_slice):
                begin.append(slice_i.start)
                end.append(slice_i.stop)
                steps.append(slice_i.step)
                start, stop, step = _get_index_range(slice_i.start, slice_i.stop,
                                                     shape[i], slice_i.step)
                dim_size = _get_dim_size(start, stop, step)
                vshape.append(dim_size)
            elif isinstance(slice_i, integer_types):
                begin.append(slice_i)
                end.append(slice_i+1 if slice_i != -1 else self.shape[i])
                steps.append(1)
            else:
                raise ValueError("basic indexing does not support index=%s of type=%s"
                                 % (str(slice_i), str(type(slice_i))))
            oshape.append(dim_size)

        oshape.extend(shape[len(key):])
        vshape.extend(shape[len(key):])
        # if key contains all integers, vshape should be (1,)
        if len(vshape) == 0:
            vshape.append(1)
        oshape = tuple(oshape)
        vshape = tuple(vshape)

        if isinstance(value, numeric_types):
            _internal._slice_assign_scalar(self, out=self, begin=begin, end=end,
                                           step=steps, scalar=float(value))
        else:
            value_nd = self._prepare_value_nd(value, vshape)
            if vshape != oshape:
                value_nd = value_nd.reshape(oshape)
            _internal._slice_assign(self, value_nd, begin, end, steps, out=self)
727054
void indexSamples() {
        sampleIndex = new HashMap<>();
        for (SampleResource sample : repoSamples) {
            if (sample.getShortName() != null) {
                sampleIndex.put(sample.getShortName().toLowerCase(), sample);
            }
        }
    }
877398
def _slice_generator(self, index):
        """"""
        start, stop, step = index.indices(len(self))
        for i in range(start, stop, step):
            yield self.get_blob(i)
1158380
def index_map(data):
  """"""
  (entry, text_fn) = data
  text = text_fn()

  logging.debug("Got %s", entry.filename)
  for s in split_into_sentences(text):
    for w in split_into_words(s.lower()):
      yield (w, entry.filename)
744901
private int linearSearch(int position) {
		int[] minSeqIndex = getMinSequenceIndex();
		int[] maxSeqIndex = getMaxSequenceIndex();
		int length = minSeqIndex.length;
		for (int i = 0; i < length; i++) {
			if (position >= minSeqIndex[i] && position <= maxSeqIndex[i]) {
				return i;
			}
		}
		throw new IndexOutOfBoundsException("Given position " + position + " does not map into this Sequence");
	}
1356863
def _slice(index, n_samples, margin=None):
    """"""
    if margin is None:
        margin = (0, 0)
    assert isinstance(n_samples, (tuple, list))
    assert len(n_samples) == 2
    before, after = n_samples
    assert isinstance(margin, (tuple, list))
    assert len(margin) == 2
    margin_before, margin_after = margin
    before += margin_before
    after += margin_after
    index = int(index)
    before = int(before)
    after = int(after)
    return slice(max(0, index - before), index + after, None)
187620
def index(self, sub, *args):
        '''
        
        '''
        if isinstance(sub, int):
            if len(args) == 0:
                start, end = 0, len(self)
            elif len(args) == 1:
                start = args[0]
            elif len(args) == 2:
                start, end = args
            else:
                raise TypeError('takes at most 3 arguments')
            return list(self)[start:end].index(sub)
        if not isinstance(sub, bytes):
            try:
                sub = self.__class__(sub)
            except (TypeError, ValueError):
                raise TypeError("can't convert sub to bytes")
        try:
            return super(newbytes, self).index(sub, *args)
        except ValueError:
            raise ValueError('substring not found')
489109
private static int binarySearch(int[] a, int fromIndex, int length, int key)
    {
        int low = fromIndex;
        int high = fromIndex + length - 1;

        while (low <= high)
        {
            int mid = (low + high) >>> 1;
            int midVal = a[mid << 1];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }
209968
private static int lastIndexOf(Object o, Object[] elements, int index) {
        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elements[i] == null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elements[i]))
                    return i;
        }
        return -1;
    }
246385
def _index_list_of_values(d, k):
    """"""
    v = d[k]
    if isinstance(v, list):
        return v
    return [v]
1112220
@Override
  public SparseTensor slice(int[] dimensionNumbers, int[] key) {
    if (dimensionNumbers.length == 0) {
      return this;
    }
    // Check for an efficient case, where the dimensions are the first
    // elements of this.
    if (ArrayUtils.subarrayEquals(getDimensionNumbers(), dimensionNumbers, 0)) {
      long minKeyInt = 0;
      int numDimensions = dimensionNumbers.length;
      for (int i = 0; i < numDimensions; i++) {
        minKeyInt += indexOffsets[i] * key[i];
      }
      long maxKeyInt = minKeyInt + indexOffsets[numDimensions - 1];

      int startIndex = getNearestIndex(minKeyInt);
      int endIndex = getNearestIndex(maxKeyInt);

      long[] newKeyInts = ArrayUtils.copyOfRange(keyNums, startIndex, endIndex);
      int numKeyInts = newKeyInts.length;
      for (int i = 0; i < numKeyInts; i++) {
        newKeyInts[i] -= minKeyInt;
      }

      int[] newDimensionNumbers = ArrayUtils.copyOfRange(getDimensionNumbers(), dimensionNumbers.length, getDimensionNumbers().length);
      int[] newDimensionSizes = ArrayUtils.copyOfRange(getDimensionSizes(), dimensionNumbers.length, getDimensionSizes().length);
      double[] newValues = ArrayUtils.copyOfRange(values, startIndex, endIndex);
      return new SparseTensor(newDimensionNumbers, newDimensionSizes, newKeyInts, newValues);
    }

    // TODO(jayantk): This is an extremely naive implementation of
    // slice.
    // Figure out the appropriate sizes for the subset of dimensions.
    int[] dimensionSizes = new int[dimensionNumbers.length];
    for (int i = 0; i < dimensionNumbers.length; i++) {
      int dimIndex = getDimensionIndex(dimensionNumbers[i]);
      Preconditions.checkArgument(dimIndex >= 0);
      dimensionSizes[i] = getDimensionSizes()[dimIndex];
    }
    SparseTensorBuilder builder = new SparseTensorBuilder(dimensionNumbers, dimensionSizes);
    builder.put(key, 1.0);
    return elementwiseProduct(builder.build()).sumOutDimensions(Ints.asList(dimensionNumbers));
  }
123891
def data_slice(self, slice_ind):
        
        if self.height is None:
            return self.data[slice_ind]
        return self.data[slice_ind, ...]
832946
def _data(self, cube, weighted, prune):
        """"""
        result = []
        for slice_ in cube.slices:
            if cube.has_mr:
                return self._mr_index(cube, weighted, prune)
            num = slice_.margin(axis=0, weighted=weighted, prune=prune)
            den = slice_.margin(weighted=weighted, prune=prune)
            margin = num / den
            proportions = slice_.proportions(axis=1, weighted=weighted, prune=prune)
            result.append(proportions / margin)

        if len(result) == 1 and cube.ndim < 3:
            result = result[0]
        else:
            if prune:
                mask = np.array([slice_.mask for slice_ in result])
                result = np.ma.masked_array(result, mask)
            else:
                result = np.array(result)

        return result