void tm_frame_rep::menu_widget (string menu, widget& w) { object xmenu= eval ("'" * menu); w= make_menu_widget (xmenu); }
arma::mat FDHessian::hessian() { // Amount of parameters size_t npar=count_params(); // Compute gradient arma::mat h(npar,npar); h.zeros(); std::vector<loopidx_t> idx; for(size_t i=0;i<npar;i++) for(size_t j=0;j<=i;j++) { loopidx_t t; t.i=i; t.j=j; idx.push_back(t); } /* This loop isn't OpenMP parallel, because parallellization is already used in the energy evaluation. Parallellizing over trials here would require use of thread-local DFT grids, and possibly even thread-local SCF solver objects (for the Coulomb part).*/ for(size_t ii=0;ii<idx.size();ii++) { size_t i=idx[ii].i; size_t j=idx[ii].j; arma::vec x(npar); // RH,RH value x.zeros(); x(i)+=ss; x(j)+=ss; double yrr=eval(x,GHMODE); // RH,LH x.zeros(); x(i)+=ss; x(j)-=ss; double yrl=eval(x,GHMODE); // LH,RH x.zeros(); x(i)-=ss; x(j)+=ss; double ylr=eval(x,GHMODE); // LH,LH x.zeros(); x(i)-=ss; x(j)-=ss; double yll=eval(x,GHMODE); // Values h(i,j)=(yrr - yrl - ylr + yll)/(4.0*ss*ss); // Symmetrize h(j,i)=h(i,j); if(std::isnan(h(i,j))) { ERROR_INFO(); std::ostringstream oss; oss << "Element (" << i << "," << j << ") of Hessian gives NaN.\n"; oss << "Step size is " << ss << ". Stencil values\n"; oss << "yrr = " << yrr << "\n"; oss << "yrl = " << yrl << "\n"; oss << "ylr = " << ylr << "\n"; oss << "yll = " << yll << "\n"; throw std::runtime_error(oss.str()); } } return h; }
VOID relr3(void) { int mode; a_uint reli, relv; int aindex, rindex, rtp, error, i; a_uint r, rtbase, rtofst, paga = 0, pags = 0; struct areax **a; struct sym **s; int bmagic = 0; int mybank; /* * Get area and symbol lists */ a = hp->a_list; s = hp->s_list; /* * Verify Area Mode */ if (eval() != (R3_WORD | R3_AREA) || eval()) { fprintf(stderr, "R input error\n"); lkerr++; return; } /* * Get area pointer */ aindex = (int) evword(); if (aindex >= hp->h_narea) { fprintf(stderr, "R area error\n"); lkerr++; return; } /* * Select Output File */ if (oflag != 0) { ap = a[aindex]->a_bap; if (ofp != NULL) { rtabnk->b_rtaflg = rtaflg; if (ofp != ap->a_ofp) { lkflush(); } } ofp = ap->a_ofp; rtabnk = ap->a_bp; rtaflg = rtabnk->b_rtaflg; } /* * Base values */ rtbase = adb_xb(0, 0); rtofst = a_bytes; /* * Relocate address */ pc = adb_xb(a[aindex]->a_addr, 0); /* * Number of 'bytes' per PC address */ pcb = 1; mybank = bankmagic(a[aindex]); #if 0 printf("area %d base address: 0x%x size: 0x%x rtbase: 0x%x\n", aindex, a[aindex]->a_addr, a[aindex]->a_size, rtbase); #endif /* * Do remaining relocations */ while (more()) { error = 0; bmagic = 0; mode = (int) eval(); if ((mode & R_ESCAPE_MASK) == R_ESCAPE_MASK) { mode = ((mode & ~R_ESCAPE_MASK) << 8) | eval(); /* printf("unescaping rmode\n"); */ } rtp = (int) eval(); rindex = (int) evword(); /* * R3_SYM or R3_AREA references */ if (mode & R3_SYM) { if (rindex >= hp->h_nsym) { fprintf(stderr, "R symbol error\n"); lkerr++; return; } reli = symval(s[rindex]); /* Check if this symbol is magic */ bmagic = bankmagic(s[rindex]->s_axp); } /* sdld specific */ else if ((IS_R_J11(mode) || IS_R_J19(mode)) && (rindex == 0xFFFF)) { /* absolute acall/ajmp address */ reli = 0; } /* end sdld specific */ else { if (rindex >= hp->h_narea) { fprintf(stderr, "R area error\n"); lkerr++; return; } reli = a[rindex]->a_addr; } /* * R3_PCR addressing */ if (mode & R3_PCR) { if (mode & R3_BYTE) { reli -= (pc + (rtp-rtofst) + 1); } else { reli -= (pc + (rtp-rtofst) + 2); } } /* * R3_PAG0 or R3_PAG addressing */ if (mode & (R3_PAG0 | R3_PAG)) { paga = sdp.s_area->a_addr; pags = sdp.s_addr; reli -= paga + pags; } /* * R3_BYTE or R3_WORD operation */ if (mode & R3_BYTE) { if (mode & R_BYT3) { /* This is a three byte address, of which * we will select one byte. */ /* sdld specific */ if (mode & R_BIT) { relv = adb_24_bit(reli, rtp); } /* sdld specific */ else if (mode & R_HIB) { /* printf("24 bit address selecting hi byte.\n"); */ relv = adb_24_hi(reli, rtp); } else if (mode & R3_MSB) { /* Note that in 24 bit mode, R3_MSB * is really the middle byte, not * the most significant byte. * * This is ugly and I can only apologize * for any confusion. */ /* printf("24 bit address selecting middle byte.\n"); */ relv = adb_24_mid(reli, rtp); } else { /* printf("24 bit address selecting lo byte.\n"); */ relv = adb_24_lo(reli, rtp); } } else if (mode & R3_BYTX) { /* This is a two byte address, of * which we will select one byte. */ if (mode & R_BIT) { relv = adb_bit(reli, rtp); } else if (mode & R3_MSB) { relv = adb_hi(reli, rtp); } else { relv = adb_lo(reli, rtp); } } else { relv = adb_1b(reli, rtp); } } else if (IS_R_J11(mode)) { /* * JLH: 11 bit jump destination for 8051. * Forms two byte instruction with * op-code bits in the MIDDLE! * rtp points at 3 byte locus: * first two will get the address, * third one has raw op-code */ /* * Calculate absolute destination * relv must be on same 2K page as pc */ relv = adb_2b(reli, rtp); if ((relv & ~((a_uint) 0x000007FF)) != ((pc + rtp - rtofst) & ~((a_uint) 0x000007FF))) { error = 6; } /* * Merge MSB with op-code, * ignoring top 5 bits of address. * Then hide the op-code. */ rtval[rtp] = ((rtval[rtp] & 0x07)<<5) | rtval[rtp+2]; rtflg[rtp + 2] = 0; rtofst += 1; } else if (IS_R_J19(mode)) { /* * BK: 19 bit jump destination for DS80C390. * Forms four byte instruction with * op-code bits in the MIDDLE! * rtp points at 4 byte locus: * first three will get the address, * fourth one has raw op-code */ relv = adb_3b(reli, rtp); /* * Calculate absolute destination * relv must be on same 512K page as pc */ if ((relv & ~((a_uint) 0x0007FFFF)) != ((pc + rtp - rtofst) & ~((a_uint) 0x0007FFFF))) { error = 7; } /* * Merge MSB with op-code, * ignoring top 5 bits of address. * Then hide the op-code. */ rtval[rtp] = ((rtval[rtp] & 0x07)<<5) | rtval[rtp+3]; rtflg[rtp + 3] = 0; rtofst += 1; } else if (IS_C24(mode)) { /* * 24 bit destination */ relv = adb_3b(reli, rtp); } else { /* 16 bit address. */ if (bmagic) bankingstub(s[rindex], a[aindex], bmagic, a[aindex]->a_addr + rtbase + rtp - rtofst); relv = adb_2b(reli, rtp); } /* * R3_BYTE with R3_BYTX offset adjust */ if (mode & R3_BYTE) { if (mode & R3_BYTX) { rtofst += (a_bytes - 1); } } /* * Unsigned Byte Checking */ if (mode & R3_USGN && mode & R3_BYTE && relv & ~((a_uint) 0x000000FF)) error = 1; /* * PCR Relocation Error Checking */ if (mode & R3_PCR && mode & R3_BYTE) { r = relv & ~0x7F; if (r != (a_uint) ~0x7F && r != 0) error = 2; } /* * Page Relocation Error Checking */ if ((TARGET_IS_GB || TARGET_IS_Z80) && mode & R3_PAG0 && (relv & ~0xFF || paga || pags)) error = 4; if (mode & R3_PAG && (relv & ~0xFF)) error = 5; /* sdld specific */ if ((mode & R_BIT) && (relv & ~0x87FF)) error = 10; /* end sdld specific */ /* * Error Processing */ if (error) { rerr.aindex = aindex; rerr.mode = mode; rerr.rtbase = rtbase + rtp - rtofst - 1; rerr.rindex = rindex; rerr.rval = relv - reli; relerr3(errmsg3[error]); for (i=rtp; i<rtp+a_bytes; i++) { if (rtflg[i]) { rterr[i] = error; break; } } } } if (uflag != 0) { lkulist(1); } if (oflag != 0) { lkout(1, mybank); } }
int led_control(int which, int mode) { int use_gpio; // int gpio_value; int enable, disable; int model; model = get_model(); // Did the user disable the leds? if ((mode == LED_ON) && (nvram_get_int("led_disable") == 1) && (which != LED_TURBO) #ifdef RTCONFIG_QTN && (which != BTN_QTN_RESET) #endif ) return 0; get_gpio_values_once(); switch(which) { case LED_POWER: use_gpio = led_pwr_gpio; break; case LED_USB: use_gpio = led_usb_gpio; break; case LED_USB3: use_gpio = led_usb3_gpio; break; case LED_WPS: use_gpio = led_wps_gpio; break; case LED_2G: if ((model == MODEL_RTN66U) || (model == MODEL_RTAC66U) || (model == MODEL_RTN16)) { if (mode == LED_ON) eval("wl", "-i", "eth1", "leddc", "0"); else if (mode == LED_OFF) eval("wl", "-i", "eth1", "leddc", "1"); use_gpio = 0xff; } else if (model == MODEL_RTAC56U) { if (mode == LED_ON) eval("wl", "-i", "eth1", "ledbh", "3", "7"); else if (mode == LED_OFF) eval("wl", "-i", "eth1", "ledbh", "3", "0"); } else if ((model == MODEL_RTAC68U) || (model == MODEL_RTAC87U)) { if (mode == LED_ON) eval("wl", "ledbh", "10", "7"); else if (mode == LED_OFF) eval("wl", "ledbh", "10", "0"); } else { use_gpio = led_2g_gpio; } break; case LED_5G_FORCED: if (model == MODEL_RTAC68U) { if (mode == LED_ON) { nvram_set("led_5g", "1"); eval("wl", "-i", "eth2", "ledbh", "10", "7"); } else if (mode == LED_OFF) { nvram_set("led_5g", "0"); eval("wl", "-i", "eth2", "ledbh", "10", "0"); } use_gpio = led_5g_gpio; } // Fall through regular LED_5G to handle other models case LED_5G: if ((model == MODEL_RTN66U) || (model == MODEL_RTN16)) { if (mode == LED_ON) eval("wl", "-i", "eth2", "leddc", "0"); else if (mode == LED_OFF) eval("wl", "-i", "eth2", "leddc", "1"); use_gpio = 0xff; } else if ((model == MODEL_RTAC66U) || (model == MODEL_RTAC56U)) { if (mode == LED_ON) nvram_set("led_5g", "1"); else if (mode == LED_OFF) nvram_set("led_5g", "0"); use_gpio = led_5g_gpio; } else { use_gpio = led_5g_gpio; } #if defined(RTAC56U) || defined(RTAC56S) if(nvram_match("5g_fail", "1")) return -1; #endif break; #ifdef RTCONFIG_LAN4WAN_LED case LED_LAN1: use_gpio = led_lan1_gpio; break; case LED_LAN2: use_gpio = led_lan2_gpio; break; case LED_LAN3: use_gpio = led_lan3_gpio; break; case LED_LAN4: use_gpio = led_lan4_gpio; break; #else case LED_LAN: use_gpio = led_lan_gpio; break; #endif case LED_WAN: use_gpio = led_wan_gpio; break; case FAN: use_gpio = fan_gpio; break; case HAVE_FAN: use_gpio = have_fan_gpio; break; case LED_SWITCH: if (mode == LED_ON) { eval("et", "robowr", "0x00", "0x18", "0x01ff"); eval("et", "robowr", "0x00", "0x1a", "0x01ff"); } else if (mode == LED_OFF) { eval("et", "robowr", "0x00", "0x18", "0x01e0"); eval("et", "robowr", "0x00", "0x1a", "0x01e0"); } use_gpio = 0xff; break; #ifdef RTCONFIG_LED_ALL case LED_ALL: use_gpio = led_all_gpio; break; #endif case LED_TURBO: use_gpio = led_turbo_gpio; break; #ifdef RTCONFIG_QTN case BTN_QTN_RESET: use_gpio = reset_qtn_gpio; break; #endif default: use_gpio = 0xff; break; } if((use_gpio&0xff) != 0xff) { enable = (use_gpio&GPIO_ACTIVE_LOW)==0 ? 1 : 0; disable = (use_gpio&GPIO_ACTIVE_LOW)==0 ? 0: 1; switch(mode) { case LED_ON: case FAN_ON: case HAVE_FAN_ON: set_gpio((use_gpio&0xff), enable); break; case LED_OFF: case FAN_OFF: case HAVE_FAN_OFF: set_gpio((use_gpio&0xff), disable); break; } } return 0; }
void FDHessian::optimize(size_t maxiter, double gthr, bool max) { arma::vec x0(count_params()); x0.zeros(); double ival=eval(x0); printf("Initial value is % .10f\n",ival); // Current and previous gradient arma::vec g, gold; // Search direction arma::vec sd; for(size_t iiter=0;iiter<maxiter;iiter++) { // Evaluate gradient gold=g; { Timer t; g=gradient(); print_status(iiter,g,t); } if(arma::norm(g,2)<gthr) break; // Initial step size double initstep=1e-4; // Factor for increase of step size double stepfac=2.0; // Do line search std::vector<double> step, val; // Update search direction arma::vec oldsd(sd); sd = max ? g : -g; if(iiter % std::min((size_t) round(sqrt(count_params())),(size_t) 5) !=0) { // Update factor double gamma; // Polak-Ribiere gamma=arma::dot(g,g-gold)/arma::dot(gold,gold); // Fletcher-Reeves //gamma=arma::dot(g,g)/arma::dot(gold,gold); // Update search direction sd+=gamma*oldsd; printf("CG step\n"); } else printf("SD step\n"); while(true) { step.push_back(std::pow(stepfac,step.size())*initstep); val.push_back(eval(step[step.size()-1]*sd)); if(val.size()>=2) printf(" %e % .10f % e\n",step[step.size()-1],val[val.size()-1],val[val.size()-1]-val[val.size()-2]); else printf(" %e % .10f\n",step[step.size()-1],val[val.size()-1]); double dval=val[val.size()-1]-val[val.size()-2]; // Check if converged if(val.size()>=2) { if(max && dval<0) break; else if(!max && dval>0) break; } } // Get optimal value arma::vec vals=arma::conv_to<arma::vec>::from(val); arma::uword iopt; if(max) vals.max(iopt); else vals.min(iopt); printf("Line search changed value by %e\n",val[iopt]-val[0]); // Optimal value is double optstep=step[iopt]; // Update x update(optstep*sd); } double fval=eval(x0); printf("Final value is % .10f; optimization changed value by %e\n",fval,fval-ival); }
GaussMixture* GaussMixtureEstimator::Estimate(vector<VecD>& pts) const { assert(pts.size() >= ncomps); int npts = pts.size(); int dim = pts[0].size(); // Compute the number of free variables in the model and in the // data. If the former is less than the latter then the system is // underspecified and will lead to singularities in the likelihood // function. int model_params; if (spherical) { model_params = ncomps * (2 + dim); } else if (axis_aligned) { model_params = ncomps * (1 + 2*dim); } else { model_params = ncomps * (1 + dim + dim*(dim+1)/2); } int data_params = npts * dim; // number of free variables in the data assert(data_params >= model_params); // is the system under-specified? // Initialize the model using k-means clustering GaussMixture* model = new GaussMixture(ncomps, dim); MatD resps(npts, ncomps); vector<VecD> initmeans; KMeans::Estimate(pts, ncomps, initmeans, resps); for (int i = 0; i < ncomps; i++) { model->weights[i] = 1.0 / ncomps; model->comps[i]->mean = initmeans[i]; // set covariances to 1e-10 * Identity so that in the first // iteration each point is assigned entirely to the nearest // component model->comps[i]->cov.SetIdentity(1e-10); } // Begin iterating double loglik = 0.0, prev_loglik = 0.0; for (int i = 0; i < max_iters; i++) { GaussMixtureEvaluator eval(*model); // Check for small determinants (indicates poor support) for (int j = 0; j < model->ncomps; j++) { double logdetcov = eval.Component(j).GetLogDetCov(); if (logdetcov < -50*dim) { cerr << "Warning: log(det(covariance of component " << j << "))" << " is very small: " << logdetcov << endl; cerr << " its total support is " << resps.GetRow(j).Sum() << endl; cerr << " at iteration " << i << endl; } } // Compute responsibilities (E step) //DLOG << "E step\n"; prev_loglik = loglik; loglik = 0.0; for (int j = 0; j < npts; j++) { double logdenom = eval.EvaluateLog(pts[j]); loglik += logdenom; // Compute the responsibilities for (int k = 0; k < ncomps; k++) { const GaussianEvaluator& g = eval.Component(k); double logresp = eval.logweights[k] + g.EvaluateLog(pts[j]); resps[j][k] = exp(logresp - logdenom); } } // Test for convergence //DLOG << "After iteration " << i << " log likelihood = " << loglik << endl; double reldiff = fabs((prev_loglik - loglik) / prev_loglik); if (reldiff < exit_thresh) { cout << "EM converged after " << i << " iterations" << endl; return model; } prev_loglik = loglik; // Estimate new parameters (M step) //DLOG << "M step\n"; for (int k = 0; k < ncomps; k++) { Gaussian* comp = model->comps[k].get(); VecD col = resps.GetColumn(k); double colsum = resps.GetColumn(k).Sum(); // Estimate means comp->mean.Fill(0.0); for (int j = 0; j < npts; j++) { comp->mean += col[j] * pts[j]; } comp->mean /= colsum; // Estimate covariances // Initialize the forward diagonal to a small constant to // prevent singularities when components only have a small // number of points assigned to them. comp->cov.SetIdentity(1e-10); for (int j = 0; j < npts; j++) { if (spherical) { double d = col[j] * VectorSSD(pts[j], comp->mean) / dim; for (int k = 0; k < dim; k++) { comp->cov[k][k] += d; } } else if (axis_aligned) { VecD d = pts[j] - comp->mean; for (int k = 0; k < dim; k++) { comp->cov[k][k] += col[j] * d[k]*d[k]; } } else { VecD v = pts[j] - comp->mean; comp->cov += col[j] * OuterProduct(v, v); } } comp->cov /= colsum; if (spherical) { for (int k = 0; k < dim; k++) { comp->cov[k][k] = sqrt(comp->cov[k][k]); } } // Estimate weights model->weights[k] = colsum; } // Normalize mixing coefficients model->weights /= model->weights.Sum(); } DLOG << "EM failed to converge after " << max_iters << " iterations" << endl; return model; }
int qtn_monitor_main(int argc, char *argv[]) { FILE *fp; sigset_t sigs_to_catch; int ret, retval = 0; time_t start_time = uptime(); /* write pid */ if ((fp = fopen("/var/run/qtn_monitor.pid", "w")) != NULL) { fprintf(fp, "%d", getpid()); fclose(fp); } /* set the signal handler */ sigemptyset(&sigs_to_catch); sigaddset(&sigs_to_catch, SIGTERM); sigprocmask(SIG_UNBLOCK, &sigs_to_catch, NULL); signal(SIGTERM, qtn_monitor_exit); QTN_RESET: ret = rpc_qcsapi_init(1); if (ret < 0) { dbG("rpc_qcsapi_init error, return: %d\n", ret); retval = -1; goto ERROR; } #if 0 /* replaced by STATELESS, send configuration from brcm to qtn */ else if (nvram_get_int("qtn_restore_defaults")) { nvram_unset("qtn_restore_defaults"); rpc_qcsapi_restore_default_config(0); dbG("Restaring Qcsapi init...\n"); sleep(15); goto QTN_RESET; } #endif #if 0 if(nvram_get_int("sw_mode") == SW_MODE_AP && nvram_get_int("wlc_psta") == 1 && nvram_get_int("wlc_band") == 1) { dbG("[sw_mode] start QTN PSTA mode\n"); start_psta_qtn(); } #endif ret = qcsapi_init(); if (ret < 0) { dbG("Qcsapi qcsapi_init error, return: %d\n", ret); retval = -1; goto ERROR; } else dbG("Qcsapi qcsapi init takes %ld seconds\n", uptime() - start_time); dbG("defer lanport_ctrl(1)\n"); lanport_ctrl(1); eval("ifconfig", "br0:1", "down"); #if defined(RTCONFIG_JFFS2ND_BACKUP) check_2nd_jffs(); #endif nvram_set("qtn_ready", "1"); if(nvram_get_int("AllLED") == 0) setAllLedOff(); // dbG("[QTN] update router_command.sh from brcm to qtn\n"); // qcsapi_wifi_run_script("set_test_mode", "update_router_command"); #if 1 /* STATELESS */ if(nvram_get_int("sw_mode") == SW_MODE_AP && nvram_get_int("wlc_psta") == 1 && nvram_get_int("wlc_band") == 1) { dbG("[sw_mode] skip start_psta_qtn, QTN will run scripts automatically\n"); // start_psta_qtn(); } else { dbG("[***] rpc_parse_nvram_from_httpd\n"); rpc_parse_nvram_from_httpd(1,-1); /* wifi0 */ rpc_parse_nvram_from_httpd(1,1); /* wifi1 */ rpc_parse_nvram_from_httpd(1,2); /* wifi2 */ rpc_parse_nvram_from_httpd(1,3); /* wifi3 */ dbG("[sw_mode] skip start_ap_qtn, QTN will run scripts automatically\n"); // start_ap_qtn(); qcsapi_mac_addr wl_mac_addr; ret = rpc_qcsapi_interface_get_mac_addr(WIFINAME, &wl_mac_addr); if (ret < 0) dbG("rpc_qcsapi_interface_get_mac_addr, return: %d\n", ret); else { nvram_set("1:macaddr", wl_ether_etoa((struct ether_addr *) &wl_mac_addr)); nvram_set("wl1_hwaddr", wl_ether_etoa((struct ether_addr *) &wl_mac_addr)); } rpc_update_wdslist(); if(nvram_get_int("wps_enable") == 1) { ret = rpc_qcsapi_wifi_disable_wps(WIFINAME, 0); if (ret < 0) dbG("rpc_qcsapi_wifi_disable_wps %s error, return: %d\n", WIFINAME, ret); ret = qcsapi_wps_set_ap_pin(WIFINAME, nvram_safe_get("wps_device_pin")); if (ret < 0) dbG("qcsapi_wps_set_ap_pin %s error, return: %d\n", WIFINAME, ret); ret = qcsapi_wps_registrar_set_pp_devname(WIFINAME, 0, (const char *) get_productid()); if (ret < 0) dbG("qcsapi_wps_registrar_set_pp_devname %s error, return: %d\n", WIFINAME, ret); } else { ret = rpc_qcsapi_wifi_disable_wps(WIFINAME, 1); if (ret < 0) dbG("rpc_qcsapi_wifi_disable_wps %s error, return: %d\n", WIFINAME, ret); } rpc_set_radio(1, 0, nvram_get_int("wl1_radio")); } #endif if(nvram_get_int("wl1_80211h") == 1) { dbG("[80211h] set_80211h_on\n"); qcsapi_wifi_run_script("router_command.sh", "80211h_on"); } else { dbG("[80211h] set_80211h_off\n"); qcsapi_wifi_run_script("router_command.sh", "80211h_off"); } if(nvram_get_int("sw_mode") == SW_MODE_ROUTER || (nvram_get_int("sw_mode") == SW_MODE_AP && nvram_get_int("wlc_psta") == 0)) { if(nvram_get_int("wl1_chanspec") == 0) { if (nvram_match("1:ccode", "EU")) { if(nvram_get_int("acs_dfs") != 1) { dbG("[dfs] start nodfs scanning and selection\n"); start_nodfs_scan_qtn(); } } else { /* all country except EU */ dbG("[dfs] start nodfs scanning and selection\n"); start_nodfs_scan_qtn(); } } } if(nvram_get_int("sw_mode") == SW_MODE_AP && nvram_get_int("wlc_psta") == 1 && nvram_get_int("wlc_band") == 0) { ret = qcsapi_wifi_reload_in_mode(WIFINAME, qcsapi_station); if (ret < 0) dbG("qtn reload_in_mode STA fail\n"); } if(nvram_get_int("QTNTELNETSRV") == 1 && nvram_get_int("sw_mode") == SW_MODE_ROUTER) { dbG("[QTNT] enable telnet server\n"); qcsapi_wifi_run_script("router_command.sh", "enable_telnet_srv 1"); } dbG("[dbg] qtn_monitor startup\n"); ERROR: remove("/var/run/qtn_monitor.pid"); return retval; }
int main() { /*Input a string and check if its a formula*/ char *name=malloc(Fsize); printf("Enter a formula: "); scanf("%s", name); int p=parse(name); switch(p) { case 0: printf("Not a formula \n");break; case 1: printf("An atomic formula \n");break; case 2: printf("A negated formula \n");break; case 3: printf("A binary connective formula \n");break; case 4: printf("An existential formula \n");break; case 5: printf("A universal quantifier \n");break; default: printf("Not a formula \n");break; } // if (p==3) { // printf("The first part is %s, the binary connective is %c, the second part is %s", partone(string[0]), bin(name), parttwo(string[1])); // } // return(1); /*Input a graph. No. of nodes, edges, then input each edge.*/ if (p != 0) { printf("How many nodes in the graph?\n"); scanf(" %d", &no_nodes); printf("The nodes are 0, 1, ..., %d\n", no_nodes-1); printf("Now the edges\n"); printf("How many edges?\n"); scanf(" %d", &no_edges); int edges[no_edges][2]; /*Store edges in 2D array*/ int i, k, j; for(i=0;i<no_edges;i++) { printf("input a pair of nodes (<%d)", no_nodes); scanf(" %d", &j);scanf(" %d", &k); edges[i][0]=j; edges[i][1]=k; } /*Assign variables x, y, z to nodes */ int V[3]; /*Store variable values in array value of x in V[0] value of y in V[1] value of z in V[2] */ printf("Assign variables x, y, z\n"); printf("x is ?(<%d)", no_nodes);scanf(" %d", &V[0]); printf("y is ?");scanf(" %d", &V[1]); printf("z is ?");scanf(" %d", &V[2]); /*Now check if formula is true in the graph with given variable assignment. */ if (eval(name, edges, no_nodes, V)==1) { printf("The formula %s is true \n", name); } else { printf("The formula %s is false \n", name); } free(name); } return(1); }
int eval(char *nm, int edges[no_edges][2], int size, int V[3]) /*this method takes a formula, the list of edges of a graph, the number of vertices and a variable assignment. It then evaluates the formula and returns 1 or 0 as appropriate. */ { if (*nm == '(') { for (int i = 0; i < no_connectives; i++) { eval(nm, edges, no_nodes, V); } } if (*nm == 'X' && var_assign == true) { if (*(nm + 2) == *(nm + 3)) { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == edges[i][1]) { return 1; } } } if (*(nm + 2) == 'x') { if (*(nm + 3) == 'y') { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == V[0]) { if (edges[i][1] == V[1]) { return 1; } } } return 0; } if (*(nm + 3) == 'z') { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == V[0]) { if (edges[i][1] == V[2]) { return 1; } } } } } if (*(nm + 2) == 'y') { if (*(nm + 3) == 'x') { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == V[1]) { if (edges[i][1] == V[0]) { return 1; } } } return 0; } if (*(nm + 3) == 'z') { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == V[1]) { if (edges[i][1] == V[2]) { return 1; } } } } } if (*(nm + 2) == 'z') { if (*(nm + 3) == 'x') { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == V[2]) { if (edges[i][1] == V[0]) { return 1; } } } return 0; } if (*(nm + 3) == 'y') { for (int i = 0; i < no_edges; i++) { if (edges[i][0] == V[2]) { if (edges[i][1] == V[1]) { return 1; } } } } } } // // Negation // if (*nm == '-') { if (eval((nm + 1), edges, no_nodes, V) == 1) { return 0; } if (eval((nm + 1), edges, no_nodes, V) == 0) { return 1; } } // // Universal Quantifier // if (*nm == 'A') { var_assign = false; // AxX[xy] if (*(nm+2) == 'X') { if (*(nm+1) == *(nm+4)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (i == edges[j][0]) { trueCount++; break; } } } } if (*(nm+1) == *(nm+5)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (i == edges[j][1]) { trueCount++; break; } } } } if (trueCount == no_nodes) { trueCount = 0; return 1; } trueCount = 0; } // AxAyX[xy] if (*(nm+2) == 'A') { if (no_edges >= no_nodes * no_nodes) { return 1; } } // AxEyX[xy] if (*(nm+2) == 'E') { if (*(nm+6) == *(nm+1) && *(nm+3) == *(nm+7)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][0] == i) { trueCount++; break; } } } } if (*(nm+7) == *(nm+1) && *(nm+6) == *(nm+3)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][1] == i) { trueCount++; break; } } } } if (trueCount == no_nodes) { trueCount = 0; return 1; } } } // // Extensial Formula // if (*nm == 'E') { var_assign = false; //ExX[xy] if (*(nm+2) == 'X') { if(*(nm+1) == *(nm+4)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][0] == i) { return 1; } } } } if(*(nm+1) == *(nm+5)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][1] == i) { return 1; } } } } } // ExAy[xy] if (*(nm+2) == 'A') { if(*(nm+1) == *(nm+6)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][0] == i) { trueCount++; } } if (trueCount == no_nodes) { trueCount = 0; return 1; } trueCount = 0; } } if(*(nm+1) == *(nm+7)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][1] == i) { trueCount++; } } if (trueCount == no_nodes) { trueCount = 0; return 1; } trueCount = 0; } } } // ExEyX[xy] if (*(nm+2) == 'E') { if(*(nm+1) == *(nm+4)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][0] == i) { return 1; } } } } if(*(nm+1) == *(nm+5)) { for (int i = 0; i < no_nodes; i++) { for (int j = 0; j < no_edges; j++) { if (edges[j][1] == i) { return 1; } } } } } } return 0; }
vec2r Fresnel::eval(real a, real s) { const real c0 = sqrt(abs(a) / PI); return eval(c0 * s) / c0; // sgn(a)? }
inline Spectrum sample(BSDFQueryRecord &bRec, Float &_pdf, const Point2 &_sample) const { AssertEx(bRec.sampler != NULL, "The BSDFQueryRecord needs to have a sampler!"); bool hasSpecularTransmission = (bRec.typeMask & EDeltaTransmission) && (bRec.component == -1 || bRec.component == 2); bool hasSingleScattering = (bRec.typeMask & EGlossy) && (bRec.component == -1 || bRec.component == 0 || bRec.component == 1); const Spectrum sigmaA = m_sigmaA->getValue(bRec.its), sigmaS = m_sigmaS->getValue(bRec.its), sigmaT = sigmaA + sigmaS, tauD = sigmaT * m_thickness; /* Probability for a specular transmission is approximated by the average (per wavelength) * probability of a photon exiting without a scattering event or an absorption event */ Float probSpecularTransmission = (-tauD/std::abs(Frame::cosTheta(bRec.wi))).exp().average(); bool choseSpecularTransmission = hasSpecularTransmission; Point2 sample(_sample); if (hasSpecularTransmission && hasSingleScattering) { if (sample.x > probSpecularTransmission) { sample.x = (sample.x - probSpecularTransmission) / (1 - probSpecularTransmission); choseSpecularTransmission = false; } } if (choseSpecularTransmission) { /* The specular transmission component was sampled */ bRec.sampledComponent = 2; bRec.sampledType = EDeltaTransmission; bRec.wo = -bRec.wi; _pdf = hasSingleScattering ? probSpecularTransmission : 1.0f; return eval(bRec, EDiscrete) / _pdf; } else { /* The glossy transmission/scattering component should be sampled */ bool hasGlossyReflection = (bRec.typeMask & EGlossyReflection) && (bRec.component == -1 || bRec.component == 0); bool hasGlossyTransmission = (bRec.typeMask & EGlossyTransmission) && (bRec.component == -1 || bRec.component == 1); /* Sample According to the phase function lobes */ PhaseFunctionQueryRecord pRec(MediumSamplingRecord(), bRec.wi, bRec.wo); m_phase->sample(pRec, _pdf, bRec.sampler); /* Store the sampled direction */ bRec.wo = pRec.wo; bool reflection = Frame::cosTheta(bRec.wi) * Frame::cosTheta(bRec.wo) >= 0; if ((!hasGlossyReflection && reflection) || (!hasGlossyTransmission && !reflection)) return Spectrum(0.0f); /* Notify that the scattering component was sampled */ bRec.sampledComponent = reflection ? 0 : 1; bRec.sampledType = EGlossy; _pdf *= (hasSpecularTransmission ? (1 - probSpecularTransmission) : 1.0f); /* Guard against numerical imprecisions */ if (_pdf == 0) return Spectrum(0.0f); else return eval(bRec, ESolidAngle) / _pdf; } }
int useCount() const { if (!isReady()) eval(); return data.use_count(); }
//FIXME: implement withOffset parameter const T* get(bool withOffset = true) const { if (!isReady()) eval(); return data.get() + (withOffset ? getOffset() : 0); }
T* get(bool withOffset = true) { if (!isReady()) eval(); return const_cast<T*>(static_cast<const Array<T>*>(this)->get(withOffset)); }
/***********************************************************************//** * @brief Set MC pre-computation cache * * @param[in] tmin Minimum time of time interval. * @param[in] tmax Maximum time of time interval. * * This method sets up an array of indices and the cumulative distribution * function needed for MC simulations. ***************************************************************************/ void GModelTemporalLightCurve::mc_update(const GTime& tmin, const GTime& tmax) const { // Get light curve normalisation value to see whether it has changed double norm = m_norm.value(); // Update the cache only if the time interval or normalisation has changed if (tmin != m_mc_tmin || tmax != m_mc_tmax || norm != m_mc_norm) { // Store new time interval and normalisation value m_mc_tmin = tmin; m_mc_tmax = tmax; m_mc_norm = norm; // Initialise cache m_mc_eff_duration = 0.0; m_mc_cum.clear(); m_mc_slope.clear(); m_mc_offset.clear(); m_mc_time.clear(); m_mc_dt.clear(); // Initialise duration double duration = 0.0; // Continue only if time interval overlaps with temporal file function // and if time interval is valid if (tmax > m_tmin && tmin < m_tmax && tmax > tmin) { // Loop over all intervals between the nodes for (int i = 0; i < m_nodes.size()-1; ++i) { // Get start and stop time of interval GTime tstart(m_nodes[i], m_timeref); GTime tstop(m_nodes[i+1], m_timeref); // Make sure that we only consider the interval that overlaps // with the requested time interval if (tmin > tstart) { tstart = tmin; } if (tmax < tstop) { tstop = tmax; } // If time interval is empty then skip this node if (tstart >= tstop) { continue; } // Evaluate rate at start and stop time double rstart = eval(tstart); double rstop = eval(tstop); // Compute mean normalization for this interval double norm = 0.5 * (rstart + rstop); // Compute integral for this interval double dt = tstop - tstart; double cum = norm * dt; // Compute slope, offset and start time of interval double slope = (rstop - rstart) / dt; double offset = rstart; double renorm = (0.5 * slope * dt + offset) * dt; slope /= renorm; offset /= renorm; // Update effective duration and real duration m_mc_eff_duration += cum; duration += dt; // Put mean normalization and integral on stack m_mc_cum.push_back(cum); m_mc_slope.push_back(slope); m_mc_offset.push_back(offset); m_mc_time.push_back(tstart.convert(m_timeref)); m_mc_dt.push_back(dt); } // endfor: next interval // Build cumulative distribution for (int i = 1; i < m_mc_cum.size(); ++i) { m_mc_cum[i] += m_mc_cum[i-1]; } double norm = m_mc_cum[m_mc_cum.size()-1]; for (int i = 0; i < m_mc_cum.size(); ++i) { m_mc_cum[i] /= norm; } } // endif: time interval overlaps } // endif: Update was required // Return return; }
void gibbsOneWayAnova(double *y, int *N, int J, int sumN, int *whichJ, double rscale, int iterations, double *chains, double *CMDE, SEXP debug, int progress, SEXP pBar, SEXP rho) { int i=0,j=0,m=0,Jp1sq = (J+1)*(J+1),Jsq=J*J,Jp1=J+1,npars=0; double ySum[J],yBar[J],sumy2[J],densDelta=0; double sig2=1,g=1; double XtX[Jp1sq], ZtZ[Jsq]; double Btemp[Jp1sq],B2temp[Jsq],tempBetaSq=0; double muTemp[J],oneOverSig2temp=0; double beta[J+1],grandSum=0,grandSumSq=0; double shapeSig2 = (sumN+J*1.0)/2, shapeg = (J+1.0)/2; double scaleSig2=0, scaleg=0; double Xty[J+1],Zty[J]; double logDet=0; double rscaleSq=rscale*rscale; double logSumSingle=0,logSumDouble=0; // for Kahan sum double kahanSumSingle=0, kahanSumDouble=0; double kahanCSingle=0,kahanCDouble=0; double kahanTempT=0, kahanTempY=0; int iOne=1, info; double dZero=0; // progress stuff SEXP sampCounter, R_fcall; int *pSampCounter; PROTECT(R_fcall = lang2(pBar, R_NilValue)); PROTECT(sampCounter = NEW_INTEGER(1)); pSampCounter = INTEGER_POINTER(sampCounter); npars=J+5; GetRNGstate(); // Initialize to 0 AZERO(XtX,Jp1sq); AZERO(ZtZ,Jsq); AZERO(beta,Jp1); AZERO(ySum,J); AZERO(sumy2,J); // Create vectors for(i=0;i<sumN;i++) { j = whichJ[i]; ySum[j] += y[i]; sumy2[j] += y[i]*y[i]; grandSum += y[i]; grandSumSq += y[i]*y[i]; } // create design matrices XtX[0]=sumN; for(j=0;j<J;j++) { XtX[j+1]=N[j]; XtX[(J+1)*(j+1)]=N[j]; XtX[(j+1)*(J+1) + (j+1)] = N[j]; ZtZ[j*J + j] = N[j]; yBar[j] = ySum[j]/(1.0*N[j]); } Xty[0] = grandSum; Memcpy(Xty+1,ySum,J); Memcpy(Zty,ySum,J); // start MCMC for(m=0; m<iterations; m++) { R_CheckUserInterrupt(); //Check progress if(progress && !((m+1)%progress)){ pSampCounter[0]=m+1; SETCADR(R_fcall, sampCounter); eval(R_fcall, rho); //Update the progress bar } // sample beta Memcpy(Btemp,XtX,Jp1sq); for(j=0;j<J;j++){ Btemp[(j+1)*(J+1)+(j+1)] += 1/g; } InvMatrixUpper(Btemp, J+1); internal_symmetrize(Btemp,J+1); for(j=0;j<Jp1sq;j++) Btemp[j] *= sig2; oneOverSig2temp = 1/sig2; F77_CALL(dsymv)("U", &Jp1, &oneOverSig2temp, Btemp, &Jp1, Xty, &iOne, &dZero, beta, &iOne); rmvGaussianC(beta, Btemp, J+1); Memcpy(&chains[npars*m],beta,J+1); // calculate density (Single Standardized) Memcpy(B2temp,ZtZ,Jsq); densDelta = -J*0.5*log(2*M_PI); for(j=0;j<J;j++) { B2temp[j*J+j] += 1/g; muTemp[j] = (ySum[j]-N[j]*beta[0])/sqrt(sig2); } InvMatrixUpper(B2temp, J); internal_symmetrize(B2temp,J); logDet = matrixDet(B2temp,J,J,1, &info); densDelta += -0.5*quadform(muTemp, B2temp, J, 1, J); densDelta += -0.5*logDet; if(m==0){ logSumSingle = densDelta; kahanSumSingle = exp(densDelta); }else{ logSumSingle = logSumSingle + LogOnePlusX(exp(densDelta-logSumSingle)); kahanTempY = exp(densDelta) - kahanCSingle; kahanTempT = kahanSumSingle + kahanTempY; kahanCSingle = (kahanTempT - kahanSumSingle) - kahanTempY; kahanSumSingle = kahanTempT; } chains[npars*m + (J+1) + 0] = densDelta; // calculate density (Double Standardized) densDelta += 0.5*J*log(g); if(m==0){ logSumDouble = densDelta; kahanSumDouble = exp(densDelta); }else{ logSumDouble = logSumDouble + LogOnePlusX(exp(densDelta-logSumDouble)); kahanTempY = exp(densDelta) - kahanCDouble; kahanTempT = kahanSumDouble + kahanTempY; kahanCDouble = (kahanTempT - kahanSumDouble) - kahanTempY; kahanSumDouble = kahanTempT; } chains[npars*m + (J+1) + 1] = densDelta; // sample sig2 tempBetaSq = 0; scaleSig2 = grandSumSq - 2*beta[0]*grandSum + beta[0]*beta[0]*sumN; for(j=0;j<J;j++) { scaleSig2 += -2.0*(yBar[j]-beta[0])*N[j]*beta[j+1] + (N[j]+1/g)*beta[j+1]*beta[j+1]; tempBetaSq += beta[j+1]*beta[j+1]; } scaleSig2 *= 0.5; sig2 = 1/rgamma(shapeSig2,1/scaleSig2); chains[npars*m + (J+1) + 2] = sig2; // sample g scaleg = 0.5*(tempBetaSq/sig2 + rscaleSq); g = 1/rgamma(shapeg,1/scaleg); chains[npars*m + (J+1) + 3] = g; } CMDE[0] = logSumSingle - log(iterations); CMDE[1] = logSumDouble - log(iterations); CMDE[2] = log(kahanSumSingle) - log(iterations); CMDE[3] = log(kahanSumDouble) - log(iterations); UNPROTECT(2); PutRNGstate(); }
/* * main - The shell's main routine */ int main(int argc, char **argv) { char c; char cmdline[MAXLINE]; int emit_prompt = 1; /* emit prompt (default) */ /* Redirect stderr to stdout (so that driver will get all output * on the pipe connected to stdout) */ dup2(1, 2); /* Parse the command line */ while ((c = getopt(argc, argv, "hvp")) != EOF) { switch (c) { case 'h': /* print help message */ usage(); break; case 'v': /* emit additional diagnostic info */ verbose = 1; break; case 'p': /* don't print a prompt */ emit_prompt = 0; /* handy for automatic testing */ break; default: usage(); } } /* Install the signal handlers */ /* These are the ones you will need to implement */ Signal(SIGINT, sigint_handler); /* ctrl-c */ Signal(SIGTSTP, sigtstp_handler); /* ctrl-z */ Signal(SIGCHLD, sigchld_handler); /* Terminated or stopped child */ /* This one provides a clean way to kill the shell */ Signal(SIGQUIT, sigquit_handler); /* Initialize the job list */ initjobs(jobs); /* Execute the shell's read/eval loop */ while (1) { /* Read command line */ if (emit_prompt) { printf("%s", prompt); fflush(stdout); } if ((fgets(cmdline, MAXLINE, stdin) == NULL) && ferror(stdin)) { app_error("fgets error"); } if (feof(stdin)) { /* End of file (ctrl-d) */ fflush(stdout); exit(0); } /* Evaluate the command line */ eval(cmdline); fflush(stdout); fflush(stdout); } exit(0); /* control never reaches here */ }
void start_sysinit(void) { time_t tm = 0; char dev[64]; char *disk = getdisc(); if (disk == NULL) { fprintf(stderr, "no valid dd-wrt partition found, calling shell"); eval("/bin/sh"); exit(0); } FILE *in = fopen("/usr/local/nvram/nvram.db", "rb"); if (in != NULL) { fclose(in); mkdir("/tmp/nvram", 0700); eval("cp", "/etc/nvram/nvram.db", "/tmp/nvram"); eval("cp", "/etc/nvram/offsets.db", "/tmp/nvram"); eval("/usr/sbin/convertnvram"); nvram_commit(); eval("rm", "-f", "/etc/nvram/nvram.db"); eval("rm", "-f", "/etc/nvram/offsets.db"); } //recover nvram if available in = fopen("/usr/local/nvram/nvram.bin", "rb"); if (in == NULL) { fprintf(stderr, "recover broken nvram\n"); sprintf(dev, "/dev/%s", disk); in = fopen(dev, "rb"); fseeko(in, 0, SEEK_END); off_t mtdlen = ftello(in); fseeko(in, mtdlen - (65536 * 2), SEEK_SET); unsigned char *mem = malloc(65536); fread(mem, 65536, 1, in); fclose(in); if (mem[0] == 0x46 && mem[1] == 0x4c && mem[2] == 0x53 && mem[3] == 0x48) { fprintf(stderr, "found recovery\n"); in = fopen("/usr/local/nvram/nvram.bin", "wb"); if (in != NULL) { fwrite(mem, 65536, 1, in); fclose(in); free(mem); eval("sync"); sleep(5); eval("event", "5", "1", "15"); } } free(mem); } else { fclose(in); } if (!nvram_match("disable_watchdog", "1")) eval("watchdog"); // system watchdog #ifdef HAVE_ERC if (isregistered_real() && nvram_match("ree_resetme", "1")) { fprintf(stderr, "Restoring REE default nvram\n"); eval("nvram", "restore", "/etc/defaults/x86ree.backup"); eval("reboot"); eval("event", "5", "1", "15"); } #endif cprintf("sysinit() setup console\n"); /* * Setup console */ cprintf("sysinit() klogctl\n"); klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel"))); cprintf("sysinit() get router\n"); /* * eval("insmod","md5"); eval("insmod","aes"); eval("insmod","blowfish"); * eval("insmod","deflate"); eval("insmod","des"); * eval("insmod","michael_mic"); eval("insmod","cast5"); * eval("insmod","crypto_null"); */ detect_ethernet_devices(); eval("ifconfig", "eth0", "0.0.0.0", "up"); eval("ifconfig", "eth1", "0.0.0.0", "up"); eval("ifconfig", "eth2", "0.0.0.0", "up"); eval("ifconfig", "eth3", "0.0.0.0", "up"); struct ifreq ifr; int s; if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))) { char eabuf[32]; strncpy(ifr.ifr_name, "eth0", IFNAMSIZ); ioctl(s, SIOCGIFHWADDR, &ifr); nvram_set("et0macaddr_safe", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf)); nvram_set("et0macaddr", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf)); close(s); } detect_wireless_devices(); mknod("/dev/rtc", S_IFCHR | 0644, makedev(253, 0)); #ifdef HAVE_CPUTEMP // insmod("nsc_gpio"); // insmod("scx200_gpio"); // insmod("scx200_i2c"); // insmod("scx200_acb"); // insmod("lm77"); #endif nvram_set("wl0_ifname", "ath0"); mknod("/dev/crypto", S_IFCHR | 0644, makedev(10, 70)); /* * Set a sane date */ stime(&tm); cprintf("done\n"); return; }
GC_USER_FUNC int main (int argc, char ** argv) { #ifdef MEMWATCH mwInit(); mwDoFlush(1); #endif // MEMWATCH ML_START_TIMING(main_time); GC_init(); //ml_print_gc_stats(); printf("Compiled for " #if defined(GC_CHERI) "GC_CHERI" #elif defined(GC_BOEHM) "GC_BOEHM" #elif defined(GC_NONE) "GC_NONE" #elif defined(GC_NOCAP) "GC_NOCAP" #else #error "Define one of GC_CHERI, GC_BOEHM, GC_NONE." #endif // GC_CHERI, GC_BOEHM, GC_NONE " at %s\n", __TIME__ " " __DATE__); //GC_CAP const char * filename = GC_cheri_ptr("ml-tmp", sizeof("ml-tmp")); //lex_read_file(filename); //const char str[] = "(fn x . ((fn x . x) 3) + x) 2"; //const char str[] = "fn f . (fn g. (f (fn a . (g g) a))) (fn g. (f (fn a . (g g) a)))"; //const char str[] = //"((fn f . fn n . if n then n * f (n-1) else 1) (fn n . n)) 5"; // factorial: //const char str[] = // "((fn f . (fn g. (f (fn a . (g g) a))) (fn g. (f (fn a . (g g) a)))) (fn f . fn n . if n then n * f (n-1) else 1)) 6"; // for the benchmark: if (argc < 2) { printf("Need a program argument\n"); return 1; } if (argc < 3) { printf("Need a number argument\n"); return 1; } printf("Program should be evaluating something to do with the number %s\n", argv[2]); int num = atoi(argv[2]); #ifdef GC_CHERI gc_cheri_grow_heap(num); #endif #ifdef GC_BOEHM GC_set_max_heap_size(num >= 1024 ? 350000*(num/1024) : num >= 256 ? 200000 : 65536); #endif /*const char str[] = "((fn f . (fn g. (f (fn a . (g g) a))) (fn g. (f (fn f . (g g) f)))) (fn f . fn n . if n then n + f (n-1) else 1)) "; GC_CAP char * str2 = ml_malloc(sizeof(str)+strlen(argv[1])); cmemcpy(str2, GC_cheri_ptr(str, sizeof(str)), sizeof(str)); cmemcpy(str2+sizeof(str)-1, GC_cheri_ptr(argv[1], strlen(argv[1]+1)), strlen(argv[1]+1)); */ GC_CAP const char * str2 = GC_cheri_ptr(argv[1], strlen(argv[1])+1); unsigned long long before = ml_time(); lex_read_string(str2); printf("program: %s\n\n", (void*)(str2)); /*size_t i; for (i=0; i<lex_state.max; i++) { putchar(((char*)lex_state.file)[i]); } GC_CAP token_t * t; t = lex(); while (t->type != TKEOF) { printf("[%d] (tag=%d alloc=%d) %s\n", ((token_t*)t)->type, (int) GC_cheri_gettag(((token_t*)t)->str), (int) GC_IS_GC_ALLOCATED(((token_t*)t)->str), (char*) ((token_t*)t)->str); GC_malloc(5000); t = lex(); } printf("Finished\n"); return 0;*/ parse_init(); GC_CAP expr_t * expr = GC_INVALID_PTR(); GC_STORE_CAP(expr, parse()); printf("AST:\n"); print_ast(expr); printf("\nDone printing AST\n"); /*printf("collecting loads\n"); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); ml_collect(); printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~done collecting loads\n"); GC_debug_print_region_stats(&GC_state.thread_local_region);*/ GC_CAP val_t * val = GC_INVALID_PTR(); int i; for (i=0; i<10; i++) { GC_STORE_CAP(val, eval(expr, GC_INVALID_PTR())); } unsigned long long after = ml_time(); unsigned long long diff = after - before; printf("eval: "); if (!PTR_VALID(val)) printf("(invalid"); else print_val(val); printf("\n\n"); printf("[plotdata] %s %llu\n", argv[2], (unsigned long long) diff); #ifdef GC_CHERI printf("(young) heap size:\n"); printf("[altplotdata] %s %llu\n", argv[2], (unsigned long long) (GC_cheri_getlen(GC_state.thread_local_region.tospace))); #ifdef GC_GENERATIONAL printf("old heap size:\n"); printf("[altplotdataold] %s %llu\n", argv[2], (unsigned long long) (GC_cheri_getlen(GC_state.old_generation.tospace))); #endif // GC_GENERATIONAL #endif // GC_CHERI #ifdef GC_BOEHM printf("[altplotdata] %s %llu\n", argv[2], (unsigned long long) GC_get_heap_size()); #endif // GC_BOEHM ML_STOP_TIMING(main_time, "main()"); ml_print_gc_stats(); ml_print_plot_data(); #ifdef MEMWATCH mwTerm(); #endif // MEMWATCH return 0; }
void QDeclarativeBind::setWhen(bool v) { Q_D(QDeclarativeBind); d->when = v; eval(); }
/* #565: Access Intranet off */ void create_mbssid_vlan(void) { if(nvram_get_int("wl1.1_bss_enabled") == 1) { if(nvram_match("wl1.1_lanaccess", "off") && !nvram_match("wl1.1_lanaccess", "")) { /* VID 4000 */ eval("vconfig", "add", "eth0", "4000"); eval("ifconfig", "vlan4000", "up"); eval("brctl", "addif", "br0", "vlan4000"); eval("et", "robowr", "0x05", "0x81", "0x0fa0"); eval("et", "robowr", "0x05", "0x83", "0x00a0"); eval("et", "robowr", "0x05", "0x80", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0080"); } else { eval("brctl", "delif", "br0", "vlan4000"); eval("et", "robowr", "0x05", "0x81", "0x0fa0"); eval("et", "robowr", "0x05", "0x83", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0080"); } } if(nvram_get_int("wl1.2_bss_enabled") == 1) { if(nvram_match("wl1.2_lanaccess", "off") && !nvram_match("wl1.2_lanaccess", "")) { /* VID 4001 */ eval("vconfig", "add", "eth0", "4001"); eval("ifconfig", "vlan4001", "up"); eval("brctl", "addif", "br0", "vlan4001"); eval("et", "robowr", "0x05", "0x81", "0x0fa1"); eval("et", "robowr", "0x05", "0x83", "0x00a0"); eval("et", "robowr", "0x05", "0x80", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0080"); } else { eval("brctl", "delif", "br0", "vlan4001"); eval("et", "robowr", "0x05", "0x81", "0x0fa1"); eval("et", "robowr", "0x05", "0x83", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0080"); } } if(nvram_get_int("wl1.3_bss_enabled") == 1) { if(nvram_match("wl1.3_lanaccess", "off") && !nvram_match("wl1.3_lanaccess", "")) { /* VID 4002 */ eval("vconfig", "add", "eth0", "4002"); eval("ifconfig", "vlan4002", "up"); eval("brctl", "addif", "br0", "vlan4002"); eval("et", "robowr", "0x05", "0x81", "0x0fa2"); eval("et", "robowr", "0x05", "0x83", "0x00a0"); eval("et", "robowr", "0x05", "0x80", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0080"); } else { eval("brctl", "delif", "br0", "vlan4002"); eval("et", "robowr", "0x05", "0x81", "0x0fa2"); eval("et", "robowr", "0x05", "0x83", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0000"); eval("et", "robowr", "0x05", "0x80", "0x0080"); } } }
void QDeclarativeBind::setObject(QObject *obj) { Q_D(QDeclarativeBind); d->obj = obj; eval(); }
void PZStability::check() { Timer tfull; // Estimate runtime { // Test value arma::vec x0(count_params()); x0.zeros(); if(x0.n_elem) x0(0)=0.1; if(x0.n_elem>=2) x0(1)=-0.1; Timer t; eval(x0,GHMODE); double dt=t.get(); // Total time is double ttot=2*x0.n_elem*(x0.n_elem+1)*dt; fprintf(stderr,"\nComputing the Hessian will take approximately %s\n",t.parse(ttot).c_str()); fflush(stderr); } // Get gradient Timer t; arma::vec g(gradient()); printf("Gradient norm is %e (%s)\n",arma::norm(g,2),t.elapsed().c_str()); fflush(stdout); if(cancheck && oocheck) { size_t nov=count_ov_params(oa,va); if(!restr) nov+=count_ov_params(ob,vb); double ovnorm=arma::norm(g.subvec(0,nov-1),2); double oonorm=arma::norm(g.subvec(nov,g.n_elem-1),2); printf("OV norm %e, OO norm %e.\n",ovnorm,oonorm); } t.set(); // Evaluate Hessian arma::mat h(hessian()); printf("Hessian evaluated (%s)\n",t.elapsed().c_str()); fflush(stdout); t.set(); // Helpers arma::mat hvec; arma::vec hval; if(cancheck && oocheck) { // Amount of parameters size_t nov=count_ov_params(oa,va); if(!restr) nov+=count_ov_params(ob,vb); // Stability of canonical orbitals arma::mat hcan(h.submat(0,0,nov-1,nov-1)); eig_sym_ordered(hval,hvec,hcan); printf("\nOV Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout); hval.t().print("Canonical orbital stability"); // Stability of optimal orbitals arma::mat hopt(h.submat(nov-1,nov-1,h.n_rows-1,h.n_cols-1)); eig_sym_ordered(hval,hvec,hopt); printf("\nOO Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout); hval.t().print("Optimal orbital stability"); } if(cplx) { // Collect real and imaginary parts of Hessian. arma::uvec rp, ip; real_imag_idx(rp,ip); arma::mat rh(rp.n_elem,rp.n_elem); for(size_t i=0;i<rp.n_elem;i++) for(size_t j=0;j<rp.n_elem;j++) rh(i,j)=h(rp(i),rp(j)); arma::mat ih(ip.n_elem,ip.n_elem); for(size_t i=0;i<ip.n_elem;i++) for(size_t j=0;j<ip.n_elem;j++) ih(i,j)=h(ip(i),ip(j)); eig_sym_ordered(hval,hvec,rh); printf("\nReal part of Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout); hval.t().print("Real orbital stability"); eig_sym_ordered(hval,hvec,ih); printf("\nImaginary part of Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout); hval.t().print("Imaginary orbital stability"); } // Total stability eig_sym_ordered(hval,hvec,h); printf("\nFull Hessian diagonalized (%s)\n",t.elapsed().c_str()); fflush(stdout); hval.t().print("Orbital stability"); fprintf(stderr,"Check completed in %s.\n",tfull.elapsed().c_str()); }
void QDeclarativeBind::setProperty(const QString &p) { Q_D(QDeclarativeBind); d->prop = p; eval(); }
double PZStability::eval(const arma::vec & x) { return eval(x,false); }
void QDeclarativeBind::componentComplete() { Q_D(QDeclarativeBind); d->componentComplete = true; eval(); }
void PZStability::set(const uscf_t & sol, const arma::uvec & dropa, const arma::uvec & dropb, bool cplx_, bool can, bool oo) { cplx=cplx_; cancheck=can; oocheck=oo; Checkpoint *chkptp=solverp->get_checkpoint(); arma::cx_mat CWa, CWb; chkptp->cread("CWa",CWa); chkptp->cread("CWb",CWb); chkptp->read(basis); grid=DFTGrid(&basis,true,method.lobatto); nlgrid=DFTGrid(&basis,true,method.lobatto); // Update solution usol=sol; usol.cCa.cols(0,CWa.n_cols-1)=CWa; usol.cCb.cols(0,CWb.n_cols-1)=CWb; // Drop orbitals if(!cancheck) { arma::uvec dra(arma::sort(dropa,"descend")); for(size_t i=0;i<dra.n_elem;i++) { usol.cCa.shed_col(dra(i)); CWa.shed_col(0); } arma::uvec drb(arma::sort(dropb,"descend")); for(size_t i=0;i<drb.n_elem;i++) { usol.cCb.shed_col(drb(i)); CWb.shed_col(0); } } // Update size parameters restr=false; oa=CWa.n_cols; ob=CWb.n_cols; va=usol.cCa.n_cols-oa; vb=usol.cCb.n_cols-ob; fprintf(stderr,"\noa = %i, ob = %i, va = %i, vb = %i\n",(int) oa, (int) ob, (int) va, (int) vb); fprintf(stderr,"There are %i parameters.\n",(int) count_params()); fflush(stdout); // Reconstruct DFT grid if(method.adaptive) { arma::cx_mat Ctilde(sol.Ca.n_rows,CWa.n_cols+CWb.n_cols); Ctilde.cols(0,oa-1)=CWa; if(ob) Ctilde.cols(oa,oa+ob-1)=CWb; grid.construct(Ctilde,method.gridtol,method.x_func,method.c_func); } else { bool strict(false); grid.construct(method.nrad,method.lmax,method.x_func,method.c_func,strict); if(method.nl) nlgrid.construct(method.nlnrad,method.nllmax,true,false,strict,true); } // Update reference arma::vec x(count_params()); x.zeros(); eval(x,-1); }
void edit_process_rep::generate_bibliography ( string bib, string style, string fname) { system_wait ("Generating bibliography, ", "please wait"); if (DEBUG_AUTO) debug_automatic << "Generating bibliography" << " [" << bib << ", " << style << ", " << fname << "]\n"; tree bib_t= buf->data->aux[bib]; if (buf->prj != NULL) bib_t= buf->prj->data->aux[bib]; tree t; url bib_file= find_bib_file (buf->buf->name, fname); //cout << fname << " -> " << concretize (bib_file) << "\n"; if (is_none (bib_file)) { url bbl_file= find_bib_file (buf->buf->name, fname, ".bbl"); if (is_none (bbl_file)) { if (supports_db ()) { t= as_tree (call (string ("bib-compile"), bib, style, bib_t)); call (string ("bib-attach"), bib, bib_t); } else { std_error << "Could not load BibTeX file " << fname; set_message ("Could not find bibliography file", "compile bibliography"); return; } } else t= bibtex_load_bbl (bib, bbl_file); } else { if (!bibtex_present () && !starts (style, "tm-")) { if (style == "abbrv") style= "tm-abbrv"; else if (style == "acm") style= "tm-acm"; else if (style == "alpha") style= "tm-alpha"; else if (style == "elsart-num") style= "tm-elsart-num"; else if (style == "ieeetr") style= "tm-ieeetr"; else if (style == "siam") style= "tm-siam"; else if (style == "unsrt") style= "tm-unsrt"; else style= "tm-plain"; } if (supports_db () && !is_rooted (bib_file)) bib_file= find_bib_file (buf->buf->name, fname, ".bib", true); if (supports_db ()) { //(void) call (string ("bib-import-bibtex"), bib_file); t= as_tree (call (string ("bib-compile"), bib, style, bib_t, bib_file)); } else if (starts (style, "tm-")) { string sbib; if (load_string (bib_file, sbib, false)) std_error << "Could not load BibTeX file " << fname; tree te= bib_entries (parse_bib (sbib), bib_t); object ot= tree_to_stree (te); eval ("(use-modules (bibtex " * style (3, N(style)) * "))"); t= stree_to_tree (call (string ("bib-process"), bib, style (3, N(style)), ot)); } else t= bibtex_run (bib, style, bib_file, bib_t); if (supports_db ()) (void) call (string ("bib-attach"), bib, bib_t, bib_file); } if (is_atomic (t) && starts (t->label, "Error:")) set_message (t->label, "compile bibliography"); else if (is_compound (t) && N(t) > 0) insert_tree (t); }
VOID relp3() { int aindex, rindex; int mode, rtp; a_uint relv; struct areax **a; struct sym **s; /* * Get area and symbol lists */ a = hp->a_list; s = hp->s_list; /* * Verify Area Mode */ if (eval() != (R3_WORD | R3_AREA) || eval()) { fprintf(stderr, "P input error\n"); lkerr++; } /* * Get area pointer */ aindex = (int) evword(); if (aindex >= hp->h_narea) { fprintf(stderr, "P area error\n"); lkerr++; return; } /* * Do remaining relocations */ while (more()) { mode = (int) eval(); rtp = (int) eval(); rindex = (int) evword(); /* * R3_SYM or R3_AREA references */ if (mode & R3_SYM) { if (rindex >= hp->h_nsym) { fprintf(stderr, "P symbol error\n"); lkerr++; return; } relv = symval(s[rindex]); } else { if (rindex >= hp->h_narea) { fprintf(stderr, "P area error\n"); lkerr++; return; } relv = a[rindex]->a_addr; } adb_2b(relv, rtp); } /* * Paged values */ aindex = (int) adb_2b(0, 2); if (aindex >= hp->h_narea) { fprintf(stderr, "P area error\n"); lkerr++; return; } sdp.s_areax = a[aindex]; sdp.s_area = sdp.s_areax->a_bap; sdp.s_addr = adb_2b(0, 4); if (sdp.s_area->a_addr & 0xFF || sdp.s_addr & 0xFF) relerp3("Page Definition Boundary Error"); }
static type eval(Seq const& seq, Case const& case_) { return eval(seq, case_, is_default_case<Case>()); }