## Table constructor

Creates a new Table object

@param {object} options Optional. Configuration for NDDB
@param {array} data Optional. Array of initial items
341445
function Table(options, data) {
        options = options || {};

        // Updates indexes on the fly.
        if (!options.update) options.update = {};

        if ('undefined' === typeof options.update.indexes) {
            options.update.indexes = true;
        }

        NDDB.call(this, options, data);

//         // ### Table.row
//         // NDDB hash containing elements grouped by row index
//         // @see NDDB.hash
//         if (!this.row) {
//             this.hash('row', function(c) {
//                 return c.x;
//             });
//         }
//
//         // ### Table.col
//         // NDDB hash containing elements grouped by column index
//         // @see NDDB.hash
//         if (!this.col) {
//             this.hash('col', function(c) {
//                 return c.y;
//             });
//         }

        // ### Table.rowcol
        // NDDB index to access elements with row.col notation
        // @see NDDB.hash
        if (!this.rowcol) {
            this.index('rowcol', function(c) {
                return c.x + '.' + c.y;
            });
        }

        /**
         * ### Table.pointers
         *
         * References to last inserted cell coordinates
         */
        this.pointers = {
            x: options.pointerX || null,
            y: options.pointerY || null
        };

        /**
         * ### Table.header
         *
         * Array containing the header elements of the table
         */
        this.header = [];

        /**
         * ### Table.footer
         *
         * Array containing the footer elements of the table
         */
        this.footer = [];

        /**
         * ### Table.left
         *
         * Array containing elements to keep on the left border of the table
         */
        this.left = [];

        /**
         * ### Table.table
         *
         * Reference to the HTMLElement Table
         */
        this.table = options.table || document.createElement('table');

        if ('string' === typeof options.id) {
            this.table.id = options.id;
        }
        else if (options.id) {
            throw new TypeError('Table constructor: options.id must be ' +
                                'string or undefined.');
        }

        if ('string' === typeof options.className) {
            this.table.className = options.className;
        }
        else if (J.isArray(options.className)) {
            this.table.className = options.className.join(' ');
        }
        else if (options.className) {
            throw new TypeError('Table constructor: options.className must ' +
                                'be string, array, or undefined.');
        }

        /**
         * ### Table.missingClassName
         *
         * Class name for "missing" cells
         *
         * "Missing" cells are cells that are added automatically to complete
         * the table because one or more cells have been added with higher
         * row and column indexes.
         */
        this.missingClassName = 'missing';

        if ('string' === typeof options.missingClassName) {
            this.missingClassName = options.missingClassName;
        }
        else if (J.isArray(options.missingClassName)) {
            this.missingClassName = options.missingClassName.join(' ');
        }
        else if (options.missingClassName) {
            throw new TypeError('Table constructor: options.className must ' +
                                'be string, array, or undefined.');
        }

        /**
         * ### Table.autoParse
         *
         * If TRUE, whenever a new cell is added the table is updated.
         * Default: FALSE
         */
        this.autoParse = 'undefined' !== typeof options.autoParse ?
            options.autoParse : false;

        /**
         * ### Table.trs
         *
         * List of TR elements indexed by their order in the parsed table
         */
        this.trs = {};

        /**
         * ### Table.trCb
         *
         * Callback function applied to each TR HTML element
         *
         * Callback receives the HTML element, and the row index, or
         * 'thead' and 'tfoot' for header and footer.
         */
        if ('function' === typeof options.tr) {
            this.trCb = options.tr;
        }
        else if ('undefined' === typeof options.tr) {
            this.trCb = null;
        }
        else {
            throw new TypeError('Table constructor: options.tr must be ' +
                                'function or undefined.');
        }

        // Init renderer.
        this.initRenderer(options.render);
    }
814704
function (data, defaults, callback) {
  // Flatten everything for ease of use.
  var options = _.defaults({}, data, data.options, defaults)

  callback(null, options)
}
309646
function(data) {
		try {
		    this.options.language = new TL.Language(this.options);

		    this._initData(data);
		} catch(e) {
		    this.showMessage(this._translateError(e));
		}
	}
996715
function create(item, h)
{
	if (h === 0)
	{
		return {
			ctor: '_Array',
			height: 0,
			table: [item]
		};
	}
	return {
		ctor: '_Array',
		height: h,
		table: [create(item, h - 1)],
		lengths: [1]
	};
}
650534
function(td, options) {
      var expected = options.indexes.expected[options.sequenceIndex] !== null;
      var exists = options.dataIndex !== null;
      td.setAttribute('data-expected', expected === exists ? 'yes' : 'no');
    }
526740
function createTables() {
            return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) {
                var entity = CRUD.EntityManager.entities[entityName];
                if (tables.indexOf(entity.table) == -1) {
                    if (!entity.createStatement) {
                        throw "No create statement found for " + entity.getType() + ". Don't know how to create table.";
                    }
                    return db.execute(entity.createStatement).then(function() {
                        tables.push(entity.table);
                        localStorage.setItem('database.version.' + entity.table, ('migrations' in entity) ? Math.max.apply(Math, Object.keys(entity.migrations)) : 1);
                        CRUD.log(entity.table + " table created.");
                        return entity;
                    }, function(err) {
                        CRUD.log("Error creating " + entity.table, err, entity.createStatement);
                        throw "Error creating table: " + entity.table;
                    }).then(createFixtures).then(function() {
                        CRUD.log("Table created and fixtures inserted for ", entityName);
                        return;
                    });
                }
                return;
            }));
        }
784120
function(element, options) {
        var that       = this;
        var $element   = that.$ = $(element);
        that.name      = NAME;
        that.uuid      = $.zui.uuid();
        that.id        = 'zui-datagrid-' + that.uuid;
        options        = $.extend({}, DataGrid.DEFAULTS, that.$.data(), options);

        var lang   = options.lang || 'zh_cn';
        that.lang  = $.isPlainObject(lang) ? ($.extend(true, {}, LANG[lang.lang || $.zui.clientLang()], lang)) : LANG[lang];

        options.valueOperator    = $.extend({}, DEFAULT_VALUE_OPERATOR, options.valueOperator);
        options.rowDefaultHeight = options.rowDefaultHeight || 30;
        options.headerHeight     = options.headerHeight || options.rowDefaultHeight || 30;
        that.options             = options;
        if (typeof options.borderWidth !== 'number') {
            options.borderWidth = 1;
        }

        // Initialize
        if ($element.is('table')) {
            options.dataSource = $.extend(loadDataSourceFromTable(that.$), options.dataSource);
            $element.hide();
            $element = $('<div class="datagrid" id="datagrid-' + that.uuid + '" />').insertAfter(that.$);
        }

        var $container = $element.find('.datagrid-container:first');
        if (!$container.length) {
            $container = $('<div class="datagrid-container" />').appendTo($element);
        }
        $container.css({
            width:       options.width,
            borderWidth: options.borderWidth
        });
        var $document = $(document);
        var createScrollbar = function(direction) {
            var $scrollbar = $container.find('.datagrid-scrollbar-' + direction);
            if (!$scrollbar.length) {
                $scrollbar = $('<div class="datagrid-scrollbar datagrid-scrollbar-' + direction + '"><div class="bar"></div></div>').appendTo($container);
            }
            var isMouseDown = false;
            var lastPos = null;
            var eventSuffix = '.scrollbar' + direction + '.' + NAME + '.' + that.uuid;
            var startPagePos, startPageOffset, isClickBar, startScrollOffset;
            var handleMousePosition = function(e) {
                if (!isMouseDown) return;
                var pos = e[direction === 'h' ? 'pageX' : 'pageY'];
                if (lastPos === pos) {
                    return;
                }
                lastPos = pos;
                pos = (pos - startPagePos) + startPageOffset;
                var scroll = that.layout[direction + 'Scroll'];
                var offset;
                if (isClickBar) {
                    offset = (lastPos - startPagePos) + startScrollOffset;
                } else {
                    offset = Math.max(0, Math.min(scroll.space, pos - Math.round(scroll.barSize/2)));
                }
                if (direction === 'h') {
                    that.setScrollbarOffset(offset);
                } else {
                    that.setScrollbarOffset(null, offset);
                }
            };
            $scrollbar.on('mousedown', function(e) {
                e.preventDefault();
                isMouseDown = true;
                var scroll = that.layout[direction + 'Scroll'];
                var degree = direction === 'h' ? 'X' : 'Y';
                startPageOffset = e['offset' + degree];
                startPagePos = e['page' + degree];
                isClickBar = $(e.target).is('.bar');
                startScrollOffset = scroll.offset;
                if (isClickBar) {
                    startPageOffset += startScrollOffset;
                }
                handleMousePosition(e);
                $scrollbar.addClass('scrolling');
                $document.on('mouseup' + eventSuffix, function(e) {
                    isMouseDown = false;
                    handleMousePosition(e);
                    $document.off(eventSuffix);
                    $scrollbar.removeClass('scrolling');
                }).on('mousemove' + eventSuffix, handleMousePosition);
            });
            that['$' + direction + 'Scroll'] = $scrollbar;
            that['$' + direction + 'Scrollbar'] = $scrollbar.find('.bar');
        };
        createScrollbar('h');
        createScrollbar('v');
        var mouseWheelFactor = options.mouseWheelFactor;
        var isWindows = window.navigator.userAgent.match(/Win/i);
        if (isWindows) mouseWheelFactor *= 20;
        $container.on('mousewheel', function(event) {
            that.scroll(that.layout.scrollLeft - Math.round(event.deltaX * mouseWheelFactor), that.layout.scrollTop - Math.round(event.deltaY * mouseWheelFactor));
            event.preventDefault();
        });

        that.$container = $container;

        var $cells = $element.find('.datagrid-cells:first');
        if (!$cells.length) {
            $cells = $('<div class="datagrid-cells" />').appendTo($container);
        }
        $cells.toggleClass('datagrid-hover-cell', !!options.hoverCell)
              .toggleClass('datagrid-hover-row', !!options.hoverRow)
              .toggleClass('datagrid-hover-col', !!options.hoverCol)
              .toggleClass('datagrid-hover-shadow', !!options.hoverCol);
        that.$cells = $cells;

        // configs is an object
        that.isFuncConfigs = $.isFunction(options.configs);
        that.configs = that.isFuncConfigs ? options.configs : $.extend({}, DEFAULT_CONFIGS, options.configs);

        that.layout       = {scrollLeft: 0, scrollTop: 0};
        that.configsCache = {};
        that.userConfigs  = {};

        // states is 2D arrays
        that.states    = $.extend(true, {}, DEFAULT_STATES, options.states);
        that.cells     = [];
        that.setPager(that.states.pager);

        that.setDataSource(options.dataSource);

        if (options.responsive) {
            var lastContainerWidth = $container.width();
            $container.on('resize', function() {
                that.layout.cols = null;
                that.render();
            });
        }

        if (options.hoverCol) {
            $cells.on('mouseenter', '.datagrid-cell-head', function() {
                var $headCol = $(this);
                var colIndex = $headCol.data('col');
                that.$cells.find('.datagrid-cell.hover').removeClass('hover');
                that.$cells.find('.datagrid-cell[data-col="' + colIndex + '"]').addClass('hover');
            }).on('mouseleave', '.datagrid-cell-head.hover', function() {
                that.$cells.find('.datagrid-cell.hover').removeClass('hover');
            });
        }

        if (options.sortable) {
            $cells.on('click', '.datagrid-col-sortable', function() {
                var colIndex = $(this).data('col');
                var col = that.getColConfig(colIndex);
                var sortBy = that.states.sortBy;
                var order = that.states.order;
                if (sortBy !== col.name) {
                    sortBy = col.name;
                    order = 'desc';
                } else if (order === 'desc') {
                    order = 'asc';
                } else if (order === 'asc') {
                    sortBy = '';
                }
                that.sortBy(sortBy, order);
            });
        }

        if (options.checkable) {
            if (options.selectable && $.fn.selectable) {
                that.selectable = $cells.selectable($.extend({
                    selector: '.datagrid-row-cell',
                    // selectClass: false,
                    trigger: options.checkByClickRow ? null : '.datagrid-row-cell .datagrid-has-checkbox',
                    clickBehavior: 'multi',
                    select: function(data) {
                        that.checkRow(data.id, true);
                    },
                    unselect: function(data) {
                        that.checkRow(data.id, false);
                    }
                }, $.isPlainObject(options.selectable) ? options.selectable : null)).data('zui.selectable');
                $cells.on('click', '.datagrid-cell-head.datagrid-has-checkbox', function() {
                    that.checkRow($(this).data('row'));
                    that.selectable.syncSelectionsFromClass();
                });
            } else {
                $cells.on('click', options.checkByClickRow ? '.datagrid-row' : '.datagrid-has-checkbox', function(e) {
                    var rowIndex = $(this).data('row');
                    if (rowIndex || $(e.target).closest('.datagrid-has-checkbox').length) {
                        that.checkRow(rowIndex);
                    }
                });
            }
        }

        // Init pager
        if ($.fn.pager) {
            var $pager = that.$.find('.pager');
            if ($pager.length) {
                that.pagerObj = $pager.pager($.extend({}, that.pager, {
                    onPageChange: function(pageInfo) {
                        that.setPager(pageInfo).render();
                    }
                })).data('zui.pager');
            }
        }

        // Init searchbox
        if ($.fn.searchBox) {
            var $searchBox = that.$.find('.search-box');
            if($searchBox)  {
                that.searchbox = $searchBox.searchBox({
                    onSearchChange: function (searchString) {
                        that.search(searchString);
                    }
                });
            }
        }

        that.render();
    }
323313
public void createTables() {
        Validate.notNull(connector, "connector must not be null");
        Validate.notNull(tableOperations, "tableOperations must not be null");

        /*
         * This code sets the default values. If you want to change them,
         * you can over-write the metadata entries instead of changing
         * the values here.
         */
        Value defaultFieldDelimiter = new Value("\t".getBytes(charset));
        Value defaultFactDelimiter = new Value("|".getBytes(charset));

        int isEdgePresent = tableOperations.exists(getEdgeTable()) ? 1 : 0;
        int isTransposePresent = tableOperations.exists(getTransposeTable()) ? 1 : 0;
        int isDegreePresent = tableOperations.exists(getDegreeTable()) ? 1 : 0;
        int isMetatablePresent = tableOperations.exists(getMetadataTable()) ? 1 : 0;
        int isTextPresent = tableOperations.exists(getTextTable()) ? 1 : 0;

        int tableCount = isEdgePresent + isTransposePresent + isDegreePresent + isMetatablePresent + isTextPresent;

        if (tableCount > 0 && tableCount < 5) {
            throw new D4MException("D4M: RootName[" + getRootName() + "] Inconsistent state - one or more D4M tables is missing.");
        }

        if (tableCount == 5) {
            // assume the tables are correct.
            return;
        }

        try {
            tableOperations.create(getEdgeTable());
            tableOperations.create(getTransposeTable());
            tableOperations.create(getDegreeTable());
            tableOperations.create(getMetadataTable());
            tableOperations.create(getTextTable());

            IteratorSetting degreeIteratorSetting = new IteratorSetting(7, SummingCombiner.class);
            SummingCombiner.setEncodingType(degreeIteratorSetting, LongCombiner.Type.STRING);
            SummingCombiner.setColumns(degreeIteratorSetting, Collections.singletonList(new IteratorSetting.Column("", "degree")));
            tableOperations.attachIterator(getDegreeTable(), degreeIteratorSetting);

            IteratorSetting fieldIteratorSetting = new IteratorSetting(7, SummingCombiner.class);
            SummingCombiner.setEncodingType(fieldIteratorSetting, LongCombiner.Type.STRING);
            SummingCombiner.setColumns(fieldIteratorSetting, Collections.singletonList(new IteratorSetting.Column("field", "")));
            tableOperations.attachIterator(getMetadataTable(), fieldIteratorSetting);

            Mutation mutation = new Mutation(PROPERTY);
            mutation.put(FIELD_DELIMITER_PROPERTY_NAME, EMPTY_CQ, defaultFieldDelimiter);
            mutation.put(FACT_DELIMITER_PROPERTY_NAME, EMPTY_CQ, defaultFactDelimiter);
            
            BatchWriterConfig bwConfig = new BatchWriterConfig();
            bwConfig.setMaxLatency(10000, TimeUnit.MINUTES);
            bwConfig.setMaxMemory(10000000);
            bwConfig.setMaxWriteThreads(5);
            bwConfig.setTimeout(5, TimeUnit.MINUTES);
            
            BatchWriter writer = connector.createBatchWriter(getMetadataTable(), bwConfig);
            writer.addMutation(mutation);
            writer.close();
        } catch (AccumuloException | AccumuloSecurityException | TableExistsException | TableNotFoundException e) {
            throw new D4MException("Error creating tables.", e);
        }

    }
332599
function addData($data, $col_id = 0, $row_id = 0) {
        foreach ($data as $row) {
            if ($row === self::CONSOLE_TABLE_HORIZONTAL_RULE) {
                $this->_data[$row_id] = self::CONSOLE_TABLE_HORIZONTAL_RULE;
                $row_id++;
                continue;
            }
            $starting_col = $col_id;
            foreach ($row as $cell) {
                $this->_data[$row_id][$starting_col++] = $cell;
            }
            $this->_updateRowsCols();
            $this->_max_cols = max($this->_max_cols, $starting_col);
            $row_id++;
        }
    }
441427
function buildTableColumns(item, tableStructuresAndCombinations) {
  if (!defined(tableStructuresAndCombinations)) {
    // Invalid selection, eg. missing a selected code for a concept.
    return []; // Remove current columns.
  }
  var tableStructures = tableStructuresAndCombinations.tableStructures;
  var activeCombinations = tableStructuresAndCombinations.activeCombinations;
  if (tableStructures.length <= 1) {
    throwLoadError(item, "GetGenericData");
  }
  // The last element of the tableStructures is the total population.
  var totalPopulationTableStructure = tableStructures.pop();

  var firstTableStructure = tableStructures[0];
  var timeColumn = firstTableStructure.columns[0];
  var regionColumn = firstTableStructure.columns[2];
  var isTimeVarying =
    defined(timeColumn) && timeColumn.minimumValue !== timeColumn.maximumValue;
  // If there is time variation, for now, let's turn off the displayPercent option.
  // (since we don't have time-varying population data yet)
  if (isTimeVarying) {
    item.canDisplayPercent = false;
    item.displayPercent = false;
  } else {
    item.canDisplayPercent = true; // Assume we can unless proven otherwise.
  }

  var newColumns = buildValueColumns(item, tableStructures, activeCombinations);
  var totalSelectedColumn = new TableColumn(
    "Total selected",
    TableColumn.sumValues(newColumns),
    {
      active: !item.displayPercent
    }
  );
  // If there's more than one combination selected, add the total selected.
  if (newColumns.length > 1) {
    newColumns.push(totalSelectedColumn);
  } else if (!item.displayPercent) {
    // If there's only one value column, activate it.
    newColumns[0].isActive = true;
  }

  // Only add the total population columns if there is no time variation
  // (for now, since we don't have time-varying population data)
  if (!isTimeVarying) {
    var totalPopColumns = totalPopulationTableStructure.columns;
    // Check that the regions correspond in the two tables.  Assume total popn table has regions as first column.
    if (
      !arraysAreEqual(
        totalPopColumns[0].values.slice(0, regionColumn.values.length),
        regionColumn.values
      )
    ) {
      console.error(
        "Region ordering is different between total population data file and ABS data set."
      );
      // Activate the last value column, turn off percentDisplay and don't add the total population columns.
      item.canDisplayPercent = false;
      item.displayPercent = false;
      newColumns[newColumns.length - 1].isActive = true;
    } else {
      var totalPopColumn = new TableColumn(
        "Total population",
        totalPopColumns[totalPopColumns.length - 1].values.slice(
          0,
          regionColumn.values.length
        )
      );
      newColumns.push(totalPopColumn);
      var percentValues = TableColumn.divideValues(
        totalSelectedColumn,
        totalPopColumn,
        0
      ).map(function(fraction) {
        return fraction < 0.01
          ? Math.round(fraction * 1000) / 10
          : Math.round(fraction * 10000) / 100;
      });
      newColumns.push(
        new TableColumn("Total selected percent", percentValues, {
          active: item.displayPercent
        })
      );
    }
  }
  // Rename the region column to conform to csv-geo-au.
  // Since only one regiontype code can be selected, all combinations have the same regiontype.
  // (Don't use getActiveRegionTypeCode() because the UI might no longer reflect which regiontype was loaded.)
  // Just use the first time from the time column; we assume these are all the same (eg. 2011).
  var loadedRegionCode = activeCombinations[0].filter(function(absCode) {
    return absCode.concept.id === item.regionTypeConcept;
  })[0];
  var regionColumnName = regionTypeToCsvGeo(loadedRegionCode.code, timeColumn);

  // Make sure the Time and REGION columns match across columns (apart from the totalPopulationTableStructure).
  // Don't worry about Description - it is a description of the region, which we get from the region mapping anyway.
  if (!isTimeVarying) {
    timeColumn.options.type = VarType.SCALAR; // Otherwise we can get a spurious clock.
  }
  timeColumn = new TableColumn("Year", timeColumn.values, timeColumn.options);
  regionColumn = new TableColumn(
    regionColumnName,
    regionColumn.values,
    regionColumn.options
  );
  tableStructures.slice(1).forEach(function(tableStructure) {
    if (
      !arraysAreEqual(tableStructure.columns[0], timeColumn) ||
      !arraysAreEqual(tableStructure.columns[2], regionColumn)
    ) {
      throwDataMergeError(item);
    }
  });

  // Put these columns to the front of the value columns.
  newColumns.unshift(timeColumn);
  newColumns.unshift(regionColumn);

  return newColumns;
}
1055387
function Builder (data) {

  if (!(this instanceof Builder)) return new Builder(data);

  debug('new builder', data);

  events.EventEmitter.call(this);

  this.message = Message(data);

}
1063879
function insertColumn(
    opts: Options,
    change: Change,
    at?: number, // Column index
    getCell?: (column: number, row: number) => Block
): Change {
    const { value } = change;
    const { startKey } = value;

    const pos = TablePosition.create(opts, value.document, startKey);
    const { table } = pos;

    const columnIndex =
        typeof at === 'undefined' ? pos.getColumnIndex() + 1 : at;

    // Insert the new cell
    table.nodes.forEach((row, rowIndex) => {
        const newCell = getCell
            ? getCell(columnIndex, rowIndex)
            : createCell(opts);
        change.insertNodeByKey(row.key, columnIndex, newCell, {
            normalize: false
        });
    });

    // Update the selection (not doing can break the undo)
    return moveSelection(
        opts,
        change,
        pos.getColumnIndex() + 1,
        pos.getRowIndex()
    );
}
311533
public function insert(array $data, array $options = []) {
		return $this->getAdapter()->insert(
			$this->getTableName(),
			$data,
			$options
		);
	}
1224355
function createTable(table, transaction) {
    return (transaction || db.knex).schema.hasTable(table)
        .then(function (exists) {
            if (exists) {
                return;
            }

            return (transaction || db.knex).schema.createTable(table, function (t) {
                var columnKeys = _.keys(schema[table]);
                _.each(columnKeys, function (column) {
                    return addTableColumn(table, t, column);
                });
            });
        });
}
436319
public function insert($data, $options = [])
    {
        return $this->database->createCommand()->insert($this->name, $data, $options);
    }
306096
async function createTable (args) {
    // get args object
    args = requireValidOptionalObject(args)
    // get create table sql
    var createTableSql = sql.createTable(this)
    // debug
    debug(createTableSql)
    // attempt to create table
    await this.mysql().query(createTableSql, {}, {}, args.session)
}
441284
function (options, chartOptions) {
		this.options = options;
		this.chartOptions = chartOptions;
		this.columns = options.columns || this.rowsToColumns(options.rows) || [];

		// No need to parse or interpret anything
		if (this.columns.length) {
			this.dataFound();

		// Parse and interpret
		} else {

			// Parse a CSV string if options.csv is given
			this.parseCSV();
			
			// Parse a HTML table if options.table is given
			this.parseTable();

			// Parse a Google Spreadsheet 
			this.parseGoogleSpreadsheet();	
		}

	}