// if, for example, missing data void NullGenotypeAllSamples(vcf::Variant & candidate_variant) { vector<string>& sampleNames = candidate_variant.sampleNames; for (vector<string>::iterator its = sampleNames.begin(); its != sampleNames.end(); ++its) { string& sampleName = *its; map<string, vector<string> >& sampleOutput = candidate_variant.samples[sampleName]; sampleOutput["GT"].push_back("./."); sampleOutput["GQ"].push_back(convertToString(0)); sampleOutput["FDP"].push_back(convertToString(0)); sampleOutput["FRO"].push_back(convertToString(0)); sampleOutput["FSRF"].push_back(convertToString(0)); sampleOutput["FSRR"].push_back(convertToString(0)); for (vector<string>::iterator I = candidate_variant.alt.begin(); I != candidate_variant.alt.end(); ++I) { sampleOutput["FAO"].push_back(convertToString(0)); sampleOutput["AF"].push_back(convertToString(0)); sampleOutput["FSAF"].push_back(convertToString(0)); sampleOutput["FSAR"].push_back(convertToString(0)); } } }
std::string XMLWrapper::getAttr(xmlNodePtr node, const char *name) { if (!node || !name) { return ""; } std::string value; xmlChar *xmlValue = xmlGetProp(node, BAD_CAST name); if (xmlValue) { convertToString(xmlValue, value); xmlFree(xmlValue); } return value; }
void Player::applyItem(vector<Item*> items) { if (creature->isBlind() && contains({ItemType::SCROLL, ItemType::BOOK}, items[0]->getType())) { privateMessage("You can't read while blind!"); return; } if (items[0]->getApplyTime() > 1) { for (const Creature* c : creature->getVisibleEnemies()) if ((c->getPosition() - creature->getPosition()).length8() < 3) { if (!model->getView()->yesOrNoPrompt("Applying " + items[0]->getAName() + " takes " + convertToString(items[0]->getApplyTime()) + " turns. Are you sure you want to continue?")) return; else break; } } tryToPerform(creature->applyItem(items[0])); }
/* =========================================================================== // Render PDF obj to string content @param none desc @return none desc ==========================================================================*/ int PDF_Object_Page::renderObj() { /* //scale.setConversion(pt); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< HERE 4/12 cout << "==============================================\n"; cout << "==============================================\n"; cout << "==============================================\n"; cout << "PDF_Object_Page::renderObj() called...\n"; // cout << "SCALE current: |"<< scale.getUnitsAsString() << "|, "; //cout << "conversion units: |" << scale.getConversionUnitsAsString() << "|\n"; //scale.setUnits(pt); //scale.setConversion(mm); cout << "SCALE current: |"<< scale.getUnitsAsString() << "|, "; cout << "conversion units: |" << scale.getConversionUnitsAsString() << "|, "; printf("scale factor: |%f|\n", scale.getConversionFactor() ); //cout << "scale factor: |" << scale.getConversionFactor() << "|\n"; cout << "==============================================\n"; cout << "==============================================\n"; cout << "==============================================\n"; //cout << "PDF_Object_Page::renderObj() called...\n"; */ string renderString = ""; renderString += getIndexString() + " " + getRevisionString(); // GET PAGES ADRESS FOR PARENT FIELD renderString += " obj <</Type /Page /Parent 2 0 R /Contents "; for (unsigned i = 0; i < contents.size(); i++) { renderString += contents[i]->getIndexString() + " "; renderString += contents[i]->getRevisionString() + " R "; } // Render UserUnit renderString += "/UserUnit "; //renderString += "2.83465"; renderString += convertToString( scale.getConversionFactor() ); renderString += " "; renderString += ">>\nendobj\n"; return setRenderContent( renderString ); }
bool XMLWrapper::getContent(xmlNodePtr node, std::string &content) { content.clear(); if (!node) { return false; } xmlChar *xmlContent = xmlNodeGetContent(node); if (!xmlContent) { return true; } bool result = convertToString(xmlContent, content); xmlFree(xmlContent); return result; }
void genWriteln (Symbol s) { if (strcmp(s.type,"string") != 0) convertToString(s); else{ int rotInicio = ++rotCount; int rotFim = ++rotCount; fprintf (asm_file," mov di, %d \n",s.adress); fprintf (asm_file," R%d: \n",rotInicio); fputs (" mov dl, ds:[di]\n",asm_file); fputs (" add di, 1\n",asm_file); fputs (" cmp dl, 024h\n",asm_file); fprintf (asm_file," je R%d\n",rotFim); fputs (" mov ah, 02h\n",asm_file); fputs (" int 21h\n",asm_file); fprintf (asm_file," jmp R%d\n",rotInicio); fprintf (asm_file," R%d: \n",rotFim); } }
// ###################################################################### std::string GenericFrameSpec::nativeTypeName() const { switch (this->nativeType) { case GenericFrame::NONE: return "(empty)"; case GenericFrame::RGB_U8: return "Image<PixRGB<byte>>"; case GenericFrame::RGB_U16: return "Image<PixRGB<uint16>>"; case GenericFrame::RGB_F32: return "Image<PixRGB<float>>"; case GenericFrame::GRAY_U8: return "Image<byte>"; case GenericFrame::GRAY_U16: return "Image<uint16>"; case GenericFrame::GRAY_F32: return "Image<float>"; case GenericFrame::VIDEO: return sformat("VideoFrame (%s%s)", convertToString(this->videoFormat).c_str(), this->videoByteSwap ? "+byteswap" : ""); case GenericFrame::RGBD: return "Image<PixRGB<byte>>+Image<uint16>"; } ASSERT(0); /* can't happen */; return 0; }
void OverwriteGenotypeForOneSample(vcf::Variant &candidate_variant, const string &my_sample_name, string &my_genotype, float genotype_quality) { // will create entry if one does not exist map<string, vector<string> >& sampleOutput = candidate_variant.samples[my_sample_name]; // clear existing values map<string, vector<string> >::iterator it; it = sampleOutput.find("GT"); if (it != sampleOutput.end()) sampleOutput["GT"].clear(); it = sampleOutput.find("GQ"); if (it != sampleOutput.end()) sampleOutput["GQ"].clear(); sampleOutput["GT"].push_back(my_genotype); // genotype quality should be an "int" int local_quality = genotype_quality; //cout << "Storing Genotype = " << my_genotype << endl; sampleOutput["GQ"].push_back(convertToString(local_quality)); }
// parse input string int Clause::parse(const List<String> &list) { // set defaults values clear(); // check if list is empty if (list.isEmpty()) { // nothing to parse type = Empty; return(OK); } // list is not empty, get options. ListIterator<String> listIter(list); String options = listIter(); // parse options StringMatcher conclusionopt(options, String("CONCLUSION")); if (!conclusionopt.done()) partOfConclusion = 1; StringMatcher setofsupportopt(options, String("SET-OF-SUPPORT")); if (!setofsupportopt.done()) setOfSupport = 1; // scan list of literal strings for (listIter++; !listIter.done(); listIter++) { // insert literal into clause; will set type. Literal literal(listIter()); if (insert(literal) != OK) return(NOTOK); } // convert to a string convertToString(inputstring); // all done return(OK); }
void configParserStruct::pythonParser::checkError() { void *Error = PyErr_Occurred(); if ( Error != NULL ) { std::string ExceptionString; PyObject *ErrType = NULL, *ErrValue = NULL, *TraceBack = NULL; PyErr_Fetch( &ErrType, &ErrValue, &TraceBack ); int LineNumber = reinterpret_cast<PyTracebackObject*>( TraceBack )->tb_lineno; if ( ErrValue != NULL ) ExceptionString = pyobjectString( ErrValue ); Py_XDECREF(ErrType); Py_XDECREF(ErrValue); Py_XDECREF(TraceBack); throw std::runtime_error( ExceptionString + " (error at line " + convertToString(LineNumber) + ")" ); } }
/**Creates a XML Tree for xerces which is used to write the data to a xml file **/ xercesc::DOMNode* XMLParser::createDOMTree(){ xercesc::DOMImplementation* impl = xercesc::DOMImplementationRegistry::getDOMImplementation(xercesc::XMLString::transcode("Core")); xercesc::DOMDocument* doc = impl->createDocument(0, xercesc::XMLString::transcode("root"), 0); xercesc::DOMElement* rootElement = doc->getDocumentElement(); xercesc::DOMElement* categorie; xercesc::DOMElement* key; xercesc::DOMText* text; //Create an iterator for the categories and one for the values auto itc = _categories.begin(); t_map::iterator itk; std::string str; for(; itc != _categories.end(); itc++){ categorie = doc->createElement(xercesc::XMLString::transcode(itc->first.c_str())); auto itk = itc->second.begin(); for(; itk != itc->second.end(); itk++){ key = doc->createElement(xercesc::XMLString::transcode(itk->first.c_str())); //Check if the value is a string and adapt "string" to the type-information of the key if(std::string(typeid(std::string).name()).compare(itk->second.type().name()) == 0){ key->setAttribute(xercesc::XMLString::transcode("type"), xercesc::XMLString::transcode("string")); } else { key->setAttribute(xercesc::XMLString::transcode("type"), xercesc::XMLString::transcode(itk->second.type().name())); } convertToString(&str, &itk->second); //Converts the value to a string, so it can bee saved text = doc->createTextNode(xercesc::XMLString::transcode(str.c_str())); key->appendChild(text); categorie->appendChild(key); } rootElement->appendChild(categorie); } return rootElement; }
bool XMLWrapper::getChildText(xmlNodePtr node, const char *childName, std::string &text) { if (node == NULL || node->children == NULL) { return false; } xmlNodePtr child = findNode(node->children, childName, true); if (!child) { return false; } if (child->type != XML_ELEMENT_NODE) { return false; } if (!child->children) { return false; } if (getAttr(child, "type") == "xhtml") { /* search div */ xmlNodePtr div = findNode(child->children, "div", false); if (!div) { return false; } return nodeDump(div, text, true); } if (child->children->type != XML_TEXT_NODE) { return false; } if (child->children->content) { return convertToString(child->children->content, text); } return true; }
std::string convertToString(const fastoredis::ssdbConfig &conf) { std::vector<std::string> argv; if(conf.hostip_){ argv.push_back("-h"); argv.push_back(conf.hostip_); } if(conf.hostport_){ argv.push_back("-p"); argv.push_back(convertToString(conf.hostport_)); } if(conf.user_){ argv.push_back("-u"); argv.push_back(conf.user_); } if(conf.password_){ argv.push_back("-a"); argv.push_back(conf.password_); } if (conf.mb_delim_) { argv.push_back("-d"); argv.push_back(conf.mb_delim_); } std::string result; for(int i = 0; i < argv.size(); ++i){ result+= argv[i]; if(i != argv.size()-1){ result+=" "; } } return result; }
IMS_Data::ListSysInfo_ptr SysInfoServer::getSysInfo() { string req = "SELECT diskspace, machineid, memory from machine WHERE vishnu_vishnuid='"+convertToString(mvishnuId)+"'"; vector<string> results = vector<string>(); vector<string>::iterator iter; if(mop.getMachineId().compare("")) { string reqnmid = "SELECT nummachineid from machine where machineid ='"+mop.getMachineId()+"'"; boost::scoped_ptr<DatabaseResult> result(mdatabase->getResult(reqnmid.c_str())); if(result->getNbTuples() == 0) { throw IMSVishnuException(ERRCODE_INVPROCESS, "Unknown machine id"); } req += " AND machineid ='"+mop.getMachineId()+"'"; } IMS_Data::IMS_DataFactory_ptr ecoreFactory = IMS_Data::IMS_DataFactory::_instance(); IMS_Data::ListSysInfo_ptr mlistObject = ecoreFactory->createListSysInfo(); try { boost::scoped_ptr<DatabaseResult> result(mdatabase->getResult(req.c_str())); for (size_t i = 0; i < result->getNbTuples(); i++){ results.clear(); results = result->get(i); iter = results.begin(); IMS_Data::SystemInfo_ptr sys = ecoreFactory->createSystemInfo(); if ((*(iter)).empty()) { sys->setDiskSpace(-1); } else { sys->setDiskSpace(convertToInt(*(iter))); } if ((*(iter+2)).empty()) { sys->setMemory(-1); } else { sys->setMemory(convertToInt(*(iter+2))); } sys->setMachineId(*(iter+1)); mlistObject->getSysInfo().push_back(sys); } } catch (SystemException& e) { throw (e); } return mlistObject; }
std::string convertToString(const fastonosql::redisConfig& conf) { std::vector<std::string> argv = conf.args(); if(conf.hostsocket){ argv.push_back("-s"); argv.push_back(conf.hostsocket); } if(conf.repeat){ argv.push_back("-r"); argv.push_back(convertToString(conf.repeat)); } if(conf.interval){ argv.push_back("-i"); argv.push_back(convertToString(conf.interval/1000000)); } if(conf.dbnum){ argv.push_back("-n"); argv.push_back(convertToString(conf.dbnum)); } if(conf.auth){ argv.push_back("-a"); argv.push_back(conf.auth); } if(conf.latency_mode){ if(conf.latency_history){ argv.push_back("--latency-history"); } else{ argv.push_back("--latency"); } } if(conf.slave_mode){ argv.push_back("--slave"); } if(conf.stat_mode){ argv.push_back("--stat"); } if(conf.scan_mode){ argv.push_back("--scan"); } if(conf.pattern){ argv.push_back("--pattern"); argv.push_back(conf.pattern); } if(conf.intrinsic_latency_mode){ argv.push_back("--intrinsic-latency"); argv.push_back(convertToString(conf.intrinsic_latency_mode)); argv.push_back(convertToString(conf.intrinsic_latency_duration)); } if(conf.getrdb_mode){ argv.push_back("--rdb"); argv.push_back(conf.rdb_filename); } if(conf.bigkeys){ argv.push_back("--bigkeys"); } if(conf.eval){ argv.push_back("--eval"); argv.push_back(conf.eval); } if(conf.cluster_mode){ argv.push_back("-c"); } std::string result; for(int i = 0; i < argv.size(); ++i){ result+= argv[i]; if(i != argv.size()-1){ result+=" "; } } return result; }
void call21h() { /* * 对21h 中的功能号进行测试 */ while(1) { cls(); print("\r\n Now, you can run some commands to test the 21h:\n\n\r"); print(" 1.ouch -- to ouch 2.upper -- change the letter to upper\n\r"); print(" 3.lower -- change the letter to lower\n\r"); print(" 4.to_digit -- change the string to digit\r\n"); print(" 5.to_string -- change the digit to string\r\n"); print(" 6.display_where -- you can assign where to display\r\n"); print(" 7.to_deci -- change the Hex to a decimal digit\r\n"); print(" 8.reverse -- to reverse your string\r\n"); print(" 9.strlen -- get the length of your string\r\n"); print(" 10.quit -- just to quit\r\n\r\n"); print("Please input your choice:"); getline(input,20); if(strcmp(input,"1") || strcmp(input,"ouch")) { /* * 测试 0 号功能 */ to_OUCH(); } else if(strcmp(input,"2") || strcmp(input,"upper")) { /* * 测试 1 号功能 */ while(1) { print("\r\nPlease input a sentence or quit to back:"); getline(input,30); if(strcmp(input,"quit")) break; upper(input); print("\r\nThe upper case is:"); print(input); print("\r\n"); } } else if(strcmp(input,"3") || strcmp(input,"lower")) { /* * 测试 2 号功能 */ while(1) { print("\r\nPlease input a sentence or quit to back:"); getline(input,30); if(strcmp(input,"quit")) break; lower(input); print("\r\nThe lower case is:"); print(input); print("\r\n"); } } else if(strcmp(input,"4") || strcmp(input,"to_digit")) { /* * 测试 3 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { int t1,t2,t3; t1 = 0;t2 = 0; if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the first digit:"); getline(input,4); if(isDigit(input)) { t1 = digital(input); } else { print("\r\nInvalid digit!We assume it is 12\n\r"); t1 = 12; } print("\r\nPlease input the second digit:"); getline(input,4); if(isDigit(input)) { t2 = digital(input); } else { print("\r\nInvalid digit!We assume it is 21\n\r"); t2 = 21; } print("\r\nThe sum of the them is:"); t3 = t1 + t2; printInt(t3); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"5") || strcmp(input,"to_string")) { /* * 测试 4 号功能 */ print("\r\nDo you want to continue? Y | N: "); getline(input,2); while(1) { char *cht; int tt = rand(); if(strcmp(input,"n") || strcmp(input,"N")) break; cht = convertToString(tt); print("\r\nI am a string: "); print(cht); print("\r\n"); print("\r\nDo you want to continue? Y | N: "); getline(input,2); } } else if(strcmp(input,"6") || strcmp(input,"display_where")) { /* * 测试 5 号功能 */ int row,col; print("\r\nPlease input the row:"); getline(input,3); if(isDigit(input)) { row = digital(input); } else { print("\r\nInvalid digit!We assume it is 12\n\r"); row = 12; } print("\r\nPlease input column:"); getline(input,3); if(isDigit(input)) { col = digital(input); } else { print("\r\nInvalid digit!We assume it is 40\n\r"); col = 40; } print("\r\nPlease input the string:"); getline(input,30); display(row,col,input); } else if(strcmp(input,"7") || strcmp(input,"to_dec")) { /* * 测试 6 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { int t1; t1 = 0; if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the hex digit:"); getline(input,3); if(isHex(input)) { t1 = convertHexToDec(input); } else { print("\r\nInvalid Hex!We assume it is 12\n\r"); t1 = 12; } print("\r\nThe decimal form is:"); printInt(t1); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"8") || strcmp(input,"reverse")) { /* * 测试 7 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the your string:"); getline(input,30); reverse(input,strlen(input)); print("\r\nThe string after reverse is:"); print(input); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"9") || strcmp(input,"strlen")) { /* * 测试 8 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { int t; if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the your string:"); getline(input,30); t = strlen(input); print("\r\nThe length of the string is:"); printInt(t); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"10") || strcmp(input,"quit")) { /* * 退出 */ break; } } }
CefHandler::RetVal HandlerAdapter::HandleTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { _browserControl->SetTitle(convertToString(title)); return RV_CONTINUE; }
Clause::operator String() { return(convertToString(inputstring)); }
Clause::operator String() const { String tmp; return(convertToString(tmp)); }
// parse input string int Clause::parse(const List<String> &list) { // set defaults values clear(); // check if list is empty if (list.isEmpty()) { // nothing to parse type = Empty; return(OK); } // list is not empty, get options. ListIterator<String> listIter(list); String options = listIter(); // parse options StringMatcher conclusionopt(options, String("CONCLUSION")); if (!conclusionopt.done()) partOfConclusion = 1; StringMatcher queryopt(options, String("QUERY")); if (!queryopt.done()) partOfQuery = 1; StringMatcher setofsupportopt(options, String("SET-OF-SUPPORT")); if (!setofsupportopt.done()) setOfSupport = 1; // scan list of literal strings for (listIter++; !listIter.done(); listIter++) { // insert literal into clause; will set type. Literal literal(listIter()); if (insert(literal) != OK) { ERROR("insert failed.", errno); return(NOTOK); } } // convert to a string convertToString(inputstring); // add answer literal if (partOfQuery) { int ivar = 0; String answerstring("( ANSWER "); StringTokens st(inputstring, " \t"); for ( ; !st.done(); st++) { String token = st(); if (token(0,2) == String("_V")) { ivar++; answerstring += token + String(" "); } else if (token(0,3) == String("_RV")) { ivar++; answerstring += token + String(" "); } } if (ivar == 0) { // no variables were found answerstring = String("ANSWER"); } else { // finish answer literal answerstring += String(") "); } // insert answer literal into answer clause Literal answerliteral(answerstring); if (insertAnswer(answerliteral) != OK) { ERROR("insertAnswer failed.", errno); return(NOTOK); } } // update clause type updateType(); // all done return(OK); }
int main(int argc, char* argv[]) { cl_int status = CL_SUCCESS; cl_float* input; try { std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if (platforms.empty()) { std::cerr <<"Platform size = 0"<<std::endl; return FAILURE; } cl::Platform targetPlatform = *platforms.begin(); for (std::vector<cl::Platform>::iterator iter = platforms.begin(); iter != platforms.end(); iter++) { std::string strPlatform = iter->getInfo<CL_PLATFORM_NAME>(); std::cout<< "Found platform: "<< strPlatform<<std::endl; if (strPlatform.find(TARGET_PLAFORM) != std::string::npos) { targetPlatform = *iter; std::cout<< "Select platform: "<< strPlatform<<std::endl; } } cl_context_properties properties[] = {CL_CONTEXT_PLATFORM, (cl_context_properties)targetPlatform(), 0}; cl::Context context(PERFER_DEVICE_TYPE, properties); std::vector<cl::Device> devices =context.getInfo<CL_CONTEXT_DEVICES>(); for (std::vector<cl::Device>::iterator iter = devices.begin(); iter != devices.end(); iter++) { std::string strDevices = iter->getInfo<CL_DEVICE_NAME>(); std::cout<< "Found device: "<< strDevices<<std::endl; } cl::CommandQueue queue(context, devices[0], 0, &status); if (status != CL_SUCCESS) { throw cl::Error(status, "CommandQueue!"); } cl_uint inputSizeBytes = GlobalThreadSize * sizeof(cl_uint); input = (cl_float*) malloc(inputSizeBytes); for (int i=0; i< GlobalThreadSize; i++) { input[i] = (float)i; } cl_mem inputBuffer = clCreateBuffer( context(), CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, inputSizeBytes, (void*) input, &status); if (status != CL_SUCCESS) { throw cl::Error(status, "Input Memory Buffer!"); } cl_mem outputBuffer = clCreateBuffer( context(), CL_MEM_WRITE_ONLY, inputSizeBytes, NULL, &status); if (status != CL_SUCCESS) { throw cl::Error(status, "Output Memory Buffer!"); } const char* filename = "./BasicDebug_Kernel.cl"; std::string sourceStr; status = convertToString(filename, sourceStr); const char *source = sourceStr.c_str(); size_t sourceSize[] ={strlen(source)}; const char* filename2 = "./BasicDebug_Kernel2.cl"; std::string sourceStr2; status = convertToString(filename2, sourceStr2); const char *source2 = sourceStr2.c_str(); size_t sourceSize2[] ={strlen(source2)}; cl::Program::Sources sources; cl::Program::Sources sources2; sources.push_back(std::make_pair(source, strlen(source))); sources2.push_back(std::make_pair(source2, strlen(source2))); cl::Program program = cl::Program(context, sources); program.build(devices, "-g"); cl::Program program2 = cl::Program(context, sources2); program2.build(devices, "-g"); cl::Kernel printfKernel(program, "printfKernel", &status); if (status != CL_SUCCESS) { throw cl::Error(status, "Printf Kernel!"); } //set kernel args. status = clSetKernelArg(printfKernel(), 0, sizeof(cl_mem), (void *)&inputBuffer); cl::Kernel debugKernel(program2, "debugKernel", &status); if (status != CL_SUCCESS) { throw cl::Error(status, "DebugKernel!"); } //set kernel args. status = clSetKernelArg(debugKernel(), 0, sizeof(cl_mem), (void *)&inputBuffer); status = clSetKernelArg(debugKernel(), 1, sizeof(cl_mem), (void *)&outputBuffer); size_t global_threads[1]; size_t local_threads[1]; global_threads[0] = GlobalThreadSize; local_threads[0] = GroupSize; // cl::Event event; status = queue.enqueueNDRangeKernel( printfKernel, cl::NullRange, cl::NDRange(global_threads[0]), cl::NDRange(local_threads[0]), NULL, NULL); // &event); // event.wait(); if (status != CL_SUCCESS) { throw cl::Error(status, "Execute printfKernel!"); } status = clFinish(queue()); status = queue.enqueueNDRangeKernel( debugKernel, cl::NullRange, cl::NDRange(global_threads[0]), cl::NDRange(local_threads[0]), NULL, NULL); if (status != CL_SUCCESS) { throw cl::Error(status, "Execute DebugKernel!"); } status = clReleaseMemObject(inputBuffer);//Release mem object. status = clReleaseMemObject(outputBuffer); status = clFinish(queue()); //#endif free(input); } catch (cl::Error err) { if (input) { free(input); } std::cerr<< "Error: " << err.what() << "(" << err.err () << ")" << std::endl; return FAILURE; } return SUCCESS; }
oret_t owatchConvertValue(const oval_t * src_val, oval_t * dst_val, char *data_buf, int data_buf_len) { oret_t rc = ERROR; char src_type, dst_type; int len; if (src_val == NULL || dst_val == NULL) return ERROR; src_type = src_val->type; dst_type = dst_val->type; if (dst_type == 's') { if (src_type == 's') { if (src_val->v.v_str == NULL) { dst_val->v.v_str = NULL; dst_val->len = 0; dst_val->time = src_val->time; if (data_buf && data_buf_len) *data_buf = 0; return OK; } if (src_val->len == 0) { dst_val->v.v_str = data_buf; dst_val->len = 0; dst_val->time = src_val->time; if (data_buf && data_buf_len) *data_buf = 0; return OK; } if (src_val->len < 0) return ERROR; if (data_buf == NULL || data_buf_len < src_val->len) return ERROR; oxbcopy(src_val->v.v_str, data_buf, src_val->len); if (src_val->len < data_buf_len) data_buf[src_val->len] = 0; dst_val->v.v_str = data_buf; dst_val->len = src_val->len; dst_val->time = src_val->time; return OK; } len = convertToString(src_type, src_val, data_buf, data_buf_len); if (len < 0) return ERROR; dst_val->v.v_str = data_buf; dst_val->len = len; dst_val->time = src_val->time; return OK; } switch (src_type) { case 'b': rc = convertSignedChar(src_val->v.v_char, dst_type, dst_val); break; case 'B': rc = convertUnsignedChar(src_val->v.v_uchar, dst_type, dst_val); break; case 'h': rc = convertSignedShort(src_val->v.v_short, dst_type, dst_val); break; case 'H': rc = convertUnsignedShort(src_val->v.v_ushort, dst_type, dst_val); break; case 'i': rc = convertSignedInt(src_val->v.v_int, dst_type, dst_val); break; case 'I': rc = convertUnsignedInt(src_val->v.v_uint, dst_type, dst_val); break; case 'l': rc = convertSignedLong(src_val->v.v_long, dst_type, dst_val); break; case 'L': rc = convertUnsignedLong(src_val->v.v_ulong, dst_type, dst_val); break; case 'f': rc = convertFloat(src_val->v.v_float, dst_type, dst_val); break; case 'd': rc = convertDouble(src_val->v.v_double, dst_type, dst_val); break; case 'E': rc = convertEnum(src_val->v.v_enum, dst_type, dst_val); break; case 's': rc = convertFromString(src_val->v.v_str, dst_type, dst_val); break; default: return ERROR; } if (rc == ERROR) return ERROR; switch (dst_val->type) { case 'b': dst_val->len = 1; break; case 'B': dst_val->len = 1; break; case 'h': dst_val->len = 2; break; case 'H': dst_val->len = 2; break; case 'i': dst_val->len = 4; break; case 'I': dst_val->len = 4; break; case 'l': dst_val->len = 4; break; case 'L': dst_val->len = 4; break; case 'q': dst_val->len = 16; break; case 'Q': dst_val->len = 16; break; case 'f': dst_val->len = 4; break; case 'd': dst_val->len = 8; break; case 'D': dst_val->len = 16; break; case 'p': dst_val->len = 4; break; case 'E': dst_val->len = 4; break; case 'v': return ERROR; case 's': return ERROR; default: return ERROR; } dst_val->time = src_val->time; return OK; }
// ###################################################################### std::list<BitObject> ObjectDetection::run(nub::soft_ref<MbariResultViewer> rv, const std::list<Winner> &winlist, const Image< PixRGB<byte> > &segmentInImg) { DetectionParameters p = DetectionParametersSingleton::instance()->itsParameters; std::list<BitObject> bosFiltered; std::list<BitObject> bosUnfiltered; std::list<Winner>::const_iterator iter = winlist.begin(); //go through each winner and extract salient objects while (iter != winlist.end()) { // get the foa mask BitObject boFOA = (*iter).getBitObject(); WTAwinner winner = (*iter).getWTAwinner(); // if the foa mask area is too small, we aren't going to find any large enough objects so bail out if (boFOA.getArea() < p.itsMinEventArea) { iter++; continue; } // if only using the foamask region and not the foamask to guide the detection if (p.itsUseFoaMaskRegion) { LINFO("----------------->Using FOA mask region"); Rectangle foaregion = boFOA.getBoundingBox(); Point2D<int> center = boFOA.getCentroid(); Dims d = segmentInImg.getDims(); Dims segmentDims = Dims((float)foaregion.width()*2.0,(float)foaregion.height()*2.0); Dims searchDims = Dims((float)foaregion.width(),(float)foaregion.height()); Rectangle searchRegion = Rectangle::centerDims(center, searchDims); searchRegion = searchRegion.getOverlap(Rectangle(Point2D<int>(0, 0), segmentInImg.getDims() - 1)); Rectangle segmentRegion = Rectangle::centerDims(center, segmentDims); segmentRegion = segmentRegion.getOverlap(Rectangle(Point2D<int>(0, 0), segmentInImg.getDims() - 1)); // get the region used for searching for a match based on the foa region LINFO("Extracting bit objects from frame %d winning point %d %d/region %s minSize %d maxSize %d %d %d", \ (*iter).getFrameNum(), winner.p.i, winner.p.j, convertToString(searchRegion).c_str(), p.itsMinEventArea, p.itsMaxEventArea, d.w(), d.h()); std::list<BitObject> sobjs = extractBitObjects(segmentInImg, center, searchRegion, segmentRegion, (float)p.itsMinEventArea/2.F, p.itsMaxEventArea); std::list<BitObject> sobjsKeep; // need at least two objects to find a match, otherwise just background if (sobjs.size() > 1 ) { // set the winning voltage for each winning bit object std::list<BitObject>::iterator iter; for (iter = sobjs.begin(); iter != sobjs.end(); ++iter) { if ( (*iter).getArea() >= p.itsMaxEventArea && (*iter).getArea() <= p.itsMaxEventArea) { (*iter).setSMV(winner.sv); sobjsKeep.push_back(*iter); } } // add to the list bosUnfiltered.splice(bosUnfiltered.begin(), sobjsKeep); } else { LINFO("Can't find bit object, checking FOA mask"); if (boFOA.getArea() >= p.itsMinEventArea && boFOA.getArea() <= p.itsMaxEventArea) { boFOA.setSMV(winner.sv); sobjsKeep.push_back(boFOA); bosUnfiltered.splice(bosUnfiltered.begin(), sobjsKeep); LINFO("FOA mask ok %d < %d < %d", p.itsMinEventArea, boFOA.getArea(), p.itsMaxEventArea); } else LINFO("FOA mask too large %d > %d or %d > %d",boFOA.getArea(), p.itsMinEventArea, boFOA.getArea(), p.itsMaxEventArea); } } else { LINFO("----------------->Using FOA mask only"); if (boFOA.getArea() >= p.itsMinEventArea && boFOA.getArea() <= p.itsMaxEventArea) { boFOA.setSMV(winner.sv); bosUnfiltered.push_back(boFOA); LINFO("FOA mask ok %d < %d < %d", p.itsMinEventArea, boFOA.getArea(), p.itsMaxEventArea); } else LINFO("FOA mask too large %d > %d or %d > %d",boFOA.getArea(), p.itsMinEventArea, boFOA.getArea(), p.itsMaxEventArea); } iter++; }// end while iter != winners.end() LINFO("Found %i bitobject(s)", bosUnfiltered.size()); bool found; int minSize = p.itsMaxEventArea; // loop until we find all non-overlapping objects starting with the smallest while (!bosUnfiltered.empty()) { std::list<BitObject>::iterator biter, siter, smallest; // find the smallest object smallest = bosUnfiltered.begin(); for (siter = bosUnfiltered.begin(); siter != bosUnfiltered.end(); ++siter) if (siter->getArea() < minSize) { minSize = siter->getArea(); smallest = siter; } // does the smallest object intersect with any of the already stored ones found = true; for (biter = bosFiltered.begin(); biter != bosFiltered.end(); ++biter) { if (smallest->isValid() && biter->isValid() && biter->doesIntersect(*smallest)) { // no need to store intersecting objects -> get rid of smallest // and look for the next smallest bosUnfiltered.erase(smallest); found = false; break; } } if (found && smallest->isValid()) bosFiltered.push_back(*smallest); } LINFO("Found total %d non intersecting objects", bosFiltered.size()); return bosFiltered; }
void MedeaTwoSunsWorldObserver::step() { if ( gWorld->getIterations() % ( int(MedeaTwoSunsSharedData::gEvaluationTime * MedeaTwoSunsSharedData::gSunLifetime) ) == 0 ) { gEnergyPoints[MedeaTwoSunsSharedData::gActiveSun].hide(); MedeaTwoSunsSharedData::gActiveSun = ( MedeaTwoSunsSharedData::gActiveSun + 1 ) % 2; std::cout << "\nActive Sun #" << MedeaTwoSunsSharedData::gActiveSun << "\n"; gEnergyPoints[MedeaTwoSunsSharedData::gActiveSun].display(); } // *** // * update iteration and generation counters + switch btw experimental setups if required // *** _lifeIterationCount++; if( _lifeIterationCount >= MedeaTwoSunsSharedData::gEvaluationTime ) // go to next generation. { // * monitoring: count number of active agents. int activeCount = 0; for ( int i = 0 ; i != gAgentCounter ; i++ ) { if ( (dynamic_cast<MedeaTwoSunsAgentWorldModel*>(gWorld->getAgent(i)->getWorldModel()))->getActiveStatus() == true ) activeCount++; } if ( !gVerbose ) { std::cout << "[" << activeCount << "]"; } gLogFile << "Info(" << gWorld->getIterations() << ") : active count is " << activeCount << std::endl; // * monitor and log orientation and distance to center for all agents // build heatmap int heatmapSize = 100; // arbitrary, but should be enough to get precise view int maxDistance = sqrt ( gAreaWidth*gAreaWidth + gAreaHeight*gAreaHeight ) / 2.0 ; // distance max to center. int *distanceHeatmap; distanceHeatmap = new int[heatmapSize]; int *orientationHeatmap; orientationHeatmap = new int[heatmapSize]; for (int i = 0 ; i != heatmapSize ; i++ ) { distanceHeatmap[i] = 0; orientationHeatmap[i] = 0; } double xRef = gAreaWidth / 2.0 ; double yRef = gAreaHeight / 2.0 ; for ( int i = 0 ; i != gAgentCounter ; i++ ) { MedeaTwoSunsAgentWorldModel *wm = (dynamic_cast<MedeaTwoSunsAgentWorldModel*>(gWorld->getAgent(i)->getWorldModel())); if ( wm->getActiveStatus() == true ) // only active agents { // monitor distance double dist = getEuclidianDistance( xRef, yRef, wm->_xReal, wm->_yReal ); int indexDist = (int)dist * heatmapSize / maxDistance; // normalize within heatmap bounds distanceHeatmap[indexDist]++; // monitor orientationHeatmap double orient = acos ( ( wm->_xReal - xRef ) / (double)dist ); if ( wm->_yReal - yRef > 0 ) // [trick] why ">0" ? : it should be <0, but as the 2D-display norm for the coordinate system origin is upper-left (and not bottom-left), the sign is inversed. { orient = -orient; } int indexOrient = ( orient + M_PI ) * heatmapSize / (2.0 * M_PI); orientationHeatmap[heatmapSize-1-((indexOrient+((heatmapSize*3)/4))%heatmapSize)]++; // index is such that list ordering is as follow: [South-West-North-East-South] //std::cout << "\n agent[" << wm->_xReal << "," << wm->_yReal << "](" << dist << "," << orient << ") -- " << wm->_xReal << ";" << xRef << ";" << ( ( wm->_xReal - xRef ) / (double)dist ) << ";" << acos ( ( wm->_xReal - xRef ) / (double)dist ); //debug } } //std::cout << "\n"; //debug // update log file std::string str_agentDistancesToRef =""; std::string str_agentOrientationsToRef = ""; for (int i = 0 ; i != heatmapSize ; i++ ) { str_agentDistancesToRef += convertToString(distanceHeatmap[i]); str_agentDistancesToRef += ","; str_agentOrientationsToRef += convertToString(orientationHeatmap[i]); str_agentOrientationsToRef += ","; } //gLogFile //std::cout << std::endl << std::endl;//debug //gLogFile << "Info(" << gWorld->getIterations() << ") : monitor distance to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentDistancesToRef << std::endl; //gLogFile << "Info(" << gWorld->getIterations() << ") : monitor orientation to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentOrientationsToRef << std::endl; for ( int i = 0 ; i != heatmapSize ; i++ ) { gLogFile << "monitorDistance: " << gAgentCounter << "," << (int)sqrt(gMaxRadioDistanceToSquare) << "," << (_generationCount+1) << "," << i << "," << distanceHeatmap[i] << std::endl; gLogFile << "monitorOrientation: " << gAgentCounter << "," << (int)sqrt(gMaxRadioDistanceToSquare) << "," << (_generationCount+1) << "," << i << "," << orientationHeatmap[i] << std::endl; } //gLogFile << "Info(" << gWorld->getIterations() << ") : monitor distance to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentDistancesToRef << std::endl; //gLogFile << "Info(" << gWorld->getIterations() << ") : monitor orientation to ref - " << (_generationCount+1) << "," << gAgentCounter << "," << str_agentOrientationsToRef << std::endl; delete [] distanceHeatmap; delete [] orientationHeatmap; // * update iterations and generations counters _lifeIterationCount = 0; _generationCount++; // * Switch btw experiment setups, if required updateExperimentalSettings(); } // * Update environment status wrt. nature and availability of energy resources (update at each iteration) updateEnvironmentResources(); // * update energy level for each agents (ONLY active agents) updateAllAgentsEnergyLevel(); // prepape and take screenshot of ultimate iteration if ( gWorld->getIterations() == gMaxIt-2 ) { gDisplayMode = 0; gDisplaySensors = true; // prepape for next it. } else { if ( gWorld->getIterations() == gMaxIt-1 ) saveScreenshot("lastIteration"); } }
/** * \brief Function to add a new VISHNU user * \fn int add(UMS_Data::User*& user, int vishnuId) * \param user The user data structure * \param vishnuId The identifier of the vishnu instance * \param sendmailScriptPath The path to the script for sending emails * \return raises an exception on error */ int UserServer::add(UMS_Data::User*& user, int vishnuId, std::string sendmailScriptPath) { std::string pwd; std::string sqlUpdate = "update users set "; std::string idUserGenerated; std::string passwordCrypted; std::string formatiduser; if (exist()) { if (isAdmin()) { //Generation of password pwd = generatePassword(user->getLastname(), user->getFirstname()); user->setPassword(pwd.substr(0,PASSWORD_MAX_SIZE)); //Generation of userid idUserGenerated = vishnu::getObjectId(vishnuId, "formatiduser", USER, user->getLastname()); user->setUserId(idUserGenerated); //To get the password encrypted passwordCrypted = vishnu::cryptPassword(user->getUserId(), user->getPassword()); // If there only one field reserved by getObjectId if (getAttribut("where userid='"+user->getUserId()+"'","count(numuserid)") == "1") { //To active the user status user->setStatus(ACTIVE_STATUS); sqlUpdate+="vishnu_vishnuid="+convertToString(vishnuId)+", "; sqlUpdate+="pwd='"+passwordCrypted+"', "; sqlUpdate+="firstname='"+user->getFirstname()+"', "; sqlUpdate+="lastname='"+user->getLastname()+"', "; sqlUpdate+="privilege="+convertToString(user->getPrivilege())+", "; sqlUpdate+="email='"+user->getEmail()+"', "; sqlUpdate+="passwordstate=0, "; sqlUpdate+="status="+convertToString(user->getStatus())+" "; sqlUpdate+="where userid='"+user->getUserId()+"';"; mdatabaseVishnu->process(sqlUpdate); //Send email std::string emailBody = getMailContent(*user, true); sendMailToUser(*user, emailBody, "Vishnu message: user created", sendmailScriptPath); }// END If the user to add exists else { UMSVishnuException e (ERRCODE_USERID_EXISTING); throw e; } } //END if the user is an admin else { UMSVishnuException e (ERRCODE_NO_ADMIN); throw e; } } //END if the user exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USER); throw e; } return 0; }//END: add(UMS_Data::User*& user)
/** * \brief Function to update user information * \fn int update(UMS_Data::User*& user) * \param user The user data structure * \return raises an exception on error */ int UserServer::update(UMS_Data::User *user) { std::string sqlCommand = ""; if (exist()) { if (isAdmin()) { //if the user whose information will be updated exists if (getAttribut("where userid='"+user->getUserId()+"'").size() != 0) { //if a new fisrtname has been defined if (user->getFirstname().size() != 0) { sqlCommand.append("UPDATE users SET firstname='"+user->getFirstname()+"'" " where userid='"+user->getUserId()+"';"); } //if a new lastname has been defined if (user->getLastname().size() != 0) { sqlCommand.append("UPDATE users SET lastname='"+user->getLastname()+"'" " where userid='"+user->getUserId()+"';"); } //if a new email has been defined if (user->getEmail().size() != 0) { sqlCommand.append("UPDATE users SET email='"+user->getEmail()+"'" " where userid='"+user->getUserId()+"';"); } //If a new status has been defined if (user->getStatus() != UNDEFINED_VALUE) { //if the user will be locked if (user->getStatus() == 0) { //if the user is not already locked if (convertToInt(getAttribut("where userid='"+user->getUserId()+"'", "status")) != 0) { sqlCommand.append("UPDATE users SET status="+convertToString(user->getStatus())+"" " where userid='"+user->getUserId()+"';"); } //End if the user is not already locked else { UMSVishnuException e (ERRCODE_USER_ALREADY_LOCKED); throw e; } } //End if the user will be locked else { sqlCommand.append("UPDATE users SET status="+convertToString(user->getStatus())+"" " where userid='"+user->getUserId()+"';"); } } // if the user whose privilege will be updated is not an admin if (convertToInt(getAttribut("where userid='"+user->getUserId()+"'", "privilege")) != 1) { sqlCommand.append("UPDATE users SET privilege="+convertToString(user->getPrivilege())+"" " where userid='"+user->getUserId()+"';"); } //If there is a change if (!sqlCommand.empty()) { mdatabaseVishnu->process(sqlCommand.c_str()); } } // End if the user whose information will be updated exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USERID); throw e; } } //END if the user is an admin else { UMSVishnuException e (ERRCODE_NO_ADMIN); throw e; } } //END if the user exists else { UMSVishnuException e (ERRCODE_UNKNOWN_USER); throw e; } return 0; } //END: update(UMS_Data::User *user)
string getPlural(const string& a, int num) { if (num == 1) return "1 " + a; else return convertToString(num) + " " + a + "s"; }
int main(void) { int n1 = 100; int n2 = n1 + 1; cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue queue; cl_program program; cl_kernel kernel; cl_int err; const char* fileName; const char* kernelName; FILE *program_handle; char *program_buffer, *program_log; size_t program_size, log_size; std::string programLog; float **x = new float*[n1]; float **h_xx = new float*[n1]; float *h_x1 = new float[n1*n2]; for(int i = 0; i < n1; i++) { x[i] = new float[n2]; h_xx[i] = new float[n2]; for(int j = 0; j < n2; j++) { x[i][j] = i*j; } } err = clGetPlatformIDs(1, &platform, NULL); if (err != CL_SUCCESS){ std::cout << "Error: Failed to locate the platform." << std::endl; system("pause"); exit(1); } err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL); if(err != CL_SUCCESS){ std::cout << "Error: Failed to locate the device." << std::endl; std::cout << "OpenCL Error code: " << err << std::endl; system("pause"); exit(1); } context = clCreateContext(NULL, 1, &device, NULL, NULL, &err); if(err != CL_SUCCESS){ std::cout << "Error: Could not create a context." << std::endl; system("pause"); exit(1); } fileName = "simple2Dindex.cl"; std::string sourceStr; int status = convertToString(fileName, sourceStr); const char *source = sourceStr.c_str(); size_t sourceSize[] = {strlen(source)}; program = clCreateProgramWithSource(context, 1, &source, sourceSize, NULL); if(err != CL_SUCCESS){ std::cout << "Error: Could not create the program" << std::endl; system("pause"); exit(1); } err = clBuildProgram(program, 1, &device, "-cl-strict-aliasing -cl-unsafe-math-optimizations -cl-finite-math-only -cl-fast-relaxed-math -DMAC" , NULL, NULL); if(err != CL_SUCCESS){ std::cout << "Error: Could not compile the program" << std::endl; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); program_log = (char*)malloc(log_size+1); program_log[log_size] = '\0'; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size+1, program_log, NULL); programLog = program_log; std::cout << programLog << std::endl; free(program_log); system("pause"); exit(1); } kernel = clCreateKernel(program, "indexing", &err); if(err != CL_SUCCESS){ std::cout << "Error: Could not create the kernel." << std::endl; system("pause"); exit(1); } queue = clCreateCommandQueue(context, device, 0, &err); if(err != CL_SUCCESS){ std::cout << "Error: Could not create the queue." << std::endl; system("pause"); exit(1); } cl_mem d_xx; d_xx = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*n1*n2, NULL, &err); if(err != CL_SUCCESS){ std::cout << "Error: Could not create the buffer." << std::endl; std::cout << "OpenCL Error code: " << err << std::endl; system("pause"); exit(1); } err = clEnqueueWriteBuffer(queue, d_xx, CL_FALSE, 0, sizeof(float)*n1*n2, h_x1, 0, NULL, NULL); if(err != CL_SUCCESS){ std::cout << "Error: Could not write to buffer." << std::endl; std::cout << "OpenCL Error Code: " << std::endl; system("pause"); exit(1); } err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &d_xx); if(err != CL_SUCCESS){ std::cout << "Error: Could not set the kernel argument." << std::endl; std::cout << "OpenCL error code: " << err << std::endl; exit(1); } err = clSetKernelArg(kernel, 1, sizeof(int), &n1); if(err != CL_SUCCESS){ std::cout << "Error: Could not set the kernel argument." << std::endl; std::cout << "OpenCL error code: " << err << std::endl; exit(1); } err = clSetKernelArg(kernel, 2, sizeof(int), &n2); if(err != CL_SUCCESS){ std::cout << "Error: Could not set the kernel argument." << std::endl; std::cout << "OpenCL error code: " << err << std::endl; exit(1); } size_t local_work_group_size[2] = {32,32}; size_t global_work_group_size[2] = {ceil((n1/local_work_group_size[0]) + 1) * local_work_group_size[0], ceil((n2/local_work_group_size[1]) + 1) * local_work_group_size[1]}; err = clEnqueueNDRangeKernel(queue, kernel, 2, NULL, global_work_group_size, local_work_group_size, 0, NULL, NULL); if(err != CL_SUCCESS){ std::cout << "Error: Could not execute the kernel." << std::endl; std::cout << "OpenCL error code: " << err << std::endl; system("pause"); exit(1); } err = clEnqueueReadBuffer(queue, d_xx, CL_TRUE, 0, sizeof(float)*n1*n2, h_x1, 0, NULL, NULL); if(err != CL_SUCCESS){ std::cout << "Error: Could not read data from the device." << std::endl; std::cout << "OpenCL error code: " << std::endl; exit(1); } clReleaseMemObject(d_xx); clReleaseKernel(kernel); clReleaseCommandQueue(queue); clReleaseProgram(program); clReleaseContext(context); int k = 0; for (int i = 0; i < n1; i++){ for (int j = 0; j < n2; j++){ h_xx[i][j] = h_x1[k]; k++; } } bool check = true; for(int i = 0; i < n1; i++) { for(int j = 0; j < n2; j++) { if(x[i][j] == h_xx[i][j]) { continue; } else { check = false; printf("Check failed at array element (%d, %d)\n", i, j); printf("CPU Value: %f\n", x[i][j]); printf("GPU Value: %f\n", h_xx[i][j]); printf("Percent Difference: %.5f Percent\n", x[i][j]/h_xx[i][j]*100.f); system("pause"); exit(1); } } } if(check == true) std::cout << "Check Passed!" << std::endl << std::endl; else std::cout << "Check Failed!" << std::endl << std::endl; delete [] h_x1; //Deallocating the 2D arrays for (int i = 0; i < n1; i++) { delete [] x[i]; delete [] h_xx[i]; } delete [] x; delete [] h_xx; return 0; }
string Player::getPluralName(Item* item, int num) { if (num == 1) return item->getTheName(false, creature->isBlind()); else return convertToString(num) + " " + item->getTheName(true, creature->isBlind()); }
//Load CL file, compile, link CL source //Try to find a precompiled binary //Build program and kernel objects void makeCLKernel(const char *kernelName,int deviceNum) { //Kernel Loading/Compilation //Attempt to load precompiled binary file for target device char binFileName[MAX_NAME_LENGTH]; sprintf(binFileName,"%s_%s.elf",kernelName,deviceName); std::fstream inBinFile(binFileName, (ios::in|ios::binary|ios::ate)); //Compile if(inBinFile.fail()) { inBinFile.close(); printf("No binary image found for specified kernel.Compiling from source.\n"); char sourceFileName[MAX_NAME_LENGTH]; sprintf(sourceFileName,"%s.cl",kernelName); std::string sourceStr = convertToString(sourceFileName); if (sourceStr == "NULL") exitOnError("Cannot read kernel source file"); const char *source = (char*)sourceStr.c_str(); size_t sourceSize[] = { strlen(source) }; program = clCreateProgramWithSource( context, 1, &source, sourceSize, &status); if(status != CL_SUCCESS) exitOnError("Loading Source into cl_program (clCreateProgramWithSource)"); // create a cl program executable for all the devices specified status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL); if (status != CL_SUCCESS) { //Build failed. printf("Error building program(clBuildProgram)\nCompiler Output:\n"); //Retrieve the size of the build log char* build_log; size_t log_size; status = clGetProgramBuildInfo(program, devices[deviceNum], CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); if(status != CL_SUCCESS) exitOnError("Cannot get compiler log size.(clGetProgramBuildInfo)"); build_log = (char*)malloc(log_size+1); // Get and display the build log status = clGetProgramBuildInfo(program, devices[deviceNum], CL_PROGRAM_BUILD_LOG, log_size, build_log, NULL); if(status != CL_SUCCESS) exitOnError("Cannot get compiler log.(clGetProgramBuildInfo)"); build_log[log_size] = '\0'; printf("%s\n",build_log); free (build_log); printf("End of Compiler Output.\n"); exit(1); } //Export Binary Images to file dumpBinary(program,kernelName); }else{ size_t *binSize = (size_t*)malloc(sizeof(size_t)); char* bin; *binSize = inBinFile.tellg(); inBinFile.seekg (0, ios::beg); bin = new char[*binSize]; inBinFile.read(bin,*binSize); inBinFile.close(); program = clCreateProgramWithBinary( context, 1, &devices[deviceNum], binSize, (const unsigned char **)&bin, NULL, &status); if(status != CL_SUCCESS) exitOnError("Loading Binary into cl_program (clCreateProgramWithBinary)"); // create a cl program executable for all the devices specified status = clBuildProgram(program,1, &devices[deviceNum], NULL, NULL, NULL); if (status != CL_SUCCESS) { //Build failed. printf("Error building program(clBuildProgram)\nCompiler Output:\n"); //Retrieve the size of the build log char* build_log; size_t log_size; status = clGetProgramBuildInfo(program, devices[deviceNum], CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); if(status != CL_SUCCESS) exitOnError("Cannot get compiler log size.(clGetProgramBuildInfo)"); build_log = (char*)malloc(log_size+1); // Get and display the build log status = clGetProgramBuildInfo(program, devices[deviceNum], CL_PROGRAM_BUILD_LOG, log_size, build_log, NULL); if(status != CL_SUCCESS) exitOnError("Cannot get compiler log.(clGetProgramBuildInfo)"); build_log[log_size] = '\0'; printf("%s\n",build_log); free (build_log); printf("End of Compiler Output."); exit(1); } } // get a kernel object handle for a kernel with the given name kernel = clCreateKernel(program,kernelName,&status); if(status != CL_SUCCESS) exitOnError("Creating Kernel from program. (clCreateKernel)"); }