void scan_bulk(const class scanner_params &sp,const recursion_control_block &rcb) { assert(sp.sp_version==scanner_params::CURRENT_SP_VERSION); // startup if(sp.phase==scanner_params::PHASE_STARTUP){ assert(sp.info->si_version==scanner_info::CURRENT_SI_VERSION); sp.info->name = "bulk"; sp.info->author = "Simson Garfinkel"; sp.info->description = "perform bulk data scan"; sp.info->flags = scanner_info::SCANNER_DISABLED | scanner_info::SCANNER_WANTS_NGRAMS | scanner_info::SCANNER_NO_ALL; sp.info->feature_names.insert("bulk"); sp.info->feature_names.insert("bulk_tags"); sp.info->get_config("bulk_block_size",&opt_bulk_block_size,"Block size (in bytes) for bulk data analysis"); debug = sp.info->config->debug; histogram::precalc_entropy_array(opt_bulk_block_size); sp.info->get_config("DFRWS2012",&dfrws_challenge,"True if running DFRWS2012 challenge code"); return; } // classify a buffer if(sp.phase==scanner_params::PHASE_SCAN){ feature_recorder *bulk = sp.fs.get_name("bulk"); feature_recorder *bulk_tags = sp.fs.get_name("bulk_tags"); if(sp.sbuf.pos0.isRecursive()){ /* Record the fact that a recursive call was made, which tells us about the data */ bulk_tags->write_tag(sp.sbuf,""); // tag that we found recursive data, not sure what kind } if(sp.sbuf.pagesize < opt_bulk_block_size) return; // can't analyze something that small // Loop through the sbuf in opt_bulk_block_size sized chunks // for each one, examine the entropy and scan for bitlocker (unfortunately hardcoded) // This needs to have a general plug-in architecture for(size_t base=0;base+opt_bulk_block_size<=sp.sbuf.pagesize;base+=opt_bulk_block_size){ sbuf_t sbuf(sp.sbuf,base,opt_bulk_block_size); bulk_ngram_entropy(sbuf,bulk,bulk_tags); bulk_bitlocker(sbuf,bulk,bulk_tags); } } // shutdown --- combine the results if we are in DFRWS mode if(sp.phase==scanner_params::PHASE_SHUTDOWN){ if(dfrws_challenge){ feature_recorder *bulk = sp.fs.get_name("bulk"); // First process the bulk_tags and lift_tags bulk_process_feature_file(bulk->outdir + "/bulk_tags.txt"); bulk_process_feature_file(bulk->outdir + "/lift_tags.txt"); // Process the remaining feature files dig d(bulk->outdir); for(dig::const_iterator it = d.begin(); it!=d.end(); ++it){ if(ends_with(*it,_TEXT("_tags.txt"))==false){ bulk_process_feature_file(*it); } } dfrws2012_bulk_process_dump(); } return; // no cleanup } }
static int stream_reset (GMimeStream *stream) { d(g_warning ("Invoked default stream_reset implementation.")); return 0; }
static gint64 stream_tell (GMimeStream *stream) { d(g_warning ("Invoked default stream_tell implementation.")); return stream->position; }
Int Interface::innerNormalDirection (Real & infeasible_gradient) { Real oldnormc = c->norm(); Vector d(*env), dcp(*env), dn(*env); Real ndn; Real alpha, Ared, Pred; Real one[2] = {1,0}; Real zero[2] = {0,0}; Int iout, naflag; Bool dnavail; Vector gtmp (*env); Vector xtmp (*xc), ctmp (*c), stmp (*env); Real normgtmp = 0; Aavail = dciFalse; Real scalingMatrix[nvar + nconI]; gtmp.sdmult (*J, 1, one, zero, ctmp); // g = J'*c pReal gtmpx = gtmp.get_doublex(); for (Int i = 0; i < nvar+nconI; i++) { Real gi = gtmpx[i], zi = xcx[i], ui = u_bndx[i], li = l_bndx[i]; if ( (gi < 0) && (ui < dciInf) ) { scalingMatrix[i] = 1.0/sqrt(ui - zi); } else if ( (gi > 0) && (li > -dciInf) ) { scalingMatrix[i] = 1.0/sqrt(zi - li); } else { scalingMatrix[i] = 1; } } normgtmp = gtmp.norm (); Vector gtmp_proj(*env); gtmp_proj.scale(gtmp, -1.0); projectBounds_xc(gtmp_proj); infeasible_gradient = gtmp_proj.norm(); // DeltaV = normgtmp; if (normgtmp < dciTiny) { normc = oldnormc; iout = 6; // std::cout << "iout = 6" << std::endl; return iout; } //Now with the infinity norm Real lower[nvar + nconI], upper[nvar + nconI]; for (Int i = 0; i < nvar+nconI; i++) { Real zi = xcx[i], li = l_bndx[i], ui = u_bndx[i]; lower[i] = Max( -DeltaV, (li > -dciInf ? (li - zi) * (1 - epsmu) : -dciInf) ); upper[i] = Min( DeltaV, (ui < dciInf ? (ui - zi) * (1 - epsmu) : dciInf) ); } Vector aux(*env); d = gtmp; pReal dx = 0; gtmpx = gtmp.get_doublex(); dx = d.get_doublex(); for (Int i = 0; i < nvar + nconI; i++) { gtmpx[i] /= scalingMatrix[i]; dx[i] = -dx[i]/pow(scalingMatrix[i], 2); } aux.sdmult(*J, 0, one, zero, d); alpha = Min(gtmp.dot(gtmp)/aux.dot(aux), DeltaV/gtmp.norm()); dcp.scale (d, alpha); pReal dcpx = dcp.get_doublex(); // alpha = -d.dot(gtmp)/aux.dot(aux); // alpha = Min(alpha, DeltaV/d.norm()); alpha = 1.0; for (int i = 0; i < nvar + nconI; i++) { Real di = dcpx[i], ui = upper[i], li = lower[i]; if (di > dciEps) { alpha = Min(alpha, ui/(di)); } else if (di < -dciEps) { alpha = Min(alpha, li/(di)); } else dcpx[i] = 0; } Real theta = 0.99995; if (alpha < 1) { alpha = Max(theta, 1 - dcp.norm())*alpha; dcp.scale(alpha); } /* for (Int i = 0; i < nvar + nconI; i++) * dcpx[i] *= scalingMatrix[i]; */ dnavail = dciFalse; ndn = 0; Ared = 0; Pred = 1; // DeltaV = DeltaV/kappa2; iout = 0; // For the inequalities pReal dnx = 0; dnavail = dciFalse; if (!dnavail) { naflag = naStep (*c, dn); dnavail = dciTrue; dnx = dn.get_doublex(); //Project this step alpha = 1.0; for (Int i = 0; i < nvar + nconI; i++) { Real di = dnx[i], ui = upper[i], li = lower[i]; if (di > dciEps) { alpha = Min(alpha, ui/di); } else if (di < -dciEps) { alpha = Min(alpha, li/di); } else di = 0; } if (alpha < 1) { alpha = Max(theta, 1 - dn.norm())*alpha; dn.scale(alpha); } if (naflag > 1) ndn = 0; else ndn = dn.norm (0); assert(ndn <= DeltaV || "ndn > DeltaV"); } /* ||a + b||^2 = <a+b,a+b> = <a,a> + 2*<a,b> + <b,b> */ /* m(d) = 0.5*||J*d + h||^2 * dtr = t*dn + (1 - t)*dcp * m(dtr) = 0.5*||J*(t*dn + (1-t)*dcp) + h||^2 * = 0.5*||J*dcp + h + t*J*(dn - dcp)||^2 * = 0.5*||J*dcp + h||^2 + t*(J*dcp + h)'*J*(dn - dcp) + 0.5*t^2*||J*(dn - dcp)||^2 */ Vector Adcph(*c), difdcdn(dn), Adif(*env); Adcph.sdmult(*J, 0, one, one, dcp); difdcdn.saxpy(dcp, -1); Adif.sdmult(*J, 0, one, zero, difdcdn); Real objValAdcph = 0.5*Adcph.dot(Adcph); Real dotAdcphAdif = Adcph.dot(Adif); Real halfSqrNormAdif = 0.5*Adif.dot(Adif); Real cauchyReduction = 0.5*oldnormc*oldnormc - objValAdcph; Real newtonReduction = cauchyReduction - dotAdcphAdif - halfSqrNormAdif; Real factor = 1.0; while (newtonReduction/cauchyReduction < beta1) { // Line search among from newton to cauchy factor *= 0.9; newtonReduction = cauchyReduction - factor*dotAdcphAdif - pow(factor,2)*halfSqrNormAdif; if (factor < 1e-8) { factor = 0; break; } } Vector xtemp(*xc); for (Int i = 0; i < nvar+nconI; i++) { if (l_bndx[i] - u_bndx[i] > -dciEps) continue; xcx[i] += (factor*dnx[i] + (1 - factor)*dcpx[i]); if (xcx[i] >= u_bndx[i]) xcx[i] = u_bndx[i] - dciEps; else if (xcx[i] <= l_bndx[i]) xcx[i] = l_bndx[i] + dciEps; } #ifndef NDEBUG checkInfactibility(); #endif call_ccfsg_xc(dciFalse); normc = c->norm (); Ared = 0.5*(oldnormc*oldnormc - normc*normc); Pred = newtonReduction; if (Ared/Pred < beta2) { DeltaV /= 4; *xc = xtmp; call_ccfsg_xc(dciFalse); normc = c->norm(); } else if (Ared/Pred > 0.75) { DeltaV *= 2; } if (normc < rho) return 0; current_time = getTime() - start_time; return 0; }
static ssize_t stream_write (GMimeStream *stream, const char *buf, size_t len) { d(g_warning ("Invoked default stream_write implementation.")); return 0; }
inline double solve_quadprog(MatrixXd & G, VectorXd & g0, const MatrixXd & CE, const VectorXd & ce0, const MatrixXd & CI, const VectorXd & ci0, VectorXd& x) { int i, j, k, l; /* indices */ int ip, me, mi; int n=g0.size(); int p=ce0.size(); int m=ci0.size(); MatrixXd R(G.rows(),G.cols()), J(G.rows(),G.cols()); LLT<MatrixXd,Lower> chol(G.cols()); VectorXd s(m+p), z(n), r(m + p), d(n), np(n), u(m + p); VectorXd x_old(n), u_old(m + p); double f_value, psi, c1, c2, sum, ss, R_norm; const double inf = std::numeric_limits<double>::infinity(); double t, t1, t2; /* t is the step length, which is the minimum of the partial step length t1 * and the full step length t2 */ VectorXi A(m + p), A_old(m + p), iai(m + p); int q; int iq, iter = 0; bool iaexcl[m + p]; me = p; /* number of equality constraints */ mi = m; /* number of inequality constraints */ q = 0; /* size of the active set A (containing the indices of the active constraints) */ /* * Preprocessing phase */ /* compute the trace of the original matrix G */ c1 = G.trace(); /* decompose the matrix G in the form LL^T */ chol.compute(G); /* initialize the matrix R */ d.setZero(); R.setZero(); R_norm = 1.0; /* this variable will hold the norm of the matrix R */ /* compute the inverse of the factorized matrix G^-1, this is the initial value for H */ // J = L^-T J.setIdentity(); J = chol.matrixU().solve(J); c2 = J.trace(); #ifdef TRACE_SOLVER print_matrix("J", J, n); #endif /* c1 * c2 is an estimate for cond(G) */ /* * Find the unconstrained minimizer of the quadratic form 0.5 * x G x + g0 x * this is a feasible point in the dual space * x = G^-1 * g0 */ x = chol.solve(g0); x = -x; /* and compute the current solution value */ f_value = 0.5 * g0.dot(x); #ifdef TRACE_SOLVER std::cerr << "Unconstrained solution: " << f_value << std::endl; print_vector("x", x, n); #endif /* Add equality constraints to the working set A */ iq = 0; for (i = 0; i < me; i++) { np = CE.col(i); compute_d(d, J, np); update_z(z, J, d, iq); update_r(R, r, d, iq); #ifdef TRACE_SOLVER print_matrix("R", R, iq); print_vector("z", z, n); print_vector("r", r, iq); print_vector("d", d, n); #endif /* compute full step length t2: i.e., the minimum step in primal space s.t. the contraint becomes feasible */ t2 = 0.0; if (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0 t2 = (-np.dot(x) - ce0(i)) / z.dot(np); x += t2 * z; /* set u = u+ */ u(iq) = t2; u.head(iq) -= t2 * r.head(iq); /* compute the new solution value */ f_value += 0.5 * (t2 * t2) * z.dot(np); A(i) = -i - 1; if (!add_constraint(R, J, d, iq, R_norm)) { // FIXME: it should raise an error // Equality constraints are linearly dependent return f_value; } } /* set iai = K \ A */ for (i = 0; i < mi; i++) iai(i) = i; l1: iter++; #ifdef TRACE_SOLVER print_vector("x", x, n); #endif /* step 1: choose a violated constraint */ for (i = me; i < iq; i++) { ip = A(i); iai(ip) = -1; } /* compute s(x) = ci^T * x + ci0 for all elements of K \ A */ ss = 0.0; psi = 0.0; /* this value will contain the sum of all infeasibilities */ ip = 0; /* ip will be the index of the chosen violated constraint */ for (i = 0; i < mi; i++) { iaexcl[i] = true; sum = CI.col(i).dot(x) + ci0(i); s(i) = sum; psi += std::min(0.0, sum); } #ifdef TRACE_SOLVER print_vector("s", s, mi); #endif if (std::abs(psi) <= mi * std::numeric_limits<double>::epsilon() * c1 * c2* 100.0) { /* numerically there are not infeasibilities anymore */ q = iq; return f_value; } /* save old values for u, x and A */ u_old.head(iq) = u.head(iq); A_old.head(iq) = A.head(iq); x_old = x; l2: /* Step 2: check for feasibility and determine a new S-pair */ for (i = 0; i < mi; i++) { if (s(i) < ss && iai(i) != -1 && iaexcl[i]) { ss = s(i); ip = i; } } if (ss >= 0.0) { q = iq; return f_value; } /* set np = n(ip) */ np = CI.col(ip); /* set u = (u 0)^T */ u(iq) = 0.0; /* add ip to the active set A */ A(iq) = ip; #ifdef TRACE_SOLVER std::cerr << "Trying with constraint " << ip << std::endl; print_vector("np", np, n); #endif l2a:/* Step 2a: determine step direction */ /* compute z = H np: the step direction in the primal space (through J, see the paper) */ compute_d(d, J, np); update_z(z, J, d, iq); /* compute N* np (if q > 0): the negative of the step direction in the dual space */ update_r(R, r, d, iq); #ifdef TRACE_SOLVER std::cerr << "Step direction z" << std::endl; print_vector("z", z, n); print_vector("r", r, iq + 1); print_vector("u", u, iq + 1); print_vector("d", d, n); print_ivector("A", A, iq + 1); #endif /* Step 2b: compute step length */ l = 0; /* Compute t1: partial step length (maximum step in dual space without violating dual feasibility */ t1 = inf; /* +inf */ /* find the index l s.t. it reaches the minimum of u+(x) / r */ for (k = me; k < iq; k++) { double tmp; if (r(k) > 0.0 && ((tmp = u(k) / r(k)) < t1) ) { t1 = tmp; l = A(k); } } /* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */ if (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0 t2 = -s(ip) / z.dot(np); else t2 = inf; /* +inf */ /* the step is chosen as the minimum of t1 and t2 */ t = std::min(t1, t2); #ifdef TRACE_SOLVER std::cerr << "Step sizes: " << t << " (t1 = " << t1 << ", t2 = " << t2 << ") "; #endif /* Step 2c: determine new S-pair and take step: */ /* case (i): no step in primal or dual space */ if (t >= inf) { /* QPP is infeasible */ // FIXME: unbounded to raise q = iq; return inf; } /* case (ii): step in dual space */ if (t2 >= inf) { /* set u = u + t * [-r 1) and drop constraint l from the active set A */ u.head(iq) -= t * r.head(iq); u(iq) += t; iai(l) = l; delete_constraint(R, J, A, u, p, iq, l); #ifdef TRACE_SOLVER std::cerr << " in dual space: " << f_value << std::endl; print_vector("x", x, n); print_vector("z", z, n); print_ivector("A", A, iq + 1); #endif goto l2a; } /* case (iii): step in primal and dual space */ x += t * z; /* update the solution value */ f_value += t * z.dot(np) * (0.5 * t + u(iq)); u.head(iq) -= t * r.head(iq); u(iq) += t; #ifdef TRACE_SOLVER std::cerr << " in both spaces: " << f_value << std::endl; print_vector("x", x, n); print_vector("u", u, iq + 1); print_vector("r", r, iq + 1); print_ivector("A", A, iq + 1); #endif if (t == t2) { #ifdef TRACE_SOLVER std::cerr << "Full step has taken " << t << std::endl; print_vector("x", x, n); #endif /* full step has taken */ /* add constraint ip to the active set*/ if (!add_constraint(R, J, d, iq, R_norm)) { iaexcl[ip] = false; delete_constraint(R, J, A, u, p, iq, ip); #ifdef TRACE_SOLVER print_matrix("R", R, n); print_ivector("A", A, iq); #endif for (i = 0; i < m; i++) iai(i) = i; for (i = 0; i < iq; i++) { A(i) = A_old(i); iai(A(i)) = -1; u(i) = u_old(i); } x = x_old; goto l2; /* go to step 2 */ } else iai(ip) = -1; #ifdef TRACE_SOLVER print_matrix("R", R, n); print_ivector("A", A, iq); #endif goto l1; } /* a patial step has taken */ #ifdef TRACE_SOLVER std::cerr << "Partial step has taken " << t << std::endl; print_vector("x", x, n); #endif /* drop constraint l */ iai(l) = l; delete_constraint(R, J, A, u, p, iq, l); #ifdef TRACE_SOLVER print_matrix("R", R, n); print_ivector("A", A, iq); #endif s(ip) = CI.col(ip).dot(x) + ci0(ip); #ifdef TRACE_SOLVER print_vector("s", s, mi); #endif goto l2a; }
void hongocompleto() { int i=0; do{ //for(i=6;i<9;i++) //{ setbkcolor(WHITE); construccion(); ////C setcolor (7); settextstyle (0,0,5); outtextxy (30,50,"C"); ////A setcolor (7); settextstyle (0,0,5); outtextxy (70,55,"A"); /////R setcolor (7); settextstyle (0,0,5); outtextxy (110,50,"R"); /////G setcolor (7); settextstyle (0,0,5); outtextxy (150,55,"G"); /////A setcolor (7); settextstyle (0,0,5); outtextxy (190,50,"A"); /////N setcolor (7); settextstyle (0,0,5); outtextxy (230,55,"N"); /////D setcolor (7); settextstyle (0,0,5); outtextxy (270,50,"D"); /////O setcolor (7); settextstyle (0,0,5); outtextxy (310,55,"O"); c(); //a1(); //r(); //g(); //a2(); //n(); //d(); //o(); //c(); delay(200); cabeza(); a1(); delay(200); ojo(); r(); delay(200); mancha1(); g(); delay(200); mancha2(); a2(); delay(200); mancha3(); n(); delay(200); mancha4(); d(); delay(200); mancha5(); o(); delay(200); //getch(); i=i++; //kbhit(); }while (i<2); //}while (!kbhit()); }
int sc_main(int, char**) { sc_signal<bool> Clk, Rst, Tx_Active, CCA_Active, MEM_Read; sc_signal< sc_uint<8> > RFST_in, MUX, Instruction; sc_signal< sc_uint<16> >Random_in; sc_signal<bool> Txcaln, Txon, Txoncca, ackset, Txoff, flush_tx, Rxon, Rxoff, flush_rx; sc_signal< sc_uint<32> > i; sc_signal< sc_uint<4> > W; sc_signal< sc_uint<3> > CSPSelmux_1; sc_signal< sc_uint<2> > CSPSelmux_2; /*sc_signal<bool> Encspx, Encspy, Incy, Decy, Encspz, Decz, Encspt, Dect, Encspctrl, Enpc, Enir, MEM_Read, Enmactimer, CSPC_out; sc_signal< sc_uint<3> > S, CSPSelmux_1; sc_signal< sc_uint<2> > CSPSelmux_2; sc_signal< sc_uint<8> > CSPX_out, CSPY_out, CSPZ_out, CSPT_out, CSPCTRL_out, CSPPC_out, CSPIR_out, RFST_out, CSPMux_1_out, Memory_out, CSPR_out, OFECou; */ CSPTOP DUT("CSPTOP"); DUT.Clk(Clk); DUT.Rst(Rst); DUT.Tx_Active(Tx_Active); DUT.CCA_Active(CCA_Active); DUT.RFST_in(RFST_in); DUT.Random_in(Random_in); DUT.CSPIR_out(Instruction); DUT.W(W); DUT.MUX(MUX); DUT.i(i); DUT.Txcaln(Txcaln); DUT.Txon(Txon); DUT.Txoncca(Txoncca); DUT.ackset(ackset); DUT.Txoff(Txoff); DUT.flush_tx(flush_tx); DUT.Rxon(Rxon); DUT.Rxoff(Rxoff); DUT.flush_rx(flush_rx); DUT.CSPSelmux_2(CSPSelmux_2); DUT.CSPSelmux_1(CSPSelmux_1); DUT.MEM_Read(MEM_Read); /* Control.Clk(Clk); Control.Rst(Rst); Control.OFECou(OFECou); Control.Instruction(CSPIR_out); Control.MUX(MUX); Control.C_out(CSPC_out); Control.i(i); Control.Encspx(Encspx); Control.Encspy(Encspy); Control.Incy(Incy); Control.Decy(Decy); Control.Encspz(Encspz); Control.Decz(Decz); Control.Encspt(Encspt); Control.Dect(Dect); Control.Encspctrl(Encspctrl); Control.Enpc(Enpc); Control.S(S); Control.Enir(Enir); Control.Selmux_1(CSPSelmux_1); Control.Selmux_2(CSPSelmux_2); Control.MEM_Read(MEM_Read); Control.Enmactimer(Enmactimer); Control.Txcaln(Txcaln); Control.Txon(Txon); Control.Txoncca(Txoncca); Control.ackset(ackset); Control.Txoff(Txoff); Control.flush_tx(flush_tx); Control.Rxon(Rxon); Control.Rxoff(Rxoff); Control.flush_rx(flush_rx); */ driver d("driver"); d.Clk(Clk); d.Rst(Rst); d.Tx_Active(Tx_Active); d.CCA_Active(CCA_Active); d.RFST_in(RFST_in); d.Random_in(Random_in); //d.CSPIR_out(CSPIR_out); //d.OFECou(OFECou); //d.MUX(MUX); //d.C_out(CSPC_out); // trace file creation sc_trace_file *tf = sc_create_vcd_trace_file("CSPTOP"); sc_trace(tf,DUT.Clk, "Clk"); sc_trace(tf,DUT.Rst, "Rst"); sc_trace(tf,DUT.Tx_Active, "Tx_Active"); sc_trace(tf,DUT.CCA_Active, "CCA_Active"); sc_trace(tf,DUT.RFST_in, "RFST_in"); sc_trace(tf,DUT.Random_in, "Random_in"); sc_trace(tf,DUT.Txcaln, "Txcaln"); sc_trace(tf,DUT.Txon, "Txon"); sc_trace(tf,DUT.Txoncca, "Txoncca"); sc_trace(tf,DUT.ackset, "ackset"); sc_trace(tf,DUT.Txoff, "Txoff"); sc_trace(tf,DUT.flush_tx, "flush_tx"); sc_trace(tf,DUT.Rxon, "Rxon"); sc_trace(tf,DUT.Rxoff, "Rxoff"); sc_trace(tf,DUT.flush_rx, "flush_rx"); sc_trace(tf,DUT.MUX, "MUX"); sc_trace(tf,DUT.i, "i"); sc_trace(tf,DUT.W, "W"); sc_trace(tf,DUT.MEM_Read, "MEM_Read"); sc_trace(tf,DUT.CSPIR_out, "CSPIR_out"); sc_trace(tf,DUT.CSPSelmux_1, "CSPSelmux_1"); sc_trace(tf,DUT.CSPSelmux_2, "CSPSelmux_2"); /* sc_trace_file *tf = sc_create_vcd_trace_file("CSPControl"); sc_trace(tf,Control.Clk, "Clk"); sc_trace(tf,Control.Rst, "Rst"); sc_trace(tf,Control.OFECou, "OFECou"); sc_trace(tf,Control.Instruction, "Instruction"); sc_trace(tf,Control.MUX, "MUX"); sc_trace(tf,Control.C_out, "C_out"); //sc_trace(tf,Control.Random_in, "Random_in"); sc_trace(tf,Control.i, "i"); */ sc_start(10000,SC_NS); sc_close_vcd_trace_file(tf); system("pause"); return 0; }
GLvoid CRenderManager::handlePickedObjects() { // if we are ower the menu we do not have to proccess things under the cursor if (CV_GAME_MANAGER->getGUIManager()->getPlayGUI()->is_mouse_over_gui()) { return; } // if we are not selling or buying we don't have to process blocks (just objects TODO) ACTION_EVENT *ae = CV_GAME_MANAGER->getGUIManager()->getLastActionEvent(); // get the block we have our cousor on CBlock *pickedBlock = CV_GAME_MANAGER->getPickingManager()->getLastPickedBlock(); if (pickedBlock) { GLint type = pickedBlock->getType(); /*if (!pickedBlock->isSellable()) { return; }*/ sBoundingBox *bbox = pickedBlock->getBoundingBox(); vector3f a(bbox->A); vector3f b(bbox->B); vector3f c(bbox->C); vector3f d(bbox->D); vector3f e(bbox->E); vector3f f(bbox->F); vector3f g(bbox->G); vector3f h(bbox->H); a[1]=b[1]=c[1]=d[1]=CV_BLOCK_HEIGHT+CV_BLOCK_HEIGHT/4.0f+CV_BLOCK_HEIGHT/32.0f; e[1]=f[1]=g[1]=h[1]=CV_BLOCK_HEIGHT/4.0f+CV_BLOCK_HEIGHT/32.0f; glLineWidth(4.0f); if (pickedBlock->isLow()) { if (!(ae->message_group==AEMG_BUILD_ROOMS || ae->message_group==AEMG_BUILD_DOORS || ae->message_group==AEMG_BUILD_TRAPS)) { return; } // draw the selection box if (pickedBlock->isSellable(CV_CURRENT_PLAYER_ID) && ae->message == AEM_SELL) { glColor3f(0.0f,1.0f,0.0f); } else if (pickedBlock->isBuildable(CV_CURRENT_PLAYER_ID) && ae->message != AEM_SELL) { glColor3f(0.0f,1.0f,0.0f); } else { glColor3f(1.0f,0.0f,0.0f); } glBegin(GL_LINES); { /*glVertex3fv(&a[0]); glVertex3fv(&b[0]); glVertex3fv(&b[0]); glVertex3fv(&c[0]); glVertex3fv(&c[0]); glVertex3fv(&d[0]); glVertex3fv(&d[0]); glVertex3fv(&a[0]);*/ glVertex3fv(&e[0]); glVertex3fv(&f[0]); glVertex3fv(&f[0]); glVertex3fv(&g[0]); glVertex3fv(&g[0]); glVertex3fv(&h[0]); glVertex3fv(&h[0]); glVertex3fv(&e[0]); /*glVertex3fv(&a[0]); glVertex3fv(&e[0]); glVertex3fv(&b[0]); glVertex3fv(&f[0]); glVertex3fv(&c[0]); glVertex3fv(&g[0]); glVertex3fv(&d[0]); glVertex3fv(&h[0]);*/ } glEnd(); } else { if (!(ae->message_group==AEMG_BUILD_ROOMS || ae->message_group==AEMG_BUILD_DOORS || ae->message_group==AEMG_BUILD_TRAPS)) glColor3f(type==CV_BLOCK_TYPE_ROCK_ID?1.0f:0.0f,type==CV_BLOCK_TYPE_ROCK_ID?0.0f:1.0f,0.0f); else glColor3f(1.0f,0.0f,0.0f); glBegin(GL_LINES); { glVertex3fv(&a[0]); glVertex3fv(&b[0]); glVertex3fv(&b[0]); glVertex3fv(&c[0]); glVertex3fv(&c[0]); glVertex3fv(&d[0]); glVertex3fv(&d[0]); glVertex3fv(&a[0]); glVertex3fv(&e[0]); glVertex3fv(&f[0]); glVertex3fv(&f[0]); glVertex3fv(&g[0]); glVertex3fv(&g[0]); glVertex3fv(&h[0]); glVertex3fv(&h[0]); glVertex3fv(&e[0]); glVertex3fv(&a[0]); glVertex3fv(&e[0]); glVertex3fv(&b[0]); glVertex3fv(&f[0]); glVertex3fv(&c[0]); glVertex3fv(&g[0]); glVertex3fv(&d[0]); glVertex3fv(&h[0]); } glEnd(); } glLineWidth(1.0f); } }
int main(int argc, char* argv[]) { Teuchos::GlobalMPISession mpiSession(&argc, &argv); Teuchos::RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm(); // This little trick lets us print to std::cout only if a (dummy) command-line argument is provided. int iprint = argc - 1; Teuchos::RCP<std::ostream> outStream; Teuchos::oblackholestream bhs; // outputs nothing if (iprint > 0 && Teuchos::rank<int>(*comm)==0) outStream = Teuchos::rcp(&std::cout, false); else outStream = Teuchos::rcp(&bhs, false); int errorFlag = 0; try { /**********************************************************************************************/ /************************* CONSTRUCT ROL ALGORITHM ********************************************/ /**********************************************************************************************/ // Get ROL parameterlist std::string filename = "input.xml"; Teuchos::RCP<Teuchos::ParameterList> parlist = Teuchos::rcp( new Teuchos::ParameterList() ); Teuchos::updateParametersFromXmlFile( filename, parlist.ptr() ); // Build ROL algorithm parlist->sublist("Status Test").set("Gradient Tolerance",1.e-8); parlist->sublist("Status Test").set("Step Tolerance",1.e-14); parlist->sublist("Status Test").set("Iteration Limit",100); /**********************************************************************************************/ /************************* CONSTRUCT VECTORS **************************************************/ /**********************************************************************************************/ // Build control vectors int nx = 256; Teuchos::RCP<std::vector<RealT> > x_rcp = Teuchos::rcp( new std::vector<RealT>(nx+2,0.0) ); ROL::StdVector<RealT> x(x_rcp); Teuchos::RCP<std::vector<RealT> > d_rcp = Teuchos::rcp( new std::vector<RealT>(nx+2,0.0) ); ROL::StdVector<RealT> d(d_rcp); for ( int i = 0; i < nx+2; i++ ) { (*x_rcp)[i] = random<RealT>(comm); (*d_rcp)[i] = random<RealT>(comm); } // Build state and adjoint vectors Teuchos::RCP<std::vector<RealT> > u_rcp = Teuchos::rcp( new std::vector<RealT>(nx,1.0) ); ROL::StdVector<RealT> u(u_rcp); Teuchos::RCP<std::vector<RealT> > p_rcp = Teuchos::rcp( new std::vector<RealT>(nx,0.0) ); ROL::StdVector<RealT> p(p_rcp); Teuchos::RCP<ROL::Vector<RealT> > up = Teuchos::rcp(&u,false); Teuchos::RCP<ROL::Vector<RealT> > pp = Teuchos::rcp(&p,false); /**********************************************************************************************/ /************************* CONSTRUCT SOL COMPONENTS *******************************************/ /**********************************************************************************************/ // Build samplers // int dim = 4; // int nSamp = 100; // std::vector<RealT> tmp(2,0.0); tmp[0] = -1.0; tmp[1] = 1.0; // std::vector<std::vector<RealT> > bounds(dim,tmp); // Teuchos::RCP<ROL::BatchManager<RealT> > bman // = Teuchos::rcp(new ROL::StdTeuchosBatchManager<RealT,int>(comm)); // Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler // = Teuchos::rcp(new ROL::MonteCarloGenerator<RealT>(nSamp,bounds,bman,false,false,100)); ROL::QuadratureInfo info; info.dim = 4; info.maxLevel = 7; info.rule1D.clear(); info.rule1D.resize(info.dim,ROL::QUAD_CLENSHAWCURTIS); info.growth1D.clear(); info.growth1D.resize(info.dim,ROL::GROWTH_DEFAULT); info.normalized = true; info.adaptive = false; Teuchos::RCP<ROL::BatchManager<RealT> > bman = Teuchos::rcp(new ROL::StdTeuchosBatchManager<RealT,int>(comm)); Teuchos::RCP<ROL::SampleGenerator<RealT> > sampler = Teuchos::rcp(new ROL::SparseGridGenerator<RealT>(bman,info)); // Print samples int width = 21; std::stringstream name; name << "samples_" << sampler->batchID() << ".txt"; std::ofstream file(name.str().c_str()); if (file.is_open()) { file << std::scientific << std::setprecision(12); for (int i = 0; i < sampler->numMySamples(); ++i) { std::vector<RealT> pt = sampler->getMyPoint(i); RealT wt = sampler->getMyWeight(i); for (int j = 0; j < static_cast<int>(pt.size()); ++j) { file << std::setw(width) << std::left << pt[j]; } file << std::setw(width) << std::left << wt << std::endl; } file.close(); } else { TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, ">>> (adapters/trikota/sol/test/test_01): Unable to open file!"); } /**********************************************************************************************/ /************************* CONSTRUCT OBJECTIVE FUNCTION ***************************************/ /**********************************************************************************************/ // Build risk-averse objective function RealT alpha = 1.e-3; Teuchos::RCP<ROL::ParametrizedObjective_SimOpt<RealT> > pobjSimOpt = Teuchos::rcp(new Objective_BurgersControl<RealT>(alpha,nx)); Teuchos::RCP<ROL::ParametrizedEqualityConstraint_SimOpt<RealT> > pconSimOpt = Teuchos::rcp(new EqualityConstraint_BurgersControl<RealT>(nx)); Teuchos::RCP<ROL::ParametrizedObjective<RealT> > pObj = Teuchos::rcp(new ROL::Reduced_ParametrizedObjective_SimOpt<RealT>(pobjSimOpt,pconSimOpt,up,pp)); Teuchos::RCP<ROL::Objective<RealT> > obj; // Test parametrized objective functions *outStream << "Check Derivatives of Parametrized Objective Function\n"; pObj->setParameter(sampler->getMyPoint(0)); pObj->checkGradient(x,d,true,*outStream); pObj->checkHessVec(x,d,true,*outStream); /**********************************************************************************************/ /************************* RISK NEUTRAL *******************************************************/ /**********************************************************************************************/ *outStream << "\nSOLVE RISK NEUTRAL OPTIMAL CONTROL PROBLEM WITH TRUST REGION\n"; // Build CVaR objective function Teuchos::ParameterList list; list.sublist("SOL").set("Stochastic Optimization Type","Risk Neutral"); list.sublist("SOL").set("Store Sampled Value and Gradient",true); // Build stochastic problem Teuchos::RCP<ROL::Vector<RealT> > xp = Teuchos::rcp(&x,false); ROL::StochasticProblem<RealT> optProb(list,pObj,sampler,xp); optProb.checkObjectiveGradient(d,true,*outStream); optProb.checkObjectiveHessVec(d,true,*outStream); // Run ROL algorithm ROL::Algorithm<RealT> algo("Trust Region",*parlist,false); clock_t start = clock(); xp->zero(); algo.run(optProb,true,*outStream); *outStream << "Optimization time: " << (RealT)(clock()-start)/(RealT)CLOCKS_PER_SEC << " seconds.\n"; } catch (std::logic_error err) { *outStream << err.what() << "\n"; errorFlag = -1000; }; // end try if (errorFlag != 0) std::cout << "End Result: TEST FAILED\n"; else std::cout << "End Result: TEST PASSED\n"; return 0; }
// Update a file or directory. bool updateFile(const QString &sourceFileName, const QStringList &nameFilters, const QString &targetDirectory, unsigned flags, JsonOutput *json, QString *errorMessage) { const QFileInfo sourceFileInfo(sourceFileName); const QString targetFileName = targetDirectory + QLatin1Char('/') + sourceFileInfo.fileName(); if (optVerboseLevel > 1) std::wcout << "Checking " << sourceFileName << ", " << targetFileName<< '\n'; if (!sourceFileInfo.exists()) { *errorMessage = QString::fromLatin1("%1 does not exist.").arg(QDir::toNativeSeparators(sourceFileName)); return false; } if (sourceFileInfo.isSymLink()) { *errorMessage = QString::fromLatin1("Symbolic links are not supported (%1).") .arg(QDir::toNativeSeparators(sourceFileName)); return false; } const QFileInfo targetFileInfo(targetFileName); if (sourceFileInfo.isDir()) { if (targetFileInfo.exists()) { if (!targetFileInfo.isDir()) { *errorMessage = QString::fromLatin1("%1 already exists and is not a directory.") .arg(QDir::toNativeSeparators(targetFileName)); return false; } // Not a directory. } else { // exists. QDir d(targetDirectory); if (optVerboseLevel) std::wcout << "Creating " << QDir::toNativeSeparators(targetFileName) << ".\n"; if (!(flags & SkipUpdateFile) && !d.mkdir(sourceFileInfo.fileName())) { *errorMessage = QString::fromLatin1("Cannot create directory %1 under %2.") .arg(sourceFileInfo.fileName(), QDir::toNativeSeparators(targetDirectory)); return false; } } // Recurse into directory QDir dir(sourceFileName); const QStringList allEntries = dir.entryList(nameFilters, QDir::Files) + dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); foreach (const QString &entry, allEntries) if (!updateFile(sourceFileName + QLatin1Char('/') + entry, nameFilters, targetFileName, flags, json, errorMessage)) return false; return true; } // Source is directory. if (targetFileInfo.exists()) { if (!(flags & ForceUpdateFile) && targetFileInfo.lastModified() >= sourceFileInfo.lastModified()) { if (optVerboseLevel) std::wcout << sourceFileInfo.fileName() << " is up to date.\n"; if (json) json->addFile(sourceFileName, targetDirectory); return true; } QFile targetFile(targetFileName); if (!(flags & SkipUpdateFile) && !targetFile.remove()) { *errorMessage = QString::fromLatin1("Cannot remove existing file %1: %2") .arg(QDir::toNativeSeparators(targetFileName), targetFile.errorString()); return false; } } // target exists QFile file(sourceFileName); if (optVerboseLevel) std::wcout << "Updating " << sourceFileInfo.fileName() << ".\n"; if (!(flags & SkipUpdateFile) && !file.copy(targetFileName)) { *errorMessage = QString::fromLatin1("Cannot copy %1 to %2: %3") .arg(QDir::toNativeSeparators(sourceFileName), QDir::toNativeSeparators(targetFileName), file.errorString()); return false; } if (json) json->addFile(sourceFileName, targetDirectory); return true; }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QDialog d(0); QVBoxLayout *gl = new QVBoxLayout(); QFormLayout *lay = new QFormLayout(); lay->setWidget(0, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Имя: "), &d)); lay->setWidget(0, QFormLayout::FieldRole, new QLineEdit(&d)); lay->setWidget(1, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Фамилия: "), &d)); lay->setWidget(1, QFormLayout::FieldRole, new QLineEdit(&d)); lay->setWidget(2, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Отчество: "), &d)); lay->setWidget(2, QFormLayout::FieldRole, new QLineEdit(&d)); gl->addLayout(lay); QFrame *line = new QFrame(&d); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); gl->addWidget(line); lay = new QFormLayout(); QComboBox *cbox = new QComboBox(&d); cbox->insertItem(0, QString::fromLocal8Bit("женский")); cbox->insertItem(1, QString::fromLocal8Bit("мужской")); lay->setWidget(0, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Пол: "), &d)); lay->setWidget(0, QFormLayout::FieldRole, cbox); lay->setWidget(1, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Дата рождения: "), &d)); lay->setWidget(1, QFormLayout::FieldRole, new QDateEdit(&d)); gl->addLayout(lay); line = new QFrame(&d); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); gl->addWidget(line); lay = new QFormLayout(); lay->setWidget(0, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Адрес: "), &d)); lay->setWidget(0, QFormLayout::FieldRole, new QLineEdit(&d)); lay->setWidget(1, QFormLayout::LabelRole, new QLabel(QString::fromLocal8Bit("Телефон: "), &d)); lay->setWidget(1, QFormLayout::FieldRole, new QLineEdit(&d)); gl->addLayout(lay); QHBoxLayout *lay2 = new QHBoxLayout(); QPushButton *ok = new QPushButton("OK", &d); ok->setDefault(true); ok->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); lay2->addWidget(ok); QPushButton *cancel = new QPushButton(QString::fromLocal8Bit("Отмена"), &d); cancel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); lay2->addWidget(cancel); gl->addItem(lay2); d.setLayout(gl); d.setWindowTitle("Address book"); d.show(); return app.exec(); }
void dp(std::vector<std::string> ref, std::vector<std::string> hyp){ int rcount = (int)ref.size(); //正解文書の単語数 int hcount = (int)hyp.size(); //コンフュージョンセットの数 std::vector<std::vector<bool> > d(rcount+1, std::vector<bool>(hcount+1)); //一致しているか std::vector<std::vector<int> > g(rcount+1, std::vector<int>(hcount+1)); //距離計算 std::vector<std::vector<int> > r(rcount+1, std::vector<int>(hcount+1)); //置換,削除,挿入 //dの算出(0:一致,1:不一致) for(int i = 1; i <= rcount; i++){ for(int j = 1; j <= hcount; j++){ d[i][j] = (ref[i-1] != hyp[j-1]); } } //g,rの端に値を代入 g[0][0] = 0; r[0][0] = 0; for(int i = 1; i <= rcount; i++){ g[i][0] = g[i-1][0] + 1; r[i][0] = 1; } for(int j = 1; j <= hcount; j++){ g[0][j] = g[0][j-1] + 1; r[0][j] = 2; } //g,rの中の計算 for(int i = 1; i <= rcount; i++){ for(int j = 1; j <= hcount; j++){ int l = g[i-1][j] + 1; int b = g[i][j-1] + 1; int lb = g[i-1][j-1] + d[i][j]; if(l <= b){ if(l <= lb){ g[i][j] = l; r[i][j] = 1; } else{ g[i][j] = lb; r[i][j] = 3; } } else{ if(b <= lb){ g[i][j] = b; r[i][j] = 2; } else{ g[i][j] = lb; r[i][j] = 3; } } } } int i = rcount; int j = hcount; for(;;){ if(r[i][j] == 1){ del++; i--; } else if(r[i][j] == 2){ ins++; j--; } else if(r[i][j] == 3){ if(d[i][j] == 1){ sub++; } else{ cor++; } i--; j--; } else if(i == 0 && j == 0){ break; } } }
static QString servername(QString fn) { QDir d(QDir::current()); fn = d.absoluteFilePath(fn); fn = QDir::cleanPath(fn); return QString("eln-%1").arg(qHash(fn)); }
void MST_linkage_core(const t_index N, const t_float * const D, cluster_result & Z2) { /* N: integer, number of data points D: condensed distance matrix N*(N-1)/2 Z2: output data structure The basis of this algorithm is an algorithm by Rohlf: F. James Rohlf, Hierarchical clustering using the minimum spanning tree, The Computer Journal, vol. 16, 1973, p. 93–95. */ t_index i; t_index idx2; doubly_linked_list active_nodes(N); auto_array_ptr<t_float> d(N); t_index prev_node; t_float min; // first iteration idx2 = 1; min = std::numeric_limits<t_float>::infinity(); for (i=1; i<N; ++i) { d[i] = D[i-1]; #if HAVE_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif if (d[i] < min) { min = d[i]; idx2 = i; } else if (fc_isnan(d[i])) throw (nan_error()); #if HAVE_DIAGNOSTIC #pragma GCC diagnostic pop #endif } Z2.append(0, idx2, min); for (t_index j=1; j<N-1; ++j) { prev_node = idx2; active_nodes.remove(prev_node); idx2 = active_nodes.succ[0]; min = d[idx2]; for (i=idx2; i<prev_node; i=active_nodes.succ[i]) { t_float tmp = D_(i, prev_node); #if HAVE_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif if (tmp < d[i]) d[i] = tmp; else if (fc_isnan(tmp)) throw (nan_error()); #if HAVE_DIAGNOSTIC #pragma GCC diagnostic pop #endif if (d[i] < min) { min = d[i]; idx2 = i; } } for (; i<N; i=active_nodes.succ[i]) { t_float tmp = D_(prev_node, i); #if HAVE_DIAGNOSTIC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif if (d[i] > tmp) d[i] = tmp; else if (fc_isnan(tmp)) throw (nan_error()); #if HAVE_DIAGNOSTIC #pragma GCC diagnostic pop #endif if (d[i] < min) { min = d[i]; idx2 = i; } } Z2.append(prev_node, idx2, min); } }
void RotatedHartenLaxLeerSolver::solve(FluidArray& F, const FluidArray& Q_l, const FluidArray& Q_r, double a_l2, double a_r2, double gamma, int dim) const { bool pureHLLC = false, pureHLL = false; Eigen::Matrix<double, 3, 1> d(dim==0 ? 1 : 0, dim==1 ? 1 : 0, dim==2 ? 1 : 0); Eigen::Matrix<double, 3, 1> n1(Q_r[UID::VEL+0]-Q_l[UID::VEL+0], Q_r[UID::VEL+1]-Q_l[UID::VEL+1], Q_r[UID::VEL+2]-Q_l[UID::VEL+2]); Eigen::Matrix<double, 3, 1> n2; if (n1(dim) < 0) n1 = -1*n1; if (n1.norm() < 1.0e-6) pureHLLC = true; else { n1.normalize(); if (n1.cross(d).norm() == 0) pureHLL = true; else { n2 = (n1.cross(d)).cross(n1); if (n2.norm() == 0) pureHLL = true; else { if (n2(dim) < 0) n2 = -1*n2; n2.normalize(); if (n2.cross(d).norm() == 0) pureHLLC = true; } } } if (!pureHLLC && !pureHLL) { FluidArray F1, F2; FluidArray Q_l_R = Q_l; FluidArray Q_r_R = Q_r; //Eigen::Matrix<double, 3, 3> R1 = getRotationMatrix(axis1, alpha1, beta1); Eigen::Matrix<double, 3, 3> R1 = getRotationFromA2B(n1, d); rotate(R1, Q_l_R); rotate(R1, Q_r_R); m_hll.solve(F1, Q_l_R, Q_r_R, a_l2, a_r2, gamma, dim); //Eigen::Matrix<double, 3, 3> R1_inv = getInverseRotationMatrix(axis1, alpha1, beta1); Eigen::Matrix<double, 3, 3> R1_inv = getRotationFromA2B(d, n1); rotate(R1_inv, Q_l_R); rotate(R1_inv, Q_r_R); rotate(R1_inv, F1); //Eigen::Matrix<double, 3, 3> R2 = getRotationMatrix(axis2, alpha2, beta2); Eigen::Matrix<double, 3, 3> R2 = getRotationFromA2B(n2, d); rotate(R2, Q_l_R); rotate(R2, Q_r_R); m_hllc.solve(F2, Q_l_R, Q_r_R, a_l2, a_r2, gamma, dim); //Eigen::Matrix<double, 3, 3> R2_inv = getInverseRotationMatrix(axis2, alpha2, beta2); Eigen::Matrix<double, 3, 3> R2_inv = getRotationFromA2B(d, n2); rotate(R2_inv, Q_l_R); rotate(R2_inv, Q_r_R); rotate(R2_inv, F2); for (int iu = 0; iu < UID::N; ++iu) F[iu] = std::abs(d.dot(n1))*F1[iu] + std::abs(d.dot(n2))*F2[iu]; } else if (pureHLL) m_hll.solve(F, Q_l, Q_r, a_l2, a_r2, gamma, dim); else if (pureHLLC) m_hllc.solve(F, Q_l, Q_r, a_l2, a_r2, gamma, dim); }
void FileTransferDlgNotify::createFile(const QString &name, unsigned size, bool bCanResume) { m_name = name; m_size = size; m_name = m_name.replace(QRegExp("\\\\"), "/"); FileTransfer *ft = m_dlg->m_msg->m_transfer; int n = m_name.findRev("/"); if (n >= 0){ QString path; QString p = m_name.left(n); while (!p.isEmpty()){ if (!path.isEmpty()) path += "/"; QString pp = getToken(p, '/'); if (pp == ".."){ QString errMsg = i18n("Bad path: %1") .arg(m_name); m_dlg->m_msg->setError(errMsg.utf8()); ft->setError(); return; } path += pp; QDir dd(ft->dir() + "/" + path); if (!dd.exists()){ QDir d(ft->dir()); if (!d.mkdir(path)){ QString errMsg = i18n("Can't create: %1") .arg(path); m_dlg->m_msg->setError(errMsg.utf8()); ft->setError(); return; } } } } m_dlg->m_msg->addFile(m_name, size); if (m_name.isEmpty() || (m_name[(int)(m_name.length() - 1)] == '/')){ ft->startReceive(0); return; } QString shortName = m_name; m_name = ft->dir() + m_name; if (ft->m_file) delete ft->m_file; m_dlg->process(); ft->m_file = new QFile(m_name); if (ft->m_file->exists()){ switch (ft->overwrite()){ case Skip: skip(); return; case Replace: if (ft->m_file->open(IO_WriteOnly | IO_Truncate)){ ft->startReceive(0); return; } break; case Resume: if (ft->m_file->open(IO_WriteOnly)){ resume(); return; } break; default: if (ft->m_file->open(IO_WriteOnly)){ QStringList buttons; QString forAll; if (ft->files()) forAll = i18n("For all files"); buttons.append(i18n("&Replace")); buttons.append(i18n("&Skip")); if (bCanResume && (ft->m_file->size() < size)) buttons.append(i18n("Resu&me")); m_dlg->m_ask = new BalloonMsg(NULL, quoteString(i18n("File %1 exists") .arg(shortName)), buttons, m_dlg->lblState, NULL, false, true, 150, forAll); QObject::connect(m_dlg->m_ask, SIGNAL(action(int, void*)), m_dlg, SLOT(action(int, void*))); raiseWindow(m_dlg); m_dlg->m_ask->show(); return; } } }else{
void MusicSearchEngine::watchForChanges() { // Gather all folders registered on music locations QFileInfoList dirs; for (QString musicPath : SettingsPrivate::instance()->musicLocations()) { QFileInfo location(musicPath); QDirIterator it(location.absoluteFilePath(), QDir::Dirs | QDir::Hidden | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while (it.hasNext()) { QString entry = it.next(); QFileInfo qFileInfo(entry); dirs << qFileInfo; } } SqlDatabase *db = SqlDatabase::instance(); db->open(); db->exec("PRAGMA journal_mode = MEMORY"); db->exec("PRAGMA synchronous = OFF"); db->exec("PRAGMA temp_store = 2"); db->exec("PRAGMA foreign_keys = 1"); QStringList newFoldersToAddInLibrary; // Add folders that were not found first for (QFileInfo f : dirs) { QSqlQuery query(*db); query.setForwardOnly(true); query.prepare("SELECT * FROM filesystem WHERE path = ?"); query.addBindValue(f.absoluteFilePath()); if (query.exec() && !query.next()) { newFoldersToAddInLibrary << f.absoluteFilePath(); QSqlQuery prepared(*db); prepared.setForwardOnly(true); prepared.prepare("INSERT INTO filesystem (path, lastModified) VALUES (?, ?)"); prepared.addBindValue(f.absoluteFilePath()); prepared.addBindValue(f.lastModified().toTime_t()); prepared.exec(); } } if (!newFoldersToAddInLibrary.isEmpty()) { this->doSearch(newFoldersToAddInLibrary); } // Process in reverse mode to clean cache: from database file and check if entry exists in database QSqlQuery cache("SELECT * FROM filesystem", *db); qDebug() << Q_FUNC_INFO << "SELECT * FROM filesystem"; cache.setForwardOnly(true); if (cache.exec()) { QStringList oldLocations; while (cache.next()) { QDir d(cache.record().value(0).toString()); d.exists(); QFileInfo fileInfo(cache.record().value(0).toString()); // Remove folder in database because it couldn't be find in the filesystem if (!fileInfo.exists()) { QSqlQuery deleteFromFilesystem(*db); deleteFromFilesystem.prepare("DELETE FROM filesystem WHERE path = ?"); deleteFromFilesystem.addBindValue(fileInfo.absoluteFilePath()); qDebug() << Q_FUNC_INFO << "DELETE FROM filesystem WHERE path = ?"; if (deleteFromFilesystem.exec()) { oldLocations << fileInfo.absoluteFilePath(); } } } qDebug() << Q_FUNC_INFO << oldLocations; if (!oldLocations.isEmpty()) { db->rebuild(oldLocations, QStringList()); } } }
app * process_eq(func_decl * f, expr * arg1, expr * arg2) { expr * v; expr * t; if (uncnstr(arg1)) { v = arg1; t = arg2; } else if (uncnstr(arg2)) { v = arg2; t = arg1; } else { return 0; } sort * s = m().get_sort(arg1); // Remark: // I currently do not support unconstrained vars that have // uninterpreted sorts, for the following reasons: // - Soundness // (forall ((x S) (y S)) (= x y)) // (not (= c1 c2)) // // The constants c1 and c2 have only one occurrence in // the formula above, but they are not really unconstrained. // The quantifier forces S to have interpretations of size 1. // If we replace (= c1 c2) with fresh k. The formula will // become satisfiable. // // - Even if the formula is quantifier free, I would still // have to build an interpretation for the eliminated // variables. // if (!m().is_fully_interp(s)) return 0; // If the interpreted sort has only one element, // then it is unsound to eliminate the unconstrained variable in the equality sort_size sz = s->get_num_elements(); if (sz.is_finite() && sz.size() <= 1) return 0; if (!m_mc) { // easy case, model generation is disabled. app * u; mk_fresh_uncnstr_var_for(f, arg1, arg2, u); return u; } expr_ref d(m()); if (mk_diff(t, d)) { app * u; if (!mk_fresh_uncnstr_var_for(f, arg1, arg2, u)) return u; add_def(v, m().mk_ite(u, t, d)); return u; } return 0; }
double BFGS ( Vector & x, // i: Startwert // o: Loesung, falls IFAIL = 0 const MinFunction & fun, const OptiParameters & par, double eps ) { int n = x.Size(); long it; char a1crit, a3acrit; Vector d(n), g(n), p(n), temp(n), bs(n), xneu(n), y(n), s(n), x0(n); DenseMatrix l(n); DenseMatrix hesse(n); double /* normg, */ alphahat, hd, fold; double a1, a2; const double mu1 = 0.1, sigma = 0.1, xi1 = 1, xi2 = 10; const double tau = 0.1, tau1 = 0.1, tau2 = 0.6; Vector typx(x.Size()); // i: typische Groessenordnung der Komponenten double f, f0; double typf; // i: typische Groessenordnung der Loesung double fmin = -1e5; // i: untere Schranke fuer Funktionswert // double eps = 1e-8; // i: Abbruchschranke fuer relativen Gradienten double tauf = 0.1; // i: Abbruchschranke fuer die relative Aenderung der // Funktionswerte int ifail; // o: 0 .. Erfolg // -1 .. Unterschreitung von fmin // 1 .. kein Erfolg bei Liniensuche // 2 .. Überschreitung von itmax typx = par.typx; typf = par.typf; l = 0; for (int i = 1; i <= n; i++) l.Elem(i, i) = 1; f = fun.FuncGrad (x, g); f0 = f; x0 = x; it = 0; do { // Restart if (it % (5 * n) == 0) { for (int i = 1; i <= n; i++) d(i-1) = typf/ sqr (typx(i-1)); // 1; for (int i = 2; i <= n; i++) for (int j = 1; j < i; j++) l.Elem(i, j) = 0; /* hesse = 0; for (i = 1; i <= n; i++) hesse.Elem(i, i) = typf / sqr (typx.Get(i)); fun.ApproximateHesse (x, hesse); Cholesky (hesse, l, d); */ } it++; if (it > par.maxit_bfgs) { ifail = 2; break; } // Solve with factorized B SolveLDLt (l, d, g, p); // (*testout) << "l " << l << endl // << "d " << d << endl // << "g " << g << endl // << "p " << p << endl; p *= -1; y = g; fold = f; // line search alphahat = 1; lines (x, xneu, p, f, g, fun, par, alphahat, fmin, mu1, sigma, xi1, xi2, tau, tau1, tau2, ifail); if(ifail == 1) (*testout) << "no success with linesearch" << endl; /* // if (it > par.maxit_bfgs/2) { (*testout) << "x = " << x << endl; (*testout) << "xneu = " << xneu << endl; (*testout) << "f = " << f << endl; (*testout) << "g = " << g << endl; } */ // (*testout) << "it = " << it << " f = " << f << endl; // if (ifail != 0) break; s.Set2 (1, xneu, -1, x); y *= -1; y.Add (1,g); // y += g; x = xneu; // BFGS Update MultLDLt (l, d, s, bs); a1 = y * s; a2 = s * bs; if (a1 > 0 && a2 > 0) { if (LDLtUpdate (l, d, 1 / a1, y) != 0) { cerr << "BFGS update error1" << endl; (*testout) << "BFGS update error1" << endl; (*testout) << "l " << endl << l << endl << "d " << d << endl; ifail = 1; break; } if (LDLtUpdate (l, d, -1 / a2, bs) != 0) { cerr << "BFGS update error2" << endl; (*testout) << "BFGS update error2" << endl; (*testout) << "l " << endl << l << endl << "d " << d << endl; ifail = 1; break; } } // Calculate stop conditions hd = eps * max2 (typf, fabs (f)); a1crit = 1; for (int i = 1; i <= n; i++) if ( fabs (g(i-1)) * max2 (typx(i-1), fabs (x(i-1))) > hd) a1crit = 0; a3acrit = (fold - f <= tauf * max2 (typf, fabs (f))); // testout << "g = " << g << endl; // testout << "a1crit, a3crit = " << int(a1crit) << ", " << int(a3acrit) << endl; /* // Output for tests normg = sqrt (g * g); testout << "it =" << setw (5) << it << " f =" << setw (12) << setprecision (5) << f << " |g| =" << setw (12) << setprecision (5) << normg; testout << " x = (" << setw (12) << setprecision (5) << x.Elem(1); for (i = 2; i <= n; i++) testout << "," << setw (12) << setprecision (5) << x.Elem(i); testout << ")" << endl; */ //(*testout) << "it = " << it << " f = " << f << " x = " << x << endl // << " g = " << g << " p = " << p << endl << endl; // (*testout) << "|g| = " << g.L2Norm() << endl; if (g.L2Norm() < fun.GradStopping (x)) break; } while (!a1crit || !a3acrit); /* (*testout) << "it = " << it << " g = " << g << " f = " << f << " fail = " << ifail << endl; */ if (f0 < f || (ifail == 1)) { (*testout) << "fail, f = " << f << " f0 = " << f0 << endl; f = f0; x = x0; } // (*testout) << "x = " << x << ", x0 = " << x0 << endl; return f; }
int main(int argc, char** argv) { set_program_options(opts, argc, argv); ///Carica l'opportuna struttura di adiacenza, selezionata da linea di comando if (opts.topologia == TORO_2D) topologia = adiacenza_toroidal_lattice(opts.lato); else if (opts.topologia == LINEARE){ opts.partition_type = LINEAR_PARTITION; topologia = adiacenza_simple_line(opts.seq_len); } else { printf("Not supported topology\n"); exit(1); } opts.seq_len = topologia.N; //logarithm lookup table, 6x program speedup mylog = new double[3 * opts.seq_len + 10]; for (int i = 1; i < 3 * opts.seq_len + 10; i++) mylog[i] = log(i); mylog[0] = 0; myexp = new double[100]; for (int i = 0; i < 100; i++) myexp[i] = exp(- opts.beta[0] * i); double media_globale = 0; double media_globale_n2 = 0; double media_rid_globale = 0; double media_rid_globale_n2 = 0; int n_estrazioni = 100; int runs = 0; // <editor-fold defaultstate="collapsed" desc="Sequenze monodimensionali"> if (opts.topologia == LINEARE) #pragma omp parallel { linear_partition *partitions = new linear_partition[opts.n_seq]; int *buf_sequenze = new int[opts.n_seq * opts.seq_len]; distance d(opts.seq_len); RandMT generatore; for (int L = 0; L < n_estrazioni; L++) { // Generazione di un nuovo vettore J_ij random // e di opts.n_seq sequenze che hanno quel J double media_locale = 0; double media_locale_n2 = 0; double media_rid_locale = 0; double media_rid_locale_n2 = 0; ising_entries_jnorm(opts, buf_sequenze, generatore); //riempi le partizioni, a partire dalle sequenze date for (int i = 0; i < opts.n_seq; i++) partitions[i].fill(&buf_sequenze[i * opts.seq_len], opts.seq_len); //media delle distanze tra le coppie di sequenze generate //#pragma omp parallel for firstprivate(d) schedule(dynamic,10) reduction(+: media_n, media_n2) for (int i = 0; i < opts.n_seq; i++) { for (int j = i + 1; j < opts.n_seq; j++) { d.dist(partitions[i], partitions[j]); media_locale += d.dist_shan; media_rid_locale += d.dist_shan_r; media_locale_n2 += (d.dist_shan)*(d.dist_shan); media_rid_locale_n2 += (d.dist_shan_r)*(d.dist_shan_r); } } #pragma omp critical { media_globale += media_locale; media_globale_n2 += media_locale_n2; media_rid_globale += media_rid_locale; media_rid_globale_n2 += media_rid_locale_n2; runs += 1; } } }// </editor-fold> // <editor-fold defaultstate="collapsed" desc="Reticoli bidimensionali"> if (opts.topologia == TORO_2D) { std::clock_t start = std::clock(); double time_diff; double completed_ratio; #pragma omp parallel num_threads(opts.threads) { general_partition *partitions = new general_partition[opts.n_seq]; distance d(opts.seq_len); RandMT generatore; for (int L = 0; L < n_estrazioni; L++) { // Generazione di un nuovo vettore J_ij random // e di opts.n_seq sequenze che hanno quel J double media_locale = 0; double media_locale_n2 = 0; double media_rid_locale = 0; double media_rid_locale_n2 = 0; ising_lattice(opts, generatore, partitions); //media delle distanze tra le coppie di sequenze generate //#pragma omp parallel for firstprivate(d) schedule(dynamic,10) reduction(+: media_n, media_n2) for (int i = 0; i < opts.n_seq; i++) { for (int j = i + 1; j < opts.n_seq; j++) { d(partitions[i], partitions[j]); media_locale += d.dist_shan; media_rid_locale += d.dist_shan_r; media_locale_n2 += (d.dist_shan)*(d.dist_shan); media_rid_locale_n2 += (d.dist_shan_r)*(d.dist_shan_r); } } #pragma omp critical { media_globale += media_locale; media_globale_n2 += media_locale_n2; media_rid_globale += media_rid_locale; media_rid_globale_n2 += media_rid_locale_n2; runs += 1; } #ifdef _OPENMP int this_thread = omp_get_thread_num(); if (this_thread) continue; double time_ratio = omp_get_num_threads(); #else double time_ratio = 1.0; #endif fprintf(stderr, "\r"); time_diff = (std::clock() - start) / (double) CLOCKS_PER_SEC / time_ratio; completed_ratio = (L + 1.0) / n_estrazioni; fprintf(stderr, "%.1f%% done, ETA %.0fs ", completed_ratio * 100, ceil(time_diff * (1 / completed_ratio - 1))); fflush(stderr); } } time_diff = (std::clock() - start) / (double) CLOCKS_PER_SEC; fprintf(stderr, "\r100%% done in %.1f seconds of CPU time\n", time_diff); }// </editor-fold> double varianza_n, varianza_r; int Nd = runs * (opts.n_seq * (opts.n_seq - 1)) / 2; media_globale /= Nd; media_globale_n2 /= Nd; media_rid_globale /= Nd; media_rid_globale_n2 /= Nd; varianza_n = media_globale_n2 - media_globale*media_globale; varianza_r = media_rid_globale_n2 - media_rid_globale*media_rid_globale; int lunghezza; if(opts.topologia == TORO_2D) lunghezza=opts.lato; else lunghezza=opts.seq_len; printf("%d %f %f %f %f\n", lunghezza, media_globale, varianza_n, media_rid_globale, varianza_r); //fprintf(stderr, "%d %f %f\n", opts.seq_len, media_globale, varianza_n); return 0; }
void Foam::chemPointISAT<CompType, ThermoType>::qrDecompose ( const label nCols, scalarSquareMatrix& R ) { scalarField c(nCols); scalarField d(nCols); scalar scale, sigma, sum; for (label k=0; k<nCols-1; k++) { scale = 0; for (label i=k; i<nCols; i++) { scale=max(scale, mag(R(i, k))); } if (scale == 0) { c[k] = d[k] = 0; } else { for (label i=k; i<nCols; i++) { R(i, k) /= scale; } sum = 0; for (label i=k; i<nCols; i++) { sum += sqr(R(i, k)); } sigma = sign(R(k, k))*sqrt(sum); R(k, k) += sigma; c[k] = sigma*R(k, k); d[k] = -scale*sigma; for (label j=k+1; j<nCols; j++) { sum=0; for ( label i=k; i<nCols; i++) { sum += R(i, k)*R(i, j); } scalar tau = sum/c[k]; for ( label i=k; i<nCols; i++) { R(i, j) -= tau*R(i, k); } } } } d[nCols-1] = R(nCols-1, nCols-1); // form R for (label i=0; i<nCols; i++) { R(i, i) = d[i]; for ( label j=0; j<i; j++) { R(i, j)=0; } } }
int main() { Date d(11,25,2015); std::cout << d.GetMonth() << "\n"; return 0; }
/* return TRUE if mon still alive */ boolean hmon(struct monst *mon, struct obj *obj, int thrown) { int tmp; boolean hittxt = FALSE; if (!obj) { tmp = rnd(2); /* attack with bare hands */ if (mon->data->mlet == 'c' && !uarmg) { pline("You hit the cockatrice with your bare hands."); pline("You turn to stone ..."); done_in_by(mon); } } else if (obj->olet == WEAPON_SYM || obj->otyp == PICK_AXE) { if (obj == uwep && (obj->otyp > SPEAR || obj->otyp < BOOMERANG)) tmp = rnd(2); else { if (strchr(mlarge, mon->data->mlet)) { tmp = rnd(objects[obj->otyp].wldam); if (obj->otyp == TWO_HANDED_SWORD) tmp += d(2, 6); else if (obj->otyp == FLAIL) tmp += rnd(4); } else { tmp = rnd(objects[obj->otyp].wsdam); } tmp += obj->spe; if (!thrown && obj == uwep && obj->otyp == BOOMERANG && !rn2(3)) { pline("As you hit %s, the boomerang breaks into splinters.", monnam(mon)); freeinv(obj); setworn((struct obj *) 0, obj->owornmask); obfree(obj, (struct obj *) 0); obj = NULL; tmp++; } } if (mon->data->mlet == 'O' && obj != NULL && obj->otyp == TWO_HANDED_SWORD && !strcmp(ONAME(obj), "Orcrist")) tmp += rnd(10); } else switch (obj->otyp) { case HEAVY_IRON_BALL: tmp = rnd(25); break; case EXPENSIVE_CAMERA: pline("You succeed in destroying your camera. Congratulations!"); freeinv(obj); if (obj->owornmask) setworn((struct obj *) 0, obj->owornmask); obfree(obj, (struct obj *) 0); return (TRUE); case DEAD_COCKATRICE: pline("You hit %s with the cockatrice corpse.", monnam(mon)); if (mon->data->mlet == 'c') { tmp = 1; hittxt = TRUE; break; } pline("%s is turned to stone!", Monnam(mon)); killed(mon); return (FALSE); case CLOVE_OF_GARLIC: /* no effect against demons */ if (strchr(UNDEAD, mon->data->mlet)) mon->mflee = 1; tmp = 1; break; default: /* non-weapons can damage because of their weight */ /* (but not too much) */ tmp = obj->owt / 10; if (tmp < 1) tmp = 1; else tmp = rnd(tmp); if (tmp > 6) tmp = 6; } /****** NOTE: perhaps obj is undefined!! (if !thrown && BOOMERANG) */ tmp += u.udaminc + dbon(); if (u.uswallow) { if ((tmp -= u.uswldtim) <= 0) { pline("Your arms are no longer able to hit."); return (TRUE); } } if (tmp < 1) tmp = 1; mon->mhp -= tmp; if (mon->mhp < 1) { killed(mon); return (FALSE); } if (mon->mtame && (!mon->mflee || mon->mfleetim)) { mon->mflee = 1; /* Rick Richardson */ mon->mfleetim += 10 * rnd(tmp); } if (!hittxt) { if (thrown) { /* this assumes that we cannot throw plural things */ if (obj == NULL) panic("thrown non-object"); hit(xname(obj) /* or: objects[obj->otyp].oc_name */ , mon, exclam(tmp)); } else if (Blind) pline("You hit it."); else pline("You hit %s%s", monnam(mon), exclam(tmp)); } if (u.umconf && !thrown) { if (!Blind) { pline("Your hands stop glowing blue."); if (!mon->mfroz && !mon->msleep) pline("%s appears confused.", Monnam(mon)); } mon->mconf = 1; u.umconf = 0; } return (TRUE); /* mon still alive */ }
static gboolean stream_eos (GMimeStream *stream) { d(g_warning ("Invoked default stream_eos implementation.")); return stream->position >= stream->bound_end; }
/* hitmm returns 0 (miss), 1 (hit), or 2 (kill) */ int hitmm(struct monst *magr, struct monst *mdef) { const struct permonst *pa = magr->data, *pd = mdef->data; int didhit; schar tmp; boolean vis; if (strchr("Eauy", pa->mlet)) return (0); if (magr->mfroz) return (0); /* riv05!a3 */ tmp = pd->ac + pa->mlevel; if (mdef->mconf || mdef->mfroz || mdef->msleep) { tmp += 4; if (mdef->msleep) mdef->msleep = 0; } didhit = (tmp > rnd(20)); if (didhit) mdef->msleep = 0; vis = (cansee(magr->mx, magr->my) && cansee(mdef->mx, mdef->my)); if (vis) { char buf[BUFSZ]; if (mdef->mimic) seemimic(mdef); if (magr->mimic) seemimic(magr); (void) snprintf(buf, sizeof(buf), "%s %s", Monnam(magr), didhit ? "hits" : "misses"); pline("%s %s.", buf, monnam(mdef)); } else { boolean far = (dist(magr->mx, magr->my) > 15); if (far != far_noise || moves - noisetime > 10) { far_noise = far; noisetime = moves; pline("You hear some noises%s.", far ? " in the distance" : ""); } } if (didhit) { if (magr->data->mlet == 'c' && !magr->cham) { magr->mhpmax += 3; if (vis) pline("%s is turned to stone!", Monnam(mdef)); else if (mdef->mtame) pline("You have a peculiarly sad feeling for a moment, then it passes."); monstone(mdef); didhit = 2; } else if ((mdef->mhp -= d(pa->damn, pa->damd)) < 1) { magr->mhpmax += 1 + rn2(pd->mlevel + 1); if (magr->mtame && magr->mhpmax > 8 * pa->mlevel) { if (pa == &li_dog) magr->data = pa = &dog; else if (pa == &dog) magr->data = pa = &la_dog; } if (vis) pline("%s is killed!", Monnam(mdef)); else if (mdef->mtame) pline("You have a sad feeling for a moment, then it passes."); mondied(mdef); didhit = 2; } } return (didhit); }
static gint64 stream_seek (GMimeStream *stream, gint64 offset, GMimeSeekWhence whence) { d(g_warning ("Invoked default stream_seek implementation.")); return -1; }
static int callback_http_only(libwebsocket_context *context, struct libwebsocket *wsi,enum libwebsocket_callback_reasons reason, void *user, void *in, size_t len) { unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 4096 + LWS_SEND_BUFFER_POST_PADDING]; DebugOut() << __SMALLFILE__ << ":" << __LINE__ << reason << "callback_http_only" << endl; switch (reason) { case LWS_CALLBACK_CLOSED: //fprintf(stderr, "mirror: LWS_CALLBACK_CLOSED\n"); //wsi_mirror = NULL; //printf("Connection closed!\n"); break; //case LWS_CALLBACK_PROTOCOL_INIT: case LWS_CALLBACK_CLIENT_ESTABLISHED: { //This happens when a client initally connects. We need to request the support event types. source->clientConnected = true; source->checkSubscriptions(); //printf("Incoming connection!\n"); DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Incoming connection" << endl; QVariantMap toSend; toSend["type"] = "method"; toSend["name"] = "getSupported"; toSend["transactionid"] = amb::createUuid().c_str(); lwsWriteVariant(wsi, toSend); break; } case LWS_CALLBACK_CLIENT_RECEIVE: { QByteArray d((char*)in, len); WebSocketSource * manager = source; if(manager->expectedMessageFrames && manager->partialMessageIndex < manager->expectedMessageFrames) { manager->incompleteMessage += d; manager->partialMessageIndex++; break; } else if(manager->expectedMessageFrames && manager->partialMessageIndex == manager->expectedMessageFrames) { d = manager->incompleteMessage + d; manager->expectedMessageFrames = 0; } DebugOut(7) << "data received: " << d.data() << endl; int start = d.indexOf("{"); if(manager->incompleteMessage.isEmpty() && start > 0) { DebugOut(7)<< "We have an incomplete message at the beginning. Toss it away." << endl; d = d.right(start-1); } int end = d.lastIndexOf("}"); if(end == -1) { manager->incompleteMessage += d; break; } QByteArray tryMessage = manager->incompleteMessage + d.left(end+1); DebugOut(6) << "Trying to parse message: " << tryMessage.data() << endl; QJsonDocument doc; QJsonParseError parseError; doc = QJsonDocument::fromJson(tryMessage, &parseError); if(doc.isNull()) { DebugOut(7) << "Invalid or incomplete message" << endl; DebugOut(7) << parseError.errorString().toStdString() << ": " << parseError.offset << endl; manager->incompleteMessage += d; break; } manager->incompleteMessage = end == d.length()-1 ? "" : d.right(end); QVariantMap call = doc.toVariant().toMap(); string type = call["type"].toString().toStdString(); string name = call["name"].toString().toStdString(); string id = call["transactionid"].toString().toStdString(); if(type == "multiframe") { manager->expectedMessageFrames = call["frames"].toInt(); manager->partialMessageIndex = 1; manager->incompleteMessage = ""; } else if (type == "valuechanged") { QVariantMap data = call["data"].toMap(); string value = data["value"].toString().toStdString(); double timestamp = data["timestamp"].toDouble(); int sequence = data["sequence"].toInt(); Zone::Type zone = data["zone"].toInt(); string type = data["type"].toString().toStdString(); DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Value changed:" << name << value << endl; try { auto property = properties.append(name, source->uuid(), zone, type); if(!property) { DebugOut(DebugOut::Warning) << "We either don't have this or don't support it (" << name << "," << zone << "," << type << ")" << endl; } property->timestamp = timestamp; property->sequence = sequence; property->fromString(value); m_re->updateProperty(property.get(), source->uuid()); double currenttime = amb::currentTime(); /** This is now the latency between when something is available to read on the socket, until * a property is about to be updated in AMB. This includes libwebsockets parsing and the * JSON parsing in this section. */ DebugOut()<<"websocket network + parse latency: "<<(currenttime - property->timestamp)*1000<<"ms"<<endl; totalTime += (currenttime - oldTimestamp)*1000; numUpdates ++; averageLatency = totalTime / numUpdates; DebugOut()<<"Average parse latency: "<<averageLatency<<endl; } catch (exception ex) { //printf("Exception %s\n",ex.what()); DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Exception:" << ex.what() << "\n"; } } else if (type == "methodReply") { if (name == "getSupported" || name == "supportedChanged") { QVariant data = call["data"]; QVariantList supported = data.toList(); DebugOut() << __SMALLFILE__ <<":"<< __LINE__ << "Got getSupported request"<<endl; double serverTime = call["systemTime"].toDouble(); DebugOut() << "Server time is: " << serverTime << endl; if(serverTime) source->serverTimeOffset = amb::Timestamp::instance()->epochTime() - serverTime; Q_FOREACH(QVariant p, supported) { QVariantMap d = p.toMap(); Zone::Type zone = d["zone"].toInt(); std::string name = d["property"].toString().toStdString(); std::string proptype = d["type"].toString().toStdString(); std::string source = d["source"].toString().toStdString(); properties.append(name, source, zone, proptype); } source->updateSupported(); } else if (name == "getRanged") { QVariantList data = call["data"].toList(); std::list<AbstractPropertyType*> propertylist; Q_FOREACH(QVariant d, data) { QVariantMap obj = d.toMap(); std::string name = obj["property"].toString().toStdString(); std::string value = obj["value"].toString().toStdString(); double timestamp = obj["timestamp"].toDouble() + source->serverTimeOffset; int sequence = obj["sequence"].toInt(); AbstractPropertyType* type = VehicleProperty::getPropertyTypeForPropertyNameValue(name, value); if(!type) { DebugOut() << "TODO: support custom types here: " << endl; continue; } type->timestamp = timestamp; type->sequence = sequence; propertylist.push_back(type); }
static GMimeStream * stream_substream (GMimeStream *stream, gint64 start, gint64 end) { d(g_warning ("Invoked default stream_tell implementation.")); return NULL; }
Application::Application(int &argc, char **argv) : PsApplication(argc, argv), serverName(psServerPrefix() + cGUIDStr()), closing(false), updateRequestId(0), updateReply(0), updateThread(0), updateDownloader(0) { DEBUG_LOG(("Application Info: creation..")); QByteArray d(QDir((cPlatform() == dbipWindows ? cExeDir() : cWorkingDir()).toLower()).absolutePath().toUtf8()); char h[33] = { 0 }; hashMd5Hex(d.constData(), d.size(), h); serverName = psServerPrefix() + h + '-' + cGUIDStr(); if (mainApp) { DEBUG_LOG(("Application Error: another Application was created, terminating..")); exit(0); } mainApp = this; installEventFilter(new _DebugWaiter(this)); #if defined Q_OS_LINUX || defined Q_OS_LINUX64 QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/DejaVuSans.ttf")); QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/NanumMyeongjo-Regular.ttf")); #endif QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/OpenSans-Regular.ttf")); QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/OpenSans-Bold.ttf")); QFontDatabase::addApplicationFont(qsl(":/gui/art/fonts/OpenSans-Semibold.ttf")); float64 dpi = primaryScreen()->logicalDotsPerInch(); if (dpi <= 108) { // 0-96-108 cSetScreenScale(dbisOne); } else if (dpi <= 132) { // 108-120-132 cSetScreenScale(dbisOneAndQuarter); } else if (dpi <= 168) { // 132-144-168 cSetScreenScale(dbisOneAndHalf); } else { // 168-192-inf cSetScreenScale(dbisTwo); } if (devicePixelRatio() > 1) { cSetRetina(true); cSetRetinaFactor(devicePixelRatio()); cSetIntRetinaFactor(int32(cRetinaFactor())); } if (!cLangFile().isEmpty() && QFileInfo(cLangFile()).exists()) { LangLoaderPlain loader(cLangFile()); cSetLangErrors(loader.errors()); if (!cLangErrors().isEmpty()) { LOG(("Lang load errors: %1").arg(cLangErrors())); } else if (!loader.warnings().isEmpty()) { LOG(("Lang load warnings: %1").arg(loader.warnings())); } } Local::start(); style::startManager(); anim::startManager(); historyInit(); DEBUG_LOG(("Application Info: inited..")); window = new Window(); psInstallEventFilter(); connect(&socket, SIGNAL(connected()), this, SLOT(socketConnected())); connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); connect(&socket, SIGNAL(error(QLocalSocket::LocalSocketError)), this, SLOT(socketError(QLocalSocket::LocalSocketError))); connect(&socket, SIGNAL(bytesWritten(qint64)), this, SLOT(socketWritten(qint64))); connect(&socket, SIGNAL(readyRead()), this, SLOT(socketReading())); connect(&server, SIGNAL(newConnection()), this, SLOT(newInstanceConnected())); connect(this, SIGNAL(aboutToQuit()), this, SLOT(closeApplication())); connect(&updateCheckTimer, SIGNAL(timeout()), this, SLOT(startUpdateCheck())); connect(this, SIGNAL(updateFailed()), this, SLOT(onUpdateFailed())); connect(this, SIGNAL(updateReady()), this, SLOT(onUpdateReady())); connect(this, SIGNAL(applicationStateChanged(Qt::ApplicationState)), this, SLOT(onAppStateChanged(Qt::ApplicationState))); connect(&writeUserConfigTimer, SIGNAL(timeout()), this, SLOT(onWriteUserConfig())); writeUserConfigTimer.setSingleShot(true); connect(&killDownloadSessionsTimer, SIGNAL(timeout()), this, SLOT(killDownloadSessions())); if (cManyInstance()) { startApp(); } else { DEBUG_LOG(("Application Info: connecting local socket to %1..").arg(serverName)); socket.connectToServer(serverName); } }