void get_check_for_nan(CppAD::vector<Base>& vec, const std::string& file_name) { // size_t n = vec.size(); size_t char_size = sizeof(Base) * n; char* char_ptr = reinterpret_cast<char*>( vec.data() ); // std::fstream file_in(file_name.c_str(), std::ios::in|std::ios::binary ); file_in.read(char_ptr, char_size); // return; }
void KeyComputeShader::loadComputeShader() { std::stringstream compute_shader_buffer; // lines to be updated std::string define_tile_size_x = "#define TILE_SIZE_X "; std::string str_tile_size_x = std::to_string(tile_size.x); bool tile_size_x_updated = false; std::string define_tile_size_y = "#define TILE_SIZE_Y "; std::string str_tile_size_y = std::to_string(tile_size.y); bool tile_size_y_updated = false; // construct shader internally std::ifstream file_in(KEY_COMPUTE_SHADER_PATH, std::ifstream::in); for (std::string line; std::getline(file_in, line);) { if (!tile_size_x_updated && line.compare(0, define_tile_size_x.size(), define_tile_size_x) == 0) { compute_shader_buffer << define_tile_size_x << str_tile_size_x << std::endl; tile_size_x_updated = true; } else if (!tile_size_y_updated && line.compare(0, define_tile_size_y.size(), define_tile_size_y) == 0) { compute_shader_buffer << define_tile_size_y << str_tile_size_y << std::endl; tile_size_y_updated = true; } else { compute_shader_buffer << line << std::endl; } } this->key_compute_shader = createComputeProgram(compute_shader_buffer.str()); }
int main( int argc, char** argv ) { std::string codec_in("XML"), codec_out("Bach"); while (1) { int c = getopt(argc, argv, "fs:i:o:"); if (c == -1) { break; } else if (c == 'f') { option_format = 1; } else if (c == 's') { option_spacing = strtol(optarg, NULL, 0); } else if (c == 'i') { codec_in = optarg; } else if (c == 'o') { codec_out = optarg; } } if ((argc - optind) != 2) { usage(argv[0]); return 1; } std::string file_in(argv[argc - 2]); std::string file_out(argv[argc - 1]); std::cout << "Reading from " << file_in << " to " << file_out << std::endl << std::flush; // convert file return convert(file_in, codec_in, file_out, codec_out); }
void EditorWidget::setSmileList(QString filename, QString sep, QString path_smile) { QFile file_in( filename ); if (file_in.exists()) { if (file_in.open(QIODevice::ReadOnly) != 0) { QString line; QStringList list; QTextStream in(&file_in); in.setCodec("UTF-8"); list_smile->clear(); // editor_rich_text->document()->clear(); while ( !in.atEnd() ) { line = in.readLine(); if (!line.isEmpty()) { list = line.split( sep ); if (QFile::exists(path_smile + list.at(1))) { QListWidgetItem *item = new QListWidgetItem(list_smile); item->setData(Qt::UserRole, list.at(1)); item->setText( list.at(0) ); item->setIcon(QIcon(path_smile + list.at(1))); editor_rich_text->document()->addResource(QTextDocument::ImageResource, QUrl("smile_rs_"+ list.at(0) +"_"+ list.at(1)), QImage(path_smile + list.at(1))); } } } } } }
QVariant RequestManager::requestFileTransfer(QTcpSocket *& caller, QVariant params) { // VIDEO TRANSFER COMING SOON // get the video name QJsonObject jobject = params.toJsonObject(); QJsonValue file_name_value = jobject["FileName"]; QString file_name; if(file_name_value.isString()) file_name = file_name_value.toString(""); else { qDebug() << "VideoTransfer function passed invalid paramter VideoName: " << file_name_value; return QVariant(); } QFile file_in(file_name,this); qint64 file_size = file_in.size(); qDebug() << "Preparing to send file: " << file_name << " of size " << file_size; //get pointer to main ui object QWidget * mainwindow = qobject_cast<QWidget *>(parent()->parent()); // spwan off stream transfer video QAbstractSocket * caller_socket = qobject_cast< QAbstractSocket *>(caller); StreamTransferThread * file_transfer = new StreamTransferThread(qobject_cast<QObject *>(this),mainwindow, file_name,caller_socket,file_size); connect(file_transfer, &StreamTransferThread::finishedTransferingStream, this, &RequestManager::videoTransferThreadFinished); file_transfer->start(); return QVariant(); }
//Assumes larva_scores is already sorted void write_larva_scores(std::string name, int score) { bool is_it_too_big = false; //assume false if(larva_scores.size() != 0) { std::tuple<std::string, int> last_entry = larva_scores.at(larva_scores.size()-1); if((score < std::get<1>(last_entry)) && larva_scores.size() == 9) { is_it_too_big = false; larva_scores.pop_back(); } else if((score > std::get<1>(last_entry)) && larva_scores.size() == 9) { is_it_too_big = true; } //else { is_it_too_big = false; } } if(is_it_too_big == true) { std::cout << "Sorry " + name + " your score isn't good enough to make the high scores :(" << std::endl; } else { if(name.size() < 10) { int initial_size = name.size(); for(int i=initial_size; i<10; i++) { name += " "; //FORMATTING } } larva_scores.push_back(std::make_tuple(name, score)); //http://stackoverflow.com/questions/23030267/custom-sorting-a-vector-of-tuples std::sort(larva_scores.begin(), larva_scores.end(), [](std::tuple<std::string, int> const &t1, std::tuple<std::string, int> const &t2) { return std::get<1>(t1) < std::get<1>(t2); }); std::string file_lines[23]; std::string line; std::ifstream file_in (scores_file); if(file_in.is_open()) { int count = 0; while(std::getline(file_in, line)) { file_lines[count] = line; count++; } file_in.close(); } else { std::cout << "Unable to open file." << std::endl; } std::ofstream file_out (scores_file); if(file_out.is_open()) { for(int i=0; i<23; i++) { int bound = larva_scores.size(); if((i > 1 && i < 11) && ((i-2)<bound)) { std::tuple<std::string, int> temp = larva_scores.at(i-2); int place = i-1; file_out << place << ". " + std::get<0>(temp) + " " << std::get<1>(temp) << "\n"; } else { file_out << file_lines[i] + "\n"; } } file_out.close(); } else { std::cout << "Unable to open file." << std::endl; } } }
qint64 PrintTask::getFileRealSize(const QString &fileName) { QFile file_in(fileName); if (!file_in.open(QIODevice::ReadOnly) ){ return 0; } file_in.close(); return file_in.size(); }
static void DumpFileData(Transaction *query, Transaction *t, String *file, FileData &data) { TOperandBoolean *var_res = query->LookupBoolean(data.processed_var); if (var_res->IsTrue()) { // already handled this file somewhere else. return; } const char *file_name = file->Value(); // get the preprocessed file contents. TOperandString *preproc_arg = new TOperandString(t, data.contents->base, data.contents->pos - data.contents->base); // get the source file contents. TOperandString *source_arg = NULL; // don't look for the source for special compiler files. if (file_name[0] != '<') { // reconstruct the absolute filename from the normalized name. Buffer abs_name; if (file_name[0] != '/') { abs_name.Append(g_base_directory, strlen(g_base_directory)); abs_name.Append("/", 1); } abs_name.Append(file_name, strlen(file_name) + 1); const char *abs_str = (const char*) abs_name.base; // compress and store the source file contents. FileInStream file_in(abs_str); if (file_in.IsError()) { logout << "WARNING: Could not find source file: " << abs_str << endl; } else { Buffer *buf = new Buffer(); t->AddBuffer(buf); ReadInStream(file_in, buf); source_arg = new TOperandString(t, buf->base, buf->pos - buf->base); } } // if we didn't get the source file contents, use the preprocessed // contents instead. if (!source_arg) source_arg = preproc_arg; // write out the file contents. t->PushAction( Backend::BlockWriteFile(t, file_name, source_arg, preproc_arg)); }
void Sudoku::loadFromFile(std::string filename) { std::ifstream file_in(filename.c_str()); if(!file_in.is_open()) std::cout << "File not found" << std::endl; for(int i = 0; i < 9; ++i){ for(int j = 0; j < 9; ++j){ file_in >> grid[i][j]; } } }
int Pass1(queue<string> oFiles, map<string, string, string> symbolTable, valueTable values, queue<string> segments){ /* //open all of the object files for (int i = 0; i < oFiles.size(); i++){ string filename = "in_file"; filename += i; ifstream file_in(filename.c_str(), ifstream::in); } */ //not necessary at all? //get program name for first segment. put in valueTable->progName //read them all into the segments data structure for (unsigned int i = 0; i < oFiles.size(); i++){ string filename = "in_file"; filename += i; filename += ".o"; ifstream file_in(filename.c_str(), ifstream::in);//open the i-th oFile while (!file_in.eof()){ string line; getline(file_in, line); segments.push(line); } } //check that they are all relocatable for (unsigned int i = 0; i < oFiles.size(); i++){ // check that load address is 0; } //calculate program size int segSize = 0; for (unsigned int i = 0; i < oFiles.size(); i++){ // segSize = length in header record of segment////////////////// values.programSize += segSize; } //caluclate page string page = segments.front(); //get header record from first segment //do some manipulation to get page value out///////////////////////// values.page = to_int(page); /* detect page boundary errors; for (each segment){ calculate PLA; add ENT symbols to symbol table; warn id duplicates found; }*/ return 0; }
int main (const int argc, char* argv[]) { string usage = string(argv [0]) + " <k> <fasta_file>"; if (argc < 3) { cout << usage << endl; return 1; } cerr << vector <int>().max_size() << endl; struct rlimit stack_limit; getrlimit(RLIMIT_STACK, &stack_limit); stack_limit.rlim_cur = RLIM_INFINITY; if (setrlimit(RLIMIT_STACK, &stack_limit) != 0) { cerr << "Unlimiting stack size failed, might crash.\n"; } int k = atol(argv [1]); boost::filesystem::path orig_file = boost::filesystem::path(argv [2]); ifstream file_in(orig_file.string(), ifstream::in); string seq; file_in >> seq; file_in >> seq; file_in.close(); SR_index index(k, seq.size()); index.construct(orig_file.string()); index.print_superstring(); string query; file_in.open(orig_file.string(), ifstream::in); int counter = 0; while (file_in >> seq) { file_in >> seq; bool ok = false; string q = seq.substr(rand()%(seq.size() - k + 1), k); vector <int> results = index.find_reads(q, false); for (auto x : results) { if (x == counter) { ok = true; break; } } if (!ok) { cerr << "String not found where expected!\n"; cerr << q << ' ' << counter << endl; } counter++; } cerr << "finish" << endl; while (cin >> query) { for (auto x : index.find_reads(query, false)) { cout << x << ' '; } cout << endl; } }
RScope* InliningDatabase::lookup_and_remove(LookupKey* outer, LookupKey* inner) { if (table_no == 0) return NULL; // Skim the cream unsigned int index = index_for(outer, inner); if (!table[index].is_filled()) return NULL; while (!table[index].equal(outer, inner)) { index = next_index(index); if (table[index].is_empty()) return NULL; } table[index].set_deleted(); table_no--; return file_in(outer, inner); }
problem Flexible_vector::Read_file_without_index(std::string filename) { std::cout<<"IN Read_file_without_index"<<std::endl; std::ifstream file_in(filename.c_str()); std::string e,line; problem prob; int elements, max_index, inst_max_index; char *endptr; prob.l = 0; elements = 0; max_index = 0; while (std::getline(file_in, line)) { //std::cout<<std::endl; inst_max_index = 0; std::stringstream lineStream(line); std::getline(lineStream, e,','); //label if(e.empty()) //empty line exit_input_error(prob.l+1); prob.y.push_back(stringToNum<double>(e)); //std::cout<<prob.y[prob.y.size()-1]<<','; //prob.y.push_back(atof(e)); //if(endptr == e || *endptr != '\0') // exit_input_error(prob.l+1); prob.x_ptr.push_back(elements); //feature while(std::getline(lineStream, e,',')) { inst_max_index++; node x_tmp; x_tmp.index = inst_max_index; x_tmp.value = stringToNum<double>(e); //x_tmp.value = atof(e); prob.x.push_back(x_tmp); //std::cout<<prob.x[prob.x.size()-1].value<<','; elements++; } prob.x_interval.push_back(inst_max_index); if(inst_max_index > max_index) max_index = inst_max_index; prob.l++; } prob.max_feature = max_index; return prob; }
int _tmain(int argc, _TCHAR* argv[]) { ifstream file_in("in.txt"); //in.txt,链表数据输入文件 List<int> L; int EndTag; //链表数据输入的结束符 file_in >> EndTag; L.PreInput(EndTag, file_in); //前插法建立单链表 bool k1; //判断是顺序输出还是反序输出单链表 file_in >> k1; FactList_Output(L.getHead(), k1); bool k2; file_in >> k2; FactList_Output(L.getHead(), k2); return 0; }
RScope* InliningDatabase::select_and_remove(bool* end_of_table) { if (table_no == 0) return NULL; // Skim the cream for (unsigned int index = 0 ; index < table_size; index++) { if (table[index].is_filled() && table[index].is_outer()) { RScope* result = file_in(&table[index].outer); table[index].set_deleted(); table_no--; *end_of_table = false; return result; } } *end_of_table = true; return NULL; }
/** * @brief Restores the state of the last simulation or places the particles in *the shape of a cube if no state is found. * * @param[out] buffer Points to the particles buffer to be filled * @param[in] parameters Contains the simulation parameters * */ void sph_simulation::init_particles(particle* buffer, const simulation_parameters& parameters) { int particles_per_cube_side = ceil(cbrtf(parameters.particles_count)); float side_length = cbrtf(initial_volume); float spacing = side_length / (float)particles_per_cube_side; std::cout << "volume: " << initial_volume << " side_length: " << side_length << " spacing: " << spacing << std::endl; // Last simualtion serialized its last frame // Lets load that and pick up where it let off std::filebuf fb; if (fb.open("last_frame.bin", std::ios::in)) { std::istream file_in(&fb); cereal::BinaryInputArchive archive(file_in); archive.loadBinary(buffer, sizeof(particle) * parameters.particles_count); fb.close(); } // No serialized particle array was found // Initialize the particles in their default position else { for (unsigned int i = 0; i < parameters.particles_count; ++i) { // Arrange the particles in the form of a cube buffer[i].position.s[0] = (float)(i % particles_per_cube_side) * spacing - side_length / 2.f; buffer[i].position.s[1] = ((float)((i / particles_per_cube_side) % particles_per_cube_side) * spacing); buffer[i].position.s[2] = (float)(i / (particles_per_cube_side * particles_per_cube_side)) * spacing - side_length / 2.f; buffer[i].velocity.s[0] = 0.f; buffer[i].velocity.s[1] = 0.f; buffer[i].velocity.s[2] = 0.f; buffer[i].intermediate_velocity.s[0] = 0.f; buffer[i].intermediate_velocity.s[1] = 0.f; buffer[i].intermediate_velocity.s[2] = 0.f; buffer[i].density = 0.f; buffer[i].pressure = 0.f; } } }
qint32 PrintTask::getFileRealSize(const QString &fileName) { QVariant max_fsize(0); QFile file_in(fileName); if (!file_in.open(QIODevice::ReadOnly) ){ return 0; } file_in.close(); max_fsize = file_in.size(); bool ok; qint32 fsize = max_fsize.toInt(&ok); if (ok){ return fsize; } return 0; }
void LLSpellChecker::addToDictFile(const std::string& dict_path, const std::string& word) { std::vector<std::string> word_list; if (gDirUtilp->fileExists(dict_path)) { llifstream file_in(dict_path.c_str(), std::ios::in); if (file_in.is_open()) { std::string word; int line_num = 0; while (getline(file_in, word)) { // Skip over the first line since that's just a line count if (0 != line_num) { word_list.push_back(word); } line_num++; } } else { // TODO: show error message? return; } } word_list.push_back(word); llofstream file_out(dict_path.c_str(), std::ios::out | std::ios::trunc); if (file_out.is_open()) { file_out << word_list.size() << std::endl; for (std::vector<std::string>::const_iterator itWord = word_list.begin(); itWord != word_list.end(); ++itWord) { file_out << *itWord << std::endl; } file_out.close(); } }
bool BFile::copy ( const BAsciiString &filename, const BAsciiString &new_filename ) { if ( !exists ( filename ) || exists ( new_filename ) ) { return false; } BFile file_in ( filename ); if ( !file_in.open ( BIODevice::ReadOnly ) ) { return false; } BFile file_out ( new_filename ); if ( !file_out.open ( BIODevice::WriteOnly ) ) { return false; } file_out.write ( file_in.Buffer ); file_in.close(); file_out.close(); return true; }
int initialize(char *filename, fileptr *metadata) { DIR *dip; struct dirent *dit; int i = 0; char md5[32+1]; //anoigma katalogou if ((dip = opendir(filename)) == NULL) { perror("opendir"); return -1; } // struct dirent *readdir(DIR *dir); // Read in the files from argv[1] and print while ((dit = readdir(dip)) != NULL) { i++; if ( dit->d_type != DT_REG ) continue; if ( !strcmp(dit->d_name,".") || !strcmp(dit->d_name,"..") ) continue; if ( MD5Sum_File(dit->d_name,md5)<0 ) { fprintf(stderr,"MD5Sum_File error\n"); continue; } //upadate listas if ( !file_in(*metadata,dit->d_name, md5) ) add_file(metadata,dit->d_name, md5); } // int closedir(DIR *dir); if (closedir(dip) == -1) { perror("closedir"); return -1; } return 0; }
bool file_io::file_load() { const char * file_name = File_name; short line = 0; if (has_ran) { file_info.clear(); } std::string local_buffer; std::ifstream file_in(file_name, std::ios::in | std::ios::binary); if (file_in.is_open()) { while (getline(file_in, local_buffer)) { file_info.push_back(local_buffer); // std::cout << file_info.at(line) << std::endl; ++line; } has_ran = true; return true; } else { std::cerr << "file_io error, could not open" << std::endl; has_ran = true; return false; } }
int main(int argc, char *argv[]) { char infile_name[256],outfile_name[256]; if (argc > 1) strcpy(infile_name,argv[1]); else strcpy(infile_name,"course_inf.txt"); ifstream file_in(infile_name); // 声明与打开输入流 if (file_in == 0) { cout << "不能打开课程信息文件 " << infile_name << endl; exit (1); } if (argc > 2) strcpy(outfile_name,argv[2]); else strcpy(outfile_name,"curriculum_scedule.txt"); ofstream file_out(outfile_name); // 声明与打开输出流 if (file_out == 0) { cout << "不能打开课程请文件 " << outfile_name << endl; exit (1); } cout<<"课程信息文件为: "<<infile_name<<endl<<endl; cout<<"正在排课,请稍候..."<<endl<<endl; //Range_Course<8,1000>表示排8学期课(从第1学期到第8学期),最多能对1000门课进行排课 Range_Course<8,1000> rc(&file_in, &file_out); rc.read(); //输入课程信息 rc.topological_order(); //用拓扑排的思进行排课 rc.write(); //输出课表 cout<<"排课结束,课表文件为: "<<outfile_name<<endl; cout<<"按任意退出"<<endl; return 0; }
Bundle(const std::string filename, const char delimiter='\t', int ignoreRows=0) : _columns(0) { // Abre o arquivo para leitura std::ifstream file_in(filename); if (!file_in.good()) throw WUPException(cat("Could not open file: ", filename)); // Carrega linha a linha int rows = 0; std::string line; std::vector<std::string> cells; while(!file_in.eof()) { getline(file_in, line); ++rows; // Ignora cabecalhos e linhas em branco if (line.empty()) continue; if (rows <= ignoreRows) continue; // Quebra a linha em celulas split(cells, line, delimiter); // Guarda o numero de colunas if (_columns == 0) _columns = cells.size(); // Guarda os dados for (uint i=0;i<cells.size();++i) _data.push_back( parse_double(cells[i]) ); } file_in.close(); }
int main(int argc, char* argv[]) { if (argc < 4 || argc > 6) { std::cout << "Usage: embedfile [-wx] [-text] <inout> <output> <fieldname>" << std::endl; return error_invalidargs; } bool wxWidgets_image = false; bool text_content = false; int argc_offset = 1; if (casecmp(argv[argc_offset], "-wx")) { wxWidgets_image = true; argc_offset++; } if (casecmp(argv[argc_offset], "-text")) { text_content = true; argc_offset++; } std::string input_file(argv[argc_offset]); std::string output_basename(argv[argc_offset + 1]); std::string field_name(argv[argc_offset + 2]); std::ios::openmode mode = std::ios::in; if (!text_content) { mode |= std::ios::binary; } std::ifstream file_in(input_file.c_str(), mode); if (file_in.bad()) { std::cout << "ERROR: Error opening input file: " << input_file << std::endl; return error_cantopenfile; } // Get the size of the input stream size_t input_size; file_in.seekg(0, std::ios::end); if ((int) file_in.tellg() != -1) { input_size = (size_t) file_in.tellg(); } else { std::cout << "ERROR: Failed to get size of input file: " << input_file << std::endl; file_in.close(); return error_ioerror; } file_in.seekg(0, std::ios::beg); // Generates two files, one header and one source file std::string headerName = output_basename + ".h"; std::string sourceName = output_basename + ".cpp"; std::ofstream source_out(sourceName.c_str()); if (source_out.bad()) { std::cout << "ERROR: Error opening output file: " << sourceName << std::endl; return error_cantoutputfile; } std::ofstream header_out(headerName.c_str()); if (header_out.bad()) { std::cout << "ERROR: Error opening output file: " << headerName << std::endl; return error_cantoutputfile; } if (text_content) { do_text_content(file_in, source_out, field_name, input_size); } else { do_binary_content(file_in, source_out, field_name, input_size, wxWidgets_image); } write_header(header_out, field_name, text_content, wxWidgets_image); file_in.close(); source_out.close(); header_out.close(); return error_none; }
int main() { remove(sr_go_1); remove(sr_go_2); remove(kl_stop_1); remove(kl_stop_2); int ready1,ready2; //new_game new_game(); countpoints(); //in file file_in(); fkl1= fopen(kl_1,"w"); fclose(fkl1); fkl2= fopen(kl_2,"w"); fclose(fkl1); if((fstop1 = fopen(kl_stop_1,"w"))==0){ printf("\nstopfile(1) error"); Sleep(3000);exit(1);} else fclose(fstop1); if((fstop2 = fopen(kl_stop_2,"w"))==0){ printf("\nstopfile(2) error"); Sleep(3000);exit(1);} else fclose(fstop2); while(1) { printf("1"); remove(sr_go_1); remove(sr_go_2); while((fstop1 = fopen(kl_stop_1,"w"))==0) printf("\nTry open kl_stop_1"); while((fstop2 = fopen(kl_stop_2,"w"))== 0) printf("\nTry open kl_stop_2") ; fclose(fstop1); fclose(fstop2); ready1= 0; ready2= 0; while(ready1*ready2 == 0) { //printf("2"); Sleep(500); if(ready1 == 0) { srgo1 = fopen(sr_go_1,"r"); if(srgo1!= 0) { check_file(1); ready1 = 1; printf("\nready 1"); fclose(srgo1); if(remove(sr_go_1) !=0) printf("\ncant del sr_go_1"); } } if(ready2 == 0) { srgo2 = fopen(sr_go_2,"r"); if(srgo2!=0) { check_file(2); ready2 = 1; printf("\nready 2"); fclose(srgo2); if(remove(sr_go_2) !=0) printf("\ncant del sr_go_2"); } } } //countwar WarCount(); countmaps(); if(countpoints()== 1); // конец игры file_in(); } }
std::string DecodeText(std::string file_name) { ifstream file_in(file_name, std::ios::binary); if (!file_in.is_open()) return "NA"; map<string, string, StringComparer> codes_map; // read sequence length int sequence_length; file_in.read(reinterpret_cast<char*>(&sequence_length), sizeof(int)); // read max_code_length int max_code_length; file_in.read(reinterpret_cast<char*>(&max_code_length), sizeof(int)); // read codes num int num_codes; file_in.read((char*)&num_codes, sizeof(int)); // read codes one by one char* str = new char[sequence_length+1]; char* code = new char[max_code_length+1]; for (int i = 0; i < num_codes; ++i) { file_in.read(str, sizeof(char)*(sequence_length+1)); file_in.read(code, sizeof(char)*(max_code_length+1)); codes_map[string(code)] = string(str); } delete [] str; delete [] code; // read num bytes to read int num_data_bytes; file_in.read((char*)&num_data_bytes, sizeof(int)); // read data string* data = new string(); for (int i = 0; i < num_data_bytes; ++i) { char byte; file_in.read((char*)&byte, sizeof(char)); (*data) += ULongToBinaryString(byte); } // retrive decoded text string decoded_text = ""; int offset = 0; bool no_more = false; while (offset < data->size() && !no_more) { for (int i = 1; i <= max_code_length; ++i) { string probable_code = data->substr(offset, i); if (codes_map.find(probable_code) != codes_map.end()) { string s = codes_map[probable_code]; decoded_text += s; offset += i; break; } if (i == max_code_length) no_more = true; } } cout << "================ " << file_name << " ================"; cout << "\nCoded file size=" << file_in.tellg(); cout << "\n\tNum of codes=" << num_codes; cout << "\n\tMax. code length=" << max_code_length; cout << "\n\tCharacter sequence length=" << sequence_length << endl; file_in.close(); return decoded_text; }
void fileTransmitter::convertFileToMsg(const QString &unicFileId,const QString &fileName) { if ( unicFileId.isEmpty ()){ emit error(VPrn::InternalAppError, QObject::trUtf8("Отсутствует индетификатор файла.\n%1:%2") .arg( __FILE__ ) .arg( __LINE__ ) ); return; } if ( !QFile::exists(fileName) ){ return; } QFile file_in(fileName); if (!file_in.open(QIODevice::ReadOnly) ){ emit error(VPrn::FileIOError, QObject::trUtf8("Не могу открыть запрошенный файл: %1.\n%2:%3") .arg(fileName) .arg( __FILE__ ) .arg( __LINE__ ) ); return ; } qint64 fSize64 = file_in.size(); if (fSize64 > m_MaxInt32 - sizeof(qint32) ){ emit error(VPrn::FileIOError, QObject::trUtf8("Файл %1 имеет слишком большой размер:[%2 байт].\n%3:%4") .arg(fileName) .arg(fSize64,0,10) .arg( __FILE__ ) .arg( __LINE__ ) ); return ; } QByteArray data = qCompress( file_in.readAll() ); file_in.close(); if (data.isEmpty()){ emit error(VPrn::FileIOError, QObject::trUtf8("Файл %1 не содержит данных или ошибка чтения.\n%2:%3") .arg(fileName) .arg( __FILE__ ) .arg( __LINE__ ) ); return ; } QByteArray task_data; QDataStream out(&task_data, QIODevice::WriteOnly ); out.setVersion(QDataStream::Qt_3_0); out << unicFileId; // уникальный индетификатор отправляемого файла out << (qint32) fSize64; // Размер не сжатого файла out << data; // Файл для печати в формате QByteArray (сжатый) // Формируем сообщение Msg Message message; message.setType(VPrn::Que_ReciveFile); message.setMessageData (task_data); emit fileReadyToSend(message); }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); // Open the installer file QString name_in = "full_installer_script.nsi"; QString name_out = name_in + "temp"; QFile file_in(name_in); QFile file_out(name_out); file_in.open(QIODevice::ReadOnly | QIODevice::Text); file_out.open(QIODevice::WriteOnly | QIODevice::Truncate); QTextStream in_enc(&file_in); QTextStream out_enc(&file_out); out_enc.setCodec("UTF-8"); while(!in_enc.atEnd()) { QString line = in_enc.readLine(); // Update to current revision if(line.contains(" !define REVISION ")) { QStringList temp = line.split("\""); temp[1] = QString::number(getLocalVersion()); line = temp.join("\""); } // Update translations lines (including commented ones) QString langString = "LangString "; if(line.startsWith("; LangString")){ langString = "; LangString "; } if(line.startsWith(langString)){ QString backup = line; // Get language infos QStringList temp_lang = line.replace("{","|").replace("}","|").split("|"); QStringList temp_lang_name = temp_lang[1].split("_"); QString langName = temp_lang_name[1]; QString langCode = getLanguageCodeFromName(langName); // Get tag QStringList temp_tag = temp_lang[0].split(" "); QString tag = temp_tag[1]; if(backup.startsWith(";")) { // Pick the second char as the first is a comment tag = temp_tag[2]; } QString translation = getTranslation(langCode, tag); if (!translation.isEmpty()) { line = langString + tag + " ${LANG_" + langName + "} " + "\"" + translation + "\""; } else { line = backup; } } out_enc << line << "\n"; } file_in.close(); file_out.close(); QFile::remove(name_in); QFile::rename(name_out,name_in); return 0; }
void LLSpellChecker::initHunspell(const std::string& dict_name) { if (mHunspell) { delete mHunspell; mHunspell = NULL; mDictName.clear(); mDictFile.clear(); mIgnoreList.clear(); } const LLSD dict_entry = (!dict_name.empty()) ? getDictionaryData(dict_name) : LLSD(); if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) || (!dict_entry["is_primary"].asBoolean())) { sSettingsChangeSignal(); return; } const std::string app_path = getDictionaryAppPath(); const std::string user_path = getDictionaryUserPath(); if (dict_entry.has("name")) { const std::string filename_aff = dict_entry["name"].asString() + ".aff"; const std::string filename_dic = dict_entry["name"].asString() + ".dic"; if ( (gDirUtilp->fileExists(user_path + filename_aff)) && (gDirUtilp->fileExists(user_path + filename_dic)) ) mHunspell = new Hunspell((user_path + filename_aff).c_str(), (user_path + filename_dic).c_str()); else if ( (gDirUtilp->fileExists(app_path + filename_aff)) && (gDirUtilp->fileExists(app_path + filename_dic)) ) mHunspell = new Hunspell((app_path + filename_aff).c_str(), (app_path + filename_dic).c_str()); if (!mHunspell) return; mDictName = dict_name; mDictFile = dict_entry["name"].asString(); if (dict_entry["has_custom"].asBoolean()) { const std::string filename_dic = user_path + mDictFile + DICT_CUSTOM_SUFFIX + ".dic"; mHunspell->add_dic(filename_dic.c_str()); } if (dict_entry["has_ignore"].asBoolean()) { llifstream file_in(user_path + mDictFile + DICT_IGNORE_SUFFIX + ".dic", std::ios::in); if (file_in.is_open()) { std::string word; int idxLine = 0; while (getline(file_in, word)) { // Skip over the first line since that's just a line count if (0 != idxLine) { LLStringUtil::toLower(word); mIgnoreList.push_back(word); } idxLine++; } } } for (dict_list_t::const_iterator it = mDictSecondary.begin(); it != mDictSecondary.end(); ++it) { const LLSD dict_entry = getDictionaryData(*it); if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) continue; const std::string filename_dic = dict_entry["name"].asString() + ".dic"; if (gDirUtilp->fileExists(user_path + filename_dic)) mHunspell->add_dic((user_path + filename_dic).c_str()); else if (gDirUtilp->fileExists(app_path + filename_dic)) mHunspell->add_dic((app_path + filename_dic).c_str()); } } sSettingsChangeSignal(); }
eventor::eventor(std::vector<std::string> iinput_fname, int imin_per, FP_TYPE imin_len, FP_TYPE imin_dev, FP_TYPE isr, int ievent_t_steps, FP_TYPE ioverlap, std::vector<std::string> mslp_file_name, std::string mslp_field_name, std::vector<std::string> wind_file_name, std::string wind_field_name, std::string lsm_file_name, std::string mesh_file) : min_per(imin_per), min_len(imin_len), min_dev(imin_dev), sr(isr), event_t_steps(ievent_t_steps), min_overlap(ioverlap), lsm(NULL), mslp_footprint(NULL), wind_footprint(NULL) { // initialise here but should be command line argument hours_per_t_step = 6; // check that there are enough netCDF files to go with the extrema files if (iinput_fname.size() != mslp_file_name.size() || iinput_fname.size() != wind_file_name.size()) throw (std::string("Number of input netCDF files do not equal the number of extrema files")); // load the extrema for (unsigned int i=0; i<iinput_fname.size(); i++) { std::ifstream file_in(iinput_fname[i].c_str(), std::ios::in); std::cout << "# Reading data" << std::endl; if (!file_in.is_open()) throw (std::string("File " + iinput_fname[i] + " could not be opened.")); ex_list.load(iinput_fname[i], mv, i>0); file_in.close(); } // load the MSLP netCDF files for (unsigned int i=0; i<mslp_file_name.size(); i++) { mslp_field.push_back(new ncdata(mslp_file_name[i], mslp_field_name)); } // load the wind speed netCDF files for (unsigned int i=0; i<wind_file_name.size(); i++) { wind_speed_field.push_back(new ncdata(wind_file_name[i], wind_field_name)); } // load the time netCDF files for (unsigned int i=0; i<mslp_file_name.size(); i++) { NcFile* nc_file = new NcFile(mslp_file_name[i].c_str()); // get the time netCDF variable NcVar* nc_t_var = nc_file->get_var(mslp_field[0]->get_time_dim_name().c_str()); int t_len = nc_t_var->get_dim(0)->size(); FP_TYPE* time_data = new FP_TYPE[t_len]; nc_t_var->get(time_data, t_len); time_field.push_back(time_data); time_length.push_back(t_len); // if this is the first netCDF file then get the reference time if (i==0) mslp_field[0]->get_reference_time(ref_year, ref_month, ref_day, ref_day_sc, ref_ndays_py); } // create the wind and mslp footprints footprint_width = mslp_field[0]->get_lon_len(); footprint_height = mslp_field[0]->get_lat_len(); wind_footprint = new FP_TYPE[footprint_height*footprint_width]; mslp_footprint = new FP_TYPE[footprint_height*footprint_width]; if (lsm_file_name != "") lsm = new ncdata(lsm_file_name, "lsm"); // load the triangular mesh file tg.load(mesh_file); }