Create a _cor file with the same format as the original input image.

    The DQ array will be replaced with the mask array used to create the _cor
    file.
489112
def createCorrFile(outfile, arrlist, template):
    
    # Remove the existing cor file if it exists
    if os.path.isfile(outfile):
        os.remove(outfile)
        print("Removing old corr file: '{:s}'".format(outfile))

    with fits.open(template, memmap=False) as ftemplate:
        for arr in arrlist:
            ftemplate[arr['sciext']].data = arr['corrFile']
            if arr['dqext'][0] != arr['sciext'][0]:
                ftemplate[arr['dqext']].data = arr['dqMask']
        ftemplate.writeto(outfile)
        print("Created CR corrected file: '{:s}'".format(outfile))
646900
def createFromMaskedArray(cls, masked_arr):
        
        if isinstance(masked_arr, ArrayWithMask):
            return masked_arr

        check_class(masked_arr, (np.ndarray, ma.MaskedArray))

        # A MaskedConstant (i.e. masked) is a special case of MaskedArray. It does not seem to have
        # a fill_value so we use None to use the default.
        # https://docs.scipy.org/doc/numpy/reference/maskedarray.baseclass.html#numpy.ma.masked
        fill_value = getattr(masked_arr, 'fill_value', None)

        return cls(masked_arr.data, masked_arr.mask, fill_value)
1331772
def createWcsHDU(wcs):  # noqa: N802
    
    header = wcs.to_header()

    header['EXTNAME'] = 'WCS'
    header['EXTVER'] = 1

    # Now, update original image size information
    header['NPIX1'] = (wcs.pixel_shape[0], "Length of array axis 1")
    header['NPIX2'] = (wcs.pixel_shape[1], "Length of array axis 2")
    header['PIXVALUE'] = (0.0, "values of pixels in array")

    if hasattr(wcs, 'orientat'):
        orientat = wcs.orientat
    else:
        # find orientat from CD or PC matrix
        if wcs.wcs.has_cd():
            cd12 = wcs.wcs.cd[0][1]
            cd22 = wcs.wcs.cd[1][1]
        elif wcs.wcs.has_pc():
            cd12 = wcs.wcs.cdelt[0] * wcs.wcs.pc[0][1]
            cd22 = wcs.wcs.cdelt[1] * wcs.wcs.pc[1][1]
        else:
            raise ValueError("Invalid WCS: WCS does not contain neither "
                             "a CD nor a PC matrix.")
        orientat = np.rad2deg(np.arctan2(cd12, cd22))
    header['ORIENTAT'] = (orientat, "position angle of "
                          "image y axis (deg. e of n)")

    return fits.ImageHDU(None, header)
563028
private function createIm() {
        $w1 = imagesx($this->image1);
        $w2 = imagesx($this->image2);
        $h1 = imagesy($this->image1);
        $h2 = imagesy($this->image2);

        if ($this->position === self::POSITION_LEFT || $this->position === self::POSITION_RIGHT) {
            $w = $w1 + $w2 + $this->space;
            $h = max($h1, $h2);
        } else {
            $w = max($w1, $w2);
            $h = $h1 + $h2 + $this->space;
        }

        $this->im = imagecreatetruecolor($w, $h);
        imagefill($this->im, 0, 0, $this->background->allocate($this->im));

        // We start defining position of images
        if ($this->position === self::POSITION_TOP) {
            if ($w1 > $w2) {
                $posX1 = 0;
                $posX2 = $this->findPosition($w1, $w2, $this->alignment);
            } else {
                $a = $this->changeAlignment($this->alignment);
                $posX1 = $this->findPosition($w1, $w2, $a);
                $posX2 = 0;
            }

            $posY2 = 0;
            $posY1 = $h2 + $this->space;
        } elseif ($this->position === self::POSITION_LEFT) {
            if ($w1 > $w2) {
                $posY1 = 0;
                $posY2 = $this->findPosition($h1, $h2, $this->alignment);
            } else {
                $a = $this->changeAlignment($this->alignment);
                $posY2 = 0;
                $posY1 = $this->findPosition($h1, $h2, $a);
            }

            $posX2 = 0;
            $posX1 = $w2 + $this->space;
        } elseif ($this->position === self::POSITION_BOTTOM) {
            if ($w1 > $w2) {
                $posX2 = $this->findPosition($w1, $w2, $this->alignment);
                $posX1 = 0;
            } else {
                $a = $this->changeAlignment($this->alignment);
                $posX2 = 0;
                $posX1 = $this->findPosition($w1, $w2, $a);
            }

            $posY1 = 0;
            $posY2 = $h1 + $this->space;
        } else { // defaults to RIGHT
            if ($w1 > $w2) {
                $posY2 = $this->findPosition($h1, $h2, $this->alignment);
                $posY1 = 0;
            } else {
                $a = $this->changeAlignment($this->alignment);
                $posY2 = 0;
                $posY1 = $this->findPosition($h1, $h2, $a);
            }

            $posX1 = 0;
            $posX2 = $w1 + $this->space;
        }

        imagecopy($this->im, $this->image1, $posX1, $posY1, 0, 0, $w1, $h1);
        imagecopy($this->im, $this->image2, $posX2, $posY2, 0, 0, $w2, $h2);
    }
473817
def create_image(self, image_name=None, scale_ratio=1, window=None):
        
        size = 48 * scale_ratio
        pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(image_name, -1, size, True)
        image = Gtk.Image()

        # Creating the cairo surface is necessary for proper scaling on HiDPI
        try:
            surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale_ratio, window)
            image.set_from_surface(surface)

        # Fallback for GTK+ older than 3.10
        except AttributeError:
            image.set_from_pixbuf(pixbuf)

        return image
596519
def new_from_file(self, filename: str, header_data: Optional[Header] = None,
                      mask_data: Optional[np.ndarray] = None):
        """"""
989191
def _new_placeholder_pic(self, image_file):
        
        rId, desc, image_size = self._get_or_add_image(image_file)
        shape_id, name = self.shape_id, self.name
        pic = CT_Picture.new_ph_pic(shape_id, name, desc, rId)
        pic.crop_to_fit(image_size, (self.width, self.height))
        return pic
1321088
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from .stickers import MaskPosition

        data = {}
        data['file_id'] = u(array.get('file_id'))
        data['width'] = int(array.get('width'))
        data['height'] = int(array.get('height'))
        data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
        data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
        data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
        data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get(
            'mask_position') is not None else None
        data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
        data['_raw'] = array
        return Sticker(**data)
814335
def create_same_as_file(self):
        

        def find_preferred_uri(uri_list):
            index = None
            for i, uri in enumerate(uri_list):
                if uri.startswith("<http://id.loc.gov/authorities/subjects/"):
                        index = i
                        print(uri)
                        break
            if not index:
                for i, uri in enumerate(uri_list):
                    if uri.startswith(\
                            "<http://id.loc.gov/authorities/childrensSubjects/"):
                        index = i
                        print(uri)
                        break
            if not index:
                index = 0
            return (uri_list.pop(index), uri_list)


        with open(os.path.join(CFG.LOCAL_DATA_PATH, self.local_filename),
                  "w") as file_obj:
            file_obj.write(NSM.prefix("turtle"))
            for item in self.uri_list:
                uris = item['uris']['value'].split(",")
                new_list = find_preferred_uri(uris)
                uris = uris[1:]
                for uir in new_list[1]:
                    file_obj.write("%s kds:mergeWith %s .\n" % (uir,
                                                                new_list[0]))
9604
def fromfits(infile, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = ft.getdata(infile, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    #print pixelarray
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "Input shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "Input file BITPIX : %s" % (hdr["BITPIX"])
    pixelarrayshape = np.asarray(pixelarrayshape)
    if verbose :
        print "Internal array type :", pixelarray.dtype.name
    
    return f2nimage(pixelarray, verbose = verbose)
630389
def createWcsHDU(self):
        
        hdu = fits.ImageHDU()
        hdu.header['EXTNAME'] = 'WCS'
        hdu.header['EXTVER'] = 1
        # Now, update original image size information
        hdu.header['WCSAXES'] = (2, "number of World Coordinate System axes")
        hdu.header['NPIX1'] = (self.naxis1, "Length of array axis 1")
        hdu.header['NPIX2'] = (self.naxis2, "Length of array axis 2")
        hdu.header['PIXVALUE'] = (0.0, "values of pixels in array")

        # Write out values to header...
        excluded_keys = ['naxis1','naxis2']
        for key in self.wcskeys:
            _dkey = self.wcstrans[key]
            if _dkey not in excluded_keys:
                hdu.header[key] = self.__dict__[_dkey]


        return hdu
1151764
def _generate_art(self, image, width, height):
        
        # Characters aren't square, so scale the output by the aspect ratio of a charater
        height = int(height * self._char_width / float(self._char_height))
        image = image.resize((width, height), Image.ANTIALIAS).convert("RGB")

        for (r, g, b) in image.getdata():
            greyscale = int(0.299 * r + 0.587 * g + 0.114 * b)
            ch = self._chars[int(greyscale / 255. * (len(self._chars) - 1) + 0.5)]
            yield (ch, rgb2short(r, g, b))
60744
def masked_rec_array_to_mgr(data, index, columns, dtype, copy):
    

    # essentially process a record array then fill it
    fill_value = data.fill_value
    fdata = ma.getdata(data)
    if index is None:
        index = get_names_from_index(fdata)
        if index is None:
            index = ibase.default_index(len(data))
    index = ensure_index(index)

    if columns is not None:
        columns = ensure_index(columns)
    arrays, arr_columns = to_arrays(fdata, columns)

    # fill if needed
    new_arrays = []
    for fv, arr, col in zip(fill_value, arrays, arr_columns):
        mask = ma.getmaskarray(data[col])
        if mask.any():
            arr, fv = maybe_upcast(arr, fill_value=fv, copy=True)
            arr[mask] = fv
        new_arrays.append(arr)

    # create the manager
    arrays, arr_columns = reorder_arrays(new_arrays, arr_columns, columns)
    if columns is None:
        columns = arr_columns

    mgr = arrays_to_mgr(arrays, arr_columns, index, columns, dtype)

    if copy:
        mgr = mgr.copy()
    return mgr
599697
def buildMaskImage(rootname, bitvalue, output, extname='DQ', extver=1):
    

    # If no bitvalue is set or rootname given, assume no mask is desired
    # However, this name would be useful as the output mask from
    # other processing, such as MultiDrizzle, so return it anyway.
    #if bitvalue == None or rootname == None:
    #    return None

    # build output name
    maskname = output

    # If an old version of the maskfile was present, remove it and rebuild it.
    if fileutil.findFile(maskname):
        fileutil.removeFile(maskname)

    # Open input file with DQ array
    fdq = fileutil.openImage(rootname, mode='readonly', memmap=False)
    try:
        _extn = fileutil.findExtname(fdq, extname, extver=extver)
        if _extn is not None:
            # Read in DQ array
            dqarr = fdq[_extn].data
        else:
            dqarr = None

        # For the case where there is no DQ array,
        # create a mask image of all ones.
        if dqarr is None:
            # We need to get the dimensions of the output DQ array
            # Since the DQ array is non-existent, look for the SCI extension
            _sci_extn = fileutil.findExtname(fdq,'SCI',extver=extver)
            if _sci_extn is not None:
                _shape = fdq[_sci_extn].data.shape
                dqarr = np.zeros(_shape,dtype=np.uint16)
            else:
                raise Exception
        # Build mask array from DQ array
        maskarr = buildMask(dqarr,bitvalue)
        #Write out the mask file as simple FITS file
        fmask = fits.open(maskname, mode='append', memmap=False)
        maskhdu = fits.PrimaryHDU(data = maskarr)
        fmask.append(maskhdu)

        #Close files
        fmask.close()
        del fmask
        fdq.close()
        del fdq

    except:
        fdq.close()
        del fdq
        # Safeguard against leaving behind an incomplete file
        if fileutil.findFile(maskname):
            os.remove(maskname)
        _errstr = "\nWarning: Problem creating MASK file for "+rootname+".\n"
        #raise IOError, _errstr
        print(_errstr)
        return None

    # Return the name of the mask image written out
    return maskname
927339
def default_mask(mask_arg)
      mask = mask_arg.dup
      mask[:width] = image_file_width if mask[:width].zero?
      mask[:height] = image_file_height if mask[:height].zero?

      crop_size = size_when_fitting({width: image_file_width, height: image_file_height}, mask)
      top_left = get_top_left_crop_corner(crop_size)

      point_and_mask_to_points(top_left, crop_size)
    end
613981
def _prepare_base_image(self):
        
        if not self.base_image:
            return defer.succeed(True)

        if self.cheap_copy:
            clone_cmd = "qemu-img"
            clone_args = "create -b %(base)s -f qcow2 %(image)s"
        else:
            clone_cmd = "cp"
            clone_args = "%(base)s %(image)s"

        clone_args = clone_args % {
            "base": self.base_image,
            "image": self.image,
        }

        log.msg("Cloning base image: %s %s'" % (clone_cmd, clone_args))

        d = utils.getProcessValue(clone_cmd, clone_args.split())

        def _log_result(res):
            log.msg("Cloning exit code was: %d" % res)
            return res

        def _log_error(err):
            log.err("Cloning failed: %s" % err)
            return err

        d.addCallbacks(_log_result, _log_error)

        return d
1270069
def create(self, width, height):
        
        return Image.new(self.mode, (width, height))