void OMR::CodeGenPhase::performSetupForInstructionSelectionPhase(TR::CodeGenerator * cg, TR::CodeGenPhase * phase) { TR::Compilation *comp = cg->comp(); if (TR::Compiler->target.cpu.isZ() && TR::Compiler->om.shouldGenerateReadBarriersForFieldLoads()) { // TODO (GuardedStorage): We need to come up with a better solution than anchoring aloadi's // to enforce certain evaluation order traceMsg(comp, "GuardedStorage: in performSetupForInstructionSelectionPhase\n"); auto mapAllocator = getTypedAllocator<std::pair<TR::TreeTop*, TR::TreeTop*> >(comp->allocator()); std::map<TR::TreeTop*, TR::TreeTop*, std::less<TR::TreeTop*>, TR::typed_allocator<std::pair<TR::TreeTop* const, TR::TreeTop*>, TR::Allocator> > currentTreeTopToappendTreeTop(std::less<TR::TreeTop*> (), mapAllocator); TR_BitVector *unAnchorableAloadiNodes = comp->getBitVectorPool().get(); for (TR::PreorderNodeIterator iter(comp->getStartTree(), comp); iter != NULL; ++iter) { TR::Node *node = iter.currentNode(); traceMsg(comp, "GuardedStorage: Examining node = %p\n", node); // isNullCheck handles both TR::NULLCHK and TR::ResolveAndNULLCHK // both of which do not operate on their child but their // grandchild (or greatgrandchild). if (node->getOpCode().isNullCheck()) { // An aloadi cannot be anchored if there is a Null Check on // its child. There are two situations where this occurs. // The first is when doing an aloadi off some node that is // being NULLCHK'd (see Ex1). The second is when doing an // icalli in which case the aloadi loads the VFT of an // object that must be NULLCHK'd (see Ex2). // // Ex1: // n1n NULLCHK on n3n // n2n aloadi f <-- First Child And Parent of Null Chk'd Node // n3n aload O // // Ex2: // n1n NULLCHK on n4n // n2n icall foo <-- First Child // n3n aloadi <vft> <-- Parent of Null Chk'd Node // n4n aload O // n4n ==> aload O TR::Node *nodeBeingNullChkd = node->getNullCheckReference(); if (nodeBeingNullChkd) { TR::Node *firstChild = node->getFirstChild(); TR::Node *parentOfNullChkdNode = NULL; if (firstChild->getOpCode().isCall() && firstChild->getOpCode().isIndirect()) { parentOfNullChkdNode = firstChild->getFirstChild(); } else { parentOfNullChkdNode = firstChild; } if (parentOfNullChkdNode && parentOfNullChkdNode->getOpCodeValue() == TR::aloadi && parentOfNullChkdNode->getNumChildren() > 0 && parentOfNullChkdNode->getFirstChild() == nodeBeingNullChkd) { unAnchorableAloadiNodes->set(parentOfNullChkdNode->getGlobalIndex()); traceMsg(comp, "GuardedStorage: Cannot anchor %p\n", firstChild); } } } else { bool shouldAnchorNode = false; if (node->getOpCodeValue() == TR::aloadi && !unAnchorableAloadiNodes->isSet(node->getGlobalIndex())) { shouldAnchorNode = true; } else if (node->getOpCodeValue() == TR::aload && node->getSymbol()->isStatic() && node->getSymbol()->isCollectedReference()) { shouldAnchorNode = true; } if (shouldAnchorNode) { TR::TreeTop* anchorTreeTop = TR::TreeTop::create(comp, TR::Node::create(TR::treetop, 1, node)); TR::TreeTop* appendTreeTop = iter.currentTree(); if (currentTreeTopToappendTreeTop.count(appendTreeTop) > 0) { appendTreeTop = currentTreeTopToappendTreeTop[appendTreeTop]; } // Anchor the aload/aloadi before the current treetop appendTreeTop->insertBefore(anchorTreeTop); currentTreeTopToappendTreeTop[iter.currentTree()] = anchorTreeTop; traceMsg(comp, "GuardedStorage: Anchored %p to treetop = %p\n", node, anchorTreeTop); } } } comp->getBitVectorPool().release(unAnchorableAloadiNodes); } if (cg->shouldBuildStructure() && (comp->getFlowGraph()->getStructure() != NULL)) { TR_Structure *rootStructure = TR_RegionAnalysis::getRegions(comp); comp->getFlowGraph()->setStructure(rootStructure); } phase->reportPhase(SetupForInstructionSelectionPhase); // Dump preIR if (comp->getOption(TR_TraceRegisterPressureDetails) && !comp->getOption(TR_DisableRegisterPressureSimulation)) { traceMsg(comp, " { Post optimization register pressure simulation\n"); TR_BitVector emptyBitVector; vcount_t vc = comp->incVisitCount(); cg->initializeRegisterPressureSimulator(); for (TR::Block *block = comp->getStartBlock(); block; block = block->getNextExtendedBlock()) { TR_LinkHead<TR_RegisterCandidate> emptyCandidateList; TR::CodeGenerator::TR_RegisterPressureState state(NULL, 0, emptyBitVector, emptyBitVector, &emptyCandidateList, cg->getNumberOfGlobalGPRs(), cg->getNumberOfGlobalFPRs(), cg->getNumberOfGlobalVRFs(), vc); TR::CodeGenerator::TR_RegisterPressureSummary summary(state._gprPressure, state._fprPressure, state._vrfPressure); cg->simulateBlockEvaluation(block, &state, &summary); } traceMsg(comp, " }\n"); } TR::LexicalMemProfiler mp(phase->getName(), comp->phaseMemProfiler()); LexicalTimer pt(phase->getName(), comp->phaseTimer()); cg->setUpForInstructionSelection(); }
/** * @param n an integer * @param m an integer * @param operators an array of point * @return an integer array */ vector<int> numIslands2(int n, int m, vector<Point>& operators) { // Write your code here int N = operators.size(); if(N == 0) return {}; vector<vector<int>> mp(n, vector<int>(m, 0)); vector<int> res(N, 0); int idx = 1; for (int i = 0; i < N; i++, idx++) { int count = 1; Point &p = operators[i]; if (mp[p.x][p.y]) { res[i] = res[i - 1]; continue; } if (p.x - 1 >= 0 && mp[p.x - 1][p.y]) { if (mp[p.x][p.y] == 0) { mp[p.x][p.y] = mp[p.x - 1][p.y]; count--; } else if (mp[p.x][p.y] != mp[p.x - 1][p.y]) { numIslands2Helper(p.x - 1, p.y, mp[p.x][p.y], mp); count--; } } if (p.x + 1 < n && mp[p.x + 1][p.y]) { if (mp[p.x][p.y] == 0) { mp[p.x][p.y] = mp[p.x + 1][p.y]; count--; } else if (mp[p.x][p.y] != mp[p.x + 1][p.y]) { numIslands2Helper(p.x + 1, p.y, mp[p.x][p.y], mp); count--; } } if (p.y - 1 >= 0 && mp[p.x][p.y - 1]) { if (mp[p.x][p.y] == 0) { mp[p.x][p.y] = mp[p.x][p.y - 1]; count--; } else if (mp[p.x][p.y] != mp[p.x][p.y - 1]) { numIslands2Helper(p.x, p.y - 1, mp[p.x][p.y], mp); count--; } } if (p.y + 1 < m && mp[p.x][p.y + 1]) { if (mp[p.x][p.y] == 0) { mp[p.x][p.y] = mp[p.x][p.y + 1]; count--; } else if (mp[p.x][p.y] != mp[p.x][p.y + 1]) { numIslands2Helper(p.x, p.y + 1, mp[p.x][p.y], mp); count--; } } if(mp[p.x][p.y] == 0) mp[p.x][p.y] = idx; if(i == 0) res[i] = count; else res[i] = res[i - 1] + count; } return res; }
int main( int argc , char * argv[] ) { std::cout << "算术" << std::endl; int a = 10 , b = 20; int ret; std::plus<int>add; ret = add(a,b); std::cout << ret << std::endl; std::minus<int> min; ret = min(b,a); std::cout << ret << std::endl; std::multiplies<int> mp; ret = mp(a,b); std::cout << ret << std::endl; std::divides<int> divi; ret = divi(a,b); std::cout << ret << std::endl; std::modulus<int> mod; ret = mod(a,b); std::cout << ret << std::endl; std::negate<int> neg; ret = neg(a); std::cout << ret << std::endl; std::cout << "关系" <<std::endl; int a2 = 10 , b2 = 20; int ret2; std::equal_to<int> et; ret2 = et(a,b); std::cout << ret2 <<std::endl; std::not_equal_to<int> net; ret2 = net(a,b); std::cout << ret2 << std::endl; std::greater<int>gt; ret2 = gt(b,a); std::cout << ret2 << std::endl; std::greater_equal<int> gte; ret2 = gte(a,b); std::cout << ret2 <<std::endl; std::less<int> ls; ret2 = ls(a,b); std::cout << ret2 << std::endl; std::less_equal<int> lel; ret2 = lel(a,b); std::cout << ret2 << std::endl; std::cout << "逻辑" << std::endl; int ret3; std::logical_and<int> la; ret3 = la(a,b); std::cout << ret3 <<std::endl; std::logical_or<int> lo; ret3 = lo(a,b); std::cout << ret3 << std::endl; std::logical_not<int>ln; ret3 = ln(b); std::cout << ret3 <<std::endl; return EXIT_SUCCESS; }
Value qsearch(Position& pos, Value alpha, Value beta, Depth depth) { // 現在のnodeのrootからの手数。これカウンターが必要。 // nanoだとこのカウンター持ってないので適当にごまかす。 const int ply_from_root = (pos.this_thread()->rootDepth - depth / ONE_PLY) + 1; // この局面で王手がかかっているのか bool InCheck = pos.checkers(); Value value; if (InCheck) { // 王手がかかっているならすべての指し手を調べる。 alpha = -VALUE_INFINITE; } else { // 王手がかかっていないなら置換表の指し手を持ってくる // この局面で何も指さないときのスコア。recaptureすると損をする変化もあるのでこのスコアを基準に考える。 value = evaluate(pos); if (alpha < value) { alpha = value; if (alpha >= beta) return alpha; // beta cut } // 探索深さが-3以下ならこれ以上延長しない。 if (depth < -3 * ONE_PLY) return alpha; } // 取り合いの指し手だけ生成する pos.check_info_update(); MovePicker mp(pos,move_to(pos.state()->lastMove)); Move move; StateInfo si; while (move = mp.next_move()) { if (!pos.legal(move)) continue; pos.do_move(move, si, pos.gives_check(move)); value = -YaneuraOuNano::qsearch<NT>(pos, -beta, -alpha, depth - ONE_PLY); pos.undo_move(move); if (Signals.stop) return VALUE_ZERO; if (value > alpha) // update alpha? { alpha = value; if (alpha >= beta) return alpha; // beta cut } } // 王手がかかっている状況ですべての指し手を調べたということだから、これは詰みである if (InCheck && alpha == -VALUE_INFINITE) return mated_in(ply_from_root); return alpha; }
// 協力詰め // depth = 残り探索深さ // no_mate_depth = この局面は、この深さの残り探索深さがあっても詰まない(あるいは詰みを発見して出力済み) void search(Position& pos, uint32_t depth, int& no_mate_depth) { // 強制停止 if (Signals.stop || mate_found) { no_mate_depth = MAX_PLY; return; } Key128 key = pos.state()->long_key(); Move tt_move; // 置換表がヒットするか if (TT.probe(key, depth, tt_move)) { no_mate_depth = depth; // foundのときにdepthはTTEntry.depth()で書き換わっている。 return; // このnodeに関しては現在の残り探索深さ以上の深さにおいて //不詰めが証明されているのでもう帰ってよい。(枝刈り) } StateInfo si; pos.check_info_update(); // legal()とgives_check()とCHECKSの指し手生成に先だって呼び出されている必要がある。 MovePicker mp(pos, tt_move); Move m; int replyCount = 0; // 確定局面以外の応手の数 Move oneReply = MOVE_NONE; no_mate_depth = MAX_PLY; // 有効な指し手が一つもなければこのnodeはいくらdepthがあろうと詰まない。 while ((m = mp.next_move()) && !Signals.stop && !mate_found) { if (!pos.legal(m)) continue; pos.do_move(m, si, pos.gives_check(m)); if (pos.is_mated()) { // 後手の詰みなら手順を表示する。先手の詰みは必要ない。 if (pos.side_to_move() == WHITE) { // 現在詰まないことが判明している探索深さ(search_depth)+2の長さの詰みを発見したときのみ。 while (!Signals.stop && !mate_found) // 他のスレッドが見つけるかも知れないのでそれを待ちながら…。 { if (search_depth + 2 >= id_depth_thread /*- depth + 1*/) { mate_found = true; sync_cout << "checkmate " << pos.moves_from_start() << sync_endl; // 開始局面からそこまでの手順 break; } sleep(100); } } } else if (depth > 1) { // 残り探索深さがあるなら再帰的に探索する。 int child_no_mate_depth; search(pos, depth - 1, child_no_mate_depth); no_mate_depth = min(child_no_mate_depth + 1, no_mate_depth); if (child_no_mate_depth != MAX_PLY) { replyCount++; oneReply = m; } } else { no_mate_depth = 1; // frontier node。この先、まだ探索すれば詰むかも知れないので.. replyCount++; oneReply = m; } pos.undo_move(m); } // このnodeに関して残り探索深さdepthについては詰みを調べきったので不詰めとして扱い、置換表に記録しておく。 // また、確定局面以外の子が1つしかなればそれを置換表に書き出しておく。(次回の指し手生成をはしょるため) if (replyCount != 1) oneReply = MOVE_NONE; TT.save(key, no_mate_depth, oneReply); }
TEST(TestJSON, NamedStruct) { MPoint mp(41, 42); qi::AnyValue gvr = qi::AnyValue::from(mp); EXPECT_EQ("{ \"x\" : 41, \"y\" : 42 }", qi::encodeJSON(gvr)); }
int maxPathSum(TreeNode *root) { max=-1000000; mp(root); return max; }
int main(int argc, char** argv){ int sock = 0; // declaración del socket e inicializado a 0 int error = 0; /** declaramos una variable que nos servirá para detectar * errores */ socklen_t length = (socklen_t) sizeof (struct sockaddr_in); // tamaño del paquete struct sockaddr_in addr; // definimos el contenedor de la dirección unsigned int port = 5678; /** creamos la variable que identifica el puerto * de conexión, siendo el puerto por defecto 5678 */ int connPos = 0; // primera posición libre en el array de conexiones int connTam = 10; // tamaño actual del array de conexiones int connGrow = 10; // factor de crecimiento del array user* conn = NULL; // array de conexiones con los clientes room rooms[DIM]; user auxConn; // conexion auxiliar sms auxMsj; fd_set connList, connListCopy; // definimos un descriptor que contendrá nuestros sockets int nbytes = 0; // contador de bytes leidos y escritos int dbName = 0; // variable que nos permitirá configurar el nombre de la base de datos sqlite3* db = NULL; // descriptor de la base de datos char cert[DIM] = "cert"; // nombre del certificado del servidor char pkey[DIM] = "pkey"; // nombre del archivo con la clave privada // <editor-fold defaultstate="collapsed" desc="Interpretado de parámetros de entrada"> //analizamos los parámetros de entrada int i = 0; for(; i < argc; i++){ if(strcmp(argv[i], "-p") == 0){ // leemos el puerto if(argc <= i + 1 || isNum(argv[i+1]) == 0){ perror("Se esperaba un número después de -p"); exit(-1); }else{ PDEBUG("ARGS: Se detectó un puerto\n"); i++; port = atoi(argv[i]); } continue; }else if(strcmp(argv[i], "-ls") == 0){ // leemos el tamaño inicial de la lista if(argc <= i + 1 || isNum(argv[i+1]) == 0){ perror("Se esperaba un número después de -ls"); exit(-1); }else{ PDEBUG("ARGS: Se detectó un tamaño inicial\n"); i++; connTam = atoi(argv[i]); } continue; }else if(strcmp(argv[i], "-lg") == 0){ // leemos el factor de creciemiento de la lista de conexiones if(argc <= i + 1 || isNum(argv[i+1]) == 0){ perror("Se esperaba un número después de -lg\n"); exit(-1); }else{ PDEBUG("ARGS: Se detectó un crecimiento\n"); i++; connGrow = atoi(argv[i]); } continue; }else if(strcmp(argv[i], "-db") == 0){ // leemos el nombre de la base de datos que queremos utilizar if(argc <= i + 1){ perror("Se esperaba una cadena depués de -db\n"); exit(-1); }else{ PDEBUG("ARGS: Se detectó un crecimiento\n"); i++; dbName = i; } continue; }else if(strcmp(argv[i], "-cert") == 0){ // leemos el nombre del archivo del certificado if(argc <= i + 1){ perror("Se esperaba una cadena depués de -cert\n"); exit(-1); }else{ PDEBUG("ARGS: Se detectó un certificado\n"); i++; strcpy(cert, argv[i]); } continue; }else if(strcmp(argv[i], "-pkey") == 0){ // leemos el nombre del archivo de que contiene la clave privada if(argc <= i + 1){ perror("Se esperaba una cadena depués de -pkey\n"); exit(-1); }else{ PDEBUG("ARGS: Se detectó una clave privada\n"); i++; strcpy(pkey, argv[i]); } continue; } } //</editor-fold> db = db_open( (dbName == 0) ? "chat.db" : argv[dbName] ); PDEBUG("INFO: Convertimos el proceso en un demonio\n"); //make_daemon(); /*******************************SSL****************************************/ PDEBUG("INFO: Inicializando la libreria SSL\n"); SSL_library_init(); PDEBUG("INFO: Cargamos los algoritmos SSL y los mensajes de error\n"); OpenSSL_add_all_algorithms(); SSL_load_error_strings(); PDEBUG("INFO: Seleccionamos SSLv2, SSLv3 y TLSv1\n"); SSL_METHOD *method; method = SSLv23_server_method(); PDEBUG("INFO: Creamos el nuevo contexto\n"); SSL_CTX *ctx; ctx = SSL_CTX_new(method); if(ctx == NULL) { // error ERR_print_errors_fp(stderr); _exit(-1); } PDEBUG("INFO: Comprobando el certificado\n"); if ( SSL_CTX_use_certificate_chain_file(ctx, cert) <= 0) { ERR_print_errors_fp(stderr); _exit(-1); } PDEBUG("INFO: Comprobando la clav eprivada\n"); if ( SSL_CTX_use_PrivateKey_file(ctx, pkey, SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); _exit(-1); } PDEBUG("INFO: Comprobando que las claves pueden trabajar juntas\n"); if ( !SSL_CTX_check_private_key(ctx) ) { fprintf(stderr, "Clave privada incorrecta.\n"); _exit(-1); } /*******************************SSL****************************************/ //Creamos el socket PDEBUG("INFO: Creando el socket\n"); sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); //Comprobamos si ha ocurrido un error al crear el socket if(sock < 0){ write(2, strcat("ERROR: creación del socket {{socket()}}: %s\n", strerror(errno)), DIM); // terminamos la ejecución del programa exit(-1); } PDEBUG("INFO: Estableciendo el puerto, origenes,...\n"); addr.sin_family = AF_INET; // familia AF_INET addr.sin_port = htons(port); // definimos el puerto de conexión addr.sin_addr.s_addr = htonl(INADDR_ANY); // permitimos conexion de cualquiera /* hacemos este "apaño" porque según hemos leido, http://www.wlug.org.nz/EADDRINUSE * hay un timeout para liberar el socket */ unsigned int opt = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))==-1) { write(2, "ERROR: al permitir la reutiización del puerto {{setsockopt()}}\n", DIM); exit(-1); } // le asignamos una dirección al socket PDEBUG("INFO: Asignando una dirección al socket\n"); error = bind(sock, (struct sockaddr *)&addr, length); //Comprobamos si ha ocurrido un error al hacer el bind if(error < 0){ write(2, strcat("ERROR: {{bind()}}: %s\n", strerror(errno)), DIM); // terminamos la ejecución del programa exit(-1); } //Ponemos el servidor a escuchar para buscar nuevas conexiones PDEBUG("INFO: Comenzamos la escucha de l programa\n"); error = listen(sock, Q_DIM); //Comprobamos si ha ocurrido un error al ponernos a escuchar if(error < 0){ write(2, strcat("ERROR: al iniciar la escucha{{listen()}}: %s\n", strerror(errno)), DIM); // terminamos la ejecución del programa exit(-1); } // realizamos la asignación inicial de memoria PDEBUG("INFO: Realizando asignación inicial de memoria, tamaño inicial 10\n"); connTam = 10; conn = malloc(connTam * sizeof(user)); // rellenamos el array con -1 memset(conn, 0, connTam * sizeof(user)); //inicializamos la lista de conexiones FD_ZERO(&connList); // Inicio del bit descriptor connList con el valor de sock FD_SET (sock, &connList); PDEBUG("INFO: Creamos la sala de chat general\n"); bzero(rooms, DIM * sizeof(room)); strcpy(rooms[0].name, "general"); // <editor-fold defaultstate="collapsed" desc="Bucle de escucha"> //comenzamos a analizar conexiones PDEBUG("INFO: Comenzamos a analizar los sockets\n"); while(1){ // hacemos una copia de seguridad para asegurarnos de no perder los datos connListCopy = connList; // ¿Hay algún socket listo para leer? PDEBUG("INFO: ¿Hay algún socket listo para leer?\n"); error = select(connTam + 1, &connListCopy, NULL, NULL, NULL); //Comprobamos si ha ocurrido un error al ponernos a escuchar if(error < 0){ write(2, strcat("ERROR: al realizar la selección {{select()}}: %s\n" , strerror(errno)), DIM); // terminamos la ejecución del programa exit(-1); } // recorriendo los sockets para ver los que están activos PDEBUG("INFO: recorriendo los sockets para ver los que están activos\n"); int i = 0; // definimos un índice for (; i <= connTam; i++){ // este socket está preparado para leer los datos if(FD_ISSET(i, &connListCopy)){ // vemos si el socket preparado para leer es el de aceptar peticiones if(i == sock){ PDEBUG("INFO: Nuevo cliente detectado, comprobando...\n"); auxConn.sock = accept(sock, (struct sockaddr *) &addr, &length); if(auxConn.sock < 0){ write(2, "ERROR: al realizar la aceptación {{accept()}}: %s\n" , *strerror(errno)); // terminamos la ejecución del programa exit(-1); } /************************SSL*******************************/ PDEBUG("INFO: Creando conexion ssl\n"); PDEBUG("INFO: Creando conexion SSL\n"); auxConn.ssl = SSL_new(ctx); PDEBUG("INFO: Asignando la conexión a SSL\n"); SSL_set_fd(auxConn.ssl, auxConn.sock); PDEBUG("INFO: Aceptando la conexión SSL\n"); error = SSL_accept(auxConn.ssl); if(error < 0){ ERR_print_errors_fp(stderr); exit(-1); } /************************SSL*******************************/ PDEBUG("INFO: Conexión establecida, autenticando...\n"); memset(&auxMsj, 0, sizeof(auxMsj)); // incializamos la estructura PDEBUG("INFO: Solicitando autenticación\n"); strcpy(auxMsj.text, "Usuario: "); // establecemos el texto que queremos que se muestre auxMsj.flag = REQ_TEXT; // le indicamos que requerimos una respuesta con texto strcpy(auxMsj.name, SERVER); // nos identificamos como el servidor SSL_write(auxConn.ssl, &auxMsj, sizeof(sms)); // enviamos la información // metemos los datos de la conexión en nuestro array de conexiones strcpy((*(conn + connPos)).name, auxMsj.text); (*(conn + connPos)).sock = auxConn.sock; (*(conn + connPos)).ssl = auxConn.ssl; (*(conn + connPos)).prov = PROV; // Añadimos el socket a nuestra lista PDEBUG("INFO: Insertando socket en la lista de monitoreo\n"); FD_SET (auxConn.sock, &connList); // como la peticion se ha aceptado incrementamos el contador de conexiones PDEBUG("INFO: Cálculo del nuevo offset\n"); nextPos(conn, &connPos, &connTam, connGrow); }else{ // si no, es un cliente ya registrado PDEBUG("DATA: Nuevo mensaje detectado\n"); nbytes = SSL_read((*(conn+searchConn(conn, connTam, i))).ssl, &auxMsj, sizeof(sms)); if(nbytes > 0){ // si hemos leido más d eun byte... switch(auxMsj.flag){ case CLI_EXIT: // desconexión del cliente closeConn(conn, &connPos, connTam, i, &connList, db); break; case SERV_ADMIN: // parámetros que ha de ejecutr el servidor execParams(conn, connTam, auxMsj.text, i, sock, db, rooms, DIM); break; case MSJ: // mensaje multicast(conn, &connTam, auxMsj, i, db, (*(conn+searchConn(conn, connTam, i))).room); break; case REQ_AUTH: // vamos a leer el nombre de usuario auth(conn, &connTam, i, auxMsj, db, rooms, DIM); break; case CHECK_ROOM: // vamos a leer el nombre de usuario roomCheckIn(conn, &connTam, i, auxMsj, db, rooms, DIM); break; case CHECK_PASS: authPassword(conn, &connTam, i, auxMsj, db, rooms, DIM); break; case MP: mp(conn, &connTam, auxMsj, i, db); break; default: write(2, "ERROR: Recibido un mensaje mal formado\n", 39); break; } }else{ // hemos detectado una desconexión por el cerrado de la conexión closeConn(conn, &connPos, connTam, i, &connList, db); } } } } }//</editor-fold> return 0; }
/** * Parse attribute data based on attribute type * * \details * Parses the attribute data based on the passed attribute type. * Parsed_data will be updated based on the attribute data parsed. * * \param [in] attr_type Attribute type * \param [in] attr_len Length of the attribute data * \param [in] data Pointer to the attribute data * \param [out] parsed_update Reference to parsed_update; will be updated with all parsed data */ void parseBgpLib::parseAttrData(u_char attr_type, uint16_t attr_len, u_char *data, parsed_update &update, MD5 &hash) { u_char ipv4_raw[4]; char ipv4_char[16]; uint32_t value32bit; uint16_t value16bit; if (p_info) hash.update((unsigned char *) p_info->peer_hash_str.c_str(), p_info->peer_hash_str.length()); /* * Parse based on attribute type */ switch (attr_type) { case ATTR_TYPE_ORIGIN : // Origin update.attrs[LIB_ATTR_ORIGIN].official_type = ATTR_TYPE_ORIGIN; update.attrs[LIB_ATTR_ORIGIN].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_ORIGIN]; switch (data[0]) { case 0 : update.attrs[LIB_ATTR_ORIGIN].value.push_back(std::string("igp")); break; case 1 : update.attrs[LIB_ATTR_ORIGIN].value.push_back(std::string("egp")); break; case 2 : update.attrs[LIB_ATTR_ORIGIN].value.push_back(std::string("incomplete")); break; } update_hash(&update.attrs[LIB_ATTR_ORIGIN].value, &hash); break; case ATTR_TYPE_AS_PATH : // AS_PATH parseAttrDataAsPath(attr_len, data, update); update_hash(&update.attrs[LIB_ATTR_AS_PATH].value, &hash); break; case ATTR_TYPE_NEXT_HOP : // Next hop v4 memcpy(ipv4_raw, data, 4); inet_ntop(AF_INET, ipv4_raw, ipv4_char, sizeof(ipv4_char)); update.attrs[LIB_ATTR_NEXT_HOP].official_type = ATTR_TYPE_NEXT_HOP; update.attrs[LIB_ATTR_NEXT_HOP].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_NEXT_HOP]; update.attrs[LIB_ATTR_NEXT_HOP].value.push_back(std::string(ipv4_char)); update_hash(&update.attrs[LIB_ATTR_NEXT_HOP].value, &hash); break; case ATTR_TYPE_MED : // MED value { memcpy(&value32bit, data, 4); parse_bgp_lib::SWAP_BYTES(&value32bit); std::ostringstream numString; numString << value32bit; update.attrs[LIB_ATTR_MED].official_type = ATTR_TYPE_MED; update.attrs[LIB_ATTR_MED].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_MED]; update.attrs[LIB_ATTR_MED].value.push_back(numString.str()); update_hash(&update.attrs[LIB_ATTR_MED].value, &hash); break; } case ATTR_TYPE_LOCAL_PREF : // local pref value { memcpy(&value32bit, data, 4); parse_bgp_lib::SWAP_BYTES(&value32bit); std::ostringstream numString; numString << value32bit; char numstring[100] = {0}; update.attrs[LIB_ATTR_LOCAL_PREF].official_type = ATTR_TYPE_LOCAL_PREF; update.attrs[LIB_ATTR_LOCAL_PREF].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_LOCAL_PREF]; update.attrs[LIB_ATTR_LOCAL_PREF].value.push_back(numString.str()); update_hash(&update.attrs[LIB_ATTR_LOCAL_PREF].value, &hash); break; } case ATTR_TYPE_ATOMIC_AGGREGATE : // Atomic aggregate update.attrs[LIB_ATTR_ATOMIC_AGGREGATE].official_type = ATTR_TYPE_ATOMIC_AGGREGATE; update.attrs[LIB_ATTR_ATOMIC_AGGREGATE].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_ATOMIC_AGGREGATE]; update.attrs[LIB_ATTR_ATOMIC_AGGREGATE].value.push_back(std::string("1")); break; case ATTR_TYPE_AGGREGATOR : // Aggregator parseAttrDataAggregator(attr_len, data, update); update_hash(&update.attrs[LIB_ATTR_AGGREGATOR].value, &hash); break; case ATTR_TYPE_ORIGINATOR_ID : // Originator ID memcpy(ipv4_raw, data, 4); inet_ntop(AF_INET, ipv4_raw, ipv4_char, sizeof(ipv4_char)); update.attrs[LIB_ATTR_ORIGINATOR_ID].official_type = ATTR_TYPE_ORIGINATOR_ID; update.attrs[LIB_ATTR_ORIGINATOR_ID].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_ORIGINATOR_ID]; update.attrs[LIB_ATTR_ORIGINATOR_ID].value.push_back(std::string(ipv4_char)); break; case ATTR_TYPE_CLUSTER_LIST : // Cluster List (RFC 4456) // According to RFC 4456, the value is a sequence of cluster id's update.attrs[LIB_ATTR_CLUSTER_LIST].official_type = ATTR_TYPE_CLUSTER_LIST; update.attrs[LIB_ATTR_CLUSTER_LIST].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_CLUSTER_LIST]; for (int i = 0; i < attr_len; i += 4) { memcpy(ipv4_raw, data, 4); data += 4; inet_ntop(AF_INET, ipv4_raw, ipv4_char, sizeof(ipv4_char)); update.attrs[LIB_ATTR_CLUSTER_LIST].value.push_back(std::string(ipv4_char)); } break; case ATTR_TYPE_COMMUNITIES : // Community list { update.attrs[LIB_ATTR_COMMUNITIES].official_type = ATTR_TYPE_COMMUNITIES; update.attrs[LIB_ATTR_COMMUNITIES].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_COMMUNITIES]; for (int i = 0; i < attr_len; i += 4) { std::ostringstream numString; // Add entry memcpy(&value16bit, data, 2); data += 2; parse_bgp_lib::SWAP_BYTES(&value16bit); numString << value16bit; numString << ":"; memcpy(&value16bit, data, 2); data += 2; parse_bgp_lib::SWAP_BYTES(&value16bit); numString << value16bit; update.attrs[LIB_ATTR_COMMUNITIES].value.push_back(numString.str()); } update_hash(&update.attrs[LIB_ATTR_COMMUNITIES].value, &hash); break; } case ATTR_TYPE_EXT_COMMUNITY : // extended community list (RFC 4360) { update.attrs[LIB_ATTR_EXT_COMMUNITY].official_type = ATTR_TYPE_EXT_COMMUNITY; update.attrs[LIB_ATTR_EXT_COMMUNITY].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_EXT_COMMUNITY]; parse_bgp_lib::ExtCommunity ec(this, logger, debug); ec.parseExtCommunities(attr_len, data, update); update_hash(&update.attrs[LIB_ATTR_EXT_COMMUNITY].value, &hash); break; } case ATTR_TYPE_IPV6_EXT_COMMUNITY : // IPv6 specific extended community list (RFC 5701) { update.attrs[LIB_ATTR_IPV6_EXT_COMMUNITY].official_type = ATTR_TYPE_IPV6_EXT_COMMUNITY; update.attrs[LIB_ATTR_IPV6_EXT_COMMUNITY].name = parse_bgp_lib::parse_bgp_lib_attr_names[LIB_ATTR_IPV6_EXT_COMMUNITY]; parse_bgp_lib::ExtCommunity ec6(this, logger, debug); ec6.parsev6ExtCommunities(attr_len, data, update); break; } case ATTR_TYPE_MP_REACH_NLRI : // RFC4760 { parse_bgp_lib::MPReachAttr mp(this, logger, debug); mp.parseReachNlriAttr(attr_len, data, update); break; } case ATTR_TYPE_MP_UNREACH_NLRI : // RFC4760 { parse_bgp_lib::MPUnReachAttr mp(this, logger, debug); mp.parseUnReachNlriAttr(attr_len, data, update); break; } case ATTR_TYPE_AS_PATHLIMIT : // deprecated { break; } case ATTR_TYPE_BGP_LS: { MPLinkStateAttr ls(this, logger, &update, debug); ls.parseAttrLinkState(attr_len, data); break; } case ATTR_TYPE_AS4_PATH: { SELF_DEBUG("%sAttribute type AS4_PATH is not yet implemented, skipping for now.", debug_prepend_string.c_str()); break; } case ATTR_TYPE_AS4_AGGREGATOR: { SELF_DEBUG("%sAttribute type AS4_AGGREGATOR is not yet implemented, skipping for now.", debug_prepend_string.c_str()); break; } default: LOG_INFO("%sAttribute type %d is not yet implemented or intentionally ignored, skipping for now.", debug_prepend_string.c_str(), attr_type); break; } // END OF SWITCH ATTR TYPE }
void ins(point s,point t,point X,int i) { double r=fabs(t.x-s.x)>eps?(X.x-s.x)/(t.x-s.x):(X.y-s.y)/(t.y-s.y); r=min(r,1.0);r=max(r,0.0); e.pb(mp(r,i)); }
void loop(void) { const float spd1=30.0f*dt(); const float spd2=15.0f*dt(); float r=0.0f; float dc=0.0f, ds=0.0f; float tc=0.0f, ts=0.0f; /*viewport(0,0,nsw,nsh);*/ use_basic(); send_lpview(pview); if(mm() || mw()!=0.0f) { if(mm()) { dir+=mx()*spd1; if(dir<-0.0f) { dir+=360.0f; ndir+=360.0f; } else if(dir>360.0f) { dir-=360.0f; ndir-=360.0f; } tilt-=my()*spd1; if(tilt<0.001f) tilt=0.001f; else if(tilt>100.0f) tilt=100.0f; } if(mw()!=0.0f) { zoom-=mw(); if(zoom<7.0f) zoom=7.0f; else if(zoom>12.0f) zoom=12.0f; } } if(mp(3)) zoom=10.0f; ndir-=(ndir-dir)*spd2; r=d2r(ndir); dc=cosf(r); ds=sinf(r); ntilt-=(ntilt-tilt)*spd2; r=d2r(ntilt); tc=cosf(r); ts=sinf(r); nzoom-=(nzoom-zoom)*spd2; look(view,v3(ds*ts*nzoom,dc*ts*nzoom,3.0f+(tc*nzoom)),v3(0.0f,0.0f,3.0f)); mult(pview,proj,view); send_pview(pview); /* ----- */ use_fb(fbos[0]); clear(); /* ----- */ use_tex(area_tex); /* ----- */ draw_vbo(&area_mod); use_fb(0); blit_fb(fbos[0],fbos[1],nsw,nsh); /* ----- */ use_fb(fbos[2]); set_drawbufs(2); clear(); draw_vbo(&area_mod); use_fb(0); use_mblur(); use_tex(texs[0]); /* ----- */ active_tex(GL_TEXTURE1,texs[2]); default_tex(); use_fb(fbos[3]); set_drawbufs(1); clear(); quad(); use_fb(0); active_tex(GL_TEXTURE1,0); default_tex(); /*viewport(0,0,sw,sh);*/ use_vig(); use_tex(texs[3]); clear(); quad(); if(kp(SDL_SCANCODE_DELETE) || kp(SDL_SCANCODE_ESCAPE)) quit(); }
/// Send off all accumulated messages for this PE: void StreamingStrategy::flushPE(int pe) { //CkPrintf("Checking %d\n", pe); if(streamingMsgCount[pe] == 0) return; //Nothing to do. MessageHolder *cmsg; int size = 0; // Build a CmiMultipleSend list of messages to be sent off: int msg_count=streamingMsgCount[pe]; // If we have a single message we don't want to copy it if(msg_count == 1) { cmsg = streamingMsgBuf[pe].deq(); char *msg = cmsg->getMessage(); //envelope *env = UsrToEnv(msg); int size = cmsg->getSize(); CmiSyncSendAndFree(pe, size, msg); ComlibPrintf("[%d] StreamingStrategy::flushPE: one message to %d\n", CmiMyPe(), pe); delete cmsg; streamingMsgCount[pe] = 0; bufSize[pe] = 0; return; } PUP_cmiAllocSizer sp; StreamingMessage hdr; sp | hdr; int nmsgs = streamingMsgCount[pe]; int count; for(count = 0; count < nmsgs; count++) { cmsg = streamingMsgBuf[pe][count]; char *msg = cmsg->getMessage(); //envelope *env = UsrToEnv(msg); size = cmsg->getSize(); sp.pupCmiAllocBuf((void**)&msg, size); } char *newmsg = (char *)CmiAlloc(sp.size()); PUP_toCmiAllocMem mp(newmsg); hdr.srcPE = CmiMyPe(); hdr.nmsgs = nmsgs; mp | hdr; for(count = 0; count < nmsgs; count++) { cmsg = streamingMsgBuf[pe][count]; char *msg = cmsg->getMessage(); //envelope *env = UsrToEnv(msg); size = cmsg->getSize(); mp.pupCmiAllocBuf((void**)&msg, size); } for(count = 0; count < nmsgs; count++) { cmsg = streamingMsgBuf[pe].deq(); //CkFreeMsg(cmsg->getCharmMessage()); CmiFree(cmsg->getMessage()); delete cmsg; } streamingMsgCount[pe] = 0; bufSize[pe] = 0; CmiSetHandler(newmsg, CpvAccess(streaming_handler_id)); CmiSyncSendAndFree(pe, sp.size(), newmsg); //} }
OSStatus QMacInputContext::globalEventProcessor(EventHandlerCallRef, EventRef event, void *) { #ifndef QT_MAC_USE_COCOA QScopedLoopLevelCounter loopLevelCounter(QApplicationPrivate::instance()->threadData); SRefCon refcon = 0; GetEventParameter(event, kEventParamTextInputSendRefCon, typeRefCon, 0, sizeof(refcon), 0, &refcon); QMacInputContext *context = reinterpret_cast<QMacInputContext*>(refcon); bool handled_event=true; UInt32 ekind = GetEventKind(event), eclass = GetEventClass(event); switch(eclass) { case kEventClassTextInput: { handled_event = false; QWidget *widget = QApplicationPrivate::focus_widget; bool canCompose = widget && (!context || widget->inputContext() == context) && !(widget->inputMethodHints() & Qt::ImhDigitsOnly || widget->inputMethodHints() & Qt::ImhFormattedNumbersOnly || widget->inputMethodHints() & Qt::ImhHiddenText); if(!canCompose) { handled_event = false; } else if(ekind == kEventTextInputOffsetToPos) { if(!widget->testAttribute(Qt::WA_InputMethodEnabled)) { handled_event = false; break; } QRect mr(widget->inputMethodQuery(Qt::ImMicroFocus).toRect()); QPoint mp(widget->mapToGlobal(QPoint(mr.topLeft()))); Point pt; pt.h = mp.x(); pt.v = mp.y() + mr.height(); SetEventParameter(event, kEventParamTextInputReplyPoint, typeQDPoint, sizeof(pt), &pt); handled_event = true; } else if(ekind == kEventTextInputUpdateActiveInputArea) { if(!widget->testAttribute(Qt::WA_InputMethodEnabled)) { handled_event = false; break; } if (context->recursionGuard) break; ByteCount unilen = 0; GetEventParameter(event, kEventParamTextInputSendText, typeUnicodeText, 0, 0, &unilen, 0); UniChar *unicode = (UniChar*)NewPtr(unilen); GetEventParameter(event, kEventParamTextInputSendText, typeUnicodeText, 0, unilen, 0, unicode); QString text((QChar*)unicode, unilen / sizeof(UniChar)); DisposePtr((char*)unicode); ByteCount fixed_length = 0; GetEventParameter(event, kEventParamTextInputSendFixLen, typeByteCount, 0, sizeof(fixed_length), 0, &fixed_length); if(fixed_length == ULONG_MAX || fixed_length == unilen) { QInputMethodEvent e; e.setCommitString(text); context->currentText = QString(); qt_sendSpontaneousEvent(context->focusWidget(), &e); handled_event = true; context->reset(); } else { ByteCount rngSize = 0; OSStatus err = GetEventParameter(event, kEventParamTextInputSendHiliteRng, typeTextRangeArray, 0, 0, &rngSize, 0); QVarLengthArray<TextRangeArray> highlight(rngSize); if (noErr == err) { err = GetEventParameter(event, kEventParamTextInputSendHiliteRng, typeTextRangeArray, 0, rngSize, &rngSize, highlight.data()); } context->composing = true; if(fixed_length > 0) { const int qFixedLength = fixed_length / sizeof(UniChar); QList<QInputMethodEvent::Attribute> attrs; attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, qFixedLength, text.length()-qFixedLength, qt_mac_compose_format()); QInputMethodEvent e(text, attrs); context->currentText = text; e.setCommitString(text.left(qFixedLength), 0, qFixedLength); qt_sendSpontaneousEvent(widget, &e); handled_event = true; } else { /* Apple's enums that they have removed from Tiger :( enum { kCaretPosition = 1, kRawText = 2, kSelectedRawText = 3, kConvertedText = 4, kSelectedConvertedText = 5, kBlockFillText = 6, kOutlineText = 7, kSelectedText = 8 }; */ #ifndef kConvertedText #define kConvertedText 4 #endif #ifndef kCaretPosition #define kCaretPosition 1 #endif QList<QInputMethodEvent::Attribute> attrs; if (!highlight.isEmpty()) { TextRangeArray *data = highlight.data(); for (int i = 0; i < data->fNumOfRanges; ++i) { int start = data->fRange[i].fStart / sizeof(UniChar); int len = (data->fRange[i].fEnd - data->fRange[i].fStart) / sizeof(UniChar); if (data->fRange[i].fHiliteStyle == kCaretPosition) { attrs << QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, start, 0, QVariant()); continue; } QTextCharFormat format; format.setFontUnderline(true); if (data->fRange[i].fHiliteStyle == kConvertedText) format.setUnderlineColor(Qt::gray); else format.setUnderlineColor(Qt::black); attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, start, len, format); } } else { attrs << QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat, 0, text.length(), qt_mac_compose_format()); } context->currentText = text; QInputMethodEvent e(text, attrs); qt_sendSpontaneousEvent(widget, &e); handled_event = true; } } #if 0 if(!context->composing) handled_event = false; #endif extern bool qt_mac_eat_unicode_key; //qapplication_mac.cpp qt_mac_eat_unicode_key = handled_event; } else if(ekind == kEventTextInputUnicodeForKeyEvent) { EventRef key_ev = 0; GetEventParameter(event, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof(key_ev), 0, &key_ev); QString text; ByteCount unilen = 0; if(GetEventParameter(key_ev, kEventParamKeyUnicodes, typeUnicodeText, 0, 0, &unilen, 0) == noErr) { UniChar *unicode = (UniChar*)NewPtr(unilen); GetEventParameter(key_ev, kEventParamKeyUnicodes, typeUnicodeText, 0, unilen, 0, unicode); text = QString((QChar*)unicode, unilen / sizeof(UniChar)); DisposePtr((char*)unicode); } unsigned char chr = 0; GetEventParameter(key_ev, kEventParamKeyMacCharCodes, typeChar, 0, sizeof(chr), 0, &chr); if(!chr || chr >= 128 || (text.length() > 0 && (text.length() > 1 || text.at(0) != QLatin1Char(chr)))) handled_event = !widget->testAttribute(Qt::WA_InputMethodEnabled); QMacInputContext *context = qobject_cast<QMacInputContext*>(qApp->inputContext()); if (context && context->lastKeydownEvent()) { qt_keymapper_private()->translateKeyEvent(widget, 0, context->lastKeydownEvent(), 0, false); context->setLastKeydownEvent(0); } } break; } default: break; } if(!handled_event) //let the event go through return eventNotHandledErr; #else Q_UNUSED(event); #endif return noErr; //we eat the event }
void SystemPartitioner::init() { #if NONDESTRUCTIVE emit done(); return; #endif // Check # of harddisks to see if RAID0-ing them makes any sense ped_device_probe_all(); PedDevice *tmp=NULL; int disks=0; QString installsource(getenv("INSTALLSOURCE")); MSG("Install source is " + installsource); while((tmp=ped_device_get_next(tmp))) { // FIXME workaround for parted breakage // Skip CD-ROMs parted accidentally marks as harddisk QString p(tmp->path); if(!p.startsWith("/dev/sd") && (p.contains("/dev/scd") || p.contains("/dev/sr") || access(QFile::encodeName("/proc/ide/" + p.section('/', 2, 2) + "/cache"), R_OK))) continue; // It's not a good idea to install on a USB stick we're installing from... if(installsource.startsWith(p)) continue; MSG(QString("Found disk: ") + QString(tmp->path) + ":" + "/proc/ide/" + p.section('/', 2, 2) + "/" + "cache" + ":" + QString::number(access(QFile::encodeName("/proc/ide/" + p.section('/', 2, 2) + "/cache"), R_OK))); #if 0 // Check if the drive is actually there -- some empty CF // readers misidentify themselves... int fd=open(tmp->path, O_RDONLY); if(fd < 0) continue; char test; if(read(fd, &test, 1) <= 0) { close(fd); continue; } close(fd); #endif disks++; } ped_device_free_all(); // Grab all disks ped_device_probe_all(); PedFileSystemType const *ext3=ped_file_system_type_get("ext2"); // parted doesn't support ext3 creation yet, so we need this hack PedFileSystemType const *bootext3=ped_file_system_type_get("ext2"); PedFileSystemType const *swap=ped_file_system_type_get("linux-swap"); Meminfo m; unsigned long long swapsize=m.suggested_swap(); QStringList raidPartitions; PedDevice *dev=NULL; PedPartition *fspart=NULL; PedGeometry *fsgeo=NULL; setHelp(tr("Removing other OSes...")); resizeEvent(0); uint32_t bootsize=0; #ifndef NO_RAID0 if(disks>1) bootsize=32*1024*2; /* size is in 512 kB blocks --> we use 32 MB */ #endif while((dev=ped_device_get_next(dev))) { // FIXME workaround for parted breakage QString p(dev->path); if(!p.startsWith("/dev/sd") && (p.contains("/dev/scd") || p.contains("/dev/sr") || access(QFile::encodeName("/proc/ide/" + p.section('/', 2, 2) + "/cache"), R_OK))) continue; // It's not a good idea to install on a USB stick we're installing from... if(installsource.startsWith(p)) continue; //unsigned long long disksize=dev->length*dev->sector_size; PedDiskType *type=ped_disk_type_get("msdos"); PedDisk *disk=ped_disk_new_fresh(dev, type); PedGeometry *part=ped_geometry_new(dev, 0, dev->length); if(swapsize && _swap.isEmpty() && ((unsigned long long)part->length > swapsize + bootsize)) { // Split disk in swap and fs partitions PedGeometry *swapgeo=ped_geometry_new(dev, 0, swapsize); PedGeometry *bootgeo=NULL; uint32_t fssize=part->end - swapsize; uint32_t fsstart=swapsize+1; if(bootsize) { bootgeo=ped_geometry_new(dev, swapsize+1, bootsize); fssize -= bootsize; fsstart += bootsize; } fsgeo=ped_geometry_new(dev, fsstart, fssize); PedPartition *swappart=ped_partition_new(disk, (PedPartitionType)0, swap, swapgeo->start, swapgeo->end); PedPartition *bootpart=NULL; if(bootsize) bootpart=ped_partition_new(disk, (PedPartitionType)0, bootext3, bootgeo->start, bootgeo->end); fspart=ped_partition_new(disk, (PedPartitionType)0, ext3, fsgeo->start, fsgeo->end); if(bootsize) ped_partition_set_flag(fspart, PED_PARTITION_RAID, 1); ped_disk_add_partition(disk, swappart, ped_constraint_any(dev)); ped_disk_commit(disk); ped_geometry_destroy(swapgeo); setHelp(tr("Creating swap filesystem")); PedFileSystem *swapfs=ped_file_system_create(&(swappart->geom), swap, NULL /*timer->timer()*/); ped_file_system_close(swapfs); _swap = dev->path + QString::number(swappart->num); // Parted's swap creator is buggy QProcess::execute("/sbin/mkswap " + _swap); if(bootpart) { setHelp(tr("Creating boot filesystem")); ped_disk_add_partition(disk, bootpart, ped_constraint_any(dev)); ped_disk_commit(disk); PedFileSystem *bootfs=ped_file_system_create(&(bootpart->geom), bootext3, timer->timer()); ped_file_system_close(bootfs); ped_partition_set_flag(bootpart, PED_PARTITION_BOOT, 1); ped_geometry_destroy(bootgeo); QString devname=dev->path + QString::number(bootpart->num); _size.insert(devname, bootpart->geom.length); if(_rootfs == "ext3") { Ext3FS e3(devname); e3.addJournal(0); e3.setCheckInterval(0); e3.setCheckMountcount(-1); e3.setDirIndex(); } else { QProcess::execute("/sbin/mkfs." + _rootfs + " " + _mkfsopts + " " + devname); } if(!_postmkfs.isEmpty()) QProcess::execute(_postmkfs + " " + devname); _partitions.insert(devname, FileSystem("/boot", _rootfs)); } } else { // Grab the whole disk for filesystem fsgeo=ped_constraint_solve_max(ped_constraint_any(dev)); fspart=ped_partition_new(disk, (PedPartitionType)0, ext3, part->start, part->end); if(bootsize) ped_partition_set_flag(fspart, PED_PARTITION_RAID, 1); } ped_disk_add_partition(disk, fspart, ped_constraint_any(dev)); if(!bootsize) ped_partition_set_flag(fspart, PED_PARTITION_BOOT, 1); ped_disk_commit(disk); if(!bootsize) { setHelp(tr("Creating Linux filesystem")); PedFileSystem *fs=ped_file_system_create(&(fspart->geom), ext3, timer->timer()); _totalSize += fspart->geom.length; ped_file_system_close(fs); } ped_geometry_destroy(fsgeo); // Convert to ext3 and turn off checking QString devname=dev->path + QString::number(fspart->num); if(bootsize) raidPartitions.append(devname); else if(!_partitions.hasMountpoint("/")) _partitions.insert(devname, FileSystem("/", _rootfs)); else { QString mp(devname); mp.replace("/dev", "/mnt"); _partitions.insert(devname, FileSystem(mp, _rootfs)); } _size.insert(devname, fspart->geom.length); if(!bootsize) { if(_rootfs == "ext3") { Ext3FS e3(devname); e3.addJournal(0); e3.setCheckInterval(0); e3.setCheckMountcount(-1); e3.setDirIndex(); } else { QProcess::execute("/sbin/mkfs." + _rootfs + " " + _mkfsopts + " " + devname); } if(!_postmkfs.isEmpty()) QProcess::execute(_postmkfs + " " + devname); ped_disk_destroy(disk); } } if(bootsize) { setHelp(tr("Combining disks...")); // Make sure we can read the array we're building first... Modules::instance()->loadWithDeps("md"); Modules::instance()->loadWithDeps("raid0"); // Now create it FILE *f=fopen("/tmp/mdadm.conf", "w"); if(!f) QMessageBox::information(0, "debug", QString("Failed to create mdadm.conf: ") + strerror(errno)); fprintf(f, "DEVICE partitions"); fprintf(f, "ARRAY /dev/md0 name=ArkLinux devices=%s level=0 num-devices=%u\n", qPrintable(raidPartitions.join(",")), raidPartitions.count()); fprintf(f, "MAILADDR root@localhost\n"); fclose(f); QString command="/sbin/mdadm --create -e 1.2 --chunk=32 --level=0 --raid-devices=" + QString::number(raidPartitions.count()) + " --name=ArkLinux --force /dev/md0 " + raidPartitions.join(" "); QProcess::execute(command); if(_rootfs == "ext3") { QProcess::execute("/sbin/mke2fs -j /dev/md0"); Ext3FS e3("/dev/md0"); e3.setCheckInterval(0); e3.setCheckMountcount(-1); e3.setDirIndex(); } else { QProcess::execute("/sbin/mkfs." + _rootfs + " " + _mkfsopts + " /dev/md0"); } if(!_postmkfs.isEmpty()) QProcess::execute(_postmkfs + " /dev/md0"); _partitions.insert("/dev/md0", FileSystem("/", _rootfs)); _size.clear(); _size.insert("/dev/md0", _totalSize); } // We don't need a UI to take the whole system - we're done. emit done(); }
void ui (void) { mp (); }
void Autodetection::mergePatcher(void) { int n; // try ipodpatcher // initialize sector buffer. Needed. struct ipod_t ipod; ipod.sectorbuf = NULL; ipod_alloc_buffer(&ipod, BUFFER_SIZE); n = ipod_scan(&ipod); // FIXME: handle more than one Ipod connected in ipodpatcher. if(n == 1) { LOG_INFO() << "Ipod found:" << ipod.modelstr << "at" << ipod.diskname; // since resolveMountPoint is doing exact matches we need to select // the correct partition. QString mp(ipod.diskname); #ifdef Q_OS_LINUX mp.append("2"); #endif #ifdef Q_OS_MACX mp.append("s2"); #endif struct Detected d; d.device = ipod.targetname; d.mountpoint = Utils::resolveMountPoint(mp); // if the found ipod is a macpod also notice it as device with problem. if(ipod.macpod) d.status = PlayerWrongFilesystem; else d.status = PlayerOk; updateDetectedDevice(d); } else { LOG_INFO() << "ipodpatcher: no Ipod found." << n; } ipod_dealloc_buffer(&ipod); // try sansapatcher // initialize sector buffer. Needed. struct sansa_t sansa; sansa_alloc_buffer(&sansa, BUFFER_SIZE); n = sansa_scan(&sansa); if(n == 1) { LOG_INFO() << "Sansa found:" << sansa.targetname << "at" << sansa.diskname; QString mp(sansa.diskname); #ifdef Q_OS_LINUX mp.append("1"); #endif #ifdef Q_OS_MACX mp.append("s1"); #endif struct Detected d; d.device = QString("sansa%1").arg(sansa.targetname); d.mountpoint = Utils::resolveMountPoint(mp); d.status = PlayerOk; updateDetectedDevice(d); } else { LOG_INFO() << "sansapatcher: no Sansa found." << n; } sansa_dealloc_buffer(&sansa); }
void go() { bool flagChanged = 1; for (int it = 0;flagChanged; it++) { //cerr << "============================\n"; //for (auto x: G) //cerr << printAns(x.fr) << " = " << printAns(x.sc) << endl; //cerr << "============================\n"; flagChanged = 0; for (int i = 0; i < (int)G.size(); i++) { if (checkEqual(G[i].fr, G[i].sc)) { G.erase(G.begin() + i); flagChanged = 1; break; } } if (flagChanged) continue; for (int i = 0; i < (int)G.size(); i++) { shared_ptr < TNode > v = G[i].fr; shared_ptr < TNode > u = G[i].sc; if (v->checkFun() && u->checkFun()) { if (v->type != u->type || v->ch.size() != u->ch.size()) { cerr << v << " != " << u << endl; cerr << "fail\n"; exit(0); } G.erase(G.begin() + i); for (int j = 0; j < (int)v->ch.size(); j++) { G.pb(mp(v->ch[j], u->ch[j])); } flagChanged = 1; break; } } if (flagChanged) continue; for (int i = 0; i < (int)G.size(); i++) { if (G[i].fr->checkFun() && G[i].sc->checkVar()) { swap(G[i].fr, G[i].sc); } } // check x = f(x, ... ); for (int i = 0; i < (int)G.size(); i++) { if (G[i].fr->checkVar() && G[i].sc->checkFun()) { if (findVar(G[i].fr->type, G[i].sc)) { cerr << endl; cerr << G[i].fr << " = " << G[i].sc << endl; cerr << "fail\n"; exit(0); } } } //cerr << "last part====================\n"; //db2(G.back().fr->checkVar(), G.back().sc->checkFun()); for (int i = 0; i < (int)G.size(); i++) //if (G[i].fr->checkVar() && G[i].sc->checkFun()) { if (G[i].fr->checkVar()) { for (int j = 0; j < (int)G.size(); j++) { if (i == j) continue; //db2(i, j); if (findVar(G[i].fr->type, G[j].fr)) { G[j].fr = makeSubst(G[j].fr, G[i].fr->type, G[i].sc); flagChanged = 1; } if (findVar(G[i].fr->type, G[j].sc)) { G[j].sc = makeSubst(G[j].sc, G[i].fr->type, G[i].sc); flagChanged = 1; } } } } }
void ack( S *p ) { p->*mp(); }
void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e) { QPoint pos = widget->mapFromGlobal(e->globalPos()); if (!moveResizeMode && !buttonDown) { if (pos.y() <= range && pos.x() <= range) mode = TopLeft; else if (pos.y() >= widget->height()-range && pos.x() >= widget->width()-range) mode = BottomRight; else if (pos.y() >= widget->height()-range && pos.x() <= range) mode = BottomLeft; else if (pos.y() <= range && pos.x() >= widget->width()-range) mode = TopRight; else if (pos.y() <= range) mode = Top; else if (pos.y() >= widget->height()-range) mode = Bottom; else if (pos.x() <= range) mode = Left; else if ( pos.x() >= widget->width()-range) mode = Right; else if (widget->rect().contains(pos)) mode = Center; else mode = Nowhere; if (widget->isMinimized() || !isActive(Resize)) mode = Center; #ifndef QT_NO_CURSOR setMouseCursor(mode); #endif return; } if (mode == Center && !movingEnabled) return; if (widget->testAttribute(Qt::WA_WState_ConfigPending)) return; QPoint globalPos = (!widget->isWindow() && widget->parentWidget()) ? widget->parentWidget()->mapFromGlobal(e->globalPos()) : e->globalPos(); if (!widget->isWindow() && !widget->parentWidget()->rect().contains(globalPos)) { if (globalPos.x() < 0) globalPos.rx() = 0; if (globalPos.y() < 0) globalPos.ry() = 0; if (sizeprotect && globalPos.x() > widget->parentWidget()->width()) globalPos.rx() = widget->parentWidget()->width(); if (sizeprotect && globalPos.y() > widget->parentWidget()->height()) globalPos.ry() = widget->parentWidget()->height(); } QPoint p = globalPos + invertedMoveOffset; QPoint pp = globalPos - moveOffset; #ifdef Q_WS_X11 // Workaround for window managers which refuse to move a tool window partially offscreen. QRect desktop = QApplication::desktop()->availableGeometry(widget); pp.rx() = qMax(pp.x(), desktop.left()); pp.ry() = qMax(pp.y(), desktop.top()); p.rx() = qMin(p.x(), desktop.right()); p.ry() = qMin(p.y(), desktop.bottom()); #endif QSize ms = qSmartMinSize(childWidget); int mw = ms.width(); int mh = ms.height(); if (childWidget != widget) { mw += 2 * fw; mh += 2 * fw + extrahei; } QSize maxsize(childWidget->maximumSize()); if (childWidget != widget) maxsize += QSize(2 * fw, 2 * fw + extrahei); QSize mpsize(widget->geometry().right() - pp.x() + 1, widget->geometry().bottom() - pp.y() + 1); mpsize = mpsize.expandedTo(widget->minimumSize()).expandedTo(QSize(mw, mh)) .boundedTo(maxsize); QPoint mp(widget->geometry().right() - mpsize.width() + 1, widget->geometry().bottom() - mpsize.height() + 1); QRect geom = widget->geometry(); switch (mode) { case TopLeft: geom = QRect(mp, widget->geometry().bottomRight()) ; break; case BottomRight: geom = QRect(widget->geometry().topLeft(), p) ; break; case BottomLeft: geom = QRect(QPoint(mp.x(), widget->geometry().y()), QPoint(widget->geometry().right(), p.y())) ; break; case TopRight: geom = QRect(QPoint(widget->geometry().x(), mp.y()), QPoint(p.x(), widget->geometry().bottom())) ; break; case Top: geom = QRect(QPoint(widget->geometry().left(), mp.y()), widget->geometry().bottomRight()) ; break; case Bottom: geom = QRect(widget->geometry().topLeft(), QPoint(widget->geometry().right(), p.y())) ; break; case Left: geom = QRect(QPoint(mp.x(), widget->geometry().top()), widget->geometry().bottomRight()) ; break; case Right: geom = QRect(widget->geometry().topLeft(), QPoint(p.x(), widget->geometry().bottom())) ; break; case Center: geom.moveTopLeft(pp); break; default: break; } geom = QRect(geom.topLeft(), geom.size().expandedTo(widget->minimumSize()) .expandedTo(QSize(mw, mh)) .boundedTo(maxsize)); if (geom != widget->geometry() && (widget->isWindow() || widget->parentWidget()->rect().intersects(geom))) { if (mode == Center) widget->move(geom.topLeft()); else widget->setGeometry(geom); } QApplication::syncX(); }
ConnectCmdPtr RtmpParser::parseConnectCmd(RtmpMsgHeaderPtr& mh) { if(mh->length < 0) { throw RtmpBadProtocalData("body length should >=0"); } ReadBufferPtr readBuffer(new ReadBuffer(mh->length)); readBuffer->appendData(mh->body, mh->length); ConnectCmdPtr mp(new ConnectCmd()); AMF0ParserPtr ap(new AMF0Parser(readBuffer)); try { string commandName = ap->parseAsString(); if(commandName != "connect") { throw RtmpBadProtocalData("expect connect command"); } mp->transactionId = ap->parseAsNumber(); if(mp->transactionId != 1) { throw RtmpBadProtocalData("transactionId is not 1 in connect"); } // parse command object AMF0Types t = ap->getNextType(false); if(t != AMF0_Object) { throw RtmpBadProtocalData("RtmpParser::parseConnectCmd, Expect Command Object"); } ap->skipObjectStart(); bool parseKey = true; string keyName; ConnectCmdObjKey key; while(!ap->isFinished()) { t = ap->getNextType(true); if(t == AMF0_ObjectEnd) { // done ap->skipObjectEnd(); break; } if(parseKey) { keyName = ap->parseObjectKey(); key = CmdConnectIsKeyValid(keyName); } else { switch(key) { case CCK_App: mp->app = ap->parseAsString(); break; case CCK_Flashver: mp->flashver = ap->parseAsString(); break; case CCK_SwfUrl: mp->swfUrl = ap->parseAsString(); break; case CCK_TcUrl: mp->tcUrl = ap->parseAsString(); break; case CCK_Type: mp->type = ap->parseAsString(); break; case CCK_Fpad: mp->fpad = ap->parseAsBool(); break; case CCK_AudioCodecs: mp->audioCodecs = (AudioCodecConst)ap->parseAsNumber(); break; case CCK_VideoCodecs: mp->videoCodecs = (VideoCodecConst)ap->parseAsNumber(); break; case CCK_PageUrl: mp->pageUrl = ap->parseAsString(); break; case CCK_ObjectEncoding: mp->objectEncoding = (ObjectEncodingConst)ap->parseAsNumber(); break; default: RTMP_LOG(LEVDEBUG, "RtmpParser::parseConnectCmd: not interested key %s\n", keyName.c_str()); ap->skip(t); break; } } parseKey = !parseKey; } return mp; } catch(RtmpNoEnoughData& e) { throw RtmpBadProtocalData("length and body do not match"); } catch(RtmpInvalidAMFData& ae) { throw RtmpBadProtocalData("parseConnectCmd, data is corrupted"); } }
int smain() { int n; string input; cin >> n >> input; if (check(input, n)) { term termb, nterm; terms.resize(n+1); terms_next.resize(sz(terms)); for (int l = 1; l <= sz(input); pows[l] = true, l *= 2); for (int i = 0; i < sz(input); i++) { if (input[i] == '1') { getterm(termb, i, n); terms[termb.second].insert(mp(termb.first, i)); } } bool f = true; while (f) { f = false; for (int i = 0; i < sz(terms); i++) { for (auto j = terms[i].begin(); j != terms[i].end(); j++) { bool prev = true, next = true; if (i < sz(terms)-1) { for (auto k = terms[i + 1].begin(); k != terms[i + 1].end(); k++) if (term_comp(*j, *k)) { f = true; next = false; int q = new_term(*j, *k, nterm); terms_next[q].insert(nterm); } } if (i > 0) { for (auto k = terms[i - 1].begin(); k != terms[i - 1].end(); k++) if (term_comp(*k, *j)) { f = true; prev = false; int q = new_term(*k, *j, nterm); terms_next[q].insert(nterm); } } if (prev && next) terms_next[i].insert(*j); } } terms.clear(); terms = terms_next; terms_next.clear(); terms_next.resize(sz(terms)); } set<string> _terms, _next, _nexta; for (int i = 0; i < sz(input); i++) { if (input[i] == '1') { getterm(termb, i, n); _terms.insert(termb.first); } } for (int i = 0; i < sz(terms); i++) for (auto j = terms[i].begin(); j != terms[i].end(); j++) _next.insert(j->first); _nexta = _next; string minterm, result; for (auto j = _terms.begin(); j != _terms.end();) { int count = 0; minterm.clear(); for (auto i = _next.begin(); i != _next.end(); i++) if (term_compa(*j, *i)) { count++; if (count == 1) minterm = *i; } if (count == 1) { _nexta.erase(minterm); for (auto z = _terms.begin(); z != _terms.end();) if (term_compa(*z, minterm)) { _terms.erase(z); z = _terms.begin(); } else z++; j = _terms.begin(); } else j++; } for (auto j = _nexta.begin(); j != _nexta.end(); j++) _next.erase(*j); for (auto j = _next.begin(); j != _next.end(); j++) { if (j != _next.begin()) result += " v "; for (int i = 0; i < sz((*j)); i++) { if ((*j)[i] == '0') result += i + 97; if ((*j)[i] == '1') result += i + 65; } } int min = (int)1e9; string minresult; if (!_terms.empty()) { findminresult(result, _terms, _nexta, _terms.begin(), &min, minresult); cout << minresult << endl; } else cout << result << endl; system("pause"); } else { system("pause"); } return 0; }
MetaDataMsgPtr RtmpParser::parseMetaData(RtmpMsgHeaderPtr& mh) { if(mh->length < 0) { throw RtmpBadProtocalData("body length should >=0"); } ReadBufferPtr readBuffer(new ReadBuffer(mh->length)); readBuffer->appendData(mh->body, mh->length); MetaDataMsgPtr mp(new MetaDataMsg()); AMF0ParserPtr ap(new AMF0Parser(readBuffer)); bool parseKey = true; string keyName; try { string dataName = ap->parseAsString(); if(dataName != "@setDataFrame") { throw RtmpBadProtocalData("expect @setDataFrame"); } // set raw data mp->metadata = readBuffer->getUnReadBuffer(); mp->metadata_size = readBuffer->getUnReadSize(); if(ap->parseAsString() != "onMetaData") { throw RtmpBadProtocalData("expect onMetaData"); } // parse command object AMF0Types t = ap->getNextType(false); if(t == AMF0_Object) { ap->skipObjectStart(); } else if(t == AMF0_EcmaArray) { ap->skipEcmaArrayStart(); } else { throw RtmpBadProtocalData("RtmpParser::parseMetaData, Expect Command Object or ECMA array"); } while(!ap->isFinished()) { t = ap->getNextType(true); if(t == AMF0_ObjectEnd) { // done ap->skipObjectEnd(); break; } if(parseKey) { keyName = ap->parseObjectKey(); } else { if(keyName == "author") { mp->author = ap->parseAsString(); } else if(keyName == "copyright") { mp->copyright = ap->parseAsString(); } else if(keyName == "description") { mp->description = ap->parseAsString(); } else if(keyName == "keywords") { mp->keywords = ap->parseAsString(); } else if(keyName == "rating") { mp->rating = ap->parseAsString(); } else if(keyName == "title") { mp->title = ap->parseAsString(); } else if(keyName == "presetname") { mp->presetname = ap->parseAsString(); } else if(keyName == "creationdate") { mp->creationdate = ap->parseAsString(); } else if(keyName == "videodevice") { mp->videodevice = ap->parseAsString(); } else if(keyName == "framerate") { mp->framerate = (int)ap->parseAsNumber(); } else if(keyName == "width") { mp->width = ap->parseAsNumber(); } else if(keyName == "height") { mp->height = ap->parseAsNumber(); } else if(keyName == "videocodecid") { if(t == AMF0_Number) { // ffmpeg sent this as number mp->videocodecid = Utility::numToStr(ap->parseAsNumber()); } else { mp->videocodecid = ap->parseAsString(); } } else if(keyName == "videodatarate") { mp->videodatarate = ap->parseAsNumber(); } else if(keyName == "avclevel") { mp->avclevel = (int)ap->parseAsNumber(); } else if(keyName == "avcprofile") { mp->avcprofile = (int)ap->parseAsNumber(); } else if(keyName == "videokeyframe_frequency") { mp->videokeyframe_frequency = (int)ap->parseAsNumber(); } else if(keyName == "audiodevice") { mp->audiodevice = ap->parseAsString(); } else if(keyName == "audiosamplerate") { mp->audiosamplerate = ap->parseAsNumber(); } else if(keyName == "audiochannels") { mp->audiochannels = (int)ap->parseAsNumber(); } else if(keyName == "audioinputvolume") { mp->audioinputvolume = (int)ap->parseAsNumber(); } else if(keyName == "audiocodecid") { if(t == AMF0_Number) { // ffmpeg sent this as number mp->audiocodecid = Utility::numToStr(ap->parseAsNumber()); } else { mp->audiocodecid = ap->parseAsString(); } } else if(keyName == "audiodatarate") { mp->audiodatarate = ap->parseAsNumber(); } else { ap->skip(t); RTMP_LOG(LEVWARN, "onMetaData: ignore unknown key %s\n", keyName.c_str()); } } parseKey = !parseKey; } return mp; } catch(RtmpNoEnoughData& e) { throw RtmpBadProtocalData("length and body do not match"); } catch(RtmpInvalidAMFData& ae) { throw RtmpBadProtocalData(("parseMetaData, data is corrupted. key: " + keyName).c_str()); } }
Value search(Position& pos, Value alpha, Value beta, Depth depth) { ASSERT_LV3(alpha < beta); // ----------------------- // nodeの種類 // ----------------------- // root nodeであるか const bool RootNode = NT == Root; // PV nodeであるか(root nodeはPV nodeに含まれる) const bool PvNode = NT == PV || NT == Root; // ----------------------- // 変数宣言 // ----------------------- // 現在のnodeのrootからの手数。これカウンターが必要。 // nanoだとこのカウンター持ってないので適当にごまかす。 const int ply_from_root = (pos.this_thread()->rootDepth - depth / ONE_PLY) + 1; // ----------------------- // 置換表のprobe // ----------------------- auto key = pos.state()->key(); bool ttHit; // 置換表がhitしたか TTEntry* tte = TT.probe(key, ttHit); // 置換表上のスコア // 置換表にhitしなければVALUE_NONE Value ttValue = ttHit ? value_from_tt(tte->value(), ply_from_root) : VALUE_NONE; auto thisThread = pos.this_thread(); // 置換表の指し手 // 置換表にhitしなければMOVE_NONE // RootNodeであるなら、指し手は現在注目している1手だけであるから、それが置換表にあったものとして指し手を進める。 Move ttMove = RootNode ? thisThread->rootMoves[thisThread->PVIdx].pv[0] : ttHit ? pos.move16_to_move(tte->move()) : MOVE_NONE; // 置換表の値による枝刈り if (!PvNode // PV nodeでは置換表の指し手では枝刈りしない(PV nodeはごくわずかしかないので..) && ttHit // 置換表の指し手がhitして && tte->depth() >= depth // 置換表に登録されている探索深さのほうが深くて && ttValue != VALUE_NONE // (VALUE_NONEだとすると他スレッドからTTEntryが読みだす直前に破壊された可能性がある) && (ttValue >= beta ? (tte->bound() & BOUND_LOWER) : (tte->bound() & BOUND_UPPER)) // ttValueが下界(真の評価値はこれより大きい)もしくはジャストな値で、かつttValue >= beta超えならbeta cutされる // ttValueが上界(真の評価値はこれより小さい)だが、tte->depth()のほうがdepthより深いということは、 // 今回の探索よりたくさん探索した結果のはずなので、今回よりは枝刈りが甘いはずだから、その値を信頼して // このままこの値でreturnして良い。 ) { return ttValue; } // ----------------------- // 1手ずつ指し手を試す // ----------------------- pos.check_info_update(); MovePicker mp(pos,ttMove); Value value; Move move; StateInfo si; // この局面でdo_move()された合法手の数 int moveCount = 0; Move bestMove = MOVE_NONE; while (move = mp.next_move()) { // root nodeでは、rootMoves()の集合に含まれていない指し手は探索をスキップする。 if (RootNode && !std::count(thisThread->rootMoves.begin() + thisThread->PVIdx, thisThread->rootMoves.end(), move)) continue; // legal()のチェック。root nodeだとlegal()だとわかっているのでこのチェックは不要。 if (!RootNode && !pos.legal(move)) continue; // ----------------------- // 1手進める // ----------------------- pos.do_move(move, si, pos.gives_check(move)); // do_moveした指し手の数のインクリメント ++moveCount; // ----------------------- // 再帰的にsearchを呼び出す // ----------------------- // PV nodeの1つ目の指し手で進めたnodeは、PV node。さもなくば、non PV nodeとして扱い、 // alphaの値を1でも超えるかどうかだけが問題なので簡単なチェックで済ませる。 // また、残り探索深さがなければ静止探索を呼び出して評価値を返す。 // (searchを再帰的に呼び出して、その先頭でチェックする呼び出しのオーバーヘッドが嫌なのでここで行なう) bool fullDepthSearch = (PV && moveCount == 1); if (!fullDepthSearch) { // nonPVならざっくり2手ぐらい深さを削っていいのでは..(本当はもっとちゃんとやるべき) Depth R = ONE_PLY * 2; value = depth - R < ONE_PLY ? -qsearch<NonPV>(pos, -beta, -alpha, depth - R) : -YaneuraOuNano::search<NonPV>(pos, -(alpha + 1), -alpha, depth - R); // 上の探索によりalphaを更新しそうだが、いい加減な探索なので信頼できない。まともな探索で検証しなおす fullDepthSearch = value > alpha; } if ( fullDepthSearch) value = depth - ONE_PLY < ONE_PLY ? -qsearch<PV>(pos, -beta, -alpha, depth - ONE_PLY) : -YaneuraOuNano::search<PV>(pos, -beta, -alpha, depth - ONE_PLY); // ----------------------- // 1手戻す // ----------------------- pos.undo_move(move); // 停止シグナルが来たら置換表を汚さずに終了。 if (Signals.stop) return VALUE_ZERO; // ----------------------- // root node用の特別な処理 // ----------------------- if (RootNode) { auto& rm = *std::find(thisThread->rootMoves.begin(), thisThread->rootMoves.end(), move); if (moveCount == 1 || value > alpha) { // root nodeにおいてPVの指し手または、α値を更新した場合、スコアをセットしておく。 // (iterationの終わりでsortするのでそのときに指し手が入れ替わる。) rm.score = value; rm.pv.resize(1); // PVは変化するはずなのでいったんリセット // ここにPVを代入するコードを書く。(か、置換表からPVをかき集めてくるか) } else { // root nodeにおいてα値を更新しなかったのであれば、この指し手のスコアを-VALUE_INFINITEにしておく。 // こうしておかなければ、stable_sort()しているにもかかわらず、前回の反復深化のときの値との // 大小比較してしまい指し手の順番が入れ替わってしまうことによるオーダリング性能の低下がありうる。 rm.score = -VALUE_INFINITE; } } // ----------------------- // alpha値の更新処理 // ----------------------- if (value > alpha) { alpha = value; bestMove = move; // αがβを上回ったらbeta cut if (alpha >= beta) break; } } // end of while // ----------------------- // 生成された指し手がない? // ----------------------- // 合法手がない == 詰まされている ので、rootの局面からの手数で詰まされたという評価値を返す。 if (moveCount == 0) alpha = mated_in(ply_from_root); // ----------------------- // 置換表に保存する // ----------------------- tte->save(key, value_to_tt(alpha, ply_from_root), alpha >= beta ? BOUND_LOWER : PvNode && bestMove ? BOUND_EXACT : BOUND_UPPER, // betaを超えているということはbeta cutされるわけで残りの指し手を調べていないから真の値はまだ大きいと考えられる。 // すなわち、このとき値は下界と考えられるから、BOUND_LOWER。 // さもなくば、(PvNodeなら)枝刈りはしていないので、これが正確な値であるはずだから、BOUND_EXACTを返す。 // また、PvNodeでないなら、枝刈りをしているので、これは正確な値ではないから、BOUND_UPPERという扱いにする。 // ただし、指し手がない場合は、詰まされているスコアなので、これより短い/長い手順の詰みがあるかも知れないから、 // すなわち、スコアは変動するかも知れないので、BOUND_UPPERという扱いをする。 depth, bestMove, VALUE_NONE,TT.generation()); return alpha; }
int main() { myPair<int, std::string> mp(42, "Hi"); std::cout << mp[0_i] << ", " << mp[1_i] << '\n'; }
vec3 color(const ray& r, hitable *world, int depth) { hit_record rec; if (world->hit(r, 0.001f, 10000, rec)) { ray scattered; vec3 albedo; float pdf; auto emit = rec.mat_ptr->emit(rec.u, rec.v, rec.p); if (depth < g_maxdepth && rec.mat_ptr->scatter(r, rec, albedo, scattered, pdf)) { #if 0 auto clr = color(scattered, world, depth + 1); auto scattering_pdf = rec.mat_ptr->scattering_pdf(r, rec, scattered); //return emit + albedo * scattering_pdf * clr / pdf; auto ret = emit + albedo * scattering_pdf * clr / pdf; return ret; #elif 0 // ライト上のランダムな位置. vec3 on_light = vec3(213 + drand48() * (343 - 213), 554, 227 + drand48() * (332 - 227)); // ライトへの方向ベクトル. vec3 to_light = on_light - rec.p; // ライトへの距離の2乗. float distance_squared = to_light.squared_length(); auto tl = to_light; to_light.make_unit_vector(); // オブジェクトの内側に向かうようなら、これ以上は処理しない. if (dot(to_light, rec.normal) < 0.0f) { return emit; } // ライトの面積. float light_area = (343 - 213) * (332 - 227); // ライトの法線とライトへの方向ベクトルのなす角. // 今回はライトは天井に変更で下向き. float light_cosine = dot(-to_light, vec3(0, -1, 0)); if (light_cosine < 0.000001f) { return emit; } pdf = distance_squared / (light_cosine * light_area); scattered = ray(rec.p, to_light); auto clr = color(scattered, world, depth + 1); auto scattering_pdf = rec.mat_ptr->scattering_pdf(r, rec, scattered); auto ret = emit + albedo * scattering_pdf * clr / pdf; return ret; #else xz_rect ligth_shape(213, 343, 227, 332, 554, nullptr); hitable_pdf p0(&ligth_shape, rec.p); cosine_pdf p1(rec.normal); mixture_pdf mp(&p0, &p1); auto direction = mp.generate(); scattered = ray(rec.p, direction); pdf = mp.value(scattered.dir); auto clr = color(scattered, world, depth + 1); auto scattering_pdf = rec.mat_ptr->scattering_pdf(r, rec, scattered); auto ret = emit + albedo * scattering_pdf * clr / pdf; return ret; #endif } else { return emit; } } else { // 暗闇. return vec3(0, 0, 0); } }
void MeshStreamingStrategy::FlushColumn (int column) { int dest_column_pe; int num_msgs; int newmsgsize; char *newmsg; CmiAssert (column < num_columns); dest_column_pe = column + (my_row * row_length); if (dest_column_pe >= num_pe) { // This means that there is a hole in the mesh. //dest_column_pe = column + ((my_row % (num_rows - 1) - 1) * row_length); int new_row = my_column % (my_row + 1); if(new_row >= my_row) new_row = 0; dest_column_pe = column + new_row * row_length; } num_msgs = column_bucket[column].length (); if(num_msgs == 0) return; ComlibPrintf ("[%d] MeshStreamingStrategy::FlushColumn() invoked. to %d\n", CkMyPe(), dest_column_pe); PUP_cmiAllocSizer sp; int i = 0; MeshStreamingHeader mhdr; mhdr.strategy_id = getInstance(); mhdr.num_msgs = num_msgs; sp | mhdr; for (i = 0; i < num_msgs; i++) { void *msg = column_bucket[column][i]; int size = SIZEFIELD(msg);//((envelope *)msg)->getTotalsize(); int destpe = column_destQ[column][i]; sp | destpe; sp.pupCmiAllocBuf((void **)&msg, size); } newmsgsize = sp.size(); newmsg = (char *) CmiAlloc (newmsgsize); //((int *) (newmsg + CmiMsgHeaderSizeBytes))[0] = strategy_id; //((int *) (newmsg + CmiMsgHeaderSizeBytes))[1] = num_msgs; PUP_toCmiAllocMem mp(newmsg); //make a structure header mp | mhdr; /* newmsgptr = (char *) (newmsg + CmiMsgHeaderSizeBytes + 2 * sizeof (int)); for (int i = 0; i < num_msgs; i++) { msgptr = column_bucket[column].deq (); msgsize = ((int *) msgptr)[1] + (3 * sizeof (int)); memcpy (newmsgptr, msgptr, msgsize); newmsgptr += msgsize; delete [] msgptr; } */ for (i = 0; i < num_msgs; i++) { void *msg = column_bucket[column][i]; int destpe = column_destQ[column][i]; int size = SIZEFIELD(msg);//((envelope*)msg)->getTotalsize(); mp | destpe; mp.pupCmiAllocBuf((void **)&msg, size); } for (i = 0; i < num_msgs; i++) { void *msg = column_bucket[column].deq(); CmiFree(msg); column_destQ[column].deq(); } column_bytes[column] = 0; CmiSetHandler (newmsg, CkpvAccess(streaming_column_handler_id)); CmiSyncSendAndFree (dest_column_pe, newmsgsize, newmsg); }
int main(int argc, char* argv[]) { constexpr float l = -0.1f; constexpr float r = 0.1f; constexpr float b = -0.1f; constexpr float t = 0.1f; constexpr float dist = 0.1f; constexpr int SAMPLES = 64; const int SAMPLEDIM = sqrt(SAMPLES); #ifndef USE_OPENGL ppm = easyppm_create(NX, NY, IMAGETYPE_PPM); #endif // Materials Material mp(Color(0.2f, 0.2f, 0.2f), Color(1.0f, 1.0f, 1.0f), Color(0.0f, 0.0f, 0.0f), 0.0f, 0.5f); Material m1(Color(0.2f, 0.0f, 0.0f), Color(1.0f, 0.0f, 0.0f), Color(0.0f, 0.0f, 0.0f), 0.0f, 0.0f); Material m2(Color(0.0f, 0.2f, 0.0f), Color(0.0f, 0.5f, 0.0f), Color(0.5f, 0.5f, 0.5f), 32.0f, 0.0f); Material m3(Color(0.0f, 0.0f, 0.2f), Color(0.0f, 0.0f, 1.0f), Color(0.0f, 0.0f, 0.0f), 0.0f, 0.8f); // Surfaces SurfaceList surfaces; surfaces.add(std::move(std::unique_ptr<Plane>(new Plane(Eigen::Vector3f(0, -2, 0), Eigen::Vector3f(0, 1, 0), mp)))); surfaces.add(std::move(std::unique_ptr<Sphere>(new Sphere(Eigen::Vector3f(-4, 0, -7), 1, m1)))); surfaces.add(std::move(std::unique_ptr<Sphere>(new Sphere(Eigen::Vector3f( 0, 0, -7), 2, m2)))); surfaces.add(std::move(std::unique_ptr<Sphere>(new Sphere(Eigen::Vector3f( 4, 0, -7), 1, m3)))); // Light Light light(Eigen::Vector3f(-4, 4, -3), 1); // Add surfaces and light to scene Scene scene(surfaces, light); // Fill pixel buffer buffer = new Color[NX*NY]; #if defined(USE_OPENMP) #pragma omp parallel for #endif for (int k = 0; k < NX*NY; k++) { int i = k % NX; int j = k / NX; Color res(0,0,0); for (int si = 0; si < SAMPLEDIM; si++) { for (int sj = 0; sj < SAMPLEDIM; sj++) { // Uniform sampling float x = (i-0.5f) + (si)/(float)SAMPLEDIM; float y = (j-0.5f) + (sj)/(float)SAMPLEDIM; float u = l + ((r-l)*(x+0.5f)/NX); float v = b + ((t-b)*(y+0.5f)/NY); auto p = Eigen::Vector3f(0, 0, 0); auto d = Eigen::Vector3f(u, v, -dist); auto ray = Ray(p, d); auto hit = std::unique_ptr<Intersection>(scene.intersect(ray)); if (hit) res += scene.shade(ray, *hit, 2, true, false).correct(2.2f); } } #if defined(USE_OPENGL) buffer[i*NY + j] = res / SAMPLES; #else auto color = res / SAMPLES; auto r = clamp(color.r * 255, 0, 255); auto g = clamp(color.g * 255, 0, 255); auto b = clamp(color.b * 255, 0, 255); easyppm_set(&ppm, i, j, easyppm_rgb(r, g, b)); #endif } #if defined(USE_OPENGL) // Write buffer to OpenGL window glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(NX, NY); glutCreateWindow("Part 4"); glutDisplayFunc(gl_display); glutKeyboardFunc(gl_keyboard); glutMainLoop(); #else // Write buffer to image file const char* path = "images/part4.ppm"; easyppm_invert_y(&ppm); easyppm_write(&ppm, path); easyppm_destroy(&ppm); printf("Image written to %s\n", path); #endif delete[] buffer; return 0; }
int main(int argc, const char * argv[]) { /* MapUtil map = MapUtil(); string mapData = "test.jpg 600 400 0 0\n20 0\n20 50\n200 50\n200 200\n600 400\nroad\n0 0 20 0 1 1\n20 0 20 50 1 1\n20 50 200 50 1 1\n200 50 200 200 1 1\n200 200 600 400 1 1\n0 0 20 50 1 1\n20 50 200 200 1 1\n"; map.initMapData(mapData); mapPoint start = mapPoint(2.0, 2.0); mapPoint end = mapPoint(201.0,201.0); mapPoint origin = mapPoint(-5.0,-5.0); vector<mapPoint> paths = map.getPath(start, end, origin, 2.0); for (int i = 0; i < paths.size(); i++) { cout << paths[i].first << "\t" << paths[i].second << endl; } */ /* vector<mapPoint> mapDataPoints; vector<Arc> mapDataRoads; string mapData = "map.jpg 650 190 "; ifstream ifs("/Users/Water/Documents/XCodeWorkspace/MapUtil/a.csv"); ifstream ifs2("/Users/Water/Documents/XCodeWorkspace/MapUtil/b.csv"); string tmp; while (getline(ifs, tmp)) { for (int i = 0; i < tmp.size(); i++) { if (tmp[i] == ';') { tmp[i] = '\t'; } else { continue; } } stringstream ss(tmp); double x; double y; while (ss >> x >> y) { mapPoint tmpPoint; tmpPoint.first = x; tmpPoint.second = y; mapDataPoints.push_back(tmpPoint); } } while (getline(ifs2, tmp)) { for (int i = 0; i < tmp.size(); i++) { if (tmp[i] == ';') { tmp[i] = '\t'; } else { continue; } } cout << "tmp:" << tmp << endl; stringstream ss(tmp); double x; double y; double x2; double y2; while (ss >> x >> y >> x2 >> y2) { mapPoint tmpPoint; tmpPoint.first = x; tmpPoint.second = y; mapPoint tmpPoint2; tmpPoint2.first = x2; tmpPoint2.second = y2; Arc tmpArc; tmpArc.startPoint = tmpPoint; tmpArc.endPoint = tmpPoint2; tmpArc.weight = 1; tmpArc.width = 1; mapDataRoads.push_back(tmpArc); } } for (int i = 0; i < mapDataPoints.size(); i++) { mapData = mapData + double2string(mapDataPoints[i].first) + " " + double2string(mapDataPoints[i].second) + '\n'; } mapData += "road\n"; for (int i = 0; i < mapDataRoads.size(); i++) { mapData = mapData + double2string(mapDataRoads[i].startPoint.first) + " " + double2string(mapDataRoads[i].startPoint.second) + " " + double2string(mapDataRoads[i].endPoint.first) + " " + double2string(mapDataRoads[i].endPoint.second) + " " + double2string(mapDataRoads[i].weight) + " " + double2string(mapDataRoads[i].width) + '\n'; } cout << mapData; MapUtil map = MapUtil(); //string mapData = "test.jpg 600 400 0 0\n20 0\n20 50\n200 50\n200 200\n600 400\nroad\n0 0 20 0 1 1\n20 0 20 50 1 1\n20 50 200 50 1 1\n200 50 200 200 1 1\n200 200 600 400 1 1\n0 0 20 50 1 1\n20 50 200 200 1 1\n"; map.initMapData(mapData); mapPoint start = mapPoint(14.0, 9.0); mapPoint end = mapPoint(650.0,188.0); mapPoint origin = mapPoint(0.0,0.0); vector<mapPoint> paths = map.getPath(start, end, origin, 1.0); for (int i = 0; i < paths.size(); i++) { cout << paths[i].first << "\t" << paths[i].second << endl; } */ mapPoint mp(40, 0); mapPoint sp(0,0); mapPoint ep(100,100); cout << getDistanceFromPointToLine(mp, sp, ep) << endl; return 0; }
bpt::ptree& FileSystemTestSetup::make_config_(bpt::ptree& pt, const fs::path& topdir, const vfs::NodeId& vrouter_id) const { be::BackendTestSetup::backend_config().persist_internal(pt, ReportDefault::T); // scocache { vd::MountPointConfigs mp_configs; mp_configs.push_back(vd::MountPointConfig(scocache_mountpoint(topdir).string(), scache_size_)); ip::PARAMETER_TYPE(scocache_mount_points)(mp_configs).persist(pt); ip::PARAMETER_TYPE(trigger_gap)(yt::DimensionedValue(scache_trigger_gap_)).persist(pt); ip::PARAMETER_TYPE(backoff_gap)(yt::DimensionedValue(scache_backoff_gap_)).persist(pt); } // clustercache { std::vector<vd::MountPointConfig> kfgs; yt::DimensionedValue csize("20MiB"); const fs::path kdev(clustercache_mountpoint(topdir)); maybe_setup_clustercache_device(kdev, csize.getBytes()); vd::MountPointConfig mp(kdev, csize.getBytes()); kfgs.push_back(mp); ip::PARAMETER_TYPE(clustercache_mount_points)(kfgs).persist(pt); ip::PARAMETER_TYPE(read_cache_serialization_path)(clustercache_serialization_path(topdir).string()).persist(pt); } // volmanager { ip::PARAMETER_TYPE(tlog_path)(tlog_dir(topdir).string()).persist(pt); ip::PARAMETER_TYPE(metadata_path)(mdstore_dir(topdir).string()).persist(pt); ip::PARAMETER_TYPE(open_scos_per_volume)(open_scos_per_volume_).persist(pt); ip::PARAMETER_TYPE(datastore_throttle_usecs)(dstore_throttle_usecs_).persist(pt); ip::PARAMETER_TYPE(clean_interval)(scache_clean_interval_).persist(pt); ip::PARAMETER_TYPE(number_of_scos_in_tlog)(num_scos_in_tlog_).persist(pt); ip::PARAMETER_TYPE(debug_metadata_path)(dump_on_halt_dir(topdir).string()).persist(pt); // (backend)threadpool ip::PARAMETER_TYPE(num_threads)(num_threads_).persist(pt); } // metadata_server - we run it outside volmanager, hence empty ServerConfigs here. { // not 'const' as clang analyzer 3.8 does not like using the defaulted default ctor: // error: default initialization of an object of const type 'const mds::ServerConfigs' (aka 'const vector<metadata_server::ServerConfig>') without a user-provided default constructor // const mds::ServerConfigs scfgs; // ^ // {} // 1 error generated. mds::ServerConfigs scfgs; mds_test_setup_->make_manager_config(pt, scfgs); } // distributed_lock_store { ip::PARAMETER_TYPE(dls_type)(vd::LockStoreType::Arakoon).persist(pt); ip::PARAMETER_TYPE(dls_arakoon_cluster_id)(arakoon_test_setup_->clusterID().str()).persist(pt); const auto node_configs(arakoon_test_setup_->node_configs()); const ip::PARAMETER_TYPE(dls_arakoon_cluster_nodes)::ValueType node_configv(node_configs.begin(), node_configs.end()); ip::PARAMETER_TYPE(dls_arakoon_cluster_nodes)(node_configv).persist(pt); } // filedriver { ip::PARAMETER_TYPE(fd_cache_path)(fdriver_cache_dir(topdir).string()).persist(pt); ip::PARAMETER_TYPE(fd_namespace)(fdriver_namespace_.str()).persist(pt); } // filesystem { ip::PARAMETER_TYPE(fs_ignore_sync)(false).persist(pt); const std::string backend_dir(source_dir().string()); ip::PARAMETER_TYPE(fs_virtual_disk_format)(vdisk_format_->name()).persist(pt); ip::PARAMETER_TYPE(fs_cache_dentries)(true).persist(pt); ip::PARAMETER_TYPE(fs_enable_shm_interface)(true).persist(pt); ip::PARAMETER_TYPE(fs_enable_network_interface)(true).persist(pt); make_mdstore_config_(pt); make_dtl_config_(vrouter_id, pt); } // volume_router { ip::PARAMETER_TYPE(vrouter_backend_sync_timeout_ms)(backend_sync_timeout_ms_).persist(pt); ip::PARAMETER_TYPE(vrouter_migrate_timeout_ms)(migrate_timeout_ms_).persist(pt); ip::PARAMETER_TYPE(vrouter_redirect_timeout_ms)(redirect_timeout_ms_).persist(pt); ip::PARAMETER_TYPE(vrouter_redirect_retries)(redirect_retries_).persist(pt); ip::PARAMETER_TYPE(vrouter_id)(vrouter_id).persist(pt); ip::PARAMETER_TYPE(scrub_manager_interval)(scrub_manager_interval_secs_).persist(pt); ip::PARAMETER_TYPE(vrouter_use_fencing)(use_fencing_).persist(pt); ip::PARAMETER_TYPE(vrouter_send_sync_response)(send_sync_response_).persist(pt); } // volume_router_cluster { ip::PARAMETER_TYPE(vrouter_cluster_id)(vrouter_cluster_id()).persist(pt); } //failovercache { ip::PARAMETER_TYPE(dtl_path)(failovercache_dir(topdir).string()).persist(pt); ip::PARAMETER_TYPE(dtl_transport)(failovercache_transport()).persist(pt); } // volume_registry make_registry_config_(pt); // event_publisher is not configured for now as it's entirely optional. // stats_collector { ip::PARAMETER_TYPE(stats_collector_interval_secs)(30).persist(pt); } return pt; }
void OMR::CodeGenPhase::performProcessRelocationsPhase(TR::CodeGenerator * cg, TR::CodeGenPhase * phase) { TR::Compilation * comp = cg->comp(); if (comp->getPersistentInfo()->isRuntimeInstrumentationEnabled()) { // This must be called before relocations to generate the relocation data for the profiled instructions. cg->createHWPRecords(); } phase->reportPhase(ProcessRelocationsPhase); TR::LexicalMemProfiler mp(phase->getName(), comp->phaseMemProfiler()); LexicalTimer pt(phase->getName(), comp->phaseTimer()); cg->processRelocations(); cg->resizeCodeMemory(); cg->registerAssumptions(); cg->syncCode(cg->getBinaryBufferStart(), cg->getBinaryBufferCursor() - cg->getBinaryBufferStart()); if (comp->getOption(TR_EnableOSR)) { if (comp->getOption(TR_TraceOSR) && !comp->getOption(TR_DisableOSRSharedSlots)) { (*comp) << "OSRCompilationData is " << *comp->getOSRCompilationData() << "\n"; } } if (comp->getOption(TR_AOT) && (comp->getOption(TR_TraceRelocatableDataCG) || comp->getOption(TR_TraceRelocatableDataDetailsCG) || comp->getOption(TR_TraceReloCG))) { traceMsg(comp, "\n<relocatableDataCG>\n"); if (comp->getOption(TR_TraceRelocatableDataDetailsCG)) // verbose output { uint8_t * relocatableMethodCodeStart = (uint8_t *)comp->getRelocatableMethodCodeStart(); traceMsg(comp, "Code start = %8x, Method start pc = %x, Method start pc offset = 0x%x\n", relocatableMethodCodeStart, cg->getCodeStart(), cg->getCodeStart() - relocatableMethodCodeStart); } cg->getAheadOfTimeCompile()->dumpRelocationData(); traceMsg(comp, "</relocatableDataCG>\n"); } if (debug("dumpCodeSizes")) { diagnostic("%08d %s\n", cg->getCodeLength(), comp->signature()); } if (comp->getCurrentMethod() == NULL) { comp->getMethodSymbol()->setMethodAddress(cg->getBinaryBufferStart()); } TR_ASSERT(cg->getCodeLength() <= cg->getEstimatedCodeLength(), "Method length estimate must be conservatively large\n" " codeLength = %d, estimatedCodeLength = %d \n", cg->getCodeLength(), cg->getEstimatedCodeLength() ); // also trace the interal stack atlas cg->getStackAtlas()->close(cg); TR::SimpleRegex * regex = comp->getOptions()->getSlipTrap(); if (regex && TR::SimpleRegex::match(regex, comp->getCurrentMethod())) { if (TR::Compiler->target.is64Bit()) { setDllSlip((char*)cg->getCodeStart(),(char*)cg->getCodeStart()+cg->getCodeLength(),"SLIPDLL64", comp); } else { setDllSlip((char*)cg->getCodeStart(),(char*)cg->getCodeStart()+cg->getCodeLength(),"SLIPDLL31", comp); } } if (comp->getOption(TR_TraceCG) || comp->getOptions()->getTraceCGOption(TR_TraceCGPostBinaryEncoding)) { const char * title = "Post Relocation Instructions"; comp->getDebug()->dumpMethodInstrs(comp->getOutFile(), title, false, true); traceMsg(comp,"<snippets>"); comp->getDebug()->print(comp->getOutFile(), cg->getSnippetList()); traceMsg(comp,"\n</snippets>\n"); auto iterator = cg->getSnippetList().begin(); int32_t estimatedSnippetStart = cg->getEstimatedSnippetStart(); while (iterator != cg->getSnippetList().end()) { estimatedSnippetStart += (*iterator)->getLength(estimatedSnippetStart); ++iterator; } } }