void do_predict(FILE *input, FILE *output) { int correct = 0; int total = 0; double error = 0; double sump = 0, sumt = 0, sumpp = 0, sumtt = 0, sumpt = 0; int nr_class=get_nr_class(model_); double *prob_estimates=NULL; int j, n; int nr_feature=get_nr_feature(model_); if(model_->bias>=0) n=nr_feature+1; else n=nr_feature; if(flag_predict_probability) { int *labels; if(!check_probability_model(model_)) { fprintf(stderr, "probability output is only supported for logistic regression\n"); exit(1); } labels=(int *) malloc(nr_class*sizeof(int)); get_labels(model_,labels); prob_estimates = (double *) malloc(nr_class*sizeof(double)); fprintf(output,"labels"); for(j=0;j<nr_class;j++) fprintf(output," %d",labels[j]); fprintf(output,"\n"); free(labels); } max_line_len = 1024; line = (char *)malloc(max_line_len*sizeof(char)); while(readline(input) != NULL) { int i = 0; double target_label, predict_label; char *idx, *val, *label, *endptr; int inst_max_index = 0; // strtol gives 0 if wrong format label = strtok(line," \t\n"); if(label == NULL) // empty line exit_input_error(total+1); target_label = strtod(label,&endptr); if(endptr == label || *endptr != '\0') exit_input_error(total+1); while(1) { if(i>=max_nr_attr-2) // need one more for index = -1 { max_nr_attr *= 2; x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node)); } idx = strtok(NULL,":"); val = strtok(NULL," \t"); if(val == NULL) break; errno = 0; x[i].index = (int) strtol(idx,&endptr,10); if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index) exit_input_error(total+1); else inst_max_index = x[i].index; errno = 0; x[i].value = strtod(val,&endptr); if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr))) exit_input_error(total+1); // feature indices larger than those in training are not used if(x[i].index <= nr_feature) ++i; } if(model_->bias>=0) { x[i].index = n; x[i].value = model_->bias; i++; } x[i].index = -1; if(flag_predict_probability) { int j; predict_label = predict_probability(model_,x,prob_estimates); fprintf(output,"%g",predict_label); for(j=0;j<model_->nr_class;j++) fprintf(output," %g",prob_estimates[j]); fprintf(output,"\n"); } else { predict_label = predict(model_,x); fprintf(output,"%g\n",predict_label); } if(predict_label == target_label) ++correct; error += (predict_label-target_label)*(predict_label-target_label); sump += predict_label; sumt += target_label; sumpp += predict_label*predict_label; sumtt += target_label*target_label; sumpt += predict_label*target_label; ++total; } if(model_->param.solver_type==L2R_L2LOSS_SVR || model_->param.solver_type==L2R_L1LOSS_SVR_DUAL || model_->param.solver_type==L2R_L2LOSS_SVR_DUAL) { info("Mean squared error = %g (regression)\n",error/total); info("Squared correlation coefficient = %g (regression)\n", ((total*sumpt-sump*sumt)*(total*sumpt-sump*sumt))/ ((total*sumpp-sump*sump)*(total*sumtt-sumt*sumt)) ); } else info("Accuracy = %g%% (%d/%d)\n",(double) correct/total*100,correct,total); if(flag_predict_probability) free(prob_estimates); }
int main(int argc, char **args) { // Test variable. int success_test = 1; if (argc < 2) error("Not enough parameters."); // Load the mesh. Mesh mesh; H3DReader mloader; if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]); // Initialize the space. #if defined NONLIN1 Ord3 order(1, 1, 1); #else Ord3 order(2, 2, 2); #endif H1Space space(&mesh, bc_types, essential_bc_values, order); #if defined NONLIN2 // Do L2 projection of zero function. WeakForm proj_wf; proj_wf.add_matrix_form(biproj_form<double, scalar>, biproj_form<Ord, Ord>, HERMES_SYM); proj_wf.add_vector_form(liproj_form<double, scalar>, liproj_form<Ord, Ord>); bool is_linear = true; DiscreteProblem lp(&proj_wf, &space, is_linear); // Initialize the solver in the case of SOLVER_PETSC or SOLVER_MUMPS. initialize_solution_environment(matrix_solver, argc, args); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver_proj = create_linear_solver(matrix_solver, matrix, rhs); // Initialize the preconditioner in the case of SOLVER_AZTECOO. if (matrix_solver == SOLVER_AZTECOO) { ((AztecOOSolver*) solver_proj)->set_solver(iterative_method); ((AztecOOSolver*) solver_proj)->set_precond(preconditioner); // Using default iteration parameters (see solver/aztecoo.h). } // Assemble the linear problem. info("Assembling (ndof: %d).", Space::get_num_dofs(&space)); lp.assemble(matrix, rhs); // Solve the linear system. info("Solving."); if(!solver_proj->solve()); error ("Matrix solver failed.\n"); delete matrix; delete rhs; #endif // Initialize the weak formulation. WeakForm wf(1); wf.add_matrix_form(0, 0, jacobi_form<double, scalar>, jacobi_form<Ord, Ord>, HERMES_UNSYM); wf.add_vector_form(0, resid_form<double, scalar>, resid_form<Ord, Ord>); // Initialize the FE problem. #if defined NONLIN2 is_linear = false; #else bool is_linear = false; #endif DiscreteProblem dp(&wf, &space, is_linear); NoxSolver solver(&dp); #if defined NONLIN2 solver.set_init_sln(solver_proj->get_solution()); delete solver_proj; #endif solver.set_conv_iters(10); info("Solving."); Solution sln(&mesh); if(solver.solve()) Solution::vector_to_solution(solver.get_solution(), &space, &sln); else error ("Matrix solver failed.\n"); Solution ex_sln(&mesh); #ifdef NONLIN1 ex_sln.set_const(100.0); #else ex_sln.set_exact(exact_solution); #endif // Calculate exact error. info("Calculating exact error."); Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM); bool solutions_for_adapt = false; double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS); if (err_exact > EPS) // Calculated solution is not precise enough. success_test = 0; if (success_test) { info("Success!"); return ERR_SUCCESS; } else { info("Failure!"); return ERR_FAILURE; } }
/* * slurm_allocate_resources_blocking * allocate resources for a job request. This call will block until * the allocation is granted, or the specified timeout limit is reached. * IN req - description of resource allocation request * IN timeout - amount of time, in seconds, to wait for a response before * giving up. * A timeout of zero will wait indefinitely. * IN pending_callback - If the allocation cannot be granted immediately, * the controller will put the job in the PENDING state. If * pending callback is not NULL, it will be called with the job_id * of the pending job as the sole parameter. * * RET allocation structure on success, NULL on error set errno to * indicate the error (errno will be ETIMEDOUT if the timeout is reached * with no allocation granted) * NOTE: free the response using slurm_free_resource_allocation_response_msg() */ resource_allocation_response_msg_t * slurm_allocate_resources_blocking (const job_desc_msg_t *user_req, time_t timeout, void(*pending_callback)(uint32_t job_id)) { int rc; slurm_msg_t req_msg; slurm_msg_t resp_msg; resource_allocation_response_msg_t *resp = NULL; char *hostname = NULL; uint32_t job_id; job_desc_msg_t *req; listen_t *listen = NULL; int errnum = SLURM_SUCCESS; slurm_msg_t_init(&req_msg); slurm_msg_t_init(&resp_msg); /* make a copy of the user's job description struct so that we * can make changes before contacting the controller */ req = (job_desc_msg_t *)xmalloc(sizeof(job_desc_msg_t)); if (req == NULL) return NULL; memcpy(req, user_req, sizeof(job_desc_msg_t)); /* * set Node and session id for this request */ if (req->alloc_sid == NO_VAL) req->alloc_sid = getsid(0); if (user_req->alloc_node != NULL) { req->alloc_node = xstrdup(user_req->alloc_node); } else if ((hostname = xshort_hostname()) != NULL) { req->alloc_node = hostname; } else { error("Could not get local hostname," " forcing immediate allocation mode."); req->immediate = 1; } if (!req->immediate) { listen = _create_allocation_response_socket(hostname); if (listen == NULL) { xfree(req->alloc_node); xfree(req); return NULL; } req->alloc_resp_port = listen->port; } req_msg.msg_type = REQUEST_RESOURCE_ALLOCATION; req_msg.data = req; rc = slurm_send_recv_controller_msg(&req_msg, &resp_msg); if (rc == SLURM_SOCKET_ERROR) { int errnum = errno; destroy_forward(&req_msg.forward); destroy_forward(&resp_msg.forward); if (!req->immediate) _destroy_allocation_response_socket(listen); xfree(req->alloc_node); xfree(req); errno = errnum; return NULL; } switch (resp_msg.msg_type) { case RESPONSE_SLURM_RC: if (_handle_rc_msg(&resp_msg) < 0) { /* will reach this when the allocation fails */ errnum = errno; } else { /* shouldn't get here */ errnum = -1; } break; case RESPONSE_RESOURCE_ALLOCATION: /* Yay, the controller has acknowledged our request! But did we really get an allocation yet? */ resp = (resource_allocation_response_msg_t *) resp_msg.data; if (resp->node_cnt > 0) { /* yes, allocation has been granted */ errno = SLURM_PROTOCOL_SUCCESS; } else if (!req->immediate) { if (resp->error_code != SLURM_SUCCESS) info("%s", slurm_strerror(resp->error_code)); /* no, we need to wait for a response */ job_id = resp->job_id; slurm_free_resource_allocation_response_msg(resp); if (pending_callback != NULL) pending_callback(job_id); resp = _wait_for_allocation_response(job_id, listen, timeout); /* If NULL, we didn't get the allocation in the time desired, so just free the job id */ if ((resp == NULL) && (errno != ESLURM_ALREADY_DONE)) { errnum = errno; slurm_complete_job(job_id, -1); } } break; default: errnum = SLURM_UNEXPECTED_MSG_ERROR; resp = NULL; } destroy_forward(&req_msg.forward); destroy_forward(&resp_msg.forward); if (!req->immediate) _destroy_allocation_response_socket(listen); xfree(req->alloc_node); xfree(req); errno = errnum; return resp; }
// VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV // Engine code below. You shouldn't need to // code down here, EXCEPT for if you need to read // WM_CHAR messages. /////////////////////////////////////////// // WndProc says: I AM WHERE "MESSAGES" GET "DISPATCHED" TO, // WHEN "EVENTS" "HAPPEN" TO YOUR WINDOW. LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam ) { // WndProc is WHERE you respond to // all messages that might happen // to your window. // When a key is pushed, when a mouse is clicked, // you can DO SOMETHING about that here, in WndProc switch( message ) { // We can call each of these "case traps" // an "event handler". These tidbits of code // "handle" the event where the user just // clicked in our window, or the user pressed a key. // A lot of these have been stripped away // vs the GDI+ version of this project.. // Here, we only handle a few select // messages... // WM_CHAR: for 'character' key presses // We use this for the user to type their name or something, // with proper preservation of capslocked letters etc case WM_CHAR: { info( "You pushed %c, ascii=%d", wparam, wparam ) ; window->sendCharacter( wparam ) ; } return 0 ; // WM_INPUT messages are for FAST keyboard and mouse // These messages are FASTER than WM_KEYDOWN or WM_MOUSEMOVE. // Both keyboard AND mouse input events get picked up here case WM_INPUT: { #pragma region pick up the raw input // DO NOT CODE HERE! use the // window->justPressed(), and // window->mouseJustPressed() functions, // in your Update() function. UINT dwSize; GetRawInputData( (HRAWINPUT)lparam, RID_INPUT, NULL, &dwSize, sizeof( RAWINPUTHEADER ) ) ; LPBYTE lpb = new BYTE[ dwSize ] ; if( lpb == NULL ) { return 0; } if( GetRawInputData( (HRAWINPUT)lparam, RID_INPUT, lpb, &dwSize, sizeof(RAWINPUTHEADER)) != dwSize ) { error( "GetRawInputData doesn't return correct size !" ) ; } RAWINPUT *raw = (RAWINPUT*)lpb; // Check if it was keyboard or mouse input. if (raw->header.dwType == RIM_TYPEKEYBOARD) { // We don't take keyboard input here. // We take it by using GetKeyboardState() function // in the window->step() function. //printRawKeyboard( raw ) ; // just so you can see } else if (raw->header.dwType == RIM_TYPEMOUSE) { //printRawMouse( raw ) ; // just so you can see window->mouseUpdateInput( raw ) ; } delete[] lpb ; #pragma endregion return 0; } case WM_ACTIVATE: switch( LOWORD(wparam) ) { case WA_ACTIVE: // got focus via alt-tab or something case WA_CLICKACTIVE: // got focus via mouse click on window { info( "Welcome back!" ) ; } break; case WA_INACTIVE: // LOST FOCUS!! OH NO!! { // This means the user is "focused" / has highlighted // another window other than our window. // You should probably pause the game here, // because some apps tend to hijack the input focus // which makes it really annoying. info( "But why would you click away?" ) ; } } return 0 ; case WM_PAINT: { // Let's NOT paint here anymore. // See Draw() function instead. HDC hdc ; PAINTSTRUCT ps; hdc = BeginPaint( hwnd, &ps ) ; // DO NOT PAINT HERE. EndPaint( hwnd, &ps ); // tell Windows that // we are done painting } return 0 ; case WM_DESTROY: PostQuitMessage( 0 ) ; return 0 ; } return DefWindowProc( hwnd, message, wparam, lparam ) ; }
void OKClicked() { info( "The ok button was clicked" ) ; window->deleteButton( ButtonOK ) ; }
/*! Gets the vaule of the synchronous option. \return True if request is synchronous , false if asynchronous. */ bool XQRequestInfo::isSynchronous() const { XQSERVICE_DEBUG_PRINT("XQRequestInfo::isSynchronous"); return info(XQServiceUtils::OptSynchronous).toBool(); }
/*! Get the value of the background option. \return True if option has been set on, false otherwise. */ bool XQRequestInfo::isBackground() const { XQSERVICE_DEBUG_PRINT("XQRequestInfo::isBackground"); return info(XQServiceUtils::OptBackground).toBool(); }
static void buildBlockHeaders() { info("pass 1 -- walk all blocks and build headers ..."); size_t nbBlocks = 0; size_t baseOffset = 0; size_t earlyMissCnt = 0; uint8_t buf[8+gHeaderSize]; const auto sz = sizeof(buf); const auto startTime = Timer::usecs(); const auto oneMeg = 1024 * 1024; for(const auto &blockFile : blockFiles) { startBlockFile(0); while(1) { auto nbRead = read(blockFile.fd, buf, sz); if(nbRead<(signed)sz) { break; } startBlock((uint8_t*)0); uint8_t *hash = 0; Block *prevBlock = 0; size_t blockSize = 0; getBlockHeader( blockSize, prevBlock, hash, earlyMissCnt, buf ); if(unlikely(0==hash)) { break; } auto where = lseek(blockFile.fd, (blockSize + 8) - sz, SEEK_CUR); auto blockOffset = where - blockSize; if(where<0) { break; } auto block = Block::alloc(); block->init(hash, &blockFile, blockSize, prevBlock, blockOffset); gBlockMap[hash] = block; endBlock((uint8_t*)0); ++nbBlocks; } baseOffset += blockFile.size; auto now = Timer::usecs(); auto elapsed = now - startTime; auto bytesPerSec = baseOffset / (elapsed*1e-6); auto bytesLeft = gChainSize - baseOffset; auto secsLeft = bytesLeft / bytesPerSec; fprintf( stderr, " %.2f%% (%.2f/%.2f Gigs) -- %6d blocks -- %.2f Megs/sec -- ETA %.0f secs -- ELAPSED %.0f secs \r", (100.0*baseOffset)/gChainSize, baseOffset/(1000.0*oneMeg), gChainSize/(1000.0*oneMeg), (int)nbBlocks, bytesPerSec*1e-6, secsLeft, elapsed*1e-6 ); fflush(stderr); endBlockFile(0); } if(0==nbBlocks) { warning("found no blocks - giving up "); exit(1); } char msg[128]; msg[0] = 0; if(0<earlyMissCnt) { sprintf(msg, ", %d early link misses", (int)earlyMissCnt); } auto elapsed = 1e-6*(Timer::usecs() - startTime); info( "pass 1 -- took %.0f secs, %6d blocks, %.2f Gigs, %.2f Megs/secs %s, mem=%.3f Gigs ", elapsed, (int)nbBlocks, (gChainSize * 1e-9), (gChainSize * 1e-6) / elapsed, msg, getMem() ); }
PageRunner::PageRunner(const QStringList& args) : QWebPage(0), out(stdout), err(stderr), view(new QWidget()) { QMap<QString, QString> settings = parseArguments(args); QStringList arguments = args.mid(settings.size() * 2); exportpdf = settings.value("export-pdf"); exportpng = settings.value("export-png"); url = QUrl(arguments[0]); nativeio = new NativeIO(this, QFileInfo(arguments[0]).dir(), QDir::current()); if (url.scheme() == "file" || url.isRelative()) { QFileInfo info(arguments[0]); url = QUrl::fromLocalFile(info.absoluteFilePath()); if (!info.isReadable() || !info.isFile()) { QTextStream err(stderr); err << "Cannot read file '" + url.toString() + "'.\n"; qApp->exit(1); } } nam = new NAM(this, QUrl(url).host(), QUrl(url).port()); setNetworkAccessManager(nam); connect(this, SIGNAL(loadFinished(bool)), this, SLOT(finished(bool))); connect(mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(slotInitWindowObjects())); sawJSError = false; setView(view); scriptMode = arguments[0].endsWith(".js"); if (scriptMode) { QByteArray html = "'" + arguments[0].toUtf8().replace('\'', "\\'") + "'"; for (int i = 1; i < arguments.length(); ++i) { html += ",'" + arguments[i].toUtf8().replace('\'', "\\'") + "'"; } html = "<html>" "<head><title></title>" "<script>var arguments=[" + html + "];</script>" "<script src=\"" + arguments[0].toUtf8() + "\"></script>"; // add runtime modification html += "<script>//<![CDATA[\n" + getRuntimeBindings() + "if (typeof(runtime) !== 'undefined' && typeof(nativeio) !== 'undefined') {\n" " runtime.libraryPaths = function () {" " /* convert to javascript array */" " var p = nativeio.libraryPaths()," " a = [], i;" " for (i in p) { a[i] = p[i]; }" " return a;" " };}//]]></script>"; html += "</head><body></body></html>\n"; QTemporaryFile tmp("XXXXXX.html"); tmp.setAutoRemove(true); tmp.open(); tmp.write(html); tmp.close(); QFileInfo info(tmp.fileName()); mainFrame()->load(QUrl::fromLocalFile(info.absoluteFilePath())); } else { // Make the url absolute. If it is not done here, QWebFrame will do // it, and it will lose the query and fragment part. QUrl absurl; if (url.isRelative()) { absurl = QUrl::fromLocalFile(QFileInfo(url.toLocalFile()).absoluteFilePath()); absurl.setQueryItems(url.queryItems()); absurl.setFragment(url.fragment()); } else { absurl = url; } mainFrame()->load(absurl); } }
static int builtin_blkid(struct udev_device *dev, int argc, char *argv[], bool test) { struct udev *udev = udev_device_get_udev(dev); int64_t offset = 0; bool noraid = false; int fd = -1; blkid_probe pr; const char *data; const char *name; int nvals; int i; size_t len; int err = 0; static const struct option options[] = { { "offset", optional_argument, NULL, 'o' }, { "noraid", no_argument, NULL, 'R' }, {} }; for (;;) { int option; option = getopt_long(argc, argv, "oR", options, NULL); if (option == -1) break; switch (option) { case 'o': offset = strtoull(optarg, NULL, 0); break; case 'R': noraid = true; break; } } pr = blkid_new_probe(); if (!pr) { err = -ENOMEM; return EXIT_FAILURE; } blkid_probe_set_superblocks_flags(pr, BLKID_SUBLKS_LABEL | BLKID_SUBLKS_UUID | BLKID_SUBLKS_TYPE | BLKID_SUBLKS_SECTYPE | BLKID_SUBLKS_USAGE | BLKID_SUBLKS_VERSION); if (noraid) blkid_probe_filter_superblocks_usage(pr, BLKID_FLTR_NOTIN, BLKID_USAGE_RAID); fd = open(udev_device_get_devnode(dev), O_RDONLY|O_CLOEXEC); if (fd < 0) { fprintf(stderr, "error: %s: %m\n", udev_device_get_devnode(dev)); goto out; } err = blkid_probe_set_device(pr, fd, offset, 0); if (err < 0) goto out; info(udev, "probe %s %sraid offset=%llu\n", udev_device_get_devnode(dev), noraid ? "no" : "", (unsigned long long) offset); err = probe_superblocks(pr); if (err < 0) goto out; nvals = blkid_probe_numof_values(pr); for (i = 0; i < nvals; i++) { if (blkid_probe_get_value(pr, i, &name, &data, &len)) continue; len = strnlen((char *) data, len); print_property(dev, test, name, (char *) data); } blkid_free_probe(pr); out: if (fd > 0) close(fd); if (err < 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { // Choose a Butcher's table or define your own. ButcherTable bt(butcher_table_type); // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("cathedral.mesh", &mesh); // Perform initial mesh refinements. for(int i = 0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(BDY_AIR, INIT_REF_NUM_BDY); mesh.refine_towards_boundary(BDY_GROUND, INIT_REF_NUM_BDY); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<std::string>(BDY_GROUND)); bc_types.add_bc_newton(BDY_AIR); // Enter Dirichlet boundary values. BCValues bc_values; bc_values.add_const(BDY_GROUND, TEMP_INIT); // Initialize an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d.", ndof); // Previous time level solution (initialized by the external temperature). Solution u_prev_time(&mesh, TEMP_INIT); // Initialize weak formulation. WeakForm wf; wf.add_matrix_form(callback(stac_jacobian)); wf.add_vector_form(callback(stac_residual)); wf.add_matrix_form_surf(callback(bilinear_form_surf), BDY_AIR); wf.add_vector_form_surf(callback(linear_form_surf), BDY_AIR); // Project the initial condition on the FE space to obtain initial solution coefficient vector. info("Projecting initial condition to translate initial condition into a vector."); scalar* coeff_vec = new scalar[ndof]; OGProjection::project_global(&space, &u_prev_time, coeff_vec, matrix_solver); // Initialize the FE problem. bool is_linear = false; DiscreteProblem dp(&wf, &space, is_linear); // Initialize views. ScalarView Tview("Temperature", new WinGeom(0, 0, 450, 600)); //Tview.set_min_max_range(0,20); Tview.fix_scale_width(30); // Time stepping loop: double current_time = 0.0; int ts = 1; do { // Perform one Runge-Kutta time step according to the selected Butcher's table. info("Runge-Kutta time step (t = %g, tau = %g, stages: %d).", current_time, time_step, bt.get_size()); bool verbose = true; bool is_linear = true; if (!rk_time_step(current_time, time_step, &bt, coeff_vec, &dp, matrix_solver, verbose, is_linear)) { error("Runge-Kutta time step failed, try to decrease time step size."); } // Convert coeff_vec into a new time level solution. Solution::vector_to_solution(coeff_vec, &space, &u_prev_time); // Update time. current_time += time_step; // Show the new time level solution. char title[100]; sprintf(title, "Time %3.2f, exterior temperature %3.5f", current_time, temp_ext(current_time)); Tview.set_title(title); Tview.show(&u_prev_time); // Increase counter of time steps. ts++; } while (current_time < T_FINAL); // Cleanup. delete [] coeff_vec; // Wait for the view to be closed. View::wait(); return 0; }
int main(int argc, char* argv[]) { // Load the mesh Mesh mesh; H2DReader mloader; mloader.load("domain.mesh", &mesh); // initial uniform mesh refinement for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Initialize the shapeset and the cache H1Shapeset shapeset; PrecalcShapeset pss(&shapeset); // Create finite element space H1Space space(&mesh, &shapeset); space.set_bc_types(bc_types); space.set_bc_values(bc_values); space.set_uniform_order(P_INIT); // Enumerate basis functions space.assign_dofs(); // initialize the weak formulation WeakForm wf(1); wf.add_biform(0, 0, bilinear_form_1, bilinear_form_ord, SYM, 1); wf.add_biform(0, 0, bilinear_form_2, bilinear_form_ord, SYM, 2); wf.add_biform(0, 0, bilinear_form_3, bilinear_form_ord, SYM, 3); wf.add_biform(0, 0, bilinear_form_4, bilinear_form_ord, SYM, 4); wf.add_biform(0, 0, bilinear_form_5, bilinear_form_ord, SYM, 5); wf.add_liform(0, linear_form_1, linear_form_ord, 1); wf.add_liform(0, linear_form_3, linear_form_ord, 3); // Visualize solution and mesh ScalarView sview("Coarse solution", 0, 100, 798, 700); OrderView oview("Polynomial orders", 800, 100, 798, 700); // Matrix solver UmfpackSolver solver; // DOF and CPU convergence graphs SimpleGraph graph_dof, graph_cpu; // prepare selector RefinementSelectors::H1NonUniformHP selector(ISO_ONLY, ADAPT_TYPE, 1.0, H2DRS_DEFAULT_ORDER, &shapeset); // Adaptivity loop int it = 1, ndofs; bool done = false; double cpu = 0.0; Solution sln_coarse, sln_fine; do { info("\n---- Adaptivity step %d ---------------------------------------------\n", it++); // Time measurement begin_time(); // Solve the coarse mesh problem LinSystem ls(&wf, &solver); ls.set_spaces(1, &space); ls.set_pss(1, &pss); ls.assemble(); ls.solve(1, &sln_coarse); // Time measurement cpu += end_time(); // View the solution and mesh sview.show(&sln_coarse); oview.show(&space); // Time measurement begin_time(); // Solve the fine mesh problem RefSystem rs(&ls); rs.assemble(); rs.solve(1, &sln_fine); // Calculate error estimate wrt. fine mesh solution H1AdaptHP hp(1, &space); double err_est = hp.calc_error(&sln_coarse, &sln_fine) * 100; info("Estimate of error: %g%%", err_est); // add entry to DOF convergence graph graph_dof.add_values(space.get_num_dofs(), err_est); graph_dof.save("conv_dof.dat"); // add entry to CPU convergence graph graph_cpu.add_values(cpu, err_est); graph_cpu.save("conv_cpu.dat"); // If err_est too large, adapt the mesh if (err_est < ERR_STOP) done = true; else { hp.adapt(THRESHOLD, STRATEGY, &selector, MESH_REGULARITY); ndofs = space.assign_dofs(); if (ndofs >= NDOF_STOP) done = true; } // Time measurement cpu += end_time(); } while (done == false); verbose("Total running time: %g sec", cpu); // Show the fine solution - this is the final result sview.set_title("Final solution"); sview.show(&sln_fine); oview.set_title("Final orders"); oview.show(&space); // Wait for keyboard or mouse input View::wait(); return 0; }
Expression::Ptr ExpressionFactory::createExpression(const QString &expr, const StaticContext::Ptr &context, const LanguageAccent lang, const SequenceType::Ptr &requiredType, const QUrl &queryURI) { pDebug() << Q_FUNC_INFO << queryURI; Q_ASSERT(context); Q_ASSERT(requiredType); Q_ASSERT(queryURI.isValid()); OptimizationPasses::Coordinator::init(); ParserContext::Ptr info(new ParserContext(context, lang, Tokenizer::Ptr(new XQueryTokenizer(expr, queryURI)))); const int bisonRetval = XPathparse(info.data()); Q_ASSERT_X(bisonRetval == 0, Q_FUNC_INFO, "We shouldn't be able to get an error, because we throw exceptions."); Q_UNUSED(bisonRetval); /* Needed when not compiled in debug mode, since bisonRetval won't * be used in the Q_ASSERT_X above. */ Expression::Ptr result(info->queryBody); if(!result) { context->error(QtXmlPatterns::tr("A library module cannot be evaluated " "directly. It must be imported from a " "main module."), ReportContext::XPST0003, QSourceLocation(queryURI, 1, 1)); } /* Here, we type check user declared functions and global variables. This means * that variables and functions that are not used are type checked(which they otherwise * wouldn't have been), and those which are used, are type-checked twice, unfortunately. */ const UserFunction::List::const_iterator end(info->userFunctions.constEnd()); UserFunction::List::const_iterator it(info->userFunctions.constBegin()); for(; it != end; ++it) { pDebug() << "----- User Function Typecheck -----"; registerLastPath((*it)->body()); /* We will most likely call body()->typeCheck() again, once for each callsite. That is, it will * be called from UserFunctionCallsite::typeCheck(), which will be called indirectly when * we check the query body. */ const Expression::Ptr typeCheck((*it)->body()->typeCheck(context, (*it)->signature()->returnType())); /* We don't have to call (*it)->setBody(typeCheck) here since it's only used directly below. */ processTreePass(typeCheck, UserFunctionTypeCheck); pDebug() << "------------------------------"; pDebug() << "----- User Function Compress -----"; const Expression::Ptr comp(typeCheck->compress(context)); (*it)->setBody(comp); processTreePass(comp, UserFunctionCompression); pDebug() << "------------------------------"; } const VariableDeclaration::Stack::const_iterator vend(info->variables.constEnd()); VariableDeclaration::Stack::const_iterator vit(info->variables.constBegin()); for(; vit != vend; ++vit) { Q_ASSERT(*vit); /* If it's already used, it will be typeChecked later on. */ if((*vit)->isUsed() || (*vit)->type == VariableDeclaration::ExternalVariable) continue; pDebug() << "----- Global Variable Typecheck -----"; Q_ASSERT((*vit)->expression()); /* We supply ZeroOrMoreItems, meaning the variable can evaluate to anything. */ // FIXME which is a source to bugs // TODO What about compressing variables? const Expression::Ptr nev((*vit)->expression()->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems)); processTreePass(nev, GlobalVariableTypeCheck); pDebug() << "------------------------------"; } pDebug() << "----- Initial AST build. -----"; processTreePass(result, QueryBodyInitial); pDebug() << "------------------------------"; pDebug() << "----- Type Check -----"; registerLastPath(result); result->rewrite(result, result->typeCheck(context, requiredType), context); processTreePass(result, QueryBodyTypeCheck); pDebug() << "------------------------------"; pDebug() << "----- Compress -----"; result->rewrite(result, result->compress(context), context); processTreePass(result, QueryBodyCompression); pDebug() << "------------------------------"; return result; }
static void parse_commandline(int argc, char* argv[], char** bathyfname, char** gridfname, char** maskfname, NODETYPE* nt, int* ppe, double* zmin, double* zmax, int* ii, int* jj) { int i; if (argc <= 1) usage(); i = 1; while (i < argc) { switch (argv[i][1]) { case 'a': i++; if (i >= argc) quit("no interpolation rule number found after -a"); rule = atoi(argv[i]); if (rule < CSA || rule > AVERAGE) quit("invalid interpolation rule number"); i++; break; case 'b': i++; if (i >= argc) quit("no file name found after -b"); *bathyfname = argv[i]; i++; break; case 'c': i++; if (i >= argc) quit("no cell <i> index found after -c"); *ii = atof(argv[i]); i++; if (i >= argc) quit("no cell <j> index found after -c"); *jj = atof(argv[i]); i++; break; case 'g': i++; if (i >= argc) quit("no file name found after -g"); *gridfname = argv[i]; i++; break; case 'h': info(); break; case 'i': i++; if (i == argc) quit("no node type found after \"-i\""); if (strcasecmp("dd", argv[i]) == 0) *nt = NT_DD; else if (strcasecmp("ce", argv[i]) == 0) *nt = NT_CEN; else if (strcasecmp("co", argv[i]) == 0) *nt = NT_COR; else quit("input node type \"%s\" not recognised", argv[i]); i++; break; case 'm': i++; if (i == argc) quit("no file name found after \"-m\""); *maskfname = argv[i]; i++; break; case 'n': i++; if (i >= argc) quit("no points per edge value found after -n"); if (!str2int(argv[i], ppe)) quit("error: could not read points per edge after -n"); i++; break; case 'r': i++; if (i >= argc) quit("no min depth found after -r"); if (!str2double(argv[i], zmin)) quit("error: could not read min depth after -r"); i++; if (i >= argc) quit("no max depth found after -r"); if (!str2double(argv[i], zmax)) quit("could not read max depth after -r"); i++; break; case 'v': i++; gu_verbose = 1; break; case 'x': i++; indexspace = 1; break; default: usage(); break; } } if (gu_verbose && argc == 2) version(); }
XMLNODE *XMLParseFile(XSLTGLOBALDATA *gctx, char *file) { info("XMLParseFile:: file %s", file); return xml_parse_file(gctx, xml_strdup(file), 0); }
/* * _thread_update_node_energy calls _read_ipmi_values and updates all values * for node consumption */ static int _update_node_filesystem(void) { static acct_filesystem_data_t previous; static int dataset_id = -1; static bool first = true; acct_filesystem_data_t current; enum { FIELD_READ, FIELD_READMB, FIELD_WRITE, FIELD_WRITEMB, FIELD_CNT }; acct_gather_profile_dataset_t dataset[] = { { "Reads", PROFILE_FIELD_UINT64 }, { "ReadMB", PROFILE_FIELD_DOUBLE }, { "Writes", PROFILE_FIELD_UINT64 }, { "WriteMB", PROFILE_FIELD_DOUBLE }, { NULL, PROFILE_FIELD_NOT_SET } }; union { double d; uint64_t u64; } data[FIELD_CNT]; slurm_mutex_lock(&lustre_lock); if (_read_lustre_counters() != SLURM_SUCCESS) { error("%s: Cannot read lustre counters", __func__); slurm_mutex_unlock(&lustre_lock); return SLURM_FAILURE; } if (first) { dataset_id = acct_gather_profile_g_create_dataset("Network", NO_PARENT, dataset); if (dataset_id == SLURM_ERROR) { error("FileSystem: Failed to create the dataset " "for Lustre"); return SLURM_ERROR; } previous.reads = lustre_se.all_lustre_nb_reads; previous.writes = lustre_se.all_lustre_nb_writes; previous.read_size = (double)lustre_se.all_lustre_read_bytes; previous.write_size = (double)lustre_se.all_lustre_write_bytes; first = false; } if (dataset_id < 0) { slurm_mutex_unlock(&lustre_lock); return SLURM_ERROR; } /* Compute the current values read from all lustre-xxxx directories */ current.reads = lustre_se.all_lustre_nb_reads; current.writes = lustre_se.all_lustre_nb_writes; current.read_size = (double)lustre_se.all_lustre_read_bytes; current.write_size = (double)lustre_se.all_lustre_write_bytes; /* record sample */ data[FIELD_READ].u64 = current.reads - previous.reads; data[FIELD_READMB].d = (current.read_size - previous.read_size) / (1 << 20); data[FIELD_WRITE].u64 = current.writes - previous.writes; data[FIELD_WRITEMB].d = (current.write_size - previous.write_size) / (1 << 20); if (debug_flags & DEBUG_FLAG_PROFILE) { char str[256]; info("PROFILE-Lustre: %s", acct_gather_profile_dataset_str( dataset, data, str, sizeof(str))); } acct_gather_profile_g_add_sample_data(dataset_id, (void *)data, lustre_se.update_time); /* Save current as previous and clean up the working * data structure. */ memcpy(&previous, ¤t, sizeof(acct_filesystem_data_t)); memset(&lustre_se, 0, sizeof(lustre_sens_t)); slurm_mutex_unlock(&lustre_lock); return SLURM_SUCCESS; }
static int add_transp_af(const struct sa *laddr) { struct sa local; int err = 0; if (str_isset(uag.cfg->local)) { err = sa_decode(&local, uag.cfg->local, str_len(uag.cfg->local)); if (err) { err = sa_set_str(&local, uag.cfg->local, 0); if (err) { warning("ua: decode failed: '%s'\n", uag.cfg->local); return err; } } if (!sa_isset(&local, SA_ADDR)) { uint16_t port = sa_port(&local); (void)sa_set_sa(&local, &laddr->u.sa); sa_set_port(&local, port); } if (sa_af(laddr) != sa_af(&local)) return 0; } else { sa_cpy(&local, laddr); sa_set_port(&local, 0); } if (uag.use_udp) err |= sip_transp_add(uag.sip, SIP_TRANSP_UDP, &local); if (uag.use_tcp) err |= sip_transp_add(uag.sip, SIP_TRANSP_TCP, &local); if (err) { warning("ua: SIP Transport failed: %m\n", err); return err; } #ifdef USE_TLS if (uag.use_tls) { /* Build our SSL context*/ if (!uag.tls) { const char *cert = NULL; if (str_isset(uag.cfg->cert)) { cert = uag.cfg->cert; info("SIP Certificate: %s\n", cert); } err = tls_alloc(&uag.tls, TLS_METHOD_SSLV23, cert, NULL); if (err) { warning("ua: tls_alloc() failed: %m\n", err); return err; } } if (sa_isset(&local, SA_PORT)) sa_set_port(&local, sa_port(&local) + 1); err = sip_transp_add(uag.sip, SIP_TRANSP_TLS, &local, uag.tls); if (err) { warning("ua: SIP/TLS transport failed: %m\n", err); return err; } } #endif return err; }
static int run_program0(struct space *space, const char *command0, char *result, size_t ressize, size_t *reslen, int log) { int retval = 0; int status; int outpipe[2] = {-1, -1}; int errpipe[2] = {-1, -1}; pid_t pid; char arg[PATH_SIZE]; char program[PATH_SIZE]; char *argv[(sizeof(arg) / 2) + 1]; int devnull; int i; /* build argv from comand */ strlcpy(arg, command0, sizeof(arg)); i = 0; if (strchr(arg, ' ') != NULL) { char *pos = arg; while (pos != NULL) { if (pos[0] == '\'') { /* don't separate if in apostrophes */ pos++; argv[i] = strsep(&pos, "\'"); while (pos != NULL && pos[0] == ' ') pos++; } else { argv[i] = strsep(&pos, " "); } dbg("arg[%i] '%s'", i, argv[i]); i++; } argv[i] = NULL; } else { argv[0] = arg; argv[1] = NULL; } info("'%s'", command0); /* prepare pipes from child to parent */ if (result || log) { if (pipe(outpipe) != 0) { Perror(space, "pipe failed: %s", strerror(errno)); return -1; } } if (log) { if (pipe(errpipe) != 0) { Perror(space, "pipe failed: %s", strerror(errno)); return -1; } } /* allow programs in /lib/alsa called without the path */ if (strchr(argv[0], '/') == NULL) { strlcpy(program, "/lib/alsa/", sizeof(program)); strlcat(program, argv[0], sizeof(program)); argv[0] = program; } pid = fork(); switch(pid) { case 0: /* child closes parent ends of pipes */ if (outpipe[READ_END] > 0) close(outpipe[READ_END]); if (errpipe[READ_END] > 0) close(errpipe[READ_END]); /* discard child output or connect to pipe */ devnull = open("/dev/null", O_RDWR); if (devnull > 0) { dup2(devnull, STDIN_FILENO); if (outpipe[WRITE_END] < 0) dup2(devnull, STDOUT_FILENO); if (errpipe[WRITE_END] < 0) dup2(devnull, STDERR_FILENO); close(devnull); } else Perror(space, "open /dev/null failed: %s", strerror(errno)); if (outpipe[WRITE_END] > 0) { dup2(outpipe[WRITE_END], STDOUT_FILENO); close(outpipe[WRITE_END]); } if (errpipe[WRITE_END] > 0) { dup2(errpipe[WRITE_END], STDERR_FILENO); close(errpipe[WRITE_END]); } execv(argv[0], argv); /* we should never reach this */ Perror(space, "exec of program '%s' failed", argv[0]); _exit(1); case -1: Perror(space, "fork of '%s' failed: %s", argv[0], strerror(errno)); return -1; default: /* read from child if requested */ if (outpipe[READ_END] > 0 || errpipe[READ_END] > 0) { ssize_t count; size_t respos = 0; /* parent closes child ends of pipes */ if (outpipe[WRITE_END] > 0) close(outpipe[WRITE_END]); if (errpipe[WRITE_END] > 0) close(errpipe[WRITE_END]); /* read child output */ while (outpipe[READ_END] > 0 || errpipe[READ_END] > 0) { int fdcount; fd_set readfds; FD_ZERO(&readfds); if (outpipe[READ_END] > 0) FD_SET(outpipe[READ_END], &readfds); if (errpipe[READ_END] > 0) FD_SET(errpipe[READ_END], &readfds); fdcount = select(MY_MAX(outpipe[READ_END], errpipe[READ_END])+1, &readfds, NULL, NULL, NULL); if (fdcount < 0) { if (errno == EINTR) continue; retval = -1; break; } /* get stdout */ if (outpipe[READ_END] > 0 && FD_ISSET(outpipe[READ_END], &readfds)) { char inbuf[1024]; char *pos; char *line; count = read(outpipe[READ_END], inbuf, sizeof(inbuf)-1); if (count <= 0) { close(outpipe[READ_END]); outpipe[READ_END] = -1; if (count < 0) { Perror(space, "stdin read failed: %s", strerror(errno)); retval = -1; } continue; } inbuf[count] = '\0'; /* store result for rule processing */ if (result) { if (respos + count < ressize) { memcpy(&result[respos], inbuf, count); respos += count; } else { Perror(space, "ressize %ld too short", (long)ressize); retval = -1; } } pos = inbuf; while ((line = strsep(&pos, "\n"))) if (pos || line[0] != '\0') info("'%s' (stdout) '%s'", argv[0], line); } /* get stderr */ if (errpipe[READ_END] > 0 && FD_ISSET(errpipe[READ_END], &readfds)) { char errbuf[1024]; char *pos; char *line; count = read(errpipe[READ_END], errbuf, sizeof(errbuf)-1); if (count <= 0) { close(errpipe[READ_END]); errpipe[READ_END] = -1; if (count < 0) Perror(space, "stderr read failed: %s", strerror(errno)); continue; } errbuf[count] = '\0'; pos = errbuf; while ((line = strsep(&pos, "\n"))) if (pos || line[0] != '\0') info("'%s' (stderr) '%s'", argv[0], line); } } if (outpipe[READ_END] > 0) close(outpipe[READ_END]); if (errpipe[READ_END] > 0) close(errpipe[READ_END]); /* return the childs stdout string */ if (result) { result[respos] = '\0'; dbg("result='%s'", result); if (reslen) *reslen = respos; } } waitpid(pid, &status, 0); if (WIFEXITED(status)) { info("'%s' returned with status %i", argv[0], WEXITSTATUS(status)); if (WEXITSTATUS(status) != 0) retval = -1; } else { Perror(space, "'%s' abnormal exit", argv[0]); retval = -1; } } return retval; }
/*! Get embedded option value. \return True if embedded mode is turned on, false otherwise. */ bool XQRequestInfo::isEmbedded() const { XQSERVICE_DEBUG_PRINT("XQRequestInfo::isEmbedded"); return info(XQServiceUtils::OptEmbedded).toBool(); }
/** * usb_hcd_omap_probe - initialize OMAP-based HCDs * Context: !in_interrupt() * * Allocates basic resources for this USB host controller, and * then invokes the start() method for the HCD associated with it * through the hotplug entry's driver_data. * * Store this function in the HCD's struct pci_driver as probe(). */ int usb_hcd_omap_probe (const struct hc_driver *driver, struct usb_hcd **hcd_out, struct omap_dev *dev) { int retval; struct usb_hcd *hcd = 0; if (!request_mem_region(dev->res.start, dev->res.end - dev->res.start + 1, hcd_name)) { dbg("request_mem_region failed"); return -EBUSY; } omap_start_hc(dev); hcd = driver->hcd_alloc (); if (hcd == NULL){ dbg ("hcd_alloc failed"); retval = -ENOMEM; goto err1; } hcd->driver = (struct hc_driver *) driver; hcd->description = driver->description; hcd->irq = dev->irq[0]; hcd->regs = dev->mapbase; hcd->self.controller = &dev->dev; retval = hcd_buffer_create (hcd); if (retval != 0) { dbg ("pool alloc fail"); goto err1; } retval = request_irq (hcd->irq, usb_hcd_omap_hcim_irq, SA_INTERRUPT, hcd->description, hcd); if (retval != 0) { dbg("request_irq failed"); retval = -EBUSY; goto err2; } info ("%s (OMAP) at 0x%p, irq %d\n", hcd->description, hcd->regs, hcd->irq); usb_bus_init (&hcd->self); hcd->self.op = &usb_hcd_operations; hcd->self.hcpriv = (void *) hcd; hcd->self.bus_name = "omap"; hcd->product_desc = "OMAP OHCI"; INIT_LIST_HEAD (&hcd->dev_list); usb_register_bus (&hcd->self); if ((retval = driver->start (hcd)) < 0) { usb_hcd_omap_remove(hcd, dev); return retval; } *hcd_out = hcd; return 0; err2: hcd_buffer_destroy (hcd); if (hcd) driver->hcd_free(hcd); err1: omap_stop_hc(dev); release_mem_region(dev->res.start, dev->res.end - dev->res.start + 1); return retval; }
static int store_file_load(void(*receive_msg)(Msg*)) { List *keys; Octstr *store_file, *key; Msg *msg; int retval, msgs; long end, pos; if (filename == NULL) return 0; mutex_lock(file_mutex); if (file != NULL) { fclose(file); file = NULL; } store_file = octstr_read_file(octstr_get_cstr(filename)); if (store_file != NULL) info(0, "Loading store file `%s'", octstr_get_cstr(filename)); else { store_file = octstr_read_file(octstr_get_cstr(newfile)); if (store_file != NULL) info(0, "Loading store file `%s'", octstr_get_cstr(newfile)); else { store_file = octstr_read_file(octstr_get_cstr(bakfile)); if (store_file != NULL) info(0, "Loading store file `%s'", octstr_get_cstr(bakfile)); else { info(0, "Cannot open any store file, starting a new one"); retval = open_file(filename); goto end; } } } info(0, "Store-file size %ld, starting to unpack%s", octstr_len(store_file), octstr_len(store_file) > 10000 ? " (may take awhile)" : ""); pos = 0; msgs = 0; end = octstr_len(store_file); while (pos < end) { if (read_msg(&msg, store_file, &pos) == -1) { error(0, "Garbage at store-file, skipped."); continue; } if (msg_type(msg) == sms) { store_to_dict(msg); msgs++; } else if (msg_type(msg) == ack) { store_to_dict(msg); } else { warning(0, "Strange message in store-file, discarded, " "dump follows:"); msg_dump(msg, 0); } msg_destroy(msg); } octstr_destroy(store_file); info(0, "Retrieved %d messages, non-acknowledged messages: %ld", msgs, dict_key_count(sms_dict)); /* now create a new sms_store out of messages left */ keys = dict_keys(sms_dict); while ((key = gwlist_extract_first(keys)) != NULL) { msg = dict_remove(sms_dict, key); if (store_to_dict(msg) != -1) { receive_msg(msg); } else { error(0, "Found unknown message type in store file."); msg_dump(msg, 0); msg_destroy(msg); } octstr_destroy(key); } gwlist_destroy(keys, octstr_destroy_item); /* Finally, generate new store file out of left messages */ retval = do_dump(); end: mutex_unlock(file_mutex); /* allow using of store */ gwlist_remove_producer(loaded); /* start dumper thread */ if ((cleanup_thread = gwthread_create(store_dumper, NULL))==-1) panic(0, "Failed to create a cleanup thread!"); return retval; }
cString cPluginSatip::SVDRPCommand(const char *commandP, const char *optionP, int &replyCodeP) { debug1("%s (%s, %s,)", __PRETTY_FUNCTION__, commandP, optionP); if (strcasecmp(commandP, "INFO") == 0) { int index = cDevice::ActualDevice()->CardIndex(); int page = SATIP_DEVICE_INFO_ALL; char *opt = strdup(optionP); char *num = skipspace(opt); char *option = num; while (*option && !isspace(*option)) ++option; if (*option) { *option = 0; option = skipspace(++option); if (isnumber(option)) index = atoi(option); } if (isnumber(num)) { page = atoi(num); if ((page < SATIP_DEVICE_INFO_ALL) || (page > SATIP_DEVICE_INFO_FILTERS)) page = SATIP_DEVICE_INFO_ALL; } free(opt); cSatipDevice *device = cSatipDevice::GetSatipDevice(index); if (device) { return device->GetInformation(page); } else { replyCodeP = 550; // Requested action not taken return cString("SATIP information not available!"); } } else if (strcasecmp(commandP, "MODE") == 0) { unsigned int mode = !SatipConfig.GetUseBytes(); SatipConfig.SetUseBytes(mode); return cString::sprintf("SATIP information mode: %s\n", mode ? "bytes" : "bits"); } else if (strcasecmp(commandP, "LIST") == 0) { cString list = cSatipDiscover::GetInstance()->GetServerList(); if (!isempty(list)) { return list; } else { replyCodeP = 550; // Requested action not taken return cString("No SATIP servers detected!"); } } else if (strcasecmp(commandP, "SCAN") == 0) { cSatipDiscover::GetInstance()->TriggerScan(); return cString("SATIP server scan requested"); } else if (strcasecmp(commandP, "STAT") == 0) { return cSatipDevice::GetSatipStatus(); } else if (strcasecmp(commandP, "CONT") == 0) { return cString::sprintf("SATIP device count: %u", cSatipDevice::Count()); } else if (strcasecmp(commandP, "OPER") == 0) { cString mode; unsigned int oper = SatipConfig.GetOperatingMode(); if (optionP && *optionP) { if (strcasecmp(optionP, "off") == 0) oper = cSatipConfig::eOperatingModeOff; else if (strcasecmp(optionP, "low") == 0) oper = cSatipConfig::eOperatingModeLow; else if (strcasecmp(optionP, "normal") == 0) oper = cSatipConfig::eOperatingModeNormal; else if (strcasecmp(optionP, "high") == 0) oper = cSatipConfig::eOperatingModeHigh; SatipConfig.SetOperatingMode(oper); } switch (oper) { case cSatipConfig::eOperatingModeOff: mode = "off"; break; case cSatipConfig::eOperatingModeLow: mode = "low"; break; case cSatipConfig::eOperatingModeNormal: mode = "normal"; break; case cSatipConfig::eOperatingModeHigh: mode = "high"; break; default: mode = "unknown"; break; } return cString::sprintf("SATIP operating mode: %s\n", *mode); } else if (strcasecmp(commandP, "ATTA") == 0) { SatipConfig.SetDetachedMode(false); info("SATIP servers attached"); return cString("SATIP servers attached"); } else if (strcasecmp(commandP, "DETA") == 0) { SatipConfig.SetDetachedMode(true); info("SATIP servers detached"); return cString("SATIP servers detached"); } else if (strcasecmp(commandP, "TRAC") == 0) { if (optionP && *optionP) SatipConfig.SetTraceMode(strtol(optionP, NULL, 0)); return cString::sprintf("SATIP tracing mode: 0x%04X\n", SatipConfig.GetTraceMode()); } return NULL; }
// In a windows program, instead of main(), we use WinMain() // Refer to earlier lessons for comments and more detail. int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow ) { // Setup a console consoleCreate() ; consoleWhite() ; consoleMove( 32, 500 ) ; consoleRowsAndCols( 10, 120 ) ; // Start up the log. logStartup() ; // Put these after log start up, b/c start up inits them with some init values logOutputsForConsole = LOG_ERROR | LOG_WARNING | LOG_INFO ; // See ERROR and WARNING messages at Console. logOutputsForFile = LOG_ERROR | LOG_WARNING | LOG_INFO ; // See all types of messages in file logOutputsForDebugStream = LOG_ERROR | LOG_WARNING ; // See all ERROR and WARNING messages at debugstream. Suppress 'info()' messages. // Start up GDI+, which we use to draw // For GDI+, used only for shape render GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); // Setup the window window = new GameWindow( hInstance, TEXT( "eternity engine base" ), 32, 32, // x pos, y pos 640, 480 // width, height ) ; // After the window comes up, we call Init // to load the game's content Init() ; MSG message ; while( 1 ) { if( PeekMessage( &message, NULL, 0, 0, PM_REMOVE ) ) { if( message.message == WM_QUIT ) // if we got a WM_QUIT message.. { break ; // ..then end the program by jumping out of the while(1) loop. } // Send the message over to WndProc for // further processing. TranslateMessage( &message ) ; DispatchMessage( &message ) ; } else { // Run our game, one frame Update() ; window->step() ; // ^^ update fmod engine, grab updated keystates, etc. // Draw the game out, all at once if( window->beginDrawing() ) // only continue if beginDrawing() succeeds { Draw() ; window->endDrawing() ; } } } info( "Game over!" ) ; logShutdown() ; GdiplusShutdown(gdiplusToken); //system( "pause" ) ; // uncomment to make it pause before exit return 0 ; }
int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("domain.mesh", &mesh); mesh.refine_all_elements(); // Enter boundary markers. BCTypes bc_types; bc_types.add_bc_dirichlet(Hermes::vector<int>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER)); // Enter Dirichlet boudnary values. BCValues bc_values; bc_values.add_function(Hermes::vector<int>(BDY_BOTTOM, BDY_OUTER, BDY_LEFT, BDY_INNER), essential_bc_values); // Create an H1 space with default shapeset. H1Space space(&mesh, &bc_types, &bc_values, P_INIT); int ndof = Space::get_num_dofs(&space); info("ndof = %d", ndof); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(callback(bilinear_form)); wf.add_vector_form(callback(linear_form)); // Testing n_dof and correctness of solution vector // for p_init = 1, 2, ..., 10 int success = 1; Solution sln; for (int p_init = 1; p_init <= 10; p_init++) { printf("********* p_init = %d *********\n", p_init); space.set_uniform_order(p_init); // Initialize the FE problem. bool is_linear = true; DiscreteProblem dp(&wf, &space, is_linear); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Initialize the solution. Solution sln; // Assemble the stiffness matrix and right-hand side vector. info("Assembling the stiffness matrix and right-hand side vector."); bool rhsonly = false; dp.assemble(matrix, rhs, rhsonly); // Solve the linear system and if successful, obtain the solution. info("Solving the matrix problem."); if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln); else error ("Matrix solver failed.\n"); int ndof = Space::get_num_dofs(&space); printf("ndof = %d\n", ndof); double sum = 0; for (int i=0; i < ndof; i++) sum += solver->get_solution()[i]; printf("coefficient sum = %g\n", sum); // Actual test. The values of 'sum' depend on the // current shapeset. If you change the shapeset, // you need to correct these numbers. if (p_init == 1 && fabs(sum - 1.7251) > 1e-3) success = 0; if (p_init == 2 && fabs(sum - 3.79195) > 1e-3) success = 0; if (p_init == 3 && fabs(sum - 3.80206) > 1e-3) success = 0; if (p_init == 4 && fabs(sum - 3.80156) > 1e-3) success = 0; if (p_init == 5 && fabs(sum - 3.80155) > 1e-3) success = 0; if (p_init == 6 && fabs(sum - 3.80154) > 1e-3) success = 0; if (p_init == 7 && fabs(sum - 3.80154) > 1e-3) success = 0; if (p_init == 8 && fabs(sum - 3.80153) > 1e-3) success = 0; if (p_init == 9 && fabs(sum - 3.80152) > 1e-3) success = 0; if (p_init == 10 && fabs(sum - 3.80152) > 1e-3) success = 0; } if (success == 1) { printf("Success!\n"); return ERR_SUCCESS; } else { printf("Failure!\n"); return ERR_FAILURE; } }
static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, char **params) { video_t *video = obs_encoder_video(obsx264->encoder); const struct video_output_info *voi = video_output_get_info(video); struct video_scale_info info; info.format = voi->format; info.colorspace = voi->colorspace; info.range = voi->range; obs_x264_video_info(obsx264, &info); int bitrate = (int)obs_data_get_int(settings, "bitrate"); int buffer_size = (int)obs_data_get_int(settings, "buffer_size"); int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); int crf = (int)obs_data_get_int(settings, "crf"); int width = (int)obs_encoder_get_width(obsx264->encoder); int height = (int)obs_encoder_get_height(obsx264->encoder); bool use_bufsize = obs_data_get_bool(settings, "use_bufsize"); bool vfr = obs_data_get_bool(settings, "vfr"); bool cbr = obs_data_get_bool(settings, "cbr"); if (keyint_sec) obsx264->params.i_keyint_max = keyint_sec * voi->fps_num / voi->fps_den; if (!use_bufsize) buffer_size = bitrate; obsx264->params.b_vfr_input = vfr; obsx264->params.rc.i_vbv_max_bitrate = bitrate; obsx264->params.rc.i_vbv_buffer_size = buffer_size; obsx264->params.rc.i_bitrate = bitrate; obsx264->params.i_width = width; obsx264->params.i_height = height; obsx264->params.i_fps_num = voi->fps_num; obsx264->params.i_fps_den = voi->fps_den; obsx264->params.pf_log = log_x264; obsx264->params.p_log_private = obsx264; obsx264->params.i_log_level = X264_LOG_WARNING; obsx264->params.vui.i_transfer = get_x264_cs_val(info.colorspace, x264_transfer_names); obsx264->params.vui.i_colmatrix = get_x264_cs_val(info.colorspace, x264_colmatrix_names); obsx264->params.vui.i_colorprim = get_x264_cs_val(info.colorspace, x264_colorprim_names); obsx264->params.vui.b_fullrange = info.range == VIDEO_RANGE_FULL; /* use the new filler method for CBR to allow real-time adjusting of * the bitrate */ if (cbr) { obsx264->params.rc.f_rf_constant = 0.0f; obsx264->params.rc.i_rc_method = X264_RC_ABR; #if X264_BUILD >= 139 obsx264->params.rc.b_filler = true; #else obsx264->params.i_nal_hrd = X264_NAL_HRD_CBR; #endif } else { obsx264->params.rc.i_rc_method = X264_RC_CRF; obsx264->params.rc.f_rf_constant = (float)crf; } if (info.format == VIDEO_FORMAT_NV12) obsx264->params.i_csp = X264_CSP_NV12; else if (info.format == VIDEO_FORMAT_I420) obsx264->params.i_csp = X264_CSP_I420; else if (info.format == VIDEO_FORMAT_I444) obsx264->params.i_csp = X264_CSP_I444; else obsx264->params.i_csp = X264_CSP_NV12; while (*params) set_param(obsx264, *(params++)); info("settings:\n" "\tbitrate: %d\n" "\tbuffer size: %d\n" "\tcrf: %d%s\n" "\tfps_num: %d\n" "\tfps_den: %d\n" "\twidth: %d\n" "\theight: %d\n" "\tkeyint: %d\n" "\tvfr: %s\n" "\tcbr: %s", obsx264->params.rc.i_vbv_max_bitrate, obsx264->params.rc.i_vbv_buffer_size, (int)obsx264->params.rc.f_rf_constant, cbr ? " (0 when CBR is enabled)" : "", voi->fps_num, voi->fps_den, width, height, obsx264->params.i_keyint_max, vfr ? "on" : "off", cbr ? "on" : "off"); }
int sensor_3h7_sunny_probe(struct i2c_client *client, const struct i2c_device_id *id) { int ret = 0; struct fimc_is_core *core; struct v4l2_subdev *subdev_module; struct fimc_is_module_enum *module; struct fimc_is_device_sensor *device; struct sensor_open_extended *ext; BUG_ON(!fimc_is_dev); core = (struct fimc_is_core *)dev_get_drvdata(fimc_is_dev); if (!core) { err("core device is not yet probed"); return -EPROBE_DEFER; } device = &core->sensor[SENSOR_S5K3H7_SUNNY_INSTANCE]; subdev_module = kzalloc(sizeof(struct v4l2_subdev), GFP_KERNEL); if (!subdev_module) { err("subdev_module is NULL"); ret = -ENOMEM; goto p_err; } module = &device->module_enum[atomic_read(&core->resourcemgr.rsccount_module)]; atomic_inc(&core->resourcemgr.rsccount_module); module->id = SENSOR_NAME_S5K3H7_SUNNY; module->subdev = subdev_module; module->device = SENSOR_S5K3H7_SUNNY_INSTANCE; module->client = client; module->active_width = 3248; module->active_height = 2438; module->pixel_width = module->active_width + 16; module->pixel_height = module->active_height + 10; module->max_framerate = 30; module->position = SENSOR_POSITION_REAR; module->mode = CSI_MODE_CH0_ONLY; module->lanes = CSI_DATA_LANES_4; module->sensor_maker = "SLSI"; module->sensor_name = "S5K3H7"; module->setfile_name = "setfile_3h7_sunny.bin"; module->cfgs = ARRAY_SIZE(config_3h7_sunny); module->cfg = config_3h7_sunny; module->ops = NULL; module->private_data = NULL; ext = &module->ext; ext->mipi_lane_num = module->lanes; ext->I2CSclk = I2C_L0; ext->sensor_con.product_name = 0; ext->sensor_con.peri_type = SE_I2C; ext->sensor_con.peri_setting.i2c.channel = SENSOR_CONTROL_I2C0; ext->sensor_con.peri_setting.i2c.slave_address = 0x20; ext->sensor_con.peri_setting.i2c.speed = 400000; ext->actuator_con.product_name = ACTUATOR_NAME_DWXXXX; ext->actuator_con.peri_type = SE_I2C; ext->actuator_con.peri_setting.i2c.channel = SENSOR_CONTROL_I2C0; ext->actuator_con.peri_setting.i2c.slave_address = 0x20; ext->actuator_con.peri_setting.i2c.speed = 400000; #if defined(CONFIG_EXYNOS5260_XYREF_REV0) ext->flash_con.product_name = FLADRV_NAME_NOTHING; #else ext->flash_con.product_name = FLADRV_NAME_AS3643; #endif ext->flash_con.peri_type = SE_I2C; ext->flash_con.peri_setting.gpio.first_gpio_port_no = 5; #if defined(CONFIG_MACH_XYREF4415) ext->flash_con.peri_setting.gpio.second_gpio_port_no = 6; #else ext->flash_con.peri_setting.gpio.second_gpio_port_no = 8; #endif ext->from_con.product_name = FROMDRV_NAME_NOTHING; ext->companion_con.product_name = COMPANION_NAME_NOTHING; if (client) v4l2_i2c_subdev_init(subdev_module, client, &subdev_ops); else v4l2_subdev_init(subdev_module, &subdev_ops); v4l2_set_subdevdata(subdev_module, module); v4l2_set_subdev_hostdata(subdev_module, device); snprintf(subdev_module->name, V4L2_SUBDEV_NAME_SIZE, "sensor-subdev.%d", module->id); p_err: info("%s(%d)\n", __func__, ret); return ret; }
// Convert to Printlines void Layer::MakePrintlines(Vector3d &lastPos, //GCodeState &state, vector<PLine3> &lines3, double offsetZ, Settings &settings) const { const double linewidth = settings.GetExtrudedMaterialWidth(thickness); const double cornerradius = linewidth*settings.get_double("Slicing","CornerRadius"); const bool clipnearest = settings.get_boolean("Slicing","MoveNearest"); const uint supportExtruder = settings.GetSupportExtruder(); const double minshelltime = settings.get_double("Slicing","MinShelltime"); const double maxshellspeed = settings.get_double("Extruder","MaxShellSpeed"); const bool ZliftAlways = settings.get_boolean("Extruder","ZliftAlways"); Vector2d startPoint(lastPos.x(),lastPos.y()); const double extr_per_mm = settings.GetExtrusionPerMM(thickness); //vector<PLine3> lines3; Printlines printlines(this, &settings, offsetZ); vector<PLine2> lines; vector<Poly> polys; // intermediate collection // polys to keep line movements inside //const vector<Poly> * clippolys = &polygons; const vector<Poly> clippolys = GetOuterShell(); // 1. Skins, all but last, because they are the lowest lines, below layer Z if (skins > 1) { for(uint s = 0; s < skins; s++) { // z offset from bottom to top: double skin_z = Z - thickness + (s+1)*thickness/skins; if ( skin_z < 0 ){ cerr << "Skin Z<0! " << s << " -- " << Z << " -- "<<skin_z <<" -- " << thickness << endl; continue; } // skin infill polys: if (skinFullInfills[s]) polys.insert(polys.end(), skinFullInfills[s]->infillpolys.begin(), skinFullInfills[s]->infillpolys.end()); // add skin infill to lines printlines.addPolys(INFILL, polys, false); polys.clear(); // make polygons at skin_z: for(size_t p = 0; p < skinPolygons.size(); p++) { polys.push_back(Poly(skinPolygons[p], skin_z)); } // add skin to lines printlines.addPolys(SKIN, polys, (s==0), // displace at first skin maxshellspeed * 60, minshelltime); if (s < skins-1) { // not on the last layer, this handle with all other lines // have to get all these separately because z changes printlines.makeLines(startPoint, lines); if (!ZliftAlways) printlines.clipMovements(clippolys, lines, clipnearest, linewidth); printlines.optimize(linewidth, minshelltime, cornerradius, lines); printlines.getLines(lines, lines3, extr_per_mm); printlines.clear(); lines.clear(); } polys.clear(); } } // last skin layer now still in lines lines.clear(); // 2. Skirt printlines.addPolys(SKIRT, skirtPolygons, false, maxshellspeed * 60, minshelltime); // 3. Support if (supportInfill) { uint extruderbefore = settings.selectedExtruder; settings.SelectExtruder(supportExtruder); printlines.addPolys(SUPPORT, supportInfill->infillpolys, false); settings.SelectExtruder(extruderbefore); } // 4. all other polygons: // Shells for(int p=shellPolygons.size()-1; p>=0; p--) { // inner to outer //cerr << "displace " << p << endl; printlines.addPolys(SHELL, shellPolygons[p], (p==(int)(shellPolygons.size())-1), maxshellspeed * 60, minshelltime); } // Infill if (normalInfill) printlines.addPolys(INFILL, normalInfill->infillpolys, false); if (thinInfill) printlines.addPolys(INFILL, thinInfill->infillpolys, false); if (fullInfill) printlines.addPolys(INFILL, fullInfill->infillpolys, false); if (skirtInfill) printlines.addPolys(INFILL, skirtInfill->infillpolys, false); if (decorInfill) printlines.addPolys(INFILL, decorInfill->infillpolys, false); for (uint b=0; b < bridgeInfills.size(); b++) if (bridgeInfills[b]) printlines.addPolys(INFILL, bridgeInfills[b]->infillpolys, false); double polyspeedfactor = printlines.makeLines(startPoint, lines); // FINISH Command lchange(LAYERCHANGE, LayerNo); lchange.where = Vector3d(0.,0.,Z); lchange.comment += info(); lines3.push_back(PLine3(lchange)); if (!ZliftAlways) printlines.clipMovements(clippolys, lines, clipnearest, linewidth); printlines.optimize(linewidth, settings.get_double("Slicing","MinLayertime"), cornerradius, lines); if ((guint)LayerNo < (guint)settings.get_integer("Slicing","FirstLayersNum")) printlines.setSpeedFactor(settings.get_double("Slicing","FirstLayersSpeed"), lines); double slowdownfactor = printlines.getSlowdownFactor() * polyspeedfactor; if (settings.get_boolean("Slicing","FanControl")) { int fanspeed = settings.get_integer("Slicing","MinFanSpeed"); if (slowdownfactor < 1 && slowdownfactor > 0) { double fanfactor = 1-slowdownfactor; fanspeed += int(fanfactor * (settings.get_integer("Slicing","MaxFanSpeed")-settings.get_integer("Slicing","MinFanSpeed"))); fanspeed = CLAMP(fanspeed, settings.get_integer("Slicing","MinFanSpeed"), settings.get_integer("Slicing","MaxFanSpeed")); //cerr << slowdownfactor << " - " << fanfactor << " - " << fanspeed << " - " << endl; } Command fancommand(FANON, fanspeed); lines3.push_back(PLine3(fancommand)); } printlines.getLines(lines, lines3, extr_per_mm); if (lines3.size()>0) lastPos = lines3.back().to; }
XMLNODE *XMLParse(XSLTGLOBALDATA *gctx, char *document) { info("XMLParse:: document"); return xml_parse_string(gctx, document, 0); }
int main(int argc, char **args) { // Test variable. int success_test = 1; // Initialize the solver in the case of SOLVER_PETSC or SOLVER_MUMPS. initialize_solution_environment(matrix_solver, argc, args); for (int i = 0; i < 48; i++) { for (int j = 0; j < 48; j++) { info("Config: %d, %d ", i, j); Mesh mesh; for (unsigned int k = 0; k < countof(vtcs); k++) mesh.add_vertex(vtcs[k].x, vtcs[k].y, vtcs[k].z); unsigned int h1[] = { hexs[0][i][0] + 1, hexs[0][i][1] + 1, hexs[0][i][2] + 1, hexs[0][i][3] + 1, hexs[0][i][4] + 1, hexs[0][i][5] + 1, hexs[0][i][6] + 1, hexs[0][i][7] + 1 }; mesh.add_hex(h1); unsigned int h2[] = { hexs[1][j][0] + 1, hexs[1][j][1] + 1, hexs[1][j][2] + 1, hexs[1][j][3] + 1, hexs[1][j][4] + 1, hexs[1][j][5] + 1, hexs[1][j][6] + 1, hexs[1][j][7] + 1 }; mesh.add_hex(h2); // bc for (unsigned int k = 0; k < countof(bnd); k++) { unsigned int facet_idxs[Quad::NUM_VERTICES] = { bnd[k][0] + 1, bnd[k][1] + 1, bnd[k][2] + 1, bnd[k][3] + 1 }; mesh.add_quad_boundary(facet_idxs, bnd[k][4]); } mesh.ugh(); // Initialize the space. H1Space space(&mesh, bc_types, essential_bc_values); #ifdef XM_YN_ZO Ord3 ord(4, 4, 4); #elif defined XM_YN_ZO_2 Ord3 ord(4, 4, 4); #elif defined X2_Y2_Z2 Ord3 ord(2, 2, 2); #endif space.set_uniform_order(ord); // Initialize the weak formulation. WeakForm wf; #ifdef DIRICHLET wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM); wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>); #elif defined NEWTON wf.add_matrix_form(bilinear_form<double, scalar>, bilinear_form<Ord, Ord>, HERMES_SYM); wf.add_matrix_form_surf(bilinear_form_surf<double, scalar>, bilinear_form_surf<Ord, Ord>); wf.add_vector_form(linear_form<double, scalar>, linear_form<Ord, Ord>); wf.add_vector_form_surf(linear_form_surf<double, scalar>, linear_form_surf<Ord, Ord>); #endif // Initialize the FE problem. bool is_linear = true; DiscreteProblem dp(&wf, &space, is_linear); // Set up the solver, matrix, and rhs according to the solver selection. SparseMatrix* matrix = create_matrix(matrix_solver); Vector* rhs = create_vector(matrix_solver); Solver* solver = create_linear_solver(matrix_solver, matrix, rhs); // Initialize the preconditioner in the case of SOLVER_AZTECOO. if (matrix_solver == SOLVER_AZTECOO) { ((AztecOOSolver*) solver)->set_solver(iterative_method); ((AztecOOSolver*) solver)->set_precond(preconditioner); // Using default iteration parameters (see solver/aztecoo.h). } // Assemble the linear problem. info("Assembling (ndof: %d).", Space::get_num_dofs(&space)); dp.assemble(matrix, rhs); // Solve the linear system. If successful, obtain the solution. info("Solving."); Solution sln(space.get_mesh()); if(solver->solve()) Solution::vector_to_solution(solver->get_solution(), &space, &sln); else error ("Matrix solver failed.\n"); ExactSolution ex_sln(&mesh, exact_solution); // Calculate exact error. info("Calculating exact error."); Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM); bool solutions_for_adapt = false; double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS); if (err_exact > EPS) { // Calculated solution is not precise enough. success_test = 0; info("failed, error:%g", err_exact); } else info("passed"); // Clean up. delete matrix; delete rhs; delete solver; delete adaptivity; } } // Properly terminate the solver in the case of SOLVER_PETSC or SOLVER_MUMPS. finalize_solution_environment(matrix_solver); if (success_test) { info("Success!"); return ERR_SUCCESS; } else { info("Failure!"); return ERR_FAILURE; } }
void CASW_Weapon_Chainsaw::Fire( const Vector &vecOrigSrc, const Vector &vecDir ) { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) { return; } StopAttackOffSound(); StartChainsawSound(); if ( m_flFireAnimTime < gpGlobals->curtime ) { pMarine->DoAnimationEvent( PLAYERANIMEVENT_FIRE_GUN_PRIMARY ); m_flFireAnimTime = gpGlobals->curtime + 0.1f; } Vector vecDest = vecOrigSrc + (vecDir * ASW_CHAINSAW_RANGE); bool bDamageTime = m_flDmgTime < gpGlobals->curtime; bool bHit = false; Ray_t ray; ray.Init( vecOrigSrc, vecDest, Vector( -5, -5, -5 ), Vector( 5, 5, 25 ) ); CBaseEntity *(pEntities[ 8 ]); CHurtableEntitiesEnum hurtableEntities( pEntities, 8 ); partition->EnumerateElementsAlongRay( PARTITION_ENGINE_NON_STATIC_EDICTS | PARTITION_ENGINE_SOLID_EDICTS, ray, false, &hurtableEntities ); trace_t tr; for ( int i = 0; i < hurtableEntities.GetCount(); ++i ) { CBaseEntity *pEntity = pEntities[ i ]; if ( pEntity == NULL || pEntity == pMarine ) continue; bHit = true; if ( bDamageTime ) { // wide mode does damage to the ent, and radius damage if ( pEntity->m_takedamage != DAMAGE_NO ) { CTraceFilterOnlyHitThis filter( pEntity ); UTIL_TraceHull( vecOrigSrc, vecDest, Vector( -5, -5, -2 ), Vector( 5, 5, 25 ), MASK_SHOT, &filter, &tr ); ClearMultiDamage(); float fDamage = 0.5f * GetWeaponInfo()->m_flBaseDamage + MarineSkills()->GetSkillBasedValueByMarine( pMarine, ASW_MARINE_SKILL_MELEE, ASW_MARINE_SUBSKILL_MELEE_DMG ); CTakeDamageInfo info( this, pMarine, fDamage * g_pGameRules->GetDamageMultiplier(), DMG_SLASH ); info.SetWeapon( this ); CalculateMeleeDamageForce( &info, vecDir, tr.endpos ); pEntity->DispatchTraceAttack( info, vecDir, &tr ); ApplyMultiDamage(); } // radius damage a little more potent in multiplayer. #ifndef CLIENT_DLL //RadiusDamage( CTakeDamageInfo( this, pMarine, sk_plr_dmg_asw_ml.GetFloat() * g_pGameRules->GetDamageMultiplier() / 4, DMG_ENERGYBEAM | DMG_BLAST | DMG_ALWAYSGIB ), tr.endpos, 128, CLASS_NONE, NULL ); #endif } } if ( bHit ) { if ( bDamageTime ) { m_bIsFiring = true; m_flLastHitTime = gpGlobals->curtime; m_flTargetChainsawPitch = 0.0f; #ifndef CLIENT_DLL pMarine->OnWeaponFired( this, 1 ); #endif if ( !pMarine->IsAlive() ) return; // uses 5 ammo/second if ( gpGlobals->curtime >= m_flAmmoUseTime ) { // chainsaw no longer uses ammo m_flAmmoUseTime = gpGlobals->curtime + 0.2; /* // decrement ammo //m_iClip1 -= 1; #ifdef GAME_DLL CASW_Marine *pMarine = GetMarine(); if (pMarine && m_iClip1 <= 0 && pMarine->GetAmmoCount(m_iPrimaryAmmoType) <= 0 ) { // check he doesn't have ammo in an ammo bay CASW_Weapon_Ammo_Bag* pAmmoBag = dynamic_cast<CASW_Weapon_Ammo_Bag*>(pMarine->GetASWWeapon(0)); if (!pAmmoBag) pAmmoBag = dynamic_cast<CASW_Weapon_Ammo_Bag*>(pMarine->GetASWWeapon(1)); if (!pAmmoBag || !pAmmoBag->CanGiveAmmoToWeapon(this)) pMarine->GetMarineSpeech()->Chatter(CHATTER_NO_AMMO); } #endif */ } m_flDmgTime = gpGlobals->curtime + ASW_CHAINSAW_DISCHARGE_INTERVAL; if ( m_flShakeTime < gpGlobals->curtime ) { CASW_Player *pPlayer = pMarine->GetCommander(); if (pPlayer && pMarine->IsInhabited()) { // #ifndef CLIENT_DLL // if (gpGlobals->maxClients == 1) // only shake the screen from the server in singleplayer (in multi it'll be predicted) // { // ASW_TransmitShakeEvent( pPlayer, 5.0f, 100.0f, 1.75f, SHAKE_START ); // } // #else // ASW_TransmitShakeEvent( pPlayer, 5.0f, 100.0f, 1.75f, SHAKE_START ); // #endif } m_flShakeTime = gpGlobals->curtime + 0.5; } } Vector vecUp, vecRight; QAngle angDir; VectorAngles( vecDir, angDir ); AngleVectors( angDir, NULL, &vecRight, &vecUp ); Vector tmpSrc = vecOrigSrc + (vecUp * -8) + (vecRight * 3); //UTIL_ImpactTrace( &tr, DMG_SLASH ); UpdateEffect( tmpSrc, tr.endpos ); } }