Universal indexing for numpy and pandas objects.
175684
def idx(df, index):
    """"""
    if isinstance(df, (pd.DataFrame, pd.Series)):
        return df.iloc[index]
    else:
        return df[index, :]
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)
1174010
def dloglikarray(self):
        """"""
        assert self.dparamscurrent, "dloglikarray requires paramscurrent == True"
        nparams = len(self._index_to_param)
        dloglikarray = scipy.ndarray(shape=(nparams,), dtype='float')
        for (i, param) in self._index_to_param.items():
            if isinstance(param, str):
                dloglikarray[i] = self.dloglik[param]
            elif isinstance(param, tuple):
                dloglikarray[i] = self.dloglik[param[0]][param[1]]
        return dloglikarray
817908
def bootstrap_indexes(data, n_samples=10000):
    
    for _ in xrange(n_samples):
        yield randint(data.shape[0], size=(data.shape[0],))
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
1272215
def _any_pandas_objects(terms):
    """"""
    return any(isinstance(term.value, pd.core.generic.PandasObject)
               for term in terms)
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
621723
def spaced_indexes(len_, n, trunc=False):
    

    if n is None:
        return np.arange(len_)
    all_indexes = np.arange(len_)
    if trunc:
        n = min(len_, n)
    if n == 0:
        return np.empty(0)
    stride = len_ // n
    try:
        indexes = all_indexes[0:-1:stride]
    except ValueError:
        raise ValueError('cannot slice list of len_=%r into n=%r parts' % (len_, n))
    return indexes
657036
def gather_indices_2d(x, block_shape, block_stride):
  """"""
  # making an identity matrix kernel
  kernel = tf.eye(block_shape[0] * block_shape[1])
  kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1])
  # making indices [1, h, w, 1] to appy convs
  x_shape = common_layers.shape_list(x)
  indices = tf.range(x_shape[2] * x_shape[3])
  indices = tf.reshape(indices, [1, x_shape[2], x_shape[3], 1])
  indices = tf.nn.conv2d(
      tf.cast(indices, tf.float32),
      kernel,
      strides=[1, block_stride[0], block_stride[1], 1],
      padding="VALID")
  # making indices [num_blocks, dim] to gather
  dims = common_layers.shape_list(indices)[:3]
  if all([isinstance(dim, int) for dim in dims]):
    num_blocks = functools.reduce(operator.mul, dims, 1)
  else:
    num_blocks = tf.reduce_prod(dims)
  indices = tf.reshape(indices, [num_blocks, -1])
  return tf.cast(indices, tf.int32)
134118
def indexes(self, indexes):
        
        self._indexes = indexes
        self._index = len(indexes) / 2
1363549
def _convert_to_spmatrix(operators):
        """"""
        # Lazy import to improve `import odl` time
        import scipy.sparse

        # Convert ops to sparse representation. This is not trivial because
        # operators can be indexable themselves and give the wrong impression
        # of an extra dimension. So we have to infer the shape manually
        # first and extract the indices of nonzero positions.
        nrows = len(operators)
        ncols = None
        irow, icol, data = [], [], []
        for i, row in enumerate(operators):
            try:
                iter(row)
            except TypeError:
                raise ValueError(
                    '`operators` must be a matrix of `Operator` objects, `0` '
                    'or `None`, got {!r} (row {} = {!r} is not iterable)'
                    ''.format(operators, i, row))

            if isinstance(row, Operator):
                raise ValueError(
                    '`operators` must be a matrix of `Operator` objects, `0` '
                    'or `None`, but row {} is an `Operator` {!r}'
                    ''.format(i, row))

            if ncols is None:
                ncols = len(row)
            elif len(row) != ncols:
                raise ValueError(
                    'all rows in `operators` must have the same length, but '
                    'length {} of row {} differs from previous common length '
                    '{}'.format(len(row), i, ncols))

            for j, col in enumerate(row):
                if col is None or col is 0:
                    pass
                elif isinstance(col, Operator):
                    irow.append(i)
                    icol.append(j)
                    data.append(col)
                else:
                    raise ValueError(
                        '`operators` must be a matrix of `Operator` objects, '
                        '`0` or `None`, got entry {!r} at ({}, {})'
                        ''.format(col, i, j))

        # Create object array explicitly, threby avoiding erroneous conversion
        # in `coo_matrix.__init__`
        data_arr = np.empty(len(data), dtype=object)
        data_arr[:] = data
        return scipy.sparse.coo_matrix((data_arr, (irow, icol)),
                                       shape=(nrows, ncols))
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
1014375
function numericIndexGetter(row, index) {
    if (row == null)
        return '';
    // mimic behavior of deepValueGetter
    if (!row || index == null)
        return row;
    var value = row[index];
    if (value == null)
        return '';
    return value;
}
267405
def index(m, val):
    
    mm = np.array(m)
    idx_tuple = np.where(mm == val)
    idx = idx_tuple[0].tolist()

    return idx
613254
def extract_indexes(coords):
    """"""
    for name, variable in coords.items():
        variable = as_variable(variable, name=name)
        if variable.dims == (name,):
            yield name, variable.to_index()
613964
def simple_nearest_indices(xs,res):
    '''
    
    '''
    maxs = [max(a) for a in xs]
    mins = [min(a) for a in xs]
    XS = [np.linspace(mn, mx, r) for mn,mx,r in zip(mins,maxs,res)];
    XS = tuple(np.meshgrid(*XS,indexing='ij'));
    if type(xs) != tuple:
        xs = tuple(xs);
    return nearest_indices(xs,XS);
436370
def _createIndexRti(self, index, nodeName):
        
        return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName,
                              iconColor=self._iconColor)