Iterate over selections of an xarray object in the provided order.
761347
def _iter_over_selections(obj, dim, values):
    """"""
    from .groupby import _dummy_copy

    dummy = None
    for value in values:
        try:
            obj_sel = obj.sel(**{dim: value})
        except (KeyError, IndexError):
            if dummy is None:
                dummy = _dummy_copy(obj)
            obj_sel = dummy
        yield obj_sel
640470
def posterior_predictive_to_xarray(self):
        """"""
        posterior_predictive = self.posterior_predictive
        columns = self.posterior[0].columns
        if (
            isinstance(posterior_predictive, (tuple, list))
            and posterior_predictive[0].endswith(".csv")
        ) or (isinstance(posterior_predictive, str) and posterior_predictive.endswith(".csv")):
            if isinstance(posterior_predictive, str):
                posterior_predictive = [posterior_predictive]
            chain_data = []
            for path in posterior_predictive:
                parsed_output = _read_output(path)
                for sample, *_ in parsed_output:
                    chain_data.append(sample)
            data = _unpack_dataframes(chain_data)
        else:
            if isinstance(posterior_predictive, str):
                posterior_predictive = [posterior_predictive]
            posterior_predictive_cols = [
                col
                for col in columns
                if any(item == col.split(".")[0] for item in posterior_predictive)
            ]
            data = _unpack_dataframes([item[posterior_predictive_cols] for item in self.posterior])
        return dict_to_dataset(data, coords=self.coords, dims=self.dims)
1314335
function _parse_select_order(ObjType, document_type, order, q, traits) {

	debug.assert(ObjType).is('function');
	debug.assert(document_type).ignore(undefined).is('object');
	debug.assert(order).is('array');

	return ARRAY(order).map(function(o) {
		var key, type, rest;
		if(is.array(o)) {
			key = parse_operator_name(o[0]);
			type = parse_operator_type(o[0], 'text');
			rest = o.slice(1);
		} else {
			key = parse_operator_name(o);
			type = parse_operator_type(o, 'text');
			rest = [];
		}

		if(key === 'BIND') {
			return _parse_function_predicate(ObjType, q, undefined, rest, type, traits);
		}

		//debug.log('key = ', key);
		var parsed_key = _parse_predicate_key(ObjType, {'traits': traits, 'epoch':true}, key);
		//debug.log('parsed_key = ', parsed_key);
		var pgcast = parse_predicate_pgcast(ObjType, document_type, key);
		//debug.log('pgcast = ', pgcast);

		return new Predicate( [pgcast(parsed_key.getString())].concat(rest).join(' '), parsed_key.getParams(), parsed_key.getMetaObject() );
	}).valueOf();
}
58843
def _call(self, x, out=None):
        """"""
        if out is None:
            out = x[self.index].copy()
        else:
            out.assign(x[self.index])
        return out
712185
def interpolate_xml_array(data, low_res_coords, shape, chunks):
        """"""
        xpoints, ypoints = low_res_coords

        return interpolate_xarray_linear(xpoints, ypoints, data, shape, chunks=chunks)
422359
def prior_predictive_to_xarray(self):
        """"""
        prior = self.prior
        prior_predictive = self.prior_predictive
        data = get_draws(prior, variables=prior_predictive)
        return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims)
954994
def _ordered(generator, *args, **kwargs):
    """"""
    unordered_dict = {k: v for k, v in generator(*args, **kwargs)}
    keys = sorted(list(dict(unordered_dict).keys()))
    result = OrderedDict()
    for key in keys:
        result[key] = unordered_dict[key]

    return result
808502
def reorder_image(dst_order, src_arr, src_order):
    
    depth = src_arr.shape[2]
    if depth != len(src_order):
        raise ValueError("src_order (%s) does not match array depth (%d)" % (
            src_order, depth))

    bands = []
    if dst_order == src_order:
        return np.ascontiguousarray(src_arr)

    elif 'A' not in dst_order or 'A' in src_order:
        # <-- we don't have to add an alpha plane, just create a new view
        idx = np.array([src_order.index(c) for c in dst_order])
        return np.ascontiguousarray(src_arr[..., idx])

    else:
        # <-- dst order requires missing alpha channel
        indexes = [src_order.index(c) for c in dst_order.replace('A', '')]
        bands = [src_arr[..., idx, np.newaxis] for idx in indexes]
        ht, wd = src_arr.shape[:2]
        dst_type = src_arr.dtype
        dst_max_val = np.iinfo(dst_type).max
        alpha = np.full((ht, wd, 1), dst_max_val, dtype=dst_type)
        bands.insert(dst_order.index('A'), alpha)

    return np.concatenate(bands, axis=-1)
628315
def xselections(items, n):
    
    if n==0:
        yield []
    else:
        for i in xrange(len(items)):
            for ss in xselections(items, n-1):
                yield [items[i]]+ss
305879
def posterior_to_xarray(self):
        """"""
        data = {}
        for i, var_name in enumerate(self.var_names):
            data[var_name] = np.expand_dims(self.posterior[i], axis=0)
        return dict_to_dataset(data, library=self.tfp, coords=self.coords, dims=self.dims)
1174140
def sort(self):
        """"""
        super(JSSObjectList, self).sort(key=lambda k: k.id)
1042169
def Field_to_xarray(field):
    ''''''
    dom = field.domain
    dims = []; dimlist = []; coords = {};
    for axname in dom.axes:
        dimlist.append(axname)
        try:
            assert field.interfaces[dom.axis_index[axname]]
            bounds_name = axname + '_bounds'
            dims.append(bounds_name)
            coords[bounds_name] = dom.axes[axname].bounds
        except:
            dims.append(axname)
            coords[axname] = dom.axes[axname].points
    #  Might need to reorder the data
    da = DataArray(field.transpose([dom.axis_index[name] for name in dimlist]),
                      dims=dims, coords=coords)
    for name in dims:
        try:
            da[name].attrs['units'] = dom.axes[name].units
        except:
            pass
    return da
152598
def process_axes(self, obj, columns=None):
        

        # make a copy to avoid side effects
        if columns is not None:
            columns = list(columns)

        # make sure to include levels if we have them
        if columns is not None and self.is_multi_index:
            for n in self.levels:
                if n not in columns:
                    columns.insert(0, n)

        # reorder by any non_index_axes & limit to the select columns
        for axis, labels in self.non_index_axes:
            obj = _reindex_axis(obj, axis, labels, columns)

        # apply the selection filters (but keep in the same order)
        if self.selection.filter is not None:
            for field, op, filt in self.selection.filter.format():

                def process_filter(field, filt):

                    for axis_name in obj._AXIS_NAMES.values():
                        axis_number = obj._get_axis_number(axis_name)
                        axis_values = obj._get_axis(axis_name)

                        # see if the field is the name of an axis
                        if field == axis_name:

                            # if we have a multi-index, then need to include
                            # the levels
                            if self.is_multi_index:
                                filt = filt.union(Index(self.levels))

                            takers = op(axis_values, filt)
                            return obj.loc._getitem_axis(takers,
                                                         axis=axis_number)

                        # this might be the name of a file IN an axis
                        elif field in axis_values:

                            # we need to filter on this dimension
                            values = ensure_index(getattr(obj, field).values)
                            filt = ensure_index(filt)

                            # hack until we support reversed dim flags
                            if isinstance(obj, DataFrame):
                                axis_number = 1 - axis_number
                            takers = op(values, filt)
                            return obj.loc._getitem_axis(takers,
                                                         axis=axis_number)

                    raise ValueError("cannot find the field [{field}] for "
                                     "filtering!".format(field=field))

                obj = process_filter(field, filt)

        return obj
669522
def posterior_to_xarray(self):
        """"""
        posterior = self.posterior
        # filter posterior_predictive and log_likelihood
        posterior_predictive = self.posterior_predictive
        if posterior_predictive is None:
            posterior_predictive = []
        elif isinstance(posterior_predictive, str):
            posterior_predictive = [posterior_predictive]
        log_likelihood = self.log_likelihood
        if not isinstance(log_likelihood, str):
            log_likelihood = []
        else:
            log_likelihood = [log_likelihood]

        ignore = posterior_predictive + log_likelihood + ["lp__"]

        data = get_draws(posterior, ignore=ignore)

        return dict_to_dataset(data, library=self.pystan, coords=self.coords, dims=self.dims)
1280294
private static <T extends Storable> OrderingList<T>
        expectedOrdering(StorageAccess<T> access, Filter<T> filter, OrderingList<T> ordering)
    {
        List<Filter<T>> split;
        if (filter == null) {
            split = Filter.getOpenFilter(access.getStorableType()).disjunctiveNormalFormSplit();
        } else {
            split = filter.disjunctiveNormalFormSplit();
        }

        Comparator comparator = CompositeScore.fullComparator();

        CompositeScore bestScore = null;
        for (StorableIndex<T> index : access.getAllIndexes()) {
            for (Filter<T> sub : split) {
                CompositeScore candidateScore = CompositeScore.evaluate(index, sub, ordering);
                if (bestScore == null || comparator.compare(candidateScore, bestScore) < 0) {
                    bestScore = candidateScore;
                }
            }
        }

        // Reduce source ordering to that which can be handled for
        // free. Otherwise, a sort would be performed which is a waste of time
        // if some source results will later be filtered out.
        int handledCount = bestScore == null ? 0 : bestScore.getOrderingScore().getHandledCount();
        return ordering.subList(0, handledCount);
    }
545242
def _sort(self):
        """"""
        self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order)
279046
def X(self) -> Optional[Union[np.ndarray, sparse.spmatrix, ArrayView]]:
        """"""
        if self.isbacked:
            if not self.file.isopen: self.file.open()
            X = self.file['X']
            if self.isview:
                X = X[self._oidx, self._vidx]
            return X
        else:
            if self.n_obs == 1 and self.n_vars == 1:
                return self._X[0, 0]
            elif self.n_obs == 1 or self.n_vars == 1:
                X = self._X
                if issparse(self._X): X = self._X.toarray()
                return X.flatten()
            else:
                return self._X