/* -------------------------------------------------------------------------------------------- * Remove all the options from the options container. */ void OptionsClear() { m_Options.clear(); }
forceinline Builder::Builder(const Options& opt0, bool b0) : opt(opt0.expand()), b(b0) {}
int main(int argc, char** argv) { int c; float col_r, col_g, col_b = -1.0f; Options opt; while ((c = getopt(argc, argv, "a:x:y:f:s:t:n:w:r:g:b:c:")) != -1) { switch(c) { /* color */ /* ------------------------------------------------------- */ case 'r': { col_r = convert_type<float>(optarg); break; } case 'g': { col_g = convert_type<float>(optarg); break; } case 'b': { col_b = convert_type<float>(optarg); break; } /* ------------------------------------------------------- */ /* foreground */ case 'c': { opt.foreground_file = convert_type<std::string>(optarg); break; } /* ------------------------------------------------------- */ /* background */ case 'x': { opt.background_x = convert_type<int>(optarg); break; } case 'y': { opt.background_y = convert_type<int>(optarg); break; } case 'f': { //printf("Got: %s", optarg); opt.background_file = convert_type<std::string>(optarg); break; } /* ------------------------------------------------------- */ /* visible size */ case 'a': { opt.visible_size = convert_type<float>(optarg); break; } /* ------------------------------------------------------- */ /* name */ case 'n': { opt.name = convert_type<std::string>(optarg); /* we expect that r,g,b has been set */ if (0 > col_r) { printf("Error: you haven't set -r -g -b for the name.\n"); exit(EXIT_FAILURE); } opt.name_r = col_r; opt.name_g = col_g; opt.name_b = col_b; break; } /* name x position */ case 's': { opt.name_x = convert_type<int>(optarg); break; } /* name y position */ case 't': { opt.name_y = convert_type<int>(optarg); break; } /* name font size */ case 'w': { opt.name_font_size = convert_type<float>(optarg); break; } default: { printf("Unkown option\n"); break; } } } if (false == opt.validate()) { printf("+ error: cannot validate the given options.\n"); exit(EXIT_FAILURE); } opt.print(); /* ------------------------------------------------------------------------------------ */ Image img; std::string path; std::string ext; cairo_surface_t* surf_bg = NULL; cairo_format_t img_format = CAIRO_FORMAT_INVALID; path = opt.foreground_file; if (false == rx_file_exists(path)) { printf("+ error: cannot find the file: %s\n", path.c_str()); exit(EXIT_FAILURE); } cairo_surface_t* surf_overlay = cairo_image_surface_create_from_png(path.c_str()); if (NULL == surf_overlay) { printf("Error: cannot create s1\n"); exit(EXIT_FAILURE); } path = opt.background_file; if (false == rx_file_exists(path)) { printf("Error: file doesn't exist: %s\n", path.c_str()); exit(EXIT_FAILURE); } /* check what file type was given. */ ext = rx_get_file_ext(path); if (ext == "jpg") { printf("+ warning: jpg as input doesn't seem to work\n"); /* cairo doesn't have support for PNG? */ if (0 > rx_load_jpg(path, &img.pixels, img.width, img.height, img.channels)) { printf("Error: failed to load: %s\n", path.c_str()); exit(EXIT_FAILURE); } if (0 == img.width || 0 == img.height || 0 == img.channels) { printf("Error: image has invalid flags: %d x %d, channels: %d\n", img.width, img.height, img.channels); exit(EXIT_FAILURE); } if (3 == img.channels) { img_format = CAIRO_FORMAT_RGB24; printf("+ Using RGB24\n"); } else if(4 == img.channels) { img_format = CAIRO_FORMAT_ARGB32; printf("+ Using ARGB32\n"); } else { printf("Error: unsupported number of channels: %d.\n", img.channels); exit(EXIT_FAILURE); } if (NULL != img.pixels && NULL == surf_bg) { printf("Stride: %d\n", cairo_format_stride_for_width(img_format, img.width)); printf("Info: creating %d x %d, channels: %d\n", img.width, img.height, img.channels); surf_bg = cairo_image_surface_create_for_data(img.pixels, img_format, img.width, img.height, cairo_format_stride_for_width(img_format, img.width)); #if 0 /* TESTING */ cairo_t* cr = cairo_create(surf_bg); if (NULL == cr) { printf("Error: cannot create the cairo"); exit(EXIT_FAILURE); } path = rx_get_exe_path() +"/generated_polaroid.png"; cairo_surface_write_to_png(surf_bg, path.c_str()); printf("Created\n"); exit(0); /* END TESTING */ #endif } } else if (ext == "png") { /* use cairo png load feature. */ surf_bg = cairo_image_surface_create_from_png(path.c_str()); if (NULL == surf_bg) { printf("Error: cannot create s2\n"); exit(EXIT_FAILURE); } } else { printf("Error: unsupported file format: %s\n", ext.c_str()); exit(EXIT_FAILURE); } /* make sure the background is loaded correctly (aka the photo) */ if (NULL == surf_bg) { printf("Error: cannot create background surface.\n"); exit(EXIT_FAILURE); } if (CAIRO_STATUS_SUCCESS != cairo_surface_status(surf_bg)) { printf("Error: something went wrong: %d\n", cairo_surface_status(surf_bg)); exit(EXIT_FAILURE); } float source_width = cairo_image_surface_get_width(surf_bg); float source_height = cairo_image_surface_get_height(surf_bg); /* create output */ int dest_width = cairo_image_surface_get_width(surf_overlay); int dest_height = cairo_image_surface_get_height(surf_overlay); printf("+ Output size: %d x %d\n", dest_width, dest_height); cairo_surface_t* surf_out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, dest_width, dest_height); if (NULL == surf_out) { printf("Error: cannot create cairo_surface_t\n"); exit(EXIT_FAILURE); } printf("+ Info: creating output surface: %d x %d\n", dest_width, dest_height); cairo_t* cr = cairo_create(surf_out); if (NULL == cr) { printf("Error: cannot create the cairo"); exit(EXIT_FAILURE); } /* fill background. */ cairo_set_source_rgba(cr, 1, 1, 1, 1); cairo_paint(cr); float scale_factor = opt.visible_size / source_width; printf("+ Scale factor: %f\n", scale_factor); /* paint background */ cairo_save(cr); cairo_scale(cr, scale_factor, scale_factor); cairo_set_source_surface(cr, surf_bg, opt.background_x, opt.background_y); cairo_rectangle(cr, 0, 0, img.width, img.height); cairo_paint(cr); cairo_restore(cr); /* paint overlay */ cairo_set_source_surface(cr, surf_overlay, 0, 0); cairo_paint(cr); cairo_surface_flush(surf_out); /* font */ cairo_select_font_face(cr, "Open Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_source_rgba(cr, opt.name_r, opt.name_g, opt.name_b, 1.0); cairo_move_to(cr, opt.name_x, opt.name_y); cairo_set_font_size(cr, opt.name_font_size); cairo_show_text(cr, opt.name.c_str()); cairo_stroke(cr); cairo_fill(cr); cairo_surface_flush(surf_out); /* write out */ path = rx_get_exe_path() +"/generated_polaroid.png"; cairo_surface_write_to_png(surf_out, path.c_str()); /* cleanup */ cairo_surface_destroy(surf_out); cairo_surface_destroy(surf_bg); cairo_surface_destroy(surf_overlay); cairo_destroy(cr); printf("\n"); return 0; }
static void spawn_command( const std::shared_ptr<w_root_t>& root, struct watchman_trigger_command* cmd, w_query_res* res, struct ClockSpec* since_spec) { long arg_max; size_t argspace_remaining; bool file_overflow = false; #ifdef _WIN32 arg_max = 32*1024; #else arg_max = sysconf(_SC_ARG_MAX); #endif if (arg_max <= 0) { argspace_remaining = UINT_MAX; } else { argspace_remaining = (uint32_t)arg_max; } // Allow some misc working overhead argspace_remaining -= 32; // Record an overflow before we call prepare_stdin(), which mutates // and resizes the results to fit the specified limit. if (cmd->max_files_stdin > 0 && res->resultsArray.array().size() > cmd->max_files_stdin) { file_overflow = true; } auto stdin_file = prepare_stdin(cmd, res); if (!stdin_file) { w_log( W_LOG_ERR, "trigger %s:%s %s\n", root->root_path.c_str(), cmd->triggername.c_str(), strerror(errno)); return; } // Assumption: that only one thread will be executing on a given // cmd instance so that mutation of cmd->env is safe. // This is guaranteed in the current architecture. // It is way too much of a hassle to try to recreate the clock value if it's // not a relative clock spec, and it's only going to happen on the first run // anyway, so just skip doing that entirely. if (since_spec && since_spec->tag == w_cs_clock) { cmd->env.set("WATCHMAN_SINCE", since_spec->clock.position.toClockString()); } else { cmd->env.unset("WATCHMAN_SINCE"); } cmd->env.set( "WATCHMAN_CLOCK", res->clockAtStartOfQuery.position().toClockString()); if (cmd->query->relative_root) { cmd->env.set("WATCHMAN_RELATIVE_ROOT", cmd->query->relative_root); } else { cmd->env.unset("WATCHMAN_RELATIVE_ROOT"); } // Compute args auto args = json_deep_copy(cmd->command); if (cmd->append_files) { // Measure how much space the base args take up for (size_t i = 0; i < json_array_size(args); i++) { const char *ele = json_string_value(json_array_get(args, i)); argspace_remaining -= strlen(ele) + 1 + sizeof(char*); } // Dry run with env to compute space size_t env_size; cmd->env.asEnviron(&env_size); argspace_remaining -= env_size; for (const auto& item : res->dedupedFileNames) { // also: NUL terminator and entry in argv uint32_t size = item.size() + 1 + sizeof(char*); if (argspace_remaining < size) { file_overflow = true; break; } argspace_remaining -= size; json_array_append_new(args, w_string_to_json(item)); } } cmd->env.set("WATCHMAN_FILES_OVERFLOW", file_overflow); Options opts; opts.environment() = cmd->env; #ifndef _WIN32 sigset_t mask; sigemptyset(&mask); opts.setSigMask(mask); #endif opts.setFlags(POSIX_SPAWN_SETPGROUP); opts.dup2(stdin_file->getFileDescriptor(), STDIN_FILENO); if (cmd->stdout_name) { opts.open(STDOUT_FILENO, cmd->stdout_name, cmd->stdout_flags, 0666); } else { opts.dup2(FileDescriptor::stdOut(), STDOUT_FILENO); } if (cmd->stderr_name) { opts.open(STDERR_FILENO, cmd->stderr_name, cmd->stderr_flags, 0666); } else { opts.dup2(FileDescriptor::stdErr(), STDERR_FILENO); } // Figure out the appropriate cwd w_string working_dir(cmd->query->relative_root); if (!working_dir) { working_dir = root->root_path; } auto cwd = cmd->definition.get_default("chdir"); if (cwd) { auto target = json_to_w_string(cwd); if (w_is_path_absolute_cstr_len(target.data(), target.size())) { working_dir = target; } else { working_dir = w_string::pathCat({working_dir, target}); } } watchman::log(watchman::DBG, "using ", working_dir, " for working dir\n"); opts.chdir(working_dir.c_str()); try { if (cmd->current_proc) { cmd->current_proc->kill(); cmd->current_proc->wait(); } cmd->current_proc = watchman::make_unique<ChildProcess>(args, std::move(opts)); } catch (const std::exception& exc) { watchman::log( watchman::ERR, "trigger ", root->root_path, ":", cmd->triggername, " failed: ", exc.what(), "\n"); } // We have integration tests that check for this string watchman::log( cmd->current_proc ? watchman::DBG : watchman::ERR, "posix_spawnp: ", cmd->triggername, "\n"); }
void ScriptBase<Space>::runMeta(const Options& o, Script* s) { using namespace std; ofstream sol_file, log_file; ostream& s_out = select_ostream(o.out_file(), sol_file); ostream& l_out = select_ostream(o.log_file(), log_file); try { switch (o.mode()) { case SM_GIST: #ifdef GECODE_HAS_GIST { Gist::Print<Script> pi(o.name()); Gist::VarComparator<Script> vc(o.name()); Gist::Options opt; opt.inspect.click(&pi); opt.inspect.compare(&vc); opt.clone = false; opt.c_d = o.c_d(); opt.a_d = o.a_d(); for (int i=0; o.inspect.click(i) != NULL; i++) opt.inspect.click(o.inspect.click(i)); for (int i=0; o.inspect.solution(i) != NULL; i++) opt.inspect.solution(o.inspect.solution(i)); for (int i=0; o.inspect.move(i) != NULL; i++) opt.inspect.move(o.inspect.move(i)); for (int i=0; o.inspect.compare(i) != NULL; i++) opt.inspect.compare(o.inspect.compare(i)); if (s == NULL) s = new Script(o); (void) GistEngine<Engine<Script> >::explore(s, opt); } break; // If Gist is not available, fall through #endif case SM_SOLUTION: { l_out << o.name() << endl; Support::Timer t; int i = o.solutions(); t.start(); if (s == NULL) s = new Script(o); unsigned int n_p = s->propagators(); unsigned int n_b = s->branchers(); Search::Options so; so.threads = o.threads(); so.c_d = o.c_d(); so.a_d = o.a_d(); so.stop = CombinedStop::create(o.node(),o.fail(), o.time(), o.interrupt()); so.cutoff = createCutoff(o); so.clone = false; so.nogoods_limit = o.nogoods() ? o.nogoods_limit() : 0U; if (o.interrupt()) CombinedStop::installCtrlHandler(true); { Meta<Engine,Script> e(s,so); if (o.print_last()) { Script* px = NULL; do { Script* ex = e.next(); if (ex == NULL) { if (px != NULL) { px->print(s_out); delete px; } break; } else { delete px; px = ex; } } while (--i != 0); } else { do { Script* ex = e.next(); if (ex == NULL) break; ex->print(s_out); delete ex; } while (--i != 0); } if (o.interrupt()) CombinedStop::installCtrlHandler(false); Search::Statistics stat = e.statistics(); s_out << endl; if (e.stopped()) { l_out << "Search engine stopped..." << endl << "\treason: "; int r = static_cast<CombinedStop*>(so.stop)->reason(stat,so); if (r & CombinedStop::SR_INT) l_out << "user interrupt " << endl; else { if (r & CombinedStop::SR_NODE) l_out << "node "; if (r & CombinedStop::SR_FAIL) l_out << "fail "; if (r & CombinedStop::SR_TIME) l_out << "time "; l_out << "limit reached" << endl << endl; } } l_out << "Initial" << endl << "\tpropagators: " << n_p << endl << "\tbranchers: " << n_b << endl << endl << "Summary" << endl << "\truntime: "; stop(t, l_out); l_out << endl << "\tsolutions: " << ::abs(static_cast<int>(o.solutions()) - i) << endl << "\tpropagations: " << stat.propagate << endl << "\tnodes: " << stat.node << endl << "\tfailures: " << stat.fail << endl << "\trestarts: " << stat.restart << endl << "\tno-goods: " << stat.nogood << endl << "\tpeak depth: " << stat.depth << endl #ifdef GECODE_PEAKHEAP << "\tpeak memory: " << static_cast<int>((heap.peak()+1023) / 1024) << " KB" << endl #endif << endl; } delete so.stop; } break; case SM_STAT: { l_out << o.name() << endl; Support::Timer t; int i = o.solutions(); t.start(); if (s == NULL) s = new Script(o); unsigned int n_p = s->propagators(); unsigned int n_b = s->branchers(); Search::Options so; so.clone = false; so.threads = o.threads(); so.c_d = o.c_d(); so.a_d = o.a_d(); so.stop = CombinedStop::create(o.node(),o.fail(), o.time(), o.interrupt()); so.cutoff = createCutoff(o); so.nogoods_limit = o.nogoods() ? o.nogoods_limit() : 0U; if (o.interrupt()) CombinedStop::installCtrlHandler(true); { Meta<Engine,Script> e(s,so); do { Script* ex = e.next(); if (ex == NULL) break; delete ex; } while (--i != 0); if (o.interrupt()) CombinedStop::installCtrlHandler(false); Search::Statistics stat = e.statistics(); l_out << endl << "\tpropagators: " << n_p << endl << "\tbranchers: " << n_b << endl << "\truntime: "; stop(t, l_out); l_out << endl << "\tsolutions: " << ::abs(static_cast<int>(o.solutions()) - i) << endl << "\tpropagations: " << stat.propagate << endl << "\tnodes: " << stat.node << endl << "\tfailures: " << stat.fail << endl << "\trestarts: " << stat.restart << endl << "\tno-goods: " << stat.nogood << endl << "\tpeak depth: " << stat.depth << endl #ifdef GECODE_PEAKHEAP << "\tpeak memory: " << static_cast<int>((heap.peak()+1023) / 1024) << " KB" << endl #endif << endl; } delete so.stop; } break; case SM_TIME: { l_out << o.name() << endl; Support::Timer t; double* ts = new double[o.samples()]; bool stopped = false; for (unsigned int s = o.samples(); !stopped && s--; ) { t.start(); for (unsigned int k = o.iterations(); !stopped && k--; ) { unsigned int i = o.solutions(); Script* s = new Script(o); Search::Options so; so.clone = false; so.threads = o.threads(); so.c_d = o.c_d(); so.a_d = o.a_d(); so.stop = CombinedStop::create(o.node(),o.fail(), o.time(), false); so.cutoff = createCutoff(o); so.nogoods_limit = o.nogoods() ? o.nogoods_limit() : 0U; { Meta<Engine,Script> e(s,so); do { Script* ex = e.next(); if (ex == NULL) break; delete ex; } while (--i != 0); if (e.stopped()) stopped = true; } delete so.stop; } ts[s] = t.stop() / o.iterations(); } if (stopped) { l_out << "\tSTOPPED" << endl; } else { double m = am(ts,o.samples()); double d = dev(ts,o.samples()) * 100.0; l_out << "\truntime: " << setw(20) << right << showpoint << fixed << setprecision(6) << m << "ms" << setprecision(2) << " (" << d << "% deviation)" << endl; } delete [] ts; } break; } } catch (Exception& e) { cerr << "Exception: " << e.what() << "." << endl << "Stopping..." << endl; if (sol_file.is_open()) sol_file.close(); if (log_file.is_open()) log_file.close(); exit(EXIT_FAILURE); } if (sol_file.is_open()) sol_file.close(); if (log_file.is_open()) log_file.close(); }
/// Actual model Alpha(const Options& opt) : le(*this,n,1,n) { IntVar a(le[ 0]), b(le[ 1]), c(le[ 2]), e(le[ 4]), f(le[ 5]), g(le[ 6]), h(le[ 7]), i(le[ 8]), j(le[ 9]), k(le[10]), l(le[11]), m(le[12]), n(le[13]), o(le[14]), p(le[15]), q(le[16]), r(le[17]), s(le[18]), t(le[19]), u(le[20]), v(le[21]), w(le[22]), x(le[23]), y(le[24]), z(le[25]); rel(*this, b+a+l+l+e+t == 45, opt.icl()); rel(*this, c+e+l+l+o == 43, opt.icl()); rel(*this, c+o+n+c+e+r+t == 74, opt.icl()); rel(*this, f+l+u+t+e == 30, opt.icl()); rel(*this, f+u+g+u+e == 50, opt.icl()); rel(*this, g+l+e+e == 66, opt.icl()); rel(*this, j+a+z+z == 58, opt.icl()); rel(*this, l+y+r+e == 47, opt.icl()); rel(*this, o+b+o+e == 53, opt.icl()); rel(*this, o+p+e+r+a == 65, opt.icl()); rel(*this, p+o+l+k+a == 59, opt.icl()); rel(*this, q+u+a+r+t+e+t == 50, opt.icl()); rel(*this, s+a+x+o+p+h+o+n+e == 134, opt.icl()); rel(*this, s+c+a+l+e == 51, opt.icl()); rel(*this, s+o+l+o == 37, opt.icl()); rel(*this, s+o+n+g == 61, opt.icl()); rel(*this, s+o+p+r+a+n+o == 82, opt.icl()); rel(*this, t+h+e+m+e == 72, opt.icl()); rel(*this, v+i+o+l+i+n == 100, opt.icl()); rel(*this, w+a+l+t+z == 34, opt.icl()); distinct(*this, le, opt.icl()); switch (opt.branching()) { case BRANCH_NONE: branch(*this, le, INT_VAR_NONE(), INT_VAL_MIN()); break; case BRANCH_INVERSE: branch(*this, le.slice(le.size()-1,-1), INT_VAR_NONE(), INT_VAL_MIN()); break; case BRANCH_SIZE: branch(*this, le, INT_VAR_SIZE_MIN(), INT_VAL_MIN()); break; } }
void QtCUrl::setOptions(Options& opt) { Options defaults; //defaults[CURLOPT_FAILONERROR] = true; defaults[CURLOPT_ERRORBUFFER].setValue(_errorBuffer); if(FileName.isEmpty()) { defaults[CURLOPT_WRITEFUNCTION].setValue(&writer); defaults[CURLOPT_WRITEDATA].setValue(&_buffer); }else { File.setFileName(FileName); defaults[CURLOPT_WRITEFUNCTION].setValue(&writer_file); defaults[CURLOPT_WRITEDATA].setValue(&File); } defaults[CURLOPT_PROGRESSFUNCTION].setValue(&progress_callback); defaults[CURLOPT_PROGRESSDATA].setValue(&AutoDelete); defaults[CURLOPT_NOPROGRESS].setValue(0); defaults[CURLOPT_SSL_VERIFYPEER].setValue(false); defaults[CURLOPT_SSL_VERIFYHOST].setValue(false); if(!Filter.isEmpty()) { //defaults[CURLOPT_VERBOSE].setValue(1); defaults[CURLOPT_HEADERFUNCTION].setValue(&writer2); defaults[CURLOPT_WRITEHEADER].setValue(&_buffer_and_filter); } //defaults[CURLOPT_VERBOSE].setValue(1); #ifdef QTCURL_DEBUG curl_easy_setopt(_curl, CURLOPT_VERBOSE, 1); curl_easy_setopt(_curl, CURLOPT_DEBUGFUNCTION, trace); #endif OptionsIterator i(defaults); while (i.hasNext()) { i.next(); if (! opt.contains(i.key())) { opt[i.key()] = i.value(); } } if(opt.contains(CURLOPT_POSTFIELDSIZE)) { int val = opt[CURLOPT_POSTFIELDSIZE].toInt(); curl_easy_setopt(_curl, CURLOPT_POSTFIELDSIZE, (long)val); } i = opt; while (i.hasNext()) { i.next(); QVariant value = i.value(); if(i.key() == CURLOPT_POSTFIELDSIZE) { continue; } switch (value.type()) { case QVariant::Bool: case QVariant::Int: { int val = value.toInt(); curl_easy_setopt(_curl, i.key(), val); break; } case QVariant::ByteArray: { QByteArray ba = value.toByteArray(); curl_easy_setopt(_curl, i.key(), ba.constData()); break; } case QVariant::Url: { QByteArray ba = value.toUrl().toEncoded(); curl_easy_setopt(_curl, i.key(), ba.constData()); break; } case QVariant::String: { curl_easy_setopt(_curl, i.key(), value.toString().toUtf8().data()); break; } case QVariant::ULongLong: { qulonglong val = value.toULongLong(); curl_easy_setopt(_curl, i.key(), (void*) val); break; } case QVariant::StringList: { struct curl_slist *slist = NULL; foreach (const QString &tmp, value.toStringList()) { slist = curl_slist_append(slist, tmp.toUtf8().data()); } _slist.append(slist); curl_easy_setopt(_curl, i.key(), slist); break; } default: const QString typeName = value.typeName(); if (typeName == "QtCUrl::WriterPtr") { curl_easy_setopt(_curl, i.key(), value.value<WriterPtr>()); }else if (typeName == "QtCUrl::WriterFilePtr") { curl_easy_setopt(_curl, i.key(), value.value<WriterFilePtr>()); }else if (typeName == "QtCUrl::HeaderPtr") { curl_easy_setopt(_curl, i.key(), value.value<HeaderPtr>()); }else if (typeName == "QtCUrl::ProgressPtr") { curl_easy_setopt(_curl, i.key(), value.value<ProgressPtr>()); } else if (typeName == "std::string*") { curl_easy_setopt(_curl, i.key(), value.value<std::string*>()); } else if (typeName == "BufferAndFilter*") { curl_easy_setopt(_curl, i.key(), value.value<BufferAndFilter*>()); } else if (typeName == "char*") { curl_easy_setopt(_curl, i.key(), value.value<char*>()); } else if (typeName == "bool*") { curl_easy_setopt(_curl, i.key(), value.value<bool*>()); } else if (typeName == "QFile*") { curl_easy_setopt(_curl, i.key(), value.value<QFile*>()); } else { //qDebug() << "[QtCUrl] Unsupported option type: " << typeName; } } } }
void run () { size_t niter = 10000; float target_power = 2.0; Options opt = get_options ("power"); if (opt.size()) target_power = opt[0][0]; opt = get_options ("niter"); if (opt.size()) niter = opt[0][0]; ndirs = to<int> (argument[0]); if (get_options ("unipolar").size()) bipolar = false; Math::RNG rng; Math::Vector<double> v (2*ndirs); for (size_t n = 0; n < 2*ndirs; n+=2) { v[n] = Math::pi * (2.0 * rng.uniform() - 1.0); v[n+1] = std::asin (2.0 * rng.uniform() - 1.0); } gsl_multimin_function_fdf fdf; fdf.f = energy_f; fdf.df = energy_df; fdf.fdf = energy_fdf; fdf.n = 2*ndirs; gsl_multimin_fdfminimizer* minimizer = gsl_multimin_fdfminimizer_alloc (gsl_multimin_fdfminimizer_conjugate_fr, 2*ndirs); { ProgressBar progress ("Optimising directions..."); for (power = -1.0; power >= -target_power/2.0; power *= 2.0) { INFO ("setting power = " + str (-power*2.0)); gsl_multimin_fdfminimizer_set (minimizer, &fdf, v.gsl(), 0.01, 1e-4); for (size_t iter = 0; iter < niter; iter++) { int status = gsl_multimin_fdfminimizer_iterate (minimizer); //for (size_t n = 0; n < 2*ndirs; ++n) //std::cout << gsl_vector_get (minimizer->x, n) << " " << gsl_vector_get (minimizer->gradient, n) << "\n"; if (iter%10 == 0) INFO ("[ " + str (iter) + " ] (pow = " + str (-power*2.0) + ") E = " + str (minimizer->f) + ", grad = " + str (gsl_blas_dnrm2 (minimizer->gradient))); if (status) { INFO (std::string ("iteration stopped: ") + gsl_strerror (status)); break; } progress.update ([&]() { return "Optimising directions (power " + str(-2.0*power) + ", current energy: " + str(minimizer->f, 8) + ")..."; }); } gsl_vector_memcpy (v.gsl(), minimizer->x); } } Math::Matrix<double> directions (ndirs, 2); for (size_t n = 0; n < ndirs; n++) { double az = gsl_vector_get (minimizer->x, 2*n); double el = gsl_vector_get (minimizer->x, 2*n+1); range (az, el); directions (n, 0) = az; directions (n, 1) = el; } gsl_multimin_fdfminimizer_free (minimizer); DWI::Directions::save (directions, argument[1], get_options ("cartesian").size()); }
Expression::Ptr TypeChecker::verifyType(const Expression::Ptr &operand, const SequenceType::Ptr &reqSeqType, const StaticContext::Ptr &context, const ReportContext::ErrorCode code, const Options options) { const ItemType::Ptr reqType(reqSeqType->itemType()); const Expression::Properties props(operand->properties()); /* If operand requires a focus, do the necessary type checking for that. */ if(props.testFlag(Expression::RequiresFocus) && options.testFlag(CheckFocus)) { const ItemType::Ptr contextType(context->contextItemType()); if(contextType) { if(props.testFlag(Expression::RequiresContextItem)) { Q_ASSERT_X(operand->expectedContextItemType(), Q_FUNC_INFO, "When the Expression sets the RequiresContextItem property, it must " "return a type in expectedContextItemType()"); const ItemType::Ptr expectedContextType(operand->expectedContextItemType()); /* Allow the empty sequence. We don't want to trigger XPTY0020 on ()/... . */ if(!expectedContextType->xdtTypeMatches(contextType) && contextType != CommonSequenceTypes::Empty) { context->error(wrongType(context->namePool(), operand->expectedContextItemType(), contextType), ReportContext::XPTY0020, operand.data()); return operand; } } } else { context->error(QtXmlPatterns::tr("The focus is undefined."), ReportContext::XPDY0002, operand.data()); return operand; } } SequenceType::Ptr operandSeqType(operand->staticType()); ItemType::Ptr operandType(operandSeqType->itemType()); /* This returns the operand if the types are identical or if operandType * is a subtype of reqType. */ if(reqType->xdtTypeMatches(operandType) || *operandType == *CommonSequenceTypes::Empty) return operand; /* Since we haven't exited yet, it means that the operandType is a super type * of reqType, and that there hence is a path down to it through the * type hierachy -- but that doesn't necessarily mean that a up-cast(down the * hierarchy) would succeed. */ Expression::Ptr result(operand); if(reqType->isAtomicType()) { const Expression::ID opID = operand->id(); if((opID == Expression::IDArgumentReference || (opID == Expression::IDCardinalityVerifier && operand->operands().first()->is(Expression::IDArgumentReference))) && *BuiltinTypes::item == *operandType) return Expression::Ptr(new ArgumentConverter(result, reqType)); if(!operandType->isAtomicType()) { result = Expression::Ptr(new Atomizer(result)); /* The atomizer might know more about the type. */ operandType = result->staticType()->itemType(); } if(reqType->xdtTypeMatches(operandType)) { /* Atomization was sufficient. Either the expected type is xs:anyAtomicType * or the type the Atomizer knows it returns, matches the required type. */ return result; } const bool compatModeEnabled = context->compatModeEnabled(); if((options.testFlag(AutomaticallyConvert) && BuiltinTypes::xsUntypedAtomic->xdtTypeMatches(operandType)) || (compatModeEnabled && BuiltinTypes::xsString->xdtTypeMatches(reqType))) { if(*reqType == *BuiltinTypes::numeric) { result = typeCheck(new UntypedAtomicConverter(result, BuiltinTypes::xsDouble, code), context, reqSeqType); } else result = typeCheck(new UntypedAtomicConverter(result, reqType, code), context, reqSeqType); /* The UntypedAtomicConverter might know more about the type, so reload. */ operandType = result->staticType()->itemType(); } else if(compatModeEnabled && *reqType == *BuiltinTypes::xsDouble) { const FunctionFactory::Ptr functions(context->functionSignatures()); Expression::List numberArgs; numberArgs.append(operand); result = functions->createFunctionCall(QXmlName(StandardNamespaces::fn, StandardLocalNames::number), numberArgs, context, operand.data())->typeCheck(context, reqSeqType); operandType = result->staticType()->itemType(); context->wrapExpressionWith(operand.data(), result); } if(reqType->xdtTypeMatches(operandType)) return result; /* Test if promotion will solve it; the xdtTypeMatches didn't * do that. */ if(options.testFlag(AutomaticallyConvert) && promotionPossible(operandType, reqType, context)) { if(options.testFlag(GeneratePromotion)) return Expression::Ptr(new UntypedAtomicConverter(result, reqType)); else return result; } if(operandType->xdtTypeMatches(reqType)) { /* For example, operandType is numeric, and reqType is xs:integer. */ return Expression::Ptr(new ItemVerifier(result, reqType, code)); } else { context->error(wrongType(context->namePool(), reqType, operandType), code, operand.data()); return result; } } else if(reqType->isNodeType()) { ReportContext::ErrorCode myCode; if(*reqType == *CommonSequenceTypes::EBV->itemType()) myCode = ReportContext::FORG0006; else myCode = code; /* empty-sequence() is considered valid because it's ok to do * for example nilled( () ). That is, to pass an empty sequence to a * function requiring for example node()?. */ if(*operandType == *CommonSequenceTypes::Empty) return result; else if(!operandType->xdtTypeMatches(reqType)) { context->error(wrongType(context->namePool(), reqType, operandType), myCode, operand.data()); return result; } /* Operand must be an item. Thus, the sequence can contain both * nodes and atomic values: we have to verify. */ return Expression::Ptr(new ItemVerifier(result, reqType, myCode)); } else { Q_ASSERT(*reqType == *CommonSequenceTypes::Empty); /* element() doesn't match empty-sequence(), but element()* does. */ if(!reqType->xdtTypeMatches(operandType) && !operandSeqType->cardinality().allowsEmpty()) { context->error(wrongType(context->namePool(), reqType, operandType), code, operand.data()); return result; } } /* This line should be reached if required type is * EBVType, and the operand is compatible. */ return result; }
int main(int argc, char **argv) { if (!run_all_tests()) return 1; _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); Options options = parseArgs(argc, argv); auto status = displayHelpIfNecessary(options, "0.0.1"); if (status.first) { return status.second; } if (options.action == Options::Average) { vec3 average = exr_average(options.input0); std::cout << "[" << average.x << " " << average.y << " " << average.z << "]" << std::endl; } else if (options.action == Options::Errors) { return compute_errors(std::cout, options); } else if (options.action == Options::Strip) { strip_exr(options.output, options.input0); } else if (options.action == Options::Merge) { merge_exr(options.output, options.input0, options.input1); } else if (options.action == Options::Time) { std::cout << query_time(options.input0); } else if (options.action == Options::Statistics) { auto metadata = load_metadata(options.input0); print_records_tabular(std::cout, statistics_t(metadata)); } else if (options.action == Options::Measurements) { auto metadata = load_metadata(options.input0); print_measurements_tabular(std::cout, statistics_t(metadata)); } else if (options.action == Options::Traces) { auto metadata = load_metadata(options.input0); print_traces_tabular(std::cout, metadata); } else if (options.action == Options::Gnuplot) { auto error_message = gnuplot(argc, argv); options.displayHelp = !error_message.empty(); options.displayMessage = error_message; auto status = displayHelpIfNecessary(options, "0.0.1"); if (status.first) { return status.second; } } else if (options.action == Options::Bake) { return bake(argc, argv); } else if (options.action == Options::RelErr) { return compute_relative_error(options); } else { if (options.action == Options::Continue) { map<string, string> metadata = load_metadata(options.input0); auto output = options.input0; options = Options(metadata); options.output = output; options.action = Options::Continue; options.num_samples = atoi(metadata["statistics.num_samples"].c_str()); options.num_seconds = atoi(metadata["statistics.total_time"].c_str()); overrideArgs(options, argc, argv); auto status = displayHelpIfNecessary(options, "0.0.1"); if (status.first) { return status.second; } } Application application(options); if (options.batch) { return application.runBatch(options.width, options.height); } else { return application.run(options.width, options.height, options.caption()); } } return 0; }
void run () { Image::Buffer<float> data_in (argument[0]); auto voxel_in = data_in.voxel(); std::vector<std::vector<int> > bounds(data_in.ndim(), std::vector<int> (2) ); for (size_t axis = 0; axis < data_in.ndim(); axis++) { bounds[axis][0] = 0; bounds[axis][1] = data_in.dim (axis) - 1; } Options opt = get_options ("mask"); if (opt.size()) { Image::Buffer<bool> data_mask (opt[0][0]); Image::check_dimensions (data_in, data_mask, 0, 3); auto voxel_mask = data_mask.voxel(); for (size_t axis = 0; axis != 3; ++axis) { bounds[axis][0] = data_in.dim (axis); bounds[axis][1] = 0; } // Note that even though only 3 dimensions are cropped when using a mask, the bounds // are computed by checking the extent for all dimensions (for example a 4D AFD mask) for (auto i = Image::Loop() (voxel_mask); i; ++i) { if (voxel_mask.value()) { for (size_t axis = 0; axis != 3; ++axis) { bounds[axis][0] = std::min (bounds[axis][0], int (voxel_mask[axis])); bounds[axis][1] = std::max (bounds[axis][1], int (voxel_mask[axis])); } } } for (size_t axis = 0; axis != 3; ++axis) { if (bounds[axis][0] > bounds[axis][1]) throw Exception ("mask image is empty; can't use to crop image"); if (bounds[axis][0]) --bounds[axis][0]; if (bounds[axis][1] < voxel_mask.dim (axis) - 1) ++bounds[axis][1]; } } opt = get_options ("axis"); for (size_t i = 0; i != opt.size(); ++i) { // Manual cropping of axis overrides mask image bounds const int axis = opt[i][0]; const int start = opt[i][1]; const int end = opt[i][2]; bounds[axis][0] = start; bounds[axis][1] = end; if (bounds[axis][0] < 0 || bounds[axis][1] >= data_in.dim(axis)) throw Exception ("Index supplied for axis " + str(axis) + " is out of bounds."); } std::vector<size_t> from(data_in.ndim()); std::vector<size_t> size(data_in.ndim()); for (size_t axis = 0; axis < data_in.ndim(); axis++) { from[axis] = bounds[axis][0]; size[axis] = bounds[axis][1] - from[axis] + 1; } Image::Adapter::Subset<decltype(voxel_in)> cropped (voxel_in, from, size); Image::Header H_out (data_in); H_out.info() = cropped.info(); Image::Buffer<float> data_out (argument[1], H_out); auto out = data_out.voxel(); Image::copy_with_progress_message ("cropping image...", cropped, out); }
int main(int argc, char** argv) { const int buf_len = 512; int rc, docheck, print_flag; char fname[buf_len], outname[buf_len], statefname[buf_len]; FILE *F, *FS; mytm TM; // These are permanent stores and we need to worry about memory management Subcatchment *SUB = NULL; NameStore *NODE_NAMES; SMap HASH; if ( argc < 3 ) { printf("Usage: %s <netlistfile> <state file name>\n", argv[0]); printf(" %s -checkonly <netlistfile>\n", argv[0]); return (-1); } docheck = 0; if ( argc == 3 && strcmp(argv[1],"-checkonly")==0 ) { docheck = 1; strncpy(fname, argv[2], buf_len); } else { docheck = 0; strncpy(fname, argv[1], buf_len); strncpy(statefname, argv[2], buf_len); } if ( (F=fopen(fname, "r")) == NULL ) { printf("Bummer: unable to open netlist file %s\n", argv[1]); return (-1); } PrintHeader(stdout); /* allocate the subcatchment and the topograph */ SUB = new Subcatchment(0); NODE_NAMES = new NameStore(); // default option values OPT.Alpha() = 0.8; OPT.Beta() = 1.03; OPT.HT() = 1e-3; OPT.MinDT() = 0.001; OPT.SSTol() = 5e-8; OPT.Tol() = 1e-6; OPT.EpsilonA() = 1e-4; OPT.DebugLevel() = 0; rc = read_spt_from_file(F, SUB, NODE_NAMES, &HASH, stdout); // also modifies OPT and // STAT in the global // namespace // save the netlist file STAT.SetInFile( get_basename( fname ) ); if (rc < 0 ) goto out; // there is error! // do a topo check rc = SUB->TopologyCheck(); if (rc < 0 ) { SUB->TopoPrintErrMsg(stdout, "== tchk ==", NODE_NAMES->Store() ); goto out; } // quit if docheck == 1 if ( OPT.CheckOnly() == 1 || docheck==1 ) { printf("The connectivity of the given netlist appears to be correct\n"); goto out; } // make solver SUB->MakeSolver( SUB->GetNumNodes() ); // SUB->InitSolutions(); FS = fopen( statefname, "r"); rc = ERROR; if ( FS ) { const int perf_check=0; // force to ignore the check. Could be dangerous! rc = SUB->LoadSteadyStateFromFile(FS, perf_check); SUB->CopyXpToXtm1(); SUB->CopyXpToX(); if ( rc == OK ) printf("[II]: Loaded states from \"%s\"\n", statefname ); fclose(FS); } // steady solve, two phases if ( rc!=OK) { // either no state file, or state file is not good rc = SUB->SteadySolve(600, 600, 2*OPT.Tol()); if (rc<0) { fprintf(stdout,"[EE]: first phase of steady-state solve failed\n"); goto out; } rc = SUB->SteadySolve(25.0, 45, 45, OPT.Tol() ); if (rc<0) { fprintf(stdout,"[EE]: second phase of steady-state solve failed\n"); goto out; } } // store back if needed if ( rc > 0 && STAT.SSFile() ) { FS=fopen(STAT.SSFile(),"w"); SUB->SaveSteadyStateToFile(FS); fclose(FS); fprintf(stdout, "[II]: Saved steady state to file \"%s\"\n", STAT.SSFile()); } // run unsteady print_flag = 0; if (OPT.PrintQ()==1) print_flag |= PRT_Q; if (OPT.PrintA()==1) print_flag |= PRT_A; if (OPT.PrintZ()==1) print_flag |= PRT_Z; if (OPT.PrintD()==1) print_flag |= PRT_D; sprintf(outname,"%s.output.dat", fname); if ( print_flag ) { FS = fopen(outname,"w"); if ( FS == NULL ) { fprintf(stdout,"[II]: Unable to open output file %s. Request ignored\n", outname); } else { fprintf(stdout,"[II]: Unsteady results will be stored in \"%s\"\n", outname); } if (OPT.PrintXY()==1) print_flag |= PRT_XY; // XY printing is only turned on when // others are enabled } else { fprintf(stdout,"[II]: No printing request made. Nothing will be stored\n"); FS = NULL; } TM.start(); rc = SUB->UnsteadySolve(OPT.StopTime(), 1, 25, OPT.Tol(), NULL, FS, print_flag, OPT.PrintStart(), NODE_NAMES->Store() ); TM.stop(); if ( FS ) fclose(FS); fprintf(stdout, "[II]: Simulation of the %d-min event took %.3f seconds.\n", (int)(OPT.StopTime()/60.0), TM.read() ); // store the states FS=fopen(statefname, "w"); if (!FS) { printf("Bummer: unable to open file \"%s\" to write state. Check permissions!\n", statefname); } else { SUB->SaveSteadyStateToFile(FS); fprintf(stdout,"[II]: Saved final states to file \"%s\"\n", statefname); } if (FS) fclose(FS); out: if (F) fclose(F); if ( SUB ) delete SUB; if ( NODE_NAMES) delete NODE_NAMES; return 0; }
void checkOptions(Options& opts, int argc, char* argv[]) { opts.define("p|print|v|visual=b", "convert to printed visual score format"); opts.define("s|sound=b", "convert to sounding score format"); opts.define("debug=b"); // determine bad input line num opts.define("author=b"); // author of program opts.define("version=b"); // compilation info opts.define("example=b"); // example usages opts.define("h|help=b"); // short description opts.process(argc, argv); // handle basic options: if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "[email protected], Oct 2004" << endl; exit(0); } else if (opts.getBoolean("version")) { cout << argv[0] << ", version: 25 Oct 2004" << endl; cout << "compiled: " << __DATE__ << endl; cout << MUSEINFO_VERSION << endl; exit(0); } else if (opts.getBoolean("help")) { usage(opts.getCommand().data()); exit(0); } else if (opts.getBoolean("example")) { example(); exit(0); } if (opts.getBoolean("sound")) { direction = +1; } else if (opts.getBoolean("visual")) { direction = -1; } if (direction == 0) { cout << "Error: specify -v to convert to visual score or -s "; cout << "for sounding score\n"; exit(1); } }
Option PipelineReader::parseElement_Option(const ptree& tree) { // cur is an option element, such as this: // <option> // <name>myname</name> // <description>my descr</description> // <value>17</value> // </option> // this function will process the element and return an Option from it map_t attrs; collect_attributes(attrs, tree); std::string name = attrs["name"]; std::string value = tree.get_value<std::string>(); boost::algorithm::trim(value); Option option(name, value); boost::optional<ptree const&> moreOptions = tree.get_child_optional("Options"); if (moreOptions) { ptree::const_iterator iter = moreOptions->begin(); Options options; while (iter != moreOptions->end()) { if (iter->first == "Option") { Option o2 = parseElement_Option(iter->second); options.add(o2); } ++iter; } option.setOptions(options); } // filenames in the XML are fixed up as follows: // - if absolute path, leave it alone // - if relative path, make it absolute using the XML file's directory // The toAbsolutePath function does exactly that magic for us. if (option.getName() == "filename") { std::string path = option.getValue<std::string>(); #ifndef PDAL_PLATFORM_WIN32 wordexp_t result; if (wordexp(path.c_str(), &result, 0) == 0) { if (result.we_wordc == 1) path = result.we_wordv[0]; } wordfree(&result); #endif if (!FileUtils::isAbsolutePath(path)) { std::string abspath = FileUtils::toAbsolutePath(m_inputXmlFile); std::string absdir = FileUtils::getDirectory(abspath); path = FileUtils::toAbsolutePath(path, absdir); assert(FileUtils::isAbsolutePath(path)); } option.setValue(path); } return option; }
int main(int argc, char * argv[]) { try { string resource; string type; string resourceEntity; string objectId; string outputPrefix; bool returnUrl; vector<string> resourceSets; bool ignoreMalformedHeaders; Options options; options.descriptions.add_options() ("resource,r", po::value<string>(&resource) ->default_value("Property"), "Object resource") ("type", po::value<string>(&type) ->default_value("Photo"), "Object type") ("output-prefix", po::value<string>(&outputPrefix) ->default_value(""), "Output file prefix") ("resource-set", po::value< vector<string> >(&resourceSets), "Resource sets (e.g. 'resource-id' or 'resource-id:#,#'))") ("return-url", po::value<bool>(&returnUrl) ->default_value(false), "Return the URL to the object (true or false)") ("ignore-malformed-headers", po::value<bool>(&ignoreMalformedHeaders) ->default_value(false), "Ignore malformed headers (true or false)") ; if (!options.ParseCommandLine(argc, argv)) { return 1; } if (resourceSets.size() == 0) { resourceSets.push_back("1"); } RetsSessionPtr session = options.RetsLogin(); if (!session) { cout << "Login failed\n"; return -1; } GetObjectRequest getObjectRequest(resource, type); vector<string>::const_iterator i; for (i = resourceSets.begin(); i != resourceSets.end(); i++) { vector<string> resourceSet; ba::split(resourceSet, *i, ba::is_any_of(":")); if (resourceSet.size() == 1) { getObjectRequest.AddAllObjects(resourceSet[0]); } else if (resourceSet.size() == 2) { vector<string> ids; ba::split(ids, resourceSet[1], ba::is_any_of(",")); vector<string>::const_iterator idString; for (idString = ids.begin(); idString != ids.end(); idString++) { int id = lexical_cast<int>(*idString); getObjectRequest.AddObject(resourceSet[0], id); } } } getObjectRequest.SetLocation(returnUrl); getObjectRequest.SetIgnoreMalformedHeaders(ignoreMalformedHeaders); GetObjectResponseAPtr getObjectResponse = session->GetObject(&getObjectRequest); StringMap contentTypeSuffixes; contentTypeSuffixes["image/jpeg"] = "jpg"; contentTypeSuffixes["text/xml"] = "xml"; ObjectDescriptor * objectDescriptor; while ((objectDescriptor = getObjectResponse->NextObject())) { int retsReplyCode = objectDescriptor->GetRetsReplyCode(); string retsReplyText = objectDescriptor->GetRetsReplyText(); string objectKey = objectDescriptor->GetObjectKey(); int objectId = objectDescriptor->GetObjectId(); string contentType = objectDescriptor->GetContentType(); string description = objectDescriptor->GetDescription(); string location = objectDescriptor->GetLocationUrl(); if (objectDescriptor->GetWildIndicator()) cout << objectKey << " object #: *"; else cout << objectKey << " object #" << objectId; if (!description.empty()) cout << ", description: " << description; if (!location.empty()) cout << ", location: " << location; if (retsReplyCode) cout << ", **** " << retsReplyCode << ": " << retsReplyText; cout << endl; string suffix = contentTypeSuffixes[contentType]; string outputFileName = outputPrefix + objectKey + "-" + lexical_cast<string>(objectId) + "." + suffix; /* * Only save the object if there was no error and we're not * using the location option. */ if (retsReplyCode == 0 && location.empty()) { ofstream outputStream(outputFileName.c_str()); istreamPtr inputStream = objectDescriptor->GetDataStream(); readUntilEof(inputStream, outputStream); } } session->Logout(); } catch (RetsException & e) { e.PrintFullReport(cerr); } catch (std::exception & e) { cerr << e.what() << endl; } }
void checkOptions(Options& opts) { opts.define("r|reverse=b", "Reverse the order of notes"); opts.define("author=b", "Author of the program"); opts.define("version=b", "Print version of the program"); opts.define("example=b", "Display example use of the program"); opts.define("help=b", "Dispay help for the program"); opts.process(); if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "[email protected], 2 December 1999" << endl; exit(0); } if (opts.getBoolean("version")) { cout << "midimixup version 2.0" << endl; cout << "compiled: " << __DATE__ << endl; } if (opts.getBoolean("help")) { usage(opts.getCommand().data()); exit(0); } if (opts.getBoolean("example")) { example(); exit(0); } reverseQ = opts.getBoolean("reverse"); }
void checkOptions(Options& opts) { opts.define("a|auto|automatic=b"); opts.define("c|const|constant=b"); opts.define("t|tempo|tempo-average=i:1"); opts.define("m|max|max-amplitude=i:64"); opts.define("p|port|out-port=i:0"); opts.define("i|inport|in-port=i:0"); opts.define("1|z|channel-collapse=b"); opts.define("author=b"); opts.define("version=b"); opts.define("example=b"); opts.define("help=b"); opts.process(); if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "[email protected], Nov 1999" << endl; exit(0); } if (opts.getBoolean("version")) { cout << "midiplay version 1.0" << endl; cout << "compiled: " << __DATE__ << endl; } if (opts.getBoolean("help")) { usage(opts.getCommand().data()); exit(0); } if (opts.getBoolean("example")) { example(); exit(0); } // can only have one output filename if (opts.getArgCount() != 1) { cout << "Error: need one input MIDI file for performance." << endl; usage(opts.getCommand().data()); exit(1); } // figure out the tempo performance method if (opts.getBoolean("automatic")) { tempoMethod = TEMPO_METHOD_AUTOMATIC; } else if (opts.getBoolean("constant")) { tempoMethod = TEMPO_METHOD_CONSTANT; } else { switch (opts.getInteger("tempo-average")) { case 1: tempoMethod = TEMPO_METHOD_ONEBACK; break; case 2: tempoMethod = TEMPO_METHOD_TWOBACK; break; case 3: tempoMethod = TEMPO_METHOD_THREEBACK; break; case 4: tempoMethod = TEMPO_METHOD_FOURBACK; break; default: tempoMethod = TEMPO_METHOD_ONEBACK; break; } } outport = opts.getInteger("out-port"); inport = opts.getInteger("in-port"); maxamp = opts.getInteger("max-amplitude"); performance.channelCollapse(opts.getBoolean("channel-collapse")); }
void doPass(const Options& opts, ld::Internal& internal) { const bool log = false; // only make tlv section in final linked images if ( opts.outputKind() == Options::kObjectFile ) return; // walk all atoms and fixups looking for TLV references and add them to list std::vector<TlVReferenceCluster> references; for (std::vector<ld::Internal::FinalSection*>::iterator sit=internal.sections.begin(); sit != internal.sections.end(); ++sit) { ld::Internal::FinalSection* sect = *sit; for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) { const ld::Atom* atom = *ait; TlVReferenceCluster ref; for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) { if ( fit->firstInCluster() ) { ref.targetOfTLV = NULL; ref.fixupWithTarget = NULL; ref.fixupWithTLVStore = NULL; } switch ( fit->binding ) { case ld::Fixup::bindingsIndirectlyBound: ref.targetOfTLV = internal.indirectBindingTable[fit->u.bindingIndex]; ref.fixupWithTarget = fit; break; case ld::Fixup::bindingDirectlyBound: ref.targetOfTLV = fit->u.target; ref.fixupWithTarget = fit; break; default: break; } switch ( fit->kind ) { case ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad: case ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad: case ld::Fixup::kindStoreX86PCRel32TLVLoad: case ld::Fixup::kindStoreX86Abs32TLVLoad: #if SUPPORT_ARCH_arm64 case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21: case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12: #endif ref.fixupWithTLVStore = fit; break; default: break; } if ( fit->lastInCluster() && (ref.fixupWithTLVStore != NULL) ) { ref.optimizable = optimizable(opts, ref.targetOfTLV); if (log) fprintf(stderr, "found reference to TLV at %s+0x%X to %s\n", atom->name(), ref.fixupWithTLVStore->offsetInAtom, ref.targetOfTLV->name()); if ( ! opts.canUseThreadLocalVariables() ) { throwf("targeted OS version does not support use of thread local variables in %s", atom->name()); } references.push_back(ref); } } } } // compute which TLV references will be weak_imports std::map<const ld::Atom*,bool> weakImportMap; for(std::vector<TlVReferenceCluster>::iterator it=references.begin(); it != references.end(); ++it) { if ( !it->optimizable ) { // record weak_import attribute std::map<const ld::Atom*,bool>::iterator pos = weakImportMap.find(it->targetOfTLV); if ( pos == weakImportMap.end() ) { // target not in weakImportMap, so add weakImportMap[it->targetOfTLV] = it->fixupWithTarget->weakImport; } else { // target in weakImportMap, check for weakness mismatch if ( pos->second != it->fixupWithTarget->weakImport ) { // found mismatch switch ( opts.weakReferenceMismatchTreatment() ) { case Options::kWeakReferenceMismatchError: throwf("mismatching weak references for symbol: %s", it->targetOfTLV->name()); case Options::kWeakReferenceMismatchWeak: pos->second = true; break; case Options::kWeakReferenceMismatchNonWeak: pos->second = false; break; } } } } } // create TLV pointers for TLV references that cannot be optimized std::map<const ld::Atom*,ld::Atom*> variableToPointerMap; for(std::map<const ld::Atom*,bool>::iterator it=weakImportMap.begin(); it != weakImportMap.end(); ++it) { std::map<const ld::Atom*,ld::Atom*>::iterator pos = variableToPointerMap.find(it->first); if ( pos == variableToPointerMap.end() ) { if (log) fprintf(stderr, "make TLV pointer for %s\n", it->first->name()); if ( it->first->contentType() != ld::Atom::typeTLV ) throwf("illegal thread local variable reference to regular symbol %s", it->first->name()); TLVEntryAtom* tlvp = new TLVEntryAtom(internal, it->first, it->second); variableToPointerMap[it->first] = tlvp; } } // sort new tvlp atoms so links are consistent for (std::vector<ld::Internal::FinalSection*>::iterator sit=internal.sections.begin(); sit != internal.sections.end(); ++sit) { ld::Internal::FinalSection* sect = *sit; if ( sect->type() == ld::Section::typeTLVPointers ) { std::sort(sect->atoms.begin(), sect->atoms.end(), AtomByNameSorter()); } } // update references to use TLV pointers or TLV object directly for(std::vector<TlVReferenceCluster>::iterator it=references.begin(); it != references.end(); ++it) { if ( it->optimizable ) { // change store to be LEA instead load (mov) if (log) fprintf(stderr, "optimizing load of TLV to %s into an LEA\n", it->targetOfTLV->name()); it->fixupWithTLVStore->binding = ld::Fixup::bindingDirectlyBound; it->fixupWithTLVStore->u.target = it->targetOfTLV; switch ( it->fixupWithTLVStore->kind ) { case ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoad: it->fixupWithTLVStore->kind = ld::Fixup::kindStoreTargetAddressX86PCRel32TLVLoadNowLEA; break; case ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoad: it->fixupWithTLVStore->kind = ld::Fixup::kindStoreTargetAddressX86Abs32TLVLoadNowLEA; break; case ld::Fixup::kindStoreX86PCRel32TLVLoad: it->fixupWithTLVStore->kind = ld::Fixup::kindStoreX86PCRel32TLVLoadNowLEA; break; case ld::Fixup::kindStoreX86Abs32TLVLoad: it->fixupWithTLVStore->kind = ld::Fixup::kindStoreX86Abs32TLVLoadNowLEA; break; #if SUPPORT_ARCH_arm64 case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPage21: it->fixupWithTLVStore->kind = ld::Fixup::kindStoreARM64TLVPLoadNowLeaPage21; break; case ld::Fixup::kindStoreTargetAddressARM64TLVPLoadPageOff12: it->fixupWithTLVStore->kind = ld::Fixup::kindStoreTargetAddressARM64TLVPLoadNowLeaPageOff12; break; #endif default: assert(0 && "bad store kind for TLV optimization"); } } else { // change target to be new TLV pointer atom if (log) fprintf(stderr, "updating load of TLV to %s to load from TLV pointer\n", it->targetOfTLV->name()); const ld::Atom* tlvpAtom = variableToPointerMap[it->targetOfTLV]; assert(tlvpAtom != NULL); it->fixupWithTarget->binding = ld::Fixup::bindingDirectlyBound; it->fixupWithTarget->u.target = tlvpAtom; } } // alter tlv definitions to have an offset as third field for (std::vector<ld::Internal::FinalSection*>::iterator sit=internal.sections.begin(); sit != internal.sections.end(); ++sit) { ld::Internal::FinalSection* sect = *sit; if ( sect->type() != ld::Section::typeTLVDefs ) continue; for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) { const ld::Atom* atom = *ait; for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) { if ( fit->offsetInAtom != 0 ) { assert(fit->binding == ld::Fixup::bindingDirectlyBound && "thread variable def contains pointer to global"); switch( fit->u.target->contentType() ) { case ld::Atom::typeTLVZeroFill: case ld::Atom::typeTLVInitialValue: switch ( fit->kind ) { case ld::Fixup::kindSetTargetAddress: fit->kind = ld::Fixup::kindSetTargetTLVTemplateOffset; break; case ld::Fixup::kindStoreTargetAddressLittleEndian32: fit->kind = ld::Fixup::kindSetTargetTLVTemplateOffsetLittleEndian32; break; case ld::Fixup::kindStoreTargetAddressLittleEndian64: fit->kind = ld::Fixup::kindSetTargetTLVTemplateOffsetLittleEndian64; break; default: assert(0 && "bad kind for target in tlv defs"); break; } break; default: assert(0 && "wrong content type for target in tlv defs"); break; } } } } } }
void IMGDock::setup(System& receptor, System& ligand, Options& input_options) { ligand_ = ligand.getMolecule(0); receptor_ = receptor.getProtein(0); name_ = "Iterative Multi-Greedy Docking"; Options* option_category = input_options.getSubcategory(ScoringFunction::SUBCATEGORY_NAME); if (!option_category) option_category = &input_options; parameter_filename_ = option_category->get("filename"); option_category = input_options.getSubcategory("IMGDock"); if (!option_category) option_category = &input_options; // == == set the input_options == == == == // global_rotation_ = option_category->setDefaultBool(Option::GLOBAL_ROTATION, Default::GLOBAL_ROTATION); step_width_ = option_category->setDefaultInteger(Option::STEP_WIDTH, Default::STEP_WIDTH); no_solutions_ = option_category->setDefaultInteger(Option::NO_SOLUTIONS, Default::NO_SOLUTIONS); post_optimization_step_width_ = option_category->setDefaultReal(Option::POST_OPTIMIZATION_STEP_WIDTH, Default::POST_OPTIMIZATION_STEP_WIDTH); post_optimization_steps_ = option_category->setDefaultInteger(Option::POST_OPTIMIZATION_STEPS, Default::POST_OPTIMIZATION_STEPS); min_inhibitor_atoms_ = option_category->setDefaultInteger(Option::MIN_INHIBITOR_ATOMS, Default::MIN_INHIBITOR_ATOMS); scoring_type_ = option_category->setDefault(Option::SCORING_TYPE, Default::SCORING_TYPE); iterations_ = option_category->setDefaultInteger(Option::ITERATIONS, Default::ITERATIONS); decrease_stepwidth_ = option_category->setDefaultBool(Option::DECREASE_STEPWIDTH, Default::DECREASE_STEPWIDTH); superpose_ligand_ = option_category->setDefaultBool(Option::SUPERPOSE_LIGAND, Default::SUPERPOSE_LIGAND); // == == == == == == == == == == == == == // if (scoring_type_ == "MM") { scoring_function_ = new MMScoring(*receptor_, *ligand_, input_options); } else if (scoring_type_ == "GridedMM") { scoring_function_ = new GridedMM(*receptor_, *ligand_, input_options); } else if (scoring_type_ == "GridedPLP") { scoring_function_ = new GridedPLP(*receptor_, *ligand_, input_options); } else if (scoring_type_ == "PLP") { scoring_function_ = new PLPScoring(*receptor_, *ligand_, input_options); } else { String mess="ScoringFunction type \'"+scoring_type_+"\' unknown/unsupported!"; throw Exception::GeneralException(__FILE__, __LINE__, "IMGDock error", mess); } if (scoring_function_->getStaticLigandFragments()->size() == 0) { // do only if not already by ScoringFunction (depended on input_options) scoring_function_->createStaticLigandFragments(); } saveBondInformation(); ReferenceArea* rf = new ReferenceArea(ligand_, 0, min_inhibitor_atoms_, 1e10); rf->setName("reference ligand area"); scoring_function_->constraints.push_back(rf); reference_center_ = scoring_function_->getLigandCenter(); sidechain_optimizer_ = NULL; if (scoring_function_->hasFlexibleResidues()) { sidechain_optimizer_ = new SideChainOptimizer(scoring_function_); } }
void checkOptions(Options& opts, int argc, char* argv[]) { opts.define("p|pause=d:2.0", "Pause given number of secs after each file"); opts.define("a|ascii=b", "Display MIDI output as ASCII text"); opts.define("author=b", "author of program"); opts.define("version=b", "compilation info"); opts.define("example=b", "example usages"); opts.define("h|help=b", "short description"); opts.process(argc, argv); // handle basic options: if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "[email protected], 16 October 2012" << endl; exit(0); } else if (opts.getBoolean("version")) { cout << argv[0] << ", version: October 2012" << endl; cout << "compiled: " << __DATE__ << endl; exit(0); } else if (opts.getBoolean("help")) { usage(opts.getCommand().data()); exit(0); } else if (opts.getBoolean("example")) { example(); exit(0); } if (opts.getArgCount() <= 1) { usage(opts.getCommand().data()); exit(1); } seconds = opts.getDouble("pause"); binaryQ = !opts.getBoolean("ascii"); }
void PipelineReaderJSON::parsePipeline(Json::Value& tree) { TagMap tags; std::vector<Stage*> inputs; Json::ArrayIndex last = tree.size() - 1; for (Json::ArrayIndex i = 0; i < tree.size(); ++i) { Json::Value& node = tree[i]; std::string filename; std::string tag; std::string type; std::vector<Stage*> specifiedInputs; Options options; // strings are assumed to be filenames if (node.isString()) { filename = node.asString(); } else { type = extractType(node); filename = extractFilename(node); tag = extractTag(node, tags); specifiedInputs = extractInputs(node, tags); if (!specifiedInputs.empty()) inputs = specifiedInputs; options = extractOptions(node); } Stage *s = nullptr; // The type is inferred from a filename as a reader if it's not // the last stage or if there's only one. if ((type.empty() && (i == 0 || i != last)) || Utils::startsWith(type, "readers.")) { StringList files = FileUtils::glob(filename); if (files.empty()) files.push_back(filename); for (const std::string& path : files) { StageCreationOptions ops { path, type, nullptr, options, tag }; s = &m_manager.makeReader(ops); if (specifiedInputs.size()) throw pdal_error("JSON pipeline: Inputs not permitted for " " reader: '" + path + "'."); inputs.push_back(s); } } else if (type.empty() || Utils::startsWith(type, "writers.")) { StageCreationOptions ops { filename, type, nullptr, options, tag }; s = &m_manager.makeWriter(ops); for (Stage *ts : inputs) s->setInput(*ts); inputs.clear(); } else { if (filename.size()) options.add("filename", filename); StageCreationOptions ops { "", type, nullptr, options, tag }; s = &m_manager.makeFilter(ops); for (Stage *ts : inputs) s->setInput(*ts); inputs.clear(); inputs.push_back(s); } // 's' should be valid at this point. makeXXX will throw if the stage // couldn't be constructed. if (tag.size()) tags[tag] = s; } }
MetricBias::MetricBias(const Options& iOptions, const Data& iData) : MetricBasic(iOptions, iData) { iOptions.check(); }
void compute(const Options& option){ // Get Visu Mesh and its vertex coordinates // cout << "## Reference Mesh" << endl << flush; Mesh visuMsh(option.getValue("-ref")[1]); fullMatrix<double> point; GroupOfElement visuGoe = visuMsh.getFromPhysical(7); visuGoe.getAllVertexCoordinate(point); // Get FEM Orders // const size_t nOrder = option.getValue("-o").size() - 1; vector<int> order(nOrder); for(size_t i = 0; i < nOrder; i++) order[i] = atoi(option.getValue("-o")[i + 1].c_str()); // Get FEM Meshes // const size_t nMesh = option.getValue("-msh").size() - 1; vector<string> mesh(nMesh); for(size_t i = 0; i < nMesh; i++) mesh[i] = option.getValue("-msh")[i + 1]; // Post Processing ? // bool nopos; try{ option.getValue("-nopos"); nopos = 1; } catch(Exception& ex){ nopos = 0; } // Scalar or Vector // bool isScalar = (option.getValue("-type")[1].compare("scalar") == 0); // Real Solutions // cout << "## Real Solution" << endl << flush; fullMatrix<double> realSol; if(isScalar) ana(fScal, point, realSol); else ana(fVect, point, realSol); // FEM Solution & L2 Error // cout << "## FEM Solutions" << endl << flush; fullMatrix<double> femSol; fullMatrix<double> l2(nOrder, nMesh); // Iterate on Meshes for(size_t i = 0; i < nMesh; i++){ cout << " ** Mesh: " << mesh[i] << endl << flush; Mesh msh(mesh[i]); GroupOfElement domain = msh.getFromPhysical(7); // Iterate on Orders for(size_t j = 0; j < nOrder; j++){ cout << " -- Order " << order[j] << ": " << flush; if(isScalar) fem(fScal, domain, order[j], point, femSol, nopos); else fem(fVect, domain, order[j], point, femSol, nopos); l2(j, i) = l2Error(femSol, realSol); cout << l2(j, i) << endl; } } // Display // cout << "## L2 Error" << endl << flush; write(isScalar, l2, option.getValue("-name")[1]); }
int skipIt(int sector, int instrument, int channel) { extern Options Opt; extern ImagerDoc imagerDoc; extern SounderDoc sounderDoc; int skip = TRUE; int i0,i1, s0, s1, c0, c1; int xstart=0, ystart=0, xend=0, yend=0, curr_hr=0, visCounts=0; if(instrument == ALL) { i0 = 0; i1 = sounder ; } else { i0 = instrument; i1 = instrument ; } for (int i=i0; i<=i1 && skip; i++){ if (sector==ALL) { s0 = 0; s1 = Opt.sectors(i); } else { s0 = sector; s1 = sector+1; } if (channel==ALL) { c0 = 0; c1 = N_Channels[i]; } else { c0 = channel; c1 = channel+1; } for(int s=s0; s<s1 && skip ; s++){ for(int c=c0; c<c1 && skip; c++){ if (i==imager) { xstart=imagerDoc.W_pix_of_frame; ystart=imagerDoc.N_line_of_frame; xend =imagerDoc.E_pix_of_frame; yend =imagerDoc.S_line_of_frame; curr_hr = imagerDoc.T_sps_current.hrs(); visCounts = IDETECTORS * imagerDoc.abs_scan_count; } else if (i==sounder){ xstart=sounderDoc.W_pix_of_frame; ystart=sounderDoc.N_line_of_frame; xend =sounderDoc.E_pix_of_frame; yend =sounderDoc.S_line_of_frame; curr_hr = sounderDoc.T_sps_current.hrs(); visCounts = SDETECTORS * sounderDoc.abs_scan_count; } if( (VALID(Opt.xstart(s,i,c),xstart) < xend ) && (VALID(Opt.ystart(s,i,c),ystart) < yend ) && (VALID(Opt.xend(s,i,c), xend) >= xstart ) && (VALID(Opt.yend(s,i,c), yend) >= ystart ) && (VALID(Opt.yend(s,i,c), yend) > visCounts ) && (Opt.wordType(s,i,c) != Undef ) ) skip = FALSE; if(skip == FALSE && Opt.area(s,i,c)) { float Area = (xend-xstart)*(yend-ystart)/ 1.0E6; if(Opt.area(s,i,c) < 0 ) { if(Area > -1.0* Opt.area(s,i,c) ) skip = TRUE; } else if ( Area < Opt.area(s,i,c) ) skip = TRUE; } if(skip==FALSE){ int h0 = Opt.gmtHoursStart(s,i,c); int h1 = Opt.gmtHoursStop(s,i,c); if (h1 > h0) {if ((curr_hr > h1 || curr_hr < h0 )) skip = TRUE; } else if (h1 < h0) {if ((curr_hr > h1 && curr_hr < h0 )) skip = TRUE; } } } } } return(skip); }
void QfitReader::processOptions(const Options& ops) { m_flip_x = ops.getValueOrDefault("flip_coordinates", true); m_scale_z = ops.getValueOrDefault("scale_z", 0.001); }
void checkOptions(Options& opts, int argc, char* argv[]) { opts.define("page|full|p=b", "print a full page instead of just table"); opts.define("textarea|ta|t=b", "print data in a textarea after main table"); opts.define("author=b", "author of program"); opts.define("version=b", "compilation info"); opts.define("example=b", "example usages"); opts.define("h|help=b", "short description"); opts.process(argc, argv); // handle basic options: if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "[email protected], March 2011" << endl; exit(0); } else if (opts.getBoolean("version")) { cout << argv[0] << ", version: March 2011" << endl; cout << "compiled: " << __DATE__ << endl; cout << MUSEINFO_VERSION << endl; exit(0); } else if (opts.getBoolean("help")) { usage(opts.getCommand()); exit(0); } else if (opts.getBoolean("example")) { example(); exit(0); } fullQ = opts.getBoolean("page"); textareaQ = opts.getBoolean("textarea"); }
Dialog::~Dialog() { delete ui; opts.Save(); }
main(int argc, char **argv){ try { if (argc==1) usage(); Options O = parse_options(&argc, &argv, options, MASK_INP, "out"); if (O.exists("help")) usage(); Options GO(O); // global options vmap::world V; while (!O.exists("out")) { if (argc<1){ if (O.get<int>("verbose",0)) cout << "no output files\n"; exit(0); } const char * ifile = argv[0]; // parse options for this file and append global options O = parse_options(&argc, &argv, options, MASK_INP, "out"); O.insert(GO.begin(), GO.end()); if (O.exists("set_source_from_fname")) O.put<string>("set_source", ifile); if (O.get<int>("verbose",0)) cout << "reading: " << ifile << "\n"; vmap::world V1 = vmap::read(ifile); filter(V1, O); V.add(V1); } /***************** output ****************/ const char * ofile = NULL; if (argc<1){ if (O.get<int>("verbose",0)) cout << "no output files\n"; } else ofile = argv[0]; // parse output options O = parse_options(&argc, &argv, options, MASK_OUT); /***************** write file ****************/ if (O.exists("legend")) V = vmap::make_legend(O.get("legend", string())); if (O.exists("set_source_from_fname")) O.put<string>("set_source", ofile); // OPTION remove_dups // OPTION remove_empty // OPTION join_objects double remove_dups_acc=O.get("remove_dups", 0.0); if (remove_dups_acc>0) remove_dups(V, remove_dups_acc); double join_objects_acc=O.get("join_objects", 0.0); if (join_objects_acc>0) join_objects(V, join_objects_acc); // remove empty objects if (O.get<int>("remove_empty", 0)) remove_empty(V); // find labels for each object if (O.get<int>("join_labels", 1)) join_labels(V); // create new labels if (O.get<int>("create_labels", 1)) create_labels(V); // move and rotate pics if (O.get<int>("move_pics", 1)) move_pics(V); filter(V, O); if (ofile){ if (GO.get<int>("verbose",0)) cout << "writing to: " << ofile << "\n"; if (!vmap::write(ofile, V, O)) exit(1); } exit(0); } catch (const char *err){ cerr << "ERROR: " << err << "\n"; exit(1); } }
void processOptions(Options& opts, int argc, char** argv) { opts.process(argc, argv); }
/* -------------------------------------------------------------------------------------------- * See whether the options container is empty or not. */ bool OptionsEmpty() const { return m_Options.empty(); }