Example #1
0
void do_for (void)
/***** do_for
	do a for command in a UDF.
	for i=value to value step value; .... ; end
*****/
{	int h,signum;
	char name[16],*jump;
	header *hd,*init,*end,*step;
	double vend,vstep;
	struct { header hd; double value; } rv;
	if (!udfon)
	{	output("For only allowed in functions!\n"); error=57; return;
	}
	rv.hd.type=s_real; *rv.hd.name=0;
	rv.hd.size=sizeof(header)+sizeof(double); rv.value=0.0;
	scan_space(); scan_name(name); if (error) return;
	kill_local(name);
	newram=endlocal;
	hd=new_reference(&rv.hd,name); if (error) return;
	endlocal=newram=(char *)hd+hd->size;
	scan_space(); if (*next!='=')
	{	output("Syntax error in for.\n"); error=71; goto end;
	}
	next++; init=scan(); if (error) goto end;
	init=getvalue(init); if (error) goto end;
	if (init->type!=s_real)
	{	output("Startvalue must be real!\n"); error=72; goto end;
	}
	rv.value=*realof(init);
	scan_space(); if (strncmp(next,"to",2))
	{	output("Endvalue missing in for!\n"); error=73; goto end;
	}
	next+=2;
	end=scan(); if (error) goto end;
	end=getvalue(end); if (error) goto end;
	if (end->type!=s_real)
	{	output("Endvalue must be real!\n"); error=73; goto end;
	}
	vend=*realof(end);
	scan_space();
	if (!strncmp(next,"step",4))
	{	next+=4;
		step=scan(); if (error) goto end;
		step=getvalue(step); if (error) goto end;
		if (step->type!=s_real)
		{	output("Stepvalue must be real!\n"); error=73; goto end;
		}
		vstep=*realof(step);
	}
	else vstep=1.0;
	signum=(vstep>=0)?1:-1;
	vend=vend+signum*epsilon;
	if (signum>0 && rv.value>vend) { scan_end(); goto end; }
	else if (signum<0 && rv.value<vend) { scan_end(); goto end; }
	newram=endlocal;
	scan_space(); if (*next==';' || *next==',') next++;
	jump=next;
	while (!error)
	{	if (*next==1)
		{	output("End missing!\n");
			error=401; goto end;
		}
		h=command();
		if (udfon!=1 || h==c_return) break;
		if (h==c_break) { scan_end(); break; }
		if (h==c_end)
		{	rv.value+=vstep;
			if (signum>0 && rv.value>vend) break;
			else if (signum<0 && rv.value<vend) break;
			else next=jump;
			if (test_key()==escape)
			{   output("User interrupted!\n");
				error=1; break;
			}
		}
	}
	end : kill_local(name);
}
Example #2
0
File: sst.c Project: aichao/sst
void debugme(void) {
	proutn("Reset levels? ");
	if (ja() != 0) {
		if (energy < inenrg) energy = inenrg;
		shield = inshld;
		torps = intorps;
		lsupres = inlsr;
	}
	proutn("Reset damage? ");
	if (ja() != 0) {
		int i;
		for (i=0; i <= ndevice; i++) if (damage[i] > 0.0) damage[i] = 0.0;
		stdamtim = 1e30;
	}
	proutn("Toggle idebug? ");
	if (ja() != 0) {
		idebug = !idebug;
		if (idebug) prout("Debug output ON");
		else prout("Debug output OFF");
	}
	proutn("Cause selective damage? ");
	if (ja() != 0) {
		int i, key;
		for (i=1; i <= ndevice; i++) {
			proutn("Kill ");
			proutn(device[i]);
			proutn("? ");
			chew();
			key = scan();
			if (key == IHALPHA &&  isit("y")) {
				damage[i] = 10.0;
				if (i == DRADIO) stdamtim = d.date;
			}
		}
	}
	proutn("Examine/change events? ");
	if (ja() != 0) {
		int i;
		for (i = 1; i < NEVENTS; i++) {
			int key;
			if (future[i] == 1e30) continue;
			switch (i) {
				case FSNOVA:  proutn("Supernova       "); break;
				case FTBEAM:  proutn("T Beam          "); break;
				case FSNAP:   proutn("Snapshot        "); break;
				case FBATTAK: proutn("Base Attack     "); break;
				case FCDBAS:  proutn("Base Destroy    "); break;
				case FSCMOVE: proutn("SC Move         "); break;
				case FSCDBAS: proutn("SC Base Destroy "); break;
			}
			cramf(future[i]-d.date, 8, 2);
			chew();
			proutn("  ?");
			key = scan();
			if (key == IHREAL) {
				future[i] = d.date + aaitem;
			}
		}
		chew();
	}
}
Example #3
0
lexer::~lexer() {
	if (state != eof) {
		scan('\0');
	}
}
Example #4
0
static void
def_program(definition *defp)
{
	token tok;
	version_list *vlist;
	version_list **vtailp;
	proc_list *plist;
	proc_list **ptailp;

	defp->def_kind = DEF_PROGRAM;
	scan(TOK_IDENT, &tok);
	defp->def_name = tok.str;
	scan(TOK_LBRACE, &tok);
	vtailp = &defp->def.pr.versions;
	scan(TOK_VERSION, &tok);
	do {
		scan(TOK_IDENT, &tok);
		vlist = ALLOC(version_list);
		vlist->vers_name = tok.str;
		scan(TOK_LBRACE, &tok);
		ptailp = &vlist->procs;
		do {
			plist = ALLOC(proc_list);
			plist->next = NULL;
			get_type(&plist->res_prefix, &plist->res_type, DEF_PROGRAM);
			if (streq(plist->res_type, "opaque")) {
				error("illegal result type");
			}
			scan(TOK_IDENT, &tok);
			plist->proc_name = tok.str;
			scan(TOK_LPAREN, &tok);
			get_type(&plist->arg_prefix, &plist->arg_type, DEF_PROGRAM);
			if (streq(plist->arg_type, "opaque")) {
				error("illegal argument type");
			}
			scan(TOK_RPAREN, &tok);
			scan(TOK_EQUAL, &tok);
			scan_num(&tok);
			scan(TOK_SEMICOLON, &tok);
			plist->proc_num = tok.str;
			*ptailp = plist;
			ptailp = &plist->next;
			peek(&tok);
		} while (tok.kind != TOK_RBRACE);
		*vtailp = vlist;
		vtailp = &vlist->next;
		scan(TOK_RBRACE, &tok);
		scan(TOK_EQUAL, &tok);
		scan_num(&tok);
		vlist->vers_num = tok.str;
		scan(TOK_SEMICOLON, &tok);
		scan2(TOK_VERSION, TOK_RBRACE, &tok);
	} while (tok.kind == TOK_VERSION);
	scan(TOK_EQUAL, &tok);
	scan_num(&tok);
	defp->def.pr.prog_num = tok.str;
	*vtailp = NULL;
}
Example #5
0
File: sst.c Project: aichao/sst
static void helpme(void) {
	int i, j;
	char cmdbuf[32];
	char linebuf[132];
	FILE *fp;
	/* Give help on commands */
	int key;
	key = scan();
	while (TRUE) {
		if (key == IHEOL) {
			proutn("Help on what command?");
			key = scan();
		}
		if (key == IHEOL) return;
		for (i = 0; i < NUMCOMMANDS; i++) {
			if (strcmp(commands[i], citem)==0) break;
		}
		if (i != NUMCOMMANDS) break;
		skip(1);
		prout("Valid commands:");
		listCommands(FALSE);
		key = IHEOL;
		chew();
		skip(1);
	}
	if (i == 23) {
		strcpy(cmdbuf, " ABBREV");
	}
	else {
		strcpy(cmdbuf, "  Mnemonic:  ");
		j = 0;
		while ((cmdbuf[j+13] = toupper(commands[i][j])) != 0) j++;
	}
	fp = fopen("sst.doc", "r");
	if (fp == NULL) {
		prout("Spock-  \"Captain, that information is missing from the");
		prout("   computer. You need to find SST.DOC and put it in the");
		prout("   current directory.\"");
		return;
	}
	i = strlen(cmdbuf);
	do {
		if (fgets(linebuf, 132, fp) == NULL) {
			prout("Spock- \"Captain, there is no information on that command.\"");
			fclose(fp);
			return;
		}
	} while (strncmp(linebuf, cmdbuf, i) != 0);

	skip(1);
	prout("Spock- \"Captain, I've found the following information:\"");
	skip(1);

	do {
		if (linebuf[0]!=12) { // ignore page break lines 
			linebuf[strlen(linebuf)-1] = '\0'; // No \n at end
			prout(linebuf);
		}
		fgets(linebuf,132,fp);
	} while (strstr(linebuf, "******")==NULL);
	fclose(fp);
}
Example #6
0
static int exec(t_hydra_console *con, t_tokenline_parsed *p, int token_pos)
{
	int dev_func;
	mode_config_proto_t* proto = &con->mode->proto;
	int action, period, continuous, t;

	action = 0;
	period = 1000;
	continuous = FALSE;
	for (t = token_pos; p->tokens[t]; t++) {
		switch (p->tokens[t]) {
		case T_SHOW:
			t += show(con, p);
			break;
		case T_TYPEA:
			proto->dev_function = NFC_TYPEA;
			break;
		case T_VICINITY:
			proto->dev_function = NFC_VICINITY;
			break;
		case T_PERIOD:
			t += 2;
			memcpy(&period, p->buf + p->tokens[t], sizeof(int));
			break;
		case T_CONTINUOUS:
			continuous = TRUE;
			break;
		case T_SCAN:
		case T_SNIFF:
		case T_SNIFF_DBG:
		case T_EMUL_MIFARE:
		case T_EMUL_ISO14443A:
			action = p->tokens[t];
			break;
		}
	}

	if (action == T_SCAN) {
		dev_func = proto->dev_function;
		if( (dev_func == NFC_TYPEA) || (dev_func == NFC_VICINITY) ) {
			if (continuous) {
				cprintf(con, "Scanning %s ",
					proto->dev_function == NFC_TYPEA ? "MIFARE" : "Vicinity");
				cprintf(con, "with %dms period. Press user button to stop.\r\n", period);
				while (!USER_BUTTON) {
					scan(con);
					chThdSleepMilliseconds(period);
				}
			} else {
				scan(con);
			}

		} else {
			cprintf(con, "Please select MIFARE or Vicinity mode first.\r\n");
			return 0;
		}
	} else if (action == T_SNIFF) {
		hydranfc_sniff_14443A(con);
	} else if (action == T_SNIFF_DBG) {
		hydranfc_sniff_14443A_dbg(con);
	} else if (action == T_EMUL_MIFARE) {
		hydranfc_emul_mifare(con);
	} else if (action == T_EMUL_ISO14443A)
		hydranfc_emul_iso14443a(con);

	return t - token_pos;
}
Example #7
0
static Extype_t
eval(Expr_t* ex, register Exnode_t* expr, void* env)
{
	register Exnode_t*	x;
	register Exnode_t*	a;
	register Extype_t**	t;
	register int		n;
	Extype_t		v;
	Extype_t		r;
	Extype_t		i;
	char*			e;
	Exnode_t		tmp;
	Exassoc_t*		assoc;
	Extype_t		args[FRAME+1];
	Extype_t		save[FRAME];

	if (!expr || ex->loopcount)
	{
		v.integer = 1;
		return v;
	}
	x = expr->data.operand.left;
	switch (expr->op)
	{
	case BREAK:
	case CONTINUE:
		v = eval(ex, x, env);
		ex->loopcount = v.integer;
		ex->loopop = expr->op;
		return v;
	case CONSTANT:
		return expr->data.constant.value;
	case DEC:
		n = -1;
	add:
		if (x->op == DYNAMIC)
			r = getdyn(ex, x, env, &assoc);
		else
		{
			if (x->data.variable.index)
				i = eval(ex, x->data.variable.index, env);
			else
				i.integer = EX_SCALAR;
			r = (*ex->disc->getf)(ex, x, x->data.variable.symbol, x->data.variable.reference, env, (int)i.integer, ex->disc);
		}
		v = r;
		switch (x->type)
		{
		case FLOATING:
			v.floating += n;
			break;
		case INTEGER:
		case UNSIGNED:
			v.integer += n;
			break;
		default:
			goto huh;
		}
	set:
		if (x->op == DYNAMIC)
		{
			if (x->type == STRING)
			{
				v.string = vmstrdup(ex->vm, v.string);
				if (e = assoc ? assoc->value.string : x->data.variable.symbol->value->data.constant.value.string)
					vmfree(ex->vm, e);
			}
			if (assoc)
				assoc->value = v;
			else
				x->data.variable.symbol->value->data.constant.value = v;
		}
		else
		{
			if (x->data.variable.index)
				i = eval(ex, x->data.variable.index, env);
			else
				i.integer = EX_SCALAR;
			if ((*ex->disc->setf)(ex, x, x->data.variable.symbol, x->data.variable.reference, env, (int)i.integer, v, ex->disc) < 0)
				exerror("%s: cannot set value", x->data.variable.symbol->name);
		}
		if (expr->subop == PRE)
			r = v;
		return r;
	case DYNAMIC:
		return getdyn(ex, expr, env, &assoc);
	case EXIT:
		v = eval(ex, x, env);
		exit((int)v.integer);
		/*NOTREACHED*/
		v.integer = -1;
		return v;
	case IF:
		v = eval(ex, x, env);
		if (v.integer)
			eval(ex, expr->data.operand.right->data.operand.left, env);
		else
			eval(ex, expr->data.operand.right->data.operand.right, env);
		v.integer = 1;
		return v;
	case FOR:
	case WHILE:
		expr = expr->data.operand.right;
		for (;;)
		{
			r = eval(ex, x, env);
			if (!r.integer)
			{
				v.integer = 1;
				return v;
			}
			if (expr->data.operand.right)
			{
				eval(ex, expr->data.operand.right, env);
				if (ex->loopcount > 0 && (--ex->loopcount > 0 || ex->loopop != CONTINUE))
				{
					v.integer = 0;
					return v;
				}
			}
			if (expr->data.operand.left)
				eval(ex, expr->data.operand.left, env);
		}
		/*NOTREACHED*/
	case SWITCH:
		v = eval(ex, x, env);
		i.integer = x->type;
		r.integer = 0;
		x = expr->data.operand.right;
		a = x->data.select.statement;
		n = 0;
		while (x = x->data.select.next)
		{
			if (!(t = x->data.select.constant))
				n = 1;
			else
				for (; *t; t++)
				{
					switch ((int)i.integer)
					{
					case INTEGER:
					case UNSIGNED:
						if ((*t)->integer == v.integer)
							break;
						continue;
					case STRING:
						if ((ex->disc->version >= 19981111L && ex->disc->matchf) ? (*ex->disc->matchf)(ex, x, (*t)->string, expr->data.operand.left, v.string, env, ex->disc) : strmatch((*t)->string, v.string))
							break;
						continue;
					case FLOATING:
						if ((*t)->floating == v.floating)
							break;
						continue;
					}
					n = 1;
					break;
				}
			if (n)
			{
				if (!x->data.select.statement)
				{
					r.integer = 1;
					break;
				}
				r = eval(ex, x->data.select.statement, env);
				if (ex->loopcount > 0)
				{
					ex->loopcount--;
					break;
				}
			}
		}
		if (!n && a)
		{
			r = eval(ex, a, env);
			if (ex->loopcount > 0)
				ex->loopcount--;
		}
		return r;
	case ITERATE:
		v.integer = 0;
		if (expr->data.generate.array->op == DYNAMIC)
		{
			n = expr->data.generate.index->type == STRING;
			for (assoc = (Exassoc_t*)dtfirst((Dt_t*)expr->data.generate.array->data.variable.symbol->local.pointer); assoc; assoc = (Exassoc_t*)dtnext((Dt_t*)expr->data.generate.array->data.variable.symbol->local.pointer, assoc))
			{
				v.integer++;
				if (n)
					expr->data.generate.index->value->data.constant.value.string = assoc->name;
				else
					expr->data.generate.index->value->data.constant.value.integer = strtol(assoc->name, NiL, 0);
				eval(ex, expr->data.generate.statement, env);
				if (ex->loopcount > 0 && (--ex->loopcount > 0 || ex->loopop != CONTINUE))
				{
					v.integer = 0;
					break;
				}
			}
		}
		else
		{
			r = (*ex->disc->getf)(ex, expr, expr->data.generate.array->data.variable.symbol, expr->data.generate.array->data.variable.reference, env, 0, ex->disc);
			for (v.integer = 0; v.integer < r.integer; v.integer++)
			{
				expr->data.generate.index->value->data.constant.value.integer = v.integer;
				eval(ex, expr->data.generate.statement, env);
				if (ex->loopcount > 0 && (--ex->loopcount > 0 || ex->loopop != CONTINUE))
				{
					v.integer = 0;
					break;
				}
			}
		}
		return v;
	case CALL:
		x = expr->data.call.args;
		for (n = 0, a = expr->data.call.procedure->value->data.procedure.args; a && x; a = a->data.operand.right)
		{
			if (n < elementsof(args))
			{
				save[n] = a->data.operand.left->data.variable.symbol->value->data.constant.value;
				args[n++] = eval(ex, x->data.operand.left, env);
			}
			else
				a->data.operand.left->data.variable.symbol->value->data.constant.value = eval(ex, x->data.operand.left, env);
			x = x->data.operand.right;
		}
		for (n = 0, a = expr->data.call.procedure->value->data.procedure.args; a && n < elementsof(save); a = a->data.operand.right)
			a->data.operand.left->data.variable.symbol->value->data.constant.value = args[n++];
		if (x)
			exerror("too many actual args");
		else if (a)
			exerror("not enough actual args");
		v = exeval(ex, expr->data.call.procedure->value->data.procedure.body, env);
		for (n = 0, a = expr->data.call.procedure->value->data.procedure.args; a && n < elementsof(save); a = a->data.operand.right)
			a->data.operand.left->data.variable.symbol->value->data.constant.value = save[n++];
		return v;
	case FUNCTION:
		n = 0;
		args[n++].string = (char*)env;
		for (x = expr->data.operand.right; x && n < elementsof(args); x = x->data.operand.right)
			args[n++] = eval(ex, x->data.operand.left, env);
		return (*ex->disc->getf)(ex, expr->data.operand.left, expr->data.operand.left->data.variable.symbol, expr->data.operand.left->data.variable.reference, args+1, EX_CALL, ex->disc);
	case ID:
		if (expr->data.variable.index)
			i = eval(ex, expr->data.variable.index, env);
		else
			i.integer = EX_SCALAR;
		return (*ex->disc->getf)(ex, expr, expr->data.variable.symbol, expr->data.variable.reference, env, (int)i.integer, ex->disc);
	case INC:
		n = 1;
		goto add;
	case PRINTF:
		v.integer = print(ex, expr, env, NiL);
		return v;
	case QUERY:
		print(ex, expr, env, sfstderr);
		v.integer = !astquery(2, "");
		return v;
	case RETURN:
		ex->loopret = eval(ex, x, env);
		ex->loopcount = 32767;
		ex->loopop = expr->op;
		return ex->loopret;
	case SCANF:
	case SSCANF:
		v.integer = scan(ex, expr, env, NiL);
		return v;
	case SPRINTF:
		print(ex, expr, env, ex->tmp);
		v.string = exstash(ex->tmp, ex->ve);
		return v;
	case '=':
		v = eval(ex, expr->data.operand.right, env);
		if (expr->subop != '=')
		{
			r = v;
			if (x->op == DYNAMIC)
				v = getdyn(ex, x, env, &assoc);
			else
			{
				if (x->data.variable.index)
					v = eval(ex, x->data.variable.index, env);
				else
					v.integer = EX_SCALAR;
				v = (*ex->disc->getf)(ex, x, x->data.variable.symbol, x->data.variable.reference, env, (int)v.integer, ex->disc);
			}
			switch (x->type)
			{
			case FLOATING:
				switch (expr->subop)
				{
				case '+':
					v.floating += r.floating;
					break;
				case '-':
					v.floating -= r.floating;
					break;
				case '*':
					v.floating *= r.floating;
					break;
				case '/':
					if (r.floating == 0.0)
						exerror("floating divide by 0");
					else
						v.floating /= r.floating;
					break;
				case '%':
					if ((r.integer = r.floating) == 0)
						exerror("floating 0 modulus");
					else
						v.floating = ((Sflong_t)v.floating) % r.integer;
					break;
				case '&':
					v.floating = ((Sflong_t)v.floating) & ((Sflong_t)r.floating);
					break;
				case '|':
					v.floating = ((Sflong_t)v.floating) | ((Sflong_t)r.floating);
					break;
				case '^':
					v.floating = ((Sflong_t)v.floating) ^ ((Sflong_t)r.floating);
					break;
				case LS:
					v.floating = ((Sflong_t)v.floating) << ((Sflong_t)r.floating);
					break;
				case RS:
#if _WIN32
					v.floating = (Sflong_t)(((Sfulong_t)v.floating) >> ((Sflong_t)r.floating));
#else
					v.floating = ((Sfulong_t)v.floating) >> ((Sflong_t)r.floating);
#endif
					break;
				default:
					goto huh;
				}
				break;
			case INTEGER:
			case UNSIGNED:
				switch (expr->subop)
				{
				case '+':
					v.integer += r.integer;
					break;
				case '-':
					v.integer -= r.integer;
					break;
				case '*':
					v.integer *= r.integer;
					break;
				case '/':
					if (r.integer == 0)
						exerror("integer divide by 0");
					else
						v.integer /= r.integer;
					break;
				case '%':
					if (r.integer == 0)
						exerror("integer 0 modulus");
					else
						v.integer %= r.integer;
					break;
				case '&':
					v.integer &= r.integer;
					break;
				case '|':
					v.integer |= r.integer;
					break;
				case '^':
					v.integer ^= r.integer;
					break;
				case LS:
					v.integer <<= r.integer;
					break;
				case RS:
					v.integer = (Sfulong_t)v.integer >> r.integer;
					break;
				default:
					goto huh;
				}
				break;
			case STRING:
				switch (expr->subop)
				{
				case '+':
					v.string = str_add(ex, v.string, r.string);
					break;
				case '|':
					v.string = str_ior(ex, v.string, r.string);
					break;
				case '&':
					v.string = str_and(ex, v.string, r.string);
					break;
				case '^':
					v.string = str_xor(ex, v.string, r.string);
					break;
				case '%':
					v.string = str_mod(ex, v.string, r.string);
					break;
				case '*':
					v.string = str_mpy(ex, v.string, r.string);
					break;
				default:
					goto huh;
				}
				break;
			default:
				goto huh;
			}
		}
		else if (x->op == DYNAMIC)
Example #8
0
void	main(void)
{
 char	local_map[9][9]; 	/* Buffer to hold the local map */
 int	x_pos,			/* Current X and Y coordinates of robot */
	y_pos;
 int	go_dir;			/* current direction (index to angle[]) */
 int	scan_angle=0;		/* Current scanning angle */
 int	range;			/* range returned from the scan routine */
 int	try;

/* Configure robot - all normal settings in this case
 * This *MUST* be the first special function called by the robot   */
 configure(2,2,2,2,2,0);

 randomize();

 go_dir=random(8);		/* Select initial direction */

/* Note - this is an *INFINITE* loop - the PCROBOTS executive program
   kills the robot off when necessary*/
 while(1)
 {
/* Get the current position */
  getxy(&x_pos,&y_pos);

/* Get a map of the local area */
  get_local_map((char *)local_map);

/* Quick and easy way of dealing with the robot being near an outside wall */
  if (x_pos<20)
   go_dir=(random(3)-1)%8;
  if (x_pos>=980)
   go_dir=random(3)+3;
  if (y_pos<20)
   go_dir=random(3)+1;
  if (y_pos>=980)
   go_dir=random(3)+5;

  try=0;
/* Look for a square which hasn't got a wall in it (ignore traps in this
 * simple program) */
  while (local_map[angle[go_dir].y][angle[go_dir].x] == ARENA_WALL)
  {
   go_dir=random(8);

/* Failsafe check to avoid the program getting trapped here */
   if (try++ > 10)
    break;
  }

/* Move in the new direction */
  movement(50,angle[go_dir].angle);

/* Check if target found, shoot at it if so, otherwise go to next angle */
  if (scan(scan_angle,5,&range)>=0)
  {
	if(!shells_left()) buy_shells(1);
   shoot(scan_angle,range);
  }
  else
   scan_angle=(scan_angle+5)%360;

 }
}
Example #9
0
 void run() {
    scan();
    E();
 }
Example #10
0
std::list<ADAPTER_INFO>
KLOP_GetAdapterList()
{
	std::list<ADAPTER_INFO> RetList;
	ADAPTER_INFO	AI;	
	HKEY			hKey = NULL;
	FILETIME		ftLastWriteTime;      // last write time 
	CHAR			achKey[MAX_PATH]; 
	wchar_t			wchKey[MAX_PATH];
	ULONG			KeyLength;
	int				i;
	DWORD			retCode;

	if ( KLOP_isWinNT() )
	{
		/*
		if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, NT_ADAPTERS_KEY, &hKey ) )
		{
			for (i = 0, retCode = ERROR_SUCCESS; retCode == ERROR_SUCCESS; i++ )
			{ 
				KeyLength = MAX_PATH;

				retCode = RegEnumKeyExW(hKey, i, wchKey, &KeyLength, NULL, NULL, NULL, &ftLastWriteTime );

				if ( ERROR_SUCCESS == retCode )
				{
					memset ( &AI , 0, sizeof ( AI ) );
					wcscpy ( (wchar_t*)AI.AdapterBuffer, L"\\Device\\");
					wcscat ( (wchar_t*)AI.AdapterBuffer, wchKey );
					AI.AdapterNameSize = ( wcslen ( (wchar_t*)AI.AdapterBuffer ) + 1 ) << 1;
					AI.LocalIp = 0;

					RetList.push_back( AI );
				}
			} 
		}
		else
		*/
		{
			// Winnt4.0
			if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards", &hKey ) )
			{
				for ( i = 0, retCode = ERROR_SUCCESS; retCode == ERROR_SUCCESS; i++ )
				{
					HKEY hSubKey = NULL;
					KeyLength = MAX_PATH;
					retCode = RegEnumKeyExW(hKey, i, wchKey, &KeyLength, NULL, NULL, NULL, &ftLastWriteTime );
					
					if ( retCode == ERROR_SUCCESS )
					{
						retCode = RegOpenKeyW(hKey, wchKey, &hSubKey );
					}

					if ( retCode == ERROR_SUCCESS )
					{			
						KeyLength = MAX_PATH;
						DWORD	type = REG_SZ;

						if ( ERROR_SUCCESS == RegQueryValueExW( 
							hSubKey, 
							L"ServiceName", 
							NULL,
							&type,
							(LPBYTE)wchKey, 
							(ULONG*)&KeyLength ) )
						{
							memset ( &AI , 0, sizeof ( AI ) );
							wcscpy ( (wchar_t*)AI.AdapterBuffer, L"\\Device\\");
							wcscat ( (wchar_t*)AI.AdapterBuffer, wchKey );
							AI.AdapterNameSize = ( wcslen ( (wchar_t*)AI.AdapterBuffer ) + 1 ) << 1;
							AI.LocalIp = 0;
							
							// Если открывается и не Hidden, тогда добавляем для проверки.
							if ( scan( (wchar_t*)wchKey ) && !IsHidden(hSubKey) )
								RetList.push_back( AI );
						}
					}

					if ( hSubKey )
						RegCloseKey( hSubKey );
				}
			}			
		}
	}
	else
	{
		if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, W9X_ADAPTER_KEY, &hKey ) )
		{			
			for (i = 0, retCode = ERROR_SUCCESS; retCode == ERROR_SUCCESS; i++ )
			{ 
				KeyLength = MAX_PATH;

				retCode = RegEnumKeyExA(hKey, i, achKey, &KeyLength, NULL, NULL, NULL, &ftLastWriteTime);
				
				if ( ERROR_SUCCESS == retCode )
				{
					memset ( &AI , 0, sizeof ( AI ) );					
					strcpy ( AI.AdapterBuffer, achKey );
					AI.AdapterNameSize = strlen ( achKey ) + 1;
					AI.LocalIp = 0;

					RetList.push_back( AI );
				}				
			} 
		}
	}

	if ( hKey )
	{
		RegCloseKey( hKey );
	}

	return RetList;
}
Example #11
0
  /**
   * Performs a garbage collection of the immix space.
   */
  void ImmixGC::collect(GCData& data) {
    Object* tmp;

    gc_.clear_lines();

    int via_handles_ = 0;
    int via_roots = 0;

    for(Roots::Iterator i(data.roots()); i.more(); i.advance()) {
      tmp = i->get();
      if(tmp->reference_p()) saw_object(tmp);
      via_roots++;
    }

    if(data.threads()) {
      for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
          i != data.threads()->end();
          ++i) {
        scan(*i, false);
      }
    }

    for(capi::Handles::Iterator i(*data.handles()); i.more(); i.advance()) {
      if(i->in_use_p() && !i->weak_p()) {
        saw_object(i->object());
        via_handles_++;
      }
    }

    for(capi::Handles::Iterator i(*data.cached_handles()); i.more(); i.advance()) {
      if(i->in_use_p() && !i->weak_p()) {
        saw_object(i->object());
        via_handles_++;
      }
    }

    std::list<capi::Handle**>* gh = data.global_handle_locations();

    if(gh) {
      for(std::list<capi::Handle**>::iterator i = gh->begin();
          i != gh->end();
          ++i) {
        capi::Handle** loc = *i;
        if(capi::Handle* hdl = *loc) {
          if(!REFERENCE_P(hdl)) continue;
          if(hdl->valid_p()) {
            Object* obj = hdl->object();
            if(obj && obj->reference_p()) {
              saw_object(obj);
              via_handles_++;
            }
          } else {
            std::cerr << "Detected bad handle checking global capi handles\n";
          }
        }
      }
    }

#ifdef ENABLE_LLVM
    if(LLVMState* ls = data.llvm_state()) ls->gc_scan(this);
#endif

    gc_.process_mark_stack(allocator_);

    // We've now finished marking the entire object graph.

    check_finalize();

    // Finalize can cause more things to continue to live, so we must
    // check the mark_stack again.
    while(gc_.process_mark_stack(allocator_)) {
      check_finalize();
    }

    // Sweep up the garbage
    gc_.sweep_blocks();

    // This resets the allocator state to sync it up with the BlockAllocator
    // properly.
    allocator_.get_new_block();

    // Clear unreachable objects from the various remember sets
    int cleared = 0;
    unsigned int mark = object_memory_->mark();
    cleared = object_memory_->unremember_objects(mark);
    for(std::list<gc::WriteBarrier*>::iterator wbi = object_memory_->aux_barriers().begin();
        wbi != object_memory_->aux_barriers().end();
        ++wbi) {
      gc::WriteBarrier* wb = *wbi;
      cleared += wb->unremember_objects(mark);
    }

    // Now, calculate how much space we're still using.
    immix::Chunks& chunks = gc_.block_allocator().chunks();
    immix::AllBlockIterator iter(chunks);

    int live_bytes = 0;
    int total_bytes = 0;

    while(immix::Block* block = iter.next()) {
      total_bytes += immix::cBlockSize;
      live_bytes += block->bytes_from_lines();
    }

    double percentage_live = (double)live_bytes / (double)total_bytes;

    if(object_memory_->state()->shared.config.gc_immix_debug) {
      std::cerr << "[GC IMMIX: " << clear_marked_objects() << " marked"
                << ", "
                << via_roots << " roots "
                << via_handles_ << " handles "
                << (int)(percentage_live * 100) << "% live"
                << ", " << live_bytes << "/" << total_bytes
                << "]\n";
    }

    if(percentage_live >= 0.90) {
      if(object_memory_->state()->shared.config.gc_immix_debug) {
        std::cerr << "[GC IMMIX: expanding. "
                   << (int)(percentage_live * 100)
                   << "%]\n";
      }
      gc_.block_allocator().add_chunk();
    }

#ifdef IMMIX_DEBUG
    std::cout << "Immix: RS size cleared: " << cleared << "\n";

    immix::Chunks& chunks = gc_.block_allocator().chunks();
    std::cout << "chunks=" << chunks.size() << "\n";

    immix::AllBlockIterator iter(chunks);

    int blocks_seen = 0;
    int total_objects = 0;
    int total_object_bytes = 0;

    while(immix::Block* block = iter.next()) {
      blocks_seen++;
      std::cout << "block " << block << ", holes=" << block->holes() << " "
                << "objects=" << block->objects() << " "
                << "object_bytes=" << block->object_bytes() << " "
                << "frag=" << block->fragmentation_ratio()
                << "\n";

      total_objects += block->objects();
      total_object_bytes += block->object_bytes();
    }

    std::cout << blocks_seen << " blocks\n";
    std::cout << gc_.bytes_allocated() << " bytes allocated\n";
    std::cout << total_object_bytes << " object bytes / " << total_objects << " objects\n";

    int* holes = new int[10];
    for(int i = 0; i < 10; i++) {
      holes[i] = 0;
    }

    immix::AllBlockIterator iter2(chunks);

    while(immix::Block* block = iter2.next()) {
      int h = block->holes();
      if(h > 9) h = 9;

      holes[h]++;
    }

    std::cout << "== hole stats ==\n";
    for(int i = 0; i < 10; i++) {
      if(holes[i] > 0) {
        std::cout << i << ": " << holes[i] << "\n";
      }
    }

    delete[] holes;
    holes = NULL;
#endif
  }
Example #12
0
void AsiMS2000::selectCommand(int commandNum)
{
  switch(commandNum)
  {
      case 0:
          accel();
          break;
      case 1:
          aalign();
          break;
      case 2:
          afcont();
          break;
      case 3:
          aflim();
          break;
      case 4:
          afocus();
          break;
      case 5:
          afset();
          break;
      case 6:
          afmove();
          break;
      case 7:
          ahome();
          break;
      case 8:
          aij();
          break;
      case 9:
          array();
          break;
      case 10:
          azero();
          break;
      case 11:
          backlash();
          break;
      case 12:
          bcustom();
          break;
      case 13:
          benable();
          break;
      case 14:
          build();
          break;
      case 15:
          cdate();
          break;
      case 16:
          cnts();
          break;
      case 17:
          customa();
          break;
      case 18:
          customb();
          break;
      case 19:
          dack();
          break;
      case 20:
          dump();
          break;
      case 21:
          ensync();
          break;
      case 22:
          epolarity();
          break;
      case 23:
          error();
          break;
      case 24:
          halt();
          break;
      case 25:
          here();
          break;
      case 26:
          home();
          break;
      case 27:
          info();
          break;
      case 28:
          joystick();
          break;
      case 29:
          jsspd();
          break;
      case 30:
          kadc();
          break;
      case 31:
          kd();
          break;
      case 32:
          ki();
          break;
      case 33:
          kp();
          break;
      case 34:
          lcd();
          break;
      case 35:
          led();
          break;
      case 36:
          lladdr();
          break;
      case 37:
          load();
          break;
      case 38:
          lock();
          break;
      case 39:
          lockrg();
          break;
      case 40:
          lockset();
          break;
      case 41:
          maintain();
          break;
      case 42:
          motctrl();
          break;
      case 43:
          move();
          break;
      case 44:
          movrel();
          break;
      case 45:
          pcros();
          break;
      case 46:
          pedal();
          break;
      case 47:
          rbmode();
          break;
      case 48:
          rdadc();
          break;
      case 49:
          rdsbyte();
          break;
      case 50:
          rdstat();
          break;
      case 51:
          relock();
          break;
      case 52:
          reset();
          break;
      case 53:
          rt();
          break;
      case 54:
          runaway();
          break;
      case 55:
          saveset();
          break;
      case 56:
          savepos();
          break;
      case 57:
          scan();
          break;
      case 58:
          scanr();
          break;
      case 59:
          scanv();
          break;
      case 60:
          secure();
          break;
      case 61:
          sethome();
          break;
      case 62:
          setlow();
          break;
      case 63:
          setup();
          break;
      case 64:
          si();
          break;
      case 65:
          speed();
          break;
      case 66:
          spin();
          break;
      case 67:
          status();
          break;
      case 68:
          stopbits();
          break;
      case 69:
          ttl();
          break;
      case 70:
          um();
          break;
      case 71:
          units();
          break;
      case 72:
          unlock();
          break;
      case 73:
          vb();
          break;
      case 74:
          vector();
          break;
      case 75:
          version();
          break;
      case 76:
          wait();
          break;
      case 77:
          where();
          break;
      case 78:
          who();
          break;
      case 79:
          wrdac();
          break;
      case 80:
          zero();
          break;
      case 81:
          z2b();
          break;
      case 82:
          zs();
          break;
      case 83:
          overshoot();
          break;
  }
}
void FaceScanner::update()
{
    m_grabber.update();
    
    if(m_grabber.isFrameNew())
    {
        if (m_shouldTrack)
        {
            m_tracker.update(toCv(m_grabber));
            
            //----If we've found a face, we store its intrinsics and begin our scanning procedure
            if (m_tracker.getFound() &&                                                                 //Have we found a face?
                ofGetElapsedTimef() > 2.0f &&                                                           //Has it been at least 2 seconds?
                m_tracker.getImageFeature(ofxFaceTracker::FACE_OUTLINE).getArea() > MIN_FACE_AREA)      //If we've found a face, is it reasonably large?
            {
                ofLogNotice("Face Scanner") << "Found a face.";
                
                //----The FBOs are cleared IFF the last sequence drawn was the particle system (denoted by the boolean m_shouldClearAmbient)
                if (!m_shouldClearAmbient) m_inkRenderer->clear();
                
                m_inkRenderer->setDrawMode(InkRenderer::FOLLOWERS);
                convertColor(m_grabber, m_thresh, CV_RGB2GRAY);
                
                m_faceOutline =         m_tracker.getImageFeature(ofxFaceTracker::FACE_OUTLINE);
                m_faceCenter =          m_faceOutline.getCentroid2D();
                m_faceArea =            m_faceOutline.getArea();       //This is a hack: something is wrong with the sign of the value returned by getArea()
                m_faceBoundingBox =     m_faceOutline.getBoundingBox();
                
                m_shouldTrack =         false;
                m_drawFrameStart =      ofGetElapsedTimef();                //When did this scan start?
                
                scan(200, 10);                                               //Start at a threshold value of 200, and decrement by 5 for each iteration
            }
            else
            {
                //----If we don't see a face and it's been m_ambientTimeout seconds, enter ambient mode
                if ((ofGetElapsedTimef() - m_ambientFrameStart) >= m_ambientTimeout) {
                    
                    //----We only want to do these operations once, otherwise the FBOs will clear every frame, and the particle system will never be drawn
                    if (m_shouldClearAmbient)
                    {
                        ofLogNotice("Face Scanner") << "Entering ambient mode.";
                        
                        //----We tell the InkRenderer to draw particles after clearing the FBOs and resetting the "draw counter"
                        m_inkRenderer->setDrawMode(InkRenderer::PARTICLES);
                        m_inkRenderer->clear();
                        m_shouldClearAmbient = false;
                    }
                }
            }
        }
        else if ((ofGetElapsedTimef() - m_drawFrameStart) >= m_drawTimeout)
        {
            //----If we shouldn't be tracking, that means we've already found a face, so begin the countdown
            ofLogNotice("Face Scanner") << "Starting a new scan.";
            
            //----After this point, we might not see another face, so we record the current time and ready the InkRenderer for a particle simulation
            m_ambientFrameStart =   ofGetElapsedTimef();
            m_shouldClearAmbient =  true;
            ofSaveScreen("screenshots/image_" + ofGetTimestampString() + ".png");
            
            reset();
        }
    }
}
Example #14
0
// loop function, can be factorized (for later)
uint8_t symaxProtocol::run( rx_values_t *rx_value )
{
    uint8_t returnValue = UNKNOWN;
    
    switch(mState)
    {
        case BOUND:
        {
            unsigned long newTime = millis();
            returnValue = BOUND_NO_VALUES;
            if( !mWireless->rxFlag() )
            {
                // Signal lost
                if((newTime - mLastSignalTime) > 4000)
                {
					reset();
                    mLastSignalTime = newTime; 
                }
            }
            else
            {
                bool incrementChannel = false;
                mWireless->resetRxFlag();
                while ( !mWireless->rxEmpty() )
                {
                    mWireless->readPayload(mFrame, PSIZE);
                    if( checksum(mFrame) == mFrame[PSIZE-1] )
                    {
                        // a valid frame has been received
                        incrementChannel = true;

                        // Discard bind frame
                        if( mFrame[5] != 0xAA && mFrame[6] != 0xAA )
                        {
                            // Extract values
                            returnValue = BOUND_NEW_VALUES;
                            rx_value->throttle = mFrame[0];
                            
                            rx_value->yaw = mFrame[2];
                            if (rx_value->yaw < 0)
                              rx_value->yaw = 128 - rx_value->yaw;
                              
                            rx_value->pitch = mFrame[1];
                            if (rx_value->pitch < 0)
                              rx_value->pitch = 128 - rx_value->pitch;
                              
                            rx_value->roll = mFrame[3];
                            if (rx_value->roll < 0)
                              rx_value->roll = 128 - rx_value->roll;
                              
                            rx_value->trim_yaw = mFrame[6] & 0x3F;
                            if (rx_value->trim_yaw >= 32)
                              rx_value->trim_yaw = 32 - rx_value->trim_yaw;

                            rx_value->trim_pitch = mFrame[5] & 0x3F;
                            if (rx_value->trim_pitch >= 32)
                              rx_value->trim_pitch = 32 - rx_value->trim_pitch;

                            rx_value->trim_roll = mFrame[7] & 0x3F;
                            if (rx_value->trim_roll >= 32)
                              rx_value->trim_roll = 32 - rx_value->trim_roll;

                            rx_value->video = mFrame[4] & 0x80;
                            rx_value->picture = mFrame[4] & 0x40;
                            rx_value->highspeed = mFrame[5] & 0x80;
                            rx_value->flip = mFrame[6] & 0x40;

                            mLastSignalTime = newTime;
                        }
                    }
                }
                if(incrementChannel)
                {
                    mRfChNum++;
                    if( mRfChNum >= FSIZE)
                    mRfChNum = 0;
                    mWireless->switchFreq(mRFChanBufs[mRfChNum]);
                }
            }
            
        }
        break;
        // Initial state
        case NO_BIND:
        {
            returnValue = NOT_BOUND;
            unsigned long newTime = millis();
            
            if( !mWireless->rxFlag() )
            {
				scan();
            }
            else
            {
                
                mWireless->resetRxFlag();
                bool bFrameOk = false;
                while ( !mWireless->rxEmpty() )
                {
                    mWireless->readPayload(mFrame, PSIZE);
                    if(checksum(mFrame) == mFrame[PSIZE-1] && mFrame[5] == 0xAA && mFrame[6] == 0xAA)
                    {
                        
                        // Bind frame is OK
                        
                        uint8_t txAddr[5];
                        for (int k=0; k<5; k++)
                        txAddr[k] = mFrame[4-k];
                        
                        // Create TX frequency array
                        
                        mWireless->setAddress(txAddr, 5);
                        
                        setRFChannel(txAddr[0]);
                        mRfChNum = 0;
                        mWireless->switchFreq(mRFChanBufs[mRfChNum]);
                        
                        mLastSignalTime = newTime;
                        mState = WAIT_FIRST_SYNCHRO;
                        mWireless->flushRx();
                        returnValue = BIND_IN_PROGRESS;
                        
                        break;
                    }
                }
            }
        }
        break;
        
        // Wait on the first frequency of TX
        case WAIT_FIRST_SYNCHRO:
        {
            
            unsigned long newTime = millis();
            returnValue = BIND_IN_PROGRESS;
            if( mWireless->rxFlag() )
            {
                mWireless->resetRxFlag();
                bool incrementChannel = false;
                while ( !mWireless->rxEmpty() )
                {
                    mWireless->readPayload(mFrame, PSIZE);
                    
                    if( checksum(mFrame) == mFrame[PSIZE-1] )
                    {
                        incrementChannel = true;
                        mState = BOUND;
                        mLastSignalTime = newTime;
                    }
                }
                
                if(incrementChannel)
                {
                    // switch channel
                    mRfChNum++;
                    if( mRfChNum >= FSIZE)
                    mRfChNum = 0;
                    mWireless->switchFreq(mRFChanBufs[mRfChNum]);
                }
            }
            
            break;
        }
        
        default:
        break;
    }
    
    return returnValue;
}
Example #15
0
clsparseStatus
reduce_by_key(
    int keys_first,
    int keys_last,
    int values_first,
    cl_mem keys_input,
    cl_mem values_input,
    cl_mem keys_output,
    cl_mem values_output,
    int *count,
    clsparseControl control
)
{

    cl_int l_Error;

    /**********************************************************************************
     * Compile Options
     *********************************************************************************/
    const int kernel0_WgSize = WAVESIZE*KERNEL02WAVES;
    const int kernel1_WgSize = WAVESIZE*KERNEL1WAVES;
    const int kernel2_WgSize = WAVESIZE*KERNEL02WAVES;

    //const std::string params = std::string() +
    //          " -DKERNEL0WORKGROUPSIZE=" + std::to_string(kernel0_WgSize)
    //        + " -DKERNEL1WORKGROUPSIZE=" + std::to_string(kernel1_WgSize)
    //        + " -DKERNEL2WORKGROUPSIZE=" + std::to_string(kernel2_WgSize);
    const std::string params;

    cl::Context context = control->getContext();
    std::vector<cl::Device> dev = context.getInfo<CL_CONTEXT_DEVICES>();
    int computeUnits  = dev[0].getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >( );
    int wgPerComputeUnit = dev[0].getInfo< CL_DEVICE_MAX_WORK_GROUP_SIZE >( );


    int resultCnt = computeUnits * wgPerComputeUnit;
    cl_uint numElements = keys_last - keys_first + 1;

    size_t sizeInputBuff = numElements;
    int modWgSize = (sizeInputBuff & (kernel0_WgSize-1));
    if( modWgSize )
    {
        sizeInputBuff &= ~modWgSize;
        sizeInputBuff += kernel0_WgSize;
    }
    cl_uint numWorkGroupsK0 = static_cast< cl_uint >( sizeInputBuff / kernel0_WgSize );

    size_t sizeScanBuff = numWorkGroupsK0;
    modWgSize = (sizeScanBuff & (kernel0_WgSize-1));
    if( modWgSize )
    {
        sizeScanBuff &= ~modWgSize;
        sizeScanBuff += kernel0_WgSize;
    }

    cl_mem tempArrayVec = clCreateBuffer(context(),CL_MEM_READ_WRITE, (numElements)*sizeof(int), NULL, NULL );

    /**********************************************************************************
     *  Kernel 0
     *********************************************************************************/

    cl::Kernel kernel0 = KernelCache::get(control->queue,"reduce_by_key", "OffsetCalculation", params);

    KernelWrap kWrapper0(kernel0);

    kWrapper0 << keys_input << tempArrayVec
              << numElements;

    cl::NDRange local0(kernel0_WgSize);
    cl::NDRange global0(sizeInputBuff);

    cl_int status = kWrapper0.run(control, global0, local0);

    if (status != CL_SUCCESS)
    {
        return clsparseInvalidKernelExecution;
    }

    int init = 0;

    scan(0,
	 numElements - 1,
         tempArrayVec,
         tempArrayVec,
         0,
         0,
         control
         );

    int pattern = 0;
    cl_mem keySumArray = clCreateBuffer(context(),CL_MEM_READ_WRITE, (sizeScanBuff)*sizeof(int), NULL, NULL );
    cl_mem preSumArray = clCreateBuffer(context(),CL_MEM_READ_WRITE, (sizeScanBuff)*sizeof(int), NULL, NULL );
    cl_mem postSumArray = clCreateBuffer(context(),CL_MEM_READ_WRITE,(sizeScanBuff)*sizeof(int), NULL, NULL );
    clEnqueueFillBuffer(control->queue(), keySumArray, &pattern, sizeof(int), 0,
                        (sizeScanBuff)*sizeof(int), 0, NULL, NULL);
    clEnqueueFillBuffer(control->queue(), preSumArray, &pattern, sizeof(int), 0,
                        (sizeScanBuff)*sizeof(int), 0, NULL, NULL);
    clEnqueueFillBuffer(control->queue(), postSumArray, &pattern, sizeof(int), 0,
                        (sizeScanBuff)*sizeof(int), 0, NULL, NULL);


    /**********************************************************************************
     *  Kernel 1
     *********************************************************************************/

    cl::Kernel kernel1 = KernelCache::get(control->queue,"reduce_by_key", "perBlockScanByKey", params);

    KernelWrap kWrapper1(kernel1);

    kWrapper1 << tempArrayVec
	      << values_input
              << numElements
	      << keySumArray
	      << preSumArray;

    cl::NDRange local1(kernel0_WgSize);
    cl::NDRange global1(sizeInputBuff);

    status = kWrapper1.run(control, global1, local1);

    if (status != CL_SUCCESS)
    {
        return clsparseInvalidKernelExecution;
    }

    /**********************************************************************************
     *  Kernel 2
     *********************************************************************************/
    cl_uint workPerThread = static_cast< cl_uint >( sizeScanBuff / kernel1_WgSize );

    cl::Kernel kernel2 = KernelCache::get(control->queue,"reduce_by_key", "intraBlockInclusiveScanByKey", params);

    KernelWrap kWrapper2(kernel2);

    kWrapper2 << keySumArray << preSumArray
              << postSumArray << numWorkGroupsK0 << workPerThread;

    cl::NDRange local2(kernel1_WgSize);
    cl::NDRange global2(kernel1_WgSize);

    status = kWrapper2.run(control, global2, local2);

    if (status != CL_SUCCESS)
    {
        return clsparseInvalidKernelExecution;
    }

    /**********************************************************************************
     *  Kernel 3
     *********************************************************************************/

    cl::Kernel kernel3 = KernelCache::get(control->queue,"reduce_by_key", "keyValueMapping", params);

    KernelWrap kWrapper3(kernel3);

    kWrapper3 << keys_input << keys_output
              << values_input << values_output << tempArrayVec
              << keySumArray << postSumArray << numElements;

    cl::NDRange local3(kernel0_WgSize);
    cl::NDRange global3(sizeInputBuff);

    status = kWrapper3.run(control, global3, local3);

    if (status != CL_SUCCESS)
    {
        return clsparseInvalidKernelExecution;
    }

    int *h_result = (int *) malloc (sizeof(int));

    clEnqueueReadBuffer(control->queue(),
                        tempArrayVec,
                        1,
                       (numElements-1)*sizeof(int),
                        sizeof(int),
                        h_result,
                        0,
                        0,
                        0);

    *count = *(h_result);
    //printf("h_result = %d\n", *count );

    //release buffers
    clReleaseMemObject(tempArrayVec);
    clReleaseMemObject(preSumArray);
    clReleaseMemObject(postSumArray);
    clReleaseMemObject(keySumArray);

    return clsparseSuccess;
}   //end of reduce_by_key
Example #16
0
/*
* Check for primitives
* Flags, Registers, Numbers, Addresses and parentheses
*/
Condition* Primitive(const char** str, Condition* c)
{
	if (isFlag(next)) /* Flags */
	{
		if (c->type1 == TYPE_NO)
		{
			c->type1 = TYPE_FLAG;
			c->value1 = next;
		}
		else
		{
			c->type2 = TYPE_FLAG;
			c->value2 = next;
		}

		scan(str);

		return c;
	}
	else if (isRegister(next)) /* Registers */
	{
		if (c->type1 == TYPE_NO)
		{
			c->type1 = TYPE_REG;
			c->value1 = next;
		}
		else
		{
			c->type2 = TYPE_REG;
			c->value2 = next;
		}

		scan(str);

		return c;
	}
	else if (isBank(next)) /* PC Bank */
	{
		if (c->type1 == TYPE_NO)
		{
			c->type1 = TYPE_BANK;
			c->value1 = next;
		}
		else
		{
			c->type2 = TYPE_BANK;
			c->value2 = next;
		}

		scan(str);

		return c;
	}
	else if (next == '#') /* Numbers */
	{
		unsigned int number = 0;
		if (!getNumber(&number, str))
		{
			return 0;
		}

		if (c->type1 == TYPE_NO)
		{
			c->type1 = TYPE_NUM;
			c->value1 = number;
		}
		else
		{
			c->type2 = TYPE_NUM;
			c->value2 = number;
		}

		return c;
	}
	else if (next == '$') /* Addresses */
	{
		if ((**str >= '0' && **str <= '9') || (**str >= 'A' && **str <= 'F')) /* Constant addresses */
		{
			unsigned int number = 0;
			if (!getNumber(&number, str))
			{
				return 0;
			}

			if (c->type1 == TYPE_NO)
			{
				c->type1 = TYPE_ADDR;
				c->value1 = number;
			}
			else
			{
				c->type2 = TYPE_ADDR;
				c->value2 = number;
			}

			return c;
		}
		else if (**str == '[') /* Dynamic addresses */
		{
			scan(str);
			Parentheses(str, c, '[', ']');

			if (c->type1 == TYPE_NO)
			{
				c->type1 = TYPE_ADDR;
			}
			else
			{
				c->type2 = TYPE_ADDR;
			}

			return c;
		}
		else
		{
			return 0;
		}
	}
	else if (next == '(')
	{
		return Parentheses(str, c, '(', ')');
	}

	return 0;
}
Example #17
0
Scanner::Scanner (QString n, DBIndex *i) : QTabDialog (0, 0, FALSE)
{
  chartIndex = i;
  scannerName = n;
  
  QString s = "Qtstalker Scanner";
  s.append(": ");
  s.append(scannerName);
  setCaption (s);

  QWidget *w = new QWidget(this);
  
  QVBoxLayout *vbox = new QVBoxLayout(w);
  vbox->setMargin(5);
  vbox->setSpacing(5);
  
  QHGroupBox *gbox = new QHGroupBox(tr("Symbol Selection"), w);  
  vbox->addWidget(gbox);

  allSymbols = new QCheckBox(tr("All symbols"), gbox);
  connect(allSymbols, SIGNAL(toggled(bool)), this, SLOT(allSymbolsToggled(bool)));

  fileButton = new QPushButton(tr("0 Symbols"), gbox);
  connect(fileButton, SIGNAL(clicked()), this, SLOT(getSymbols()));

  basePath = new QComboBox(gbox);
  basePath->insertItem(tr("Chart"), -1);
  basePath->insertItem(tr("Group"), -1);

  QGridLayout *grid = new QGridLayout(vbox, 1, 2);
  grid->setColStretch(1, 1);

  QLabel *label = new QLabel(tr("Bar Length"), w);
  grid->addWidget(label, 0, 0);

  BarData bd(scannerName);
  period = new QComboBox(w);
  bd.getBarLengthList(barLengthList);
  period->insertStringList(barLengthList, -1);
  period->setCurrentText("Daily");
  grid->addWidget(period, 0, 1);

  label = new QLabel(tr("Bars"), w);
  grid->addWidget(label, 1, 0);

  bars = new QSpinBox(1, 99999999, 1, w);
  bars->setValue(100);
  grid->addWidget(bars, 1, 1);
  
  list = new FormulaEdit(w, FormulaEdit::Logic);
  vbox->addWidget(list);
  
  setDefaultButton(tr("&Scan"));
  connect(this, SIGNAL(defaultButtonPressed()), this, SLOT(scan()));
  
  setApplyButton(tr("&Apply"));  
  connect(this, SIGNAL(applyButtonPressed()), this, SLOT(saveRule()));
  
  setCancelButton(tr("&Cancel"));  
  connect(this, SIGNAL(cancelButtonPressed()), this, SLOT(exitDialog()));
  
  setOkButton(QString::null);  
  
  setHelpButton();
  QObject::connect(this, SIGNAL(helpButtonPressed()), this, SLOT(slotHelp()));
  
  addTab(w, tr("Parms"));

  loadRule();
}
Example #18
0
  /**
   * Perform garbage collection on the young objects.
   */
  void BakerGC::collect(GCData& data, YoungCollectStats* stats) {

#ifdef HAVE_VALGRIND_H
    VALGRIND_MAKE_MEM_DEFINED(next->start().as_int(), next->size());
    VALGRIND_MAKE_MEM_DEFINED(current->start().as_int(), current->size());
#endif

    Object* tmp;
    ObjectArray *current_rs = object_memory_->swap_remember_set();

    total_objects = 0;

    copy_spills_ = 0;
    reset_promoted();

    // Start by copying objects in the remember set
    for(ObjectArray::iterator oi = current_rs->begin();
        oi != current_rs->end();
        ++oi) {
      tmp = *oi;
      // unremember_object throws a NULL in to remove an object
      // so we don't have to compact the set in unremember
      if(tmp) {
        // assert(tmp->mature_object_p());
        // assert(!tmp->forwarded_p());

        // Remove the Remember bit, since we're clearing the set.
        tmp->clear_remember();
        scan_object(tmp);
      }
    }

    delete current_rs;

    for(std::list<gc::WriteBarrier*>::iterator wbi = object_memory_->aux_barriers().begin();
        wbi != object_memory_->aux_barriers().end();
        ++wbi) {
      gc::WriteBarrier* wb = *wbi;
      ObjectArray* rs = wb->swap_remember_set();
      for(ObjectArray::iterator oi = rs->begin();
          oi != rs->end();
          ++oi) {
        tmp = *oi;

        if(tmp) {
          tmp->clear_remember();
          scan_object(tmp);
        }
      }

      delete rs;
    }

    for(Roots::Iterator i(data.roots()); i.more(); i.advance()) {
      i->set(saw_object(i->get()));
    }

    if(data.threads()) {
      for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
          i != data.threads()->end();
          ++i) {
        scan(*i, true);
      }
    }

    for(Allocator<capi::Handle>::Iterator i(data.handles()->allocator()); i.more(); i.advance()) {
      if(!i->in_use_p()) continue;

      if(!i->weak_p() && i->object()->young_object_p()) {
        i->set_object(saw_object(i->object()));

      // Users manipulate values accessible from the data* within an
      // RData without running a write barrier. Thusly if we see a mature
      // rdata, we must always scan it because it could contain
      // young pointers.
      } else if(!i->object()->young_object_p() && i->is_rdata()) {
        scan_object(i->object());
      }

      assert(i->object()->type_id() > InvalidType && i->object()->type_id() < LastObjectType);
    }

    std::list<capi::GlobalHandle*>* gh = data.global_handle_locations();

    if(gh) {
      for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();
          i != gh->end();
          ++i) {
        capi::GlobalHandle* global_handle = *i;
        capi::Handle** loc = global_handle->handle();
        if(capi::Handle* hdl = *loc) {
          if(!REFERENCE_P(hdl)) continue;
          if(hdl->valid_p()) {
            Object* obj = hdl->object();
            if(obj && obj->reference_p() && obj->young_object_p()) {
              hdl->set_object(saw_object(obj));
            }
          } else {
            std::cerr << "Detected bad handle checking global capi handles\n";
          }
        }
      }
    }

#ifdef ENABLE_LLVM
    if(LLVMState* ls = data.llvm_state()) ls->gc_scan(this);
#endif

    // Handle all promotions to non-young space that occurred.
    handle_promotions();

    assert(fully_scanned_p());
    // We're now done seeing the entire object graph of normal, live references.
    // Now we get to handle the unusual references, like finalizers and such.

    // Objects with finalizers must be kept alive until the finalizers have
    // run.
    walk_finalizers();

    // Process possible promotions from processing objects with finalizers.
    handle_promotions();

    if(!promoted_stack_.empty()) rubinius::bug("promote stack has elements!");
    if(!fully_scanned_p()) rubinius::bug("more young refs");

    // Check any weakrefs and replace dead objects with nil
    clean_weakrefs(true);

    // Remove unreachable locked objects still in the list
    if(data.threads()) {
      for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
          i != data.threads()->end();
          ++i) {
        clean_locked_objects(*i, true);
      }
    }

    // Swap the 2 halves
    Heap *x = next;
    next = current;
    current = x;

    if(stats) {
      stats->lifetime = lifetime_;
      stats->percentage_used = current->percentage_used();
      stats->promoted_objects = promoted_objects_;
      stats->excess_objects = copy_spills_;
    }

    // Tune the age at which promotion occurs
    if(autotune_) {
      double used = current->percentage_used();
      if(used > cOverFullThreshold) {
        if(tune_threshold_ >= cOverFullTimes) {
          if(lifetime_ > cMinimumLifetime) lifetime_--;
        } else {
          tune_threshold_++;
        }
      } else if(used < cUnderFullThreshold) {
        if(tune_threshold_ <= cUnderFullTimes) {
          if(lifetime_ < cMaximumLifetime) lifetime_++;
        } else {
          tune_threshold_--;
        }
      } else if(tune_threshold_ > 0) {
        tune_threshold_--;
      } else if(tune_threshold_ < 0) {
        tune_threshold_++;
      } else if(tune_threshold_ == 0) {
        if(lifetime_ < original_lifetime_) {
          lifetime_++;
        } else if(lifetime_ > original_lifetime_) {
          lifetime_--;
        }
      }
    }

  }
void timelib_strtointerval(char *s, int len,
                           timelib_time **begin, timelib_time **end,
                           timelib_rel_time **period, int *recurrences,
                           struct timelib_error_container **errors)
{
    Scanner in;
    int t;
    char *e = s + len - 1;

    memset(&in, 0, sizeof(in));
    in.errors = malloc(sizeof(struct timelib_error_container));
    in.errors->warning_count = 0;
    in.errors->warning_messages = NULL;
    in.errors->error_count = 0;
    in.errors->error_messages = NULL;

    if (len > 0) {
        while (isspace(*s) && s < e) {
            s++;
        }
        while (isspace(*e) && e > s) {
            e--;
        }
    }
    if (e - s < 0) {
        add_error(&in, "Empty string");
        if (errors) {
            *errors = in.errors;
        } else {
            timelib_error_container_dtor(in.errors);
        }
        return;
    }
    e++;

    /* init cursor */
    in.str = malloc((e - s) + YYMAXFILL);
    memset(in.str, 0, (e - s) + YYMAXFILL);
    memcpy(in.str, s, (e - s));
    in.lim = in.str + (e - s) + YYMAXFILL;
    in.cur = in.str;

    /* init value containers */
    in.begin = timelib_time_ctor();
    in.begin->y = TIMELIB_UNSET;
    in.begin->d = TIMELIB_UNSET;
    in.begin->m = TIMELIB_UNSET;
    in.begin->h = TIMELIB_UNSET;
    in.begin->i = TIMELIB_UNSET;
    in.begin->s = TIMELIB_UNSET;
    in.begin->f = 0;
    in.begin->z = 0;
    in.begin->dst = 0;
    in.begin->is_localtime = 0;
    in.begin->zone_type = TIMELIB_ZONETYPE_OFFSET;

    in.end = timelib_time_ctor();
    in.end->y = TIMELIB_UNSET;
    in.end->d = TIMELIB_UNSET;
    in.end->m = TIMELIB_UNSET;
    in.end->h = TIMELIB_UNSET;
    in.end->i = TIMELIB_UNSET;
    in.end->s = TIMELIB_UNSET;
    in.end->f = 0;
    in.end->z = 0;
    in.end->dst = 0;
    in.end->is_localtime = 0;
    in.end->zone_type = TIMELIB_ZONETYPE_OFFSET;

    in.period = timelib_rel_time_ctor();
    in.period->y = 0;
    in.period->d = 0;
    in.period->m = 0;
    in.period->h = 0;
    in.period->i = 0;
    in.period->s = 0;
    in.period->weekday = 0;
    in.period->weekday_behavior = 0;
    in.period->first_last_day_of = 0;
    in.period->days = TIMELIB_UNSET;

    in.recurrences = 1;

    do {
        t = scan(&in);
#ifdef DEBUG_PARSER
        printf("%d\n", t);
#endif
    } while(t != EOI);

    free(in.str);
    if (errors) {
        *errors = in.errors;
    } else {
        timelib_error_container_dtor(in.errors);
    }
    if (in.have_begin_date) {
        *begin = in.begin;
    } else {
        timelib_time_dtor(in.begin);
    }
    if (in.have_end_date) {
        *end   = in.end;
    } else {
        timelib_time_dtor(in.end);
    }
    if (in.have_period) {
        *period = in.period;
    } else {
        timelib_rel_time_dtor(in.period);
    }
    if (in.have_recurrences) {
        *recurrences = in.recurrences;
    }
}
Example #20
0
int
main (int argc, char *argv[])
{
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEBASEDIR);
  textdomain (PACKAGE);

  enum { HELP_OPTION = CHAR_MAX + 1 };

  static const char *options = "a:c:d:P:qvVx";
  static const struct option long_options[] = {
    { "add", 1, 0, 'a' },
    { "connect", 1, 0, 'c' },
    { "domain", 1, 0, 'd' },
    { "format", 2, 0, 0 },
    { "help", 0, 0, HELP_OPTION },
    { "long-options", 0, 0, 0 },
    { "quiet", 0, 0, 'q' },
    { "uuid", 0, 0, 0, },
    { "verbose", 0, 0, 'v' },
    { "version", 0, 0, 'V' },
    { 0, 0, 0, 0 }
  };
  struct drv *drvs = NULL;
  const char *format = NULL;
  bool format_consumed = true;
  int c;
  int option_index;
  int exit_code;
  size_t max_threads = 0;
  int r;

  g = guestfs_create ();
  if (g == NULL) {
    fprintf (stderr, _("guestfs_create: failed to create handle\n"));
    exit (EXIT_FAILURE);
  }

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, &option_index);
    if (c == -1) break;

    switch (c) {
    case 0:			/* options which are long only */
      if (STREQ (long_options[option_index].name, "long-options"))
        display_long_options (long_options);
      else if (STREQ (long_options[option_index].name, "format")) {
        OPTION_format;
      } else if (STREQ (long_options[option_index].name, "uuid")) {
        uuid = 1;
      } else {
        fprintf (stderr, _("%s: unknown long option: %s (%d)\n"),
                 program_name, long_options[option_index].name, option_index);
        exit (EXIT_FAILURE);
      }
      break;

    case 'a':
      OPTION_a;
      break;

    case 'c':
      OPTION_c;
      break;

    case 'd':
      OPTION_d;
      break;

    case 'P':
      if (sscanf (optarg, "%zu", &max_threads) != 1) {
        fprintf (stderr, _("%s: -P option is not numeric\n"), program_name);
        exit (EXIT_FAILURE);
      }
      break;

    case 'q':
      quiet = 1;
      break;

    case 'v':
      OPTION_v;
      break;

    case 'V':
      OPTION_V;
      break;

    case 'x':
      OPTION_x;
      break;

    case HELP_OPTION:
      usage (EXIT_SUCCESS);

    default:
      usage (EXIT_FAILURE);
    }
  }

  /* These are really constants, but they have to be variables for the
   * options parsing code.  Assert here that they have known-good
   * values.
   */
  assert (read_only == 1);
  assert (inspector == 0);
  assert (live == 0);

  /* Must be no extra arguments on the command line. */
  if (optind != argc)
    usage (EXIT_FAILURE);

  CHECK_OPTION_format_consumed;

  /* virt-alignment-scan has two modes.  If the user didn't specify
   * any drives, then we do the scan on every libvirt guest.  That's
   * the if-clause below.  If the user specified domains/drives, then
   * we assume they belong to a single guest.  That's the else-clause
   * below.
   */
  if (drvs == NULL) {
#if defined(HAVE_LIBVIRT)
    get_all_libvirt_domains (libvirt_uri);
    r = start_threads (max_threads, g, scan_work);
    free_domains ();
    if (r == -1)
      exit (EXIT_FAILURE);
#else
    fprintf (stderr, _("%s: compiled without support for libvirt.\n"),
             program_name);
    exit (EXIT_FAILURE);
#endif
  } else {                      /* Single guest. */
    if (uuid) {
      fprintf (stderr, _("%s: --uuid option cannot be used with -a or -d\n"),
               program_name);
      exit (EXIT_FAILURE);
    }

    /* Add domains/drives from the command line (for a single guest). */
    add_drives (drvs, 'a');

    if (guestfs_launch (g) == -1)
      exit (EXIT_FAILURE);

    /* Free up data structures, no longer needed after this point. */
    free_drives (drvs);

    /* Perform the scan. */
    r = scan (g, NULL, stdout);

    guestfs_close (g);

    if (r == -1)
      exit (EXIT_FAILURE);
  }

  /* Decide on an appropriate exit code. */
  if (worst_alignment < 10) /* 2^10 = 4096 */
    exit_code = 3;
  else if (worst_alignment < 16) /* 2^16 = 65536 */
    exit_code = 2;
  else
    exit_code = 0;

  exit (exit_code);
}
Example #21
0
void mbadblocks(int argc, char **argv, int type)
{
	unsigned int i;
	unsigned int startSector=2;
	unsigned int endSector=0;
	struct MainParam_t mp;
	Fs_t *Fs;
	Stream_t *Dir;
	int ret;
	char *filename = NULL;
	char c;
	unsigned int badClus;
	int sectorMode=0;
	int writeMode=0;

	while ((c = getopt(argc, argv, "i:s:cwS:E:")) != EOF) {
		switch(c) {
		case 'i':
			set_cmd_line_image(optarg, 0);
			break;
		case 'c':
			checkListTwice(filename);
			filename = strdup(optarg);
			break;
		case 's':
			checkListTwice(filename);
			filename = strdup(optarg);
			sectorMode = 1;
			break;
		case 'S':
			startSector = atol(optarg); 
			break;
		case 'E':
			endSector = atol(optarg); 
			break;
		case 'w':
			writeMode = 1;
			break;
		case 'h':
			usage(0);
		default:
			usage(1);
		}
	}

	if (argc != optind+1 ||
	    !argv[optind][0] || argv[optind][1] != ':' || argv[optind][2]) {
		usage(1);
	}

	init_mp(&mp);

	Dir = open_root_dir(argv[optind][0], O_RDWR, NULL);
	if (!Dir) {
		fprintf(stderr,"%s: Cannot initialize drive\n", argv[0]);
		exit(1);
	}

	Fs = (Fs_t *)GetFs(Dir);
	in_len = Fs->cluster_size * Fs->sector_size;
	in_buf = malloc(in_len);
	if(!in_buf) {
		printOom();
		ret = 1;
		goto exit_0;
	}
	if(writeMode) {
		int i;
		pat_buf=malloc(in_len * N_PATTERN);
		if(!pat_buf) {
			printOom();
			ret = 1;
			goto exit_0;
		}
		srandom(time(NULL));
		for(i=0; i < in_len * N_PATTERN; i++) {
			pat_buf[i] = random();
		}
	}
	for(i=0; i < Fs->clus_start; i++ ){
		ret = READS(Fs->Next, in_buf, 
			    sectorsToBytes((Stream_t*)Fs, i), Fs->sector_size);
		if( ret < 0 ){
			perror("early error");
			goto exit_0;
		}
		if(ret < (signed int) Fs->sector_size){
			fprintf(stderr,"end of file in file_read\n");
			ret = 1;
			goto exit_0;
		}
	}
	ret = 0;

	badClus = Fs->last_fat + 1;

	if(startSector < 2)
		startSector = 2;
	if(endSector > Fs->num_clus + 2 || endSector <= 0) 
		endSector = Fs->num_clus + 2;

	if(filename) {
		char line[80];

		FILE *f = fopen(filename, "r");
		if(f == NULL) {
			fprintf(stderr, "Could not open %s (%s)\n",
				filename, strerror(errno));
			ret = 1;
			goto exit_0;
		}
		while(fgets(line, sizeof(line), f)) {
			char *ptr = line + strspn(line, " \t");
			long offset = strtoul(ptr, 0, 0);
			if(sectorMode)
				offset = (offset-Fs->clus_start)/Fs->cluster_size + 2;
			if(offset < 2) {
				fprintf(stderr, "Sector before start\n");
			} else if(offset >= Fs->num_clus) {
				fprintf(stderr, "Sector beyond end\n");
			} else {
				mark(Fs, offset, badClus);
				ret = 1;
			}
		}
	} else {
		Stream_t *dev;
		dev = Fs->Next;
		if(dev->Next)
			dev = dev->Next;

		in_len = Fs->cluster_size * Fs->sector_size;
		if(writeMode) {
			/* Write pattern */
			for(i=startSector; i< endSector; i++){
				if(got_signal)
					break;
				progress(i, Fs->num_clus);
				ret |= scan(Fs, dev, i, badClus, 
					    pat_buf + in_len * (i % N_PATTERN),
					    1);
			}

			/* Flush cache, so that we are sure we read the data
			   back from disk, rather than from the cache */
			if(!got_signal)
				DISCARD(dev);

			/* Read data back, and compare to pattern */
			for(i=startSector; i< endSector; i++){
				if(got_signal)
					break;
				progress(i, Fs->num_clus);
				ret |= scan(Fs, dev, i, badClus, 
					    pat_buf + in_len * (i % N_PATTERN),
					    0);
			}

		} else {

			for(i=startSector; i< endSector; i++){
				if(got_signal)
					break;
				progress(i, Fs->num_clus);
				ret |= scan(Fs, dev, i, badClus, NULL, 0);
			}
		}
	}
 exit_0:
	FREE(&Dir);
	exit(ret);
}
Example #22
0
/* Expand a call to a macro named ID, whose definition is DEF.  Append
   its expansion to DEST.  SRC is the input text following the ID
   token.  We are currently rescanning the expansions of the macros
   named in NO_LOOP; don't re-expand them.  Use LOOKUP_FUNC and
   LOOKUP_BATON to find definitions for any nested macro references.

   Return 1 if we decided to expand it, zero otherwise.  (If it's a
   function-like macro name that isn't followed by an argument list,
   we don't expand it.)  If we return zero, leave SRC unchanged.  */
static int
expand (const char *id,
        struct macro_definition *def, 
        struct macro_buffer *dest,
        struct macro_buffer *src,
        struct macro_name_list *no_loop,
        macro_lookup_ftype *lookup_func,
        void *lookup_baton)
{
  struct macro_name_list new_no_loop;

  /* Create a new node to be added to the front of the no-expand list.
     This list is appropriate for re-scanning replacement lists, but
     it is *not* appropriate for scanning macro arguments; invocations
     of the macro whose arguments we are gathering *do* get expanded
     there.  */
  new_no_loop.name = id;
  new_no_loop.next = no_loop;

  /* What kind of macro are we expanding?  */
  if (def->kind == macro_object_like)
    {
      struct macro_buffer replacement_list;

      init_shared_buffer (&replacement_list, (char *) def->replacement,
                          strlen (def->replacement));

      scan (dest, &replacement_list, &new_no_loop, lookup_func, lookup_baton);
      return 1;
    }
  else if (def->kind == macro_function_like)
    {
      struct cleanup *back_to = make_cleanup (null_cleanup, 0);
      int argc = 0;
      struct macro_buffer *argv = NULL;
      struct macro_buffer substituted;
      struct macro_buffer substituted_src;
      struct macro_buffer va_arg_name = {0};
      int is_varargs = 0;

      if (def->argc >= 1)
	{
	  if (strcmp (def->argv[def->argc - 1], "...") == 0)
	    {
	      /* In C99-style varargs, substitution is done using
		 __VA_ARGS__.  */
	      init_shared_buffer (&va_arg_name, "__VA_ARGS__",
				  strlen ("__VA_ARGS__"));
	      is_varargs = 1;
	    }
	  else
	    {
	      int len = strlen (def->argv[def->argc - 1]);

	      if (len > 3
		  && strcmp (def->argv[def->argc - 1] + len - 3, "...") == 0)
		{
		  /* In GNU-style varargs, the name of the
		     substitution parameter is the name of the formal
		     argument without the "...".  */
		  init_shared_buffer (&va_arg_name,
				      (char *) def->argv[def->argc - 1],
				      len - 3);
		  is_varargs = 1;
		}
	    }
	}

      make_cleanup (free_current_contents, &argv);
      argv = gather_arguments (id, src, is_varargs ? def->argc : -1,
			       &argc);

      /* If we couldn't find any argument list, then we don't expand
         this macro.  */
      if (! argv)
        {
          do_cleanups (back_to);
          return 0;
        }

      /* Check that we're passing an acceptable number of arguments for
         this macro.  */
      if (argc != def->argc)
        {
	  if (is_varargs && argc >= def->argc - 1)
	    {
	      /* Ok.  */
	    }
          /* Remember that a sequence of tokens like "foo()" is a
             valid invocation of a macro expecting either zero or one
             arguments.  */
          else if (! (argc == 1
		      && argv[0].len == 0
		      && def->argc == 0))
            error (_("Wrong number of arguments to macro `%s' "
                   "(expected %d, got %d)."),
                   id, def->argc, argc);
        }

      /* Note that we don't expand macro invocations in the arguments
         yet --- we let subst_args take care of that.  Parameters that
         appear as operands of the stringifying operator "#" or the
         splicing operator "##" don't get macro references expanded,
         so we can't really tell whether it's appropriate to macro-
         expand an argument until we see how it's being used.  */
      init_buffer (&substituted, 0);
      make_cleanup (cleanup_macro_buffer, &substituted);
      substitute_args (&substituted, def, is_varargs, &va_arg_name,
		       argc, argv, no_loop, lookup_func, lookup_baton);

      /* Now `substituted' is the macro's replacement list, with all
         argument values substituted into it properly.  Re-scan it for
         macro references, but don't expand invocations of this macro.

         We create a new buffer, `substituted_src', which points into
         `substituted', and scan that.  We can't scan `substituted'
         itself, since the tokenization process moves the buffer's
         text pointer around, and we still need to be able to find
         `substituted's original text buffer after scanning it so we
         can free it.  */
      init_shared_buffer (&substituted_src, substituted.text, substituted.len);
      scan (dest, &substituted_src, &new_no_loop, lookup_func, lookup_baton);

      do_cleanups (back_to);

      return 1;
    }
  else
    internal_error (__FILE__, __LINE__, _("bad macro definition kind"));
}
Example #23
0
static void
def_union(definition *defp)
{
	token tok;
	declaration dec;
	case_list *cases;
	case_list **tailp;

	defp->def_kind = DEF_UNION;
	scan(TOK_IDENT, &tok);
	defp->def_name = tok.str;
	scan(TOK_SWITCH, &tok);
	scan(TOK_LPAREN, &tok);
	get_declaration(&dec, DEF_UNION);
	defp->def.un.enum_decl = dec;
	tailp = &defp->def.un.cases;
	scan(TOK_RPAREN, &tok);
	scan(TOK_LBRACE, &tok);
	scan(TOK_CASE, &tok);
	while (tok.kind == TOK_CASE) {
		scan(TOK_IDENT, &tok);
		cases = ALLOC(case_list);
		cases->case_name = tok.str;
		scan(TOK_COLON, &tok);
		get_declaration(&dec, DEF_UNION);
		cases->case_decl = dec;
		*tailp = cases;
		tailp = &cases->next;
		scan(TOK_SEMICOLON, &tok);
		scan3(TOK_CASE, TOK_DEFAULT, TOK_RBRACE, &tok);
	}
	*tailp = NULL;
	if (tok.kind == TOK_DEFAULT) {
		scan(TOK_COLON, &tok);
		get_declaration(&dec, DEF_UNION);
		defp->def.un.default_decl = ALLOC(declaration);
		*defp->def.un.default_decl = dec;
		scan(TOK_SEMICOLON, &tok);
		scan(TOK_RBRACE, &tok);
	} else {
		defp->def.un.default_decl = NULL;
	}
}
Example #24
0
static void
substitute_args (struct macro_buffer *dest, 
                 struct macro_definition *def,
		 int is_varargs, const struct macro_buffer *va_arg_name,
                 int argc, struct macro_buffer *argv,
                 struct macro_name_list *no_loop,
                 macro_lookup_ftype *lookup_func,
                 void *lookup_baton)
{
  /* A macro buffer for the macro's replacement list.  */
  struct macro_buffer replacement_list;
  /* The token we are currently considering.  */
  struct macro_buffer tok;
  /* The replacement list's pointer from just before TOK was lexed.  */
  char *original_rl_start;
  /* We have a single lookahead token to handle token splicing.  */
  struct macro_buffer lookahead;
  /* The lookahead token might not be valid.  */
  int lookahead_valid;
  /* The replacement list's pointer from just before LOOKAHEAD was
     lexed.  */
  char *lookahead_rl_start;

  init_shared_buffer (&replacement_list, (char *) def->replacement,
                      strlen (def->replacement));

  gdb_assert (dest->len == 0);
  dest->last_token = 0;

  original_rl_start = replacement_list.text;
  if (! get_token (&tok, &replacement_list))
    return;
  lookahead_rl_start = replacement_list.text;
  lookahead_valid = get_token (&lookahead, &replacement_list);

  for (;;)
    {
      /* Just for aesthetics.  If we skipped some whitespace, copy
         that to DEST.  */
      if (tok.text > original_rl_start)
        {
          appendmem (dest, original_rl_start, tok.text - original_rl_start);
          dest->last_token = dest->len;
        }

      /* Is this token the stringification operator?  */
      if (tok.len == 1
          && tok.text[0] == '#')
	{
	  int arg;

	  if (!lookahead_valid)
	    error (_("Stringification operator requires an argument."));

	  arg = find_parameter (&lookahead, is_varargs, va_arg_name,
				def->argc, def->argv);
	  if (arg == -1)
	    error (_("Argument to stringification operator must name "
		     "a macro parameter."));

	  stringify (dest, argv[arg].text, argv[arg].len);

	  /* Read one token and let the loop iteration code handle the
	     rest.  */
	  lookahead_rl_start = replacement_list.text;
	  lookahead_valid = get_token (&lookahead, &replacement_list);
	}
      /* Is this token the splicing operator?  */
      else if (tok.len == 2
	       && tok.text[0] == '#'
	       && tok.text[1] == '#')
	error (_("Stray splicing operator"));
      /* Is the next token the splicing operator?  */
      else if (lookahead_valid
	       && lookahead.len == 2
	       && lookahead.text[0] == '#'
	       && lookahead.text[1] == '#')
	{
	  int finished = 0;
	  int prev_was_comma = 0;

	  /* Note that GCC warns if the result of splicing is not a
	     token.  In the debugger there doesn't seem to be much
	     benefit from doing this.  */

	  /* Insert the first token.  */
	  if (tok.len == 1 && tok.text[0] == ',')
	    prev_was_comma = 1;
	  else
	    {
	      int arg = find_parameter (&tok, is_varargs, va_arg_name,
					def->argc, def->argv);

	      if (arg != -1)
		appendmem (dest, argv[arg].text, argv[arg].len);
	      else
		appendmem (dest, tok.text, tok.len);
	    }

	  /* Apply a possible sequence of ## operators.  */
	  for (;;)
	    {
	      if (! get_token (&tok, &replacement_list))
		error (_("Splicing operator at end of macro"));

	      /* Handle a comma before a ##.  If we are handling
		 varargs, and the token on the right hand side is the
		 varargs marker, and the final argument is empty or
		 missing, then drop the comma.  This is a GNU
		 extension.  There is one ambiguous case here,
		 involving pedantic behavior with an empty argument,
		 but we settle that in favor of GNU-style (GCC uses an
		 option).  If we aren't dealing with varargs, we
		 simply insert the comma.  */
	      if (prev_was_comma)
		{
		  if (! (is_varargs
			 && tok.len == va_arg_name->len
			 && !memcmp (tok.text, va_arg_name->text, tok.len)
			 && argv[argc - 1].len == 0))
		    appendmem (dest, ",", 1);
		  prev_was_comma = 0;
		}

	      /* Insert the token.  If it is a parameter, insert the
		 argument.  If it is a comma, treat it specially.  */
	      if (tok.len == 1 && tok.text[0] == ',')
		prev_was_comma = 1;
	      else
		{
		  int arg = find_parameter (&tok, is_varargs, va_arg_name,
					    def->argc, def->argv);

		  if (arg != -1)
		    appendmem (dest, argv[arg].text, argv[arg].len);
		  else
		    appendmem (dest, tok.text, tok.len);
		}

	      /* Now read another token.  If it is another splice, we
		 loop.  */
	      original_rl_start = replacement_list.text;
	      if (! get_token (&tok, &replacement_list))
		{
		  finished = 1;
		  break;
		}

	      if (! (tok.len == 2
		     && tok.text[0] == '#'
		     && tok.text[1] == '#'))
		break;
	    }

	  if (prev_was_comma)
	    {
	      /* We saw a comma.  Insert it now.  */
	      appendmem (dest, ",", 1);
	    }

          dest->last_token = dest->len;
	  if (finished)
	    lookahead_valid = 0;
	  else
	    {
	      /* Set up for the loop iterator.  */
	      lookahead = tok;
	      lookahead_rl_start = original_rl_start;
	      lookahead_valid = 1;
	    }
	}
      else
	{
	  /* Is this token an identifier?  */
	  int substituted = 0;
	  int arg = find_parameter (&tok, is_varargs, va_arg_name,
				    def->argc, def->argv);

	  if (arg != -1)
	    {
	      struct macro_buffer arg_src;

	      /* Expand any macro invocations in the argument text,
		 and append the result to dest.  Remember that scan
		 mutates its source, so we need to scan a new buffer
		 referring to the argument's text, not the argument
		 itself.  */
	      init_shared_buffer (&arg_src, argv[arg].text, argv[arg].len);
	      scan (dest, &arg_src, no_loop, lookup_func, lookup_baton);
	      substituted = 1;
	    }

	  /* If it wasn't a parameter, then just copy it across.  */
	  if (! substituted)
	    append_tokens_without_splicing (dest, &tok);
	}

      if (! lookahead_valid)
	break;

      tok = lookahead;
      original_rl_start = lookahead_rl_start;

      lookahead_rl_start = replacement_list.text;
      lookahead_valid = get_token (&lookahead, &replacement_list);
    }
}
Example #25
0
File: sst.c Project: aichao/sst
static void makemoves(void) {
	int i, hitme;
	char ch;
	while (TRUE) { /* command loop */
		hitme = FALSE;
		justin = 0;
		Time = 0.0;
		i = -1;
		while (TRUE)  { /* get a command */
			chew();
			skip(1);
			proutn("COMMAND> ");
      // Use of scan() here (after chew) will get a new line of input
      // and will return IHEOL iff new line of input contains nothing
      // or a numeric input is detected but conversion fails.
			if (scan() == IHEOL) continue;
			for (i=0; i < 26; i++)
				if (isit(commands[i]))
					break;
			if (i < 26) break;
			for (; i < NUMCOMMANDS; i++)
				if (strcmp(commands[i], citem) == 0) break;
			if (i < NUMCOMMANDS) break;
      // we get here iff the first parsed input from the line does not 
      // match one of the commands. In this case, the rest of the line
      // is discarded, the below message is printed, and we go back to 
      // get a new command.
			if (skill <= 2)  {
				prout("UNRECOGNIZED COMMAND. LEGAL COMMANDS ARE:");
				listCommands(TRUE);
			}
			else prout("UNRECOGNIZED COMMAND.");
		} // end get command loop
    // we get here iff the first parsed input from the line matches one
    // of the commands (i.e., command i). We use i to dispatch the 
    // handling of the command. The line may still contain additional
    // inputs (i.e., parameters of the command) that is to be parsed by
    // the dispatched command handler. If the line does not contain
    // all the necessary parameters, the dispatched command handler is 
    // responsible to get additional input(s) interactively using scan().
    // The dispatched command handler is also responsible to handle any 
    // input errors.
		switch (i) { /* command switch */
			case 0:			// srscan
				srscan(1);
				break;
			case 1:			// lrscan
				lrscan();
				break;
			case 2:			// phasers
				phasers();
				if (ididit) hitme = TRUE;
				break;
			case 3:			// photons
				photon();
				if (ididit) hitme = TRUE;
				break;
			case 4:			// move
				warp(1);
				break;
			case 5:			// shields
				sheild(1);
				if (ididit) {
					attack(2);
					shldchg = 0;
				}
				break;
			case 6:			// dock
				dock();
				break;
			case 7:			// damages
				dreprt();
				break;
			case 8:			// chart
				chart(0);
				break;
			case 9:			// impulse
				impuls();
				break;
			case 10:		// rest
				waiting();
				if (ididit) hitme = TRUE;
				break;
			case 11:		// warp
				setwrp();
				break;
			case 12:		// status
				srscan(3);
				break;
			case 13:			// sensors
				sensor();
				break;
			case 14:			// orbit
				orbit();
				if (ididit) hitme = TRUE;
				break;
			case 15:			// transport "beam"
				beam();
				break;
			case 16:			// mine
				mine();
				if (ididit) hitme = TRUE;
				break;
			case 17:			// crystals
				usecrystals();
				break;
			case 18:			// shuttle
				shuttle();
				if (ididit) hitme = TRUE;
				break;
			case 19:			// Planet list
				preport();
				break;
			case 20:			// Status information
				srscan(2);
				break;
			case 21:			// Game Report 
				report(0);
				break;
			case 22:			// use COMPUTER!
				eta();
				break;
			case 23:
				listCommands(TRUE);
				break;
			case 24:		// Emergency exit
				clearscreen();	// Hide screen
				freeze(TRUE);	// forced save
				exit(1);		// And quick exit
				break;
			case 25:
				probe();		// Launch probe
				break;
			case 26:			// Abandon Ship
				abandn();
				break;
			case 27:			// Self Destruct
				dstrct();
				break;
			case 28:			// Save Game
				freeze(FALSE);
				if (skill > 3)
					prout("WARNING--Frozen games produce no plaques!");
				break;
			case 29:			// Try a desparation measure
				deathray();
				if (ididit) hitme = TRUE;
				break;
			case 30:			// What do we want for debug???
#ifdef DEBUG
				debugme();
#endif
				break;
			case 31:		// Call for help
				help();
				break;
			case 32:
				alldone = 1;	// quit the game
#ifdef DEBUG
				if (idebug) score();
#endif
				break;
			case 33:
				helpme();	// get help
				break;
		} // end command switch
		for (;;) {
			if (alldone) break;		// Game has ended
#ifdef DEBUG
			if (idebug) prout("2500");
#endif
			if (Time != 0.0) {
				events();
				if (alldone) break;		// Events did us in
			}
			if (d.galaxy[quadx][quady] == 1000) { // Galaxy went Nova!
				atover(0);
				continue;
			}
			if (nenhere == 0) movetho();
			if (hitme && justin==0) {
				attack(2);
				if (alldone) break;
				if (d.galaxy[quadx][quady] == 1000) {	// went NOVA! 
					atover(0);
					hitme = TRUE;
					continue;
				}
			}
			break;
		} // end event loop
		if (alldone) break;
	} // end command loop
}
Example #26
0
double Gen::getFONC()
{

    // verificar el parametro indiceParaOrdenarTablaC que especifica el indice a utilizar
    int index = MainWindow::getIndexToSortCTable();

    QString database("test_18.1.db");

    // tipo de experimento para extraer las muestras: full -> full scanning
    QString experiment("full");

    //Scan scan(database.toStdString(),experiment.toStdString());
    ScanningCampaing scan(database.toStdString(),experiment.toStdString(), 0);
    scan.init();
    scan.prepareIRD();

    // sumatorio de APs en min
    double minAPsum = 0;

    // APs promedio encontrados con min
    double APmin = 0;

    // sumatorio de APs en min
    double maxAPsum = 0;

    // APs promedio encontrados con min
    double APmax = 0;

    // valor del indice para el gen
    double fonc = 0;

    for (int i=0; i<30; i++)
    {
        // (ch, min, 0) corresponde a los APs encontrados con minchanneltime
        minAPsum = minAPsum + scan.getAPs(channel, minChannelTime, 0);
    }
    APmin = minAPsum/30;

    for (int i=0; i<30; i++)
    {
        // (ch, min, max) corresponde a los APs encontrados con maxchanneltime
        maxAPsum = maxAPsum + scan.getAPs(channel, minChannelTime, maxChannelTime);
    }
    APmax = maxAPsum/30;

    if (index == 0)
    {
        // si maxChannelTime es cero no se suman los aps encontrados con max
        if (maxChannelTime ==0)
        {
            fonc = (APmin/minChannelTime);
        }
        else
        {
            fonc = (APmin/minChannelTime)*0.2 + (std::abs(APmax-APmin)/maxChannelTime)*0.8;
        }
    }
    else if (index == 1)
    {
        // si maxChannelTime es cero no se suman los aps encontrados con max
        if (maxChannelTime ==0)
        {
            fonc = (APmin/minChannelTime);
        }
        else
        {
            fonc = (APmin/minChannelTime)*0.4 + (std::abs(APmax-APmin)/maxChannelTime)*0.6;
        }
    }
    else // index == 2
    {
        // si maxChannelTime es cero no se suman los aps encontrados con max
        if (maxChannelTime ==0)
        {
            fonc = (APmin/minChannelTime);
        }
        else
        {
            //fonc = (APmin/minChannelTime)*0.6 + (std::abs(APmax-APmin)/maxChannelTime)*0.4;

            // para prueba de simulation200gFONC 0.7 y 0.3
            fonc = (APmin/minChannelTime)*0.7 + (std::abs(APmax-APmin)/maxChannelTime)*0.3;
        }
    }
    return fonc;
}
/**
 * @brief Programa para obtener el numero de APs que se descubriria dada una secuencia de canales
 * y sus respectivos temporizadores MinChannelTime y MaxChannelTime.
 * @param argc cantidad de argumentos del programa
 * @param argv lista de argumentos
 * @return
 *
 * Para ejecutar:
 * ./test_getap_for_sequence <DATABASE> <EXPERIMENT> <SEQUENCEFILE>
 *
 * DATABASE: base de datos de scanning
 * EXPERIMENT: tipo de experimento utilizado en la campaña de scanning
 * SEQUENCEFILE: ruta absoluta al archivo de texto que posee la secuencia
 *
 */
int main(int argc, char ** argv) {

  if (argc != 4) {
    std::cerr << argv[0] << " <DATABASE> <EXPERIMENT> <SEQUENCEFILE> " << std::endl;
    // std::cerr << argv[0] << " <DATABASE> <EXPERIMENT> <chan seq> <MinCT list> <MaxCT list>" << std::endl;
    return 1;
  }

  ScanningCampaing scan(argv[1], argv[2]);
  scan.init();

  scan.prepareIRD();

  // vector de canales de la secuencia
  std::vector<int> channelList;

  // vector de MinChannelTime de la secuencia
  std::vector<int> minChannelTimeList;

  // vector de MaxChannelTime de la secuencia
  std::vector<int> maxChannelTimeList;

  // linea de la secuencia
  std::string line;

  // archivo de la secuencia
  std::ifstream myfile (argv[3]);

  if (myfile.is_open()) {

      getline (myfile,line);
      std::cout << line << std::endl;

      std::vector<std::string> tokens;
      std::istringstream f(line);
      std::string s;
      while (getline(f, s, ',')) {
          //std::cout << s << std::endl;
          tokens.push_back(s);
      }
      printf("numero de parametros de la secuencia: %d \n", tokens.size());
      int sequenceLength = tokens.size()/3;
      printf("sequenceLength: %d \n", sequenceLength);

      for (int i=0; i<sequenceLength; i++) {

          //printf("canal: %d \n", stoi(tokens.at(i*3)));
          //printf("min: %d \n", stoi(tokens.at(i*3+1)));
          //printf("max: %d \n", stoi(tokens.at(i*3+2)));


          channelList.push_back(std::stoi(tokens.at(i*3)));
          minChannelTimeList.push_back(std::stoi(tokens.at(i*3+1)));
          maxChannelTimeList.push_back(std::stoi(tokens.at(i*3+2)));
      }


      printf("canales: ");
      for (int j=0; j<channelList.size(); j++) {
          printf("%d ", channelList.at(j));
      }
      printf("\n");

      printf("min: ");
      for (int j=0; j<minChannelTimeList.size(); j++) {
          printf("%d ", minChannelTimeList.at(j));
      }
      printf("\n");

      printf("max: ");
      for (int j=0; j<maxChannelTimeList.size(); j++) {
          printf("%d ", maxChannelTimeList.at(j));
      }
      printf("\n");


      int aps = scan.getAPsForSequence(channelList, minChannelTimeList, maxChannelTimeList);
      printf("numero de aps descubiertos por la cadena: %d \n", aps);

      printf("**************************************************\n");
/*
      aps = 0;
      int sum = 0;
      for (int j=0; j<30; j++) {
          aps = scan.getAPsForSequence(channelList, minChannelTimeList, maxChannelTimeList);
          printf("%d,", aps);
          sum = sum + aps;
      }
      printf("\npromedio de APs en 30 ejecuciones: %d \n", sum/30);
*/
      myfile.close();
  }
  else {
      std::cout << "Unable to open file with sequence\n";
      return 1;
  }

  return 0;
}
Example #28
0
void loop() {
  scan();
  report_update();
}
Example #29
0
cloud_normal_t::Ptr
read_scan_with_normals(e57::Reader& reader, uint32_t scan_index,
                       const Eigen::Vector3d& demean_offset) {
    e57::Data3D header;
    reader.ReadData3D(scan_index, header);
    int64_t nColumn = 0, nRow = 0, nPointsSize = 0, nGroupsSize = 0,
            nCounts = 0;
    bool bColumnIndex = 0;
    reader.GetData3DSizes(scan_index, nRow, nColumn, nPointsSize, nGroupsSize,
                          nCounts, bColumnIndex);

    int64_t n_size = (nRow > 0) ? nRow : 1024;

    double* data_x = new double[n_size], * data_y = new double[n_size],
            * data_z = new double[n_size];
    double* nrm_x = new double[n_size], * nrm_y = new double[n_size],
            * nrm_z = new double[n_size];
    int8_t valid_normals = 0;
    auto block_read = reader.SetUpData3DPointsData(
        scan_index, n_size, data_x, data_y, data_z, NULL, NULL, NULL, NULL,
        NULL, NULL, NULL, nrm_x, nrm_y, nrm_z, &valid_normals);

    Eigen::Affine3d rotation;
    rotation =
        Eigen::Quaterniond(header.pose.rotation.w, header.pose.rotation.x,
                           header.pose.rotation.y, header.pose.rotation.z);
    Eigen::Affine3d registration;
    registration = Eigen::Translation<double, 3>(
                       header.pose.translation.x + demean_offset[0],
                       header.pose.translation.y + demean_offset[1],
                       header.pose.translation.z + demean_offset[2]) *
                   rotation;
    Eigen::Affine3d normal_transformation;
    normal_transformation = rotation.matrix().inverse().transpose();

    unsigned long size = 0;
    cloud_normal_t::Ptr scan(new cloud_normal_t());
    while ((size = block_read.read()) > 0) {
        for (unsigned long i = 0; i < size; i++) {
            point_normal_t p;
            Eigen::Vector3d pos(data_x[i], data_y[i], data_z[i]);
            pos = registration * pos;
            p.x = static_cast<float>(pos[0]);
            p.y = static_cast<float>(pos[1]);
            p.z = static_cast<float>(pos[2]);
            Eigen::Vector3d nrm(nrm_x[i], nrm_y[i], nrm_z[i]);
            nrm = normal_transformation * nrm;
            p.normal[0] = static_cast<float>(nrm[0]);
            p.normal[1] = static_cast<float>(nrm[1]);
            p.normal[2] = static_cast<float>(nrm[2]);
            scan->push_back(p);
        }
    }
    block_read.close();

    delete[] data_x;
    delete[] data_y;
    delete[] data_z;
    delete[] nrm_x;
    delete[] nrm_y;
    delete[] nrm_z;

    // get origin position
    scan->sensor_origin_ =
        Eigen::Vector4f(header.pose.translation.x + demean_offset[0],
                        header.pose.translation.y + demean_offset[1],
                        header.pose.translation.z + demean_offset[2], 1.0);

    return scan;
}
Example #30
0
void CreateCadTesselation::operate()
{
  double preview_memory = min(1024*1024*100.0, m_ScanMemory);
  int N = int(pow(preview_memory/sizeof(float), 1.0/3.0));
  m_Ni = N;
  m_Nj = N;
  m_Nk = N;
  m_X1 = vec3_t(-1e6,-1e6,-1e6);
  m_X2 = vec3_t( 1e6, 1e6, 1e6);
  m_Dx = (m_X2[0] - m_X1[0])/(m_Ni-1);
  m_Dy = (m_X2[1] - m_X1[1])/(m_Nj-1);
  m_Dz = (m_X2[2] - m_X1[2])/(m_Nk-1);
  double new_vol, old_vol;
  int count = 0;
  do {
    old_vol = (m_X2[0]-m_X1[0])*(m_X2[1]-m_X1[1])*(m_X2[2]-m_X1[2]);
    QString num;
    QString text = "scanning (V=";
    num.setNum(old_vol);
    text += num + ")";

    GuiMainWindow::pointer()->resetProgress(text, 3*N*N);
    scan(false);
    if (m_GeometryFound) {
      m_X1 = m_XScan1 - 2*vec3_t(m_Dx, m_Dy, m_Dz);
      m_X2 = m_XScan2 + 2*vec3_t(m_Dx, m_Dy, m_Dz);
    } else {
      m_X1 *= 0.1;
      m_X2 *= 0.1;
    }
    new_vol = (m_X2[0]-m_X1[0])*(m_X2[1]-m_X1[1])*(m_X2[2]-m_X1[2]);
  } while (count < 20 && (old_vol - new_vol)/old_vol > 0.05);

  // bounding box should now be established
  // last scan run with the full resoluion (if required)
  double Lx = m_X2[0] - m_X1[0];
  double Ly = m_X2[1] - m_X1[1];
  double Lz = m_X2[2] - m_X1[2];
  double max_size = m_ScanMemory/sizeof(float);
  double delta = max(m_SmallestResolution, pow(Lx*Ly*Lz/max_size, 1.0/3.0));
  int interlaces = 0;
  if (preserveFluid() || preserveSolid()) {
    interlaces = int(2*delta/m_SmallestFeatureSize);
  }
  m_Ni = int(Lx/delta) + 1;
  m_Nj = int(Ly/delta) + 1;
  m_Nk = int(Lz/delta) + 1;
  QString num;
  QString text = "scanning (h=";
  num.setNum(delta/(interlaces+1));
  text += num + ")";
  GuiMainWindow::pointer()->resetProgress(text, m_Ni*m_Nj + m_Ni*m_Nk + m_Nj*m_Nk);
  scan(true, interlaces);

  updateNodeIndex(m_Grid);
  updateCellIndex(m_Grid);
  GuiMainWindow::pointer()->resetXmlDoc();
  GuiMainWindow::pointer()->clearBCs();
  GuiMainWindow::pointer()->setBC(1, BoundaryCondition("imported", "patch", 1));

  GuiMainWindow::pointer()->resetProgress(" ", 100);
}