SGVector<float64_t> CConjugateGradientSolver::solve( CLinearOperator<float64_t>* A, SGVector<float64_t> b) { SG_DEBUG("CConjugateGradientSolve::solve(): Entering..\n"); // sanity check REQUIRE(A, "Operator is NULL!\n"); REQUIRE(A->get_dimension()==b.vlen, "Dimension mismatch!\n"); // the final solution vector, initial guess is 0 SGVector<float64_t> result(b.vlen); result.set_const(0.0); // the rest of the part hinges on eigen3 for computing norms Map<VectorXd> x(result.vector, result.vlen); Map<VectorXd> b_map(b.vector, b.vlen); // direction vector SGVector<float64_t> p_(result.vlen); Map<VectorXd> p(p_.vector, p_.vlen); // residual r_i=b-Ax_i, here x_0=[0], so r_0=b VectorXd r=b_map; // initial direction is same as residual p=r; // the iterator for this iterative solver IterativeSolverIterator<float64_t> it(b_map, m_max_iteration_limit, m_relative_tolerence, m_absolute_tolerence); // CG iteration begins float64_t r_norm2=r.dot(r); // start the timer CTime time; time.start(); // set the residuals to zero if (m_store_residuals) m_residuals.set_const(0.0); for (it.begin(r); !it.end(r); ++it) { SG_DEBUG("CG iteration %d, residual norm %f\n", it.get_iter_info().iteration_count, it.get_iter_info().residual_norm); if (m_store_residuals) { m_residuals[it.get_iter_info().iteration_count] =it.get_iter_info().residual_norm; } // apply linear operator to the direction vector SGVector<float64_t> Ap_=A->apply(p_); Map<VectorXd> Ap(Ap_.vector, Ap_.vlen); // compute p^{T}Ap, if zero, failure float64_t p_dot_Ap=p.dot(Ap); if (p_dot_Ap==0.0) break; // compute the alpha parameter of CG float64_t alpha=r_norm2/p_dot_Ap; // update the solution vector and residual // x_{i}=x_{i-1}+\alpha_{i}p x+=alpha*p; // r_{i}=r_{i-1}-\alpha_{i}p r-=alpha*Ap; // compute new ||r||_{2}, if zero, converged float64_t r_norm2_i=r.dot(r); if (r_norm2_i==0.0) break; // compute the beta parameter of CG float64_t beta=r_norm2_i/r_norm2; // update direction, and ||r||_{2} r_norm2=r_norm2_i; p=r+beta*p; } float64_t elapsed=time.cur_time_diff(); if (!it.succeeded(r)) SG_WARNING("Did not converge!\n"); SG_INFO("Iteration took %ld times, residual norm=%.20lf, time elapsed=%lf\n", it.get_iter_info().iteration_count, it.get_iter_info().residual_norm, elapsed); SG_DEBUG("CConjugateGradientSolve::solve(): Leaving..\n"); return result; }
EIB_STD_EXPORT CTime operator+(const CTime& t1, const int t2) { CTime res(t1.GetTime() + t2); return res; }
BOOL CServerDlg::OnInitDialog() { CDialog::OnInitDialog(); g_pMain = this; // Default Init ... DefaultInit(); //---------------------------------------------------------------------- // Sets a random number starting point. //---------------------------------------------------------------------- SetTimer( CHECK_ALIVE, 10000, NULL ); srand( (unsigned)time(NULL) ); InitializeCriticalSection( &g_region_critical ); InitializeCriticalSection( &g_User_critical ); m_sMapEventNpc = 0; m_bFirstServerFlag = FALSE; // User Point Init for(int i=0; i<MAX_USER; i++) m_pUser[i] = NULL; // Server Start CTime time = CTime::GetCurrentTime(); AddToList("[AI ServerStart - %d-%d-%d, %02d:%02d]", time.GetYear(), time.GetMonth(), time.GetDay(), time.GetHour(), time.GetMinute() ); //---------------------------------------------------------------------- // DB part initialize //---------------------------------------------------------------------- GetServerInfoIni(); if(m_byZone == UNIFY_ZONE) m_strStatus.Format("Server zone: ALL"); else if(m_byZone == KARUS_ZONE) m_strStatus.Format("Server zone: KARUS"); else if(m_byZone == ELMORAD_ZONE) m_strStatus.Format("Server zone: EL MORAD"); else if(m_byZone == BATTLE_ZONE) m_strStatus.Format("Server zone: BATTLE"); //---------------------------------------------------------------------- // DB part initialize //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Communication Part Initialize ... //---------------------------------------------------------------------- uint16 sPort = BATTLE_ZONE; if (m_byZone == KARUS_ZONE || m_byZone == UNIFY_ZONE) sPort = AI_KARUS_SOCKET_PORT; else if (m_byZone == ELMORAD_ZONE) sPort = AI_ELMO_SOCKET_PORT; if (!s_socketMgr.Listen(sPort, MAX_SOCKET)) { EndDialog(IDCANCEL); return FALSE; } //---------------------------------------------------------------------- // Load tables //---------------------------------------------------------------------- if (!GetMagicTableData() || !GetMagicType1Data() || !GetMagicType2Data() || !GetMagicType3Data() || !GetMagicType4Data() || !GetNpcItemTable() || !GetMakeWeaponItemTableData() || !GetMakeDefensiveItemTableData() || !GetMakeGradeItemTableData() || !GetMakeLareItemTableData() || !GetNpcTableData(false) || !GetNpcTableData(true) // Load maps || !MapFileLoad() // Spawn NPC threads || !CreateNpcThread()) { EndDialog(IDCANCEL); return FALSE; } //---------------------------------------------------------------------- // Start NPC THREAD //---------------------------------------------------------------------- ResumeAI(); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control }
CTime::CTime(const CTime& time) { _time_val = time.GetTime(); }
bool CTime::operator<=(const CTime& time2) const { return (GetTime() <= time2.GetTime()); }
SGVector<complex128_t> CCGMShiftedFamilySolver::solve_shifted_weighted( CLinearOperator<SGVector<float64_t>, SGVector<float64_t> >* A, SGVector<float64_t> b, SGVector<complex128_t> shifts, SGVector<complex128_t> weights) { SG_DEBUG("Entering\n"); // sanity check REQUIRE(A, "Operator is NULL!\n"); REQUIRE(A->get_dimension()==b.vlen, "Dimension mismatch! [%d vs %d]\n", A->get_dimension(), b.vlen); REQUIRE(shifts.vector,"Shifts are not initialized!\n"); REQUIRE(weights.vector,"Weights are not initialized!\n"); REQUIRE(shifts.vlen==weights.vlen, "Number of shifts and number of " "weights are not equal! [%d vs %d]\n", shifts.vlen, weights.vlen); // the solution matrix, one column per shift, initial guess 0 for all MatrixXcd x_sh=MatrixXcd::Zero(b.vlen, shifts.vlen); MatrixXcd p_sh=MatrixXcd::Zero(b.vlen, shifts.vlen); // non-shifted direction SGVector<float64_t> p_(b.vlen); // the rest of the part hinges on eigen3 for computing norms Map<VectorXd> b_map(b.vector, b.vlen); Map<VectorXd> p(p_.vector, p_.vlen); // residual r_i=b-Ax_i, here x_0=[0], so r_0=b VectorXd r=b_map; // initial direction is same as residual p=r; p_sh=r.replicate(1, shifts.vlen).cast<complex128_t>(); // non shifted initializers float64_t r_norm2=r.dot(r); float64_t beta_old=1.0; float64_t alpha=1.0; // shifted quantities SGVector<complex128_t> alpha_sh(shifts.vlen); SGVector<complex128_t> beta_sh(shifts.vlen); SGVector<complex128_t> zeta_sh_old(shifts.vlen); SGVector<complex128_t> zeta_sh_cur(shifts.vlen); SGVector<complex128_t> zeta_sh_new(shifts.vlen); // shifted initializers zeta_sh_old.set_const(1.0); zeta_sh_cur.set_const(1.0); // the iterator for this iterative solver IterativeSolverIterator<float64_t> it(r, m_max_iteration_limit, m_relative_tolerence, m_absolute_tolerence); // start the timer CTime time; time.start(); // set the residuals to zero if (m_store_residuals) m_residuals.set_const(0.0); // CG iteration begins for (it.begin(r); !it.end(r); ++it) { SG_DEBUG("CG iteration %d, residual norm %f\n", it.get_iter_info().iteration_count, it.get_iter_info().residual_norm); if (m_store_residuals) { m_residuals[it.get_iter_info().iteration_count] =it.get_iter_info().residual_norm; } // apply linear operator to the direction vector SGVector<float64_t> Ap_=A->apply(p_); Map<VectorXd> Ap(Ap_.vector, Ap_.vlen); // compute p^{T}Ap, if zero, failure float64_t p_dot_Ap=p.dot(Ap); if (p_dot_Ap==0.0) break; // compute the beta parameter of CG_M float64_t beta=-r_norm2/p_dot_Ap; // compute the zeta-shifted parameter of CG_M compute_zeta_sh_new(zeta_sh_old, zeta_sh_cur, shifts, beta_old, beta, alpha, zeta_sh_new); // compute beta-shifted parameter of CG_M compute_beta_sh(zeta_sh_new, zeta_sh_cur, beta, beta_sh); // update the solution vector and residual for (index_t i=0; i<shifts.vlen; ++i) x_sh.col(i)-=beta_sh[i]*p_sh.col(i); // r_{i}=r_{i-1}+\beta_{i}Ap r+=beta*Ap; // compute new ||r||_{2}, if zero, converged float64_t r_norm2_i=r.dot(r); if (r_norm2_i==0.0) break; // compute the alpha parameter of CG_M alpha=r_norm2_i/r_norm2; // update ||r||_{2} r_norm2=r_norm2_i; // update direction p=r+alpha*p; compute_alpha_sh(zeta_sh_new, zeta_sh_cur, beta_sh, beta, alpha, alpha_sh); for (index_t i=0; i<shifts.vlen; ++i) { p_sh.col(i)*=alpha_sh[i]; p_sh.col(i)+=zeta_sh_new[i]*r; } // update parameters for (index_t i=0; i<shifts.vlen; ++i) { zeta_sh_old[i]=zeta_sh_cur[i]; zeta_sh_cur[i]=zeta_sh_new[i]; } beta_old=beta; } float64_t elapsed=time.cur_time_diff(); if (!it.succeeded(r)) SG_WARNING("Did not converge!\n"); SG_INFO("Iteration took %d times, residual norm=%.20lf, time elapsed=%f\n", it.get_iter_info().iteration_count, it.get_iter_info().residual_norm, elapsed); // compute the final result vector multiplied by weights SGVector<complex128_t> result(b.vlen); result.set_const(0.0); Map<VectorXcd> x(result.vector, result.vlen); for (index_t i=0; i<x_sh.cols(); ++i) x+=x_sh.col(i)*weights[i]; SG_DEBUG("Leaving\n"); return result; }
void CVersionChecker::SetNextCheck(int nDays) { CTimeSpan tPeriod( nDays, 0, 0, 0 ); CTime tNextCheck = CTime::GetCurrentTime() + tPeriod; theApp.WriteProfileInt( _T("VersionCheck"), _T("NextCheck"), (DWORD)tNextCheck.GetTime() ); }
CString MyTools::GetFormatedTime(CTime time){ CString str = time.Format("%X"); return str; }
void SVDLinearSolver<TMatrix,TVector>::solve(Matrix& M, Vector& x, Vector& b) { #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printComment("SVD"); #endif #ifdef DISPLAY_TIME CTime timer; double time1 = (double) timer.getTime(); #endif const bool verbose = f_verbose.getValue(); /// Convert the matrix and the right-hand vector to Eigen objects Eigen::MatrixXd m(M.rowSize(),M.colSize()); Eigen::VectorXd rhs(M.rowSize()); for(unsigned i=0; i<(unsigned)M.rowSize(); i++ ) { for( unsigned j=0; j<(unsigned)M.colSize(); j++ ) m(i,j) = M[i][j]; rhs(i) = b[i]; } msg_info_when(verbose) << "solve, Here is the matrix m: " << m ; /// Compute the SVD decomposition and the condition number Eigen::JacobiSVD<Eigen::MatrixXd> svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV); f_conditionNumber.setValue( (Real)(svd.singularValues()(0) / svd.singularValues()(M.rowSize()-1)) ); if(verbose) { msg_info() << "solve, the singular values are:" << sendl << svd.singularValues() << msgendl << "Its left singular vectors are the columns of the thin U matrix: " << msgendl << svd.matrixU() << msgendl << "Its right singular vectors are the columns of the thin V matrix:" msgendl << svd.matrixV() ; }else{ msg_info() << "solve, the singular values are:" << sendl << svd.singularValues() << msgendl; } /// Solve the equation system and copy the solution to the SOFA vector // Eigen::VectorXd solution = svd.solve(rhs); // for(unsigned i=0; i<M.rowSize(); i++ ){ // x[i] = solution(i); // } Eigen::VectorXd Ut_b = svd.matrixU().transpose() * rhs; Eigen::VectorXd S_Ut_b(M.colSize()); for( unsigned i=0; i<(unsigned)M.colSize(); i++ ) /// product with the diagonal matrix, using the threshold for near-null values { if( svd.singularValues()[i] > f_minSingularValue.getValue() ) S_Ut_b[i] = Ut_b[i]/svd.singularValues()[i]; else S_Ut_b[i] = (Real)0.0 ; } Eigen::VectorXd solution = svd.matrixV() * S_Ut_b; for(unsigned i=0; i<(unsigned)M.rowSize(); i++ ) { x[i] = (Real) solution(i); } #ifdef DISPLAY_TIME time1 = (double)(((double) timer.getTime() - time1) * timeStamp / (nb_iter-1)); dmsg_info() << " solve, SVD = "<<time1; #endif dmsg_info() << "solve, rhs vector = " << msgendl << rhs.transpose() << msgendl << " solution = \n" << msgendl << x << msgendl << " verification, mx - b = " << msgendl << (m * solution - rhs ).transpose() << msgendl; }
CString MyTools::GetFormatedDate(CTime time){ CString str = time.Format("%Y-%m-%d"); return str; }
CString MyTools::GetFormatedTime(){ CTime time = CTime::GetCurrentTime(); //time.get CString str = time.Format("%X"); return str; }
//工作者线程 int WINAPI HashThreadFunc(void *param) { ThreadData *thrdData = (ThreadData *)param; UIBridgeBase *uiBridge = thrdData->uiBridge; thrdData->threadWorking = true; uint32_t i; thrdData->totalSize = 0; uint64_t finishedSize = 0; uint64_t finishedSizeWhole = 0; bool isSizeCaled = false; //ULONGLONG* fSizes = NULL; ULLongVector fSizes(thrdData->nFiles); int positionWhole = 0; // 全局进度条位置 tstring tstrFileSize; tstring tstrFileVersion; tstring tstrFileMD5; tstring tstrFileSHA1; tstring tstrFileSHA256; tstring tstrFileCRC32; uiBridge->preparingCalc(); // 获得文件总大小 if(thrdData->nFiles < 200) // 文件太多就不预先计算了 { isSizeCaled = true; for(i = 0; i < (thrdData->nFiles); i++) { if(thrdData->stop) { thrdData->threadWorking = false; uiBridge->calcStop(); return 0; } uint64_t fSize = 0; const TCHAR* path; path = thrdData->fullPaths[i].c_str(); OsFile osFile(path); if(osFile.openRead()) { fSize = osFile.getLength();//fsize=status.m_size; // Fix 4GB file osFile.close(); } fSizes[i] = fSize; thrdData->totalSize += fSize; } } uiBridge->removePreparingCalc(); // 计算循环 for(i = 0; i < (thrdData->nFiles); i++) { if(thrdData->stop) { thrdData->threadWorking = false; uiBridge->calcStop(); return 0; } #if defined (WIN32) Sleep(50); #else usleep(50 * 1000); #endif // Declaration for calculator const TCHAR* path; uint64_t fsize, times, t = 0; finishedSize = 0; //unsigned int len; //unsigned char buffer[65534]; DataBuffer databuf; MD5_CTX mdContext; // MD5 context CSHA1 sha1; // SHA1 object char strSHA1[256]; SHA256_CTX sha256Ctx; // SHA256 context string strSHA256; uint32_t ulCRC32; // CRC32 context // Declaration for calculator ResultData resultNew; thrdData->resultList.push_back(resultNew); ResultData& result = thrdData->resultList.back(); result.enumState = RESULT_NONE; path = thrdData->fullPaths[i].c_str(); result.tstrPath = thrdData->fullPaths[i]; int position = 0; // 进度条位置 result.enumState = RESULT_PATH; uiBridge->showFileName(result); //Calculating begins #if defined (WIN32) CFileException fExc; #else char fExc[1024] = {0}; #endif OsFile osFile(path); if(osFile.openRead((void *)&fExc)) { MD5Init(&mdContext, 0); // MD5开始 sha1.Reset(); // SHA1开始 sha256_init(&sha256Ctx); // SHA256开始 crc32Init(&ulCRC32); // CRC32开始 uiBridge->updateProg(0); /* // get file size - start // fsize=thrdData->File.GetLength(); tsize+=fsize; // get file size - end // */ // get file status // tstring tstrLastModifiedTime; #if defined (WIN32) CTime ctModifedTime; #else struct timespec ctModifedTime; #endif if(osFile.getModifiedTime((void *)&ctModifedTime)) { #if defined (WIN32) tstrLastModifiedTime = ctModifedTime.Format("%Y-%m-%d %H:%M").GetString(); #else time_t ttModifiedTime; struct tm *tmModifiedTime; ttModifiedTime = ctModifedTime.tv_sec; tmModifiedTime = localtime(&ttModifiedTime); char szTmBuf[1024] = {0}; strftime(szTmBuf, 1024, "%Y-%m-%d %H:%M", tmModifiedTime); tstrLastModifiedTime = strtotstr(string(szTmBuf)); #endif result.tstrMDate = tstrLastModifiedTime; } fsize = osFile.getLength(); // Fix 4GB file result.ulSize = fsize; if(!isSizeCaled) // 如果没有计算过大小 { thrdData->totalSize += fsize; } else { thrdData->totalSize = thrdData->totalSize + fsize - fSizes[i]; // 修正总大小 fSizes[i] = fsize; // 修正文件大小 } #if defined (WIN32) // get file version // CString cstrVer = WindowsUtils::GetExeFileVersion((TCHAR *)path); tstrFileVersion = cstrVer.GetString(); result.tstrVersion = tstrFileVersion; #endif result.enumState = RESULT_META; uiBridge->showFileMeta(result); // get calculating times // times = fsize / DataBuffer::preflen + 1; //UINT bufferSize = sizeof(buffer); do { if(thrdData->stop) { osFile.close(); thrdData->threadWorking = false; uiBridge->calcStop(); return 0; } int64_t readRet = osFile.read(databuf.data, DataBuffer::preflen); if(readRet >= 0) databuf.datalen = (unsigned int)readRet; else databuf.datalen = 0; t++; MD5Update (&mdContext, databuf.data, databuf.datalen); // MD5更新 sha1.Update(databuf.data, databuf.datalen); // SHA1更新 sha256_update(&sha256Ctx, databuf.data, databuf.datalen); // SHA256更新 crc32Update(&ulCRC32, databuf.data, databuf.datalen); // CRC32更新 finishedSize += databuf.datalen; int progressMax = uiBridge->getProgMax(); int positionNew; if(fsize == 0) positionNew = progressMax; // 注意除0错误 else positionNew = (int)(progressMax * finishedSize / fsize); if(positionNew > position) { uiBridge->updateProg(positionNew); position = positionNew; } finishedSizeWhole += databuf.datalen; int positionWholeNew; if(thrdData->totalSize == 0) positionWholeNew = progressMax; // 注意除0错误 else positionWholeNew = (int)(progressMax * finishedSizeWhole / thrdData->totalSize); if(isSizeCaled && positionWholeNew > positionWhole) { positionWhole = positionWholeNew; uiBridge->updateProgWhole(positionWhole); } } while(databuf.datalen >= DataBuffer::preflen); uiBridge->fileCalcFinish(); MD5Final (&mdContext); // MD5完成 sha1.Final(); // SHA1完成 sha256_final(&sha256Ctx); // SHA256完成 crc32Finish(&ulCRC32); //CRC32完成 if(!isSizeCaled) { if(thrdData->nFiles == 0) { uiBridge->updateProgWhole(0); } else { uiBridge->updateProgWhole((i + 1) * 100 / (thrdData->nFiles)); } } osFile.close(); //Calculating ends char chHashBuff[1024] = {0}; // MD5 #if defined (WIN32) sprintf_s(chHashBuff, 1024, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", mdContext.digest[0], mdContext.digest[1], mdContext.digest[2], mdContext.digest[3], mdContext.digest[4], mdContext.digest[5], mdContext.digest[6], mdContext.digest[7], mdContext.digest[8], mdContext.digest[9], mdContext.digest[10], mdContext.digest[11], mdContext.digest[12], mdContext.digest[13], mdContext.digest[14], mdContext.digest[15]); #else sprintf(chHashBuff, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", mdContext.digest[0], mdContext.digest[1], mdContext.digest[2], mdContext.digest[3], mdContext.digest[4], mdContext.digest[5], mdContext.digest[6], mdContext.digest[7], mdContext.digest[8], mdContext.digest[9], mdContext.digest[10], mdContext.digest[11], mdContext.digest[12], mdContext.digest[13], mdContext.digest[14], mdContext.digest[15]); #endif tstrFileMD5 = strtotstr(string(chHashBuff)); // SHA1 sha1.ReportHash(strSHA1, CSHA1::REPORT_HEX); tstrFileSHA1 = strtotstr(string(strSHA1)); // SHA256 sha256_digest(&sha256Ctx, &strSHA256); tstrFileSHA256 = strtotstr(string(strSHA256)); // CRC32 #if defined (WIN32) sprintf_s(chHashBuff, 1024, "%08X", ulCRC32); #else sprintf(chHashBuff, "%08X", ulCRC32); #endif tstrFileCRC32 = strtotstr(string(chHashBuff)); // 在没做转换前,结果都是大写的 result.tstrMD5 = tstrFileMD5; result.tstrSHA1 = tstrFileSHA1; result.tstrSHA256 = tstrFileSHA256; result.tstrCRC32 = tstrFileCRC32; result.enumState = RESULT_ALL; uiBridge->showFileHash(result, thrdData->uppercase); } // end if(File.Open(path, CFile::modeRead|CFile::shareDenyWrite, &ex)) else { #if defined (WIN32) TCHAR szError[1024] = {0}; fExc.GetErrorMessage(szError, 1024); result.tstrError = szError; #else result.tstrError = strtotstr(string(fExc)); #endif result.enumState = RESULT_ERROR; uiBridge->showFileErr(result); } uiBridge->fileFinish(); } // end for(i = 0; i < (thrdData->nFiles); i++) uiBridge->calcFinish(); thrdData->threadWorking = false; return 0; }
static void s_TestMisc(int idx) { // AsString() {{ CTime t1; assert(t1.AsString() == ""); CTime t2(2000, 365 / 2); t2.SetFormat("M/D/Y h:m:s"); assert(t2.AsString() == "06/30/2000 00:00:00"); }} // Year 2000 problem {{ CTime t(1999, 12, 30); t.SetFormat("M/D/Y"); t.AddDay(); assert(t.AsString() == "12/31/1999"); t.AddDay(); assert(t.AsString() == "01/01/2000"); t.AddDay(); assert(t.AsString() == "01/02/2000"); t="02/27/2000"; t.AddDay(); assert(t.AsString() == "02/28/2000"); t.AddDay(); assert(t.AsString() == "02/29/2000"); t.AddDay(); assert(t.AsString() == "03/01/2000"); t.AddDay(); assert(t.AsString() == "03/02/2000"); }} // String assignment {{ CTime::SetFormat("M/D/Y h:m:s"); CTime t("02/15/2000 01:12:33"); assert(t.AsString() == "02/15/2000 01:12:33"); t = "3/16/2001 02:13:34"; assert(t.AsString() == "03/16/2001 02:13:34"); }} CTime::SetFormat("M/D/Y h:m:s.S"); // Adding Nanoseconds {{ CTime t; for (CTime ti(1999, 12, 31, 23, 59, 59, 999999995); ti <= CTime(2000, 1, 1, 0, 0, 0, 000000003); t = ti, ti.AddNanoSecond(2)) { } assert(t.AsString() == "01/01/2000 00:00:00.000000003"); }} CTime::SetFormat("M/D/Y h:m:s"); // Adding seconds {{ CTime t; for (CTime ti(1999, 12, 31, 23, 59, 5); ti <= CTime(2000, 1, 1, 0, 1, 20); t = ti, ti.AddSecond(11)) { } assert(t.AsString() == "01/01/2000 00:01:17"); }} // Adding minutes {{ CTime t; for (CTime ti(1999, 12, 31, 23, 45); ti <= CTime(2000, 1, 1, 0, 15); t = ti, ti.AddMinute(11)) { } assert(t.AsString() == "01/01/2000 00:07:00"); }} // Adding hours {{ CTime t; for (CTime ti(1999, 12, 31); ti <= CTime(2000, 1, 1, 15); t = ti, ti.AddHour(11)) { } assert(t.AsString() == "01/01/2000 09:00:00"); }} // Adding months {{ CTime t; for (CTime ti(1998, 12, 29); ti <= CTime(1999, 4, 1); t = ti, ti.AddMonth()) { } assert(t.AsString() == "03/28/1999 00:00:00"); }} // Difference {{ CTime t1(2000, 10, 1, 12, 3, 45,1); CTime t2(2000, 10, 2, 14, 55, 1,2); assert((t2.DiffDay(t1)-1.12) < 0.01); assert((t2.DiffHour(t1)-26.85) < 0.01); assert((t2.DiffMinute(t1)-1611.27) < 0.01); assert(t2.DiffSecond(t1) == 96676); }} // Database time formats {{ CTime t(2000, 1, 1, 1, 1, 1, 10000000); CTime::SetFormat("M/D/Y h:m:s.S"); TDBTimeI dbi = t.GetTimeDBI(); CTime::SetFormat("M/D/Y h:m:s"); dbi.days = 37093; dbi.time = 12301381; t.SetTimeDBI(dbi); assert(t.AsString() == "07/23/2001 11:23:24"); }} }
static void s_TestGMT(int idx) { // Write time in timezone format {{ CTime::SetFormat("M/D/Y h:m:s Z"); CTime t1(2001, 3, 12, 11, 22, 33, 999, CTime::eGmt); assert(t1.AsString() == "03/12/2001 11:22:33 GMT"); CTime t2(2001, 3, 12, 11, 22, 33, 999, CTime::eLocal); assert(t2.AsString() == "03/12/2001 11:22:33 "); }} // Process timezone string {{ CTime t; t.SetFormat("M/D/Y h:m:s Z"); t="03/12/2001 11:22:33 GMT"; assert(t.AsString() == "03/12/2001 11:22:33 GMT"); t="03/12/2001 11:22:33 "; assert(t.AsString() == "03/12/2001 11:22:33 "); }} // Day of week {{ CTime t(2001, 4, 1); t.SetFormat("M/D/Y h:m:s w"); int i; for (i=0; t<=CTime(2001, 4, 10); t.AddDay(),i++) { assert(t.DayOfWeek() == (i%7)); } }} // Test GetTimeT {{ time_t timer = time(0); CTime tgmt(CTime::eCurrent, CTime::eGmt, CTime::eTZPrecisionDefault); CTime tloc(CTime::eCurrent, CTime::eLocal, CTime::eTZPrecisionDefault); CTime t(timer); // Set the same time to all time objects tgmt.SetTimeT(timer); tloc.SetTimeT(timer); assert(timer == t.GetTimeT()); assert(timer == tgmt.GetTimeT()); // On the day of changing to summer/winter time, the local time // converted to GMT may differ from the value returned by time(0), // because in the common case API don't know if DST is in effect for // specified local time or not (see mktime()). time_t l_ = tloc.GetTimeT(); if (timer != l_ ) { if ( abs((int)(timer - l_)) > 3600 ) assert(timer == l_); } }} // Test TimeZoneOffset (1) -- EST timezone only {{ CTime tw(2001, 1, 1, 12); CTime ts(2001, 6, 1, 12); assert(tw.TimeZoneOffset() / 3600 == -5); assert(ts.TimeZoneOffset()/3600 == -4); }} // Test TimeZoneOffset (2) -- EST timezone only {{ CTime tw(2001, 6, 1, 12); CTime ts(2002, 1, 1, 12); assert(tw.TimeZoneOffset() / 3600 == -4); assert(ts.TimeZoneOffset() / 3600 == -5); }} // Test AdjustTime {{ CTime::SetFormat("M/D/Y h:m:s"); CTime t("03/11/2007 01:01:00"); CTime tn; t.SetTimeZonePrecision(CTime::eTZPrecisionDefault); // GMT t.SetTimeZone(CTime::eGmt); tn = t; tn.AddDay(5); assert(tn.AsString() == "03/16/2007 01:01:00"); tn = t; tn.AddDay(40); assert(tn.AsString() == "04/20/2007 01:01:00"); // Local eNone t.SetTimeZone(CTime::eLocal); t.SetTimeZonePrecision(CTime::eNone); tn = t; tn.AddDay(5); assert(tn.AsString() == "03/16/2007 01:01:00"); tn = t; tn.AddDay(40); assert(tn.AsString() == "04/20/2007 01:01:00"); //Local eMonth t.SetTimeZonePrecision(CTime::eMonth); tn = t; tn.AddDay(5); assert(tn.AsString() == "03/16/2007 01:01:00"); tn = t; tn.AddMonth(-1); assert(tn.AsString() == "02/11/2007 01:01:00"); tn = t; tn.AddMonth(+1); assert(tn.AsString() == "04/11/2007 02:01:00"); // Local eDay t.SetTimeZonePrecision(CTime::eDay); tn = t; tn.AddDay(-1); assert(tn.AsString() == "03/10/2007 01:01:00"); tn.AddDay(); assert(tn.AsString() == "03/11/2007 01:01:00"); tn = t; tn.AddDay(); assert(tn.AsString() == "03/12/2007 02:01:00"); // Local eHour t.SetTimeZonePrecision(CTime::eHour); tn = t; tn.AddHour(-3); CTime te = t; te.AddHour(3); assert(tn.AsString() == "03/10/2007 22:01:00"); assert(te.AsString() == "03/11/2007 05:01:00"); CTime th = tn; th.AddHour(49); assert(th.AsString() == "03/13/2007 00:01:00"); tn = "11/04/2007 00:01:00"; tn.SetTimeZonePrecision(CTime::eHour); te = tn; tn.AddHour(-3); te.AddHour(9); assert(tn.AsString() == "11/03/2007 21:01:00"); assert(te.AsString() == "11/04/2007 08:01:00"); th = tn; th.AddHour(49); assert(th.AsString() == "11/05/2007 21:01:00"); tn = "11/04/2007 09:01:00"; tn.SetTimeZonePrecision(CTime::eHour); te = tn; tn.AddHour(-10); te.AddHour(+10); assert(tn.AsString() == "11/04/2007 00:01:00"); assert(te.AsString() == "11/04/2007 19:01:00"); }} }
void CFirstPageDlg::OnFpTest() { if(bRecording==FALSE){ //mean that stay in the state of Stop. //click the button can triger the behavior of record. pBuffer1=(PBYTE)malloc(INP_BUFFER_SIZE); pBuffer2=(PBYTE)malloc(INP_BUFFER_SIZE); if (!pBuffer1 || !pBuffer2) { if (pBuffer1) free(pBuffer1); if (pBuffer2) free(pBuffer2); MessageBeep(MB_ICONEXCLAMATION); AfxMessageBox(TEXT("Memory erro!"));//TEXT() return ; } //open waveform audo for input //fill in the structure WAVEFORMATEX waveform.wFormatTag=WAVE_FORMAT_PCM; //PCM pulse code modulation waveform.nChannels=1; waveform.nSamplesPerSec=11025;//sample rate =25khz waveform.nAvgBytesPerSec=11025;//ave data rate = 25khz waveform.nBlockAlign=1; waveform.wBitsPerSample=8; //8 bits per sample waveform.cbSize=0; if (waveInOpen(&hWaveIn,WAVE_MAPPER,&waveform,(DWORD)this->m_hWnd,NULL,CALLBACK_WINDOW)) { free(pBuffer1); free(pBuffer2); MessageBeep(MB_ICONEXCLAMATION); AfxMessageBox(_T("Audio can not be open!")); } //PWAVEHDR pWaveHdr1,pWaveHdr2; pWaveHdr1->lpData=(LPSTR)pBuffer1; pWaveHdr1->dwBufferLength=INP_BUFFER_SIZE; pWaveHdr1->dwBytesRecorded=0; pWaveHdr1->dwUser=0; pWaveHdr1->dwFlags=0; pWaveHdr1->dwLoops=1; pWaveHdr1->lpNext=NULL; pWaveHdr1->reserved=0; waveInPrepareHeader(hWaveIn,pWaveHdr1,sizeof(WAVEHDR)); pWaveHdr2->lpData=(LPSTR)pBuffer2; pWaveHdr2->dwBufferLength=INP_BUFFER_SIZE; pWaveHdr2->dwBytesRecorded=0; pWaveHdr2->dwUser=0; pWaveHdr2->dwFlags=0; pWaveHdr2->dwLoops=1; pWaveHdr2->lpNext=NULL; pWaveHdr2->reserved=0; waveInPrepareHeader(hWaveIn,pWaveHdr2,sizeof(WAVEHDR)); ////////////////////////////////////////////////////////////////////////// pSaveBuffer = (PBYTE)realloc (pSaveBuffer, 1) ; // Add the buffers waveInAddBuffer (hWaveIn, pWaveHdr1, sizeof (WAVEHDR)) ; waveInAddBuffer (hWaveIn, pWaveHdr2, sizeof (WAVEHDR)) ; // Begin sampling this->showMsg+=_T("Recording...\r\n"); ((CEdit *)GetDlgItem(IDC_FP_TESTOUT))->SetWindowText(this->showMsg); dwDataLength = 0 ; waveInStart (hWaveIn) ; } else{ //bRecording == TRUE //Recording state,click the button will stop recording and finish the Test. if(bRecording){ //bEnding=TRUE; waveInReset(hWaveIn);//stop the record! } bRecording = FALSE; CString filepath; filepath = _T("E:\\Speechdata\\Test"); //find the directory if(!PathIsDirectory(filepath)){ CreateDirectory(filepath,NULL); } //set the test filename CTime current = CTime::GetCurrentTime(); CString filename; int y = current.GetYear(); int m = current.GetMonth(); int d = current.GetDay(); int h = current.GetHour(); int min = current.GetMinute(); int s = current.GetSecond(); filename.Format(_T("%d%d%d%d%d%d"),y,m,d,h,min,s); filename+=".wav"; filepath+=_T("\\")+filename; CFileFind find; if(!find.FindFile(filepath)){ save(filepath); } find.Close(); USES_CONVERSION;// #define CString to char * //CStdioFile myfile; CString file1; CString folderName = _T("E:\\Speechdata\\"); file1=_T("speakerdata.mat"); //file2=_T("NameTable.txt"); file1=folderName+file1; //E:\\Speechdata\\speakerdata.mat //file2=folderName+file2; //make sure the corresponse of the file1 and file2 CFileFind find1; //CFileException fileException; if(!find1.FindFile(file1)){ Initial(); /* if(find2.FindFile(file2)){ myfile.Remove(file2); if(!myfile.Open(file2,CFile::modeCreate,&fileException)){ AfxMessageBox(_T("Create Failure!")); } } find2.Close(); */ } find1.Close(); char* mysph=W2A(filename); mwArray speaker;//store the output mwArray sphName(mysph); try { //TestSpeech(int nargout, mwArray& pytest, const mwArray& SpeechName); TestSpeech(1,speaker,sphName); //conversion from mwArray to CString. mwString str=speaker.ToString(); const char* pytest = (const char*)str; CString name; name=pytest; CTime current = CTime::GetCurrentTime(); CString curtime; int h = current.GetHour(); int min = current.GetMinute(); int s = current.GetSecond(); curtime.Format(_T("%02d:%02d:%02d"),h,min,s); this->showMsg+=curtime+_T(":")+name+_T("\r\n");//Display the outcome of TEST ((CEdit *)GetDlgItem(IDC_FP_TESTOUT))->SetWindowText(this->showMsg); //显示用户信息(姓名,编号,部门等); Users signer; if(!signer.isExist(name,_T("train"))){ AfxMessageBox(_T("Invalid users or the existence of inconformity.")); return; } signer.GetUserInfo(name); CString signerinfo; signerinfo.Format(_T("UserName:%s\r\nUserId:%s\r\nDepartment:%s\r\nEmail:%s\r\n"),signer.getUserName(),signer.getUserId(),signer.getDep(),signer.getEmail()); UINT inret = MessageBox(signerinfo,_T("测试ing"),MB_ICONQUESTION|MB_OKCANCEL); if(inret==IDCANCEL){ ErrorCnt++; if(ErrorCnt == 2){ AfxMessageBox(_T("Your stored information may have been destroyed.Please contact the Administrator to re-enrollment")); } AfxMessageBox(_T("SignIn Error: identity discrepancy.Leave %d times to try again!"),2-ErrorCnt); return; } else if(inret == IDOK){ //flush the signer's signin record. //userid timetoarrive current = CTime::GetCurrentTime(); int year = current.GetYear(); int month = current.GetMonth(); int day = current.GetDay(); int hour = current.GetHour(); int minute = current.GetMinute(); int second = current.GetSecond(); CString signtime,signdate; signdate.Format(_T("%d/%d/%d"),month,day,year); signtime.Format(_T("%02d:%02d:%02d"),hour,minute,second); signer.setDTA(signdate); signer.setTTA(signtime); if(signer.InsertSignIn()) AfxMessageBox(_T("SignIn Success")); else AfxMessageBox(_T("SignIn Error")); this->showMsg=""; ErrorCnt=0; } } catch(const mwException &e){ CString ex; char *str=(char *)e.what(); str[strlen(e.what())]='\0'; ex=str; //display this->showMsg+=ex+_T("\r\n"); ((CEdit *)GetDlgItem(IDC_FP_TESTOUT))->SetWindowText(this->showMsg); CString caption=_T("warning"); MessageBox(ex,caption); } } }
//绘画界面 void CGameClientView::DrawGameView(CDC * pDC, int nWidth, int nHeight) { CString strFile,strTemp; CTime tmCur = CTime::GetCurrentTime(); CString strTime = tmCur.Format("%m%d"); strFile.Format("log\\%sDrawGameView.log",strTime); if (nWidth > 0 && nWidth < 1500) { if (xOffInt != nWidth) { xOffInt=nWidth; yOffInt=nHeight; AfxGetMainWnd()->SendMessage(IDM_RESET_UI, nWidth, nHeight); } } //绘画背景 DrawViewImage(pDC,m_ImageBack,enMode_Spread); int iXPos; int iYPos; for (int i=0; i < GAME_PLAYER; i++) { iXPos= m_PtVideo[i].x; iYPos=m_PtVideo[i].y; if ( 1 == m_uVideoInt[i]) DrawOtherVideoPic( pDC, iXPos, iYPos); }//End for //自己 int myX,myY,myW,myH; myW= MYSLEF_VIDEO_W; myH= MYSLEF_VIDEO_H; myX= 10-3;// myY= nHeight-myH-10-35; DrawMyselfVideoPic( pDC, myX, myY); //绘画用户 pDC->SetTextColor(RGB(255,255,0)); for (WORD i=0;i<GAME_PLAYER;i++) { //变量定义 const tagUserData * pUserData=GetUserInfo(i); if (pUserData!=NULL) { //用户名字 pDC->SetTextAlign((i==1)?(TA_RIGHT|TA_TOP):(TA_LEFT|TA_TOP)); DrawTextString(pDC,pUserData->szName,RGB(240,240,240),RGB(50,50,50),m_ptNameNew[i].x,m_ptName[i].y); if( m_tDice>0 && m_tDice<12) { ActionDice1( pDC,m_tDice); strTemp.Format("ActionDice1 "); theApp.WriteLog(strFile, strTemp); } else { if( m_tDice== 12) { ActionDice2( pDC,m_nDiceCount1,m_nDiceCount2); strTemp.Format("ActionDice2 m_nDiceCount1=%d,m_nDiceCount2=%d", m_nDiceCount1,m_nDiceCount2); theApp.WriteLog(strFile, strTemp); // m_tDice++; }//End if }//End if //其他信息 WORD wUserTimer=GetUserTimer(i); if (wUserTimer!=0) DrawUserTimer(pDC,m_ptTimer[i].x,m_ptTimer[i].y,wUserTimer); if (pUserData->cbUserStatus==US_READY) DrawUserReady(pDC,m_ptReady[i].x,m_ptReady[i].y); //DrawUserFace(pDC,pUserData->wFaceID,m_ptFace[i].x,m_ptFace[i].y,pUserData->cbUserStatus==US_OFFLINE); //画听标记 if( m_bTingFlag[i] ) { ShowTingPic( pDC, m_ptFace[i].x,m_ptFace[i].y); }//End if } } //用户标志 if (m_wBankerUser!=INVALID_CHAIR) { //加载位图 CImageHandle ImageHandle(&m_ImageUserFlag); int nImageWidth=m_ImageUserFlag.GetWidth()/4; int nImageHeight=m_ImageUserFlag.GetHeight(); //绘画标志 for (WORD i=0;i<GAME_PLAYER;i++) { WORD wIndex=((i+GAME_PLAYER)-m_wBankerUser)%GAME_PLAYER; m_ImageUserFlag.BitBlt(pDC->m_hDC,m_UserFlagPos[i].x,m_UserFlagPos[i].y,nImageWidth,nImageHeight,nImageWidth*wIndex,0); } } //桌面麻将 for (WORD i=0;i<4;i++) { m_TableCard[i].DrawCardControl(pDC); m_DiscardCard[i].DrawCardControl(pDC); m_WeaveCard[i][0].DrawCardControl(pDC); m_WeaveCard[i][1].DrawCardControl(pDC); m_WeaveCard[i][2].DrawCardControl(pDC); m_WeaveCard[i][3].DrawCardControl(pDC); } //堆积麻将 m_HeapCard[3].DrawCardControl(pDC); m_HeapCard[0].DrawCardControl(pDC); m_HeapCard[1].DrawCardControl(pDC); m_HeapCard[2].DrawCardControl(pDC); //用户麻将 m_UserCard[0].DrawCardControl(pDC); m_UserCard[1].DrawCardControl(pDC); m_UserCard[2].DrawCardControl(pDC); m_HandCardControl.DrawCardControl(pDC); //出牌提示 if (m_bOutCard==true) { CImageHandle HandleOutCard(&m_ImageOutCard); m_ImageOutCard.AlphaDrawImage(pDC,(nWidth-m_ImageOutCard.GetWidth())/2,nHeight-150,RGB(255,0,255)); //显示听牌 if ( !m_bTingFlag[2] ) { m_btTingCard.ShowWindow(SW_SHOW); } else { m_btTingCard.ShowWindow(SW_HIDE); } } else { m_btTingCard.ShowWindow(SW_HIDE); } //等待提示 if (m_bWaitOther==true) { CImageHandle HandleWait(&m_ImageWait); m_ImageWait.AlphaDrawImage(pDC,(nWidth-m_ImageWait.GetWidth())/2,nHeight-150,RGB(255,0,255)); } //荒庄标志 if (m_bHuangZhuang==true) { CImageHandle HandleHuangZhuang(&m_ImageHuangZhuang); m_ImageHuangZhuang.AlphaDrawImage(pDC,(nWidth-m_ImageHuangZhuang.GetWidth())/2,nHeight/2-103,RGB(255,0,255)); } //用户状态 for (WORD i=0;i<GAME_PLAYER;i++) { if ((m_wOutCardUser==i)||(m_cbUserAction[i]!=0)) { //计算位置 int nXPos=0,nYPos=0; switch (i) { case 0: //北向 { nXPos=nWidth/2-32; nYPos=m_nYBorder+95; break; } case 1: //东向 { nXPos=nWidth-m_nXBorder-170; nYPos=nHeight/2-71; break; } case 2: //南向 { nXPos=nWidth/2-32; nYPos=nHeight-m_nYBorder-220; break; } case 3: //西向 { nXPos=m_nXBorder+115; nYPos=nHeight/2-71 -45; break; } } //动作背景 CImageHandle ImageHandle(&m_ImageActionBack); m_ImageActionBack.AlphaDrawImage(pDC,nXPos,nYPos,m_ImageActionBack.GetWidth()/4,m_ImageActionBack.GetHeight(), i*m_ImageActionBack.GetWidth()/4,0,RGB(255,0,255)); //绘画动作 if (m_cbUserAction[i]!=WIK_NULL) { //变量定义 int nXImagePos=0; CImageHandle ImageHandle(&m_ImageUserAction); int nItemWidth=m_ImageUserAction.GetWidth()/7; //计算位置 if (m_cbUserAction[i]&WIK_PENG) nXImagePos=nItemWidth; else if (m_cbUserAction[i]&WIK_FILL) nXImagePos=nItemWidth*2; else if (m_cbUserAction[i]&WIK_GANG) nXImagePos=nItemWidth*3; else if (m_cbUserAction[i]&WIK_CHI_HU) nXImagePos=nItemWidth*4; //绘画动作 int nItemHeight=m_ImageUserAction.GetHeight(); m_ImageUserAction.BitBlt(pDC->m_hDC,nXPos+13,nYPos+15,nItemWidth,nItemHeight,nXImagePos,0); } else { //如果已经听了,而且打了第一张出去 if ( m_IntFirstTingFlag[i]==1 && m_bTingFlag[i] ) { //绘画麻将 g_CardResource.m_ImageTableBottom.DrawCardItem(pDC,0,nXPos+18,nYPos+15); } else { //绘画麻将 g_CardResource.m_ImageTableBottom.DrawCardItem(pDC,m_cbCardData,nXPos+18,nYPos+15); } } } } return; }
//把录像文件按时间逆序,然后反应到控件上 yjj 090304 void CAppealDlg::ProcessRecordFile(const CString& strUserName) { if (strUserName == "") { return; } GetDlgItem(IDC_EDIT_USERNAME)->SetWindowText(strUserName); GetDlgItem(IDC_EDIT_PHONE_NUM)->SetWindowText(""); GetDlgItem(IDC_EDIT_APPEAL_EMAIL)->SetWindowText(""); GetDlgItem(IDC_EDIT_APPEAL_CONTENT)->SetWindowText(""); CString strPath = CBcfFile::GetAppPath(); //得到当前的目录 strPath += "log"; strPath += "\\"; CString gamenamefile = strPath + "gamename.bcf"; DWORD dwHandle = cfgOpenFile(gamenamefile); if(dwHandle < 0x10) return; strPath += "log_"; strPath += strUserName; strPath += "\\"; CTime tCurTime = CTime::GetCurrentTime(); CString direct = tCurTime.Format("%Y-%m-%d"); CString strCurDir = strPath + direct; strCurDir += "\\"; CFileFind finder; strCurDir += _T("*.*"); int iFindFileCount = 0; m_fileList.clear(); //从当前,向前找6个目录 for (int i=0; i<6; i++) { BOOL bWorking = finder.FindFile(strCurDir); while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDots()) continue; //找到一个文件 //CString sFileName = finder.GetFileName(); //CString sFilePath = finder.GetFilePath(); RecordFileStruct recordfile; recordfile.strWholeName = finder.GetFilePath(); //得到完整名字 recordfile.strFileName = finder.GetFileName(); //得到文件名字 //wushuqun 2009.5.20 recordfile.strGamePath = finder.GetFilePath(); //if (recordfile.strFileName.Find(".zxh") == -1) //{ // continue; //} CString strNameId = GetFileNameID(recordfile.strFileName); recordfile.strGameName = GetGameName(dwHandle,strNameId); //得到游戏名字 if (recordfile.strGameName == "") { continue; } finder.GetCreationTime(recordfile.timeCreatTime); //得到创建文件时间 recordfile.strGameTime = recordfile.timeCreatTime.Format("%m-%d %H:%M "); m_fileList.push_back(recordfile); //把文件信息加入链表 iFindFileCount ++; } //找完整个目录 if (iFindFileCount >= 20) { break; } // CTimeSpan ts(1, 0, 0, 0); tCurTime -= ts; direct = tCurTime.Format("%Y-%m-%d"); strCurDir = strPath + direct; strCurDir += "\\"; strCurDir +=_T("*.*"); //找上一天的目录 } //按升序排列 m_fileList.sort(); m_FileListCtrl.DeleteAllItems(); list<RecordFileStruct>::iterator iter = m_fileList.begin(); int iCount = 0; for (; iter != m_fileList.end(); iter++) { RecordFileStruct recordfile = *iter; //RecordFileStruct* pRecordFile = iter; //iter ++; //CString strListNmae; //strListNmae.Format("%s %s",recordfile.strGameName,recordfile.strGameTime); int iItem = m_FileListCtrl.InsertItem(m_FileListCtrl.GetItemCount(),recordfile.strGameName); m_FileListCtrl.SetItemText(iItem,1,recordfile.strGameTime); //wushuqun 2009.5.20 //新增加一列“文件名称" m_FileListCtrl.SetItemText(iItem,2,recordfile.strFileName); //m_FileListCtrl.SetItemData(iItem,(DWORD)&iter); iCount++; //m_ListBox.AddString(strListNmae); //m_ListBox.InsertString(iCount++,strListNmae); if (iCount == 20) { break; } } cfgClose(dwHandle); finder.Close(); }
void CMonitorPage::UpdateGameStatus(const i8desk::GameInfoMap& GameInfos) { int nIdcCount = 0, nSvrCount = 0, nMatchCount = 0; int nAutoUptCount = 0, nNeedUptCount = 0; int nIdcAddInThisWeekCount = 0, nIdcUpdateCount = 0; int nIdcI8PlayCount = 0, nIdcI8PlayNotDownloadCount = 0; unsigned __int64 ullIdcSize = 0, ullSvrSize = 0; unsigned __int64 ullIdcI8PlaySize = 0, ullIdcI8PlayNotDownloadSize = 0; int nAddGameNoDownNum = 0; //近期新增资源(未下载) int nConVirRunGameNum = 0; //配置为虚拟盘运行的资源数 unsigned __int64 ullConVirRunGameSize = 0; int nConLocRunGameNum = 0; //配置为本地更新运行的资源数 unsigned __int64 ullConLocRunGameSize = 0; int nConRunNotUptGameNum = 0;//配置为不更新,直接运行的资源数 unsigned __int64 ullConRunNotUptGameSize = 0; CTime now = CTime::GetCurrentTime(); int nowYear = now.GetYear(); int nowMonth = now.GetMonth(); int nowDay = now.GetDay(); CTime start(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0); start -= CTimeSpan(30,0,0,0); //30天算近期 DWORD StartTime = (DWORD)start.GetTime(); //得到本周开始的时刻,用于计算本周中心更新的游戏数 int nowDayOfWeek = now.GetDayOfWeek(); CTime ThisWeekStart = now - CTimeSpan(nowDayOfWeek); CTime ThisWeekStartDay(ThisWeekStart.GetYear(), ThisWeekStart.GetMonth(), ThisWeekStart.GetDay(), 0, 0, 0); DWORD ThisWeekStartTime = (DWORD)ThisWeekStartDay.GetTime(); i8desk::GameInfoMapCItr it = GameInfos.begin(); for (; it != GameInfos.end(); ++it) { if (it->second->GID >= MIN_IDC_GID) { nIdcCount++; ullIdcSize += it->second->Size; if (it->second->Status == 1) nMatchCount++; if (it->second->AddDate > StartTime && it->second->Status == 0) { nAddGameNoDownNum++; } if (it->second->IdcVer > ThisWeekStartTime) { nIdcAddInThisWeekCount++; CTime IdcUpdateTime = it->second->IdcVer; if (IdcUpdateTime.GetDay() == nowDay && IdcUpdateTime.GetMonth() == nowMonth && IdcUpdateTime.GetYear() == nowYear) { nIdcUpdateCount++; } } if (it->second->I8Play == 1) { nIdcI8PlayCount++; ullIdcI8PlaySize += it->second->Size; if (it->second->Status == 0) { nIdcI8PlayNotDownloadCount++; ullIdcI8PlayNotDownloadSize += it->second->Size; } } } if (it->second->Status == 1) { nSvrCount++; ullSvrSize += it->second->Size; if (it->second->AutoUpt == 1) nAutoUptCount++; if (it->second->GID >= MIN_IDC_GID && it->second->IdcVer != it->second->SvrVer) nNeedUptCount++; bool bConLocRunGame = false; bool bConVirRunGame = false; bool bConRunNotUptGame = false; for (size_t i = 0; i < it->second->RunTypes.size(); i++) { switch (it->second->RunTypes[i].RunType) { case ERT_LOCAL: bConLocRunGame = true; break; case ERT_VDISK: bConVirRunGame = true; break; case ERT_DIRECT: bConRunNotUptGame = true; break; default: break; } } if (bConLocRunGame) { nConLocRunGameNum++; ullConLocRunGameSize += it->second->Size; } if (bConVirRunGame) { nConVirRunGameNum++; ullConVirRunGameSize += it->second->Size; } if (bConRunNotUptGame) { nConRunNotUptGameNum++; ullConRunNotUptGameSize += it->second->Size; } } } sprintf(m_GameInfo.CGameNum, "%d个/%.2fG", nIdcCount, ullIdcSize/1024.0/1024.0); //中心游戏数 sprintf(m_GameInfo.MatchGameNum, "%d个", nMatchCount); //本地己匹配到中心资源的游戏 sprintf(m_GameInfo.LGameNum, "%d个/%.2fG", nSvrCount, ullSvrSize/1024.0/1024.0); //本地游戏数 sprintf(m_GameInfo.CAddGameNum, "%d个", nAddGameNoDownNum); //近期新增资源(未下载) sprintf(m_GameInfo.ConLocRunGameNum, "%d个/%.2fG", nConLocRunGameNum, ullConLocRunGameSize/1024.0/1024.0); //增值游戏本地未下载数 sprintf(m_GameInfo.ConVirRunGameNum, "%d个/%.2fG", nConVirRunGameNum, ullConVirRunGameSize/1024.0/1024.0); //增值游戏本地未下载数 sprintf(m_GameInfo.ConRunNotUptGameNum, "%d个/%.2fG", nConRunNotUptGameNum, ullConRunNotUptGameSize/1024.0/1024.0); //增值游戏本地未下载数 sprintf(m_GameInfo.HaveUptGameNum, "%d个", nNeedUptCount); //有更新的游戏数 }
bmrm_return_value_T svm_bmrm_solver( bmrm_data_T* data, float64_t* W, float64_t TolRel, float64_t TolAbs, float64_t lambda, uint32_t _BufSize, bool cleanICP, uint32_t cleanAfter, float64_t K, uint32_t Tmax, CRiskFunction* risk_function) { bmrm_return_value_T bmrm = {0, 0, 0, 0, 0, 0, 0}; libqp_state_T qp_exitflag; float64_t *b, *beta, *diag_H, sq_norm_W; float64_t R, *subgrad, *A, QPSolverTolRel, rsum, C=1.0; uint32_t *I, *ICPcounter, *ICPs, cntICP=0; uint8_t S = 1; uint32_t nDim=data->w_dim; CTime ttime; float64_t tstart, tstop; float64_t *b2, *beta2, *diag_H2, *A2, *H2; uint32_t *I2, *ICPcounter2, nCP_new=0, idx=0, idx2=0, icp_iter=0, icp_iter2=0; int32_t idx_icp=0, idx_icp2=0; bool flag1=true, flag2=true; tstart=ttime.cur_time_diff(false); BufSize=_BufSize; QPSolverTolRel=TolRel*0.5; H=NULL; b=NULL; beta=NULL; A=NULL; subgrad=NULL; diag_H=NULL; I=NULL; ICPcounter=NULL; ICPs=NULL; b2=NULL; beta2=NULL; H2=NULL; I2=NULL; ICPcounter2=NULL; A2=NULL; diag_H2=NULL; H=(float64_t*)LIBBMRM_CALLOC(BufSize*BufSize, sizeof(float64_t)); if (H==NULL) { bmrm.exitflag=-2; goto cleanup; } A=(float64_t*)LIBBMRM_CALLOC(nDim*BufSize, sizeof(float64_t)); if (A==NULL) { bmrm.exitflag=-2; goto cleanup; } b=(float64_t*)LIBBMRM_CALLOC(BufSize, sizeof(float64_t)); if (b==NULL) { bmrm.exitflag=-2; goto cleanup; } beta=(float64_t*)LIBBMRM_CALLOC(BufSize, sizeof(float64_t)); if (beta==NULL) { bmrm.exitflag=-2; goto cleanup; } subgrad=(float64_t*)LIBBMRM_CALLOC(nDim, sizeof(float64_t)); if (subgrad==NULL) { bmrm.exitflag=-2; goto cleanup; } diag_H=(float64_t*)LIBBMRM_CALLOC(BufSize, sizeof(float64_t)); if (diag_H==NULL) { bmrm.exitflag=-2; goto cleanup; } I=(uint32_t*)LIBBMRM_CALLOC(BufSize, sizeof(uint32_t)); if (I==NULL) { bmrm.exitflag=-2; goto cleanup; } ICPcounter=(uint32_t*)LIBBMRM_CALLOC(BufSize, sizeof(uint32_t)); if (ICPcounter==NULL) { bmrm.exitflag=-2; goto cleanup; } ICPs=(uint32_t*)LIBBMRM_CALLOC(BufSize, sizeof(uint32_t)); if (ICPs==NULL) { bmrm.exitflag=-2; goto cleanup; } /* Temporary buffers for ICP removal */ b2=(float64_t*)LIBBMRM_CALLOC(BufSize, sizeof(float64_t)); beta2=(float64_t*)LIBBMRM_CALLOC(BufSize, sizeof(float64_t)); ICPcounter2=(uint32_t*)LIBBMRM_CALLOC(BufSize, sizeof(uint32_t)); I2=(uint32_t*)LIBBMRM_CALLOC(BufSize, sizeof(uint32_t)); diag_H2=(float64_t*)LIBBMRM_CALLOC(BufSize, sizeof(float64_t)); A2=(float64_t*)LIBBMRM_CALLOC(nDim*BufSize, sizeof(float64_t)); H2=(float64_t*)LIBBMRM_CALLOC(BufSize*BufSize, sizeof(float64_t)); if (b2==NULL || beta2==NULL || ICPcounter2==NULL || I2==NULL || diag_H2==NULL || A2==NULL || H2==NULL) { bmrm.exitflag=-2; } /* Iinitial solution */ risk_function->risk(data, &R, subgrad, W); bmrm.nCP=0; bmrm.nIter=0; bmrm.exitflag=0; b[0]=-R; LIBBMRM_MEMCPY(A, subgrad, nDim*sizeof(float64_t)); /* Compute initial value of Fp, Fd, assuming that W is zero vector */ sq_norm_W=0; bmrm.Fp=R+0.5*lambda*sq_norm_W; bmrm.Fd=-LIBBMRM_PLUS_INF; tstop=ttime.cur_time_diff(false); /* Verbose output */ SG_SPRINT("%4d: tim=%.3lf, Fp=%lf, Fd=%lf, R=%lf\n", bmrm.nIter, tstop-tstart, bmrm.Fp, bmrm.Fd, R); /* main loop */ while (bmrm.exitflag==0) { tstart=ttime.cur_time_diff(false); bmrm.nIter++; /* Update H */ if (bmrm.nCP>0) { for (uint32_t i=0; i<bmrm.nCP; ++i) { rsum=0.0; for (uint32_t j=0; j<nDim; ++j) { rsum+=A[LIBBMRM_INDEX(j, i, nDim)]*A[LIBBMRM_INDEX(j, bmrm.nCP, nDim)]; } H[LIBBMRM_INDEX(i, bmrm.nCP, BufSize)]=rsum/lambda; } for (uint32_t i=0; i<bmrm.nCP; ++i) { H[LIBBMRM_INDEX(bmrm.nCP, i, BufSize)]=H[LIBBMRM_INDEX(i, bmrm.nCP, BufSize)]; } } H[LIBBMRM_INDEX(bmrm.nCP, bmrm.nCP, BufSize)]=0.0; for (uint32_t i=0; i<nDim; ++i) H[LIBBMRM_INDEX(bmrm.nCP, bmrm.nCP, BufSize)]+=A[LIBBMRM_INDEX(i, bmrm.nCP, nDim)]*A[LIBBMRM_INDEX(i, bmrm.nCP, nDim)]/lambda; diag_H[bmrm.nCP]=H[LIBBMRM_INDEX(bmrm.nCP, bmrm.nCP, BufSize)]; I[bmrm.nCP]=1; bmrm.nCP++; /* call QP solver */ qp_exitflag = libqp_splx_solver(&get_col, diag_H, b, &C, I, &S, beta, bmrm.nCP, QPSolverMaxIter, 0.0, QPSolverTolRel, -LIBBMRM_PLUS_INF, 0); bmrm.qp_exitflag=qp_exitflag.exitflag; /* Update ICPcounter (add one to unused and reset used) + compute number of active CPs*/ bmrm.nzA=0; for (uint32_t aaa=0; aaa<bmrm.nCP; ++aaa) { if (beta[aaa]>epsilon) { bmrm.nzA+=1; ICPcounter[aaa]=0; } else { ICPcounter[aaa]+=1; } } /* W update */ for (uint32_t i=0; i<nDim; ++i) { rsum = 0.0; for (uint32_t j=0; j<bmrm.nCP; ++j) { rsum += A[LIBBMRM_INDEX(i, j, nDim)]*beta[j]; } W[i] = -rsum/lambda; } /* risk and subgradient computation */ risk_function->risk(data, &R, subgrad, W); LIBBMRM_MEMCPY(A+bmrm.nCP*nDim, subgrad, nDim*sizeof(float64_t)); b[bmrm.nCP]=-R; for (uint32_t j=0; j<nDim; ++j) b[bmrm.nCP]+=subgrad[j]*W[j]; sq_norm_W = 0; for (uint32_t j=0; j<nDim; ++j) sq_norm_W+=W[j]*W[j]; bmrm.Fp=R+0.5*lambda*sq_norm_W; bmrm.Fd=-qp_exitflag.QP; /* Stopping conditions */ if (bmrm.Fp - bmrm.Fd <= TolRel*LIBBMRM_ABS(bmrm.Fp)) bmrm.exitflag=1; if (bmrm.Fp - bmrm.Fd <= TolAbs) bmrm.exitflag=2; if (bmrm.nCP >= BufSize) bmrm.exitflag=-1; tstop=ttime.cur_time_diff(false); /* Verbose output */ SG_SPRINT("%4d: tim=%.3lf, Fp=%lf, Fd=%lf, (Fp-Fd)=%lf, (Fp-Fd)/Fp=%lf, R=%lf, nCP=%d, nzA=%d\n", bmrm.nIter, tstop-tstart, bmrm.Fp, bmrm.Fd, bmrm.Fp-bmrm.Fd, (bmrm.Fp-bmrm.Fd)/bmrm.Fp, R, bmrm.nCP, bmrm.nzA); /* Check size of Buffer */ if (bmrm.nCP>=BufSize) { bmrm.exitflag=-2; SG_SERROR("Buffer exceeded.\n"); } /* Inactive Cutting Planes (ICP) removal */ if (cleanICP) { /* find ICP */ cntICP = 0; for (uint32_t aaa=0; aaa<bmrm.nCP; ++aaa) if (ICPcounter[aaa]>=cleanAfter) { ICPs[cntICP++]=aaa; } /* do ICP */ if (cntICP > 0) { nCP_new=bmrm.nCP-cntICP; idx=0; idx2=0; icp_iter=0; icp_iter2=0; idx_icp=ICPs[icp_iter]; idx_icp2=ICPs[icp_iter2]; flag1=true; flag2=true; for (uint32_t i=0; i<bmrm.nCP; ++i) { if ((int32_t)i != idx_icp) { b2[idx]=b[i]; beta2[idx]=beta[i]; ICPcounter2[idx]=ICPcounter[i]; I2[idx]=I[i]; diag_H2[idx]=diag_H[i]; LIBBMRM_MEMCPY(A2+idx*nDim, A+i*nDim, nDim*sizeof(float64_t)); idx2=0; icp_iter2=0; idx_icp2=ICPs[icp_iter2]; flag2=true; for (uint32_t j=0; j<bmrm.nCP; ++j) { if ((int32_t)j != idx_icp2) { H2[LIBBMRM_INDEX(idx, idx2, BufSize)]=H[LIBBMRM_INDEX(i, j, BufSize)]; idx2++; } else { if (flag2 && icp_iter2+1 < cntICP) { idx_icp2=ICPs[++icp_iter2]; } else { flag2=false; idx_icp2=-1; } } } idx++; } else { if (flag1 && icp_iter+1 < cntICP) { idx_icp=ICPs[++icp_iter]; } else { flag1=false; idx_icp=-1; } } } /* copy data from tmps back to original */ LIBBMRM_MEMCPY(b, b2, nCP_new*sizeof(float64_t)); LIBBMRM_MEMCPY(beta, beta2, nCP_new*sizeof(float64_t)); LIBBMRM_MEMCPY(ICPcounter, ICPcounter2, nCP_new*sizeof(uint32_t)); LIBBMRM_MEMCPY(I, I2, nCP_new*sizeof(uint32_t)); LIBBMRM_MEMCPY(diag_H, diag_H2, nCP_new*sizeof(float64_t)); LIBBMRM_MEMCPY(A, A2, nDim*nCP_new*sizeof(float64_t)); for (uint32_t i=0; i<nCP_new; ++i) for (uint32_t j=0; j<nCP_new; ++j) H[LIBBMRM_INDEX(i, j, BufSize)]=H2[LIBBMRM_INDEX(i, j, BufSize)]; bmrm.nCP=nCP_new; } } } /* end of main loop */ cleanup: LIBBMRM_FREE(H); LIBBMRM_FREE(b); LIBBMRM_FREE(beta); LIBBMRM_FREE(A); LIBBMRM_FREE(subgrad); LIBBMRM_FREE(diag_H); LIBBMRM_FREE(I); LIBBMRM_FREE(ICPcounter); LIBBMRM_FREE(ICPs); LIBBMRM_FREE(H2); LIBBMRM_FREE(b2); LIBBMRM_FREE(beta2); LIBBMRM_FREE(A2); LIBBMRM_FREE(diag_H2); LIBBMRM_FREE(I2); LIBBMRM_FREE(ICPcounter2); return(bmrm); }
void CActiveWindow::GetMyCurrentTime(CString &time) { CTime tm; tm=CTime::GetCurrentTime(); time.Format(L"%d-%d-%d-%d-%d-%d",tm.GetYear(),tm.GetMonth(),tm.GetDay(),tm.GetHour(),tm.GetMinute(),tm.GetSecond()); }
void CXunJianDlg::OnOK() { try{ pList= (CListBox *)GetDlgItem(IDC_HOSTLIST); /*if( pList->GetTextLen(0)>15 || pList->GetTextLen(0)<7 ) { MessageBox("主机列表文件未加载,请重新选择!"); return; }*/ _GUID clsid; IUnknown *pUnk; IDispatch *pDisp; LPDISPATCH lpDisp; _Application app; Workbooks xj_books; _Workbook xj_book; Worksheets xj_sheets; _Worksheet xj_sheet; Range range; Range unionRange; Range cols; Font font; // COleVariant background; COleVariant covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR); ::CLSIDFromProgID(L"Excel.Application",&clsid); // from registry if(GetActiveObject(clsid, NULL,&pUnk) == S_OK) { VERIFY(pUnk->QueryInterface(IID_IDispatch,(void**) &pDisp) == S_OK); app.AttachDispatch(pDisp); pUnk->Release(); } else { if(!app.CreateDispatch("Excel.Application")) { MessageBox("Excel program not found"); app.Quit(); return; } } xj_books=app.GetWorkbooks(); xj_book= xj_books.Add(covOptional); xj_sheets= xj_book.GetSheets(); xj_sheet= xj_sheets.GetItem(COleVariant((short)1)); int i; Range item; range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1")); for(i= 0; i < 6; i++) { item.AttachDispatch(range.GetItem(COleVariant((long)1),COleVariant((long)i+1)).pdispVal); item.SetValue2(COleVariant(PROJ[i])); } //描绘第一行目录 //range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1")); lpDisp=range.GetInterior(); Interior cellinterior; cellinterior.AttachDispatch(lpDisp); cellinterior.SetColor(COleVariant((long)0xc0c0c0)); //设置背景色为灰色 cellinterior.ReleaseDispatch(); //range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1")); range.SetHorizontalAlignment(COleVariant((long)-4108)); //全部居中 Borders bord; bord=range.GetBorders(); bord.SetLineStyle(COleVariant((short)1)); //设置边框 //range=xj_sheet.GetRange(COleVariant("A1"),COleVariant("F1")); cols=range.GetEntireColumn(); cols.AutoFit(); //自动调整 /**************************表格初始绘画完成************************************/ long usedRowNum; //行计数 CString handleFile; CString hostFileName,hostip; bool error = false; CString infos,info; ExcelFile excelFile; ReadTxt xj_txt; xj_HostCount=pList->GetCount(); for(int n_host=0;n_host<xj_HostCount;n_host++) //主循环,一个文件一次循环。 { pList->GetText(n_host,hostFileName); hostip = hostFileName; handleFile = hostFileName + _T(" 正在处理..."); pList->DeleteString(n_host); pList->InsertString(n_host,handleFile); pList->SetCurSel(n_host); pList->UpdateWindow(); hostFileName = xj_FilePath + hostFileName; hostFileName += _T(".txt"); CStdioFile hostFile; if(!hostFile.Open(hostFileName,CFile::modeRead,0)) { //记录不存在文件名 handleFile.Replace("正在处理...","失败!"); error = true; pList->DeleteString(n_host); pList->InsertString(n_host,handleFile); pList->UpdateWindow(); continue; } usedRowNum = excelFile.GetRowCount(xj_sheet); range.AttachDispatch(xj_sheet.GetCells()); //info.Format( _T("%d"), n_host+1); info = xj_txt.ReadHostName(&hostFile,COMMAND[0],COMMAND[1]); //获取节点名称 range.SetItem(COleVariant(usedRowNum+1),COleVariant(long(1)),COleVariant(info)); int portCount = 0; //端口数目,不包括7/1 CString nSend, nRecv; float n_Send,n_Recv; while(hostFile.ReadString(info)) if(info.Find( COMMAND[4]) > -1) break; while( hostFile.ReadString(info) && info.Find( "[local]" ) == -1 ) //端口号和流量 { if( info.Find( "/" ) == -1 || info.Find( "7/1" ) > -1 ) continue; info.Replace( "ethernet",""); info = _T("'") + info; infos = info; while( hostFile.ReadString(info) ) if( info.Find( "send bit rate" ) > -1 ) break; nSend = info.Mid( 60 ); hostFile.ReadString(info); nRecv = info.Mid( 60 ); nSend.Trim(); nRecv.Trim(); n_Send = (float)atof(nSend); n_Recv = (float)atof(nRecv); if( n_Send < 1000 && n_Recv < 1000 ) continue; portCount++; range.SetItem(COleVariant(usedRowNum+portCount),COleVariant(long(2)),COleVariant(infos.Trim())); range.SetItem(COleVariant(usedRowNum+portCount),COleVariant(long(4)),COleVariant((n_Send>n_Recv)?nSend:nRecv)); } hostFile.SeekToBegin(); infos = xj_txt.ReadLine(&hostFile,"ubscriber Address"); //历史在线最大用户数 if( infos == _T("") ) info = _T("0"); else { int token = 0; for(i = 0; i < 5 ; i++) info = infos.Tokenize(" ",token); } range.SetItem(COleVariant(usedRowNum+1),COleVariant(long(6)),COleVariant(info.Trim())); hostFile.Close(); if(portCount > 1) { unionRange.AttachDispatch(range.GetItem(COleVariant(usedRowNum+1),COleVariant((long)1)).pdispVal); unionRange.AttachDispatch(unionRange.GetResize(COleVariant((long)portCount),COleVariant((long)1))); unionRange.Merge(COleVariant((long)0)); //节点名称单元格合并 unionRange.AttachDispatch(range.GetItem(COleVariant(usedRowNum+1),COleVariant((long)6)).pdispVal); unionRange.AttachDispatch(unionRange.GetResize(COleVariant((long)portCount),COleVariant((long)1))); unionRange.Merge(COleVariant((long)0)); //历史最大用户数合并 } unionRange.AttachDispatch(range.GetItem(COleVariant(usedRowNum+1),COleVariant((long)1)).pdispVal); unionRange.AttachDispatch(unionRange.GetResize(COleVariant((long)portCount),COleVariant((long)6))); unionRange.SetRowHeight(COleVariant(13.5)); bord = unionRange.GetBorders(); bord.SetLineStyle(COleVariant((short)1)); //设置边框 handleFile.Replace("正在处理...","已完成"); pList->DeleteString(n_host); pList->InsertString(n_host,handleFile); pList->UpdateWindow(); } CTime time; time = time.GetCurrentTime(); infos = time.Format("%Y%m%d%H%M%S"); //time.Format(); info = _T("巡检报表") + infos + _T(".xlsx"); info = xj_FilePath + info; info.Replace("\\\\","\\"); xj_book.SaveAs(COleVariant(info),covOptional,covOptional,covOptional,covOptional,covOptional,0,covOptional,covOptional,covOptional,covOptional,covOptional); if(error == true ) { MessageBox("巡检报表已完成,已保存到\r\n" + info + "\r\n有文件打开错误,点击\"确定\"返回查看","有文件打开错误!",MB_OK|MB_ICONWARNING); app.Quit(); } else { if(MessageBox("巡检报表已完成,已保存到\r\n" + info + "\r\n点击\"确定\"打开文件查看","生成报表完成",MB_OKCANCEL) == IDOK) { app.SetVisible(TRUE); app.SetUserControl(TRUE); } else app.Quit(); } } catch (CFileException* e) { e->ReportError(); e->Delete(); } //CDialog::OnOK(); }
//this is the thread function which calls the subversion function UINT CCacheDlg::WatchTestThread() { CDirFileEnum direnum(m_sRootPath); m_filelist.RemoveAll(); CString filepath; bool bIsDir = false; while (direnum.NextFile(filepath, &bIsDir)) m_filelist.Add(filepath); CTime starttime = CTime::GetCurrentTime(); GetDlgItem(IDC_STARTTIME)->SetWindowText(starttime.Format(L"%H:%M:%S")); ULONGLONG startticks = GetTickCount64(); CString sNumber; std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<INT_PTR> dist(0, max(0, m_filelist.GetCount() - 1)); filepath = m_filelist.GetAt(dist(mt)); GetStatusFromRemoteCache(CTGitPath(m_sRootPath), false); for (int i=0; i < 10000; ++i) { filepath = m_filelist.GetAt(dist(mt)); GetDlgItem(IDC_FILEPATH)->SetWindowText(filepath); TouchFile(filepath); CopyRemoveCopy(filepath); sNumber.Format(L"%d", i); GetDlgItem(IDC_DONE)->SetWindowText(sNumber); } // create dummy directories and remove them again several times for (int outer = 0; outer<100; ++outer) { for (int i=0; i<10; ++i) { filepath.Format(L"__MyDummyFolder%d", i); CreateDirectory(m_sRootPath + L'\\' + filepath, nullptr); HANDLE hFile = CreateFile(m_sRootPath + L'\\' + filepath + L"\\file", GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); CloseHandle(hFile); SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, m_sRootPath + L'\\' + filepath + L"\\file", NULL); } Sleep(500); for (int i=0; i<10; ++i) { filepath.Format(L"__MyDummyFolder%d", i); DeleteFile(m_sRootPath + L'\\' + filepath + L"\\file"); RemoveDirectory(m_sRootPath + L'\\' + filepath); } sNumber.Format(L"%d", outer); GetDlgItem(IDC_DONE)->SetWindowText(sNumber); } CTime endtime = CTime::GetCurrentTime(); CString sEnd = endtime.Format(L"%H:%M:%S"); ULONGLONG endticks = GetTickCount64(); CString sEndText; sEndText.Format(L"%s - %I64u ms", (LPCTSTR)sEnd, endticks - startticks); GetDlgItem(IDC_ENDTIME)->SetWindowText(sEndText); return 0; }
bool CTime::operator>(const CTime& time2) const { return (GetTime() > time2.GetTime()); }
bool CLPBoost::train(CFeatures* data) { ASSERT(labels); ASSERT(features); int32_t num_train_labels=labels->get_num_labels(); int32_t num_feat=features->get_dim_feature_space(); int32_t num_vec=features->get_num_vectors(); ASSERT(num_vec==num_train_labels); delete[] w; w=new float64_t[num_feat]; memset(w,0,sizeof(float64_t)*num_feat); w_dim=num_feat; CCplex solver; solver.init(E_LINEAR); SG_PRINT("setting up lpboost\n"); solver.setup_lpboost(C1, num_vec); SG_PRINT("finished setting up lpboost\n"); float64_t result=init(num_vec); ASSERT(result); int32_t num_hypothesis=0; CTime time; CSignal::clear_cancel(); while (!(CSignal::cancel_computations())) { int32_t max_dim=0; float64_t violator=find_max_violator(max_dim); SG_PRINT("iteration:%06d violator: %10.17f (>1.0) chosen: %d\n", num_hypothesis, violator, max_dim); if (violator <= 1.0+epsilon && num_hypothesis>1) //no constraint violated { SG_PRINT("converged after %d iterations!\n", num_hypothesis); break; } float64_t factor=+1.0; if (max_dim>=num_svec) { factor=-1.0; max_dim-=num_svec; } SGSparseVectorEntry<float64_t>* h=sfeat[max_dim].features; int32_t len=sfeat[max_dim].num_feat_entries; solver.add_lpboost_constraint(factor, h, len, num_vec, labels); solver.optimize(u); //CMath::display_vector(u, num_vec, "u"); num_hypothesis++; if (get_max_train_time()>0 && time.cur_time_diff()>get_max_train_time()) break; } float64_t* lambda=new float64_t[num_hypothesis]; solver.optimize(u, lambda); //CMath::display_vector(lambda, num_hypothesis, "lambda"); for (int32_t i=0; i<num_hypothesis; i++) { int32_t d=dim->get_element(i); if (d>=num_svec) w[d-num_svec]+=lambda[i]; else w[d]-=lambda[i]; } //solver.write_problem("problem.lp"); solver.cleanup(); cleanup(); return true; }
EIB_STD_EXPORT CTime operator-(const CTime& t1, const CTime& t2) { CTime res(t1.GetTime() - t2.GetTime()); return res; }
bool CShareBoost::train_machine(CFeatures* data) { if (data) set_features(data); if (m_features == NULL) SG_ERROR("No features given for training\n") if (m_labels == NULL) SG_ERROR("No labels given for training\n") if (m_nonzero_feas <= 0) SG_ERROR("Set a valid (> 0) number of non-zero features to seek before training\n") if (m_nonzero_feas >= dynamic_cast<CDenseFeatures<float64_t>*>(m_features)->get_num_features()) SG_ERROR("It doesn't make sense to use ShareBoost with num non-zero features >= num features in the data\n") m_fea = dynamic_cast<CDenseFeatures<float64_t> *>(m_features)->get_feature_matrix(); m_rho = SGMatrix<float64_t>(m_multiclass_strategy->get_num_classes(), m_fea.num_cols); m_rho_norm = SGVector<float64_t>(m_fea.num_cols); m_pred = SGMatrix<float64_t>(m_fea.num_cols, m_multiclass_strategy->get_num_classes()); m_pred.zero(); m_activeset = SGVector<int32_t>(m_fea.num_rows); m_activeset.vlen = 0; m_machines->reset_array(); for (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i) m_machines->push_back(new CLinearMachine()); CTime *timer = new CTime(); float64_t t_compute_pred = 0; // t of 1st round is 0, since no pred to compute for (int32_t t=0; t < m_nonzero_feas; ++t) { timer->start(); compute_rho(); int32_t i_fea = choose_feature(); m_activeset.vector[m_activeset.vlen] = i_fea; m_activeset.vlen += 1; float64_t t_choose_feature = timer->cur_time_diff(); timer->start(); optimize_coefficients(); float64_t t_optimize = timer->cur_time_diff(); SG_SDEBUG(" SB[round %03d]: (%8.4f + %8.4f) sec.\n", t, t_compute_pred + t_choose_feature, t_optimize); timer->start(); compute_pred(); t_compute_pred = timer->cur_time_diff(); } SG_UNREF(timer); // release memory m_fea = SGMatrix<float64_t>(); m_rho = SGMatrix<float64_t>(); m_rho_norm = SGVector<float64_t>(); m_pred = SGMatrix<float64_t>(); return true; }
// Нажали Старт void CAlsIzmFormView::OnBnClickedStartIzm() { // TODO: добавьте свой код обработчика уведомлений // setup update timer (25 - 4hz)2c 1c /* timer = timeSetEvent(950, // — интервал времени до наступления таймерного события в миллисекундах. 50, // — разрешение таймера при отсчете интервала, в миллисекундах. Нулевое значение требует максимально возможного разрешения 0, // — указатель функции уведомления. 0, // — произвольное 32-разрядное значение, передаваемое функции уведомления при вызове в качестве параметра. TIME_PERIODIC); // тип таймерного события: TIME_ONESHOT — однократное, TIME_PERIODIC — периодическое. */ dataObject.MoveFirst(); ///// // получить доступ к объекту класса CMainFrame можно так: /// CMainFrame *pMainFrame = (CMainFrame*)(::AfxGetMainWnd()); /// put = &pMainFrame->m_ViewPut; sss.Format(L"\xFEFF\r\nМаршрут\t%s\r\n",dataObject.m_ItineraryName); //sss = L'\xFEFF'+ ssf; //sss += dataObject.m_ItineraryName; //sss += L"\r\n"; //+L"Маршрут\t" //sss += _T("\r\n" ); /// put->asimfile.SeekToEnd(); /// put->asimfile.Write(sss,sss.GetLength()*sizeof(TCHAR )); // dataObject.MoveNext(); //AfxMessageBox(dataObject.m_ObgectName); //m_PK_obgect_start = m_PK_obgect; m_PK_obgect = dataObject.m_Pk; m_CurSel = 0; //// if (FileTok.m_hFile!=(HANDLE)-1) { sss = L"\r\n"; // CTime time = CTime::GetCurrentTime(); sss += time.Format("%x %X\t"); //%Y // //sss += L"\t"; sss += L"Маршрут: "; //sss += L"\t"; sss += dataObject.m_ItineraryName; sss += L"\r\n"; FileTok.SeekToEnd(); FileTok.Write(sss, sss.GetLength()*sizeof(TCHAR)); } //Запустить навигацию OziExplorer if (m_gOziExplorer_OnOff) { COziExplorerApi OziExplorer; // Доступ к карте if (!OziExplorer.OziExplorerIsRun) return ; // если апи не загружен - выход if (OziExplorer.CheckOziExplorerRunning() == -1) { AfxMessageBox(L" Запуск OziExplorer от имени администратора. \n Проверьте панель задач для подтверждения"); ////AfxMessageBox(L"OziExplorer Не запущен",0,0); //::ShellExecute(NULL, L"Open", m_gstrPathOz, // NULL, // m_gstrPathOz.Left(m_gstrPathOz.ReverseFind(_T('\\'))+1), // SW_SHOWNORMAL); ////////////////////////////////////////////////////////////////////////////// SHELLEXECUTEINFO se; se.cbSize =sizeof(se); se.fMask = NULL; //se.hwnd = GetDesktopWindow(); se.lpVerb = L"runas"; se.lpFile = m_gstrPathOz; se.lpDirectory = m_gstrPathOz.Left(m_gstrPathOz.ReverseFind(_T('\\'))+1); se.nShow = SW_NORMAL; //se.lpParameters = ::ShellExecuteEx(&se); ///////////////////////////////////////////////////////////////////////////// //Sleep(2000); do {} while (OziExplorer.CheckOziExplorerRunning()); Sleep(3000); /////////////////////////////////////////////////////////// } // Получить маршрут m_Itinerary.GetLBText(m_Itinerary.GetCurSel(),sss); // Удалить старые путевые точки OziExplorer.ClearAllWaypoints(); // Загрузить путевые точки if (OziExplorer.LoadWaypoint(&sss)) // 0 при удаче { AfxMessageBox (L"Ошибка загрузки путевых точек " + sss); return ; } // Загрузить маршрут //AfxMessageBox (L"Пытаемся загрузить маршрут" + sss); if (OziExplorer.LoadRoute(&sss)) // 0 при удаче { AfxMessageBox (L"Ошибка загрузки маршрута " + sss); return ; } //else if (OziExplorer.StartMovingMapSerial()) // запустить навигацию,перед точками НЕ работает { AfxMessageBox(L"Не удаеться запустить связь с GPS",0,0); return ; } OziExplorer.ShowTrack(1); // показать трек ////Запустить скоростиметр №1 //////int res = oziOedometer1ON((int*)& Oedometer1); //////if (res) //////{ ////// AfxMessageBox(L"Путимер НЕ запущен",0,0); ////// return ; //////} //double m_gPiket; //m_gPiket = NULL; //m_gPiket = 333,0; //double* m_Pk; //m_Pk = & m_gPiket; //int mp; //mp = NULL; //int* mpp; //mpp = & mp; ////if (OziExplorer.OedometerON(1, &m_gPiket, &mp)) // theApp.m_PK_current theApp.m_ipiketkp ////{ //// AfxMessageBox(L"Путимер НЕ запущен",0,0); //// return ; ////} ////else AfxMessageBox(L"Путимер запущен",0,0); //} } //// SetTimer(10, 500, NULL); //1000 }
//----------------------------------------------------------------------------- int main( int argc, char* argv[]) //----------------------------------------------------------------------------- { const char* pDevSerial = "BF*"; cout << "\n ++ Start PowerDownTest sample: " << __DATE__ << "/" << __TIME__ << endl; if( argc > 1 ) { pDevSerial = argv[1]; } unsigned int uiDevCount = 0; DeviceManager DevMgr; if( ( uiDevCount = DevMgr.deviceCount() ) == 0 ) { cout << "*** Error: No MATRIX VISION device found! Unable to continue!" << endl; return 0; } cout << "Have found " << uiDevCount << " devices on this platform!" << endl; for( unsigned i=0; i<uiDevCount; i++ ) { Device* pDevTmp = DevMgr.getDevice( i ); cout << " " << i << " Serial: " << pDevTmp->serial.read() << endl; } cout << "Initialising the device: "<< pDevSerial << ". This might take some time..." << endl; // create an interface to the first MATRIX VISION device with the serila number pDevSerial Device* pDev = DevMgr.getDeviceBySerial( pDevSerial ); try { pDev->open(); } catch( ImpactAcquireException& e ) { // this e.g. might happen if the same device is already opened in another process... cout << "*** Error: An error occurred while opening the device(error code: " << e.getErrorCode() << ")." << endl; return 0; } FunctionInterface fi( pDev ); // only 8Bit/pixel destination image are supported by the \c writeFile() function ImageDestination imgDst( pDev ); imgDst.pixelFormat.write( idpfMono8 ); // get mvBF system settings SystemBlueFOX sbf( pDev ); bool bPowerDown = false; do { cout << "Ready to snap. Press 'p'<return> to power down, 'q'<return> to quit or <return> to snap an image.." << endl; char ch = getchar(); if( ch == 'p' ) { // for mvBlueFOX only: test power down / up cout << "Power off!" << endl; sbf.powerMode.write( dpmOff ); bPowerDown = true; // read and discard the <return> getchar(); } else if( ch == 'q' ) { // break out of loop to finish application // read and discard the <return> getchar(); break; } else { // snap if( bPowerDown ) { // first we need to power up again CTime timer1; sbf.powerMode.write( dpmOn ); bPowerDown = false; cout << "Power On!" << ". Power On took " << timer1.elapsed() << "s., " << endl; } CTime timer; // send a request to the default request queue of the device and wait for the result. fi.imageRequestSingle(); const int iMaxWaitTime_ms = 5000; // wait for results from the default capture queue int iRequestNr = fi.imageRequestWaitFor( iMaxWaitTime_ms ); cout << "Request Nr.: " << iRequestNr << ". Snap took " << timer.elapsed() << "s., " << endl; // check if the image has been captured without any problems if( !fi.isRequestNrValid( iRequestNr ) ) { // this can not happen in this sample, but may happen if you wait for a request without // sending one to the driver before cout << "*** Error: No request has been sent to the driver." << endl; // unlock the buffer to let the driver know that you no longer need this buffer fi.imageRequestUnlock( iRequestNr ); // free resources fi.imageRequestReset( 0, 0 ); pDev->close(); return 0; } const Request* psRequest = fi.getRequest(iRequestNr); if( !fi.isRequestOK( psRequest ) ) { cout << "*** " << psRequest->requestResult << endl; // unlock the buffer to let the driver know that you no longer need this buffer fi.imageRequestUnlock( iRequestNr ); // free resources fi.imageRequestReset( 0, 0 ); pDev->close(); return 0; } // Everything went well. Save the result const char* pImageName = "SingCapt.pgm"; cout << "Will save the file as: " << pImageName << endl; if( writeFile( (const unsigned char*)psRequest->imageData.read(), psRequest->imageWidth.read(), psRequest->imageHeight.read(), psRequest->imageLinePitch.read(), psRequest->imagePixelPitch.read(), pImageName ) < 0 ) cout << "*** Error: File: "<< pImageName << " could not be saved!!" << endl; // unlock the buffer to let the driver know that you no longer need this buffer fi.imageRequestUnlock( iRequestNr ); } // snap } while( true ); // free resources fi.imageRequestReset( 0, 0 ); pDev->close(); return 0; }
BOOL CAujardDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon //---------------------------------------------------------------------- // Logfile initialize //---------------------------------------------------------------------- CTime time=CTime::GetCurrentTime(); char strLogFile[50]; sprintf_s(strLogFile, sizeof(strLogFile), "AujardLog-%d-%d-%d.txt", time.GetYear(), time.GetMonth(), time.GetDay()); m_LogFile.Open( strLogFile, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate | CFile::shareDenyNone ); m_LogFile.SeekToEnd(); m_iLogFileDay = time.GetDay(); if (!m_LoggerRecvQueue.InitailizeMMF(MAX_PKTSIZE, MAX_COUNT, SMQ_LOGGERSEND, FALSE) || !m_LoggerSendQueue.InitailizeMMF(MAX_PKTSIZE, MAX_COUNT, SMQ_LOGGERRECV, FALSE) || !InitializeMMF()) { AfxMessageBox("Unable to initialize shared memory. Ensure Ebenezer is running."); AfxPostQuitMessage(0); return FALSE; } CIni ini("Aujard.ini"); ini.GetString("ODBC", "ACCOUNT_DSN", "KN_online", m_strAccountDSN, sizeof(m_strAccountDSN)); ini.GetString("ODBC", "ACCOUNT_UID", "knight", m_strAccountUID, sizeof(m_strAccountUID)); ini.GetString("ODBC", "ACCOUNT_PWD", "knight", m_strAccountPWD, sizeof(m_strAccountPWD)); ini.GetString("ODBC", "GAME_DSN", "KN_online", m_strGameDSN, sizeof(m_strGameDSN)); ini.GetString("ODBC", "GAME_UID", "knight", m_strGameUID, sizeof(m_strGameUID)); ini.GetString("ODBC", "GAME_PWD", "knight", m_strGamePWD, sizeof(m_strGamePWD)); m_nServerNo = ini.GetInt("ZONE_INFO", "GROUP_INFO", 1); m_nZoneNo = ini.GetInt("ZONE_INFO", "ZONE_INFO", 1); if (!m_DBAgent.Connect() || !m_DBAgent.LoadItemTable()) { AfxPostQuitMessage(0); return FALSE; } SetTimer( PROCESS_CHECK, 40000, NULL ); SetTimer( CONCURRENT_CHECK, 300000, NULL ); DWORD id; m_hReadQueueThread = ::CreateThread( NULL, 0, ReadQueueThread, (LPVOID)this, 0, &id); CTime cur = CTime::GetCurrentTime(); CString starttime; starttime.Format("Aujard Start : %02d/%02d/%04d %d:%02d\r\n", cur.GetDay(), cur.GetMonth(), cur.GetYear(), cur.GetHour(), cur.GetMinute()); m_LogFile.Write(starttime, starttime.GetLength()); return TRUE; // return TRUE unless you set the focus to a control }
//写日志 void WriteLog(CString srcStr,int iFlag) { CTime currTime = CTime::GetCurrentTime(); try { CString filepath = ""; CString destStr = ""; CString folder = ""; CString filename = ""; CString strAppPath = ""; if (iFlag == 0) //注册成功列表 { folder = "log"; filename.Format("%s_registerList.txt",currTime.Format("%Y%m%d")); } else if(iFlag == 1) //信息日志 { folder = "log"; filename.Format("%s_log.txt",currTime.Format("%Y%m%d")); } else if ( iFlag == 2 ) //缓冲日志 { folder = "log"; filename.Format("%s_bufinfo.txt",currTime.Format("%Y%m%d")); } else if ( iFlag == 3 ) //缓冲日志 { folder = "log"; filename.Format("%s_可用的IP.txt",currTime.Format("%Y%m%d")); } else //异常日志 (3) { folder = "exception"; filename.Format("%s_exception.txt",currTime.Format("%Y%m%d")); } CUserFile *pFile = CUserFile::GetInstance(); if ( pFile ) { pFile->GetAppPath(strAppPath); } CString folderName = ""; folderName.Format("%s%s",strAppPath,folder); if(_access(folderName,0)!=0) { if( mkdir(folderName) != 0 )//创建目录 { return; } } destStr.Format("%s %s",srcStr,currTime.Format("%Y-%m-%d %H:%M:%S")); filepath.Format("%s\\%s",folderName,filename); FILE *fp; char szfile[1000]={0}; sprintf(szfile,filepath); fp=fopen(szfile,"a+"); fprintf(fp,"%s\r\n",destStr); fclose(fp); } catch (...) { } }