void read_header(struct header_t * header, FILE * f) { int code; code = fseek(f, 0, SEEK_SET); if (code == -1) WTF(); code = fread(header, HEADER_SIZE, 1, f); if (1 != code) WTF(); }
void selfTestCallback::execute (XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { ModuleFactory::map_type* mods = ModuleFactory::getMap(); ModuleFactory::map_type::iterator it; if(mods->size() == 0) { WTF("no modules are registered!"); result = 0; } else { for(it = mods->begin(); it != mods->end(); it++) { printf("\n** creating node with name %s **\n", ((std::string)it->first).c_str()); Module* m = ModuleFactory::createInstance((std::string)it->first); printf("description : %s\n", m->description().c_str()); printf("input type : %s\n", m->inputType().c_str()); printf("is input : %s\n", m->isInput() ? "INPUT" : "NO"); printf("output type : %s\n", m->outputType().c_str()); printf("is output : %s\n", m->isOutput() ? "OUTPUT" : "NO"); printf("is strem : %s\n", m->isStream() ? "STREAM" : "NO"); printf("usage : %s\n", m->usage().c_str()); delete m; printf("** module successfully deleted ** \n\n"); } } fflush(stdout); result = 1; }
int remove_words(FILE * f, char * word) { int count = 0; // асимптотика квадратичная :) // TODO: сделать параметр from в find_word, чтобы сделать её линейной. while (1) { uint64 start = find_word(f, word); if (start == 0) { // Если нет слова, и мы его не удаляли return count; } struct entry_t entry; // TODO: дважды read_entry -- плохо read_entry(f, &entry, start, READ_ENTRY_ALL); mark_deleted_entry(&entry); count++; int code = fseek(f, start, SEEK_SET); if (0 != code) WTF(); write_entry(f, &entry); header.actual_words--; write_header(&header, f); } }
void command_defragment(FILE * f) { uint64 read_index, write_index, index; read_index = write_index = jump_to_first_word(f); int read_count = 0; int write_count = 0; struct entry_t entry; again: if (write_count < header.actual_words) { index = read_entry(f, &entry, read_index, READ_ENTRY_ALL); if (existent_entry(&entry)) { read_index = index; read_count++; int code = fseek(f, write_index, SEEK_SET); if (0 != code) WTF(); write_entry(f, &entry); write_count++; write_index += entry_size(&entry); goto again; } else { read_index = index; goto again; } } else { header.total_words = header.actual_words; write_header(&header, f); ftruncate(fileno(f), write_index); } }
void write_entry( FILE * f, struct entry_t * entry ) { assert( entry->word_len <= 128 ); assert( entry->content_len < 16777216 ); uint32 temp = (entry->word_len & 0xFF) | ((entry->content_len) << 8); int code = fwrite( &temp, 4, 1, f ); if( 1 != code ) WTF(); if( entry->word_len != 0 ) { code = fwrite( entry->word, entry->word_len, 1, f ); if( 1 != code ) WTF(); code = fwrite( entry->content, entry->content_len, 1, f ); if( 1 != code ) WTF(); } }
void write_new_header(struct header_t * header, FILE * f) { header->version = 1; header->total_words = 0; header->actual_words = 0; int code; write_header(header, f); fflush(f); code = ftruncate(fileno(f), HEADER_SIZE); if (0 != code) { fprintf( stderr, "errno = %d\n", errno); WTF(); } }
void showModulesCallback::execute (XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { int i = 0; ModuleFactory::map_type* mods = ModuleFactory::getMap(); ModuleFactory::map_type::iterator it; if(mods->size() == 0) { WTF("no modules are registered!"); result = 0; } else { std::vector<std::string> input_mods; std::vector<std::string> flow_mods; std::vector<std::string> output_mods; for(it = mods->begin(); it != mods->end(); it++) { Module* m = ModuleFactory::createInstance((std::string)it->first); // input, output, or flow node? if(!m->isInput() && !m->isOutput()) { flow_mods.push_back((std::string)it->first); } else if(m->isInput()) { input_mods.push_back((std::string)it->first); } else { output_mods.push_back((std::string)it->first); } delete m; } result.setSize(int(mods->size())); std::vector<std::string>::iterator itm; for(itm = input_mods.begin(); itm != input_mods.end(); itm++) { result[i++] = (*itm); } for(itm = flow_mods.begin(); itm != flow_mods.end(); itm++) { result[i++] = (*itm); } for(itm = output_mods.begin(); itm != output_mods.end(); itm++) { result[i++] = (*itm); } } fflush(stdout); }
void startLoopbackCallback::execute (XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result) { // if no arguments were received if (!params.valid()) { ctrl_xmlrpc->startProcessing(); } else { switch(params.size()) { case 3: FYI("params[0]: %d\n\tparams[1]: %s\n\tparams[2]: %d\n\t", (int)params[0], ((std::string)params[1]).c_str(), (int)params[2]); ctrl_xmlrpc->startLoopback((int)params[0], (std::string) params[1], (int) params[2]); break; default: WTF("WARNING! Server got wrong number of arguments!"); break; } } fflush(stdout); result = 0; }
uint64 read_entry( FILE * f, struct entry_t * entry, uint64 offset, int flags ) { int code; if( ( flags & READ_ENTRY_DO_SEEK ) != 0 ) { code = fseek( f, offset, SEEK_SET ); if( 0 != code ) WTF(); } uint32 temp = 0; fseek( f, offset, SEEK_SET ); code = fread( &temp, 1, 4, f ); if( 4 != code ) WTF(); offset += 4; entry->word_len = temp & 0xFF; entry->content_len = temp >> 8; // если запись не удалена if( 0 != entry->word_len ) { // выделяем память под слово и читаем его, устанавливаем \0. if( ( flags & READ_ENTRY_WORD ) != 0 ) { entry->word = malloc( entry->word_len+1 ); code = fread( entry->word, 1, entry->word_len, f ); if( entry->word_len != code ) WTF(); offset += entry->word_len; entry->word[entry->word_len] = 0; } else { entry->word = NULL; offset += entry->word_len; code = fseek( f, offset, SEEK_SET ); if( 0 != code ) WTF(); } // если надо, то читаем статью if( ( flags & READ_ENTRY_CONTENT ) != 0 ) { entry->content = malloc( entry->content_len+1 ); code = fread( entry->content, entry->content_len, 1, f); if( 1 != code ) WTF(); offset += entry->content_len; entry->content[entry->content_len] = 0; } // или пропускаем её else { entry->content = NULL; offset += entry->content_len; code = fseek( f, offset, SEEK_SET ); if( 0 != code ) WTF(); } } else { entry->word = NULL; entry->content = NULL; offset += entry->content_len; code = fseek( f, offset, SEEK_SET ); if( 0 != code ) WTF(); } return offset; }
vector <int> CFunction::split(string s) { vector <int> oper, tmp, binf; priority_queue <int, vector<int>,cmp> unf; int n_oper=0; int st=0, end=0; while (st<s.size()){ // if (s[st]=='('){ int num=0; for (end=st; end<s.size(); ++end){ if (s[end]=='('){ ++num; } else if (s[end]==')'){ --num; } if (!num) break; } tmp=split(s.substr(st+1, end-st-1)); if (tmp.empty()) return tmp; int t=oper.size(); oper.resize(oper.size()+tmp.size()); copy(tmp.begin(), tmp.end(), oper.begin()+t); n_oper++; // ERROR! if (n_oper>1 && binf.empty()) return vector <int> (); //ERROR! if (unf.size()>2) return vector<int>(); if (!unf.empty()){ oper.push_back(unf.top()); unf.pop(); } // ERROR! if (!unf.empty()){ // ATTENTION if (unf.top()==UNMINUS){ oper.push_back(unf.top()); unf.pop(); } else return vector <int>(); } st=end+1; } // else if (isdigit(s[st])){ for (end=st; end<s.size(); ++end){ if (!isdigit(s[end])) break; } oper.push_back( StrToInt( s.substr(st, end-st) ) ); n_oper++; // ERROR! if (n_oper>1 && binf.empty()) return vector <int> (); st=end; } // else if (isalpha(s[st])){ if (s[st]=='x'){ end=st+1; oper.push_back(VAR); n_oper++; // ERROR! if (unf.size()>2) return vector<int>(); // ATTENTION if (!unf.empty() && unf.top()==UNMINUS){ oper.push_back(unf.top()); unf.pop(); } // ERROR! if (n_oper>1 && binf.empty()) return vector <int> (); if (end<s.size() && s[end]=='^'){ st+=2; end=st; if (end<s.size() && isdigit(s[end])){ for (; end<s.size(); ++end){ if (!isdigit(s[end])) break; } oper.push_back(POW-StrToInt(s.substr(st, end-st) ) ); } //ERROR! else{ return vector<int>(); } } st=end; } else{ end=st+3; if (end<s.size()){ int t=WTF(s.substr(st, end-st)); //ERROR! if (!t) return vector <int>(); unf.push( t ); } //ERROR! else{ return vector<int>(); } st=end; } } // else if (s[st]=='*' || s[st]=='+'||s[st]=='-'||s[st]=='/'){ if (binf.size()==2){ if (n_oper==3){ n_oper=2; oper.push_back(binf.back()); binf.pop_back(); } // ERROR! else{ return vector<int>(); } } int op=WTO(s[st++]); // if there is no operands waiting if (!n_oper){ if (op==MINUS){ unf.push(UNMINUS); } // ERROR! else{ return vector <int>(); } } else if (n_oper==1){ if (binf.empty()) binf.push_back(op); // ERROR! else return vector<int>(); } else if (n_oper==2){ if (binf.size()==1){ if ( (binf.back()==MINUS || binf.back()==PLUS) && (op==MULT || op==DIV) ){ binf.push_back(op); } else{ n_oper=1; oper.push_back(binf.back()); binf.back()=op; } } // ERROR! else{ return vector <int>(); } } // ERROR! else return vector <int>(); } // else{ oper.clear(); return oper; } // end of while } // end of method if (n_oper>1){ if (n_oper==2){ if (!binf.empty()){ oper.push_back(binf.back()); } else return vector<int>(); } else if (n_oper==3){ if (binf.size()==2){ oper.push_back(binf.back()); oper.push_back(*binf.begin()); } else return vector <int>(); } else return vector <int>(); } if (!unf.empty()) return vector <int>(); return oper; }
static void trains_server(void) { register_as("trains"); struct trainsrv_state state; trainsrv_state_init(&state); train_alert_start(switch_historical_get_current(&state.switch_history), true); // TODO: we should block the creating task from continuing until init is done for (;;) { int tid = -1; struct trains_request req; receive(&tid, &req, sizeof(req)); /* printf("Trains server got message! %d"EOL, req.type); */ switch (req.type) { case QUERY_ACTIVE: { int active_trains[MAX_ACTIVE_TRAINS]; int num_active_trains = handle_query_active(&state, active_trains); reply(tid, &active_trains, num_active_trains * sizeof(active_trains[0])); break; } case QUERY_SPATIALS: { struct train_state ts = handle_query_spatials(&state, req.train_number); reply(tid, &ts, sizeof(ts)); break; } case QUERY_ARRIVAL: { int ticks = handle_query_arrival(&state, req.train_number, req.distance); reply(tid, &ticks, sizeof(ticks)); break; } case QUERY_ERROR: { int error = handle_query_error(&state, req.train_number); reply(tid, &error, sizeof(error)); break; } case SEND_SENSORS: handle_sensors(&state, req.sensors); reply(tid, NULL, 0); break; case SET_SPEED: handle_set_speed(&state, req.train_number, req.speed); reply(tid, NULL, 0); break; case REVERSE: handle_reverse(&state, req.train_number); reply(tid, NULL, 0); break; case REVERSE_UNSAFE: handle_reverse_unsafe(&state, req.train_number); reply(tid, NULL, 0); break; case SWITCH_SWITCH: handle_switch(&state, req.switch_number, req.direction); reply(tid, NULL, 0); break; case SWITCH_GET: { struct switch_state switches = switch_historical_get_current(&state.switch_history); reply(tid, &switches, sizeof(switches)); break; } case GET_STOPPING_DISTANCE: { struct internal_train_state *ts = get_train_state(&state, req.train_number); int distance = ts->est_stopping_distances[train_speed_index(ts, 1)]; reply(tid, &distance, sizeof(distance)); break; } case SET_STOPPING_DISTANCE: { struct internal_train_state *ts = get_train_state(&state, req.train_number); ts->est_stopping_distances[train_speed_index(ts, 1)] = req.stopping_distance; reply(tid, NULL, 0); break; } case GET_LAST_KNOWN_SENSOR: { struct internal_train_state *ts = get_train_state(&state, req.train_number); int last_sensor_hit = sensor_historical_get_current(&ts->sensor_history); reply(tid, &last_sensor_hit, sizeof(last_sensor_hit)); break; } default: nameserver_dump_names(); WTF("UNKNOWN TRAINS REQ %d FROM %d"EOL, req.type, tid); break; } } }
int main(int argc, char ** argv) { check(); // Передан файл базы как параметр if (argc == 2) { db_filename = argv[1]; } // Файл не передан, используется имя по умолчанию else if (argc == 1) { db_filename = "default.db"; } // Неправильное использование else { fprintf( stderr, "Usage: dictionary [words.db]\n"); exit( EXIT_WRONG_USAGE); } assert(NULL != db_filename); FILE * f = NULL; int code = access(db_filename, R_OK | W_OK); // Нет прав, не существует файл или что-нибудь ещё if (-1 == code) { // Нет файла, можно создавать if ( errno == ENOENT) { f = fopen(db_filename, "w+"); fprintf( stderr, "INFO: Файл не существовал и теперь создан.\n"); } else if ( errno == EACCES) { fprintf( stderr, "FATAL: Нет прав доступа к базе.\n"); exit( EXIT_WRONG_RIGHTS); } else { printf("errno = %d\n", errno); exit( EXIT_WTF); } } // Есть права и файл существует else { f = fopen(db_filename, "r+"); fprintf( stderr, "INFO: Существующий файл открыт для работы.\n"); } assert(NULL != f); fseek(f, 0, SEEK_END); int length = ftell(f); fprintf( stderr, "DEBUG: Длина файла: %d\n", length); if (length < HEADER_SIZE) { // Длина файла заведомо меньше размера header. Пишем новый. write_new_header(&header, f); } else { // Читаем read_header(&header, f); // Проверяем if (header.version != 1 || header.actual_words > header.total_words) { fprintf( stderr, "FATAL: База данных (%s), вероятно, испорчена. Возможно, стоит её удалить.\n", db_filename); WTF(); } } // Всё есть. Можно работать. printf("Введите help для справки, quit для выхода.\n"); int working = 1; while (working) { printf("> "); char str[6]; fgets(str, 6, stdin); remove_newline(str); if (strcmp(str, "help") == 0) { command_help(); } else if (strcmp(str, "quit") == 0 || strcmp(str, "exit") == 0 || strcmp(str, "bye") == 0) { save_database(f); exit( EXIT_SUCCESS); } else if (strcmp(str, "add") == 0) { command_add(f); } else if (strcmp(str, "find") == 0) { command_find(f); } else if (strcmp(str, "del") == 0 || strcmp(str, "rm") == 0) { command_remove(f); } else if (strcmp(str, "frag") == 0) { command_defragment(f); } else { fprintf( stderr, "ERROR: Неизвестная команда '%s'\n", str); } } /* Операции: 1. Добавить слово. Имя (128 байт), содержание (не ограничено) -> 2. Найти слово. Имя -> содержание 3. Удалить. Имя -> */ if (f != NULL) fclose(f); return EXIT_SUCCESS; }