Ejemplo n.º 1
0
def _write_log_pass_content_in_html(
        logical_file: LogicalFile.LogicalFile,
        xhtml_stream: XmlWrite.XhtmlStream,
        # Used for anchor
        logical_file_index: int,
        number_of_preceeding_eflrs: int,
        *,
        frame_slice: Slice.Slice) -> typing.Tuple[HTMLFrameArraySummary]:
    assert logical_file.has_log_pass
    ret = []
    lp: LogPass.LogPass = logical_file.log_pass
    frame_array: LogPass.FrameArray
    for fa, frame_array in enumerate(lp.frame_arrays):
        anchor = _anchor(logical_file_index, number_of_preceeding_eflrs, fa)
        with XmlWrite.Element(xhtml_stream, 'a', {'id': anchor}):
            pass
        with XmlWrite.Element(xhtml_stream, 'h3'):
            xhtml_stream.characters(
                f'Frame Array: {stringify.stringify_object_by_type(frame_array.ident)} [{fa}/{len(lp.frame_arrays)}]'
            )
        ret.append(
            _write_frame_array_in_html(
                logical_file,
                frame_array,
                frame_slice,
                anchor,
                xhtml_stream,
            ))
    return tuple(ret)
Ejemplo n.º 2
0
def write_logical_file_to_xml(logical_file_index: int,
                              logical_file: LogicalFile,
                              xml_stream: XmlWrite.XmlStream,
                              private: bool) -> None:
    with XmlWrite.Element(
            xml_stream,
            'LogicalFile',
        {
            'has_log_pass': str(logical_file.has_log_pass),
            'index': f'{logical_file_index:d}',
            # 'schema_version': XML_SCHEMA_VERSION,
        }):
        for position, eflr in logical_file.eflrs:
            attrs = {
                'vr_position': f'0x{position.vr_position:x}',
                'lrsh_position': f'0x{position.lrsh_position:x}',
                'lr_type': f'{eflr.lr_type:d}',
                'set_type': f'{eflr.set.type.decode("ascii")}',
                'set_name': f'{eflr.set.name.decode("ascii")}',
                'object_count': f'{len(eflr.objects):d}'
            }
            with XmlWrite.Element(xml_stream, 'EFLR', attrs):
                if private or LogicalRecord.Types.is_public(eflr.lr_type):
                    for obj in eflr.objects:
                        _write_xml_eflr_object(obj, xml_stream)
        if logical_file.has_log_pass:
            log_pass_to_XML(logical_file.log_pass,
                            logical_file.iflr_position_map, xml_stream)
Ejemplo n.º 3
0
    def test_08(self):
        """TestXmlWrite.test_08(): raise during write."""
        myF = io.StringIO()
        try:
            with XmlWrite.XmlStream(myF) as xS:
                with XmlWrite.Element(xS, 'Root', {'version': '12.0'}):
                    self.assertRaises(XmlWrite.ExceptionXmlEndElement,
                                      xS.endElement, 'NotRoot')
                    with XmlWrite.Element(xS, 'E', {'attr_1': '1'}):
                        xS._elemStk.pop()
                        xS._elemStk.append('F')
                        raise Exception('Some exception')
        except Exception as e:
            print(e)
        else:
            print('No exception raised')


#        print()
#        print(myF.getvalue())
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<Root version="12.0">
  <E attr_1="1"/>
</Root>
""")
Ejemplo n.º 4
0
def xml_write_value(xml_stream: XmlWrite.XmlStream, value: typing.Any) -> None:
    """Write a value to the XML stream with specific type as an attribute.
    This writes either a <Value> or an <ObjectName> element."""
    if isinstance(value, RepCode.ObjectName):
        with XmlWrite.Element(xml_stream, 'ObjectName',
                              xml_object_name_attributes(value)):
            pass
    else:
        if isinstance(value, bytes):
            typ = 'bytes'
            # print('TRACE: xml_write_value()', value)
            _value = value.decode('latin-1')  #, errors='ignore')
        elif isinstance(value, float):
            typ = 'float'
            _value = str(value)
        elif isinstance(value, int):
            typ = 'int'
            _value = str(value)
        elif isinstance(value, RepCode.DateTime):
            typ = 'TotalDepth.RP66V1.core.RepCode.DateTime'
            _value = str(value)
        elif isinstance(value, str):  # pragma: no cover
            typ = 'str'
            _value = value
        else:
            typ = 'unknown'
            _value = str(value)
        with XmlWrite.Element(xml_stream, 'Value', {
                'type': typ,
                'value': _value
        }):
            pass
Ejemplo n.º 5
0
 def _HTMLVerbatim(self, theIe, theFi, theS):
     self._HTMLEntryBasic(theIe, theS)
     theIe.setLogicalRecord(theFi)
     myLr = theIe.logicalRecord
     assert (myLr is not None)
     with XmlWrite.Element(theS, 'p'):
         theS.characters('Verbatim bytes [{:d}]:'.format(len(myLr.bytes)))
     with XmlWrite.Element(theS, 'pre', {'class': 'verbatim'}):
         theS.characters(myLr.bytes.decode('ascii', 'replace'))
Ejemplo n.º 6
0
def writeHtmlFileAnchor(theS, theLineNum, theText='', theClass=None):
    """Write an anchor to the stream."""
    with XmlWrite.Element(theS, 'a', {'name': "%d" % theLineNum}):
        if theText:
            if theClass is None:
                theS.characters(theText)
            else:
                with XmlWrite.Element(theS, 'span', {'class': theClass}):
                    theS.characters(theText)
Ejemplo n.º 7
0
def frame_array_to_XML(frame_array: LogPass.FrameArray,
                       iflr_data: typing.Sequence[IFLRReference],
                       xml_stream: XmlWrite.XmlStream) -> None:
    """Writes a XML FrameArray node suitable for RP66V1.

    Example:

    .. code-block:: xml

        <FrameArray C="0" I="0B" O="11" description="">
          <Channels channel_count="9">
            <Channel C="0" I="DEPT" O="11" count="1" dimensions="1" long_name="MWD Tool Measurement Depth" rep_code="2" units="0.1 in"/>
            <Channel C="0" I="INC" O="11" count="1" dimensions="1" long_name="Inclination" rep_code="2" units="deg"/>
            <Channel C="0" I="AZI" O="11" count="1" dimensions="1" long_name="Azimuth" rep_code="2" units="deg"/>
            ...
          </Channels>
          <IFLR count="83">
              <FrameNumbers count="83" rle_len="1">
                <RLE datum="1" repeat="82" stride="1"/>
              </FrameNumbers>
              <LRSH count="83" rle_len="2">
                <RLE datum="0x14ac" repeat="61" stride="0x30"/>
                <RLE datum="0x2050" repeat="20" stride="0x30"/>
              </LRSH>
              <Xaxis count="83" rle_len="42">
                <RLE datum="0.0" repeat="1" stride="75197.0"/>
                <RLE datum="154724.0" repeat="1" stride="79882.0"/>
              </Xaxis>
          </IFLR>
        </FrameArray>
    """
    frame_array_attrs = {
        'O': f'{frame_array.ident.O}',
        'C': f'{frame_array.ident.C}',
        'I': f'{frame_array.ident.I.decode("ascii")}',
        'description': frame_array.description.decode('ascii'),
        'x_axis': frame_array.channels[0].ident.I.decode("ascii"),
        'x_units': frame_array.channels[0].units.decode("ascii"),
    }

    with XmlWrite.Element(xml_stream, 'FrameArray', frame_array_attrs):
        with XmlWrite.Element(xml_stream, 'Channels',
                              {'count': f'{len(frame_array)}'}):
            for channel in frame_array.channels:
                frame_channel_to_XML(channel, xml_stream)
        with XmlWrite.Element(xml_stream, 'IFLR',
                              {'count': f'{len(iflr_data)}'}):
            # Frame number output
            rle = Rle.create_rle(v.frame_number for v in iflr_data)
            xml_rle_write(rle, 'FrameNumbers', xml_stream, hex_output=False)
            # IFLR file position
            rle = Rle.create_rle(v.logical_record_position.lrsh_position
                                 for v in iflr_data)
            xml_rle_write(rle, 'LRSH', xml_stream, hex_output=True)
            # Xaxis output
            rle = Rle.create_rle(v.x_axis for v in iflr_data)
            xml_rle_write(rle, 'Xaxis', xml_stream, hex_output=False)
Ejemplo n.º 8
0
 def _writeHtmlToc(self, myFi, myIdx, theS):
     """Write the table of contents at the top of the page."""
     with XmlWrite.Element(theS, 'a', {'name' : 'toc'}):
         pass
     with XmlWrite.Element(theS, 'h1', {}):
         theS.characters('Logical records in {:s}'.format(myFi.fileId))
     for anIdx in myIdx.genAll():
         with XmlWrite.Element(theS, 'p', {}):
             theS.literal('&nbsp;' * 8 * self._retIndentDepth(anIdx))
             with XmlWrite.Element(theS, 'a', {'href' : '#{:d}'.format(anIdx.tell)}):
                 theS.characters(anIdx.tocStr())
Ejemplo n.º 9
0
def write_logical_file_sequence_to_xml(logical_index: LogicalFile.LogicalIndex,
                                       output_stream: typing.TextIO,
                                       private: bool) -> None:
    """Takes a LogicalIndex and writes the index to an XML stream."""
    with XmlWrite.XmlStream(output_stream) as xml_stream:
        with XmlWrite.Element(
                xml_stream, 'RP66V1FileIndex', {
                    'path':
                    logical_index.id,
                    'size':
                    f'{os.path.getsize(logical_index.id):d}',
                    'schema_version':
                    XML_SCHEMA_VERSION,
                    'utc_file_mtime':
                    str(
                        datetime.datetime.utcfromtimestamp(
                            os.stat(logical_index.id).st_mtime)),
                    'utc_now':
                    str(datetime.datetime.utcnow()),
                    'creator':
                    f'{__name__}',
                }):
            with XmlWrite.Element(
                    xml_stream, 'StorageUnitLabel', {
                        'sequence_number':
                        str(logical_index.storage_unit_label.
                            storage_unit_sequence_number),
                        'dlis_version':
                        logical_index.storage_unit_label.dlis_version.decode(
                            'ascii'),
                        'storage_unit_structure':
                        logical_index.storage_unit_label.
                        storage_unit_structure.decode('ascii'),
                        'maximum_record_length':
                        str(logical_index.storage_unit_label.
                            maximum_record_length),
                        'storage_set_identifier':
                        logical_index.storage_unit_label.
                        storage_set_identifier.decode('ascii'),
                    }):
                pass
            with XmlWrite.Element(
                    xml_stream, 'LogicalFiles',
                {'count': f'{len(logical_index.logical_files):d}'}):
                for lf, logical_file in enumerate(logical_index.logical_files):
                    write_logical_file_to_xml(lf, logical_file, xml_stream,
                                              private)
            # Visible records at the end
            rle_visible_records = Rle.create_rle(
                logical_index.visible_record_positions)
            xml_rle_write(rle_visible_records,
                          'VisibleRecords',
                          xml_stream,
                          hex_output=True)
Ejemplo n.º 10
0
 def _HTMLGeneralTable(self, theS, theTitleS, theTab):
     """Create a table. theTitleS is a list of titles, theTab is a list of lists."""
     with XmlWrite.Element(theS, 'table', {'class' : "monospace"}):
         with XmlWrite.Element(theS, 'tr', {}):
             for v in theTitleS:
                 with XmlWrite.Element(theS, 'th', {'class' : "monospace"}):
                     theS.characters(v)
         for row in theTab:
             with XmlWrite.Element(theS, 'tr', {}):
                 for v in row:
                     with XmlWrite.Element(theS, 'td', {'class' : "monospace"}):
                         theS.characters(v)
Ejemplo n.º 11
0
def _write_x_axis_summary(x_axis: XAxis.XAxis,
                          xhtml_stream: XmlWrite.XhtmlStream) -> None:
    # Parent section is heading h3

    # with XmlWrite.Element(xhtml_stream, 'h4'):
    #     xhtml_stream.characters('X Axis summary (all IFLRs)')
    with XmlWrite.Element(xhtml_stream, 'h4'):
        xhtml_stream.characters('X Axis')
    units = x_axis.units.decode('ascii')
    x_axis_table = [
        ['X Axis', 'Value'],
        ['Channel', f'{x_axis.ident}'],
        ['Long Name', f'{x_axis.long_name.decode("ascii")}'],
        ['Minimum', f'{x_axis.summary.min} [{units}]'],
        ['Maximum', f'{x_axis.summary.max} [{units}]'],
        ['Frame Count', f'{x_axis.summary.count}'],
    ]
    html_write_table(x_axis_table, xhtml_stream, class_style='monospace')
    with XmlWrite.Element(xhtml_stream, 'h4'):
        xhtml_stream.characters('X Axis Spacing')
    with XmlWrite.Element(xhtml_stream, 'p'):
        xhtml_stream.characters(f'Definitions: {XAxis.SPACING_DEFINITIONS}')
    x_spacing_table = [
        ['X Axis Spacing', 'Value'],
    ]
    if x_axis.summary.spacing is not None:
        spacing = x_axis.summary.spacing
        x_spacing_table.append(['Minimum', f'{spacing.min} [{units}]'])
        x_spacing_table.append(['Mean', f'{spacing.mean} [{units}]'])
        x_spacing_table.append(['Median', f'{spacing.median} [{units}]'])
        x_spacing_table.append(['Maximum', f'{spacing.max} [{units}]'])
        if spacing.median != 0:
            x_spacing_table.append([
                'Range',
                f'{spacing.max - spacing.min} ({(spacing.max - spacing.min) / spacing.median:%}) [{units}]'
            ])
        else:
            x_spacing_table.append(
                ['Range', f'{spacing.max - spacing.min} [{units}]'])
        x_spacing_table.append(['Std. Dev.', f'{spacing.std} [{units}]'])
        x_spacing_table.append(
            ['Count of Normal', f'{spacing.counts.norm:,d}'])
        x_spacing_table.append(
            ['Count of Duplicate', f'{spacing.counts.dupe:,d}'])
        x_spacing_table.append(
            ['Count of Skipped', f'{spacing.counts.skip:,d}'])
        x_spacing_table.append(['Count of Back', f'{spacing.counts.back:,d}'])
    html_write_table(x_spacing_table, xhtml_stream, class_style='monospace')
    if x_axis.summary.spacing is not None:
        with XmlWrite.Element(xhtml_stream, 'p'):
            xhtml_stream.characters('Frame spacing frequency:')
        with XmlWrite.Element(xhtml_stream, 'pre'):
            xhtml_stream.characters(x_axis.summary.spacing.histogram_str())
Ejemplo n.º 12
0
def writeDictTreeAsTable(theS, theDt, tableAttrs, includeKeyTail):
    """Writes a DictTreeHtmlTable object as a table, for example as a directory
    structure.
    
    The key list in the DictTreeHtmlTable object is the path to the file
    i.e. os.path.abspath(p).split(os.sep) and the value is expected to be a
    pair of (link, nav_text) or None."""
    # Write: <table border="2" width="100%">
    # Propogate table class attribute
    myAttrs = {}
    try:
        myAttrs['class'] = tableAttrs['class']
    except KeyError:
        pass
    with XmlWrite.Element(theS, 'table', tableAttrs):
        for anEvent in theDt.genColRowEvents():
            if anEvent == theDt.ROW_OPEN:
                # Write out the '<tr>' element
                theS.startElement('tr', {})
            elif anEvent == theDt.ROW_CLOSE:
                # Write out the '</tr>' element
                theS.endElement('tr')
            else:
                #print 'TRACE: anEvent', anEvent
                k, v, r, c = anEvent
                # Write '<td rowspan="%d" colspan="%d">%s</td>' % (r, c, txt[-1])
                myTdAttrs = {}
                myTdAttrs.update(myAttrs)
                if r > 1:
                    myTdAttrs['rowspan'] = "%d" % r
                if c > 1:
                    myTdAttrs['colspan'] = "%d" % c
                with XmlWrite.Element(theS, 'td', myTdAttrs):
                    if v is not None:
                        if includeKeyTail:
                            theS.characters('%s:' % k[-1])
                        # Output depending on the type of the value
                        if isinstance(v, list):
                            for h, n in v:
                                theS.characters(' ')
                                with XmlWrite.Element(theS, 'a', {'href': h}):
                                    # Write the nav text
                                    theS.characters('%s' % n)
                        elif isinstance(v, tuple) and len(v) == 2:
                            with XmlWrite.Element(theS, 'a', {'href': v[0]}):
                                # Write the nav text
                                theS.characters(v[1])
                        else:
                            # Treat as string
                            theS.characters(str(v))
                    else:
                        theS.characters(k[-1])
Ejemplo n.º 13
0
    def test_07(self):
        """TestXmlWrite.test_07(): comments."""
        myF = io.StringIO()
        with XmlWrite.XmlStream(myF) as xS:
            with XmlWrite.Element(xS, 'Root', {'version': '12.0'}):
                xS.comment(' a comment ')
        #print
        #print myF.getvalue()
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<Root version="12.0"><!-- a comment -->
</Root>
""")
Ejemplo n.º 14
0
    def test_all_byte_values(self):
        fout = io.StringIO()
        with XmlWrite.XhtmlStream(fout) as xS:
            with XmlWrite.Element(xS, 'Root', {'version': '12.0'}):
                s = ''.join(chr(v) for v in range(256))
                xS.characters(s)
        result = fout.getvalue()
        self.assertEqual(
            result, r"""<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <Root version="12.0">&#000;&#001;&#002;&#003;&#004;&#005;&#006;&#007;&#008;&#009;&#010;&#011;&#012;&#013;&#014;&#015;&#016;&#017;&#018;&#019;&#020;&#021;&#022;&#023;&#024;&#025;&#026;&#027;&#028;&#029;&#030;&#031; !&quot;#$%&amp;&apos;()*+,-./0123456789:;&lt;=&gt;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~&#128;&#129;&#130;&#131;&#132;&#133;&#134;&#135;&#136;&#137;&#138;&#139;&#140;&#141;&#142;&#143;&#144;&#145;&#146;&#147;&#148;&#149;&#150;&#151;&#152;&#153;&#154;&#155;&#156;&#157;&#158;&#159;&#160;&#161;&#162;&#163;&#164;&#165;&#166;&#167;&#168;&#169;&#170;&#171;&#172;&#173;&#174;&#175;&#176;&#177;&#178;&#179;&#180;&#181;&#182;&#183;&#184;&#185;&#186;&#187;&#188;&#189;&#190;&#191;&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#215;&#216;&#217;&#218;&#219;&#220;&#221;&#222;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#240;&#241;&#242;&#243;&#244;&#245;&#246;&#247;&#248;&#249;&#250;&#251;&#252;&#253;&#254;&#255;</Root>
</html>
""")
Ejemplo n.º 15
0
 def _writeCols(self, theS, theObj):
     """Write the columns after the first one. theObj is expected to have certain attributes..."""
     with XmlWrite.Element(theS, 'td', {'align' : 'right'}):
         theS.characters('{:.3f}'.format(theObj.lisSize / 1024**2))
     with XmlWrite.Element(theS, 'td', {'align' : 'right'}):
         theS.characters('{:d}'.format(theObj.numLr))
     with XmlWrite.Element(theS, 'td', {'align' : 'right'}):
         theS.characters('{:.3f}'.format(theObj.cpuTime))
     if theObj.cpuTime != 0:
         with XmlWrite.Element(theS, 'td', {'align' : 'right'}):
             theS.characters('{:.3f}'.format(theObj.lisSize / (theObj.cpuTime * 1024**2)))
     else:
         with XmlWrite.Element(theS, 'td', {'align' : 'right'}):
             theS.characters('N/A')                             
Ejemplo n.º 16
0
 def _writeValues(self, theS, theVal, theFilePath):
     assert(theVal is not None)
     for i, aVal in enumerate(theVal):
         myValAttrs = {}
         if i in (4, 6):
             # Curve list and link
             myValAttrs = {'align' : 'left'}
         else:
             myValAttrs = {'align' : 'right'}
         with XmlWrite.Element(theS, 'td', myValAttrs):
             if i == len(theVal)-1:
                 with XmlWrite.Element(theS, 'a', {'href' : self.retRelPath(os.path.dirname(theFilePath), aVal)}):
                     theS.characters(os.path.basename(aVal))
             else:
                 theS.characters(str(aVal))
Ejemplo n.º 17
0
    def test_03(self):
        """TestXmlWrite.test_03(): processing instruction."""
        myF = io.StringIO()
        with XmlWrite.XmlStream(myF) as xS:
            with XmlWrite.Element(xS, 'Root', {'version': '12.0'}):
                with XmlWrite.Element(xS, 'A', {'attr_1': '1'}):
                    xS.pI('Do <&> this')
        #print
        #print myF.getvalue()
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<Root version="12.0">
  <A attr_1="1"><?Do &lt;&amp;&gt; this?></A>
</Root>
""")
Ejemplo n.º 18
0
    def test_02(self):
        """TestXmlWrite.test_02(): mixed content."""
        myF = io.StringIO()
        with XmlWrite.XmlStream(myF) as xS:
            with XmlWrite.Element(xS, 'Root', {'version': '12.0'}):
                with XmlWrite.Element(xS, 'A', {'attr_1': '1'}):
                    xS.characters('<&>')
        #print
        #print myF.getvalue()
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<Root version="12.0">
  <A attr_1="1">&lt;&amp;&gt;</A>
</Root>
""")
Ejemplo n.º 19
0
    def test_01(self):
        """TestXmlWrite.test_01(): simple elements."""
        myF = io.StringIO()
        with XmlWrite.XmlStream(myF) as xS:
            with XmlWrite.Element(xS, 'Root', {'version': '12.0'}):
                with XmlWrite.Element(xS, 'A', {'attr_1': '1'}):
                    pass
        #print
        #print myF.getvalue()
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<Root version="12.0">
  <A attr_1="1"/>
</Root>
""")
Ejemplo n.º 20
0
    def test_01(self):
        """Test_writeFileListTrippleAsTable.test_01(): writeFileListTrippleAsTable() - Single file list"""
        myFileNameS = [
            '0eggs.lis',
            '1chips.lis',
            '2beans.lis',
        ]
        myFileLinkS = [(f, HtmlUtils.retHtmlFileName(f),
                        'Link text {:d}'.format(i))
                       for i, f in enumerate(myFileNameS)]
        myF = io.StringIO()
        with XmlWrite.XhtmlStream(myF) as myS:
            HtmlUtils.writeFileListTrippleAsTable(myS, myFileLinkS, {}, False)
        # print()
        # print(myF.getvalue())
        self.assertEqual(
            fix_hrefs(myF.getvalue()),
            fix_hrefs("""<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <table>
    <tr>
      <td> <a href="0eggs.lis_794a10f9fa60f4b19f27a7e42e209f01.html">Link text 0</a></td>
    </tr>
    <tr>
      <td> <a href="1chips.lis_48b0b051146cd7a23f5aa347318124b7.html">Link text 1</a></td>
    </tr>
    <tr>
      <td> <a href="2beans.lis_302d2e55820514cd6d7f0636303ea6a1.html">Link text 2</a></td>
    </tr>
  </table>
</html>
"""))
Ejemplo n.º 21
0
    def test_01(self):
        """Test_writeFileListTrippleAsTable.test_01(): writeFileListTrippleAsTable() - Single file list"""
        myFileNameS = [
            '0eggs.lis',
            '1chips.lis',
            '2beans.lis',
        ]
        myFileLinkS = [(f, HtmlUtils.retHtmlFileName(f),
                        'Link text {:d}'.format(i))
                       for i, f in enumerate(myFileNameS)]
        myF = io.StringIO()
        with XmlWrite.XhtmlStream(myF) as myS:
            HtmlUtils.writeFileListTrippleAsTable(myS, myFileLinkS, {}, False)
        # print()
        # print(myF.getvalue())


#        print(myF.getvalue())
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <table>
    <tr>
      <td> <a href="0eggs.lis_5fdd58d724c849dd9d217fbe6a35b3e6.html">Link text 0</a></td>
    </tr>
    <tr>
      <td> <a href="1chips.lis_3cdd79989f0c867f42464c2c02fa184f.html">Link text 1</a></td>
    </tr>
    <tr>
      <td> <a href="2beans.lis_999dc8fa0c627e259d489d8694205092.html">Link text 2</a></td>
    </tr>
  </table>
</html>
""")
Ejemplo n.º 22
0
def test_log_pass_write_XML():
    log_pass = _log_pass()
    ostream = io.StringIO()
    xml_stream = XmlWrite.XmlStream(ostream)
    iflr_map = {
        RepCode.ObjectName(O=11, C=0, I=b'0B'): [],
    }
    TotalDepth.RP66V1.IndexXML.log_pass_to_XML(log_pass, iflr_map, xml_stream)
    # print(ostream.getvalue())
    expected = """
<LogPass count="1">
  <FrameArray C="0" I="0B" O="11" description="" x_axis="DEPT" x_units="0.1 in">
    <Channels count="9">
      <Channel C="0" I="DEPT" O="11" count="1" dimensions="1" long_name="MWD Tool Measurement Depth" rep_code="2" units="0.1 in"/>
      <Channel C="0" I="INC" O="11" count="1" dimensions="1" long_name="Inclination" rep_code="2" units="deg"/>
      <Channel C="0" I="AZI" O="11" count="1" dimensions="1" long_name="Azimuth" rep_code="2" units="deg"/>
      <Channel C="0" I="MTTVD" O="11" count="1" dimensions="1" long_name="MWD Tool Measurement TVD" rep_code="2" units="m"/>
      <Channel C="0" I="SECT" O="11" count="1" dimensions="1" long_name="Section" rep_code="2" units="m"/>
      <Channel C="0" I="RCN" O="11" count="1" dimensions="1" long_name="Rectangular Co-ordinates North" rep_code="2" units="m"/>
      <Channel C="0" I="RCE" O="11" count="1" dimensions="1" long_name="Rectangular Co-ordinates East" rep_code="2" units="m"/>
      <Channel C="0" I="DLSEV" O="11" count="1" dimensions="1" long_name="Dog-leg Severity" rep_code="2" units="deg/30m"/>
      <Channel C="0" I="TLTS" O="11" count="1" dimensions="1" long_name="Tool Temperature Static" rep_code="2" units="degC"/>
    </Channels>
    <IFLR count="0">
      <FrameNumbers count="0" rle_len="0"/>
      <LRSH count="0" rle_len="0"/>
      <Xaxis count="0" rle_len="0"/>
    </IFLR>
  </FrameArray>
</LogPass>"""
    assert ostream.getvalue() == expected
Ejemplo n.º 23
0
    def test_02(self):
        """Test_writeFileListTrippleAsTable.test_02(): writeFileListTrippleAsTable() - Single directory list"""
        myFileNameS = [
            'spam/beans.lis',
            'spam/chips.lis',
            'spam/eggs.lis',
        ]
        myFileLinkS = [(f, HtmlUtils.retHtmlFileName(f),
                        'Link text {:d}'.format(i))
                       for i, f in enumerate(myFileNameS)]
        myF = io.StringIO()
        with XmlWrite.XhtmlStream(myF) as myS:
            HtmlUtils.writeFileListTrippleAsTable(myS, myFileLinkS, {}, False)
        # print()
        # print(myF.getvalue())
        self.assertEqual(
            fix_hrefs(myF.getvalue()),
            fix_hrefs("""<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <table>
    <tr>
      <td rowspan="3">spam/</td>
      <td> <a href="beans.lis_ef9772ccc720deea37e190898b7167de.html">Link text 0</a></td>
    </tr>
    <tr>
      <td> <a href="chips.lis_4beafb06c2c4383049c520ec80713ad4.html">Link text 1</a></td>
    </tr>
    <tr>
      <td> <a href="eggs.lis_68357c85d8f3631e6db02fe6a036040e.html">Link text 2</a></td>
    </tr>
  </table>
</html>
"""))
Ejemplo n.º 24
0
def xml_rle_write(rle: Rle.RLE, element_name: str,
                  xml_stream: XmlWrite.XmlStream, hex_output: bool) -> None:
    with XmlWrite.Element(xml_stream, element_name, {
            'count': f'{rle.num_values():d}',
            'rle_len': f'{len(rle):d}',
    }):
        for rle_item in rle.rle_items:
            attrs = {
                'datum':
                f'0x{rle_item.datum:x}' if hex_output else f'{rle_item.datum}',
                'stride': f'0x{rle_item.stride:x}'
                if hex_output else f'{rle_item.stride}',
                'repeat': f'{rle_item.repeat:d}',
            }
            with XmlWrite.Element(xml_stream, 'RLE', attrs):
                pass
Ejemplo n.º 25
0
    def test_02(self):
        """Test_writeFileListTrippleAsTable.test_02(): writeFileListTrippleAsTable() - Single directory list"""
        myFileNameS = [
            'spam/beans.lis',
            'spam/chips.lis',
            'spam/eggs.lis',
        ]
        myFileLinkS = [(f, HtmlUtils.retHtmlFileName(f),
                        'Link text {:d}'.format(i))
                       for i, f in enumerate(myFileNameS)]
        myF = io.StringIO()
        with XmlWrite.XhtmlStream(myF) as myS:
            HtmlUtils.writeFileListTrippleAsTable(myS, myFileLinkS, {}, False)
#        print()
#        print(myF.getvalue())
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <table>
    <tr>
      <td rowspan="3">spam/</td>
      <td> <a href="beans.lis_e6a41188a589cc6b52882b9cd7d22eb9.html">Link text 0</a></td>
    </tr>
    <tr>
      <td> <a href="chips.lis_f429ae32a9c46981370bb498ad597041.html">Link text 1</a></td>
    </tr>
    <tr>
      <td> <a href="eggs.lis_4bedd293e6272aaf67cd473127969aac.html">Link text 2</a></td>
    </tr>
  </table>
</html>
""")
Ejemplo n.º 26
0
    def test_01(self):
        """Test_writeFileListTrippleAsTable.test_01(): writeFileListTrippleAsTable() - Single file list"""
        myFileNameS = [
            '0eggs.lis',
            '1chips.lis',
            '2beans.lis',
        ]
        myFileLinkS = [(f, HtmlUtils.retHtmlFileName(f),
                        'Link text {:d}'.format(i))
                       for i, f in enumerate(myFileNameS)]
        myF = io.StringIO()
        with XmlWrite.XhtmlStream(myF) as myS:
            HtmlUtils.writeFileListTrippleAsTable(myS, myFileLinkS, {}, False)
#        print()
#        print(myFileLinkS)
#        print(myF.getvalue())
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <table>
    <tr>
      <td> <a href="0eggs.lis_d23a40cf926df40ac0a0567acdadd443.html">Link text 0</a></td>
    </tr>
    <tr>
      <td> <a href="1chips.lis_10659a53a7e19d0a410fff859afda9bf.html">Link text 1</a></td>
    </tr>
    <tr>
      <td> <a href="2beans.lis_45bf4fdc3882cef7e749605e515b7624.html">Link text 2</a></td>
    </tr>
  </table>
</html>
""")
Ejemplo n.º 27
0
    def test_07(self):
        """TestSVGlWriter.test_07(): text.
        Based on http://www.w3.org/TR/2003/REC-SVG11-20030114/text.html#TextElement"""
        myF = io.StringIO()
        myViewPort = Coord.Box(
            Coord.Dim(12, 'cm'),
            Coord.Dim(4, 'cm'),
        )
        with SVGWriter.SVGWriter(myF, myViewPort,
                                 {'viewBox': "0 0 1000 300"}) as xS:
            with XmlWrite.Element(xS, 'desc'):
                xS.characters("Example text01 - 'Hello, out there' in blue")
            myPt = Coord.Pt(Coord.baseUnitsDim(250), Coord.baseUnitsDim(150))
            with SVGWriter.SVGText(xS, myPt, "Verdans", 55, {'fill': "blue"}):
                xS.characters('Hello, out there')
            #xS.comment(" Show outline of canvas using 'rect' element ")
            myPt = Coord.Pt(Coord.baseUnitsDim(1), Coord.baseUnitsDim(1))
            myBx = Coord.Box(Coord.baseUnitsDim(998), Coord.baseUnitsDim(298))
            with SVGWriter.SVGRect(xS, myPt, myBx, {
                    'fill': "none",
                    'stroke': "blue",
                    'stroke-width': "2"
            }):
                pass
        # print()
        # print(myF.getvalue())
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="4.000cm" version="1.1" viewBox="0 0 1000 300" width="12.000cm" xmlns="http://www.w3.org/2000/svg">
  <desc>Example text01 - &apos;Hello, out there&apos; in blue</desc>
  <text fill="blue" font-family="Verdans" font-size="55" x="250.000px" y="150.000px">Hello, out there</text>
  <rect fill="none" height="298.000px" stroke="blue" stroke-width="2" width="998.000px" x="1.000px" y="1.000px"/>
</svg>
""")
Ejemplo n.º 28
0
    def test_02(self):
        """Test_writeFileListTrippleAsTable.test_02(): writeFileListTrippleAsTable() - Single directory list"""
        myFileNameS = [
            'spam/beans.lis',
            'spam/chips.lis',
            'spam/eggs.lis',
        ]
        myFileLinkS = [(f, HtmlUtils.retHtmlFileName(f),
                        'Link text {:d}'.format(i))
                       for i, f in enumerate(myFileNameS)]
        myF = io.StringIO()
        with XmlWrite.XhtmlStream(myF) as myS:
            HtmlUtils.writeFileListTrippleAsTable(myS, myFileLinkS, {}, False)
        # print()
        # print(myF.getvalue())
        self.assertEqual(
            myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <table>
    <tr>
      <td rowspan="3">spam/</td>
      <td> <a href="beans.lis_bd0fa0db0dba3d5deae8b324f475096e.html">Link text 0</a></td>
    </tr>
    <tr>
      <td> <a href="chips.lis_8b5af66b7399116b669c1b12a95d7d33.html">Link text 1</a></td>
    </tr>
    <tr>
      <td> <a href="eggs.lis_b6b735a7daac22b82ecd20fae6189ea5.html">Link text 2</a></td>
    </tr>
  </table>
</html>
""")
Ejemplo n.º 29
0
    def test_03(self):
        """TestSVGlWriter.test_03(): an elipse.
        Based on http://www.w3.org/TR/2003/REC-SVG11-20030114/shapes.html#EllipseElement"""
        myF = io.StringIO()
        myViewPort = Coord.Box(
            Coord.Dim(12, 'cm'),
            Coord.Dim(4, 'cm'),
        )
        with SVGWriter.SVGWriter(myF, myViewPort) as xS:
            with XmlWrite.Element(xS, 'desc'):
                xS.characters('Example ellipse01 - examples of ellipses')
            #xS.comment(" Show outline of canvas using 'rect' element ")
            myPt = Coord.Pt(Coord.baseUnitsDim(1), Coord.baseUnitsDim(1))
            myBx = Coord.Box(Coord.baseUnitsDim(1198), Coord.baseUnitsDim(398))
            with SVGWriter.SVGRect(xS, myPt, myBx, {'fill':"none", 'stroke':"blue",'stroke-width':"2"}):
                pass
            myPt = Coord.Pt(Coord.baseUnitsDim(600), Coord.baseUnitsDim(200))
            myRadX = Coord.baseUnitsDim(250)
            myRadY = Coord.baseUnitsDim(100)
            with SVGWriter.SVGElipse(xS, myPt, myRadX, myRadY, {'fill':"red", 'stroke':"blue",'stroke-width':"10"}):
                pass
        #print
        #print myF.getvalue()
#        self.maxDiff = None
        self.assertEqual(myF.getvalue(), """<?xml version='1.0' encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="4cm" version="1.1" width="12cm" xmlns="http://www.w3.org/2000/svg">
  <desc>Example ellipse01 - examples of ellipses</desc>
  <rect fill="none" height="398px" stroke="blue" stroke-width="2" width="1198px" x="1px" y="1px"/>
  <elipse cx="600px" cy="200px" fill="red" rx="250px" ry="100px" stroke="blue" stroke-width="10"/>
</svg>
""")
Ejemplo n.º 30
0
def _write_low_level_indexes(path_out: str,
                             index: typing.Dict[str, HTMLResult]) -> None:
    assert os.path.isdir(path_out)
    logging.info(f'_write_low_level_indexes(): to "{path_out}"')
    # Write low level indexes
    for root, dirs, files in os.walk(path_out):
        files_to_link_to = []
        for file in files:
            out_file_path = os.path.join(root, file)
            if out_file_path in index:
                files_to_link_to.append(file)
        if len(files_to_link_to):
            with open(os.path.join(root, INDEX_FILE), 'w') as fout:
                logging.info(
                    f'_write_low_level_indexes(): to "{os.path.join(root, INDEX_FILE)}"'
                )
                with XmlWrite.XhtmlStream(fout) as xhtml_stream:
                    with XmlWrite.Element(xhtml_stream, 'head'):
                        with XmlWrite.Element(
                                xhtml_stream, 'meta', {
                                    'charset': "UTF-8",
                                    'name': "viewport",
                                    'content':
                                    "width=device-width, initial-scale=1",
                                }):
                            pass
                        with XmlWrite.Element(xhtml_stream, 'title'):
                            xhtml_stream.charactersWithBr(
                                f'Index of RP66V1 Scan: {root}')
                        with XmlWrite.Element(xhtml_stream, 'style'):
                            xhtml_stream.literal(CSS_RP66V1_INDEX)
                    with XmlWrite.Element(xhtml_stream, 'body'):
                        with XmlWrite.Element(xhtml_stream, 'h1'):
                            xhtml_stream.charactersWithBr(
                                f'Index of RP66V1 Scan {root}')
                        with XmlWrite.Element(xhtml_stream, 'table',
                                              {'class': 'filetable'}):
                            with XmlWrite.Element(xhtml_stream, 'tr',
                                                  {'class': 'filetable'}):
                                for header in ('Physical File', 'File',
                                               'Frame Array', 'Frames',
                                               'Channels', 'X Start', 'X Stop',
                                               'dX', 'X Units'):
                                    with XmlWrite.Element(
                                            xhtml_stream, 'th',
                                        {'class': 'filetable'}):
                                        xhtml_stream.characters(header)