bool OBMoleculeFormat::ReadChemObjectImpl(OBConversion* pConv, OBFormat* pFormat) { std::istream &ifs = *pConv->GetInStream(); if (!ifs.good()) //Possible to omit? ifs.peek() == EOF || return false; OBMol* pmol = new OBMol; std::string auditMsg = "OpenBabel::Read molecule "; std::string description(pFormat->Description()); auditMsg += description.substr(0,description.find('\n')); obErrorLog.ThrowError(__FUNCTION__, auditMsg, obAuditMsg); if(pConv->IsOption("C",OBConversion::GENOPTIONS)) return DeferMolOutput(pmol, pConv, pFormat); bool ret; if(pConv->IsOption("separate",OBConversion::GENOPTIONS)) { //On first call, separate molecule and put fragments in MolArray. //On subsequent calls, remove a fragment from MolArray and send it for writing //Done this way so that each fragment can be written to its own file (with -m option) if(!StoredMolsReady) { ret = pFormat->ReadMolecule(pmol,pConv); if(ret && (pmol->NumAtoms() > 0 || (pFormat->Flags()&ZEROATOMSOK))) MolArray = pmol->Separate(); //use un-transformed molecule //Add an appropriate title to each fragment for(int i=0;i<MolArray.size();++i) { stringstream ss; ss << pmol->GetTitle() << '#' << i+1; string title = ss.str(); MolArray[i].SetTitle(title); } reverse(MolArray.begin(),MolArray.end()); StoredMolsReady = true; //Clear the flags of the input stream(which may have found eof) to ensure will //try to read anothe molecule and allow the stored ones to be sent for output. pConv->GetInStream()->clear(); } if(MolArray.empty()) //normal end of fragments ret =false; else { // Copying is needed because the OBMol passed to AddChemObject will be deleted. // The OBMol in the vector is deleted here. OBMol* pMolCopy = new OBMol( MolArray.back()); MolArray.pop_back(); ret = pConv->AddChemObject( pMolCopy->DoTransformations(pConv->GetOptions(OBConversion::GENOPTIONS)))!=0; } if(!ret) StoredMolsReady = false; delete pmol; return ret; } ret=pFormat->ReadMolecule(pmol,pConv); OBMol* ptmol = NULL; //Molecule is valid if it has some atoms //or the format allows zero-atom molecules and it has a title if(ret && (pmol->NumAtoms() > 0 || (pFormat->Flags()&ZEROATOMSOK && *pmol->GetTitle()))) { ptmol = static_cast<OBMol*>(pmol->DoTransformations(pConv->GetOptions(OBConversion::GENOPTIONS))); if(ptmol && (pConv->IsOption("j",OBConversion::GENOPTIONS) || pConv->IsOption("join",OBConversion::GENOPTIONS))) { //With j option, accumulate all mols in one stored in this class if(pConv->IsFirstInput()) _jmol = new OBMol; pConv->AddChemObject(_jmol); //will be discarded in WriteChemObjectImpl until the last input mol. This complication //is needed to allow joined molecules to be from different files. pOb1 in AddChem Object //is zeroed at the end of a file and _jmol is in danger of not being output. *_jmol += *ptmol; delete ptmol; return true; } } else delete pmol; // Normal operation - send molecule to be written ret = ret && (pConv->AddChemObject(ptmol)!=0); //success of both writing and reading return ret; }
static JSValueRef getDescriptionCallback(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) { JSRetainPtr<JSStringRef> description(Adopt, toAXElement(thisObject)->description()); return JSValueMakeString(context, description.get()); }
LinearAdv2D::LinearAdv2D(const std::string& name) : VariablesT<LinearAdv2D>(name) { description().set_variables("U",MODEL::_ndim); }
// Entry Point int main(int argc, char* argv[]) { bool verbose = false; std::vector<std::string> material_fields; std::string output_path = kDefaultOutputName; double scale = kDefaultScale; double lipschitz = kDefaultLipschitz; double multiplier = kDefaultMultiplier; int padding = kDefaultPadding; //------------------------------- // Parse Command Line Params //------------------------------- try{ po::options_description description("Command line flags"); description.add_options() ("help,h", "display help message") ("verbose,v", "enable verbose output") ("version", "display version information") ("material_fields", po::value<std::vector<std::string> >()->multitoken(), "material field paths") ("grading", po::value<double>(&lipschitz)->default_value(kDefaultLipschitz, kDefaultLipschitzString), "sizing field grading") ("multiplier", po::value<double>(&multiplier)->default_value(kDefaultMultiplier), "sizing field multiplier") ("scale", po::value<double>(&scale)->default_value(kDefaultScale), "sizing field scale") ("output", po::value<std::string>()->default_value(kDefaultOutputName, "sizingfield"), "output path") ("padding", po::value<int>()->default_value(kDefaultPadding), "padding") ; boost::program_options::variables_map variables_map; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, description), variables_map); boost::program_options::notify(variables_map); // print version info if (variables_map.count("version")) { std::cout << cleaver::Version << std::endl; return 0; } // print help else if (variables_map.count("help") || (argc ==1)) { std::cout << description << std::endl; return 0; } // enable verbose mode if (variables_map.count("verbose")) { verbose = true; } // parse the material field input file names if (variables_map.count("material_fields")) { material_fields = variables_map["material_fields"].as<std::vector<std::string> >(); int file_count = material_fields.size(); } else{ std::cout << "Error: At least one material field file must be specified." << std::endl; return 0; } // set output path if (variables_map.count("output")) { output_path = variables_map["output"].as<std::string>(); } } catch (std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 0; } catch(...) { std::cerr << "Unhandled exception caught. Terminating." << std::endl; return 0; } //----------------------------------- // Load Data & Construct Volume //----------------------------------- std::cout << " Loading input fields:" << std::endl; for (size_t i=0; i < material_fields.size(); i++) { std::cout << " - " << material_fields[i] << std::endl; } std::vector<cleaver::AbstractScalarField*> fields = NRRDTools::loadNRRDFiles(material_fields); if(fields.empty()){ std::cerr << "Failed to load image data. Terminating." << std::endl; return 0; } else if(fields.size() == 1) { fields.push_back(new cleaver::InverseScalarField(fields[0])); } cleaver::Volume *volume = new cleaver::Volume(fields); //------------------------------------------------------------ // Construct Sizing Field //------------------------------------------------------------ cleaver::FloatField *sizingField = cleaver::SizingFieldCreator::createSizingFieldFromVolume( volume, (float)(1.0/lipschitz), (float)scale, (float)multiplier, (int)padding, false); //------------------------------------------------------------ // Write Field to File //------------------------------------------------------------ std::cout << " Writing sizing field to file: " << output_path << ".nrrd" << std::endl; // todo(jrb) strip path NRRDTools::saveNRRDFile(sizingField, output_path); // done std::cout << " Done." << std::endl; return 0; }
void SwapClaimsMsg::cancelMessage(char const *reason) { dprintf(D_ALWAYS,"Canceling swap claims request for claim %s %s\n", description(),reason ? reason : ""); DCMsg::cancelMessage(reason); }
int main( int argc, char* argv[] ) { int resultCode = EXIT_SUCCESS; std::string input; std::string output; unsigned int iterations; boost::program_options::options_description description( "Allowed options" ); description.add_options() ( "help,h", "display this help" ) ( "input,i", boost::program_options::value< std::string >( &input ), "input model file" ) ( "output,o", boost::program_options::value< std::string >( &output ), "output model file" ) ( "iterations,n", boost::program_options::value< unsigned int >( &iterations ), "number of iterations" ) ; try { boost::program_options::variables_map variables; boost::program_options::store( boost::program_options::command_line_parser( argc, argv ).options( description ).run(), variables ); boost::program_options::notify( variables ); if ( variables.count( "help" ) ) { std::cout << "Optimizes the SVM problem contained in the input model file, saving the result" << std::endl << "to the output model file. Optimization will continue until the maximum number" << std::endl << "of iterations has been exceeded." << std::endl << std::endl << description << std::endl; } else { if ( ! variables.count( "input" ) ) throw std::runtime_error( "You must provide an input file" ); if ( ! variables.count( "output" ) ) throw std::runtime_error( "You must provide an output file" ); if ( ! variables.count( "iterations" ) ) throw std::runtime_error( "You must provide an iterations parameter" ); boost::shared_ptr< SVM::Optimizer::Base > pOptimizer; { std::ifstream inputFile( input.c_str(), std::ios::in | std::ios::binary ); if ( inputFile.fail() ) throw std::runtime_error( "Unable to open input file" ); boost::iostreams::filtering_streambuf< boost::iostreams::input > inputStream; inputStream.push( inputFile ); boost::archive::binary_iarchive inputArchive( inputStream ); inputArchive >> pOptimizer; } Random::Generator::LaggedFibonacci4<> generator; { Random::Generator::LinearCongruential<> seedGenerator; seedGenerator.Seed(); generator.Seed( seedGenerator ); } for ( unsigned int ii = 0; ii < iterations; ++ii ){ pOptimizer->Iterate( generator ); //std::cout << "1 IT" << std::endl; } { std::ofstream outputFile( output.c_str(), std::ios::out | std::ios::binary | std::ios::trunc ); if ( outputFile.fail() ) throw std::runtime_error( "Unable to open output file" ); boost::iostreams::filtering_streambuf< boost::iostreams::output > outputStream; outputStream.push( outputFile ); boost::archive::binary_oarchive outputArchive( outputStream ); outputArchive << pOptimizer; } pOptimizer->WriteSupport(output+"-SupportSet.txt"); } } catch( std::exception& error ) { std::cerr << "Error: " << error.what() << std::endl << std::endl << description << std::endl; resultCode = EXIT_FAILURE; } return resultCode; }
int main(int argc, char* argv[]) { try { unsigned int size; double wait_after_connect = 0.0; std::size_t hwm; std::string server; boost::program_options::options_description description( "options" ); description.add_options() ( "help,h", "display help message; --help --verbose for more help" ) ( "publish", "use bind and publish (as opposed to connect and subscribe)" ) ( "connect", "use connect instead of bind" ) ( "bind", "use bind instead of connect" ) ( "request", "request/reply client" ) ( "reply", "request/reply server" ) ( "size,s", boost::program_options::value< unsigned int >( &size ), "packet size in bytes, in publish, request, or reply mode; if not present, data is line-based ascii" ) ( "buffer,b", boost::program_options::value< std::size_t >( &hwm )->default_value( 1024 ), "set buffer size in packets (high water mark in zmq)" ) ( "server", boost::program_options::value< std::string >( &server ), "in subscribe mode, republish the data on a socket, eg tcp:1234" ) ( "wait-after-connect,conwait", boost::program_options::value< double >( &wait_after_connect ), "time to wait, in seconds, after initial connection before attempting to read or write" ) ( "quiet-interrupt", "suppress error messages due to interrupt" ) ( "verbose,v", "more output" ); boost::program_options::variables_map vm; boost::program_options::store( boost::program_options::parse_command_line( argc, argv, description), vm ); boost::program_options::parsed_options parsed = boost::program_options::command_line_parser(argc, argv).options( description ).allow_unregistered().run(); boost::program_options::notify( vm ); if( vm.count( "help" ) ) { usage( description, !vm.count( "verbose" ) ); return 0; } const std::vector< std::string >& endpoints = boost::program_options::collect_unrecognized( parsed.options, boost::program_options::include_positional ); if( endpoints.empty() ) { std::cerr << "zero-cat: please provide at least one endpoint" << std::endl; return 1; } bool binary = vm.count( "size" ); quiet_interrupt = vm.count( "quiet-interrupt" ); comma::signal_flag is_shutdown; zmq::context_t context( 1 ); const bool is_request = vm.count( "request" ); const bool is_reply = vm.count( "reply" ); const bool is_publisher = bool( vm.count( "publish" ) ); if( is_request + is_reply + is_publisher > 1 ) { std::cerr << "zero-cat: expected only one of: --publisher, --request, --reply; got " << ( is_request + is_reply + is_publisher ) << std::endl; return 1; } if( is_request || is_reply ) { #ifdef WIN32 if( binary ) { _setmode( _fileno( stdin ), _O_BINARY ); _setmode( _fileno( stdout ), _O_BINARY ); } #endif zmq::socket_t socket( context, is_request ? ZMQ_REQ : ZMQ_REP ); #if ZMQ_VERSION_MAJOR == 2 socket.setsockopt( ZMQ_HWM, &hwm, sizeof( hwm ) ); #endif if( endpoints.size() != 1 ) { std::cerr << "zero-cat: request/reply server/client expected 1 endpoint, got " << endpoints.size() << ": " << comma::join( endpoints, ',' ) << std::endl; return 1; } if( is_request || vm.count( "connect" ) ) { socket.connect( &endpoints[0][0] ); } else if( is_reply || vm.count( "bind" ) ) { socket.bind( &endpoints[0][0] ); } if( is_request ) { std::string buffer; if( binary ) { buffer.resize( size ); } while( !is_shutdown && std::cin.good() ) { if( binary ) { std::cin.read( &buffer[0], size ); int count = std::cin.gcount(); if( count == 0 ) { break; } if( count < int( size ) ) { std::cerr << "zero-cat: expected " << size << " byte(s), got: " << count << std::endl; return 1; } } else { std::getline( std::cin, buffer ); if( buffer.empty() ) { break; } buffer += endl; } zmq::message_t request( buffer.size() ); ::memcpy( ( void * )request.data(), &buffer[0], buffer.size() ); #if ZMQ_VERSION_MAJOR == 2 if( !socket.send( request ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #else // ZMQ_VERSION_MAJOR == 2 if( !socket.send( &buffer[0], buffer.size() ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #endif // ZMQ_VERSION_MAJOR == 2 zmq::message_t reply; if( !socket.recv( &reply ) ) { break; } std::cout.write( reinterpret_cast< const char* >( reply.data() ), reply.size() ); if( binary ) { std::cout.flush(); } } } else { std::string buffer; if( binary ) { buffer.resize( size ); } while( !is_shutdown && std::cin.good() ) { zmq::message_t request; if( !socket.recv( &request ) ) { break; } std::cout.write( reinterpret_cast< const char* >( request.data() ), request.size() ); if( binary ) { std::cout.flush(); } if( binary ) { std::cin.read( &buffer[0], size ); int count = std::cin.gcount(); if( count == 0 ) { break; } if( count < int( size ) ) { std::cerr << "zero-cat: expected " << size << " byte(s), got: " << count << std::endl; return 1; } } else { std::getline( std::cin, buffer ); if( buffer.empty() ) { break; } buffer += endl; } zmq::message_t reply( buffer.size() ); ::memcpy( ( void * )reply.data(), &buffer[0], buffer.size() ); #if ZMQ_VERSION_MAJOR == 2 if( !socket.send( reply ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #else // ZMQ_VERSION_MAJOR == 2 if( !socket.send( &buffer[0], buffer.size() ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #endif // ZMQ_VERSION_MAJOR == 2 } } return 0; } int mode = is_publisher ? ZMQ_PUB : ZMQ_SUB; zmq::socket_t socket( context, mode ); #ifdef WIN32 if( is_publisher && binary ) { _setmode( _fileno( stdin ), _O_BINARY ); } #endif // Although the documentation says that HWM is supported in ZMQ4, the // code shows that if the sock opt is HWM an exception will be thrown. #if ZMQ_VERSION_MAJOR == 2 socket.setsockopt( ZMQ_HWM, &hwm, sizeof( hwm ) ); #endif if( is_publisher ) { bool output_to_stdout = false; for( unsigned int i = 0; i < endpoints.size(); i++ ) { if( endpoints[i] == "-" ) { output_to_stdout = true; } else if( vm.count( "connect" ) ) { socket.connect( endpoints[i].c_str() ); } else { socket.bind( &endpoints[i][0] ); } } // we convert to milliseconds as converting to second floors the number so 0.99 becomes 0 if( wait_after_connect > 0 ) { boost::this_thread::sleep(boost::posix_time::milliseconds(wait_after_connect * 1000.0)); } std::string buffer; if( binary ) { buffer.resize( size ); } while( !is_shutdown && std::cin.good() && !std::cin.eof() && !std::cin.bad() ) { if( binary ) { std::cin.read( &buffer[0], buffer.size() ); int count = std::cin.gcount(); if( count <= 0 ) { break; } buffer.resize( std::size_t( count ) ); } else { std::getline( std::cin, buffer ); if( !is_shutdown && std::cin.good() && !std::cin.eof() && !std::cin.bad() ) { buffer += endl; } } if( buffer.empty() ) { break; } #if ZMQ_VERSION_MAJOR == 2 zmq::message_t message( buffer.size() ); ::memcpy( ( void * )message.data(), &buffer[0], buffer.size() ); if( !socket.send( message ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #else // ZMQ_VERSION_MAJOR == 2 if( !socket.send( &buffer[0], buffer.size() ) ) { std::cerr << "zero-cat: failed to send " << buffer.size() << " bytes; zmq errno: EAGAIN" << std::endl; return 1; } #endif // ZMQ_VERSION_MAJOR == 2 if( !output_to_stdout ) { continue; } std::cout.write( &buffer[0], buffer.size() ); if( binary ) { std::cout.flush(); } } } else { for( unsigned int i = 0; i < endpoints.size(); i++ ) { if( vm.count( "bind" ) ) { socket.bind( endpoints[i].c_str() ); } else { socket.connect( endpoints[i].c_str() ); } } socket.setsockopt( ZMQ_SUBSCRIBE, "", 0 ); if( wait_after_connect > 0 ) { boost::this_thread::sleep( boost::posix_time::milliseconds( wait_after_connect * 1000.0 ) ); } if( vm.count( "server" ) ) { comma::io::publisher publisher( server, comma::io::mode::binary, true, false ); while( !is_shutdown ) { zmq::message_t message; socket.recv( &message ); publisher.write( reinterpret_cast< const char* >( message.data() ), message.size() ); } } else { while( !is_shutdown && std::cout.good() ) { zmq::message_t message; socket.recv( &message ); std::cout.write( reinterpret_cast< const char* >( message.data() ), message.size() ); if( binary ) { std::cout.flush(); } } } } return 0; } catch ( zmq::error_t& e ) { if( !quiet_interrupt || e.num() != EINTR ) { std::cerr << argv[0] << ": zeromq error: (" << e.num() << ") " << e.what() << std::endl; } } catch ( std::exception& e ) { std::cerr << argv[0] << ": " << e.what() << std::endl; } catch ( ... ) { std::cerr << argv[0] << ": unknown exception" << std::endl; } return 1; }
static gboolean wxgtk_webview_webkit_error(WebKitWebView*, WebKitWebFrame*, gchar *uri, gpointer web_error, wxWebViewWebKit* webKitWindow) { webKitWindow->m_busy = false; wxWebViewNavigationError type = wxWEB_NAV_ERR_OTHER; GError* error = (GError*)web_error; wxString description(error->message, wxConvUTF8); if (strcmp(g_quark_to_string(error->domain), "soup_http_error_quark") == 0) { switch (error->code) { case SOUP_STATUS_CANCELLED: type = wxWEB_NAV_ERR_USER_CANCELLED; break; case SOUP_STATUS_CANT_RESOLVE: case SOUP_STATUS_NOT_FOUND: type = wxWEB_NAV_ERR_NOT_FOUND; break; case SOUP_STATUS_CANT_RESOLVE_PROXY: case SOUP_STATUS_CANT_CONNECT: case SOUP_STATUS_CANT_CONNECT_PROXY: case SOUP_STATUS_SSL_FAILED: case SOUP_STATUS_IO_ERROR: type = wxWEB_NAV_ERR_CONNECTION; break; case SOUP_STATUS_MALFORMED: //case SOUP_STATUS_TOO_MANY_REDIRECTS: type = wxWEB_NAV_ERR_REQUEST; break; //case SOUP_STATUS_NO_CONTENT: //case SOUP_STATUS_RESET_CONTENT: case SOUP_STATUS_BAD_REQUEST: type = wxWEB_NAV_ERR_REQUEST; break; case SOUP_STATUS_UNAUTHORIZED: case SOUP_STATUS_FORBIDDEN: type = wxWEB_NAV_ERR_AUTH; break; case SOUP_STATUS_METHOD_NOT_ALLOWED: case SOUP_STATUS_NOT_ACCEPTABLE: type = wxWEB_NAV_ERR_SECURITY; break; case SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED: type = wxWEB_NAV_ERR_AUTH; break; case SOUP_STATUS_REQUEST_TIMEOUT: type = wxWEB_NAV_ERR_CONNECTION; break; //case SOUP_STATUS_PAYMENT_REQUIRED: case SOUP_STATUS_REQUEST_ENTITY_TOO_LARGE: case SOUP_STATUS_REQUEST_URI_TOO_LONG: case SOUP_STATUS_UNSUPPORTED_MEDIA_TYPE: type = wxWEB_NAV_ERR_REQUEST; break; case SOUP_STATUS_BAD_GATEWAY: case SOUP_STATUS_SERVICE_UNAVAILABLE: case SOUP_STATUS_GATEWAY_TIMEOUT: type = wxWEB_NAV_ERR_CONNECTION; break; case SOUP_STATUS_HTTP_VERSION_NOT_SUPPORTED: type = wxWEB_NAV_ERR_REQUEST; break; //case SOUP_STATUS_INSUFFICIENT_STORAGE: //case SOUP_STATUS_NOT_EXTENDED: } } else if (strcmp(g_quark_to_string(error->domain), "webkit-network-error-quark") == 0) { switch (error->code) { //WEBKIT_NETWORK_ERROR_FAILED: //WEBKIT_NETWORK_ERROR_TRANSPORT: case WEBKIT_NETWORK_ERROR_UNKNOWN_PROTOCOL: type = wxWEB_NAV_ERR_REQUEST; break; case WEBKIT_NETWORK_ERROR_CANCELLED: type = wxWEB_NAV_ERR_USER_CANCELLED; break; case WEBKIT_NETWORK_ERROR_FILE_DOES_NOT_EXIST: type = wxWEB_NAV_ERR_NOT_FOUND; break; } } else if (strcmp(g_quark_to_string(error->domain), "webkit-policy-error-quark") == 0) { switch (error->code) { //case WEBKIT_POLICY_ERROR_FAILED: //case WEBKIT_POLICY_ERROR_CANNOT_SHOW_MIME_TYPE: //case WEBKIT_POLICY_ERROR_CANNOT_SHOW_URL: //case WEBKIT_POLICY_ERROR_FRAME_LOAD_INTERRUPTED_BY_POLICY_CHANGE: case WEBKIT_POLICY_ERROR_CANNOT_USE_RESTRICTED_PORT: type = wxWEB_NAV_ERR_SECURITY; break; } } /* webkit_plugin_error_quark else { printf("Error domain %s\n", g_quark_to_string(error->domain)); } */ wxWebViewEvent event(wxEVT_COMMAND_WEB_VIEW_ERROR, webKitWindow->GetId(), uri, ""); event.SetString(description); event.SetInt(type); if (webKitWindow && webKitWindow->GetEventHandler()) { webKitWindow->GetEventHandler()->ProcessEvent(event); } return FALSE; }
int ndnsec_get_default(int argc, char** argv) { namespace po = boost::program_options; bool wantDefaultKey = false; bool wantDefaultCert = false; bool isQuiet = false; Name identityName; Name keyName; po::options_description description( "Usage: ndnsec get-default [-h] [-k|-c] [-i ID|-K KEY] [-q]\n" "\n" "Options"); description.add_options() ("help,h", "produce help message") ("default-key,k", po::bool_switch(&wantDefaultKey), "show default key, instead of identity") ("default-cert,c", po::bool_switch(&wantDefaultCert), "show default certificate, instead of identity") ("identity,i", po::value<Name>(&identityName), "target identity") ("key,K", po::value<Name>(&keyName), "target key") ("quiet,q", po::bool_switch(&isQuiet), "do not print trailing newline") ; po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, description), vm); po::notify(vm); } catch (const std::exception& e) { std::cerr << "ERROR: " << e.what() << "\n\n" << description << std::endl; return 2; } if (vm.count("help") > 0) { std::cout << description << std::endl; return 0; } if (wantDefaultKey && wantDefaultCert) { std::cerr << "ERROR: cannot specify both '--default-key' and '--default-cert'" << std::endl; return 2; } if (vm.count("identity") && vm.count("key")) { std::cerr << "ERROR: cannot specify both '--identity' and '--key'" << std::endl; return 2; } security::v2::KeyChain keyChain; if (vm.count("key") > 0) { if (wantDefaultCert) { auto cert = keyChain.getPib() .getIdentity(security::v2::extractIdentityFromKeyName(keyName)) .getKey(keyName) .getDefaultCertificate(); std::cout << cert.getName(); if (!isQuiet) { std::cout << std::endl; } return 0; } return 2; } else if (vm.count("identity") > 0) { auto key = keyChain.getPib() .getIdentity(identityName) .getDefaultKey(); if (wantDefaultKey) { std::cout << key.getName(); if (!isQuiet) std::cout << std::endl; return 0; } if (wantDefaultCert) { std::cout << key.getDefaultCertificate().getName(); if (!isQuiet) std::cout << std::endl; return 0; } return 2; } else { auto identity = keyChain.getPib() .getDefaultIdentity(); if (wantDefaultKey) { std::cout << identity.getDefaultKey().getName(); } else if (wantDefaultCert) { std::cout << identity.getDefaultKey().getDefaultCertificate().getName(); } else { std::cout << identity.getName(); } if (!isQuiet) std::cout << std::endl; return 0; } }
int main(int argc, char** argv) { try { namespace po = boost::program_options; po::options_description description("=== intersects ===\nAllowed options"); int width_x = 7; int count = 1; int count_x = 10; int count_y = 10; bool ccw = false; bool open = false; p_q_settings settings; description.add_options() ("help", "Help message") ("count", po::value<int>(&count)->default_value(1), "Number of tests") ("count_x", po::value<int>(&count_x)->default_value(10), "Triangle count in x-direction") ("count_y", po::value<int>(&count_y)->default_value(10), "Triangle count in y-direction") ("width_x", po::value<int>(&width_x)->default_value(7), "Width of triangle in x-direction") ("ccw", po::value<bool>(&ccw)->default_value(false), "Counter clockwise polygons") ("open", po::value<bool>(&open)->default_value(false), "Open polygons") ("wkt", po::value<bool>(&settings.wkt)->default_value(false), "Create a WKT of the inputs, for all tests") ("svg", po::value<bool>(&settings.svg)->default_value(false), "Create a SVG for all tests") ; po::variables_map varmap; po::store(po::parse_command_line(argc, argv, description), varmap); po::notify(varmap); if (varmap.count("help")) { std::cout << description << std::endl; return 1; } if (ccw && open) { test_all<double, false, false>(count, count_x, count_y, width_x, settings); } else if (ccw) { test_all<double, false, true>(count, count_x, count_y, width_x, settings); } else if (open) { test_all<double, true, false>(count, count_x, count_y, width_x, settings); } else { test_all<double, true, true>(count, count_x, count_y, width_x, settings); } #if defined(HAVE_TTMATH) // test_all<ttmath_big, true, true>(seed, count, max, svg, level); #endif } catch(std::exception const& e) { std::cout << "Exception " << e.what() << std::endl; } catch(...) { std::cout << "Other exception" << std::endl; } return 0; }
void Kopete::Transfer::emitCopying(const KUrl &src, const KUrl &dest) { emit description(this, i18n("Copying"), qMakePair(i18n("Source"), src.prettyUrl()), qMakePair(i18n("Destination"), dest.prettyUrl())); }
bool FastSearchFormat::WriteChemObject(OBConversion* pConv) { //Prepares or updates an index file. Called for each molecule indexed bool update = pConv->IsOption("u")!=NULL; static ostream* pOs; static bool NewOstreamUsed; if(fsi==NULL) { //First pass sets up FastSearchIndexer object pOs = pConv->GetOutStream();// with named index it is already open NewOstreamUsed=false; string mes("prepare an"); if(update) mes = "update the"; clog << "This will " << mes << " index of " << pConv->GetInFilename() << " and may take some time..." << flush; if(!pConv->IsLastFile()) { obErrorLog.ThrowError(__FUNCTION__, "There should not be multiple input files. A .fs file is an index of a single datafile.", obError); return false; } std::string auditMsg = "OpenBabel::Write fastsearch index "; std::string description(Description()); auditMsg += description.substr( 0, description.find('\n') ); obErrorLog.ThrowError(__FUNCTION__,auditMsg,obAuditMsg); FptIndex* pidx=NULL; //used with update //if(pOs==&cout) did not work with GUI if(!dynamic_cast<ofstream*>(pOs)) { //No index filename specified //Derive index name from datafile name string indexname=pConv->GetInFilename(); string::size_type pos=indexname.find_last_of('.'); if(pos!=string::npos) indexname.erase(pos); indexname += ".fs"; bool idxok=true; if(update) { LastSeekpos = 0; //Read in existing index idxok=false; ifstream ifs(indexname.c_str(),ifstream::binary); if(ifs.good()) { pidx = new FptIndex; idxok = pidx->Read(&ifs); } }//ifs closed here pOs = new ofstream(indexname.c_str(),ofstream::binary); if(!pOs->good() || !idxok) { stringstream errorMsg; errorMsg << "Trouble opening or reading " << indexname << endl; obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError); static_cast<ofstream *>(pOs)->close(); // close the file before quitting delete pOs; delete pidx; // remove possible memory leak return false; } NewOstreamUsed=true; } else // not cout { if(update) { obErrorLog.ThrowError(__FUNCTION__, "Currently, updating is only done on index files that" "have the same name as the datafile.\n" "Do not specify an output file; use the form:\n" " babel datafile.xxx -ofs -xu", obError); return false; } } int nbits = 0; const char* p = pConv->IsOption("N"); if(p) nbits = atoi(p); string fpid; //fingerprint type p=pConv->IsOption("f"); if(p) fpid=p; //Prepare name without path string datafilename = pConv->GetInFilename(); if(datafilename.empty()) { obErrorLog.ThrowError(__FUNCTION__, "No datafile!", obError); return false; } string::size_type pos = datafilename.find_last_of("/\\"); if(pos!=string::npos) datafilename=datafilename.substr(pos+1); nmols = pConv->NumInputObjects(); if(nmols>0) clog << "\nIt contains " << nmols << " molecules" << flush; if(nmols>500000) { istream* is = pConv->GetInStream(); streampos origpos = is->tellg(); is->seekg(0,ios_base::end); long long filesize = is->tellg(); if(filesize > 4294967295u) { obErrorLog.ThrowError(__FUNCTION__, "The datafile must not be larger than 4GB", obError); return false; } is->seekg(origpos); } sw.Start(); if(update) { fsi = new FastSearchIndexer(pidx, pOs, nmols);//using existing index //Seek to position in datafile of last of old objects LastSeekpos = *(pidx->seekdata.end()-1); pConv->GetInStream()->seekg(LastSeekpos); } else fsi = new FastSearchIndexer(datafilename, pOs, fpid, nbits, nmols); obErrorLog.StopLogging(); } //All passes provide an object for indexing OBBase* pOb = pConv->GetChemObject(); OBMol* pmol = dynamic_cast<OBMol*> (pOb); if(pmol) pmol->ConvertDativeBonds();//use standard form for dative bonds streampos seekpos = pConv->GetInPos(); if(!update || seekpos>LastSeekpos) { fsi->Add(pOb, seekpos ); if(pConv->GetOutputIndex()==400 && nmols>1000) { clog << " Estimated completion time "; double secs = sw.Elapsed() * nmols / 400; // streamsize op = clog.precision(0); if(secs>150) clog << secs/60 << " minutes" << endl; else clog << secs << " seconds" << endl; clog.precision(op); } } else //Don't index old objects during update. Don't increment pConv->Index. pConv->SetOutputIndex(pConv->GetOutputIndex()-1); if(pConv->IsLast()) { //Last pass delete fsi; //saves index file if(NewOstreamUsed) delete pOs; //return to starting conditions fsi=NULL; obErrorLog.StartLogging(); double secs = sw.Elapsed(); if(secs>150) clog << "\n It took " << secs/60 << " minutes" << endl; else clog << "\n It took " << secs << " seconds" << endl; } delete pOb; return true; }
bool FastSearchFormat::ReadChemObject(OBConversion* pConv) { //Searches index file for structural matches //This function is called only once per search std::string auditMsg = "OpenBabel::Read fastsearch index "; std::string description(Description()); auditMsg += description.substr(0,description.find('\n')); obErrorLog.ThrowError(__FUNCTION__, auditMsg, obAuditMsg); //Derive index name string indexname = pConv->GetInFilename(); string::size_type pos=indexname.find_last_of('.'); if(pos!=string::npos) { indexname.erase(pos); indexname += ".fs"; } //Have to open input stream again because needs to be in binary mode ifstream ifs; stringstream errorMsg; if(!indexname.empty()) ifs.open(indexname.c_str(),ios::binary); if(!ifs) { errorMsg << "Couldn't open " << indexname << endl; obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError); return false; } string datafilename = fs.ReadIndex(&ifs); if(datafilename.empty()) { errorMsg << "Difficulty reading from index " << indexname << endl; obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError); return false; } vector<OBMol> patternMols; if(!ObtainTarget(pConv, patternMols, indexname)) return false; bool exactmatch = pConv->IsOption("e",OBConversion::INOPTIONS)!=NULL;// -ae option //Open the datafile and put it in pConv //datafile name derived from index file probably won't have a file path //but indexname may. Derive a full datafile name string path; pos = indexname.find_last_of("/\\"); if(pos==string::npos) path = datafilename; else path = indexname.substr(0,pos+1) + datafilename; ifstream datastream(path.c_str()); if(!datastream) { errorMsg << "Difficulty opening " << path << endl; obErrorLog.ThrowError(__FUNCTION__, errorMsg.str(), obError); return false; } pConv->SetInStream(&datastream); //Input format is currently fs; set it appropriately if(!pConv->SetInAndOutFormats(pConv->FormatFromExt(datafilename.c_str()),pConv->GetOutFormat())) return false; // If target has dative bonds like -[N+](=O)[O-] convert it to the uncharged form // (-N(=O)=O and add uncharged form to vector of mols which are sent to // the -s (SMARTS)filter. // Also check whether the target has dative bonds in the uncharged form and supply // the charged form to the -s filter. // Together with the automatic conversion to the uncharged form when the fs index is made, // this ensures that both forms are found however they occur in the datafile or the taget. vector<OBBase*> extraSMARTSMols; vector<OBMol>extraUnchargedMols; for(unsigned i=0;i<patternMols.size();++i) { if(patternMols[i].ConvertDativeBonds()) extraSMARTSMols.push_back(&patternMols[i]); else { // If target has uncharged dative bonds, still use it for fastsearching, // but add the charged form for -s filter. extraUnchargedMols.push_back(patternMols[i]); if(extraUnchargedMols.back().MakeDativeBonds()) extraSMARTSMols.push_back(&extraUnchargedMols.back()); } } OBOp* sFilter = OBOp::FindType("s"); if(sFilter) sFilter->ProcessVec(extraSMARTSMols); //Now do searching const char* p = pConv->IsOption("t",OBConversion::INOPTIONS); if(p) { //Do a similarity search multimap<double, unsigned int> SeekposMap; string txt=p; if(txt.find('.')==string::npos) { //Finds n molecules with largest Tanimoto int n = atoi(p); fs.FindSimilar(&patternMols[0], SeekposMap, n); } else { //Finds molecules with Tanimoto > MinTani double MaxTani = 1.1; size_t pos = txt.find(','); if( pos != string::npos ) { MaxTani = atof( txt.substr( pos + 1 ).c_str() ); } double MinTani = atof( txt.substr( 0, pos ).c_str() ); fs.FindSimilar(&patternMols[0], SeekposMap, MinTani, MaxTani); } //Don't want to filter through SMARTS filter pConv->RemoveOption("s", OBConversion::GENOPTIONS); //also because op names are case independent pConv->RemoveOption("S", OBConversion::GENOPTIONS); multimap<double, unsigned int>::reverse_iterator itr; for(itr=SeekposMap.rbegin();itr!=SeekposMap.rend();++itr) { datastream.seekg(itr->second); if(pConv->IsOption("a", OBConversion::INOPTIONS)) { //Adds Tanimoto coeff to title //First remove any previous value pConv->RemoveOption("addtotitle", OBConversion::GENOPTIONS); stringstream ss; ss << " " << itr->first; pConv->AddOption("addtotitle",OBConversion::GENOPTIONS, ss.str().c_str()); } pConv->SetOneObjectOnly(); if(itr != --SeekposMap.rend()) pConv->SetMoreFilesToCome();//so that not seen as last on output pConv->Convert(NULL,NULL); } } else { //Structure search int MaxCandidates = 4000; p = pConv->IsOption("l",OBConversion::INOPTIONS); if(p && atoi(p)) MaxCandidates = atoi(p); vector<unsigned int> SeekPositions; if(exactmatch) { //Find mols where all fingerprint bits are the same as the target fs.FindMatch(&patternMols[0], SeekPositions, MaxCandidates); // ensure that SMARTS filter in transform.cpp looks only for an exact match // by setting an option with the number of heavy atoms in the pattern mol included. stringstream ss; ss << patternMols[0].NumHvyAtoms(); pConv->AddOption("exactmatch", OBConversion::GENOPTIONS, ss.str().c_str()); } else { //Do a substructure search for each target vector<OBMol>::iterator iter; for(iter=patternMols.begin();iter!=patternMols.end();++iter) fs.Find(&*iter, SeekPositions, MaxCandidates); clog << SeekPositions.size() << " candidates from fingerprint search phase" << endl; } vector<unsigned int>::iterator seekitr, begin = SeekPositions.begin(), end = SeekPositions.end(); if(patternMols.size()>1)//only sort and eliminate duplicates if necessary { sort(begin, end); end = unique(begin, end); //removed duplicates are after new end } //Output the candidate molecules, filtering through s filter, unless it was not requested if(pConv->IsOption("n", OBConversion::INOPTIONS) ) pConv->RemoveOption("s",OBConversion::GENOPTIONS); pConv->SetLast(false); for(seekitr=begin; seekitr!=end; ++seekitr) { datastream.seekg(*seekitr); if(!pConv->GetInFormat()->ReadChemObject(pConv)) return false; pConv->SetFirstInput(false); //needed for OpSort } } return false; //To finish }
const t_string& editor_name() const { return editor_name_.empty() ? description() : editor_name_; }
int main( int argc, char* argv[] ) { int resultCode = EXIT_SUCCESS; std::string dataset; std::string input; std::string output; bool smallClusters; unsigned int activeClusters; boost::program_options::options_description description( "Allowed options" ); description.add_options() ( "help,h", "display this help" ) ( "file,f", boost::program_options::value< std::string >( &dataset ), "dataset file (SVM-Light format)" ) ( "input,i", boost::program_options::value< std::string >( &input ), "input model file" ) ( "output,o", boost::program_options::value< std::string >( &output ), "output text file" ) ( "small_clusters,s", boost::program_options::value< bool >( &smallClusters )->default_value( false ), "use size-16 instead of size-256 clusters?" ) ( "active_clusters,a", boost::program_options::value< unsigned int >( &activeClusters )->default_value( 64 ), "number of \"active\" clusters" ) ; try { boost::program_options::variables_map variables; boost::program_options::store( boost::program_options::command_line_parser( argc, argv ).options( description ).run(), variables ); boost::program_options::notify( variables ); if ( variables.count( "help" ) ) { std::cout << "Classifies a dataset (in SVM-Light format). For binary classifiers, the result" << std::endl << "is saved to a text file containing one floating-point number per line: the" << std::endl << "value of the classification function applied the corresponding testing vector" << std::endl << "(the signs of these numbers are the classifications). For multiclass" << std::endl << "classifiers, each line of the output file contains a comma-separated list of" << std::endl << "values of the classification functions of the classes, applied to the" << std::endl << "corresponding testing vector (the index of the largest of these is the" << std::endl << "classification)." << std::endl << std::endl << "This implementation handles sparsity using a greedy clustering approach. The" << std::endl << "small_clusters parameter indicates the size of the clusters: 16 (small) or 256" << std::endl << "(not small). Generally, size-256 clusters will give significantly better" << std::endl << "performance. The active_clusters parameter is the number of clusters which will" << std::endl << "be active at every point in the greedy clustering algorithm. We have found that" << std::endl << "64 works well, but increasing this number will improve the quality of the" << std::endl << "clustering (at the cost of more time being required to find it)." << std::endl << std::endl << description << std::endl; } else { if ( ! variables.count( "file" ) ) throw std::runtime_error( "You must provide a dataset file" ); if ( ! variables.count( "input" ) ) throw std::runtime_error( "You must provide an input file" ); if ( ! variables.count( "output" ) ) throw std::runtime_error( "You must provide an output file" ); // load the dataset file unsigned int rows = 0; unsigned int columns = 0; std::vector< float > values; std::vector< size_t > indices; std::vector< size_t > offsets; { unsigned int const bufferSize = ( 1u << 24 ); boost::shared_array< char > buffer( new char[ bufferSize ] ); const boost::regex spaceRegex( "[[:space:]]+" ); const boost::regex elementRegex( "^[[:space:]]*([[:digit:]]+):(-?[[:digit:]]+(\\.[[:digit:]]+)?([eE]-?[[:digit:]]+)?)[[:space:]]*$" ); offsets.push_back( 0 ); std::ifstream file( dataset.c_str() ); if ( file.fail() ) throw std::runtime_error( "Unable to open dataset file" ); while ( ! file.eof() ) { file.getline( buffer.get(), bufferSize ); if ( file.fail() ) break; std::string lineString( buffer.get() ); boost::sregex_token_iterator ii( lineString.begin(), lineString.end(), spaceRegex, -1 ); boost::sregex_token_iterator iiEnd; if ( ii != iiEnd ) { // ignore blank lines std::string const signString = ii->str(); if ( ii == iiEnd ) throw std::runtime_error( "Failed to parse first element of dataset line" ); // we don't care about the value of the label, since we're classifying int lastIndex = -1; for ( ++ii; ii != iiEnd; ++ii ) { std::string const elementString = ii->str(); boost::smatch elementMatch; if ( ! boost::regex_match( elementString, elementMatch, elementRegex, boost::match_extra ) ) throw std::runtime_error( "Failed to parse element of dataset line" ); std::string const indexString = elementMatch[ 1 ].str(); int index = atoi( indexString.c_str() ); std::string const valueString = elementMatch[ 2 ].str(); float const value = static_cast< float >( atof( valueString.c_str() ) ); if ( index < 0 ) throw std::runtime_error( "Failed to parse element of dataset line: negative index encountered" ); if ( index <= lastIndex ) throw std::runtime_error( "Failed to parse element of dataset line: features must be listed in order of increasing index" ); lastIndex = index; if ( value != 0 ) { values.push_back( value ); indices.push_back( index ); if ( index + 1 > static_cast< int >( columns ) ) columns = index + 1; } } BOOST_ASSERT( values.size() == indices.size() ); offsets.push_back( values.size() ); } } file.close(); rows = offsets.size() - 1; } AutoContext context; if ( GTSVM_Load( context, input.c_str(), false, 1 ) ) { throw std::runtime_error( GTSVM_Error() ); } if ( GTSVM_Shrink( context, smallClusters, activeClusters ) ) { throw std::runtime_error( GTSVM_Error() ); } unsigned int classes; if ( GTSVM_GetClasses( context, &classes ) ) { throw std::runtime_error( GTSVM_Error() ); } boost::shared_array< double > result( new double[ rows * classes ] ); if ( GTSVM_ClassifySparse( context, result.get(), GTSVM_TYPE_DOUBLE, &values[ 0 ], &indices[ 0 ], &offsets[ 0 ], GTSVM_TYPE_FLOAT, rows, columns, false ) ) { throw std::runtime_error( GTSVM_Error() ); } { std::ofstream file( output.c_str() ); if ( file.fail() ) throw std::runtime_error( "Unable to open output file" ); for ( unsigned int ii = 0; ii < rows; ++ii ) { file << result[ ii * classes + 0 ]; for ( unsigned int jj = 1; jj < classes; ++jj ) file << ", " << result[ ii * classes + jj ]; file << std::endl; } file.close(); } } } catch( std::exception& error ) { std::cerr << "Error: " << error.what() << std::endl << std::endl << description << std::endl; resultCode = EXIT_FAILURE; } return resultCode; }
//+---------------------------------------------------------------------------- // // method : SimulatorCCDClass::write_class_property // // description : Set class description as property in database // //----------------------------------------------------------------------------- void SimulatorCCDClass::write_class_property() { // First time, check if database used //-------------------------------------------- if (Tango::Util::_UseDb == false) return; Tango::DbData data; string classname = get_name(); string header; string::size_type start, end; // Put title Tango::DbDatum title("ProjectTitle"); string str_title(""); title << str_title; data.push_back(title); // Put Description Tango::DbDatum description("Description"); vector<string> str_desc; str_desc.push_back(" "); description << str_desc; data.push_back(description); // put cvs or svn location string filename(classname); filename += "Class.cpp"; // Create a string with the class ID to // get the string into the binary string class_id(ClassId); // check for cvs information string src_path(CvsPath); start = src_path.find("/"); if (start!=string::npos) { end = src_path.find(filename); if (end>start) { string strloc = src_path.substr(start, end-start); // Check if specific repository start = strloc.find("/cvsroot/"); if (start!=string::npos && start>0) { string repository = strloc.substr(0, start); if (repository.find("/segfs/")!=string::npos) strloc = "ESRF:" + strloc.substr(start, strloc.length()-start); } Tango::DbDatum cvs_loc("cvs_location"); cvs_loc << strloc; data.push_back(cvs_loc); } } // check for svn information else { string src_path(SvnPath); start = src_path.find("://"); if (start!=string::npos) { end = src_path.find(filename); if (end>start) { header = "$HeadURL: "; start = header.length(); string strloc = src_path.substr(start, (end-start)); Tango::DbDatum svn_loc("svn_location"); svn_loc << strloc; data.push_back(svn_loc); } } } // Get CVS or SVN revision tag // CVS tag string tagname(TagName); header = "$Name: "; start = header.length(); string endstr(" $"); end = tagname.find(endstr); if (end!=string::npos && end>start) { string strtag = tagname.substr(start, end-start); Tango::DbDatum cvs_tag("cvs_tag"); cvs_tag << strtag; data.push_back(cvs_tag); } // SVN tag string svnpath(SvnPath); header = "$HeadURL: "; start = header.length(); end = svnpath.find(endstr); if (end!=string::npos && end>start) { string strloc = svnpath.substr(start, end-start); string tagstr ("/tags/"); start = strloc.find(tagstr); if ( start!=string::npos ) { start = start + tagstr.length(); end = strloc.find(filename); string strtag = strloc.substr(start, end-start-1); Tango::DbDatum svn_tag("svn_tag"); svn_tag << strtag; data.push_back(svn_tag); } } // Get URL location string httpServ(HttpServer); if (httpServ.length()>0) { Tango::DbDatum db_doc_url("doc_url"); db_doc_url << httpServ; data.push_back(db_doc_url); } // Put inheritance Tango::DbDatum inher_datum("InheritedFrom"); vector<string> inheritance; inheritance.push_back("Device_4Impl"); inher_datum << inheritance; data.push_back(inher_datum); // Call database and and values //-------------------------------------------- get_db_class()->put_property(data); }
int main(int argc, char ** argv) { int status = EXIT_FAILURE; try { avatar::AppEnvironment env(argc, argv); avatar::cmdline_utils::Parser cmdlineParser; std::unique_ptr<avatar::RiftApp> app; auto cmdlineParserResult = cmdlineParser.parseOptions(); switch (cmdlineParserResult.first) { case avatar::cmdline_utils::Parser::Status::LaunchColorCubeDemo: { std::wcout << L"Info >> description: launching color cube demo" << std::endl; app.reset(new avatar::ColorCubeApp); } break; case avatar::cmdline_utils::Parser::Status::LaunchTextureCubeDemo: { std::wcout << L"Info >> description: launching texture cube demo" << std::endl; app.reset(new avatar::TexCubeApp); } break; case avatar::cmdline_utils::Parser::Status::LaunchMonoWebcamDemo: { std::wcout << L"Info >> description: launching mono webcam demo" << std::endl; app.reset(new avatar::WebcamMonoApp); } break; case avatar::cmdline_utils::Parser::Status::LaunchStereoWebcamDemo: { std::wcout << L"Info >> description: launching stereo webcam demo" << std::endl; app.reset(new avatar::WebcamStereoApp); } break; case avatar::cmdline_utils::Parser::Status::LaunchClientDemo: { QString const serverAddressString = cmdlineParser.value(avatar::cmdline_utils::launchClientDemo); QHostAddress serverAddress(serverAddressString); std::wcout << L"Info >> description: launching client demo with server IP address " << serverAddressString.toStdWString() << std::endl; app.reset(new avatar::VideoStreamClientApp(serverAddress)); } break; case avatar::cmdline_utils::Parser::Status::LaunchServerDemo: { std::wcout << L"Info >> description: launching server demo" << std::endl; app.reset(new avatar::VideoStreamServerApp); } break; case avatar::cmdline_utils::Parser::Status::LaunchFirstPersonViewDemo: { std::wcout << L"Info >> description: launching FPV demo" << std::endl; // // Find arduino serial port. // QList<QSerialPortInfo> const ports = QSerialPortInfo::availablePorts(); QList<QSerialPortInfo>::const_iterator arduinoPort = ports.cend(); for (auto it = ports.cbegin(); it != ports.cend(); ++it) { QString const description = it->description(); if (description.contains("arduino", Qt::CaseInsensitive)) { arduinoPort = it; break; } } if (arduinoPort == ports.cend()) { std::wcout << L"Error >> description: failed to find arduino serial port" << std::endl; return EXIT_FAILURE; } // // Find a webcam. // auto const cameras = QCameraInfo::availableCameras(); if (cameras.empty()) { std::wcout << L"Error >> description: failed to find webcam devices" << std::endl; return EXIT_FAILURE; } // // Setup both the interpreter for the arduino port and the camera. // auto commandInterpreter = avatar::FirstPersonViewSerialCli::create(*arduinoPort, QSerialPort::Baud115200, QByteArray("Servo>"), 50); auto imageSystem = avatar::ImageSystem::create(std::make_unique<avatar::WebcamImageReader>(cameras[0]), std::make_unique<avatar::WebcamImageProcessor>()); app.reset(new avatar::FirstPersonViewApp(std::move(commandInterpreter), std::move(imageSystem))); } break; case avatar::cmdline_utils::Parser::Status::ShowHelp: { cmdlineParser.showHelp(EXIT_SUCCESS); // showHelp() will exit the application } break; case avatar::cmdline_utils::Parser::Status::Error: { std::wcout << cmdlineParserResult.second.toStdWString() << std::endl; cmdlineParser.showHelp(EXIT_FAILURE); // showHelp() will exit the application } break; default: { Q_ASSERT(false); cmdlineParser.showHelp(EXIT_FAILURE); // showHelp() will exit the application } } app->show(); status = env.exec(); } catch (avatar::Exception const & e) { std::wcout << e.what().toStdWString() << std::endl; } return status; }
int main( int argc, char* argv[] ) { std::cout << "\nImporting FACETRACER Data from Annotation Tool into SQLite3 DB " << std::endl; //----------------- program options po::positional_options_description pod; pod.add("sqldb-file",1); pod.add("imgdbname",1); pod.add("imgfolder",1); pod.add("faceindex-file",1); pod.add("facestats-file",1); pod.add("facelabel-file",1); pod.add("attribute-file",1); pod.add("clear-sqldb",1); po::options_description description("Options"); description.add_options() ("help", "produce help message") ("sqldb-file", po::value< string >(), "sql database file") ("imgdbname", po::value< string >(), "image database name") ("image-folder", po::value< string >(), "image folder") ("faceindex-file", po::value< string >(), "faceindex file (../faceindex.txt)") ("facestats-file", po::value< string >(), "facestats file (../facestats.txt)") ("facelabel-file", po::value< string >(), "facelabel file (../facelabel.txt)") ("attribute-file", po::value< string >(), "attribute file (../attribute.txt)") ("clear-sqldb", po::value< string >(), "optinal: clear sql database (default: false)") ; po::variables_map variablesMap; try { po::store(po::command_line_parser(argc, argv).options(description).positional(pod).run(), variablesMap); po::notify(variablesMap); } catch ( const boost::program_options::error& e ) { std::cerr << e.what() << std::endl; } bool showHelp = false; string sqlDBFile; if (variablesMap.count("sqldb-file")) sqlDBFile = variablesMap["sqldb-file"].as<string>(); else showHelp = true; string imgDBName; if (variablesMap.count("imgdbname")) imgDBName = variablesMap["imgdbname"].as<string>(); else showHelp = true; string imgFolder; if (variablesMap.count("image-folder")) imgFolder = variablesMap["image-folder"].as<string>(); else showHelp = true; string faceindexFile; if (variablesMap.count("faceindex-file")) faceindexFile = variablesMap["faceindex-file"].as<string>(); else showHelp = true; string facestatsFile; if (variablesMap.count("facestats-file")) facestatsFile = variablesMap["facestats-file"].as<string>(); else showHelp = true; string facelabelFile; if (variablesMap.count("facelabel-file")) facelabelFile = variablesMap["facelabel-file"].as<string>(); else showHelp = true; string attributeFile; if (variablesMap.count("attribute-file")) attributeFile = variablesMap["attribute-file"].as<string>(); else showHelp = true; string clearSqlDB; if (variablesMap.count("clear-sqldb")) clearSqlDB = variablesMap["clear-sqldb"].as<string>(); else clearSqlDB = "false"; if (variablesMap.count("help") || showHelp) { cout << description << "\n"; return 1; } std::string basePath = ""; std::cout << "-------------------------------------------------------" << std::endl; std::cout << " Config:" << std::endl; std::cout << " SQL DB Name: " << sqlDBFile << std::endl; std::cout << " Image DB Name: " << imgDBName << std::endl; std::cout << " Image Folder: " << imgFolder << std::endl; std::cout << " FaceIndex File: " << faceindexFile << std::endl; std::cout << " FaceStats File: " << facestatsFile << std::endl; std::cout << " FaceLabel File: " << facelabelFile << std::endl; std::cout << " Attribute File: " << attributeFile << std::endl; std::cout << " Optional: clear SqlDB -> " << clearSqlDB << std::endl; std::cout << " Base Path: " << basePath << std::endl; std::cout << "-------------------------------------------------------" << std::endl; //------------------ DELETE db entries from sql database if (clearSqlDB.compare("true") == 0) { cout << " \nCLEAR Sql Database " << endl; DeleteSqlEntries dsde; dsde.deleteAllSqlEntries(sqlDBFile); return 0; } else { std::cout << " \nADD data to Sql Database" << std::endl; std::string::size_type pos = sqlDBFile.find_last_of("\\/"); if (pos != std::string::npos) { basePath = sqlDBFile.substr(0,pos+1); } } //------------------ INSERT dbname INTO sql database DeleteSqlEntries dnsf; bool deleted = false; deleted = dnsf.deleteDBName(sqlDBFile, imgDBName); if (deleted == true) { dnsf.insertDBName(sqlDBFile, imgDBName); } // get all *jpg files in img file folder ImagesFromFolder iff; PathVector paths = iff.getImagesFromFolder(imgFolder, ".JPG"); if (paths.empty()) { std::cout << " FACETRACERIMPORTER -> Folderpath '" << imgFolder << "' is empty! " << std::endl; } else { iff.printFoundFiles(paths); bool available = true; for (unsigned int n = 0; n < paths.size(); ++n) { // extract faceId from path int faceId = utils::convertToInt(paths.at(n).stem().string()); FaceTracerFileReader faceTracerFileReader; std::string faceindexFileName = faceindexFile; available = faceTracerFileReader.loadFaceindex(faceId, faceindexFileName, imgFolder); std::string facestatsFileName = facestatsFile; available = faceTracerFileReader.loadFacestats(faceId, facestatsFileName); std::string facelabelFileName = facelabelFile; available = faceTracerFileReader.loadFacelabel(faceId, facelabelFileName); // faceTracerFileReader.printFaceTracerData(); // Draw landmarks to image. //faceTracerFileReader.drawFacestats(faceId); if (available == false) { std::cout << "facetrace_import::main() data for faceId('" << faceId << "') missing." << std::endl; break; } //------------------ INSERT INTO sql db SQLiteDBConnection sqlConn; if (sqlConn.open(sqlDBFile)) { int annotTypeID_FACETRACER = getAnnotTypeID(&sqlConn); // get the feature IDs from the database - matching the feature codes from the input file FeatureCoordTypes fct; fct.load(&sqlConn); //fct.debugPrint(); vector<int> featIDs; for (int i = 0; i < FaceTracerFileData::numFeaturesFileFeatureCodes; ++i) { string featCode = FaceTracerFileData::featuresFileFeatureCodes[i]; int featID = fct.getIDByCode(featCode); if (featID < 0) std::cout << "Error: No ID for feature '" << featCode << "'" << std::endl; else { featIDs.push_back(featID); } } string insertFaceSqlStmtStr = "INSERT INTO Faces(file_id,db_id) VALUES (?1,?2)"; SQLiteStmt *insertFaceSqlStmt = sqlConn.prepare(insertFaceSqlStmtStr); string insertFeatureCoordsSqlStmtStr = "INSERT INTO FeatureCoords(face_id,feature_id,x,y) VALUES (?1, ?2, ?3, ?4)"; SQLiteStmt *insertFeatureCoordsSqlStmt = sqlConn.prepare(insertFeatureCoordsSqlStmtStr); string insertImageSqlStmtStr = "INSERT INTO FaceImages(db_id,file_id,filepath,bw,width,height) VALUES (?1, ?2, ?3, ?4, ?5, ?6)"; SQLiteStmt *insertImageSqlStmt = sqlConn.prepare(insertImageSqlStmtStr); string insertPoseSqlStmtStr = "INSERT INTO FacePose(face_id,roll,pitch,yaw,annot_type_id) VALUES (?1, ?2, ?3, ?4, ?5)"; SQLiteStmt *insertPoseSqlStmt = sqlConn.prepare(insertPoseSqlStmtStr); string insertMetaDataSqlStmtStr = "INSERT INTO FaceMetadata(face_id,sex,occluded,glasses,bw,annot_type_id) VALUES (?1, ?2, ?3, ?4, ?5, ?6)"; SQLiteStmt *insertMetaDataSqlStmt = sqlConn.prepare(insertMetaDataSqlStmtStr); bool allOK = true; if (insertFaceSqlStmt && insertFeatureCoordsSqlStmt) { sqlConn.exec("PRAGMA synchronous = OFF;"); sqlConn.exec("BEGIN TRANSACTION;"); std::map<int, FaceTracerFileData>::iterator faceTracerIt = faceTracerFileReader.m_faceTracerDataMap.begin(); vector<std::pair<double, double> >::iterator facestatsIt = faceTracerIt->second.facestats.begin(); std::string fileName = faceTracerIt->second.faceIdFilename; insertFaceSqlStmt->reset(); insertFaceSqlStmt->bind(1,fileName); insertFaceSqlStmt->bind(2,imgDBName); allOK = allOK && (sqlConn.step(insertFaceSqlStmt) == SQLITE_DONE); if (!allOK) { break; } // get database id of inserted face int dbFaceId = sqlConn.getLastInsertRowid(); // insert image std::string filePath = (boost::filesystem::path(faceTracerIt->second.imageFoldername) / boost::filesystem::path(faceTracerIt->second.faceIdFilename)).string(); cv::Mat img = cv::imread(filePath, -1); if (!img.data) { std::cout << "Could not load image: " << filePath.c_str() << std::endl; allOK = false; } else { std::string relativeFilePath = ""; if (filePath.size() > imgFolder.size()) { relativeFilePath = filePath.substr(imgFolder.size()+1); } //db_id,file_id,filepath,bw,width,height insertImageSqlStmt->bind(1,imgDBName); insertImageSqlStmt->bind(2,fileName); insertImageSqlStmt->bind(3,relativeFilePath); insertImageSqlStmt->bind(4,img.channels() == 1); insertImageSqlStmt->bind(5,img.cols); insertImageSqlStmt->bind(6,img.rows); allOK = allOK && (sqlConn.step(insertImageSqlStmt) == SQLITE_DONE); if (!allOK) { break; } insertImageSqlStmt->reset(); } // insert features insertFeatureCoordsSqlStmt->bind(1,dbFaceId); for (unsigned int i = 0 ; facestatsIt != faceTracerIt->second.facestats.end(); ++facestatsIt, ++i) { if ( (facestatsIt->first > 0) && (facestatsIt->second > 0) ) { if (i >= featIDs.size()) { allOK = false; } if ((facestatsIt->first >= img.cols) || (facestatsIt->second >= img.rows)) { allOK = false; } insertFeatureCoordsSqlStmt->bind(2,featIDs[i]); insertFeatureCoordsSqlStmt->bind(3,static_cast<float>(facestatsIt->first)); insertFeatureCoordsSqlStmt->bind(4,static_cast<float>(facestatsIt->second)); allOK = allOK && (sqlConn.step(insertFeatureCoordsSqlStmt) == SQLITE_DONE); if (!allOK) { break; } insertFeatureCoordsSqlStmt->reset(); } } // insert pose insertPoseSqlStmt->reset(); insertPoseSqlStmt->bind(1,dbFaceId); insertPoseSqlStmt->bind(2,faceTracerIt->second.roll); insertPoseSqlStmt->bind(3,faceTracerIt->second.pitch); insertPoseSqlStmt->bind(4,faceTracerIt->second.yaw); insertPoseSqlStmt->bind(5,annotTypeID_FACETRACER); allOK = allOK && (sqlConn.step(insertPoseSqlStmt) == SQLITE_DONE); if (!allOK) { // break; } //// insert meta data //insertMetaDataSqlStmt->reset(); //insertMetaDataSqlStmt->bind(1,dbFaceId); //insertMetaDataSqlStmt->bind(2,faceTracerIt->second.sex); //insertMetaDataSqlStmt->bind(3,faceTracerIt->second.occluded); //insertMetaDataSqlStmt->bind(4,faceTracerIt->second.glasses); //insertMetaDataSqlStmt->bind(5,faceTracerIt->second.bw); //insertMetaDataSqlStmt->bind(6,annotTypeID_FACETRACER); //allOK = allOK && (sqlConn.step(insertMetaDataSqlStmt) == SQLITE_DONE); //if (!allOK) { // // break; //} if (allOK) { sqlConn.exec("COMMIT;"); std::cout << "Reading ... Inserting... File: '" << faceId << "' into Database" << std::endl; } else { sqlConn.exec("ROLLBACK TRANSACTION;"); } sqlConn.exec("PRAGMA synchronous = NORMAL;"); sqlConn.finalize(insertFaceSqlStmt); delete insertFaceSqlStmt; sqlConn.finalize(insertFeatureCoordsSqlStmt); delete insertFeatureCoordsSqlStmt; sqlConn.finalize(insertPoseSqlStmt); delete insertPoseSqlStmt; sqlConn.finalize(insertMetaDataSqlStmt); delete insertMetaDataSqlStmt; } sqlConn.close(); } else { std::cout << "failed to open sql db file ('" << sqlDBFile << "')" << std::endl; } } } std::cout << "done." << std::endl; }
QString security::displayText() const { return description().isEmpty() ? "(New)" : functions::join(description(), functions::fitString(functions::removeNewLines(note()), 20), " | "); }
bool SFB::Audio::MP3Metadata::_ReadMetadata(CFErrorRef *error) { UInt8 buf [PATH_MAX]; if(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX)) return false; std::unique_ptr<TagLib::FileStream> stream(new TagLib::FileStream((const char *)buf, true)); if(!stream->isOpen()) { if(error) { SFB::CFString description(CFCopyLocalizedString(CFSTR("The file “%@” could not be opened for reading."), "")); SFB::CFString failureReason(CFCopyLocalizedString(CFSTR("Input/output error"), "")); SFB::CFString recoverySuggestion(CFCopyLocalizedString(CFSTR("The file may have been renamed, moved, deleted, or you may not have appropriate permissions."), "")); *error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion); } return false; } TagLib::MPEG::File file(stream.get(), TagLib::ID3v2::FrameFactory::instance()); if(!file.isValid()) { if(nullptr != error) { SFB::CFString description(CFCopyLocalizedString(CFSTR("The file “%@” is not a valid MPEG file."), "")); SFB::CFString failureReason(CFCopyLocalizedString(CFSTR("Not an MPEG file"), "")); SFB::CFString recoverySuggestion(CFCopyLocalizedString(CFSTR("The file's extension may not match the file's type."), "")); *error = CreateErrorForURL(Metadata::ErrorDomain, Metadata::InputOutputError, description, mURL, failureReason, recoverySuggestion); } return false; } CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MP3")); if(file.audioProperties()) { auto properties = file.audioProperties(); AddAudioPropertiesToDictionary(mMetadata, properties); // TODO: Is this too much information? #if 0 switch(properties->version()) { case TagLib::MPEG::Header::Version1: switch(properties->layer()) { case 1: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-1 Layer I")); break; case 2: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-1 Layer II")); break; case 3: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-1 Layer III")); break; } break; case TagLib::MPEG::Header::Version2: switch(properties->layer()) { case 1: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-2 Layer I")); break; case 2: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-2 Layer II")); break; case 3: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-2 Layer III")); break; } break; case TagLib::MPEG::Header::Version2_5: switch(properties->layer()) { case 1: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-2.5 Layer I")); break; case 2: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-2.5 Layer II")); break; case 3: CFDictionarySetValue(mMetadata, kFormatNameKey, CFSTR("MPEG-2.5 Layer III")); break; } break; } #endif if(properties->xingHeader() && properties->xingHeader()->totalFrames()) AddIntToDictionary(mMetadata, kTotalFramesKey, (int)properties->xingHeader()->totalFrames()); } if(file.APETag()) AddAPETagToDictionary(mMetadata, mPictures, file.APETag()); if(file.ID3v1Tag()) AddID3v1TagToDictionary(mMetadata, file.ID3v1Tag()); if(file.ID3v2Tag()) AddID3v2TagToDictionary(mMetadata, mPictures, file.ID3v2Tag()); return true; }
int itkFiltersMultiplyProcess::update ( void ) { DTK_D(itkFiltersMultiplyProcess); if ( !d->input ) return -1; QString id = d->input->identifier(); qDebug() << "itkFilters, update : " << id; if ( id == "itkDataImageChar3" ) { d->update<char>(); } else if ( id == "itkDataImageUChar3" ) { d->update<unsigned char>(); } else if ( id == "itkDataImageShort3" ) { d->update<short>(); } else if ( id == "itkDataImageUShort3" ) { d->update<unsigned short>(); } else if ( id == "itkDataImageInt3" ) { d->update<int>(); } else if ( id == "itkDataImageUInt3" ) { d->update<unsigned int>(); } else if ( id == "itkDataImageLong3" ) { d->update<long>(); } else if ( id== "itkDataImageULong3" ) { d->update<unsigned long>(); } else if ( id == "itkDataImageFloat3" ) { d->update<float>(); } else if ( id == "itkDataImageDouble3" ) { d->update<double>(); } else { qDebug() << description() <<", Error : pixel type not yet implemented (" << id << ")"; return -1; } return EXIT_SUCCESS; }
QString Challenge::tier() const { return description().desttier; }
bool ClaimStartdMsg::readMsg( DCMessenger * /*messenger*/, Sock *sock ) { // Now, we set the timeout on the socket to 1 second. Since we // were called by as a Register_Socket callback, this should not // block if things are working as expected. // However, if the Startd wigged out and sent a // partial int or some such, we cannot afford to block. -Todd 3/2000 sock->timeout(1); if( !sock->get(m_reply) ) { dprintf( failureDebugLevel(), "Response problem from startd when requesting claim %s.\n", description() ); sockFailed( sock ); return false; } /* Reply of 0 (NOT_OK) means claim rejected. Reply of 1 (OK) means claim accepted. Reply of 3 (REQUEST_CLAIM_LEFTOVERS) means claim accepted by a partitionable slot, and the "leftovers" slot ad and claim id will be sent next. Reply of 4 (REQUEST_CLAIM_PAIR) means claim accepted by a slot that is paired, and the partner slot ad and claim id will be sent next. */ if( m_reply == OK ) { // no need to log success, because DCMsg::reportSuccess() will } else if( m_reply == NOT_OK ) { dprintf( failureDebugLevel(), "Request was NOT accepted for claim %s\n", description() ); } else if( m_reply == REQUEST_CLAIM_LEFTOVERS ) { if( !sock->get(m_leftover_claim_id) || !getClassAd( sock, m_leftover_startd_ad ) ) { // failed to read leftover partitionable slot info dprintf( failureDebugLevel(), "Failed to read paritionable slot leftover from startd - claim %s.\n", description() ); // treat this failure same as NOT_OK, since this startd is screwed m_reply = NOT_OK; } else { // successfully read leftover partitionable slot info m_have_leftovers = true; // change reply to OK cuz claim was a success m_reply = OK; } } else if( m_reply == REQUEST_CLAIM_PAIR ) { if( !sock->get(m_paired_claim_id) || !getClassAd( sock, m_paired_startd_ad ) ) { // failed to read paired slot info dprintf( failureDebugLevel(), "Failed to read paired slot info from startd - claim %s.\n", description() ); // treat this failure same as NOT_OK, since this startd is screwed m_reply = NOT_OK; } else { // successfully read paired slot info m_have_paired_slot = true; // change reply to OK cuz claim was a success m_reply = OK; } } else { dprintf( failureDebugLevel(), "Unknown reply from startd when requesting claim %s\n",description()); } // end_of_message() is done by caller return true; }
Pokemon::gen Challenge::gen() const { return description().gen; }
void Character::SaveCharacter() { _log( ITEM__TRACE, "Saving character %u.", itemID() ); // Calculate total Skill Points trained at this time to save to DB: _CalculateTotalSPTrained(); sLog.Debug( "Character::SaveCharacter()", "Saving all character info and skill attribute info to DB for character %s...", itemName().c_str() ); // character data m_factory.db().SaveCharacter( itemID(), CharacterData( accountID(), title().c_str(), description().c_str(), gender(), bounty(), balance(), aurBalance(), securityRating(), logonMinutes(), m_totalSPtrained.get_float(), corporationID(), allianceID(), warFactionID(), stationID(), solarSystemID(), constellationID(), regionID(), ancestryID(), careerID(), schoolID(), careerSpecialityID(), startDateTime(), createDateTime(), corporationDateTime() ) ); // corporation data m_factory.db().SaveCorpMemberInfo( itemID(), CorpMemberInfo( corporationHQ(), corpRole(), rolesAtAll(), rolesAtBase(), rolesAtHQ(), rolesAtOther() ) ); // Save this character's own attributes: SaveAttributes(); // Loop through all skills and invoke mAttributeMap.SaveAttributes() for each std::vector<InventoryItemRef> skills; GetSkillsList( skills ); std::vector<InventoryItemRef>::iterator cur, end; cur = skills.begin(); end = skills.end(); for(; cur != end; cur++) cur->get()->SaveAttributes(); //cur->get()->mAttributeMap.Save(); SaveCertificates(); }
bool readXml(std::istream &in, StateDefinition &state) { pugi::xml_document doc; in.seekg(0, std::ios::end); auto fileSize = in.tellg(); in.seekg(0, std::ios::beg); std::unique_ptr<char[]> fileData(new char[fileSize]); in.read(fileData.get(), fileSize); if (!in) { std::cerr << "Failed to read " << fileSize << "bytes from input file\n"; return false; } boost::uuids::detail::sha1 sha; sha.reset(); sha.process_bytes(fileData.get(), fileSize); unsigned int hashValue[5]; sha.get_digest(hashValue); for (int i = 0; i < 5; i++) { unsigned int v = hashValue[i]; for (int j = 0; j < 4; j++) { // FIXME: Probably need to do the reverse for big endian? char stringBuf[3]; unsigned int byteHex = v & 0xff000000; byteHex >>= 24; snprintf(stringBuf, sizeof(stringBuf), "%02x", byteHex); state.hashString += stringBuf; v <<= 8; } } auto ret = doc.load_buffer(fileData.get(), fileSize); if (!ret) { std::cerr << "Failed to parse file:" << ret.description() << "\n"; return false; } auto rootNode = doc.first_child(); while (rootNode) { if (std::string(rootNode.name()) == "openapoc_gamestate") { auto objectNode = rootNode.first_child(); while (objectNode) { if (std::string(objectNode.name()) == "object") { SerializeObject obj(""); auto externalAttr = objectNode.attribute("external"); if (!externalAttr.empty()) { std::string externalValue = externalAttr.as_string(); if (externalValue == "true") { obj.external = true; } else { std::cerr << "Unknown object external attribute \"" << externalValue << "\"\n"; } } auto memberNode = objectNode.first_child(); while (memberNode) { if (std::string(memberNode.name()) == "member") { std::string memberName = memberNode.text().as_string(); NodeType type = NodeType::Normal; auto typeAttr = memberNode.attribute("type"); if (!typeAttr.empty()) { std::string typeName = typeAttr.as_string(); if (typeName == "Normal") type = NodeType::Normal; else if (typeName == "Section") type = NodeType::Section; else if (typeName == "SectionMap") type = NodeType::SectionMap; else std::cerr << "Unknown member type attribute \"" << typeName << "\"\n"; } SerializeNode member(memberName); member.type = type; obj.members.push_back(std::make_pair(member.name, member)); } else if (std::string(memberNode.name()) == "name") { obj.name = memberNode.text().as_string(); } memberNode = memberNode.next_sibling(); } state.objects.push_back(obj); } else if (std::string(objectNode.name()) == "enum") { SerializeEnum sEnum; auto valueNode = objectNode.first_child(); while (valueNode) { if (std::string(valueNode.name()) == "value") { sEnum.values.push_back(valueNode.text().as_string()); } else if (std::string(valueNode.name()) == "name") { sEnum.name = valueNode.text().as_string(); } valueNode = valueNode.next_sibling(); } state.enums.push_back(sEnum); } objectNode = objectNode.next_sibling(); } } rootNode = rootNode.next_sibling(); } return true; }
bool RDReport::ExportMusicPlayout(const QDate &startdate,const QDate &enddate, const QString &mixtable) { QString sql; RDSqlQuery *q; FILE *f; QString cut; QString str; QString cart_fmt; QString cart_num; #ifdef WIN32 QString filename=RDDateDecode(exportPath(RDReport::Windows),startdate); #else QString filename=RDDateDecode(exportPath(RDReport::Linux),startdate); #endif QFile file(filename); if((f=fopen((const char *)filename,"w"))==NULL) { report_error_code=RDReport::ErrorCantOpen; return false; } if(useLeadingZeros()) { cart_fmt=QString().sprintf("%%0%uu",cartDigits()); } else { cart_fmt="%6u"; } sql=QString("select ")+ "`"+mixtable+"_SRT`.LENGTH,"+ // 00 "`"+mixtable+"_SRT`.CART_NUMBER,"+ // 01 "`"+mixtable+"%s_SRT`.EVENT_DATETIME,"+ // 02 "`"+mixtable+"_SRT`.EXT_EVENT_ID,"+ // 03 "`"+mixtable+"_SRT`.TITLE,"+ // 04 "`"+mixtable+"_SRT`.CUT_NUMBER,"+ // 05 "`"+mixtable+"_SRT`.ARTIST,"+ // 06 "`"+mixtable+"_SRT`.ALBUM,"+ // 07 "`"+mixtable+"_SRT`.LABEL "+ // 08 "from `"+mixtable+"_SRT` left join CART "+ "on `"+mixtable+"_SRT`.CART_NUMBER=CART.NUMBER "+ "order by EVENT_DATETIME"; q=new RDSqlQuery(sql); // // Write File Header // if(startdate==enddate) { fprintf(f," Rivendell RDAirPlay Music Playout Report for %s\n", (const char *)startdate.toString("MM/dd/yyyy")); } else { fprintf(f," Rivendell RDAirPlay Music Playout Report for %s - %s\n", (const char *)startdate.toString("MM/dd/yyyy"), (const char *)enddate.toString("MM/dd/yyyy")); } str=QString().sprintf("%s -- %s\n",(const char *)name(), (const char *)description()); for(int i=0;i<(180-str.length())/2;i++) { fprintf(f," "); } fprintf(f,"%s\n",(const char *)str); fprintf(f,"--Time-- -Cart- Cut A-Len --Title----------------------- --Artist---------------------- --Album------------------ --Label-------------\n"); // // Write Data Rows // while(q->next()) { if(q->value(5).toInt()>0) { cut=QString().sprintf("%03d",q->value(5).toInt()); } else { if((RDAirPlayConf::TrafficAction)q->value(6).toInt()== RDAirPlayConf::TrafficMacro) { cut="rml"; } else { cut=" "; } } cart_num=QString().sprintf(cart_fmt,q->value(1).toUInt()); fprintf(f,"%8s %6s %3s %5s %-30s %-30s %-25s %-20s\n", (const char *)q->value(2).toDateTime().time().toString("hh:mm:ss"), (const char *)cart_num, (const char *)cut, (const char *)RDGetTimeLength(q->value(0).toInt(),true,false). right(5), (const char *)StringField(q->value(4).toString().left(30)), (const char *)StringField(q->value(6).toString().left(30)), (const char *)StringField(q->value(7).toString().left(25)), (const char *)StringField(q->value(8).toString().left(20))); } delete q; fclose(f); report_error_code=RDReport::ErrorOk; return true; }
//-------------------------------------------------------- void WebSocketDSClass::write_class_property() { // First time, check if database used if (Tango::Util::_UseDb == false) return; Tango::DbData data; string classname = get_name(); string header; string::size_type start, end; // Put title Tango::DbDatum title("ProjectTitle"); string str_title("WebSocket access to tango device-server attributes, pipes and commands"); title << str_title; data.push_back(title); // Put Description Tango::DbDatum description("Description"); vector<string> str_desc; str_desc.push_back("WebSocket access to tango device-server attributes."); str_desc.push_back(""); str_desc.push_back("Configuration should be done via properties:"); str_desc.push_back(""); str_desc.push_back("Port - port to listen incoming ws connections;"); str_desc.push_back("DeviceServer - tango id of a required device server;"); str_desc.push_back("Attributes - list of required DS attributes, you wish to read via WS;"); str_desc.push_back("Commands - list of required DS commandes, you wish to executed via WS;"); str_desc.push_back("AuthDS - Tango web authentication device server (TangoWebAuth ) name."); str_desc.push_back("Secure - It will be used wss connection (websocket secure). (true if you want)"); str_desc.push_back("Certificate - Certificate file name (crt) with full path (if Secure = true)"); str_desc.push_back("Key - Private key file name (if Secure = true)"); str_desc.push_back("Options - Various options for the device server"); str_desc.push_back(""); str_desc.push_back("Then you should set polling to the UpdateData command. (1000 means that all connected clients would read attributes once per second)."); str_desc.push_back(""); str_desc.push_back("Data format: JSON string with array of attrubute objects {atrrtibute name, attribute value, quality, timestamp};"); str_desc.push_back(""); str_desc.push_back("if you want to record in the logs, define uselog in Property ``Options``."); str_desc.push_back("The database (defined in AuthDS) must contain a table `command_history` with columns:"); str_desc.push_back(" // id - autoincrement"); str_desc.push_back(" // argin[0] = timestamp_string UNIX_TIMESTAMP"); str_desc.push_back(" // argin[1] = login"); str_desc.push_back(" // argin[2] = deviceName"); str_desc.push_back(" // argin[3] = IP"); str_desc.push_back(" // argin[4] = commandName"); str_desc.push_back(" // argin[5] = commandJson"); str_desc.push_back(" // argin[6] = statusBool"); str_desc.push_back(" // argin[7] = isGroup"); description << str_desc; data.push_back(description); // put cvs or svn location string filename("WebSocketDS"); filename += "Class.cpp"; // check for cvs information string src_path(CvsPath); start = src_path.find("/"); if (start!=string::npos) { end = src_path.find(filename); if (end>start) { string strloc = src_path.substr(start, end-start); // Check if specific repository start = strloc.find("/cvsroot/"); if (start!=string::npos && start>0) { string repository = strloc.substr(0, start); if (repository.find("/segfs/")!=string::npos) strloc = "ESRF:" + strloc.substr(start, strloc.length()-start); } Tango::DbDatum cvs_loc("cvs_location"); cvs_loc << strloc; data.push_back(cvs_loc); } } // check for svn information else { string src_path(SvnPath); start = src_path.find("://"); if (start!=string::npos) { end = src_path.find(filename); if (end>start) { header = "$HeadURL: "; start = header.length(); string strloc = src_path.substr(start, (end-start)); Tango::DbDatum svn_loc("svn_location"); svn_loc << strloc; data.push_back(svn_loc); } } } // Get CVS or SVN revision tag // CVS tag string tagname(TagName); header = "$Name: "; start = header.length(); string endstr(" $"); end = tagname.find(endstr); if (end!=string::npos && end>start) { string strtag = tagname.substr(start, end-start); Tango::DbDatum cvs_tag("cvs_tag"); cvs_tag << strtag; data.push_back(cvs_tag); } // SVN tag string svnpath(SvnPath); header = "$HeadURL: "; start = header.length(); end = svnpath.find(endstr); if (end!=string::npos && end>start) { string strloc = svnpath.substr(start, end-start); string tagstr ("/tags/"); start = strloc.find(tagstr); if ( start!=string::npos ) { start = start + tagstr.length(); end = strloc.find(filename); string strtag = strloc.substr(start, end-start-1); Tango::DbDatum svn_tag("svn_tag"); svn_tag << strtag; data.push_back(svn_tag); } } // Get URL location string httpServ(HttpServer); if (httpServ.length()>0) { Tango::DbDatum db_doc_url("doc_url"); db_doc_url << httpServ; data.push_back(db_doc_url); } // Put inheritance Tango::DbDatum inher_datum("InheritedFrom"); vector<string> inheritance; inheritance.push_back("TANGO_BASE_CLASS"); inher_datum << inheritance; data.push_back(inher_datum); // Call database and and values get_db_class()->put_property(data); }
static mtx::xml::document_cptr retrieve_and_parse_xml(std::string const &url) { bool debug = debugging_requested("version_check|releases_info|curl"); std::string data; auto result = url_retriever_c().set_timeout(10, 20).retrieve(url, data); if (0 != result) { mxdebug_if(debug, boost::format("CURL error for %2%: %1%\n") % static_cast<unsigned int>(result) % url); return mtx::xml::document_cptr(); } try { data = compressor_c::create_from_file_name(url)->decompress(data); mtx::xml::document_cptr doc(new pugi::xml_document); std::stringstream sdata(data); auto xml_result = doc->load(sdata); if (xml_result) { mxdebug_if(debug, boost::format("Doc loaded fine from %1%\n") % url); return doc; } else mxdebug_if(debug, boost::format("Doc load error for %1%: %1% at %2%\n") % url % xml_result.description() % xml_result.offset); } catch (mtx::compression_x &ex) { mxdebug_if(debug, boost::format("Decompression exception for %2%: %1%\n") % ex.what() % url); } return mtx::xml::document_cptr(); }
void CSDReader::softpkg (DOMElement* element) throw(CSDReadException) { if ( !package_ ) abort(); std::string element_name; DOMNode* child = element->getFirstChild(); while (child != 0) { if (child->getNodeType() == DOMNode::ELEMENT_NODE) { element_name = Qedo::transcode(child->getNodeName()); // // title // if (element_name == "title") { title((DOMElement*)child); } // // pkgtype // else if (element_name == "pkgtype") { pkgtype((DOMElement*)child); } // // repository // else if (element_name == "repository") { // TODO } // // author // else if (element_name == "author") { author((DOMElement*)child); } // // description // else if (element_name == "description") { description((DOMElement*)child); } // // license // else if (element_name == "license") { license((DOMElement*)child); } // // idl // else if (element_name == "idl") { idl((DOMElement*)child); } // // propertyfile // else if (element_name == "propertyfile") { propertyfile((DOMElement*)child); } // // dependency // else if (element_name == "dependency") { dependency((DOMElement*)child); } // // extension // else if (element_name == "extension") { extension((DOMElement*)child); } } // get next child child = child->getNextSibling(); } DOMNodeList* nodeList; DOMElement* elem; unsigned int len = 0; unsigned int i = 0; std::string uuid = data_->uuid; // // implementation // nodeList = element->getElementsByTagName(X("implementation")); len = nodeList->getLength(); bool impl_found = false; for (i = 0; i < len; ++i) { elem = (DOMElement*)(nodeList->item(i)); if (!XMLString::compareString(elem->getAttribute(X("id")), X(uuid.c_str()))) { impl_found = true; break; } } if(impl_found) { implementation(elem); } else { NORMAL_ERR3( "CSDReader: implementation for ", uuid, " missing!" ); throw CSDReadException(); } // // corba component descriptor // if (ccd_file_.empty()) { nodeList = element->getElementsByTagName(X("descriptor")); len = nodeList->getLength(); if(len == 1) { ccd_file_ = descriptor((DOMElement*)(nodeList->item(0))); } else if(len > 1) { NORMAL_ERR( "CSDReader: multiple descriptor elements!" ); } if (ccd_file_.empty()) { NORMAL_ERR2( "CSDReader: missing component descriptor for ", uuid ); throw CSDReadException(); } } // // parse the corba component descriptor file // CCDReader reader( path_ + ccd_file_, path_ ); reader.readCCD( &(data_->component), package_ ); }