Esempio n. 1
0
def encode2decode():
    encoderTable = Table()
    decoderTable = Table()
    for i in range(len(TESTCASE)):
        stories = [TESTCASE[i] + name for name in os.listdir(TESTCASE[i])]
        for story in stories:
            allPass = True
            with open(story) as f:
                data = json.loads(f.read())
                for seqno in range(len(data["cases"])):
                    if data["cases"][seqno].has_key("header_table_size"):
                        encoderTable.setHeaderTableSize(int(data["cases"][seqno]["header_table_size"]))

                    headers = [[h.keys()[0], h.values()[0]] for h in data["cases"][seqno]["headers"]]
                    wire = encode(headers, 'static' in story or 'linear' in story, 'linear' in story, 'huffman' in story, encoderTable) #init header table or not
                    try:
                        decodedHeaders = decode(wire, decoderTable)
                        if decodedHeaders != data["cases"][seqno]["headers"]:
                            allPass = False
                            print('Missed in %s seqno %d' % (story, seqno))
                            break
                    except Exception as e:
                        print("Error at %s seqno %d" % (story, seqno))
                        allPass = False
                        break
            if allPass:
                print("Passed the %s" % story)
Esempio n. 2
0
def build_shift_comparison_table(year):
    header = [
        'year',
        'shift',
        'minimal investment',
        'raw profit, uah',
        'profit, %',
    ]
    data = []
    for s in range(0, 31):
        shift = s + 1

        stats = launch_trading(
            year=year,
            shift=shift,
            starting_amount_uah=0,
            verbose=False,
        )
        min_investment = -stats['debt']
        row = [
            year,
            shift,
            '{:.2f}'.format(min_investment),
            '{:.2f}'.format(stats['end_amount']),
            '{:.2f}'.format(stats['end_amount'] / min_investment * 100),
        ]
        data.append(row)

    t = Table(header=header, data=data)
    t.print()
Esempio n. 3
0
 def test_nested_table_in_cell(self):
     """Test nested table in cell"""
     inner_table = Table([['1', '2', '3']])
     cell = TableCell(inner_table)
     self.html += '  <h2>Table nested in Cell</h2>\n'
     body = (' <tbody>\n'
             '  <tr>\n'
             '   <td><table class="table table-striped condensed">\n'
             ' <tbody>\n'
             '  <tr>\n'
             '   <td>1</td>\n'
             '   <td>2</td>\n'
             '   <td>3</td>\n'
             '  </tr>\n'
             ' </tbody>\n'
             '</table></td>\n'
             '  </tr>\n'
             ' </tbody>\n')
     expected_result = ('%s%s%s' % (self.html_table_start,
                                    body,
                                    self.html_table_end))
     actual_result = Table([[cell]])
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     self.html += str(actual_result)
     self.writeHtml('table_nested_in_cell')
     assert expected_result.strip() == str(actual_result).strip(), message
Esempio n. 4
0
 def test__len__(self):
     # expect = fill
     expect = [
         (None, 13),
         ([], 13),
         ([''], 18),
         ('hey', 15),
         ('', 13),
         ([None], 24),
         ([''] * 4, 54),
         ([''] * 10, 126),
         ('helloworld', 36),
         (['\n'], 24),
         ('\n', 13),
         (['\n\n\n'], 36),
         ('\n\n\n\n\n', 13),
     ]
     for (data, length) in expect:
         T = Table(rows=3, columns=3, fill=data)
         self.assertEqual(len(T), length, msg=f'fill={data}')
     # Small dimension check.
     for x in range(1, 12):
         for y in range(1, 12):
             T = Table(rows=x, columns=y)
             length = 5 * y - 2
             self.assertEqual(len(T), length, msg=f'rows={x},columns={y}')
Esempio n. 5
0
    def test_table_caption(self):
        """Test table caption"""
        self.html += '  <h2>Caption Top</h2>\n'
        expected_result = ('%s%s%s%s' % (self.html_table_start,
                                       self.html_caption,
                                       self.html_body,
                                       self.html_table_end))
        actual_result = Table(self.table_data, caption=self.table_caption)
        message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
        assert expected_result.strip() == str(actual_result).strip(), message
        self.html += str(actual_result)

        #also test bottom caption
        self.html += '  <h2>Caption Bottom</h2>\n'
        expected_result = ('%s%s%s%s' % (self.html_table_start,
                                       self.html_bottom_caption,
                                       self.html_body,
                                       self.html_table_end))
        actual_result = Table(self.table_data,
                              caption=self.table_caption,
                              caption_at_bottom=True)
        message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
        self.html += str(actual_result)
        self.writeHtml('table_caption')

        assert expected_result.strip() == str(actual_result).strip(), message
        self.html += str(actual_result)
Esempio n. 6
0
 def test__init__(self):
     # data
     for k, v in self.types.items():
         if k != 'double_iter' and k != 'str':
             for x in v:
                 with self.assertRaises((TypeError, KeyError),
                                        msg=f'data={x}'):
                     Table(data=x)
     for x in self.types['double_iter'] + self.types['str']:
         self.assertIsInstance(Table(data=x), Table, msg=f'data={x}')
     # rows
     for k, v in self.types.items():
         if k != 'positive_int':
             for x in v:
                 with self.assertRaises((ValueError, TypeError, KeyError),
                                        msg=f'rows={x}'):
                     Table(rows=x)
     for x in self.types['positive_int']:
         self.assertIsInstance(Table(rows=x), Table, msg=f'rows={x}')
     # columns
     for k, v in self.types.items():
         if k != 'positive_int':
             for x in v:
                 with self.assertRaises((ValueError, TypeError, KeyError),
                                        msg=f'columns={x}'):
                     Table(rows=1, columns=x)
     for x in self.types['positive_int']:
         self.assertIsInstance(Table(columns=x), Table, msg=f'columns={x}')
     # col_sep
     for k, v in self.types.items():
         for x in v:
             if k != 'str' or (k == 'str' and len(x) > 1):
                 with self.assertRaises((ValueError, TypeError, KeyError),
                                        msg=f'col_sep={x}'):
                     Table(col_sep=x)
     for x in self.types['str']:
         if len(x) < 2:
             self.assertIsInstance(Table(col_sep=x),
                                   Table,
                                   msg=f'col_sep={x}')
     # head_sep
     for k, v in self.types.items():
         for x in v:
             if k != 'str' or (k == 'str' and len(x) > 2):
                 with self.assertRaises((ValueError, TypeError, KeyError),
                                        msg=f'head_sep={x}'):
                     Table(head_sep=x)
     for x in self.types['str']:
         if len(x) < 3:
             self.assertIsInstance(Table(head_sep=x),
                                   Table,
                                   msg=f'head_sep={x}')
    def long_print_conn(self, type, connections):
        print '-'*80
        print type
        print '-'*80
        if len(connections) == 0:
            return
        t_headers = ['Alias', 'user', 'host', 'port', 'Password','Options', 'Description']
        t_rows = []
        for conn in connections:
            row = (conn.alias, conn.user, conn.host, conn.port, conn.password, conn.options, conn.description.strip())
            t_rows.append(row)

        table = Table(t_headers, t_rows)
        table.output()
Esempio n. 8
0
    def load(self, filepath):
        self._sections = list()
        with open(filepath, 'r') as f:
            data = json.load(f)
            for head in data:
                section = SectionHeading()
                section.style_name = head['style_name']
                section.section_number = head['section_number']
                section.title = head['title']
                section.section_points = head['section_points']

                for content in head['contents']:
                    if isinstance(content, int):
                        section.contents.append(content)
                    elif isinstance(content, dict):
                        table = Table()

                        table.heading = content.get('heading')
                        table.doc_table_number = content.get(
                            'doc_table_number')
                        table.table_number = content.get('table_number')
                        table.num_columns = content.get('num_columns')
                        table.full_title = content.get('full_title')
                        table.short_title = content.get('short_title')

                        if isinstance(content.get('rows'), list):
                            for row in content['rows']:
                                table.rows.append(row)

                        section.contents.append(table)
                    else:
                        print('Unknown type: {}'.format(type(content)))

                self._sections.append(section)
    def getvalue(self, value):
        print(value)
        print(type(value))

        if value == 1:
            pass
        elif value == 2:
            self.hide()
            view = Employee(self)
        elif value == 3:
            self.hide()
            view = Table(self)
        elif value == 4:
            self.hide()
            view = Reservations(self)
        elif value == 5:
            self.hide()
            view = Category(self)
        elif value == 6:
            self.hide()
            view = Settings(self)
        elif value == 7:
            self.hide()
            view = Orders(self)
        elif value == 8:
            self.hide()
            view = Menu(self)
        elif value == 9:
            self.hide()
            view = Bill(self)
Esempio n. 10
0
 def test_row_span(self):
     """Testing row spanning"""
     table_cell_aa = TableCell('aa spanned', row_span=2)
     table_row1 = TableRow([table_cell_aa,
                           self.table_cell_b,
                           self.table_cell_c,
                           self.table_cell_d])
     table_row2 = TableRow([self.table_cell_b,
                            self.table_cell_c,
                            self.table_cell_d])
     self.html += '  <h2>Spanning Table Columns</h2>\n'
     body = (' <tbody>\n'
             '  <tr>\n'
             '   <td rowspan="2">aa spanned</td>\n'
             '   <td>b</td>\n'
             '   <td>c</td>\n'
             '   <td>d</td>\n'
             '  </tr>\n'
             '  <tr>\n'
             '   <td>b</td>\n'
             '   <td>c</td>\n'
             '   <td>d</td>\n'
             '  </tr>\n'
             ' </tbody>\n')
     expected_result = ('%s%s%s' % (self.html_table_start,
                                    body,
                                    self.html_table_end))
     actual_result = Table([table_row1, table_row2])
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     assert expected_result.strip() == str(actual_result).strip(), message
     self.html += str(actual_result)
     self.writeHtml('table_rowspanning')
Esempio n. 11
0
 def test_row_from_string(self):
     """Test row from string - it should span to the table width too"""
     table_row1 = TableRow([self.table_cell_a,
                            self.table_cell_b,
                            self.table_cell_c,
                            self.table_cell_d])
     self.html += '  <h2>Table row from string</h2>\n'
     body = (' <tbody>\n'
             '  <tr>\n'
             '   <td>a</td>\n'
             '   <td>b</td>\n'
             '   <td>c</td>\n'
             '   <td>d</td>\n'
             '  </tr>\n'
             '  <tr>\n'
             '   <td colspan="100%">foobar</td>\n'
             '  </tr>\n'
             '  <tr>\n'
             '   <td colspan="100%">Piet Pompies</td>\n'
             '  </tr>\n'
             ' </tbody>\n')
     expected_result = ('%s%s%s' % (self.html_table_start,
                                    body,
                                    self.html_table_end))
     actual_result = Table([table_row1, 'foobar', 'Piet Pompies'])
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     self.html += str(actual_result)
     self.writeHtml('table_row_from_string')
     assert expected_result.strip() == str(actual_result).strip(), message
 def __init__(self, parentNode, name, description=None,
              title="", filters=None,
              expectedrows=EXPECTED_ROWS_TABLE,
              chunkshape=None, byteorder=None, _log=True):
     new = description is None
     if not new:
         maskedarray = ma.asanyarray(description)
         description = tabulate(maskedarray)
     Table.__init__(self, parentNode, name, 
                    description=description, title=title,
                    filters=filters,
                    expectedrows=expectedrows,
                    chunkshape=chunkshape, byteorder=byteorder,
                    _log=_log)
     if not new:
         self.attrs.special_attrs = self._update_special_attrs(maskedarray)
     return
    def list(self, alias=None):
        print "Usage: mcm [OPTIONS] [ALIAS]\n"
        t_headers = ['Alias', 'user', 'host', 'port']
        t_rows = []
        _ids = []
        for conn in self.connections.values():
            _ids.append(int(conn.id))
        
        _ids.sort()
        for _id in _ids:
            for conn in self.connections.values():
                if conn.id == str(_id):
                    t_rows.append((conn.alias, conn.user, conn.host, conn.port))

        table = Table(t_headers, t_rows)
        table.output()
        exit(0)
Esempio n. 14
0
def landingPage():
    t = Table(table="Experiment")
    rows = t.rows
    eids = []
    number_of_runs = []
    experiment_names = []
    for row in rows:
        experiment_names.append(row[1])
        eids.append(row[0])
        t_for_count = Table('Run', [Query('eid', '=', row[0])])
        number_of_runs.append(len(t_for_count.rows))
    template_args = {
        "experiment_names": experiment_names,
        "number_of_runs": number_of_runs,
        "eid": eids,
    }
    return render_template('landing.html', **template_args)
Esempio n. 15
0
 def __init__(self,name):
     self.name = name
     self.screen = pygame.display.get_surface().copy()
     self.width = self.screen.get_width()
     self.height = self.screen.get_height()
     Screen.screenList.append(self)
     self.buttons = Button.clone(name)    # these are the buttons for THIS screen
     self.tables = Table.clone(name)      # these are the tables for THIS screen
     self.title = None
Esempio n. 16
0
 def test_column(self):
     """Test to retrieve all element in a column.
     """
     table_body = []
     header = TableRow(["header1", "header2", "header3", "header4"], header=True)
     table_body.append(header)
     table_body.append(TableRow([1, 2, 3, 4]))
     table_body.append(TableRow(["a", "b", "c", "d"]))
     table_body.append(TableRow(["x", "y", "z", "t"]))
     myTable = Table(table_body)
     expected_result1 = ["header1", 1, "a", "x"]
     expected_result2 = [2, "b", "y"]
     real_result1 = myTable.column(0, True)
     real_result2 = myTable.column(1)
     myMessage1 = "Expected %s but got %s" % (expected_result1, real_result1)
     myMessage2 = "Expected %s but got %s" % (expected_result2, real_result2)
     assert expected_result1 == real_result1, myMessage1
     assert expected_result2 == real_result2, myMessage2
Esempio n. 17
0
def add_tables():

  tables_to_add = int(input("How many tables to add? "))
  
  counter = tables_to_add

  while counter > 0:
    pool_table = Table(counter, "unoccupied")
    pool_tables.append(pool_table.__dict__)
    counter = counter - 1
Esempio n. 18
0
 def test_max_width(self):
     # Blowing up...
     expect = [
         ((None, 26), 13),
         (([], 15), 13),
         (([''], 79), 18),
         (('hey', 30), 15),
         (('', 21), 13),
         (([None], 121), 24),
         (([''] * 4, 200), 54),
         (([''] * 10, 1337), 126),
         (('helloworld', 72), 36),
         ((['\n'], 25), 24),
         (('\n', 13), 13),
         ((['\n\n\n'], 37), 36),
         (('\n\n\n\n\n', 13), 13),
     ]
     for ((data, max_width), length) in expect:
         T = Table(rows=3, columns=3, fill=data)
         T.max_width = max_width
         self.assertEqual(len(T),
                          length,
                          msg=f'max_width={max_width},fill={data}')
     # Shrinking...
     # Small values can't be shrinkend (next test)
     expect = [
         ([''], 15),
         ('hey', 13),
         ([None], 21),
         ([''] * 4, 13),
         ([''] * 10, 100),
         ('helloworld', 30),
         (['\n'], 21),
         (['\n\n\n'], 35),
     ]
     for (data, max_width) in expect:
         T = Table(rows=3, columns=3, fill=data)
         T.max_width = max_width
         self.assertEqual(len(T),
                          max_width,
                          msg=f'max_width={max_width},fill={data}')
     expect = [((None, 10), 13), (([], 11), 13), (('', 12), 13),
               (('\n', 10), 13), (('\n\n\n\n\n', 12), 13)]
     for ((data, max_width), length) in expect:
         T = Table(rows=3, columns=3, fill=data)
         with self.assertRaises(ValueError, msg=f'fill={data}'):
             T.max_width = max_width
Esempio n. 19
0
 def test_table_cells(self):
     """Test table from individual cells"""
     self.html += '  <h2>Using Table Cells</h2>\n'
     expected_result = ('%s%s%s' % (self.html_table_start,
                                    self.html_body,
                                    self.html_table_end))
     actual_result = Table(self.table_cell_data)
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     assert expected_result.strip() == str(actual_result).strip(), message
     self.html += str(actual_result)
     self.writeHtml('table_by_cell_objects')
Esempio n. 20
0
 def test_simple_table(self):
     """Test simple table creation"""
     self.html += '  <h2>Simple Table</h2>\n'
     expected_result = ('%s%s%s' % (self.html_table_start,
                                    self.html_body,
                                    self.html_table_end))
     actual_result = Table(self.table_data)
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     assert expected_result.strip() == str(actual_result).strip(), message
     self.html += str(actual_result)
     self.writeHtml('simple_table')
Esempio n. 21
0
class TableInterpolateMinor(ParameterGetter):
    _table: Table

    def __init__(self, xy_points: typing.Sequence[XY]):
        self._table = Table()
        self._table.set_table_data(xy_points)

    def __call__(self, current_inc: CurrentInc) -> float:
        return self._table.interp(current_inc.minor_inc)

    def __str__(self):
        return f"Table.interp(minor_iter), Table({self._table.data})"

    def __rmul__(self, other) -> "TableInterpolateMinor":
        if not isinstance(other, numbers.Number):
            raise TypeError(other)

        scaled_table = self._table.copy_scaled(x_scale=1.0, y_scale=other)

        return TableInterpolateMinor(scaled_table.data)
Esempio n. 22
0
 def test_table_with_header(self):
     '''Test html render of a table with header row(s).'''
     self.html += '  <h2>Table with header</h2>\n'
     expected_result = ('%s%s%s%s' %
                        (self.html_table_start, self.html_header,
                         self.html_body, self.html_table_end))
     actual_result = Table(self.table_data, header_row=self.table_header)
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     assert expected_result.strip() == str(actual_result).strip(), message
     self.html += str(actual_result)
     self.writeHtml('table_with_header')
Esempio n. 23
0
 def test_fill(self):
     expect = [(None, (3, 3, 3)), ([], (3, 3, 3)), ([''], (3, 3, 3)),
               ('hey', (3, 3, 3)), ('', (3, 3, 3)), ([None], (3, 3, 3)),
               ([''] * 4, (3, 3, 3)), ([''] * 10, (3, 3, 3)),
               ('helloworld', (3, 3, 3)),
               (' ', (3, 3, 3)), ('\n', (3, 3, 6)), (['\n'], (3, 3, 3)),
               ('\n\n\n', (3, 3, 12))]
     for (data, (rows, columns, lines)) in expect:
         T = Table(rows=3, columns=3, fill=data)
         # No row sep for testing
         T.row_sep = ''
         msg = f'Not {rows} rows, with Table(fill={data})'
         self.assertEqual(T.row_count, rows, msg=msg)
         msg = f'Not {columns} columns, with Table(fill={data})'
         self.assertEqual(T.column_count, columns, msg=msg)
         msg = f'Not {lines} lines in table, with Table(fill={data})'
         self.assertEqual(len(str(T).splitlines()), lines, msg=msg)
     for v in self.types.values():
         for x in v:
             self.assertIsInstance(Table(fill=x), Table, msg=f'fill={x}')
Esempio n. 24
0
 def test_column(self):
     """Test to retrieve all element in a column.
     """
     table_body = []
     header = TableRow(['header1', 'header2', 'header3', 'header4'],
                       header=True)
     table_body.append(header)
     table_body.append(TableRow([1, 2, 3, 4]))
     table_body.append(TableRow(['a', 'b', 'c', 'd']))
     table_body.append(TableRow(['x', 'y', 'z', 't']))
     myTable = Table(table_body)
     expected_result1 = ['header1', 1, 'a', 'x']
     expected_result2 = [2, 'b', 'y']
     real_result1 = myTable.column(0, True)
     real_result2 = myTable.column(1)
     myMessage1 = "Expected %s but got %s" % (expected_result1,
                                             real_result1)
     myMessage2 = "Expected %s but got %s" % (expected_result2,
                                              real_result2)
     assert expected_result1 == real_result1, myMessage1
     assert expected_result2 == real_result2, myMessage2
Esempio n. 25
0
 def test_column(self):
     """Test to retrieve all element in a column.
     """
     table_body = []
     header = TableRow(['header1', 'header2', 'header3', 'header4'],
                       header=True)
     table_body.append(header)
     table_body.append(TableRow([1, 2, 3, 4]))
     table_body.append(TableRow(['a', 'b', 'c', 'd']))
     table_body.append(TableRow(['x', 'y', 'z', 't']))
     myTable = Table(table_body)
     expected_result1 = ['header1', 1, 'a', 'x']
     expected_result2 = [2, 'b', 'y']
     real_result1 = myTable.column(0, True)
     real_result2 = myTable.column(1)
     myMessage1 = "Expected %s but got %s" % (expected_result1,
                                             real_result1)
     myMessage2 = "Expected %s but got %s" % (expected_result2,
                                              real_result2)
     assert expected_result1 == real_result1, myMessage1
     assert expected_result2 == real_result2, myMessage2
Esempio n. 26
0
 def test_copy(self):
     for v in self.types.values():
         for x in v:
             T = Table(rows=2, columns=2, fill=x)
             for (col, row) in product([None, 0, 1], repeat=2):
                 C = T.copy(rows=row, columns=col)
                 self.assertIsNot(T,
                                  C,
                                  msg=f'Tables not a copy for fill={x}')
                 if col is None:
                     columns = 2
                 else:
                     columns = 1
                 if row is None:
                     rows = 2
                 else:
                     rows = 1
                 msg = (f'Not {rows} rows, with '
                        f'copy(rows={row},columns={col})')
                 self.assertEqual(C.row_count, rows, msg=msg)
                 msg = (f'Not {columns} columns, with '
                        f'copy(rows={row},columns={col})')
                 self.assertEqual(C.column_count, columns, msg=msg)
                 for (t, c) in zip(T.cells, C.cells):
                     self.assertIsNot(
                         t,
                         c,
                         msg=f'Cells {t} and {c} not a copy for fill={x}')
                     # Mutable objects
                     # Shallow search
                     # TODO deep search
                     if not isinstance(t.value,
                                       (str, int, bool, float, tuple)):
                         if not isinstance(c.value,
                                           (str, int, bool, float, tuple)):
                             self.assertIsNot(
                                 t.value,
                                 c.value,
                                 msg=(f'Cellvalues {t} and {c}'
                                      f' not a copy for fill={x}'))
Esempio n. 27
0
def make_example_table() -> Table:
    STRESS_START = 400
    stress_end = 450
    dilation_ratio = 0.008

    prestrain_table = Table([
        XY(0.0, 0.0),
        XY(STRESS_START, 0.0),
        XY(stress_end, -1*dilation_ratio),
        XY(stress_end+200, -1*dilation_ratio),
    ])

    return prestrain_table
Esempio n. 28
0
def encodeTest():
    table = Table()
    for i in range(len(TESTCASE)):
        cases = [TESTCASE[i] + name for name in os.listdir(TESTCASE[i])]
        for case in cases:
            allPass = True
            with open(case) as f:
                data = json.loads(f.read())
                for seqno in range(len(data["cases"])):
                    if data["cases"][seqno].has_key("header_table_size"):
                        table.setHeaderTableSize(int(data["cases"][seqno]["header_table_size"]))

                    headers = [[h.keys()[0], h.values()[0]]for h in data["cases"][seqno]["headers"]]
                    code = encode(headers, 'static' in case or 'linear' in case, 'linear' in case, 'huffman' in case, table) #init header table or not
                    if code != unhexlify(data["cases"][seqno]["wire"]):
                        allPass = False
                        print('encoder: %s' % code)
                        print('answer: %s' % data["cases"][seqno]["wire"])
                        print("Missed in %s seqno %d" % (case, seqno))
                        break
            if allPass:
                print('Passed the %s' % case)                        
Esempio n. 29
0
 def _parse(self):
     indices = []
     text = self.text
     lines = text.split("\n")
     for line_num in range(len(lines)):
         l = lines[line_num]
         if re.search(_header_regex, l.strip(_trash)):
             indices.append(line_num)
     if len(indices) == 0:
         return None
     table_text = []
     for i in range(len(indices) - 1):
         table_text.append("\n".join(lines[indices[i]:indices[i + 1]]))
     table_text.append("\n".join(lines[indices[-1]:]))
     self.tables = [Table(t) for t in table_text]
Esempio n. 30
0
 def test_table_from_string(self):
     """Test table from string - should be a single cell in a single row"""
     self.html += '  <h2>Table from string</h2>\n'
     body = (' <tbody>\n'
             '  <tr>\n'
             '   <td colspan="100%">foobar</td>\n'
             '  </tr>\n'
             ' </tbody>\n')
     expected_result = ('%s%s%s' %
                        (self.html_table_start, body, self.html_table_end))
     actual_result = Table('foobar')
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     assert expected_result.strip() == str(actual_result).strip(), message
     self.html += str(actual_result)
     self.writeHtml('table_table_from_string')
Esempio n. 31
0
    def buildReplacementRules(self, state, callbacks):
        """
        Builds the replacement rules section in the configuration page
        """
        rules = JPanel()
        rules.setLayout(None)
        rules.setMaximumSize(Dimension(self.CONFIG_PAGE_WIDTH, 300))

        title = self.getTitle("Replacement Rules", 20, 10)

        add = self.getButton("Add", 20, 50)
        add.addActionListener(self.callbacks.addButtonClicked)

        edit = self.getButton("Edit", 20, 90)
        edit.addActionListener(self.callbacks.editButtonClicked)
        delete = self.getButton("Delete", 20, 130)
        delete.addActionListener(self.callbacks.deleteButtonClicked)

        table = Table(state.replacementRuleTableModel)
        tableView = JScrollPane(table)
        tableView.setBounds(180, 50, 800, 240)

        rules.add(title)
        rules.add(add)
        rules.add(edit)
        rules.add(delete)
        rules.add(tableView)

        try:
            storedReplacementRules = callbacks.loadExtensionSetting(
                "replacementRules")
            if storedReplacementRules:
                state.replacementRuleTableModel.importJsonRules(
                    storedReplacementRules)
            else:
                log("No replacement rules stored.")
        except (ValueError, KeyError):
            log("Invalid replacement rules stored. Ignoring.")
            pass

        return rules
Esempio n. 32
0
 def test_cell_link(self):
     """Test cell links work"""
     table_cell_link = Link('InaSAFE', 'http://inasafe.org')
     table_row = TableRow([
         TableCell(table_cell_link), self.table_cell_b, self.table_cell_c,
         self.table_cell_d
     ])
     self.html += '  <h2>Link Cell Columns</h2>\n'
     body = (' <tbody>\n'
             '  <tr>\n'
             '   <td><a href="http://inasafe.org">InaSAFE</a></td>\n'
             '   <td>b</td>\n'
             '   <td>c</td>\n'
             '   <td>d</td>\n'
             '  </tr>\n'
             ' </tbody>\n')
     expected_result = ('%s%s%s' %
                        (self.html_table_start, body, self.html_table_end))
     actual_result = Table([table_row])
     message = 'Expected: %s\n\nGot: %s' % (expected_result, actual_result)
     assert expected_result.strip() == str(actual_result).strip(), message
     self.html += str(actual_result)
     self.writeHtml('table_colspanning')
Esempio n. 33
0
KX_unk     = module.getOutput('KX_output')
print "KX =",KX_unk[-1][1].getColumn(3)[0:30]
T_unk     = module.getOutput('T_output')
print "tracor =",T_unk[-1][1].getColumn(3)[0:30]
time        = K_unk[-1][0]
print "time = ",time
KY      = K_unk[-1][1]
TY      = T_unk[-1][1]

XListe   = KY.getColumn(0)
dx0 = 0.04/100
dxListe = [dx0] * 100

from tables import Table

tab1  = Table(name='KY')
tab1.addColumn('X',XListe)
tab1.addColumn('Y',KY.getColumn(1))
tab1.addColumn('K',KY.getColumn(3))
KY = tab1
tab2  = Table(name='KT')
tab2.addColumn('X',XListe)
tab2.addColumn('Y',TY.getColumn(1))
tab2.addColumn('K',TY.getColumn(3))
TY = tab2

from _erffunctions import *

C0 = 1.0e-03
porosity = 1.0
darcy = 1.e-3/3600
Esempio n. 34
0
 def read_where(self, *args, **kwargs):
     return Table.read_where(self, *args, **kwargs)
Esempio n. 35
0
 def __init__(self, xy_points: typing.Sequence[XY]):
     self._table = Table()
     self._table.set_table_data(xy_points)
Esempio n. 36
0
    def start(self, source_file, output):
        sections = SectionList()
        document = Document(source_file)

        paragraphs = document.paragraphs
        doc_sections = document.sections
        styles = document.styles
        tables = document.tables

        print('Number of sections  : {}'.format(len(doc_sections)))
        print('Number of paragraphs: {}'.format(len(paragraphs)))
        print('Number of styles    : {}, {} are built-in styles'.format(
            len(styles), len([x for x in styles if x.builtin])))
        print('Number of tables    : {}'.format(len(tables)))
        print('Parsing paragraphs & tables to extract high level information.')
        print('This will take a little while (4-5 minutes)')

        pnum = 0
        tnum = 0
        current_section = None

        def is_section_header(p):
            return (isinstance(p, Paragraph) and len(p.text)
                    and p.style.builtin and 'heading ' in p.style.name.lower())

        for block in Main.iter_block_items(document):
            if isinstance(block, Paragraph):
                if is_section_header(block):
                    # Save of previous
                    current_section = SectionHeading.create(pnum, block)
                    sections.add(current_section)

                elif len(block.text) > 0 and current_section is not None:
                    current_section.add_contents(pnum)

                pnum += 1

            elif isinstance(block, DocxTable):
                if current_section is not None:
                    table = Table.create(tnum, block)
                    current_section.add_contents(table)
                tnum += 1

            else:
                print('Unsupported block type: {}'.format(type(block)))

            if pnum % 25 == 24:
                print('.', end='')
                sys.stdout.flush()
            if pnum % 2000 == 1999:
                print('')

        # Save to file
        print('')
        print('Saving Section parsing information to {}'.format(output))
        sections.save(output)

        print('Section pre-parsing are complete')
        sections.dump()

        # Restore and verify
        sections.load(output)

        print('Dumping data loaded from saved file for verification')
        for section in sections:
            print('  Section: {} -> {}'.format(section,
                                               section.section_points))
Esempio n. 37
0
KX_unk = module.getOutput('KX_output')
print "KX =", KX_unk[-1][1].getColumn(3)[0:30]
T_unk = module.getOutput('T_output')
print "tracor =", T_unk[-1][1].getColumn(3)[0:30]
time = K_unk[-1][0]
print "time = ", time
KY = K_unk[-1][1]
TY = T_unk[-1][1]

XListe = KY.getColumn(0)
dx0 = 0.04 / 100
dxListe = [dx0] * 100

from tables import Table

tab1 = Table(name='KY')
tab1.addColumn('X', XListe)
tab1.addColumn('Y', KY.getColumn(1))
tab1.addColumn('K', KY.getColumn(3))
KY = tab1
tab2 = Table(name='KT')
tab2.addColumn('X', XListe)
tab2.addColumn('Y', TY.getColumn(1))
tab2.addColumn('K', TY.getColumn(3))
TY = tab2

from _erffunctions import *

C0 = 1.0e-03
porosity = 1.0
darcy = 1.e-3 / 3600
 def append(self, rows):
     """
     """
     rows = tabulate(rows)
     Table.append(self, rows)
Esempio n. 39
0
   
    ### ID calculation and assignment phase
    ### Occupied IDs are determined and free IDs are assigned
    ### to new values

    min_free_ids = {}
    args = parse_args()
    all_cards = get_data_frames(args.inputs)

    # Obtain first free_id
    min_free_ids['card_id'] = get_free_min_id(args.cards_table, args.card_id_column)

    new_cards = []
    physical_cards = []
    color_table = []
    current_artists = Table(args.artist_id_column, args.artists_table, columns=['artist'])
    current_types = Table(args.type_id_column, args.types_table, columns=['type'])
    current_physicals = Table(args.physical_card_id_column, args.physical_cards_table, columns=['gatherer_id'])
    current_sets = Table(args.set_id_column, args.sets_table, columns=['set'])

    joins_artists_table = []
    joins_types_table = []
    
    corrections = artists.load_artist_correction_dict(args.correction_file)

    # Begin to parse new cards to generate new database import tables
    for index, raw_card in all_cards.iterrows():
        print 'Processing: %s' % raw_card['card_name']
        new_card_id = index + min_free_ids['card_id']
        new_card = generate_new_card(raw_card, new_card_id, args.card_id_column)
Esempio n. 40
0
    def test_table_with_colalign(self):
        """Table columns can be right justified"""

        # First with default alignment
        actual_result = Table(['12', '3000', '5'])

        expected_strings = ['<td colspan="100%">12</td>',
                            '<td colspan="100%">3000</td>',
                            '<td colspan="100%">5</td>']
        for s in expected_strings:
            message = ('Did not find expected string "%s" in result: %s'
                       % (s, actual_result))
            assert s in str(actual_result).strip(), message

        # Then using explicit alignment (all right justified)
        # FIXME (Ole): This does not work if e.g. col_align has
        # different strings: col_align = ['right', 'left', 'center']
        actual_result = Table(['12', '3000', '5'],
                              col_align=['right', 'right', 'right'])

        expected_strings = [
            ('<td colspan="100%" align="right" style="text-align: '
             'right;">12</td>'),
            ('<td colspan="100%" align="right" style="text-align: '
             'right;">3000</td>'),
            ('<td colspan="100%" align="right" style="text-align: '
             'right;">5</td>')]
        for s in expected_strings:
            message = ('Did not find expected string "%s" in result: %s'
                       % (s, actual_result))
            assert s in str(actual_result).strip(), message

        # Now try at the TableRow level
        # FIXME (Ole): Breaks tables!
        #row = TableRow(['12', '3000', '5'],
        #               col_align=['right', 'right', 'right'])
        #actual_result = Table(row)
        #print actual_result

        # This breaks too - what's going on?
        #row = TableRow(['12', '3000', '5'])
        #actual_result = Table(row)
        #print actual_result

        # Try at the cell level
        cell_1 = TableCell('12')
        cell_2 = TableCell('3000')
        cell_3 = TableCell('5')
        row = TableRow([cell_1, cell_2, cell_3])
        #print row  # OK
        table = Table(row)
        #print table  # Broken

        # Try at the cell level
        cell_1 = TableCell('12', align='right')
        cell_2 = TableCell('3000', align='right')
        cell_3 = TableCell('5', align='right')
        row = TableRow([cell_1, cell_2, cell_3])
        #print row  # OK

        # This is OK
        for cell in [cell_1, cell_2, cell_3]:
            msg = 'Wrong cell alignment %s' % cell
            assert 'align="right"' in str(cell), msg

        table = Table(row)
        self.html += str(table)
        self.writeHtml('table_column_alignment')
Esempio n. 41
0
    def buildRequestTable(self, state, callbacks):
        """
        Builds the request list on the results page on the right.
        """
        splitpane = JSplitPane()
        splitpane.setDividerLocation(1000)

        endpointTable = Table(state.endpointTableModel)
        endpointTable.setDefaultRenderer(Class.forName('java.lang.Object'),
                                         CellHighlighterRenderer(state))

        endpointTable.getColumnModel().getColumn(0).setPreferredWidth(15)
        endpointTable.getColumnModel().getColumn(1).setPreferredWidth(500)
        endpointTable.setAutoCreateRowSorter(True)
        endpointTable.addMouseListener(TableMouseAdapter())

        endpointView = JScrollPane(endpointTable)
        callbacks.customizeUiComponent(endpointTable)
        callbacks.customizeUiComponent(endpointView)

        requestTable = Table(state.requestTableModel)
        requestTable.getColumnModel().getColumn(0).setPreferredWidth(500)

        requestView = JScrollPane(requestTable)
        callbacks.customizeUiComponent(requestTable)
        callbacks.customizeUiComponent(requestView)

        splitpane.setLeftComponent(endpointView)
        splitpane.setRightComponent(requestView)

        return splitpane