bpp: Martello and Toth's model to solve the bin packing problem.
    Parameters:
        - s: list with item widths
        - B: bin capacity
    Returns a model, ready to be solved.
778486
def bpp(s,B):
    
    n = len(s)
    U = len(FFD(s,B)) # upper bound of the number of bins
    model = Model("bpp")
    # setParam("MIPFocus",1)
    x,y = {},{}
    for i in range(n):
        for j in range(U):
            x[i,j] = model.addVar(vtype="B", name="x(%s,%s)"%(i,j))
    for j in range(U):
        y[j] = model.addVar(vtype="B", name="y(%s)"%j)

    # assignment constraints
    for i in range(n):
        model.addCons(quicksum(x[i,j] for j in range(U)) == 1, "Assign(%s)"%i)

    # bin capacity constraints
    for j in range(U):
        model.addCons(quicksum(s[i]*x[i,j] for i in range(n)) <= B*y[j], "Capac(%s)"%j)

    # tighten assignment constraints
    for j in range(U):
        for i in range(n):
            model.addCons(x[i,j] <= y[j], "Strong(%s,%s)"%(i,j))

    # tie breaking constraints
    for j in range(U-1):
        model.addCons(y[j] >= y[j+1],"TieBrk(%s)"%j)

    # SOS constraints
    for i in range(n):
        model.addConsSOS1([x[i,j] for j in range(U)])

    model.setObjective(quicksum(y[j] for j in range(U)), "minimize")
    model.data = x,y

    return model
1289444
def cublasSsymm(handle, side, uplo, m, n, alpha, A, lda, B, ldb, beta, C, ldc):
    
    
    status = _libcublas.cublasSsymm_v2(handle,
                                       _CUBLAS_SIDE_MODE[side], 
                                       _CUBLAS_FILL_MODE[uplo], 
                                       m, n, ctypes.byref(ctypes.c_float(alpha)),
                                       int(A), lda, int(B), ldb, 
                                       ctypes.byref(ctypes.c_float(beta)), 
                                       int(C), ldc)
    cublasCheckStatus(status)
542771
function(sbmA, sbmB) {
    // check if size compatible
    if (sbmA.y !== sbmB.x) {
      return
    }
    // create a new matrix
    return this.make((function (i, j) {
      return _.reduce(_.map(_.range(sbmA.y), (function(id) {
        return this.check(sbmA, i, id) && this.check(sbmB, id, j)
      }).bind(this)), function (sum, a) {
        return sum ^ a
      }) == 1
    }).bind(this), { x: sbmA.x, y: sbmB.y })
  }
132694
def positions_binning(records):
    
    def get_key(d):
        return (d.year, d.day, d.hour, d.minute // 30)

    chunks = itertools.groupby(records, key=lambda r: get_key(r.datetime))

    for _, items in chunks:
        positions = [i.position for i in items]
        # Given the low number of positions per chunk of 30 minutes, and
        # the need for a deterministic value, we use max and not Counter
        yield max(positions, key=positions.count)
834107
def bfd(items, targets, **kwargs):
    
    sizes = zip(items, weight(items, **kwargs))
    sizes = sorted(sizes, key=operator.itemgetter(1), reverse=True)
    items = map(operator.itemgetter(0), sizes)
    return bf(items, targets, **kwargs)
598980
def _heuristic_bin_width(obs):
    """"""
    IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25)
    N = len(obs)
    return 2*IQR*N**(-1/3)
44742
def _filtdim(items, shape, dim, nsl):
    """"""
    normshape = tuple(stop - start for start, stop in shape)
    nsl_type = type(nsl)
    newitems = list()
    # Number of groups
    num = reduce(operator.mul, normshape[:dim+1])
    # Size of each group
    size = len(items) // num
    # Size of the dimension
    n = normshape[dim]
    if nsl_type is int:
        for i in range(num):
            if i % n == nsl:
                newitems += items[size*i:size*(i+1)]
        # Collapse dimension
        newshape = shape[:dim] + shape[dim+1:]
    elif nsl_type is slice:
        for i in range(num):
            if nsl.start <= (i % n) < nsl.stop:
                newitems += items[size*i:size*(i+1)]
        # Reshape dimension
        offset = shape[dim][0]
        redim = (offset + nsl.start, offset + nsl.stop)
        newshape = shape[:dim] + (redim, ) + shape[dim+1:]
    # farray
    else:
        if nsl.size < clog2(n):
            fstr = "expected dim {} select to have >= {} bits, got {}"
            raise ValueError(fstr.format(dim, clog2(n), nsl.size))
        groups = [list() for _ in range(n)]
        for i in range(num):
            groups[i % n] += items[size*i:size*(i+1)]
        for muxins in zip(*groups):
            it = boolfunc.iter_terms(nsl._items)
            xs = [reduce(operator.and_, (muxin, ) + next(it))
                  for muxin in muxins]
            newitems.append(reduce(operator.or_, xs))
        # Collapse dimension
        newshape = shape[:dim] + shape[dim+1:]
    return newitems, newshape
69161
def S(self):
        
        S = np.array([[self._plane_width / self._vol_width, 0, 0],
                      [0, self._plane_height / self._vol_height, 0],
                      [0, 0, self._depth_scale / self._vol_depth]])
        return S
1209877
def _lscmp(a, b):
    '''  '''
    return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b)
1152654
def sbar(Ss):
    
    if type(Ss) == list:
        Ss = np.array(Ss)
    npts = Ss.shape[0]
    Ss = Ss.transpose()

    avd, avs = [], []
    # D=np.array([Ss[0],Ss[1],Ss[2],Ss[3]+0.5*(Ss[0]+Ss[1]),Ss[4]+0.5*(Ss[1]+Ss[2]),Ss[5]+0.5*(Ss[0]+Ss[2])]).transpose()
    D = np.array([Ss[0], Ss[1], Ss[2], Ss[3] + 0.5 * (Ss[0] + Ss[1]),
                  Ss[4] + 0.5 * (Ss[1] + Ss[2]), Ss[5] + 0.5 * (Ss[0] + Ss[2])])
    for j in range(6):
        avd.append(np.average(D[j]))
        avs.append(np.average(Ss[j]))
    D = D.transpose()
    # for s in Ss:
    #    print 'from sbar: ',s
    #    D.append(s[:]) # append a copy of s
    #    D[-1][3]=D[-1][3]+0.5*(s[0]+s[1])
    #    D[-1][4]=D[-1][4]+0.5*(s[1]+s[2])
    #    D[-1][5]=D[-1][5]+0.5*(s[0]+s[2])
    #    for j in range(6):
    #        avd[j]+=(D[-1][j])/float(npts)
    #        avs[j]+=(s[j])/float(npts)
#   calculate sigma
    nf = (npts - 1) * 6  # number of degrees of freedom
    s0 = 0
    Dels = (D - avd)**2
    s0 = np.sum(Dels)
    sigma = np.sqrt(s0/float(nf))
    return nf, sigma, avs
1036
def RRlist2bitmap(lst):
    
    # RFC 4034, 4.1.2. The Type Bit Maps Field

    import math

    bitmap = b""
    lst = [abs(x) for x in sorted(set(lst)) if x <= 65535]

    # number of window blocks
    max_window_blocks = int(math.ceil(lst[-1] / 256.))
    min_window_blocks = int(math.floor(lst[0] / 256.))
    if min_window_blocks == max_window_blocks:
        max_window_blocks += 1

    for wb in range(min_window_blocks, max_window_blocks + 1):
        # First, filter out RR not encoded in the current window block
        # i.e. keep everything between 256*wb <= 256*(wb+1)
        rrlist = sorted(x for x in lst if 256 * wb <= x < 256 * (wb + 1))
        if not rrlist:
            continue

        # Compute the number of bytes used to store the bitmap
        if rrlist[-1] == 0:  # only one element in the list
            bytes_count = 1
        else:
            max = rrlist[-1] - 256 * wb
            bytes_count = int(math.ceil(max // 8)) + 1  # use at least 1 byte
        if bytes_count > 32:  # Don't encode more than 256 bits / values
            bytes_count = 32

        bitmap += struct.pack("BB", wb, bytes_count)

        # Generate the bitmap
        # The idea is to remove out of range Resource Records with these steps
        # 1. rescale to fit into 8 bits
        # 2. x gives the bit position ; compute the corresponding value
        # 3. sum everything
        bitmap += b"".join(
            struct.pack(
                b"B",
                sum(2 ** (7 - (x - 256 * wb) + (tmp * 8)) for x in rrlist
                    if 256 * wb + 8 * tmp <= x < 256 * wb + 8 * tmp + 8),
            ) for tmp in range(bytes_count)
        )

    return bitmap
437790
def _rebuild_blknos_and_blklocs(self):
        
        new_blknos = np.empty(self.shape[0], dtype=np.int64)
        new_blklocs = np.empty(self.shape[0], dtype=np.int64)
        new_blknos.fill(-1)
        new_blklocs.fill(-1)

        for blkno, blk in enumerate(self.blocks):
            rl = blk.mgr_locs
            new_blknos[rl.indexer] = blkno
            new_blklocs[rl.indexer] = np.arange(len(rl))

        if (new_blknos == -1).any():
            raise AssertionError("Gaps in blk ref_locs")

        self._blknos = new_blknos
        self._blklocs = new_blklocs
527085
def get_possible_splits(n):
    
    get_bin = lambda x, n: x >= 0 and str(bin(x))[2:].zfill(n) or "-" + str(bin(x))[3:].zfill(n)
    possible_splits = []
    for i in range(2**(n - 1)):
        possible_splits.append(get_bin(i, n - 1))
    return possible_splits
282485
def packbools(bools, dtype='L'):
    
    r = NBITS[dtype]
    atoms = ATOMS[dtype]

    for chunk in zip_longest(*[iter(bools)] * r, fillvalue=False):
        yield sum(compress(atoms, chunk))
472926
def _grouper(iterable, n, fillvalue=0):
        
        args = [iter(iterable)] * n
        return zip_longest(fillvalue=fillvalue, *args)
302731
def sizes(self: Any) -> Mapping[Hashable, int]:
        
        return Frozen(OrderedDict(zip(self.dims, self.shape)))
490544
def pack_tuple(self, values):
        
        assert isinstance(values, (tuple, list))
        cardinality = [struct_L.pack(len(values))]
        packed_items = [self.pack_field(v) for v in values]
        return b''.join(itertools.chain(cardinality, packed_items))