Ejemplo n.º 1
0
/* Creates and returns a new chain.  Returns NULL if the chain cannot be
 * created. */
struct sw_chain *chain_create(void)
{
    struct sw_chain *chain = calloc(1, sizeof *chain);
    if (chain == NULL)
        return NULL;

    if (add_table(chain, table_hash2_create(0x1EDC6F41, TABLE_HASH_MAX_FLOWS,
                                               0x741B8CD7, TABLE_HASH_MAX_FLOWS))
        || add_table(chain, table_linear_create(TABLE_LINEAR_MAX_FLOWS))) {
        chain_destroy(chain);
        return NULL;
    }

    return chain;
}
Ejemplo n.º 2
0
void restore_databases(struct configuration *conf, MYSQL *conn) {
	GError *error= NULL;
	GDir* dir= g_dir_open(directory, 0, &error);

	if (error) {
		g_critical("cannot open directory %s, %s\n", directory, error->message);
		errors++;
		return;
	}

	const gchar* filename= NULL;

	while((filename= g_dir_read_name(dir))) {
		if (g_strrstr(filename, "-schema.sql")) {
			add_schema(filename, conn);
		}
	}

	g_dir_rewind(dir);

	while((filename= g_dir_read_name(dir))) {
		if (!g_strrstr(filename, "-schema.sql") && g_strrstr(filename, ".sql")) {
			add_table(filename, conf);
		}
	}

	g_dir_close(dir);
}
Ejemplo n.º 3
0
Archivo: model.cpp Proyecto: mrG7/lda
microscopes::lda::state::state(const model_definition &defn,
      float alpha,
      float beta,
      float gamma,
      const microscopes::lda::nested_vector &dish_assignments,
      const microscopes::lda::nested_vector &table_assignments,
      const microscopes::lda::nested_vector &docs)
    : state(defn, alpha, beta, gamma, docs) {
        // Explicit initialization constructor for state used for
        // deserialization and testing
        // table_assignment maps words to tables (and should be the same
        //  shape as docs)
        // dish_assignment maps tables to dishes (its outer length should
        //  be the the same as docs. Its inner length one plus the maximum
        //  table index value for the given entity/doc.)

        // Create all the dishes we will need.
        for(auto dish: lda_util::unique_members(dish_assignments)) {
            create_dish(dish);
        }
        for (size_t eid = 0; eid < nentities(); ++eid) {
            create_entity(eid);
            // Create all the tables we will need and assign them to their dish.
            for(auto did: dish_assignments[eid]){
                create_table(eid, did);
            }
            // Assign words to tables.
            for(size_t word_index = 0; word_index < table_assignments[eid].size(); word_index++){
                auto tid  = table_assignments[eid][word_index];
                add_table(eid, tid, word_index);
            }
        }
}
Ejemplo n.º 4
0
Tables::Tables(){

  if ( !existingDir( string( "data" ) )){
    if ( !existingDir( "data" ) )
    {
      if ( system( "mkdir data" ) != 0  ){
        cerr << "Error making database directory" << endl;
        exit(1);
      }
      system( "cd data" );
    }
  }
      
    
    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir( "./data" )) != NULL ){
      while( (ent = readdir( dir )) != NULL) {
        string file_name( ent->d_name );
        if ( isTBLfile( file_name ) ){
          string first_line;  
        
          ifstream table( toChars( string ( string( "./data/") + string (ent->d_name ) ) ) );
          if( table.is_open() ){
            getline( table, first_line );
            table.close();
          }

          add_table( file_name.substr(0, file_name.size() - 4 ) , first_line );
        }
      }
    }
  }
Ejemplo n.º 5
0
void
create_toolbar_button_dialog(ToolbarButton **tb)
{
  GtkWidget *dialog_vbox;
  GtkWidget *action_area;
  GtkWidget *table;
  GList *tmp, *strings = NULL;

  dialog = gtk_dialog_new();
  dialog_vbox = GTK_DIALOG(dialog)->vbox;
  action_area = GTK_DIALOG(dialog)->action_area;
  gtk_container_set_border_width(GTK_CONTAINER(dialog_vbox), 5);
  gtk_box_set_spacing(GTK_BOX(dialog_vbox), 5);
  gtk_signal_connect(GTK_OBJECT(dialog), "delete_event", delete_event_cb, NULL);
  gtk_signal_connect(GTK_OBJECT(dialog), "key_press_event",
                     GTK_SIGNAL_FUNC(key_press_cb), NULL);

  table = add_table(dialog_vbox, 2, 2, FALSE, FALSE, 0);
  gtk_table_set_row_spacings(GTK_TABLE(table), 5);

  add_label_to_table(table, _("Label: "), 0.0, 0, 1, 0, 1);
  add_label_to_table(table, _("Tooltip: "), 0.0, 0, 1, 1, 2);
  title_entry = add_entry_to_table(table, "", 1, 2, 0, 1);
  tooltip_entry = add_entry_to_table(table, "", 1, 2, 1, 2);

  table = add_framed_table(dialog_vbox, _("Action: "), 2, 2, FALSE, 0);

  shell_radio_button = add_radio_button_to_table(table, _("Command: "), NULL,
                FALSE, shell_radio_cb, NULL, 0, 1, 0, 1);
  action_entry = add_entry_to_table(table, "", 1, 2, 0, 1);

  if (*tb != NULL)
  {
    gtk_entry_set_text(GTK_ENTRY(title_entry), (*tb)->label);
    gtk_entry_set_text(GTK_ENTRY(tooltip_entry), (*tb)->tooltip);
    gtk_entry_set_text(GTK_ENTRY(action_entry), (*tb)->action);
  }
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(shell_radio_button), TRUE);

  gtk_signal_connect(GTK_OBJECT(title_entry), "activate", 
                     GTK_SIGNAL_FUNC(ok_cb), tb);

  gtk_signal_connect(GTK_OBJECT(tooltip_entry), "activate", 
                     GTK_SIGNAL_FUNC(ok_cb), tb);

  gtk_signal_connect(GTK_OBJECT(action_entry), "activate", 
                     GTK_SIGNAL_FUNC(ok_cb), tb);

  gtk_widget_grab_focus(title_entry);

  add_button(action_area, _("Ok"), TRUE, 0, ok_cb, tb);
  add_button(action_area, _("Info"), TRUE, 0, help_cb, NULL);
  add_button(action_area, _("Cancel"), TRUE, 0, cancel_cb, NULL);

  gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_MOUSE);
  gtk_widget_show(dialog);
}
Ejemplo n.º 6
0
Archivo: seabios.c Proyecto: CPFL/gxen
static void seabios_acpi_build_tables(void)
{
    uint32_t rsdp = (uint32_t)scratch_alloc(sizeof(struct acpi_20_rsdp), 0);
    struct acpi_config config = {
        .dsdt_anycpu = dsdt_anycpu_qemu_xen,
        .dsdt_anycpu_len = dsdt_anycpu_qemu_xen_len,
        .dsdt_15cpu = NULL,
        .dsdt_15cpu_len = 0,
    };

    acpi_build_tables(&config, rsdp);
    add_table(rsdp);
}

static void seabios_create_mp_tables(void)
{
    add_table(create_mp_tables(NULL));
}
Ejemplo n.º 7
0
void dump_reduction( a_reduce_action *rx, unsigned *base )
{
    a_pro *pro;
    short *p;

    pro = rx->pro;
    p = Members( rx->follow, setmembers );
    while( --p >= setmembers ) {
        add_table( *p, ACTION_REDUCE | pro->pidx );
        ++(*base);
    }
}
Ejemplo n.º 8
0
/*
 * Add a single one-to-many mapping.
 */
void
pdf_map_one_to_many(fz_context *ctx, pdf_cmap *cmap, int low, int *values, int len)
{
    int offset, i;

    if (len == 1)
    {
        add_range(ctx, cmap, low, low, PDF_CMAP_SINGLE, values[0]);
        return;
    }

    if (len > 8)
    {
        fz_warn(ctx, "one to many mapping is too large (%d); truncating", len);
        len = 8;
    }

    if (len == 2 &&
            values[0] >= 0xD800 && values[0] <= 0xDBFF &&
            values[1] >= 0xDC00 && values[1] <= 0xDFFF)
    {
        fz_warn(ctx, "ignoring surrogate pair mapping in cmap %s", cmap->cmap_name);
        return;
    }

    if (cmap->tlen + len + 1 >= USHRT_MAX + 1)
        fz_warn(ctx, "cannot map one to many; table is full");
    else
    {
        int fail;
        offset = cmap->tlen;
        fail = add_table(ctx, cmap, len);
        for (i = 0; i < len; i++)
            fail |= add_table(ctx, cmap, values[i]);
        if (!fail)
            add_range(ctx, cmap, low, low, PDF_CMAP_MULTI, offset);
        else
            cmap->tlen = offset; /* ignore one-to-many mappings when the table is full */
    }
}
Ejemplo n.º 9
0
/* Creates and returns a new chain associated with 'dp'.  Returns NULL if the
 * chain cannot be created. */
struct sw_chain *chain_create(struct datapath *dp)
{
	struct sw_chain *chain = kzalloc(sizeof *chain, GFP_KERNEL);
	if (chain == NULL)
		goto error;
	chain->dp = dp;
	chain->owner = try_module_get(hw_table_owner) ? hw_table_owner : NULL;
	if (chain->owner && create_hw_table_hook) {
		struct sw_table *hwtable = create_hw_table_hook();
		if (!hwtable || add_table(chain, hwtable))
			goto error;
	}

	if (add_table(chain, table_hash2_create(0x1EDC6F41, TABLE_HASH_MAX_FLOWS,
						0x741B8CD7, TABLE_HASH_MAX_FLOWS))
	    || add_table(chain, table_linear_create(TABLE_LINEAR_MAX_FLOWS)))
		goto error;
	return chain;

error:
	if (chain)
		chain_destroy(chain);
	return NULL;
}
Ejemplo n.º 10
0
static char *construct_query(void)
{
	json_t *root, *params, *po;
	char *res;

	root = json_object();
	json_object_set_new(root, "method", json_string("monitor"));
	json_object_set_new(root, "id", json_integer(0));

	params = json_array();
	json_array_append_new(params, json_string("Open_vSwitch"));
	json_array_append_new(params, json_null());
	po = json_object();
	add_table(po, "Open_vSwitch", "bridges", "ovs_version", NULL);
	add_table(po, "Bridge", "name", "ports", NULL);
	add_table(po, "Port", "interfaces", "name", "tag", "trunks", "bond_mode", NULL);
	add_table(po, "Interface", "name", "type", "options", "admin_state", "link_state", NULL);
	json_array_append_new(params, po);
	json_object_set_new(root, "params", params);

	res = json_dumps(root, 0);
	json_decref(root);
	return res;
}
Ejemplo n.º 11
0
/*
 * Add a range-to-table mapping.
 */
void
pdf_map_range_to_table(fz_context *ctx, pdf_cmap *cmap, int low, int *table, int len)
{
	int i;
	int high = low + len;
	int offset = cmap->tlen;
	if (cmap->tlen + len >= USHRT_MAX)
		fz_warn(ctx, "cannot map range to table; table is full");
	else
	{
		for (i = 0; i < len; i++)
			add_table(ctx, cmap, table[i]);
		add_range(ctx, cmap, low, high, PDF_CMAP_TABLE, offset);
	}
}
Ejemplo n.º 12
0
SymbolTable build( Program program )
{
    SymbolTable table;
    Declarations *decls = program.declarations;
    Declaration current;

    InitializeTable(&table);

    while(decls !=NULL){
        current = decls->first;
        add_table(&table, current.name, current.type);
        decls = decls->rest;
    }

    return table;
}
Ejemplo n.º 13
0
void ajouter_transition(
	Automate * automate, int origine, char lettre, int fin
){
	ajouter_etat( automate, origine );
	ajouter_etat( automate, fin );
	ajouter_lettre( automate, lettre );

	Cle cle;
	initialiser_cle( &cle, origine, lettre );
	Table_iterateur it = trouver_table( automate->transitions, (intptr_t) &cle );
	Ensemble * ens;
	if( iterateur_est_vide( it ) ){
		ens = creer_ensemble( NULL, NULL, NULL );
		add_table( automate->transitions, (intptr_t) &cle, (intptr_t) ens );
	}else{
		ens = (Ensemble*) get_valeur( it );
	}
	ajouter_element( ens, fin );
}
Ejemplo n.º 14
0
/*
 * Add a range-to-table mapping.
 */
void
pdf_map_range_to_table(fz_context *ctx, pdf_cmap *cmap, int low, int *table, int len)
{
    int i;
    int high = low + len;
    int offset = cmap->tlen;
    if (cmap->tlen + len >= USHRT_MAX + 1)
    {
        /* no space in the table; emit as a set of single lookups instead */
        for (i = 0; i < len; i++)
            add_range(ctx, cmap, low + i, low + i, PDF_CMAP_SINGLE, table[i]);
    }
    else
    {
        /* add table cannot fail here, we already checked that it will fit */
        for (i = 0; i < len; i++)
            add_table(ctx, cmap, table[i]);
        add_range(ctx, cmap, low, high, PDF_CMAP_TABLE, offset);
    }
}
Ejemplo n.º 15
0
 void process_block_impl(Block* block, ThreadData* data) const {
     BranchData* d = boost::polymorphic_downcast<BranchData*>(data);
     AlignmentStat stat;
     make_stat(stat, block);
     double block_weight = stat.noident_nogap() + stat.noident_gap();
     if (block_weight < opt_value("min-noident").as<int>()) {
         return;
     }
     if (opt_value("log").as<bool>()) {
         block_weight = log(block_weight);
     }
     boost::scoped_ptr<TreeNode> tree(print_tree_->make_tree(block));
     Leafs leafs;
     tree->all_leafs(leafs);
     std::sort(leafs.begin(), leafs.end(), GenomeNameCompare());
     BranchTable t;
     tree->branch_table(t, leafs, block_weight);
     add_table(d->table, t);
     BOOST_FOREACH (const BranchTable::value_type& branch_length,
                   t) {
         d->branch_blocks[branch_length.first].push_back(block);
     }
Ejemplo n.º 16
0
void restore_databases(struct configuration *conf, MYSQL *conn) {
	GError *error= NULL;
	GDir* dir= g_dir_open(directory, 0, &error);

	if (error) {
		g_critical("cannot open directory %s, %s\n", directory, error->message);
		errors++;
		return;
	}

	const gchar* filename= NULL;

	while((filename= g_dir_read_name(dir))) {
		if (!source_db || g_str_has_prefix(filename, g_strdup_printf("%s.", source_db))){
			if (g_strrstr(filename, "-schema.sql")) {
				add_schema(filename, conn);
			}
		}
	}

	g_dir_rewind(dir);

	while((filename= g_dir_read_name(dir))) {
		if (!source_db || g_str_has_prefix(filename, g_strdup_printf("%s.", source_db))){
			if (!g_strrstr(filename, "-schema.sql")
			 && !g_strrstr(filename, "-schema-view.sql")
			 && !g_strrstr(filename, "-schema-triggers.sql")
			 && !g_strrstr(filename, "-schema-post.sql")
			 && !g_strrstr(filename, "-schema-create.sql")
			 && g_strrstr(filename, ".sql")) {
				add_table(filename, conf);
			}
		}
	}

	g_dir_close(dir);
}
Ejemplo n.º 17
0
Archivo: seabios.c Proyecto: CPFL/gxen
static void seabios_create_smbios_tables(void)
{
    uint32_t ep = (uint32_t)scratch_alloc(sizeof(struct smbios_entry_point), 0);
    hvm_write_smbios_tables(ep, 0UL, 0UL);
    add_table(ep);
}
Ejemplo n.º 18
0
void
pdf_sort_cmap(fz_context *ctx, pdf_cmap *cmap)
{
	pdf_range *a;			/* last written range on output */
	pdf_range *b;			/* current range examined on input */

	if (cmap->rlen == 0)
		return;

	qsort(cmap->ranges, cmap->rlen, sizeof(pdf_range), cmprange);

	if (cmap->tlen == USHRT_MAX)
	{
		fz_warn(ctx, "cmap table is full; will not combine ranges");
		return;
	}

	a = cmap->ranges;
	b = cmap->ranges + 1;

	while (b < cmap->ranges + cmap->rlen)
	{
		/* ignore one-to-many mappings */
		if (pdf_range_flags(b) == PDF_CMAP_MULTI)
		{
			*(++a) = *b;
		}

		/* input contiguous */
		else if (pdf_range_high(a) + 1 == b->low)
		{
			/* output contiguous */
			if (pdf_range_high(a) - a->low + a->offset + 1 == b->offset)
			{
				/* SR -> R and SS -> R and RR -> R and RS -> R */
				if ((pdf_range_flags(a) == PDF_CMAP_SINGLE || pdf_range_flags(a) == PDF_CMAP_RANGE) && (pdf_range_high(b) - a->low <= 0x3fff))
				{
					pdf_range_set_flags(a, PDF_CMAP_RANGE);
					pdf_range_set_high(a, pdf_range_high(b));
				}

				/* LS -> L */
				else if (pdf_range_flags(a) == PDF_CMAP_TABLE && pdf_range_flags(b) == PDF_CMAP_SINGLE && (pdf_range_high(b) - a->low <= 0x3fff))
				{
					pdf_range_set_high(a, pdf_range_high(b));
					add_table(ctx, cmap, b->offset);
				}

				/* LR -> LR */
				else if (pdf_range_flags(a) == PDF_CMAP_TABLE && pdf_range_flags(b) == PDF_CMAP_RANGE)
				{
					*(++a) = *b;
				}

				/* XX -> XX */
				else
				{
					*(++a) = *b;
				}
			}

			/* output separated */
			else
			{
				/* SS -> L */
				if (pdf_range_flags(a) == PDF_CMAP_SINGLE && pdf_range_flags(b) == PDF_CMAP_SINGLE)
				{
					pdf_range_set_flags(a, PDF_CMAP_TABLE);
					pdf_range_set_high(a, pdf_range_high(b));
					add_table(ctx, cmap, a->offset);
					add_table(ctx, cmap, b->offset);
					a->offset = cmap->tlen - 2;
				}

				/* LS -> L */
				else if (pdf_range_flags(a) == PDF_CMAP_TABLE && pdf_range_flags(b) == PDF_CMAP_SINGLE && (pdf_range_high(b) - a->low <= 0x3fff))
				{
					pdf_range_set_high(a, pdf_range_high(b));
					add_table(ctx, cmap, b->offset);
				}

				/* XX -> XX */
				else
				{
					*(++a) = *b;
				}
			}
		}

		/* input separated: XX -> XX */
		else
		{
			*(++a) = *b;
		}

		b ++;
	}

	cmap->rlen = a - cmap->ranges + 1;
}
Ejemplo n.º 19
0
int execute(char *sql, cursor * c)
{
    int i, j, tab, ret;
    SQLPSTMT *st;
    ROW *dbrows;
    VALUE *dbval;
    int row, nrows;
    int *cols = NULL, ncols, col;
    int *selset;
    int dtype, stype;
    int width, decimals;
    char *tmpsql, name[500];
    SQLPVALUE *calctmp;		/* store for calculated values in UPDATE, if any */

    /* parse sql statement */
    /* I don't know why, but if the statement ends by string in quotes 'xxx' and is not 
     *  followed by space or '\n' it is not parsed properly -> */
    tmpsql = (char *)G_malloc(strlen(sql) + 2);
    sprintf(tmpsql, "%s ", sql);
    st = sqpInitStmt();
    st->stmt = tmpsql;
    sqpInitParser(st);

    if (yyparse() != 0) {
	G_free(tmpsql);
	append_error("SQL parser error: %s\n", st->errmsg);
	append_error("in statement:\n%s\n", sql);
	sqpFreeStmt(st);
	return DB_FAILED;
    }
    G_free(tmpsql);

    G_debug(3, "SQL statement parsed successfully: %s", sql);

    /* sqpPrintStmt(st); *//* debug output only */

    /* find table */
    tab = find_table(st->table);
    if (tab < 0 && st->command != SQLP_CREATE) {
	append_error("Table '%s' doesn't exist.\n", st->table);
	return DB_FAILED;
    }

    /* For DROP we have to call load_table_head() because it reads permissions */
    if ((st->command != SQLP_CREATE)) {
	ret = load_table_head(tab);
	if (ret == DB_FAILED) {
	    append_error("Cannot load table head.\n");
	    return DB_FAILED;
	}
    }

    if ((st->command == SQLP_DROP) || (st->command == SQLP_DELETE) ||
	(st->command == SQLP_INSERT) || (st->command == SQLP_UPDATE) ||
	(st->command == SQLP_ADD_COLUMN) || (st->command == SQLP_DROP_COLUMN)
	) {
	if (db.tables[tab].write == FALSE) {
	    append_error
		("Cannot modify table, don't have write permission for DBF file.\n");
	    return DB_FAILED;
	}
    }

    /* find columns */
    ncols = st->nCol;
    if (st->command == SQLP_INSERT || st->command == SQLP_SELECT
	|| st->command == SQLP_UPDATE || st->command == SQLP_DROP_COLUMN) {
	if (ncols > 0) {	/* colums were specified */
	    cols = (int *)G_malloc(ncols * sizeof(int));
	    for (i = 0; i < ncols; i++) {
		cols[i] = find_column(tab, st->Col[i].s);
		if (cols[i] == -1) {
		    append_error("Column '%s' not found\n", st->Col[i].s);
		    return DB_FAILED;
		}
	    }
	}
	else {			/* all columns */

	    ncols = db.tables[tab].ncols;
	    cols = (int *)G_malloc(ncols * sizeof(int));
	    for (i = 0; i < ncols; i++)
		cols[i] = i;
	}
    }

    /* check column types */
    if (st->command == SQLP_INSERT || st->command == SQLP_UPDATE) {
	for (i = 0; i < st->nVal; i++) {
	    col = cols[i];
	    if (st->Val[i].type != SQLP_NULL && st->Val[i].type != SQLP_EXPR) {
		dtype = db.tables[tab].cols[col].type;
		stype = st->Val[i].type;
		if ((dtype == DBF_INT && stype != SQLP_I)
		    || (dtype == DBF_DOUBLE && stype == SQLP_S)
		    || (dtype == DBF_CHAR && stype != SQLP_S)) {
		    append_error("Incompatible value type.\n");
		    return DB_FAILED;
		}
	    }
	}
    }

    /* do command */
    G_debug(3, "Doing SQL command <%d> on DBF table... (see include/sqlp.h)",
	    st->command);
    switch (st->command) {
    case (SQLP_ADD_COLUMN):
	load_table(tab);
	get_col_def(st, 0, &dtype, &width, &decimals);
	ret = add_column(tab, dtype, st->Col[0].s, width, decimals);
	if (ret == DB_FAILED) {
	    append_error("Cannot add column.\n");
	    return DB_FAILED;
	}
	/* Add column to each row */
	for (i = 0; i < db.tables[tab].nrows; i++) {
	    db.tables[tab].rows[i].values =
		(VALUE *) G_realloc(db.tables[tab].rows[i].values,
				    db.tables[tab].ncols * sizeof(VALUE));

	    dbval =
		&(db.tables[tab].rows[i].values[db.tables[tab].ncols - 1]);
	    dbval->i = 0;
	    dbval->d = 0.0;
	    dbval->c = NULL;
	    dbval->is_null = 1;
	}
	db.tables[tab].updated = TRUE;
	break;

    case (SQLP_DROP_COLUMN):
	load_table(tab);
	if (drop_column(tab, st->Col[0].s) != DB_OK) {
	    append_error("Cannot delete column.\n");
	    return DB_FAILED;
	}
	db.tables[tab].updated = TRUE;
	break;

    case (SQLP_CREATE):
	if (tab >= 0) {
	    append_error("Table %s already exists\n", st->table);
	    return DB_FAILED;
	}
	sprintf(name, "%s.dbf", st->table);
	add_table(st->table, name);

	tab = find_table(st->table);
	db.tables[tab].read = TRUE;
	db.tables[tab].write = TRUE;

	for (i = 0; i < ncols; i++) {
	    get_col_def(st, i, &dtype, &width, &decimals);
	    ret = add_column(tab, dtype, st->Col[i].s, width, decimals);
	    if (ret == DB_FAILED) {
		append_error("Cannot create table.\n");
		db.tables[tab].alive = FALSE;
		return DB_FAILED;
	    }
	}
	db.tables[tab].described = TRUE;
	db.tables[tab].loaded = TRUE;
	db.tables[tab].updated = TRUE;
	break;

    case (SQLP_DROP):
	unlink(db.tables[tab].file);
	db.tables[tab].alive = FALSE;
	break;

    case (SQLP_INSERT):
	load_table(tab);

	/* add row */
	if (db.tables[tab].nrows == db.tables[tab].arows) {
	    db.tables[tab].arows += 1000;
	    db.tables[tab].rows =
		(ROW *) G_realloc(db.tables[tab].rows,
				  db.tables[tab].arows * sizeof(ROW));
	}
	dbrows = db.tables[tab].rows;
	row = db.tables[tab].nrows;
	dbrows[row].values =
	    (VALUE *) G_calloc(db.tables[tab].ncols, sizeof(VALUE));
	dbrows[row].alive = TRUE;

	/* set to null */
	for (i = 0; i < db.tables[tab].ncols; i++) {
	    VALUE *dbval;

	    dbval = &(dbrows[row].values[i]);
	    dbval->is_null = 1;
	}

	/* set values */
	for (i = 0; i < st->nVal; i++) {
	    col = cols[i];
	    set_val(tab, row, col, &(st->Val[i]));
	}

	db.tables[tab].nrows++;
	db.tables[tab].updated = TRUE;
	break;

    case (SQLP_SELECT):
	G_debug(2, "SELECT");
	c->st = st;
	c->table = tab;
	c->cols = cols;
	c->ncols = ncols;
	c->nrows = sel(st, tab, &(c->set));
	if (c->nrows < 0) {
	    append_error("Error in selecting rows\n");
	    return DB_FAILED;
	}
	c->cur = -1;

	break;

    case (SQLP_UPDATE):
	nrows = sel(st, tab, &selset);
	if (nrows < 0) {
	    append_error("Error in selecting rows\n");
	    return DB_FAILED;
	}
	dbrows = db.tables[tab].rows;

	/* update rows */
	for (i = 0; i < nrows; i++) {
	    SQLPVALUE *temp_p;

	    calctmp = (SQLPVALUE *) G_malloc((st->nVal) * sizeof(SQLPVALUE));
	    row = selset[i];
	    for (j = 0; j < st->nVal; j++) {
		col = cols[j];
		eval_val(tab, row, col, &(st->Val[j]), &(calctmp[j]));
	    }
	    temp_p = st->Val;
	    st->Val = calctmp;
	    for (j = 0; j < st->nVal; j++) {
		col = cols[j];
		set_val(tab, row, col, &(st->Val[j]));
		db.tables[tab].updated = TRUE;
	    }
	    st->Val = temp_p;
	    G_free(calctmp);
	}
	break;

    case (SQLP_DELETE):
	nrows = sel(st, tab, &selset);
	if (nrows < 0) {
	    append_error("Error in selecting rows\n");
	    return DB_FAILED;
	}
	dbrows = db.tables[tab].rows;

	/* delete rows */
	for (i = 0; i < nrows; i++) {
	    row = selset[i];
	    dbrows[row].alive = FALSE;
	    db.tables[tab].updated = TRUE;
	}
	break;

    }
    if (st->command != SQLP_SELECT) {	/* because statement is released with cursor */
	sqpFreeStmt(st);
	if (cols)
	    G_free(cols);
    }

    return DB_OK;
}
Ejemplo n.º 20
0
/***********************************************************************
** CreateSQLTable()
**
** This function creates the SQL tables (and some day indexes and views)
** which don't already exist and will be used by the processes.
************************************************************************/
short CreateSQLTable(TableDescription *table_ptr)
{
   char command_line[SQL_MAX_COMMAND_LENGTH];
   char *StringPtr;
   NomadInfo *NPtr;
   TableInfo *TPtr;
   TableInfo *TempTPtr;
   ReturnStatus *RSPtr;
	RETCODE rc;
	HENV henv;
	HDBC hdbc;
	HSTMT hstmt;
   short table_num;


   NPtr=table_ptr->NomadInfoPtr;
   TPtr=table_ptr->TableInfoPtr;
   RSPtr=NULL;
	henv=table_ptr->henv;
	hdbc=table_ptr->hdbc;
	hstmt=table_ptr->hstmt;

   printf("NOMAD: creating SQL table '%s'\n",TPtr->TableName);

   /* First, make sure any old SQL tables are deleted */
   /* handle the case where NOPURGEUNTIL and SECURE */
   /* are set so that we can't drop the tables */
/*   sprintf(command_line,"ALTER TABLE %s SECURE 'OOOO' "
           "NOPURGEUNTIL 01 JAN 1980",TPtr->Tname);
   blank_pad(command_line,SQL_MAX_COMMAND_LENGTH);
   exec sql EXECUTE IMMEDIATE :command_line;
   if((sqlcode!=0)&&(sqlcode!=SQL_TABLE_NOT_FOUND)){
      //>>> handle error somehow
      sql_error();
      }
*/
   // now drop the tables (ignore errors since we don't care if table are there or not)
   sprintf(command_line,"DROP TABLE %s",TPtr->TableName);
	rc=SQLExecDirect(hstmt,command_line,SQL_NTS);

   sprintf(command_line,"DROP TABLE %sV",TPtr->TableName);
	rc=SQLExecDirect(hstmt,command_line,SQL_NTS);

   /* handle creation like an existing table */
   if(strlen(NPtr->like_name)!=0){
      sprintf(command_line,"CREATE TABLE %s LIKE %s",
              TPtr->TableName,NPtr->like_name);
		rc=SQLExecDirect(hstmt,command_line,SQL_NTS);
		if(!CHECKRC(SQL_SUCCESS,rc,"SQLExecDirect")){
         printf("%s return code=%d on %s\n",g_errstr,rc,command_line);
			LogAllErrors(henv,hdbc,hstmt);
			return(FAILURE);
			}
      }

   /* handle creation of a new table from scratch */
   else {

      StringPtr=BuildCreateTableString(TPtr);
      if(strlen(StringPtr)==0) return(FAILURE);
      strncpy(g_CommandLine,StringPtr,sizeof(g_CommandLine));
		rc=SQLExecDirect(hstmt,g_CommandLine,SQL_NTS);
		if(!CHECKRC(SQL_SUCCESS,rc,"SQLExecDirect")){
         printf("%s return code=%d\n",g_errstr,rc);
			LogAllErrors(henv,hdbc,hstmt);
			if(gDebug) assert(FALSE);
         FormatForSQLCI(StringPtr);
			return(FAILURE);
			}
      free(StringPtr);
   }

	// get info about table we just created
	if(TPtr->Organization==KEY_SEQ){
		TempTPtr=GetTableInfo(hdbc,TPtr->TableName,FALSE,&RSPtr);
		}
	else{
		TempTPtr=GetTableInfo(hdbc,TPtr->TableName,TRUE,&RSPtr);
		}

	FreeTableInfo(TPtr);
	TPtr=TempTPtr;
	table_ptr->TableInfoPtr=TempTPtr;

	RSPtr=FindRequiredColumns(table_ptr);
	if(RSPtr!=NULL){
		printf("ReturnType=%d  ReturnCode=%d\n%s\n%s\n",
				 RSPtr->ReturnType,RSPtr->ReturnCode,
				 RSPtr->Message1,RSPtr->Message2);
		return(FAILURE);
		}

	/* add the table name to the list (if it's already in... */
	/* ...the list then only its number is returned) */
	table_num=add_table(TPtr->TableName);
	if(table_num<0) {
		printf("%s Problem with table '%s'\n",g_errstr,TPtr->TableName);
		return(FAILURE);
	}

   return(SUCCESS);

   } /* end: CreateSQLTable() */
Ejemplo n.º 21
0
static int play_vorbis(lua_State *lstate) {
	char buf[BLOCKSIZE];
	char *pt, *oggbuf, **comm, *mark;
	int n, sock, sr_err, port;
	const char *host, *mount;
	VORBIS_FEED *feed;
	lua_pushstring(lstate, "host");
	lua_gettable(lstate, -2);
	lua_pushstring(lstate, "port");
	lua_gettable(lstate, -3);
	lua_pushstring(lstate, "mount");
	lua_gettable(lstate, -4);
	mount = lua_tostring(lstate, -1);
	port = lua_tointeger(lstate, -2);
	host = lua_tostring(lstate, -3);
	sock = stream_connect(host, port, mount, buf, &mark);
	lua_pop(lstate, 3);
	if (sock == 0) {
		lua_pop(lstate, 1);
		return 0;
		}
	lua_pushstring(lstate, "intern");
	lua_gettable(lstate, -2);
	feed = (VORBIS_FEED *)lua_touserdata(lstate, -1);
	lua_pop(lstate, 1);
	feed->base.sock = sock;
	pthread_mutex_init(&(feed->base.thread_lock), NULL);
	pthread_cond_init(&(feed->base.data_ready), NULL);
	ogg_sync_init(&(feed->oy));
	oggbuf = ogg_sync_buffer(&(feed->oy), BLOCKSIZE);
	n = BLOCKSIZE - (mark - buf);
	memcpy(oggbuf, mark, n);
	read_sock(feed->base.sock, oggbuf + n, BLOCKSIZE - n);
	ogg_sync_wrote(&(feed->oy), BLOCKSIZE);
	if ((n = ogg_sync_pageout(&(feed->oy), &(feed->og))) != 1) {
		logmsg("out of data: %d\n", n);
		free_vorbis((FEED *)feed);
		lua_pop(lstate, 1);
		return 0;
		}
	ogg_stream_init(&(feed->os), ogg_page_serialno(&(feed->og)));
	vorbis_info_init(&(feed->vi));
	vorbis_comment_init(&(feed->vc));
	if (ogg_stream_pagein(&(feed->os), &(feed->og)) < 1) {
		logmsg("error reading first ogg page\n");
		//free_feed(feed);
		//return 0;
		}
	if (ogg_stream_packetout(&(feed->os), &(feed->op)) != 1) {
		logmsg("error reading first header packet\n");
		free_vorbis((FEED *)feed);
		lua_pop(lstate, 1);
		return 0;
		}
	if (vorbis_synthesis_headerin(&(feed->vi),
			&(feed->vc), &(feed->op)) < 0) {
		logmsg("stream is not vorbis\n");
		free_vorbis((FEED *)feed);
		lua_pop(lstate, 1);
		return 0;
		}
	vorbis_headers(feed);
	add_table(lstate, "info");
	add_table(lstate, "comments");
	comm = feed->vc.user_comments;
	while (*comm) {
		if ((pt = index(*comm, '=')) != NULL) {
			*pt++ = '\0';
			set_string(lstate, *comm, pt);
			}
		++comm;
		}
	lua_pop(lstate, 1); // comments
	feed->base.channels = feed->vi.channels;
	set_integer(lstate, "channels", feed->base.channels);
	set_integer(lstate, "srate", feed->vi.rate);
	lua_pop(lstate, 1); // info
	feed->base.cbuf = new_ringbuf(feed->vi.rate, feed->base.channels,
			BUFSECS, 0.333, 0.667);
	if (jack_sr != feed->vi.rate) {
		feed->base.converter = src_new(SRC_SINC_MEDIUM_QUALITY,
				feed->base.channels, &sr_err);
		feed->base.src_data_in = (float *)malloc(SRC_DATA_FRAMES *
				feed->base.channels * sizeof(float));
		feed->base.src_data.data_in = feed->base.src_data_in;
		feed->base.src_data_remain = 0;
		feed->base.src_data.src_ratio = jack_sr
					/ (double)feed->vi.rate;
		feed->base.src_data_out = (float *)malloc(
				(int)ceil(SRC_DATA_FRAMES *
				feed->base.channels * sizeof(float) *
				feed->base.src_data.src_ratio));
		}
	feed->base.init = 1;
	lua_pop(lstate, 1);
	pthread_create(&(feed->base.thread_id), NULL, vorbis_thread, feed);
	return 0;
	}
Ejemplo n.º 22
0
// À chaque itération de l'algo, on prend une lettre du premier ou du second automate, jusqu'à ce qu'on arrive à la dernière lettre.
// Produit cartésien des états.
// Exemple : mot 1 : aaaa, mot 2 : bbbb
// Quelques résulats possibles : aabbaabb; aaaabbbb: bbbbaaaa; aaababbb: baababba
Automate * creer_automate_du_melange(
	const Automate* automate1,  const Automate* automate2
){
	int i, j, k, nbelau1, nbelau2, etat_act, et1, et2;
	int ** nouveaux_etats = NULL;
	Automate * melange = creer_automate();
	Ensemble_iterateur it1, it2;
	Table_iterateur it_transition;
	Table *cle1 = creer_table(
		( int(*)(const intptr_t, const intptr_t) ) comparer_int , 
		( intptr_t (*)( const intptr_t ) ) copier_int,
		( void(*)(intptr_t) ) supprimer_int
	);
	Table *cle2 = creer_table(
		( int(*)(const intptr_t, const intptr_t) ) comparer_int , 
		( intptr_t (*)( const intptr_t ) ) copier_int,
		( void(*)(intptr_t) ) supprimer_int
	);
	const Ensemble * finaux1 = get_finaux(automate1); const Ensemble * finaux2 = get_finaux(automate2);
	const Ensemble * initiaux1 = get_initiaux(automate1); const Ensemble * initiaux2 = get_initiaux(automate2);
	
	nbelau1 = taille_ensemble(automate1->etats);
	nbelau2 = taille_ensemble(automate2->etats);
	nouveaux_etats = malloc(nbelau1 * sizeof(int *));
	for(i=0; i<nbelau1; i++)
		nouveaux_etats[i]=malloc(nbelau2 * sizeof(int));
	k = 0;
	
	// Création des états, états initiaux, états finaux de l'automate.
	for (it1 = premier_iterateur_ensemble(automate1->etats), i=0; ! iterateur_ensemble_est_vide(it1); it1 = iterateur_suivant_ensemble(it1), i++){
		
		et1 = get_element(it1);
		add_table(cle1, et1, i);
		for (it2 = premier_iterateur_ensemble(automate2->etats), j=0; ! iterateur_ensemble_est_vide(it2); it2 = iterateur_suivant_ensemble(it2), j++){
			
			et2 = get_element(it2);
			ajouter_etat(melange, k);
			add_table(cle2, et2, j);
			if (est_dans_l_ensemble(finaux1, et1) && est_dans_l_ensemble(finaux2, et2))
				ajouter_etat_final(melange, k);
			if (est_dans_l_ensemble(initiaux1, et1) && est_dans_l_ensemble(initiaux2, et2))
				ajouter_etat_initial(melange, k);
			
			
			nouveaux_etats[i][j] = k;
			k++;
		}
	}
	
	// Les transitions sont ensuite crées
	// D'abord celles de l'ancien automate 1
	for (it_transition = premier_iterateur_table(automate1->transitions); !iterateur_est_vide(it_transition); it_transition = iterateur_suivant_table(it_transition)) {
		
		Cle * cle = (Cle*) get_cle(it_transition);
		Ensemble * fins = (Ensemble*) get_valeur(it_transition);

		for (it1 = premier_iterateur_ensemble(fins), i=0; ! iterateur_ensemble_est_vide(it1); it1 = iterateur_suivant_ensemble(it1), i++){
			
			etat_act = get_element(it1);
			for(i = 0; i < nbelau2; i++) {

				ajouter_transition(melange,
					nouveaux_etats[(int)get_valeur(trouver_table(cle1, cle->origine))][i],
					cle->lettre,
					nouveaux_etats[(int)get_valeur(trouver_table(cle1, etat_act))][i]);
			}
		}
	}
	
	// Puis celles de l'ancien automate 2
	for (it_transition = premier_iterateur_table(automate2->transitions); !iterateur_est_vide(it_transition); it_transition = iterateur_suivant_table(it_transition)) {
		
		Cle * cle = (Cle*) get_cle(it_transition);
		Ensemble * fins = (Ensemble*) get_valeur(it_transition);

		for (it1 = premier_iterateur_ensemble(fins), i=0; ! iterateur_ensemble_est_vide(it1); it1 = iterateur_suivant_ensemble(it1), i++){
			
			etat_act = get_element(it1);
			for(i = 0; i < nbelau1; i++) {

				ajouter_transition(melange,
					nouveaux_etats[i][(int)get_valeur(trouver_table(cle2, cle->origine))],
					cle->lettre,
					nouveaux_etats[i][(int)get_valeur(trouver_table(cle2, etat_act))]);
			}
		}
	}
	
	liberer_table(cle1);
	liberer_table(cle2);
	return melange;
}
Ejemplo n.º 23
0
void genobj( void )
{
    int i;
    int ntoken;
    int this_token;
    int any_token;
    int action;
    short *p;
    a_pro *pro;
    a_state *x;
    a_reduce_action *rx;
    a_reduce_action *default_reduction;
    a_shift_action *tx;
    a_sym *sym;
    an_item *item;
    unsigned max;
    unsigned sum;
    unsigned savings;
    unsigned base;
    unsigned rule_base;
    short *state_base;

    ntoken = 0;
    for( i = 0; i < nterm; ++i ) {
        this_token = symtab[i]->token;
        if( this_token > ntoken ) {
            ntoken = this_token;
        }
    }
    for( i = nterm; i < nsym; ++i ) {
        symtab[i]->token = ++ntoken;
    }
    any_token = ++ntoken;
    state_base = CALLOC( nstate, short );
    base = 0;
    max = 0;
    sum = 0;
    for( i = 0; i < nstate; ++i ){
        state_base[i] = base;
        x = statetab[i];
        for( tx = x->trans; sym = tx->sym; ++tx ) {
            add_table( sym->idx, ACTION_SHIFT | tx->state->sidx );
            ++base;
        }
        default_reduction = NULL;
        savings = 0;
        for( rx = x->redun; rx->pro != NULL; ++rx ){
            p = Members( rx->follow, setmembers );
            if( p != setmembers ) {
                if( p - setmembers > savings ) {
                    savings = p - setmembers;
                    if( default_reduction != NULL ) {
                        dump_reduction( default_reduction, &base );
                    }
                    default_reduction = rx;
                } else {
                    dump_reduction( rx, &base );
                }
            }
        }
        if( default_reduction != NULL ) {
            pro = default_reduction->pro;
            action = ACTION_REDUCE | pro->pidx;
        } else {
            action = ACTION_SHIFT | 0;
        }
        add_table( any_token, action );
        ++base;
        sum += base - state_base[i];
        if( base - state_base[i] > max ) {
            max = base - state_base[i];
        }
    }
    printf( "avg: %u max: %u\n", sum / nstate, max );
    dump_define( "YYANYTOKEN", any_token );
    dump_define( "YYEOFTOKEN", eofsym->token );
    dump_define( "YYSTART", startstate->sidx );
    begin_table( "YYACTTYPE", "yybasetab" );
    for( i = 0; i < nstate; ++i ) {
        puttab( FITS_A_WORD, state_base[i] );
    }
    end_table();
    begin_table( "YYCHKTYPE", "yychktab" );
    for( i = 0; i < used; ++i ) {
        puttab( FITS_A_BYTE, table[i].token );
    }
    end_table();
    begin_table( "YYACTTYPE", "yyacttab" );
    for( i = 0; i < used; ++i ) {
        puttab( FITS_A_WORD, table[i].action );
    }
    end_table();
    begin_table( "YYPLENTYPE", "yyplentab" );
    for( i = 0; i < npro; ++i ) {
        for( item = protab[i]->item; item->p.sym; ++item )
          /* do nothing */;
        puttab( FITS_A_BYTE, item - protab[i]->item );
    }
    end_table();
    begin_table( "YYPLHSTYPE", "yyplhstab" );
    for( i = 0; i < npro; ++i ) {
        puttab( FITS_A_BYTE, protab[i]->sym->token );
    }
    end_table();
    fprintf( actout, "#ifdef YYDEBUG\n" );
    rule_base = 0;
    begin_table( "unsigned short", "yyrulebase" );
    for( i = 0; i < npro; ++i ) {
        for( item = protab[i]->item; item->p.sym; ++item )
          /* do nothing */;
        puttab( FITS_A_WORD, rule_base );
        rule_base += item - protab[i]->item;
    }
    end_table();
    begin_table( "YYCHKTYPE", "yyrhstoks" );
    for( i = 0; i < npro; ++i ) {
        for( item = protab[i]->item; item->p.sym; ++item ) {
            puttab( FITS_A_BYTE, item->p.sym->token );
        }
    }
    end_table();
    begin_table( "char YYFAR *", "yytoknames" );
    fputc( '\n', actout );
    for( i = 0; i < nsym; ++i ) {
        fprintf( actout, "\"%s\",\n", symtab[ i ]->name );
    }
    fprintf( actout, "\"\"" );
    end_table();
    fprintf( actout, "#endif\n" );
}
Ejemplo n.º 24
0
Archivo: seabios.c Proyecto: CPFL/gxen
static void seabios_create_pir_tables(void)
{
    add_table(create_pir_tables());
}
Ejemplo n.º 25
0
/*
 * THE (s)printf() function.
 * It returns a pointer to it's internal buffer (or a string in the text
 * segment) thus, the string must be copied if it has to survive after
 * this function is called again, or if it's going to be modified (esp.
 * if it risks being free()ed).
 */
char *string_print_formatted (const char * format_str, int argc, svalue_t * argv)
{
    format_info finfo;
    svalue_t *carg;     /* current arg */
    unsigned int nelemno = 0;   /* next offset into array */
    unsigned int fpos;          /* position in format_str */
    int fs;                     /* field size */
    int pres;                   /* precision */
    pad_info_t pad;             /* fs pad string */
    unsigned int i;
    char *retvalue;
    int last;

    push_sprintf_state();
    STACK_INC;
    sp->type = T_ERROR_HANDLER;
    sp->u.error_handler = pop_sprintf_state;

    last = 0;
    for (fpos = 0; 1; fpos++) {
        char c = format_str[fpos];

        if (c == '\n' || !c) {
            int column_stat = 0;

            if (last != fpos) {
                add_nstr(format_str + last, fpos - last);
                last = fpos + 1;
            } else last++;

            if (!sprintf_state->csts) {
                if (!c)
                    break;
                ADD_CHAR('\n');
                continue;
            }
            ADD_CHAR('\n');
            while (sprintf_state->csts) {
                cst **temp;

                temp = &(sprintf_state->csts);
                while (*temp) {
                    if ((*temp)->info & INFO_COLS) {
                        if (*((*temp)->d.col - 1) != '\n')
                            while (*((*temp)->d.col) == ' ')
                                (*temp)->d.col++;
                        add_pad(0, (*temp)->start - get_curpos());
                        column_stat = add_column(temp, 0);
                        if (!column_stat)
                            temp = &((*temp)->next);
                    } else {
                        add_pad(0, (*temp)->start - get_curpos());
                        if (!add_table(temp))
                            temp = &((*temp)->next);
                    }
                }               /* of while (*temp) */
                if (sprintf_state->csts || c == '\n')
                    ADD_CHAR('\n');
            }                   /* of while (sprintf_state->csts) */
            if (column_stat == 2)
                ADD_CHAR('\n');
            if (!c)
                break;
        } else
            if (c == '%') {
                if (last != fpos) {
                    add_nstr(format_str + last, fpos - last);
                    last = fpos + 1;
                } else last++;
                if (format_str[fpos + 1] == '%') {
                    ADD_CHAR('%');
                    fpos++;
                    last++;
                    continue;
                }
                GET_NEXT_ARG;
                fs = 0;
                pres = 0;
                pad.len = 0;
                finfo = 0;
                for (fpos++; !(finfo & INFO_T); fpos++) {
                    if (!format_str[fpos]) {
                        finfo |= INFO_T_ERROR;
                        break;
                    }
                    if (((format_str[fpos] >= '0') && (format_str[fpos] <= '9'))
                            || (format_str[fpos] == '*')) {
                        if (pres == -1) {   /* then looking for pres */
                            if (format_str[fpos] == '*') {
                                if (carg->type != T_NUMBER)
                                    ERROR(ERR_INVALID_STAR);
                                pres = carg->u.number;
                                GET_NEXT_ARG;
                                continue;
                            }
                            pres = format_str[fpos] - '0';
                            for (fpos++;
                                    (format_str[fpos] >= '0') && (format_str[fpos] <= '9'); fpos++) {
                                pres = pres * 10 + format_str[fpos] - '0';
                            }
                            if (pres < 0) pres = 0;
                        } else {    /* then is fs (and maybe pres) */
                            if ((format_str[fpos] == '0') && (((format_str[fpos + 1] >= '1')
                                            && (format_str[fpos + 1] <= '9')) || (format_str[fpos + 1] == '*'))) {
                                pad.what = "0";
                                pad.len = 1;
                            } else {
                                if (format_str[fpos] == '*') {
                                    if (carg->type != T_NUMBER)
                                        ERROR(ERR_INVALID_STAR);
                                    fs = carg->u.number;
                                    if (fs < 0) fs = 0;
                                    if (pres == -2)
                                        pres = fs;  /* colon */
                                    GET_NEXT_ARG;
                                    continue;
                                }
                                fs = format_str[fpos] - '0';
                            }
                            for (fpos++;
                                    (format_str[fpos] >= '0') && (format_str[fpos] <= '9'); fpos++) {
                                fs = fs * 10 + format_str[fpos] - '0';
                            }
                            if (fs < 0) fs = 0;
                            if (pres == -2) {       /* colon */
                                pres = fs;
                            }
                        }
                        fpos--; /* about to get incremented */
                        continue;
                    }
                    switch (format_str[fpos]) {
                        case ' ':
                            finfo |= INFO_PP_SPACE;
                            break;
                        case '+':
                            finfo |= INFO_PP_PLUS;
                            break;
                        case '-':
                            finfo |= INFO_J_LEFT;
                            break;
                        case '|':
                            finfo |= INFO_J_CENTRE;
                            break;
                        case '@':
                            finfo |= INFO_ARRAY;
                            break;
                        case '=':
                            finfo |= INFO_COLS;
                            break;
                        case '#':
                            finfo |= INFO_TABLE;
                            break;
                        case '.':
                            pres = -1;
                            break;
                        case ':':
                            pres = -2;
                            break;
#ifdef DEBUG
                        case '%':
                            finfo |= INFO_T_NULL;
                            break;      /* never reached */
#endif
                        case 'O':
                            finfo |= INFO_T_LPC;
                            break;
                        case 's':
                            finfo |= INFO_T_STRING;
                            break;
                        case 'd':
                        case 'i':
                            finfo |= INFO_T_INT;
                            break;
                        case 'f':
                            finfo |= INFO_T_FLOAT;
                            break;
                        case 'c':
                            finfo |= INFO_T_CHAR;
                            break;
                        case 'o':
                            finfo |= INFO_T_OCT;
                            break;
                        case 'x':
                            finfo |= INFO_T_HEX;
                            break;
                        case 'X':
                            finfo |= INFO_T_C_HEX;
                            break;
                        case '\'':
                            fpos++;
                            pad.what = format_str + fpos;
                            while (1) {
                                if (!format_str[fpos])
                                    ERROR(ERR_UNEXPECTED_EOS);
                                if (format_str[fpos] == '\\') {
                                    if (!format_str[++fpos])
                                        ERROR(ERR_UNEXPECTED_EOS);
                                } else
                                    if (format_str[fpos] == '\'') {
                                        pad.len = format_str + fpos - pad.what;
                                        if (!pad.len)
                                            ERROR(ERR_NULL_PS);
                                        break;
                                    }
                                fpos++;
                            }
                            break;
                        default:
                            finfo |= INFO_T_ERROR;
                    }
                }                   /* end of for () */
                if (pres < 0)
                    ERROR(ERR_PRES_EXPECTED);
                /*
                 * now handle the different arg types...
                 */
                if (finfo & INFO_ARRAY) {
                    if (carg->type != T_ARRAY)
                        ERROR(ERR_ARRAY_EXPECTED);
                    if (carg->u.arr->size == 0) {
                        last = fpos;
                        fpos--;     /* 'bout to get incremented */
                        continue;
                    }
                    carg = (argv + sprintf_state->cur_arg)->u.arr->item;
                    nelemno = 1;    /* next element number */
                }
                while (1) {
                    if ((finfo & INFO_T) == INFO_T_LPC) {
                        outbuffer_t outbuf;

                        outbuf_zero(&outbuf);
                        svalue_to_string(carg, &outbuf, 0, 0, 0);
                        outbuf_fix(&outbuf);

                        sprintf_state->clean.type = T_STRING;
                        sprintf_state->clean.subtype = STRING_MALLOC;
                        sprintf_state->clean.u.string = outbuf.buffer;
                        carg = &(sprintf_state->clean);
                        finfo ^= INFO_T_LPC;
                        finfo |= INFO_T_STRING;
                    }
                    if ((finfo & INFO_T) == INFO_T_ERROR) {
                        ERROR(ERR_INVALID_FORMAT_STR);
#ifdef DEBUG
                    } else if ((finfo & INFO_T) == INFO_T_NULL) {
                        /* never reached... */
                        fprintf(stderr, "/%s: (s)printf: INFO_T_NULL.... found.\n",
                                current_object->obname);
                        ADD_CHAR('%');
#endif
                    } else if ((finfo & INFO_T) == INFO_T_STRING) {
                        int slen;
                        /*
                         * %s null handling added 930709 by Luke Mewburn
                         * <*****@*****.**>
                         */
                        if (carg->type == T_NUMBER && carg->u.number == 0) {
                            sprintf_state->clean.type = T_STRING;
                            sprintf_state->clean.subtype = STRING_MALLOC;
                            sprintf_state->clean.u.string = string_copy(NULL_MSG, "sprintf NULL");
                            carg = &(sprintf_state->clean);
                        } else
                            if (carg->type != T_STRING) {
                                ERROR(ERR_INCORRECT_ARG_S);
                            }
                        slen = SVALUE_STRLEN(carg);
                        if ((finfo & INFO_COLS) || (finfo & INFO_TABLE)) {
                            cst **temp;

                            if (!fs) {
                                ERROR(ERR_CST_REQUIRES_FS);
                            }

                            temp = &(sprintf_state->csts);
                            while (*temp)
                                temp = &((*temp)->next);
                            if (finfo & INFO_COLS) {
                                int tmp;
                                if (pres > fs) pres = fs;
                                *temp = ALLOCATE(cst, TAG_TEMPORARY, "string_print: 3");
                                (*temp)->next = 0;
                                (*temp)->d.col = carg->u.string;
                                (*temp)->pad = make_pad(&pad);
                                (*temp)->size = fs;
                                (*temp)->pres = (pres) ? pres : fs;
                                (*temp)->info = finfo;
                                (*temp)->start = get_curpos();
#ifdef TCC
                                puts("tcc has some bugs");
#endif
                                tmp = ((format_str[fpos] != '\n')
                                        && (format_str[fpos] != '\0'))
                                    || ((finfo & INFO_ARRAY)
                                            && (nelemno < (argv + sprintf_state->cur_arg)->u.arr->size));
                                tmp = add_column(temp, tmp);
                                if (tmp == 2 && !format_str[fpos]) {
                                    ADD_CHAR('\n');
                                }
                            } else {/* (finfo & INFO_TABLE) */
                                unsigned int n, len, max_len;
                                const char *p1, *p2;

#define TABLE carg->u.string
                                (*temp) = ALLOCATE(cst, TAG_TEMPORARY, "string_print: 4");
                                (*temp)->d.tab = 0;
                                (*temp)->pad = make_pad(&pad);
                                (*temp)->info = finfo;
                                (*temp)->start = get_curpos();
                                (*temp)->next = 0;
                                max_len = 0;
                                n = 1;

                                p2 = p1 = TABLE;
                                while (*p1) {
                                    if (*p1 == '\n') {
                                        if (p1 - p2 > max_len)
                                            max_len = p1 - p2;
                                        p1++;
                                        if (*(p2 = p1))
                                            n++;
                                    } else
                                        p1++;
                                }
                                if (!pres) {
                                    /* the null terminated word */
                                    if (p1 - p2 > max_len)
                                        max_len = p1 - p2;
                                    pres = fs / (max_len + 2); /* at least two
                                                                * separating spaces */
                                    if (!pres)
                                        pres = 1;

                                    /* This moves some entries from the right side
                                     * of the table to fill out the last line,
                                     * which makes the table look a bit nicer.
                                     * E.g.
                                     * (n=13,p=6)      (l=3,p=5)
                                     * X X X X X X     X X X X X
                                     * X X X X X X  -> X X X X X
                                     * X               X X X X
                                     *
                                     */
                                    len = (n-1)/pres + 1;
                                    if (n > pres && n % pres)
                                        pres -= (pres - n % pres) / len;
                                } else {
                                    len = (n-1)/pres + 1;
                                }
                                (*temp)->size = fs / pres;
                                (*temp)->remainder = fs % pres;
                                if (n < pres) {
                                    /* If we have fewer elements than columns,
                                     * pretend we are dealing with a smaller
                                     * table.
                                     */
                                    (*temp)->remainder += (pres - n)*((*temp)->size);
                                    pres = n;
                                }

                                (*temp)->d.tab = CALLOCATE(pres + 1, tab_data_t,
                                        TAG_TEMPORARY, "string_print: 5");
                                (*temp)->nocols = pres;     /* heavy sigh */
                                (*temp)->d.tab[0].start = TABLE;
                                if (pres == 1) {
                                    (*temp)->d.tab[1].start = TABLE + SVALUE_STRLEN(carg) + 1;
                                } else {
                                    i = 1;  /* the next column number */
                                    n = 0;  /* the current "word" number in this
                                             * column */

                                    p1 = TABLE;
                                    while (*p1) {
                                        if (*p1++ == '\n' && ++n >= len) {
                                            (*temp)->d.tab[i++].start = p1;
                                            n = 0;
                                        }
                                    }
                                    for ( ; i <= pres; i++)
                                        (*temp)->d.tab[i].start = ++p1;
                                }
                                for (i = 0; i < pres; i++)
                                    (*temp)->d.tab[i].cur = (*temp)->d.tab[i].start;

                                add_table(temp);
                            }
                        } else {    /* not column or table */
                            const char *tmp = carg->u.string; //work around tcc bug;
                            if (pres && pres < slen)
                                slen = pres;
                            add_justified(tmp, slen, &pad, fs, finfo,
                                    (((format_str[fpos] != '\n') && (format_str[fpos] != '\0'))
                                     || ((finfo & INFO_ARRAY) && (nelemno < (argv + sprintf_state->cur_arg)->u.arr->size)))
                                    || carg->u.string[slen - 1] != '\n');
                        }
                    } else if (finfo & INFO_T_INT) {        /* one of the integer
                                                             * types */
                        char cheat[20];
                        char temp[100];

                        *cheat = '%';
                        i = 1;
                        switch (finfo & INFO_PP) {
                            case INFO_PP_SPACE:
                                cheat[i++] = ' ';
                                break;
                            case INFO_PP_PLUS:
                                cheat[i++] = '+';
                                break;
                        }
                        if (pres) {
                            cheat[i++] = '.';
                            if(pres >= sizeof(temp))
                                sprintf(cheat + i, "%ld", sizeof(temp) - 1);
                            else
                                sprintf(cheat + i, "%d", pres);

                            i += strlen(cheat + i);
                        }
                        switch (finfo & INFO_T) {
                            case INFO_T_INT:
                                cheat[i++] = 'l';
                                cheat[i++] = 'd';
                                break;
                            case INFO_T_FLOAT:
                                cheat[i++] = 'f';
                                break;
                            case INFO_T_CHAR:
                                cheat[i++] = 'c';
                                break;
                            case INFO_T_OCT:
                                cheat[i++] = 'l';
                                cheat[i++] = 'o';
                                break;
                            case INFO_T_HEX:
                                cheat[i++] = 'l';
                                cheat[i++] = 'x';
                                break;
                            case INFO_T_C_HEX:
                                cheat[i++] = 'l';
                                cheat[i++] = 'X';
                                break;
                            default:
                                ERROR(ERR_BAD_INT_TYPE);
                        }
                        if ((cheat[i - 1] == 'f' && carg->type != T_REAL) || (cheat[i - 1] != 'f' && carg->type != T_NUMBER)) {
#ifdef RETURN_ERROR_MESSAGES
                            sprintf(buff,
                                    "ERROR: (s)printf(): Incorrect argument type to %%%c. (arg: %u)\n",
                                    cheat[i - 1], sprintf_state->cur_arg);
                            fprintf(stderr, "Program /%s File: %s: %s", current_prog->name,
                                    get_line_number_if_any(), buff);
                            debug_message("%s", buff);
                            if (current_object) {
                                debug_message("program: /%s, object: %s, file: %s\n",
                                        current_prog ? current_prog->name : "",
                                        current_object->name,
                                        get_line_number_if_any());
                            }
                            ERROR(ERR_RECOVERY_ONLY);
#else
                            error("ERROR: (s)printf(): Incorrect argument type to %%%c.\n",
                                    cheat[i - 1]);
#endif                          /* RETURN_ERROR_MESSAGES */
                        }
                        cheat[i] = '\0';

                        if (carg->type == T_REAL) {
                            sprintf(temp, cheat, carg->u.real);
                        } else
                            sprintf(temp, cheat, carg->u.number);
                        {
                            int tmpl = strlen(temp);

                            add_justified(temp, tmpl, &pad, fs, finfo,
                                    (((format_str[fpos] != '\n') && (format_str[fpos] != '\0'))
                                     || ((finfo & INFO_ARRAY) && (nelemno < (argv + sprintf_state->cur_arg)->u.arr->size))));
                        }
                    } else          /* type not found */
                        ERROR(ERR_UNDEFINED_TYPE);
                    if (sprintf_state->clean.type != T_NUMBER) {
                        free_svalue(&(sprintf_state->clean), "string_print_formatted");
                        sprintf_state->clean.type = T_NUMBER;
                    }

                    if (!(finfo & INFO_ARRAY))
                        break;
                    if (nelemno >= (argv + sprintf_state->cur_arg)->u.arr->size)
                        break;
                    carg = (argv + sprintf_state->cur_arg)->u.arr->item + nelemno++;
                }                   /* end of while (1) */
                last = fpos;
                fpos--;             /* bout to get incremented */
            }
    }                           /* end of for (fpos=0; 1; fpos++) */

    outbuf_fix(&sprintf_state->obuff);
    retvalue = sprintf_state->obuff.buffer;
    sprintf_state->obuff.buffer = 0;
    pop_stack();                /* pop off our error handler, will call pop_sprintf_state */
    return retvalue;
}                               /* end of string_print_formatted() */
Ejemplo n.º 26
0
int db__driver_open_database(dbHandle * handle)
{
    const char *name;
    int len;
    dbConnection connection;
    char buf[1024];
    DIR *dir;
    struct dirent *ent;
    char **tokens;
    int no_tokens, n;

    G_debug(2, "DBF: db__driver_open_database() name = '%s'",
	    db_get_handle_dbname(handle));

    db.name[0] = '\0';
    db.tables = NULL;
    db.atables = 0;
    db.ntables = 0;

    db_get_connection(&connection);
    name = db_get_handle_dbname(handle);

    /* if name is empty use connection.databaseName */
    if (strlen(name) == 0) {
	name = connection.databaseName;
    }

    strcpy(db.name, name);

    /* open database dir and read table ( *.dbf files ) names 
     * to structure */

    /* parse variables in db.name if present */
    if (db.name[0] == '$') {
	tokens = G_tokenize(db.name, "/");
	no_tokens = G_number_of_tokens(tokens);
	db.name[0] = '\0';	/* re-init */

	for (n = 0; n < no_tokens; n++) {
	    G_debug(3, "tokens[%d] = %s", n, tokens[n]);
	    if (tokens[n][0] == '$') {
		G_strchg(tokens[n], '$', ' ');
		G_chop(tokens[n]);
		strcat(db.name, G__getenv(tokens[n]));
		G_debug(3, "   -> %s", G__getenv(tokens[n]));
	    }
	    else
		strcat(db.name, tokens[n]);

	    strcat(db.name, "/");
	}
	G_free_tokens(tokens);
    }

    G_debug(2, "db.name = %s", db.name);

    errno = 0;
    dir = opendir(db.name);
    if (dir == NULL) {
	if (errno == ENOENT) {
	    int status;

	    status = G_mkdir(db.name);
	    if (status != 0) {	/* mkdir failed */
		append_error("Cannot create dbf database: %s\n", name);
		report_error();
		return DB_FAILED;
	    }
	}
	else {			/* some other problem */
	    append_error("Cannot open dbf database: %s\n", name);
	    report_error();
	    return DB_FAILED;
	}
    }

    while ((ent = readdir(dir))) {
	len = strlen(ent->d_name) - 4;
	if ((len > 0) && (G_strcasecmp(ent->d_name + len, ".dbf") == 0)) {
	    strcpy(buf, ent->d_name);
	    buf[len] = '\0';
	    add_table(buf, ent->d_name);
	}
    }

    closedir(dir);
    return DB_OK;
}