Feature SupportVectorMachine::getWeights() const { if(_model == NULL) throw CError("Asking for SVM weights but there is no model. Either load one from file or train one before."); Feature weightVec(_fVecShape); weightVec.ClearPixels(); weightVec.origin[0] = _fVecShape.width / 2; weightVec.origin[1] = _fVecShape.height / 2; int nSVs = _model->l; // number of support vectors for(int s = 0; s < nSVs; s++) { double coeff = _model->sv_coef[0][s]; svm_node* sv = _model->SV[s]; for(int y = 0, d = 0; y < _fVecShape.height; y++) { float* w = (float*) weightVec.PixelAddress(0,y,0); for(int x = 0; x < _fVecShape.width * _fVecShape.nBands; x++, d++, w++, sv++) { assert(sv->index == d); *w += sv->value * coeff; } } } return weightVec; }
void ReadFile (CImage& img, const char* filename) { // Determine the file extension const char *dot = strrchr(filename, '.'); if (strcmp(dot, ".tga") == 0 || strcmp(dot, ".tga") == 0) { if ((&img.PixType()) == 0) img.ReAllocate(CShape(), typeid(uchar), sizeof(uchar), true); if (img.PixType() == typeid(uchar)) ReadFileTGA(*(CByteImage *) &img, filename); else throw CError("ReadFile(%s): haven't implemented conversions yet", filename); } else throw CError("ReadFile(%s): file type not supported", filename); }
bool CBaseLexer::CheckOverflowDirective() { SkipSpaces(); CTokenWord* tkn = (CTokenWord*)IsStringToken(); if (tkn == 0) throw CError("expected value for 'overflow' directive",nLine); if (strcmp(tkn->GetValue(), "extent")==0) CIdValue::SetOverflow(OF_EXTENT);else if (strcmp(tkn->GetValue(), "error")==0) CIdValue::SetOverflow(OF_ERROR);else if (strcmp(tkn->GetValue(), "skip")==0) CIdValue::SetOverflow(OF_SKIP);else throw CError("unknown value for 'overflow' directive",nLine); delete tkn; return true; }
static void Check(void) { PyObject* err_type = PyErr_Occurred(); if ( err_type ) { throw CError(); } }
void ReadFileJPEG(CImage& img, const char* filename) { JPEGReader loader; loader.header(filename); if(loader.components() != loader.colorComponents()) { throw CError("Loading of indexed JPEG not implemented"); } CByteImage imgAux(loader.width(), loader.height(), loader.components()); std::vector<uchar*> rowPointers(loader.height()); CShape shape = imgAux.Shape(); for(int y = 0; y < shape.height; y++) { rowPointers[shape.height - y - 1] = (uchar*) imgAux.PixelAddress(0,y,0); } loader.load(rowPointers.begin()); img.ReAllocate(shape, typeid(uchar), sizeof(uchar), true); // Reverse color channel order for(int y = 0; y < shape.height; y++) { uchar* auxIt = (uchar*)imgAux.PixelAddress(0, y, 0); uchar* imgIt = (uchar*)img.PixelAddress(0, y, 0); for(int x = 0; x < shape.width; x++, auxIt += shape.nBands, imgIt += shape.nBands) { for(int c = 0; c < shape.nBands; c++) { imgIt[c] = auxIt[shape.nBands - c - 1]; } } } }
int main(int argc, char *argv[]) { try { int argn = 1; if (argc > 1 && argv[1][0]=='-' && argv[1][1]=='q') { verbose = 0; argn++; } if (argn >= argc-3 && argn <= argc-2) { char *flowname = argv[argn++]; char *outname = argv[argn++]; float maxmotion = argn < argc ? atof(argv[argn++]) : -1; CFloatImage im, fband; ReadFlowFile(im, flowname); CByteImage band, outim; CShape sh = im.Shape(); sh.nBands = 3; outim.ReAllocate(sh); outim.ClearPixels(); MotionToColor(im, outim, maxmotion); WriteImageVerb(outim, outname, verbose); } else throw CError(usage, argv[0]); } catch (CError &err) { fprintf(stderr, err.message); fprintf(stderr, "\n"); return -1; } return 0; }
void SupportVectorMachine::load(const char *filename) { FILE* f = fopen(filename, "rb"); if(f == NULL) throw CError("Failed to open file %s for reading", filename); this->load(f); }
CError CSystemStateMachine::onCounterCADisconnected() { LOG4CPLUS_TRACE(sLogger, __PRETTY_FUNCTION__); hardReset(true); return CError(CError::NO_ERROR, "SystemStateMachine"); }
CError CSystemStateMachine::onAuthenticationCanceled() { LOG4CPLUS_TRACE(sLogger, "onAuthenticationCanceled()"); mSystemState->cancelAuthentication(this); return CError(CError::NO_ERROR, "SystemStateMachine"); }
double SupportVectorMachine::getBiasTerm() const { if(_model == NULL) throw CError("Asking for SVM bias term but there is no " "model. Either load one from file or train one before."); return _model->rho[0]; }
void WriteFile(CImage& img, const char* filename) { // Determine the file extension char *dot = strrchr(filename, '.'); // Fixed by Loren. Was: // if (strcmp(dot, ".tga") == 0 || strcmp(dot, ".tga") == 0) if (dot != NULL && strcmp(dot, ".tga") == 0) { if (img.PixType() == typeid(uchar)) WriteFileTGA(*(CByteImage *) &img, filename); else throw CError("ReadFile(%s): haven't implemented conversions yet", filename); } else throw CError("WriteFile(%s): file type not supported", filename); }
/////////////////////////////////// // Make new Tank on BattleField // // Params: // name - tank name // x - coord on X axis // y - coord on Y axis // angle - facing direction void CBattleField::MakeTank(PointName_t name, Pixel_t x, Pixel_t y, Angle_t angle) { //Checking for tank exist if (GetTankByName(name)) throw CError(ERR_TANK_EXIST); //Add Tank on BattleField! _points.push_back(CPoint(name, x, y, angle, g_TankVelocity, STOP, false)); }
CError write(T const& val) { if (sizeof(T) > mFullSize - mUsedSize) return CError(1, moduleName, CError::ERROR, "insufficient buffer size (from generic write)"); *reinterpret_cast<T*>(mpBuffer + mUsedSize) = val; mUsedSize += sizeof(T); return CError::NoError(moduleName); }
bstr::bstr( char *str ) { ptr = NULL; size = 0; if ( assign( str ) == false ) throw CError( "bstr::bstr 메모리 할당 실패" ); }
CGlobalUserList::CGlobalUserList() : m_fixedMemory( GLOBALLIST_MAXLIST ) { if ( !m_listUser.InitHashTable( GLOBALLIST_MAXBUCKET, IHT_ROUNDUP ) ) throw CError( "CGlobalUserList::CGlobalUserList 해쉬테이블 생성 실패" ); m_listUser.SetGetKeyFunction( __cbGetKey ); }
IplImage* IPLCreateImage(CImage img) { // Compute the required parameters CShape sh = img.Shape(); int nChannels = sh.nBands; // Number of channels in the image. int alphaChannel = // Alpha channel number (0 if there is no alpha channel in the image). (nChannels == 4) ? img.alphaChannel+1 : 0; int depth = // Bit depth of pixels. Can be one of: (img.PixType() == typeid(uchar)) ? IPL_DEPTH_8U : (img.PixType() == typeid(char)) ? IPL_DEPTH_8S : (img.PixType() == typeid(unsigned short)) ? IPL_DEPTH_16U : (img.PixType() == typeid(short)) ? IPL_DEPTH_16S : (img.PixType() == typeid(int )) ? IPL_DEPTH_32S : (img.PixType() == typeid(float)) ? IPL_DEPTH_32F : 0; char* colorModel = // A four-character string describing the color model. (nChannels == 1) ? "Gray" : "RGBA"; char* channelSeq = // The sequence of color channels. (nChannels == 1) ? "GRAY" : "BGRA"; int dataOrder = IPL_DATA_ORDER_PIXEL; int origin = IPL_ORIGIN_TL; // The origin of the image. int align = // Alignment of image data. ((((int) img.PixelAddress(0, 0, 0)) | ((int) img.PixelAddress(0, 1, 0))) & 7) ? IPL_ALIGN_DWORD : IPL_ALIGN_QWORD; int width = sh.width; // Width of the image in pixels. int height = sh.height; // Height of the image in pixels. IplROI* roi = 0; // Pointer to an ROI (region of interest) structure. IplImage* maskROI = 0; // Pointer to the header of another image that specifies the mask ROI. void* imageID = 0; // The image ID (field reserved for the application). IplTileInfo* tileInfo = 0; // The pointer to the IplTileInfo structure // Create the header IplImage* ptr = iplCreateImageHeader( nChannels, alphaChannel, depth, colorModel, channelSeq, dataOrder, origin, align, width, height, roi, maskROI, imageID, tileInfo); if (ptr == 0) throw CError("IPLCreateImage: could not create the header"); // Fill in the image data pointers char* imgData = ((char *) img.PixelAddress(0, 0, 0)); int nBytes = ((char *) img.PixelAddress(0, 1, 0)) - imgData; ptr->imageSize = nBytes * sh.height; // useful size in bytes ptr->imageData = imgData; // pointer to aligned image ptr->widthStep = nBytes; // size of aligned line in bytes ptr->imageDataOrigin = imgData; // ptr to full, nonaligned image // Set the border mode int mode = (img.borderMode == eBorderZero) ? IPL_BORDER_CONSTANT : (img.borderMode == eBorderReplicate)? IPL_BORDER_REPLICATE : (img.borderMode == eBorderReflect) ? IPL_BORDER_REFLECT : (img.borderMode == eBorderCyclic) ? IPL_BORDER_WRAP : 0; iplSetBorderMode(ptr, mode, IPL_SIDE_ALL, 0); return ptr; }
void CodeGenerator::ProcessClassTerm(int flags) { Class *class_ptr; infunc(CodeGenerator::ProcessClassTerm); if (flags & FLAGS_IN_CLASS) throw CompileError("(Line %d) Already within a class", CUR_TOKEN.line); if (NEXT_TOKEN.type != TOKEN_NAME) throw CompileError("(Line %d) Expecting class name", CUR_TOKEN.line); // Move onto the name and grab it INC_TOKEN; IsolateTokenString(CUR_TOKEN); // Sneak passed it INC_TOKEN; if (g_Object == NULL) { // Allocate the memory if ((class_ptr = new Class) == NULL) throw CError("Couldn't allocate Class structure"); class_ptr->SetName(token_string); } else { // Class already defined, get it from the environment class_ptr = g_Env->GetClass(token_string); } ProcessClassModifiers(class_ptr); // Set the current class g_Env->SetActiveClass(class_ptr); cur_class = class_ptr; ProcessBlock(flags | FLAGS_IN_CLASS); // Go passed the close block INC_TOKEN; if (g_Object == NULL) { // Add the defined class to the environment class_ptr->SetDefined(); g_Env->AddClassPtr(class_ptr); } else { // Write the class information to file g_Object->WriteClassInfo(cur_class); } outfunc; }
void CodeGenerator::ProcessReturnTerm(int flags) { infunc(CodeGenerator::ProcessKeywordTerm); ParseTree *tree; if (!(flags & FLAGS_IN_FUNCTION)) throw CompileError("(Line %d) Cannot specify return keyword outside of a function", CUR_TOKEN.line); INC_TOKEN; // Does this function return any values? if (cur_class->cur_function->GetReturnType().id == VARIABLE_TYPEID_VOID) { // Can only end here if (CUR_TOKEN.type != TOKEN_END_OF_LINE) throw CompileError("(Line %d) Cannot specify return value for void function", CUR_TOKEN.line); return; } // Allocate the parse tree if ((tree = new ParseTree) == NULL) throw CError("Couldn't allocate parse tree"); // Build the parse tree tree->Build(tokeniser, TOKEN_END_OF_LINE, TOKEN_NULL); // Reduce it tree->Optimise(); if (g_Object) { tree->CompleteTypes(flags | FLAGS_IMPLICIT_ASSIGNMENT); tree->GenerateCode(flags | FLAGS_IMPLICIT_ASSIGNMENT); } // Don't need the tree delete tree; // Mark the return cur_class->cur_function->had_return = 1; if (g_Object) { // Pop the return value to a safe place if (cur_class->cur_function->GetReturnType().id != VARIABLE_TYPEID_VOID) g_Object->WriteOp(OPCODE_POP_RETURN); // Write the return code cur_class->cur_function->WriteReturn(g_Object); } outfunc; }
void SupportVectorMachine::load(FILE* fp) { deinit(); fscanf(fp, "%d %d %d", &_fVecShape.width, &_fVecShape.height, &_fVecShape.nBands); _model = svm_load_model_fp(fp); if(_model == NULL) { throw CError("Failed to load SVM model"); } }
CError CSystemStateMachine::onCounterCAConnected(UInt8 role) { LOG4CPLUS_TRACE(sLogger, "onCounterCAConnected(" + convertIntegerToString(role) + ")"); mSystemGender = role; mSystemState->onConnectivityAgentHandshakeDone(this); return CError(CError::NO_ERROR, "SystemStateMachine"); }
/* ** Reads the measure specific configs. ** */ void CMeasureRegistry::ReadConfig(CConfigParser& parser, const WCHAR* section) { CMeasure::ReadConfig(parser, section); const WCHAR* keyname = parser.ReadString(section, L"RegHKey", L"HKEY_CURRENT_USER").c_str(); if (_wcsicmp(keyname, L"HKEY_CURRENT_USER") == 0) { m_HKey = HKEY_CURRENT_USER; } else if (_wcsicmp(keyname, L"HKEY_LOCAL_MACHINE") == 0) { m_HKey = HKEY_LOCAL_MACHINE; } else if (_wcsicmp(keyname, L"HKEY_CLASSES_ROOT") == 0) { m_HKey = HKEY_CLASSES_ROOT; } else if (_wcsicmp(keyname, L"HKEY_CURRENT_CONFIG") == 0) { m_HKey = HKEY_CURRENT_CONFIG; } else if (_wcsicmp(keyname, L"HKEY_PERFORMANCE_DATA") == 0) { m_HKey = HKEY_PERFORMANCE_DATA; } else if (_wcsicmp(keyname, L"HKEY_DYN_DATA") == 0) { m_HKey = HKEY_DYN_DATA; } else { std::wstring error = L"RegHKey="; error += keyname; error += L" is not valid in ["; error += m_Name; error += L']'; throw CError(error); } m_RegKeyName = parser.ReadString(section, L"RegKey", L""); m_RegValueName = parser.ReadString(section, L"RegValue", L""); if (m_MaxValue == 0.0) { m_MaxValue = 1.0; m_LogMaxValue = true; } // Try to open the key if (m_RegKey) RegCloseKey(m_RegKey); RegOpenKeyEx(m_HKey, m_RegKeyName.c_str(), 0, KEY_READ, &m_RegKey); }
////////////////////////////////////////////////////////////////////////////// /// @brief sets a new value in the VMC but not here in the API /// @returns true = OK / false = Error ////////////////////////////////////////////////////////////////////////////// bool CSendTwo::Set( const double Value1, const double Value2) { if(!m_bInitialized) { VMC_Errors.push_back( CError("not initialized", "CStendTwo::Set()") ); return false; } CMessage MessageToSend(m_CommandGroup, m_Command); if(!MessageToSend.appendToDataFrame(Value1, m_DataType)) { VMC_Errors.push_back( CError("out of datatype range", "CStendTwo::Set()") ); return false; } if(!MessageToSend.appendToDataFrame(Value2, m_DataType)) { VMC_Errors.push_back( CError("out of datatype range", "CStendTwo::Set()") ); return false; } if(m_CommandGroup == 0x52) { // Motor Control Command if(!MessageToSend.appendToDataFrame(*m_pNextRequestCommand, UnsignedChar)) { VMC_Errors.push_back( CError("out of datatype range", "CStendTwo::Set()") ); return false; } } ///////////////////////////////////DEBUG/////////////////////////////////////////// #ifdef VMC_DEBUG std::cout <<" sendtwo " << MessageToSend << "\n"; //debug only #endif ///////////////////////////////////DEBUG/////////////////////////////////////////// if(false == m_pTrans->sendMessage(MessageToSend)) { VMC_Errors.push_back( CError("unable to send to adapter", "CStendTwo::Set()") ); return false; } return true; }
CError CBufferWriter::write<std::string>(std::string const& val) { UInt32 valSize = val.size(); CError err = write(valSize); if (!err.isNoError()) return err; if (valSize > mFullSize - mUsedSize) return CError(1, moduleName, CError::ERROR, "insufficient buffer size (from std::string write)"); memcpy(mpBuffer + mUsedSize, val.c_str(), valSize); mUsedSize += valSize; return CError::NoError(moduleName); }
void InverseWarpLine(float src[], float dst[], float disp[], int w, int n_bands, int order, float *fwd_disp, float disp_gap) { // Inverse warp a single line for (int x = 0; x < w ; x++, dst += n_bands) { // Warped (source) location float d = disp[x]; float y = x - d; if (y < 0.0 || y > w-1) continue; // Check for occlusion/gap int xx = int(y); if (fwd_disp && disp_gap && fabs(d - fwd_disp[xx]) >= disp_gap) continue; // Resampling float *ps0 = &src[xx * n_bands]; if (order == 0 || xx == y) memcpy(dst, ps0, n_bands*sizeof(float)); else if (order == 1 || xx-1 < 0 || xx+2 > w-1) { // Linear interpolation float f = y - xx; float *ps1 = &ps0[n_bands]; for (int b = 0; b < n_bands; b++) { float v = ps0[b] + f * (ps1[b] - float(ps0[b])); dst[b] = v; } } else if (order == 3) { // Cubic interpolation float f = y - xx; float *psp = &ps0[-n_bands]; float *ps1 = &ps0[n_bands]; float *ps2 = &ps0[2*n_bands]; for (int b = 0; b < n_bands; b++) { float v = CubicInterpolate(f, (float) psp[b], (float) ps0[b], (float) ps1[b], (float) ps2[b]); dst[b] = v; } } else throw CError("InverseWarp: order = %d not implemented", order); } }
CError CBufferWriter::write<iviLink::CUid>(iviLink::CUid const& val) { UInt8 const* uid = NULL; UInt32 uidSize = val.getByteArray(uid); CError err = write(uidSize); if (!err.isNoError()) return err; if (uidSize > mFullSize - mUsedSize) return CError(1, moduleName, CError::ERROR, "insufficient buffer size (from CUid write)"); memcpy(mpBuffer + mUsedSize, uid, uidSize); mUsedSize += uidSize; return CError::NoError(moduleName); }
CError CBufferReader::read<std::string>(std::string & val) { UInt32 valSize = 0; CError err = read(valSize); if (!err.isNoError()) return err; if (valSize > mFullSize - mUsedSize) return CError(1, moduleName, CError::ERROR, "insufficient buffer size (from std::string write)"); val.assign(reinterpret_cast<char const*>(mpBuffer + mUsedSize), valSize); mUsedSize += valSize; return err; }
CError CPIM::sessionRequest(iviLink::Service::SessionUid session, iviLink::Service::Uid service) { LOG4CPLUS_TRACE_METHOD(logger, __PRETTY_FUNCTION__ + (" session " + session.value() + " service " + service.value())); CPMALComponentMgr *pMgr = CPMALComponentMgr::getInstance(); if (pMgr) { IPMALIpcToPIM* ipc = pMgr->getIpcToPIM(); if (ipc) { CError err = ipc->readyToServe(session); if (!err.isNoError()) { LOG4CPLUS_ERROR(logger, static_cast<std::string>(err)); } return err; } return CError(1, gModuleName, CError::ERROR, "sessionRequest() no ipc"); } return CError(1, gModuleName, CError::ERROR, "sessionRequest() no manager"); }
CError CBufferReader::read<iviLink::CUid>(iviLink::CUid & val) { UInt32 uidSize = 0; CError err = read(uidSize); if (!err.isNoError()) return err; if (uidSize > mFullSize - mUsedSize) return CError(1, moduleName, CError::ERROR, "insufficient buffer size (from CUid write)"); err = val.fromByteArray(mpBuffer + mUsedSize, uidSize); mUsedSize += uidSize; return err; }
void Environment::AddObject(const char *filename) { infunc(Environment::AddObject); int offset; Class *class_ptr; // Open the object file for reading if ((file = new CFile(cur_filename = filename, FILEOPEN_READ)) == NULL) throw CError("Couldn't allocate a new object file"); // Read where the code segment ends file->SeekTo(-4, FILESEEK_END); file->Read(&offset, 4); file->SeekTo(offset, FILESEEK_START); // Allocate the new class if ((class_ptr = new Class) == NULL) throw CError("Couldn't allocate new class"); // Read the class information from file class_ptr->Read(file); // The class has been defined so set it class_ptr->SetDefined(); // Add it! AddClassPtr(class_ptr); // Close the file delete file; // Set the output filename class_ptr->SetObjectFile((char *)filename); outfunc; }
void SDL::displayScore(Player const * const p) { SDL_Rect scorePoz; SDL_Surface *score = NULL; TTF_Font *font = NULL; SDL_Color color = {255, 255, 255, 0}; std::stringstream s_score; s_score << p->getScore(); if ((font = TTF_OpenFont("ressources/font/arial.ttf", 16)) == NULL) throw CError("Can't open font."); TTF_SetFontStyle(font, TTF_STYLE_BOLD); if ((score = TTF_RenderText_Solid(font, s_score.str().c_str(), color)) == NULL) throw CError("Can't Render Text."); scorePoz.x = this->_screen->w - score->w - 10; scorePoz.y = 10; SDL_BlitSurface(score, NULL, this->_screen, &scorePoz); // SDL_Flip(this->_screen); TTF_CloseFont(font); SDL_FreeSurface(score); }