Create tables and indices as needed.
197674
def initdb(self):
        """"""
        if hasattr(self, 'alchemist'):
            self.alchemist.meta.create_all(self.engine)
            if 'branch' not in self.globl:
                self.globl['branch'] = 'trunk'
            if 'rev' not in self.globl:
                self.globl['rev'] = 0
            return
        from sqlite3 import OperationalError
        cursor = self.connection.cursor()
        try:
            cursor.execute('SELECT * FROM global;')
        except OperationalError:
            cursor.execute(self.strings['create_global'])
        if 'branch' not in self.globl:
            self.globl['branch'] = 'trunk'
        if 'turn' not in self.globl:
            self.globl['turn'] = 0
        if 'tick' not in self.globl:
            self.globl['tick'] = 0
        for table in (
            'branches',
            'turns',
            'graphs',
            'graph_val',
            'nodes',
            'node_val',
            'edges',
            'edge_val',
            'plans',
            'plan_ticks'
        ):
            try:
                cursor.execute('SELECT * FROM ' + table + ';')
            except OperationalError:
                cursor.execute(self.strings['create_' + table])
1060781
async def setup(self):
        """"""
        try:
            engine = await self.db
            created = False
            if not await engine.has_table(self.table_name):
                # create table
                logger.info("Creating SQL table [{}]".format(self.table_name))
                items = self._get_table()
                await engine.execute(CreateTable(items))
                # create indeces
                conn = await engine.connect()
                await conn.execute(
                    "CREATE INDEX `lb_last_updated` ON `{}` (`source_id` DESC,`updated` DESC);".format(self.table_name))
                await conn.execute(
                    "CREATE INDEX `lb_post` ON `{}` (`target_id` DESC,`post_id` DESC);".format(self.table_name))
                await conn.close()
                created = True
            # create control table if not already created.
            if self.control_table_name and not await engine.has_table(self.control_table_name):
                # create table
                logger.info("Creating SQL control table [{}]".format(self.control_table_name))
                items = self._get_control_table()
                await engine.execute(CreateTable(items))
                created = True
            return created
        except Exception as exc:
            logger.error("[DB] Error when setting up SQL table: {}".format(exc))
        return False
823302
def create_index(self, columns, name=None, **kw):
        
        columns = [normalize_column_name(c) for c in ensure_tuple(columns)]
        with self.db.lock:
            if not self.exists:
                raise DatasetException("Table has not been created yet.")

            for column in columns:
                if not self.has_column(column):
                    return

            if not self.has_index(columns):
                self._threading_warn()
                name = name or index_name(self.name, columns)
                columns = [self.table.c[c] for c in columns]
                idx = Index(name, *columns, **kw)
                idx.create(self.db.executable)
999631
def create_index(group, chunk_size, compression=None, compression_opts=None):
    """"""
    dtype = np.int64
    if chunk_size == 'auto':
        chunks = True
    else:
        chunks = (nb_per_chunk(np.dtype(dtype).itemsize, 1, chunk_size),)

    group.create_dataset(
        'index', (0,), dtype=dtype,
        chunks=chunks, maxshape=(None,),
        compression=compression, compression_opts=compression_opts)
81729
def outputscreate():
    
    # Create table with a nested index
    r.db("Brain").table_create("Outputs").run()
    r.db("Brain").table("Outputs").index_create("Output_job_id", r.row["OutputJob"]["id"]).run()
    r.db("Brain").table("Outputs").index_wait("Output_job_id").run()
762025
def take_table(tbl, indices, axis=None, out=None, mode='raise', blen=None, storage=None,
               create='table', **kwargs):
    """"""

    # setup
    if axis is not None and axis != 0:
        raise NotImplementedError('only axis 0 is supported')
    if out is not None:
        # argument is only there for numpy API compatibility
        raise NotImplementedError('out argument is not supported')
    if mode is not None and mode != 'raise':
        raise NotImplementedError('only mode=raise is supported')
    names, columns = _util.check_table_like(tbl)
    length = len(columns[0])

    # check that indices are strictly increasing
    indices = np.asanyarray(indices)
    if np.any(indices[1:] <= indices[:-1]):
        raise NotImplementedError(
            'indices must be strictly increasing'
        )

    # implement via compress()
    condition = np.zeros((length,), dtype=bool)
    condition[indices] = True
    return compress_table(condition, tbl, blen=blen, storage=storage,
                          create=create, **kwargs)
143039
def _create_table(self):
        '''
        
        '''
        self._cursor.execute('''
            CREATE TABLE IF NOT EXISTS %(name)s ( %(fields)s )
        ''' % {
            'name': self._name,
            'fields': ','.join('%s %s' % (k, v) for (k, v) in self._fields)
        })
        self._connection.commit()
1357481
private void createTable() {
        if (oxidationStateTable == null) {
            oxidationStateTable = new HashMap<String, int[]>();
            oxidationStateTable.put("H", new int[]{1});
            //            oxidationStateTable.put("Li", 1);
            //            oxidationStateTable.put("Be", 2);
            oxidationStateTable.put("B", new int[]{3});
            oxidationStateTable.put("C", new int[]{4});
            oxidationStateTable.put("N", new int[]{3});
            oxidationStateTable.put("O", new int[]{2});
            oxidationStateTable.put("F", new int[]{1});
            oxidationStateTable.put("Na", new int[]{1});
            oxidationStateTable.put("Mg", new int[]{2});
            oxidationStateTable.put("Al", new int[]{3});
            oxidationStateTable.put("Si", new int[]{4});
            oxidationStateTable.put("P", new int[]{3, 5});
            oxidationStateTable.put("S", new int[]{2, 4, 6});
            oxidationStateTable.put("Cl", new int[]{1});
            //            oxidationStateTable.put("K", 1);
            //            oxidationStateTable.put("Ca", 2);
            //            oxidationStateTable.put("Ga", 3);
            //            oxidationStateTable.put("Ge", 4);
            //            oxidationStateTable.put("As", 5);
            //            oxidationStateTable.put("Se", 6);
            //            oxidationStateTable.put("Br", 7);
            //            oxidationStateTable.put("Rb", 1);
            //            oxidationStateTable.put("Sr", 2);
            //            oxidationStateTable.put("In", 3);
            //            oxidationStateTable.put("Sn", 4);
            //            oxidationStateTable.put("Sb", 5);
            //            oxidationStateTable.put("Te", 6);
            oxidationStateTable.put("I", new int[]{1});
            //            oxidationStateTable.put("Cs", 1);
            //            oxidationStateTable.put("Ba", 2);
            //            oxidationStateTable.put("Tl", 3);
            //            oxidationStateTable.put("Pb", 4);
            //            oxidationStateTable.put("Bi", 5);
            //            oxidationStateTable.put("Po", 6);
            //            oxidationStateTable.put("At", 7);
            //            oxidationStateTable.put("Fr", 1);
            //            oxidationStateTable.put("Ra", 2);
            //            oxidationStateTable.put("Cu", 2);
            //            oxidationStateTable.put("Mn", 2);
            //            oxidationStateTable.put("Co", 2);
        }
    }
99541
def create(self):
        """"""
        body = dict()
        if self.mapping is not None:
            body['mappings'] = self.mapping
        if self.settings is not None:
            body['settings'] = self.settings
        else:
            body['settings'] = self._default_settings()
        self.instance.indices.create(self.index, body)
693142
def _create_table(self, table_name):
        ''' 
        '''
        if self.fieldnames:
            sql_fields = []
            for field in self._fields:
                if field != '_id':
                    if 'dblite' in self._fields[field]:
                        sql_fields.append(' '.join([field, self._fields[field]['dblite']]))
                    else:
                        sql_fields.append(field)
            sql_fields = ','.join(sql_fields)
            SQL = 'CREATE TABLE IF NOT EXISTS %s (%s);' % (table_name, sql_fields)
            try:
                self._cursor.execute(SQL)
            except sqlite3.OperationalError, err:
                raise RuntimeError('Create table error, %s, SQL: %s' % (err, SQL))
495583
def create_table(db, schema_name, table_name, columns):
    
    table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name
    db.execute('DROP TABLE IF EXISTS {0}'.format(table))
    columns_list = ', '.join(columns)
    db.execute('CREATE TABLE {0} ({1})'.format(table, columns_list))
1109473
def make_table(self):
        """"""
        num_records = int(np.sum([1 for frame in self.timeseries]))
        dtype = [
                ("frame",float),("time",float),("proteinring",list),
                ("ligand_ring_ids",list),("distance",float),("angle",float),
                ("offset",float),("type","|U4"),("resid",int),("resname","|U4"),("segid","|U8") ]
        out = np.empty((num_records,),dtype=dtype)
        cursor=0
        for contact in self.timeseries:
            out[cursor] = (contact.frame, contact.time,contact.proteinring,contact.ligandring,contact.distance,contact.angle,contact.offset,contact.type,contact.resid,contact.resname,contact.segid)
            cursor+=1
        return out.view(np.recarray)
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
604322
def create(self, using=None, **kwargs):
        
        self._get_connection(using).indices.create(index=self._name, body=self.to_dict(), **kwargs)
859875
def make_table(headers=None, rows=None):
    """"""
    if callable(headers):
        headers = headers()
    if callable(rows):
        rows = rows()
    assert isinstance(headers, list)
    assert isinstance(rows, list)
    assert all(len(row) == len(headers) for row in rows)

    plain_headers = [strip_ansi(six.text_type(v)) for v in headers]
    plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]]

    plain_headers = []
    column_widths = []

    for k, v in enumerate(headers):
        v = six.text_type(v)
        plain = strip_ansi(v)
        plain_headers.append(plain)
        column_widths.append(len(plain))

        if len(v) == len(plain):
            # Value was unstyled, make it bold
            v = click.style(v, bold=True)

        headers[k] = v

    plain_rows = []
    for row in rows:
        plain_row = []
        for k, v in enumerate(row):
            v = six.text_type(v)
            plain = strip_ansi(v)
            plain_row.append(plain)
            column_widths[k] = max(column_widths[k], len(plain))

        plain_rows.append(plain_row)

    return Table(
        headers=headers,
        plain_headers=plain_headers,
        rows=rows,
        plain_rows=plain_rows,
        column_widths=column_widths,
    )
83051
def ensure_table(self, cls):
        """"""
        id_len = len(uuid())
        index_names = cls.index_names() or []
        cols = [
            'id char(%d) primary key' % (id_len,),
            'value jsonb'
        ] + [
            name + ' text' for name in index_names
        ]

        table_name = cls.get_table_name()

        with self._conn() as conn:
            with conn.cursor() as cur:
                cur.execute('create table if not exists %s (%s);' % (
                    table_name,
                    ','.join(cols)
                ))
                for name in index_names:
                    cur.execute('create index if not exists %s on %s(%s);' % (
                        table_name + '_' + name + '_idx',
                        table_name,
                        name
                    ))
876163
def create():
    """"""
    if not all(map(os.path.isdir, ARGS.directory)):
        exit('Error: One or more of the specified directories does not exist.')
    with sqlite3.connect(ARGS.database) as connection:
        connection.text_factory = str
        cursor = connection.cursor()
        cursor.execute('DROP TABLE IF EXISTS Movies')
        cursor.execute('''CREATE TABLE Movies(name TEXT, path TEXT, size TEXT,
                          files BLOB)''')
        for dir in ARGS.directory:
            cursor.executemany('INSERT INTO Movies VALUES(?, ?, ?, ?)',
                               local_data(dir))