Write out the all_radec catalog for this image to a file.
493960
def write_skycatalog(self,filename):
        
        if self.all_radec is None:
            return
        ralist = self.all_radec[0]#.tolist()
        declist = self.all_radec[1]#.tolist()
        f = open(filename,'w')
        f.write("#Sky positions for: "+self.name+'\n')
        f.write("#RA        Dec\n")
        f.write("#(deg)     (deg)\n")
        for i in range(len(ralist)):
            f.write('%0.12f  %0.12f\n'%(ralist[i],declist[i]))
        f.close()
866167
def write(self, arg, **kwargs):
        """"""
        if hasattr(arg, 'seek'):
            self._tofile(arg, **kwargs)
        else:
            with open(arg, 'wb') as fid:
                self._tofile(fid, **kwargs)
468100
def write_file(fname, info):
    """"""
    with open(fname, 'w') as outfile:
        # File header
        outfile.write('# Copyright (c) 2018 MetPy Developers.\n')
        outfile.write('# Distributed under the terms of the BSD 3-Clause License.\n')
        outfile.write('# SPDX-License-Identifier: BSD-3-Clause\n\n')
        outfile.write('# flake8: noqa\n')
        outfile.write('# Generated file -- do not modify\n')

        # Variable descriptions
        outfile.write('descriptions = {')
        outdata = ',\n                '.join('"{name}": "{desc}"'.format(
            **i) for i in info if need_desc(i))
        outfile.write(outdata)
        outfile.write('}\n\n')

        # Now the struct format
        outfile.write('fields = [')
        outdata = ',\n          '.join('({fname}, "{fmt}")'.format(
            fname=field_name(i), **i) for i in info)
        outfile.write(outdata)
        outfile.write(']\n')
566307
def write_catalogue(self, output_file, key_list=SORTED_ATTRIBUTE_LIST):
        

        with open(output_file, 'w') as of:
            writer = csv.DictWriter(of, fieldnames=key_list)
            writer.writeheader()
            for i in range(self.get_number_events()):
                row_dict = {}
                for key in key_list:
                    if len(self.data[key]) > 0:
                        data = self.data[key][i]
                        if key in self.INT_ATTRIBUTE_LIST:
                            if np.isnan(data):
                                data = ''
                            else:
                                data = int(data)
                        if key in self.FLOAT_ATTRIBUTE_LIST:
                            if np.isnan(data):
                                data = ''
                            else:
                                data = float(data)
                    row_dict[key] = data
                writer.writerow(row_dict)
856628
def write(self, outfile):
        """"""

        hdu_pri = fits.PrimaryHDU()

        hdu_exp = self._create_exp_hdu(self.data)
        hdu_exp.name = 'EXPOSURE'
        hdu_exp_wt = self._create_exp_hdu(self._data_wt)
        hdu_exp_wt.name = 'WEIGHTED_EXPOSURE'

        cols = [Column(name='CTHETA_MIN', dtype='f4',
                       data=self.costh_edges[:-1][::-1]),
                Column(name='CTHETA_MAX',  dtype='f4',
                       data=self.costh_edges[1:][::-1]), ]
        hdu_bnds = fits.table_to_hdu(Table(cols))
        hdu_bnds.name = 'CTHETABOUNDS'

        hdu_gti = fits.table_to_hdu(self._tab_gti)
        hdu_gti.name = 'GTI'

        hdus = [hdu_pri, hdu_exp, hdu_exp_wt,
                hdu_bnds, hdu_gti]

        for hdu in hdus:
            hdu.header['TSTART'] = self.tstart
            hdu.header['TSTOP'] = self.tstop

        with fits.HDUList(hdus) as hdulist:
            hdulist.writeto(outfile, clobber=True)
723355
def _write_image_description(self):
        """"""
        if (not self._datashape or self._datashape[0] == 1 or
                self._descriptionoffset <= 0):
            return

        colormapped = self._colormap is not None
        if self._imagej:
            isrgb = self._shape[-1] in (3, 4)
            description = imagej_description(
                self._datashape, isrgb, colormapped, **self._metadata)
        else:
            description = json_description(self._datashape, **self._metadata)

        # rewrite description and its length to file
        description = description.encode('utf-8')
        description = description[:self._descriptionlen-1]
        pos = self._fh.tell()
        self._fh.seek(self._descriptionoffset)
        self._fh.write(description)
        self._fh.seek(self._descriptionlenoffset)
        self._fh.write(struct.pack(self._byteorder+self._offsetformat,
                                   len(description)+1))
        self._fh.seek(pos)

        self._descriptionoffset = 0
        self._descriptionlenoffset = 0
        self._descriptionlen = 0
170732
def write_image(r, filename):
    
    with open(filename, 'wb') as fd:
        for chunk in r.iter_content(1024):
            fd.write(chunk)
938973
def print_all_metadata(fname):
    
    print("Filename   :", fname )
    print("Basename   :", os.path.basename(fname))
    print("Path       :", os.path.dirname(fname))
    print("Size       :", os.path.getsize(fname))
    img = Image.open(fname)
    # get the image's width and height in pixels
    width, height = img.size
    # get the largest dimension
    #max_dim = max(img.size)
    print("Width      :", width)
    print("Height     :", height)
    print("Format     :", img.format)
    print("palette    :", img.palette )
     
    print_stats(img)
    #print_exif_data(img)
    exif_data = get_exif_data(img)
    (lat, lon) = get_lat_lon(exif_data)
    print("GPS Lat    :", lat )
    print("GPS Long   :", lon )
1297042
def write_files(self):
        
        warnings = self.validate_data()

        print('-I- Writing all saved data to files')
        if self.measurements:
            self.write_measurements_file()
        for dtype in ['specimen', 'sample', 'site']:
            if self.data_lists[dtype][0]:
                do_pmag = dtype in self.incl_pmag_data
                self.write_magic_file(dtype, do_er=True, do_pmag=do_pmag)
                if not do_pmag:
                    pmag_file = os.path.join(self.WD, 'pmag_' + dtype + 's.txt')
                    if os.path.isfile(pmag_file):
                        os.remove(pmag_file)

        if self.locations:
            self.write_magic_file('location', do_er=True, do_pmag=False)

        self.write_age_file()

        if self.results:
            self.write_result_file()

        if warnings:
            print('-W- ' + str(warnings))
            return False, warnings

        return True, None
1225659
def list_all():
    '''
    
    '''
    ret = []
    if _sd_version() >= 219:
        for line in _machinectl('list-images')['stdout'].splitlines():
            try:
                ret.append(line.split()[0])
            except IndexError:
                continue
    else:
        rootdir = _root()
        try:
            for dirname in os.listdir(rootdir):
                if os.path.isdir(os.path.join(rootdir, dirname)):
                    ret.append(dirname)
        except OSError:
            pass
    return ret
4221
def write(self)->None:
        ""
        for param_name, values in self.params: self._write_histogram(param_name=param_name, values=values)
100540
function writeImageDesc() {

    out.writeByte(0x2c); // image separator
    WriteShort(0); // image position x,y = 0,0
    WriteShort(0);
    WriteShort(width); // image size
    WriteShort(height);

    // packed fields
    if (firstFrame) {
      // no LCT - GCT is used for first (or only) frame
      out.writeByte(0);
    } else {
      // specify normal LCT
      out.writeByte(0x80 | // 1 local color table 1=yes
        0 | // 2 interlace - 0=no
        0 | // 3 sorted - 0=no
        0 | // 4-5 reserved
        palSize); // 6-8 size of color table
    }
  }
154
def to_file(self, filename=None, write_style=True):
        
        out = zipwrap.Zippier(filename, "w")
        out.write("mimetype", self.mime_type)
        for p in self._pictures:
            out.write("Pictures/%s" % p.internal_name, p.get_data())
        out.write("content.xml", self.to_xml())
        if write_style:
            out.write("styles.xml", self.styles_xml())
        out.write("meta.xml", self.meta_xml())
        out.write("settings.xml", self.settings_xml())
        out.write("META-INF/manifest.xml", self.manifest_xml(out))
        return out
734416
def _write_segments(self, filename):
        
        # Column headers
        shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first',
                           'last', 'order'])
        with open(filename, 'w') as fhandle:
            fhandle.write(shead + '\n')
            for mrow in self.segments:
                fhandle.write('\t'.join([str(e) for e in mrow]) + '\n')
1129911
def write_multiple_files(args, base_dir, crawler):
    """"""
    for i, query in enumerate(args['query']):
        if query in args['files']:
            # Write files
            if args['out'] and i < len(args['out']):
                outfilename = args['out'][i]
            else:
                outfilename = '.'.join(query.split('.')[:-1])
            write_files(args, [query], outfilename)
        elif query in args['urls']:
            # Scrape/crawl urls
            domain = utils.get_domain(query)
            if args['html']:
                # Create a directory to save PART.html files in
                if not args['quiet']:
                    print('Storing html files in {0}/'.format(domain))
                utils.mkdir_and_cd(domain)

            if args['crawl'] or args['crawl_all']:
                # Crawl and save HTML files/image files to disk
                infilenames = crawler.crawl_links(query)
            else:
                raw_resp = utils.get_raw_resp(query)
                if raw_resp is None:
                    return False

                # Saves page as PART.html file
                prev_part_num = utils.get_num_part_files()
                utils.write_part_file(args, query, raw_resp)
                curr_part_num = prev_part_num + 1
                infilenames = utils.get_part_filenames(curr_part_num, prev_part_num)

            # Convert output or leave as PART.html files
            if args['html']:
                # HTML files have been written already, so return to base dir
                os.chdir(base_dir)
            else:
                # Write files to text or pdf
                if infilenames:
                    if args['out'] and i < len(args['out']):
                        outfilename = args['out'][i]
                    else:
                        outfilename = utils.get_outfilename(query, domain)
                    write_files(args, infilenames, outfilename)
                else:
                    sys.stderr.write('Failed to retrieve content from {0}.\n'
                                     .format(query))
    return True
1349921
def write(self, outfile):
        
        data = odict()
        data['PIXEL']=self.roi.pixels_target
        # Full data output (too large for survey)
        if self.config['scan']['full_pdf']:
            data['LOG_LIKELIHOOD']=self.log_likelihood_sparse_array.T
            data['RICHNESS']=self.richness_sparse_array.T
            data['RICHNESS_LOWER']=self.richness_lower_sparse_array.T
            data['RICHNESS_UPPER']=self.richness_upper_sparse_array.T
            data['RICHNESS_LIMIT']=self.richness_upper_limit_sparse_array.T
            #data['STELLAR_MASS']=self.stellar_mass_sparse_array.T
            data['FRACTION_OBSERVABLE']=self.fraction_observable_sparse_array.T
        else:
            data['LOG_LIKELIHOOD']=self.log_likelihood_sparse_array.T
            data['RICHNESS']=self.richness_sparse_array.T
            data['FRACTION_OBSERVABLE']=self.fraction_observable_sparse_array.T

        # Convert to 32bit float
        for k in list(data.keys())[1:]:
            data[k] = data[k].astype('f4',copy=False)
            
        # Stellar mass can be calculated from STELLAR * RICHNESS
        header = odict()
        header['STELLAR']=round(self.stellar_mass_conversion,8)
        header['LKDNSIDE']=self.config['coords']['nside_likelihood']
        header['LKDPIX']=ang2pix(self.config['coords']['nside_likelihood'],
                                 self.roi.lon,self.roi.lat)
        header['NROI']=self.roi.inROI(self.loglike.catalog_roi.lon,
                                      self.loglike.catalog_roi.lat).sum()
        header['NANNULUS']=self.roi.inAnnulus(self.loglike.catalog_roi.lon,
                                              self.loglike.catalog_roi.lat).sum()
        header['NINSIDE']=self.roi.inInterior(self.loglike.catalog_roi.lon,
                                              self.loglike.catalog_roi.lat).sum()
        header['NTARGET']=self.roi.inTarget(self.loglike.catalog_roi.lon,
                                            self.loglike.catalog_roi.lat).sum()

        # Flatten if there is only a single distance modulus
        # ADW: Is this really what we want to do?
        if len(self.distance_modulus_array) == 1:
            for key in data:
                data[key] = data[key].flatten()

        logger.info("Writing %s..."%outfile)
        write_partial_map(outfile,data,
                          nside=self.config['coords']['nside_pixel'],
                          header=header,
                          clobber=True
                          )
        
        fitsio.write(outfile,
                     dict(DISTANCE_MODULUS=self.distance_modulus_array.astype('f4',copy=False)),
                     extname='DISTANCE_MODULUS',
                     clobber=False)
308534
def dump(self):
        """"""
        scan_lines = bytearray()
        for y in range(self.height):
            scan_lines.append(0)  # filter type 0 (None)
            scan_lines.extend(
                self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)]
            )
        # image represented as RGBA tuples, no interlacing
        return SIGNATURE + \
            self.pack_chunk(b'IHDR', struct.pack(b"!2I5B",
                                                 self.width, self.height,
                                                 8, 6, 0, 0, 0)) + \
            self.pack_chunk(b'IDAT', zlib.compress(bytes(scan_lines), 9)) + \
            self.pack_chunk(b'IEND', b'')