Takes a model class and attempts to create a table in TSV format
        that can be imported into a spreadsheet program.
551138
def tableToTsv(self, model):
        
        first = True
        for item in model.select():
            if first:
                header = "".join(
                    ["{}\t".format(x) for x in model._meta.fields.keys()])
                print(header)
                first = False
            row = "".join(
                ["{}\t".format(
                    getattr(item, key)) for key in model._meta.fields.keys()])
            print(row)
1336539
def table= table
      raise(ArgumentError, "value should be nil or Workbook::Table") unless [NilClass,Workbook::Table].include? table.class
      @table = table
    end
1207518
def create_tables(name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options):
    '''
    
    '''

    # get common folder of sourcefiles
    common_prefix = os.path.commonprefix([r.filename for r in rows]) # maybe with parts of filename
    common_prefix = common_prefix[: common_prefix.rfind('/') + 1] # only foldername
    for row in rows:
        Row.set_relative_path(row, common_prefix, outputPath)

    # compute nice name of each run set for displaying
    firstBenchmarkName = Util.prettylist(runSetResults[0].attributes['benchmarkname'])
    allBenchmarkNamesEqual = all(Util.prettylist(r.attributes['benchmarkname']) == firstBenchmarkName for r in runSetResults)
    for r in runSetResults:
        if not r.attributes['name']:
            r.attributes['niceName'] = r.attributes['benchmarkname']
        elif allBenchmarkNamesEqual:
            r.attributes['niceName'] = r.attributes['name']
        else:
            r.attributes['niceName'] = [Util.prettylist(r.attributes['benchmarkname']) + '.' + Util.prettylist(r.attributes['name'])]

    template_values = lambda: None # dummy object as dict replacement for simpler syntax
    template_values.head = get_table_head(runSetResults, common_prefix)
    template_values.run_sets = [runSetResult.attributes for runSetResult in runSetResults]
    template_values.columns = [[column for column in runSet.columns] for runSet in runSetResults]
    template_values.columnTitles =\
        [[column.format_title() for column in runSet.columns] for runSet in runSetResults]

    template_values.relevant_id_columns = select_relevant_id_columns(rows)
    template_values.count_id_columns = template_values.relevant_id_columns.count(True)

    template_values.lib_url = options.lib_url
    template_values.base_dir = outputPath
    template_values.href_base = os.path.dirname(options.xmltablefile) if options.xmltablefile else None
    template_values.version = __version__

    futures = []

    def write_table(table_type, title, rows, use_local_summary):
        # calculate statistics if necessary
        if not options.format == ['csv']:
            local_summary = get_summary(runSetResults) if use_local_summary else None
            stats, stats_columns = get_stats(rows, local_summary, options.correct_only)
        else:
            stats = stats_columns = None

        for template_format in (options.format or TEMPLATE_FORMATS):
            if outputFilePattern == '-':
                outfile = None
                logging.info('Writing %s to stdout...', template_format.upper().ljust(4))
            else:
                outfile = os.path.join(outputPath, outputFilePattern.format(name=name, type=table_type, ext=template_format))
                logging.info('Writing %s into %s ...', template_format.upper().ljust(4), outfile)

            this_template_values = dict(title=title, body=rows, foot=stats, foot_columns=stats_columns)
            this_template_values.update(template_values.__dict__)

            futures.append(parallel.submit(
                write_table_in_format,
                template_format, outfile, this_template_values,
                options.show_table and template_format == 'html',
                ))

    # write normal tables
    write_table("table", name, rows,
                use_local_summary=(not options.correct_only and not options.common))

    # write difference tables
    if rowsDiff:
        write_table("diff", name + " differences", rowsDiff, use_local_summary=False)

    return futures
628167
def bind_collection_to_model_cls(cls):
        
        cls.Collection = type('{0}.Collection'.format(cls.__name__),
                              (cls.Collection,),
                              {'value_type': cls})
        cls.Collection.__module__ = cls.__module__
903669
def dump_tables_to_tskit(pop):
    
    node_view = np.array(pop.tables.nodes, copy=True)
    node_view['time'] -= node_view['time'].max()
    node_view['time'][np.where(node_view['time'] != 0.0)[0]] *= -1.0
    edge_view = np.array(pop.tables.edges, copy=False)
    mut_view = np.array(pop.tables.mutations, copy=False)

    tc = tskit.TableCollection(pop.tables.genome_length)

    # We must initialize population and individual
    # tables before we can do anything else.
    # Attempting to set population to anything
    # other than -1 in an tskit.NodeTable will
    # raise an exception if the PopulationTable
    # isn't set up.
    _initializePopulationTable(node_view, tc)
    node_to_individual = _initializeIndividualTable(pop, tc)

    individual = [-1 for i in range(len(node_view))]
    for k, v in node_to_individual.items():
        individual[k] = v
    flags = [1]*2*pop.N + [0]*(len(node_view) - 2*pop.N)
    # Bug fixed in 0.3.1: add preserved nodes to samples list
    for i in pop.tables.preserved_nodes:
        flags[i] = 1
    tc.nodes.set_columns(flags=flags, time=node_view['time'],
                         population=node_view['population'],
                         individual=individual)
    tc.edges.set_columns(left=edge_view['left'],
                         right=edge_view['right'],
                         parent=edge_view['parent'],
                         child=edge_view['child'])

    mpos = np.array([pop.mutations[i].pos for i in mut_view['key']])
    ancestral_state = np.zeros(len(mut_view), dtype=np.int8)+ord('0')
    ancestral_state_offset = np.arange(len(mut_view)+1, dtype=np.uint32)
    tc.sites.set_columns(position=mpos,
                         ancestral_state=ancestral_state,
                         ancestral_state_offset=ancestral_state_offset)

    derived_state = np.zeros(len(mut_view), dtype=np.int8)+ord('1')
    md, mdo = _generate_mutation_metadata(pop)
    tc.mutations.set_columns(site=np.arange(len(mpos), dtype=np.int32),
                             node=mut_view['node'],
                             derived_state=derived_state,
                             derived_state_offset=ancestral_state_offset,
                             metadata=md,
                             metadata_offset=mdo)
    return tc.tree_sequence()
1002356
def _create(cls, model_class, *args, **kwargs):
        """"""
        session = cls._meta.sqlalchemy_session
        session_persistence = cls._meta.sqlalchemy_session_persistence
        if cls._meta.force_flush:
            session_persistence = SESSION_PERSISTENCE_FLUSH

        obj = model_class(*args, **kwargs)
        if session is None:
            raise RuntimeError("No session provided.")
        session.add(obj)
        if session_persistence == SESSION_PERSISTENCE_FLUSH:
            session.flush()
        elif session_persistence == SESSION_PERSISTENCE_COMMIT:
            session.commit()
        return obj
201058
def generate_models(args):
  """"""
  data_table = get_data_table(args.filename)
  tables = to_tables(data_table.rows_to_dicts())
  attr_indent = "\n" + args.indent * 2
  attr_sep = "," + attr_indent

  for tname, cols in tables.items():
    model_name = table_to_model_name(tname, list(cols.values())[0]["table_schema"])
    pk_cols, oth_cols = split_pks(cols)
    timestamps = get_timestamps(cols, args.created_at_col_name, args.updated_at_col_name)
    is_auto = len(pk_cols) == 1 and cols[pk_cols[0]]["is_auto"] == "t"

    attrs = OrderedDict()
    for cname in oth_cols:
      if cname not in timestamps:
        attrs[cname] = None

    print(_MODEL_SOURCE.format(
      class_name=model_name,
      base_class_name="ModelBase",
      indent=args.indent,
      table_name=repr(tname),
      pk_name=repr(pk_cols[0] if len(pk_cols) == 1 else pk_cols),
      pk_is_auto=is_auto,
      timestamps=timestamps,
      attrs="dict(" + attr_indent + attr_sep.join("{0}={1}".format(k, v) for k, v in attrs.items()) + ")"))
    print()
999013
def import_from_xlsx(
    filename_or_fobj,
    sheet_name=None,
    sheet_index=0,
    start_row=None,
    start_column=None,
    end_row=None,
    end_column=None,
    workbook_kwargs=None,
    *args,
    **kwargs
):
    

    workbook_kwargs = workbook_kwargs or {}
    if "read_only" not in workbook_kwargs:
        workbook_kwargs["read_only"] = True

    workbook = load_workbook(filename_or_fobj, **workbook_kwargs)
    if sheet_name is None:
        sheet_name = workbook.sheetnames[sheet_index]
    sheet = workbook[sheet_name]

    # The openpyxl library reads rows and columns starting from 1 and ending on
    # sheet.max_row/max_col. rows uses 0-based indexes (from 0 to N - 1), so we
    # need to adjust the ranges accordingly.
    min_row, min_column = sheet.min_row - 1, sheet.min_column - 1
    max_row, max_column = sheet.max_row - 1, sheet.max_column - 1
    # TODO: consider adding a parameter `ignore_padding=True` and when it's
    # True, consider `start_row` starting from `sheet.min_row` and
    # `start_column` starting from `sheet.min_col`.
    start_row = start_row if start_row is not None else min_row
    end_row = end_row if end_row is not None else max_row
    start_column = start_column if start_column is not None else min_column
    end_column = end_column if end_column is not None else max_column
    table_rows = []
    is_empty = lambda row: all(cell is None for cell in row)
    selected_rows = sheet.iter_rows(
        min_row=start_row + 1,
        max_row=end_row + 1,
        min_col=start_column + 1,
        max_col=end_column + 1,
    )
    for row in selected_rows:
        row = [_cell_to_python(cell) for cell in row]
        if not is_empty(row):
            table_rows.append(row)

    source = Source.from_file(filename_or_fobj, plugin_name="xlsx")
    source.fobj.close()
    # TODO: pass a parameter to Source.from_file so it won't open the file
    metadata = {"imported_from": "xlsx", "source": source, "name": sheet_name}
    return create_table(table_rows, meta=metadata, *args, **kwargs)
1160688
def appendtsv(table, source=None, encoding=None, errors='strict',
              write_header=False, **csvargs):
    

    csvargs.setdefault('dialect', 'excel-tab')
    return appendcsv(table, source=source, encoding=encoding, errors=errors,
                     write_header=write_header, **csvargs)
428811
def _createTimeSeriesObjects(self, timeSeries, filename):
        
        try:
            # Determine number of value columns
            valColumns = len(timeSeries[0]['values'])

            # Create List of GSSHAPY TimeSeries objects
            series = []
            for i in range(0, valColumns):
                ts = TimeSeries()
                ts.timeSeriesFile = self
                series.append(ts)

            for record in timeSeries:
                for index, value in enumerate(record['values']):
                    # Create GSSHAPY TimeSeriesValue objects
                    tsVal = TimeSeriesValue(simTime=record['time'],
                                            value=value)

                    # Associate with appropriate TimeSeries object via the index
                    tsVal.timeSeries = series[index]
        except IndexError:
            log.warning(('%s was opened, but the contents of the file were empty.'
                     'This file will not be read into the database.') % filename)
        except:
            raise
929434
def create_table(self, table, fields):
        
        table = table.get_soap_object(self.client)
        return self.call('createTable', table, fields)
124288
def _create_table(self):
        
        self.StrTable = ""
        self.AttributesLength = []
        self.Lines_num = 0
        # Prepare some values..
        for col in self.Table:
            # Updates the table line count if necessary
            values = list(col.values())[0]
            self.Lines_num = max(self.Lines_num, len(values))
            # find the length of longest value in current column
            key_length = max([self._disp_width(v) for v in values] or [0])
            # and also the table header
            key_length = max(key_length, self._disp_width(list(col.keys())[0]))
            self.AttributesLength.append(key_length)
        # Do the real thing.
        self._print_head()
        self._print_value()
751885
def as_table(self, fn=None, col=None, col_label=None):
        
        if col_label is None:
            col_label = col
        if fn is None:
            fn = len
            if col_label is None:
                col_label = 'count'
        ret = Table()
        # topattr = self._pivot_attrs[0]
        do_all(ret.create_index(attr) for attr in self._pivot_attrs)
        if len(self._pivot_attrs) == 1:
            for sub in self.subtables:
                subattr, subval = sub._attr_path[-1]
                attrdict = {subattr: subval}
                if col is None or fn is len:
                    attrdict[col_label] = fn(sub)
                else:
                    attrdict[col_label] = fn(s[col] for s in sub)
                ret.insert(DataObject(**attrdict))
        elif len(self._pivot_attrs) == 2:
            for sub in self.subtables:
                for ssub in sub.subtables:
                    attrdict = dict(ssub._attr_path)
                    if col is None or fn is len:
                        attrdict[col_label] = fn(ssub)
                    else:
                        attrdict[col_label] = fn(s[col] for s in ssub)
                    ret.insert(DataObject(**attrdict))
        elif len(self._pivot_attrs) == 3:
            for sub in self.subtables:
                for ssub in sub.subtables:
                    for sssub in ssub.subtables:
                        attrdict = dict(sssub._attr_path)
                        if col is None or fn is len:
                            attrdict[col_label] = fn(sssub)
                        else:
                            attrdict[col_label] = fn(s[col] for s in sssub)
                        ret.insert(DataObject(**attrdict))
        else:
            raise ValueError("can only dump summary counts for 1 or 2-attribute pivots")
        return ret
1195356
def import_model(self, source):
        """"""
        source = self._resolve_source(source)
        self._context = FilePathContext(source)
        with self._context.open() as f:
            self._reader = self._open_reader(f)

        return self._reader.create_model()
798347
function createTable (spec) {
  assert.equal(typeof spec.paths, 'object', 'paths should be object')

  const tableHead = u('tableHeader', [
    u('tableCell', [ u('text', 'Path') ]),
    u('tableCell', [ u('text', 'Method') ]),
    u('tableCell', [ u('text', 'Summary') ])
  ])

  // convert swagger to table rows
  const tableRows = Object.keys(spec.paths).reduce(function (arr, route) {
    Object.keys(spec.paths[route]).forEach(function (method) {
      const summary = spec.paths[route][method].summary || '[ not available ]'
      arr.push(u('tableRow', [
        u('tableCell', [ u('text', route) ]),
        u('tableCell', [ u('text', method.toUpperCase()) ]),
        u('tableCell', [ u('text', summary) ])
      ]))
    })
    return arr
  }, [])

  return u('table', [tableHead].concat(tableRows))
}
438879
function createTableColumn (model, name, spec) {
    // require spec to be object
    assert.ok(typeof spec === 'object', `${name} spec must be object`)
    // require valid type
    assert.ok(columnTypes[spec.type], `invalid type ${spec.type} for ${name}`)
    // build sql string
    var columnType = spec.type === 'id'
        ? (model.binaryIds ? 'BINARY(16)' : 'CHAR(32)')
        : columnTypes[spec.type]
    var sql = `${quoteName(name)} ${columnType}`
    // add unsigned flag if set
    if (spec.unsigned && (spec.type === 'int' || spec.type === 'smallint')) {
        sql += ' UNSIGNED'
    }
    // add not null if null specifically set to false
    if (spec.null === false) {
        sql += ' NOT NULL'
    }
    // add auto increment
    if (spec.auto) {
        sql += ' AUTO_INCREMENT PRIMARY KEY'
    }
    // add default value if set
    if (spec.default !== undefined) {
        // use 0/1 for boolean
        if (spec.type === 'boolean') {
            sql += ` DEFAULT ${spec.default ? 1 : 0}`
        }
        // otherwise use quoteNamed value
        else {
            sql += ` DEFAULT '${spec.default}'`
        }
    }
    // return sql string
    return sql
}
348090
private TableModel createTableModel() {
		//String[][] data = new String[][]{};//{new String[]{"Row 1", "Row 1"}, new String[]{"Row 2", "Row 2"}, new String[]{"Row 3", "Row 3"}};
		int capcity = 100;

		List<String[]> list = new ArrayList<>();
		int i = 1;
		do {
			list.add(new String[]{"Row " + String.valueOf(i), "Row " + String.valueOf(i)});
		} while (++i <= capcity);

		String[][] data = list.toArray(new String[capcity][2]);
		return new AdapterBasicTableModel(new SimpleTableModel(data));
	}