subtract the given sky value from each the data array
    that has been passed. image is a fits object that
    contains the data and header for one image extension
770226
def _subtractSky(image,skyValue,memmap=False):
    
    try:
        np.subtract(image.data,skyValue,image.data)

    except IOError:
        print("Unable to perform sky subtraction on data array")
        raise IOError
785699
def tenengrad(img, ksize=3):
    '''''''
    Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
    Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
    FM = Gx*Gx + Gy*Gy
    mn = cv2.mean(FM)[0]
    if np.isnan(mn):
        return np.nanmean(FM)
    return mn
72947
def point_image_value(image, xy, scale=1):
    """"""
    return getinfo(ee.Image(image).reduceRegion(
        reducer=ee.Reducer.first(), geometry=ee.Geometry.Point(xy),
        scale=scale))
88859
def get_b(self):
        

        try:

            return self.b.value

        except AttributeError:

            # Transform from L,B to R.A., Dec

            return self.sky_coord.transform_to('galactic').b.value
784393
def _read_image_slice(self, arg):
        
        if 'ndims' not in self._info:
            raise ValueError("Attempt to slice empty extension")

        if isinstance(arg, slice):
            # one-dimensional, e.g. 2:20
            return self._read_image_slice((arg,))

        if not isinstance(arg, tuple):
            raise ValueError("arguments must be slices, one for each "
                             "dimension, e.g. [2:5] or [2:5,8:25] etc.")

        # should be a tuple of slices, one for each dimension
        # e.g. [2:3, 8:100]
        nd = len(arg)
        if nd != self._info['ndims']:
            raise ValueError("Got slice dimensions %d, "
                             "expected %d" % (nd, self._info['ndims']))

        targ = arg
        arg = []
        for a in targ:
            if isinstance(a, slice):
                arg.append(a)
            elif isinstance(a, int):
                arg.append(slice(a, a+1, 1))
            else:
                raise ValueError("arguments must be slices, e.g. 2:12")

        dims = self._info['dims']
        arrdims = []
        first = []
        last = []
        steps = []

        # check the args and reverse dimensions since
        # fits is backwards from numpy
        dim = 0
        for slc in arg:
            start = slc.start
            stop = slc.stop
            step = slc.step

            if start is None:
                start = 0
            if stop is None:
                stop = dims[dim]
            if step is None:
                step = 1
            if step < 1:
                raise ValueError("slice steps must be >= 1")

            if start < 0:
                start = dims[dim] + start
                if start < 0:
                    raise IndexError("Index out of bounds")

            if stop < 0:
                stop = dims[dim] + start + 1

            # move to 1-offset
            start = start + 1

            if stop < start:
                raise ValueError("python slices but include at least one "
                                 "element, got %s" % slc)
            if stop > dims[dim]:
                stop = dims[dim]

            first.append(start)
            last.append(stop)
            steps.append(step)
            arrdims.append(stop-start+1)

            dim += 1

        first.reverse()
        last.reverse()
        steps.reverse()
        first = numpy.array(first, dtype='i8')
        last = numpy.array(last, dtype='i8')
        steps = numpy.array(steps, dtype='i8')

        npy_dtype = self._get_image_numpy_dtype()
        array = numpy.zeros(arrdims, dtype=npy_dtype)
        self._FITS.read_image_slice(self._ext+1, first, last, steps, array)
        return array
776551
def imscatter(images, positions):
    '''
        
    '''
    positions = np.array(positions)

    bottoms = positions[:, 1] - np.array([im.shape[1] / 2.0 for im in images])
    tops = bottoms + np.array([im.shape[1] for im in images])

    lefts = positions[:, 0] - np.array([im.shape[0] / 2.0 for im in images])
    rigths = lefts + np.array([im.shape[0] for im in images])

    most_bottom = int(np.floor(bottoms.min()))
    most_top = int(np.ceil(tops.max()))

    most_left = int(np.floor(lefts.min()))
    most_right = int(np.ceil(rigths.max()))

    scatter_image = np.zeros(
        [most_right - most_left, most_top - most_bottom, 3], dtype=imgs[0].dtype)

    # shift, now all from zero
    positions -= [most_left, most_bottom]

    for im, pos in zip(images, positions):

        xl = int(pos[0] - im.shape[0] / 2)
        xr = xl + im.shape[0]

        yb = int(pos[1] - im.shape[1] / 2)
        yt = yb + im.shape[1]

        scatter_image[xl:xr, yb:yt, :] = im
    return scatter_image
12238
function() {
            var data = {
                src: this._image.src,
                width: this._image.w,
                height: this._image.h,
                crops: []
            };

            for(var n = 0; n < this._image.crops.length; n++) {
                data.crops.push({
                    id: this._image.crops[n].id,
                    x: Math.round(this._image.crops[n].x),
                    y: Math.round(this._image.crops[n].y),
                    width: Math.round(this._image.crops[n].w),
                    height: Math.round(this._image.crops[n].h),
                    usable: this._image.crops[n].usable
                });
            }

            return data;
        }
1029388
function process_SOFn($data, $marker)
    {
        $data_precision = 0;
        $num_components = 0;

        $data_precision = ord($data[2]);

        if ($this->debug)
        {
            print("Image Dimension Calculation:");
            print("((ord($data[3]) << 8) | ord($data[4]));");
        }
        $this->ImageInfo["h"]["Height"] = ((ord($data[3]) << 8) | ord($data[4]));
        $this->ImageInfo["h"]["Width"] = ((ord($data[5]) << 8) | ord($data[6]));

        $num_components = ord($data[7]);

        if ($num_components == 3)
        {
            $this->ImageInfo["h"]["IsColor"] = 1;
        }
        else
        {
            $this->ImageInfo["h"]["IsColor"] = 0;
        }

        $this->ImageInfo["h"]["Process"] = $marker;
        $this->debug("JPEG image is " . $this->ImageInfo["h"]["Width"] . " * " . $this->ImageInfo["h"]["Height"] . ", $num_components color components, $data_precision bits per sample\n");
    }
1098053
def sky_fraction(self):
        
        pix_id = self._best_res_pixels()
        nb_pix_filled = pix_id.size
        return nb_pix_filled / float(3 << (2*(self.max_order + 1)))
1338170
public double subtract(int[] indices, double val) {
        checkIndices(indices);
        int c = getConfigIdx(indices);
        double prev = values[c];
        values[c] = s.minus(values[c], val);
        return prev;
    }
1160069
def estimateFromImages(imgs1, imgs2=None, mn_mx=None, nbins=100):
    '''
    
    '''
    if imgs2 is None:
        imgs2 = [None] * len(imgs1)
    else:
        assert len(imgs1) == len(imgs2)

    y_vals = np.empty((len(imgs1), nbins))
    w_vals = np.zeros((len(imgs1), nbins))

    if mn_mx is None:
        print('estimating min and max image value')
        mn = 1e6
        mx = -1e6
        # get min and max image value checking all first images:
        for n, i1 in enumerate(imgs1):
            print('%s/%s' % (n + 1, len(imgs1)))
            i1 = imread(i1)
            mmn, mmx = _getMinMax(i1)
            mn = min(mn, mmn)
            mx = mx = max(mx, mmx)
        print('--> min(%s), max(%s)' % (mn, mx))
    else:
        mn, mx = mn_mx

    x = None
    print('get noise level function')
    for n, (i1, i2) in enumerate(zip(imgs1, imgs2)):
        print('%s/%s' % (n + 1, len(imgs1)))

        i1 = imread(i1)
        if i2 is not None:
            i2 = imread(i2)

        x, y, weights, _ = calcNLF(i1, i2, mn_mx_nbins=(mn, mx, nbins), x=x)
        y_vals[n] = y
        w_vals[n] = weights

    # filter empty places:
    filledPos = np.sum(w_vals, axis=0) != 0
    w_vals = w_vals[:, filledPos]
    y_vals = y_vals[:, filledPos]
    x = x[filledPos]

    y_avg = np.average(np.nan_to_num(y_vals),
                       weights=w_vals,
                       axis=0)
    w_vals = np.sum(w_vals, axis=0)
    w_vals /= w_vals.sum()

    fitParams, fn, i = _evaluate(x, y_avg, w_vals)
    return x, fn, y_avg, y_vals, w_vals, fitParams, i
296758
def plot_subtract_from_data_all(self):
        
        f, axes = plt.subplots(2, 3, figsize=(16, 8))

        self.subtract_from_data_plot(ax=axes[0, 0], text='Data')
        self.subtract_from_data_plot(ax=axes[0, 1], text='Data - Point Source', point_source_add=True)
        self.subtract_from_data_plot(ax=axes[0, 2], text='Data - Lens Light', lens_light_add=True)
        self.subtract_from_data_plot(ax=axes[1, 0], text='Data - Source Light', source_add=True)
        self.subtract_from_data_plot(ax=axes[1, 1], text='Data - Source Light - Point Source', source_add=True,
                                         point_source_add=True)
        self.subtract_from_data_plot(ax=axes[1, 2], text='Data - Lens Light - Point Source', lens_light_add=True,
                                         point_source_add=True)
        f.tight_layout()
        f.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0., hspace=0.05)
        return f, axes
957330
function unpackPNG(w, h, c, str) {
  var canvas = document.createElement("canvas")
  canvas.width = h
  canvas.height = w
  var img = new Image()
  img.src = "data:image/png;base64," + str
  var context = canvas.getContext("2d")
  context.drawImage(img, 0, 0)
  var pixels = context.getImageData(0, 0, h, w)
  return ndarray(pixels.data, [w, h, c], [4, 4*w, 1], 0)
}
1361765
function (inData, outData, width, height, options) {
        options = defaultOptions(options, {amount: 1, angle: 0});
        var i, n = width * height * 4,
            amount = options.amount,
            angle = options.angle,
            x = Math.cos(-angle) * amount,
            y = Math.sin(-angle) * amount,

            a00 = -x - y,
            a10 = -x,
            a20 = y - x,
            a01 = -y,
            a21 = y,
            a02 = -y + x,
            a12 = x,
            a22 = y + x,

            tmpData = [];

        convolve3x3(inData, tmpData, width, height,
            [
                [a00, a01, a02],
                [a10, 0, a12],
                [a20, a21, a22]
            ]);

        for (i = 0; i < n; i += 4) {
            outData[i] = 128 + tmpData[i];
            outData[i + 1] = 128 + tmpData[i + 1];
            outData[i + 2] = 128 + tmpData[i + 2];
            outData[i + 3] = inData[i + 3];
        }
    }
1096360
public void performLearning(T image) {
		// use the update track location
		get_subwindow(image, templateNew);

		// Kernel Regularized Least-Squares, calculate alphas (in Fourier domain)
		//	k = dense_gauss_kernel(sigma, x);
		dense_gauss_kernel(sigma, templateNew, templateNew, k);
		fft.forward(k,kf);

		// new_alphaf = yf ./ (fft2(k) + lambda);   %(Eq. 7)
		computeAlphas(gaussianWeightDFT, kf, lambda, newAlphaf);

		// subsequent frames, interpolate model
		// alphaf = (1 - interp_factor) * alphaf + interp_factor * new_alphaf;
		int N = alphaf.width*alphaf.height*2;
		for( int i = 0; i < N; i++ ) {
			alphaf.data[i] = (1-interp_factor)*alphaf.data[i] + interp_factor*newAlphaf.data[i];
		}

		// Set the previous image to be an interpolated version
		//		z = (1 - interp_factor) * z + interp_factor * new_z;
		N = templateNew.width* templateNew.height;
		for( int i = 0; i < N; i++ ) {
			template.data[i] = (1-interp_factor)* template.data[i] + interp_factor*templateNew.data[i];
		}
	}
370378
public static void subtract(double[] array1, double[] array2) {
        assert (array1.length == array2.length);
        for (int i=0; i<array1.length; i++) {
            array1[i] -= array2[i];
        }
    }
1259465
def rd2xy(input,ra=None,dec=None,coordfile=None,colnames=None,
            precision=6,output=None,verbose=True):
    
    single_coord = False
    if coordfile is not None:
        if colnames in blank_list:
            colnames = ['c1','c2']
        elif isinstance(colnames,type('a')):
            colnames = colnames.split(',')
        # convert input file coordinates to lists of decimal degrees values
        xlist,ylist = tweakutils.readcols(coordfile,cols=colnames)
    else:
        if isinstance(ra,np.ndarray):
            ralist = ra.tolist()
            declist = dec.tolist()
        elif not isinstance(ra, list):
            ralist = [ra]
            declist = [dec]
        else:
            ralist = ra
            declist = dec
        xlist  = [0]*len(ralist)
        ylist = [0]*len(ralist)
        if len(xlist) == 1:
            single_coord = True
        for i,(r,d) in enumerate(zip(ralist,declist)):
            # convert input value into decimal degrees value
            xval,yval = tweakutils.parse_skypos(r,d)
            xlist[i] = xval
            ylist[i] = yval

    # start by reading in WCS+distortion info for input image
    inwcs = wcsutil.HSTWCS(input)
    if inwcs.wcs.is_unity():
        print("####\nNo valid WCS found in {}.\n  Results may be invalid.\n####\n".format(input))

    # Now, convert pixel coordinates into sky coordinates
    try:
        outx,outy = inwcs.all_world2pix(xlist,ylist,1)
    except RuntimeError:
        outx,outy = inwcs.wcs_world2pix(xlist,ylist,1)

    # add formatting based on precision here...
    xstr = []
    ystr = []
    fmt = "%."+repr(precision)+"f"
    for x,y in zip(outx,outy):
        xstr.append(fmt%x)
        ystr.append(fmt%y)

    if verbose or (not verbose and util.is_blank(output)):
        print ('# Coordinate transformations for ',input)
        print('# X      Y         RA             Dec\n')
        for x,y,r,d in zip(xstr,ystr,xlist,ylist):
            print("%s  %s    %s  %s"%(x,y,r,d))

    # Create output file, if specified
    if output:
        f = open(output,mode='w')
        f.write("# Coordinates converted from %s\n"%input)
        for x,y in zip(xstr,ystr):
            f.write('%s    %s\n'%(x,y))
        f.close()
        print('Wrote out results to: ',output)

    if single_coord:
        outx = outx[0]
        outy = outy[0]

    return outx, outy