Example #1
0
/* Clears ckt and removes current circuit from database */
void
com_remcirc(wordlist *wl)
{
    struct variable *v, *next;
    struct line *dd;     /*in: the spice deck */
    struct circ *p, *prev = NULL;
#ifdef SHARED_MODULE
    TRANan *job;
#endif

    NG_IGNORE(wl);

    if (ft_curckt == NULL) {
        fprintf(cp_err, "Error: there is no circuit loaded.\n");
        return;
    }

#ifdef SHARED_MODULE
    /* This may happen only with shared ngspice during transient analysis,
       if simulation is stopped with 'bg_halt'
       and then circuit shall be removed prematurely. */
    job = (TRANan *) ft_curckt->ci_ckt->CKTcurJob;
    if (job && (job->JOBtype == 4) && (job->TRANplot))
        SPfrontEnd->OUTendPlot (job->TRANplot);
#endif

    /* delete numparam data structure dicoS */
    nupa_del_dicoS();

    dbfree(ft_curckt->ci_dbs);
    ft_curckt->ci_dbs = NULL;
    dbs = NULL;

    /* The next lines stem from com_rset */
    INPkillMods();

    if_cktfree(ft_curckt->ci_ckt, ft_curckt->ci_symtab);
    for (v = ft_curckt->ci_vars; v; v = next) {
        next = v->va_next;
        tfree(v->va_name);
        tfree(v);
    }
    ft_curckt->ci_vars = NULL;
    /* delete the deck, parameter list, and options list in ft_curckt */
    dd = ft_curckt->ci_deck;
    line_free(dd, TRUE);
    dd = ft_curckt->ci_param;
    line_free(dd, TRUE);
    dd = ft_curckt->ci_options;
    line_free(dd, TRUE);

    wl_free(ft_curckt->ci_commands);

    tfree(ft_curckt->FTEstats);

    ft_sim->deleteTask (ft_curckt->ci_ckt, ft_curckt->ci_defTask);

    if (ft_curckt->ci_name)
        tfree(ft_curckt->ci_name);
    if (ft_curckt->ci_filename)
        tfree(ft_curckt->ci_filename);

    /* delete the actual circuit entry from ft_circuits */
    for (p = ft_circuits; p; p = p->ci_next) {
        if (ft_curckt == p) {
            if (prev == NULL) {
                ft_circuits = p->ci_next;
                tfree(p);
                p = NULL;
                break;
            } else {
                prev->ci_next = p->ci_next;
                tfree(p);
                p = NULL;
                break;
            }
        }
        prev = p;
    }

    /* make first entry in ft_circuits the actual circuit (or NULL) */
    ft_curckt = ft_circuits;
    if (ft_curckt) {
        modtab = ft_curckt->ci_modtab;
        dbs = ft_curckt->ci_dbs;
    }
}
Example #2
0
int grtr_sc_create(Dbptr dbsc, char *net_expr, char *sta_expr, 
        char *chan_expr, double tstart, double tend, char *gap,
        int calib, int ir, Dbptr *trscgr)
{
	char time_str[100];
	char endtime_str[100];
	int ret, n, n2, i;
	double time, time2, endtime, endtime2;
	char sta[32], chan[32];
	char sta2[32], chan2[32];
	char string[1024];
	char string2[64];
	int new_view = 0;
	int is, crunch;
	Response *resp;
	Dbptr db;

	/* Subset input view */

	strcpy (string, "");
	if (sta_expr) {
		strcpy (string, "( ");
        	sprintf (string2, "sta =~ /%s/", sta_expr);
        	strcat (string, string2);
	}
	if (chan_expr) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "chan =~ /%s/", chan_expr);
        	strcat (string, string2);
	}
	if (string[0]) {
		strcat (string, " )");
		dbsc = dbsubset (dbsc, string, 0);
		new_view = 1;
	}
        dbquery (dbsc, dbRECORD_COUNT, &n);
        if (n < 1) {
		register_error (0, "grtr_sc_create: No data to process.\n");
		if (new_view) dbfree (dbsc);
		return (-1);
        }

	/* Read in data */

	if (tstart == 0.0 && tend == 0.0) {
		dbquery (dbsc, dbRECORD_COUNT, &n);
		for (dbsc.record = 0; dbsc.record < n; dbsc.record++) {
			if (dbgetv (dbsc, 0, "time", &time, "endtime", &endtime, 0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
        		if (tstart == 0.0 && tend == 0.0) {
        			tstart = time;
        			tend = endtime;
			} else {
				if (time < tstart) tstart = time;
				if (endtime > tend) tend = endtime;
			}
		}
	}
        sprintf (time_str, "(%.5f)", tstart);
        sprintf (endtime_str, "(%.5f)", tend);
	dbsc.record = dbALL;
        ret = trload_css (dbsc, time_str, endtime_str, trscgr, "wfdisc", 0);

	/* Split, splice, apply calib */

	if (gap == NULL) strcpy (string, "seg");
	else strcpy (string, gap);
	if (!strcmp(string, "leave")) {
	} else if (!strcmp(string, "seg")) {
		trsplit (*trscgr, 0, 0);
		trsplice (*trscgr, 0.5, 0, 0);
	} else if (!strcmp(string, "interp")) {
		register_error (0, "grtr_sc_create: gap value '%s' not implemented yet.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	} else if (!strcmp(string, "zero")) {
		register_error (0, "grtr_sc_create: gap value '%s' not implemented yet.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	} else if (!strcmp(string, "drop")) {
		trsplit (*trscgr, 0, 0);
		trsplice (*trscgr, 0.5, 0, 0);
		crunch = 0;
		dbquery (*trscgr, dbRECORD_COUNT, &n);
		strcpy (sta2, "");
		strcpy (chan2, "");
		n2 = 0;
		db = *trscgr;
		for (trscgr->record=0; trscgr->record<n; (trscgr->record)++) {
			if (dbgetv (*trscgr, 0, "sta", sta, "chan", chan,
					0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
			if (strcmp(sta, sta2) || strcmp(chan, chan2)) {
				if (n2 > 1) {
        				for (db.record = is; db.record < is+n2; db.record++) {
        					trfree (db);
        					crunch = 1;
        				}
				}
				n2 = 1;
				is = trscgr->record;
				strcpy (sta2, sta);
				strcpy (chan2, chan);
				continue;
        		}
        		n2++;
		}
		if (n2 > 1) {
       			for (db.record = is; db.record < is+n2; db.record++) {
       				trfree (db);
       				crunch = 1;
       			}
		}
		if (crunch) {
			dbcrunch (db);
		}
	} else {
		register_error (0, "grtr_sc_create: Illegal gap value '%s'.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	}
	if (calib) trapply_calib (*trscgr);

	/* Read in instrument responses. */

	if (ir )
	{
	/* Run this section if instrument response is to be loaded */
	    dbsc.record = 0;
	    if (dbgetv (dbsc, 0, "instrument.inid", &i, 0) != dbINVALID && i >= 0) {
		dbquery (*trscgr, dbRECORD_COUNT, &n);
		dbquery (dbsc, dbRECORD_COUNT, &n2);
		for (trscgr->record=0; trscgr->record<n; (trscgr->record)++) {
			if (dbgetv (*trscgr, 0, "sta", sta, "chan", chan,
					"time", &time, 0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
			for (dbsc.record=0; dbsc.record<n2; dbsc.record++) {
				if (dbgetv (dbsc, 0, "sta", sta2, "chan", chan2,
					"time", &time2, "endtime", &endtime2, 0) == dbINVALID) {
        				register_error (0, "grtr_sc_create: dbgetv() error.\n");
					if (new_view) dbfree (dbsc);
        				return (-1);
				}
				if (strcmp(sta, sta2)) continue;
				if (strcmp(chan, chan2)) continue;
				if (time < time2) continue;
				if (time >= endtime2) continue;
				dbextfile (dbsc, "instrument", string);
				resp = (Response *) getarr (resp_arr, string);
				dbputv (*trscgr, 0, "response", resp, 0);
				break;
			}
		}
	    }
	}
	clear_register (0);
	if (new_view) dbfree (dbsc);

	/* Normal exit. */

	return (0);
}
Example #3
0
int
main(int argc, char **argv)
{
	double          modified_after =now() , last_lddate, last_mtime, mtime;
	char           *orbname = NULL;
	char           *dbname = NULL;
	int             orb;
	int             naptime = -1, check_lddate_interval = -1;
	Dbptr           db, dbt, dbs;
	char           *prefix = NULL;
	struct stat     filestat;
	int             i;
	Tbl            *tablenames, *tables_containing_dfile, *check_tables = NULL,
	               *ignore_tables = NULL;
	long            table_present, recc, is_view;
	char           *tablename, *schemaname;
	char           *filename;
	int             counter = 0, force_check = 0;
	char            expr[512];
	char           *statefilename = NULL, *pfname = "dbnew2orb";
	Pf             *pf = NULL;
	void           *priv_dfile = (void *) NULL;
	void           *private = (void *) NULL;
	int             pmsi;	/* poor man's string index, replacment for
				 * searchtbl... */
	char           *pmsp;
	double          lastburytime;
	Relic           relic;
	char           *s;
	Expression     *expr_lddate;
	double         *mtimes;
	double         *lddates;

	elog_init(argc, argv);

	if (argc < 2) {
		usage();
		exit(1);
	}
	for (argc--, argv++; argc > 0; argc--, argv++) {
		if (!strcmp(*argv, "-modified_after")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -modified_after argument.\n");
				usage();
				exit(1);
			}
			modified_after = str2epoch(*argv);
		} else if (!strcmp(*argv, "-prefix")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -prefix argument.\n");
				usage();
				exit(1);
			}
			prefix = *argv;
		} else if (!strcmp(*argv, "-pf")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -pf argument.\n");
				usage();
				exit(1);
			}
			pfname = *argv;
		} else if (!strcmp(*argv, "-state")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -state argument.\n");
				usage();
				exit(1);
			}
			statefilename = *argv;
		} else if (!strcmp(*argv, "-sleep")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -sleep argument.\n");
				usage();
				exit(1);
			}
			naptime = atoi(*argv);
		} else if (!strcmp(*argv, "-check_lddate_interval")) {
			argc--;
			argv++;
			if (argc < 1) {
				complain(0, "Need -check_lddate_interval argument.\n");
				usage();
				exit(1);
			}
			check_lddate_interval = atoi(*argv);
		} else if (!strcmp(*argv, "-v")) {
			verbose++;
		} else if (**argv != '-') {
			break;
		} else {
			complain(0, "Unrecognized argument '%s'.\n", *argv);
			usage();
			exit(1);
		}
	}


	if (pfread(pfname, &pf)) {
		elog_die(0, "parse_pf: pfread('%s') error.\n", pfname);
	}
	if (check_lddate_interval < 1) {
		if (parse_param(pf, "check_lddate_interval", P_LINT, 1, &check_lddate_interval) < 0) {
			elog_die(1, "parse_pf: sleep check_lddate_interval needed!\n");
		} else {
			if (check_lddate_interval < 0) {
				check_lddate_interval = 1;
			}
		}
	}
	if (naptime < 1) {
		if (parse_param(pf, "sleep", P_LINT, 1, &naptime) < 0) {
			elog_die(1, "parse_pf: sleep value needed!\n");
		} else {
			if (naptime < 0) {
				naptime = 1;
			}
		}
	}
	if (!prefix) {
		if (parse_param(pf, "prefix", P_STR, 0, &prefix) < 0) {
			printf("NO PREFIX!\n");
			prefix = NULL;
		}
	}
	parse_param(pf, "check_tables", P_TBL, 0, &check_tables);
	if (check_tables) {
		if (maxtbl(check_tables) < 1) {
			freetbl(check_tables, 0);
			check_tables = NULL;
		}
	}
	parse_param(pf, "ignore_tables", P_TBL, 0, &ignore_tables);
	if (ignore_tables) {
		if (maxtbl(ignore_tables) < 1) {
			freetbl(ignore_tables, 0);
			ignore_tables = NULL;
		}
	}
	/*
	 * no good here, would erase the table above pffree(pf);
	 */

	if (argc < 1) {
		complain(0, "Need db argument.\n");
		usage();
		exit(1);
	}
	dbname = *argv;

	argc--;
	argv++;
	if (argc < 1) {
		complain(0, "Need orb argument.\n");
		usage();
		exit(1);
	}
	orbname = *argv;
	argc--;
	argv++;
	if (argc > 0) {
		complain(0, "Unrecognized argument '%s'.\n", *argv);
		usage();
		exit(1);
	}
	if (dbopen(dbname, "r", &db) < 0) {
		elog_complain(0, "Can't open database");
		exit(1);
	}
	dbquery(db, dbSCHEMA_NAME, &schemaname);
	orb = orbopen(orbname, "w&");
	if (orb < 0) {
		elog_die(0, "orbopen(%s) error\n", orbname);
	}
	/*
	 * prepare for later call to dbquery(dbFIELD_TABLES) to find only
	 * tables containing lddate
	 */

	/*
	 * dbtables is much better, does not require the existence of table
	 * origin dbf = dblookup(db, 0, "origin", "lddate", "dbNULL");
	 * dbquery(dbf, dbFIELD_TABLES, &tablenames);
	 */

	dbex_compile(db, "max(lddate)", &expr_lddate, dbTIME);
	tablenames = dbtables(db, "lddate");
	tables_containing_dfile = dbtables(db, "dfile");

	/* waste a few bytes... */
	ntables = maxtbl(tablenames);
	mtimes = malloc(ntables * sizeof(double));
	lddates = malloc(ntables * sizeof(double));
	bury_times = malloc(ntables * sizeof(double));
	static_flags = malloc(ntables * sizeof(long));
	if (statefilename) {
		if (exhume(statefilename, &Stop, 10, mortician)) {
			elog_notify(0, "read old state file\n");
		} else {
			elog_complain(0, "could not read old statefile\n");
		}
	}
	for (i = 0; i < ntables; i++) {
		/*
		 * mtimes[i] = modified_after; lddates[i] = modified_after;
		 */
		static_flags[i] = NEW_TABLE;
	}
	for (;;) {
		tablenames = dbtables(db, "lddate");

		for (i = 0; i < ntables; i++) {
			tablename = gettbl(tablenames, i);
			if (!tablename) {
				continue;
			}
			dbt = dblookup(db, 0, tablename, 0, 0);
			dbquery(dbt, dbTABLE_PRESENT, &table_present);
			if (!table_present) {
				continue;
			}
			dbquery(dbt, dbTABLE_IS_VIEW, &is_view);
			if (is_view) {
				continue;
			}
			/* lastid is not a good idea (my personal choice)... */
			if (strcmp(tablename, "lastid") == 0) {
				continue;
			}
			/* remove after Dan fixed the bug with remark */
			if (strcmp(tablename, "remark") == 0) {
				continue;
			}
			if (findtbl(tablename, tables_containing_dfile)) {
				continue;
			}
			if (check_tables) {
				if (!findtbl(tablename,check_tables)) {
					if (verbose > 1 && static_flags[i]==NEW_TABLE) elog_notify(0,"ignoring table %s because it's NOT in 'check_tables'\n",tablename);
					continue;
				}
			}
			if (ignore_tables) {
				if (findtbl(tablename,ignore_tables)) {
					if (verbose > 1 && static_flags[i]==NEW_TABLE) elog_notify(0,"ignoring table %s because it's in 'ignore_tables'\n",tablename);
					continue;
				}
			}
			dbquery(dbt, dbRECORD_COUNT, &recc);
			if (recc < 1) {
				continue;
			}
			if (statefilename) {
			if (static_flags[i] == NEW_TABLE) {
				relic.dp = &bury_times[i];
				if (resurrect(tablename, relic, TIME_RELIC) == 0) {
					mtimes[i] = bury_times[i];
					lddates[i] = bury_times[i];
					if (verbose > 1) {
						elog_notify(0, "resurrection successful: check %s after %s\n", tablename, s = strtime(bury_times[i]));
						free(s);
					}
				} else {
					bury_times[i] = modified_after;
					mtimes[i] = modified_after;
					lddates[i] = modified_after;
					if (verbose > 1) {
						elog_notify(0, "resurrection unsuccessful: check %s after %s\n", tablename, s = strtime(modified_after));
						free(s);
					}
				}
				static_flags[i] = TABLE_SEEN;
			}
			} else {
				if (static_flags[i] == NEW_TABLE) {
					bury_times[i] = modified_after;
					mtimes[i] = modified_after;
					lddates[i] = modified_after;
					static_flags[i] = TABLE_SEEN;
				}
			}
			dbquery(dbt, dbTABLE_FILENAME, &filename);
			if (stat(filename, &filestat) < 0) {
				elog_die(1, "stat(%s) error.\n", filename);
			}
			last_mtime = mtimes[i];
			last_lddate = lddates[i];

			mtime = filestat.st_mtime;
			/*
			 * the whole mtime stuff is not soo good: mtime is
			 * typically > lddate, so setting modified_after to
			 * mtime will certainly ignore the last value. To get
			 * everything, I will have to keep 2 arrays: mtimes
			 * to detect file modifications and lddates to get
			 * the actual entries...
			 */
			if (force_check || mtime > last_mtime) {
				sprintf(expr, "lddate > %f", last_lddate);
				dbs = dbsubset(dbt, expr, 0);
				dbquery(dbs, dbRECORD_COUNT, &recc);
				if (recc > 0) {
					if (dbrows2orb(dbs, orb, prefix) == 0) {
						/*
						 * dbex_evalstr(dbs,
						 * "max(lddate)", dbTIME,
						 * &lddates[i]);
						 */
						dbex_eval(dbs, expr_lddate, 0, &lddates[i]);
						mtimes[i] = mtime;
						bury_times[i] = lddates[i];
					}
				}
				dbfree(dbs);
			}
			/*
			 * a call to dbfree(dbt) would remove it from the
			 * list of tablenames, all later calls to tablename
			 * would return NIL...
			 */
			if (Stop) {
				bury();
				return (0);
			}
		}
		sleep(naptime);
		if ((counter + 1) >= check_lddate_interval) {
			counter = 0;
			force_check = 1;
		} else {
			force_check = 0;
			counter++;
		}
		if (statefilename) {
			double          nowtime;

			nowtime = now();
			if (nowtime - lastburytime > 600.0) {
				lastburytime = nowtime;
				bury();
			}
		}
	}
}
Example #4
0
ramo *consultar_asignatura(char* asignatura) {
    ramo *r = NULL;
    char sql[512];
    int num = 0;
    PGconn *conexion = NULL;
    PGresult *resultado = NULL;

    if (strlen(asignatura) > 0) {
        r = (ramo *) malloc(sizeof (ramo));
        r->asignatura = (char *) calloc(strlen(asignatura) + 1, sizeof (asignatura));
        r->aprobacion = 0.0;
        r->reprobacion = 0.0;
        r->promedio = 0.0;
        r->stddev = 0.0;
        sprintf(r->asignatura, "%s", asignatura);

        // Busco Reprobados
        memset(sql, 0, sizeof (sql));
        sprintf(sql, "SELECT AVG(nota) FROM asignaturas_cursadas WHERE curso_id IN (SELECT curso_id FROM cursos WHERE UPPER(asignatura) = UPPER('%s')) AND nota < 4", asignatura);
        conexion = dbconnect(SERVIDOR, PUERTO, NOMBREDB, USUARIODB, PASSDB);
        if (conexion != NULL) {
            resultado = dbquery(conexion, sql);
            num = dbnumrows(resultado);
            if (num > 0) {
                r->reprobacion = getDouble(dbresult(resultado, 0, 0));
                dbfree(resultado);
            }
            dbclose(conexion);
        }

        // Busco Aprobados
        memset(sql, 0, sizeof (sql));
        sprintf(sql, "SELECT AVG(nota) FROM asignaturas_cursadas WHERE curso_id IN (SELECT curso_id FROM cursos WHERE UPPER(asignatura) = UPPER('%s')) AND nota >= 4", asignatura);
        conexion = dbconnect(SERVIDOR, PUERTO, NOMBREDB, USUARIODB, PASSDB);
        if (conexion != NULL) {
            resultado = dbquery(conexion, sql);
            num = dbnumrows(resultado);
            if (num > 0) {
                r->aprobacion = getDouble(dbresult(resultado, 0, 0));
                dbfree(resultado);
            }
            dbclose(conexion);
        }

        // Busco Promedio
        memset(sql, 0, sizeof (sql));
        sprintf(sql, "SELECT AVG(nota), STDDEV(nota) FROM asignaturas_cursadas WHERE curso_id IN (SELECT curso_id FROM cursos WHERE UPPER(asignatura) = UPPER('%s'))", asignatura);
        conexion = dbconnect(SERVIDOR, PUERTO, NOMBREDB, USUARIODB, PASSDB);
        if (conexion != NULL) {
            resultado = dbquery(conexion, sql);
            num = dbnumrows(resultado);
            if (num > 0) {
                r->promedio = getDouble(dbresult(resultado, 0, 0));
                r->stddev = getDouble(dbresult(resultado, 0, 1));
                dbfree(resultado);
            }
            dbclose(conexion);
        }
    }

    return r;
}
Example #5
0
alumno *consultar_estudiante(long estudiante_id) {
    alumno *a = NULL;
    char sql[512];
    int num = 0;
    PGconn *conexion = NULL;
    PGresult *resultado = NULL;

    if (estudiante_id > 0) {
        a = (alumno *) malloc(sizeof (alumno));
        a->estudiante_id = estudiante_id;
        a->aprobacion = 0.0;
        a->mediana = 0.0;
        a->promedio = 0.0;
        a->reprobacion = 0.0;
        a->stddev = 0.0;

        // Busco Reprobados
        memset(sql, 0, sizeof (sql));
        sprintf(sql, "SELECT AVG(nota) FROM asignaturas_cursadas WHERE estudiante_id='%ld' AND nota < 4", estudiante_id);
        conexion = dbconnect(SERVIDOR, PUERTO, NOMBREDB, USUARIODB, PASSDB);
        if (conexion != NULL) {
            resultado = dbquery(conexion, sql);
            num = dbnumrows(resultado);
            if (num > 0) {
                a->reprobacion = getDouble(dbresult(resultado, 0, 0));
                dbfree(resultado);
            }
            dbclose(conexion);
        }

        // Busco Aprobados
        memset(sql, 0, sizeof (sql));
        sprintf(sql, "SELECT AVG(nota) FROM asignaturas_cursadas WHERE estudiante_id='%ld' AND nota >= 4", estudiante_id);
        conexion = dbconnect(SERVIDOR, PUERTO, NOMBREDB, USUARIODB, PASSDB);
        if (conexion != NULL) {
            resultado = dbquery(conexion, sql);
            num = dbnumrows(resultado);
            if (num > 0) {
                a->aprobacion = getDouble(dbresult(resultado, 0, 0));
                dbfree(resultado);
            }
            dbclose(conexion);
        }

        // Busco Promedio
        memset(sql, 0, sizeof (sql));
        sprintf(sql, "SELECT AVG(nota), median(nota), STDDEV(nota) FROM asignaturas_cursadas WHERE estudiante_id='%ld'", estudiante_id);
        conexion = dbconnect(SERVIDOR, PUERTO, NOMBREDB, USUARIODB, PASSDB);
        if (conexion != NULL) {
            resultado = dbquery(conexion, sql);
            num = dbnumrows(resultado);
            if (num > 0) {
                a->promedio = getDouble(dbresult(resultado, 0, 0));
                a->mediana = getDouble(dbresult(resultado, 0, 1));
                a->stddev = getDouble(dbresult(resultado, 0, 2));
                dbfree(resultado);
            }
            dbclose(conexion);
        }
    }

    return a;
}
Dbptr inWhichPolygons(Dbptr db,Point P) {
	Point *poly;
	long i;
	long nrec;
	Dbptr dbr= dblookup(db,0,"polygon",0,0);
	double lat,lon;
	Dbptr dbs;
	long npoints;
	char expr[STRSZ];
	char temp[STRSZ];
	long pid;
	int first;
	int found=0;
	char name[STRSZ];

	lat= P.lat;
	lon= P.lon;
	
	dbs=dblookup(db,0,"polygon",0,0);
/*
   Nice idea, but breaks too many programs (older versions of the polygon-schema)
   sprintf(expr,"closed=~/y/ && north >= %f && south <= %f && east >= %f && west <= %f",
   */
	sprintf(expr,"north >= %f && south <= %f && east >= %f && west <= %f",
			lat,lat,lon,lon);
	dbs=dbsubset(dbs,expr,0);
	dbquery(dbs, dbRECORD_COUNT,&nrec);
	if (nrec < 1) {
		/*
		elog_log(0,"inWhichPolygons: initial check of Bounding Box returns 0!");
		*/
		dbr=dbinvalid();
		return dbr;
	}
	first=1;
	for (i= 0; i< nrec; i++) {
		dbs.record=i;
		dbgetv(dbs,0,"pname",&name,NULL );

		if ((npoints=readPolygon(dbs,&poly))>0) {
			if (isGeographicallyInside(P,poly,npoints)) {
				found=1;
				dbgetv(dbs,0,"pid",&pid,NULL );
				if (first) {
					sprintf(expr,"pid==%ld",pid);
					first=0;
				} else {
					sprintf(temp,"|| pid==%ld",pid);
					strcat(expr,temp);
				}
			}
			free(poly);
		}
	}
	
	/*dbr=dblist2subset(dbs,list);*/
	if (found) {
		dbr=dbsubset(dbs,expr,0);
	} else {
		dbr=dbinvalid();
	}
	dbfree(dbs);
	return dbr;
}
Example #7
0
int main(int argc, char **argv)
 { Pf 		*pf;
   char		*orbname,
		*dbname,
		*expr,
		*table,
		*rowtemp,
                verbose;
   int  	orb,
		totalrecords,
		records,
 		record;
   Dbptr  	db,
		dbinput,
		dbscratch;

  elog_init(argc,argv);		

  /* initialize variables */

  verbose = 0;
  expr = NULL;
  loop = 0;
  record = 0;
  totalrecords = 0;

  rowtemp = malloc(ROW_MAX_LENGTH);
  
  if (rowtemp == NULL) die(1,"malloc() error.\n");

  /* read in command line options */

  { int c;
    unsigned char errflg = 0;

    while (( c = getopt( argc, argv, "vl:s:")) != -1)
        switch (c) {
          case 'l': loop = atoi(optarg);
                    sigset(SIGINT,done);
                    break;
          case 's': expr = optarg;
                    break;
          case 'v': verbose = 1;
                    break;
          case '?': errflg++;
        }

    if ( (argc - optind) != 3 ) errflg++;

    if (errflg) 
       { elog_die(0,"usage: %s [-v] [-s subset] [-l delay] db table orb\n",argv[0]); 
       }
    
    dbname = argv[optind++];
    table  = argv[optind++];
    orbname= argv[optind++];
  }
    
  /* start our work */

  if ( dbopen ( dbname,  "r+",  &dbinput ) == dbINVALID )
     { elog_die(1,"Couldn't open input database, \"%s\".\n",dbname); }

  dbinput   = dblookup( dbinput, 0, table, 0, 0);
  dbscratch = dblookup( dbinput, 0, 0, 0, "dbSCRATCH");

  if ( dbinput.table == dbINVALID )
   { elog_die(1,"Couldn't lookup the table \"%s\" in the database \"%s\".\n",
		table,dbname); }
  if ( dbscratch.record == dbINVALID )
   { elog_die(1,"Couldn't lookup the scratch record in the database \"%s\".\n",
		dbname); }
  
  if ( dbquery( dbinput, dbRECORD_COUNT, &records) < 0 )
   { elog_die(1,"dbquery dbRECORD_COUNT failed.\n"); }

  orb      = orbopen( orbname, "w&" );

  if ( orb == -1 )
   { elog_die(1,"Couldn't open the orb, \"%s\".\n",orbname); }

  if (loop == 0) loop = -1;

  while (loop)
   { db = dbinput;
     
     if ( expr != NULL) db = dbsubset( db, expr, 0 );
     
     db.record = record;

     if ( dbquery( db, dbRECORD_COUNT, &records) < 0 )
   	 elog_die(1,"dbquery dbRECORD_COUNT failed.\n");  
     
     for (;db.record<records;db.record++)
       { if (verbose) printf("writing record %d to orb...\n",db.record); 

         /* copy the row from what could be a view into the scratch record of the
            input database, so as to avoid putting a view on the ORB */
         if ( dbget( db,        rowtemp) == dbINVALID ) die(1,"dbget error.\n");
         if ( dbput( dbscratch, rowtemp) == dbINVALID ) die(1,"dbput error.\n");

         if ( db2orbpkt( dbscratch, orb ) < 0 )
            { complain ( 0, "Couldn't write record #%d to %s.\n",
              	   db.record, orbname); } 
         totalrecords++;
       }

     record = db.record; 

     /* if a subset expression was supplied, then we're working with
        a view, which should be freed. */

     if ( expr != NULL) dbfree(db);
     if ( loop == -1 ) loop = 0;
     sleep(loop);
   } 

  printf("posted %d records from database %s to orb %s.\n",totalrecords,dbname,orbname);
  dbclose(dbinput);
  orbclose(orb); 
  free(rowtemp);
 }