Example #1
0
def readtable(tablesource):

    # tablesource is expected to be a sequence containing the
    # following positional arguments:
    # 1. pathname to xls file (mandatory)
    # 2. name of desired worksheet (mandatory)
    # 3. headers (an int [row number for headers] or a sequence of
    #    strings; optional)
    # 4. dataslice (optional; a slice specification)

    assert tc.issequence(tablesource)
    nargs = len(tablesource)
    assert 2 <= nargs <= 4

    path, sheetname = tablesource[:2]
    sheet = x2p.Workbook(path)[sheetname]

    headers = tablesource[2] if nargs > 2 else 0
    dataslice = tablesource[3] if nargs > 3 else None

    if isinstance(headers, int):
        labels = tuple(unicode(cell) for cell in sheet[headers])
        first_data_row = headers + 1
    else:
        labels = headers
        first_data_row = 0

    if dataslice is None:
        data = sheet[first_data_row:]
    else:
        data = sheet[dataslice]

    return x2p.Table(data, labels)
Example #2
0
    def as_table(self, dataslice=slice(1, None), header=0,
                 types=None, formatting=None):
        if header is None or issequence(header):
            header_row = header
        else:
            header_row = self[header]

        if formatting is None:
            formatting = self._format
        return Table(self[dataslice], header_row, types=types, **formatting)
Example #3
0
def kgroups(seq, k):
    """ Yield successive k-sized groups from l.
    """
    if not tc.issequence(seq):
        raise TypeError('seq is not a sequence')
    if not k > 0:
        raise ValueError('k must be positive')

    for i in xrange(0, len(seq), k):
        yield seq[i:i+k]
Example #4
0
    def as_table(self,
                 dataslice=slice(1, None),
                 header=0,
                 types=None,
                 formatting=None):
        if header is None or issequence(header):
            header_row = header
        else:
            header_row = self[header]

        if formatting is None:
            formatting = self._format
        return Table(self[dataslice], header_row, types=types, **formatting)
Example #5
0
def ipartition(seq, pred):
    """
    >>> from partition import ipartition
    >>> pred = lambda x: int(x) % 3 == 2
    >>> seq = imap(str, xrange(15))
    >>> ipartition(seq, pred)
    [<itertools.ifilter at 0x33193d0>, <itertools.ifilterfalse at 0x3319a10>]
    >>> map(tuple, ipartition(seq, pred))
    [('2', '5', '8', '11', '14'),
     ('0', '1', '3', '4', '6', '7', '9', '10', '12', '13')]
    """
    if not tc.issequence(seq):
        raise TypeError('seq is not a sequence')

    t1, t2 = it.tee(seq)
    return [it.ifilter(pred, t1), it.ifilterfalse(pred, t2)]
Example #6
0
def partition(seq, pred):
    """
    >>> from partition import partition
    >>> pred = lambda x: int(x) % 3 == 2
    >>> seq = map(str, range(15))
    >>> partition(seq, pred)
    [('2', '5', '8', '11', '14'), ('0', '1', '3', '4', '6', '7', '9', '10', '12', '13')]
    """

    if not tc.issequence(seq):
        raise TypeError('seq is not a sequence')

    t, f = [], []
    for d in seq:
        if pred(d): t.append(d)
        else: f.append(d)
    return [tuple(t), tuple(f)]
Example #7
0
def splitseq(seq, m, truncate=False):
    """ Yield (approximately) m subsequences from seq.

    If n = len(seq), and n >= m, then the function will yield m
    consecutive subsequences of length n//m.  Then, if r = n % m > 0
    and truncate is not a true value, it will yield one more
    subsequence of length r.

    If n < m, a ValueError is raised.
    """

    if not tc.issequence(seq):
        raise TypeError('seq is not a sequence')

    n = len(seq)
    if not isinstance(m, int) or n < m:
        raise ValueError('m must be a positive integer not greater than len(seq)')

    stride = n // m
    i = 0
    while i < n:
        j = i + stride
        yield seq[i:j]
        i = j
Example #8
0
def _tolist(x):
    return [_tolist(i) for i in x] if issequence(x) else x
Example #9
0
def _seq2type(seq, type_):
    assert tc.issequence(seq)
    return type(seq)([type_(v) for v in seq])
Example #10
0
def getmodel(appname_and_modelname):
    assert tc.issequence(appname_and_modelname)
    assert len(appname_and_modelname) == 2

    return mo.get_model(*appname_and_modelname)
Example #11
0
def _tolist(x):
    return [_tolist(i) for i in x] if issequence(x) else x
Example #12
0
def unique(seq, unique_as=lambda x: x, keeplast=False, constructor=None,
           with_star=False, tally=None):
    """Remove duplicates from seq, preserving order and type.

    Testing for duplicates happens after applying unique_as to each
    element of seq.  By default, the returned value contains the first
    element x of seq for each value of unique_as(x) encountered.  If
    keeplast is set to True, then the last such element will be
    included in the returned value instead.

    The constructor argument specifies the constructor callable to use
    to create the returned value.  By default this callable is set to
    the value of type(seq).

    By default, the value returned will be constructor(nodups), where
    nodups is a sequence having the desired elements, but not
    necessarily having the desired type.  If with_star as a true
    value, then constructor(*nodups) is returned instead.

    If tally is set to a dictionary, when the function returns its
    keys will consist of the same elements as in those in the returned
    value, and its values will be the number of times each key appears
    in seq (or, more precisely, the number of times that the result
    from applying unique_as to the key appears in map(unique_as,
    seq)).  Note that if tally is set, its contents, if any, will be
    overwritten.

    If tally is set to a non-dict true value, then the function will
    return a sequence (value, count) pairs, analogous to the items of
    the tally dictionary described in the previous paragraph, but
    ordered in the way its keys would have been ordered in the default
    (i.e. with tally option unset) case.
    """

    assert tc.issequence(seq)
    seen = set()
    u = []

    tally_mode = (_IN_PLACE_TALLY if isinstance(tally, dict)
                  else _RETURN_TALLY if tally else _NO_TALLY)
    keep_tally = tally_mode != _NO_TALLY

    if keep_tally:
        temp_tally = dict()

    for x in (reversed(seq) if keeplast else seq):
        y = unique_as(x)

        if y not in seen:
            seen.add(y)
            u.append(x)

        if keep_tally:
            temp_tally.setdefault(y, [x, 0])[1] += 1

    if keep_tally:
        temp_tally = dict(temp_tally.values())
        if tally_mode == _IN_PLACE_TALLY:
            tally.clear()
            tally.update(temp_tally)
        else:
            assert tally_mode == _RETURN_TALLY
            u = [(v, temp_tally[v]) for v in u]

    if constructor is None:
        constructor = type(seq)

    return constructor(*u) if with_star else constructor(u)
Example #13
0
def _seq2type(seq, type_):
    assert tc.issequence(seq)
    return type(seq)([type_(v) for v in seq])