int main() { try { std::auto_ptr<swk::mr3::job> wc(swk::mr3::make_job<uint64_t, std::string, std::string, uint64_t>( wordcount_mapper, wordcount_reducer )); wc->add_input_path("data1.txt"); wc->add_input_path("data2.txt"); wc->add_input_path("data3.txt"); wc->set_output_dir("output"); wc->run(); return 0; } catch (std::exception e) { return 1; } }
int main(int argc, char** argv) { char szPath[MAX_PATH]; for (int i = 1; i < argc; i++) { PathRemoveFileSpec(lstrcpy(szPath, argv[i])); WIN32_FIND_DATA findData; HANDLE hFind = FindFirstFile(argv[i], &findData); if (hFind != INVALID_HANDLE_VALUE) { do { char szFile[MAX_PATH]; PathAppend(lstrcpy(szFile, szPath), findData.cFileName); printf("%s\n", szFile); wc_info wci; FILE* fp = fopen(szFile, "r"); if (fp) { ZeroMemory(&wci, sizeof(wci)); wci.m_size = _filelength(fileno(fp)); wci.m_p = malloc(wci.m_size); fread(wci.m_p, sizeof(char), wci.m_size, fp); fclose(fp); wc(wci); printf("バイト数: %u\n", wci.m_count_byte); printf(" 文字数: %u\n", wci.m_count_char); free(wci.m_p); } } while (FindNextFile(hFind, &findData)); FindClose(hFind); } } _getch(); return 0; }
TEST (test_person, test_list_employees) { Person jlp("Jean Luc Piccard"); Person wc("Wesley Crusher"); Employer emp1("Star Fleet Federation", "galaxy"); Position cpt("captain", "the big boss"); Position lieut("lieutenant", "second in command"); emp1.hire(jlp, cpt); emp1.hire(wc, lieut); EXPECT_EQ(emp1.getNbEmployees(), 2); EXPECT_STREQ(jlp.getEmployer().c_str(), emp1.getName().c_str()); EXPECT_STREQ(wc.getEmployer().c_str(), emp1.getName().c_str()); }
int main(int argc, char *argv[]) { int status = seteuid(getuid()); if (status < 0) { printf("Failed to seteuid to real user\n"); exit(status); } QCoreApplication a(argc, argv); QSettings *settings = loadSettings(a.arguments()); BoneConsole wc(settings, &a); return a.exec(); }
int main(int argc, char *argv[]) { printf("%d + %d = %d\n", 4, 5, add(4, 5)); int arr[] = { 1,2,3,4,5,6,7,8,9,0 }; printf("max numer is %d\n", max(10, arr)); char *str = "one two three four five six"; printf("word count is %d\n", wc(str, strlen(str))); int A[2][3] = { 1,2,3,4,5,6 }; int B[3][2] = { 1,2,3,4,5,6 }; int C[2][2]; multiply(&A[0][0], 2, 3, &B[0][0], 3, 2, &C[0][0], 2, 2); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { printf("%4d", C[i][j]); } printf("\n"); } return 0; }
int runCommand(){ int i = 0; int argc = splitString(textBuffer, ' '); for(i =0;i<argc;i++){argv[i]=stringArray[i];} if(k_strcmp(argv[0], "")==0){} else if(k_strcmp(argv[0], "clear")==0){ clearScreen(); typeOffset = 0;} else if(k_strcmp(argv[0], "history")==0){ printHistory();} else if(k_strcmp(argv[0], "pong")==0){ pong();} else if(k_strcmp(argv[0], "help")==0){ listCommands();} else if(k_strcmp(argv[0], "welcome")==0){ welcome();} else if(k_strcmp(argv[0], "splash")==0){ splash();} else if(k_strcmp(argv[0], "ls")==0){ ls(argc, argv); } else if(k_strcmp(argv[0], "cat")==0){ cat(argc, argv); } else if(k_strcmp(argv[0], "rm")==0){ rm(argc, argv); } else if(k_strcmp(argv[0], "chmod")==0){ chmod(argc, argv); } else if(k_strcmp(argv[0], "te")==0){ te(argc, argv); } else if(k_strcmp(argv[0], "cp")==0){ cp(argc, argv); } else if(k_strcmp(argv[0], "diff")==0){ diff(argc, argv); } else if(k_strcmp(argv[0], "wc")==0){ wc(argc, argv); } else if(k_strcmp(argv[0], "su")==0){ su(argc, argv); } else if(k_strcmp(argv[0], "chown")==0){ chown(argc, argv); } else if(k_strcmp(argv[0], "echo")==0){ echo(argc, argv); } else if(k_strcmp(argv[0], "adduser")==0){ adduser(argc, argv); } else if(k_strcmp(argv[0], "deluser")==0){ deluser(argc, argv); } else if(k_strcmp(argv[0], "listus")==0){ listus(); } else if(k_strcmp(argv[0], "passwd")==0){ passwd(argc, argv); } else if(k_strcmp(argv[0], "mkdir")==0){ mkdir(argc, argv); } else if(k_strcmp(argv[0], "rmdir")==0){ rmdir(argc, argv); } else if(k_strcmp(argv[0], "cd")==0){ cd(argc, argv); } else if(k_strcmp(argv[0], "pwd")==0){ pwd(argc, argv); } else if(k_strcmp(argv[0], "mv")==0){ mv(argc, argv); } // else check files else { printToConsole("Error: Unknown command '"); printToConsole(argv[0]); printToConsole("'\n"); } return 0; }
/*********************************************************************** * Method: MonteCarloAnalysis::updateImpl * Params: * Returns: void * Effects: ***********************************************************************/ void MonteCarloAnalysis::updateImpl() { const Forest* f = ((ForestAnalysis*)inputs[0])->getForest(); nodeCount = f->getGraph().size(); std::cout << currentTimeString() << " Forest has " << nodeCount << " nodes" << std::endl; vecN pf = ((AxesAnalysis*)inputs[1])->getPF(); WidthCalculator wco(f, pf); originalWidth = wco.getWidth(); DistributionAnalysis* dist = (DistributionAnalysis*)inputs[2]; widths.clear(); int nodeCount = f->getGraph().size(); for (int i = 0; i < mTreeCount; i++) { if (!(i % 20)) std::cout << i / 10; else if (!(i % 10)) std::cout << "."; auto angleGenerator = std::bind(&DistributionAnalysis::generateAngle, dist,std::placeholders::_1,std::placeholders::_2); int alteredNodeCount; Forest* ff = f->generateForest(angleGenerator, pf, alteredNodeCount); WidthCalculator wc(ff, pf); widths.push_back(wc.getWidth()); alteredFractions.push_back(((float)alteredNodeCount) / nodeCount); assert(f->compare(ff)); delete ff; } std::cout << std::endl; mean = { 0.f, 0.f, 0.f }; for (const auto width : widths) { mean = mean + width; } mean = mean / mTreeCount; SD = { 0.f, 0.f, 0.f }; for (const auto width : widths) { SD = SD + (width - mean)*(width - mean); } SD = SD / mTreeCount; // mTreeCount-1? SD = SD.sqrtWG(); discrepancy = (mean - originalWidth) / SD; }
void Dictionary::InnerCompressStrMultibyte(const std::string& uncompressed) { prdc_lzw::LzwNode<string>* current_node = root_string.get(); //初期位置 std::string w; //複数回の圧縮で共通数字を出力するため、元のテキストを保存しておく int char_size = 0; //読み込んだ文字のバイト数 unsigned int contents_size = max_dicsize + MultiByteCharList::list.size(); //数値→文字列変換のための配列のサイズ設定 contents.reserve(contents_size); for (std::string::const_iterator it = uncompressed.begin(); it != uncompressed.end(); it += char_size) { unsigned char pre_lead = *it; //未圧縮の文字列から一文字取り出す char_size = CharSize(pre_lead); string c = uncompressed.substr(distance(uncompressed.begin(), it), char_size); //未圧縮の文字列から一文字取り出す std::string wc(w + c); prdc_lzw::LzwNode<string>* q = current_node->FindChild(c); if (q != NULL) { //辞書に文字列が追加されていたら current_node = q; //探索ノードを一つ進める w = wc; } else { compressed.push_back(current_node->get_data()); if (size < max_dicsize) { AddNode(current_node, c); //current_nodeの下に文字cのノードを作成 contents.push_back(wc); } //NOTE:圧縮文字列に0以下、または256以上の文字コードが入っていた場合エラーになる current_node = get_root_string()->FindChild(c); //最初から検索し直す w = string(c); } } contents.shrink_to_fit(); compressed.push_back(current_node->get_data()); compressed.number_of_type = contents.size(); }
static void near lineout (void) //************************************************************************* // // Gibt die aktuelle Zeile fuer den Horizontal-Editor aus // und setzt den Hardwarecursor // //************************************************************************* { int i; setzcurs(e->curcol-e->xoffset+e->frame, e->readlines+e->frame, e); if (e->linbuf) { int zeile = e->y+e->readlines+e->frame; int block = (e->readindex>=e->blockbegin) && (e->readindex<e->blockend); int farbe = block ? color.edit_block : color.edit_text; int xpos = e->xoffset-e->x-e->frame; for (i = e->x+e->frame; i<e->xend; i++) wc(i, zeile, farbe, e->linbuf[xpos+i]); } }
int main (int argc, char *argv[]) { //printf("%s is the name of the file maybe", argv[1]); int i; for(i=1;i<argc;i++){ char* name = argv[i]; FILE* file = fopen(name,"r"); wc(file, name); fclose(file); } if(argc>2){ printf("%5d",totalL); printf("%5d",totalW); printf("%7d",totalB); printf("%10s\n","total"); } return 0; }
int main (int argc, char *argv[]) { char input_file1[MAX_FILE_NAME_LENGTH]; double th; FILE *fp; COUNT row_num1, col_num1, dim1; COUNT row_num2, col_num2, dim2; COUNT pf_i, pf_i2; int score; BIN_PF *score_pfs1, *score_pfs2; if (argc < 3) { fprintf(stderr, "Usage: score input_file1 score_threshold\n"); exit(0); } strcpy(input_file1, argv[1]); th = atof(argv[2]); wc(input_file1, &row_num1, &col_num1); if ((fp = fopen(input_file1, "r")) == NULL) { fprintf(stderr, "Fail to open file %s!\n", input_file1); return -1; } read_bin_pfs(fp, row_num1, col_num1, &score_pfs1); fclose (fp); dim1=col_num1-1; for (pf_i = 0; pf_i < row_num1; pf_i ++) { for (pf_i2 =pf_i+1 ; pf_i2<row_num1; pf_i2++) { score = custom_score( (score_pfs1 + pf_i)->pf, (score_pfs1 + pf_i2)->pf, dim1 ); if(isnan(score)) score = 0; if ((double)score >= th * (double)dim1) printf ("%s\t%s\t%f\n", (score_pfs1 + pf_i)->name, (score_pfs1 + pf_i2)->name, (double)score/(double)dim1); } } return 0; }
void DownloadAvatarTask::doTask() { try { if (strncmp(m_szUrl.c_str(),"http://", 7)==0) { HttpHandle wc(m_szUrl.c_str()); wc->getWeb(); if (wc->getDataSize() != 0) { if (UTIL::MISC::isValidImage((const unsigned char*)wc->getData()) == IMAGE_VOID) throw gcException(ERR_INVALIDDATA, gcString("The url [{0}] is not an image format", m_szUrl)); UTIL::FS::Path urlPath(m_szUrl, "", true); UTIL::FS::Path path(getUserCore()->getAppDataPath(), "", false); path += "users"; path += gcString("{0}", m_uiUserId); path += urlPath.getFile(); UTIL::FS::recMakeFolder(path); UTIL::FS::FileHandle fh(path, UTIL::FS::FILE_WRITE); fh.write(wc->getData(), wc->getDataSize()); fh.close(); getUserCore()->setAvatarUrl(path.getFullPath().c_str()); } else { throw gcException(ERR_BADRESPONSE); } } } catch (gcException &e) { onErrorEvent(e); } }
void MCF::dlMCFFromHttp( const char* url, const char* installDir ) { gcTrace( "Url: {0}", url ); if ( m_bStopped ) return; if ( !url ) throw gcException( ERR_BADURL ); //FIXME: Needs error checking on getweb HttpHandle wc( url ); wc->setDownloadRange( 0, MCFCore::MCFHeader::getSizeS() ); wc->setUserAgent( USERAGENT_UPDATE ); wc->getWeb(); if ( wc->getDataSize() != MCFCore::MCFHeader::getSizeS() ) throw gcException( ERR_BADHEADER ); MCFCore::MCFHeader webHeader( wc->getData() ); setHeader( &webHeader ); if ( !webHeader.isValid() ) throw gcException( ERR_BADHEADER ); unsigned int totalSize = webHeader.getXmlStart() + webHeader.getXmlSize(); wc->cleanUp(); wc->setUserAgent( USERAGENT_UPDATE ); wc->setDownloadRange( 0, totalSize ); wc->getWeb(); if ( wc->getDataSize() == 0 || wc->getDataSize() != totalSize ) throw gcException( ERR_WEBDL_FAILED, "Failed to download MCF xml from web (size is ether zero or didnt match header size)" ); UTIL::FS::FileHandle fh( installDir, UTIL::FS::FILE_WRITE ); fh.write( wc->getData(), wc->getDataSize() ); }
//Downloads update info from web void UMcfEx::getUpdateInfo(bool saveXml) { HttpHandle wc(PRIMUPDATE); wc->getWeb(); if (wc->getDataSize() == 0) { ::MessageBox(NULL, "Failed to get update data.\n\nDesura webserver might be down or you are not connected to the internet.", "Desura: ERROR", MB_OK); exit(-1); } XML::gcXMLDocument doc(wc->getData(), wc->getDataSize()); parseUpdateXml(doc); if (m_pFileList.size() == 0) { ::MessageBox(NULL, "Failed to get update files.\n\nEther Desura download server is down or the update xml feed is bad.", "Desura: ERROR", MB_OK); exit(-1); } if (saveXml) doc.SaveFile(UPDATEXML); }
void HGTController::doDownload() { //header should be saved all ready so appened to it m_hFile.open(m_szFile, UTIL::FS::FILE_APPEND); m_hFile.seek(0); HttpHandle wc(m_szUrl.c_str()); //wc->getProgressEvent() += delegate(this, &HGTController::onProgress); wc->getWriteEvent() += delegate(this, &HGTController::onWriteMemory); for (size_t x=0; x<m_vSuperBlockList.size(); x++) { m_pCurBlock = m_vSuperBlockList[x]; wc->cleanUp(); wc->setDownloadRange(m_pCurBlock->offset, m_pCurBlock->size); try { m_hFile.seek(m_pCurBlock->vBlockList[0]->fileOffset); wc->getWeb(); } catch (gcException &e) { onErrorEvent(e); nonBlockStop(); } } size_t fsSize = m_rvFileList.size(); for (size_t x=0; x<fsSize; x++) { if (!HasAllFlags(m_rvFileList[x]->getFlags(), MCFFileI::FLAG_CANUSEDIFF)) m_rvFileList[x]->addFlag(MCFFileI::FLAG_COMPLETE); } }
int main (int argc, char *argv[]) { int char_count = 0; int line_count = 0; int word_count = 0; if(argv[2]) { if(access(argv[2],F_OK) != -1) { wc(fopen(argv[2], "r"),"",""); } else { char_count = count_characters(argv[2]); line_count = count_lines(argv[2]); word_count = count_words(argv[2]); printf(" %d\t%d\t%d\t%s\n", line_count, char_count, word_count, argv[2]); } } else { printf("No argument passed"); } return 0; }
void UMcfEx::downloadMcf() { uint32 prog = 0; onProgressEvent(prog); if (m_szUrl == "") { ::MessageBox(NULL, "Invalid Download URL.", "Desura: Error", MB_OK); exit(-1); } if (m_szFile == L"") { ::MessageBox(NULL, "Invalid MCF file path.", "Desura: Error", MB_OK); exit(-1); } HttpHandle wc(m_szUrl.c_str()); wc->setOutFile(gcString(m_szFile).c_str()); wc->getProgressEvent() += delegate((UMcf*)this, &UMcf::updateAllCB); try { wc->getWebToFile(); } catch (gcException &e) { char msg[255]; _snprintf_s(msg, 255, _TRUNCATE, "Failed to download Desura Files. \n\n%s [%d.%d]", e.getErrMsg(), e.getErrId(), e.getSecErrId()); ::MessageBox(NULL, msg, "Desura: Error", MB_OK); exit(-1); } m_sHeader->setBuild(MCFBuild::BuildFromInt(m_iAppBuild)); m_sHeader->setId(m_iAppId); }
void GRIBTable::InitGribTable( int zone, ArrayOfGribRecordSets *rsa ) { //init fonts and colours wxFont dayfont = wxFont( 11, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD ); wxFont labelfont = wxFont( 10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD ); wxFont timefont = wxFont( 9, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD ); wxFont datafont = wxFont( 9, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL ); wxColour colour; GetGlobalColor(_T("DILG1"), &colour); //populate "cursor position" display wxString l; l.Append(toSDMM_PlugIn(1, m_pGDialog->m_cursor_lat)).Append(_T(" ")) .Append(toSDMM_PlugIn(2, m_pGDialog->m_cursor_lon)); m_pCursorPosition->SetLabel(l); m_pCursorPosition->SetFont(wxFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); m_pPositionText->SetFont(wxFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); //init row attr wxGridCellAttr *daysrow = new wxGridCellAttr(); daysrow->SetFont(dayfont); daysrow->SetBackgroundColour(colour); daysrow->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE); wxGridCellAttr *timerow = new wxGridCellAttr(); timerow->SetFont(timefont); timerow->SetBackgroundColour(colour); timerow->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE); wxGridCellAttr *singledatarow = new wxGridCellAttr(); singledatarow->SetFont(datafont); singledatarow->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE); wxGridCellAttr *doubledatarow = new wxGridCellAttr(); doubledatarow->SetFont(datafont); doubledatarow->SetAlignment(wxALIGN_CENTRE, -1); //init labels m_pGribTable->SetLabelFont(labelfont); m_pGribTable->SetLabelBackgroundColour(colour); //create as columns as necessary m_pGribTable->AppendCols(rsa->GetCount()); m_pGribTable->SetSelectionBackground(colour); m_pGribTable->SetSelectionForeground(m_pGribTable->GetDefaultCellTextColour()); //init days row m_pGribTable->SetRowLabelValue(0, wxEmptyString); m_pGribTable->SetRowAttr(0, daysrow); //init time row m_pGribTable->SetRowLabelValue(1, wxEmptyString); m_pGribTable->SetRowAttr(1, timerow); //populate grib wxDateTime day(rsa->Item(0).m_Reference_Time); wxDateTime time; int ncols = -1,nrows,dcol = 0; for(unsigned i = 0; i < rsa->GetCount(); i++ ) { time = rsa->Item(i).m_Reference_Time; //populate 'time' row m_pGribTable->SetCellValue(GetTimeRowsStrings( rsa->Item(i).m_Reference_Time, zone , 0), 1, i ); nrows = 2; m_pTimeset = m_pGDialog->GetTimeLineRecordSet(time); GribRecord **RecordArray = m_pTimeset->m_GribRecordPtrArray; //create and polulate wind data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_WIND_VX) != wxNOT_FOUND && m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_WIND_VY) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Wind"), doubledatarow ); wxString wc(GetWind(RecordArray)); //wind is a special case: if current unit is not bf ==> double speed display (current unit + bf) if(m_pGDialog->m_OverlaySettings.Settings[GribOverlaySettings::WIND].m_Units != GribOverlaySettings::BFS) if(!wc.IsEmpty()) wc.Append(_T("\n")).Append(GetWindBf(RecordArray)); // m_pGribTable->SetCellValue(nrows, i, wc); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate Pressure data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_PRESSURE) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Pressure"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetPressure(RecordArray)); nrows++; } //create and polulate Wind gusts data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_WIND_GUST) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Wind Gust"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetWindGust(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate Waves data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_HTSIGW) != wxNOT_FOUND || m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_WVDIR) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Waves"), doubledatarow ); m_pGribTable->SetCellValue(nrows, i, GetWaves(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate total rainfall data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_PRECIP_TOT) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Rainfall"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetRainfall(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate total cloud control if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_CLOUD_TOT) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Cloud"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetCloudCover(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate the Air Temperature data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_AIR_TEMP) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Air\nTemperature"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetAirTemp(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate the Sea Surface Temperature data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_SEA_TEMP) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Sea\nTemperature"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetSeaTemp(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate the Convective Available Potential Energy (CAPE) data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_CAPE) != wxNOT_FOUND) { AddDataRow( nrows, i, _("CAPE"), singledatarow ); m_pGribTable->SetCellValue(nrows, i, GetCAPE(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } //create and polulate the current data row if(m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_SEACURRENT_VX) != wxNOT_FOUND && m_pGDialog->m_bGRIBActiveFile->m_GribIdxArray.Index(Idx_SEACURRENT_VY) != wxNOT_FOUND) { AddDataRow( nrows, i, _("Current"), doubledatarow ); m_pGribTable->SetCellValue(nrows, i, GetCurrent(RecordArray)); m_pGribTable->SetCellBackgroundColour(nrows, i, m_pDataCellsColour); nrows++; } m_pGribTable->AutoSizeColumn(i, false); ncols++; //write 'days' row if(time.GetDateOnly() != day.GetDateOnly() || i == rsa->GetCount()- 1){ if( i == 0 ) continue; //not the first item if(i == rsa->GetCount() - 1 && ncols != 1) ncols++; ////if end of time range don't forgett the last col m_pGribTable->SetCellSize(0, dcol, 1, ncols); m_pGribTable->SetCellValue(0, dcol, GetTimeRowsStrings(day.GetDateOnly() , zone, 1)); day = rsa->Item(i).m_Reference_Time; dcol = i; if( ncols == 1){ //if only one item per day m_pGribTable->AutoSizeColumn(i-1, false); if(i == rsa->GetCount() - 1 ) { //if end of time range m_pGribTable->SetCellValue(0, i, GetTimeRowsStrings(day.GetDateOnly() , zone, 1)); m_pGribTable->AutoSizeColumn(i, false); } } ncols = 0; } } AutoSizeDataRows(); m_pGribTable->SetGridCursor( m_pGribTable->GetNumberRows(), 0); //put cursor outside the grid this->Fit(); this->Refresh(); }
void RegularizedHingeIntegration::getWeightsDeriv(int numSections, double L, double dLdh, double *dwtsdh) { double oneOverL = 1.0/L; const int Nc = 4; int Nf = numSections - Nc; double dxcdh[Nc]; double dwcdh[Nc]; double dxfdh[100]; for (int i = 0; i < numSections; i++) { dwtsdh[i] = 0.0; dxfdh[i] = 0.0; } for (int i = 0; i < Nc; i++) { dwcdh[i] = 0.0; dxcdh[i] = 0.0; } if (parameterID == 1 || parameterID == 3) { // lpI dwcdh[0] = oneOverL; dwcdh[1] = -oneOverL; } if (parameterID == 2 || parameterID == 3) { // lpJ dwcdh[2] = -oneOverL; dwcdh[3] = oneOverL; } if (parameterID == 4 || parameterID == 6) // epsI dxcdh[1] = oneOverL; if (parameterID == 5 || parameterID == 6) // epsJ dxcdh[2] = -oneOverL; dwtsdh[0] = dwcdh[0]; dwtsdh[1] = dwcdh[1]; dwtsdh[2] = dwcdh[2]; dwtsdh[3] = dwcdh[3]; if (Nf > 0) { double wt[100]; this->getSectionWeights(numSections, L, wt); double pt[100]; this->getSectionLocations(numSections, L, pt); Vector wc(wt, Nc); Vector xc(pt, Nc); Vector xf(&pt[Nc], Nf); Vector R(Nf); double sum = 0.0; for (int j = 0; j < Nc; j++) sum += dwcdh[j]; R(0) = -sum; for (int i = 1; i < Nf; i++) { sum = 0.0; for (int j = 0; j < Nf; j++) sum += i*pow(xf(j),i-1)*dxfdh[j]*wt[Nc+j]; for (int j = 0; j < Nc; j++) sum += i*pow(xc(j),i-1)*dxcdh[j]*wc[j]; for (int j = 0; j < Nc; j++) sum += pow(xc(j),i)*dwcdh[j]; R(i) = -sum; } Matrix J(Nf,Nf); for (int i = 0; i < Nf; i++) for (int j = 0; j < Nf; j++) J(i,j) = pow(xf(j),i); Vector dwfdh(Nf); J.Solve(R,dwfdh); for (int i = 0; i < Nf; i++) dwtsdh[i+Nc] = dwfdh(i); } if (dLdh != 0.0) { // STILL TO DO opserr << "getWeightsDeriv -- to do" << endln; } return; }
void MCF::getDownloadProviders(const char* url, MCFCore::Misc::UserCookies *pCookies, bool *unauthed, bool local) { if (!pCookies) throw gcException(ERR_INVALID, "Cookies are null (getDownloadProviders)"); HttpHandle wc(url); pCookies->set(wc); DesuraId id = m_sHeader->getDesuraId(); gcString type = id.getTypeString(); wc->addPostText("siteareaid", id.getItem()); wc->addPostText("sitearea", type.c_str()); wc->addPostText("branch", m_sHeader->getBranch()); MCFBuild build = m_sHeader->getBuild(); if (build != 0) wc->addPostText("build", build); if (local) wc->addPostText("local", "yes"); wc->postWeb(); if (wc->getDataSize() == 0) throw gcException(ERR_BADRESPONSE); TiXmlDocument doc; doc.SetCondenseWhiteSpace(false); XML::loadBuffer(doc, const_cast<char*>(wc->getData()), wc->getDataSize()); TiXmlNode *uNode = doc.FirstChild("itemdownloadurl"); if (!uNode) throw gcException(ERR_BADXML); TiXmlNode* sNode = uNode->FirstChild("status"); if (!sNode) throw gcException(ERR_BADXML); uint32 status = 0; TiXmlElement* sEl = sNode->ToElement(); if (sEl) { const char* statStr = sEl->Attribute("code"); if (statStr) status = atoi(statStr); else throw gcException(ERR_BADXML); } else { throw gcException(ERR_BADXML); } if (status != 0) throw gcException(ERR_BADSTATUS, status, gcString("Status: {0}", sEl->GetText())); TiXmlNode* iNode = uNode->FirstChild("item"); if (!iNode) { throw gcException(ERR_BADXML); } TiXmlNode* mNode = iNode->FirstChild("mcf"); if (!mNode) { throw gcException(ERR_BADXML); } TiXmlElement *melNode = mNode->ToElement(); if (melNode) { const char* build = melNode->Attribute("build"); const char* branch = melNode->Attribute("branch"); //Debug(gcString("MCF: R: {0}.{1} G: {2}.{3}\n", m_sHeader->getBranch(), m_sHeader->getBuild(), build, branch)); if (build) m_sHeader->setBuild(MCFBuild::BuildFromInt(atoi(build))); if (branch) m_sHeader->setBranch(MCFBranch::BranchFromInt(atoi(branch))); } safe_delete(m_pFileAuth); char *szAuthCode = NULL; XML::GetChild("authhash", szAuthCode, mNode); if (!szAuthCode) throw gcException(ERR_BADXML); m_pFileAuth = new Misc::GetFile_s; memset(m_pFileAuth, 0, sizeof(Misc::GetFile_s)); Safe::strncpy(m_pFileAuth->authhash, 33, szAuthCode, 33); char buff[10]; Safe::snprintf(buff, 10, "%d", pCookies->getUserId()); size_t size = Safe::strlen(buff, 10); memcpy(m_pFileAuth->authkey, buff, size); safe_delete(szAuthCode); TiXmlNode* urlNode = mNode->FirstChild("urls"); if (!urlNode) throw gcException(ERR_BADXML); char * szAuthed = NULL; XML::GetChild("authed", szAuthed, mNode); if (unauthed && szAuthed) { *unauthed = (atoi(szAuthed) == 0); } safe_delete(szAuthed); #ifdef DEBUG #if 0 m_vProviderList.clear(); m_vProviderList.push_back(new MCFCore::Misc::DownloadProvider("localhost", "mcf://10.0.0.121:62001", "", "")); return; #endif #endif TiXmlElement* pChild = urlNode->FirstChildElement("url"); while (pChild) { MCFCore::Misc::DownloadProvider* temp = new MCFCore::Misc::DownloadProvider(pChild); m_vProviderList.push_back(temp); pChild = pChild->NextSiblingElement(); } if (m_vProviderList.size() == 0) throw gcException(ERR_ZEROSIZE); }
int main (int argc, char *argv[]) { char input_file1[MAX_FILE_NAME_LENGTH]; char input_file2[MAX_FILE_NAME_LENGTH]; COUNT i,len,th; FILE *fp; COUNT row_num1, col_num1, dim1; COUNT row_num2, col_num2, dim2; COUNT pf_i, pf_i2; NUM pcc,tmp_pcc; NUM_PF *pcc_pfs1, *pcc_pfs2; IJ2F *pccs; NUM pre_cut; COUNT min; if (argc < 3) { fprintf(stderr, "Usage: pcc input_file1 input_file2 pcc_threshold\n"); exit(0); } strcpy(input_file1, argv[1]); strcpy(input_file2, argv[2]); th = atoi(argv[3]); wc(input_file1, &row_num1, &col_num1); if ((fp = fopen(input_file1, "r")) == NULL) { fprintf(stderr, "Fail to open file %s!\n", input_file1); return -1; } read_num_pfs(fp, row_num1, col_num1, &pcc_pfs1); fclose (fp); dim1=col_num1-1; wc(input_file2, &row_num2, &col_num2); if ((fp = fopen(input_file2, "r")) == NULL) { fprintf(stderr, "Fail to open file %s!\n", input_file2); return -1; } read_num_pfs(fp, row_num2, col_num2, &pcc_pfs2); fclose (fp); dim2=col_num2-1; if(dim1 != dim2){ fprintf(stderr,"Unequal dim!\n"); return -1; } for (pf_i=0; pf_i<row_num1; pf_i++) Z_transform (&(pcc_pfs1 + pf_i)->pf, dim1); for (pf_i=0; pf_i<row_num2; pf_i++) Z_transform (&(pcc_pfs2 + pf_i)->pf, dim2); // printf("memory allocated\n"); pccs = (IJ2F *) malloc( row_num2 * sizeof(IJ2F) ); for (pf_i = 0; pf_i < row_num1; pf_i ++) { len=0; for (pf_i2 =0 ; pf_i2 < row_num2; pf_i2++) { if (pf_i == pf_i2) continue; pcc = inner_prod( (pcc_pfs1 + pf_i)->pf, (pcc_pfs2 + pf_i2)->pf, dim1 ) / (dim1-1); if(isnan(pcc)) pcc = 0; if(pcc>pre_cut){ pccs[len].i=pf_i; pccs[len].j=pf_i2; pccs[len].f=pcc; len++; } } sort_ij2f_d(&pccs, len); for(i=0; i<th; i++){ printf("%s\t%s\t%.3f\n", (pcc_pfs1+pccs[i].i)->name, (pcc_pfs2+pccs[i].j)->name, pccs[i].f); } } return 0; }
static void Diagonalizer_and_CrossCorrelationTable_qdiag (Diagonalizer me, CrossCorrelationTables thee, double *cweights, long maxNumberOfIterations, double delta) { try { CrossCorrelationTable c0 = (CrossCorrelationTable) thy item[1]; double **w = my data; long dimension = c0 -> numberOfColumns; autoEigen eigen = Thing_new (Eigen); autoCrossCorrelationTables ccts = Data_copy (thee); autoNUMmatrix<double> pinv (1, dimension, 1, dimension); autoNUMmatrix<double> d (1, dimension, 1, dimension); autoNUMmatrix<double> p (1, dimension, 1, dimension); autoNUMmatrix<double> m1 (1, dimension, 1, dimension); autoNUMmatrix<double> wc (1, dimension, 1, dimension); autoNUMvector<double> wvec (1, dimension); autoNUMvector<double> wnew (1, dimension); autoNUMvector<double> mvec (1, dimension); for (long i = 1; i <= dimension; i++) // Transpose W for (long j = 1; j <= dimension; j++) { wc[i][j] = w[j][i]; } // d = diag(diag(W'*C0*W)); // W = W*d^(-1/2); NUMdmatrix_normalizeColumnVectors (wc.peek(), dimension, dimension, c0 -> data); // scale eigenvectors for sphering // [vb,db] = eig(C0); // P = db^(-1/2)*vb'; Eigen_initFromSymmetricMatrix (eigen.peek(), c0 -> data, dimension); for (long i = 1; i <= dimension; i++) { if (eigen -> eigenvalues[i] < 0) { Melder_throw (U"Covariance matrix not positive definite, eigenvalue[", i, U"] is negative."); } double scalef = 1 / sqrt (eigen -> eigenvalues[i]); for (long j = 1; j <= dimension; j++) { p[dimension - i + 1][j] = scalef * eigen -> eigenvectors[i][j]; } } // P*C[i]*P' for (long ic = 1; ic <= thy size; ic++) { CrossCorrelationTable cov1 = (CrossCorrelationTable) thy item[ic]; CrossCorrelationTable cov2 = (CrossCorrelationTable) ccts -> item[ic]; NUMdmatrices_multiply_VCVp (cov2 -> data, p.peek(), dimension, dimension, cov1 -> data, 1); } // W = P'\W == inv(P') * W NUMpseudoInverse (p.peek(), dimension, dimension, pinv.peek(), 0); NUMdmatrices_multiply_VpC (w, pinv.peek(), dimension, dimension, wc.peek(), dimension); // initialisation for order KN^3 for (long ic = 2; ic <= thy size; ic++) { CrossCorrelationTable cov = (CrossCorrelationTable) ccts -> item[ic]; // C * W NUMdmatrices_multiply_VC (m1.peek(), cov -> data, dimension, dimension, w, dimension); // D += scalef * M1*M1' NUMdmatrices_multiplyScaleAdd (d.peek(), m1.peek(), dimension, dimension, 2 * cweights[ic]); } long iter = 0; double delta_w; autoMelderProgress progress (U"Simultaneous diagonalization of many CrossCorrelationTables..."); try { do { // the standard diagonality measure is rather expensive to calculate so we compare the norms of // differences of eigenvectors. delta_w = 0; for (long kol = 1; kol <= dimension; kol++) { for (long i = 1; i <= dimension; i++) { wvec[i] = w[i][kol]; } update_one_column (ccts.peek(), d.peek(), cweights, wvec.peek(), -1, mvec.peek()); Eigen_initFromSymmetricMatrix (eigen.peek(), d.peek(), dimension); // Eigenvalues already sorted; get eigenvector of smallest ! for (long i = 1; i <= dimension; i++) { wnew[i] = eigen -> eigenvectors[dimension][i]; } update_one_column (ccts.peek(), d.peek(), cweights, wnew.peek(), 1, mvec.peek()); for (long i = 1; i <= dimension; i++) { w[i][kol] = wnew[i]; } // compare norms of eigenvectors. We have to compare ||wvec +/- w_new|| because eigenvectors // may change sign. double normp = 0, normm = 0; for (long j = 1; j <= dimension; j++) { double dm = wvec[j] - wnew[j], dp = wvec[j] + wnew[j]; normp += dm * dm; normm += dp * dp; } normp = normp < normm ? normp : normm; normp = sqrt (normp); delta_w = normp > delta_w ? normp : delta_w; } iter++; Melder_progress ((double) iter / (double) (maxNumberOfIterations + 1), U"Iteration: ", iter, U", norm: ", delta_w); } while (delta_w > delta && iter < maxNumberOfIterations); } catch (MelderError) { Melder_clearError (); } // Revert the sphering W = P'*W; // Take transpose to make W*C[i]W' diagonal instead of W'*C[i]*W => (P'*W)'=W'*P NUMmatrix_copyElements (w, wc.peek(), 1, dimension, 1, dimension); NUMdmatrices_multiply_VpC (w, wc.peek(), dimension, dimension, p.peek(), dimension); // W = W'*P: final result // Calculate the "real" diagonality measure // double dm = CrossCorrelationTables_and_Diagonalizer_getDiagonalityMeasure (thee, me, cweights, 1, thy size); } catch (MelderError) { Melder_throw (me, U" & ", thee, U": no joint diagonalization (qdiag)."); } }
void MCF::dlHeaderFromHttp(const char* url) { if (m_bStopped) return; if (!url) throw gcException(ERR_BADURL); //FIXME: Needs error checking on getweb HttpHandle wc(url); wc->setDownloadRange(0, MCFCore::MCFHeader::getSizeS()); wc->getWeb(); if (wc->getDataSize() != MCFCore::MCFHeader::getSizeS()) throw gcException(ERR_BADHEADER); MCFCore::MCFHeader webHeader((uint8*)wc->getData()); setHeader(&webHeader); if (!webHeader.isValid()) throw gcException(ERR_BADHEADER); wc->cleanUp(); wc->setDownloadRange(webHeader.getXmlStart(), webHeader.getXmlSize()); wc->getWeb(); if (wc->getDataSize() == 0 || wc->getDataSize() != webHeader.getXmlSize()) throw gcException(ERR_WEBDL_FAILED, "Failed to download MCF xml from web (size is ether zero or didnt match header size)"); uint32 bz2BuffLen = webHeader.getXmlSize()*25; char* bz2Buff = NULL; if ( isCompressed() ) { bz2Buff = new char[bz2BuffLen]; UTIL::STRING::zeroBuffer(bz2Buff, bz2BuffLen); try { UTIL::BZIP::BZ2DBuff((char*)bz2Buff, &bz2BuffLen, const_cast<char*>(wc->getData()), wc->getDataSize()); parseXml(bz2Buff, bz2BuffLen); safe_delete(bz2Buff); } catch (gcException &) { safe_delete(bz2Buff); throw; } } else { parseXml(const_cast<char*>(wc->getData()), wc->getDataSize()); } //we remove the complete flag due to the files not existing in the MCF for (size_t x=0; x< m_pFileList.size(); x++) { m_pFileList[x]->delFlag(MCFCore::MCFFileI::FLAG_COMPLETE); } }
double //wire cap with triple spacing Router::Cw3(double length) { Wire wc(g_ip->wt, length, 1, 3, 3); return (wc.wire_cap(length)); }
int main(int argc, char **argv) { char **argp, *p, showtotal; int returnval, f; noflags=1; for(argp=argv+1;*argp&&**argp=='-';argp++) for(p=*argp+1;*p;p++) switch(*p) { case 'c': cflag=1; noflags=0; break; case 'l': lflag=1; noflags=0; break; case 'w': wflag=1; noflags=0; break; default: usage(); return -1; } if(argp-argv==argc) { returnval=wc(0); putchar('\n'); return returnval; } if(argc-(argp-argv)>1) showtotal=1; else showtotal=0; totalc=0; totall=0; totalw=0; for(returnval=0;*argp;argp++) if((f=open(*argp,O_RDONLY))==-1) if(errno==ENOENT) { writestr(2,"wc: "); writestr(2,*argp); writestr(2,": not found\n"); returnval=1; } else { writestr(2,"wc: "); writestr(2,*argp); writestr(2,": can't open\n"); returnval=1; } else { if(wc(f)) returnval=1; writestr(1,*argp); writestr(1,"\n"); close(f); } if(showtotal) { if(lflag||noflags) printf("%u ",totall); if(wflag||noflags) printf("%u ",totalw); if(cflag||noflags) printf("%u ",totalc); fflush(stdout); /* You can never trust that sneaky bastard */ writestr(1,"total\n"); } return returnval; }
//this is a feature of webcore but we need it here in case we need to shutdown during a download void DownloadUpdateTask::downloadUpdate() { #ifdef DEBUG return; #endif uint32 appver = m_uiAppVer; uint32 appbuild = m_uiAppBuild; HttpHandle wc(PRIMUPDATE); getWebCore()->setWCCookies(wc); wc->addPostText("appid", appver); wc->postWeb(); if (wc->getDataSize() == 0) throw gcException(ERR_INVALIDDATA); XML::gcXMLDocument doc(const_cast<char*>(wc->getData()), wc->getDataSize()); doc.ProcessStatus("appupdate"); auto mNode = doc.GetRoot("appupdate").FirstChildElement("mcf"); if (!mNode.IsValid()) throw gcException(ERR_BADXML); uint32 version = 0; uint32 build = 0; mNode.GetAtt("appid", version); mNode.GetAtt("build", build); if (version == 0 || build == 0) throw gcException(ERR_BADXML); //check to see if its newer than last if (appbuild != 0 && build <= appbuild && appver == version) return; gcString url = mNode.GetChild("url"); if (url.size() == 0) throw gcException(ERR_BADXML); #ifdef WIN32 const char *comAppPath = getUserCore()->getAppDataPath(); m_szPath = gcString("{0}{1}{2}", comAppPath, DIRS_STR, UPDATEFILE); #else m_szPath = gcString("{0}", UPDATEFILE); #endif m_hMcfHandle->setFile(m_szPath.c_str()); m_hMcfHandle->setWorkerCount(1); try { m_hMcfHandle->dlHeaderFromHttp(url.c_str()); #ifdef WIN32 const char* dir = ".\\"; #else const char* dir = "./"; #endif //Dont use courgette for non admins for now bool useCourgette = false; #ifdef WIN32 if (getUserCore()->isAdmin()) useCourgette = true; #endif bool res = m_hMcfHandle->verifyInstall(dir, true, useCourgette); m_hMcfHandle->getProgEvent() += delegate(this, &DownloadUpdateTask::onDownloadProgress); UserCore::Misc::update_s info; info.build = build; if (!res) { Msg(gcString("Downloading " PRODUCT_NAME " update: Ver {0} build {1}\n", appver, build)); info.alert = true; onDownloadStartEvent(info); if (useCourgette) m_hMcfHandle->dlFilesFromHttp(url.c_str(), dir); else m_hMcfHandle->dlFilesFromHttp(url.c_str()); if (!isStopped()) onDownloadCompleteEvent(info); } else { //sometimes this gets called after shutdown and causes major problems if (!getUserCore() || !getUserCore()->getServiceMain()) return; gcString av("{0}", appver); gcString ab("{0}", build); info.alert = false; try { getUserCore()->getServiceMain()->updateRegKey(APPID, av.c_str()); getUserCore()->getServiceMain()->updateRegKey(APPBUILD, ab.c_str()); } catch (gcException &e) { Warning(gcString("Failed to update reg key: {0}\n", e)); } onDownloadCompleteEvent(info); } } catch (gcException &e) { Warning(gcString("Download update failed: {0}\n", e)); } }
int main (int argc, char *argv[]) { char input_file1[MAX_FILE_NAME_LENGTH]; COUNT i,len,th; FILE *fp; COUNT row_num1, col_num1, dim1; COUNT pf_i, pf_i2; NUM pcc,tmp_pcc,pre_cut; NUM_PF *pcc_pfs1; IJ2F *pccs; NUM perc; COUNT min; if (argc < 3) { fprintf(stderr, "Usage: pcc input_file1 input_file2 pcc_threshold\n"); exit(0); } strcpy(input_file1, argv[1]); perc = atof(argv[2]); pre_cut = atof(argv[3]); wc(input_file1, &row_num1, &col_num1); th = perc * (NUM)row_num1 * (NUM)(row_num1-1) / 2; if ((fp = fopen(input_file1, "r")) == NULL) { fprintf(stderr, "Fail to open file %s!\n", input_file1); return -1; } read_num_pfs(fp, row_num1, col_num1, &pcc_pfs1); fclose (fp); dim1=col_num1-1; for (pf_i=0; pf_i<row_num1; pf_i++) Z_transform (&(pcc_pfs1 + pf_i)->pf, dim1); pccs = (IJ2F *) malloc( INT_MAX * sizeof(IJ2F) ); // printf("memory allocated\n"); len=0; for (pf_i = 0; pf_i < row_num1; pf_i ++) { for (pf_i2 = pf_i+1 ; pf_i2 < row_num1; pf_i2++) { pcc = inner_prod( (pcc_pfs1 + pf_i)->pf, (pcc_pfs1 + pf_i2)->pf, dim1 ) / (dim1-1); // printf("%s\t%s\t%.3f\n",(pcc_pfs1+pf_i)->name,(pcc_pfs1+pf_i2)->name,pcc); if(pcc<pre_cut || isnan(pcc)){ continue; } pccs[len].i=pf_i; pccs[len].j=pf_i2; pccs[len].f=pcc; len++; } } sort_ij2f_d(&pccs, len); if(th>len){ fprintf(stderr,"pre_cut is too high\n"); fprintf(stderr,"number of pairs with value more than pre_cut: %d\n",len); fprintf(stderr,"number of pairs within top %f: %d\n",perc, th); } min=MIN(th,len); for(i=0; i<min; i++){ printf("%s\t%s\t%.3f\n", (pcc_pfs1+pccs[i].i)->name, (pcc_pfs1+pccs[i].j)->name, pccs[i].f); } return 0; }
Real Q2PBorehole::jac(unsigned int jvar) { if (_i != _j) return 0.0; const Real character = _character.value(_t, _q_point[_qp]); if (character == 0.0) return 0.0; const Real bh_pressure = _p_bot + _unit_weight * (_q_point[_qp] - _bottom_point); // really want to use _q_point instaed of _current_point, i think?! const Real phi = 1; // Get the ID we initially assigned to this point const unsigned current_dirac_ptid = currentPointCachedID(); // If getting the ID failed, fall back to the old bodge! // if (current_dirac_ptid == libMesh::invalid_uint) // current_dirac_ptid = (_zs.size() > 2) ? 1 : 0; Real outflowp(0.0); const bool deriv_wrt_pp = (_var_is_pp && (jvar == _var.number())) || (!_var_is_pp && (jvar == _other_var_num)); Real wc(0.0); if (current_dirac_ptid > 0) // contribution from half-segment "behind" this point { wc = wellConstant(_permeability[0], _rot_matrix[current_dirac_ptid - 1], _half_seg_len[current_dirac_ptid - 1], _current_elem, _rs[current_dirac_ptid]); if ((character < 0.0 && _pp[_i] < bh_pressure) || (character > 0.0 && _pp[_i] > bh_pressure)) { // injection, so outflow<0 || // production, so outflow>0 if (deriv_wrt_pp) outflowp += std::abs(character) * wc * (_mobility[_i] * phi + _dmobility_dp[_i] * phi * (_pp[_i] - bh_pressure)); else outflowp += std::abs(character) * wc * _dmobility_ds[_i] * phi * (_pp[_i] - bh_pressure); } } if (current_dirac_ptid < _zs.size() - 1 || _zs.size() == 1) // contribution from half-segment "ahead of" this point { wc = wellConstant(_permeability[0], _rot_matrix[current_dirac_ptid], _half_seg_len[current_dirac_ptid], _current_elem, _rs[current_dirac_ptid]); if ((character < 0.0 && _pp[_i] < bh_pressure) || (character > 0.0 && _pp[_i] > bh_pressure)) { // injection, so outflow<0 || // production, so outflow>0 if (deriv_wrt_pp) outflowp += std::abs(character) * wc * (_mobility[_i] * phi + _dmobility_dp[_i] * phi * (_pp[_i] - bh_pressure)); else outflowp += std::abs(character) * wc * _dmobility_ds[_i] * phi * (_pp[_i] - bh_pressure); } } return _test[_i][_qp] * outflowp; }
void ReadAnimalsData(lhVec& landHerbs, whVec& waterHerbs, lcVec& landCarns, wcVec& waterCarns, waterVec& wv){ ifstream myfile("EcosystemFile.txt"); int waterLines = ReadWaterAreas(); int grassLines = ReadGrassAreas(); int algaeLines = ReadAlgaeAreas(); int animalsLines = ReadAnimalsNumber(); string line; vector <int> values(7); char gender; if (myfile.is_open()){ for (int i = 0; i < waterLines + grassLines + algaeLines + animalsLines + 6; i++){ getline(myfile, line); if (i > waterLines + grassLines + algaeLines + 5){ int found = line.find('|'); string typeFeeding(line.begin()+ found +1, line.begin()+ found + 1 + 9); line.erase(found, 10); gender = line[found + 1]; line.erase(found, 2); for (int k = 0; k < line.size(); k++){ if (line[k] == ',' || line[k]== '|') line[k] = ' '; } istringstream iss(line); for (int j = 0; j < 7; j++){ int val; iss >> val; values[j] = val; } if (typeFeeding == "herbivore"){ bool inWater = false; shared_ptr<Herbivore> h (new Herbivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6])); for(int m = 0; m < wv.size(); m++){ if (wv[m]->HasThisCoordinate(*h)){ inWater = true; break; } } if (inWater){ shared_ptr<WaterHerbivore> wh (new WaterHerbivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6])); waterHerbs.push_back(wh); } else { shared_ptr<LandHerbivore> lh (new LandHerbivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6])); landHerbs.push_back(lh); } } else if(typeFeeding == "carnivore"){ bool inWater = false; shared_ptr<Carnivore> c (new Carnivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6])); for(int m = 0; m < wv.size(); m++){ if (wv[m]->HasThisCoordinate(*c)){ inWater = true; break; } } if (inWater){ shared_ptr<WaterCarnivore> wc (new WaterCarnivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6])); waterCarns.push_back(wc); }else{ shared_ptr<LandCarnivore> lc (new LandCarnivore(values[0], values[1], gender, values[2], values[3], values[4], values[5], values[6])); landCarns.push_back(lc); } } } } }
void OnInitDialog() { btnOK->Enable(false); { CWaitCursor wc(this); // free the internal token list first, just in case we are being displayed twice FreeTokenInfo(); FetchTokenInfo(); InitListView(); } bInitialized = TRUE; // TODO: Implement me /* ARROWCURSOR; CWindow win; int heightChange; RECT oldRect = {0}, newRect = {0}; NONCLIENTMETRICS ncm; memset(&ncm, 0, sizeof(ncm)); ncm.cbSize = sizeof(ncm); SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, &ncm, 0); HDC hDC = this->GetDC(); HANDLE hFont = ::CreateFontIndirect(&ncm.lfMessageFont); ::SelectObject(hDC, hFont); if (hFont) ::DeleteObject(hFont); // get the current size of the explanation control win.Attach(GetDlgItem(IDC_EXPLANATION)); win.GetWindowRect(&oldRect); // sometimes the width is calculated wrong, so we don't resize width int rightSide = oldRect.right; // calculate the height of the new text and find the delta heightChange = oldRect.bottom; ::DrawText(hDC, m_reason, m_reason.size(), &oldRect, DT_CALCRECT | DT_LEFT | DT_WORDBREAK); // | DT_NOPREFIX heightChange = oldRect.bottom - heightChange; this->ReleaseDC(hDC); // resize the explanation control using the new height and // change the text of the explanation control oldRect.right = rightSide; this->ScreenToClient(&oldRect); win.MoveWindow(&oldRect, TRUE); win.SetWindowText(myExplanation); win.Detach(); // resize the main dialog window this->GetWindowRect(&oldRect); oldRect.bottom += heightChange; this->MoveWindow(&oldRect, TRUE); // move the token list win.Attach(GetDlgItem(IDC_TOKEN_LIST)); win.GetWindowRect(&oldRect); this->ScreenToClient(&oldRect); oldRect.top += heightChange; oldRect.bottom += heightChange; win.MoveWindow(&oldRect, TRUE); win.Detach(); // move the refresh button win.Attach(GetDlgItem(IDREFRESH)); win.GetWindowRect(&oldRect); this->ScreenToClient(&oldRect); oldRect.top += heightChange; oldRect.bottom += heightChange; win.MoveWindow(&oldRect, TRUE); win.Detach(); // move the ok button win.Attach(GetDlgItem(wxID_OK)); win.GetWindowRect(&oldRect); this->ScreenToClient(&oldRect); oldRect.top += heightChange; oldRect.bottom += heightChange; win.MoveWindow(&oldRect, TRUE); win.Detach(); // move the cancel button win.Attach(GetDlgItem(wxID_CANCEL)); win.GetWindowRect(&oldRect); this->ScreenToClient(&oldRect); oldRect.top += heightChange; oldRect.bottom += heightChange; win.MoveWindow(&oldRect, TRUE); win.Detach(); */ // TODO: Implement change detection here //m_tokenChange = new TokenChangeDetector(hDlg); //m_tokenChangeCookie = gMonitor->RegisterChangeConsumer(m_tokenChange); //gConsumerCookieList.add(m_tokenChangeCookie); //SetTimer(hDlg, 1, 500, NULL); }