Lng32 CliGlobals::setEnvVar(const char * name, const char * value, NABoolean reset) { if ((! name) || (! value) || (isESPProcess_)) return 0; NABoolean found = FALSE; Lng32 envvarPos = -1; if (ComRtGetEnvValueFromEnvvars((const char**)envvars_, name, &envvarPos)) found = TRUE; if ((NOT found) && (reset)) return 0; Int32 nEnvs = 0; if (envvars_) { for (nEnvs=0; envvars_[nEnvs]; nEnvs++); } if (reset) { // nEnvs--; } else if (NOT found) { envvarPos = nEnvs; nEnvs++; } // one extra entry, if envvar not found. // one extra to null terminate envvar list. // long envvarsLen = (nEnvs + (NOT found ? 1 : 0) + 1) * sizeof(char*); Lng32 newEnvvarsLen = (nEnvs + 1) * sizeof(char*); Int32 count; for (count=0; count < nEnvs; count++) { if (count == envvarPos) // if ((found) && (count == envvarPos)) { if (NOT reset) newEnvvarsLen += strlen(name) + strlen("=") + strlen(value) + 1; } else newEnvvarsLen += str_len(envvars_[count])+1; } /* if (NOT found) { nEnvs++; newEnvvarsLen += strlen(name) + strlen("=") + strlen(value) + 1; } */ // allocate contiguous space for envvars char ** newEnvvars = (char**)(new(ipcHeap_) char[newEnvvarsLen]); char * newEnvvarsValue = (char*)(newEnvvars + ((reset ? (nEnvs-1) : nEnvs) + 1)); // and copy envvars_ to newEnvvars Int32 tgtCount = 0; for (count=0; count < nEnvs; count++) { newEnvvars[tgtCount] = newEnvvarsValue; Lng32 l = 0; if (count == envvarPos) { if (NOT reset) { strcpy(newEnvvarsValue, name); strcat(newEnvvarsValue, "="); strcat(newEnvvarsValue, value); l = strlen(name) + strlen("=") + strlen(value) + 1; tgtCount++; } } else { l = str_len(envvars_[count])+1; str_cpy_all(newEnvvarsValue, envvars_[count], l); tgtCount++; } newEnvvarsValue = newEnvvarsValue + l; } if (reset) { nEnvs--; } newEnvvars[nEnvs] = 0; if (envvars_) { // deallocate the current set of envvars ipcHeap_->deallocateMemory(envvars_); envvars_ = NULL; } envvars_ = newEnvvars; // set or reset this envvar in SessionDefaults. SessionEnvvar * se = new(ipcHeap_) SessionEnvvar(ipcHeap_, (char*)name, (char*)value); // remove if an entry exists currContext()->getSessionDefaults()->sessionEnvvars()->remove(*se); // insert a new entry, if this is not a RESET operation. if (NOT reset) { currContext()->getSessionDefaults()->sessionEnvvars()->insert(*se); } delete se; // also set it in IpcEnvironment so it could be used to send // it to mxcmp. getEnvironment()->setEnvVars(envvars_); getEnvironment()->setEnvVarsLen(newEnvvarsLen); envvarsContext_++; #ifdef NA_CMPDLL // need to set the env to the embedded compiler too if (currContext()->isEmbeddedArkcmpInitialized()) { currContext()->getEmbeddedArkcmpContext() ->setArkcmpEnvDirect(name, value, reset); } #endif // NA_CMPDLL return sendEnvironToMxcmp(); }
void SystemInterpreter::restoreEnvironment( void *CurrentEnv) /* saved environment */ { char *current; /* ptr to saved environment */ size_t size; /* size of the saved space */ size_t length; /* string length */ char *begin; /* begin of saved space */ char **Environment; /* environment pointer */ char *del = NULL; /* ptr to old unused memory */ char *Env_Var_String; /* enviornment entry */ char namebufsave[256],namebufcurr[256]; char *np; int i; Environment = getEnvironment(); /* get the current environment*/ begin = current = (char *)CurrentEnv;/* get the saved space */ size = ((ENVENTRY*)current)->size; /* first read out the size */ current += sizeof(size_t); /* update the pointer */ if (chdir(current) == -1) /* restore the curr dir */ { char msg[1024]; sprintf(msg, "Error restoring current directory: %s", current); reportException(Error_System_service_service, msg); } current += strlen(current); /* update the pointer */ current++; /* jump over '\0' */ if (!putflag) { /* first change in the */ /* environment ? */ /* copy all entries to dynamic memory */ /*for all entries in the env */ for (;*Environment != NULL;Environment++) { length = strlen(*Environment)+1; /* get the size of the string */ /* and alloc space for it */ Env_Var_String = (char *)malloc(length); memcpy(Env_Var_String,*Environment,length);/* copy the string */ putenv(Env_Var_String); /* and make it part of env */ } putflag = 1; /* prevent do it again */ } /* Loop through the saved env */ /* entries and restore them */ for (;(size_t)(current-begin)<size;current+=(strlen(current)+1)) { Environment = getEnvironment(); /* get the environment */ del = NULL; np = current; /* extract the the name */ /* from the saved enviroment */ for (i=0;(*np!='=')&&(i<255);np++,i++) { memcpy(&(namebufsave[i]),np,1); /* copy the character */ } memcpy(&(namebufsave[i]),"\0",1); /* copy the terminator */ /* find the entry in the env */ for (;*Environment != NULL;Environment++) { np = *Environment; /* extract the the name */ /* from the current env */ for (i=0;(*np!='=')&&(i<255);np++,i++) { memcpy(&(namebufcurr[i]),np,1);/* copy the character */ } memcpy(&(namebufcurr[i]),"\0",1);/* copy the terminator */ if (!strcmp(namebufsave,namebufcurr)) {/* have a match ? */ del = *Environment; /* remember it for deletion */ break; /* found, so get out of here */ } } if (putenv(current) == -1) { reportException(Error_System_service_service, "Error restoring environment variable"); } if (del) /* if there was an old entry */ { free(del); /* free it */ } } }
int main(int argc, char **argv) { int /*ch, */ i, ii, ret, err_flag = 0; clock_t beg, end, Beg, End; int files = 0; struct tms ts; char buf[256]; char *e; prgname = strrchr(argv[0], '/'); if (prgname) prgname++; else prgname = argv[0]; e = getenv("CLIP_HOSTCS"); if (e && *e) { sourceCharset = targetCharset = strdup(e); } else if (!e) { e = getenv("CLIP_LANG"); if (e == NULL) e = getenv("LANG"); if (!e || !*e || !strcmp(e, "C")) e = getenv("LC_MESSAGES"); if (!e || !*e || !strcmp(e, "C")) e = getenv("LC_ALL"); if (e && *e) { char *s = strrchr(e, '.'); if (s) { snprintf(buf, sizeof(buf), "%s", s + 1); for (s = buf; *s; s++) *s = tolower(*s); sourceCharset = targetCharset = strdup(buf); } } } { e = getenv("CLIP_LANG"); if (e == NULL) e = getenv("LANG"); if (!e || !*e || !strcmp(e, "C")) e = getenv("LC_MESSAGES"); if (!e || !*e || !strcmp(e, "C")) e = getenv("LC_ALL"); if (e && *e) { char *s = strrchr(e, '.'); if (s) { snprintf(buf, sizeof(buf), "%s", s + 1); for (s = buf; *s; s++) *s = tolower(*s); out_charset = strdup(buf); } } } { char *locale; locale = getenv("CLIP_LANG"); if (!locale || !*locale) locale = getenv("LANG"); /*if (locale && *locale && strcasecmp(locale, "C") && strcasecmp(locale, "POSIX")) */ /* setlocale(LC_ALL, locale); */ } if (!sourceCharset) sourceCharset = targetCharset = strdup("c"); getEnvironment(); init_Coll(&includePaths, NULL, NULL); init_Coll(&lib_dirs, NULL, NULL); init_Coll(&arglibs, NULL, NULL); #if 1 insert_Coll(&includePaths, "."); snprintf(buf, sizeof(buf), "%s/include", CLIPROOT); insert_Coll(&includePaths, strdup(buf)); #ifdef STD_LIBDIR snprintf(buf, sizeof(buf), STD_LIB_DIR); insert_Coll(&lib_dirs, strdup(buf)); #endif snprintf(buf, sizeof(buf), "%s/lib", CLIPROOT); insert_Coll(&lib_dirs, strdup(buf)); #endif init_Coll(&predefines, NULL, NULL); init_Coll(&poName, NULL, NULL); init_Coll(&paName, NULL, NULL); init_Coll(&include_files, NULL, NULL); snprintf(buf, sizeof(buf), "__CLIP__=\"%s\"", CLIP_VERSION); append_Coll(&predefines, strdup(buf)); init_module(); { char buf[256], *s; s = getenv("HOME"); if (s && *s) { snprintf(buf, sizeof(buf), "%s/.cliprc", s); getrc(buf); } } getrc(".cliprc"); { char buf[256], *s; DIR *dp; s = CLIPROOT; if (s && *s) { snprintf(buf, sizeof(buf), "%s/.cliprc", s); getrc(buf); } snprintf(buf, sizeof(buf), "%s/cliprc", CLIPROOT); dp = opendir(buf); if (dp) { struct dirent *ep; struct stat st; Coll files; int i; init_Coll(&files, free, strcmp); while ((ep = readdir(dp))) { snprintf(buf, sizeof(buf), "%s/cliprc/%s", CLIPROOT, ep->d_name); if (stat(buf, &st)) continue; if (!S_ISREG(st.st_mode)) continue; if (access(buf, R_OK)) continue; insert_Coll(&files, strdup(buf)); } closedir(dp); for (i = 0; i < files.count_of_Coll; i++) { char *name = (char *) files.items_of_Coll[i]; getrc(name); } destroy_Coll(&files); } } argc--; argv++; get_opt(argc, argv); argc -= optind; argv += optind; if (err_flag) return 1; #if 0 insert_Coll(&includePaths, "."); snprintf(buf, sizeof(buf), "%s/include", CLIPROOT); insert_Coll(&includePaths, strdup(buf)); #ifdef STD_LIBDIR snprintf(buf, sizeof(buf), STD_LIBDIR); insert_Coll(&lib_dirs, strdup(buf)); #endif snprintf(buf, sizeof(buf), "%s/lib", CLIPROOT); insert_Coll(&lib_dirs, strdup(buf)); #endif if (syntax_tree_flag) { write_obj_flag = 0; codegen_flag = 1; compile_flag = 0; pcode_flag = 0; pc_flag = 0; asm_flag = 0; exec_flag = 0; } if (!write_obj_flag) { /*codegen_flag = 0; */ compile_flag = 0; } if (preproc_flag) { write_obj_flag = 0; codegen_flag = 0; syntax_tree_flag = 0; compile_flag = 0; exec_flag = 0; pcode_flag = 0; pc_flag = 0; asm_flag = 0; shared_flag = 0; } if (pcode_flag) { pc_flag = 0; asm_flag = 0; shared_flag = 0; } if (pc_flag) { pcode_flag = 1; #ifdef USE_AS if (use_asm) asm_flag = 1; else asm_flag = 0; #endif } if (xpc_flag) { pcode_flag = 1; pc_flag = 1; #ifdef USE_AS if (use_asm) asm_flag = 0; else asm_flag = 1; #endif } #if 0 if (shared_flag && pcode_flag) { v_printf(0, "conflict between -s and -p flags\n"); exit(1); } #endif if (pcode_flag && c_flag) { v_printf(0, "conflict between -c and -p flags\n"); exit(1); } /*if ( exec_flag && !main_flag && !shared_flag) { v_printf(0, "-e(xec) flag without -M(ain) or -s(hared) flags\n"); exit(2); } */ if (pcode_flag) { compile_flag = 0; } if (nomain_flag && main_flag) { v_printf(0, "conflict between -n and -m flags\n"); exit(1); } if (!exec_flag && oname) { char *e; if (oname[0] == '/') snprintf(buf, sizeof(buf), "%s", oname); else snprintf(buf, sizeof(buf), "%s%s%s", outdir ? outdir : "", outdir ? "/" : "", oname); e = strrchr(buf, '/'); if (e) { *e = 0; outdir = strdup(buf); } } if (!outdir) outdir = "."; if (outdir) { char cdir[256]; getcwd(cdir, sizeof(cdir)); if (!chdir(outdir)) { getcwd(buf, sizeof(buf)); outdir = strdup(buf); chdir(cdir); } else { yyerror("cannot change to output dir '%s': %s", outdir, strerror(errno)); exit(1); } } if (!preproc_flag) { v_printf(2, "set source charset to %s\n", sourceCharset); v_printf(2, "set target charset to %s\n", targetCharset); } init_lex(); init_parser(); if (argc < 1) ii = -1; else ii = 0; Beg = times(&ts); if (argc > 0) { for (i = 0; i < argc; i++) { char *e; e = argv[i]; if (e[0] == '-' && e[1] == 'L') { insert_Coll(&lib_dirs, strdup(e + 2)); continue; } e = strrchr(argv[i], '.'); if (!e) { e = argv[i]; if (e[0] == '-' && e[1] == 'l') /*append_Coll(&arglibs, strdup(e+2)) */ ; else yyerror("unknown file type '' file '%s'", argv[i]); continue; } else if (!strcasecmp(e, ".po")) insert_Coll(&poName, strdup(argv[i])); else if (!strcasecmp(e, ".pa")) insert_Coll(&paName, strdup(argv[i])); else if (strcasecmp(e, ".prg") && strcasecmp(e, ".c") && strcasecmp(e, ".cc") && strcasecmp(e, OBJSUF) && strcasecmp(e, SOBJSUF) && strcasecmp(e, ".a") && strcasecmp(e, ".lib")) { /*yywarning("unknown file type '%s' file '%s'", e, argv[i]); */ continue; } } } for (; clic_errorcount == 0 && ii < argc; ii++) { ++files; if (ii < 0) { v_printf(1, "no input files, so use stdin; -h will help\n"); fflush(stderr); set_locale_name("stdin"); ret = clic_parse("stdin", stdin); add_name("stdin"); } else { char *e; e = strrchr(argv[ii], '.'); add_name(argv[ii]); if (!e) continue; else if (!strcasecmp(e, ".c") || !strcasecmp(e, ".cc") || !strcasecmp(e, ".cpp")) { if (!preproc_flag) { v_printf(1, "process file '%s' ..", argv[ii]); v_neednl = 1; } beg = times(&ts); compile_CFile(argv[ii]); end = times(&ts); if (!preproc_flag) { v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(1); } continue; } else if (strcasecmp(e, ".prg")) { continue; } if (ii > 0) main_flag = 0; if (!preproc_flag) { v_printf(1, "parsing file '%s' ..", argv[ii]); v_neednl = 1; } beg = times(&ts); set_locale_name(argv[ii]); ret = clic_parse(argv[ii], 0); end = times(&ts); if (!preproc_flag) { v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done (%d/%d %s, %d %s, %s)\n", clic_line, all_lines, _clic_ngettext("line", "lines", clic_line), clic_warncount, _clic_ngettext("warning", "warnings", clic_warncount), diff_clock(beg, end)); else vr_printf(1, "%d %s, %d %s\n", clic_errorcount, _clic_ngettext("error", "errors", clic_errorcount), clic_warncount, _clic_ngettext("warning", "warnings", clic_warncount)); } } if (ret) break; if (clic_errorcount == 0 && codegen_flag) { v_printf(2, "codegen file '%s' ..", curFile->name_of_File); v_neednl = 1; beg = times(&ts); codegen_File(curFile); end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(2, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(2); } if (clic_errorcount == 0 && syntax_tree_flag) { print_File(curFile); } if (clic_errorcount == 0 && write_obj_flag) { if (pcode_flag) { long len; v_printf(1, "writing file '%s' ..", curFile->s_cname_of_File); v_neednl = 1; beg = times(&ts); write_OFile(curFile, &len); write_names(curFile); end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %ld %s ,%s\n", len, _clic_ngettext("byte", "bytes", len), diff_clock(beg, end)); else pr_errorcount(1); } else { v_printf(2, "writing file '%s' ..", curFile->s_cname_of_File); v_neednl = 1; write_File(curFile); write_names(curFile); v_neednl = 0; if (clic_errorcount == 0) v_printf(2, ".. done\n"); else pr_errorcount(2); } } if (clic_errorcount == 0 && (compile_flag || pc_flag)) { if (ii) main_flag = 0; v_printf(1, "compile file '%s' ..", curFile->s_cname_of_File); v_neednl = 1; beg = times(&ts); compile_File(curFile->cname_of_File); end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(1); if (clic_errorcount == 0 && shared_flag && !exec_flag) { v_printf(1, "make shared object '%s' ..", curFile->s_cname_of_File); v_neednl = 1; beg = times(&ts); share_File(curFile->cname_of_File); end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(1); } } if (ii < 0) break; delete_File(curFile); curFile = NULL; } if (clic_errorcount == 0 && exec_flag) { char cmd[1024 * 8], *e; char cfuncname[256], ofuncname[256]; char *libroot; int i; Coll ex, nm; init_Coll(&ex, free, strcasecmp); init_Coll(&nm, free, strcasecmp); #ifdef STD_LIBDIR libroot = 0; #else libroot = CLIPROOT; #endif ++files; #ifdef STD_LIBDIR if (eshared_flag || shared_flag) { snprintf(cmd, sizeof(cmd), "-lclip"); add_name(cmd); } else #endif { e = (eshared_flag || shared_flag) ? CLIPSLIB : CLIPLIB; lib_name(cmd, sizeof(cmd), libroot, "lib", e, strlen(e)); add_name(cmd); } for (e = CLIPLIBS; *e;) { int l; l = strspn(e, " \t"); e += l; l = strcspn(e, " \t"); if (!l) break; lib_name(cmd, sizeof(cmd), libroot, "lib", e, l); add_name(cmd); e += l; } for (e = ADDLIBS; *e;) { int l; l = strspn(e, " \t"); e += l; l = strcspn(e, " \t"); if (!l) break; memcpy(cmd, e, l); cmd[l] = 0; add_name(cmd); e += l; } add_name(MATHLIB); add_name(DLLIB); /* generate _cfunctions */ if (asm_flag) sprintf(cfuncname, "%s_ref.s", oname); else sprintf(cfuncname, "%s_ref.c", oname); sprintf(ofuncname, "%s_ref.o", oname); v_printf(1, "generate reference file '%s' ..", cfuncname); v_neednl = 1; beg = times(&ts); write_Cfunc(cfuncname, onum, ovect, &ex, &nm); check_names(&ex, &nm); end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(1); if (clic_errorcount) goto end; v_printf(1, "compile file '%s' ..", cfuncname); v_neednl = 1; beg = times(&ts); compile_File(cfuncname); end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(1); #ifdef USE_LD if (use_asm && (shared_flag || eshared_flag)) { int ll; const char *ld_prg, *ld_end; if (shared_flag || eshared_flag) { ld_prg = LD_PRG; ld_end = LD_END; } else { ld_prg = LDS_PRG; ld_end = LDS_END; } snprintf(cmd, sizeof(cmd), "%s", ld_prg); ll = strlen(cmd); for (e = cmd + ll, i = 0; i < lib_dirs.count_of_Coll; ++i) { snprintf(e, sizeof(cmd) - ll, " -L%s", (char *) lib_dirs.items_of_Coll[i]); ll = strlen(cmd); e = cmd + ll; } ll = strlen(cmd); snprintf(cmd + ll, sizeof(cmd) - ll, " %s %s %s -o %s", optLevel ? COPT : "", genDebug ? CDBG : "", ofuncname, oname); ll = strlen(cmd); for (e = cmd + ll, i = 0; i < onum; ++i) { snprintf(e, sizeof(cmd) - ll, " %s", ovect[i]); ll = strlen(cmd); e = cmd + ll; } ll = strlen(cmd); snprintf(cmd + ll, sizeof(cmd) - ll, " %s", ld_end); } else #endif { sprintf(cmd, "%s", CC); for (e = cmd + strlen(cmd), i = 0; i < includePaths.count_of_Coll; ++i) { sprintf(e, " %s %s", INCLUDE_FLAG, (char *) includePaths.items_of_Coll[i]); e = cmd + strlen(cmd); } for (e = cmd + strlen(cmd), i = 0; i < lib_dirs.count_of_Coll; ++i) { sprintf(e, " -L%s", (char *) lib_dirs.items_of_Coll[i]); e = cmd + strlen(cmd); } sprintf(cmd + strlen(cmd), " %s %s %s %s %s %s %s", optLevel ? COPT : "", genDebug ? CDBG : "", CFLAGS, ADDCFLAGS, ofuncname, OUT_FLAG, oname); for (e = cmd + strlen(cmd), i = 0; i < onum; ++i) { sprintf(e, " %s", ovect[i]); e = cmd + strlen(cmd); } } v_printf(1, "make file '%s' ..", oname); v_neednl = 1; beg = times(&ts); v_printf(2, "%s\n", cmd); if (system(cmd)) yyerror("C level error in command: %s", cmd); else if (rmc_flag) { unlink(cfuncname); unlink(ofuncname); } end = times(&ts); v_neednl = 0; if (clic_errorcount == 0) v_printf(1, ".. done, %s\n", diff_clock(beg, end)); else pr_errorcount(1); } end: End = times(&ts); resume_parser(); resume_lex(); resume_locale(); if (!preproc_flag) v_printf(1, "clip: %d %s, %s\n", files, _clic_ngettext("file", "files", files), diff_clock(Beg, End)); return clic_errorcount == 0 ? 0 : 1; }
void MeshWSN::print(void) { printf("STATS:-----------------------------------------------------\n"); printf("Transmits: %d\n", mTXs); printf("Avg. RX per TX: %f\n", double(mRXs) / mTXs); printf("Corruption rate: %.2f%%\n", 100.0 * double(mCorrupted) / mRXs); printf("Cluster heads: %d\n", mCHs); printf("Cluster head rate: %f\n", double(mCHs) / getDeviceCount()); uint32_t loners = 0; std::vector<ClusterMeshDev*> clusterHeads; for (Device* pDev : mDevices) { ClusterMeshDev* pMDev = (ClusterMeshDev*)pDev; if (pMDev->mNeighbors.size() == 0) ++loners; if (pMDev->isCH()) clusterHeads.push_back(pMDev); } printf("Loners: %d\n", loners); struct ch { ClusterMeshDev* pCH; uint32_t conns; }; std::vector<struct ch> clusterHeadSubscribers(clusterHeads.size()); uint32_t symmetric = 0; for (connection_t& conn : mConnections) { if (conn.symmetric) symmetric++; ClusterMeshDev* chsInConn[] = { (ClusterMeshDev*)conn.pFirst, (ClusterMeshDev*)conn.pSecond }; for (uint8_t i = 0; i < 2; ++i) { if (chsInConn[i]->isCH()) { bool exists = false; for (struct ch& chs : clusterHeadSubscribers) { if (chs.pCH == chsInConn[i]) { chs.conns++; exists = true; break; } } if (!exists) clusterHeadSubscribers.push_back({ chsInConn[i], 1 }); } } } struct ch *pMaxCh=NULL; uint32_t totalCHSubs = 0; for (struct ch& chs : clusterHeadSubscribers) { if (pMaxCh == NULL || chs.conns > pMaxCh->conns) pMaxCh = &chs; totalCHSubs += chs.conns; } printf("Symmetric connection rate: %.2f%%\n", 100.0 * double(symmetric) / mConnections.size()); printf("Max CH subs: %d\n", pMaxCh->conns); printf("Useless CHs: %d\n", clusterHeadSubscribers.size() - clusterHeads.size()); printf("Avg CH subs: %.2f\n", double(totalCHSubs) / clusterHeads.size()); double totalRadioDutyCycle = 0.0; for (Device* pDev : mDevices) { totalRadioDutyCycle += pDev->getRadio()->getTotalDutyCycle(); } printf("Average radio duty cycle: %.2f%%\n", totalRadioDutyCycle / double(mDevices.size()) * 100.0); double totPowerUsage = 0.0; double maxPowerUsage = 0.0; double minPowerUsage = 100000000.0; double peukert = 1.15; std::string minDev, maxDev; for (auto it = mDevices.begin(); it != mDevices.end(); it++) { double usage = (*it)->getPowerUsageAvg(MESH_STABILIZATION_TIME, getEnvironment()->getTimestamp(), peukert); // don't count the search totPowerUsage += usage; if (usage > maxPowerUsage) { maxPowerUsage = usage; maxDev = (*it)->mName; } if (usage < minPowerUsage) { minPowerUsage = usage; minDev = (*it)->mName; } } totPowerUsage *= (getEnvironment()->getTimestamp() - MESH_STABILIZATION_TIME) / float(HOURS); // mA -> mAh maxPowerUsage *= (getEnvironment()->getTimestamp() - MESH_STABILIZATION_TIME) / float(HOURS); // mA -> mAh minPowerUsage *= (getEnvironment()->getTimestamp() - MESH_STABILIZATION_TIME) / float(HOURS); // mA -> mAh printf("Avg power usage: %.5fmAh\n", totPowerUsage / mDevices.size()); printf("Max power usage: %.5fmAh\n", maxPowerUsage); printf("Min power usage: %.5fmAh\n", minPowerUsage); timestamp_t firstDeath = BATTERY_DRAINAGE_TIME_h * (pow(BATTERY_CAPACITY_mAh, peukert) / pow(maxPowerUsage * BATTERY_DRAINAGE_TIME_h, peukert)); // in hours timestamp_t lastDeath = BATTERY_DRAINAGE_TIME_h * (pow(BATTERY_CAPACITY_mAh, peukert) / pow(minPowerUsage * BATTERY_DRAINAGE_TIME_h, peukert)); // in hours printf("First dead node (%s): %d years, %d days and %d hours\n", maxDev.c_str(),uint32_t(firstDeath / (24ULL * 365ULL)), uint32_t((firstDeath / 24ULL) % 365ULL), uint32_t(firstDeath % 24ULL)); printf("Last dead node (%s): %d years, %d days and %d hours\n", minDev.c_str(), uint32_t(lastDeath / (24ULL * 365ULL)), uint32_t((lastDeath / 24ULL) % 365ULL), uint32_t(lastDeath % 24ULL)); }
virtual void articulation(const Task& task) { // The coordinate system at the hub. CoordinateSystem hubCoordinateSystem(getLink().getCoordinateSystem()); // Get the ground values in the hub coordinate system. GroundValues groundValues = getEnvironment().getGroundPlane(hubCoordinateSystem, task.getTime()); // Transform the plane equation to the local frame. Plane lp = groundValues.plane; // Get the intersection length. real_type distHubGround = fabs(lp.getDist()); Vector3 down = -copysign(1, lp.getDist())*lp.getNormal(); real_type compressLength = mWheelContact->getWheelRadius() - distHubGround; // Don't bother if we do not intersect the ground. if (compressLength < 0) return; Vector3 contactPoint = distHubGround*down; // The relative velocity of the ground wrt the contact point Vector6 relVel = getLink().getLocalVelocity() - groundValues.vel; // The velocity perpandicular to the plane. // Positive when the contact spring is compressed, // negative when decompressed. real_type compressVel = - lp.scalarProjectToNormal(relVel.getLinear()); // Get a transform from the current frames coordinates into // wheel coordinates. // The wheel coordinates x axis is defined by the forward orientation // of the wheel, the z axis points perpandicular to the ground // plane downwards. Vector3 forward = normalize(cross(mWheelContact->getAxis(), down)); Vector3 side = normalize(cross(down, forward)); // Transformed velocity to the ground plane Vector2 wheelVel(dot(forward, relVel.getLinear()), dot(side, relVel.getLinear())); // The wheel rotation speed wrt ground Vector3 rotVel = relVel.getAngular(); real_type omegaR = dot(rotVel, mWheelContact->getAxis()) * distHubGround; // Log(Model,Error) << trans(groundValues.vel) << " " // << trans(wheelVel) << " " // << omegaR << " " // << compressLength << " " // << distHubGround << std::endl; // Get the plane normal force. real_type normForce = mWheelContact->computeNormalForce(compressLength, compressVel, mPortValueList); // The normal force cannot get negative here. normForce = max(static_cast<real_type>(0), normForce); // Get the friction force. Vector2 fricForce = mWheelContact->computeFrictionForce(normForce, wheelVel, omegaR, groundValues.friction, mPortValueList); // The resulting force is the sum of both. // The minus sign is because of the direction of the surface normal. Vector3 force = fricForce(0)*forward + fricForce(1)*side - normForce*down; // We don't have an angular moment. getLink().applyBodyForce(contactPoint, force); }
void AdvDevice::start(void) { startAdv(getEnvironment()->getTimestamp(), NULL); }
void BulletSoftObject::destroy() { getEnvironment()->bullet->dynamicsWorld->removeSoftBody(softBody.get()); }
void Widget::removeFocus() { getEnvironment()->removeFocus( this ); }
OracleConnection::ObjectType OracleConnection::ReadSPDescriptionFromDB( const String &command, Anything &desc ) { StartTrace(OracleConnection.ReadSPDescriptionFromDB); String strErr( "ReadSPDescriptionFromDB: " ); MemChecker aCheckerLocal( "OracleConnection.ReadSPDescriptionFromDB", getEnvironment().getAllocator() ); MemChecker aCheckerGlobal( "OracleConnection.ReadSPDescriptionFromDB", coast::storage::Global()); sword attrStat; DscHandleType aDschp; if ( checkError( ( attrStat = OCIHandleAlloc( getEnvironment().EnvHandle(), aDschp.getVoidAddr(), OCI_HTYPE_DESCRIBE, 0, 0 ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("after HandleAlloc, local allocator:" << reinterpret_cast<long>(getEnvironment().getAllocator())); Trace("after HandleAlloc, global allocator:" << reinterpret_cast<long>(coast::storage::Global())); OCIParam *parmh( 0 ); ObjectType aStmtType = DescribeObjectByName(command, aDschp, parmh); if ( aStmtType == TYPE_SYN ) { Trace("as we identified a synonym, we need to collect the scheme name and the referenced object name to ask for description"); text *name(0); ub4 namelen(0); String strSchemaName; attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_SCHEMA_NAME, ErrorHandle() ); if ( checkError( ( attrStat ) ) ) { throw OracleException( *this, attrStat ); } strSchemaName.Append(String( (char *) name, namelen )); Trace("SchemaName: " << strSchemaName); attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_NAME, ErrorHandle() ); if ( checkError( ( attrStat ) ) ) { throw OracleException( *this, attrStat ); } if ( strSchemaName.Length() ) { strSchemaName.Append('.'); } strSchemaName.Append(String( (char *) name, namelen )); Trace("trying to get descriptions for " << strSchemaName); aStmtType = DescribeObjectByName(strSchemaName, aDschp, parmh); } bool bIsFunction = ( aStmtType == TYPE_FUNC ); Trace("get the number of arguments and the arg list for stored " << (bIsFunction ? "function" : "procedure")) OCIParam *arglst( 0 ); ub2 numargs = 0; if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) parmh, OCI_DTYPE_PARAM, (dvoid *) &arglst, (ub4 *) 0, OCI_ATTR_LIST_ARGUMENTS, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arglst, OCI_DTYPE_PARAM, (dvoid *) &numargs, (ub4 *) 0, OCI_ATTR_NUM_PARAMS, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace(String("number of arguments: ") << numargs); OCIParam *arg( 0 ); text *name; ub4 namelen; ub2 dtype; OCITypeParamMode iomode; ub4 data_len; // For a procedure, we begin with i = 1; for a function, we begin with i = 0. int start = 0; int end = numargs; if ( !bIsFunction ) { ++start; ++end; } for ( int i = start; i < end; ++i ) { if ( checkError( ( attrStat = OCIParamGet( (dvoid *) arglst, OCI_DTYPE_PARAM, ErrorHandle(), (dvoid **) &arg, (ub4) i ) ) ) ) { throw OracleException( *this, attrStat ); } namelen = 0; name = 0; data_len = 0; if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &dtype, (ub4 *) 0, OCI_ATTR_DATA_TYPE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("Data type: " << dtype) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &name, (ub4 *) &namelen, OCI_ATTR_NAME, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } String strName( (char *) name, namelen ); // the first param of a function is the return param if ( bIsFunction && i == start ) { strName = command; Trace("Name: " << strName) } // 0 = IN (OCI_TYPEPARAM_IN), 1 = OUT (OCI_TYPEPARAM_OUT), 2 = IN/OUT (OCI_TYPEPARAM_INOUT) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &iomode, (ub4 *) 0, OCI_ATTR_IOMODE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("IO type: " << iomode) if ( checkError( ( attrStat = OCIAttrGet( (dvoid *) arg, OCI_DTYPE_PARAM, (dvoid *) &data_len, (ub4 *) 0, OCI_ATTR_DATA_SIZE, ErrorHandle() ) ) ) ) { throw OracleException( *this, attrStat ); } Trace("Size: " << (int)data_len) Anything param( desc.GetAllocator() ); param["Name"] = strName; param["Type"] = dtype; param["Length"] = (int) data_len; param["IoMode"] = iomode; param["Idx"] = (long) ( bIsFunction ? i + 1 : i ); desc.Append( param ); if ( checkError( ( attrStat = OCIDescriptorFree( arg, OCI_DTYPE_PARAM ) ) ) ) { throw OracleException( *this, attrStat ); } }
/* Handle "export" command in same process */ bool sys_process_export(RexxExitContext *context, const char * cmd, RexxObjectPtr &rc, int flag) { char *Env_Var_String = NULL; /* Environment variable string for */ size_t size, allocsize; /* size of the string */ char **Environment; /* environment pointer */ char *np; size_t i,j,k,l,iLength, copyval; char namebufcurr[1281]; /* buf for extracted name */ char cmd_name[1281]; /* name of the envvariable setting */ char *array, *runarray, *runptr, *endptr, *maxptr; char temparray[1281]; const char *st; char *tmpptr; char name[1281]; /* is the name + value + = */ char value[1281]; /* is the part behind = */ char *del = NULL; /* ptr to old unused memory */ char *hit = NULL; bool HitFlag = false; l = 0; j = 0; allocsize = 1281 * 2; memset(temparray, '\0', sizeof(temparray)); Environment = getEnvironment(); /* get the environment */ if (flag == EXPORT_FLAG) { st = &cmd[6]; } else if (flag == UNSET_FLAG) { st = &cmd[5]; } else { st = &cmd[3]; } while ((*st) && (*st == ' ')) { st++; } strcpy(name, st); iLength = strlen(st) + 1; /* if string == EXPORT_FLAG or string == SET and only blanks are delivered */ if ( ((flag == EXPORT_FLAG) || (flag == SET_FLAG)) && (iLength == 1) ) { return false; } if (!putflag) { /* first change in the environment ? */ /* copy all entries to dynamic memory */ for (;*Environment != NULL; Environment++) { /*for all entries in the env */ size = strlen(*Environment)+1; /* get the size of the string */ Env_Var_String = (char *)malloc(size); /* and alloc space for it */ memcpy(Env_Var_String,*Environment,size);/* copy the string */ putenv(Env_Var_String); /* and chain it in */ } } putflag = 1; /* prevent do it again */ Environment = getEnvironment(); /* reset the environment pointer */ /* do we have a assignment operator? If not return true */ /* The operating system treads this like no command, and so do we */ if ( !(strchr(name, '=')) && (flag != UNSET_FLAG) ) /*only set and export */ { /* we do not have a assignment operator, but maybe a '|' for a */ /* controlled output */ if ( (strchr(name, '|')) || (strchr(name, '>')) || (strstr(name, ">>")) ) { return false; } else { // this worked ok (well, sort of) rc = context->False(); return true; } } /* no '=' for unset, so force a shell error message */ if ( (strchr(name, '=')) && (flag == UNSET_FLAG) ) { return false; } for (i=0;(name[i]!='=')&&(i<iLength);i++) { cmd_name[i] = name[i]; } /* lets try handling variables in the assignment string */ cmd_name[i] = '\0'; /* copy the terminator */ i++; /* the place after'=' */ /* lets search the value for variable part(s) */ strcpy(value, &(name[i])); /* value contains the part behind '=' */ array = (char *) malloc(1281); strcpy(array, cmd_name); array[strlen(cmd_name)] = '='; array[i] = '\0'; /* copy the terminator */ runarray = array + strlen(array); runptr = value; endptr = runptr + strlen(value); /*this is the end of the input*/ maxptr = array + MAX_VALUE -1; /* this is the end of our new string */ while ((tmpptr = (strchr(runptr, '$'))) != 0) { Environment = getEnvironment(); /* get the beginning of the environment*/ HitFlag = true; /* if not true inputvalue= outputvalue*/ copyval = tmpptr - runptr; if (copyval) /* runarray should keep the 'real' environment */ { while ((runarray + copyval) > maxptr) { array = (char *) realloc(array, allocsize); runarray = array + strlen(array); maxptr = array + allocsize - 1; allocsize = allocsize * 2; } memcpy(runarray,runptr, copyval); runarray= runarray + copyval; /* a new place to copy */ *runarray = '\0'; runptr = tmpptr; /* now runptr is at the place of $ */ } runptr++; for (j = 0;(*runptr != '/') && (*runptr != ':') && (*runptr != '$') && (*runptr); j++) { memcpy(&(temparray[j]), runptr,1); /*temparray is the env var to search*/ runptr++; } temparray[j] = '\0'; /* lets see what we can do */ np = NULL; for (;(*Environment != NULL) && (hit == NULL) ;Environment++) { np = *Environment; for (k=0;(*np!='=')&&(k<255);np++,k++) { memcpy(&(namebufcurr[k]),np,1); /* copy the character */ } namebufcurr[k] = '\0'; /* copy the terminator */ if (!strcmp(temparray,namebufcurr)) /* have a match ? */ { hit = *Environment; /* copy value to new string*/ } } if (hit) /* if we have found an entry of the env var in the env list */ { np ++; /* don't copy equal */ while ((runarray + strlen(np)) > maxptr) { array = (char *) realloc(array, allocsize); runarray = array + strlen(array); maxptr = array + allocsize - 1; allocsize = allocsize * 2; } strcpy(runarray, np); runarray = runarray + strlen(np); *runarray = '\0'; hit = NULL; } } if (HitFlag == true) { if (runptr < endptr) { while ((runarray + strlen(runptr)) > maxptr) { array = (char *) realloc(array, allocsize); runarray = array + strlen(array); maxptr = array + allocsize - 1; allocsize = allocsize * 2; } strcpy(runarray, runptr); /* if there is a part after a var */ runarray = runarray + strlen(runptr); *runarray = '\0'; } } else /* no hit so lets copy the value as it is */ { while ((runarray + strlen(value)) > maxptr) { array = (char *) realloc(array, allocsize); runarray = array + strlen(array); maxptr = array + allocsize - 1; allocsize = allocsize * 2; } strcpy(runarray,value); runarray = runarray + strlen(runptr); *runarray = '\0'; } Environment = getEnvironment(); /* get the beginning of the environment*/ for (;*Environment != NULL;Environment++) { np = *Environment; for (i=0;(*np!='=')&&(i<255);np++,i++) { memcpy(&(namebufcurr[i]),np,1); /* copy the character */ } namebufcurr[i] = '\0'; /* copy the terminator */ if (!strcmp(cmd_name,namebufcurr))/* have a match ? */ { del = *Environment; /* remember it for deletion */ } } /* find the entry in the environ */ if (flag != UNSET_FLAG) { size = strlen(array)+1; Env_Var_String = (char *)malloc(size);/* get the memory */ memcpy(Env_Var_String, array, size); int errCode = putenv(Env_Var_String); if (errCode != 0) { // non-zero is an error condition context->RaiseCondition("ERROR", context->String(cmd), NULL, context->WholeNumberToObject(errCode)); } else { rc = context->False(); } } if (del) /* if there was a old one */ { free(del); /* free it */ } rc = context->False(); return true; }
void Widget::setFocus() { getEnvironment()->setFocus( this ); }
void BulletObject::destroy() { getEnvironment()->bullet->dynamicsWorld->removeRigidBody(rigidBody.get()); }
void GrabberKinematicObject::releaseConstraint() { if (!constraint) return; getEnvironment()->bullet->dynamicsWorld->removeConstraint(constraint.get()); constraint.reset(); }
void init() { getEnvironment().init(); }
//! called if an event happened. bool MainMenu::onEvent(const NEvent& event) { if (isEnabled()) { switch(event.EventType) { case sEventGui: switch(event.GuiEvent.EventType) { case guiElementFocusLost: if (event.GuiEvent.Caller == this && !isMyChild(event.GuiEvent.Element)) { closeAllSubMenus_(); setHoverIndex_( -1 ); } break; case guiElementFocused: if (event.GuiEvent.Caller == this ) { bringToFront(); } break; default: break; } break; case sEventMouse: switch(event.MouseEvent.Event) { case mouseLbtnPressed: { if (!getEnvironment()->hasFocus(this)) { getEnvironment()->setFocus(this); } bringToFront(); Point p(event.MouseEvent.getPosition() ); bool shouldCloseSubMenu = hasOpenSubMenu_(); if (!getAbsoluteClippingRect().isPointInside(p)) { shouldCloseSubMenu = false; } isHighlighted_( event.MouseEvent.getPosition(), true); if ( shouldCloseSubMenu ) { getEnvironment()->removeFocus(this); } return true; } case mouseLbtnRelease: { Point p(event.MouseEvent.getPosition() ); if (!getAbsoluteClippingRect().isPointInside(p)) { int t = sendClick_(p); if ((t==0 || t==1) && isFocused()) removeFocus(); } return true; } case mouseMoved: { if (getEnvironment()->hasFocus(this) && getHoveredIndex() >= 0) { int oldHighLighted = getHoveredIndex(); isHighlighted_( event.MouseEvent.getPosition(), true); if ( getHoveredIndex() < 0 ) { setHoverIndex_( oldHighLighted ); // keep last hightlight active when moving outside the area } } return true; } default: break; } break; default: break; } } return Widget::onEvent(event); }
//! called if an event happened. bool MainMenu::onEvent(const NEvent& event) { if (isEnabled()) { switch(event.EventType) { case OC3_GUI_EVENT: switch(event.GuiEvent.EventType) { case OC3_ELEMENT_FOCUS_LOST: if (event.GuiEvent.Caller == this && !isMyChild(event.GuiEvent.Element)) { closeAllSubMenus_(); setHoverIndex_( -1 ); } break; case OC3_ELEMENT_FOCUSED: if (event.GuiEvent.Caller == this ) { bringToFront(); } break; default: break; } break; case OC3_MOUSE_EVENT: switch(event.MouseEvent.Event) { case OC3_LMOUSE_PRESSED_DOWN: { if (!getEnvironment()->hasFocus(this)) { getEnvironment()->setFocus(this); } bringToFront(); Point p(event.MouseEvent.getPosition() ); bool shouldCloseSubMenu = hasOpenSubMenu_(); if (!getAbsoluteClippingRect().isPointInside(p)) { shouldCloseSubMenu = false; } isHighlighted_( event.MouseEvent.getPosition(), true); if ( shouldCloseSubMenu ) { getEnvironment()->removeFocus(this); } return true; } case OC3_LMOUSE_LEFT_UP: { Point p(event.MouseEvent.getPosition() ); if (!getAbsoluteClippingRect().isPointInside(p)) { int t = sendClick_(p); if ((t==0 || t==1) && isFocused()) removeFocus(); } return true; } case OC3_MOUSE_MOVED: { if (getEnvironment()->hasFocus(this) && getHoveredIndex() >= 0) { int oldHighLighted = getHoveredIndex(); isHighlighted_( event.MouseEvent.getPosition(), true); if ( getHoveredIndex() < 0 ) { setHoverIndex_( oldHighLighted ); // keep last hightlight active when moving outside the area } } return true; } default: break; } break; default: break; } } return Widget::onEvent(event); }