QString sumit(const QString& path, int num_bytes, const QString& temporary_path) { if (num_bytes != 0) { return compute_the_file_hash(path, num_bytes); } //the file id is a hashed function of device,inode,size, and modification time (in seconds) //note that it is not dependent on the file name struct stat SS; stat(path.toLatin1().data(), &SS); //didn't compile on mac so using the following which only depends on size and modification date QFileInfo info(path); QString id_string = QString("%1:%2:%3:%4").arg(path).arg(info.size()).arg(info.lastModified().toMSecsSinceEpoch()).arg(info.size()); //QString id_string = QString("%1:%2:%3:%4").arg(SS.st_dev).arg(SS.st_ino).arg(SS.st_size).arg(SS.st_mtim.tv_sec); QString file_id = compute_the_string_hash(id_string); QString dirname = QString(temporary_path + "/sumit/sha1/%1").arg(file_id.mid(0, 4)); create_directory_if_doesnt_exist(dirname); QString hash_path = QString("%1/%2").arg(dirname).arg(file_id); QString hash_sum = read_text_file(hash_path); if (hash_sum.isEmpty()) { create_hash_file(path, hash_path); hash_sum = read_text_file(hash_path); } if (hash_sum.count() != 40) { create_hash_file(path, hash_path); hash_sum = read_text_file(hash_path); } return hash_sum; }
Shader::Shader(const std::string &vertexPath, const std::string &fragmentPath) { GLuint vshader = compile_shader(GL_VERTEX_SHADER, read_text_file(vertexPath)); GLuint fshader = compile_shader(GL_FRAGMENT_SHADER, read_text_file(fragmentPath)); GLuint shader = link_shader(vshader, fshader); glDeleteShader(vshader); glDeleteShader(fshader); this->program = shader; }
/* * Read a section of a file, returning it as text * * No superuser check done here- instead privileges are handled by the * GRANT system. */ Datum pg_read_file_v2(PG_FUNCTION_ARGS) { text *filename_t = PG_GETARG_TEXT_PP(0); int64 seek_offset = 0; int64 bytes_to_read = -1; bool missing_ok = false; char *filename; text *result; /* handle optional arguments */ if (PG_NARGS() >= 3) { seek_offset = PG_GETARG_INT64(1); bytes_to_read = PG_GETARG_INT64(2); if (bytes_to_read < 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("requested length cannot be negative"))); } if (PG_NARGS() >= 4) missing_ok = PG_GETARG_BOOL(3); filename = convert_and_check_filename(filename_t); result = read_text_file(filename, seek_offset, bytes_to_read, missing_ok); if (result) PG_RETURN_TEXT_P(result); else PG_RETURN_NULL(); }
/* * Load cheats from text file. */ int load_cheats(const char *cheatfile, cheats_t *cheats) { char *buf = NULL; int ret; cheats_destroy(cheats); buf = read_text_file(cheatfile, 0); if (buf == NULL) { fprintf(stderr, "%s: could not read cheats file '%s'\n", __FUNCTION__, cheatfile); return -1; } cheats_init(cheats); ret = cheats_read_buf(cheats, buf); free(buf); if (ret != CHEATS_TRUE) { fprintf(stderr, "%s: line %i: %s\n", cheatfile, cheats->error_line, cheats->error_text); cheats_destroy(cheats); return -1; } return 0; }
void file_source_read_file(Value* file_source, Value* name, Value* contents) { if (file_source_is_map(file_source)) { Value* entry = hashtable_get(file_source, name); if (entry == NULL) set_null(contents); else copy(list_get(entry, 1), contents); return; } else if (file_source_is_filesystem_backed(file_source)) { Value fullPath; Value* rootDir = list_get(file_source, 1); copy(rootDir, &fullPath); join_path(&fullPath, name); read_text_file(as_cstring(&fullPath), contents); return; } else if (file_source_is_tarball_backed(file_source)) { Value* tarball = list_get(file_source, 1); tar_read_file(tarball, as_cstring(name), contents); return; } internal_error("file_source_read_file: file_source type not recognized"); }
void Sequence1::loadFromFile(const QString &fname) { d->m_commands.clear(); QMap<QString,QVariant> simblocks=parseJSON(read_text_file(fname)).toMap(); QList<QVariant> rf_waveforms=simblocks["rf_waveforms"].toList(); QList<QVariant> blocks=simblocks["blocks"].toList(); { SimCommand CC; CC.command="initialize"; d->m_commands << CC; } for (int i=0; i<rf_waveforms.count(); i++) { SimCommand CC; CC.command="add_RF_waveform"; CC.data=rf_waveforms[i].toMap(); d->m_commands << CC; } for (int i=0; i<blocks.count(); i++) { SimCommand CC; CC.command="run_block"; CC.data=blocks[i].toMap(); d->m_commands << CC; } { SimCommand CC; CC.command="finalize"; d->m_commands << CC; } }
// Read in the stats from one directory and add to the counters. void stats_read(const char *sfile, struct counters *counters) { char *data = read_text_file(sfile, 1024); if (data) { parse_stats(counters, data); } free(data); }
void STMainWindow::slot_new_sequence() { STSequenceView *SV=new STSequenceView; connect_sequence_view(SV); STMetaSequence *Seq=new STMetaSequence; STMetaClass *root_class=new STMetaClass; root_class->setClassName("STRoot"); root_class->setCode(read_text_file(ST_TEMPLATES_DIR+"/stroot.h"),read_text_file(ST_TEMPLATES_DIR+"/stroot.cpp")); Seq->addMetaClass(root_class); Seq->loadFoundationClasses(ST_FOUNDATION_DIR,false); Seq->loadFoundationClasses(ST_USER_DIR,true); SV->setSequence(Seq); ui.tabWidget->addTab(SV,"[untitled]"); ui.tabWidget->setCurrentWidget(SV); update_window_title(); qApp->processEvents(); SV->setPreferredSizes(); update_actions(); }
void IPC::open_udp_channel(const string recipient, const int port_num) { udp_map[recipient] = &(udp_pool[udp_pool_index]); ++udp_pool_index; UDP* udp_ptr = udp_map[recipient]; bool file_found = false; vector<string> file_name_vec = list_files_in_directory(ipc_path); for (string file_name_current : file_name_vec) if (file_name_current == "udp_port") file_found = true; if (!file_found) { if (port_num == -1) { int port_old = 0; int port_new = 0; int* port_new_ptr = &port_new; get_response(recipient, "open udp channel", "", [udp_ptr, port_new_ptr](const string message_body) { const int port = atoi(message_body.c_str()); udp_ptr->set_port(port); *port_new_ptr = port; COUT << "udp port is " << port << endl; }); while (port_old == port_new) { Sleep(20); update(); } } else { send_message(recipient, "open udp channel", to_string(port_num)); const int port = port_num; udp_ptr->set_port(port); COUT << "udp port is " << port << endl; } } else { int port = atoi(read_text_file(ipc_path + "\\udp_port")[0].c_str()); udp_ptr->set_port(port); COUT << "udp port is " << port << endl; } }
/* Read in the stats from one directory and add to the counters. */ void stats_read(const char *sfile, struct counters *counters) { char *data = read_text_file(sfile); if (data) { parse_stats(counters, data); } else { stats_default(counters); } free(data); }
static void run( Competitor& client ) { const std::string root = "./resources/"; const std::string problemClassFile = root + "classFolder.txt"; const std::vector< std::string > lines = read_text_file( problemClassFile ); if( lines.empty() ) throw std::runtime_error( "bad format for classFolder.txt" ); const std::string problemClassName = lines.front(); const std::string problemFolder( root + problemClassName ); ProblemClass problemClass( problemFolder, client.getTrainingCategory() ); long long actualTestingTime = -1, actualTrainingTime = -1; switch( client.getTrainingCategory() ) { case TrainingCategory::NONE : { actualTestingTime = testClient( client, problemClass.getTestingInstances() ); std::clog << "actualTestingTime:" << actualTestingTime << std::endl; } break; case TrainingCategory::SHORT : case TrainingCategory::LONG : { actualTrainingTime = trainClient( client, problemClass.getTrainingInstances() ); std::clog <<"actualTrainingTime:" << actualTrainingTime << std::endl; actualTestingTime = testClient( client, problemClass.getTestingInstances() ); std::clog <<"actualTestingTime:" << actualTestingTime << std::endl; } break; default : throw std::logic_error( "Bad training category in CBBOC2015.run()" ); } /////////////////////////// const std::time_t now = std::time(NULL); char buffer[ 1024 ]; std::strftime( buffer, sizeof(buffer), "%Y-%m-%d-%H-%M-%S", // "%T", std::localtime(&now)); const std::string timestamp( buffer ); const std::string className = classname( client ); OutputResults results( className, timestamp, problemClassName, problemClass, actualTrainingTime, actualTestingTime ); std::string outputPath = problemFolder + "/results/"; outputPath += "CBBOC2015results-" + className + "-" + problemClassName + "-" + timestamp + ".json"; std::ofstream out( outputPath ); out << results.toJSonString() << std::endl; /////////////////////////// std::cout << results.toJSonString() << std::endl; }
void MountainViewWidget::slot_statistics() { QList<SpikeStats> spike_stats; int num=d->m_times.totalSize(); for (int ii=0; ii<num; ii++) { //int t0=d->m_times.value1(ii); int label0=d->m_labels.value1(ii); while (label0>=spike_stats.count()) { SpikeStats X; X.count=0; spike_stats << X; } spike_stats[label0].count++; } QString statistics_css=read_text_file(":/statistics.css"); QString html; html+="<html>\n"; html+=QString("<head>\n"); html+=QString("<style>\n"); html+=QString("%1\n\n").arg(statistics_css); html+=QString("</style>\n"); html+=QString("</head>\n"); html+=QString("<table>\n"); html+=QString("<tr><th>Template</th><th>Primary Channel</th><th># Spikes</th><th>Spikes per minute</th></tr>"); for (int k=1; k<spike_stats.count(); k++) { SpikeStats X=spike_stats[k]; int primary_channel=(int)d->m_primary_channels.value1(k-1); if (X.count!=0) { float frequency=X.count*1.0/(d->m_raw->size(1)*1.0/30000/60); html+=QString("<tr><td>%1</td><td>%2</td><td>%3</td><td>%4</td></tr>\n") .arg(k) .arg(primary_channel) .arg(X.count) .arg(frequency,0,'f',1,' '); } } html+=QString("</table>\n"); html+="</html>\n"; { QTextBrowser *W=new QTextBrowser; W->setAttribute(Qt::WA_DeleteOnClose); W->setHtml(html); W->show(); W->resize(600,800); W->move(this->geometry().topRight()+QPoint(100,50)); } }
/* * Read the whole of a file, returning it as text */ Datum pg_read_file_all(PG_FUNCTION_ARGS) { text *filename_t = PG_GETARG_TEXT_P(0); char *filename; if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), (errmsg("must be superuser to read files")))); filename = convert_and_check_filename(filename_t); PG_RETURN_TEXT_P(read_text_file(filename, 0, -1)); }
void DirectoryTree::import_from_files() { QModelIndexList ids = selectionModel()->selectedIndexes(); if (ids.size() == 0) return; QModelIndex index = ids.at(0); if (!index.isValid()) return; // 弹出对话框 QStringList files = QFileDialog::getOpenFileNames(this, tr("打开文件"), QString::fromLocal8Bit(_last_visited_dir.data(), _last_visited_dir.length()), "Text file (*.txt)"); const size_t size = files.size(); if (size == 0) return; DirectoryTreeModel *m = dynamic_cast<DirectoryTreeModel*>(model()); assert(NULL != m); for (size_t i = 0; i < size; ++i) { const QString& file = files.at(i); // get title string dir, name; Path::split(file.toLocal8Bit(), &dir, &name); if (!ends_with(name.c_str(), ".txt") && !ends_with(name.c_str(), ".TXT")) continue; string title; Path::split_ext(name.c_str(), &title, NULL); _last_visited_dir = dir; // get content QString all = read_text_file(file); all = convert_txt_to_html(all); // insert to db m->insert_article(index, QString::fromLocal8Bit(title.data(), title.length()), MIME_PKM_RICHTEXT, all); } // 发送通知 DirectoryItem *p = static_cast<DirectoryItem*>(index.internalPointer()); assert(NULL != p); PkmPlugin *plugin = dynamic_cast<PkmPlugin*>(get_plugin().pointer()); plugin->directory_activated(p->get_id(), p->get_name()); }
int init_scan_info_by_file(const char *file_name,scan_info *info) { int err = SHE_NO_ERROR; err = read_text_file(file_name,&(info->data)); if(err != SHE_NO_ERROR) return err; info->scanner = NULL; info->scan_error = SHE_NO_ERROR; if(scan_info_home(info)) err = SHE_SCAN_ERROR; return err; }
// Designed to import from TexturePacker, because that's a good a standard as any void texture_atlas_t::import_from_json(std::string const& filepath) { string json_str = read_text_file(filepath); cJSON* root = cJSON_Parse(json_str.c_str()); ASSERT(root, "Error loading imported textures json file"); auto meta_json = cJSON_GetObjectItem(root, "meta"); auto atlas_texture_filename = cJSON_GetObjectItem(meta_json, "image")->valuestring; //atlas texture is in the same folder, so just chop off the data filename from its path and append the texture filename std::string atlas_texture_filepath; auto last_slash_index = filepath.find_last_of("/\\"); if(last_slash_index == std::string::npos) { atlas_texture_filepath = atlas_texture_filename ; } else { atlas_texture_filepath = filepath.substr(0, last_slash_index) + "/" + atlas_texture_filename; } atlas_texture = make_shared<texture_t>(atlas_texture_filepath); auto frames_json = cJSON_GetObjectItem(root, "frames"); //array of entries ('frames') size_t len = cJSON_GetArraySize(frames_json); for(size_t i = 0; i < len; ++i) { auto entry_json = cJSON_GetArrayItem(frames_json, i); auto frame_json = cJSON_GetObjectItem(entry_json, "frame"); entry_t entry{string(cJSON_GetObjectItem(entry_json, "filename")->valuestring) , uvec2(cJSON_GetObjectItem(frame_json, "x")->valueint, cJSON_GetObjectItem(frame_json, "y")->valueint) , uvec2(cJSON_GetObjectItem(frame_json, "w")->valueint, cJSON_GetObjectItem(frame_json, "h")->valueint) }; atlas_entries.push_back(std::move(entry)); } cJSON_Delete(root); }
/* * Read a section of a file, returning it as text */ Datum pg_read_file(PG_FUNCTION_ARGS) { text *filename_t = PG_GETARG_TEXT_P(0); int64 seek_offset = PG_GETARG_INT64(1); int64 bytes_to_read = PG_GETARG_INT64(2); char *filename; if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), (errmsg("must be superuser to read files")))); filename = convert_and_check_filename(filename_t); if (bytes_to_read < 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("requested length cannot be negative"))); PG_RETURN_TEXT_P(read_text_file(filename, seek_offset, bytes_to_read)); }
/* * Read a section of a file, returning it as text * * This function is kept to support adminpack 1.0. */ Datum pg_read_file(PG_FUNCTION_ARGS) { text *filename_t = PG_GETARG_TEXT_PP(0); int64 seek_offset = 0; int64 bytes_to_read = -1; bool missing_ok = false; char *filename; text *result; if (!superuser()) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), (errmsg("must be superuser to read files with adminpack 1.0"), errhint("Consider using pg_file_read(), which is part of core, instead.")))); /* handle optional arguments */ if (PG_NARGS() >= 3) { seek_offset = PG_GETARG_INT64(1); bytes_to_read = PG_GETARG_INT64(2); if (bytes_to_read < 0) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("requested length cannot be negative"))); } if (PG_NARGS() >= 4) missing_ok = PG_GETARG_BOOL(3); filename = convert_and_check_filename(filename_t); result = read_text_file(filename, seek_offset, bytes_to_read, missing_ok); if (result) PG_RETURN_TEXT_P(result); else PG_RETURN_NULL(); }
/** * Opens the file given by the filepath in lpszXML and returns the main node. * (Includes error handling) * @param filename Filepath to the XML file to parse * @param tag (?) * @param pResults Pointer to the XMLResults object to fill on error or success * @return The main XMLNode or an empty node on error */ XMLNode * XMLNode::parseFile(const char *filename, XMLResults *pResults) { // Open the file for reading tstring buffer; // If file can't be read if (!read_text_file(filename, buffer)) { // If XMLResults object exists if (pResults) { // -> Save the error type into it pResults->error = eXMLErrorFileNotFound; pResults->nLine = 0; pResults->nColumn = 0; } // -> Return empty XMLNode return NULL; } // Parse the string and get the main XMLNode return parseString(buffer.c_str(), pResults); }
int main(int argc, char *argv[]) { GtkWidget *win, *sci; GtkBuilder *builder; GError *error = NULL; gchar *sample_text; gtk_init(&argc, &argv); builder = gtk_builder_new(); if (!gtk_builder_add_from_file(builder, DEMO_UI_FILE, &error)) { g_printerr("Error: %s\n", error->message); g_error_free(error); return 1; } win = GTK_WIDGET(gtk_builder_get_object(builder, "window1")); gtk_window_set_default_size(GTK_WINDOW(win), 640, 480); g_signal_connect(win, "destroy", gtk_main_quit, NULL); sci = GTK_WIDGET(gtk_builder_get_object(builder, "scintilla1")); sample_text = read_text_file(DEMO_SAMPLE_FILE); if (sample_text != NULL) { gtk_scintilla_set_text(GTK_SCINTILLA(sci), sample_text); g_free(sample_text); } gtk_scintilla_set_keywords(GTK_SCINTILLA(sci), 0, "int char return"); gtk_widget_show_all(win); gtk_main(); return 0; }
int * search_of_the_same_elem(char*file_name ,int number_of_elements_text_file,char* binary_file_name,int number_of_elements_binary_file) { FILE *f,*fb; int i_txt; int *txt; int *binary; txt = (int *) calloc(number_of_elements_text_file, sizeof(int)); binary = (int *) calloc(number_of_elements_binary_file, sizeof(int)); fb = open_file(spis_1,"rb"); f = open_file(spis_2,"r"); read_text_file(file_name ,number_of_elements_text_file,txt); read_bin_f(binary_file_name , number_of_elements_binary_file, binary); rewind(f); rewind(fb); txt= delete_the_item (binary,txt, &number_of_elements_text_file, number_of_elements_binary_file); f = open_file(spis_2,"r"); for(i_txt = 0; i_txt < number_of_elements_text_file; i_txt++) { fprintf(f,"%2d",&txt[i_txt]); } printf_txt_file(file_name , number_of_elements_text_file); fclose(f); fclose(fb); return 0; }
int main(int argc, char *argv[]) { QApplication a(argc, argv); //MainWindow w; //w.show(); QStringList args; for (int i=1; i<argc; i++) { args << QString(argv[i]); } qsrand(QDateTime::currentDateTime().toMSecsSinceEpoch()); //args << "/tmp/tp903426a1_f13b_43a2_a1b8_5ff229f26018_run_java_script.js"; // FTElectrodeArrayView *V=new FTElectrodeArrayView; // int M=100,T=30; // Mda L; L.allocate(M,2); // Mda W; W.allocate(M,T); // for (int i=0; i<M; i++) { // L.setValue(i/6 + ((i%6)%2)*0.5,i,0); // L.setValue(i%6,i,1); // for (int t=0; t<T; t++) { // W.setValue(i+t,i,t); // } // } // V->setElectrodeLocations(L); // V->setWaveform(W); // V->show(); // return a.exec(); QString script_path; QString waveforms_path; QString locations_path; for (int i=0; i<args.count(); i++) { QString str=args[i]; if (str=="--waveforms") { waveforms_path=args.value(i+1); } if (str=="--locations") { locations_path=args.value(i+1); } } QScriptEngine *engine=new QScriptEngine; //qScriptRegisterMetaType(engine, myObjectToScriptValue, myObjectFromScriptValue); FTController FIRETRACK; QScriptValue FIRETRACK_value = engine->newQObject(&FIRETRACK); //QScriptValue FIRETRACK_value = engine->newQObject(new QObject()); engine->globalObject().setProperty("FIRETRACK", FIRETRACK_value); QString script; if (!script_path.isEmpty()) { script=read_text_file(script_path); } else { if (waveforms_path.isEmpty()) { waveforms_path=a.applicationDirPath()+"/../testdata/waveforms_first_5e5_points.mda"; if ((!QFile::exists(waveforms_path))||(QFileInfo(waveforms_path).size()<1e6)) { QMessageBox::StandardButton reply= QMessageBox::question(0,"Start download?","Test data must be downloaded. Start download?",QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes); if (reply==QMessageBox::No) exit(0); QMessageBox::information(0,"Downloading","Please wait while file is downloaded. Click OK to start download."); QString url="http://97.107.129.125/waveforms_first_5e5_points.mda"; if (!download_file(url,waveforms_path)) { QMessageBox::information(0,"Error Downloading","There was a problem downloading the file "+url+". Is curl installed? Exiting."); exit(0); } QMessageBox::information(0,"File downloaded","It appears that the file was downloaded properly. Press OK to continue."); } //waveforms_path="/home/magland/gazelle_backup/current/matlab/scda_ss/jfm/core/scratch/test_all_channels/first_1e3_points_filtered.mda"; } if (locations_path.isEmpty()) { locations_path=a.applicationDirPath()+"/../testdata/locations.mda"; } script=""; script+=QString("var V%1=FIRETRACK.createFireTrackWidget();\n").arg(0); script+=QString("var X%1=FIRETRACK.readArray('%2');\n").arg(0).arg(waveforms_path); script+=QString("var L%1=FIRETRACK.readArray('%2');\n").arg(0).arg(locations_path); script+=QString("V%1.setWaveforms(X%1);\n").arg(0); script+=QString("V%1.setElectrodeLocations(L%1);\n").arg(0); //script+=QString("V%1.setTitle(\"This is a test %1.\");\n").arg(0); script+=QString("V%1.show();\n").arg(0); script+=QString("V%1.animate();\n").arg(0); script+="\n"; } QScriptValue result = engine->evaluate(script); if (result.isError()) { qWarning() << "Error running script: "+result.toString(); } CleanupObject cleanup_object; QObject::connect(&a, SIGNAL(aboutToQuit()), &cleanup_object, SLOT(closing())); int ret=a.exec(); engine->collectGarbage(); delete engine; printf("Number of files open: %d, number of unfreed mallocs: %d, number of unfreed megabytes: %g\n",jnumfilesopen(),jmalloccount(),(int)jbytesallocated()*1.0/1000000); return ret; }
static int encode_and_post(newspost_data *data, SList *file_list, SList *parfiles) { int number_of_parts; int number_of_files; int i; file_entry *file_data = NULL; int retval = NORMAL; char *data_buffer = (char *) malloc(get_buffer_size_per_encoded_part(data)); Buff *subject = NULL; Buff *text_buffer = NULL; /* create the socket */ ui_socket_connect_start(data->address->data); retval = socket_create(data->address->data, data->port); if (retval < 0) return retval; ui_socket_connect_done(); /* log on to the server */ ui_nntp_logon_start(data->address->data); if (nntp_logon(data) == FALSE) { socket_close(); return LOGON_FAILED; } ui_nntp_logon_done(); if (data->text == TRUE) { file_data = file_list->data; /* post */ text_buffer = read_text_file(text_buffer, file_data->filename->data); if(text_buffer != NULL) retval = nntp_post(data->subject->data, data, text_buffer->data, text_buffer->length, TRUE); } else { /* post any sfv files... */ if (data->sfv != NULL) { file_data = file_entry_alloc(file_data); file_data->filename = buff_create(file_data->filename, "%s", data->sfv->data); if (stat(data->sfv->data, &file_data->fileinfo) == -1) ui_sfv_gen_error(data->sfv->data, errno); else { retval = post_file(data, file_data, 1, 1, "SFV File", data_buffer); if (retval < 0) return retval; unlink(data->sfv->data); } free(file_data); } number_of_files = slist_length(file_list); /* if there's a prefix, post that */ if (data->prefix != NULL) { ui_posting_prefix_start(data->prefix->data); file_data = (file_entry *) file_list->data; number_of_parts = get_number_of_encoded_parts(data, file_data); subject = make_subject(subject, data, 1 , number_of_files, file_data->filename->data, 0 , number_of_parts, "File"); text_buffer = read_text_file(text_buffer, data->prefix->data); if (text_buffer != NULL) { retval = nntp_post(subject->data, data, text_buffer->data, text_buffer->length, TRUE); if (retval == POSTING_NOT_ALLOWED) return retval; else if (retval == POSTING_FAILED) { /* dont bother retrying... who knows what's in that file */ ui_posting_prefix_failed(); retval = NORMAL; } else if (retval == NORMAL) ui_posting_prefix_done(); } else ui_posting_prefix_failed(); buff_free(subject); } /* post the files */ i = 1; while (file_list != NULL) { file_data = (file_entry *) file_list->data; retval = post_file(data, file_data, i, number_of_files, "File", data_buffer); if (retval < 0) return retval; i++; file_list = slist_next(file_list); } /* post any par files */ i = 1; file_list = parfiles; number_of_files = slist_length(parfiles); while (file_list != NULL) { file_data = (file_entry *) file_list->data; retval = post_file(data, file_data, i, number_of_files, "PAR File", data_buffer); if (retval < 0) return retval; unlink(file_data->filename->data); buff_free(file_data->filename); free(file_data); i++; file_list = slist_next(file_list); } slist_free(parfiles); } nntp_logoff(); socket_close(); free(data_buffer); buff_free(text_buffer); return retval; }
void IPC::update() { static bool updated = true; if (!updated) return; updated = false; static unordered_map<string, bool> file_name_processed_map; vector<string> file_name_vec = list_files_in_directory(ipc_path); for (string file_name_current : file_name_vec) { string file_name_lock = ""; if (file_name_current.size() >= 4) file_name_lock = file_name_current.substr(0, 4); if (file_name_lock == "lock") { updated = true; return; } } for (string file_name_current : file_name_vec) { string file_name_everyone = ""; if (file_name_current.size() >= 8) file_name_everyone = file_name_current.substr(0, 8); if (file_name_current.size() > self_name.size() || file_name_everyone == "everyone") { if (file_name_processed_map[file_name_current] == true) continue; else file_name_processed_map[file_name_current] = true; string file_name = ""; string file_name_id_str = ""; if (file_name_everyone != "everyone") { file_name = file_name_current.substr(0, self_name.size()); file_name_id_str = file_name_current.substr(self_name.size(), file_name_current.size()); } if (file_name == self_name || file_name_everyone == "everyone") { Sleep(20); vector<string> lines = read_text_file(ipc_path + slash + file_name_current); // delete_file(ipc_path + slash + file_name_current); vector<string> message_vec = split_string(lines[0], "!"); string message_head = message_vec[0]; string message_body = message_vec[1]; // console_log("message_received " + message_head + " " + message_body + " " + file_name_current, false); if (response_map.count(message_head) == 0) { if (command_map.count(message_head)) command_map[message_head](message_body); } else { function<void (string)> func = response_map[message_head]; response_map.erase(message_head); func(message_body); } } } } updated = true; }
GLuint shaderSetup( const char *vert, const char *frag ) { GLchar *vsrc = NULL, *fsrc = NULL; GLuint vs, fs, prog; GLint flag; // Assume that everything will work shaderErrorCode = E_NO_ERROR; // Create the shader handles vs = glCreateShader( GL_VERTEX_SHADER ); fs = glCreateShader( GL_FRAGMENT_SHADER ); // Read in shader source vsrc = read_text_file( vert ); if( vsrc == NULL ) { fprintf( stderr, "Error reading vertex shader file %s\n", vert); shaderErrorCode = E_VS_LOAD; return( 0 ); } fsrc = read_text_file( frag ); if( fsrc == NULL ) { fprintf( stderr, "Error reading fragment shader file %s\n", frag); shaderErrorCode = E_FS_LOAD; #ifdef __cplusplus delete [] vsrc; #else free( vsrc ); #endif return( 0 ); } // Attach the source to the shaders glShaderSource( vs, 1, (const GLchar **) &vsrc, NULL ); glShaderSource( fs, 1, (const GLchar **) &fsrc, NULL ); // We're done with the source code now #ifdef __cplusplus delete [] vsrc; delete [] fsrc; #else free(vsrc); free(fsrc); #endif // Compile the shaders, and print any relevant message logs glCompileShader( vs ); glGetShaderiv( vs, GL_COMPILE_STATUS, &flag ); print_shader_info_log( vs ); if( flag == GL_FALSE ) { shaderErrorCode = E_VS_COMPILE; return( 0 ); } glCompileShader( fs ); glGetShaderiv( fs, GL_COMPILE_STATUS, &flag ); print_shader_info_log( fs ); if( flag == GL_FALSE ) { shaderErrorCode = E_FS_COMPILE; return( 0 ); } // Create the program and attach the shaders prog = glCreateProgram(); glAttachShader( prog, vs ); glAttachShader( prog, fs ); // Report any message log information print_program_info_log( prog ); // Link the program, and print any message log information glLinkProgram( prog ); glGetProgramiv( prog, GL_LINK_STATUS, &flag ); print_program_info_log( prog ); if( flag == GL_FALSE ) { shaderErrorCode = E_SHADER_LINK; return( 0 ); } return( prog ); }
bool WIPShader::load( const char* vs,const char* fs ,const char* gs) { std::string fss; if (!read_text_file(fs,fss)) { printf("fs read failed!"); return false; } std::string vss; if (!read_text_file(vs,vss)) { printf("vs read failed!"); return false; } const char* fssc = fss.data(); const char* vssc = vss.data(); GLint compiled; GLint linked; _program = glCreateProgram(); GLuint fsc = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fsc,1,&fssc,NULL); glCompileShader(fsc); glGetShaderiv ( fsc, GL_COMPILE_STATUS, &compiled ); if (!compiled) { GLint infoLen = 0; glGetShaderiv ( fsc, GL_INFO_LOG_LENGTH, &infoLen ); if ( infoLen > 1 ) { char *infoLog = (char*)malloc ( sizeof ( char ) * infoLen ); glGetShaderInfoLog ( fsc, infoLen, NULL, infoLog ); printf( "Error compiling shader:\n%s\n", infoLog ); free ( infoLog ); } glDeleteShader ( fsc ); printf("fs_source failed!\n"); return false; } GLuint vsc = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vsc,1,&vssc,NULL); glCompileShader(vsc); glGetShaderiv ( vsc, GL_COMPILE_STATUS, &compiled ); if (!compiled) { GLint infoLen = 0; glGetShaderiv ( vsc, GL_INFO_LOG_LENGTH, &infoLen ); if ( infoLen > 1 ) { char *infoLog = (char*)malloc ( sizeof ( char ) * infoLen ); glGetShaderInfoLog ( vsc, infoLen, NULL, infoLog ); printf( "Error compiling shader:\n%s\n", infoLog ); free ( infoLog ); } glDeleteShader ( vsc ); printf("vs_source failed!\n"); return false; } glAttachShader(_program,vsc); glAttachShader(_program,fsc); GLuint gsc = 0; if (gs) { std::string gss; if (!read_text_file(gs,gss)) { printf("gs read failed!"); return false; } const char* gssc = gss.data(); gsc = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(gsc,1,&gssc,NULL); glCompileShader(gsc); glGetShaderiv ( gsc, GL_COMPILE_STATUS, &compiled ); if (!compiled) { GLint infoLen = 0; glGetShaderiv ( gsc, GL_INFO_LOG_LENGTH, &infoLen ); if ( infoLen > 1 ) { char *infoLog = (char*)malloc ( sizeof ( char ) * infoLen ); glGetShaderInfoLog ( gsc, infoLen, NULL, infoLog ); printf( "Error compiling shader:\n%s\n", infoLog ); free ( infoLog ); } glDeleteShader ( gsc ); printf("fs_source failed!\n"); return false; } glAttachShader(_program,gsc); } glLinkProgram(_program); glGetProgramiv ( _program, GL_LINK_STATUS, &linked ); if ( !linked ) { GLint infoLen = 0; glGetProgramiv ( _program, GL_INFO_LOG_LENGTH, &infoLen ); if ( infoLen > 1 ) { char *infoLog = (char*)malloc ( sizeof ( char ) * infoLen ); glGetProgramInfoLog ( _program, infoLen, NULL, infoLog ); printf( "Error linking program:\n%s\n", infoLog ); free ( infoLog ); } glDeleteProgram ( _program ); return 0; } glDeleteShader ( vsc ); glDeleteShader ( fsc ); if(gsc) { glDeleteShader(gsc); } return true; }
int main(int argc,char **argv) { QMap<QString,QString> parameters; for (int i=1; i<argc; i++) { QString str=argv[i]; QStringList vals=str.split("="); if (vals.count()==2) { if (vals[0].mid(0,2)=="--") { parameters[vals[0].mid(2)]=vals[1]; } } } QString phantom_name=parameters["phantom"]; QString simblocks_file=parameters["simblocks"]; QString output_file=parameters["output"]; int num_isochromats=parameters.value("num_iso","10000").toInt(); if ((phantom_name.isEmpty())||(simblocks_file.isEmpty())||(output_file.isEmpty())) { usage(); return 1; } if (phantom_name!="phantom1") { qWarning() << "Unrecognized phantom: "+phantom_name; usage(); return 1; } Phantom1 PP; QList<double> x,y,z,f,d; PP.generateRandomLocations(x,y,z,num_isochromats); for (int i=0; i<num_isochromats; i++) { SpinProperties SP=PP.spinPropertiesAt(x[i],y[i],z[i]); f << SP.chemical_shift*42.57*1.5; d << SP.density; } QMap<QString,QVariant> simblocks0=parseJSON(read_text_file(simblocks_file)).toMap(); VmriSimulator VS; VS.setT1(PP.T1()); VS.setT2(PP.T2()); VS.setIsochromats(x,y,z,f,d); VS.setSimBlocks(simblocks0); VS.simulate(); QList<VmriReadout> readouts=VS.getReadouts(); FILE *outf=fopen(output_file.toAscii().data(),"wb"); for (int i=0; i<readouts.count(); i++) { VmriReadout RO=readouts[i]; quint32 N0=RO.real.count(); quint32 readout_index0=RO.readout_index; float dwell_time0=RO.dwell_time; fwrite(&N0,sizeof(quint32),1,outf); fwrite(&readout_index0,sizeof(quint32),1,outf); fwrite(&dwell_time0,sizeof(float),1,outf); for (int i=0; i<29; i++) { quint32 tmp=0; fwrite(&tmp,sizeof(quint32),1,outf); } for (int i=0; i<N0; i++) { float tmp_real=RO.real.value(i); float tmp_imag=RO.imag.value(i); fwrite(&tmp_real,sizeof(float),1,outf); fwrite(&tmp_imag,sizeof(float),1,outf); } } fclose(outf); printf("\n"); return 0; }
int check_process_running(string name, bool partial) { #ifdef _WIN32 int process_count = 0; HANDLE SnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if(SnapShot == INVALID_HANDLE_VALUE) return false; PROCESSENTRY32 procEntry; procEntry.dwSize = sizeof(PROCESSENTRY32); if(!Process32First(SnapShot, &procEntry)) return false; do { if(strcmp(procEntry.szExeFile, name.c_str()) == 0) ++process_count; } while (Process32Next(SnapShot, &procEntry)); return process_count; #elif __APPLE__ vector<string> file_name_vec = list_files_in_directory(executable_path); for (string file_name_current : file_name_vec) if (file_name_current == "lock") return true; write_string_to_file(executable_path + "/lock", ""); string command = "ps -e > " + executable_path + "/processes.txt"; system(command.c_str()); vector<string> lines = read_text_file(executable_path + "/processes.txt"); delete_file(executable_path + "/processes.txt"); for (string& str : lines) if (partial) { if (str.find(name) != std::string::npos) { delete_file(executable_path + "/lock"); return true; } } else { vector<string> str_parts = split_string(str, "/"); if (str_parts.size() > 1) { string process_name = str_parts[str_parts.size() - 1]; if (process_name == name) { delete_file(executable_path + "/lock"); return true; } } } delete_file(executable_path + "/lock"); return false; #endif }
static int execute_cert_test(CT_TEST_FIXTURE fixture) { int test_failed = 0; X509 *cert = NULL, *issuer = NULL; STACK_OF(SCT) *scts = NULL; SCT *sct = NULL; char expected_sct_text[CT_TEST_MAX_FILE_SIZE]; int sct_text_len = 0; unsigned char *tls_sct = NULL; size_t tls_sct_len = 0; CT_POLICY_EVAL_CTX *ct_policy_ctx = CT_POLICY_EVAL_CTX_new(); if (fixture.sct_text_file_path != NULL) { sct_text_len = read_text_file( fixture.sct_text_file_path, expected_sct_text, CT_TEST_MAX_FILE_SIZE - 1); if (sct_text_len < 0) { test_failed = 1; fprintf(stderr, "Test data file not found: %s\n", fixture.sct_text_file_path); goto end; } expected_sct_text[sct_text_len] = '\0'; } CT_POLICY_EVAL_CTX_set0_log_store(ct_policy_ctx, fixture.ctlog_store); if (fixture.certificate_file_path != NULL) { int sct_extension_index; X509_EXTENSION *sct_extension = NULL; cert = load_pem_cert(fixture.certificate_file_path); if (cert == NULL) { test_failed = 1; fprintf(stderr, "Unable to load certificate: %s\n", fixture.certificate_file_path); goto end; } CT_POLICY_EVAL_CTX_set0_cert(ct_policy_ctx, cert); if (fixture.issuer_file_path != NULL) { issuer = load_pem_cert(fixture.issuer_file_path); if (issuer == NULL) { test_failed = 1; fprintf(stderr, "Unable to load issuer certificate: %s\n", fixture.issuer_file_path); goto end; } CT_POLICY_EVAL_CTX_set0_issuer(ct_policy_ctx, issuer); } sct_extension_index = X509_get_ext_by_NID(cert, NID_ct_precert_scts, -1); sct_extension = X509_get_ext(cert, sct_extension_index); if (fixture.expected_sct_count > 0) { if (sct_extension == NULL) { test_failed = 1; fprintf(stderr, "SCT extension not found in: %s\n", fixture.certificate_file_path); goto end; } if (fixture.sct_text_file_path) { test_failed = compare_extension_printout(sct_extension, expected_sct_text); if (test_failed != 0) goto end; } if (fixture.test_validity) { int are_scts_validated = 0; scts = X509V3_EXT_d2i(sct_extension); SCT_LIST_set_source(scts, SCT_SOURCE_X509V3_EXTENSION); are_scts_validated = SCT_LIST_validate(scts, ct_policy_ctx); if (are_scts_validated < 0) { fprintf(stderr, "Error verifying SCTs\n"); test_failed = 1; } else if (!are_scts_validated) { int invalid_sct_count = 0; int valid_sct_count = 0; int i; for (i = 0; i < sk_SCT_num(scts); ++i) { SCT *sct_i = sk_SCT_value(scts, i); switch (SCT_get_validation_status(sct_i)) { case SCT_VALIDATION_STATUS_VALID: ++valid_sct_count; break; case SCT_VALIDATION_STATUS_INVALID: ++invalid_sct_count; break; default: /* Ignore other validation statuses. */ break; } } if (valid_sct_count != fixture.expected_sct_count) { int unverified_sct_count = sk_SCT_num(scts) - invalid_sct_count - valid_sct_count; fprintf(stderr, "%d SCTs failed verification\n" "%d SCTs passed verification (%d expected)\n" "%d SCTs were unverified\n", invalid_sct_count, valid_sct_count, fixture.expected_sct_count, unverified_sct_count); } test_failed = 1; } if (test_failed != 0) goto end; } } else if (sct_extension != NULL) { test_failed = 1; fprintf(stderr, "Expected no SCTs, but found SCT extension in: %s\n", fixture.certificate_file_path); goto end; } } if (fixture.tls_sct != NULL) { const unsigned char *p = fixture.tls_sct; if (o2i_SCT(&sct, &p, fixture.tls_sct_len) == NULL) { test_failed = 1; fprintf(stderr, "Failed to decode SCT from TLS format\n"); goto end; } if (fixture.sct_text_file_path) { test_failed = compare_sct_printout(sct, expected_sct_text); if (test_failed != 0) goto end; } tls_sct_len = i2o_SCT(sct, &tls_sct); if (tls_sct_len != fixture.tls_sct_len || memcmp(fixture.tls_sct, tls_sct, tls_sct_len) != 0) { test_failed = 1; fprintf(stderr, "Failed to encode SCT into TLS format correctly\n"); goto end; } if (fixture.test_validity && cert != NULL) { int is_sct_validated = SCT_validate(sct, ct_policy_ctx); if (is_sct_validated < 0) { test_failed = 1; fprintf(stderr, "Error validating SCT\n"); goto end; } else if (!is_sct_validated) { test_failed = 1; fprintf(stderr, "SCT failed verification\n"); goto end; } } } end: X509_free(cert); X509_free(issuer); SCT_LIST_free(scts); SCT_free(sct); CT_POLICY_EVAL_CTX_free(ct_policy_ctx); OPENSSL_free(tls_sct); return test_failed; }
struct args * args_init_from_gcc_atfile(const char *filename) { char *argtext; if (!(argtext = read_text_file(filename, 0))) { return NULL; } struct args *args = args_init(0, NULL); char *pos = argtext; char *argbuf = x_malloc(strlen(argtext) + 1); char *argpos = argbuf; // Used to track quoting state; if \0, we are not inside quotes. Otherwise // stores the quoting character that started it, for matching the end quote. char quoting = '\0'; while (1) { switch (*pos) { case '\\': pos++; if (*pos == '\0') { continue; } break; case '\"': case '\'': if (quoting != '\0') { if (quoting == *pos) { quoting = '\0'; pos++; continue; } else { break; } } else { quoting = *pos; pos++; continue; } case '\n': case '\r': case '\t': case ' ': if (quoting) { break; } // Fall through. case '\0': // End of token *argpos = '\0'; if (argbuf[0] != '\0') { args_add(args, argbuf); } argpos = argbuf; if (*pos == '\0') { goto out; } else { pos++; continue; } } *argpos = *pos; pos++; argpos++; } out: free(argbuf); free(argtext); return args; }