Trim and pad first dimension of all features to size length.
967863
def trim_and_pad_all_features(features, length):
  """"""
  return {k: _trim_and_pad(v, length) for k, v in features.items()}
605155
def trim(self, length):
        """"""
        if length > 0:
            for child in self.children.values(): child.trim(length-1)
        else:
            if hasattr(self, 'count'): self.count = sum(map(lambda x: x.count, self))
            self.children = OrderedDict()
285029
def p_width(self, p):
        ''
        p[0] = Width(p[2], p[4], lineno=p.lineno(1))
        p.set_lineno(0, p.lineno(1))
1093086
def _dims2shape(*dims):
    """"""
    if not dims:
        raise ValueError("expected at least one dimension spec")
    shape = list()
    for dim in dims:
        if isinstance(dim, int):
            dim = (0, dim)
        if isinstance(dim, tuple) and len(dim) == 2:
            if dim[0] < 0:
                raise ValueError("expected low dimension to be >= 0")
            if dim[1] < 0:
                raise ValueError("expected high dimension to be >= 0")
            if dim[0] > dim[1]:
                raise ValueError("expected low <= high dimensions")
            start, stop = dim
        else:
            raise TypeError("expected dimension to be int or (int, int)")
        shape.append((start, stop))
    return tuple(shape)
870820
def p_features(self, t):
        """"""

        if len(t) == 4:
            t[0] = t[1]
            t[0].append(t[3])
        elif t[1]:
            t[0] = [t[1]]
        else:
            t[0] = []
526468
def dimensions(self):
        """"""
        # First of all: Select this dataset
        if self.scraper.current_item is not self:
            self._move_here()

        if self._dimensions is None:
            self._dimensions = DimensionList()
            for d in self.scraper._fetch_dimensions(self):
                d.dataset = self
                d.scraper = self.scraper
                self._dimensions.append(d)
        return self._dimensions
477015
def preScale(self, sx, sy):
        """"""
        self.a *= sx
        self.b *= sx
        self.c *= sy
        self.d *= sy
        return self
231388
def _create_features(self, constraints):
    """"""
    affine_warp_constraints = constraints
    if not isinstance(affine_warp_constraints, AffineWarpConstraints):
      affine_warp_constraints = AffineWarpConstraints(affine_warp_constraints)
    mask = affine_warp_constraints.mask
    psi = _create_affine_features(output_shape=self._output_shape,
                                  source_shape=self._source_shape)
    scales = [(x - 1.0) * .5 for x in reversed(self._source_shape)]
    offsets = scales
    # Transforming a point x's i-th coordinate via an affine transformation
    # is performed via the following dot product:
    #
    #  x_i' = s_i * (T_i * x) + t_i                                          (1)
    #
    # where Ti is the i-th row of an affine matrix, and the scalars s_i and t_i
    # define a decentering and global scaling into the source space.
    # In the AffineGridWarper some of the entries of Ti are provided via the
    # input, some others are instead fixed, according to the constraints
    # assigned in the constructor.
    # In create_features the internal dot product (1) is accordingly broken down
    # into two parts:
    #
    # x_i' = Ti[uncon_i] * x[uncon_i, :] + offset(con_var)                   (2)
    #
    # i.e. the sum of the dot product of the free parameters (coming
    # from the input) indexed by uncond_i and an offset obtained by
    # precomputing the fixed part of (1) according to the constraints.
    # This step is implemented by analyzing row by row the constraints matrix
    # and saving into a list the x[uncon_i] and offset(con_var) data matrices
    # for each output dimension.
    features = []
    for row, scale in zip(mask, scales):
      x_i = np.array([x for x, is_active in zip(psi, row) if is_active])
      features.append(x_i * scale if len(x_i) else None)

    for row_i, row in enumerate(mask):
      x_i = None
      s = scales[row_i]
      for i, is_active in enumerate(row):
        if is_active:
          continue

        # In principle a whole row of the affine matrix can be fully
        # constrained. In that case the corresponding dot product between input
        # parameters and grid coordinates doesn't need to be implemented in the
        # computation graph since it can be precomputed.
        # When a whole row if constrained, x_i - which is initialized to
        # None - will still be None at the end do the loop when it is appended
        # to the features list; this value is then used to detect this setup
        # in the build function where the graph is assembled.
        if x_i is None:
          x_i = np.array(psi[i]) * affine_warp_constraints[row_i][i] * s
        else:
          x_i += np.array(psi[i]) * affine_warp_constraints[row_i][i] * s
      features.append(x_i)

    features += offsets
    return features
585476
def dimensions(filenames):
    """"""

    single = type(filenames) is str
    if single:
        filenames = [filenames]
    dims = get_dimensions(filenames)
    if single:
        dims = dims[0]
    return dims
3834
function toAllPadding(padding) {
    var top = 0;
    var left = 0;
    var right = 0;
    var bottom = 0;

    if (Util.isNumber(padding) || Util.isString(padding)) {
      top = left = right = bottom = padding;
    } else if (Util.isArray(padding)) {
      top = padding[0];
      right = !Util.isNil(padding[1]) ? padding[1] : padding[0];
      bottom = !Util.isNil(padding[2]) ? padding[2] : padding[0];
      left = !Util.isNil(padding[3]) ? padding[3] : right;
    } else if (Util.isObject(padding)) {
      top = padding.top || 0;
      right = padding.right || 0;
      bottom = padding.bottom || 0;
      left = padding.left || 0;
    }
    return [top, right, bottom, left];
  }
594416
def pad_to_size(text, x, y):
    
    input_lines = text.rstrip().split("\n")
    longest_input_line = max(map(len, input_lines))
    number_of_input_lines = len(input_lines)
    x = max(x, longest_input_line)
    y = max(y, number_of_input_lines)
    output = ""

    padding_top = int((y - number_of_input_lines) / 2)
    padding_bottom = y - number_of_input_lines - padding_top
    padding_left = int((x - longest_input_line) / 2)

    output += padding_top * (" " * x + "\n")
    for line in input_lines:
        output += padding_left * " " + line + " " * (x - padding_left - len(line)) + "\n"
    output += padding_bottom * (" " * x + "\n")

    return output
969313
function pad(text, length, align = 'left') {
  let pad = ' '.repeat(length - stringWidth(text));
  if (align === 'right') {
    return pad + text;
  }

  return text + pad;
}
1138711
def with_added_dimensions(self, n):
        
        if n > 0:
            return Rect(np.pad(self.data, ((0, 0), (0, n)), 'constant'))
        return Rect(self.data[:, :self.dimensions + n])
883897
def __shpFileLength(self):
        """"""
        # Start with header length
        size = 100
        # Calculate size of all shapes
        for s in self._shapes:
            # Add in record header and shape type fields
            size += 12
            # nParts and nPoints do not apply to all shapes
            #if self.shapeType not in (0,1):
            #       nParts = len(s.parts)
            #       nPoints = len(s.points)
            if hasattr(s,'parts'):
                nParts = len(s.parts)
            if hasattr(s,'points'):
                nPoints = len(s.points)
            # All shape types capable of having a bounding box
            if self.shapeType in (3,5,8,13,15,18,23,25,28,31):
                size += 32
            # Shape types with parts
            if self.shapeType in (3,5,13,15,23,25,31):
                # Parts count
                size += 4
                # Parts index array
                size += nParts * 4
            # Shape types with points
            if self.shapeType in (3,5,8,13,15,23,25,31):
                # Points count
                size += 4
                # Points array
                size += 16 * nPoints
            # Calc size of part types for Multipatch (31)
            if self.shapeType == 31:
                size += nParts * 4
            # Calc z extremes and values
            if self.shapeType in (13,15,18,31):
                # z extremes
                size += 16
                # z array
                size += 8 * nPoints
            # Calc m extremes and values
            if self.shapeType in (23,25,31):
                # m extremes
                size += 16
                # m array
                size += 8 * nPoints
            # Calc a single point
            if self.shapeType in (1,11,21):
                size += 16
            # Calc a single Z value
            if self.shapeType == 11:
                size += 8
            # Calc a single M value
            if self.shapeType in (11,21):
                size += 8
        # Calculate size as 16-bit words
        size //= 2
        return size
877037
def pad_to_shape(d, dshape, mode = "constant"):
    
    if d.shape == dshape:
        return d

    diff = np.array(dshape)- np.array(d.shape)
    #first shrink
    slices  = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff)
    res = d[slices]
    #then pad
    # return np.pad(res,[(n/2,n-n/2) if n>0 else (0,0) for n in diff],mode=mode)
    return np.pad(res,[(int(np.ceil(d/2.)),d-int(np.ceil(d/2.))) if d>0 else (0,0) for d in diff],mode=mode)
121488
def p_feature_simple(self, t):
        """"""

        if len(t) == 6:
            t[0] = Feature(t[1], t[2], t[4], line=t.lineno(1))
        elif len(t) == 5:
            t[0] = Feature(t[1], t[2], t[3], unit=t[4], line=t.lineno(1))
        elif len(t) == 4:
            t[0] = Feature(t[1], t[2], t[3], line=t.lineno(1))
677919
def _initializeDimensions(self, inputData):
    
    if len(inputData.shape) == 2:
      self.imageHeight, self.numImages = inputData.shape
      self.imageWidth, self.numChannels = None, None

    elif len(inputData.shape) == 3:
      self.imageHeight, \
      self.imageWidth, \
      self.numImages = inputData.shape
      self.numChannels = None

    elif len(inputData.shape) == 4:
      self.imageHeight, \
      self.imageWidth, \
      self.numChannels, \
      self.numImages = inputData.shape

    else:
      raise ValueError("The provided image set has more than 4 dimensions.")