Calculate ewald real part. Box has to be a cuboidal box you should
    transform any other box shape to a cuboidal box before using this.
501334
def _real(coords1, charges1, coords2, charges2, rcut, alpha, box):
    
    n = coords1.shape[0]
    m = coords2.shape[0]
    # Unit vectors
    a = box[0]
    b = box[1]
    c = box[2]
    
    
    # This is helpful to add the correct number of boxes
    l_max = int(np.ceil(2.0 * rcut / np.min(np.trace(box))))
    result = np.zeros(n)
    
    
    for i in range(n):
        q_i = charges1[i]
        r_i = coords1[i]

        for j in range(m):
            q_j = charges2[j]
            r_j = coords2[j]

            for l_i in range(-l_max, l_max + 1):
                for l_j in range(-l_max, l_max + 1):
                    for l_k in range(-l_max, l_max + 1):
                        nv = l_i * a + l_j * b + l_k * c
                        r_j_n = r_j + nv
                        
                        r_ij = _dist(r_i, r_j_n)
                        if r_ij < 1e-10 or r_ij > rcut:
                            continue
                        value = q_i * q_j * math.erfc(alpha * r_ij) / r_ij
                        result[i] += value

    return result
1353269
function(shape, context, top) {
            var m = shape.getAbsoluteTransform(top).getMatrix();
            context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
        }
703549
@SuppressWarnings("deprecation")
   private void updateParentBoundingBox(SvgElement obj)
   {
      if (obj.parent == null)       // skip this if obj is root element
         return;
      if (obj.boundingBox == null)  // empty bbox, possibly as a result of a badly defined element (eg bad use reference etc)
         return;

      // Convert the corners of the child bbox to world space
      Matrix  m = new Matrix();
      // Get the inverse of the child transform
      if (matrixStack.peek().invert(m)) {
         float[] pts = {obj.boundingBox.minX, obj.boundingBox.minY,
                        obj.boundingBox.maxX(), obj.boundingBox.minY,
                        obj.boundingBox.maxX(), obj.boundingBox.maxY(),
                        obj.boundingBox.minX, obj.boundingBox.maxY()};
         // Now concatenate the parent's matrix to create a child-to-parent transform
         m.preConcat(canvas.getMatrix());
         m.mapPoints(pts);
         // Finally, find the bounding box of the transformed points
         RectF  rect = new RectF(pts[0], pts[1], pts[0], pts[1]);
         for (int i=2; i<=6; i+=2) {
            if (pts[i] < rect.left) rect.left = pts[i]; 
            if (pts[i] > rect.right) rect.right = pts[i]; 
            if (pts[i+1] < rect.top) rect.top = pts[i+1]; 
            if (pts[i+1] > rect.bottom) rect.bottom = pts[i+1]; 
         }
         // Update the parent bounding box with the transformed bbox
         SvgElement  parent = (SvgElement) parentStack.peek();
         if (parent.boundingBox == null)
            parent.boundingBox = Box.fromLimits(rect.left, rect.top, rect.right, rect.bottom);
         else
            parent.boundingBox.union(Box.fromLimits(rect.left, rect.top, rect.right, rect.bottom));
      }
   }
629062
protected void updateBox ()
    {
        int hmin = _horz.getMinimum();
        int vmin = _vert.getMinimum();
        _hFactor = (_active.width) / (float) (_horz.getMaximum() - hmin);
        _vFactor = (_active.height) / (float) (_vert.getMaximum() - vmin);

        _box.x = _active.x + Math.round((_horz.getValue() - hmin) * _hFactor);
        _box.width = Math.round(_horz.getExtent() * _hFactor);
        _box.y = _active.y + Math.round((_vert.getValue() - vmin) * _vFactor);
        _box.height = Math.round(_vert.getExtent() * _vFactor);
    }
20347
function shapeBox(shape) {
  let minX = shape[0][0],
    minY = shape[0][1],
    maxX = minX,
    maxY = minY;
  shape.forEach((curve) => {
    const x1 = curve[0],
      x2 = curve[2],
      x3 = curve[4],
      x4 = curve[6],
      y1 = curve[1],
      y2 = curve[3],
      y3 = curve[5],
      y4 = curve[7];

    minX = Math.min(minX, x1, x2, x3, x4);
    minY = Math.min(minY, y1, y2, y3, y4);
    maxX = Math.max(maxX, x1, x2, x3, x4);
    maxY = Math.max(maxY, y1, y2, y3, y4);
  });

  return [minX, minY, maxX, maxY];
}
791184
def getBox(box, pagesize):
    
    box = str(box).split()
    if len(box) != 4:
        raise Exception("box not defined right way")
    x, y, w, h = [getSize(pos) for pos in box]
    return getCoords(x, y, w, h, pagesize)
891490
def bounding_box(self):
        

        w2 = self.width / 2.
        h2 = self.height / 2.
        cos_angle = np.cos(self.angle)    # self.angle is a Quantity
        sin_angle = np.sin(self.angle)    # self.angle is a Quantity
        dx1 = abs(w2 * cos_angle - h2 * sin_angle)
        dy1 = abs(w2 * sin_angle + h2 * cos_angle)
        dx2 = abs(w2 * cos_angle + h2 * sin_angle)
        dy2 = abs(w2 * sin_angle - h2 * cos_angle)
        dx = max(dx1, dx2)
        dy = max(dy1, dy2)

        xmin = self.center.x - dx
        xmax = self.center.x + dx
        ymin = self.center.y - dy
        ymax = self.center.y + dy

        return BoundingBox.from_float(xmin, xmax, ymin, ymax)
1071838
function HexSphere(r, level) {
  r = r || 0.5;
  level = level || 1;

  var baseGeom = new Icosahedron(r);
  for(var i=0; i<level; i++) {
    baseGeom = baseGeom.subdivideEdges();
  }

  var vertices = [];
  var faces = [];


  var halfEdgeForVertex = [];
  var halfEdges = baseGeom.computeHalfEdges();
  halfEdges.forEach(function(e) {
    halfEdgeForVertex[e.face[e.slot]] = e;
  });

  for(var i=0; i<baseGeom.vertices.length; i++) {
    var vertexIndex = vertices.length;
    var midPoints = [];
    //collect center points of neighbor faces
    vertexEdgeLoop(halfEdgeForVertex[i], function(e) {
      var midPoint = centroid(elements(baseGeom.vertices, e.face));
      midPoints.push(midPoint);
    });
    midPoints.forEach(function(p, i){
      vertices.push(p);
    });
    if (midPoints.length == 5) {
      faces.push([vertexIndex, vertexIndex+1, vertexIndex+2, vertexIndex+3, vertexIndex+4]);
    }
    if (midPoints.length == 6) {
      faces.push([vertexIndex, vertexIndex+1, vertexIndex+2, vertexIndex+3, vertexIndex+4, vertexIndex+5]);
    }
  }

  vertices.forEach(function(v) {
    v.normalize().scale(r);
  });

  Geometry.call(this, { vertices: vertices, faces: faces });

  this.computeEdges();
}
594278
def _solidAngleMMD(self):
        
        # Take upper corner of the magnitude bin
        mag_2,mag_1 = np.meshgrid(self.roi.bins_mag[1:],self.roi.bins_mag[1:])

        # Havent tested since adding fracdet
        unmasked_mag_1 = (self.mask_1.mask_annulus_sparse[:,np.newaxis]>mag_1[:,np.newaxis])
        unmasked_mag_2 = (self.mask_2.mask_annulus_sparse[:,np.newaxis]>mag_2[:,np.newaxis])
        n_unmasked_pixels = (unmasked_mag_1*unmasked_mag_2*self.frac_annulus_sparse).sum(axis=1)

        self.solid_angle_mmd = self.roi.area_pixel * n_unmasked_pixels

        if self.solid_angle_mmd.sum() == 0:
            msg = "Mask annulus contains no solid angle."
            logger.error(msg)
            raise Exception(msg)
1134030
def get_blocks_3d(A, blocksizes, pagesizes=None):
    
    assert (A.shape[0]==A.shape[1]) and len(A.shape)==3, "can't blockify this non-square matrix, may need to use 2d version"
    N = np.sum(blocksizes)
    assert A.shape[0] == N, "bad blocksizes"
    num_blocks = len(blocksizes)
    if pagesizes == None:
        #Assume each page of A should be its own dimension
        pagesizes = range(A.shape[2])#[0]*A.shape[2]
    num_pages = len(pagesizes)
    B = np.empty(shape=(num_blocks, num_blocks, num_pages), dtype=np.object)
    count_k = 0
    #for Bk, k in enumerate(pagesizes):
    for Bk in pagesizes:
        count_i = 0
        for Bi, i in enumerate(blocksizes):
            count_j = 0
            for Bj, j in enumerate(blocksizes):
                #We want to have it count_k:count_k + k but its annoying as it makes a NxNx1 array is page sizes are set to 1
                B[Bi, Bj, Bk] = A[count_i:count_i + i, count_j:count_j + j, Bk]
                count_j += j
            count_i += i
        #count_k += k
    return B
434517
protected void		calcWorld(Bone bone, int parentId)
    {
        getWorldMatrix(parentId, mTempMtxB);   // WorldMatrix (parent) TempMtxB
        mTempMtxB.mul(bone.LocalMatrix);       // WorldMatrix = WorldMatrix(parent) * LocalMatrix
        bone.WorldMatrix.set(mTempMtxB);
     }
122161
function(shape, context, top) {
            if (!top || top._id !== this._id) {
                var m = shape.getTransform().getMatrix();
                context.transform(m[0], m[1], m[2], m[3], m[4], m[5]);
            }
        }
757776
def __shapefileHeader(self, fileObj, headerType='shp'):
        """"""
        f = self.__getFileObj(fileObj)
        f.seek(0)
        # File code, Unused bytes
        f.write(pack(">6i", 9994,0,0,0,0,0))
        # File length (Bytes / 2 = 16-bit words)
        if headerType == 'shp':
            f.write(pack(">i", self.__shpFileLength()))
        elif headerType == 'shx':
            f.write(pack('>i', ((100 + (self.shpNum * 8)) // 2)))
        # Version, Shape type
        if self.shapeType is None:
            self.shapeType = NULL
        f.write(pack("<2i", 1000, self.shapeType))
        # The shapefile's bounding box (lower left, upper right)
        if self.shapeType != 0:
            try:
                bbox = self.bbox()
                if bbox is None:
                    # The bbox is initialized with None, so this would mean the shapefile contains no valid geometries.
                    # In such cases of empty shapefiles, ESRI spec says the bbox values are 'unspecified'.
                    # Not sure what that means, so for now just setting to 0s, which is the same behavior as in previous versions.
                    # This would also make sense since the Z and M bounds are similarly set to 0 for non-Z/M type shapefiles.
                    bbox = [0,0,0,0] 
                f.write(pack("<4d", *bbox))
            except error:
                raise ShapefileException("Failed to write shapefile bounding box. Floats required.")
        else:
            f.write(pack("<4d", 0,0,0,0))
        # Elevation
        if self.shapeType in (11,13,15,18):
            # Z values are present in Z type
            zbox = self.zbox()
        else:
            # As per the ESRI shapefile spec, the zbox for non-Z type shapefiles are set to 0s
            zbox = [0,0]
        # Measure
        if self.shapeType in (11,13,15,18,21,23,25,28,31):
            # M values are present in M or Z type
            mbox = self.mbox()
        else:
            # As per the ESRI shapefile spec, the mbox for non-M type shapefiles are set to 0s
            mbox = [0,0]
        # Try writing
        try:
            f.write(pack("<4d", zbox[0], zbox[1], mbox[0], mbox[1]))
        except error:
            raise ShapefileException("Failed to write shapefile elevation and measure values. Floats required.")
967410
function calcBBox(node, toBBox) {
    distBBox(node, 0, node.children.length, toBBox, node);
}
448726
function(e, local, decoratee, absolute, smoothOrigin) {
				var tm = e._gsTransform,
					m = _getMatrix(e, true),
					v, x, y, xOrigin, yOrigin, a, b, c, d, tx, ty, determinant, xOriginOld, yOriginOld;
				if (tm) {
					xOriginOld = tm.xOrigin; //record the original values before we alter them.
					yOriginOld = tm.yOrigin;
				}
				if (!absolute || (v = absolute.split(" ")).length < 2) {
					b = e.getBBox();
					local = _parsePosition(local).split(" ");
					v = [(local[0].indexOf("%") !== -1 ? parseFloat(local[0]) / 100 * b.width : parseFloat(local[0])) + b.x,
						 (local[1].indexOf("%") !== -1 ? parseFloat(local[1]) / 100 * b.height : parseFloat(local[1])) + b.y];
				}
				decoratee.xOrigin = xOrigin = parseFloat(v[0]);
				decoratee.yOrigin = yOrigin = parseFloat(v[1]);
				if (absolute && m !== _identity2DMatrix) { //if svgOrigin is being set, we must invert the matrix and determine where the absolute point is, factoring in the current transforms. Otherwise, the svgOrigin would be based on the element's non-transformed position on the canvas.
					a = m[0];
					b = m[1];
					c = m[2];
					d = m[3];
					tx = m[4];
					ty = m[5];
					determinant = (a * d - b * c);
					x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + ((c * ty - d * tx) / determinant);
					y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - ((a * ty - b * tx) / determinant);
					xOrigin = decoratee.xOrigin = v[0] = x;
					yOrigin = decoratee.yOrigin = v[1] = y;
				}
				if (tm) { //avoid jump when transformOrigin is changed - adjust the x/y values accordingly
					if (smoothOrigin || (smoothOrigin !== false && CSSPlugin.defaultSmoothOrigin !== false)) {
						x = xOrigin - xOriginOld;
						y = yOrigin - yOriginOld;
						//originally, we simply adjusted the x and y values, but that would cause problems if, for example, you created a rotational tween part-way through an x/y tween. Managing the offset in a separate variable gives us ultimate flexibility.
						//tm.x -= x - (x * m[0] + y * m[2]);
						//tm.y -= y - (x * m[1] + y * m[3]);
						tm.xOffset += (x * m[0] + y * m[2]) - x;
						tm.yOffset += (x * m[1] + y * m[3]) - y;
					} else {
						tm.xOffset = tm.yOffset = 0;
					}
				}
				e.setAttribute("data-svg-origin", v.join(" "));
			}
638547
function(
      x, y, padding, width, height, centerX, centerY) {
      
      var cornerRadius = $$.math.getRoundRectangleRadius(width, height);
      
      // Check hBox
      if ($$.math.pointInsidePolygon(x, y, nodeShapes['roundrectangle'].points,
        centerX, centerY, width, height - 2 * cornerRadius, [0, -1], padding)) {
        return true;
      }
      
      // Check vBox
      if ($$.math.pointInsidePolygon(x, y, nodeShapes['roundrectangle'].points,
        centerX, centerY, width - 2 * cornerRadius, height, [0, -1], padding)) {
        return true;
      }
      
      var checkInEllipse = function(x, y, centerX, centerY, width, height, padding) {
        x -= centerX;
        y -= centerY;
        
        x /= (width / 2 + padding);
        y /= (height / 2 + padding);
        
        return (Math.pow(x, 2) + Math.pow(y, 2) <= 1);
      }
      
      
      // Check top left quarter circle
      if (checkInEllipse(x, y,
        centerX - width / 2 + cornerRadius,
        centerY - height / 2 + cornerRadius,
        cornerRadius * 2, cornerRadius * 2, padding)) {
        
        return true;
      }
      
      /*
      if (renderer.boxIntersectEllipse(x, y, x, y, padding, 
        cornerRadius * 2, cornerRadius * 2,
        centerX - width + cornerRadius,
        centerY - height + cornerRadius)) {
        return true;
      }
      */
      
      // Check top right quarter circle
      if (checkInEllipse(x, y,
        centerX + width / 2 - cornerRadius,
        centerY - height / 2 + cornerRadius,
        cornerRadius * 2, cornerRadius * 2, padding)) {
        
        return true;
      }
      
      // Check bottom right quarter circle
      if (checkInEllipse(x, y,
        centerX + width / 2 - cornerRadius,
        centerY + height / 2 - cornerRadius,
        cornerRadius * 2, cornerRadius * 2, padding)) {
        
        return true;
      }
      
      // Check bottom left quarter circle
      if (checkInEllipse(x, y,
        centerX - width / 2 + cornerRadius,
        centerY + height / 2 - cornerRadius,
        cornerRadius * 2, cornerRadius * 2, padding)) {
        
        return true;
      }
      
      return false;
    }
39682
protected boolean fit2D(List<Box> containerProducts, Container holder, Box usedSpace, Space freeSpace, BooleanSupplier interrupt) {

		if(rotate3D) {
			// minimize footprint
			usedSpace.fitRotate3DSmallestFootprint(freeSpace);
		}

		// add used space box now, but possibly rotate later - this depends on the actual remaining free space selected further down
		// there is up to possible 4 free spaces, 2 in which the used space box is rotated
		holder.add(new Placement(freeSpace, usedSpace));

		if(containerProducts.isEmpty()) {
			// no additional boxes
			// just make sure the used space fits in the free space
			usedSpace.fitRotate2D(freeSpace);

			return true;
		}

		if(interrupt.getAsBoolean()) {
			return false;
		}

		Space[] spaces = getFreespaces(freeSpace, usedSpace);

		Placement nextPlacement = getBestBoxAndSpace(containerProducts, spaces, holder.getFreeWeight());
		if(nextPlacement == null) {
			// no additional boxes along the level floor (x,y)
			// just make sure the used space fits in the free space
			usedSpace.fitRotate2D(freeSpace);
		} else {
			// check whether the selected free space requires the used space box to be rotated
			if(nextPlacement.getSpace() == spaces[2] || nextPlacement.getSpace() == spaces[3]) {
				// the desired space implies that we rotate the used space box
				usedSpace.rotate2D();
			}
	
			// holder.validateCurrentLevel(); // uncomment for debugging
	
			removeIdentical(containerProducts, nextPlacement.getBox());
	
			// attempt to fit in the remaining (usually smaller) space first
	
			// stack in the 'sibling' space - the space left over between the used box and the selected free space
			Space remainder = nextPlacement.getSpace().getRemainder();
			if(remainder.nonEmpty()) {
				Box box = getBestBoxForSpace(containerProducts, remainder, holder.getFreeWeight());
				if(box != null) {
					removeIdentical(containerProducts, box);
	
					if(!fit2D(containerProducts, holder, box, remainder, interrupt)) {
						return false;
					}
				}
			}
			// double check that there is still free weight
			// TODO possibly rewind if the value of the boxes in the remainder is lower than the one in next placement
			if(holder.getFreeWeight() >= nextPlacement.getBox().getWeight()) {
				if(!fit2D(containerProducts, holder, nextPlacement.getBox(), nextPlacement.getSpace(), interrupt)) {
					return false;
				}
			}
		} 
		
		// also use the space above the placed box, if any.
		if(freeSpace.getHeight() > usedSpace.getHeight()) {
			// so there is some free room; between the used space and the level height

			// the level by level approach is somewhat crude, but at least some of the inefficiency
			// can be avoided this way
			Space above;
			if(nextPlacement == null) {
				// full width / depth
				above = new Space(
						freeSpace.getWidth(), 
						freeSpace.getDepth(), 
						freeSpace.getHeight() - usedSpace.getHeight(),
						freeSpace.getX(),
						freeSpace.getY(),
						freeSpace.getZ() + usedSpace.getHeight()
						);
			} else {
				// just directly above the used space
				
				// TODO possible include the sibling space if no box was fitted there
				above = new Space(
						usedSpace.getWidth(), 
						usedSpace.getDepth(), 
						freeSpace.getHeight() - usedSpace.getHeight(),
						freeSpace.getX(),
						freeSpace.getY(),
						freeSpace.getZ() + usedSpace.getHeight()
						);
			}
			int currentIndex = getBestBox(holder, above, containerProducts);

			if(currentIndex != -1) {
				// should be within weight already
				Box currentBox = containerProducts.get(currentIndex); 
				
				containerProducts.remove(currentIndex);
				
				if(!fit2D(containerProducts, holder, currentBox, above, interrupt)) {
					return false;
				}
			}
		}
		
		return true;
	}