If the normalizedScale is equal to 1, then the image is made to fit the screen. Otherwise,
it is made to fit the screen according to the dimensions of the previous image matrix. This
allows the image to maintain its zoom after rotation.
2453
private void fitImageToView() {
        Drawable drawable = getDrawable();
        if (drawable == null || drawable.getIntrinsicWidth() == 0 || drawable.getIntrinsicHeight() == 0) {
            return;
        }
        if (matrix == null || prevMatrix == null) {
            return;
        }

        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();

        //
        // Scale image for view
        //
        float scaleX = (float) viewWidth / drawableWidth;
        float scaleY = (float) viewHeight / drawableHeight;

        switch (mScaleType) {
            case CENTER:
                scaleX = scaleY = 1;
                break;

            case CENTER_CROP:
                scaleX = scaleY = Math.max(scaleX, scaleY);
                break;

            case CENTER_INSIDE:
                scaleX = scaleY = Math.min(1, Math.min(scaleX, scaleY));

            case FIT_CENTER:
                scaleX = scaleY = Math.min(scaleX, scaleY);
                break;

            case FIT_XY:
                break;

            default:
                //
                // FIT_START and FIT_END not supported
                //
                throw new UnsupportedOperationException("TouchImageView does not support FIT_START or FIT_END");

        }

        //
        // Center the image
        //
        float redundantXSpace = viewWidth - (scaleX * drawableWidth);
        float redundantYSpace = viewHeight - (scaleY * drawableHeight);
        matchViewWidth = viewWidth - redundantXSpace;
        matchViewHeight = viewHeight - redundantYSpace;
        if (!isZoomed() && !imageRenderedAtLeastOnce) {
            //
            // Stretch and center image to fit view
            //
            matrix.setScale(scaleX, scaleY);
            matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
            normalizedScale = 1;

        } else {
            //
            // These values should never be 0 or we will set viewWidth and viewHeight
            // to NaN in translateMatrixAfterRotate. To avoid this, call savePreviousImageValues
            // to set them equal to the current values.
            //
            if (prevMatchViewWidth == 0 || prevMatchViewHeight == 0) {
                savePreviousImageValues();
            }

            prevMatrix.getValues(m);

            //
            // Rescale Matrix after rotation
            //
            m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth * normalizedScale;
            m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight * normalizedScale;

            //
            // TransX and TransY from previous matrix
            //
            float transX = m[Matrix.MTRANS_X];
            float transY = m[Matrix.MTRANS_Y];

            //
            // Width
            //
            float prevActualWidth = prevMatchViewWidth * normalizedScale;
            float actualWidth = getImageWidth();
            translateMatrixAfterRotate(Matrix.MTRANS_X, transX, prevActualWidth, actualWidth, prevViewWidth, viewWidth, drawableWidth);

            //
            // Height
            //
            float prevActualHeight = prevMatchViewHeight * normalizedScale;
            float actualHeight = getImageHeight();
            translateMatrixAfterRotate(Matrix.MTRANS_Y, transY, prevActualHeight, actualHeight, prevViewHeight, viewHeight, drawableHeight);

            //
            // Set the matrix to the adjusted scale and translate values.
            //
            matrix.setValues(m);
        }
        fixTrans();
        setImageMatrix(matrix);
    }
894737
function () {
            // Sets properties of '_features' that change on resize and/or orientation.
            var w   = win.innerWidth || _viewport.clientWidth,
                h   = win.innerHeight || _viewport.clientHeight,
                dw  = win.screen.width,
                dh  = win.screen.height,
                c   = win.screen.colorDepth,
                x   = win.devicePixelRatio;

            _features.width                     = w;
            _features.height                    = h;
            _features['aspect-ratio']           = (w / h).toFixed(2);
            _features['device-width']           = dw;
            _features['device-height']          = dh;
            _features['device-aspect-ratio']    = (dw / dh).toFixed(2);
            _features.color                     = c;
            _features['color-index']            = Math.pow(2, c);
            _features.orientation               = (h >= w ? 'portrait' : 'landscape');
            _features.resolution                = (x && x * 96) || win.screen.deviceXDPI || 96;
            _features['device-pixel-ratio']     = x || 1;
        }
1203740
public Planed normalize(Planed dest) {
        double invLength = 1.0 / Math.sqrt(a * a + b * b + c * c);
        dest.a = a * invLength;
        dest.b = b * invLength;
        dest.c = c * invLength;
        dest.d = d * invLength;
        return dest;
    }
549542
function resizeImage(ctx, imageData, width, height) {
  const {naturalWidth, naturalHeight} = imageData;
  if (width === naturalWidth && height === naturalHeight) {
    return imageData;
  }

  ctx.canvas.height = height;
  ctx.canvas.width = width;

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  // image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
  ctx.drawImage(imageData, 0, 0, naturalWidth, naturalHeight, 0, 0, width, height);

  return ctx.canvas;
}
918349
public static Bitmap shrink(Bitmap bitmap, float scale) {
        if (scale >= 1.0f) {
            return bitmap.copy(bitmap.getConfig(), false);
        }

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        return Bitmap.createBitmap(bitmap, 0, 0, (int) (scale * bitmap.getWidth()), (int) (scale * bitmap.getHeight()), matrix, true);
    }
532141
public final void normalize() {
		double norm;

		norm = (this.x*this.x + this.y*this.y + this.z*this.z + this.w*this.w);

		if (norm > 0f) {
			norm = 1f / Math.sqrt(norm);
			this.x *= norm;
			this.y *= norm;
			this.z *= norm;
			this.w *= norm;
		} else {
			this.x = 0f;
			this.y = 0f;
			this.z = 0f;
			this.w = 0f;
		}
	}
234359
public void normalize() {
        double lenSqr = x * x + y * y + z * z;
        double err = lenSqr - 1;
        if (err > (2 * DOUBLE_PREC) || err < -(2 * DOUBLE_PREC)) {
            double len = Math.sqrt(lenSqr);
            x /= len;
            y /= len;
            z /= len;
        }
    }
128124
public boolean process() {
		int numViews = depths.numRows;
		int numFeatures = depths.numCols;
		P.reshape(3*numViews,4);
		X.reshape(4,numFeatures);

		A.reshape(numViews*3,numFeatures);
		B.reshape(numViews*3,numFeatures);

		// Scale depths so that they are close to unity
		normalizeDepths(depths);

		// Compute the initial A matirx
		assignValuesToA(A);

		for (int iter = 0; iter < maxIterations; iter++) {
			if( !svd.decompose(A) )
				return false;

			svd.getU(U,false);
			svd.getV(Vt,true);
			double sv[] = svd.getSingularValues();

			SingularOps_DDRM.descendingOrder(U,false,sv,A.numCols,Vt,true);

			// This is equivalent to forcing the rank to be 4
			CommonOps_DDRM.extract(U,0,0,P);
			CommonOps_DDRM.multCols(P,sv);
			CommonOps_DDRM.extract(Vt,0,0,X);

			// Compute the new value of A
			CommonOps_DDRM.mult(P,X,B);

			// See how much change there is
			double delta = SpecializedOps_DDRM.diffNormF(A,B)/(A.numCols*A.numRows);

			// swap arrays for the next iteration
			DMatrixRMaj tmp = A;
			A = B;
			B = tmp;

			// exit if converged
			if( delta <= minimumChangeTol )
				break;
		}

		return true;
	}
385419
def _fits_surface(self, width, height):
        
        assert(width > 0 and height > 0)
        if self.rot and (width > self.width or height > self.height):
            width, height = height, width

        if width > self.width or height > self.height:
            return False
        else:
            return True
918789
def size_when_fitting(target, dimensions = get_base_dimensions)
      zoom = [
        dimensions[:width].to_f / target[:width],
        dimensions[:height].to_f / target[:height]
      ].max

      if zoom == 0.0
        width = target[:width]
        height = target[:height]
      else
        width = (dimensions[:width] / zoom).round
        height = (dimensions[:height] / zoom).round
      end

      {width: width.to_i, height: height.to_i}
    end
478029
private void resize() {
        width                        = getWidth() - getInsets().getLeft() - getInsets().getRight();
        height                       = getHeight() - getInsets().getTop() - getInsets().getBottom();
        pixelSize                    = (width / cols) < (height / rows) ? (width / cols) : (height / rows);
        pixelWidth                   = (width / cols);
        pixelHeight                  = (height / rows);
        spacer                       = useSpacer ? pixelSize * getSpacerSizeFactor() : 0;
        pixelSizeMinusDoubleSpacer   = pixelSize - spacer * 2;
        pixelWidthMinusDoubleSpacer  = pixelWidth - spacer * 2;
        pixelHeightMinusDoubleSpacer = pixelHeight - spacer * 2;


        if (width > 0 && height > 0) {
            if (squarePixels) {
                pixelWidth                   = pixelSize;
                pixelHeight                  = pixelSize;
                pixelWidthMinusDoubleSpacer  = pixelSizeMinusDoubleSpacer;
                pixelHeightMinusDoubleSpacer = pixelSizeMinusDoubleSpacer;
            }
            canvas.setWidth(cols * pixelWidth);
            canvas.setHeight(rows * pixelHeight);

            canvas.relocate((getWidth() - (cols *pixelWidth)) * 0.5, (getHeight() - (rows * pixelHeight)) * 0.5);

            drawMatrix();
        }
    }
495529
def correct(self, image, keepSize=False, borderValue=0):
        '''
        
        '''
        image = imread(image)
        (h, w) = image.shape[:2]
        mapx, mapy = self.getUndistortRectifyMap(w, h)
        self.img = cv2.remap(image, mapx, mapy, cv2.INTER_LINEAR,
                             borderMode=cv2.BORDER_CONSTANT,
                             borderValue=borderValue
                             )
        if not keepSize:
            xx, yy, ww, hh = self.roi
            self.img = self.img[yy: yy + hh, xx: xx + ww]
        return self.img
761829
function downScaleCanvas(cv, scale) {
  if (!(scale < 1) || !(scale > 0)) throw ('scale must be a positive number <1 ');
  scale = normaliseScale(scale);
  var tBuffer = new Float32Array(3 * cv.width * cv.height) // temporary buffer Float32 rgb
  var sqScale = scale * scale; // square scale =  area of a source pixel within target
  var sw = cv.width; // source image width
  var sh = cv.height; // source image height
  var tw = Math.floor(sw * scale); // target image width
  var th = Math.floor(sh * scale); // target image height
  var sx = 0, sy = 0, sIndex = 0; // source x,y, index within source array
  var tx = 0, ty = 0, yIndex = 0, tIndex = 0; // target x,y, x,y index within target array
  var tX = 0, tY = 0; // rounded tx, ty
  var w = 0, nw = 0, wx = 0, nwx = 0, wy = 0, nwy = 0; // weight / next weight x / y
  // weight is weight of current source point within target.
  // next weight is weight of current source point within next target's point.
  var crossX = false; // does scaled px cross its current px right border ?
  var crossY = false; // does scaled px cross its current px bottom border ?
  var sBuffer = cv.getContext('2d').getImageData(0, 0, sw, sh).data; // source buffer 8 bit rgba
  var sR = 0, sG = 0,  sB = 0; // source's current point r,g,b

  for (sy = 0; sy < sh; sy++) {
    ty = sy * scale; // y src position within target
    tY = 0 | ty;     // rounded : target pixel's y
    yIndex = 3 * tY * tw;  // line index within target array
    crossY = (tY !== (0 | ( ty + scale )));
    if (crossY) { // if pixel is crossing botton target pixel
      wy = (tY + 1 - ty); // weight of point within target pixel
      nwy = (ty + scale - tY - 1); // ... within y+1 target pixel
    }
    for (sx = 0; sx < sw; sx++, sIndex += 4) {
      tx = sx * scale; // x src position within target
      tX = 0 |  tx;    // rounded : target pixel's x
      tIndex = yIndex + tX * 3; // target pixel index within target array
      crossX = (tX !== (0 | (tx + scale)));
      if (crossX) { // if pixel is crossing target pixel's right
        wx = (tX + 1 - tx); // weight of point within target pixel
        nwx = (tx + scale - tX - 1); // ... within x+1 target pixel
      }
      sR = sBuffer[sIndex    ];   // retrieving r,g,b for curr src px.
      sG = sBuffer[sIndex + 1];
      sB = sBuffer[sIndex + 2];
      if (!crossX && !crossY) { // pixel does not cross
        // just add components weighted by squared scale.
        tBuffer[tIndex    ] += sR * sqScale;
        tBuffer[tIndex + 1] += sG * sqScale;
        tBuffer[tIndex + 2] += sB * sqScale;
      } else if (crossX && !crossY) { // cross on X only
        w = wx * scale;
        // add weighted component for current px
        tBuffer[tIndex    ] += sR * w;
        tBuffer[tIndex + 1] += sG * w;
        tBuffer[tIndex + 2] += sB * w;
        // add weighted component for next (tX+1) px
        nw = nwx * scale
        tBuffer[tIndex + 3] += sR * nw;
        tBuffer[tIndex + 4] += sG * nw;
        tBuffer[tIndex + 5] += sB * nw;
      } else if (!crossX && crossY) { // cross on Y only
        w = wy * scale;
        // add weighted component for current px
        tBuffer[tIndex    ] += sR * w;
        tBuffer[tIndex + 1] += sG * w;
        tBuffer[tIndex + 2] += sB * w;
        // add weighted component for next (tY+1) px
        nw = nwy * scale
        tBuffer[tIndex + 3 * tw    ] += sR * nw;
        tBuffer[tIndex + 3 * tw + 1] += sG * nw;
        tBuffer[tIndex + 3 * tw + 2] += sB * nw;
      } else { // crosses both x and y : four target points involved
        // add weighted component for current px
        w = wx * wy;
        tBuffer[tIndex    ] += sR * w;
        tBuffer[tIndex + 1] += sG * w;
        tBuffer[tIndex + 2] += sB * w;
        // for tX + 1; tY px
        nw = nwx * wy;
        tBuffer[tIndex + 3] += sR * nw;
        tBuffer[tIndex + 4] += sG * nw;
        tBuffer[tIndex + 5] += sB * nw;
        // for tX ; tY + 1 px
        nw = wx * nwy;
        tBuffer[tIndex + 3 * tw    ] += sR * nw;
        tBuffer[tIndex + 3 * tw + 1] += sG * nw;
        tBuffer[tIndex + 3 * tw + 2] += sB * nw;
        // for tX + 1 ; tY +1 px
        nw = nwx * nwy;
        tBuffer[tIndex + 3 * tw + 3] += sR * nw;
        tBuffer[tIndex + 3 * tw + 4] += sG * nw;
        tBuffer[tIndex + 3 * tw + 5] += sB * nw;
      }
    } // end for sx
  } // end for sy

  // create result canvas
  var resCV = document.createElement('canvas');
  resCV.width = tw;
  resCV.height = th;
  var resCtx = resCV.getContext('2d');

//    var imgRes = resCtx.getImageData(resCV.width/2 - tw/2, resCV.height/2 - th/2, tw, th);
  var imgRes = resCtx.getImageData(0, 0, tw, th);
  var tByteBuffer = imgRes.data;
  // convert float32 array into a UInt8Clamped Array
  var pxIndex = 0; //
  for (sIndex = 0, tIndex = 0; pxIndex < tw * th; sIndex += 3, tIndex += 4, pxIndex++) {
    tByteBuffer[tIndex] = 0 | ( tBuffer[sIndex]);
    tByteBuffer[tIndex + 1] = 0 | (tBuffer[sIndex + 1]);
    tByteBuffer[tIndex + 2] = 0 | (tBuffer[sIndex + 2]);
    tByteBuffer[tIndex + 3] = 255;
    // set back temp buffer
    tBuffer[sIndex] = 0
    tBuffer[sIndex + 1] = 0
    tBuffer[sIndex + 2] = 0
  }

  // writing result to canvas.
  resCtx.putImageData(imgRes, 0, 0);
  return resCV;

}
788022
def apply_scale(self, scale):
        
        dimension = self.vertices.shape[1]
        matrix = np.eye(dimension + 1)
        matrix[:dimension, :dimension] *= scale
        self.apply_transform(matrix)
797836
function () {
            var state = this.state,
                fitWidth = this.calculateZoomValue(ZOOM_FIT_WIDTH),
                fitHeight = this.calculateZoomValue(ZOOM_FIT_HEIGHT);

            // landscape
            if (state.widestPage.actualWidth > state.tallestPage.actualHeight) {
                return Math.min(fitWidth, fitHeight);
            }
            // portrait
            else {
                if (browser.mobile) {
                    return fitHeight;
                }
                // limit max zoom to 1.0
                return Math.min(1, fitHeight);
            }
        }
358304
def fitToSize(rect, targetWidth, targetHeight, bounds):
	
	
	# Determine the difference between the current size and target size
	x,y,w,h = rect
	diffX = w - targetWidth
	diffY = h - targetHeight
	
	# Determine if we are cropping or padding the width
	if diffX > 0:
		cropLeft  = math.floor(diffX / 2)
		cropRight = diffX - cropLeft
		x,y,w,h   = cropRect((x,y,w,h), 0, 0, cropLeft, cropRight)
	elif diffX < 0:
		padLeft  = math.floor(abs(diffX) / 2)
		padRight = abs(diffX) - padLeft
		x,y,w,h  = padRect((x,y,w,h), 0, 0, padLeft, padRight, bounds, False)
	
	# Determine if we are cropping or padding the height
	if diffY > 0:
		cropTop    = math.floor(diffY / 2)
		cropBottom = diffY - cropTop
		x,y,w,h    = cropRect((x,y,w,h), cropTop, cropBottom, 0, 0)
	elif diffY < 0:
		padTop    = math.floor(abs(diffY) / 2)
		padBottom = abs(diffY) - padTop
		x,y,w,h   = padRect((x,y,w,h), padTop, padBottom, 0, 0, bounds, False)
	
	return (x,y,w,h)
1205767
public void setCamera( double skew , double cx , double cy , int width , int height ) {

		// Define normalization matrix
		// center points, remove skew, scale coordinates
		double d = Math.sqrt(width*width + height*height);
		V.zero();
		V.set(0,0,d/2); V.set(0,1,skew); V.set(0,2,cx);
		V.set(1,1,d/2); V.set(1,2,cy);
		V.set(2,2,1);

		CommonOps_DDRM.invert(V,Vinv);
	}