Given two shapes that are not identical, find the shape
    that both input shapes can broadcast to.
340289
def _get_broadcast_shape(shape1, shape2):
    """"""
    if shape1 == shape2:
        return shape1

    length1 = len(shape1)
    length2 = len(shape2)
    if length1 > length2:
        shape = list(shape1)
    else:
        shape = list(shape2)
    i = max(length1, length2) - 1
    for a, b in zip(shape1[::-1], shape2[::-1]):
        if a != 1 and b != 1 and a != b:
            raise ValueError('shape1=%s is not broadcastable to shape2=%s' % (shape1, shape2))
        shape[i] = max(a, b)
        i -= 1
    return tuple(shape)
997094
def trace2(A, B):
    
    """
    A = asarray(A, float)
    B = asarray(B, float)

    layout_error = "Wrong matrix layout."

    if not (len(A.shape) == 2 and len(B.shape) == 2):
        raise ValueError(layout_error)

    if not (A.shape[1] == B.shape[0] and A.shape[0] == B.shape[1]):
        raise ValueError(layout_error)

    return _sum(A.T * B)
860215
def output_shape(self):
    """"""
    if self._output_shape is None:
      self._ensure_is_connected()
    if callable(self._output_shape):
      self._output_shape = tuple(self._output_shape())
    return self._output_shape
654452
public Shape[] union(Shape target, Shape other) {
		target = target.transform(new Transform());
		other = other.transform(new Transform());
		
		if (!target.intersects(other)) {
			return new Shape[] {target, other};
		}
		
		// handle the case where intersects is true but really we're talking
		// about edge points
		boolean touches = false;
		int buttCount = 0;
		for (int i=0;i<target.getPointCount();i++) {
			if (other.contains(target.getPoint(i)[0], target.getPoint(i)[1])) {
				if (!other.hasVertex(target.getPoint(i)[0], target.getPoint(i)[1])) {
					touches = true;
					break;
				}
			}
			if (other.hasVertex(target.getPoint(i)[0], target.getPoint(i)[1])) {
				buttCount++;
			} 
		}
		for (int i=0;i<other.getPointCount();i++) {
			if (target.contains(other.getPoint(i)[0], other.getPoint(i)[1])) {
				if (!target.hasVertex(other.getPoint(i)[0], other.getPoint(i)[1])) {
					touches = true;
					break;
				}
			}
		}
		
		if ((!touches) && (buttCount < 2)) {
			return new Shape[] {target, other};
		}
		
		// so they are definitely touching, consider the union
		return combine(target, other, false);
	}
754025
def _fix_broadcast(op_name, inputs, broadcast_axis, proto_obj):
    """"""
    if int(len(proto_obj._params)) > 0:
        assert len(list(inputs)) == 2

        input0_shape = get_input_shape(inputs[0], proto_obj)
        #creating reshape shape
        reshape_shape = list(len(input0_shape) * (1,))
        reshape_shape[broadcast_axis] = -1
        reshape_shape = tuple(reshape_shape)
        reshape_op_sym = symbol.reshape(inputs[1], shape=reshape_shape)
        op_sym = getattr(symbol, op_name)(inputs[0], reshape_op_sym)
    else:
        op_sym = op_name
    return op_sym
826810
public static boolean shapeEqualWithSqueeze(long[] shape1, long[] shape2){
        if(shape1 == null)
            return shape2 == null;
        if(shape2 == null)
            return false;   //Shape 1 must be non-null by this point
        if(shape1.length == 0 && shape2.length == 0)
            return true;

        int pos1 = 0;
        int pos2 = 0;
        while(pos1 < shape1.length && pos2 < shape2.length){
            if(shape1[pos1] == 1){
                pos1++;
                continue;
            }
            if(shape2[pos2] == 1){
                pos2++;
                continue;
            }
            //Both are non-1 shape. Must be equal
            if(shape1[pos1] != shape2[pos2]){
                return false;
            }
            pos1++;
            pos2++;
        }
        //Handle trailing 1s
        while(pos1 < shape1.length && shape1[pos1] == 1)
            pos1++;
        while(pos2 < shape2.length && shape2[pos2] == 1)
            pos2++;

        //2 possibilities: all entries consumed -> same shape. Or some remaining - something like [2] vs. [2,3,4,5]
        return pos1 == shape1.length && pos2 == shape2.length;
    }
697860
def shape(self, shape=None):
        """"""
        if shape is None:
            return self._shape
        data, color = self.renderer.manager.set_shape(self.model.id, shape)
        self.model.data = data
        self.color = color
        self._shape = shape
467825
def GetMatchingShape(pattern_poly, trip, matches, max_distance, verbosity=0):
  
  if len(matches) == 0:
    print ('No matching shape found within max-distance %d for trip %s '
           % (max_distance, trip.trip_id))
    return None

  if verbosity >= 1:
    for match in matches:
      print("match: size %d" % match.GetNumPoints())
  scores = [(pattern_poly.GreedyPolyMatchDist(match), match)
            for match in matches]

  scores.sort()

  if scores[0][0] > max_distance:
    print ('No matching shape found within max-distance %d for trip %s '
           '(min score was %f)'
           % (max_distance, trip.trip_id, scores[0][0]))
    return None

  return scores[0][1]
1145717
def _check_shape(shape):
    """"""
    if isinstance(shape, tuple):
        for dim in shape:
            if (isinstance(dim, tuple) and len(dim) == 2 and
                    isinstance(dim[0], int) and isinstance(dim[1], int)):
                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")
            else:
                raise TypeError("expected shape dimension to be (int, int)")
    else:
        raise TypeError("expected shape to be tuple of (int, int)")
164087
def _reduction_output_shape(x, output_shape, reduced_dim):
  """"""
  if output_shape is None:
    if reduced_dim is None:
      return Shape([])
    else:
      if reduced_dim not in x.shape.dims:
        raise ValueError(
            "reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
      return x.shape - reduced_dim
  if reduced_dim is not None:
    if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:
      raise ValueError(
          "reduced_dim contradicts output_shape:"
          "x=%s output_shape=%s reduced_dim=%s" %
          (x, output_shape, reduced_dim))
  return output_shape
1147700
def _parse_shape(self, space):
    
    if isinstance(space, gym.spaces.Discrete):
      return ()
    if isinstance(space, gym.spaces.Box):
      return space.shape
    raise NotImplementedError()
943969
public static void checkIdenticalShape(DMatrixRBlock A , DMatrixRBlock B ) {
        if( A.blockLength != B.blockLength )
            throw new IllegalArgumentException("Block size is different");
        if( A.numRows != B.numRows )
            throw new IllegalArgumentException("Number of rows is different");
        if( A.numCols != B.numCols )
            throw new IllegalArgumentException("NUmber of columns is different");
    }
74424
def resolve_broadcast_params(inputs, function_proto, batch_size):
    '''
    '''
    f = function_proto  # alias

    # A. Detect multiple negative dimensions (not allowed).
    negative_count = 0
    for d in f.broadcast_param.shape.dim:
        if d < 0:
            negative_count += 1
    if negative_count > 1:
        raise ValueError('Reshape: shape has multiple negative number.')

    # B. Fill negative dimensions with batch size.
    shape = tuple(
        [d if d >= 0 else batch_size for d in f.broadcast_param.shape.dim])
    return shape
1058278
def getShape(self, includeJunctions=False):
        """"""
        if self._shape is None:
            self.rebuildShape()
        if includeJunctions:
            return self._shapeWithJunctions
        return self._shape
1094301
public void addShape(Shape shape) {
		if (shape.points.length != points.length) {
			throw new RuntimeException("Attempt to morph between two shapes with different vertex counts");
		}
		
		Shape prev = (Shape) shapes.get(shapes.size()-1);
		if (equalShapes(prev, shape)) {
			shapes.add(prev);
		} else {
			shapes.add(shape);
		}
		
		if (shapes.size() == 2) {
			next = (Shape) shapes.get(1);
		}
	}
1045715
def fix_shape(source):
    
    if source.a < source.b:
        source.a, source.b = source.b, source.a
        source.err_a, source.err_b = source.err_b, source.err_a
        source.pa += 90
    return
695805
def handleSubRectangles(self, images, subRectangles):
        

        if isinstance(subRectangles, (tuple, list)):
            # xy given directly

            # Check xy
            xy = subRectangles
            if xy is None:
                xy = (0, 0)
            if hasattr(xy, '__len__'):
                if len(xy) == len(images):
                    xy = [xxyy for xxyy in xy]
                else:
                    raise ValueError("len(xy) doesn't match amount of images.")
            else:
                xy = [xy for im in images]
            xy[0] = (0, 0)

        else:
            # Calculate xy using some basic image processing

            # Check Numpy
            if np is None:
                raise RuntimeError("Need Numpy to use auto-subRectangles.")

            # First make numpy arrays if required
            for i in range(len(images)):
                im = images[i]
                if isinstance(im, Image.Image):
                    tmp = im.convert()  # Make without palette
                    a = np.asarray(tmp)
                    if len(a.shape) == 0:
                        raise MemoryError("Too little memory to convert PIL image to array")
                    images[i] = a

            # Determine the sub rectangles
            images, xy = self.getSubRectangles(images)

        # Done
        return images, xy