Based on the code of http://themetalmuncher.github.io/fov-calc/
337201
function getVerticalFOV(hFov, aspectRatio) {
  var hFovRad = hFov * Math.PI / 180;
  var vFovRad = 2 * Math.atan(Math.tan(hFovRad / 2) / aspectRatio);
  return vFovRad * 180 / Math.PI;
}
621921
def _vmomentsurfaceIntegrand(vR,vT,R,az,df,n,m,sigmaR1,sigmaT1,t,initvmoment):
    """"""
    o= Orbit([R,vR*sigmaR1,vT*sigmaT1,az])
    return vR**n*vT**m*df(o,t)/initvmoment
1276475
private void calchillshade( WritableRaster pitWR, WritableRaster hillshadeWR, WritableRaster gradientWR, double dx ) {

        pAzimuth = Math.toRadians(pAzimuth);
        pElev = Math.toRadians(pElev);

        double[] sunVector = calcSunVector();
        double[] normalSunVector = calcNormalSunVector(sunVector);
        double[] inverseSunVector = calcInverseSunVector(sunVector);
        int rows = pitWR.getHeight();
        int cols = pitWR.getWidth();
        WritableRaster sOmbraWR = calculateFactor(rows, cols, sunVector, inverseSunVector, normalSunVector, pitWR, dx);
        pm.beginTask(msg.message("hillshade.calculating"), rows * cols);
        for( int j = 1; j < rows - 1; j++ ) {
            for( int i = 1; i < cols - 1; i++ ) {

                double[] ng = gradientWR.getPixel(i, j, new double[3]);
                double cosinc = scalarProduct(sunVector, ng);
                if (cosinc < 0) {
                    sOmbraWR.setSample(i, j, 0, 0);
                }
                hillshadeWR.setSample(i, j, 0, (int) (212.5 * (cosinc * sOmbraWR.getSample(i, j, 0) + pMinDiffuse)));
                pm.worked(1);
            }
        }
        pm.done();
    }
894471
function(min, max) {
    return function limitVfov(params) {
      params.fov = clamp(params.fov, min, max);
      return params;
    };
  }
1038543
function _calcScaling() {
        var $sb = _getScrollbar(editor);

        trackHt = $sb[0].offsetHeight;

        if (trackHt > 0) {
            trackOffset = getScrollbarTrackOffset();
            trackHt -= trackOffset * 2;
        } else {
            // No scrollbar: use the height of the entire code content
            var codeContainer = $(editor.getRootElement()).find("> .CodeMirror-scroll > .CodeMirror-sizer > div > .CodeMirror-lines > div")[0];
            trackHt = codeContainer.offsetHeight;
            trackOffset = codeContainer.offsetTop;
        }
    }
627296
def get_translation_speed(self, distance_from_target):
        
        return (distance_from_target *
                np.tan(self.fov_deg / 2.0 / 180.0 * np.pi))
1247614
def obfn_fvar(self, i):
        
        """

        return self.X[..., i] if self.opt['fEvalX'] else self.Y
602717
function calculateMirrorOffset({sensorEvent, sourceRect, options, ...args}) {
  return withPromise((resolve) => {
    const top = options.cursorOffsetY === null ? sensorEvent.clientY - sourceRect.top : options.cursorOffsetY;
    const left = options.cursorOffsetX === null ? sensorEvent.clientX - sourceRect.left : options.cursorOffsetX;

    const mirrorOffset = {top, left};

    resolve({sensorEvent, sourceRect, mirrorOffset, options, ...args});
  });
}
832519
def calc_retinotopy(note, error, subject, clean, run_lh, run_rh,
                    invert_rh_angle, max_in_eccen, min_in_eccen,
                    angle_lh_file, theta_lh_file,
                    eccen_lh_file, rho_lh_file,
                    weight_lh_file, radius_lh_file,
                    angle_rh_file, theta_rh_file,
                    eccen_rh_file, rho_rh_file,
                    weight_rh_file, radius_rh_file):
    '''
    
    '''
    ctcs = {}
    for (h,ang,tht,ecc,rho,wgt,rad,run) in [
            ('lh', angle_lh_file,theta_lh_file, eccen_lh_file,rho_lh_file,
             weight_lh_file, radius_lh_file, run_lh),
            ('rh', angle_rh_file,theta_rh_file, eccen_rh_file,rho_rh_file,
             weight_rh_file, radius_rh_file, run_rh)]:
        if not run: continue
        hemi = getattr(subject, h)
        props = {}
        # load the properties or find them in the auto-properties
        if ang:
            try: props['polar_angle'] = _guess_surf_file(ang)
            except Exception: error('could not load surface file %s' % ang)
        elif tht:
            try:
                tmp = _guess_surf_file(tht)
                props['polar_angle'] = 90.0 - 180.0 / np.pi * tmp
            except Exception: error('could not load surface file %s' % tht)
        else:
            props['polar_angle'] = empirical_retinotopy_data(hemi, 'polar_angle')
        if ecc:
            try: props['eccentricity'] = _guess_surf_file(ecc)
            except Exception: error('could not load surface file %s' % ecc)
        elif rho:
            try:
                tmp = _guess_surf_file(rhp)
                props['eccentricity'] = 180.0 / np.pi * tmp
            except Exception: error('could not load surface file %s' % rho)
        else:
            props['eccentricity'] = empirical_retinotopy_data(hemi, 'eccentricity')
        if wgt:
            try: props['weight'] = _guess_surf_file(wgt)
            except Exception: error('could not load surface file %s' % wgt)
        else:
            props['weight'] = empirical_retinotopy_data(hemi, 'weight')
        if rad:
            try: props['radius'] = _guess_surf_file(rad)
            except Exception: error('could not load surface file %s' % rad)
        else:
            props['radius'] = empirical_retinotopy_data(hemi, 'radius')
        # Check for inverted rh
        if h == 'rh' and invert_rh_angle:
            props['polar_angle'] = -props['polar_angle']
        # and zero-out weights for high eccentricities
        props['weight'] = np.array(props['weight'])
        if max_in_eccen is not None:
            props['weight'][props['eccentricity'] > max_in_eccen] = 0
        if min_in_eccen is not None:
            props['weight'][props['eccentricity'] < min_in_eccen] = 0
        # Do smoothing, if requested
        if clean:
            note('Cleaning %s retinotopy...' % h.upper())
            (ang,ecc) = clean_retinotopy(hemi, retinotopy=props, mask=None, weight='weight')
            props['polar_angle']  = ang
            props['eccentricity'] = ecc
        ctcs[h] = hemi.with_prop(props)
    return {'cortices': pyr.pmap(ctcs)}
581199
def _jmomentsurfaceMCIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,mvT,n,m,o):
    """"""
    return df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,use_physical=False,
              func=(lambda x,y,z: x**n*y**m*z**o))\
              *numpy.exp(vR**2./2.+(vT-mvT)**2./2.+vz**2./2.)
300018
function perspective (fovy, aspect, near, far) {
    var f = 1.0 / Math.tan(fovy / 2)
    var nf = 1 / (near - far)

    return [
      f / aspect, 0.0, 0.0, 0.0,
      0.0, f, 0.0, 0.0,
      0.0, 0.0, (far + near) * nf, -1.0,
      0.0, 0.0, (2 * far * near) * nf, 0.0
    ]
  }
1181809
function () {

    /**
     * @type {number}
     */
    this.motionBlurFactor = 0.99;
    /**
     * Vector field lookup image
     * @type {clay.Texture2D}
     */
    this.vectorFieldTexture = new Texture2D({
        type: Texture.FLOAT,
        // minFilter: Texture.NEAREST,
        // magFilter: Texture.NEAREST,
        flipY: false
    });

    /**
     * Particle life range
     * @type {Array.<number>}
     */
    this.particleLife = [5, 20];

    this._particleType = 'point';

    /**
     * @type {number}
     */
    this._particleSize = 1;

    /**
     * @type {Array.<number>}
     */
    this.particleColor = [1, 1, 1, 1];

    /**
     * @type {number}
     */
    this.particleSpeedScaling = 1.0;

    /**
     * @type {clay.Texture2D}
     */
    this._thisFrameTexture = null;

    this._particlePass = null;
    this._spawnTexture = null;
    this._particleTexture0 = null;
    this._particleTexture1 = null;

    this._particlePointsMesh = null;

    this._surfaceFrameBuffer = null;

    this._elapsedTime = 0.0;

    this._scene = null;
    this._camera = null;

    this._lastFrameTexture = null;

    // this._temporalSS = new TemporalSS(50);

    // this._antialising = false;

    this._supersampling = 1;

    this._downsampleTextures = [];

    this._width = 512;
    this._height = 512;

    this.init();
}
456598
def _gen_reference(fixed_image, moving_image, fov_mask=None, out_file=None,
                   message=None, force_xform_code=None):
    

    if out_file is None:
        out_file = fname_presuffix(fixed_image,
                                   suffix='_reference',
                                   newpath=os.getcwd())

    # Moving images may not be RAS/LPS (more generally, transverse-longitudinal-axial)
    reoriented_moving_img = nb.as_closest_canonical(nb.load(moving_image))
    new_zooms = reoriented_moving_img.header.get_zooms()[:3]

    # Avoid small differences in reported resolution to cause changes to
    # FOV. See https://github.com/poldracklab/fmriprep/issues/512
    # A positive diagonal affine is RAS, hence the need to reorient above.
    new_affine = np.diag(np.round(new_zooms, 3))

    resampled = nli.resample_img(fixed_image,
                                 target_affine=new_affine,
                                 interpolation='nearest')

    if fov_mask is not None:
        # If we have a mask, resample again dropping (empty) samples
        # out of the FoV.
        fixednii = nb.load(fixed_image)
        masknii = nb.load(fov_mask)

        if np.all(masknii.shape[:3] != fixednii.shape[:3]):
            raise RuntimeError(
                'Fixed image and mask do not have the same dimensions.')

        if not np.allclose(masknii.affine, fixednii.affine, atol=1e-5):
            raise RuntimeError(
                'Fixed image and mask have different affines')

        # Get mask into reference space
        masknii = nli.resample_img(fixed_image,
                                   target_affine=new_affine,
                                   interpolation='nearest')
        res_shape = np.array(masknii.shape[:3])

        # Calculate a bounding box for the input mask
        # with an offset of 2 voxels per face
        bbox = np.argwhere(masknii.get_data() > 0)
        new_origin = np.clip(bbox.min(0) - 2, a_min=0, a_max=None)
        new_end = np.clip(bbox.max(0) + 2, a_min=0,
                          a_max=res_shape - 1)

        # Find new origin, and set into new affine
        new_affine_4 = resampled.affine.copy()
        new_affine_4[:3, 3] = new_affine_4[:3, :3].dot(
            new_origin) + new_affine_4[:3, 3]

        # Calculate new shapes
        new_shape = new_end - new_origin + 1
        resampled = nli.resample_img(fixed_image,
                                     target_affine=new_affine_4,
                                     target_shape=new_shape.tolist(),
                                     interpolation='nearest')

    xform = resampled.affine  # nibabel will pick the best affine
    _, qform_code = resampled.header.get_qform(coded=True)
    _, sform_code = resampled.header.get_sform(coded=True)

    xform_code = sform_code if sform_code > 0 else qform_code
    if xform_code == 1:
        xform_code = 2

    if force_xform_code is not None:
        xform_code = force_xform_code

    # Keep 0, 2, 3, 4 unchanged
    resampled.header.set_qform(xform, int(xform_code))
    resampled.header.set_sform(xform, int(xform_code))
    resampled.header['descrip'] = 'reference image generated by %s.' % (
        message or '(unknown software)')
    resampled.to_filename(out_file)
    return out_file
1024153
def magnification(self, x, y, kwargs, diff=diff):
        
        f_xx, f_xy, f_yx, f_yy = self.hessian(x, y, kwargs, diff=diff)
        det_A = (1 - f_xx) * (1 - f_yy) - f_xy*f_yx
        return 1/det_A
932704
def calc_fwhm(img, region, fexpand=3, axis=0):
    """"""

    # We compute know the FWHM of the slit
    # Given the computed position of the slit
    # Expand 'fexpand' pixels around
    # and cut an slice in the median filtered image

    xpregion = expand_region(region, fexpand, fexpand)
    cslit = img[xpregion]

    # Collapse it
    pslit = cslit.mean(axis=axis)

    # Estimate the background as a flat line
    # starting in pslit[0] and ending in pslit[-1]
    x2 = len(pslit)
    y1, y2 = pslit[0], pslit[-1]
    mslope = (y2-y1) / x2
    # background estimation
    backstim = mslope*numpy.arange(x2) + y1

    # We subtract background
    qslit = pslit-backstim
    # and find the pixel of the maximum
    pidx = numpy.argmax(qslit)
    peak, fwhm = fmod.compute_fwhm_1d_simple(qslit, pidx)
    return fwhm
1184484
function fitRect(rect, target, mode) {
    mode = mode || 'contain';

    var sw = target[2]/rect[2];
    var sh = target[3]/rect[3];
    var scale = 1;

    if (mode == 'contain') {
        scale = Math.min(sw, sh);
    }
    else if (mode == 'cover') {
        scale = Math.max(sw, sh);
    }

    return [
        target[0] + (target[2] - rect[2]*scale)/2,
        target[1] + (target[3] - rect[3]*scale)/2,
        rect[2]*scale,
        rect[3]*scale
    ]
}
839623
def genericCameraMatrix(shape, angularField=60):
    '''
    
    '''
    # http://nghiaho.com/?page_id=576
    # assume that the optical centre is in the middle:
    cy = int(shape[0] / 2)
    cx = int(shape[1] / 2)

    # assume that the FOV is 60 DEG (webcam)
    fx = fy = cx / np.tan(angularField / 2 * np.pi /
                          180)  # camera focal length
    # see
    # http://docs.opencv.org/doc/tutorials/calib3d/camera_calibration/camera_calibration.html
    return np.array([[fx, 0, cx],
                     [0, fy, cy],
                     [0, 0, 1]
                     ], dtype=np.float32)