text
stringlengths
8
6.88M
// // main.cpp // TEST // // Created by ruby on 2017. 10. 13.. // Copyright © 2017년 ruby. All rights reserved. // #include <iostream> #include <fstream> #include "ToppingList.hpp" #include "DoughList.hpp" #include "EdgeList.hpp" #include "Topping.hpp" #include "Dough.hpp" #include "Edge.hpp" using namespace std; bool readInput(string inputName, ToppingList * toppingList, DoughList * doughList, EdgeList * edgeList); int main(int argc, const char * argv[]) { ToppingList toppingList; DoughList doughList; EdgeList edgeList; string inputName = argv[1]; if(!readInput(inputName, &toppingList, &doughList, &edgeList)) return -1; while (true) { // 메인 메뉴 출력 cout << "==============" << endl << "0: 모든 메뉴 보기" << endl << "1: 주문하기" << endl << "2: 메뉴 추가" << endl << "3: 메뉴 삭제" << endl << "4: 메뉴 검색" << endl << "5: 인기메뉴 추천" << endl << "6: 프로그램 종료" << endl << "==============" << endl << ">> "; int inputNum; cin >> inputNum; if (inputNum == 6) { // 프로그램을 종료하기 전 동적 할당받은 메모리 반환하기 위해 모든 메뉴를 삭제 // Topping * tempT = toppingList.get_head(); // Dough * tempD = doughList.get_head(); // Edge * tempE = edgeList.get_head(); for (int i = 0; i < toppingList.get_size(); i++) { toppingList.del((toppingList.get_head())->get_name()); } for (int i = 0; i < doughList.get_size(); i++) { doughList.del((doughList.get_head())->get_name()); } for (int i = 0; i < edgeList.get_size(); i++) { edgeList.del((edgeList.get_head())->get_name()); } // while (true) { // doughList.del(tempD->get_name()); // if (tempD->get_next() == NULL) { // 리스트의 마지막 객체인 경우 // doughList.del(tempD->get_name()); // break; // } // tempD = tempD->get_next(); // } // while (true) { // edgeList.del(tempE->get_name()); // if (tempE->get_next() == NULL) { // 리스트의 마지막 객체인 경우 // edgeList.del(tempE->get_name()); // break; // } // tempE = tempE->get_next(); // } cout << "프로그램을 종료합니다..." << endl; break; } switch (inputNum) { case 0: { // 모든 메뉴 보기 cout << "-TOPPING <" << toppingList.get_size() << ">" << endl; toppingList.show_all_menu(); cout << "-DOUGH <" << doughList.get_size() << ">" << endl; doughList.show_all_menu(); cout << "-EDGE <" << edgeList.get_size() << ">" << endl; edgeList.show_all_menu(); break; } case 1: { // 주문 하기 // Topping 선택 cout << "-TOPPING <" << toppingList.get_size() << ">" << endl; toppingList.show_all_menu(); cout << endl << "원하시는 토핑 이름을 입력하세요." << endl << ">> "; string toppingName; cin >> toppingName; toppingList.pick(toppingName)->inc_sellcount(); // Dough 선택 cout << "-DOUGH <" << doughList.get_size() << ">" << endl; doughList.show_all_menu(); cout << endl << "원하시는 도우 이름을 입력하세요." << endl << ">> "; string doughName; cin >> doughName; doughList.pick(doughName)->inc_sellcount(); // Edge 선택 cout << "-EDGE <" << edgeList.get_size() << ">" << endl; edgeList.show_all_menu(); cout << endl << "원하시는 에지 이름을 입력하세요." << endl << ">> "; string edgeName; cin >> edgeName; edgeList.pick(edgeName)->inc_sellcount(); // 주문 결과 출력 cout << endl << "주문하신 피자는 \"" << doughName << " " << edgeName << " " << toppingName << "\" 입니다." << endl; cout << "가격은 \"" << doughList.pick(doughName)->get_extra_cost() + edgeList.pick(edgeName)->get_extra_cost() + toppingList.pick(toppingName)->get_price() << "\"원 입니다." << endl; break; } case 2: { // 메뉴 추가 cout << "추가하고자 하는 메뉴의 종류를 선택하세요." << endl << "1: 토핑" << endl << "2: 도우" << endl << "3: 에지" << endl << ">> "; int inputAddNum; cin >> inputAddNum; string name, ingredient_all, mousse_all, comment, dummy; float thickness; int price, extra_cost; switch (inputAddNum) { case 1: // 토핑 추가 cout << "이름" << endl << ">> "; cin >> name; cout << "재료" << endl << ">> "; cin >> ingredient_all; cout << "가격" << endl << ">> "; cin >> price; cout << "소개말" << endl << ">> "; getline(cin, dummy); getline(cin, comment); toppingList.add(new Topping(name, ingredient_all, price, comment)); cout << "메뉴 추가가 완료되었습니다." << endl << endl; cout << "-TOPPING <" << toppingList.get_size() << ">" << endl; toppingList.show_all_menu(); break; case 2: // 도우 추가 cout << "이름" << endl << ">> "; cin >> name; cout << "두께" << endl << ">> "; cin >> thickness; cout << "추가비용" << endl << ">> "; cin >> extra_cost; cout << "소개말" << endl << ">> "; getline(cin, dummy); getline(cin, comment); doughList.add(new Dough(name, thickness, extra_cost, comment)); cout << "메뉴 추가가 완료되었습니다." << endl << endl; cout << "-DOUGH <" << doughList.get_size() << ">" << endl; doughList.show_all_menu(); break; case 3: // 에지 추가 cout << "이름" << endl << ">> "; cin >> name; cout << "무스" << endl << ">> "; getline(cin, dummy); getline(cin, mousse_all); cout << "추가비용" << endl << ">> "; cin >> extra_cost; cout << "소개말" << endl << ">> "; getline(cin, dummy); getline(cin, comment); edgeList.add(new Edge(name, mousse_all, extra_cost, comment)); cout << "메뉴 추가가 완료되었습니다." << endl << endl; cout << "-EDGE <" << edgeList.get_size() << ">" << endl; edgeList.show_all_menu(); break; default: cout << "1~3 값을 입력하지 않았습니다. 메인화면으로 돌아갑니다." << endl; } break; } case 3: { // 메뉴 삭제 cout << "삭제하고자 하는 메뉴의 종류를 선택하세요." << endl << "1: 토핑" << endl << "2: 도우" << endl << "3: 에지" << endl << ">> "; int inputDelNum; cin >> inputDelNum; string inputDelName; switch (inputDelNum) { case 1: // 토핑 삭제 toppingList.show_all_menu(); cout << "삭제하고자 하는 메뉴 이름을 입력하세요." << endl << ">> "; cin >> inputDelName; toppingList.del(inputDelName); cout << "메뉴 삭제가 완료되었습니다." << endl << endl; cout << "-TOPPING <" << toppingList.get_size() << ">" << endl; toppingList.show_all_menu(); break; case 2: // 도우 삭제 doughList.show_all_menu(); cout << "삭제하고자 하는 메뉴 이름을 입력하세요." << endl << ">> "; cin >> inputDelName; doughList.del(inputDelName); cout << "메뉴 삭제가 완료되었습니다." << endl << endl; cout << "-DOUGH <" << doughList.get_size() << ">" << endl; doughList.show_all_menu(); break; case 3: // 에지 삭제 edgeList.show_all_menu(); cout << "삭제하고자 하는 메뉴 이름을 입력하세요." << endl << ">> "; cin >> inputDelName; edgeList.del(inputDelName); cout << "메뉴 삭제가 완료되었습니다." << endl << endl; cout << "-EDGE <" << edgeList.get_size() << ">" << endl; edgeList.show_all_menu(); break; default: cout << "1~3 값을 입력하지 않았습니다. 메인화면으로 돌아갑니다." << endl; } break; } case 4: { // 메뉴 검색 cout << "검색하고자 하는 메뉴의 종류를 선택하세요." << endl << "1: 토핑" << endl << "2: 도우" << endl << "3: 에지" << endl << ">> "; int inputSearchNum; cin >> inputSearchNum; int inputSearchBy; switch (inputSearchNum) { case 1: // 토핑 검색 cout << "검색 기준을 선택하세요." << endl << "1: 재료로 검색" << endl << "2: 가격으로 검색" << endl << ">> "; cin >> inputSearchBy; switch (inputSearchBy) { case 1: { // 재료 이름으로 검색 cout << "재료 이름을 입력해주세요." << endl << ">> "; string ingredient; cin >> ingredient; toppingList.search_by_ingred(ingredient); break; } case 2: { // 가격 범위로 검색 cout << "가격 범위 중 하한을 입력해주세요." << endl << ">> "; int min_price; cin >> min_price; cout << "가격 범위 중 상한을 입력해주세요." << endl << ">> "; int max_price; cin >> max_price; toppingList.search_by_price(min_price, max_price); break; } default: cout << "1~2 값을 입력하지 않았습니다. 메인화면으로 돌아갑니다." << endl; } break; case 2: // 도우 검색 cout << "검색 기준을 선택하세요." << endl << "1: 두께로 검색" << endl << ">> "; cin >> inputSearchBy; switch (inputSearchBy) { case 1: { // 두께 범위로 검색 cout << "두께 범위 중 하한을 입력해주세요." << endl << ">> "; float min_thick; cin >> min_thick; cout << "두께 범위 중 상한을 입력해주세요." << endl << ">> "; float max_thick; cin >> max_thick; doughList.search_by_thick(min_thick, max_thick); break; } default: cout << "1 값을 입력하지 않았습니다. 메인화면으로 돌아갑니다." << endl; } break; case 3: // 에지 검색 cout << "검색 기준을 선택하세요." << endl << "1: 무스로 검색" << endl << ">> "; cin >> inputSearchBy; switch (inputSearchBy) { case 1: { // 재료 이름으로 검색 cout << "무스 이름을 입력해주세요." << endl << ">> "; string mousse; cin >> mousse; edgeList.search_by_mousse(mousse); break; } break; } break; default: cout << "1~3 값을 입력하지 않았습니다. 메인화면으로 돌아갑니다." << endl; } break; } case 5: { // 인기메뉴 추천 toppingList.show_most_popular(); doughList.show_most_popular(); edgeList.show_most_popular(); break; } default: { cout << "0~6 값을 입력하지 않았습니다. 메인화면으로 돌아갑니다." << endl; } } } return 0; } bool readInput(string inputName, ToppingList * toppingList, DoughList * doughList, EdgeList * edgeList){ // 텍스트 파일 읽어서 리스트에 객체 생성 및 리스트에 추가 ifstream fin(inputName); if ( !fin.is_open() ) { // 파일 오픈 실패 시 오류 메시지 출력하고 프로그램 종료 cout << inputName << " 이 열리지 않음" << endl; return false; } string name, ingredient_all, mousse_all, _price, _thickness, _extra_cost, comment, dummy; float thickness; int price, extra_cost; while ( !fin.eof() ) { getline(fin, dummy); int i = 3; while (i-- > 0) { // Topping 객체 생성 및 ToppingList에 추가 getline(fin, name, '\t'); // name 임시 저장 getline(fin, ingredient_all, '\t'); // 모든 ingredient 임시 저장 getline(fin, _price, '\t'); price = stoi(_price); // price 임시 저장 getline(fin, comment, '\r'); // comment 임시 저장 getline(fin, dummy, '\n'); toppingList->add(new Topping(name, ingredient_all, price, comment)); } getline(fin, dummy); int j = 3; while (j-- > 0) { // Dough 객체 생성 및 DoughList에 추가 getline(fin, name, '\t'); // name 임시 저장 getline(fin, _thickness, '\t'); thickness = stof(_thickness); // thickness 임시 저장 getline(fin, _extra_cost, '\t'); extra_cost = stoi(_extra_cost); // extra_cost 임시 저장 getline(fin, comment, '\r'); // comment 임시 저장 getline(fin, dummy, '\n'); doughList->add(new Dough(name, thickness, extra_cost, comment)); } getline(fin, dummy); int k = 4; while (k-- > 0) { // Edge 객체 생성 및 EdgeList에 추가 getline(fin, name, '\t'); // name 임시 저장 if (name == "") break; getline(fin, mousse_all, '\t'); // 모든 mousse 임시 저장 getline(fin, _extra_cost, '\t'); extra_cost = stoi(_extra_cost); // extra_cost 임시 저장 getline(fin, comment, '\r'); // comment 임시 저장 getline(fin, dummy, '\n'); edgeList->add(new Edge(name, mousse_all, extra_cost, comment)); } break; } fin.close(); return true; }
/* * This software split a media file (in Container such as MKV, FLV, AVI...) * to video and audio bitstream. * In this example, it demux a MPEG2TS file to H.264 bitstream * and AAC bitstream. */ #include <stdio.h> #define __STDC_CONSTANT_MACROS extern "C" { #include "libavformat/avformat.h" }; /* FIX: H.264 in some container format (FLV, MP4, MKV etc.) need "h264_mp4toannexb" bitstream filter (BSF). Add SPS,PPS in front of IDR frame Add start code ("0,0,0,1") in front of NALU H.264 in some container (MPEG2TS) don't need this BSF. */ // '1': Use H.264 Bitstream Filter #define USE_H264BSF 1 int main(int argc, char* argv[]) { /* Step 1: FFmpeg init. */ av_register_all(); /* Step 2: Set up A/V input and output content and format. */ AVOutputFormat *pOutFmtA = NULL, *pOoutFmtV = NULL; AVFormatContext *pInFmtCtx = NULL, *pOutFmtCtxA = NULL, *pOutFmtCtxV = NULL; const char *pInFile = "c://work//cuc_ieschool.flv"; const char *pOutFileV = "c://work//cuc_ieschool.h264"; const char *pOutFileA = "c://work//cuc_ieschool.aac"; // Input int ret = 0; if ((ret = avformat_open_input(&pInFmtCtx, pInFile, 0, 0)) < 0) { printf( "Can't open input file."); goto end; } if ((ret = avformat_find_stream_info(pInFmtCtx, 0)) < 0) { printf( "Failed to retrieve input stream information."); goto end; } // Output avformat_alloc_output_context2(&pOutFmtCtxV, NULL, NULL, pOutFileV); if (!pOutFmtCtxV) { printf( "Can't create output context.\n"); ret = AVERROR_UNKNOWN; goto end; } pOoutFmtV = pOutFmtCtxV->oformat; avformat_alloc_output_context2(&pOutFmtCtxA, NULL, NULL, pOutFileA); if (!pOutFmtCtxA) { printf( "Could not create output context.\n"); ret = AVERROR_UNKNOWN; goto end; } pOutFmtA = pOutFmtCtxA->oformat; /* Step 3: Create output A/V stream. */ int videoIndex = -1, audioIndex = -1; for (int i = 0; i < pInFmtCtx->nb_streams; i++) { // Create output AVStream according to input AVStream. AVFormatContext *ofmt_ctx = NULL; AVStream *in_stream = pInFmtCtx->streams[i]; AVStream *out_stream = NULL; if (pInFmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { videoIndex = i; out_stream = avformat_new_stream(pOutFmtCtxV, in_stream->codec->codec); ofmt_ctx = pOutFmtCtxV; } else if (pInFmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) { audioIndex = i; out_stream = avformat_new_stream(pOutFmtCtxA, in_stream->codec->codec); ofmt_ctx = pOutFmtCtxA; } else { break; } if (!out_stream) { printf( "Failed allocating output stream.\n"); ret = AVERROR_UNKNOWN; goto end; } // Copy the settings of AVCodecContext. if (avcodec_copy_context(out_stream->codec, in_stream->codec) < 0) { printf( "Failed to copy context from input to output stream codec context.\n"); goto end; } out_stream->codec->codec_tag = 0; if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) { out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER; } } // Dump Format------------------ printf("\n============== Input Video =============\n"); av_dump_format(pInFmtCtx, 0, pInFile, 0); printf("\n============== Output Video ============\n"); av_dump_format(pOutFmtCtxV, 0, pOutFileV, 1); printf("\n============== Output Audio ============\n"); av_dump_format(pOutFmtCtxA, 0, pOutFileA, 1); printf("\n======================================\n"); /* Step 4: Open output file. */ if (!(pOoutFmtV->flags & AVFMT_NOFILE)) { if (avio_open(&pOutFmtCtxV->pb, pOutFileV, AVIO_FLAG_WRITE) < 0) { printf( "Can't open output file '%s'. ", pOutFileV); goto end; } } if (!(pOutFmtA->flags & AVFMT_NOFILE)) { if (avio_open(&pOutFmtCtxA->pb, pOutFileA, AVIO_FLAG_WRITE) < 0) { printf( "Can't open output file '%s'. ", pOutFileA); goto end; } } /* Step 5: Write file header to output file. */ if (avformat_write_header(pOutFmtCtxV, NULL) < 0) { printf( "Error occurred when opening video output file. \n"); goto end; } if (avformat_write_header(pOutFmtCtxA, NULL) < 0) { printf( "Error occurred when opening audio output file. \n"); goto end; } /* Step 5: Write packets to output file */ #if USE_H264BSF AVBitStreamFilterContext* h264bsfc = av_bitstream_filter_init("h264_mp4toannexb"); #endif AVPacket pkt; int frameIndex = 0; while (1) { AVFormatContext *ofmt_ctx; AVStream *in_stream, *out_stream; // Get an AVPacket if (av_read_frame(pInFmtCtx, &pkt) < 0) { break; } in_stream = pInFmtCtx->streams[pkt.stream_index]; if (pkt.stream_index == videoIndex) { out_stream = pOutFmtCtxV->streams[0]; ofmt_ctx=pOutFmtCtxV; printf("Write Video Packet. size:%d\tpts:%lld\n", pkt.size, pkt.pts); #if USE_H264BSF av_bitstream_filter_filter(h264bsfc, in_stream->codec, NULL, &pkt.data, &pkt.size, pkt.data, pkt.size, 0); #endif } else if (pkt.stream_index == audioIndex) { out_stream = pOutFmtCtxA->streams[0]; ofmt_ctx = pOutFmtCtxA; printf("Write Audio Packet. size:%d\tpts:%lld\n", pkt.size, pkt.pts); } else { continue; } // Convert PTS/DTS pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX)); pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base); pkt.pos = -1; pkt.stream_index = 0; // Write if (av_interleaved_write_frame(ofmt_ctx, &pkt) < 0) { printf( "Error muxing packet\n"); break; } // printf("Write %8d frames to output file\n",frame_index); av_free_packet(&pkt); frameIndex++; } #if USE_H264BSF av_bitstream_filter_close(h264bsfc); #endif /* Step 6: Write file trailer */ //Write file trailer av_write_trailer(pOutFmtCtxA); av_write_trailer(pOutFmtCtxV); /* Step 7: Clean up. */ end: avformat_close_input(&pInFmtCtx); /* close output */ if (pOutFmtCtxA && !(pOutFmtA->flags & AVFMT_NOFILE)) { avio_close(pOutFmtCtxA->pb); } if (pOutFmtCtxV && !(pOoutFmtV->flags & AVFMT_NOFILE)) { avio_close(pOutFmtCtxV->pb); } avformat_free_context(pOutFmtCtxA); avformat_free_context(pOutFmtCtxV); if (ret < 0 && ret != AVERROR_EOF) { printf( "Error occurred.\n"); return -1; } return 0; }
#include "SymbolStorage.hpp" #include <cstdlib> using wali::printKey; namespace opennwa { namespace details { //Constructors SymbolStorage::SymbolStorage( ) { //Epsilon is always a symbol of the NWA. addSymbol( EPSILON ); } SymbolStorage::SymbolStorage( const SymbolStorage & other ) : Printable(other) , symbols(other.symbols) { } SymbolStorage & SymbolStorage::operator=( const SymbolStorage & other ) { if( this == &other ) return *this; symbols = other.symbols; return *this; } //Accessors /** * * @brief add the given symbol * * @param - sym: the symbol to add * @return false if the symbol already exists, true otherwise * */ bool SymbolStorage::addSymbol( Sym sym ) { if (sym == EPSILON || sym == WILD) { return false; } bool inserted = symbols.insert(sym).second; return inserted; } /** * * @brief add all the symbols in the given collection to this collection * * @param - symSet: the collection of symbols to add to this collection of symbols * */ void SymbolStorage::addAllSymbols( SymbolStorage symSet ) { symbols.insert(symSet.symbols.begin(),symSet.symbols.end()); } /** * * @brief remove the given symbol * * @param - sym: the symbol to remove * @return false if the symbol does not exist, true otherwise * */ bool SymbolStorage::removeSymbol( Sym sym ) { size_t erased = symbols.erase(sym); return erased > 0; } /** * * @brief remove all the symbols in the given collection from this collection * * @param - symSet: the collection of symbols to remove from this collection * */ void SymbolStorage::removeAll( SymbolStorage symSet ) { // FIXME: Make this not suck (void) symSet; assert(0); std::exit(10); //symbols.erase(symSet.symbols.begin(),symSet.symbols.end()); } //Utilities /** * * @brief print the collection of symbols * * @param - o: the output stream to print to * @return the output stream that was printed to * */ std::ostream & SymbolStorage::print( std::ostream & o ) const { //Print the set of all symbols. o << "Sigma: {\n "; bool first = true; for( const_iterator it = symbols.begin(); it != symbols.end(); it++, first = false ) { if( !first ) { o << ",\n "; } if( *it == EPSILON ) o << "Epsilon"; else printKey(o,*it); } o << "}\n"; return o; } /** * * @brief tests whether this collection of symbols is equivalent to the collection * of symbols 'other' * * @param - other: the SymbolStorage to which to compare this SymbolStorage * @return true if this SymbolStorage is equivalent to the SymbolStorage 'other' * */ bool SymbolStorage::operator==( const SymbolStorage & other ) const { return symbols == other.symbols; } ///////// Class Label //Constructors Label::Label( ) { neg = false; } Label::Label( const Label & other ) { syms = other.syms; neg = other.neg; } Label & Label::operator=( const Label & other ) { if( this == &other ) return *this; syms = other.syms; neg = other.neg; return *this; } //Accessors /** * * @brief tests whether this collection represents the wild symbol * * The Label is wild if syms is empty and neg is true ( {}, T ) * or syms is equal to the symbolPool and neg is false ( symbolPool, F }. * * @return true if this collection represents the wild symbol * */ bool Label::isWild( const SymbolStorage & symbolPool ) const { if( neg ) return syms.empty(); //No symbols not on the edge. else { //Check that all symbols in the symbolPool are in syms. for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if( syms.find(*it) == syms.end() ) return false; } return true; //All symbols are on the edge. } } /** * * @brief make this collection represent wild * * The Label is wild if syms is empty and neg is true ( {}, T ). * */ void Label::makeWild( ) { syms.clear(); neg = true; } /** * * @brief tests whether this collection represents the absence of all symbols * * The Label is absent if syms is empty and neg is false ( {}, F ) * or syms is equal to the symbolPool and neg is true ( symbolPool, T ). * * @return true if this collection represents the absence of all symbols * */ bool Label::isAbsent( const SymbolStorage & symbolPool ) const { if( neg ) { //Check that all symbols in the symbolPool are in syms. for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if( syms.find(*it) == syms.end() ) return false; } return true; //All symbols are not on the edge. } else return ( syms.empty() ); //No symbols are on the edge. } /** * * @brief make this collection represent the absence of all symbols * * The Label is absent if syms is empty and neg is false ( {}, F ) * */ void Label::makeAbsent( ) { syms.clear(); neg = false; } /** * * @brief provides access to some symbol in this collection * * @return some symbol in this collection of symbols * */ Label::Sym Label::getAnySymbol( const SymbolStorage & symbolPool ) const { if(neg) { for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if( syms.find(*it) == syms.end() ) return *it; //Return the first symbol in the symbolPool which //is not in the set of symbols not on the edge. } // This shouldn't happen for now, because I don't know what the function // should do. Maybe return a bool/Sym pair? Define an "INVALID_SYMBOL" // somewhere? // // Regardless, 'return NULL' is NOT it, as that essentially means "return // epsilon". assert(false); throw "SymbolStorage.cpp line 262 (or thereabouts); talk to Evan."; //return NULL; } else { return *(syms.begin()); //Return the first symbol in the set. } } /** * * @brief add all the symbols in the given collection to this collection * * @param - symSet: the collection of symbols to add to this collection of symbols * */ void Label::addAll( Label lbl, const SymbolStorage & symbolPool ) { if( lbl.neg ) { //Note: we cannot directly add symbols from syms because syms only // records symbols not on the edge. //Need to add all symbols from the transition pool that are in symSet. for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if( lbl.containsSymbol(*it) ) addSymbol(*it); } } else { for( const_iterator it = lbl.syms.begin(); it != lbl.syms.end(); it++ ) { addSymbol(*it); } } } /** * * @brief remove the given symbol * * @param - sym: the symbol to remove * @return false if the symbol does not exist, true otherwise * */ bool Label::removeSymbol( Sym sym ) { if(! containsSymbol(sym) ) return false; if( neg ) { //syms records symbols not on the edge, so add sym to syms syms.insert(sym); } else { //syms records symbols on the edge, so remove sym from syms syms.erase(syms.find(sym)); } return true; } /** * * @brief remove all the symbols in the given collection from this collection * * @param - symSet: the collection of symbols to remove from this collection * */ void Label::removeAll( Label lbl, const SymbolStorage & symbolPool ) { if( lbl.neg ) { //Note: we cannot directly add symbols from syms because syms only // records symbols not on the edge. //Need to add all symbols from the transition pool that are in symSet. for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if( lbl.containsSymbol(*it) ) removeSymbol(*it); } } else { for( const_iterator it = lbl.syms.begin(); it != lbl.syms.end(); it++ ) { removeSymbol(*it); } } } //Utilities /** * * @brief print the collection of symbols * * @param - o: the output stream to print to * @return the output stream that was printed to * */ std::ostream & Label::print( std::ostream & o, const SymbolStorage & symbolPool ) const { if( isWild(symbolPool) ) o << "wild"; else if( isAbsent(symbolPool) ) o << "absent"; else { if( neg ) o << "wild - { "; else o << "{ "; bool first = true; for( const_iterator it = syms.begin(); it != syms.end(); it++ ) { if( !first ) { o << ", "; first = false; } if( *it == EPSILON ) o << "Epsilon"; else printKey(o,*it); } o << " }"; } return o; } /** * * @brief tests whether this collection of symbols is equivalent to the collection * of symbols 'other' * * @param - other: the Label to which to compare this Label * @return true if this Label is equivalent to the Label 'other' * */ bool Label::operator==( const Label & other ) const { if( neg == other.neg ) { //This checks for both wild or both absent without using the symbolPool. if( syms.empty() ) return other.syms.empty(); //returning true if both syms are empty, false otherwise else if( other.syms.empty() ) return false; //we already know that syms is not empty else return ( syms == other.syms ); } else if( neg ) { //Anything in syms should not be a symbol in 'other'. for( const_iterator it = syms.begin(); it != syms.end(); it++ ) { if ( other.containsSymbol(*it) ) return false; } return true; } else { //Anything in syms should be a symbol in 'other'. for( const_iterator it = syms.begin(); it != syms.end(); it++ ) { if (! other.containsSymbol(*it) ) return false; } return true; } } /** * * @brief provides access to all symbols in the collection * * @return a set containing all symbols in this collection * */ const std::set<Label::Sym> Label::getSymbolsIn( const SymbolStorage & symbolPool ) const { if( neg ) { std::set<Sym> symsIn; for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if( containsSymbol(*it) ) symsIn.insert(*it); } return symsIn; } else { return syms; } } /** * * @brief provides access to all symbols not in the collection * * @return a set containing all symbols not in this collection * */ const std::set<Label::Sym> Label::getSymbolsNotIn( const SymbolStorage & symbolPool ) const { if( neg ) { return syms; } else { std::set<Sym> symsNotIn; for( const_iterator it = symbolPool.beginSymbols(); it != symbolPool.endSymbols(); it++ ) { if(! containsSymbol(*it) ) symsNotIn.insert(*it); } return symsNotIn; } } } // namespace details } // namespace opennwa // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End:
#include "Card.h"
#include "TileDefinitionDialog.hpp" #include "ui_TileDefinitionDialog.h" #include "LevelManager.hpp" #include <Tileset.hpp> using namespace Maint; TileDefinitionDialog::TileDefinitionDialog(Tileset const*tileset, LevelManager* levelManager, TextureManager* textureManager, QWidget *parent) : QDialog(parent), ui(new Ui::TileDefinitionDialog) { ui->setupUi(this); ui->tilePreview->SetTileset(tileset); ui->tilePreview->SetDependencies( levelManager, textureManager ); } TileDefinitionDialog::~TileDefinitionDialog() { delete ui; } TileDefinition TileDefinitionDialog::GetTileDefinition() { TileDefinition definition; definition.name = ui->tileName->text().toStdString(); definition.param = 0; definition.tile = ui->tileIndexBox->value(); return definition; } void TileDefinitionDialog::SetFields(const TileDefinition *definition) { ui->tileName->setText(QString(definition->name.c_str())); ui->tileIndexBox->setValue(definition->tile); }
#ifndef CDOUBLESLIDER_H #define CDOUBLESLIDER_H #include <QDialog> class DoubleSlider : public QWidget { Q_OBJECT public: DoubleSlider(QWidget* parent = 0); void setRange(float min, float max); void setSingleStep(float step); enum State{ MinHandle,MaxHandle,None}; float minValue() const; float maxValue() const; float minRange() const; float maxRange() const; public slots: void setMaxValue(float val); void setMinValue(float val); signals: void minValueChanged(float); void maxValueChanged(float); private: float m_min; float m_max; float m_singleStep; float m_minValue; float m_maxValue; QRect minHandleRegion; QRect maxHandleRegion; State m_state; protected: void paintEvent(QPaintEvent* event); void paintColoredRect(QRect rect, QColor color, QPainter* painter); void paintValueLabel(QPainter* painter); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); void keyPressEvent(QKeyEvent *event); void leaveEvent(QEvent* event); }; #endif // CDOUBLESLIDER_H
// // simulator.hpp // QueueSimulation // // Created by Quincy Copeland on 3/29/19. // Copyright © 2019 Quincy Copeland. All rights reserved. // #ifndef simulator_hpp #define simulator_hpp #include <iostream> #include <string> #include <vector> #include <queue> #include <array> #include <unordered_map> #define NUM_TELLERS 6 #define SIMULATION_LEN 43200 // seconds in 12 hours day enum EventType {arrival, departure}; //Event Struct struct Event { //member variables double eventTime; double serviceDuration; double totalServiceTime; int customerID; int cashier; EventType event; }; struct compareEventTime { bool operator()(const Event& lhs, const Event& rhs) const { return lhs.eventTime > rhs.eventTime; } }; //******************BASE CLASS***************// class Service { private: //std::priority_queue<Event, std::vector<Event>, compareEventTime> eventQueue; int currentTime = 0; public: virtual void runSim() = 0; void addEvent(Event& event); int getCurentTime(); std::vector<int> serviceTimes; std::priority_queue<Event, std::vector<Event>, compareEventTime> eventQueue; }; //************Bank Class*****************// class Bank : public Service { private: //member variables std::queue<Event> bankQueue; int tellersAvailable = NUM_TELLERS; public: //methods void addBankQueueCustomer(Event& event); void runSim(); //public member variable std::vector<int> serviceTimes; }; //************Grocery Class*****************// class Grocery : public Service { private: //member variables std::array<int, 6> checkers; public: //methods int chooseShortestLine(std::array<int, 6>& checkers); void runSim(); //public member variable std::vector<int> serviceTimes; }; #endif /* simulator_hpp */
/*! * \file Material.cpp * * \author Stanley * \date October 2016 * * */ #include "pch.h" #include "Material.h" #include "Core\FileUtils.h" #include "Texture.h" #include "CommonDef.h" Hourglass::MaterialManager Hourglass::g_MaterialManager; void Hourglass::MaterialManager::Init() { LoadMateriales("Assets/Material/"); m_DefaultMaterial = GetMaterial("Assets/Material/Default-Material.xml"); } void Hourglass::MaterialManager::Shutdown() { for (std::vector<Material*>::iterator iter = m_Materials.begin(); iter != m_Materials.end(); iter++) { delete *iter; } m_Materials.clear(); } Hourglass::Material* Hourglass::MaterialManager::GetMaterial(const char* path) const { std::string matPath(path); FileUtils::TrimPathDelimiter(matPath); std::string paths = path; for (int i = 0; i < m_Materials.size(); i++) { if (FileUtils::iequals(matPath, m_Materials[i]->GetPath())) return m_Materials[i]; } return nullptr; } Hourglass::Material* Hourglass::MaterialManager::GetDefaultMaterial() const { return m_DefaultMaterial; } void Hourglass::MaterialManager::LoadMateriales(const char* path) { char searchPath[MAX_PATH]; strcpy_s(searchPath, path); strcat_s(searchPath, "\\*.*"); FileUtils::IterateFolderForFiles(searchPath, ".xml", [&](const char* filename) { tinyxml2::XMLDocument doc; doc.LoadFile(filename); tinyxml2::XMLElement * xmlMat = doc.FirstChildElement("Material"); if (xmlMat) { Material* mat = new Material(); ZeroMemory(mat->m_Textures, sizeof(Texture*) * 8); // Get trimmed path name std::string matPath = filename; FileUtils::TrimPathDelimiter(matPath); mat->SetPath(matPath); // Get material pass mat->m_BlendMode = kBlend_Opaque; const char* passName = xmlMat->Attribute("blend"); if (passName) { if (strcmp(passName, "AlphaBlend") == 0) { mat->m_BlendMode = kBlend_AlphaBlend; } else if (strcmp(passName, "AlphaToCoverage") == 0) { mat->m_BlendMode = kBlend_AlphaToCoverage; } else if (strcmp(passName, "Additive") == 0) { mat->m_BlendMode = kBlend_Additive; } } // Get material color mat->m_UniformColor = Color(1, 1, 1, 1); tinyxml2::XMLElement* xmlColor = xmlMat->FirstChildElement("UniformColor"); if (xmlColor) { xmlColor->QueryFloatAttribute("r", &mat->m_UniformColor.x); xmlColor->QueryFloatAttribute("g", &mat->m_UniformColor.y); xmlColor->QueryFloatAttribute("b", &mat->m_UniformColor.z); xmlColor->QueryFloatAttribute("a", &mat->m_UniformColor.w); } // Get all textures from child nodes tinyxml2::XMLElement* xmlTex = xmlMat->FirstChildElement("Texture"); while (xmlTex) { int slot = -1; xmlTex->QueryIntAttribute("slot", &slot); const char* texName = xmlTex->Attribute("file"); mat->m_Textures[slot] = g_TextureManager.GetTexture(texName); xmlTex = xmlTex->NextSiblingElement("Texture"); } m_Materials.push_back(mat); } }); }
//===-- context.h - OpenCL Context ------------------------------*- C++ -*-===// // // TODO (Zhongliang): Add a license. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file contains the definition of OpenCL context class. /// //===----------------------------------------------------------------------===// #ifndef CONTEXT_H_ #define CONTEXT_H_ #include <stdint.h> #include <list> #include <map> #include <vector> #include "CL/cl.h" /// \brief The OpenCL context definition. struct _cl_context { public: _cl_context(); _cl_context(const cl_context_properties* property_list); ~_cl_context(); // ID. int id; // The information used by clGetContextInfo. int ref_cnt; std::vector<cl_device_id> devices; std::map<uint32_t, cl_context_properties> properties; // The OpenCL objects attached. std::list<cl_command_queue> command_queues; std::list<cl_mem> mem_objects; std::list<cl_program> programs; std::list<cl_kernel> kernels; }; #endif // CONTEXT_H_
#include <GL/glut.h> #include "Object3d.h" Object3d::Object3d() { } Object3d::Object3d(int id1, bool visible1, Posizione pos1) { idTexture = id1; visible = visible1; posizione = pos1; } void Object3d::setPosizione(Posizione pos1) { posizione = pos1; } Posizione Object3d::getPosizione() { return posizione; } bool Object3d::isVisible() { return visible; } void Object3d::setVisible(bool visible1) { visible = visible1; } int Object3d::getIdTexture() { return idTexture; } void Object3d::setIdTexture(int id1) { idTexture = id1; }
// // Bell.hpp // final_sketch2 // // Created by Kris Li on 12/1/16. // // #pragma once #include "ofMain.h" class Bell { public: Bell(); void init(ofPoint pos); void update(float _rad1, float _rad2); void draw(); ofPoint getLink(int _loop); ofMesh bell; float rad1, rad2; int gridScale; int size; float theta; float phi; float angle; int radius; int i1,i2,i3,i4; };
#ifndef wali_MERGE_FN_GUARD #define wali_MERGE_FN_GUARD 1 /** * @author Akash Lal * @author Nicholas Kidd */ #include "wali/Common.hpp" #include "wali/ref_ptr.hpp" #include "wali/IMergeFn.hpp" #include <iostream> namespace wali { class MergeFn; //typedef ref_ptr< MergeFn > merge_fn_t; class MergeFn : public IMergeFn//public Printable, public Countable { public: //static const std::string XMLTag; MergeFn(); explicit MergeFn(sem_elem_t sr); virtual ~MergeFn(); virtual sem_elem_t apply_f(sem_elem_t w1, sem_elem_t w2); virtual bool equal(merge_fn_t mf); virtual MergeFn *parse_element(const char *s, sem_elem_t sem); virtual std::ostream &print(std::ostream &o) const; private: sem_elem_t sr_data; }; } // namespacw wali #endif // wali_MERGE_FN_GUARD
#ifndef APPROX_FUNCTIONS_H #define APPROX_FUNCTIONS_H #include <vector> #include "lorentz.h" // Xsection scalar approx_X22(std::vector<double> params); scalar approx_X22QQbar(std::vector<double> params); scalar approx_dX22_max(std::vector<double> params); #endif
/* * DecrementaService.cpp * * Created on: 10/12/2019 * Author: Jean */ #include <DecrementaService.h> DecrementaService::DecrementaService() { // TODO Auto-generated constructor stub a = 0; } void DecrementaService::decrementa(Contador *ContadorSeg, Contador *ContadorSegD, Contador *ContadorMin, Contador *ContadorMinD){ this->a = ContadorSeg->decrementa(); if(this->a){ this->a = ContadorSegD->decrementa(); if(this->a) this->a = ContadorMin->decrementa(); if(this->a) ContadorMinD->decrementa(); } }
// Created on: 1996-02-13 // Created by: Jacques GOUSSARD // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepFeat_Form_HeaderFile #define _BRepFeat_Form_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> #include <TopoDS_Shape.hxx> #include <TopTools_ListOfShape.hxx> #include <BRepFeat_PerfSelection.hxx> #include <TopoDS_Face.hxx> #include <TopTools_DataMapOfShapeShape.hxx> #include <BRepFeat_StatusError.hxx> #include <BRepBuilderAPI_MakeShape.hxx> #include <TColGeom_SequenceOfCurve.hxx> #include <Standard_Integer.hxx> class Geom_Curve; class LocOpe_Gluer; class BRepAlgoAPI_BooleanOperation; //! Provides general functions to build form features. //! Form features can be depressions or protrusions and include the following types: //! - Cylinder //! - Draft Prism //! - Prism //! - Revolved feature //! - Pipe //! In each case, you have a choice of operation type between the following: //! - removing matter (a Boolean cut: Fuse setting 0) //! - adding matter (Boolean fusion: Fuse setting 1) //! The semantics of form feature creation is based on the construction of shapes: //! - along a length //! - up to a limiting face //! - from a limiting face to a height //! - above and/or below a plane //! The shape defining construction of the feature can be either the //! supporting edge or the concerned area of a face. //! In case of the supporting edge, this contour can be attached to a //! face of the basis shape by binding. When the contour is bound to this //! face, the information that the contour will slide on the face //! becomes available to the relevant class methods. In case of the //! concerned area of a face, you could, for example, cut it out and //! move it to a different height which will define the limiting face of a //! protrusion or depression. //! Topological definition with local operations of this sort makes //! calculations simpler and faster than a global operation. The latter //! would entail a second phase of removing unwanted matter to get the same result. class BRepFeat_Form : public BRepBuilderAPI_MakeShape { public: DEFINE_STANDARD_ALLOC //! returns the list of generated Faces. Standard_EXPORT virtual const TopTools_ListOfShape& Modified (const TopoDS_Shape& F) Standard_OVERRIDE; //! returns a list of the created faces //! from the shape <S>. Standard_EXPORT virtual const TopTools_ListOfShape& Generated (const TopoDS_Shape& S) Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean IsDeleted (const TopoDS_Shape& S) Standard_OVERRIDE; //! Returns the list of shapes created at the bottom of //! the created form. It may be an empty list. Standard_EXPORT const TopTools_ListOfShape& FirstShape() const; //! Returns the list of shapes created at the top of the //! created form. It may be an empty list. Standard_EXPORT const TopTools_ListOfShape& LastShape() const; //! Returns a list of the limiting and glueing edges //! generated by the feature. These edges did not originally //! exist in the basis shape. //! The list provides the information necessary for //! subsequent addition of fillets. It may be an empty list. Standard_EXPORT const TopTools_ListOfShape& NewEdges() const; //! Returns a list of the tangent edges among the limiting //! and glueing edges generated by the feature. These //! edges did not originally exist in the basis shape and are //! tangent to the face against which the feature is built. //! The list provides the information necessary for //! subsequent addition of fillets. It may be an empty list. //! If an edge is tangent, no fillet is possible, and the edge //! must subsequently be removed if you want to add a fillet. Standard_EXPORT const TopTools_ListOfShape& TgtEdges() const; //! Initializes the topological construction if the basis shape is present. void BasisShapeValid(); //! Initializes the topological construction if the generated shape S is present. void GeneratedShapeValid(); //! Initializes the topological construction if the shape is //! present from the specified integer on. void ShapeFromValid(); //! Initializes the topological construction if the shape is //! present until the specified integer. void ShapeUntilValid(); //! Initializes the topological construction if the glued face is present. void GluedFacesValid(); //! Initializes the topological construction if the sketch face //! is present. If the sketch face is inside the basis shape, //! local operations such as glueing can be performed. void SketchFaceValid(); //! Initializes the topological construction if the selected face is present. void PerfSelectionValid(); Standard_EXPORT virtual void Curves (TColGeom_SequenceOfCurve& S) = 0; Standard_EXPORT virtual Handle(Geom_Curve) BarycCurve() = 0; Standard_EXPORT BRepFeat_StatusError CurrentStatusError() const; protected: //! Redefines the empty constructor. BRepFeat_Form(); //! General perform method... Standard_EXPORT void GlobalPerform(); Standard_EXPORT void UpdateDescendants (const LocOpe_Gluer& G); Standard_EXPORT void UpdateDescendants (const BRepAlgoAPI_BooleanOperation& aBOP, const TopoDS_Shape& SResult, const Standard_Boolean SkipFace = Standard_False); Standard_EXPORT Standard_Boolean TransformShapeFU (const Standard_Integer flag); Standard_Boolean myFuse; Standard_Boolean myModify; TopTools_DataMapOfShapeListOfShape myMap; TopoDS_Shape myFShape; TopoDS_Shape myLShape; TopTools_ListOfShape myNewEdges; TopTools_ListOfShape myTgtEdges; BRepFeat_PerfSelection myPerfSelection; Standard_Boolean myJustGluer; Standard_Boolean myJustFeat; TopoDS_Shape mySbase; TopoDS_Face mySkface; TopoDS_Shape myGShape; TopoDS_Shape mySFrom; TopoDS_Shape mySUntil; TopTools_DataMapOfShapeShape myGluedF; private: Standard_Boolean mySbOK; Standard_Boolean mySkOK; Standard_Boolean myGSOK; Standard_Boolean mySFOK; Standard_Boolean mySUOK; Standard_Boolean myGFOK; Standard_Boolean myPSOK; BRepFeat_StatusError myStatusError; }; #include <BRepFeat_Form.lxx> #endif // _BRepFeat_Form_HeaderFile
#include "guest.h" /*void guest_call(uint32_t call, void* data) { uint32_t magic = CALL_MAGIC; asm volatile("mov r0, %0\n" "mov r1, %1\n" "mov r2, %2\n" "bxj r0\n" : : "r"(call), "r"(data), "r"(magic) : "memory", "r0", "r1", "r2"); } */ void guest_prepare_buffer_read(const void* data, int size) { /* int j = 0; int i; for (i = 0; i < size; i += 0x1000) j += ((const char*) data)[i]; if (size) j += ((const char*) data)[size - 1]; return j;*/ return; } void guest_prepare_buffer_write(void* data, int size) { /*int i; for (i = 0; i < size; i += 0x1000) ((char*) data)[i] = 1; if (size) ((char*) data)[size - 1] = 1;*/ }
#ifndef _MSG_0XC9_PLAYERLISTITEM_STC_H_ #define _MSG_0XC9_PLAYERLISTITEM_STC_H_ #include "mcprotocol_base.h" namespace MC { namespace Protocol { namespace Msg { class PlayerListItem : public BaseMessage { public: PlayerListItem(); PlayerListItem(const String16& _playerName, bool _online, int16_t _ping); size_t serialize(Buffer& _dst, size_t _offset); size_t deserialize(const Buffer& _src, size_t _offset); const String16& getPlayerName() const; bool getOnline() const; int16_t getPing() const; void setPlayerName(const String16& _val); void setOnline(bool _val); void setPing(int16_t _val); private: String16 _pf_playerName; bool _pf_online; int16_t _pf_ping; }; } // namespace Msg } // namespace Protocol } // namespace MC #endif // _MSG_0XC9_PLAYERLISTITEM_STC_H_
#include "electionresult.h" EAnalyzer::ElectionResult::ElectionResult(int NCandidates) :candidates(NCandidates), PeopleVotedInAdvance(0), PeopleTookAbsenteeBallots(0), PeopleTookAbsenteeBallotsFromTEC(0), PeopleVotedWithAbsenteeBallots(0), AbsenteeBallots(0), AbsenteeBallotsLost(0), CanceledAbsenteeBallots(0) { } bool EAnalyzer::ElectionResult::operator ==(const EAnalyzer::ElectionResult &other) { bool f = N_LEC == other.N_LEC && TEC == other.TEC && VotersAtLEC == other.VotersAtLEC && VotingBallots == other.VotingBallots && PeopleVotedInAdvance == other.PeopleVotedInAdvance && PeopleVotedIn == other.PeopleVotedIn && PeopleVotedOut == other.PeopleVotedOut && CanceledBallots == other.CanceledBallots && BallotsFoundOut == other.BallotsFoundOut && BallotsFoundIn == other.BallotsFoundIn && InvalidBallots == other.InvalidBallots && ValidBallots == other.ValidBallots && AbsenteeBallots == other.AbsenteeBallots && PeopleTookAbsenteeBallots == other.PeopleTookAbsenteeBallots && PeopleVotedWithAbsenteeBallots == other.PeopleVotedWithAbsenteeBallots && CanceledAbsenteeBallots == other.CanceledAbsenteeBallots && PeopleTookAbsenteeBallotsFromTEC == other.PeopleTookAbsenteeBallotsFromTEC && AbsenteeBallotsLost == other.AbsenteeBallotsLost && VotingBallotsLost == other.VotingBallotsLost && VotingBallotsUnaccounted == other.VotingBallotsUnaccounted && candidates.size() == other.candidates.size(); for(size_t i = 0; i < candidates.size(); ++i) f = f && candidates[i] == other.candidates[i]; return f; }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Header guard ] //[-------------------------------------------------------] #pragma once //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "RendererRuntime/Core/Manager.h" #include <limits.h> // For "USHRT_MAX" // Disable warnings in external headers, we can't fix them PRAGMA_WARNING_PUSH PRAGMA_WARNING_DISABLE_MSVC(4668) // warning C4668: '_M_HYBRID_X86_ARM64' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' #include <inttypes.h> // For uint32_t, uint64_t etc. PRAGMA_WARNING_POP //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace RendererRuntime { //[-------------------------------------------------------] //[ Classes ] //[-------------------------------------------------------] /** * @brief * Packed element manager template * * @note * - Basing on "Managing Decoupling Part 4 -- The ID Lookup Table" https://github.com/niklasfrykholm/blog/blob/master/2011/managing-decoupling-4.md by Niklas Frykholm ( http://www.frykholm.se/ ) */ template <class ELEMENT_TYPE, typename ID_TYPE, uint32_t MAXIMUM_NUMBER_OF_ELEMENTS> class PackedElementManager final : private Manager { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] public: inline PackedElementManager(); inline ~PackedElementManager(); inline uint32_t getNumberOfElements() const; inline ELEMENT_TYPE& getElementByIndex(uint32_t index) const; inline bool isElementIdValid(ID_TYPE id) const; inline ELEMENT_TYPE& getElementById(ID_TYPE id) const; inline ELEMENT_TYPE* tryGetElementById(ID_TYPE id) const; inline ELEMENT_TYPE& addElement(); inline void removeElement(ID_TYPE id); //[-------------------------------------------------------] //[ Private methods ] //[-------------------------------------------------------] private: explicit PackedElementManager(const PackedElementManager&) = delete; PackedElementManager& operator=(const PackedElementManager&) = delete; //[-------------------------------------------------------] //[ Private definitions ] //[-------------------------------------------------------] private: static const uint32_t INDEX_MASK = 0xffff; static const uint32_t NEW_OBJECT_ID_ADD = 0x10000; struct Index final { ID_TYPE id; uint16_t index; uint16_t next; }; //[-------------------------------------------------------] //[ Private data ] //[-------------------------------------------------------] private: uint32_t mNumberOfElements; mutable ELEMENT_TYPE mElements[MAXIMUM_NUMBER_OF_ELEMENTS]; Index mIndices[MAXIMUM_NUMBER_OF_ELEMENTS]; uint16_t mFreeListEnqueue; uint16_t mFreeListDequeue; }; //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // RendererRuntime //[-------------------------------------------------------] //[ Implementation ] //[-------------------------------------------------------] #include "RendererRuntime/Core/PackedElementManager.inl"
#include <stdio.h> #include <iostream> #include <stdlib.h> #include <time.h> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; #define channel 3 /*double activation(const double sigma) { return 1/(1+exp(-sigma)); } */ Mat Max_pooling(int F_row, int F_col, double ** F,int stride , Mat image) { int A_row=image.rows; int A_col=image.cols; int M_row = (A_row - F_row)/stride + 1; int M_col = (A_col - F_col)/stride+ 1; int i,j,k,l,ch; int max = 0; Mat result_Max(M_row,M_col,image.type()); for(ch=0; ch<channel; ch++) { for(i=0; i < M_row; i++) { for(j=0; j< M_col; j++) { max=0; for(k=0; k<F_row;k++) { for(l=0; l<F_col; l++) { if( image.at<cv::Vec3b>(k+i*stride,l+j*stride)[ch] > max ) max = image.at<cv::Vec3b>(k+i*stride,l+j*stride)[ch]; } } result_Max.at<cv::Vec3b>(i,j)[ch] = max; } } } return result_Max; } Mat Convolution( int F_row, int F_col, double **F, int padding, int stride, int ***P, Mat image) { clock_t begin,end; int A_row=image.rows; int A_col=image.cols; int ***C; int C_row = (A_row - F_row + 2*padding)/stride + 1; int C_col = (A_col - F_col + 2*padding)/stride + 1; int i,j,k,l,ch; Mat result_con(C_row,C_col,image.type()); C = (int ***)malloc(channel*sizeof(int **)); for(i=0; i<channel; i++){ *(C+i) = (int**)malloc(C_row * sizeof(int*)); for(j=0; j<C_row;j++){ *(*(C+i)+j) = (int*)malloc(C_col*sizeof(int)); } } for(ch=0;ch<channel;ch++) { for (i = 0; i < C_row; i++) { for (j = 0; j < C_col; j++) C[ch][i][j] = 0; } } begin = clock(); for(ch=0; ch<channel; ch++) { for(i=0; i< C_row; i++) { for(j=0; j< C_col; j++) { for(k=0; k<F_row;k++) { for(l=0; l<F_col; l++) C[ch][i][j] += P[ch][k+i*stride][l+j*stride] * F[k][l]; } if(C[ch][i][j]>255) C[ch][i][j] = 255; else if(C[ch][i][j]<0) C[ch][i][j] = 0; result_con.at<cv::Vec3b>(i,j)[ch] = C[ch][i][j]; } } } end = clock(); cout<<"총 소요 시간 : "<< (double)(end - begin)/CLOCKS_PER_SEC<<endl; for(i=0; i<channel;i++) { for(j=0; j<C_row; j++) { free(*(*(C+i)+j)); } free(*(C+i)); } free(C); return result_con; } int main() { Mat image; int i,j,k,l,data; int ***A; int ***P; double **F; int stride; int padding; int ch; int F_row; int F_col; int max=0; //////////////////////////////////////////////image image = imread("test.jpg", IMREAD_COLOR); if(image.empty()) { cout << "Could not open or find the image" << endl; return -1; } int A_row = image.rows; int A_col = image.cols; printf("padding , stride �� �Է�: "); scanf("%d %d",&padding,&stride); ////////////////////////////////image A 3���� �����Ҵ� A = (int ***)malloc(channel*sizeof(int **)); for(i=0; i<channel; i++){ *(A+i) = (int**)malloc(A_row * sizeof(int*)); for(j=0; j<A_row;j++){ *(*(A+i)+j) = (int*)malloc(A_col*sizeof(int)); } } for(ch=0; ch<channel; ch++) { for(i=0; i<A_row; i++) { for(j=0; j<A_col; j++) A[ch][i][j] = image.at<Vec3b>(i,j)[ch]; } } ///////////////////////////////padding int P_row = A_row + 2*padding; int P_col = A_col + 2*padding; P = (int ***)malloc(channel*sizeof(int **)); for(i=0; i<channel; i++){ *(P+i) = (int**)malloc(P_row * sizeof(int*)); for(j=0; j<P_row;j++){ *(*(P+i)+j) = (int*)malloc(P_col*sizeof(int)); } } for(ch=0;ch<channel; ch++) { for ( i=0; i < P_row ;i++) { for( j=0; j < P_col ;j++) { if(i<padding || j<padding || i>= A_row+padding || j>= A_col+padding) P[ch][i][j] = 0; else P[ch][i][j] = image.at<Vec3b>(i-padding,j-padding)[ch]; } } } //////////////////////////////////////////////���� F �����Ҵ� printf("F_row , F_col �� �Է�: "); scanf("%d %d",&F_row,&F_col); F = (double **)malloc(F_row*sizeof(double *)); for(i=0; i<F_row; i++) { *(F+i)= (double *)malloc(F_col*sizeof(double)); } double x =0; for(i=0; i<F_row; i++) { for(j=0; j<F_col; j++){ scanf("%lf", &F[i][j]); x += F[i][j]; printf("%lf",F[i][j]); } printf("\n"); } if(x>1) { for(i=0; i<F_row; i++) { for(j=0; j<F_col; j++){ F[i][j]= F[i][j] / x; } } } Mat result_max = Max_pooling(F_row, F_col,F, stride,image); namedWindow("Max", WINDOW_AUTOSIZE); imshow("Max",result_max); //imwrite("Max.jpg",result_max); //waitKey(0); Mat result_con = Convolution(F_row, F_col, F, padding, stride, P, image); namedWindow("Con", WINDOW_AUTOSIZE); imshow("Con",result_con); //imwrite("Con.jpg",result_con); waitKey(0); }
#pragma once #include "proto/data_base.pb.h" #include "proto/data_condition.pb.h" #include "proto/data_player.pb.h" #include <set> using namespace std; namespace pd = proto::data; namespace nora { namespace scene { class role; void condition_merge(pd::condition_array& a, const pd::condition_array& b); pd::result condition_check(const pd::condition_array& ca, const pd::role_info& ri); pd::result condition_check(const pd::condition_array& ca, const role& role, const pd::ce_env& env = pd::ce_env()); vector<pd::condition> condition_find(const pd::condition_array& ca, pd::condition::condition_type type); } }
// -*- LSST-C++ -*- /* * LSST Data Management System * Copyright 2015 LSST Corporation. * * This product includes software developed by the * LSST Project (http://www.lsst.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the LSST License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ #ifndef LSST_QSERV_UTIL_PACKETBUFFER_H #define LSST_QSERV_UTIL_PACKETBUFFER_H // System headers #include <memory> #include <string> #include <utility> namespace lsst { namespace qserv { namespace util { /// An iterator that provides iteration over arbitrarily-sized pieces /// of a stream. Access either a local file or an xrootd file /// descriptor. Facilitates transferring bytes directly from the xrootd /// realm to a fragment consumer (probably the table merger). Allowing /// both types input sources makes it easier to reduce buffering and /// disk usage, theoretically improving overall latency. class PacketBuffer { public: typedef std::shared_ptr<PacketBuffer> Ptr; typedef std::pair<char*, unsigned> Value; typedef unsigned long long Pos; /// The interface for a backend to be plugged into a PacketBuffer class Source { public: virtual ~Source() {} virtual Value getFirstValue() = 0; virtual void increment(PacketBuffer& p) = 0; virtual bool incrementExtend(PacketBuffer& p) { return false; } virtual int getErrno() const { return 0; } protected: void setPos(PacketBuffer& p, Pos pos) { p._pos = pos; } void setCurrent(PacketBuffer&p, char* buf, unsigned len) { p._current.first = buf; p._current.second = len; } }; friend class Source; /// A simple Source implementation on top of a fixed buffer. class FixedSource : public Source { public: FixedSource(char const* buf, unsigned size) : _orig(const_cast<char*>(buf), size) {} virtual Value getFirstValue() { return _orig; } virtual void increment(PacketBuffer& p) { // can increment only once: to end. setPos(p, _orig.second); setCurrent(p, 0, 0); } Value _orig; }; /// Constructor. /// @param buf read-only buffer. unowned, does not take ownership /// @param size size of buffer PacketBuffer(char const* buf, int size) : _pos(0) { _source.reset(new FixedSource(buf, size)); _current = _source->getFirstValue(); } /// Construct a PacketBuffer with a specified backend. /// Takes ownership of Source. PacketBuffer(Source* s) : _source(s), _pos(0) { _current = _source->getFirstValue(); } virtual ~PacketBuffer() {} // Dereference const Value& operator*() const { return _current; } const Value* operator->() const { return &_current; } // Increment virtual PacketBuffer& operator++() { _source->increment(*this); return *this; } // Increment, but combine next packet into current buffer. // Result: iterator points at same place in the stream, but // current chunk is bigger. // @return false if could not extend. bool incrementExtend() { return _source->incrementExtend(*this); } // Const accessors: bool isDone() const { return _current.second == 0; } Pos getPos() const { return _pos; } int getErrno() const { return _source->getErrno();} ssize_t getTotalSize() const { return _pos + _current.second; } private: /// Unimplemented. Shouldn't really be comparing. bool operator==(PacketBuffer const& rhs) const; /// Unimplemented. Copying this is not really safe without a lot /// more implementation. PacketBuffer operator++(int); std::unique_ptr<Source> _source; Pos _pos; Value _current; }; }}} // namespace lsst::qserv::util #endif // LSST_QSERV_UTIL_PACKETBUFFER_H
#include <cstdlib> #include <cstdio> #include "library.h" #include "json/json.h" using namespace std; int main(int argc, char* argv[]) { if (argc < 7) { cout << "ERROR: invalid input parameters!" << endl; cout << "Please enter <schema_file> <input_file> <output_file> <mem_capacity> <k> <sorting_attributes>" << endl; exit(1); } // Read in command line arguments string schema_file(argv[1]); char *input_file = argv[2]; char *output_file = argv[3]; long mem_capacity = atol(argv[4]); int k = atoi(argv[5]); string sort_attribute(argv[6]); // assuming a single sort attribute for now // Parse the schema JSON file Json::Value json_schema; Json::Reader json_reader; // Support for std::string argument is added in C++11 // so you don't have to use .c_str() if you are on that. ifstream schema_file_istream(schema_file.c_str(), ifstream::binary); bool successful = json_reader.parse(schema_file_istream, json_schema, false); if (!successful) { cout << "ERROR: " << json_reader.getFormatedErrorMessages() << endl; exit(1); } // Struct to store the schema Schema schema; schema.nattrs = json_schema.size(); schema.attrs = (Attribute*) malloc(sizeof(Attribute) * schema.nattrs); schema.n_sort_attrs = 1; // TODO: change if we end up supporting multiple sort attributes schema.sort_attrs = (int*) malloc(sizeof(int) * schema.n_sort_attrs); // Variables for loading an attribute string attr_name; string attr_type; int attr_len; // Load and print out the schema for (int i = 0; i < json_schema.size(); ++i) { attr_name = json_schema[i].get("name", "UTF-8" ).asString(); attr_len = json_schema[i].get("length", "UTF-8").asInt(); attr_type = json_schema[i].get("type", "UTF-8").asString(); cout << "{name : " << attr_name << ", length : " << attr_len << "}" << endl; // Create an Attribute struct for the current attribute Attribute attribute; attribute.name = (char*) malloc(sizeof(attr_name.c_str())); strcpy(attribute.name, attr_name.c_str()); attribute.type = (char*) malloc(sizeof(attr_type.c_str())); strcpy(attribute.type, attr_type.c_str()); attribute.length = attr_len; attribute.offset = schema.total_record_length; // Add attribute to the schema and increment record length schema.attrs[i] = attribute; schema.total_record_length += attr_len; // If this is a sorting attribute, add it to the list // of sort attributes if (sort_attribute.compare(attr_name) == 0) { schema.sort_attrs[0] = i; } } // k input buffers for merging + 1 output buffer int buf_size = mem_capacity / (k + 1); // The length of a run is measured in # of records and is initially // determined by the size of the buffer and the total length // of a record (+1 for null-terminating character) long run_length = buf_size / (schema.total_record_length + 1); // Helper files for reading and writing runs char* helper = (char*) "helper.txt"; char* helper2 = (char*) "helper2.txt"; // First phase: Make the runs int num_runs = mk_runs(input_file, helper, run_length, &schema); // The number of passes we have to do for the merge is log_k(num_runs) int num_passes = ceil(log(num_runs) / log(k)); cout << "buf_size : " << buf_size << ", run_length : " << run_length << ", num_runs : " << num_runs <<", num_passes : " << num_passes << endl; // Second phase: Do in-memory sort // The attribute to sort on Attribute sort_attr = schema.attrs[schema.sort_attrs[0]]; // Indicates whether the sort attirubte is a numeric value bool is_numeric = (strcmp(sort_attr.type, INTEGER) == 0) || (strcmp(sort_attr.type, FLOAT) == 0); // Struct for comparing records RecordCompare rc {sort_attr.offset, sort_attr.length, is_numeric}; // The number of runs that have been sorted so far on the current pass int runs_sorted = 0; // The number of buffers required for the current merge operation // (This is k, except at the very end of the list of runs) int buffers_needed = k; // The starting position in the input file for the merge operation int merge_start_pos = 0; /** * On a given pass, we read from one file and write to another * (simultaneous reading and writing of the same file doesn't * work here for obvious reasons). The output for the previous * pass becomes the input to the next one. On the final pass, * the output is written to the specified output file. */ char* curr_pass_input = helper; char* curr_pass_output = helper2; char* output_buffer = new char[buf_size]; // Initialize the k input buffers RunIterator* iters[k]; for (int i = 0; i < k; i++) { iters[i] = new RunIterator(buf_size, &schema); } // Repeat for the required number of passes for (int pass = 0; pass < num_passes; pass++) { // If this is the final pass, ensure we're writing to the output file if (pass == num_passes - 1) { curr_pass_output = output_file; } // Do one pass of the sort while (runs_sorted != num_runs) { // The number of runs remaining to be sorted int runs_remaining = num_runs - runs_sorted; // The number of buffers we actually need for the current merge iteration. // This will be < k when we reach the end of the input file. buffers_needed = runs_remaining < k ? runs_remaining : k; // Allocate the buffers needed to merge these runs for (int j = 0; j < buffers_needed; j++) { // The start position for the current run int start_pos = (run_length * (schema.total_record_length + 1)) * runs_sorted; // If this is the start position for the first of the runs, this will // also be the start position for the current merge operation. if (j == 0) { merge_start_pos = start_pos; } // reset the iterator for this run iters[j]->reset(curr_pass_input, start_pos, run_length); // The number of runs that have been sorted so far. runs_sorted++; } // Merge the runs merge_runs(iters, buffers_needed, curr_pass_output, merge_start_pos, buf_size, output_buffer, rc); } // Runs are now at most k times their previous length run_length *= k; // Update the number of runs for the next iteration num_runs = ceil((double) num_runs / k); // Reset the number of sorted runs runs_sorted = 0; // Swap input and output files char* temp = curr_pass_input; curr_pass_input = curr_pass_output; curr_pass_output = temp; } // Free the iterators, the output buffer, and the schema for (int i = 0; i < k; i++) { delete iters[i]; } free(output_buffer); free(schema.attrs); free(schema.sort_attrs); return 0; }
class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { if(!nums.size()) return 0; int maxx = 0, now=nums[0], res=0; for(int i=0;i<nums.size();i++){ if(nums[i]==1) maxx++; else maxx=0; res = max(maxx, res); } return res; } };
#ifndef POPRIGHT_H #define POPRIGHT_H #include <QString> #include <cmath> #include "operation.h" class PopRight : public Operation { public: PopRight(); ~PopRight(void); double compute(const double input) const override; QString toQString() const override; }; #endif // POPRIGHT_H
#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; #define int long long int #define ld long double #define F first #define S second #define P pair<int,int> #define pb push_back #define endl '\n' const int N = 1e5 + 5; vector <int> Graph[N]; bool visited[N] = {false}; vector <int> dis(N), parent(N); void bfs(int src) { queue <int> q; q.push(src); visited[src] = true; parent[src] = -1; while (!q.empty()) { int temp = q.front(); q.pop(); cout << temp << " "; for (int i = 0; i < Graph[temp].size(); i++) { int to = Graph[temp][i]; if (!visited[to]) { q.push(to); visited[to] = true; dis[to] = dis[temp] + 1; parent[to] = temp; } } } cout << endl; } void shortest_path(int des) { if (!visited[des]) { cout << "No Path!!" << endl; } else { vector <int> path; for (int i = des; i != -1; i = parent[i]) { path.pb(i); } reverse(path.begin(), path.end()); cout << "Path : "; for (auto x : path) { cout << x << " "; } cout << endl; } } int connected_comp(int nodes) { int count = 0; for (int i = 1; i <= nodes; i++) { if (visited[i]) continue; bfs(i); count++; } return count; } int32_t main() { ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // code starts //int t;cin>>t;while(t--){} int n, e; cin >> n >> e; for (int i = 0; i < e; i++) { int x, y; cin >> x >> y; Graph[x].pb(y); Graph[y].pb(x); } bfs(1); shortest_path(5); //cout << connected_comp(n) << endl; return 0; }
#include <bits/stdc++.h> using namespace std; int arr[100009],i,N,M,x,p=1,b,saltos,queda,ultimo,pudo; char c; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> N >> M; arr[1] = -1; for(i=0;i<N;i++){ cin >> c; if(c == '0'){ b++; }else{ arr[p] = b+1; p++; b =0; } } arr[1] = -1; if(N == 1){ cout << 0; }else if(N == 2){ cout << 1; }else { i = p-1; queda = M; while(i>=1){ queda-= arr[i]; /// 0 9 if(queda >= 0){ ultimo = i; i--; pudo++; }else { if(pudo){ saltos++; i = ultimo-1; queda = M; pudo = 0; } else { cout << -1 << '\n'; return 0; } } } cout << saltos+1 << '\n'; } /// 2 /// 0 3 /// 4 /// 0 3 2 2 return 0; }
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include "hwlib.h" #include "socal/socal.h" #include "socal/hps.h" #include "socal/alt_gpio.h" #include "hps_0.h" #include "can.hpp" #include <limits.h> #define HW_REGS_BASE ( ALT_STM_OFST ) #define HW_REGS_SPAN ( 0x04000000 ) #define HW_REGS_MASK ( HW_REGS_SPAN - 1 ) int main(int argc, char *argv[]) { void *virtual_base; int fd; int loop_count; int led_direction = 0; int led_mask = 0x01; void *h2p_lw_led_addr, *h2p_lw_can_addr; // map the address space for the LED registers into user space so we can interact with them. // we'll actually map in the entire CSR span of the HPS since we want to access various registers within that span if( ( fd = open( "/dev/mem", ( O_RDWR | O_SYNC ) ) ) == -1 ) { printf( "ERROR: could not open \"/dev/mem\"...\n" ); return( 1 ); } virtual_base = mmap( NULL, HW_REGS_SPAN, ( PROT_READ | PROT_WRITE ), MAP_SHARED, fd, HW_REGS_BASE ); if( virtual_base == MAP_FAILED ) { printf( "ERROR: mmap() failed...\n" ); close( fd ); return( 1 ); } h2p_lw_led_addr=virtual_base + ( ( unsigned long )( ALT_LWFPGASLVS_OFST + LED_PIO_BASE ) & ( unsigned long)( HW_REGS_MASK ) ); h2p_lw_can_addr=virtual_base + ( ( unsigned long )( ALT_LWFPGASLVS_OFST + CAN_0_BASE ) & ( unsigned long)( HW_REGS_MASK ) ); printf("Start CAN operation:\n"); unsigned int temp; read_status(h2p_lw_can_addr); read_mode(h2p_lw_can_addr); // reset_mode(h2p_lw_can_addr); read_interrupt_enable_register(h2p_lw_can_addr); read_acceptance_code_register(h2p_lw_can_addr); read_acceptance_mask_register(h2p_lw_can_addr); // read_status(h2p_lw_can_addr); // // uint8_t can_tx[8]; // can_tx[0]= 0x01; // can_tx[1]= 0x02; // can_tx[2]= 0x03; // can_tx[3]= 0x04; // can_tx[4]= 0x05; // can_tx[5]= 0x06; // can_tx[6]= 0x07; // can_tx[7]= 0x08; //// // send_msg(h2p_lw_can_addr, can_tx, 0x0001, 0x08, 0); // uint8_t status; do { // IOWR(h2p_lw_can_addr,1,1); status = read_status(h2p_lw_can_addr); // if((status&0x40)){ // read_error_capture_register(h2p_lw_can_addr); // reset_mode(h2p_lw_can_addr); // usleep(1000000); // } read_regs_can(h2p_lw_can_addr); usleep(100000); }while(status != 0x4); // send_msg(h2p_lw_can_addr, can_tx, 0x0001, 0x08, 0); // receive_msg(h2p_lw_can_addr, can_tx, 0x0001, 0x08); // // reset_mode(h2p_lw_can_addr); // read_regs_can(h2p_lw_can_addr); // op_mode(h2p_lw_can_addr); // read_regs_can(h2p_lw_can_addr); // // send_msg(h2p_lw_can_addr, can_tx, 0x0001, 0x08, 0); // read_regs_can(h2p_lw_can_addr); // read_status(h2p_lw_can_addr); // unsigned int temp; // int i = 0; // printf("Control Register \n"); // temp = IORD(h2p_lw_can_addr,0x0000); // printf("%u : R %u \n",i,temp); // printf("Goint to OP mode \n"); // IOWR_32DIRECT(h2p_lw_can_addr,0,32); // temp = IORD_32DIRECT(h2p_lw_can_addr,0x0000); // printf("%u : R %u \n",i,temp); // /*printf("Goint to reset mode \n"); // IOWR_32DIRECT(h2p_lw_can_addr,0,32); // temp = IORD_32DIRECT(h2p_lw_can_addr,0x0000); // printf("%u : R %u \n",i,temp); */ // printf("Double check \n"); // temp = IORD(h2p_lw_can_addr,0x0000); // printf("%u : R %u \n",i,temp); // printf("Read Clock Divider Reg \n"); // i=31; // temp = IORD(h2p_lw_can_addr,31); // printf("%u : R %u \n",i,temp); // printf("Set it to extended mode \n"); // IOWR(h2p_lw_can_addr,31,128); // temp = IORD(h2p_lw_can_addr,31); // printf("%u : R %u \n",i,temp); // printf("And back \n"); // IOWR(h2p_lw_can_addr,31,0); // temp = IORD(h2p_lw_can_addr,31); // printf("%u : R %u \n",i,temp); // for(i = 1; i < 32; i++) { // IOWR_32DIRECT(h2p_lw_can_addr,i*4,0); // temp = IORD_32DIRECT(h2p_lw_can_addr,i*4); // printf("%u: R %u \n",i,temp); // } // printf("Goint to reset mode \n"); // IOWR_32DIRECT(h2p_lw_can_addr,0,33); // temp = IORD_32DIRECT(h2p_lw_can_addr,0x0000); // printf("%u : R %u \n",i,temp); // printf("Double check \n"); // temp = IORD(h2p_lw_can_addr,0x0000); // for(i = 1; i < 32; i++) { // IOWR_32DIRECT(h2p_lw_can_addr,i*4,0); // temp = IORD_32DIRECT(h2p_lw_can_addr,i*4); // printf("%u: R %u \n",i,temp); // } // printf("\nDONE"); // clean up our memory mapping and exit if( munmap( virtual_base, HW_REGS_SPAN ) != 0 ) { printf( "ERROR: munmap() failed...\n" ); close( fd ); return( 1 ); } close( fd ); return( 0 ); }
#include <QDebug> // RsaToolbox includes #include "General.h" #include "VnaPowerSweep.h" #include "VnaChannel.h" #include "Vna.h" using namespace RsaToolbox; // Qt includes // #include <Qt> /*! * \class RsaToolbox::VnaPowerSweep * \ingroup VnaGroup * \brief The \c %VnaPowerSweep class * configures and controls a power * sweep with linearly-spaced * measurement points. */ VnaPowerSweep::VnaPowerSweep(QObject *parent) : QObject(parent) { placeholder.reset(new Vna()); _vna = placeholder.data(); _channel.reset(new VnaChannel()); _channelIndex = 0; } VnaPowerSweep::VnaPowerSweep(VnaPowerSweep &other) { if (other.isFullyInitialized()) { _vna = other._vna; _channel.reset(new VnaChannel(*other._channel.data())); _channelIndex = other._channelIndex; } else { placeholder.reset(new Vna()); _vna = placeholder.data(); _channel.reset(new VnaChannel()); _channelIndex = 0; } } VnaPowerSweep::VnaPowerSweep(Vna *vna, VnaChannel *channel, QObject *parent) : QObject(parent) { _vna = vna; _channel.reset(new VnaChannel(*channel)); _channelIndex = channel->index(); } VnaPowerSweep::VnaPowerSweep(Vna *vna, uint index, QObject *parent) : QObject(parent) { _vna = vna; _channel.reset(new VnaChannel(vna, index)); _channelIndex = index; } VnaPowerSweep::~VnaPowerSweep() { } uint VnaPowerSweep::points() { QString scpi = ":SENS%1:SWE:POIN?\n"; scpi = scpi.arg(_channelIndex); return(_vna->query(scpi).trimmed().toUInt()); } void VnaPowerSweep::setPoints(uint numberOfPoints) { QString scpi = ":SENS%1:SWE:POIN %2\n"; scpi = scpi.arg(_channelIndex).arg(numberOfPoints); _vna->write(scpi); } double VnaPowerSweep::start_dBm() { QString scpi = "SOUR%1:POW:STAR?\n"; scpi = scpi.arg(_channelIndex); return(_vna->query(scpi).trimmed().toDouble()); } void VnaPowerSweep::setStart(double power_dBm) { QString scpi = "SOUR%1:POW:STAR %2\n"; scpi = scpi.arg(_channelIndex); scpi = scpi.arg(power_dBm); _vna->write(scpi); } double VnaPowerSweep::stop_dBm() { QString scpi = "SOUR%1:POW:STOP?\n"; scpi = scpi.arg(_channelIndex); return(_vna->query(scpi).trimmed().toDouble()); } void VnaPowerSweep::setStop(double power_dBm) { QString scpi = "SOUR%1:POW:STOP %2\n"; scpi = scpi.arg(_channelIndex); scpi = scpi.arg(power_dBm); _vna->write(scpi); } QVector<double> VnaPowerSweep::powers_dBm() { return(QVector<double>()); } double VnaPowerSweep::frequency_Hz() { QString scpi = ":SOUR%1:FREQ?\n"; scpi = scpi.arg(_channelIndex); return(_vna->query(scpi).trimmed().toDouble()); } void VnaPowerSweep::setFrequency(double frequency, SiPrefix prefix) { QString scpi = ":SOUR%1:FREQ %2%3\n"; scpi = scpi.arg(_channelIndex); scpi = scpi.arg(frequency).arg(toString(prefix, Units::Hertz)); _vna->write(scpi); } double VnaPowerSweep::ifBandwidth_Hz() { QString scpi = "SENS%1:BAND?\n"; scpi = scpi.arg(_channelIndex); return(_vna->query(scpi).trimmed().toDouble()); } void VnaPowerSweep::setIfbandwidth(double bandwidth, SiPrefix prefix) { QString scpi = "SENS%1:BAND %2%3\n"; scpi = scpi.arg(_channelIndex); scpi = scpi.arg(bandwidth); scpi = scpi.arg(toString(prefix, Units::Hertz)); _vna->write(scpi); } bool VnaPowerSweep::isAutoSweepTimeOn() { return _channel->linearSweep().isAutoSweepTimeOn(); } bool VnaPowerSweep::isAutoSweepTimeOff() { return _channel->linearSweep().isAutoSweepTimeOff(); } void VnaPowerSweep::autoSweepTimeOn(bool isOn) { _channel->linearSweep().autoSweepTimeOn(isOn); } void VnaPowerSweep::autoSweepTimeOff(bool isOff) { _channel->linearSweep().autoSweepTimeOff(isOff); } uint VnaPowerSweep::sweepTime_ms() { return _channel->linearSweep().sweepTime_ms(); } void VnaPowerSweep::setSweepTime(uint time_ms) { _channel->linearSweep().setSweepTime(time_ms); } void VnaPowerSweep::operator=(VnaPowerSweep const &other) { if (other.isFullyInitialized()) { _vna = other._vna; _channel.reset(new VnaChannel(*other._channel.data())); _channelIndex = _channel->index(); } else { _vna = placeholder.data(); _channel.reset(new VnaChannel()); _channelIndex = 0; } } //void VnaPowerSweep::moveToThread(QThread *thread) { // QObject::moveToThread(thread); // if (_channel.isNull() == false) // _channel->moveToThread(thread); //} // Private bool VnaPowerSweep::isFullyInitialized() const { if (_vna == NULL) return(false); if (_vna == placeholder.data()) return(false); //else return(true); }
#include "Jogo.h" Jogo::Jogo() { } Jogo::~Jogo() { destroy_bitmap(buffer); // Destrói a imagem; } void Jogo::Inicializar() { buffer = create_bitmap(800, 600); M1.setbuffer(buffer); M1.Inicializar(); /* As funções foram colocardas nesse método "Inicializar", porque, caso colocadas na construtora, causam um erro no programa. Esse erro ocorre porque a Biblioteca Gráfica está sendo inicializada na classe Principal, sendo assim, os objetos agregados nessa classe têm suas construtoras 'lidas' antes da inicialização da biblioteca, portanto o programa não reconhece as funções e ocorre o erro. Desta forma, os objetos são inicializados depois da biblioteca gráfica portanto, não há problemas. */ } void Jogo::Iniciar() { M1.setjogadores(P1, P2); // Associa os jogadores ao Mapa. M1.setmenu(M); // Associa o Menu ao mapa. M1.Entrar(); // 'entra' na área do mapa. (inicia o mapa) } /* Sets */ void Jogo::setjogadores(Jogador* P, Jogador* PP) { P1 = P; P2 = PP; } void Jogo::setmenu(Menu* ME) { M = ME; } /* Gets */ BITMAP* Jogo::getbuffer() { return buffer; }
#pragma once #include "PrimeFinder.h" class Sieve : public PrimeFinder { // Inherited via PrimeFinder virtual std::string name() override; virtual int* find(int min, int max, int* size) override; };
//==================================================================================== // @Title: COMRADE //------------------------------------------------------------------------------------ // @Location: /game/battle/include/cComrade.cpp // @Author: Kevin Chen // @Rights: Copyright(c) 2011 Visionary Games //==================================================================================== #include "../include/cComrade.h" #include "../include/cBattle.h" #include "../../../prolix/common/include/xVector.h" #include "../../../prolix/framework/include/cGame.h" //==================================================================================== // cComrade //==================================================================================== cComrade::cComrade(cBattle *rBattle, cSpriteGroup *rSpriteGroup): cCombatant(rBattle) { health = maxhealth = 100; selected = true; mSpriteGroup = rSpriteGroup; Commands = new cCommandGroup(); Commands->AddCommand(MOVE_LEFT, new cCommand(SDLK_LEFT, 0, true)); Commands->AddCommand(MOVE_RIGHT, new cCommand(SDLK_RIGHT, 0, true)); Commands->AddCommand(MOVE_UP, new cCommand(SDLK_UP, 0, true)); Commands->AddCommand(MOVE_DOWN, new cCommand(SDLK_DOWN, 0, true)); SpriteGroup->AddSprite("fighter", new cSprite("comrade.png", 3, 4)); cSprite *WalkingSprite = SpriteGroup->GetSprite("fighter"); dim = Dimensions( WalkingSprite->spritesheet->dim.w / WalkingSprite->numX, WalkingSprite->spritesheet->dim.h / WalkingSprite->numY); // initialize frameset vector for walking int arr[] = {0,1,2,1}; std::vector<int> frameset = arrayToVector(arr, sizeof(arr)/sizeof(int)); // create walking animations for (unsigned int i=0; i<frameset.size(); frameset[i] = arr[i] + FRONT * WalkingSprite->numX, i++); AnimationGroup->AddAnimation("walking_forward", new cAnimation(WalkingSprite, frameset)); for (unsigned int i=0; i<frameset.size(); frameset[i] = arr[i] + LEFT * WalkingSprite->numX, i++); AnimationGroup->AddAnimation("walking_left", new cAnimation(WalkingSprite, frameset)); for (unsigned int i=0; i<frameset.size(); frameset[i] = arr[i] + RIGHT * WalkingSprite->numX, i++); AnimationGroup->AddAnimation("walking_right", new cAnimation(WalkingSprite, frameset)); for (unsigned int i=0; i<frameset.size(); frameset[i] = arr[i] + BACK * WalkingSprite->numX, i++); AnimationGroup->AddAnimation("walking_backward", new cAnimation(WalkingSprite, frameset)); // initialize frameset vector for idle frameset.clear(); frameset.resize(1); // create idle animations frameset[0] = FRONT * WalkingSprite->numX + 1; AnimationGroup->AddAnimation("idle_front", new cAnimation(WalkingSprite, frameset)); frameset[0] = LEFT * WalkingSprite->numX + 1; AnimationGroup->AddAnimation("idle_left", new cAnimation(WalkingSprite, frameset)); frameset[0] = RIGHT * WalkingSprite->numX + 1; AnimationGroup->AddAnimation("idle_right", new cAnimation(WalkingSprite, frameset)); frameset[0] = BACK * WalkingSprite->numX + 1; AnimationGroup->AddAnimation("idle_back", new cAnimation(WalkingSprite, frameset)); frameset.clear(); coll_rect = PRLX_Rect(Point(motion.pos.x, motion.pos.y), Dimensions(WalkingSprite->spritesheet->dim.w/WalkingSprite->numX, WalkingSprite->spritesheet->dim.h/WalkingSprite->numY)); motion.pos.x = SCREEN_WIDTH/2; motion.pos.y = SCREEN_HEIGHT/2; direction = FRONT; } void cComrade::Draw() { switch (direction) { case FRONT: (motion.vel.y == 0) ? AnimationGroup->GetAnimation("idle_front")->Play(Point(motion.pos.x, motion.pos.y)) : AnimationGroup->GetAnimation("walking_forward")->Play(Point(motion.pos.x, motion.pos.y), 150); break; case LEFT: (motion.vel.x == 0) ? AnimationGroup->GetAnimation("idle_left")->Play(Point(motion.pos.x, motion.pos.y)) : AnimationGroup->GetAnimation("walking_left")->Play(Point(motion.pos.x, motion.pos.y), 150); break; case RIGHT: (motion.vel.x == 0) ? AnimationGroup->GetAnimation("idle_right")->Play(Point(motion.pos.x, motion.pos.y)) : AnimationGroup->GetAnimation("walking_right")->Play(Point(motion.pos.x, motion.pos.y), 150); break; case BACK: (motion.vel.y == 0) ? AnimationGroup->GetAnimation("idle_back")->Play(Point(motion.pos.x, motion.pos.y)) : AnimationGroup->GetAnimation("walking_backward")->Play(Point(motion.pos.x, motion.pos.y), 150); break; default: break; } if (health >= 0) { int xoffset = (int)motion.pos.x - (HealthBar->GetSprite("negative")->spritesheet->dim.w - SpriteGroup->GetSprite("fighter")->spriteset[0].dim.w)/2; int yoffset = (int)motion.pos.y - (HealthBar->GetSprite("negative")->spritesheet->dim.h + 5); HealthBar->GetSprite("negative")->DrawFrame(0, Point(xoffset,yoffset)); for (int frame=xoffset; frame - xoffset< HealthBar->GetSprite("positive")->spritesheet->dim.w * ((float)health/(float)maxhealth); frame++) { HealthBar->GetSprite("positive")->DrawFrame(frame - xoffset, Point(frame * HealthBar->GetSprite("positive")->spriteset[0].dim.w, yoffset)); } } } void cComrade::Move() { float xvel = 1.0f; float yvel = 1.0f; float xfric = 0.18f; float yfric = 0.18f; if (selected) { #pragma region PLAYER KEYBOARD INPUT // check for keyboard input and act accordingly // NOTE: We have support for multi-directional and easing movement to reflect AI fluidity // handle left-movement key if (Commands->GetCommand(MOVE_LEFT)->Pollable()) { direction = LEFT; motion.vel.x = -xvel; } // handle right-movement key else if (Commands->GetCommand(MOVE_RIGHT)->Pollable()) { direction = RIGHT; motion.vel.x = xvel; } else { motion.vel.x = 0; } // handle up-movement key if (Commands->GetCommand(MOVE_UP)->Pollable()) { direction = BACK; motion.vel.y = -yvel; } // handle down-movement key else if (Commands->GetCommand(MOVE_DOWN)->Pollable()) { direction = FRONT; motion.vel.y = yvel; } // disable vertical movement (with easing) else { motion.vel.y = 0; } #pragma endregion } else { #pragma region AI MOVEMENT // do some AI work. #pragma endregion } coll_rect.pos = Point(motion.pos.x, motion.pos.y); // do the physics cEntity::Move(); } void cComrade::Update() { Draw(); Move(); } void cComrade::Select() { selected = true; } cComrade::~cComrade() { LogMgr->Write(INFO, "cComrade::~cComrade >>>> Comrade vanquished"); }
#ifndef _FATFS_H #define _FATFS_H #include "disk.h" #include "integer.h" #define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr)) #define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr)) #define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val) #define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val) class FATFS { public: private: BYTE fs_type; /* FAT sub-type (0:Not mounted) */ BYTE drv; /* Physical drive number */ BYTE csize; /* Sectors per cluster (1,2,4...128) */ BYTE n_fats; /* Number of FAT copies (1 or 2) */ bool wflag; /* win[] flag (b0:dirty) */ BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ WORD id; /* File system mount ID */ WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ DWORD last_clust; /* Last allocated cluster */ DWORD free_clust; /* Number of free clusters */ DWORD n_fatent; /* Number of FAT entries, = number of clusters + 2 */ DWORD fsize; /* Sectors per FAT */ DWORD volbase; /* Volume start sector */ DWORD fatbase; /* FAT start sector */ DWORD dirbase; /* Root directory start sector (FAT32:Cluster#) */ DWORD database; /* Data start sector */ DWORD winsect; /* Current sector appearing in the win[] */ BYTE win[512]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */ bool sync_window() { if (wflag) { if (disk_write(win, winsect, 1)) { wflag = false; return true; } return false; } return true; } bool move_window(DWORD sector) { if (sector != winsect) { if (sync_window()) { if (disk_read(win, sector, 1)) { winsect = sector; return true; } winsect = 0xFFFFFFFF; } return false; } return true; } DWORD clust2sect(DWORD clust) { if (clust >= n_fatent) { return 0; } clust -= 2; return clust*csize + database; } DWORD get_fat(DWORD clust) { if (move_window(fatbase + clust / 512 / 2)) { BYTE * p = &win[clust * 2 / 512]; return LD_WORD(p); } return 0xFFFFFFFF; } bool put_fat(DWORD clust, DWORD val) { if (clust >= 2 && clust < n_fatent) { if (move_window(fatbase + clust / 512 / 2)); { BYTE *p = &win[clust * 2 % 512]; ST_WORD(p, (WORD)val); wflag = true; return true; } } return false; } inline bool remove_chain(DWORD clust); inline DWORD create_chain(DWORD clust); }; #endif /* _FATFS_H */
/******************************************************* cache.cc Ahmad Samih & Yan Solihin 2009 {aasamih,solihin}@ece.ncsu.edu ********************************************************/ #include <stdlib.h> #include <assert.h> #include "cache.h" using namespace std; extern int noProcs; extern CacheMSI *MSIcachesArray[]; extern CacheMESI *MESIcachesArray[]; extern CacheMOESI *MOESIcachesArray[]; Cache::Cache(int s,int a,int b, int id) { ulong i, j; reads = readMisses = writes = 0; writeMisses = writeBacks = currentCycle = 0; selfID = id; size = (ulong)(s); lineSize = (ulong)(b); assoc = (ulong)(a); sets = (ulong)((s/b)/a); numLines = (ulong)(s/b); log2Sets = (ulong)(log2(sets)); log2Blk = (ulong)(log2(b)); //*******************// //initialize your counters here// //*******************// noReads = 0; noReadMiss = 0; noWrites = 0; noWriteMiss = 0; noWriteBack = 0; IToE = 0; IToS = 0; MToS = 0; EToS = 0; SToM = 0; IToM = 0; EToM = 0; OToM = 0; MToO = 0; CCT = 0; noIntervention = 0; noInvalidate = 0; noFlush = 0; tagMask =0; for(i=0;i<log2Sets;i++) { tagMask <<= 1; tagMask |= 1; } /**create a two dimentional cache, sized as cache[sets][assoc]**/ cache = new cacheLine*[sets]; for(i=0; i<sets; i++) { cache[i] = new cacheLine[assoc]; for(j=0; j<assoc; j++) { cache[i][j].invalidate(); } } } /**you might add other parameters to Access() since this function is an entry point to the memory hierarchy (i.e. caches)**/ void Cache::Access(ulong addr,uchar op) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Op = " << op << "\t" << std::hex<<addr << endl; #endif currentCycle++;/*per cache global counter to maintain LRU order among cache ways, updated on every cache access*/ if(op == 'w') writes++; else reads++; cacheLine * line = findLine(addr); if(line == NULL)/*miss*/ { if(op == 'w') writeMisses++; else readMisses++; cacheLine *newline = fillLine(addr); updateStats(newline->getFlags(), MODIFIED); if(op == 'w') newline->setFlags(MODIFIED); } else { /**since it's a hit, update LRU and update dirty flag**/ updateLRU(line); updateStats(line->getFlags(), MODIFIED); if(op == 'w') line->setFlags(MODIFIED); } } /*look up line*/ cacheLine * Cache::findLine(ulong addr) { ulong i, j, tag, pos; pos = assoc; tag = calcTag(addr); i = calcIndex(addr); for(j=0; j<assoc; j++) if(cache[i][j].isValid()) if(cache[i][j].getTag() == tag) { pos = j; break; } if(pos == assoc) return NULL; else return &(cache[i][pos]); } /*upgrade LRU line to be MRU line*/ void Cache::updateLRU(cacheLine *line) { line->setSeq(currentCycle); } /*return an invalid line as LRU, if any, otherwise return LRU line*/ cacheLine * Cache::getLRU(ulong addr) { ulong i, j, victim, min; victim = assoc; min = currentCycle; i = calcIndex(addr); for(j=0;j<assoc;j++) { if(cache[i][j].isValid() == 0) return &(cache[i][j]); } for(j=0;j<assoc;j++) { if(cache[i][j].getSeq() <= min) { victim = j; min = cache[i][j].getSeq();} } assert(victim != assoc); return &(cache[i][victim]); } /*find a victim, move it to MRU position*/ cacheLine *Cache::findLineToReplace(ulong addr) { cacheLine * victim = getLRU(addr); updateLRU(victim); return (victim); } /*allocate a new line*/ cacheLine *Cache::fillLine(ulong addr) { ulong tag; cacheLine *victim = findLineToReplace(addr); assert(victim != 0); if((victim->getFlags() == MODIFIED) || (victim->getFlags() == OWNER)) writeBack(addr); tag = calcTag(addr); victim->setTag(tag); // updateStats(victim->getFlags(), SHARED); // victim->setFlags(SHARED); /**note that this cache line has been already upgraded to MRU in the previous function (findLineToReplace)**/ return victim; } void Cache::printStats() { printf("===== Simulation results (Cache_%d) =====\n",selfID); /****print out the rest of statistics here.****/ /****follow the ouput file format**************/ printf("01. number of reads: %ld\n",reads); printf("02. number of read misses: %ld\n",readMisses); printf("03. number of writes: %ld\n",writes); printf("04. number of write misses: %ld\n",writeMisses); printf("05. number of write backs: %ld\n",writeBacks); printf("06. number of invalid to exclusive (INV->EXC): %d\n",IToE); printf("07. number of invalid to shared (INV->SHD): %d\n",IToS); printf("08. number of modified to shared (MOD->SHD): %d\n",MToS); printf("09. number of exclusive to shared (EXC->SHD): %d\n",EToS); printf("10. number of shared to modified (SHD->MOD): %d\n",SToM); printf("11. number of invalid to modified (INV->MOD): %d\n",IToM); printf("12. number of exclusive to modified (EXC->MOD): %d\n",EToM); printf("13. number of owned to modified (OWN->MOD): %d\n",OToM); printf("14. number of modified to owned (MOD->OWN): %d\n",MToO); printf("15. number of cache to cache transfers: %d\n",CCT); printf("16. number of interventions: %d\n",noIntervention); printf("17. number of invalidations: %d\n",noInvalidate); printf("18. number of flushes: %d\n",noFlush); } void CacheMSI::Access(ulong addr, uchar op, int procNo) { #ifdef DEBUG cout << "Cache id = "<< selfID << op << "\t" << std::hex<<addr << endl; #endif currentCycle++;/*per cache global counter to maintain LRU order among cache ways, updated on every cache access*/ if(op == 'w') writes++; else reads++; cacheLine * line = findLine(addr); if(line == NULL)/*miss*/ { #ifdef DEBUG cout << "Cache id = "<< selfID << "Line miss" <<endl; #endif if(op == 'r') { readMisses++; for(int i = 0; i < noProcs; i++) { if(i != procNo) { MSIcachesArray[i]->BusRd(addr, procNo); } } /* Check if line was obtained as a flush operation from other caches */ if(findLine(addr) == NULL) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Read Op:Line was not present in other caches. Fetching from memory" <<endl; #endif cacheLine *newline = fillLine(addr); updateStats(INVALID, SHARED); newline->setFlags(SHARED); } } else if(op == 'w') { writeMisses++; for(int i = 0; i < noProcs; i++) { if(i != procNo) { MSIcachesArray[i]->BusRdX(addr, procNo); } } /* Check if line was obtained as a flush operation from other caches */ if(findLine(addr) == NULL) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Write Op:Line was not present in other caches. Fetching from memory" <<endl; #endif cacheLine *newline = fillLine(addr); updateStats(INVALID, MODIFIED); newline->setFlags(MODIFIED); } } } else { #ifdef DEBUG cout << "Cache id = "<< selfID << "Cache hit" << endl; #endif /**since it's a hit, update LRU and update dirty flag**/ updateLRU(line); if(op == 'w') { for(int i = 0; i < noProcs; i++) { if(i != procNo) { MSIcachesArray[i]->BusRdX(addr, procNo); } } updateStats(line->getFlags(), MODIFIED); line->setFlags(MODIFIED); } } } void CacheMSI::BusRd(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == MODIFIED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRd, Result: Flush" << endl; #endif MSIcachesArray[procNo]->BusFlushRd(addr); noFlush++; updateStats(line->getFlags(), SHARED); line->setFlags(SHARED); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid/Shared, Snooped Operation: BusRd, Result: Do nothing" << endl; #endif } } void CacheMSI::BusRdX(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == SHARED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRdX, Result: Invalidate" << endl; #endif updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else if(line->getFlags() == MODIFIED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRdX, Result: Flush and Invalidate" << endl; #endif MSIcachesArray[procNo]->BusFlushRdX(addr); noFlush++; updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid, Snooped Operation: BusRdX, Result: Do nothing" << endl; #endif } } void CacheMSI::BusFlushRd(ulong addr) { cacheLine *newline = fillLine(addr); //noFlush++; updateStats(INVALID, SHARED); newline->setFlags(SHARED); } void CacheMSI::BusFlushRdX(ulong addr) { cacheLine *newline = fillLine(addr); //noFlush++; updateStats(INVALID, MODIFIED); newline->setFlags(MODIFIED); } cacheLine *CacheMSI::fillLine(ulong addr) { ulong tag; cacheLine *victim = findLineToReplace(addr); assert(victim != 0); if(victim->getFlags() == MODIFIED) writeBack(addr); tag = calcTag(addr); victim->setTag(tag); // updateStats(INVALID, SHARED); // victim->setFlags(SHARED); /**note that this cache line has been already upgraded to MRU in the previous function (findLineToReplace)**/ return victim; } void CacheMESI::Access(ulong addr, uchar op, int procNo) { #ifdef DEBUG cout << "Cache id = "<< selfID << op << "\t" << std::hex<<addr << endl; #endif currentCycle++;/*per cache global counter to maintain LRU order among cache ways, updated on every cache access*/ if(op == 'w') writes++; else reads++; cacheLine * line = findLine(addr); if((line == NULL) || (line->getFlags() == INVALID))/*miss*/ { #ifdef DEBUG cout << "Cache id = "<< selfID << "Line miss" <<endl; #endif if(op == 'r') { readMisses++; for(int i = 0; i < noProcs; i++) { if(i != procNo) { MESIcachesArray[i]->BusRd(addr, procNo); } } /* Check if line was obtained as a flush operation from other caches */ if(findLine(addr) == NULL) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Read Op:Line was not present in other caches. Fetching from memory" <<endl; #endif cacheLine *newline = fillLine(addr); updateStats(INVALID, EXCLUSIVE); newline->setFlags(EXCLUSIVE); } } else if(op == 'w') { writeMisses++; for(int i = 0; i < noProcs; i++) { if(i != procNo) { MESIcachesArray[i]->BusRdX(addr, procNo); } } /* Check if line was obtained as a flush operation from other caches */ if(findLine(addr) == NULL) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Write Op:Line was not present in other caches. Fetching from memory" <<endl; #endif cacheLine *newline = fillLine(addr); updateStats(INVALID, MODIFIED); newline->setFlags(MODIFIED); } } } else { #ifdef DEBUG cout << "Cache id = "<< selfID << "Cache hit" << endl; #endif /**since it's a hit, update LRU and update dirty flag**/ updateLRU(line); if(line->getFlags() == SHARED) { if(op == 'w') { for(int i = 0; i < noProcs; i++) { if(i != procNo) { MESIcachesArray[i]->BusUpgr(addr, procNo); } } updateStats(line->getFlags(), MODIFIED); line->setFlags(MODIFIED); } } else if(line->getFlags() == EXCLUSIVE) { if(op == 'w') { updateStats(line->getFlags(), MODIFIED); line->setFlags(MODIFIED); } } } } void CacheMESI::BusRd(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == MODIFIED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRd, Result: Flush" << endl; #endif MESIcachesArray[procNo]->BusFlushRd(addr); noFlush++; updateStats(line->getFlags(), SHARED); line->setFlags(SHARED); } else if(line->getFlags() == SHARED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRd, Result: Flush" << endl; #endif MESIcachesArray[procNo]->BusFlushOpt(addr, 'r'); } else if(line->getFlags() == EXCLUSIVE) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Exclusive, Snooped Operation: BusRd, Result: Flush" << endl; #endif MESIcachesArray[procNo]->BusFlushOpt(addr, 'r'); updateStats(line->getFlags(), SHARED); line->setFlags(SHARED); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid/Shared, Snooped Operation: BusRd, Result: Do nothing" << endl; #endif } } void CacheMESI::BusFlushRd(ulong addr) { cacheLine *line = findLine(addr); if((line == NULL) || (line->getFlags() == INVALID)){ cacheLine *newline = fillLine(addr); CCT++; updateStats(INVALID, SHARED); newline->setFlags(SHARED); } } void CacheMESI::BusFlushRdX(ulong addr) { cacheLine *line = findLine(addr); if((line == NULL) || (line->getFlags() == INVALID)){ cacheLine *newline = fillLine(addr); CCT++; updateStats(INVALID, MODIFIED); newline->setFlags(MODIFIED); } } void CacheMESI::BusFlushOpt(ulong addr, char op) { if(op == 'r') BusFlushRd(addr); else BusFlushRdX(addr); } void CacheMESI::BusRdX(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == SHARED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRdX, Result: Invalidate" << endl; #endif MESIcachesArray[procNo]->BusFlushOpt(addr, 'w'); //noFlush++; updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else if(line->getFlags() == MODIFIED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRdX, Result: Flush and Invalidate" << endl; #endif MESIcachesArray[procNo]->BusFlushRdX(addr); noFlush++; updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else if(line->getFlags() == EXCLUSIVE) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRdX, Result: Flush and Invalidate" << endl; #endif MESIcachesArray[procNo]->BusFlushOpt(addr, 'w'); //noFlush++; updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid, Snooped Operation: BusRdX, Result: Do nothing" << endl; #endif } } void CacheMESI::BusUpgr(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == SHARED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRdX, Result: Invalidate" << endl; #endif updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid, Snooped Operation: BusRdX, Result: Do nothing" << endl; #endif } } void CacheMOESI::Access(ulong addr, uchar op, int procNo) { int c = 0; int ret = 0; #ifdef DEBUG cout << "Cache id = "<< selfID << op << "\t" << std::hex<<addr << endl; #endif currentCycle++;/*per cache global counter to maintain LRU order among cache ways, updated on every cache access*/ if(op == 'w') writes++; else reads++; cacheLine * line = findLine(addr); if((line == NULL) || (line->getFlags() == INVALID))/*miss*/ { #ifdef DEBUG cout << "Cache id = "<< selfID << "Line miss" <<endl; #endif if(op == 'r') { readMisses++; for(int i = 0; i < noProcs; i++) { if(i != procNo) { ret = MOESIcachesArray[i]->BusRd(addr, procNo); if(ret == 1) c = 1; } } /* Check if line was obtained as a flush operation from other caches */ if(findLine(addr) == NULL) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Read Op:Line was not present in other caches. Fetching from memory" <<endl; #endif cacheLine *newline = fillLine(addr); if(c != 1){ updateStats(INVALID, EXCLUSIVE); newline->setFlags(EXCLUSIVE); } else{ updateStats(INVALID, SHARED); newline->setFlags(SHARED); } } } else if(op == 'w') { writeMisses++; for(int i = 0; i < noProcs; i++) { if(i != procNo) { MOESIcachesArray[i]->BusRdX(addr, procNo); } } /* Check if line was obtained as a flush operation from other caches */ if(findLine(addr) == NULL) { #ifdef DEBUG cout << "Cache id = "<< selfID << "Write Op:Line was not present in other caches. Fetching from memory" <<endl; #endif cacheLine *newline = fillLine(addr); updateStats(INVALID, MODIFIED); newline->setFlags(MODIFIED); } } } else { #ifdef DEBUG cout << "Cache id = "<< selfID << "Cache hit" << endl; #endif /**since it's a hit, update LRU and update dirty flag**/ updateLRU(line); if(line->getFlags() == SHARED) { if(op == 'w') { for(int i = 0; i < noProcs; i++) { if(i != procNo) { MOESIcachesArray[i]->BusUpgr(addr, procNo); } } updateStats(line->getFlags(), MODIFIED); line->setFlags(MODIFIED); } } else if(line->getFlags() == EXCLUSIVE) { if(op == 'w') { updateStats(line->getFlags(), MODIFIED); line->setFlags(MODIFIED); } } else if(line->getFlags() == OWNER) { if(op == 'w') { for(int i = 0; i < noProcs; i++) { if(i != procNo) { MOESIcachesArray[i]->BusUpgr(addr, procNo); } } updateStats(line->getFlags(), MODIFIED); line->setFlags(MODIFIED); } } } } int CacheMOESI::BusRd(ulong addr, int procNo) { int ret = 0; cacheLine *line = findLine(addr); if(line == NULL){ return ret; } if(line->getFlags() == MODIFIED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRd, Result: Flush" << endl; #endif MOESIcachesArray[procNo]->BusFlushRd(addr); noFlush++; updateStats(line->getFlags(), OWNER); line->setFlags(OWNER); ret = 1; } else if(line->getFlags() == SHARED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRd, Result: Flush" << endl; #endif ret = 1; } else if(line->getFlags() == EXCLUSIVE) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Exclusive, Snooped Operation: BusRd, Result: Flush" << endl; #endif MOESIcachesArray[procNo]->BusFlushOpt(addr, 'r'); //noFlush++; updateStats(line->getFlags(), SHARED); line->setFlags(SHARED); ret = 1; } else if(line->getFlags() == OWNER) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Owner, Snooped Operation: BusRd, Result: Flush" << endl; #endif MOESIcachesArray[procNo]->BusFlushRd(addr); noFlush++; ret = 1; } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid/Shared, Snooped Operation: BusRd, Result: Do nothing" << endl; #endif } return ret; } void CacheMOESI::BusFlushRd(ulong addr) { cacheLine *line = findLine(addr); if((line == NULL) || (line->getFlags() == INVALID)){ cacheLine *newline = fillLine(addr); CCT++; updateStats(INVALID, SHARED); newline->setFlags(SHARED); } } void CacheMOESI::BusFlushRdX(ulong addr) { cacheLine *line = findLine(addr); if((line == NULL) || (line->getFlags() == INVALID)){ cacheLine *newline = fillLine(addr); CCT++; updateStats(INVALID, MODIFIED); newline->setFlags(MODIFIED); } } void CacheMOESI::BusFlushOpt(ulong addr, char op) { if(op == 'r') BusFlushRd(addr); else BusFlushRdX(addr); } void CacheMOESI::BusRdX(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == SHARED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRdX, Result: Invalidate" << endl; #endif updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else if(line->getFlags() == MODIFIED) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRdX, Result: Flush and Invalidate" << endl; #endif MOESIcachesArray[procNo]->BusFlushRdX(addr); noFlush++; updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else if(line->getFlags() == EXCLUSIVE) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Modified, Snooped Operation: BusRdX, Result: Flush and Invalidate" << endl; #endif MOESIcachesArray[procNo]->BusFlushOpt(addr, 'w'); updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else if(line->getFlags() == OWNER) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Owner, Snooped Operation: BusRdX, Result: Flush and Invalidate" << endl; #endif MOESIcachesArray[procNo]->BusFlushRdX(addr); noFlush++; updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid, Snooped Operation: BusRdX, Result: Do nothing" << endl; #endif } } void CacheMOESI::BusUpgr(ulong addr, int procNo) { cacheLine *line = findLine(addr); if(line == NULL){ return; } if(line->getFlags() == SHARED || line->getFlags() == OWNER) { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Shared, Snooped Operation: BusRdX, Result: Invalidate" << endl; #endif updateStats(line->getFlags(), INVALID); line->setFlags(INVALID); } else { #ifdef DEBUG cout << "Cache id = "<< selfID << ":State: Invalid, Snooped Operation: BusRdX, Result: Do nothing" << endl; #endif } }
//--------------------------------------------------------------------------- #ifndef ObjPoolH #define ObjPoolH #include "alist.h" #include <deque> //--------------------------------------------------------------------------- //指针对象 管理池, 支持随机快速存取,支持快速查找空闲对象和释放空闲对象 //特性(设计目标): //基于AList实现指针对象管理,并且使用一个deque来管理已分配和未分配对象 //可以自动释放元素,list保存元素指针以节省内存空间 // 内存分配队列算法 // --------- // Free(T *) | FREE | <----Get() // | |-------- | // | | FREE | | // | |-------- | // | | FREE | | // | |-------- | // | | FREE | | // SetUsed(T *,false) |-------- | T * Data = At(0); //从第一个元素取出 // |push_back() | FREE | | pop_front(); //移除 // | |-------- | SetUsed(T *,true) //置为已经使用 // | | FREE | // |---------------> -------- // //构造时间: 2007.09.21 //作者: Bluely template <class T> class AObjPool { typedef bool (*TCLASS_OPFUNC_IS_USED)(T * Item1); typedef void (*TCLASS_OPFUNC_SET_USED)(T * Item1,bool Used); private: protected: AList<T> * TTable; //元素容器 deque<T *> IndexTable; //元素索引表 , int m_PoolSize; //池最大大小 public: int LastError; public: AObjPool(int PoolSize); //参数指明移除元素的时候,是否自动调用delete释放删除元素 ~AObjPool(); __inline int Count(){return TTable->Count();} //返回元素的总数 __inline int FreeCount(){return IndexTable.size();} //返回未使用元素的总数 bool Add(T *Data); //添加一个元素,如果存在则覆盖他的值,AddToFirst如果为真,那么将会插入到第一个元素 ,为假则插入到最后一个元素 T * At(int Index){return TTable->At(Index);} //根据Index获得一个元素 T * AtFreeQueue(int Index){return IndexTable.at(Index);} //根据索引从空闲队列获得一个元素 T * operator[](int Index){return At(Index);} int IndexOf(T *Data){return TTable->IndexOf(Data);} //根据T获得元素的Index void Clear(); //清空 T * Get(); //从缓冲区里面获取一个空闲的对象 void Free(T * Data); //删除一个元素 bool IsUsed(T * Data) { if (CB_IsUsedFunc) { return CB_IsUsedFunc(Data); } return false; } void SetUsed(T * Data, bool Used) { if(CB_SetUsedFunc) { CB_SetUsedFunc(Data,Used); } } TCLASS_OPFUNC_IS_USED CB_IsUsedFunc; //测试一个元素是否被使用了,需要使用者根据实际情况指定 TCLASS_OPFUNC_SET_USED CB_SetUsedFunc; //设置一个元素的使用标志 ,需要使用者根据实际情况实现 }; //--------------------------------------------------------------------------- template <class T> AObjPool<T>::AObjPool(int PoolSize) { m_PoolSize = PoolSize; if (m_PoolSize <=0) m_PoolSize = 1; TTable = new AList<T>(true,m_PoolSize); LastError = AERR_NOERR; CB_IsUsedFunc=NULL; CB_SetUsedFunc=NULL; } //--------------------------------------------------------------------------- template <class T> AObjPool<T>::~AObjPool() { delete TTable; } //--------------------------------------------------------------------------- template <class T> bool AObjPool<T>::Add(T *Data) { TTable->Add(Data); IndexTable.push_back(Data); //第一次加入的元素默认为空闲内存, SetUsed(Data,false); //设置为空闲未使用 return true; } //--------------------------------------------------------------------------- template <class T> void AObjPool<T>::Clear() { IndexTable.clear(); TTable->Clear(); } //--------------------------------------------------------------------------- template <class T> T * AObjPool<T>::Get() { if (FreeCount()<=0) { return NULL; //没有空闲缓冲区了 } T * Data = IndexTable.at(0); //取出第一个元素 while(IsUsed(Data)) { //此元素已经被用过,按照正常情况不可能放在空闲队列里面,用户有重复Free错误操作导致 IndexTable.pop_front(); //删除第一个元素 Data = IndexTable.at(0); //再次取一个元素 } IndexTable.pop_front(); SetUsed(Data,true); //设置为已经使用 return Data; } //--------------------------------------------------------------------------- template <class T> void AObjPool<T>::Free(T * Data) { if(!IsUsed(Data)) { //标志已经被设置成空闲的,为了防止重复放置,不放到空闲队列 return; } SetUsed(Data,false); IndexTable.push_back(Data); //添加到空闲队列 } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/pi/OpSystemInfo.h" #include "modules/stdlib/util/opdate.h" /* The following definition of UTIME_T is supposed to provide an unsigned version of the 'time_t' type. This is not easy to establish for the 64-bit versions of 'time_t' - so we use the 'time_t' itself in this case. This is OK since a 64-bit 'time_t' is more than large enough to hold the interesting (positive) dates anyway. */ #if STDLIB_SIXTY_FOUR_BIT_TIME_T #define UTIME_T time_t #else #define UTIME_T UINT32 #endif /* Code in this file assumes that a time_t represents a number of seconds since the UNIX EPOCH of 1970-01-01 00:00:00 UTC. */ #define ONE_DAY_SECS ((UTIME_T)(24*60*60)) #define COMMON_YEAR_SECS ((UTIME_T)(365*24*60*60)) #define LEAP_YEAR_SECS ((UTIME_T)(366*24*60*60)) #define FOUR_YEARS_SECS ((UTIME_T)(1461*24*60*60)) #ifndef HAVE_TIME time_t op_time(time_t* pt) { /* This requires that GetTimeUTC() is not implemented in terms of op_time, but then it's probably wrong for porting interfaces to be implemented on top of the op_ functions in most cases, so let's not worry about it. */ time_t t = (g_op_time_info->GetTimeUTC() / 1000.0); if (pt) *pt = t; return t; } #endif #ifndef HAVE_MKTIME /* mktime does two things: creates a time_t value, and adjusts the values of struct tm. */ time_t op_mktime(struct tm* tm) { tm->tm_sec = tm->tm_sec >= 0 && tm->tm_sec <= 60 ? tm->tm_sec : 0; tm->tm_min = tm->tm_min >= 0 && tm->tm_sec <= 59 ? tm->tm_min : 0; tm->tm_hour = tm->tm_hour >= 0 && tm->tm_hour <= 59 ? tm->tm_hour : 0; tm->tm_mday = tm->tm_mday >= 1 && tm->tm_mday <= 31 ? tm->tm_mday : 1; // Will be adjusted later tm->tm_mon = tm->tm_mon >= 0 && tm->tm_mon <= 11 ? tm->tm_mon : 0; tm->tm_year = tm->tm_year >= 0 ? tm->tm_year : 0; tm->tm_isdst = tm->tm_isdst == 0 || tm->tm_isdst == 1 ? tm->tm_isdst : -1; // Will be adjusted later if -1 tm->tm_wday = 0; // Will be set later tm->tm_yday = 0; // Will be set later int tz_hour = 0; int tz_min = 0; // Interpret as in local timezone; correct for zone and for daylight // savings time at the time double tmptime = OpDate::MakeDate(OpDate::MakeDay(tm->tm_year + 1900, tm->tm_mon, tm->tm_mday), OpDate::MakeTime(tm->tm_hour, tm->tm_min, tm->tm_sec, 0)); // If tm_isdst == 0 we do not adjust for DST int tz = op_double2int32(OpDate::LocalTZA() + (tm->tm_isdst != 0 ? OpDate::DaylightSavingTA(tmptime) : 0)); tz_hour = (tz / (int)msPerHour); tz_min = (tz % (int)msPerHour) / (int)msPerMinute; /* Is this enough? What if we pass into the previous day? What if these fields go negative? */ struct tm adjusted = *tm; adjusted.tm_hour -= tz_hour; adjusted.tm_min -= tz_min; double t = OpDate::MakeDate(OpDate::MakeDay(adjusted.tm_year + 1900, adjusted.tm_mon, adjusted.tm_mday), OpDate::MakeTime(adjusted.tm_hour, adjusted.tm_min, adjusted.tm_sec, 0)); tm->tm_wday = OpDate::WeekDay(t); tm->tm_yday = OpDate::DayWithinYear(t); return op_double2uint32(t / msPerSecond); } #endif #ifndef HAVE_GMTIME // // Given a number of days into a year (yday), and info on leap year // status (leap_year), the following function will calculate and // return the month of the given day (range 0-11), and also return // the numbe of days before the start of the month returned (this // can be used to further calculate the day of the month etc.) // static int find_month(int yday, BOOL leap_year, int &prior_days) { int month; // The month to be returned int work_yday = yday; // Modify this as we go int march; int mp; OP_ASSERT(yday >= 0); OP_ASSERT(yday < (leap_year ? 366 : 365)); // Check for January if ( yday < 31 ) { month = 0; // We return 0 for January, like gmtime() goto done; } // Find the day when march starts march = 59; if ( leap_year ) march++; // Check for February if ( yday < march ) { // February month = 1; work_yday -= 31; // Subtract January goto done; } // Realign and make work_yday == 0 become the 1st of March and continue month = 2; work_yday -= march; // The remaining months March-December have days like this: // 31,30,31,30,31 and 31,30,31,30,31 // Notice the repeating pattern; we can fold the upper block // Starting at 1st of August down into the lower one: // (153 is the number of days between 1st of March and 1st of August) if ( work_yday >= 153 ) { work_yday -= 153; month += 5; } // Notice how the remaining months March to July have alternating // 31 and 30 days: We can exploit this and first do "months pairs" // of 31+30 days: mp = work_yday / 61; // Number of "month pairs": 0, 1 or 2 only month += (2*mp); work_yday -= (mp*61); // What possibly remains is the first half of a "month pair": if ( work_yday >= 31 ) { month++; work_yday -= 31; } done: prior_days = yday - work_yday; return month; } #ifndef STDLIB_UNSIGNED_TIME_T // // The type 'time_t' is signed, so we bias it so the original time_t value // of zero (The UNIX epoc - 1970-01-01 00:00:00) will be represented as an // unsigned and biased value of 0x80000000. // #define BIASED_TIME_T_VALUE 0x80000000 // // A bias value of 0x80000000 means that we will have e.g. the following // relationships between biased_time and signed time_t: // // Date biased_time time_t value // -------------------------------------------------------------- // 1901-12-13 20:45:52 0x0000000000 -2147483648 (-2^31) // 1901-12-14 00:00:00 0x0000002d80 -2147472000 (first whole day) // 1902-01-01 00:00:00 0x000017e880 -2145916800 (first whole year) // 1904-01-01 00:00:00 0x0003da4f80 -2082844800 (first leap year) // 1968-09-09 12:15:00 0x007d892dc4 -41341500 // 1969-12-31 23:59:59 0x007fffffff -1 // 1970-01-01 00:00:00 0x0080000000 0 // 1972-01-01 00:00:00 0x0083c26700 63072000 // 2000-01-01 00:00:00 0x00b86d4380 946684800 // 2008-08-08 08:08:08 0x00c89bfee8 1218182888 // 2038-01-19 03:14:07 0x00ffffffff 2147483647 (2^31-1) // 2100-01-01 00:00:00 0x0174865700 4102444800 // 2106-02-07 06:28:15 0x017fffffff 4294967295 (2^32-1) // 9999-12-31 23:59:59 0x3b7ff4417f 253402300799 // // This arrengement will make it easier to deal with leap years, // undefined modulo operations etc. for negative time_t values. // // // This defines the biased date of the year 2000. This is used to // calculate the leap-year exceptions that repeat every 400 years. // #define BIASED_YEAR_2000_SECS (UTIME_T)0xb86d4380 // // This define is the very last second in a "sensible" date, that of // 9999-12-31 23:59:59 which is the last one with a 4-digit year. // #define BIASED_VERY_LAST_SECOND (UTIME_T)0x3b7ff4417f #else // STDLIB_UNSIGNED_TIME_T // // The 'time_t' datatype is unsigned. This means that no dates prior to // 1970-01-01 00:00:00 can be represented and time_t can't be used to // hold a negative time-difference, but on the other hand, dates up to // 2106-02-07 06:28:15 can be held in a 32-bit variable (On systems // with a signed time_t, the maximum date is 2038-01-19 03:14:07). // #define BIASED_TIME_T_VALUE (UTIME_T)0 #define BIASED_YEAR_2000_SECS (UTIME_T)946684800 #define BIASED_VERY_LAST_SECOND (UTIME_T)253402300799 #endif // STDLIB_UNSIGNED_TIME_T #define FOUR_CENTURIES_DAYS (97*366 + 303*365) #define FOUR_CENTURIES_SECS (UTIME_T)(ONE_DAY_SECS * FOUR_CENTURIES_DAYS) #define BIASED_YEAR_1904_SECS (UTIME_T)0x03da4f80 #define YEAR_1972_SECS (UTIME_T)63072000 struct tm* op_gmtime(const time_t *timer) { time_t time = *timer; // // Verify that our predicted size of 'time_t' is correct. If it is not // correct, we will not be able to reproduce the dates of the system, // and possibly make incorrect computations if 'time_t' is 32-bits when // we think it is 64-bit. // #if STDLIB_SIXTY_FOUR_BIT_TIME_T OP_STATIC_ASSERT(sizeof(time_t) == 8); #else OP_STATIC_ASSERT(sizeof(time_t) == 4); #endif UTIME_T biased_time = time + BIASED_TIME_T_VALUE; // // Make sure we return NULL if the 'time_t' value is spectacularly // outside the range that we support, which is: // // 1901-12-13 20:45:52 ==> 2038-01-19 03:14:07 (32-bit signed time_t) // 1901-12-13 20:45:52 ==> 9999-12-31 23:59:59 (64-bit signed time_t) // 1970-01-01 00:00:00 ==> 2106-02-07 06:28:15 (32-bit unsigned time_t) // 1970-01-01 00:00:00 ==> 9999-12-31 23:59:59 (64-bit unsigned time_t) // #if STDLIB_SIXTY_FOUR_BIT_TIME_T # ifndef STDLIB_UNSIGNED_TIME_T // Make sure we don't go earlier than 1901-12-13 20:45:52 if ( biased_time < 0 ) return 0; # endif // Make sure we don't go past 9999-12-31 23:59:59 if ( biased_time > BIASED_VERY_LAST_SECOND ) return 0; #endif int base_year; int base_wday; int days; int wday; int sec; BOOL leap_year; #if STDLIB_SIXTY_FOUR_BIT_TIME_T // // We can do multiple centuries, so we need to take the leap year // rules of 100 and 400 years into account. First map all 400 // year blocks into a block starting at some year: // if ( biased_time < BIASED_YEAR_2000_SECS ) { base_year = 1600; base_wday = 6; // FIXME: Don't know biased_time += (FOUR_CENTURIES_SECS - BIASED_YEAR_2000_SECS); } else { base_year = 2000; base_wday = 6; biased_time -= BIASED_YEAR_2000_SECS; } days = (int)(biased_time / ONE_DAY_SECS); wday = (base_wday + days) % 7; int qcent = (int)(days / FOUR_CENTURIES_DAYS); biased_time -= qcent * FOUR_CENTURIES_SECS; days -= qcent * FOUR_CENTURIES_DAYS; if ( days < 366 ) { // This is the first year of a quad-century; it is a leap year. leap_year = TRUE; } else { days--; // Compensate for the leap year first in the quad-century int cent = days / (365*76 + 366*24); base_year += cent * 100; days -= cent * (365*76 + 366*24); if ( days < 365 ) { // This is the first year of a century; it is not a leap year. leap_year = FALSE; } else { days++; // Compensate for missing leap year first in every century int quad = days / (365*3 + 366); base_year += quad * 4; days -= quad * (365*3 + 366); if ( days < 366 ) { // First year in every four year cycle; it is a leap year leap_year = TRUE; } else { days--; // Compensate for leap year first in four year cycle int y = days / 365; base_year += y; days -= y * 365; leap_year = FALSE; } } } #else // STDLIB_SIXTY_FOUR_BIT_TIME_T // // Provide the 32-bit version(s) here. All 32-bit numbers will // represent valid dates. Signed/unsigned will determine the // range of dates that 'time_t' represents. // #ifdef STDLIB_UNSIGNED_TIME_T // // For unsigned 32-bit support, we have to handle 2100 specially; it // is not a leap year (but 2000 is). // if ( biased_time < YEAR_1972_SECS ) { // Fold 1970 and 1971 into 1974 and 1975 to base_year = 1968; base_wday = 1; biased_time += (FOUR_YEARS_SECS - YEAR_1972_SECS); } else { base_year = 1972; base_wday = 6; biased_time -= YEAR_1972_SECS; } days = biased_time / ONE_DAY_SECS; wday = (days + base_wday) % 7; // // Check for the year 2100 - which is not a leap year // if ( days >= 46752 ) { // 2100-01-01 or later if ( days < 47117 ) { // 2100-12-31 or earlier: Fake it so it doesn't become a leap year days += 366; base_year--; } else { // Adjust so years 2101 and up are correct days++; } } #else // STDLIB_UNSIGNED_TIME_T // // 32-bit signed time_t will not need any special rules for leap year // calculation, so we just fold years 1-3 into years 5-7. // if ( biased_time < BIASED_YEAR_1904_SECS ) { base_year = 1900; base_wday = 0; // FIXME biased_time += (FOUR_YEARS_SECS - BIASED_YEAR_1904_SECS); } else { base_year = 1904; base_wday = 5; // FIXME biased_time -= BIASED_YEAR_1904_SECS; } days = biased_time / ONE_DAY_SECS; wday = (days + base_wday) % 7; #endif // STDLIB_UNSIGNED_TIME_T // // At this point, assume the year is aligned so year+0 is a leap year, // while year+1..year+3 are not. // int quad = days / (365*3 + 366); base_year += quad * 4; days -= quad * (365*3 + 366); if ( days < 366 ) { // First year in every four year cycle; it is a leap year leap_year = TRUE; } else { days--; int y = days / 365; base_year += y; days -= y * 365; leap_year = FALSE; } #endif // STDLIB_SIXTY_FOUR_BIT_TIME_T struct tm* r = &g_opera->stdlib_module.m_gmtime_result; int prior_days; r->tm_mon = find_month(days, leap_year, prior_days); r->tm_mday = days - prior_days + 1; r->tm_wday = wday; r->tm_yday = days; r->tm_year = base_year - 1900; sec = (int)(biased_time % ONE_DAY_SECS); r->tm_hour = sec / 3600; r->tm_min = (sec - r->tm_hour*3600) / 60; r->tm_sec = sec % 60; r->tm_isdst = 0; return r; } #endif // !HAVE_GMTIME #ifndef HAVE_LOCALTIME struct tm* op_localtime(const time_t *time_p) { /* This will cause a loop if either OpSystemInfo::GetTimezone() or * ::DaylightSavingsTimeAdjustmentMS() is implemented using * op_localtime(). */ time_t adjusted_time = *time_p // subtract current time zone - g_op_time_info->GetTimezone() // add daylight saving relevant for target date + static_cast<time_t>(g_op_time_info->DaylightSavingsTimeAdjustmentMS(static_cast<double>(*time_p) * 1000.0) / 1000.0) // subtract current daylight saving - static_cast<time_t>(g_op_time_info->DaylightSavingsTimeAdjustmentMS(static_cast<double>(op_time(NULL)) * 1000.0) / 1000.0); return op_gmtime(&adjusted_time); } #endif // !HAVE_LOCALTIME
// includes, system #include <algorithm> #include <cassert> #include <cmath> // includes, project #include "distribution.h" using namespace std; red_random::red_random(uint32_t seed) : idx(0) { I[ 0] = seed & 0xffffffff; for(int i = 1; i < 624; ++i) { I[i] = (1812433253*(I[i-1]^I[i-1]>>30)+i)&0xffffffff; } } red_random::~red_random() { } uint32_t red_random::rand() { uint32_t j = (idx < 623) ? (idx + 1) : 0; uint32_t y = I[idx]&0x80000000 | I[j]&0x7fffffff; y = I[idx] = I[idx < 227 ? idx + 397 : idx-227]^y>>1^(y&1)*0x9908b0df; idx = j; return y^(y^=(y^=(y^=y>>11)<<7&0x9d2c5680)<<15&0xefc60000)>>18; } var_t red_random::uniform() { return ((rand() + 1.0) / 4294967296.0); } var_t red_random::uniform(var_t x_min, var_t x_max) { return (x_min + (x_max - x_min)*(rand() + 1.0) / 4294967296.0); } int red_random::uniform(int x_min, int x_max) { return (x_min + (uint32_t)(rand()/4294967296.*(x_max - x_min + 1))); } distribution_base::distribution_base(uint32_t seed, var_t x_min, var_t x_max) : rr(seed), x_min(x_min), x_max(x_max) { assert(x_min <= x_max); } distribution_base::~distribution_base() { } uniform_distribution::uniform_distribution(uint32_t seed) : distribution_base(seed, 0.0, 1.0) { } uniform_distribution::uniform_distribution(uint32_t seed, var_t x_min, var_t x_max) : distribution_base(seed, x_min, x_max) { } uniform_distribution::~uniform_distribution() { } var_t uniform_distribution::get_next() { var_t u = rr.uniform(x_min, x_max); return u; } exponential_distribution::exponential_distribution(uint32_t seed, var_t lambda) : distribution_base(seed, 0.0, 1.0), lambda(lambda) { assert(lambda > 0.0); } exponential_distribution::~exponential_distribution() { } var_t exponential_distribution::get_next() { var_t u = rr.uniform(); return (-1.0 / lambda * log(u)); } rayleigh_distribution::rayleigh_distribution(uint32_t seed, var_t sigma) : distribution_base(seed, 0.0, 1.0), sigma(sigma) { assert(sigma > 0.0); } rayleigh_distribution::~rayleigh_distribution() { } var_t rayleigh_distribution::get_next() { var_t u = rr.uniform(); return (sigma * sqrt(-2.0 * log(u))); } normal_distribution::normal_distribution(uint32_t seed, var_t mean, var_t variance) : distribution_base(seed, 0.0, 1.0), mean(mean), variance(variance) { assert(variance > 0.0); } normal_distribution::~normal_distribution() { } var_t normal_distribution::get_next() { var_t u = rr.uniform(); return (mean + variance*sqrt(-2.0*log(u)) * cos(1.4629180792671596E-9*(rr.rand() + 1.0))); } power_law_distribution::power_law_distribution(uint32_t seed, var_t x_min, var_t x_max, var_t power): distribution_base(seed, x_min, x_max), power(power) { assert(x_min != 0.0); assert(x_max != 0.0); } power_law_distribution::~power_law_distribution() { } var_t power_law_distribution::get_next() { var_t y_min = power == 0.0 ? 0.0 : pow(x_min, power); var_t y_max = power == 0.0 ? 1.0 : pow(x_max, power); if (y_min > y_max) { swap(y_min, y_max); } var_t d_y = y_max - y_min; var_t d_x = x_max - x_min; var_t x, y; var_t area_max = d_x * d_y; do { x = rr.uniform(0.0, area_max) / d_y + x_min; y = rr.uniform(y_min, y_max); } while (y > pow(x, power)); return x; } lognormal_distribution::lognormal_distribution(uint32_t seed, var_t x_min, var_t x_max, var_t mu, var_t sigma) : distribution_base(seed, x_min, x_max), mu(mu), sigma(sigma) { assert(x_min > 0.0); assert(sigma > 0.0); } lognormal_distribution::~lognormal_distribution() { } var_t lognormal_distribution::get_next() { var_t y_min = 0.0; var_t max_loc = exp(mu - SQR(sigma)); var_t y_max = pdf(max_loc); if (y_min > y_max) { swap(y_min, y_max); } var_t d_y = y_max - y_min; var_t d_x = x_max - x_min; var_t x, y; var_t area_max = d_x * d_y; do { x = rr.uniform(0.0, area_max) / d_y + x_min; y = rr.uniform(y_min, y_max); } while (y > pdf(x)); return x; } var_t lognormal_distribution::pdf(var_t x) { return (1.0/(sqrt(2.0*PI)*sigma * x) * exp( -SQR(log(x) - mu) / (2.0 * SQR(sigma))) ); }
/** * File Matrix.cpp * Description: implementation of Matrix class * */ #include "Matrix.hpp" // construct an identity matrix as mat Matrix::Matrix() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) this->mat[i][j] = 1; else this->mat[i][j] = 0; } } } // multiplication mat <- m * mat void Matrix::matrix_pre_multiply(Matrix* m) { Matrix* temp = new Matrix(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { GLfloat sum = 0; for (int k = 0; k < 4; k++) { sum += m->mat[i][k] * this->mat[k][j]; } temp->mat[i][j] = sum; } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { this->mat[i][j] = temp->mat[i][j]; } } delete temp; } // translate the origin of MC void Matrix::translate(GLfloat tx, GLfloat ty, GLfloat tz) { this->mat[0][3] += tx; this->mat[1][3] += ty; this->mat[2][3] += tz; this->mat[3][3] = 1; } void Matrix::transpose() { GLfloat tmp; for (int i = 0; i < 4; i++) { for (int j = i + 1; j < 4; j++) { tmp = mat[i][j]; mat[i][j] = mat[j][i]; mat[j][i] = tmp; } } } // normalize MC void Matrix::normalize() { GLfloat vectLen = sqrt(mat[0][0] * mat[0][0] + mat[1][0] * mat[1][0] + mat[2][0] * mat[2][0]); //normalize first 3 mat[0][0] /= vectLen; mat[1][0] /= vectLen; mat[2][0] /= vectLen; //take determinants for first 3 values in col 2 mat[0][2] = mat[1][0] * mat[2][1] - mat[2][0] * mat[1][1]; mat[1][2] = mat[2][0] * mat[0][1] - mat[0][0] * mat[2][1]; mat[2][2] = mat[0][0] * mat[1][1] - mat[1][0] * mat[0][1]; vectLen = sqrt(mat[0][2] * mat[0][2] + mat[1][2] * mat[1][2] + mat[2][2] * mat[2][2]); // normalize first 3 in column 2 mat[0][2] /= vectLen; mat[1][2] /= vectLen; mat[2][2] /= vectLen; //set fisrt 3 in column 1 to the determinants calcululated from column 0 and column 2 mat[0][1] = mat[1][2] * mat[2][0] - mat[1][0] * mat[2][2]; mat[1][1] = mat[2][2] * mat[0][0] - mat[2][0] * mat[0][2]; mat[2][1] = mat[0][2] * mat[1][0] - mat[0][0] * mat[1][2]; //reset column 3 mat[3][0] = 0; mat[3][1] = 0; mat[3][2] = 0; mat[3][3] = 1; } // v <- mat * v. V must have 4 elements void Matrix::multiply_vector(GLfloat* v) { double sum, temp[4]; for (int i = 0; i < 4; i++) { sum = 0; for (int j = 0; j < 4; j++) { sum += v[j] * this->mat[j][i]; } temp[i] = sum; } for (int i = 0; i < 4; i++) { v[i] = temp[i]; } } // MC <= rotation matrix * MC, i.e., rotate cordinate vectors and the origin void Matrix::rotate(GLfloat x, GLfloat y, GLfloat z, GLfloat angle) { GLfloat radAngle = angle * 3.1415926 / 180; GLfloat vectLen = sqrt(x * x + y * y + z * z); GLfloat cosA = cos(radAngle); GLfloat sinA = sin(radAngle); GLfloat ux = x / vectLen, uy = y / vectLen, uz = z / vectLen; Matrix r; // rotation matrix to be multiplied as this*r r.mat[0][0] = ux * ux * (1 - cosA) + cosA; r.mat[0][1] = ux * uy * (1 - cosA) - uz * sinA; r.mat[0][2] = ux * uz * (1 - cosA) + uy * sinA; r.mat[1][0] = uy * ux * (1 - cosA) + uz * sinA; r.mat[1][1] = uy * uy * (1 - cosA) + cosA; r.mat[1][2] = uy * uz * (1 - cosA) - ux * sinA; r.mat[2][0] = uz * ux * (1 - cosA) - uy * sinA; r.mat[2][1] = uz * uy * (1 - cosA) + ux * sinA; r.mat[2][2] = uz * uz * (1 - cosA) + cosA; matrix_pre_multiply(&r); } void Matrix::printMatrix() { std::cout << "Matrix:" << std::endl; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { std::cout << mat[i][j] << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } Vector Matrix::getPosVect() { Vector v; v.x = mat[0][3]; v.y = mat[1][3]; v.z = mat[2][3]; return v; } void Matrix::copy(Matrix from) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { mat[i][j] = from.mat[i][j]; } } } void Matrix::ctm_multiply(){ GLfloat M[16]; M[0] = mat[0][0]; M[1] = mat[1][0]; M[2] = mat[2][0]; M[3] = 0; M[4] = mat[0][1]; M[5] = mat[1][1]; M[6] = mat[2][1]; M[7] = 0; M[8] = mat[0][2]; M[9] = mat[1][2]; M[10] = mat[2][2]; M[11] = 0; M[12] = mat[0][3]; M[13] = mat[1][3]; M[14] = mat[2][3]; M[15] = 1; glMultMatrixf(M); }
#include "PrecisionRecall.h" using namespace std; static void computePrecisionRecallForThreshold(const vector<float> &gt, const vector<float>& preds, float threshold, int nGroundTruthDetections, float& precision, float& recall) { // Compute tp, fp, fn, tn int truePos = 0, trueNeg = 0, falsePos = 0, falseNeg = 0; for(int i = 0; i < preds.size(); i++) { if(preds[i] > threshold) { if(gt[i] > 0) truePos++; else falsePos++; } else if(preds[i] <= threshold) { if(gt[i] < 0) trueNeg++; else falseNeg++; } } if(truePos + falsePos == 0) precision = 1.0; else precision = float(truePos) / (truePos + falsePos); int nGt = (nGroundTruthDetections >= 0)? nGroundTruthDetections:(truePos + falseNeg); if(truePos + falseNeg == 0) recall = 1.0; else recall = float(truePos) / nGt; } bool sortByRecall(const PrecisionRecallPoint& a, const PrecisionRecallPoint& b) { return a.recall < b.recall; } PrecisionRecall::PrecisionRecall(const std::vector<float> &gt, const std::vector<float>& preds, int nGroundTruthDetections) { std::set<float> thresholds; for (int i = 0; i < preds.size(); ++i) { thresholds.insert(preds[i]); } _data.resize(0); for(std::set<float>::iterator th = thresholds.begin(); th != thresholds.end(); th++) { PrecisionRecallPoint pr; computePrecisionRecallForThreshold(gt, preds, *th, nGroundTruthDetections, pr.precision, pr.recall); pr.threshold = *th; _data.push_back(pr); } std::sort(_data.begin(), _data.end(), sortByRecall); // Remove jags in precision recall curve float maxPrecision = -1; for(std::vector<PrecisionRecallPoint>::reverse_iterator pr = _data.rbegin(); pr != _data.rend(); pr++) { pr->precision = max(maxPrecision, pr->precision); maxPrecision = max(pr->precision, maxPrecision); } // Compute average precision as area under the curve _averagePrecision = 0.0; for(std::vector<PrecisionRecallPoint>::iterator pr = _data.begin() + 1, prPrev = _data.begin(); pr != _data.end(); pr++, prPrev++) { float xdiff = pr->recall - prPrev->recall; float ydiff = pr->precision - prPrev->precision; _averagePrecision += xdiff * prPrev->precision + xdiff * ydiff / 2.0; } } void PrecisionRecall::save(const char* filename) const { std::ofstream f(filename); if(f.bad()) throw std::runtime_error("ERROR: Could not open file for writing"); f << "# precision recall threshold\n"; for(std::vector<PrecisionRecallPoint>::const_iterator pr = _data.begin(); pr != _data.end(); pr++) { f << pr->precision << " " << pr->recall << " " << pr->threshold << "\n"; } } double PrecisionRecall::getBestThreshold() const { double bestFMeasure = -1, bestThreshold = -1; for(std::vector<PrecisionRecallPoint>::const_iterator pr = _data.begin(); pr != _data.end(); pr++) { double fMeasure = (pr->precision * pr->recall) / (pr->precision + pr->recall); if(fMeasure > bestFMeasure) { bestFMeasure = fMeasure; bestThreshold = pr->threshold; } } return bestThreshold; }
// Created on: 1993-01-09 // Created by: CKY / Contract Toubro-Larsen ( Kiran ) // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESGeom_BSplineSurface_HeaderFile #define _IGESGeom_BSplineSurface_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <TColStd_HArray1OfReal.hxx> #include <TColStd_HArray2OfReal.hxx> #include <TColgp_HArray2OfXYZ.hxx> #include <IGESData_IGESEntity.hxx> class gp_Pnt; class IGESGeom_BSplineSurface; DEFINE_STANDARD_HANDLE(IGESGeom_BSplineSurface, IGESData_IGESEntity) //! defines IGESBSplineSurface, Type <128> Form <0-9> //! in package IGESGeom //! A parametric equation obtained by dividing two summations //! involving weights (which are real numbers), the control //! points, and B-Spline basis functions class IGESGeom_BSplineSurface : public IGESData_IGESEntity { public: Standard_EXPORT IGESGeom_BSplineSurface(); //! This method is used to set the fields of the class //! BSplineSurface //! - anIndexU : Upper index of first sum //! - anIndexV : Upper index of second sum //! - aDegU, aDegV : Degrees of first and second sets //! of basis functions //! - aCloseU, aCloseV : 1 = Closed in U, V directions //! 0 = open in U, V directions //! - aPolynom : 0 = Rational, 1 = polynomial //! - aPeriodU, aPeriodV : 0 = Non periodic in U or V direction //! 1 = Periodic in U or V direction //! - allKnotsU, allKnotsV : Knots in U and V directions //! - allWeights : Array of weights //! - allPoles : XYZ coordinates of all control points //! - aUmin : Starting value of U direction //! - aUmax : Ending value of U direction //! - aVmin : Starting value of V direction //! - aVmax : Ending value of V direction //! raises exception if allWeights & allPoles are not of same size. Standard_EXPORT void Init (const Standard_Integer anIndexU, const Standard_Integer anIndexV, const Standard_Integer aDegU, const Standard_Integer aDegV, const Standard_Boolean aCloseU, const Standard_Boolean aCloseV, const Standard_Boolean aPolynom, const Standard_Boolean aPeriodU, const Standard_Boolean aPeriodV, const Handle(TColStd_HArray1OfReal)& allKnotsU, const Handle(TColStd_HArray1OfReal)& allKnotsV, const Handle(TColStd_HArray2OfReal)& allWeights, const Handle(TColgp_HArray2OfXYZ)& allPoles, const Standard_Real aUmin, const Standard_Real aUmax, const Standard_Real aVmin, const Standard_Real aVmax); //! Changes FormNumber (indicates the Shape of the Surface) //! Error if not in range [0-9] Standard_EXPORT void SetFormNumber (const Standard_Integer form); //! returns the upper index of the first sum (U) Standard_EXPORT Standard_Integer UpperIndexU() const; //! returns the upper index of the second sum (V) Standard_EXPORT Standard_Integer UpperIndexV() const; //! returns degree of first set of basis functions Standard_EXPORT Standard_Integer DegreeU() const; //! returns degree of second set of basis functions Standard_EXPORT Standard_Integer DegreeV() const; //! True if closed in U direction else False Standard_EXPORT Standard_Boolean IsClosedU() const; //! True if closed in V direction else False Standard_EXPORT Standard_Boolean IsClosedV() const; //! True if polynomial, False if rational //! <flag> False (D) : computed from Weights //! <flag> True : recorded Standard_EXPORT Standard_Boolean IsPolynomial (const Standard_Boolean flag = Standard_False) const; //! True if periodic in U direction else False Standard_EXPORT Standard_Boolean IsPeriodicU() const; //! True if periodic in V direction else False Standard_EXPORT Standard_Boolean IsPeriodicV() const; //! returns number of knots in U direction //! KnotsU are numbered from -DegreeU Standard_EXPORT Standard_Integer NbKnotsU() const; //! returns number of knots in V direction //! KnotsV are numbered from -DegreeV Standard_EXPORT Standard_Integer NbKnotsV() const; //! returns the value of knot referred to by anIndex in U direction //! raises exception if //! anIndex < -DegreeU() or anIndex > (NbKnotsU() - DegreeU()) Standard_EXPORT Standard_Real KnotU (const Standard_Integer anIndex) const; //! returns the value of knot referred to by anIndex in V direction //! raises exception if //! anIndex < -DegreeV() or anIndex > (NbKnotsV() - DegreeV()) Standard_EXPORT Standard_Real KnotV (const Standard_Integer anIndex) const; //! returns number of poles in U direction Standard_EXPORT Standard_Integer NbPolesU() const; //! returns number of poles in V direction Standard_EXPORT Standard_Integer NbPolesV() const; //! returns the weight referred to by anIndex1, anIndex2 //! raises exception if anIndex1 <= 0 or anIndex1 > NbPolesU() //! or if anIndex2 <= 0 or anIndex2 > NbPolesV() Standard_EXPORT Standard_Real Weight (const Standard_Integer anIndex1, const Standard_Integer anIndex2) const; //! returns the control point referenced by anIndex1, anIndex2 //! raises exception if anIndex1 <= 0 or anIndex1 > NbPolesU() //! or if anIndex2 <= 0 or anIndex2 > NbPolesV() Standard_EXPORT gp_Pnt Pole (const Standard_Integer anIndex1, const Standard_Integer anIndex2) const; //! returns the control point referenced by anIndex1, anIndex2 //! after applying the Transf.Matrix //! raises exception if anIndex1 <= 0 or anIndex1 > NbPolesU() //! or if anIndex2 <= 0 or anIndex2 > NbPolesV() Standard_EXPORT gp_Pnt TransformedPole (const Standard_Integer anIndex1, const Standard_Integer anIndex2) const; //! returns starting value in the U direction Standard_EXPORT Standard_Real UMin() const; //! returns ending value in the U direction Standard_EXPORT Standard_Real UMax() const; //! returns starting value in the V direction Standard_EXPORT Standard_Real VMin() const; //! returns ending value in the V direction Standard_EXPORT Standard_Real VMax() const; DEFINE_STANDARD_RTTIEXT(IGESGeom_BSplineSurface,IGESData_IGESEntity) protected: private: Standard_Integer theIndexU; Standard_Integer theIndexV; Standard_Integer theDegreeU; Standard_Integer theDegreeV; Standard_Boolean isClosedU; Standard_Boolean isClosedV; Standard_Boolean isPolynomial; Standard_Boolean isPeriodicU; Standard_Boolean isPeriodicV; Handle(TColStd_HArray1OfReal) theKnotsU; Handle(TColStd_HArray1OfReal) theKnotsV; Handle(TColStd_HArray2OfReal) theWeights; Handle(TColgp_HArray2OfXYZ) thePoles; Standard_Real theUmin; Standard_Real theUmax; Standard_Real theVmin; Standard_Real theVmax; }; #endif // _IGESGeom_BSplineSurface_HeaderFile
#ifndef GNSCREENMESHOBJECT_H #define GNSCREENMESHOBJECT_H class GNSCREENMESH_ENTRY GnScreenMeshObject { public: GnScreenMeshObject(); ~GnScreenMeshObject(); protected: private: }; #endif // GNSCREENMESHOBJECT_H
// // 10.cpp // REVIEW BAGUS // // Created by Mikha Yupikha on 16/10/2016. // Copyright © 2016 Mikha Yupikha. All rights reserved. // #include <iostream> using namespace std; int main() { int month, year; cout<<"Please input the number of month (1-12): "; cin>>month; if (month<1 || month>12) cout<<"Please input the right month."<<endl; else { cout<<"Please input the number of year: "; cin>>year; if (year % 100 == 0 && year % 400 == 0 && month == 2) cout<< "29 days."<<endl; else if (year % 100 != 0 && year % 4 == 0 && month == 2) cout<< "29 days."<<endl; else if (month==2) cout<<"28 days."<<endl; else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) cout<<"31 days."<<endl; else cout<<"30 days."<<endl; } return 0; }
#include "stdafx.h" #include "MainGame.h" #include "TestScene.h" MainGame::MainGame() { SUBWIN->Init(); } MainGame::~MainGame() { } HRESULT MainGame::Init() { GameNode::Init(); isDebug = false; IMAGE->AddImage("restore", "images/restore.bmp", 0, 0, 50, 50, true, RGB(255, 0, 255)); IMAGE->AddImage("bg", "images/background.bmp", 0, 0, WINSIZEX, WINSIZEY, false, RGB(255, 0, 255)); TestScene * test = new TestScene; SCENE->AddScene("Test", test); SOUND->Init(); SOUND->AddSound("Test", "sounds/¿µÀü3.wav", true, true); SUBWIN->SetScene(test); SCENE->ChangeScene("Test"); return S_OK; } void MainGame::Release() { GameNode::Release(); } void MainGame::Update() { GameNode::Update(); SUBWIN->Update(); SCENE->Update(); //====================== Debug =====================// if (INPUT->GetKeyDown(VK_F11)) { isDebug = !isDebug; } //==================================================// } void MainGame::Render() { PatBlt(GetMemDC(), 0, 0, WINSIZEX, WINSIZEY, WHITENESS); //================================================= { SCENE->Render(); SUBWIN->Render(); } //================== Debug ==================== if (isDebug) { } //================================================= FRAME->Render(GetMemDC()); this->SetBackBuffer()->Render(GetHDC()); }
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<(n);i++) #define for1(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) const int INF = 1<<29; const int MOD=1073741824; //#define pp pair<ll,ll> typedef long long int ll; bool isPowerOfTwo (ll x) { return x && (!(x&(x-1))); } void fastio() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); } long long binpow(long long a, long long b) { long long res = 1; while (b > 0) { if (b & 1) res = res * a; a = a * a; b >>= 1; } return res; } const int dx[] = {1,0,-1,0,1,1,-1,-1}; const int dy[] = {0,-1,0,1,1,-1,-1,1}; //////////////////////////////////////////////////////////////////// int main() { fastio(); int t=1; //cin>>t; while(t--) { int n; vector<int> first,second; int x; cin>>n; ll sumf=0,sums=0; int move=0; REP(i,n) { cin>>x; if(x>=0) { first.push_back(x); sumf+=x; } else {second.push_back(abs(x));sums+=abs(x);} if(i==n-1) { if(x>0)move=1; else move=0; } } if(sumf>sums)cout<<"first"; else if(sums>sumf)cout<<"second"; else { REP(i,min(first.size(),second.size())) { if(first[i]>second[i]) return cout<<"first",0; if(second[i]>first[i]) return cout<<"second",0; } if(move==1)cout<<"first"; else cout<<"second"; } } return 0; }
#include "stdio.h" #include "conio.h" #include "string.h" int fibonacci(int n){ int a=n,b=0,i; printf("\nFibonacci Series for the given number is:\n\n"); for(i=1; i<=10; i++){ a=a+b; b=a-b; printf(" %d ",b); } } void main(){ clrscr(); int number; printf("Enter any number: "); scanf("%d",&number); fibonacci(number); getch(); }
#include "stdafx.h" #include "Win32Utils.h" Win32Utils::Win32Utils() { } Win32Utils::~Win32Utils() { } // Return current working directory (with trailing backslash) string Win32Utils::GetCurrentWorkingDirectory() { string folder; const DWORD buffsize = 2048; char buffer[buffsize + 1]; DWORD ret = ::GetCurrentDirectory(buffsize, buffer); folder = string(buffer) + string("\\"); return folder; }
#ifndef INSERTMODE_H #define INSERTMODE_H #include "Mode.h" class InsertMode:public Mode { public: InsertMode(); virtual void update(const Ogre::FrameEvent&); virtual void init(); virtual bool keyReleased(const OIS::KeyEvent &keyEventRef); virtual bool keyPressed(const OIS::KeyEvent &keyEventRef); virtual bool mouseMoved(const OIS::MouseEvent &evt); virtual bool mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id); virtual bool mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id); private: bool rMode; bool sMode; void rotateModel(const OIS::MouseEvent &evt); void scaleModel(const OIS::MouseEvent &evt); }; #endif /* INSERTMODE_H */
#pragma once #include "Render/DrawPass/BaseDrawPass.h" #include "Render/DrawSubPass/Geometry2DSubPass.h" #include "Render/DrawSubPass/GeometrySubPass.h" #include "Render/DrawSubPass/SkyBoxSubPass.h" #include "Render/DrawSubPass/GuiSubPass.h" namespace Rocket { class ForwardGeometryPass : implements BaseDrawPass { public: ForwardGeometryPass() { m_DrawSubPasses.push_back(CreateRef<Geometry2DSubPass>()); m_DrawSubPasses.push_back(CreateRef<GeometrySubPass>()); m_DrawSubPasses.push_back(CreateRef<SkyBoxSubPass>()); m_DrawSubPasses.push_back(CreateRef<GuiSubPass>()); } }; }
#ifndef GNSMGROUP_H #define GNSMGROUP_H class GNMESH_ENTRY Gn2DNode : public Gn2DMeshObject { GnDeclareRTTI; GnDeclareStream; protected: GnTObjectArray<Gn2DMeshObjectPtr> mChildern; public: Gn2DNode(gtuint uiChildSize = 0); virtual ~Gn2DNode(){}; void AttachChild(Gn2DMeshObject* pObject); virtual void Update(float fTime); //virtual void UpdateRect(bool bUpdateMeshData); virtual Gn2DMeshObjectPtr DetachChild(Gn2DMeshObject* pChild); virtual Gn2DMeshObjectPtr DetachChildAt(gtuint uiIndex); virtual GnObjectForm* GetObjectByName(const GnSimpleString& strName); inline Gn2DMeshObject* GetAt(gtuint uiIndex) { return mChildern.GetAt( uiIndex ); } inline gtuint GetChildCount() { return mChildern.GetSize(); } }; GnSmartPointer(Gn2DNode); #endif // GNSMGROUP_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2003-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined _NATIVE_SSL_SUPPORT_ && defined SSL_CHECK_EXT_VALIDATION_POLICY #include "modules/libssl/sslbase.h" #include "modules/libssl/options/sslopt.h" #include "modules/libssl/data/ev_oid_update.h" SSL_EV_OID_updater::SSL_EV_OID_updater() { } SSL_EV_OID_updater::~SSL_EV_OID_updater() { } OP_STATUS SSL_EV_OID_updater::Construct(OpMessage fin_msg) { URL url; url = g_url_api->GetURL(AUTOUPDATE_SCHEME "://" AUTOUPDATE_SERVER "/" AUTOUPDATE_VERSION "/ev-oids.xml"); g_url_api->MakeUnique(url); return SSL_XML_Updater::Construct(url, fin_msg); } OP_STATUS SSL_EV_OID_updater::ProcessFile() { if(!CheckOptionsManager(SSL_LOAD_CA_STORE)) return OpStatus::ERR; int i=0; SSL_CertificateItem *cert_item = NULL; while((cert_item = optionsManager->Find_Certificate(SSL_CA_Store, i++)) != NULL) { if(cert_item->ev_policies.GetLength()>0) { cert_item->ev_policies.Resize(0); cert_item->decoded_ev_policies.Resize(0); cert_item->cert_status = Cert_Updated; } } if(!parser.EnterElement(UNI_L("ev-oid-list"))) return OpStatus::ERR; while(parser.EnterElement(UNI_L("issuer"))) { RETURN_IF_ERROR(ProcessCertificate()); parser.LeaveElement(); } parser.LeaveElement(); return OpStatus::OK; } OP_STATUS SSL_EV_OID_updater::ProcessCertificate() { SSL_DistinguishedName issuer_name; SSL_varvector32 issuer_keyid; SSL_varvector32 ev_oids; while(parser.EnterAnyElement()) { SSL_varvector32 *base_64_target = NULL; /* if(parser.GetElementName() == UNI_L("issuer-name") || parser.GetElementName() == UNI_L("ev-oid-text")) { // Ignore } else */ if(parser.GetElementName() == UNI_L("issuer-id")) { base_64_target = &issuer_name; } else if(parser.GetElementName() == UNI_L("issuer-key")) { base_64_target = &issuer_keyid; // SHA-1 hash } else if(parser.GetElementName() == UNI_L("ev-oids")) base_64_target = &ev_oids; if(base_64_target != NULL) { RETURN_IF_ERROR(GetBase64Data(*base_64_target)); if(base_64_target->GetLength() == 0) return OpStatus::ERR; } parser.LeaveElement(); } SSL_CertificateItem *cert_item = optionsManager->Find_Certificate(SSL_CA_Store, issuer_name); while(cert_item) { SSL_CertificateHandler *cert = cert_item->GetCertificateHandler(); if(cert) { SSL_varvector16 keyhash; cert->GetPublicKeyHash(0, keyhash); if(keyhash == issuer_keyid) { cert_item->ev_policies = ev_oids; cert_item->cert_status = Cert_Updated; break; } } cert_item = optionsManager->Find_Certificate(SSL_CA_Store, issuer_name, cert_item); } return OpStatus::OK; } #endif
#include "ResultLayer.h" ResultLayer::ResultLayer() { } ResultLayer::~ResultLayer() { } bool ResultLayer::init() { if (!Layer::init()) return false; return true; }
#include <iostream> #define abs(n) (n<0?-(n):n) int main() { int sumSq = 0; for (int n = 1; n <= 100; n++) sumSq += n * n; int sqSum = 50 * 101; sqSum *= sqSum; std::cout << abs(sumSq - sqSum) << "\n"; }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ncurses.h> #include <string> using namespace std; void doPrint(int n, char sChar) { for (int i = 0; i < n; i++) { printf("%C", sChar); } } int main() { int h, w, r, n; freopen("labiec34.inp", "r", stdin); scanf("%d", &h); scanf("%d", &w); scanf("%d", &r); n = 1 + r; if (w > 2 && h > 1 && r >1) { for (int i = 0; i < h; i++) { if (i == 1 || i == n) { doPrint(w, '*'); printf("\n"); n = i + r; } else { doPrint(1, '*'); doPrint(w - 2, ' '); doPrint(1, '*'); printf("\n"); } } } else { printf("Chieu rong lon hon 2 va hai so con lai deu lon hon 1\n"); } getchar(); return 0; }
// ------------------------------------------------------------------------------------------------ // File name: Parser.h // Author: Marc Ochsenmeier // Email: info@winitor.net // Web: www.winitor.net // Date: 20.08.2011 // // Description: This file contains a set of Interfaces that can be used to inquire the internals // of a Program Data Base (PDB) file. PDB files are used by Visual Studio and other // debugging tools like WinDbg to allow debugging and program inspection. // // The items presented here describes the interface of a C++ based DLL which // is called "PdbParser.dll". // // This file must be included in the "consumer" application. // // Our PdbParser uses the "Debug Interface Access" (DIA) which is // part of the Visual Studio 2008 SDK of Microsoft Corporation. // // ------------------------------------------------------------------------------------------------ #pragma once #include <comutil.h> #include <map> #include <vector> using namespace std; // The following ifdef block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the PDBPARSER_EXPORTS // symbol defined. This symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // PDBPARSER_EXPORTS functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifdef PDBPARSER_EXPORTS #define PDBPARSER_API __declspec(dllexport) #else #define PDBPARSER_API __declspec(dllimport) #endif namespace PdbParser { // Forwarded references struct IPdbParser; struct IPdbFile; struct IPdbModule; struct IPdbModuleDetails; struct IPdbSourceFile; enum CheckSumType { CheckSumType_None, // No checksum is available CheckSumType_MD5, CheckSumType_SHA1, CheckSumType_Unknown }; /*! @brief An enumeration of the several potential languages that can be used as source. */ enum PdbLanguage { PdbLanguage_Unavailable, // language information is not available PdbLanguage_C, // language is C. PdbLanguage_CPP, // language is C++. PdbLanguage_Fortran, // language is FORTRAN. PdbLanguage_MASM, // language is Microsoft Macro Assembler. PdbLanguage_PASCAL, // language is Pascal. PdbLanguage_BASIC, // language is BASIC. PdbLanguage_COBOL, // language is COBOL. PdbLanguage_LINK, // Linker-generated module. PdbLanguage_CVTRES, // Resource module converted with CVTRES tool. PdbLanguage_CVTPGD, // POGO optimized module generated with CVTPGD tool. PdbLanguage_CSHARP, // Application language is C#. PdbLanguage_VB, // Application language is Visual Basic. PdbLanguage_ILASM, // language is intermediate language assembly. PdbLanguage_JAVA, // language is Java. PdbLanguage_JSCRIPT, // language is Jscript. PdbLanguage_MSIL // language is an unknown MSIL. }; /*! @brief An enumeration of several potential CPU types that can be targeted by a program.*/ enum PdbTargetCPU { PdbTargetCPU_Unavailable, PdbTargetCPU_I386, PdbTargetCPU_PENTIUM, PdbTargetCPU_PENTIUMII, PdbTargetCPU_PENTIUMPRO, PdbTargetCPU_PENTIUMIII, PdbTargetCPU_MIPS , PdbTargetCPU_MIPSR4000, PdbTargetCPU_MIPS16 , PdbTargetCPU_MIPS32 , PdbTargetCPU_MIPS64 , PdbTargetCPU_MIPSI, PdbTargetCPU_MIPSII , PdbTargetCPU_MIPSIII, PdbTargetCPU_MIPSIV , PdbTargetCPU_MIPSV, PdbTargetCPU_IA64, PdbTargetCPU_IA64_1, PdbTargetCPU_IA64_2, PdbTargetCPU_TRICORE, PdbTargetCPU_X64, PdbTargetCPU_AMD64, PdbTargetCPU_Unknown }; /*! @brief An enumeration of all the potential PDB symbols. */ enum PdbSymbolType { PdbSymbolTypeNull, PdbSymbolType_Exe, PdbSymbolType_Compiland, PdbSymbolType_CompilandDetails, PdbSymbolType_CompilandEnv, PdbSymbolType_Function, PdbSymbolType_Block, PdbSymbolType_Data, PdbSymbolType_Annotation, PdbSymbolType_Label, PdbSymbolType_PublicSymbol, PdbSymbolType_UDT, PdbSymbolType_Enum, PdbSymbolType_FunctionType, PdbSymbolType_PointerType, PdbSymbolType_ArrayType, PdbSymbolType_BaseType, PdbSymbolType_Typedef, PdbSymbolType_BaseClass, PdbSymbolType_Friend, PdbSymbolType_FunctionArgType, PdbSymbolType_FuncDebugStart, PdbSymbolType_FuncDebugEnd, PdbSymbolType_UsingNamespace, PdbSymbolType_VTableShape, PdbSymbolType_VTable, PdbSymbolType_Custom, PdbSymbolType_Thunk, PdbSymbolType_CustomType, PdbSymbolType_ManagedType, PdbSymbolType_Dimension, PdbSymbolType_Max }; /*! @brief A Class to instantiate the PDB engine.*/ struct PDBPARSER_API IPdbParserFactory { /*! @brief Instantiate the PDB parser Engine @return Is a pointer to an instance of the PDB Parser engine, NULL if a failure occured.*/ static IPdbParser* Create(); /*! @brief Cleanup the resources alloacated by the PDB engine.*/ static void Destroy(); }; /* @brief A class to Parse Program Database (PDB) files. */ struct IPdbParser { /*! @brief Instantiate the IPdbFile interface by opening a PDB file @param Is the path of the Image file to open @return Is a pointer to an instance of the IPdbFile interface the file has been successfully opened, NULL otherwise.*/ virtual IPdbFile* OpenFile(const std::wstring& path) = 0; }; /* @brief A class that represents a PDB file that has been opened using IPdbParser::Open(..). */ struct IPdbFile { /*! @brief Retrieve the GUID of the file. @return Is the GUID embbeded in the file, zero is not available.*/ virtual GUID GetGuid() const = 0; /*! @brief . Get the File Modules @return Is a collection of interface to the Module objects.*/ virtual std::vector<IPdbModule*>& GetModules() = 0; /*! @brief Check whether the PDB file has been stripped (private symbols have been removed). @return Is true when the PDB file has been stripped, false otherwise.*/ virtual bool IsStripped() = 0; /*! @brief . Close the File.*/ virtual void Close() = 0; }; /* @brief A class that represents a Module referenced in a PDB file. */ struct IPdbModule { /*! @brief Retrieve the Module name... @return .. Is the Name of the module.*/ virtual const std::wstring& GetName() const = 0; /*! @brief Retrieve the details of a Module @return Is a pointer to the Interface provinding the Details when successfull, NULL otherwise.*/ virtual IPdbModuleDetails* GetModuleDetails() = 0; /*! @brief . Get the Sources Files @return Is a collection of interface to the Module source file object.*/ virtual std::vector< IPdbSourceFile* >& GetSourceFiles() = 0; }; /* @brief A class that contains some details of a Module referenced in a PDB file. */ struct IPdbModuleDetails { /*! @brief Retrieve the Language (e.g C++, C#..) used to create the Module. @retutn . Is the Language used to create the Module.*/ virtual PdbLanguage GetLanguage() const = 0; /* @brief Retrieve the name of the compiler used to build the Module @return Is the Name of the Compiler.*/ virtual const std::wstring& GetCompilerName() const = 0; /* @brief Returns the target CPU @return .. */ virtual PdbTargetCPU GetTargetCPU() const = 0; /*! @brief .. Retrieve the Back End build Number <xx>.<yy>.<zzzz>. @return .. */ virtual const std::wstring& GetBackEndBuildNumber() const = 0; /*! @brief .. Check whether the Module is Managed code. @return .. Is true when the Code is managed, false otherwise.*/ virtual bool IsManagedCode() const = 0; }; /* @brief A class to handle a source of a Module. */ struct IPdbSourceFile { virtual const wstring& GetSourceFileName() = 0; virtual DWORD GetUniqueId() = 0; virtual CheckSumType GetCheckSumType() const = 0; virtual const char* GetCheckSum() const = 0; }; }
#include <iostream> #include <cstdlib> #include <string> #include "manager.h" using namespace std; Manager::Manager():_name("Manager"), _number("1"){ } Manager::Manager(string name = "Manager",string number = "1"):_name(name),_number(number) { } void Manager::PrintOperations() { cout<<"\t++++++++++++++++++++++++++++++++++++++++"<<endl <<"\t+ +"<<endl <<"\t+ Welcome to the ManagerSystem +"<<endl <<"\t+ 1. Display Menu +"<<endl <<"\t+ 2. Add Category +"<<endl <<"\t+ 3. Delete Category +"<<endl <<"\t+ 4. Modify Categories +"<<endl <<"\t+ 5. Manage Storage +"<<endl <<"\t+ 6. Delete Item +"<<endl <<"\t+ 7. Exit +"<<endl <<"\t+ +"<<endl <<"\t++++++++++++++++++++++++++++++++++++++++"<<endl; } void Manager::AddCategory(FullMenu& menu) { string name, description; cout<<"Please input category name:"; cin.ignore(); getline(cin, name); cout<<"Please input category description:"; cin.ignore(); getline(cin, description); Category newCat(name, description); menu.AddCategory(newCat); } void Manager::AddCategory(FullMenu& menu, Category& newCat) { //Category newCat(name, description); menu.AddCategory(newCat); } void Manager::DelCategory(FullMenu& menu) { string name; cout<<"Please input category name:"; cin.ignore(); getline(cin, name); menu.DelCategory(name); } void Manager::ModifyCategory(FullMenu& menu, vector<Item>& item) { string command; cout << "1. Add items to category" << endl << "2. Delete items from category" << endl << endl; cout << "Please choose your command: "; cin.ignore(); getline(cin, command); if(command == "1") AddItemToCategory(menu, item); if(command == "2") DeleteItemFromCategory(menu); } void Manager::AddItemToCategory(FullMenu& menu, vector<Item>& item) { int category; cout << endl; for(int n = 0; n < menu.GetSize(); n++) { cout << n + 1 << ". " << menu.GetCategory(n).GetName() << endl; } cout << "Choose category: "; cin >> category; cout << endl; int itemChosen; for(int n = 0; n < item.size(); n++) { cout << n + 1 << ". " << item[n].GetName() << endl; } cout << "Choose item to add: "; cin >> itemChosen; menu.GetCategory(category - 1).AddItem(&item[itemChosen - 1]); } void Manager::AddItemToCategory(FullMenu& menu, vector<Item>& item, int catIndex, int itemIndex) { menu.GetCategory(catIndex - 1).AddItem(&item[itemIndex - 1]); } void Manager::DeleteItemFromCategory(FullMenu& menu) { int category, itemChosen; cout << endl; for(int n = 0; n < menu.GetSize(); n++) { cout << n + 1 << ". " << menu.GetCategory(n).GetName() << endl; } cout << "Choose category: "; cin >> category; cout << endl; for(int n = 0; n < menu.GetCategory(category - 1).GetSize(); n++) { cout << n + 1 << ". " << menu.GetCategory(category - 1).GetItem(n).GetName() << endl; } cout << "Choose item to delete: "; cin >> itemChosen; string itemName = menu.GetCategory(category - 1).GetItem(itemChosen - 1).GetName(); menu.GetCategory(category - 1).DelItem(itemName); } void Manager::ManageStorage(vector<Item>& item, vector<Ingredient>& ingredient) { string command; cout << "\n1. Create new item" << endl << "2. Delete item" << endl; cout << "Please choose your command: "; cin.ignore(); getline(cin, command); if(command == "1") CreateItem(item, ingredient); if(command == "2") DeleteItemFromStorage(item); } void Manager::CreateItem(vector<Item>& item, vector<Ingredient>& ingredient) { double price; string name, description, itemCode; cout << "Enter the item's name: "; getline(cin, name); cout << "Enter the item's description: "; getline(cin, description); cout << "Enter the item's price: "; cin >> price; cout << "Enter the item's code: "; cin >> itemCode; item.push_back(Item(name, description, itemCode, price)); AddIngredientToItem(item[item.size() - 1], ingredient); } void Manager::DeleteItemFromStorage(vector<Item>& item) { cout << endl; for(int n = 0; n < item.size(); n++) cout << item[n].GetName() << endl; string name; cout << "Enter the item's name: "; getline(cin, name); for(int n = 0; n < item.size(); n++) { if(item[n].GetName() == name) { item[n].NotifyDeletion(); item.erase(item.begin() + n); break; } } } void Manager::AddIngredientToItem(Item& item, vector<Ingredient>& ingredient) { string command; cout << endl; for(int n = 0; n < ingredient.size(); n++) { cout << n + 1 << ". " << ingredient[n].GetName() << endl; } do { cout << "Add ingredients to your item(input 'x' when finished): "; cin >> command; int index = atoi(command.c_str()); if(command == "x") break; else if(index >= 0 && index <= ingredient.size()) { item.AddIngredient(&ingredient[index - 1]); } else cout << "Invalid input\n"; }while(1); }
#include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> #define inf 1073741823 using namespace std; using namespace __gnu_pbds; struct ope{ int t,x; }; ope o[200000]; int ans[200000],n,tot=0; void readit(){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d%d",&o[i].t,&o[i].x); } void writeit(){ for (int i=1;i<=tot;i++) printf("%d\n",ans[i]); } void work(){ tree<double,null_type,less<double>,rb_tree_tag,tree_order_statistics_node_update> tr; tr.insert(-inf); tr.insert(inf); for (int i=1;i<=n;i++){ int t=o[i].t,x=o[i].x; if (t==1){ double l=*--tr.lower_bound(x+1); if (l>=x) tr.insert(l+0.000001); else tr.insert(x); } else if (t==2){ double l=*--tr.lower_bound(x+1); if (l!=-inf) tr.erase(l); } else if (t==3) ans[++tot]=tr.order_of_key(x); else if (t==4) ans[++tot]=*tr.find_by_order(x); else if (t==5) ans[++tot]=*--tr.lower_bound(x); else ans[++tot]=*tr.lower_bound(x+1); } } int main(){ readit(); work(); writeit(); return 0; }
#include "PBRPipeline.h" #include "RenderTarget.h" #include "SceneManager.h" #include "engine_struct.h" #include "ResourceManager.h" #include "pass.h" #include "RenderSystem.h" #include "TextureManager.h" #include "EGLUtil.h" #include <random> #include "Image.h" #include "Texture.h" void PBREffect::Init() { auto& rt_mgr = RenderTargetManager::getInstance(); auto& tm = TextureManager::getInstance(); mainwindow = rt_mgr.get("MainWindow"); mRenderSystem = GlobalResourceManager::getInstance().m_RenderSystem; vector<string> e1 = { "ennis_c00.hdr", "ennis_c01.hdr", "ennis_c02.hdr", "ennis_c03.hdr", "ennis_c04.hdr", "ennis_c05.hdr" }; vector<string> e2 = { "pisa_c00.hdr", "pisa_c01.hdr", "pisa_c02.hdr", "pisa_c03.hdr", "pisa_c04.hdr", "pisa_c05.hdr" }; vector<string> e3 = { "cubemap/posx.jpg", "cubemap/negx.jpg", "cubemap/negy.jpg","cubemap/posy.jpg", "cubemap/posz.jpg", "cubemap/negz.jpg" }; vector<string> e4 = { "hdrmap/LightProbes/glacier_c00.hdr", "hdrmap/LightProbes/glacier_c01.hdr", "hdrmap/LightProbes/glacier_c02.hdr", "hdrmap/LightProbes/glacier_c03.hdr", "hdrmap/LightProbes/glacier_c04.hdr", "hdrmap/LightProbes/glacier_c05.hdr" }; vector<string> e5 = { "cubemap/rnl_cross/1.png","cubemap/rnl_cross/2.png", "cubemap/rnl_cross/3.png", "cubemap/rnl_cross/4.png", "cubemap/rnl_cross/5.png", "cubemap/rnl_cross/6.png" }; #ifdef ANDROID vector<string> e6 = { "cubemap/cloud_c00.jpg","cubemap/cloud_c01.jpg", "cubemap/cloud_c02.jpg", "cubemap/cloud_c03.jpg", "cubemap/cloud_c04.jpg", "cubemap/cloud_c05.jpg" }; #else vector<string> e6 = { "cubemap/cloud_c00.hdr","cubemap/cloud_c01.hdr", "cubemap/cloud_c02.hdr", "cubemap/cloud_c03.hdr", "cubemap/cloud_c04.hdr", "cubemap/cloud_c05.hdr" }; #endif // ANDROID vector<string> e7 = { "cubemap/ennis_diffuse_c00.bmp", "cubemap/ennis_diffuse_c01.bmp", "cubemap/ennis_diffuse_c02.bmp", "cubemap/ennis_diffuse_c03.bmp", "cubemap/ennis_diffuse_c04.bmp", "cubemap/ennis_diffuse_c05.bmp" }; vector<string> e8 = { "ennis_c00.jpg", "ennis_c01.jpg", "ennis_c02.jpg", "ennis_c03.jpg", "ennis_c04.jpg", "ennis_c05.jpg" }; vector<string> e9 = { "hdrmap/LightProbes/uffizi_c00.hdr", "hdrmap/LightProbes/uffizi_c01.hdr", "hdrmap/LightProbes/uffizi_c02.hdr", "hdrmap/LightProbes/uffizi_c03.hdr", "hdrmap/LightProbes/uffizi_c04.hdr", "hdrmap/LightProbes/uffizi_c05.hdr" }; vector<string> e9_diffuse = { "hdrmap/diffuse/uffizi_d_c00.hdr", "hdrmap/diffuse/uffizi_d_c01.hdr", "hdrmap/diffuse/uffizi_d_c02.hdr", "hdrmap/diffuse/uffizi_d_c03.hdr", "hdrmap/diffuse/uffizi_d_c04.hdr", "hdrmap/diffuse/uffizi_d_c05.hdr" }; vector<string> e10 = { "cubemap/rnl_c00.hdr", "cubemap/rnl_c01.hdr", "cubemap/rnl_c02.hdr", "cubemap/rnl_c03.hdr", "cubemap/rnl_c04.hdr", "cubemap/rnl_c05.hdr" }; env = tm.CreateTextureCubeMap(e9, "pbr_envmap1"); env->createInternalRes(); env_filtered = tm.CreateTextureCubeMap(e9_diffuse, "pbr_env_filter"); lut=tm.CreateTextureFromImage("convolution_spec.tga", "pbr_lut"); lut->mipmap_mode = Texture::TextureMipmap_None; pbr_pass=PassManager::getInstance().LoadPass("pbr/pbr_prog.json"); createNoise(); createSamples(); createggxTexture(); if (!isRendertoMainWindow){ output_rt = rt_mgr.CreateRenderTargetFromPreset("basic","effect_pbr"); output_rt->createInternalRes(); color = tm.get("effect_pbr_tex1"); } } void PBREffect::Render() { SceneManager* scene = SceneContainer::getInstance().get("scene1"); auto camera = scene->getCamera("main"); //get a screen quad auto quad = GlobalResourceManager::getInstance().as_meshManager.get("ScreenQuad.obj"); RenderQueueItem item; item.asMesh = quad; RenderQueue queue2; queue2.push_back(item); RenderQueue queue; scene->getVisibleRenderQueue_as(camera, queue);//暂时禁用了octree的剔除 auto& tm = TextureManager::getInstance(); GpuProgram* p = pbr_pass->mProgram; p->setProgramConstantData("gbuffer_depth", input_depth); p->setProgramConstantData("gbuffer_normal", input_normal1); p->setProgramConstantData("gbuffer_diffuse", input_diffuse); p->setProgramConstantData("gbuffer_specular", input_specular); p->setProgramConstantData("gbuffer_normal2", input_normal2); p->setProgramConstantData("env_map", env); p->setSampler("env_map", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("env_map_filtered", env_filtered); p->setSampler("env_map_filtered", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("random_direction_3x3_sampler", tex_noise); p->setSampler("lut_sampler", SamplerManager::getInstance().get("ClampPoint")); p->setProgramConstantData("lut_sampler", lut); //p->setSampler("ggx_sampler", SamplerManager::getInstance().get("ClampPoint")); p->setProgramConstantData("ggx_sampler", tex_ggx); p->setProgramConstantData("cosine_hemisphere_sampler", &samples_IBL_cosine[0][0], "vec3", num_samples_IBL*sizeof(Vector3)); p->setProgramConstantData("metalness", &metalness, "float", sizeof(float)); p->setProgramConstantData("roughness", &roughness, "float", sizeof(float)); p->setProgramConstantData("num_samples", &num_samples_IBL, "int", sizeof(int)); p->setProgramConstantData("sun_light_direction", &light_dir[0], "vec3", sizeof(Vector3)); if (shadow_map != NULL) { p->setProgramConstantData("shadow_map_sampler", shadow_map); //p->setSampler("shadow_map_sampler",SamplerManager::getInstance().get("ShadowMap")); p->setProgramConstantData("shadow_mat", &shadow_mat[0][0], "mat4", sizeof(Matrix4)); } if (ao_map != NULL) { p->setProgramConstantData("ao_map_sampler", ao_map); } if (isRendertoMainWindow) mRenderSystem->RenderPass(camera, queue, pbr_pass, mainwindow); else mRenderSystem->RenderPass(camera, queue2, pbr_pass, output_rt); } void PBREffect::changeSampleNum(int num) { num_samples_IBL = num; createSamples(); refreshGgxTexture(); } void PBREffect::createNoise() { std::vector<Vector4> noise(3 * 3); for (int i = 0; i != noise.size(); ++i) { float angle = 2.f * M_PI * ((uniform_1d_sample() * noise.size() + uniform_1d_sample()) / noise.size()); noise[i].x = cos(angle); noise[i].y = sin(angle); } auto& tm = TextureManager::getInstance(); Texture* t = tm.CreateTextureFromPreset("image_noise_repeat"); t->width = 3; t->height = 3; t->name = "pbr_noise_texture"; tm.add(t); Image* im = new Image; im->CreateImageFromData(Image::FLOAT_32_32_32_32, 3, 3, &noise[0][0]); t->image = im; t->createInternalRes(); tex_noise = t; } float PBREffect::uniform_1d_sample() { std::mt19937_64 engine; std::uniform_real_distribution<float> dist; return dist(engine); } Vector3 PBREffect::sample_hemisphere_ggx(Vector2 u2d, float alpha) { float cosphi = cos(2.f * M_PI * u2d.x); float costheta = sqrt((1.f - u2d.y) / (1.f + (alpha * alpha - 1.f) * u2d.y)); float sinphi = sin(2.f * M_PI * u2d.x); float sintheta = sqrt(1.f - costheta * costheta); return Vector3(sintheta * cosphi, sintheta * sinphi, costheta); } Vector3 PBREffect::sample_hemisphere_cosine(Vector2 u2d) { float cosphi = cos(2.f * M_PI * u2d.x); float costheta = sqrt(u2d.y); float sinphi = sin(2.f * M_PI * u2d.x); float sintheta = sqrt(1.f - costheta * costheta); return Vector3(sintheta * cosphi, sintheta * sinphi, costheta); } void PBREffect::stratified_2d_samples(int nx, int ny, vector<Vector2> &samples) { std::mt19937_64 engine; std::uniform_real_distribution<float> dist; for (int j = 0; j != ny; ++j) { for (int i = 0; i != nx; ++i) { float y = (j + dist(engine)) / ny; float x = (i + dist(engine)) / nx; samples.push_back(Vector2(x, y)); } } std::shuffle(samples.begin(), samples.end(), engine); } void PBREffect::createSamples() { std::vector<Vector2> u2d; stratified_2d_samples(num_samples_IBL, num_samples_IBL, u2d); samples_IBL_cosine.clear(); samples_IBL_ggx.clear(); for (int i = 0; i != num_samples_IBL; ++i) samples_IBL_cosine.push_back(sample_hemisphere_cosine(u2d[i])); for (int j = 0; j != 100; ++j) { float r = (j + .5f) / 100; float a = r * r; for (int i = 0; i != num_samples_IBL; ++i) samples_IBL_ggx.push_back(sample_hemisphere_ggx(u2d[i], a)); } } void PBREffect::createggxTexture() { auto& tm = TextureManager::getInstance(); Texture* t = tm.CreateTextureFromPreset("image_noise_repeat"); t->name = "ggx_texture"; t->mipmap_mode = Texture::TextureMipmap_None; Image* im = new Image; im->CreateImageFromData(Image::FLOAT_32_32_32, num_samples_IBL, 100, &samples_IBL_ggx[0][0]); t->image = im; t->setFormatFromImage(im); t->setFormat(Texture::RGB16F); tm.add(t); t->createInternalRes(); tex_ggx = t; } void PBREffect::refreshGgxTexture() { tex_ggx->releaseInternalRes(); tex_ggx->width = num_samples_IBL; tex_ggx->height = 100; tex_ggx->image->CreateImageFromData(Image::FLOAT_32_32_32, num_samples_IBL, 100, &samples_IBL_ggx[0][0]); tex_ggx->createInternalRes(); } void PBRPipeline::Init() { gbuffer_effect.input_scenename = "scene1"; gbuffer_effect.input_cameraname = "main"; gbuffer_effect.Init(); pbr_effect.input_depth = gbuffer_effect.depth; pbr_effect.input_diffuse = gbuffer_effect.diffuse; pbr_effect.input_normal1 = gbuffer_effect.normal1; pbr_effect.input_normal2 = gbuffer_effect.normal2; pbr_effect.input_specular = gbuffer_effect.specular; pbr_effect.isRendertoMainWindow = true; pbr_effect.Init(); } void PBRPipeline::Render() { gbuffer_effect.Render(); pbr_effect.Render(); } void PBREffect2::Init() { auto& rt_mgr = RenderTargetManager::getInstance(); auto& tm = TextureManager::getInstance(); mainwindow = rt_mgr.get("MainWindow"); mRenderSystem = GlobalResourceManager::getInstance().m_RenderSystem; rt1 = rt_mgr.CreateRenderTargetFromPreset("basic_float", "effect_pbr"); color = rt1->m_attach_textures["color0"]; depth = rt1->m_attach_textures["depth"]; pbr_pass = PassManager::getInstance().LoadPass("pbr/pbr_prog.json"); env_pass = PassManager::getInstance().LoadPass("pbr/pbr_render_env_prog.json"); filter_env_pass= PassManager::getInstance().LoadPass("pbr/pbr_filter_envmap_prog.json"); integrateBRDF_pass= PassManager::getInstance().LoadPass("pbr/pbr_IntegrateBRDF_prog.json"); pbr_use_prefilter_pass= PassManager::getInstance().LoadPass("pbr/pbr_use_prefilter_prog.json"); auto e_pisa = GenCubemapList("hdrmap/LightProbes/pisa_c0", ".hdr"); auto e_pisa_diffuse= GenCubemapList("hdrmap/diffuse/pisa_d_c0", ".hdr"); auto e_uffizi= GenCubemapList("hdrmap/LightProbes/uffizi_c0", ".hdr"); auto e_uffizi_diffuse= GenCubemapList("hdrmap/diffuse/uffizi_d_c0", ".hdr"); env = tm.CreateTextureCubeMap(e_pisa, "pisa"); env_diffuse = tm.CreateTextureCubeMap(e_pisa_diffuse, "pbr_env_filter"); // 对一个 cubemap 进行 ggx filter 操作 //PrefilterEnvMapSaveImages(env, "default_asserts/hdrmap/ggx_filtered/pisa"); LoadPrefilterEnvMap(env, "default_asserts/hdrmap/ggx_filtered/pisa"); lut = tm.CreateTextureFromImage("convolution_spec.tif", "pbr_lut"); lut->mipmap_mode = Texture::TextureMipmap_None; base_color = Vector3(1.0, 1.0, 1.0); //e_showtex.input_texture = tm.CreateTextureFromImage("hdrmap/LightProbes/pisa_c00.hdr"); //e_showtex.Init(); } void PBREffect2::Render() { SceneManager* scene = SceneContainer::getInstance().get("scene1"); auto camera = scene->getCamera("main"); //get a screen quad auto quad = GlobalResourceManager::getInstance().as_meshManager.get("ScreenQuad.obj"); RenderQueueItem item; item.asMesh = quad; RenderQueue queue2; queue2.push_back(item); RenderQueue queue; scene->getVisibleRenderQueue_as(camera, queue);//暂时禁用了octree的剔除 auto& tm = TextureManager::getInstance(); auto render_pass = pbr_pass; render_pass = pbr_use_prefilter_pass; GpuProgram* p = render_pass->mProgram; pbr_pass->mClearState.mClearColor = Vector4(0.3,0.3,0.3,1.0); p->setProgramConstantData("env_map", env); p->setSampler("env_map", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("env_map_filtered", env_diffuse); p->setSampler("env_map_filtered", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("IntegrateBRDFSampler", lut); p->setSampler("IntegrateBRDFSampler", SamplerManager::getInstance().get("ClampPoint")); p->setProgramConstantData("BaseColor", &base_color[0], "vec3", sizeof(Vector3)); int b = 0; if (b) mRenderSystem->RenderPass(camera, queue, render_pass, mainwindow); else { mRenderSystem->RenderPass(camera, queue, render_pass, rt1); p = env_pass->mProgram; p->setProgramConstantData("env_map", env); p->setSampler("env_map", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("depth", depth); p->setSampler("depth", SamplerManager::getInstance().get("ClampPoint")); p->setProgramConstantData("front", color); p->setSampler("front", SamplerManager::getInstance().get("ClampPoint")); if(in_RT==NULL) mRenderSystem->RenderPass(camera, queue2, env_pass, mainwindow); else mRenderSystem->RenderPass(camera, queue2, env_pass, in_RT); } //mRenderSystem->RenderPass(NULL, queue2, integrateBRDF_pass, mainwindow); //e_showtex.Render(); } void PBREffect2::PrefilterEnvMapSaveImages(Texture* env,string path) { auto& rt_mgr = RenderTargetManager::getInstance(); auto& tm = TextureManager::getInstance(); auto quadmesh = GlobalResourceManager::getInstance().as_meshManager.get("ScreenQuad.obj"); RenderQueueItem item; item.asMesh = quadmesh; RenderQueue quad; quad.push_back(item); int w = env->width, h = env->height; int ImageMip = env->CalcMipmapLevel(w, h); assert(ImageMip >= 10); for (int mip = 1; mip <= 5; mip++) { w /= 2; h /= 2; RenderTarget* rt_filter = rt_mgr.CreateRenderTargetFromPreset("basic_float", "prefilter_cubemap_fbo_mip" + to_string(mip) ,w,h); rt_filter->createInternalRes(); float r = 0.2*mip; for (int face = 0; face < 6; face++) { auto p = filter_env_pass->mProgram; p->setProgramConstantData("env_map", env); p->setSampler("env_map", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("roughness", &r, "float", sizeof(float)); p->setProgramConstantData("face", &face, "int", sizeof(int)); mRenderSystem->RenderPass(NULL, quad, filter_env_pass, rt_filter); string ImageName = path + "_mip" + to_string(mip) + "_face" + to_string(face); rt_filter->m_attach_textures["color0"]->SaveTextureToImage(ImageName, Texture::ST_FLOAT); //rt_filter->m_attach_textures["color0"]->SaveTextureToImage("s1", Texture::ST_UNSIGNED_BYTE); } } } void PBREffect2::PrefilterEnvMapLatitude(Texture* env, string path) { auto& rt_mgr = RenderTargetManager::getInstance(); auto& tm = TextureManager::getInstance(); auto quadmesh = GlobalResourceManager::getInstance().as_meshManager.get("ScreenQuad.obj"); RenderQueueItem item; item.asMesh = quadmesh; RenderQueue quad; quad.push_back(item); int w = env->width, h = env->height; int ImageMip = env->CalcMipmapLevel(w, h); assert(ImageMip >= 10); w = 4096; h = 2048; for (int mip = 1; mip < 10; mip++) { w /= 2; h /= 2; RenderTarget* rt_filter = rt_mgr.CreateRenderTargetFromPreset("basic_float", "prefilter_cubemap_fbo_mip" + to_string(mip) , w, h); rt_filter->createInternalRes(); float r = 0.1*mip; int UseLatitude = 1; auto p = filter_env_pass->mProgram; p->setProgramConstantData("env_map", env); p->setSampler("env_map", SamplerManager::getInstance().get("ClampLinear")); p->setProgramConstantData("roughness", &r, "float", sizeof(float)); p->setProgramConstantData("UseLatitude", &UseLatitude, "int", sizeof(int)); p->setProgramConstantData("textureSize", &w, "int", sizeof(int)); mRenderSystem->RenderPass(NULL, quad, filter_env_pass, rt_filter); string ImageName = path + "_mip" + to_string(mip); rt_filter->m_attach_textures["color0"]->SaveTextureToImage(ImageName, Texture::ST_FLOAT); } } void PBREffect2::LoadPrefilterEnvMap(Texture* env, string path) { int w = env->width, h = env->height; int ImageMip = env->CalcMipmapLevel(w, h); assert(ImageMip >= 10); env->useTexture(); for (int mip = 1; mip <= 5; mip++) { w /= 2; h /= 2; for (int face = 0; face < 6; face++) { Image im; string ImageName = path + "_mip" + to_string(mip) + "_face" + to_string(face)+".hdr"; im.LoadImage(ImageName, true); glTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face,mip, 0, 0, w, h, GL_RGB, GL_FLOAT, &im.pdata[0]); } } GL_CHECK(); } void PBRPipeline2::Init() { ePBr.Init(); } void PBRPipeline2::Render() { ePBr.Render(); }
#include "item/conn_line.h" #include <QStyleOptionGraphicsItem> #include <QPainter> #include <boost/range/adaptors.hpp> #include <boost/range/algorithm_ext.hpp> #include <boost/range/algorithm.hpp> #include <QPolygonF> #include <base/lang/scope.hpp> #include <QGraphicsScene> using namespace boost::adaptors; using namespace std; const auto get_center = [] (auto && item) { return item->sceneBoundingRect ().center (); }; std::unique_ptr<conn_line> conn_line::make(std::vector<item *> items) { auto ret = unique_ptr<conn_line> (new conn_line (std::move (items))); if (ret->init () == false) { return nullptr; } else { return ret; } } conn_line::conn_line(std::vector<item *> items) :item () ,items_ (std::move (items)) { } bool conn_line::init() { if (items_.size() < 2) { return false; } for (auto & it : items_) { if (it == nullptr) { return false; } connect (it, &item::destroyed, [this, it] { auto found = std::find (begin (items_), end (items_), it); if (found != end (items_)) { *found = nullptr; decltype (items_) other_item2; other_item2.resize (static_cast<size_t> (std::distance (found + 1, end (items_)))); std::copy (found + 1, end (items_), begin (other_item2)); items_.erase (found, end (items_)); if (items_.size () < 2) { deleteLater (); } // if (other_item2.size () >= 2) // { // auto new_item = make (std::move (other_item2)); // scene ()->addItem (new_item.release ()); // } } }); } setFlag (ItemIsMovable, false); setFlag (ItemIsSelectable, false); setPos (0, 0); return true; } void conn_line::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget * widget) { item::paint(painter, option, widget); if (std::any_of (begin (items_), end (items_), [] (auto && it) { return it == nullptr; })) { return; } auto the_pen = painter->pen(); the_pen.setWidthF(0.01 * item_width_); the_pen.setColor(Qt::black); painter->setPen(the_pen); std::vector<QPointF> conn_points; boost::push_back (conn_points, items_ | transformed (get_center)); painter->drawPolyline(conn_points.data(), static_cast<int> (conn_points.size())); } QRectF conn_line::boundingRect() const { QVector<QPointF> points; if (std::any_of (begin (items_), end (items_), [] (auto && it) { return it == nullptr; })) { return {}; } for (auto & it : items_) { points.push_back(get_center (it)); } return QPolygonF (points).boundingRect (); }
#include <iostream> #include <string> #include "cifrado.h" using std::string; using namespace std; int main() { string mensaje="MIRA ESA COLINA "; monobi algo; string cifrado=algo.cifrar(mensaje); cout<<cifrado<<endl<<endl; string descifrado=algo.descifrar(cifrado); cout<<descifrado<<endl; return 0; }
#include "nt.h" #include <intrin.h> void* nt::kernel_base_address() { return *reinterpret_cast<void**>(reinterpret_cast<std::uintptr_t>(PsLoadedModuleList) + 0x30); } std::size_t nt::kernel_base_size() { return *reinterpret_cast<std::size_t*>(reinterpret_cast<std::uintptr_t>(PsLoadedModuleList) + 0x40); } std::uintptr_t nt::get_process_cr3(PEPROCESS process) { KAPC_STATE kapc_state; KeStackAttachProcess(process, &kapc_state); const auto cr3 = __readcr3(); KeUnstackDetachProcess(&kapc_state); return cr3; } // unexported PMMPTE(NTAPI *MiGetPteAddress)(PVOID VirtualAddress) = nullptr;
#ifndef STRING_REVERSE_HPP #define STRING_REVERSE_HPP #include <string> #include <algorithm> namespace String { static constexpr void reverse(const std::string &str) { std::reverse(str.begin(), str.end()); } static constexpr void reverse(const std::string &str, size_t reverseSize) { std::reverse(str.begin(), str.begin() + reverseSize); } } #endif /* end of include guard : STRING_REVERSE_HPP */
//知识点:BFS/图论 /* 欲求得到达每个点的 最短路 的条数 显然, 每个点的最短路条数 = 所有父亲点的最短路条数 之和 所有边权值都为1 所以可以通过BFS来解决 当访问到这个节点时, 如果是第一次访问, 由于是从起点1 开始BFS, 所以之前访问的时候,路径长度不会比之后访问小 将这个节点的答案+=他父节点的答案, 并将此节点入队; 如果是第二次访问 且当前的距离等于之前记录的距离, 说明这是第二条最短路, 同样,将这个节点的答案+=他父节点的答案, 但不需要入队了。 */ #include<cstdio> #include<ctype.h> #include<queue> #include<algorithm> const int MARX = 1e6+10; const int INF = 2147483647; //============================================================= struct edge { int v,ne; }a[MARX*2]; int head[MARX],dis[MARX],ans[MARX]={0,1}; bool vis[MARX]; int n,m,x,y,num; //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } void add(int u,int v)//建图 { a[++num].ne=head[u],a[num].v=v,head[u]=num; } void bfs()//BFS { for(int i=2; i<=n; i++) dis[i]=INF; std::queue <int> s; s.push(1); while(!s.empty()) { int top=s.front(); s.pop(); for(int i=head[top]; i; i=a[i].ne) { int v=a[i].v; if(dis[v] >= dis[top]+1) { if(dis[v] == dis[top]+1)//更新答案 ans[v] = (ans[v]+ans[top])%100003; if(dis[v] > dis[top]+1) //更新答案并入队 { dis[v] = dis[top]+1, ans[v] = ans[top]%100003, s.push(v); } } } } } //============================================================= signed main() { n=read(),m=read(); for(int i=1; i<=m; i++)//建图 { x=read(),y=read(); add(x,y),add(y,x); } bfs(); for(int i=1; i<=n; i++) printf("%d\n",ans[i]%100003); }
// // BangManager.hpp // // Created by Yajun Shi // // The manager of the game, controls game flow. // Records points, generates enemies and bullet packages. // #include "stdafx.h" class BangManager : public GameManager { public: BangManager(); void Reset(); void GameOver(); virtual void Update(float dt); void AddPoint(); private: FullScreenActor* _gameOverScreen; bool _initialSetup; bool _gameOver; int _points; TextActor *_PointBoard; float _enemyCooldown; float _Enemy3CD; };
void empty(void) { /* empty */ }
// 问题的描述:环形链表插值 // 给定一个元素有序的环形链表(以vector的形式),将一个新的元素val插入到链表中,要求保持链表依旧有序 // 要求先构造出环形链表再进行插值 // 链表为空;链表不为空 // 测试用例有4组: // 1、空链表 val = 2 // 输入:NULL 2 // 输出:2 // 2、非空链表 val = 2 // 输入:{1,3,4,5,7} 2 // 输出:1,2,3,4,5,7 // 3、非空链表 val = 8 // 输入:{1,3,4,5,7} 8 // 输出:1,3,4,5,7,8 // 4、非空链表 val = 0 // 输入:{1,3,4,5,7} 0 // 输出:0,1,3,4,5,7 #include <iostream> #include <vector> using namespace std; // 链表结点的定义 struct ListNode { int val; struct ListNode *next; ListNode(int x) :val(x), next(nullptr) {} }; ListNode* InsertValue(vector<int> &nums, int value) { if (nums.size() == 0) { ListNode *head = new ListNode(value); head->next = head; return head; } // 先构造环形链表 ListNode *head = new ListNode(nums[0]); ListNode *temp = head; ListNode *new_node = nullptr; for (int i = 1; i < nums.size(); ++i) { new_node = new ListNode(nums[i]); temp->next = new_node; temp = new_node; } temp->next = head; // 再进行插入值 ListNode *target_node = new ListNode(value); // 链表长度为1 if (nums.size() == 1) { head->next = target_node; target_node->next = head; if (nums[0] < value) return head; else return target_node; } // 链表长度大于1,遍历链表 // 1 目标结点插入到链表之中 ListNode *current_node = head, *next_node = head->next; while (next_node != head) { if (current_node->val <= value && next_node->val >= value) { current_node->next = target_node; target_node->next = next_node; return head; } current_node = next_node; next_node = next_node->next; } // 2 目标结点插入到头结点前面 target_node->next = head; current_node->next = target_node; if (value < head->val) return target_node; else return head; } int main() { // 空链表 //vector<int> nums; // 非空链表 vector<int> nums = { 1,3,4,5,7 }; int insert_value = 2; ListNode *root = InsertValue(nums, insert_value); // 遍历链表,输出元素值 ListNode *node = root; int list_length = nums.size() + 1; while (list_length > 0) { cout << node->val << "\t"; node = node->next; --list_length; } cout << endl; // 回收分配给链表结点的内存 ListNode *delete_node = nullptr; for (int i = 0; i < nums.size() + 1; ++i) { delete_node = node; node = node->next; delete delete_node; } node = nullptr; delete_node = nullptr; root = nullptr; system("pause"); return 0; }
#include <algorithm> #include <iostream> #include <queue> #include <string> #include <tuple> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); while (true) { int w, h; std::cin >> w >> h; if (w == 0 && h == 0) { break; } std::vector<std::vector<int>> map(h, std::vector<int>(w)); std::vector<std::vector<bool>> check(h, std::vector<bool>(w, false)); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { std::cin >> map[i][j]; } } int cnt{}; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (check[i][j] || map[i][j] == 0) { continue; } std::queue<std::tuple<int, int>> q; q.emplace(j, i); check[i][j] = true; ++cnt; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); constexpr int dx[] = { 0, 1, 1, 1, -1, -1, -1, 0 }; constexpr int dy[] = { 1, -1, 0, 1, -1, 0, 1, -1 }; for (int k = 0; k < 8; ++k) { int nx = x + dx[k]; int ny = y + dy[k]; if (nx >= 0 && ny >= 0 && nx < w && ny < h && !check[ny][nx] && map[ny][nx] == 1) { check[ny][nx] = 1; q.emplace(nx, ny); } } } } } std::cout << cnt << '\n'; } return 0; }
#include <iostream> #include <algorithm> using namespace std; typedef unsigned long long int ll; int n, *a, *b; ll sum1 = 0, sum2 = 0, res = 0; void nhap(){ cin >> n; a = new int[n]; b = new int[n]; int i; for(i = 0; i < n; i++){ cin >> a[i]; sum1 = sum1 + a[i]; } for(i = 0; i < n; i++){ cin >> b[i]; sum2 = sum2 + b[i]; } } bool Compare(int a, int b, int k){ switch(k){ case 1: return a < b; break; case -1: return a > b; break; } return false; } void quicksort(int l, int r, int *rr, int k){ int x = rr[(l+r)/2], i = l, j = r; do{ while(Compare(rr[i], x, k)) i++; while(Compare(x, rr[j], k)) j--; if(i <= j) swap(rr[i++], rr[j--]); } while(i < j); if(l < j) quicksort(l, j, rr, k); if(i < r) quicksort(i, r, rr, k); } void solve(){ quicksort(0, n-1, a, -1); quicksort(0, n-1, b, 1); for(int i = 0; i < n; i++) if(sum1 > sum2){ sum1 = sum1 - a[i] + b[i]; sum2 = sum2 -b[i] + a[i]; res++; } else break; cout << res; } int main(){ nhap(); solve(); delete []a; delete []b; return 0; }
#include "ccameraslist.h" #include "ui_ccameraslist.h" DISABLE_COMPILER_WARNINGS #include <QStringBuilder> RESTORE_COMPILER_WARNINGS CCamerasList::CCamerasList(QWidget *parent) : QDialog(parent), ui(new Ui::CCamerasList) { ui->setupUi(this); } CCamerasList::~CCamerasList() { delete ui; } void CCamerasList::listUpdated(const QStringList& camerasList, int currentCameraIndex) { ui->_list->clear(); QString text = "<ul>"; for (int i = 0; i < camerasList.size(); ++i) text.append("<li>" % (i != currentCameraIndex ? camerasList[i] : ("<b>" % camerasList[i] % "</b>")) % "</li>"); text.append("</ul>"); ui->_list->setHtml(text); }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; const int N = 5555; int n, k, m, color[N]; vector<int> g[N]; int d[N]; vector<pair<int, int> > order; int mex[22]; bool matrix[22][22]; int cycle[22]; int main() { freopen("galaxy.in", "r", stdin); freopen("galaxy.out", "w", stdout); scanf("%d%d%d", &n, &k, &m); while (m--) { int x, y; scanf("%d%d", &x, &y); g[x].push_back(y); g[y].push_back(x); if (x <= k && y <= k) matrix[x][y] = matrix[y][x] = true; } for (int i = 0; i < k; ++i) cycle[i] = i + 1; do { bool cool = true; for (int i = 0; i < k; ++i) if (!matrix[ cycle[i] ][ cycle[(i + 1) % k] ]) { cool = false; break; } if (cool) { for (int i = 0; i < k; ++i) color[ cycle[i] ] = i + 1; break; } } while (next_permutation(cycle, cycle + k)); memset(d, 63, sizeof(d)); queue<int> q; for (int i = 1; i <= k; ++i) { d[i] = 0; q.push(i); } while (!q.empty()) { int x = q.front(); q.pop(); for (int i = 0; i < g[x].size(); ++i) if (d[ g[x][i] ] > d[x] + 1) { d[ g[x][i] ] = d[x] + 1; q.push(g[x][i]); } } for (int i = k + 1; i <= n; ++i) { pair<int, int> c; c.first = d[i]; c.second = i; order.push_back(c); } sort(order.begin(), order.end()); for (int j = 0; j < order.size(); ++j) { int x = order[j].second; memset(mex, 0, sizeof(mex)); for (int i = 0; i < g[x].size(); ++i) mex[ color[ g[x][i] ] ] = true; mex[0] = mex[k]; for (int i = 0; i < k; ++i) if (!mex[i] && mex[(i + 1) % k]) { color[x] = i; if (i == 0) color[x] = k; break; } } for (int i = 1; i <= n; ++i) printf("%d ", color[i]); cout << endl; return 0; }
#ifndef __VIVADO_SYNTH__ #include <fstream> using namespace std; // Debug utility ofstream* global_debug_handle; #endif //__VIVADO_SYNTH__ #include "mp23_1_opt_compute_units.h" #include "hw_classes.h" struct in_in_update_0_write0_merged_banks_4_cache { // RAM Box: {[0, 127], [0, 127], [0, 63]} // Capacity: 130 // # of read delays: 4 hw_uint<32> f0; hw_uint<32> f2; fifo<hw_uint<32> , 126> f3; hw_uint<32> f4; hw_uint<32> f6; inline hw_uint<32> peek_0() { return f0; } inline hw_uint<32> peek_1() { return f2; } inline hw_uint<32> peek_127() { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ return f3.back(); } inline hw_uint<32> peek_128() { return f4; } inline hw_uint<32> peek_129() { return f6; } inline void push(const hw_uint<32> value) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 1 f6 = f4; #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 126 f4 = f3.back(); #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 126 reading from capacity: 1 f3.push(f2); #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 1 f2 = f0; // cap: 1 f0 = value; } }; struct in_cache { in_in_update_0_write0_merged_banks_4_cache in_in_update_0_write0_merged_banks_4; }; inline void in_in_update_0_write0_write(hw_uint<32> & in_in_update_0_write0, in_cache& in, int d0, int d1, int d2) { in.in_in_update_0_write0_merged_banks_4.push(in_in_update_0_write0); } inline hw_uint<32> mp23_1_rd0_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp23_1_rd0 read pattern: { mp23_1_update_0[d0, d1, d2] -> in[2d0, 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Read schedule : { mp23_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 63 } // DD fold: { mp23_1_update_0[d0, d1, d2] -> 129 : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_129(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp23_1_rd1_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp23_1_rd1 read pattern: { mp23_1_update_0[d0, d1, d2] -> in[2d0, 1 + 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Read schedule : { mp23_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 63 } // DD fold: { mp23_1_update_0[d0, d1, d2] -> 1 : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_1(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp23_1_rd2_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp23_1_rd2 read pattern: { mp23_1_update_0[d0, d1, d2] -> in[1 + 2d0, 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Read schedule : { mp23_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 63 } // DD fold: { mp23_1_update_0[d0, d1, d2] -> 128 : 0 <= d0 <= 62 and 0 <= d1 <= 63 and 0 <= d2 <= 63; mp23_1_update_0[d0, d1, d2] -> (2 + 2 * d0) : d0 = 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_128(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp23_1_rd3_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp23_1_rd3 read pattern: { mp23_1_update_0[d0, d1, d2] -> in[1 + 2d0, 1 + 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Read schedule : { mp23_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 63 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 63 } // DD fold: { } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_0(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } // # of bundles = 2 // in_update_0_write // in_in_update_0_write0 inline void in_in_update_0_write_bundle_write(hw_uint<32>& in_update_0_write, in_cache& in, int d0, int d1, int d2) { hw_uint<32> in_in_update_0_write0_res = in_update_0_write.extract<0, 31>(); in_in_update_0_write0_write(in_in_update_0_write0_res, in, d0, d1, d2); } // mp23_1_update_0_read // mp23_1_rd0 // mp23_1_rd1 // mp23_1_rd2 // mp23_1_rd3 inline hw_uint<128> in_mp23_1_update_0_read_bundle_read(in_cache& in, int d0, int d1, int d2) { // # of ports in bundle: 4 // mp23_1_rd0 // mp23_1_rd1 // mp23_1_rd2 // mp23_1_rd3 hw_uint<128> result; hw_uint<32> mp23_1_rd0_res = mp23_1_rd0_select(in, d0, d1, d2); set_at<0, 128>(result, mp23_1_rd0_res); hw_uint<32> mp23_1_rd1_res = mp23_1_rd1_select(in, d0, d1, d2); set_at<32, 128>(result, mp23_1_rd1_res); hw_uint<32> mp23_1_rd2_res = mp23_1_rd2_select(in, d0, d1, d2); set_at<64, 128>(result, mp23_1_rd2_res); hw_uint<32> mp23_1_rd3_res = mp23_1_rd3_select(in, d0, d1, d2); set_at<96, 128>(result, mp23_1_rd3_res); return result; } // Operation logic inline void in_update_0(HWStream<hw_uint<32> >& /* buffer_args num ports = 1 */in_oc, in_cache& in, int d0, int d1, int d2) { // Consume: in_oc auto in_oc_0_c__0_value = in_oc.read(); auto compute_result = id_unrolled_1(in_oc_0_c__0_value); // Produce: in in_in_update_0_write_bundle_write(compute_result, in, d0, d1, d2); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ } inline void mp23_1_update_0(in_cache& in, HWStream<hw_uint<32> >& /* buffer_args num ports = 1 */mp23_1, int d0, int d1, int d2) { // Consume: in auto in_0_c__0_value = in_mp23_1_update_0_read_bundle_read(in/* source_delay */, d0, d1, d2); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ auto compute_result = max_pool_2x2_unrolled_1(in_0_c__0_value); // Produce: mp23_1 mp23_1.write(compute_result); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ } // Driver function void mp23_1_opt(HWStream<hw_uint<32> >& /* get_args num ports = 1 */in_oc, HWStream<hw_uint<32> >& /* get_args num ports = 1 */mp23_1, int num_epochs) { #ifndef __VIVADO_SYNTH__ ofstream debug_file("mp23_1_opt_debug.csv"); global_debug_handle = &debug_file; #endif //__VIVADO_SYNTH__ in_cache in; #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ #ifdef __VIVADO_SYNTH__ #pragma HLS inline recursive #endif // __VIVADO_SYNTH__ for (int epoch = 0; epoch < num_epochs; epoch++) { // Schedules... // in_oc_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*0] // in_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*1] // mp23_1_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*2 + 1*1,1*d0*1*2 + 1*1,1*2] for (int c0 = 0; c0 <= 63; c0++) { for (int c1 = 0; c1 <= 127; c1++) { for (int c2 = 0; c2 <= 127; c2++) { #ifdef __VIVADO_SYNTH__ #pragma HLS pipeline II=1 #endif // __VIVADO_SYNTH__ if ((0 <= c2 && c2 <= 127) && ((c2 - 0) % 1 == 0) && (0 <= c1 && c1 <= 127) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 63) && ((c0 - 0) % 1 == 0)) { in_update_0(in_oc, in, (c2 - 0) / 1, (c1 - 0) / 1, (c0 - 0) / 1); } if ((1 <= c2 && c2 <= 127) && ((c2 - 1) % 2 == 0) && (1 <= c1 && c1 <= 127) && ((c1 - 1) % 2 == 0) && (0 <= c0 && c0 <= 63) && ((c0 - 0) % 1 == 0)) { mp23_1_update_0(in, mp23_1, (c2 - 1) / 2, (c1 - 1) / 2, (c0 - 0) / 1); } } } } } #ifndef __VIVADO_SYNTH__ debug_file.close(); #endif //__VIVADO_SYNTH__ } void mp23_1_opt(HWStream<hw_uint<32> >& /* get_args num ports = 1 */in_oc, HWStream<hw_uint<32> >& /* get_args num ports = 1 */mp23_1) { mp23_1_opt(in_oc, mp23_1, 1); } #ifdef __VIVADO_SYNTH__ #include "mp23_1_opt.h" const int in_update_0_read_num_transfers = 1048576; const int mp23_1_update_0_write_num_transfers = 262144; extern "C" { static void read_in_update_0_read(hw_uint<32>* input, HWStream<hw_uint<32> >& v, const int size) { hw_uint<32> burst_reg; int num_transfers = in_update_0_read_num_transfers*size; for (int i = 0; i < num_transfers; i++) { #pragma HLS pipeline II=1 burst_reg = input[i]; v.write(burst_reg); } } static void write_mp23_1_update_0_write(hw_uint<32>* output, HWStream<hw_uint<32> >& v, const int size) { hw_uint<32> burst_reg; int num_transfers = mp23_1_update_0_write_num_transfers*size; for (int i = 0; i < num_transfers; i++) { #pragma HLS pipeline II=1 burst_reg = v.read(); output[i] = burst_reg; } } void mp23_1_opt_accel(hw_uint<32>* in_update_0_read, hw_uint<32>* mp23_1_update_0_write, const int size) { #pragma HLS dataflow #pragma HLS INTERFACE m_axi port = in_update_0_read offset = slave depth = 65536 bundle = gmem0 #pragma HLS INTERFACE m_axi port = mp23_1_update_0_write offset = slave depth = 65536 bundle = gmem1 #pragma HLS INTERFACE s_axilite port = in_update_0_read bundle = control #pragma HLS INTERFACE s_axilite port = mp23_1_update_0_write bundle = control #pragma HLS INTERFACE s_axilite port = size bundle = control #pragma HLS INTERFACE s_axilite port = return bundle = control static HWStream<hw_uint<32> > in_update_0_read_channel; static HWStream<hw_uint<32> > mp23_1_update_0_write_channel; read_in_update_0_read(in_update_0_read, in_update_0_read_channel, size); mp23_1_opt(in_update_0_read_channel, mp23_1_update_0_write_channel, size); write_mp23_1_update_0_write(mp23_1_update_0_write, mp23_1_update_0_write_channel, size); } } #endif //__VIVADO_SYNTH__
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #ifndef UNIX_WIDGET_PAINTER_H #define UNIX_WIDGET_PAINTER_H #include "modules/skin/IndpWidgetPainter.h" #include "platforms/quix/toolkits/ToolkitWidgetPainter.h" class UnixWidgetPainter : public IndpWidgetPainter { public: UnixWidgetPainter(ToolkitWidgetPainter* toolkit_painter); virtual ~UnixWidgetPainter(); virtual BOOL DrawScrollbar(const OpRect &drawrect); virtual BOOL DrawSlider(const OpRect& rect, BOOL horizontal, double min, double max, double pos, BOOL highlighted, BOOL pressed_knob, OpRect& out_knob_position, OpPoint& out_start_track, OpPoint& out_end_track); virtual OpWidgetInfo* GetInfo(OpWidget* widget); /** Get a scrollbar (owned by this UnixWidgetPainter) for a widget */ ToolkitScrollbar* GetScrollbarForWidget(OpWidget* widget); /** Get a slider (owned by this UnixWidgetPainter) for a widget */ ToolkitSlider* GetSliderForWidget(OpWidget* widget); ToolkitWidgetPainter* GetToolkitPainter() { return m_toolkit_painter; } private: ToolkitScrollbar::HitPart ConvertHitPartToToolkit(SCROLLBAR_PART_CODE part); OP_STATUS DrawWidget(ToolkitWidget* widget, const OpRect& cliprect); ToolkitWidgetPainter* m_toolkit_painter; OpWidgetInfo* m_widget_info; ToolkitScrollbar* m_scrollbar; ToolkitSlider* m_slider; }; #endif // UNIX_WIDGET_PAINTER_H
#include "driver.h" std::string Driver :: getName() { return jina; }
#include "comn.h" #include "city_forecast.h" #ifndef CITY_STATIS #define CITY_STATIS class stat_result { public: int avail_days; std::vector<int> min_t, min_t_high, min_t_low, max_t, max_t_high, max_t_low; std::vector<int> rain_all; std::vector<int> rain_right, rain_empty, rain_miss; //默认降水为4个时次 最高最低各为2个时次 stat_result() :rain_right(4,0), rain_empty(4,0), rain_miss(4,0),rain_all(4,0) ,min_t(2,0), min_t_high(2,0), min_t_low(2,0) ,max_t(2,0), max_t_high(2,0), max_t_low(2,0) { avail_days = 0; } }; bool stat_day(std::string worker, CTime when, std::map<int, stat_result> & statis_result); #endif //CITY_STATIS
#pragma once #include "controller.h" #include <chrono> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> class SFMLController : public Controller { private: sf::RenderWindow *window; Point<int> offset; bool _isLeftPressed, _wasLeftPressed; bool _isRightPressed, _wasRightPressed; Point<int> mousePos, oldMousePos; int prevLeftClickTime, leftClickTime; int getMilisecondsFromEpoch(); public: SFMLController(sf::RenderWindow *window); virtual ~SFMLController(); virtual void update(); virtual bool isLeftPressed(); virtual bool isRightPressed(); virtual bool wasLeftPressed(); virtual bool wasRightPressed(); virtual bool isLeftClicked(); virtual bool isRightClicked(); virtual bool wasLeftClickDouble(int gapInMiliseconds); virtual Point<float> getMousePos(); virtual Point<float> getPrevMousePos(); virtual Point<int> getOffset(); virtual void setOffset(Point<int> _offset); };
// // Runner.cpp // GLFW3 // // Created by William Meaton on 09/12/2015. // Copyright © 2015 WillMeaton.uk. All rights reserved. // #include "Runner.hpp" float Runner::r = 1; float Runner::g = 1; float Runner::b = 1; float Runner::a = 1; int Runner::keysPressed =0; int Runner::mbsPressed = 0; Runner::Runner(float windowWidth, float windowHeight, int frameRate,const char* title,BaseCore* c){ //assign the core to the pointer this->c = c; //sets the event call back method in basecore //set the error method in basecore glfwSetErrorCallback(errorCallback); //if it fails then exit if (!glfwInit()){ exit(EXIT_FAILURE); } //stop the window from being resizeable glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); //create the window using the height and stuff c->getWindow() = glfwCreateWindow(windowWidth, windowHeight, title, NULL, NULL); GLFWwindow* window = c->getWindow(); //set a userpointer for the window to this version of Runner glfwSetWindowUserPointer(window, this); //set the key_callback method glfwSetKeyCallback(window, keyCallback); //set mousepressed callback glfwSetMouseButtonCallback(window, mouseCallback); //set cursor call back glfwSetCursorPosCallback(window, cursorCallback); //set the window height/width in the BaseCore c->windowHeight = windowHeight; c->windowWidth = windowWidth; //if the window is dead, stop the program if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } //sets the context to the window glfwMakeContextCurrent(window); //sets the intervals of buffer swaps glfwSwapInterval(1); //set a base colour of black, makes it easier for beginners glColor4f(1, 1, 1, 1); //call setup for first time run c->setup(); //the game loop while (!glfwWindowShouldClose(window)) { int iconified = glfwGetWindowAttrib(window, GLFW_ICONIFIED); int focused = glfwGetWindowAttrib(window, GLFW_FOCUSED); //this stops the window running in the background and if it's been minimised if(iconified || !focused){ glfwWaitEvents(); } if(fps(frameRate)){ continue; } glClearColor(r, g, b, a); int width, height; //this allows GLtransparancy glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //set view port, allows pixeltopixel things glfwGetFramebufferSize(window, &width, &height); glViewport(0, 0, width, height); //clear the buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //set the ortho to pixels so it can be used like processing glOrtho(0.f, windowWidth, windowHeight, 0.f, -1.f, 1.f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //call update and then draw if the window isn't iconified if(!iconified && focused){ //draw c->draw(); } //swap the buffers glfwSwapBuffers(window); if(!iconified && focused){ c->update(); } glfwPollEvents(); } //end the program glfwDestroyWindow(window); glfwTerminate(); exit(EXIT_SUCCESS); } bool Runner::fps(int framerate) { currentTime = glfwGetTime(); if(currentTime - lastTime >= 1.0 / framerate) { lastTime = currentTime; return true; } return false; } void Runner::errorCallback(int error, const char* description){ fputs(description, stderr); } void Runner::cursorCallback(GLFWwindow* window, double xpos, double ypos){ void* data = glfwGetWindowUserPointer(window); Runner* r = static_cast<Runner*>(data); r->c->mouseX = xpos; r->c->mouseY = ypos; } void Runner::mouseCallback(GLFWwindow *window, int button, int action, int mods){ void* data = glfwGetWindowUserPointer(window); Runner* r = static_cast<Runner*>(data); if(action == GLFW_PRESS){ mbsPressed++; r->c->mousePressed(button); r->c->mouseIsPressed = true; r->c->mouseButton = button; return; } if(action == GLFW_RELEASE){ mbsPressed--; if(mbsPressed < 1){ r->c->mouseIsPressed = false; r->c->mouseButton = -1; } r->c->mouseReleased(button); return; } } void Runner::keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods){ if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ void* data = glfwGetWindowUserPointer(window); Runner* r = static_cast<Runner*>(data); r->c->exitCalled(); return; } void* data = glfwGetWindowUserPointer(window); Runner* r = static_cast<Runner*>(data); if(action == GLFW_PRESS){ r->c->keyIsPressed = true; r->c->keyCode = key; r->c->keyPressed(key); keysPressed++; return; } if(action == GLFW_RELEASE){ keysPressed--; if(keysPressed <1){ r->c->keyCode = 0; r->c->keyIsPressed = false; } r->c->keyReleased(key); return; } }
#include <iostream> #include <vector> using namespace std; int main() { std::pair<string,int> p1,p11; std::pair<float,int> p2; p1.first = "dae"; p1.second =20; p11.first = "somchai"; p11.second = -5; p2.first = 2.33; p2.second = 9999; p1 = p11; //p2 = p1; p11.first = "xxx"; cout << p1.first << " : " << p1.second << endl; cout << p2.first << " : " << p2.second << endl; cout << p11.first << " : " << p11.second << endl; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (5e18); const int INF = (1<<29); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; typedef pair<string, string> P; typedef pair<int, int> T; class Undo { public: P parse(string s) { string command = s.substr(0,4); string arg = s.substr(5); return P(command, arg); } int conv(string n) { int c; stringstream ss; ss << n; ss >> c; return c; } string getText(vector <string> commands, vector <int> time) { int N = (int)commands.size(); vector<int> use(N,1); vector<string> type(N,""); vector<T> step(N,T(-1,0)); for (int i=N-1; i>=0; --i) { P p = parse(commands[i]); if (p.first == "type") { type[i] = p.second; } else if (p.first == "undo" && use[i] == 1) { int n = conv(p.second); int t = time[i] - n; int p = (int)distance(time.begin(), lower_bound(time.begin(), time.end(), t)); for (int j=p; j<i; ++j) { use[j] = -use[j]; } } } string ans = ""; for (int i=0; i<N; ++i) { if (use[i] == 1) { ans += type[i]; } } return ans; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"type a", "type b", "type c", "undo 3"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 3, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "a"; verify_case(0, Arg2, getText(Arg0, Arg1)); } void test_case_1() { string Arr0[] = {"type a", "type b", "undo 2", "undo 2"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "a"; verify_case(1, Arg2, getText(Arg0, Arg1)); } void test_case_2() { string Arr0[] = {"type a", "undo 1", "undo 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "a"; verify_case(2, Arg2, getText(Arg0, Arg1)); } void test_case_3() { string Arr0[] = {"type a", "type b", "type c", "undo 10"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 3, 1000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "abc"; verify_case(3, Arg2, getText(Arg0, Arg1)); } void test_case_4() { string Arr0[] = {"undo 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = ""; verify_case(4, Arg2, getText(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { Undo ___test; ___test.run_test(-1); } // END CUT HERE
#include "global.h" #include "siet.h" /* void sir_na_z_vidale(short i,short j,short k,short smer,short zi,short zj,short zk) { Bod b(smer,i,j,k); b.sirFD(zi,zj,zk); if (b.t>-1) { pq.push(b); at[i][j][k] = b.t; } } void Bod::sir() { //vyber najmensieho prvku z haldy a sirenie vlny z neho if ((i == 0) || (j == 0) || (k == 0) || (i == nx-1) || (j == ny-1) || (k == nz-1)) { return; } if (s != 1) if (at[i-1][j][k]<-1) sir_na_z_vidale(i-1,j,k,-1,i,j,k); if (s !=-1) if (at[i+1][j][k]<-1) sir_na_z_vidale(i+1,j,k, 1,i,j,k); if (s != 2) if (at[i][j-1][k]<-1) sir_na_z_vidale(i,j-1,k,-2,i,j,k); if (s !=-2) if (at[i][j+1][k]<-1) sir_na_z_vidale(i,j+1,k, 2,i,j,k); if (s != 3) if (at[i][j][k-1]<-1) sir_na_z_vidale(i,j,k-1,-3,i,j,k); if (s !=-3) if (at[i][j][k+1]<-1) sir_na_z_vidale(i,j,k+1, 3,i,j,k); } */ float stencil_A(const float &v,const float &t0,const float &t1,const float &t2,const float &t3,const float &t4,const float &t5,const float &t6) { float ss = 1.f/SQR(v); return t0 + sqrtf((6.f*ss - min(SQR(t1 - t2),ss) - min(SQR(t2 - t4),ss) - min(SQR(t4 - t1),ss) - min(SQR(t3 - t5),ss) - min(SQR(t5 - t6),ss) - min(SQR(t6 - t3),ss))/2.f); //return t0 + sqrtf((6.f/SQR(v) - SQR(t1 - t2) - SQR(t2 - t4) - SQR(t4 - t1) - SQR(t3 - t5) - SQR(t5 - t6) - SQR(t6 - t3))/2.f); } float stencil_B(const float &v,const float &t0,const float &t1,const float &t2,const float &t3,const float &t4) { return t1 + sqrtf(2.f/SQR(v) - 0.5f*SQR(t0 - t3) - SQR(t2 - t4)); } float stencil_C(const float &v,const float &t0,const float &t1,const float &t2,const float &t3,const float &t4) { return t2 + sqrtf(1.f/SQR(v) - 0.25f*(SQR(t1 - t3) + SQR(t0 - t4))); } void Bod::sirFD(const short &si, const short &sj, const short &sk) { float tl,tp,td,th,tld,tpd,tlh,tph,sl,sp,sd,sh,sld,spd,slh,sph,sc; sc = at[si][sj][sk]; float w = (v[si][sj][sk] + v[i][j][k])/2.f; if (s == 1 || s == -1) { tl = at[i][j+1][k]; tp = at[i][j-1][k]; th = at[i][j][k+1]; td = at[i][j][k-1]; tld = at[i][j+1][k-1]; tpd = at[i][j-1][k-1]; tlh = at[i][j+1][k+1]; tph = at[i][j-1][k+1]; sl = at[si][j+1][k]; sp = at[si][j-1][k]; sh = at[si][j][k+1]; sd = at[si][j][k-1]; sld = at[si][j+1][k-1]; spd = at[si][j-1][k-1]; slh = at[si][j+1][k+1]; sph = at[si][j-1][k+1]; } else if (s == 2 || s == -2) { tl = at[i+1][j][k]; tp = at[i-1][j][k]; th = at[i][j][k+1]; td = at[i][j][k-1]; tld = at[i+1][j][k-1]; tpd = at[i-1][j][k-1]; tlh = at[i+1][j][k+1]; tph = at[i-1][j][k+1]; sl = at[i+1][sj][k]; sp = at[i-1][sj][k]; sh = at[i][sj][k+1]; sd = at[i][sj][k-1]; sld = at[i+1][sj][k-1]; spd = at[i-1][sj][k-1]; slh = at[i+1][sj][k+1]; sph = at[i-1][sj][k+1]; } else { tl = at[i][j+1][k]; tp = at[i][j-1][k]; th = at[i+1][j][k]; td = at[i-1][j][k]; tld = at[i-1][j+1][k]; tpd = at[i-1][j-1][k]; tlh = at[i+1][j+1][k]; tph = at[i+1][j-1][k]; sl = at[i][j+1][sk]; sp = at[i][j-1][sk]; sh = at[i+1][j][sk]; sd = at[i-1][j][sk]; sld = at[i-1][j+1][sk]; spd = at[i-1][j-1][sk]; slh = at[i+1][j+1][sk]; sph = at[i+1][j-1][sk]; } if (tl>-1) { if (td>-1 && tld>-1 && sl>-1 && sd>-1 && sld>-1) { t = stencil_A(w,sld,tld,sd,td,sl,tl,sc); return; } if (th>-1 && tlh>-1 && sl>-1 && sh>-1 && slh>-1) { t = stencil_A(w,slh,tlh,sh,th,sl,tl,sc); return; } } if (tp>-1) { if (td>-1 && tpd>-1 && sp>-1 && sd>-1 && spd>-1) { t = stencil_A(w,spd,tpd,sd,td,sp,tp,sc); return; } if (th>-1 && tph>-1 && sp>-1 && sh>-1 && sph>-1) { t = stencil_A(w,sph,tph,sh,th,sp,tp,sc); return; } } if (td>-1) { if (sd>-1 && sld>-1 && spd>-1) { t = stencil_B(w,sld,sd,td,spd,sc); return; } } if (th>-1) { if (sh>-1 && slh>-1 && sph>-1) { t = stencil_B(w,slh,sh,th,sph,sc); return; } } if (tl>-1) { if (sl>-1 && sld>-1 && slh>-1) { t = stencil_B(w,sld,sl,tl,slh,sc); return; } } if (tp>-1) { if (sp>-1 && spd>-1 && sph>-1) { t = stencil_B(w,spd,sp,tp,sph,sc); return; } } if (sl>-1 && sp>-1 && sd>-1 && sh>-1) { t = stencil_C(w,sp,sd,sc,sh,sl); return; } t = -2; #ifdef DEBUG cout<<"ERR1402050946 NO STENCIL"<<endl; #endif }
#ifndef QTEXCEL_H #define QTEXCEL_H #include <QObject> #include <QFile> #include <QString> #include <QStringList> #include <QVariant> #include <QAxBase> #include <QAxObject> typedef unsigned int UINT; class QtExcel { public: QtExcel(); QtExcel(QString xlsFile); ~QtExcel(); public: bool Open(UINT nSheet = 1, bool visible = false); //打开xls文件 bool Open(QString xlsFile, UINT nSheet = 1, bool visible = false); void Save(); //保存xls报表 void SaveAs(QString path, bool isXls = true); //另存为xls报表 void Close(); //关闭xls报表 QVariant GetCellData(UINT row, UINT column); //获取指定单元数据 QVariantList GetCellData(QString strRange); //获取多个单元数据,写法为“A2:C60” bool SetCellData(UINT row, UINT column, QVariant data); //修改指定单元数据 bool IsOpen(); bool IsValid(); protected: void Clear(); private: QAxObject *m_pExcel; //指向整个excel应用程序 QAxObject *m_pWorkbooks; //指向工作簿集,excel有很多工作簿 QAxObject *m_pWorkbook; //指向sXlsFile对应的工作簿 QAxObject *m_pWorksheet; //指向工作簿中的某个sheet表单 QString m_strXlsFile; //xls文件路径 UINT m_nCurrSheet; //当前打开的第几个sheet bool m_bIsVisible; //excel是否可见 int m_nRowCount; //行数 int m_nColumnCount; //列数 int m_nStartRow; //开始有数据的行下标值 int m_nStartColumn; //开始有数据的列下标值 bool m_bIsOpen; //是否已打开 bool m_bIsValid; //是否有效 bool m_bIsANewFile; //是否是一个新建xls文件,用来区分打开的excel是已存在文件还是有本类新建的 bool m_bIsSaveAlready;//防止重复保存 }; #endif // QTEXCEL_H
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <sstream> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> #include <numeric> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; struct Tp { int x, c; bool operator<(const Tp& B)const{ return c < B.c; } } a[111111]; int n, k; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); cin >> n >> k; for (int i = 0; i < n; i++) { cin >> a[i].x; a[i].c = a[i].x; } sort(a, a + n); LL ans = 0; int cc = 0; for (int i = n - 1; i >= 0; i--) { ans += a[i].x * (1 + cc / k); ++cc; } cout << ans << endl; return 0; }
// RsaToolbox includes #include "General.h" #include "VnaMarker.h" #include "VnaChannel.h" #include "Vna.h" using namespace RsaToolbox; // Qt includes // #include <Qt> /*! * \class RsaToolbox::VnaMarker * \ingroup VnaGroup * \brief The \c %VnaMarker class * is used to control a marker * on a trace. */ VnaMarker::VnaMarker(QObject *parent) : QObject(parent) { placeholder.reset(new Vna()); _vna = placeholder.data(); _trace.reset(new VnaTrace()); _traceName = QString(); _index = 0; } VnaMarker::VnaMarker(const VnaMarker &other) { if (other.isFullyInitialized()) { _vna = other._vna; _trace.reset(new VnaTrace(*other._trace.data())); _traceName = other._traceName; _index = other._index; } else { placeholder.reset(new Vna()); _vna = placeholder.data(); _trace.reset(new VnaTrace()); _traceName = QString(); _index = 0; } } VnaMarker::VnaMarker(Vna *vna, VnaTrace *trace, uint index, QObject *parent) : QObject(parent) { _vna = vna; _trace.reset(new VnaTrace(*trace)); _traceName = trace->name(); _index = index; } VnaMarker::VnaMarker(Vna *vna, QString traceName, uint index, QObject *parent) : QObject(parent) { _vna = vna; _trace.reset(new VnaTrace(vna, traceName)); _traceName = traceName; _index = index; } VnaMarker::~VnaMarker() { } QString VnaMarker::name() { _trace->select(); QString scpi = ":CALC%1:MARK%2:NAME?\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); return(_vna->query(scpi).trimmed().remove('\'')); } void VnaMarker::setName(QString name) { _trace->select(); QString scpi = ":CALC%1:MARK%2:NAME \'%3\'\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); scpi = scpi.arg(name); _vna->write(scpi); } bool VnaMarker::isDeltaOn() { _trace->select(); QString scpi = ":CALC%1:MARK%2:DELT?\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); return(_vna->query(scpi).trimmed() == "1"); } bool VnaMarker::isDeltaOff() { return(!isDeltaOn()); } void VnaMarker::deltaOn(bool isOn) { _trace->select(); QString scpi = ":CALC%1:MARK%2:DELT %3\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); if (isOn) scpi = scpi.arg(1); else scpi = scpi.arg(0); _vna->write(scpi); } void VnaMarker::deltaOff(bool isOff) { deltaOn(!isOff); } double VnaMarker::y() { _trace->select(); QString scpi = ":CALC%1:MARK%2:Y?\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); return(_vna->query(scpi).trimmed().toDouble()); } double VnaMarker::x() { _trace->select(); QString scpi = ":CALC%1:MARK%2:X?\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); return(_vna->query(scpi).trimmed().toDouble()); } void VnaMarker::coordinates(double &x, double &y) { x = this->x(); y = this->y(); } void VnaMarker::setX(double x, SiPrefix prefix) { _trace->select(); QString scpi = ":CALC%1:MARK%2:X %3\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); scpi = scpi.arg(x * toDouble(prefix), 0, 'E', 12); _vna->write(scpi); } void VnaMarker::searchForMax() { searchForScpi("MAX"); } void VnaMarker::searchForMin() { searchForScpi("MIN"); } void VnaMarker::searchFor(double y) { setSearchValue(y); searchForScpi("TARG"); } void VnaMarker::searchRightFor(double y) { setSearchValue(y); searchForScpi("RTAR"); } void VnaMarker::searchRightForPeak() { searchForScpi("RPE"); } void VnaMarker::searchLeftFor(double y) { setSearchValue(y); searchForScpi("LTAR"); } void VnaMarker::searchLeftForPeak() { searchForScpi("LPE"); } // Calculate: void VnaMarker::measureBandpassFilter() { } void VnaMarker::operator=(VnaMarker const &other) { if (other.isFullyInitialized()) { _vna = other._vna; _trace.reset(new VnaTrace(*other._trace.data())); _traceName = other._traceName; _index = other._index; } else { placeholder.reset(new Vna()); _vna = placeholder.data(); _trace.reset(new VnaTrace()); _traceName = QString(); _index = 0; } } // Private bool VnaMarker::isFullyInitialized() const { if (_vna == NULL) return(false); if (_vna == placeholder.data()) return(false); //else return(true); } void VnaMarker::setSearchValue(double value) { _trace->select(); QString scpi = "CALC%1:MARK%2:TARG %3\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); scpi = scpi.arg(value); _vna->write(scpi); } void VnaMarker::searchForScpi(QString type) { _trace->select(); QString scpi = ":CALC%1:MARK%2:FUNC:EXEC %3\n"; scpi = scpi.arg(_trace->channel()); scpi = scpi.arg(_index); scpi = scpi.arg(type); _vna->write(scpi); }
/* -*- coding: utf-8 -*- !@time: 2020/3/6 21:21 !@author: superMC @email: 18758266469@163.com !@fileName: 0051_building_product_array.cpp */ #include <environment.h> class Solution { public: vector<int> multiply(const vector<int> &A) { if (A.empty()) return A; vector<int> b(A.size(), 1); int tmp = 1; for (int i = 1; i < A.size(); ++i) { tmp = tmp * A[i - 1]; b[i] = tmp; } tmp = 1; for (int j = A.size() - 2; j >= 0; --j) { tmp = tmp * A[j + 1]; b[j] = tmp * b[j]; } return b; } }; int fun() { vector<int> A = {1, 2, 3, 4, 5}; Solution().multiply(A); return 0; }
#ifndef _YTOPEN_SDK_ #define _YTOPEN_SDK_ #include <string> #include <vector> class ytopen_sdk { public: typedef struct AppSign { uint32_t app_id; std::string secret_id; std::string secret_key; uint32_t expired; std::string user_id; }AppSign; public: void Init(const AppSign& t_app_sign, const std::string& t_host); void DetectFace(const std::string& imageData, std::string &rsp); void FaceCompare(const std::string& imageA, const std::string&imageB, std::string &rsp); void FaceVerify(const std::string& person_id, const std::string& imageData, std::string &rsp); void FaceIdentify(const std::string& group_id, const std::string& imageData, std::string &rsp); void NewPerson(const std::string& person_id, const std::string &person_name, const std::vector<std::string> &group_ids, const std::string& imageData, const std::string &tag, std::string &rsp); void DelPerson(const std::string& person_id, std::string &rsp); void AddFace(const std::string& person_id, const std::vector<std::string>& imageDatas, const std::string &tag, std::string &rsp); void DelFace(const std::string& person_id, const std::vector<std::string>& face_ids, std::string &rsp); void SetInfo(const std::string& person_id, const std::string& person_name, const std::string& tag, std::string &rsp); void GetInfo(const std::string& person_id, std::string &rsp); void GetGroupIds(std::string &rsp); void GetPersonIds(const std::string& group_id, std::string &rsp); void GetFaceIds(const std::string& person_id, std::string &rsp); void GetFaceInfo(const std::string&face_id , std::string &rsp); private: void curl_method(const std::string& addr, const std::string &req_str, std::string &rsp_str); private: std::string host; AppSign app_sign; std::string app_id; }; #endif
#include "stdlib.h" #include "stdio.h" int main(int argc, char **argv) { int *arr = new int[12]; return 0; }
// VideoManager.cpp : 定义应用程序的入口点。 // #ifdef WIN32 #include <shlobj.h> #endif #include "framework.h" #include "VideoManager.h" #include "VMDef.h" #include "shlwapi.h" #define MAX_LOADSTRING 100 #pragma comment(lib, "shlwapi.lib") // 全局变量: HINSTANCE hInst; // 当前实例 WCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 WCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 // 自定义全局变量 CONFIG g_config; // 此代码模块中包含的函数的前向声明: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: 在此处放置代码。 // 初始化全局字符串 LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_VIDEOMANAGER, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } // 初始化配置 IniConfig(); // 若无根目录配置,主动弹出根目录选择对话框 HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_VIDEOMANAGER)); MSG msg; // 主消息循环: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // 函数: MyRegisterClass() // // 目标: 注册窗口类。 // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_VIDEOMANAGER)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_VIDEOMANAGER); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // 函数: InitInstance(HINSTANCE, int) // // 目标: 保存实例句柄并创建主窗口 // // 注释: // // 在此函数中,我们在全局变量中保存实例句柄并 // 创建和显示主程序窗口。 // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // 将实例句柄存储在全局变量中 HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // 函数: WndProc(HWND, UINT, WPARAM, LPARAM) // // 目标: 处理主窗口的消息。 // // WM_COMMAND - 处理应用程序菜单 // WM_PAINT - 绘制主窗口 // WM_DESTROY - 发送退出消息并返回 // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); // 分析菜单选择: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; case ID_CHOSEFILEROOT: //选择系统文件的根目录文件夹 ChoseFileRoot(); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: 在此处添加使用 hdc 的任何绘图代码... EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // “关于”框的消息处理程序。 INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } //选择系统的根目录文件夹 void ChoseFileRoot() { //弹出文件选择对话框 BROWSEINFO bi; bi.hwndOwner = NULL; bi.pidlRoot = CSIDL_DESKTOP;//文件夹的根目录,此处为桌面 bi.pszDisplayName = NULL; bi.lpszTitle = NULL;//显示位于对话框左上部的提示信息 bi.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;//有新建文件夹按钮 bi.lpfn = NULL; bi.iImage = 0; LPITEMIDLIST pidl = SHBrowseForFolder(&bi);//调用选择对话框 if (pidl == NULL) { MessageBox(NULL, "没有配置玩你妈呢", NULL, 0); return ; } TCHAR strFolder[MAX_PATH]; SHGetPathFromIDList(pidl, strFolder); //将根目录文件夹的路径存储到全局标识符中 g_config.rootPath = strFolder; MessageBox(NULL, g_config.rootPath, NULL, 0); } ///<summary> /// Function:获得当前程序所在路径 /// Author :Webster /// Date :2020年9月13日18:27:27 /// ParamIn :NULL /// ParamOut:path 程序路径 ///</summary> bool VM_GetModuleFilePath(char* path) { TCHAR szPath[MAX_PATH] = { 0 }; if (!GetModuleFileName(NULL, szPath, MAX_PATH)) { return false; } char drive[5]; char dir[100]; char filename[100]; char fileext[10]; // 拆分获取当前程序所处的驱动器号、文件夹路径、文件名和文件类型 _splitpath_s(szPath, drive, dir, filename, fileext); // 组合path的到当前程序的所在路径 _makepath_s(path, _MAX_PATH, drive, dir, NULL, NULL); return true; } ///<summary> /// Function:读取文件初始化配置 /// Author :Webster /// Date :2020年9月13日18:34:25 /// ParamIn :path config.ini文件路径 /// ParamOut: ///</summary> bool IniConfigByPath(char* iniPath) { // 确定工作根目录 char buf[MAX_PATH] = {0}; GetPrivateProfileString("ROOT", //节名 "path", //项名 "No Path", //没找到此项时的返回值 buf, //目标缓冲区地址 MAX_PATH, //目标缓冲区长度 iniPath); //配置文件的准确路径 g_config.rootPath = buf; // 检查根目录是否存在 if (PathIsDirectory(g_config.rootPath) != FILE_ATTRIBUTE_DIRECTORY) { return CONFIG_NOROOTFILE; } return CONFIG_SUCESS; } ///<summary> /// Function:初始化配置 /// Author :Webster /// Date :2020年9月13日18:37:34 /// ParamIn :NULL /// ParamOut:NULL ///</summary> bool IniConfig() { // 获得程序所在文件夹 char path[MAX_PATH] = { 0 }; VM_GetModuleFilePath(path); // 获得配置文件地址iniPath char iniPath[MAX_PATH]; char fileName[] = "config.ini"; sprintf_s(iniPath, "%.*s%.*s", sizeof(path), path, sizeof(fileName), fileName); if (IniConfigByPath(iniPath) == CONFIG_NOROOTFILE) // 无工作目录配置信息 { ChoseFileRoot(); // 选择工作目录 // TODO:将当前工作目录写入配置文件 } return CONFIG_SUCESS; }
#define BOOST_SP_DISABLE_THREADS #include <iostream> #include <iomanip> #include <dax/Types.h> #include <dax/cont/Scheduler.h> #include <dax/cont/arg/ExecutionObject.h> #include <dax/exec/WorkletMapField.h> #include <dax/cont/Timer.h> #include "Point3D.h" #include "tests/RandomPoints3D.h" #include "PointLocator.h" #include "PointLocatorExec.h" using namespace dax::cont; struct TestWorklet : dax::exec::WorkletMapField { // signatures typedef void ControlSignature(Field(In), ExecObject(), Field(Out), Field(Out), Field(Out)); // bucketId, point count, coincident point typedef void ExecutionSignature(_1, _2, _3, _4, _5); // overload operator() template<typename Functor> DAX_EXEC_EXPORT void operator()(const dax::Vector3& point, const Functor& execLocator, dax::Id& bucketId, int& pointCount, dax::Vector3& coinPoint) const { bucketId = execLocator.getBucketId(point); pointCount = execLocator.getBucketPointCount(bucketId); dax::Id coinId = execLocator.findPoint(point); if (coinId < 0) coinPoint = dax::make_Vector3(-1.f, -1.f, -1.f); else coinPoint = execLocator.getPoint(coinId); } }; // main int main(void) { // first generate a bunch of random points RandomPoints3D random; random.setExtent(0, 3, 0, 3, 0, 3); random.setPointCount(20); random.generate(); std::vector<Point3D> points = random.getPoints(); points.push_back(Point3D(0.99, 0.99, 0.99)); // translate Point3D to dax::vector3 std::vector<dax::Vector3> daxPoints(points.size()); for (unsigned int i = 0; i < points.size(); ++i) { Point3D point = points[i]; dax::Vector3 daxvec(point.x(), point.y(), point.z()); daxPoints[i] = daxvec; } // initialize the dax::cont::Timer Timer<> timer; timer.Reset(); // use PointLocator class PointLocator locator; locator.setDimensions(3, 3, 3); locator.setBounds(3, 3, 3); locator.setPoints(daxPoints); locator.build(); std::cout.precision(4); std::cout << std::fixed; // search strcuture construction timing result dax::Scalar time_construct = timer.GetElapsedTime(); std::cout << std::setw(10) << "Const: " << std::setw(6) << time_construct << std::endl; // outputs std::vector<dax::Vector3> sortPoints = locator.getSortPoints(); std::vector<dax::Id> pointStarts = locator.getPointStarts(); std::vector<int> pointCounts = locator.getPointCounts(); // print std::cout << std::setw(10) << "Sort X: "; for (unsigned int i = 0; i < sortPoints.size(); ++i) std::cout << std::setw(6) << sortPoints[i][0] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Sort Y: "; for (unsigned int i = 0; i < sortPoints.size(); ++i) std::cout << std::setw(6) << sortPoints[i][1] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Sort Z: "; for (unsigned int i = 0; i < sortPoints.size(); ++i) std::cout << std::setw(6) << sortPoints[i][2] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Pt Start: "; for (unsigned int i = 0; i < pointStarts.size(); ++i) std::cout << std::setw(3) << pointStarts[i] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Pt Count: "; for (unsigned int i = 0; i < pointCounts.size(); ++i) std::cout << std::setw(3) << pointCounts[i] << ", "; std::cout << std::endl; // setup the PointLocatorExec, which is a ExecutionObject PointLocatorExec execLocator = locator.prepareExecutionObject(); // use the local TestWorklet to test the PointLocatorExec // 1. create test inputs, which are points std::vector<dax::Vector3> testPoints(19); for (int i = 0; i < 19; ++i) testPoints[i] = daxPoints[i]; testPoints.push_back(dax::make_Vector3(0.0, 0.0, 0.0)); ArrayHandle<dax::Vector3> hTestPoints = make_ArrayHandle(testPoints); // 2. create output array handles ArrayHandle<dax::Id> hTestBucketIds; ArrayHandle<int> hTestCounts; ArrayHandle<dax::Vector3> hTestCoinPoints; // 3. run the worklet Scheduler<> scheduler; scheduler.Invoke(TestWorklet(), hTestPoints, execLocator, hTestBucketIds, hTestCounts, hTestCoinPoints); // 4. copy the output std::vector<dax::Id> testBucketIds(hTestBucketIds.GetNumberOfValues()); std::vector<int> testCounts(hTestCounts.GetNumberOfValues()); std::vector<dax::Vector3> testCoinPoints(hTestCoinPoints.GetNumberOfValues()); hTestBucketIds.CopyInto(testBucketIds.begin()); hTestCounts.CopyInto(testCounts.begin()); hTestCoinPoints.CopyInto(testCoinPoints.begin()); // 5. print std::cout << std::setw(10) << "Test X: "; for (unsigned int i = 0; i < testPoints.size(); ++i) std::cout << std::setw(6) << testPoints[i][0] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Test Y: "; for (unsigned int i = 0; i < testPoints.size(); ++i) std::cout << std::setw(6) << testPoints[i][1] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Bucket: "; for (unsigned int i = 0; i < testBucketIds.size(); ++i) std::cout << std::setw(6) << testBucketIds[i] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Count: "; for (unsigned int i = 0; i < testCounts.size(); ++i) std::cout << std::setw(6) << testCounts[i] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Coin X: "; for (unsigned int i = 0; i < testCoinPoints.size(); ++i) std::cout << std::setw(6) << testCoinPoints[i][0] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Coin Y: "; for (unsigned int i = 0; i < testCoinPoints.size(); ++i) std::cout << std::setw(6) << testCoinPoints[i][1] << ", "; std::cout << std::endl; std::cout << std::setw(10) << "Coin Z: "; for (unsigned int i = 0; i < testCoinPoints.size(); ++i) std::cout << std::setw(6) << testCoinPoints[i][2] << ", "; std::cout << std::endl; return 0; }
#ifndef SCENE_HPP #define SCENE_HPP #include <list> #include "shape.hpp" #include "light_source.hpp" #include "camera.hpp" #include "material.hpp" #include <string> #include <map> struct scene { public: scene(); scene(std::string const& datei); scene(const scene& orig); virtual ~scene(); void render(camera const& cam, std::string const& filename, double const&, double const&); void sdfloader(); // void sdfloader(std::string const&); void scenetest(); std::list<shape*> ls_; std::list<light_source> lls_; std::map<std::string,material> mmat_; camera cam_; light_source ambientl_; private: }; #endif /* SCENE_HPP */
#pragma once #include"TorreTeamA.h" #include<list> class ListTorreTeamA { public: ListTorreTeamA(); ~ListTorreTeamA(); list<TorreTeamA*> list_TorreA; void Agregar(int x, int y, int vida, Bitmap^bmp); void Mostrar(Graphics^gr, Bitmap^bmp); }; ListTorreTeamA::ListTorreTeamA() { } ListTorreTeamA::~ListTorreTeamA() { } void ListTorreTeamA::Agregar(int x, int y, int vida, Bitmap^bmp){ list_TorreA.push_back(new TorreTeamA(x, y, vida, bmp)); } void ListTorreTeamA::Mostrar(Graphics^gr, Bitmap^bmp){ for (list<TorreTeamA*>::iterator it = list_TorreA.begin(); it != list_TorreA.end();++it){ if ((*it)->GET_transparente() == true){ (*it)->Dibujar(gr, bmp); (*it)->DibujarVida(gr); } } }
#include <iostream> #include "Q02.h" using namespace std; void CreateWeightGraphMatrix(MGraph *G) { G->numEdges = 15; G->numVertexes = MAXSIZE; /* 读入顶点信息,建立顶点表 */ G->vexs[0] = 'A'; G->vexs[1] = 'B'; G->vexs[2] = 'C'; G->vexs[3] = 'D'; G->vexs[4] = 'E'; G->vexs[5] = 'F'; G->vexs[6] = 'G'; G->vexs[7] = 'H'; G->vexs[8] = 'I'; for(int i=0; i<G->numVertexes; i++) { for(int j=0; j<G->numVertexes; j++) { G->arc[i][j] = 0; } } /* A B C D E F G H I A 0 2 0 0 0 9 0 0 0 B 0 0 5 0 0 0 3 0 7 C 0 0 0 1 0 0 0 0 2 D 0 0 0 0 6 0 4 1 9 E 0 0 0 0 0 5 0 4 0 F 0 0 0 0 0 0 1 0 0 G 0 0 0 0 0 0 0 8 0 H 0 0 0 0 0 0 0 0 0 I 0 0 0 0 0 0 0 0 0 */ G->arc[0][1] = 2; // A->B G->arc[0][5] = 9; // A->F G->arc[1][2] = 5; // B->C G->arc[1][6] = 3; // B->G G->arc[1][8] = 7; // B->I G->arc[2][3] = 1; // C->D G->arc[2][8] = 2; // C->I G->arc[3][4] = 6; // D->E G->arc[3][6] = 4; // D->G G->arc[3][7] = 1; // D->H G->arc[3][8] = 9; // D->I G->arc[4][5] = 5; // E->F G->arc[4][7] = 4; // E->H G->arc[5][6] = 1; // F->G G->arc[6][7] = 8; // G->H for(int i=0; i<G->numVertexes; i++) { for(int j=i; j<G->numVertexes; j++) { if(G->arc[i][j] == 0) G->arc[i][j] = INFINITY; G->arc[j][i] = G->arc[i][j]; } } cout << "邻接矩阵创建完成:" << endl; for(int i=0; i<G->numVertexes; i++) { for(int j=0; j<G->numVertexes; j++) { cout << G->arc[i][j] << '\t'; } cout << endl; } } void CreateWeightGraphList(MGraph G, GraphAdjList *GL) { EdgeNode* e; *GL = (GraphAdjList)malloc(sizeof(graphAdjList)); (*GL)->numVertexes = G.numVertexes; (*GL)->numEdges = G.numEdges; for(int i=0; i<G.numVertexes; i++) /* 读入顶点信息,建立顶点表 */ { (*GL)->adjList[i].in = 0; (*GL)->adjList[i].data = G.vexs[i]; (*GL)->adjList[i].firstEdge = nullptr; // 将边表置空 } for(int i=0; i<G.numVertexes; i++) { for(int j=0; j<G.numVertexes; j++) { if(G.arc[i][j] != 0) { e = (EdgeNode*)malloc(sizeof(EdgeNode)); e->weight = G.arc[i][j]; e->adjvex = j; /* 邻接序号为j */ e->next = (*GL)->adjList[i].firstEdge; /* 将当前顶点上的指向的结点指针赋值给e */ (*GL)->adjList[i].firstEdge = e; /* 将当前顶点的指针指向e */ (*GL)->adjList[j].in++; } } } for(int i=0; i<MAXSIZE; i++) { (*GL)->vexs[i] = G.vexs[i]; } cout << "邻接表创建完成:" << endl; for(int i=0; i<(*GL)->numVertexes; i++) { cout << (*GL)->vexs[i]; e = (*GL)->adjList[i].firstEdge; while(e) { cout << "->" << G.vexs[e->adjvex] << e->weight; e = e->next; } cout << endl; } } // 在辅助数组中找出权值最小的边的数组下标,就可以间接找到此边的终点顶点。 int minimum(MGraph MG, CloseEdge close) { int min = INFINITY; int min_i = -1; for(int vexId=0; vexId<MG.numVertexes; vexId++) { //权值为0,说明顶点已经归入最小生成树中;然后每次和min变量进行比较,最后找出最小的。 if(close[vexId].lowcost > 0 && close[vexId].lowcost < min) { min = close[vexId].lowcost; min_i = vexId; } } return min_i; } // 将所有点分成已知和未知,然后不断在已知的点中和未知点中寻找最小的边,然后将未知变成已知 void Prim(MGraph MG) { int startVexId = 1, minVexId; //首先将与该起始点相关的所有边的信息 for(int i=0; i<MG.numVertexes; i++) { if(MG.arc[startVexId][i] != 0) { gClose[i].adjvex = i; gClose[i].lowcost = MG.arc[startVexId][i]; } } gClose[startVexId].lowcost = 0; printf("%c", MG.vexs[startVexId]); for(int i=1; i<MG.numVertexes; i++) { minVexId = minimum(MG, gClose); printf("--%d-->%c", gClose[minVexId].lowcost, MG.vexs[gClose[minVexId].adjvex]); //归入最小生成树的顶点的辅助数组中的权值设为0 gClose[minVexId].lowcost = 0; // 信息辅助数组中存储的信息,由于此时树中新加入了一个顶点,需要判断, // 由此顶点出发,到达其它各顶点的权值是否比之前记录的权值还要小,如果还小,则更新 for(int j=0; j<MG.numVertexes; j++) { if(MG.arc[minVexId][j] < gClose[j].lowcost) { gClose[j].adjvex = j; gClose[j].lowcost = MG.arc[minVexId][j]; } } } printf("\n"); } void Prim(GraphAdjList LG) { } void CreateEdges(const MGraph *MG, Edge edges[]) { cout << "bug" << endl; for(int i=0; i<MAXSIZE; i++) { cout << MG->vexs[i] << ' '; } cout << endl; cout << "bug" << endl; int edgeId = 0; Edge* e; int vertexValues[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // 顶点实际id for(int i=0; i<MG->numVertexes; i++) { // MG.arc[i][i] = vertexValues[i]; // 对角线存放顶点的值 for(int j=0; j<MG->numVertexes; j++) { if((MG->arc[i][j] < INFINITY) && (i!=j)) { e = (Edge*)malloc(sizeof(Edge)); e->weight = MG->arc[i][j]; // e->startVex = MG.arc[i][i]; // e->endVex = MG.arc[j][j]; e->startVex = vertexValues[i]; e->endVex = vertexValues[j]; edges[edgeId] = *e; edgeId++; cout << i << ' ' << j << ' ' << MG->arc[i][j] << endl; for(int k=0; k<MAXSIZE; k++) { cout << (*MG).vexs[k] << ' '; } cout << endl; } } assists[i].value = vertexValues[i]; // vertex value assists[i].sign = i; // vertex id } cout << "bug" << endl; for(int x=0; x<MAXSIZE; x++) { cout << (*MG).vexs[x] << ' '; } cout << endl; cout << "bug" << endl; } int cmp(const void *a, const void *b) { return ((Edge*)a)->weight - ((Edge*)b)->weight; } // 返回顶点id int LocateVex(int numVertexes, int point) { for(int i=0; i<numVertexes; i++) { if(assists[i].value == point) // 判断顶点是否相同 { return i; } } return -1; } /* http://data.biancheng.net/view/41.html 将所有边按照权值的大小进行升序排序,然后从小到大一一判断,条件为:如果这个边不会与之前选择的所有边组成回路, 就可以作为最小生成树的一部分;反之,舍去。直到具有 n 个顶点的连通网筛选出来 n-1 条边为止。筛选出来的边和 所有的顶点构成此连通网的最小生成树。 */ void Kruskal(MGraph MG) { printf("\n"); Edge edges[MAXEDGE], minTree[MAXSIZE]; int treeEdgeId = 0; CreateEdges(&MG, edges); cout << "11111" << endl; for(int i; i<MAXSIZE; i++) { cout << MG.vexs[i] << ' '; } cout << endl; qsort(edges, MAXEDGE, sizeof(edges[0]), cmp); // 遍历所有的边 for(int eId=0; eId<MAXEDGE; eId++) { // cout << "---" << eId << "---" << endl; int startVexId = LocateVex(MG.numVertexes, edges[eId].startVex); int endVexId = LocateVex(MG.numVertexes, edges[eId].endVex); //如果顶点位置存在且顶点的标记不同,说明不在一个集合中,不会产生回路 if(startVexId!=-1 && endVexId!=-1 && assists[startVexId].sign!=assists[endVexId].sign) { cout << startVexId << "-->" << endVexId << endl; cout << MG.vexs[startVexId] << "==>" << MG.vexs[endVexId] << endl; //记录该边,作为最小生成树的组成部分 minTree[treeEdgeId++] = edges[eId]; //将新加入生成树的顶点标记全部更改为一样的:3->4: 3->3 for(int i=0; i<MG.numVertexes; i++) { if(assists[i].sign == assists[endVexId].sign) { assists[i].sign = assists[startVexId].sign; } } //如果选择的边的数量和顶点数相差1,证明最小生成树已经形成,退出循环 if(treeEdgeId == MG.numVertexes-1) break; } // cout << "===" << treeEdgeId << "===" << MG.numVertexes-1 << endl; } printf("===========\n"); for(int i=0; i<MG.numVertexes-1; i++) { if(i == 0) { printf("%d->%d", MG.vexs[minTree[i].startVex-1], MG.vexs[minTree[i].endVex-1]); } else { printf("->%d", MG.vexs[minTree[i].endVex-1]); } } } void Kruskal(GraphAdjList LG) { }
/* * @lc app=leetcode id=990 lang=cpp * * [990] Satisfiability of Equality Equations * * https://leetcode.com/problems/satisfiability-of-equality-equations/description/ * * algorithms * Medium (40.64%) * Likes: 213 * Dislikes: 3 * Total Accepted: 8.5K * Total Submissions: 20.8K * Testcase Example: '["a==b","b!=a"]' * * Given an array equations of strings that represent relationships between * variables, each string equations[i] has length 4 and takes one of two * different forms: "a==b" or "a!=b".  Here, a and b are lowercase letters (not * necessarily different) that represent one-letter variable names. * * Return true if and only if it is possible to assign integers to variable * names so as to satisfy all the given equations. * * * * * * * * Example 1: * * * Input: ["a==b","b!=a"] * Output: false * Explanation: If we assign say, a = 1 and b = 1, then the first equation is * satisfied, but not the second. There is no way to assign the variables to * satisfy both equations. * * * * Example 2: * * * Input: ["b==a","a==b"] * Output: true * Explanation: We could assign a = 1 and b = 1 to satisfy both equations. * * * * Example 3: * * * Input: ["a==b","b==c","a==c"] * Output: true * * * * Example 4: * * * Input: ["a==b","b!=c","c==a"] * Output: false * * * * Example 5: * * * Input: ["c==c","b==d","x!=z"] * Output: true * * * * * Note: * * * 1 <= equations.length <= 500 * equations[i].length == 4 * equations[i][0] and equations[i][3] are lowercase letters * equations[i][1] is either '=' or '!' * equations[i][2] is '=' * * * * * * * */ class Solution { public: bool equationsPossible(vector<string>& equations) { } };
# include "eoJsonUtils.h" # include <serial/Parser.h> # include <string> namespace eoserial { void printOn(const eoserial::Persistent& obj, std::ostream& out) { eoserial::Object* jsonThis = obj.pack(); jsonThis->print( out ); delete jsonThis; } void readFrom(eoserial::Persistent& obj, std::istream& _is) { std::string str; char temp[4096]; while( _is ) { _is.getline( temp, 4096, '\n' ); str += temp; str += '\n'; } eoserial::Object* read = eoserial::Parser::parse( str ); obj.unpack( read ); delete read; } } // namespace eoserial
/* ** WormWithWeapon.cpp for cpp_indie_studio in /home/lopez_i/cpp_indie_studio/WormWithWeapon.cpp ** ** Made by Loïc Lopez ** Login <loic.lopez@epitech.eu> ** ** Started on jeu. juin 15 19:15:02 2017 Loïc Lopez // Last update Sun Jun 18 16:27:36 2017 Stanislas Deneubourg */ #include "Worms/Worm.hpp" void Worm::wormMoveLeft(size_t const &currentSelectedWeapon) { this->wormPos.X -= WORM_MOVEMENT_SPEED; this->wormMesh->setAnimationSpeed(10); if (this->lookingDirection == Worm::LookingDirection::RIGHT || this->lookingDirection == Worm::LookingDirection::FRONT) { this->wormMesh->setRotation(irr::core::vector3df(0.0, 90.0f, 0.0)); this->lookingDirection = Worm::LookingDirection::LEFT; this->inventory.setWeaponRotationToWormPosition(currentSelectedWeapon, this->wormMesh->getRotation()); } this->wormMesh->setPosition(this->wormPos); this->inventory.setWeaponPositionToWormPosition(currentSelectedWeapon, this->wormPos); this->infos->setPosition(irr::core::vector3df(this->wormPos.X, this->wormPos.Y + 5.0f, this->wormPos.Z - 1.75f)); } void Worm::wormMoveRight(size_t const &currentSelectedWeapon) { this->wormPos.X += WORM_MOVEMENT_SPEED; this->wormMesh->setAnimationSpeed(10); if (this->lookingDirection == Worm::LookingDirection::LEFT || this->lookingDirection == Worm::LookingDirection::FRONT) { this->wormMesh->setRotation(irr::core::vector3df(0.0, -90.0f, 0.0)); this->lookingDirection = Worm::LookingDirection::RIGHT; this->inventory.setWeaponRotationToWormPosition(currentSelectedWeapon, this->wormMesh->getRotation()); } this->wormMesh->setPosition(this->wormPos); this->inventory.setWeaponPositionToWormPosition(currentSelectedWeapon, this->wormPos); this->infos->setPosition(irr::core::vector3df(this->wormPos.X, this->wormPos.Y + 5.0f, this->wormPos.Z - 1.75f)); } void Worm::wormLeftCollision(std::vector<irr::scene::IMeshSceneNode *> groundObjects, size_t currentSelectedWeapon) { int collision = 0; irr::f32 collisionPos = 0; for (unsigned int i = 0; i < groundObjects.size(); i++) { if ((this->wormMesh->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 0.7f - 2.30f) && (this->wormMesh->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 0.7f - 2.30f) && (this->wormMesh->getPosition().X <= groundObjects.at(i)->getPosition().X + 3.35f) && (this->wormMesh->getPosition().X >= groundObjects.at(i)->getPosition().X + 3.25f)) { collision = 1; collisionPos = groundObjects.at(i)->getPosition().X + 3.4f; } } if (collision == 0) { this->collideLeft = false; this->wormMoveLeft(currentSelectedWeapon); } else { this->wormPos.X = collisionPos; this->collideLeft = true; this->collideRight = false; } } void Worm::wormRightCollision(std::vector<irr::scene::IMeshSceneNode *> groundObjects, size_t currentSelectedWeapon) { int collision = 0; irr::f32 collisionPos = 0; for (unsigned int i = 0; i < groundObjects.size(); i++) { if ((this->wormMesh->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 0.7f - 2.30f) && (this->wormMesh->getPosition().Y <= groundObjects.at(i)->getPosition().Y + 0.7f - 2.30f) && (this->wormMesh->getPosition().X >= groundObjects.at(i)->getPosition().X - 3.35f) && (this->wormMesh->getPosition().X <= groundObjects.at(i)->getPosition().X - 3.25f)) { collision = 1; collisionPos = groundObjects.at(i)->getPosition().X - 3.4f; } } if (collision == 0) { this->collideRight = false; this->wormMoveRight(currentSelectedWeapon); } else { this->wormPos.X = collisionPos; this->collideRight = true; this->collideLeft = false; } } void Worm::wormGravity(std::vector<irr::scene::IMeshSceneNode *> groundObjects, size_t currentSelectedWeapon) { int collision = 0; for (unsigned int i = 0; i < groundObjects.size(); i++) { if ((this->wormMesh->getPosition().Y >= groundObjects.at(i)->getPosition().Y - 1.0f) && (this->wormMesh->getPosition().Y <= groundObjects.at(i)->getPosition().Y - 0.8f) && (this->wormMesh->getPosition().X >= groundObjects.at(i)->getPosition().X - 2.3f) && (this->wormMesh->getPosition().X <= groundObjects.at(i)->getPosition().X + 2.3f)) { collision = 1; this->isCollisioning = true; } } if (collision == 0) { this->wormPos.Y -= WORM_MOVEMENT_SPEED; this->wormMesh->setPosition(this->wormPos); this->inventory.setWeaponPositionToWormPosition(currentSelectedWeapon, this->wormPos); this->infos->setPosition(irr::core::vector3df(this->wormPos.X, this->wormPos.Y + 5.0f, this->wormPos.Z - 1.75f)); this->isCollisioning = false; } } void Worm::wormJump(size_t currentSelectedWeapon) { if (this->lookingDirection == Worm::LookingDirection::RIGHT) { if (this->isJumping == false && this->isCollisioning == true) { for (irr::f32 i = jumpConstraintsY; i >= 0; i = i - 0.001f) { this->isJumping = true; this->wormPos.X += i; this->wormPos.Y += i; this->wormMesh->setPosition(this->wormPos); this->inventory.setWeaponPositionToWormPosition(currentSelectedWeapon, this->wormPos); } this->isJumping = false; } } else if (this->lookingDirection == Worm::LookingDirection::LEFT) { if (this->isJumping == false && this->isCollisioning == true) { for (irr::f32 i = -jumpConstraintsY; i <= 0; i = i + 0.001f) { this->isJumping = true; this->wormPos.X += i; this->wormPos.Y -= i; this->wormMesh->setPosition(this->wormPos); this->inventory.setWeaponPositionToWormPosition(currentSelectedWeapon, this->wormPos); } this->isJumping = false; } } } void Worm::removeMeshSceneNode() { this->wormMesh->getParent()->removeChild(this->wormMesh); this->infos->getParent()->removeChild(this->infos); }
/* XMRig * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/net/stratum/AutoClient.h" #include "3rdparty/rapidjson/document.h" #include "base/io/json/Json.h" #include "net/JobResult.h" xmrig::AutoClient::AutoClient(int id, const char *agent, IClientListener *listener) : EthStratumClient(id, agent, listener) { } bool xmrig::AutoClient::handleResponse(int64_t id, const rapidjson::Value &result, const rapidjson::Value &error) { if (m_mode == DEFAULT_MODE) { return Client::handleResponse(id, result, error); } return EthStratumClient::handleResponse(id, result, error); } bool xmrig::AutoClient::parseLogin(const rapidjson::Value &result, int *code) { if (result.HasMember("job")) { return Client::parseLogin(result, code); } setRpcId(Json::getString(result, "id")); if (rpcId().isNull()) { *code = 1; return false; } const Algorithm algo(Json::getString(result, "algo")); if (algo.family() != Algorithm::KAWPOW) { *code = 6; return false; } try { setExtraNonce(Json::getValue(result, "extra_nonce")); } catch (const std::exception &ex) { *code = 6; return false; } m_mode = ETH_MODE; setAlgo(algo); return true; } int64_t xmrig::AutoClient::submit(const JobResult &result) { if (result.algorithm.family() != Algorithm::KAWPOW) { return Client::submit(result); } return EthStratumClient::submit(result); } void xmrig::AutoClient::parseNotification(const char *method, const rapidjson::Value &params, const rapidjson::Value &error) { if (strcmp(method, "job") == 0) { m_mode = DEFAULT_MODE; return Client::parseNotification(method, params, error); } m_mode = ETH_MODE; return EthStratumClient::parseNotification(method, params, error); }
#include <iostream> #include <vector> #include <unordered_map> #include <queue> using namespace std; class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { // str -> word, bool -> visited unordered_map<string, bool> dict; int n = wordList.size(); for(int i=0;i<n;i++) dict[wordList[i]] = false; queue< pair<string, int> > q; q.push(make_pair(beginWord, 1)); while(!q.empty()){ string word = q.front().first; int length = q.front().second; q.pop(); if(word == endWord) return length; int m = word.size(); for(int j=0;j<m;j++){ char c = word[j]; for(int i=0;i<26;i++){ // transform word[j] = 'a' + i; // new word in dict but not visited before if(dict.find(word) != dict.end() && !dict[word]){ dict[word] = true; pair<string, int> transformed = make_pair(word, length+1); q.push(transformed); } } word[j] = c; } } return 0; } }; int main(){ Solution s; std::vector<string> v; v.push_back("hot"); v.push_back("dot"); v.push_back("dog"); v.push_back("lot"); v.push_back("log"); v.push_back("cog"); cout << s.ladderLength("hit", "cog", v) << endl; }
#ifndef __PENALTY_FORCE_H__ #define __PENALTY_FORCE_H__ #include <Eigen/Core> #include "Force.h" #include <iostream> class TwoDScene; class PenaltyForce : public Force { public: PenaltyForce( const TwoDScene &scene, const scalar stiffness, const scalar thickness ); virtual ~PenaltyForce(); virtual void addEnergyToTotal( const VectorXs& x, const VectorXs& v, const VectorXs& m, scalar& E ); virtual void addGradEToTotal( const VectorXs& x, const VectorXs& v, const VectorXs& m, VectorXs& gradE ); virtual void addHessXToTotal( const VectorXs& x, const VectorXs& v, const VectorXs& m, MatrixXs& hessE ); virtual void addHessVToTotal( const VectorXs& x, const VectorXs& v, const VectorXs& m, MatrixXs& hessE ); virtual Force* createNewCopy(); void addParticleParticleGradEToTotal(const VectorXs &x, int idx1, int idx2, VectorXs &gradE); void addParticleEdgeGradEToTotal(const VectorXs &x, int vidx, int eidx, VectorXs &gradE); void addParticleHalfplaneGradEToTotal(const VectorXs &x, int vidx, int pidx, VectorXs &gradE); private: const TwoDScene &m_scene; const scalar m_k; const scalar m_thickness; }; #endif
#ifndef MAIN_CPP #define MAIN_CPP #include "ros/ros.h" #include "std_msgs/String.h" #include "am2315.hpp" int main(int argc,char ** argv){ ros::init(argc, argv, "am2315_node"); std::string i2cBus("/dev/i2c-1"); std::string zoneId("Greenhouse"); am2315Sensor s(i2cBus,zoneId); try{ ros::NodeHandle n; ros::Publisher environmentTopic = n.advertise<am2315::Environment>("environment", 1000); ros::Rate loop_rate((double)1/(double)60); s.init(); uint32_t sequentialNumber; while(ros::ok()){ am2315::Environment env; env.header.seq =sequentialNumber; s.read(env); environmentTopic.publish(env); ros::spinOnce(); loop_rate.sleep(); sequentialNumber++; } } catch(std::exception & e){ std::cerr << e.what() << std::endl; } } #endif
#include "MoveFactory.h" #include "MoveManager.h" namespace Move { IMoveManager* createDevice() { return MoveManager::getInstance(); } }
#include <cstdio> #include <arpa/inet.h> #include <sys/socket.h> #include <unistd.h> using namespace std; int main(){ int sockfd; int bind_flag; int bytes_received; socklen_t addrlen; char buffer[1024]; struct sockaddr_in server_address; struct sockaddr_in client_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(4747); server_address.sin_addr.s_addr = inet_addr("192.168.10.100"); sockfd = socket(AF_INET, SOCK_DGRAM, 0); bind_flag = bind(sockfd, (struct sockaddr*) &server_address, sizeof(sockaddr_in)); while(true){ //printf("in while\n"); bytes_received = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr*) &client_address, &addrlen); printf("[%s:%d]: %s\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port), buffer); } return 0; }
/* SPDX-FileCopyrightText: 1997 Bernd Johannes Wuebben <wuebben@kde.org> SPDX-FileCopyrightText: 1999 Preston Brown <pbrown@kde.org> SPDX-FileCopyrightText: 1999 Mario Weilguni <mweilguni@kde.org> SPDX-License-Identifier: LGPL-2.0-or-later */ #ifndef K_FONT_CHOOSER_H #define K_FONT_CHOOSER_H #include <QWidget> #define KWIDGETSADDONS_EXPORT /**/ class QFont; class QStringList; /** * @class KFontChooser kfontchooser.h KFontChooser * * @short A font selection widget. * * While KFontChooser as an ordinary widget can be embedded in * custom dialogs and therefore is very flexible, in most cases * it is preferable to use the convenience functions in * QFontDialog. * * \image html kfontchooser.png "KFontChooser Widget" * * @see KFontRequester * * @author Preston Brown <pbrown@kde.org>, Bernd Wuebben <wuebben@kde.org> */ class KWIDGETSADDONS_EXPORT KFontChooser : public QWidget { Q_OBJECT Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontSelected USER true) Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) Q_PROPERTY(Qt::CheckState sizeIsRelative READ sizeIsRelative WRITE setSizeIsRelative) Q_PROPERTY(QString sampleText READ sampleText WRITE setSampleText) public: /** * Displayed columns. */ enum FontColumn { FamilyList = 0x01, ///< Identifies the family (leftmost) list. StyleList = 0x02, ///< Identifies the style (center) list. SizeList = 0x04 ///< Identifies the size (rightmost) list. }; /** * Flags for selecting which font attributes to change * @see FontDiffFlags */ enum FontDiff { NoFontDiffFlags = 0, ///< No flags set FontDiffFamily = 1, ///< Identifies a requested change in the font family. FontDiffStyle = 2, ///< Identifies a requested change in the font style. FontDiffSize = 4, ///< Identifies a requested change in the font size. AllFontDiffs = FontDiffFamily | FontDiffStyle | FontDiffSize }; /** * Stores an combination of #FontDiff values. */ Q_DECLARE_FLAGS(FontDiffFlags, FontDiff) /** * Flags for selecting what is displayed in the widget. * @see DisplayFlags */ enum DisplayFlag { NoDisplayFlags = 0, ///< No flags set FixedFontsOnly = 1, ///< Only show monospaced/fixed-width fonts, excluding proportional fonts, (the ///< checkbox to toggle showing only monospaced fonts is not shown in this case) DisplayFrame = 2, ///< Show a visual frame around the chooser ShowDifferences = 4, ///< Display the font differences interfaces }; /** * Stores a combination of #DisplayFlag values. */ Q_DECLARE_FLAGS(DisplayFlags, DisplayFlag) /** * Constructs a font picker widget. * It normally comes up with all font families present on the system; the * getFont method below does allow some more fine-tuning of the selection of fonts * that will be displayed in the dialog. * <p>Consider the following code snippet; * \code * QStringList list; * KFontChooser::getFontList(list, KFontChooser::SmoothScalableFonts); * KFontChooser *chooseFont = new KFontChooser(nullptr, KFontChooser::NoDisplayFlags, list); * \endcode * <p> * The above creates a font chooser dialog with only SmoothScaleble fonts. * * @param parent The parent widget. * @param flags Defines how the font chooser is displayed. * @param fontList A list of fonts to display, in XLFD format. If * no list is formatted, the internal KDE font list is used. * If that has not been created, X is queried, and all fonts * available on the system are displayed. * @param visibleListSize The minimum number of visible entries in the * fontlists. * @param sizeIsRelativeState If not zero the widget will show a * checkbox where the user may choose whether the font size * is to be interpreted as relative size. * Initial state of this checkbox will be set according to * *sizeIsRelativeState, user choice may be retrieved by * calling sizeIsRelative(). */ explicit KFontChooser(QWidget *parent = nullptr, const DisplayFlags &flags = DisplayFrame, const QStringList &fontList = QStringList(), int visibleListSize = 8, Qt::CheckState *sizeIsRelativeState = nullptr); /** * Destructs the font chooser. */ ~KFontChooser() override; /** * Enables or disable a font column in the chooser. * * Use this * function if your application does not need or supports all font * properties. * * @param column Specify the columns. An or'ed combination of * @p FamilyList, @p StyleList and @p SizeList is possible. * @param state If @p false the columns are disabled. */ void enableColumn(int column, bool state); /** * Sets the currently selected font in the chooser. * * @param font The font to select. * @param onlyFixed Readjust the font list to display only fixed * width fonts if @p true, or vice-versa. */ void setFont(const QFont &font, bool onlyFixed = false); /** * @return The bitmask corresponding to the attributes the user * wishes to change. */ FontDiffFlags fontDiffFlags() const; /** * @return The currently selected font in the chooser. */ QFont font() const; /** * Sets the color to use in the preview. */ void setColor(const QColor &col); /** * @return The color currently used in the preview (default: the text * color of the active color group) */ QColor color() const; /** * Sets the background color to use in the preview. */ void setBackgroundColor(const QColor &col); /** * @return The background color currently used in the preview (default: * the base color of the active colorgroup) */ QColor backgroundColor() const; /** * Sets the state of the checkbox indicating whether the font size * is to be interpreted as relative size. * NOTE: If parameter sizeIsRelative was not set in the constructor * of the widget this setting will be ignored. */ void setSizeIsRelative(Qt::CheckState relative); /** * @return Whether the font size is to be interpreted as relative size * (default: QButton:Off) */ Qt::CheckState sizeIsRelative() const; /** * @return The current text in the sample text input area. */ QString sampleText() const; /** * Sets the sample text. * * Normally you should not change this * text, but it can be better to do this if the default text is * too large for the edit area when using the default font of your * application. * * @param text The new sample text. The current will be removed. */ void setSampleText(const QString &text); /** * Shows or hides the sample text box. * * @param visible Set it to true to show the box, to false to hide it. */ void setSampleBoxVisible(bool visible); /** * The selection criteria for the font families shown in the dialog. */ enum FontListCriteria { /** * When included only fixed-width fonts are returned. * The fonts where the width of every character is equal. */ FixedWidthFonts = 0x01, /** * When included only scalable fonts are returned; * certain configurations allow bitmap fonts to remain unscaled and * thus these fonts have limited number of sizes. */ ScalableFonts = 0x02, /** * When included only return smooth scalable fonts. * This will return only non-bitmap fonts which are scalable to any size requested. * Setting this option to true will mean the "scalable" flag is irrelevant. */ SmoothScalableFonts = 0x04 }; /** * Creates a list of font strings. * * @param list The list is returned here. * @param fontListCriteria should contain all the restrictions for font selection as OR-ed values * from KFontChooser::FontListCriteria */ static void getFontList(QStringList &list, uint fontListCriteria); /** * Reimplemented for internal reasons. */ QSize sizeHint(void) const override; Q_SIGNALS: /** * Emitted whenever the selected font changes. */ void fontSelected(const QFont &font); private: class Private; Private *const d; Q_DISABLE_COPY(KFontChooser) Q_PRIVATE_SLOT(d, void _k_family_chosen_slot(const QString &)) Q_PRIVATE_SLOT(d, void _k_size_chosen_slot(const QString &)) Q_PRIVATE_SLOT(d, void _k_style_chosen_slot(const QString &)) Q_PRIVATE_SLOT(d, void _k_displaySample(const QFont &font)) Q_PRIVATE_SLOT(d, void _k_size_value_slot(double)) }; Q_DECLARE_OPERATORS_FOR_FLAGS(KFontChooser::DisplayFlags) #endif
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define show(x) for(auto i: x){cout << i << " ";} typedef long long ll; int n; vector<string> dic; void fds(int bitinfo, string s){ if (s.size() == n){ dic.push_back(s); return; } for (int i = 1; i <= n; i++) { if (!((bitinfo >> (i-1)) & 1)){ string t = s + to_string(i); int nextbit = bitinfo + (1 << (i-1)); fds(nextbit, t); } } } void perm(){ vector<int> v(n); iota(v.begin(), v.end(), 1); do { string s; for (auto x : v) s += to_string(x); dic.push_back(s); } while (next_permutation(v.begin(), v.end()) ); } int main() { cin >> n; //fds(0, ""); perm(); sort(dic.begin(), dic.end()); //show(dic); string s,t; rep(i, n) {int tmp; cin >> tmp; s += to_string(tmp);} rep(i, n) {int tmp; cin >> tmp; t += to_string(tmp);} int s_itr, t_itr; // for (int i = 0; i < dic.size(); i++) // { // if (s == dic[i]) s_itr = i; // if (t == dic[i]) t_itr = i; // } s_itr = lower_bound(dic.begin(), dic.end(), s) - dic.begin(); t_itr = lower_bound(dic.begin(), dic.end(), t) - dic.begin(); cout << abs(s_itr - t_itr) << endl; }