Create an lexiographical sorted basis for a given order.

    Examples
    --------
    >>> chaospy.bertran.olindex(3, 2)
    array([[0, 3],
           [1, 2],
           [2, 1],
           [3, 0]])
191510
def olindex(order, dim):
    
    idxm = [0]*dim
    out = []

    def _olindex(idx):
        """Recursive backend for olindex."""
        if numpy.sum(idxm) == order:
            out.append(idxm[:])
            return

        if idx == dim:
            return

        idxm_sum = numpy.sum(idxm)
        idx_saved = idxm[idx]

        for idxi in range(order - numpy.sum(idxm) + 1):

            idxm[idx] = idxi

            if idxm_sum < order:
                _olindex(idx+1)

            else:
                break
        idxm[idx] = idx_saved

    _olindex(0)
    return numpy.array(out)
943962
def format_result(input):
        
        items = list(iteritems(input))
        return OrderedDict(sorted(items, key=lambda x: x[0]))
738638
def deterministic_dict(normal_dict):
  
  out = OrderedDict()
  for key in sorted(normal_dict.keys()):
    out[key] = normal_dict[key]
  return out
1064950
def _stieltjes_analytical(dist, order, normed):
    """"""
    dimensions = len(dist)
    mom_order = numpy.arange(order+1).repeat(dimensions)
    mom_order = mom_order.reshape(order+1, dimensions).T
    coeff1, coeff2 = dist.ttr(mom_order)
    coeff2[:, 0] = 1.

    poly = chaospy.poly.collection.core.variable(dimensions)
    if normed:
        orth = [
            poly**0*numpy.ones(dimensions),
            (poly-coeff1[:, 0])/numpy.sqrt(coeff2[:, 1]),
        ]
        for order_ in range(1, order):
            orth.append(
                (orth[-1]*(poly-coeff1[:, order_])
                 -orth[-2]*numpy.sqrt(coeff2[:, order_]))
                /numpy.sqrt(coeff2[:, order_+1])
            )
        norms = numpy.ones(coeff2.shape)
    else:
        orth = [poly-poly, poly**0*numpy.ones(dimensions)]
        for order_ in range(order):
            orth.append(
                orth[-1]*(poly-coeff1[:, order_])
                - orth[-2]*coeff2[:, order_]
            )
        orth = orth[1:]
        norms = numpy.cumprod(coeff2, 1)

    return orth, norms, coeff1, coeff2
624562
def sortby(listoflists,sortcols):
    
    newlist = abut(colex(listoflists,sortcols),listoflists)
    newlist.sort()
    try:
        numcols = len(sortcols)
    except TypeError:
        numcols = 1
    crit = '[' + str(numcols) + ':]'
    newlist = colex(newlist,crit)
    return newlist
528062
def ordered_dirs(self):
        
        return [item[0] for item in sorted(
            self.byte_contents.items(), key=lambda entry: entry[1].st_ino)]
517773
def _bunchify(b):
    """"""
    assert isinstance(b, dict)
    b = Bunch(b)
    for k in b:
        if isinstance(b[k], dict):
            b[k] = Bunch(b[k])
    return b
415252
def create_column_index(annotations):
    
    _column_index = OrderedDict({'Column Name' : annotations['Column Name']})
    categorical_rows = annotation_rows('C:', annotations)
    _column_index.update(categorical_rows)
    numerical_rows = {name: [float(x) if x != '' else float('NaN') for x in values]
            for name, values in annotation_rows('N:', annotations).items()} # to floats
    _column_index.update(numerical_rows)
    column_index = pd.MultiIndex.from_tuples(list(zip(*_column_index.values())), names=list(_column_index.keys()))
    if len(column_index.names) == 1:
        # flatten single-level index
        name = column_index.names[0]
        column_index = column_index.get_level_values(name)
    return column_index
1246654
def items(cls):
        
        items = [(value.name, key) for key, value in cls.values.items()]
        return sorted(items, key=lambda x: x[1])
804623
def todict(self):
        """"""
        return OrderedDict((name, self[i]) for i, name in enumerate(self._fields))
244550
def sorted_bits(self) -> List[Tuple[str, int]]:
        """"""
        return sorted(self.bit.items(), key=lambda x: x[1])
1220506
def ordered(self, ord='desc'):
        """"""
        if ord not in ('asc', 'desc', ):
            raise
        ord_f = getattr(PIDRelation.index, ord)()
        return self.order_by(ord_f)
388968
def argsort_indices(a, axis=-1):
    
    a = np.asarray(a)
    ind = list(np.ix_(*[np.arange(d) for d in a.shape]))
    ind[axis] = a.argsort(axis)
    return tuple(ind)
127489
def assoc_indexed(cls, ops, kwargs):
    
    """
    from qnet.algebra.core.abstract_quantum_algebra import (
        ScalarTimesQuantumExpression)
    term, *ranges = ops

    if isinstance(term, cls):
        coeff = 1
    elif isinstance(term, ScalarTimesQuantumExpression):
        coeff = term.coeff
        term = term.term
        if not isinstance(term, cls):
            return ops, kwargs
    else:
        return ops, kwargs

    term = term.make_disjunct_indices(*ranges)
    combined_ranges = tuple(ranges) + term.ranges

    if coeff == 1:
        return cls.create(term.term, *combined_ranges)
    else:
        bound_symbols = set([r.index_symbol for r in combined_ranges])
        if len(coeff.free_symbols.intersection(bound_symbols)) == 0:
            return coeff * cls.create(term.term, *combined_ranges)
        else:
            return cls.create(coeff * term.term, *combined_ranges)
507306
def create_dicts(data):
    
    chars = set()
    for sample in data:
        chars.update(set(sample))
    char_indices = dict((c, i) for i, c in enumerate(chars))
    indices_char = dict((i, c) for i, c in enumerate(chars))
    return char_indices, indices_char
227997
def as_sorted_list(options):
        
        if len(options) > 0:
            options = sorted(options, key=lambda o: o.number)
        return options
474107
def _grouped(iterable, n):
        
        args = [iter(iterable)] * n
        return [[e for e in t if not e is None] for t in zip_longest(*args, fillvalue=None)]