Write out the all_radec catalog for this image to a file.
325260
def write_skycatalog(self, filename, show_flux=False, show_id=False):
        
        f = open(filename,'w')
        f.write("#Sky positions for cumulative reference catalog. Initial catalog from: "+self.name+'\n')
        header1 = "#RA        Dec"
        header2 = "#(deg)     (deg)"
        if show_flux:
            header1 += "        Flux"
            header2 += "       (counts)"
        if show_id:
            header1 += "        ID        Origin"
            header2 += ""
        header1 += "\n"
        header2 += "\n"

        f.write(header1)
        f.write(header2)

        show_details = show_flux or show_id
        flux_end_char = ''
        if show_details and show_flux:
            if show_id:
                flux_end_char = '\t'

        for i in range(self.all_radec[0].shape[0]):
            src_line = "{:.7f}  {:.7f}" \
                .format(self.all_radec[0][i], self.all_radec[1][i])
            if show_details:
                #src_line += " #"
                if show_flux:
                    #src_line += " flux: {:.5g}{:s}" \
                        #.format(self.xy_catalog[2][i], flux_end_char)
                    src_line += "  {:.5g}".format(self.xy_catalog[2][i])
                if show_id:
                    #src_line += " ID: {:d}\torigin: '{:s}'" \
                        #.format(self.xy_catalog[3][i], self.xy_catalog[-1][i])
                    src_line += "  {:d}  {:s}".format(self.xy_catalog[3][i],
                                                      self.xy_catalog[-1][i])
            f.write(src_line + '\n')
        f.close()
1267419
def write_to_directory(self, dataset_info_dir):
    """"""
    # Save the metadata from the features (vocabulary, labels,...)
    if self.features:
      self.features.save_metadata(dataset_info_dir)

    if self.redistribution_info.license:
      with tf.io.gfile.GFile(self._license_filename(dataset_info_dir),
                             "w") as f:
        f.write(self.redistribution_info.license)

    with tf.io.gfile.GFile(self._dataset_info_filename(dataset_info_dir),
                           "w") as f:
      f.write(self.as_json)
80791
def write_geoms_to_file(self, fp, geoms, names=None):
        """"""
        if fp[-5:] != '.gpkg':
            fp = fp + '.gpkg'
        if names is not None:
            assert len(geoms) == len(names), "Inconsistent length of geometries and names"
        else:
            names = ("Merged geometry {}".format(count) for count in itertools.count())
        meta = {
            'crs': {'no_defs': True, 'ellps': 'WGS84', 'datum': 'WGS84', 'proj': 'longlat'},
            'driver': 'GPKG',
            'schema': {'geometry': 'MultiPolygon', 'properties': {'name': 'str', 'id': 'int'}}
        }
        with fiona.drivers():
            with fiona.open(fp, 'w', **meta) as sink:
                for geom, name, count in zip(geoms, names, itertools.count(1)):
                    sink.write({
                        'geometry': _to_fiona(geom),
                        'properties': {'name': name, 'id': count}
                    })
        return fp
799749
def store_output_files(self, dir_path):
        """"""
        if self.last_result:
            for entry in os.listdir(self.last_result["output_dir"]):
                path = os.path.join(self.last_result["output_dir"], entry)
                if os.path.isfile(path):
                    shutil.copy(path, os.path.join(dir_path, entry))
            shutil.copy(
                self.get_path(OslomRunner.SEED_FILE),
                os.path.join(dir_path, OslomRunner.SEED_FILE))
            args_file = os.path.join(dir_path, OslomRunner.ARGS_FILE)
            with open(args_file, "w") as writer:
                writer.write("{}\n".format(" ".join(self.last_result["args"])))
            self.id_remapper.store_mapping(
                os.path.join(dir_path, OslomRunner.IDS_MAPPING_FILE))
552442
def write_src(hdf5_out, gctoo_object, out_file_name):
    
    if gctoo_object.src == None:
        hdf5_out.attrs[src_attr] = out_file_name
    else:
        hdf5_out.attrs[src_attr] = gctoo_object.src
731410
def write(self, outfile, encoding):
        
        """
        cal = Calendar()
        cal.add('version', '2.0')
        cal.add('calscale', 'GREGORIAN')

        for ifield, efield in FEED_FIELD_MAP:
            val = self.feed.get(ifield)
            if val is not None:
                cal.add(efield, val)

        self.write_items(cal)

        to_ical = getattr(cal, 'as_string', None)
        if not to_ical:
            to_ical = cal.to_ical
        outfile.write(to_ical())
574270
def exportdb(outdir):
    """"""
    ecode = 0
    try:
        imgdir = os.path.join(outdir, "images")
        feeddir = os.path.join(outdir, "feeds")
        storedir = os.path.join(outdir, "storedfiles")

        for d in [outdir, imgdir, feeddir, storedir]:
            if not os.path.exists(d):
                os.makedirs(d)

        anchore_print("exporting images...")
        imagelist = anchore_utils.get_image_list().keys()
        for imageId in imagelist:
            thefile = os.path.join(imgdir, imageId+".json")
            if not os.path.exists(thefile):
                with open(thefile, 'w') as OFH:
                    OFH.write(json.dumps(contexts['anchore_db'].load_image_new(imageId)))

            stored_namespaces = contexts['anchore_db'].load_files_namespaces(imageId)
            for namespace in stored_namespaces:
                stored_files = contexts['anchore_db'].load_files_tarfile(imageId, namespace)
                if os.path.exists(stored_files):
                    thedir = os.path.join(storedir, imageId, namespace)
                    if not os.path.exists(thedir):
                        os.makedirs(thedir)
                    thefile = os.path.join(thedir, "stored_files.tar.gz")
                    shutil.copy(stored_files, thefile)

        anchore_print("exporting feeds...")
        feedmeta = contexts['anchore_db'].load_feedmeta()
        thefile = os.path.join(feeddir, "feedmeta.json")
        with open(thefile, 'w') as OFH:
            OFH.write(json.dumps(feedmeta))

        for feed in feedmeta:
            feedobj = feedmeta[feed]
            for group in feedobj['groups']:
                groupobj = feedobj['groups'][group]
                datafiles = groupobj.pop('datafiles', [])
                for datafile in datafiles:
                    thedir = os.path.join(feeddir, feed, group)
                    if not os.path.exists(thedir):
                        os.makedirs(thedir)
                    thefile = os.path.join(thedir, datafile)
                    if not os.path.exists(thefile):
                        with open(thefile, 'w') as OFH:
                            OFH.write(json.dumps(contexts['anchore_db'].load_feed_group_data(feed, group, datafile)))

    except Exception as err:
        anchore_print_err("operation failed: " + str(err))
        ecode = 1

    sys.exit(ecode)
170732
def write_image(r, filename):
    
    with open(filename, 'wb') as fd:
        for chunk in r.iter_content(1024):
            fd.write(chunk)
32336
def dump_info(self, dump=None):
        """"""
        
        
        if dump is None:
            dump = Dump()
        
        warnings = self.get_warnings()
        if warnings:
            dump.add_header('Parsing Warnings')
            for warning in warnings:
                dump.add_line(warning)
                dump.add_newline()
        
        
        dump.add_header('DOS_HEADER')
        dump.add_lines(self.DOS_HEADER.dump())
        dump.add_newline()
        
        dump.add_header('NT_HEADERS')
        dump.add_lines(self.NT_HEADERS.dump())
        dump.add_newline()
        
        dump.add_header('FILE_HEADER')
        dump.add_lines(self.FILE_HEADER.dump())
        
        image_flags = retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_')
        
        dump.add('Flags: ')
        flags = []
        for flag in image_flags:
            if getattr(self.FILE_HEADER, flag[0]):
                flags.append(flag[0])
        dump.add_line(', '.join(flags))
        dump.add_newline()
        
        if hasattr(self, 'OPTIONAL_HEADER') and self.OPTIONAL_HEADER is not None:
            dump.add_header('OPTIONAL_HEADER')
            dump.add_lines(self.OPTIONAL_HEADER.dump())
        
        dll_characteristics_flags = retrieve_flags(DLL_CHARACTERISTICS, 'IMAGE_DLL_CHARACTERISTICS_')
        
        dump.add('DllCharacteristics: ')
        flags = []
        for flag in dll_characteristics_flags:
            if getattr(self.OPTIONAL_HEADER, flag[0]):
                flags.append(flag[0])
        dump.add_line(', '.join(flags))
        dump.add_newline()
        
        
        dump.add_header('PE Sections')
        
        section_flags = retrieve_flags(SECTION_CHARACTERISTICS, 'IMAGE_SCN_')
        
        for section in self.sections:
            dump.add_lines(section.dump())
            dump.add('Flags: ')
            flags = []
            for flag in section_flags:
                if getattr(section, flag[0]):
                    flags.append(flag[0])
            dump.add_line(', '.join(flags))
            dump.add_line('Entropy: %f (Min=0.0, Max=8.0)' % section.get_entropy() )
            if md5 is not None:
                dump.add_line('MD5     hash: %s' % section.get_hash_md5() )
            if sha1 is not None:
                dump.add_line('SHA-1   hash: %s' % section.get_hash_sha1() )
            if sha256 is not None:
                dump.add_line('SHA-256 hash: %s' % section.get_hash_sha256() )
            if sha512 is not None:
                dump.add_line('SHA-512 hash: %s' % section.get_hash_sha512() )
            dump.add_newline()
            
        
        
        if (hasattr(self, 'OPTIONAL_HEADER') and
            hasattr(self.OPTIONAL_HEADER, 'DATA_DIRECTORY') ):
            
            dump.add_header('Directories')
            for idx in xrange(len(self.OPTIONAL_HEADER.DATA_DIRECTORY)):
                directory = self.OPTIONAL_HEADER.DATA_DIRECTORY[idx]
                dump.add_lines(directory.dump())
            dump.add_newline()
            
        
        def convert_char(char):
            if char in string.ascii_letters or char in string.digits or char in string.punctuation or char in string.whitespace:
                return char
            else:
                return r'\x%02x' % ord(char)
                
        def convert_to_printable(s):
            return ''.join([convert_char(c) for c in s])
        
        if hasattr(self, 'VS_VERSIONINFO'):
            dump.add_header('Version Information')
            dump.add_lines(self.VS_VERSIONINFO.dump())
            dump.add_newline()
            
            if hasattr(self, 'VS_FIXEDFILEINFO'):
                dump.add_lines(self.VS_FIXEDFILEINFO.dump())
                dump.add_newline()
            
            if hasattr(self, 'FileInfo'):
                for entry in self.FileInfo:
                    dump.add_lines(entry.dump())
                    dump.add_newline()
                    
                    if hasattr(entry, 'StringTable'):
                        for st_entry in entry.StringTable:
                            [dump.add_line('  '+line) for line in st_entry.dump()]
                            dump.add_line('  LangID: '+st_entry.LangID)
                            dump.add_newline()
                            for str_entry in st_entry.entries.items():
                                dump.add_line( '    ' +
                                    convert_to_printable(str_entry[0]) + ': ' +
                                    convert_to_printable(str_entry[1]) )
                        dump.add_newline()
                    
                    elif hasattr(entry, 'Var'):
                        for var_entry in entry.Var:
                            if hasattr(var_entry, 'entry'):
                                [dump.add_line('  '+line) for line in var_entry.dump()]
                                dump.add_line(
                                    '    ' + 
                                    convert_to_printable(var_entry.entry.keys()[0]) +
                                    ': ' + var_entry.entry.values()[0])
                        
                        dump.add_newline()

            
        
        if hasattr(self, 'DIRECTORY_ENTRY_EXPORT'):
            dump.add_header('Exported symbols')
            dump.add_lines(self.DIRECTORY_ENTRY_EXPORT.struct.dump())
            dump.add_newline()
            dump.add_line('%-10s   %-10s  %s' % ('Ordinal', 'RVA', 'Name'))
            for export in self.DIRECTORY_ENTRY_EXPORT.symbols:
                if export.address is not None:
                    dump.add('%-10d 0x%08Xh    %s' % (
                        export.ordinal, export.address, export.name))
                    if export.forwarder:
                        dump.add_line(' forwarder: %s' % export.forwarder)
                    else:
                        dump.add_newline()
            
            dump.add_newline()
        
        if hasattr(self, 'DIRECTORY_ENTRY_IMPORT'):
            dump.add_header('Imported symbols')
            for module in self.DIRECTORY_ENTRY_IMPORT:
                dump.add_lines(module.struct.dump())
                dump.add_newline()
                for symbol in module.imports:
                    
                    if symbol.import_by_ordinal is True:
                        dump.add('%s Ordinal[%s] (Imported by Ordinal)' % (
                            module.dll, str(symbol.ordinal)))
                    else:
                        dump.add('%s.%s Hint[%s]' % (
                            module.dll, symbol.name, str(symbol.hint)))
                    
                    if symbol.bound:
                        dump.add_line(' Bound: 0x%08X' % (symbol.bound))
                    else:
                        dump.add_newline()
                dump.add_newline()
        
        
        if hasattr(self, 'DIRECTORY_ENTRY_BOUND_IMPORT'):
            dump.add_header('Bound imports')
            for bound_imp_desc in self.DIRECTORY_ENTRY_BOUND_IMPORT:
                
                dump.add_lines(bound_imp_desc.struct.dump())
                dump.add_line('DLL: %s' % bound_imp_desc.name)
                dump.add_newline()
                
                for bound_imp_ref in bound_imp_desc.entries:
                    dump.add_lines(bound_imp_ref.struct.dump(), 4)
                    dump.add_line('DLL: %s' % bound_imp_ref.name, 4)
                    dump.add_newline()

        
        if hasattr(self, 'DIRECTORY_ENTRY_DELAY_IMPORT'):
            dump.add_header('Delay Imported symbols')
            for module in self.DIRECTORY_ENTRY_DELAY_IMPORT:
                
                dump.add_lines(module.struct.dump())
                dump.add_newline()
                
                for symbol in module.imports:
                    if symbol.import_by_ordinal is True:
                        dump.add('%s Ordinal[%s] (Imported by Ordinal)' % (
                            module.dll, str(symbol.ordinal)))
                    else:
                        dump.add('%s.%s Hint[%s]' % (
                            module.dll, symbol.name, str(symbol.hint)))
                    
                    if symbol.bound:
                        dump.add_line(' Bound: 0x%08X' % (symbol.bound))
                    else:
                        dump.add_newline()
                dump.add_newline()
        
        
        if hasattr(self, 'DIRECTORY_ENTRY_RESOURCE'):
            dump.add_header('Resource directory')
            
            dump.add_lines(self.DIRECTORY_ENTRY_RESOURCE.struct.dump())
            
            for resource_type in self.DIRECTORY_ENTRY_RESOURCE.entries:
                
                if resource_type.name is not None:
                    dump.add_line('Name: [%s]' % resource_type.name, 2)
                else:
                    dump.add_line('Id: [0x%X] (%s)' % (
                        resource_type.struct.Id, RESOURCE_TYPE.get(
                            resource_type.struct.Id, '-')),
                        2)
                
                dump.add_lines(resource_type.struct.dump(), 2)
                
                if hasattr(resource_type, 'directory'):
                    
                    dump.add_lines(resource_type.directory.struct.dump(), 4)
                    
                    for resource_id in resource_type.directory.entries:
                        
                        if resource_id.name is not None:
                            dump.add_line('Name: [%s]' % resource_id.name, 6)
                        else:
                            dump.add_line('Id: [0x%X]' % resource_id.struct.Id, 6)
                        
                        dump.add_lines(resource_id.struct.dump(), 6)
                        
                        if hasattr(resource_id, 'directory'):
                            dump.add_lines(resource_id.directory.struct.dump(), 8)
                            
                            for resource_lang in resource_id.directory.entries:
                                if hasattr(resource_lang, 'data'):
                                    dump.add_line('\\--- LANG [%d,%d][%s,%s]' % (
                                        resource_lang.data.lang,
                                        resource_lang.data.sublang,
                                        LANG.get(resource_lang.data.lang, '*unknown*'), 
                                        get_sublang_name_for_lang( resource_lang.data.lang, resource_lang.data.sublang ) ), 8)
                                    dump.add_lines(resource_lang.struct.dump(), 10)
                                    dump.add_lines(resource_lang.data.struct.dump(), 12)
                            if hasattr(resource_id.directory, 'strings') and resource_id.directory.strings:
                                dump.add_line( '[STRINGS]' , 10 )
                                for idx, res_string in resource_id.directory.strings.items():
                                    dump.add_line( '%6d: %s' % (idx, convert_to_printable(res_string) ), 12 )
                                        
                dump.add_newline()
            
            dump.add_newline()
        
        
        if ( hasattr(self, 'DIRECTORY_ENTRY_TLS') and
             self.DIRECTORY_ENTRY_TLS and
             self.DIRECTORY_ENTRY_TLS.struct ):
            
            dump.add_header('TLS')
            dump.add_lines(self.DIRECTORY_ENTRY_TLS.struct.dump())
            dump.add_newline()
        
        
        if ( hasattr(self, 'DIRECTORY_ENTRY_LOAD_CONFIG') and
             self.DIRECTORY_ENTRY_LOAD_CONFIG and
             self.DIRECTORY_ENTRY_LOAD_CONFIG.struct ):
             
            dump.add_header('LOAD_CONFIG')
            dump.add_lines(self.DIRECTORY_ENTRY_LOAD_CONFIG.struct.dump())
            dump.add_newline()
        
        
        if hasattr(self, 'DIRECTORY_ENTRY_DEBUG'):
            dump.add_header('Debug information')
            for dbg in self.DIRECTORY_ENTRY_DEBUG:
                dump.add_lines(dbg.struct.dump())
                try:
                    dump.add_line('Type: '+DEBUG_TYPE[dbg.struct.Type])
                except KeyError:
                    dump.add_line('Type: 0x%x(Unknown)' % dbg.struct.Type)
                dump.add_newline()
        
        
        if hasattr(self, 'DIRECTORY_ENTRY_BASERELOC'):
            dump.add_header('Base relocations')
            for base_reloc in self.DIRECTORY_ENTRY_BASERELOC:
                dump.add_lines(base_reloc.struct.dump())
                for reloc in base_reloc.entries:
                    try:
                        dump.add_line('%08Xh %s' % (
                            reloc.rva, RELOCATION_TYPE[reloc.type][16:]), 4)
                    except KeyError:
                        dump.add_line('0x%08X 0x%x(Unknown)' % (
                            reloc.rva, reloc.type), 4)
                dump.add_newline()

        
        return dump.get_text()
648466
protected void writeFull() {
        byte[] imageData = rawImage.getData();
        int numOfComponents = frameHeader.getNf();
        int[] pixes = new int[numOfComponents * DCTSIZE2];
        int blockIndex = 0;
        int startCoordinate = 0, scanlineStride = numOfComponents * rawImage.getWidth(), row = 0;

        x = 0;
        y = 0;

        for (int m = 0; m < MCUsPerColumn * MCUsPerRow; m++) {
            blockIndex = 0;

            // one MCU
            for (int v = 0; v < maxVSampleFactor; v++) {
                for (int h = 0; h < maxHSampleFactor; h++) {
                    row = y + 1;
                    startCoordinate = (y * rawImage.getWidth() + x) * numOfComponents;

                    // one block
                    for (int k = blockIndex * DCTSIZE2, i = 0; k < blockIndex * DCTSIZE2 + DCTSIZE2; k++) {
                        pixes[i++] = allMCUDatas[0][m][k];

                        if (numOfComponents > 1) {
                            pixes[i++] = allMCUDatas[1][m][k];
                            pixes[i++] = allMCUDatas[2][m][k];
                        }

                        if (numOfComponents > 3) {
                            pixes[i++] = allMCUDatas[3][m][k];
                        }

                        x++;

                        if (x % 8 == 0) {
                            y++;
                            x -= 8;
                        }
                    }

                    colorConvertor.convertBlock(pixes, 0, imageData, numOfComponents, startCoordinate, row,
                                                scanlineStride);

                    blockIndex++;

                    x += 8;
                    y -= 8;
                }

                x -= maxHSampleFactor * 8;
                y += 8;
            }

            x += maxHSampleFactor * 8;
            y -= maxVSampleFactor * 8;

            if (x >= rawImage.getWidth()) {
                x = 0;
                y += maxVSampleFactor * 8;
            }

        }
    }
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
314046
def WritePythonFile(file_descriptor, package, version, printer):
    """"""
    _WriteFile(file_descriptor, package, version,
               _ProtoRpcPrinter(printer))
268254
def imgwriteincr(fn: Path, imgs, imgslice):
    
    if isinstance(imgslice, int):
        if imgslice and not (imgslice % 2000):
            print(f'appending images {imgslice} to {fn}')

    if isinstance(fn, Path):
        # avoid accidental overwriting of source file due to misspecified command line
        assert fn.suffix == '.h5', 'Expecting to write .h5 file'

        with h5py.File(fn, 'r+') as f:
            f['/rawimg'][imgslice, :, :] = imgs
    elif isinstance(fn, h5py.File):
        f['/rawimg'][imgslice, :, :] = imgs
    else:
        raise TypeError(
            f'{fn} must be Path or h5py.File instead of {type(fn)}')
785489
def write_image_to_disk(self, msg, result, fh):
        """"""
        cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh)
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
122441
def dump_info(self, dump=None, encoding='ascii'):
        """"""

        if dump is None:
            dump = Dump()

        warnings = self.get_warnings()
        if warnings:
            dump.add_header('Parsing Warnings')
            for warning in warnings:
                dump.add_line(warning)
                dump.add_newline()


        dump.add_header('DOS_HEADER')
        dump.add_lines(self.DOS_HEADER.dump())
        dump.add_newline()

        dump.add_header('NT_HEADERS')
        dump.add_lines(self.NT_HEADERS.dump())
        dump.add_newline()

        dump.add_header('FILE_HEADER')
        dump.add_lines(self.FILE_HEADER.dump())

        image_flags = retrieve_flags(IMAGE_CHARACTERISTICS, 'IMAGE_FILE_')

        dump.add('Flags: ')
        flags = []
        for flag in sorted(image_flags):
            if getattr(self.FILE_HEADER, flag[0]):
                flags.append(flag[0])
        dump.add_line(', '.join(flags))
        dump.add_newline()

        if hasattr(self, 'OPTIONAL_HEADER') and self.OPTIONAL_HEADER is not None:
            dump.add_header('OPTIONAL_HEADER')
            dump.add_lines(self.OPTIONAL_HEADER.dump())

        dll_characteristics_flags = retrieve_flags(DLL_CHARACTERISTICS, 'IMAGE_DLLCHARACTERISTICS_')

        dump.add('DllCharacteristics: ')
        flags = []
        for flag in sorted(dll_characteristics_flags):
            if getattr(self.OPTIONAL_HEADER, flag[0]):
                flags.append(flag[0])
        dump.add_line(', '.join(flags))
        dump.add_newline()


        dump.add_header('PE Sections')

        section_flags = retrieve_flags(SECTION_CHARACTERISTICS, 'IMAGE_SCN_')

        for section in self.sections:
            dump.add_lines(section.dump())
            dump.add('Flags: ')
            flags = []
            for flag in sorted(section_flags):
                if getattr(section, flag[0]):
                    flags.append(flag[0])
            dump.add_line(', '.join(flags))
            dump.add_line('Entropy: {0:f} (Min=0.0, Max=8.0)'.format(
                section.get_entropy()))
            if md5 is not None:
                dump.add_line('MD5     hash: {0}'.format(
                    section.get_hash_md5()))
            if sha1 is not None:
                dump.add_line('SHA-1   hash: %s' % section.get_hash_sha1() )
            if sha256 is not None:
                dump.add_line('SHA-256 hash: %s' % section.get_hash_sha256() )
            if sha512 is not None:
                dump.add_line('SHA-512 hash: %s' % section.get_hash_sha512() )
            dump.add_newline()



        if (hasattr(self, 'OPTIONAL_HEADER') and
            hasattr(self.OPTIONAL_HEADER, 'DATA_DIRECTORY') ):

            dump.add_header('Directories')
            for idx in range(len(self.OPTIONAL_HEADER.DATA_DIRECTORY)):
                directory = self.OPTIONAL_HEADER.DATA_DIRECTORY[idx]
                dump.add_lines(directory.dump())
            dump.add_newline()

        if hasattr(self, 'VS_VERSIONINFO'):
            for idx in range(len(self.VS_VERSIONINFO)):
                if len(self.VS_VERSIONINFO) > 1:
                    dump.add_header('Version Information {:d}'.format(idx + 1))
                else:
                    dump.add_header('Version Information')
                dump.add_lines(self.VS_VERSIONINFO[idx].dump())
                dump.add_newline()

                if hasattr(self, 'VS_FIXEDFILEINFO'):
                    dump.add_lines(self.VS_FIXEDFILEINFO[idx].dump())
                    dump.add_newline()

                if hasattr(self, 'FileInfo') and len(self.FileInfo) > idx:
                    for entry in self.FileInfo[idx]:
                        dump.add_lines(entry.dump())
                        dump.add_newline()

                        if hasattr(entry, 'StringTable'):
                            for st_entry in entry.StringTable:
                                [dump.add_line(u'  '+line) for line in st_entry.dump()]
                                dump.add_line(u'  LangID: {0}'.format(
                                    st_entry.LangID.decode(encoding, 'backslashreplace_')))
                                dump.add_newline()
                                for str_entry in sorted(list(st_entry.entries.items())):
                                    # try:
                                    dump.add_line( u'    {0}: {1}'.format(
                                        str_entry[0].decode(encoding, 'backslashreplace_'),
                                        str_entry[1].decode(encoding, 'backslashreplace_')))

                            dump.add_newline()

                        elif hasattr(entry, 'Var'):
                            for var_entry in entry.Var:
                                if hasattr(var_entry, 'entry'):
                                    [dump.add_line('  '+line) for line in var_entry.dump()]
                                    dump.add_line(
                                        u'    {0}: {1}'.format(
                                            list(var_entry.entry.keys())[0].decode(
                                                'utf-8', 'backslashreplace_'),
                                            list(var_entry.entry.values())[0]))

                            dump.add_newline()

        if hasattr(self, 'DIRECTORY_ENTRY_EXPORT'):
            dump.add_header('Exported symbols')
            dump.add_lines(self.DIRECTORY_ENTRY_EXPORT.struct.dump())
            dump.add_newline()
            dump.add_line(u'%-10s   %-10s  %s' % ('Ordinal', 'RVA', 'Name'))
            for export in self.DIRECTORY_ENTRY_EXPORT.symbols:
                if export.address is not None:
                    name = b('None')
                    if export.name:
                        name = export.name
                    dump.add(u'%-10d 0x%08X    %s' % (
                        export.ordinal, export.address, name.decode(encoding)))
                    if export.forwarder:
                        dump.add_line(u' forwarder: {0}'.format(
                            export.forwarder.decode(encoding, 'backslashreplace_')))
                    else:
                        dump.add_newline()

            dump.add_newline()

        if hasattr(self, 'DIRECTORY_ENTRY_IMPORT'):
            dump.add_header('Imported symbols')
            for module in self.DIRECTORY_ENTRY_IMPORT:
                dump.add_lines(module.struct.dump())
                # Print the name of the DLL if there are no imports.
                if not module.imports:
                    dump.add('  Name -> {0}'.format(
                        self.get_string_at_rva(module.struct.Name).decode(
                            encoding, 'backslashreplace_')))
                    dump.add_newline()
                dump.add_newline()
                for symbol in module.imports:
                    if symbol.import_by_ordinal is True:
                        if symbol.name is not None:
                            dump.add('{0}.{1} Ordinal[{2}] (Imported by Ordinal)'.format(
                                     module.dll.decode('utf-8'),
                                     symbol.name.decode('utf-8'),
                                     symbol.ordinal))
                        else:
                            dump.add('{0} Ordinal[{1}] (Imported by Ordinal)'.format(
                                module.dll.decode('utf-8'), symbol.ordinal))
                    else:
                        dump.add('{0}.{1} Hint[{2:d}]'.format(
                            module.dll.decode(encoding, 'backslashreplace_'),
                            symbol.name.decode(encoding, 'backslashreplace_'),
                            symbol.hint))

                    if symbol.bound:
                        dump.add_line(' Bound: 0x{0:08X}'.format(symbol.bound))
                    else:
                        dump.add_newline()
                dump.add_newline()


        if hasattr(self, 'DIRECTORY_ENTRY_BOUND_IMPORT'):
            dump.add_header('Bound imports')
            for bound_imp_desc in self.DIRECTORY_ENTRY_BOUND_IMPORT:

                dump.add_lines(bound_imp_desc.struct.dump())
                dump.add_line('DLL: {0}'.format(
                    bound_imp_desc.name.decode(encoding, 'backslashreplace_')))
                dump.add_newline()

                for bound_imp_ref in bound_imp_desc.entries:
                    dump.add_lines(bound_imp_ref.struct.dump(), 4)
                    dump.add_line('DLL: {0}'.format(
                        bound_imp_ref.name.decode(encoding, 'backslashreplace_')), 4)
                    dump.add_newline()


        if hasattr(self, 'DIRECTORY_ENTRY_DELAY_IMPORT'):
            dump.add_header('Delay Imported symbols')
            for module in self.DIRECTORY_ENTRY_DELAY_IMPORT:

                dump.add_lines(module.struct.dump())
                dump.add_newline()

                for symbol in module.imports:
                    if symbol.import_by_ordinal is True:
                        dump.add('{0} Ordinal[{1:d}] (Imported by Ordinal)'.format(
                            module.dll.decode(encoding, 'backslashreplace_'),
                            symbol.ordinal))
                    else:
                        dump.add('{0}.{1} Hint[{2}]'.format(
                            module.dll.decode(encoding, 'backslashreplace_'),
                            symbol.name.decode(encoding, 'backslashreplace_'), symbol.hint))

                    if symbol.bound:
                        dump.add_line(' Bound: 0x{0:08X}'.format(symbol.bound))
                    else:
                        dump.add_newline()
                dump.add_newline()


        if hasattr(self, 'DIRECTORY_ENTRY_RESOURCE'):
            dump.add_header('Resource directory')

            dump.add_lines(self.DIRECTORY_ENTRY_RESOURCE.struct.dump())

            for resource_type in self.DIRECTORY_ENTRY_RESOURCE.entries:

                if resource_type.name is not None:
                    # name = str(resource_type.name) #.string if resource_type.name.string else ''
                    dump.add_line(u'Name: [{0}]'.format(
                        resource_type.name.decode(encoding, 'backslashreplace_')
                        ), 2)
                else:
                    dump.add_line(u'Id: [0x{0:X}] ({1})'.format(
                        resource_type.struct.Id, RESOURCE_TYPE.get(
                            resource_type.struct.Id, '-')),
                        2)

                dump.add_lines(resource_type.struct.dump(), 2)

                if hasattr(resource_type, 'directory'):

                    dump.add_lines(resource_type.directory.struct.dump(), 4)

                    for resource_id in resource_type.directory.entries:

                        if resource_id.name is not None:
                            dump.add_line(u'Name: [{0}]'.format(
                                resource_id.name.decode(
                                    'utf-8', 'backslashreplace_')), 6)
                        else:
                            dump.add_line('Id: [0x{0:X}]'.format(resource_id.struct.Id), 6)

                        dump.add_lines(resource_id.struct.dump(), 6)

                        if hasattr(resource_id, 'directory'):
                            dump.add_lines(resource_id.directory.struct.dump(), 8)

                            for resource_lang in resource_id.directory.entries:
                                if hasattr(resource_lang, 'data'):
                                    dump.add_line(u'\\--- LANG [%d,%d][%s,%s]' % (
                                        resource_lang.data.lang,
                                        resource_lang.data.sublang,
                                        LANG.get(resource_lang.data.lang, '*unknown*'),
                                        get_sublang_name_for_lang( resource_lang.data.lang, resource_lang.data.sublang ) ), 8)
                                    dump.add_lines(resource_lang.struct.dump(), 10)
                                    dump.add_lines(resource_lang.data.struct.dump(), 12)
                            if hasattr(resource_id.directory, 'strings') and resource_id.directory.strings:
                                dump.add_line(u'[STRINGS]' , 10 )
                                for idx, res_string in list(sorted(resource_id.directory.strings.items())):
                                    dump.add_line( '{0:6d}: {1}'.format(idx,
                                        res_string.encode(
                                            'unicode-escape',
                                            'backslashreplace').decode(
                                                'ascii')),
                                        12)

                dump.add_newline()

            dump.add_newline()


        if ( hasattr(self, 'DIRECTORY_ENTRY_TLS') and
             self.DIRECTORY_ENTRY_TLS and
             self.DIRECTORY_ENTRY_TLS.struct ):

            dump.add_header('TLS')
            dump.add_lines(self.DIRECTORY_ENTRY_TLS.struct.dump())
            dump.add_newline()


        if ( hasattr(self, 'DIRECTORY_ENTRY_LOAD_CONFIG') and
             self.DIRECTORY_ENTRY_LOAD_CONFIG and
             self.DIRECTORY_ENTRY_LOAD_CONFIG.struct ):

            dump.add_header('LOAD_CONFIG')
            dump.add_lines(self.DIRECTORY_ENTRY_LOAD_CONFIG.struct.dump())
            dump.add_newline()

        if hasattr(self, 'DIRECTORY_ENTRY_DEBUG'):
            dump.add_header('Debug information')
            for dbg in self.DIRECTORY_ENTRY_DEBUG:
                dump.add_lines(dbg.struct.dump())
                try:
                    dump.add_line('Type: '+DEBUG_TYPE[dbg.struct.Type])
                except KeyError:
                    dump.add_line(
                        'Type: 0x{0:x}(Unknown)'.format(dbg.struct.Type))
                dump.add_newline()
                if dbg.entry:
                    dump.add_lines(dbg.entry.dump(), 4)
                    dump.add_newline()

        if self.has_relocs():
            dump.add_header('Base relocations')
            for base_reloc in self.DIRECTORY_ENTRY_BASERELOC:
                dump.add_lines(base_reloc.struct.dump())
                for reloc in base_reloc.entries:
                    try:
                        dump.add_line('%08Xh %s' % (
                            reloc.rva, RELOCATION_TYPE[reloc.type][16:]), 4)
                    except KeyError:
                        dump.add_line('0x%08X 0x%x(Unknown)' % (
                            reloc.rva, reloc.type), 4)
                dump.add_newline()

        return dump.get_text()
521362
def output_to_fd(self, fd):
        
        for library in self.libraries_found:
            fd.write("%s==%s\n" % (library.key, library.version))