bool XmlSchemaGenerator::getSequence ( std::vector<wxString> &sequence,
		const std::map<wxString, ChildData> &elmtMap )
{
	bool deadlock = false;

	sequence.clear();

	std::vector<wxString>::iterator seqItr, seqFindItr;
	std::set<wxString>::const_iterator prevItr, prevEnd;
	std::map<wxString, ChildData>::const_iterator itr;

	bool retry;
	do
	{
		retry = false;
		for ( itr = elmtMap.begin(); itr != elmtMap.end(); ++itr )
		{
			seqFindItr = std::find ( sequence.begin(), sequence.end(),
					itr->first );
			if ( seqFindItr != sequence.end() )
				continue;

			seqItr = sequence.begin();
			prevItr = itr->second.prevSiblings.begin();
			prevEnd = itr->second.prevSiblings.end();
			for ( ; prevItr != prevEnd; ++prevItr )
			{ // Find last index of dependent elements
				seqFindItr = std::find ( sequence.begin(), sequence.end(),
						*prevItr );
				if ( seqFindItr != sequence.end() )
				{
					if ( seqItr < seqFindItr )
					{
						seqItr = seqFindItr;
					}
					continue;
				}
				const std::set<wxString> &previous =
						elmtMap.find ( *prevItr )->second.prevSiblings;
				if ( previous.find ( itr->first ) == previous.end() )
				{ // Not a deadlock
					retry = true;
					break;
				}
				else
				{
					deadlock = true;
				}
			}
			if ( prevItr != prevEnd )
				continue; // The preceding doesn't exist

			if ( seqItr != sequence.end() )
			{
				++seqItr;
			}
			sequence.insert ( seqItr, itr->first );
			wxLogDebug ( _T(" %s"), itr->first.c_str() );
		}
	} while ( retry );

	return !deadlock;
}
Exemplo n.º 2
0
Arquivo: query.hpp Projeto: Yurry/espp
 BoolQ && should(std::initializer_list<Query> queries) &&
 {
     _should.insert(_must.end(), queries);
     return std::move(*this);
 }
Exemplo n.º 3
0
void
ImageProcessing::SegmentColours( FrameBuffer * frame, 
				 FrameBuffer * outFrame, 
				 unsigned int threshold, 
				 unsigned int minLength,
				 unsigned int minSize,
				 unsigned int subSample,
				 ColourDefinition const & target,
				 RawPixel const & mark,
				 std::vector<VisionObject> & results
				 )
{
  FrameBufferIterator it( frame );
  FrameBufferIterator oit( outFrame );
  Pixel cPixel;
  RawPixel oPixel;
  //  unsigned int len;
  FloodFillState state;
  unsigned int count;
  
  for( unsigned int row = 0; row < frame->height; row = row + subSample )
    {
      it.goPosition(row, subSample);
      oit.goPosition(row, subSample);

      count = 0;
      for( unsigned int col = subSample; col < frame->width; col = col + subSample, it.goRight( subSample ),oit.goRight( subSample ) )
	{
	  oit.getPixel( & oPixel );
	  if ( oPixel == RawPixel( 0, 0, 0 ) )
	    {
	      it.getPixel( & cPixel );
	      
	      if ( target.isMatch( cPixel ) )
		{
		  count++;
		}
	      else
		{
		  count = 0;
		}
	      
	      if ( count >= minLength )
		{
		  state.initialize();
		  doFloodFill( frame, outFrame, Point( col, row), 
			       cPixel, threshold, & target, 
			       subSample, & state );
		  
#ifdef XX_DEBUG
		  if ( state.size() > minSize )
		    {
		      std::cout << "Flood fill returns size " << state.size() << std::endl;
		    }
#endif
		  if ( state.size() > minSize )
		    {
		      unsigned int tlx = state.bBox().topLeft().x();
		      unsigned int tly = state.bBox().topLeft().y();
		      unsigned int brx = state.bBox().bottomRight().x();
		      unsigned int bry = state.bBox().bottomRight().y();
		      
		      drawBresenhamLine( outFrame, tlx, tly, tlx, bry, mark );
		      drawBresenhamLine( outFrame, tlx, bry, brx, bry, mark );
		      drawBresenhamLine( outFrame, brx, bry, brx, tly, mark );
		      drawBresenhamLine( outFrame, brx, tly, tlx, tly, mark );

		      drawBresenhamLine( frame, tlx, tly, tlx, bry, mark );
		      drawBresenhamLine( frame, tlx, bry, brx, bry, mark );
		      drawBresenhamLine( frame, brx, bry, brx, tly, mark );
		      drawBresenhamLine( frame, brx, tly, tlx, tly, mark );
		      //		      swapColours( outFrame, 0, state.bBox(), 1, ColourDefinition( Pixel(colour), Pixel(colour) ), state.averageColour() );
		      VisionObject vo( target.name, state.size(), state.x(), state.y(), state.averageColour(), state.bBox() );

		      std::vector<VisionObject>::iterator i;

		      for( i = results.begin();
			   i != results.end();
			   ++i)
			{
			  if ( (*i).size < vo.size )
			    {
			      break;
			    }
			}
		      results.insert(i, vo );
		    }
		  count = 0;
		}
	    }
	  else
	    {
	      count = 0;
	    }
	}
    }
}
Exemplo n.º 4
0
void SingleQubitGateStoreImpl::getMatrixOrthonormalBasis(std::vector<MatrixPtr>& pBasis) {
	pBasis.insert(pBasis.end(), m_basis2.begin(), m_basis2.end());
}
void SphericalStereoApp::fileDrop( FileDropEvent event )
{
	mPanos.insert( mPanos.begin() + mPanoIndex, Pano{ event.getFile( 0 ) } );
}
Exemplo n.º 6
0
void LDB::compute( const cv::Mat& image,
                   std::vector<cv::KeyPoint>& _keypoints,
                   cv::Mat& _descriptors,
				   bool flag) const
{
    // Added to work with color images.
    cv::Mat _image;
    image.copyTo(_image);

	if(_image.empty() )
		return;

	//ROI handling
	int halfPatchSize = patchSize / 2;
	int border = halfPatchSize*1.415 + 1;
	if( _image.type() != CV_8UC1 )
		cvtColor(_image, _image, CV_BGR2GRAY);
	int levelsNum = 0;
	for( size_t i = 0; i < _keypoints.size(); i++ )
		levelsNum = std::max(levelsNum, std::max(_keypoints[i].octave, 0));
	levelsNum++;
	
	//Compute Orientation
    if(flag == 1){
       computeOrientation(_image, _keypoints, halfPatchSize);
    }

	// Pre-compute the scale pyramids
    std::vector<cv::Mat> imagePyramid(levelsNum);
	for (int level = 0; level < levelsNum; ++level)
	{
		float scale = 1/getScale(level, firstLevel, scaleFactor);
        cv::Size sz(cvRound(_image.cols*scale), cvRound(_image.rows*scale));
        cv::Size wholeSize(sz.width + border*2, sz.height + border*2);
        cv::Mat temp(wholeSize, _image.type()), masktemp;
        imagePyramid[level] = temp(cv::Rect(border, border, sz.width, sz.height));

		// Compute the resized image
		if( level != firstLevel )
		{
			if( level < firstLevel )
                resize(_image, imagePyramid[level], sz, 0, 0, cv::INTER_LINEAR);
			else
                resize(imagePyramid[level-1], imagePyramid[level], sz, 0, 0, cv::INTER_LINEAR);

            cv::copyMakeBorder(imagePyramid[level], temp, border, border, border, border,
                cv::BORDER_REFLECT_101+cv::BORDER_ISOLATED);
		}
		else
            cv::copyMakeBorder(_image, temp, border, border, border, border,
                cv::BORDER_REFLECT_101);
	}

	// Pre-compute the keypoints (we keep the best over all scales, so this has to be done beforehand
    std::vector < std::vector<cv::KeyPoint> > allKeypoints;

	// Cluster the input keypoints depending on the level they were computed at
	allKeypoints.resize(levelsNum);
    for (std::vector<cv::KeyPoint>::iterator keypoint = _keypoints.begin(),
		keypointEnd = _keypoints.end(); keypoint != keypointEnd; ++keypoint)
		allKeypoints[keypoint->octave].push_back(*keypoint);

	// Make sure we rescale the coordinates
	for (int level = 0; level < levelsNum; ++level)
	{
		if (level == firstLevel)
			continue;

        std::vector<cv::KeyPoint> & keypoints = allKeypoints[level];
		float scale = 1/getScale(level, firstLevel, scaleFactor);
        for (std::vector<cv::KeyPoint>::iterator keypoint = keypoints.begin(),
			keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
			keypoint->pt *= scale;
	}

    cv::Mat descriptors;
    std::vector<cv::Point> pattern;

	int nkeypoints = 0;
	for (int level = 0; level < levelsNum; ++level){
        std::vector<cv::KeyPoint>& keypoints = allKeypoints[level];
        cv::Mat& workingmat = imagePyramid[level];
		if(keypoints.size() > 1)
            cv::KeyPointsFilter::runByImageBorder(keypoints, workingmat.size(), border);

		nkeypoints += keypoints.size();
	}
	if( nkeypoints == 0 )
		_descriptors.release();
	else
	{
		_descriptors.create(nkeypoints, descriptorSize(), CV_8U);
		descriptors = _descriptors;
	}

	_keypoints.clear();
	int offset = 0;
	for (int level = 0; level < levelsNum; ++level)
	{
		// preprocess the resized image
        cv::Mat& workingmat = imagePyramid[level];
		// Get the features and compute their orientation
        std::vector<cv::KeyPoint>& keypoints = allKeypoints[level];
		if(keypoints.size() > 1)
            cv::KeyPointsFilter::runByImageBorder(keypoints, workingmat.size(), border);
		int nkeypoints = (int)keypoints.size();

		// Compute the descriptors
        cv::Mat desc;
		if (!descriptors.empty())
		{
			desc = descriptors.rowRange(offset, offset + nkeypoints);
		}

		offset += nkeypoints;
        //boxFilter(working_cv::Mat, working_cv::Mat, working_cv::Mat.depth(), Size(5,5), Point(-1,-1), true, BORDER_REFLECT_101);
        GaussianBlur(workingmat, workingmat, cv::Size(7, 7), 2, 2, cv::BORDER_REFLECT_101);
        cv::Mat integral_image;
        integral(workingmat, integral_image, CV_32S);
        computeDescriptors(workingmat, integral_image, patchSize, keypoints, desc, descriptorSize(), flag);

		// Copy to the output data
		if (level != firstLevel)
		{
			float scale = getScale(level, firstLevel, scaleFactor);
            for (std::vector<cv::KeyPoint>::iterator keypoint = keypoints.begin(),
				keypointEnd = keypoints.end(); keypoint != keypointEnd; ++keypoint)
				keypoint->pt *= scale;
		}
		// And add the keypoints to the output
		_keypoints.insert(_keypoints.end(), keypoints.begin(), keypoints.end());
	}
	
}
Exemplo n.º 7
0
 /// @brief Add the parameters of Source to this result.
 void addParamsFrom(const ValidatorResult &Source) {
   Parameters.insert(Parameters.end(), Source.Parameters.begin(),
                     Source.Parameters.end());
 }
Exemplo n.º 8
0
void prependVec(std::vector<T>& vec, const std::vector<T>& otherVec) {
	vec.insert(vec.begin(), otherVec.begin(), otherVec.end());
}
Exemplo n.º 9
0
void prependVec(std::vector<T>& vec, const T& singleValue) {
	vec.insert(vec.begin(), singleValue);
}
void CJoystickInterfaceCallback::GetScanResults(std::vector<CJoystick*>& joysticks)
{
  joysticks.insert(joysticks.end(), m_scanResults.begin(), m_scanResults.end());
  m_scanResults.clear();
}
Exemplo n.º 11
0
void	CPrimitiveClass::CParameter::CConstStringValue::appendFilePath(std::vector<std::string> &pathList)	const
{
	pathList.insert(pathList.end(), Values.begin(), Values.end());
}
Exemplo n.º 12
0
static void InitializePredefinedMacros(const TargetInfo &TI,
                                       const LangOptions &LangOpts,
                                       std::vector<char> &Buf) {
  char MacroBuf[60];
  // Compiler version introspection macros.
  DefineBuiltinMacro(Buf, "__llvm__=1");   // LLVM Backend
  DefineBuiltinMacro(Buf, "__clang__=1");  // Clang Frontend

  // Currently claim to be compatible with GCC 4.2.1-5621.
  DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
  DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
  DefineBuiltinMacro(Buf, "__GNUC__=4");
  DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
  DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\"");


  // Initialize language-specific preprocessor defines.

  // These should all be defined in the preprocessor according to the
  // current language configuration.
  if (!LangOpts.Microsoft)
    DefineBuiltinMacro(Buf, "__STDC__=1");
  if (LangOpts.AsmPreprocessor)
    DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");

  if (!LangOpts.CPlusPlus) {
    if (LangOpts.C99)
      DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
    else if (!LangOpts.GNUMode && LangOpts.Digraphs)
      DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
  }

  // Standard conforming mode?
  if (!LangOpts.GNUMode)
    DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1");

  if (LangOpts.CPlusPlus0x)
    DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__");

  if (LangOpts.Freestanding)
    DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0");
  else
    DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");

  if (LangOpts.ObjC1) {
    DefineBuiltinMacro(Buf, "__OBJC__=1");
    if (LangOpts.ObjCNonFragileABI) {
      DefineBuiltinMacro(Buf, "__OBJC2__=1");
      DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1");
    }

    if (LangOpts.getGCMode() != LangOptions::NonGC)
      DefineBuiltinMacro(Buf, "__OBJC_GC__=1");

    if (LangOpts.NeXTRuntime)
      DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
  }

  // darwin_constant_cfstrings controls this. This is also dependent
  // on other things like the runtime I believe.  This is set even for C code.
  DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");

  if (LangOpts.ObjC2)
    DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");

  if (LangOpts.PascalStrings)
    DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");

  if (LangOpts.Blocks) {
    DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
    DefineBuiltinMacro(Buf, "__BLOCKS__=1");
  }

  if (LangOpts.Exceptions)
    DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");

  if (LangOpts.CPlusPlus) {
    DefineBuiltinMacro(Buf, "__DEPRECATED=1");
    DefineBuiltinMacro(Buf, "__GNUG__=4");
    DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
    if (LangOpts.GNUMode)
      DefineBuiltinMacro(Buf, "__cplusplus=1");
    else
      // C++ [cpp.predefined]p1:
      //   The name_ _cplusplusis defined to the value199711Lwhen compiling a
      //   C++ translation unit.
      DefineBuiltinMacro(Buf, "__cplusplus=199711L");
    DefineBuiltinMacro(Buf, "__private_extern__=extern");
    // Ugly hack to work with GNU libstdc++.
    DefineBuiltinMacro(Buf, "_GNU_SOURCE=1");
  }

  if (LangOpts.Microsoft) {
    // Filter out some microsoft extensions when trying to parse in ms-compat
    // mode.
    DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
    DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
    DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
    DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
    // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
    // VC++ appears to only like __FUNCTION__.
    DefineBuiltinMacro(Buf, "__PRETTY_FUNCTION__=__FUNCTION__");
    // Work around some issues with Visual C++ headerws.
    if (LangOpts.CPlusPlus) {
      // Since we define wchar_t in C++ mode.
      DefineBuiltinMacro(Buf, "_WCHAR_T_DEFINED=1");
      DefineBuiltinMacro(Buf, "_NATIVE_WCHAR_T_DEFINED=1");
      // FIXME:  This should be temporary until we have a __pragma
      // solution, to avoid some errors flagged in VC++ headers.
      DefineBuiltinMacro(Buf, "_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES=0");
    }
  }

  if (LangOpts.Optimize)
    DefineBuiltinMacro(Buf, "__OPTIMIZE__=1");
  if (LangOpts.OptimizeSize)
    DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1");

  // Initialize target-specific preprocessor defines.

  // Define type sizing macros based on the target properties.
  assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
  DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");

  DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
  DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Buf);
  DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Buf);
  DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Buf);
  DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Buf);
  DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Buf);
  DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Buf);

  DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
  DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
  DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Buf);
  DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
  DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Buf);
  DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
  DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Buf);
  DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
  DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Buf);
  DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
  DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Buf);
  DefineType("__WINT_TYPE__", TI.getWIntType(), Buf);
  DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Buf);
  DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Buf);

  DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
  DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
  DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());

  // Define a __POINTER_WIDTH__ macro for stdint.h.
  sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
  DefineBuiltinMacro(Buf, MacroBuf);

  if (!LangOpts.CharIsSigned)
    DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");

  // Define exact-width integer types for stdint.h
  sprintf(MacroBuf, "__INT%d_TYPE__=char", TI.getCharWidth());
  DefineBuiltinMacro(Buf, MacroBuf);

  if (TI.getShortWidth() > TI.getCharWidth())
    DefineExactWidthIntType(TargetInfo::SignedShort, TI, Buf);
                      
  if (TI.getIntWidth() > TI.getShortWidth())
    DefineExactWidthIntType(TargetInfo::SignedInt, TI, Buf);
                              
  if (TI.getLongWidth() > TI.getIntWidth())
    DefineExactWidthIntType(TargetInfo::SignedLong, TI, Buf);
                                      
  if (TI.getLongLongWidth() > TI.getLongWidth())
    DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Buf);
  
  // Add __builtin_va_list typedef.
  {
    const char *VAList = TI.getVAListDeclaration();
    Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
    Buf.push_back('\n');
  }

  if (const char *Prefix = TI.getUserLabelPrefix()) {
    sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
    DefineBuiltinMacro(Buf, MacroBuf);
  }

  // Build configuration options.  FIXME: these should be controlled by
  // command line options or something.
  DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");

  if (LangOpts.GNUInline)
    DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1");
  else
    DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1");

  if (LangOpts.NoInline)
    DefineBuiltinMacro(Buf, "__NO_INLINE__=1");

  if (unsigned PICLevel = LangOpts.PICLevel) {
    sprintf(MacroBuf, "__PIC__=%d", PICLevel);
    DefineBuiltinMacro(Buf, MacroBuf);

    sprintf(MacroBuf, "__pic__=%d", PICLevel);
    DefineBuiltinMacro(Buf, MacroBuf);
  }

  // Macros to control C99 numerics and <float.h>
  DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
  DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
  sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
          PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36));
  DefineBuiltinMacro(Buf, MacroBuf);

  if (LangOpts.getStackProtectorMode() == LangOptions::SSPOn)
    DefineBuiltinMacro(Buf, "__SSP__=1");
  else if (LangOpts.getStackProtectorMode() == LangOptions::SSPReq)
    DefineBuiltinMacro(Buf, "__SSP_ALL__=2");

  // Get other target #defines.
  TI.getTargetDefines(LangOpts, Buf);
}
Exemplo n.º 13
0
/**
* オプションファイル解析
*/
BOOL COption::AnalysisOptionFile(std::vector<izanagi::tool::CString>& tvArgs)
{
    BOOL ret = TRUE;

    FILE* fp = NULL;

    // テンポラリファイル名を作成する
    izanagi::tool::CString strTmp;
    _CreateTmpFileName(strTmp);

    // プリプロセスする
    {
        // プリプロセス用
        COption cOpt;
        cOpt.Copy(*this);
        {
            // プリプロセス用にいろいろ変更・・・
            cOpt.shader = cOpt.optionFile;      // 入力
            cOpt.preprocFile = strTmp;          // 出力
        }

        // exe名
        izanagi::tool::CFileUtility::GetExeModuleName(s_BUF, sizeof(s_BUF));

        // 自分自身をプリプロセス処理モードで呼び出す
        ret = ExecWithPreprocMode(s_BUF, cOpt);

        if (!ret) {
            // 失敗・・・
            IZ_ASSERT(FALSE);

            // TODO

            goto __EXIT__;
        }
    }

    // オプションを引数リストに戻す
    ConvetOptionToArgs(tvArgs);

    // ファイル開く
    fopen_s(&fp, strTmp, "rt");
    if (fp == NULL) {
        IZ_ASSERT(FALSE);

        // TODO

        return FALSE;
    }

    memset(s_BUF, 0, sizeof(s_BUF));

    // リストファイルを解析
    while (fgets(s_BUF, sizeof(s_BUF), fp) != NULL) {
        izanagi::tool::CString str;
        str.format("%s", s_BUF);

        if (strlen(str) > 0) {
            if (_IsOptionString(str)) {
                // オプションを表している文字列
                std::vector<izanagi::tool::CString> tvTmp;

                _BreakString(str, tvTmp);

                // リストに登録
                tvArgs.insert(tvArgs.end(), tvTmp.begin(), tvTmp.end());
            }
        }

        // 次に向けてクリア
        memset(s_BUF, 0, sizeof(s_BUF));
    }

__EXIT__:
    // ファイル閉じる
    if (fp != NULL) {
        fclose(fp);
    }

    // テンポラリファイルを削除
    DeleteFile(strTmp);

    if (!optionFile.empty()) {
        optionFile.replace('/', '\\');
        ret = izanagi::tool::CFileUtility::GetPathWithoutFileName(s_BUF, sizeof(s_BUF), optionFile);
        VRETURN(ret);

        baseDir.append(s_BUF);
    }

    // クリアする
    Clear();

    return ret;
}
void MultiGaussianDistribution::addBaselineModes(std::vector<SimpleGaussian*> &distribution) {
   std::vector<SimpleGaussian*> baseline = SimpleGaussian::createBaselineGaussians();
   distribution.insert(distribution.end(), baseline.begin(), baseline.end());
}
Exemplo n.º 15
0
	std::unique_ptr< i_population_wide_observer > resultant_objective::create_instance(
		prm::param_accessor param,
		std::vector< std::unique_ptr< i_observer > >& required_observations)
		//std::set< agent_objective::Type >& required_observations)
	{
#if 0
		auto type = prm::find_value(param, "obj_type")[0].as< i_population_wide_observer::Type >();
		switch(type)
		{
			case i_population_wide_observer::Single:
			{
				auto ao_type = prm::find_value(param, "single_obj")[0].as< agent_objective::Type >();
				required_observations.insert(ao_type);
				return new rtp_single_objective(agent_objective::Names[ao_type]);
			}

			case i_population_wide_observer::Pareto:
			{
				auto ep = prm::find_value(param, "pareto_obj").as< prm::enum_param_val >();
				auto objectives = boost::any_cast<std::vector< std::string >>(ep.contents);
				for(auto const& obj_name : objectives)
				{
					required_observations.insert(YAML::Node(obj_name).as< agent_objective::Type >());
				}

				/*				std::vector< std::string > obj_names;
								for(auto const& obj : agent_objective::Names)
								{
								if(prm::find_value(param, obj).as< bool >())
								{
								required_observations.insert(YAML::Node(obj).as< agent_objective::Type >());
								obj_names.push_back(obj);
								}
								}
								*/
				return new rtp_pareto(objectives);// obj_names);
			}

			default:
			return nullptr;
		}
#endif

		param.push_relative_path(prm::qualified_path("objective"));
		auto obj_type = param["obj_type"][0].as< i_population_wide_observer::Type >();
		param.push_relative_path(prm::qualified_path("objective_components"));
		std::unique_ptr< i_population_wide_observer > result;
		switch(obj_type)
		{
			case i_population_wide_observer::Type::Single:
			{
				auto man_obj = manual_objective::create_instance(param, std::function< double(state_value_id) >());	// TODO:
				auto observation_name = std::string("SINGLE");
				auto wrapped = std::make_unique< temp_manual_objective_wrapper >(std::move(man_obj), observation_name);
				required_observations.emplace_back(std::move(wrapped));

				// TODO:
				auto merge = param["trial_merging"][0].as< std::string >();
				rtp_single_objective::MergeMethod merge_method = rtp_single_objective::MergeMethod::Default;
				if(merge == "Average")
				{
					merge_method = rtp_single_objective::MergeMethod::Average;
				}
				else
				{
					merge_method = rtp_single_objective::MergeMethod::Minimum;
				}

				result = std::make_unique< rtp_single_objective >(observation_name, merge_method);
			}
			break;

			case i_population_wide_observer::Type::Pareto:
			{
				std::vector< std::string > components;
				auto node = param["pareto_components"];
				//assert(node[prm::ParamNode::Value] && node[prm::ParamNode::Value].IsMap());
				assert(node.IsMap());
				for(auto inst : node)//[prm::ParamNode::Value])
				{
					auto inst_num = inst.first.as< unsigned int >();
					auto rel_path = prm::qualified_path("pareto_components");
					rel_path.leaf().set_index(inst_num);
					param.push_relative_path(rel_path);
					auto man_obj = manual_objective::create_instance(param, std::function< double(state_value_id) >());	// TODO: ?? Currently set in every update() call, so this is not used...
					// TODO: For now just using unique path as observation name
					std::stringstream ss;
					ss << rel_path;
					auto observation_name = ss.str();
					auto wrapped = std::make_unique< temp_manual_objective_wrapper >(std::move(man_obj), observation_name);
					required_observations.emplace_back(std::move(wrapped));
					param.pop_relative_path();
					components.push_back(observation_name);
				}
				result = std::make_unique< rtp_pareto >(components);
			}
			break;

			case i_population_wide_observer::Type::Null_Debug:
			{
				result = std::make_unique< rtp_null_objective >();
			}
			break;
		}
		param.pop_relative_path();
		param.pop_relative_path();

		return result;
	}
Exemplo n.º 16
0
void addOtherVec(std::vector<T>& reads, const std::vector<T>& otherVec) {
	reads.reserve(reads.size() + otherVec.size());
	reads.insert(reads.end(), otherVec.begin(), otherVec.end());
}
//==============================================================//
void ObjDetector::detect(cv::Mat src, std::vector<cv::Rect>& box,
                          std::vector<float>& vote) 
{
    int i, j;



    float m=m_slidParam.m_init_scale;

    box.clear();
    vote.clear();
    std::cout << "original size: " << src.size() << std::endl;
    std::cout << "objsize: " << m_objsize[0] << "/" << m_objsize[1] << "\n";

    for(i=0; i<m_slidParam.m_scale_num; ++i, m*=m_slidParam.m_shrink_ratio) {

        cv::Size newSize(src.cols*m, src.rows*m);

        //std::cout << "objsize: " << m_objsize[0] << "/" << m_objsize[1] << "\n";
        std::cout << i << ": scale " << m << "\n";

        int maxlen = 2048;
        if(newSize.width>maxlen || newSize.height>maxlen) {
            std::cout << "**** image size > " << maxlen << "\n";
            std::cout << "**** stop detection\n";
            continue;
        }

        if(newSize.width<m_objsize[0] || newSize.height<m_objsize[1]) {
            break;
        }
        cv::Mat resized;        
        cv::resize(src, resized, newSize, 0, 0, cv::INTER_AREA);

        std::vector<cv::Rect> tempbox;
        std::vector<float> tempvote;

        detect_image(resized, m, tempbox, tempvote);

        box.insert(box.end(), tempbox.begin(), tempbox.end());
        vote.insert(vote.end(), tempvote.begin(), tempvote.end());
    }
    //remove overlapping area
    if(m_remove_overlap) {
        for(i=0; i<vote.size(); ++i) {
            bool toremove=false;
            for(j=0; j<vote.size(); ++j) {
                if(i!=j) 
                { 
                    if(  vote[i]<=vote[j]
                      && overlapRatio(box[i],box[j])>m_overlap_thres) 
                    {
                        toremove=true;
                        break;
                    }   

                    //if( (box[i]&box[j])==box[i] )
                     // && overlapRatio(box[i],box[j])>m_overlap_thres-0.1)
                    if( (box[i]&box[j]).area()/float(box[i].area())>0.85)
                    {
                        float cx = box[j].x+box[j].width/2.0;
                        float cy = box[j].y+box[j].height/2.0;
                        if( (box[i].x<cx && box[i].x+box[i].width >cx) 
                          ||(box[i].y<cy && box[i].y+box[i].height>cy) )
                        {
                            if(vote[i]<=vote[j]) { 
                                toremove=true;
                                break;
                            }
                            else {
                                vote.erase(vote.begin()+j);
                                box.erase(box.begin()+j);
                                --j;
                            }
                        }
                    }
                }
            }
            if(toremove) {
                vote.erase(vote.begin()+i);
                box.erase(box.begin()+i);
                --i;
            }
        }  
    }
}
Exemplo n.º 18
0
void R600SchedStrategy::MoveUnits(std::vector<SUnit *> &QSrc,
                                  std::vector<SUnit *> &QDst)
{
  QDst.insert(QDst.end(), QSrc.begin(), QSrc.end());
  QSrc.clear();
}
Exemplo n.º 19
0
/// \brief Strips any positional args and possible argv[0] from a command-line
/// provided by the user to construct a FixedCompilationDatabase.
///
/// FixedCompilationDatabase requires a command line to be in this format as it
/// constructs the command line for each file by appending the name of the file
/// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
/// start of the command line although its value is not important as it's just
/// ignored by the Driver invoked by the ClangTool using the
/// FixedCompilationDatabase.
///
/// FIXME: This functionality should probably be made available by
/// clang::driver::Driver although what the interface should look like is not
/// clear.
///
/// \param[in] Args Args as provided by the user.
/// \return Resulting stripped command line.
///          \li true if successful.
///          \li false if \c Args cannot be used for compilation jobs (e.g.
///          contains an option like -E or -version).
static bool stripPositionalArgs(std::vector<const char *> Args,
                                std::vector<std::string> &Result) {
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  UnusedInputDiagConsumer DiagClient;
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()),
      &*DiagOpts, &DiagClient, false);

  // The clang executable path isn't required since the jobs the driver builds
  // will not be executed.
  std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
      /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
      Diagnostics));
  NewDriver->setCheckInputsExist(false);

  // This becomes the new argv[0]. The value is actually not important as it
  // isn't used for invoking Tools.
  Args.insert(Args.begin(), "clang-tool");

  // By adding -c, we force the driver to treat compilation as the last phase.
  // It will then issue warnings via Diagnostics about un-used options that
  // would have been used for linking. If the user provided a compiler name as
  // the original argv[0], this will be treated as a linker input thanks to
  // insertng a new argv[0] above. All un-used options get collected by
  // UnusedInputdiagConsumer and get stripped out later.
  Args.push_back("-c");

  // Put a dummy C++ file on to ensure there's at least one compile job for the
  // driver to construct. If the user specified some other argument that
  // prevents compilation, e.g. -E or something like -version, we may still end
  // up with no jobs but then this is the user's fault.
  Args.push_back("placeholder.cpp");

  // Remove -no-integrated-as; it's not used for syntax checking,
  // and it confuses targets which don't support this option.
  Args.erase(std::remove_if(Args.begin(), Args.end(),
                            MatchesAny(std::string("-no-integrated-as"))),
             Args.end());

  const std::unique_ptr<driver::Compilation> Compilation(
      NewDriver->BuildCompilation(Args));

  const driver::JobList &Jobs = Compilation->getJobs();

  CompileJobAnalyzer CompileAnalyzer;

  for (const auto &Cmd : Jobs) {
    // Collect only for Assemble jobs. If we do all jobs we get duplicates
    // since Link jobs point to Assemble jobs as inputs.
    if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass)
      CompileAnalyzer.run(&Cmd.getSource());
  }

  if (CompileAnalyzer.Inputs.empty()) {
    // No compile jobs found.
    // FIXME: Emit a warning of some kind?
    return false;
  }

  // Remove all compilation input files from the command line. This is
  // necessary so that getCompileCommands() can construct a command line for
  // each file.
  std::vector<const char *>::iterator End = std::remove_if(
      Args.begin(), Args.end(), MatchesAny(CompileAnalyzer.Inputs));

  // Remove all inputs deemed unused for compilation.
  End = std::remove_if(Args.begin(), End, MatchesAny(DiagClient.UnusedInputs));

  // Remove the -c add above as well. It will be at the end right now.
  assert(strcmp(*(End - 1), "-c") == 0);
  --End;

  Result = std::vector<std::string>(Args.begin() + 1, End);
  return true;
}
Exemplo n.º 20
0
bool LoadWavFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency)
{
    if (!fileData || numBytes == 0)
    {
        LogError("Null input data passed in");
        return false;
    }

    if (!isStereo || !is16Bit || !frequency)
    {
        LogError("Outputs not set");
        return false;
    }

    unsigned int index = 0;
    
    u8 riff_text[4];
    ReadBytes(riff_text, fileData, index, 4);
    if (!!memcmp(riff_text, "RIFF", 4))
    {
        LogError("No RIFF chunk in WAV data");
        return false;
    }
    if (index >= numBytes) 
        return false;

    ReadU32(fileData, index);
    u8 wave_text[4];
    ReadBytes(wave_text, fileData, index, 4);
    if (!!memcmp(wave_text, "WAVE", 4))
    {
        LogError("No WAVE chunk in WAV data");
        return false;
    }
    
    // Search for the fmt chunk
    for(;;)
    {
        if (index >= numBytes)
        {
            LogError("No fmt chunk in WAV data");
            return false;
        }
        u8 chunk_text[4]; 
        ReadBytes(chunk_text, fileData, index, 4);
        unsigned int chunk_size = ReadU32(fileData, index);
        if (!memcmp(chunk_text, "fmt ", 4))
            break;
        if (!chunk_size)
            return false;
        index += chunk_size;
    }
    
    if (index >= numBytes) 
        return false;

    u16 format = ReadU16(fileData, index);
    u16 channels = ReadU16(fileData, index);
    unsigned int sampleFrequency = ReadU32(fileData, index);
    /*unsigned int avgbytes =*/ ReadU32(fileData, index);
    /*unsigned int blockalign =*/ ReadU16(fileData, index);
    u16 bits = ReadU16(fileData, index);

    if (format != 1)
    {
        LogError("Sound is not PCM data");
        return false;
    }
    if (channels != 1 && channels != 2)
    {
        LogError("Sound is not either mono or stereo");
        return false;
    }
    if (bits != 8 && bits != 16)
    {
        LogError("Sound is not either 8bit or 16bit");
        return false;
    }
                            
    // Search for the data chunk
    unsigned int data_length = 0;
    for(;;)
    {
        if (index >= numBytes)
        {
            LogError("No data chunk in WAV data");
            return false;
        }
        u8 chunk_text[4]; 
        ReadBytes(chunk_text, fileData, index, 4);
        data_length = ReadU32(fileData, index);
        if (!memcmp(chunk_text, "data", 4))
            break;
        if (!data_length) return false;
        index += data_length;
    }        
    
    if (!data_length)
    {
        LogError("Zero numBytes data chunk in WAV data");
        return false;
    }
    
    std::ostringstream msg;
    msg << "Loaded WAV sound with " << channels << " channels " << bits << " bits, frequency " << sampleFrequency << " datasize " << data_length; 
    LogDebug(msg.str());
 
    dst.clear();
    dst.insert(dst.end(), &fileData[index], &fileData[index + data_length]);
    *isStereo = (channels == 2);
    *is16Bit = (bits == 16);
    *frequency = sampleFrequency;

    return true;
}
Exemplo n.º 21
0
void RxCompile::insert(int i, Element* e)
	{
	pat.insert(pat.begin() + i, e);
	inChars = false;
	}
Exemplo n.º 22
0
	//--------------------------------------//
	// 名称 : InsertAt()					//
	// 用途 : 要素の挿入					//
	// 引数 : nIdx		: インデックス位置	//
	//		  Element	: 新要素			//
	// 戻値 : なし							//
	//--------------------------------------//
	void InsertAt(const int nIdx, const Type& Element)
	{
		m_arElement.insert(m_arElement.begin() + nIdx, Element);
	}
Exemplo n.º 23
0
//! ofObject = true   => returns list of objects this object depends on
//! ofObject = false  => returns list of objects that depend on this object
void MetadataItem::getDependencies(std::vector<Dependency>& list,
    bool ofObject)
{
    DatabasePtr d = getDatabase();

    int mytype = -1;            // map DBH type to RDB$DEPENDENT TYPE
    NodeType dep_types[] = {    ntTable,    ntView,     ntTrigger,  ntUnknown,  ntUnknown,
                                ntProcedure,ntUnknown,  ntException,ntUnknown,  ntUnknown,
                                ntUnknown,  ntUnknown,  ntUnknown,  ntUnknown,  ntGenerator,
                                ntFunction
    };
    int type_count = sizeof(dep_types)/sizeof(NodeType);
    for (int i = 0; i < type_count; i++)
        if (typeM == dep_types[i])
            mytype = i;
    // system tables should be treated as tables
    if (typeM == ntSysTable)
        mytype = 0;

    int mytype2 = mytype;
    // views count as relations(tables) when other object refer to them
    if (mytype == 1 && !ofObject)
        mytype2 = 0;

    if (typeM == ntUnknown || mytype == -1)
        throw FRError(_("Unsupported type"));
    IBPP::Database& db = d->getIBPPDatabase();
    IBPP::Transaction tr1 = IBPP::TransactionFactory(db, IBPP::amRead);
    tr1->Start();
    IBPP::Statement st1 = IBPP::StatementFactory(db, tr1);

    wxString o1 = (ofObject ? "DEPENDENT" : "DEPENDED_ON");
    wxString o2 = (ofObject ? "DEPENDED_ON" : "DEPENDENT");
    wxString sql =
        "select RDB$" + o2 + "_TYPE, RDB$" + o2 + "_NAME, RDB$FIELD_NAME \n "
        " from RDB$DEPENDENCIES \n "
        " where RDB$" + o1 + "_TYPE in (?,?) and RDB$" + o1 + "_NAME = ? \n ";
    int params = 1;
    if ((typeM == ntTable || typeM == ntSysTable || typeM == ntView) && ofObject)  // get deps for computed columns
    {                                                       // view needed to bind with generators
        sql += " union  \n"
            " SELECT DISTINCT d.rdb$depended_on_type, d.rdb$depended_on_name, d.rdb$field_name \n"
            " FROM rdb$relation_fields f \n"
            " LEFT JOIN rdb$dependencies d ON d.rdb$dependent_name = f.rdb$field_source \n"
            " WHERE d.rdb$dependent_type = 3 AND f.rdb$relation_name = ? \n";
        params++;
    }
    if (!ofObject) // find tables that have calculated columns based on "this" object
    {
        sql += "union  \n"
            " SELECT distinct cast(0 as smallint), f.rdb$relation_name, f.rdb$field_name \n"
            " from rdb$relation_fields f \n"
            " left join rdb$dependencies d on d.rdb$dependent_name = f.rdb$field_source \n"
            " where d.rdb$dependent_type = 3 and d.rdb$depended_on_name = ? ";
        params++;
    }
    // get the exact table and fields for views
    // rdb$dependencies covers deps. for WHERE clauses in SELECTs in VIEW body
    // but we also need mapping for column list in SELECT. These 2 queries cover it:
    if (ofObject && typeM == ntView)
    {
        sql += " union \n"
            " select distinct cast(0 as smallint), vr.RDB$RELATION_NAME, f.RDB$BASE_FIELD \n"
            " from RDB$RELATION_FIELDS f \n"
            " join RDB$VIEW_RELATIONS vr on f.RDB$VIEW_CONTEXT = vr.RDB$VIEW_CONTEXT \n"
            "   and f.RDB$RELATION_NAME = vr.RDB$VIEW_NAME \n"
            " where f.rdb$relation_name = ? \n";
        params++;
    }
    // views can depend on other views as well
    // we might need to add procedures here one day when Firebird gains support for it
    if (!ofObject && (typeM == ntView || typeM == ntTable || typeM == ntSysTable))
    {
        sql += " union \n"
            " select distinct cast(0 as smallint), f.RDB$RELATION_NAME, f.RDB$BASE_FIELD \n"
            " from RDB$RELATION_FIELDS f \n"
            " join RDB$VIEW_RELATIONS vr on f.RDB$VIEW_CONTEXT = vr.RDB$VIEW_CONTEXT \n"
            "   and f.RDB$RELATION_NAME = vr.RDB$VIEW_NAME \n"
            " where vr.rdb$relation_name = ? \n";
        params++;
    }

    sql += " order by 1, 2, 3";
    st1->Prepare(wx2std(sql, d->getCharsetConverter()));
    st1->Set(1, mytype);
    st1->Set(2, mytype2);
    for (int i = 0; i < params; i++)
        st1->Set(3 + i, wx2std(getName_(), d->getCharsetConverter()));
    st1->Execute();
    MetadataItem* last = 0;
    Dependency* dep = 0;
    while (st1->Fetch())
    {
        int object_type;
        st1->Get(1, &object_type);
        if (object_type > type_count)   // some system object, not interesting for us
            continue;
        NodeType t = dep_types[object_type];
        if (t == ntUnknown)             // ditto
            continue;

        std::string objname_std;
        st1->Get(2, objname_std);
        wxString objname(std2wxIdentifier(objname_std,
            d->getCharsetConverter()));

        MetadataItem* current = d->findByNameAndType(t, objname);
        if (!current)
        {
            if (t == ntTable) {
                // maybe it's a view masked as table
                current = d->findByNameAndType(ntView, objname);
                // or possibly a system table
                if (!current)
                    current = d->findByNameAndType(ntSysTable, objname);
            }
            if (!ofObject && t == ntTrigger)
            {
                // system trigger dependent of this object indicates possible check constraint on a table
                // that references this object. So, let's check if this trigger is used for check constraint
                // and get that table's name
                IBPP::Statement st2 = IBPP::StatementFactory(db, tr1);
                st2->Prepare(
                    "select r.rdb$relation_name from rdb$relation_constraints r "
                    " join rdb$check_constraints c on r.rdb$constraint_name=c.rdb$constraint_name "
                    " and r.rdb$constraint_type = 'CHECK' where c.rdb$trigger_name = ? "
                );
                st2->Set(1, objname_std);
                st2->Execute();
                if (st2->Fetch()) // table using that trigger found
                {
                    std::string s;
                    st2->Get(1, s);
                    wxString tablecheck(std2wxIdentifier(s, d->getCharsetConverter()));
                    if (getName_() != tablecheck)    // avoid self-reference
                        current = d->findByNameAndType(ntTable, tablecheck);
                }
            }
            if (!current)
                continue;
        }
        if (current != last)            // new object
        {
            Dependency de(current);
            list.push_back(de);
            dep = &list.back();
            last = current;
        }
        if (!st1->IsNull(3))
        {
            std::string s;
            st1->Get(3, s);
            dep->addField(std2wxIdentifier(s, d->getCharsetConverter()));
        }
    }

    // TODO: perhaps this could be moved to Table?
    //       call MetadataItem::getDependencies() and then add this
    if ((typeM == ntTable || typeM == ntSysTable) && ofObject)   // foreign keys of this table + computed columns
    {
        Table *t = dynamic_cast<Table *>(this);
        std::vector<ForeignKey> *f = t->getForeignKeys();
        for (std::vector<ForeignKey>::const_iterator it = f->begin();
            it != f->end(); ++it)
        {
            MetadataItem *table = d->findByNameAndType(ntTable,
                (*it).getReferencedTable());
            if (!table)
            {
                throw FRError(wxString::Format(_("Table %s not found."),
                    (*it).getReferencedTable().c_str()));
            }
            Dependency de(table);
            de.setFields((*it).getReferencedColumns());
            list.push_back(de);
        }

        // Add check constraints here (CHECKS are checked via system triggers), example:
        // table1::check( table1.field1 > select max(field2) from table2 )
        // So, table vs any object from this ^^^ select
        // Algorithm: 1.find all system triggers bound to that CHECK constraint
        //            2.find dependencies for those system triggers
        //            3.display those dependencies as deps. of this table
        st1->Prepare("select distinct c.rdb$trigger_name from rdb$relation_constraints r "
            " join rdb$check_constraints c on r.rdb$constraint_name=c.rdb$constraint_name "
            " and r.rdb$constraint_type = 'CHECK' where r.rdb$relation_name= ? "
        );
        st1->Set(1, wx2std(getName_(), d->getCharsetConverter()));
        st1->Execute();
        std::vector<Dependency> tempdep;
        while (st1->Fetch())
        {
            std::string s;
            st1->Get(1, s);
            Trigger t(d->shared_from_this(),
                std2wxIdentifier(s, d->getCharsetConverter()));
            t.getDependencies(tempdep, true);
        }
        // remove duplicates, and self-references from "tempdep"
        while (true)
        {
            std::vector<Dependency>::iterator to_remove = tempdep.end();
            for (std::vector<Dependency>::iterator it = tempdep.begin();
                it != tempdep.end(); ++it)
            {
                if ((*it).getDependentObject() == this)
                {
                    to_remove = it;
                    break;
                }
                to_remove = std::find(it + 1, tempdep.end(), (*it));
                if (to_remove != tempdep.end())
                    break;
            }
            if (to_remove == tempdep.end())
                break;
            else
                tempdep.erase(to_remove);
        }
        list.insert(list.end(), tempdep.begin(), tempdep.end());
    }

    // TODO: perhaps this could be moved to Table?
    if ((typeM == ntTable || typeM == ntSysTable) && !ofObject)  // foreign keys of other tables
    {
        st1->Prepare(
            "select r1.rdb$relation_name, i.rdb$field_name "
            " from rdb$relation_constraints r1 "
            " join rdb$ref_constraints c on r1.rdb$constraint_name = c.rdb$constraint_name "
            " join rdb$relation_constraints r2 on c.RDB$CONST_NAME_UQ = r2.rdb$constraint_name "
            " join rdb$index_segments i on r1.rdb$index_name=i.rdb$index_name "
            " where r2.rdb$relation_name=? "
            " and r1.rdb$constraint_type='FOREIGN KEY' "
        );
        st1->Set(1, wx2std(getName_(), d->getCharsetConverter()));
        st1->Execute();
        wxString lasttable;
        Dependency* dep = 0;
        while (st1->Fetch())
        {
            std::string s;
            st1->Get(1, s);
            wxString table_name(std2wxIdentifier(s, d->getCharsetConverter()));
            st1->Get(2, s);
            wxString field_name(std2wxIdentifier(s, d->getCharsetConverter()));

            if (table_name != lasttable)    // new
            {
                MetadataItem* table = d->findByNameAndType(ntTable, table_name);
                if (!table)
                    continue;           // dummy check
                Dependency de(table);
                list.push_back(de);
                dep = &list.back();
                lasttable = table_name;
            }
            dep->addField(field_name);
        }
    }

    tr1->Commit();
}
  void SpacesInteriorPartitionsGridController::addColumns(const QString &category, std::vector<QString> & fields)
  {
    // always show name and selected columns
    fields.insert(fields.begin(), { NAME, SELECTED });

    m_baseConcepts.clear();

    for (const auto &field : fields) {

      if (field == NAME) {
        addNameLineEditColumn(Heading(QString(NAME), false, false),
          false,
          false,
          CastNullAdapter<model::Space>(&model::Space::name),
          CastNullAdapter<model::Space>(&model::Space::setName)
          );
      }
      else {

          std::function<std::vector<model::ModelObject>(const model::Space &)> allInteriorPartitionSurfaceGroups(
            [](const model::Space &t_space) {
            std::vector<model::ModelObject> allModelObjects;
            auto interiorPartitionSurfaceGroups = t_space.interiorPartitionSurfaceGroups();
            allModelObjects.insert(allModelObjects.end(), interiorPartitionSurfaceGroups.begin(), interiorPartitionSurfaceGroups.end());
            return allModelObjects;
          }
          );

          std::function<std::vector<model::ModelObject>(const model::Space &)> allInteriorPartitionSurfaces(
            [allInteriorPartitionSurfaceGroups](const model::Space &t_space) {
            std::vector<model::ModelObject> allModelObjects;
            for (auto interiorPartitionSurfaceGroup : allInteriorPartitionSurfaceGroups(t_space)) {
              auto interiorPartitionSurfaces = interiorPartitionSurfaceGroup.cast<model::InteriorPartitionSurfaceGroup>().interiorPartitionSurfaces();
              for (auto interiorPartitionSurface : interiorPartitionSurfaces) {
                allModelObjects.push_back(interiorPartitionSurface);
              }
            }
            return allModelObjects;
          }
          );

          std::function<std::vector<boost::optional<model::ModelObject> >(const model::Space &)> allInteriorPartitionSurfaceInteriorPartitionSurfaceGroups(
            [allInteriorPartitionSurfaceGroups](const model::Space &t_space) {
            std::vector<boost::optional<model::ModelObject> > allModelObjects;
            for (auto interiorPartitionSurfaceGroup : allInteriorPartitionSurfaceGroups(t_space)) {
              auto interiorPartitionSurfaces = interiorPartitionSurfaceGroup.cast<model::InteriorPartitionSurfaceGroup>().interiorPartitionSurfaces();
              for (auto interiorPartitionSurface : interiorPartitionSurfaces) {
                auto group = interiorPartitionSurface.interiorPartitionSurfaceGroup();
                if (group) {
                  allModelObjects.push_back(*group);
                }
                else {
                  allModelObjects.emplace_back();
                }
              }
            }
            return allModelObjects;
          }
          );

        if (field == SELECTED) {
          auto checkbox = QSharedPointer<QCheckBox>(new QCheckBox());
          checkbox->setToolTip("Check to select all rows");
          connect(checkbox.data(), &QCheckBox::stateChanged, this, &SpacesInteriorPartitionsGridController::selectAllStateChanged);
          connect(checkbox.data(), &QCheckBox::stateChanged, this->gridView(), &OSGridView::gridRowSelectionChanged);

          addSelectColumn(Heading(QString(SELECTED), false, false, checkbox), "Check to select this row",
            DataSource(
            allInteriorPartitionSurfaces,
            true
            )
            );
        }
        else if (field == INTERIORPARTITIONGROUPNAME) {
          addNameLineEditColumn(Heading(QString(INTERIORPARTITIONGROUPNAME), true, false),
            false,
            false,
            CastNullAdapter<model::InteriorPartitionSurfaceGroup>(&model::InteriorPartitionSurfaceGroup::name),
            CastNullAdapter<model::InteriorPartitionSurfaceGroup>(&model::InteriorPartitionSurfaceGroup::setName),
            boost::optional<std::function<void(model::InteriorPartitionSurfaceGroup *)>>(),
            DataSource(
            allInteriorPartitionSurfaceInteriorPartitionSurfaceGroups,
            true)
            );
        }
        else if (field == INTERIORPARTITIONNAME) {
          addNameLineEditColumn(Heading(QString(INTERIORPARTITIONNAME), true, false),
          false,
          false,
          CastNullAdapter<model::InteriorPartitionSurface>(&model::InteriorPartitionSurface::name),
          CastNullAdapter<model::InteriorPartitionSurface>(&model::InteriorPartitionSurface::setName),
          boost::optional<std::function<void(model::InteriorPartitionSurface *)>>(),
          DataSource(
          allInteriorPartitionSurfaces,
          true)
          );
        }
        else if (field == CONSTRUCTIONNAME) {
          m_constructionColumn = 4;
          addDropZoneColumn(Heading(QString(CONSTRUCTIONNAME), true, false),
            CastNullAdapter<model::InteriorPartitionSurface>(&model::InteriorPartitionSurface::construction),
            CastNullAdapter<model::InteriorPartitionSurface>(&model::InteriorPartitionSurface::setConstruction),
            boost::optional<std::function<void(model::InteriorPartitionSurface*)> >(NullAdapter(&model::InteriorPartitionSurface::resetConstruction)),
            boost::optional<std::function<bool(model::InteriorPartitionSurface*)> >(NullAdapter(&model::InteriorPartitionSurface::isConstructionDefaulted)),
            DataSource(
            allInteriorPartitionSurfaces,
            true
            )
            );
        }
        else if (field == CONVERTTOINTERNALMASS) {
          addCheckBoxColumn(Heading(QString(CONVERTTOINTERNALMASS), true, false),
            std::string("Check to enable convert to InternalMass."),
            NullAdapter(&model::InteriorPartitionSurface::converttoInternalMass),
            NullAdapter(&model::InteriorPartitionSurface::setConverttoInternalMass),
            DataSource(
            allInteriorPartitionSurfaces,
            true
            )
            );
        }
        else if (field == SURFACEAREA) {
          std::function<bool(model::InteriorPartitionSurface *, double)> setter(
            [](model::InteriorPartitionSurface *t_interiorPartitionSurface, double t_arg) {
            return t_interiorPartitionSurface->setSurfaceArea(t_arg);
          }
          );

          addValueEditColumn(Heading(QString(SURFACEAREA)),
            CastNullAdapter<model::InteriorPartitionSurface>(&model::InteriorPartitionSurface::surfaceArea),
            setter//,
            //boost::optional<std::function<void(model::ModelObject *)>>(),
            //boost::optional<std::function<bool(model::ModelObject *)>>()//,
            //DataSource(
            //allInteriorPartitionSurfaces,
            //true
            //)
            );

          //boost::optional<double> surfaceArea() const; // TODO this optional is causing troubles
          //bool setSurfaceArea(boost::optional<double> surfaceArea);
          //bool setSurfaceArea(double surfaceArea);
          //void resetSurfaceArea();

        }
        else if (field == DAYLIGHTINGSHELFNAME) {
          //boost::optional<DaylightingDeviceShelf> daylightingDeviceShelf() const;

        }
        else {
          // unhandled
          OS_ASSERT(false);
        }
      }
    }
  }
Exemplo n.º 25
0
void PU_DivideAndConquer::approximateInterval(
		std::vector<MixtureComponent *> &components,
		std::vector<double> &weights, int componentNumber, double start,
		double end, Distribution *dist)
{
	double x1 = start;
	double x2;
	double x3 = end;
	std::vector<double> errors;

	Uniform *curr = new Uniform(x1, x3);
	double w = dist->cdf(x3) - dist->cdf(x1);
	components.push_back(curr);
	weights.push_back(w);
	errors.push_back(0);

	while (components.size() != (unsigned) componentNumber)
	{
		std::vector<MixtureComponent *>::iterator it_comp = components.begin();
		std::vector<double>::iterator it_w = weights.begin();
		std::vector<double>::iterator it_er = errors.begin();
		MixtureComponent *popComponent = *it_comp;

		components.erase(it_comp);
		weights.erase(it_w);
		x1 = popComponent->getLeftMargin();
		x3 = popComponent->getRightMargin();
		x2 = (x1 + x3) / 2;

		Uniform *split1 = new Uniform(x1, x2);
		Uniform *split2 = new Uniform(x2, x3);
		double w1 = dist->cdf(x2) - dist->cdf(x1);
		if (w1 < 0)
			w1 = 0;
		double w2 = dist->cdf(x3) - dist->cdf(x2);
		if (w2 < 0)
			w2 = 0;
		double error1 = errorMeasure(split1, w1, dist);
		double error2 = errorMeasure(split2, w2, dist);

		int i;
		it_comp = components.begin();
		it_w = weights.begin();
		it_er = errors.begin();
		int insertedFlag = 0;
		for (i = 0; errors.size() < (unsigned) i; i++)
		{
			if (error1 > errors[i])
			{
				components.insert(it_comp, split1);
				weights.insert(it_w, w1);
				errors.insert(it_er, error1);
				insertedFlag = 1;
				break;
			}
			it_comp++;
			it_w++;
			it_er++;
		}
		if (!insertedFlag)
		{
			components.push_back(split1);
			weights.push_back(w1);
			errors.push_back(error1);
		}

		it_comp = components.begin();
		it_w = weights.begin();
		it_er = errors.begin();
		insertedFlag = 0;
		for (i = 0; errors.size() < (unsigned) i; i++)
		{
			if (error2 > errors[i])
			{
				components.insert(it_comp, split2);
				weights.insert(it_w, w2);
				errors.insert(it_er, error2);
				insertedFlag = 1;
				break;
			}
			it_comp++;
			it_w++;
			it_er++;
		}
		if (!insertedFlag)
		{
			components.push_back(split2);
			weights.push_back(w2);
			errors.push_back(error2);
		}
	}
}
void ising_NestedSampling_Algorithm_2D(float** ptrMatrix, float* Matrix, std::vector<double>& coordinates, std::vector<double>& likelyhoods, std::vector<double>& postlikelyhoods, Lattice lattice, RandomLib::Random& r, double const J, double const h, double const label_coeff, int const K, int const mcycle)
{
  int k, p, z, distance, iteration, K_iteration;
  double H_tot, H_in, H_fin, H_tot_constraint, H_tot_trial;
        
  initialise_likelyhoods(likelyhoods, K);
  initialise_likelyhoods(postlikelyhoods, K);
  initialise_coordinates(coordinates, lattice, K);
  
  for(int i = 0; i < K; i++)
    {
      generate_random_matrix_2D(Matrix, lattice, r);
      
      H_tot = ising_total_hamiltonian_2D(ptrMatrix,lattice,J,h);
      
      H_tot = label_likelyhood(H_tot, label_coeff, r);
      
      likelyhoods.insert(likelyhoods.end(), H_tot); 
      
      add_coordinates(Matrix, coordinates, lattice);
    }
  
  std::cout<<"END OF INITIALISATION"<<std::endl;
  std::cout<<"likelyhoods.size: "<<likelyhoods.size()<<std::endl;
  std::cout<<"coordinates.size: "<<coordinates.size()<<std::endl;
  
  bool LOOP = true; 
  std::vector<double>::iterator max_likelyhood;
  
  while(LOOP == true)
    {
      max_likelyhood = std::max_element(likelyhoods.begin(),likelyhoods.end());
      distance = std::distance(likelyhoods.begin(), max_likelyhood);
      H_tot_constraint = likelyhoods.at(distance);
      postlikelyhoods.insert(postlikelyhoods.end(), H_tot_constraint);
      //std::cout<<"H_tot_constraint: "<<H_tot_constraint<<std::endl;
      
      distance = get_randomlikelyhood_coordinates(Matrix, coordinates, likelyhoods, r, lattice);
      H_tot = likelyhoods.at(distance);
      K_iteration = 0;
      
      for(z = 0; z < mcycle; z++)
	{
	  Matrix_samplepoint_2D(lattice, r, &k, &p);
	      
	  H_in = ising_nodal_hamiltonian_2D(ptrMatrix, p, lattice, J, h);
	  
	  //flip spin
	  Matrix[k] = - Matrix[k];
	  
	  H_fin = ising_nodal_hamiltonian_2D(ptrMatrix, p, lattice, J, h);
	  
	  H_tot_trial = H_tot - H_in + H_fin;

	  H_tot_trial = label_likelyhood(H_tot_trial, label_coeff, r);
	  
	  if (H_tot_trial < H_tot_constraint)
	    {
	      H_tot = H_tot_trial;
	    }
	  else 
	    {
	      Matrix[k] = -Matrix[k];
	    }
	  
	  if (z == mcycle - 1)
	    {
	      if (H_tot < H_tot_constraint)
		{
		  replace_maxlikelyhood_coordinates(Matrix, coordinates, likelyhoods, lattice, H_tot);
		  break;
		}
	      else
		{
		  //std::cout<<"change"<<std::endl;
		  K_iteration = get_alternativelikelyhood_coordinates_random(Matrix, coordinates, likelyhoods,lattice, r, K, H_tot, K_iteration);
		  z = 0;
		  ++K_iteration;
		}
	    }
	  else if (K_iteration == K )
	    {
	      LOOP = false;
	      std::cout<<"Algorithm termination condition met"<<std::endl;
	      break;
	    }
	}
    }
}
Exemplo n.º 27
0
Arquivo: main.cpp Projeto: CCJY/coliru
 std::vector<T,A1> invoke( std::vector<T,A1> lhs, concat_tag, std::vector<T,A2> const& rhs ) {
     lhs.insert(lhs.end(), rhs.begin(), rhs.end());
     return std::move(lhs); // RVO blocked
 }
/////////////////////////
///// CRF Processor /////
/////////////////////////
void DenseCRF3DProcessor::calculate_map(std::vector<short> &v_map) {
  // check if image and features are set
  if (img_ == NULL || feat_ == NULL) {
    std::cerr << "Error. Image or features not set. Abort." << std::endl;
    return;
  }

  // check if shapes of image and features are equal
  if ((img_row_ != feat_row_) || (img_col_ != feat_col_) || (img_slc_ != feat_slc_)) {
    std::cerr << "Error. Image shape differs from features shape. Abort." << std::endl;
    return;
  }

  // check if shape not 0
  if ((!img_row_) || (!img_col_) || (!img_slc_)) {
    std::cerr << "Error. Either rows, columns or slices are 0. Abort." << std::endl;
    return;
  }
  // transform feature to unary
  unary_3d_ = new float[feat_row_ * feat_col_ * feat_slc_ * feat_channel_];
  calc_unary(unary_3d_, feat_, feat_row_, feat_col_, feat_slc_, feat_channel_);

  // Initialize the magic..
  DenseCRF3D crf(img_slc_, img_col_, img_row_, feat_channel_);

  // Set verbose
  crf.verbose(verb_);

  // Specify the unary potential as an array of size W*H*D*(#classes)
  // packing order: x0y0z0l0 x0y0z0l1 x0y0z0l2 .. x1y0z0l0 x1y0z0l1 ... (row-order) (image packing order is std fortran order, like numpy.ravel(img, order='F'))
  if (crf.isVerbose())
    std::cout << "pre energy" << std::endl;
  crf.setUnaryEnergy(unary_3d_);
  // add a gray intensity independent term (feature = pixel location 0..W-1, 0..H-1)
  if (crf.isVerbose())
    std::cout << "pre gaussian" << std::endl;
  crf.addPairwiseGaussian(inp_.PosXStd, inp_.PosYStd, inp_.PosZStd, inp_.PosW);
  // add a gray intensity dependent term (feature = xyzg)
  if (crf.isVerbose())
    std::cout << "pre bilateral" << std::endl;
  crf.addPairwiseBilateral(inp_.BilateralXStd, inp_.BilateralYStd, inp_.BilateralZStd, inp_.BilateralGStd, img_, inp_.BilateralW);

  // create map (=maximum a posteriori)
  map_ = new short[img_row_ * img_col_ * img_slc_];

  if (crf.isVerbose())
    std::cout << "pre premap" << std::endl;

  crf.map(inp_.MaxIterations, map_);

  // print out some values from raw Map array configuration
  if (crf.isVerbose()) {
    long ctr = 0;
    for (long i = 0; i < img_row_ * img_col_ * img_slc_; i++) {
      if (map_[i] > 0) {
	  ctr++;
      }
      if (i % (img_row_ * img_col_ * img_slc_/20) == 0) {
	  std::cout << map_[i] << " ";
      }
    }
    std::cout << std::endl << "Maximum a posteriori > 0: " << ctr << std::endl;
  }

  // transform to vector
  short * start = map_;
  short * end = map_ + img_row_ * img_col_ * img_slc_;
  v_map.clear();
  v_map.insert(v_map.end(), start, end);

  // tidy up
  tidy_up();

  if (crf.isVerbose())
    std::cout << "Done." << std::endl;
}
Exemplo n.º 29
0
bool RectanglePacker::addRectangle(uint16_t _width, uint16_t _height, uint16_t& _outX, uint16_t& _outY)
{
	int best_height, best_index;
	int32_t best_width;
	Node* node;
	Node* prev;
	_outX = 0;
	_outY = 0;

	best_height = INT_MAX;
	best_index = -1;
	best_width = INT_MAX;
	for (uint16_t ii = 0, num = uint16_t(m_skyline.size() ); ii < num; ++ii)
	{
		int32_t yy = fit(ii, _width, _height);
		if (yy >= 0)
		{
			node = &m_skyline[ii];
			if ( ( (yy + _height) < best_height)
			|| ( ( (yy + _height) == best_height) && (node->width < best_width) ) )
			{
				best_height = uint16_t(yy) + _height;
				best_index = ii;
				best_width = node->width;
				_outX = node->x;
				_outY = uint16_t(yy);
			}
		}
	}

	if (best_index == -1)
	{
		return false;
	}

	Node newNode(_outX, _outY + _height, _width);
	m_skyline.insert(m_skyline.begin() + best_index, newNode);

	for (uint16_t ii = uint16_t(best_index + 1), num = uint16_t(m_skyline.size() ); ii < num; ++ii)
	{
		node = &m_skyline[ii];
		prev = &m_skyline[ii - 1];
		if (node->x < (prev->x + prev->width) )
		{
			uint16_t shrink = uint16_t(prev->x + prev->width - node->x);
			node->x += shrink;
			node->width -= shrink;
			if (node->width <= 0)
			{
				m_skyline.erase(m_skyline.begin() + ii);
				--ii;
				--num;
			}
			else
			{
				break;
			}
		}
		else
		{
			break;
		}
	}

	merge();
	m_usedSpace += _width * _height;
	return true;
}
void mod_ui::try_add(const std::string &mod_to_add,
                     std::vector<std::string> &active_list)
{
    if (std::find(active_list.begin(), active_list.end(), mod_to_add) != active_list.end()) {
        // The same mod can not be added twice. That makes no sense.
        return;
    }
    MOD_INFORMATION &mod = *active_manager->mod_map[mod_to_add];
    bool errs;
    try {
        dependency_node *checknode = mm_tree->get_node(mod.ident);
        if (!checknode) {
            return;
        }
        errs = checknode->has_errors();
    } catch (std::exception &e) {
        errs = true;
    }

    if (errs) {
        // cannot add, something wrong!
        return;
    }
    // get dependencies of selection in the order that they would appear from the top of the active list
    std::vector<std::string> dependencies = mm_tree->get_dependencies_of_X_as_strings(mod.ident);

    // check to see if mod is a core, and if so check to see if there is already a core in the mod list
    if (mod._type == MT_CORE) {
        //  (more than 0 active elements) && (active[0] is a CORE)                            &&    active[0] is not the add candidate
        if ((active_list.size() > 0) && (active_manager->mod_map[active_list[0]]->_type == MT_CORE) &&
            (active_list[0] != mod_to_add)) {
            // remove existing core
            try_rem(0, active_list);
        }

        // add to start of active_list if it doesn't already exist in it
        active_list.insert(active_list.begin(), mod_to_add);
    } else { // _type == MT_SUPPLEMENTAL
        // now check dependencies and add them as necessary
        std::vector<std::string> mods_to_add;
        bool new_core = false;
        for (int i = 0; i < dependencies.size(); ++i) {
            if(std::find(active_list.begin(), active_list.end(), dependencies[i]) == active_list.end()) {
                if (active_manager->mod_map[dependencies[i]]->_type == MT_CORE) {
                    mods_to_add.insert(mods_to_add.begin(), dependencies[i]);
                    new_core = true;
                } else {
                    mods_to_add.push_back(dependencies[i]);
                }
            }
        }

        if (new_core && active_list.size() > 0) {
            try_rem(0, active_list);
            active_list.insert(active_list.begin(), mods_to_add[0]);
            mods_to_add.erase(mods_to_add.begin());
        }
        // now add the rest of the dependencies serially to the end
        for (int i = 0; i < mods_to_add.size(); ++i) {
            active_list.push_back(mods_to_add[i]);
        }
        // and finally add the one we are trying to add!
        active_list.push_back(mod.ident);
    }
}