当前位置: 首页>>代码示例>>C++>>正文


C++ vector::empty方法代码示例

本文整理汇总了C++中std::vector::empty方法的典型用法代码示例。如果您正苦于以下问题:C++ vector::empty方法的具体用法?C++ vector::empty怎么用?C++ vector::empty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在std::vector的用法示例。


在下文中一共展示了vector::empty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: D_DoDefDehackedPatch

//
// D_DoDefDehackedPatch
//
// [Russell] - Change the meaning, this will load multiple patch files if
//             specified
void D_DoDefDehackedPatch (const std::vector<std::string> patch_files = std::vector<std::string>())
{
    DArgs files;
    BOOL noDef = false;
    BOOL chexLoaded = false;
    QWORD i;

    if (!patch_files.empty())
    {
        std::string f;
        std::string ext;

        // we want the extension of the file
        for (i = 0; i < patch_files.size(); i++)
        {
            if (M_ExtractFileExtension(patch_files[i], ext))
            {
                f = BaseFileSearch (patch_files[i], ext);

                if (f.length())
                {
                    DoDehPatch (f.c_str(), false);

                    noDef = true;
                }
            }
        }
    }
    else // [Russell] - Only load if patch_files is empty
    {
        // try .deh files on command line

        files = Args.GatherFiles ("-deh", ".deh", false);

        if (files.NumArgs())
        {
            for (i = 0; i < files.NumArgs(); i++)
            {
                std::string f = BaseFileSearch (files.GetArg (i), ".DEH");

                if (f.length()) {
                    DoDehPatch (f.c_str(), false);
                    if (!strncmp(files.GetArg (i),"chex.deh",8))
						chexLoaded = true;
                }
            }
            noDef = true;
        }

        if (gamemode == retail_chex && !multiplayer && !chexLoaded)
			Printf(PRINT_HIGH,"Warning: chex.deh not loaded, experience may differ from the original!\n");

        // remove the old arguments
        files.FlushArgs();

        // try .bex files on command line
        files = Args.GatherFiles ("-bex", ".bex", false);

        if (files.NumArgs())
        {
            for (i = 0; i < files.NumArgs(); i++)
            {
                std::string f = BaseFileSearch (files.GetArg (i), ".BEX");

                if (f.length())
                    DoDehPatch (f.c_str(), false);
            }
            noDef = true;
        }
    }

    // try default patches
    if (!noDef)
        DoDehPatch (NULL, true);	// See if there's a patch in a PWAD
}
开发者ID:JohnnyonFlame,项目名称:odamex,代码行数:80,代码来源:d_main.cpp

示例2: skinDetect

Mat visionUtils::skinDetect(Mat captureframe, Mat3b *skinDetectHSV, Mat *skinMask, std::vector<int> adaptiveHSV, int minPixelSize, int imgBlurPixels, int imgMorphPixels, int singleRegionChoice, bool displayFaces)
{

    if (adaptiveHSV.size()!=6 || adaptiveHSV.empty())
    {
        adaptiveHSV.clear();
        adaptiveHSV.push_back(5);
        adaptiveHSV.push_back(38);
        adaptiveHSV.push_back(51);
        adaptiveHSV.push_back(17);
        adaptiveHSV.push_back(250);
        adaptiveHSV.push_back(242);
    }


    //int step = 0;
    Mat3b frameTemp;
    Mat3b frame;
    // Forcing resize to 640x480 -> all thresholds / pixel filters configured for this size.....
    // Note returned to original size at end...
    Size s = captureframe.size();
    cv::resize(captureframe,captureframe,Size(640,480));



    if (useGPU)
    {
        GpuMat imgGPU, imgGPUHSV;
        imgGPU.upload(captureframe);
        cv::cvtColor(imgGPU, imgGPUHSV, CV_BGR2HSV);
        GaussianBlur(imgGPUHSV, imgGPUHSV, Size(imgBlurPixels,imgBlurPixels), 1, 1);
        imgGPUHSV.download(frameTemp);
    }
    else
    {
        cv::cvtColor(captureframe, frameTemp, CV_BGR2HSV);
        GaussianBlur(frameTemp, frameTemp, Size(imgBlurPixels,imgBlurPixels), 1, 1);
    }

    // Potential FASTER VERSION using inRange
    Mat frameThreshold = Mat::zeros(frameTemp.rows,frameTemp.cols, CV_8UC1);
    Mat hsvMin = (Mat_<int>(1,3) << adaptiveHSV[0], adaptiveHSV[1],adaptiveHSV[2] );
    Mat hsvMax = (Mat_<int>(1,3) << adaptiveHSV[3], adaptiveHSV[4],adaptiveHSV[5] );
    inRange(frameTemp,hsvMin ,hsvMax, frameThreshold);
    frameTemp.copyTo(frame,frameThreshold);

    /* BGR CONVERSION AND THRESHOLD */
    Mat1b frame_gray;

    // send HSV to skinDetectHSV for return
    *skinDetectHSV=frame.clone();

    cv::cvtColor(frame, frame_gray, CV_BGR2GRAY);


    // Adaptive thresholding technique
    // 1. Threshold data to find main areas of skin
    adaptiveThreshold(frame_gray,frame_gray,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY_INV,9,1);


    if (useGPU)
    {
        GpuMat imgGPU;
        imgGPU.upload(frame_gray);
        // 2. Fill in thresholded areas
#if CV_MAJOR_VERSION == 2
        gpu::morphologyEx(imgGPU, imgGPU, CV_MOP_CLOSE, Mat1b(imgMorphPixels,imgMorphPixels,1), Point(-1, -1), 2);
        gpu::GaussianBlur(imgGPU, imgGPU, Size(imgBlurPixels,imgBlurPixels), 1, 1);
#elif CV_MAJOR_VERSION == 3
        //TODO: Check if that's correct
        Mat element = getStructuringElement(MORPH_RECT, Size(imgMorphPixels, imgMorphPixels), Point(-1, -1));
        Ptr<cuda::Filter> closeFilter = cuda::createMorphologyFilter(MORPH_CLOSE, imgGPU.type(), element, Point(-1, -1), 2);
        closeFilter->apply(imgGPU, imgGPU);
        cv::Ptr<cv::cuda::Filter> gaussianFilter = cv::cuda::createGaussianFilter(imgGPU.type(), imgGPU.type(), Size(imgMorphPixels, imgMorphPixels), 1, 1);
        gaussianFilter->apply(imgGPU, imgGPU);
#endif

        imgGPU.download(frame_gray);
    }
    else
    {
        // 2. Fill in thresholded areas
        morphologyEx(frame_gray, frame_gray, CV_MOP_CLOSE, Mat1b(imgMorphPixels,imgMorphPixels,1), Point(-1, -1), 2);
        GaussianBlur(frame_gray, frame_gray, Size(imgBlurPixels,imgBlurPixels), 1, 1);
        // Select single largest region from image, if singleRegionChoice is selected (1)
    }


    if (singleRegionChoice)
    {
        *skinMask = cannySegmentation(frame_gray, -1, displayFaces);
    }
    else // Detect each separate block and remove blobs smaller than a few pixels
    {
        *skinMask = cannySegmentation(frame_gray, minPixelSize, displayFaces);
    }

    // Just return skin
    Mat frame_skin;
    captureframe.copyTo(frame_skin,*skinMask);  // Copy captureframe data to frame_skin, using mask from frame_ttt
//.........这里部分代码省略.........
开发者ID:towardthesea,项目名称:wysiwyd,代码行数:101,代码来源:visionUtils.cpp

示例3: handle_event

void sdl_event_handler::handle_event(const SDL_Event& event)
{
	/** No dispatchers drop the event. */
	if(dispatchers_.empty()) {
		return;
	}

	switch(event.type) {
		case SDL_MOUSEMOTION:
			mouse(SDL_MOUSE_MOTION, {event.motion.x, event.motion.y});
			break;

		case SDL_MOUSEBUTTONDOWN:
			mouse_button_down({event.button.x, event.button.y},
							  event.button.button);
			break;

		case SDL_MOUSEBUTTONUP:
			mouse_button_up({event.button.x, event.button.y},
							event.button.button);
			break;

		case SDL_MOUSEWHEEL:
			mouse_wheel(get_mouse_position(), event.wheel.x, event.wheel.y);
			break;

		case SHOW_HELPTIP_EVENT:
			mouse(SHOW_HELPTIP, get_mouse_position());
			break;

		case HOVER_REMOVE_POPUP_EVENT:
			// remove_popup();
			break;

		case DRAW_EVENT:
			draw(false);
			break;
		case DRAW_ALL_EVENT:
			draw(true);
			break;

		case TIMER_EVENT:
			execute_timer(reinterpret_cast<size_t>(event.user.data1));
			break;

		case CLOSE_WINDOW_EVENT: {
			/** @todo Convert this to a proper new style event. */
			DBG_GUI_E << "Firing " << CLOSE_WINDOW << ".\n";

			window* window = window::window_instance(event.user.code);
			if(window) {
				window->set_retval(window::AUTO_CLOSE);
			}
		} break;

		case SDL_JOYBUTTONDOWN:
			button_down(event);
			break;

		case SDL_JOYBUTTONUP:
			break;

		case SDL_JOYAXISMOTION:
			break;

		case SDL_JOYHATMOTION:
			hat_motion(event);
			break;

		case SDL_KEYDOWN:
			key_down(event);
			break;

		case SDL_WINDOWEVENT:
			switch(event.window.event) {
				case SDL_WINDOWEVENT_EXPOSED:
					draw(true);
					break;

				case SDL_WINDOWEVENT_RESIZED:
					video_resize({event.window.data1, event.window.data2});
					break;

				case SDL_WINDOWEVENT_ENTER:
				case SDL_WINDOWEVENT_FOCUS_GAINED:
					activate();
					break;
			}

			break;

		case SDL_TEXTINPUT:
			text_input(event.text.text);
			break;

#if(defined(_X11) && !defined(__APPLE__)) || defined(_WIN32)
		case SDL_SYSWMEVENT:
			/* DO NOTHING */
			break;
#endif
//.........这里部分代码省略.........
开发者ID:doofus-01,项目名称:wesnoth,代码行数:101,代码来源:handler.cpp

示例4: detectCharsInPlates

std::vector<PossiblePlate> detectCharsInPlates(std::vector<PossiblePlate> &vectorOfPossiblePlates) {
    int intPlateCounter = 0;				// this is only for showing steps
    cv::Mat imgContours;
    std::vector<std::vector<cv::Point> > contours;
    cv::RNG rng;

    if (vectorOfPossiblePlates.empty()) {               // if vector of possible plates is empty
        return(vectorOfPossiblePlates);                 // return
    }
            // at this point we can be sure vector of possible plates has at least one plate

    for (auto &possiblePlate : vectorOfPossiblePlates) {            // for each possible plate, this is a big for loop that takes up most of the function
		
        preprocess(possiblePlate.imgPlate, possiblePlate.imgGrayscale, possiblePlate.imgThresh);        // preprocess to get grayscale and threshold images

#ifdef SHOW_STEPS
        cv::imshow("5a", possiblePlate.imgPlate);
        cv::imshow("5b", possiblePlate.imgGrayscale);
        cv::imshow("5c", possiblePlate.imgThresh);
#endif	// SHOW_STEPS

                // upscale size by 60% for better viewing and character recognition
        cv::resize(possiblePlate.imgThresh, possiblePlate.imgThresh, cv::Size(), 1.6, 1.6);

                // threshold again to eliminate any gray areas
        cv::threshold(possiblePlate.imgThresh, possiblePlate.imgThresh, 0.0, 255.0, CV_THRESH_BINARY | CV_THRESH_OTSU);

#ifdef SHOW_STEPS
        cv::imshow("5d", possiblePlate.imgThresh);
#endif	// SHOW_STEPS

                // find all possible chars in the plate,
                // this function first finds all contours, then only includes contours that could be chars (without comparison to other chars yet)
        std::vector<PossibleChar> vectorOfPossibleCharsInPlate = findPossibleCharsInPlate(possiblePlate.imgGrayscale, possiblePlate.imgThresh);

#ifdef SHOW_STEPS
        imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK);
        contours.clear();
		
        for (auto &possibleChar : vectorOfPossibleCharsInPlate) {
            contours.push_back(possibleChar.contour);
        }

        cv::drawContours(imgContours, contours, -1, SCALAR_WHITE);

        cv::imshow("6", imgContours);
#endif	// SHOW_STEPS
        
                // given a vector of all possible chars, find groups of matching chars within the plate
        std::vector<std::vector<PossibleChar> > vectorOfVectorsOfMatchingCharsInPlate = findVectorOfVectorsOfMatchingChars(vectorOfPossibleCharsInPlate);

#ifdef SHOW_STEPS
        imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK);

        contours.clear();

        for (auto &vectorOfMatchingChars : vectorOfVectorsOfMatchingCharsInPlate) {
            int intRandomBlue = rng.uniform(0, 256);
            int intRandomGreen = rng.uniform(0, 256);
            int intRandomRed = rng.uniform(0, 256);

            for (auto &matchingChar : vectorOfMatchingChars) {
                contours.push_back(matchingChar.contour);
            }
            cv::drawContours(imgContours, contours, -1, cv::Scalar((double)intRandomBlue, (double)intRandomGreen, (double)intRandomRed));
        }
        cv::imshow("7", imgContours);
#endif	// SHOW_STEPS

        if (vectorOfVectorsOfMatchingCharsInPlate.size() == 0) {                // if no groups of matching chars were found in the plate
#ifdef SHOW_STEPS
            std::cout << "chars found in plate number " << intPlateCounter << " = (none), click on any image and press a key to continue . . ." << std::endl;
            intPlateCounter++;
            cv::destroyWindow("8");
            cv::destroyWindow("9");
            cv::destroyWindow("10");
            cv::waitKey(0);
#endif	// SHOW_STEPS
            possiblePlate.strChars = "";            // set plate string member variable to empty string
            continue;                               // go back to top of for loop
        }

        for (auto &vectorOfMatchingChars : vectorOfVectorsOfMatchingCharsInPlate) {                                         // for each vector of matching chars in the current plate
            std::sort(vectorOfMatchingChars.begin(), vectorOfMatchingChars.end(), PossibleChar::sortCharsLeftToRight);      // sort the chars left to right
            vectorOfMatchingChars = removeInnerOverlappingChars(vectorOfMatchingChars);                                     // and eliminate any overlapping chars
        }

#ifdef SHOW_STEPS
        imgContours = cv::Mat(possiblePlate.imgThresh.size(), CV_8UC3, SCALAR_BLACK);

        for (auto &vectorOfMatchingChars : vectorOfVectorsOfMatchingCharsInPlate) {
            int intRandomBlue = rng.uniform(0, 256);
            int intRandomGreen = rng.uniform(0, 256);
            int intRandomRed = rng.uniform(0, 256);

            contours.clear();

            for (auto &matchingChar : vectorOfMatchingChars) {
                contours.push_back(matchingChar.contour);
            }
//.........这里部分代码省略.........
开发者ID:Boduke217,项目名称:OpenCV_3_License_Plate_Recognition_Cpp,代码行数:101,代码来源:DetectChars.cpp

示例5: simplePeakIntegration

/**
 * @brief IntegratePeaksCWSD::simplePeakIntegration
 * Purpose:
 *   Integrate a single crystal peak with the simplest algorithm, i.e.,
 *   by adding all the signal with normalization to monitor counts
 * Requirements:
 *   Valid MDEventWorkspace
 *   Valid PeaksWorkspace
 * Guarantees:
 *   A valid value is given
 */
void IntegratePeaksCWSD::simplePeakIntegration(
    const std::vector<detid_t> &vecMaskedDetID,
    const std::map<int, signal_t> &run_monitor_map) {
  // Check requirements
  if (!m_inputWS)
    throw std::runtime_error("MDEventWorkspace is not defined.");

  // Go through to get value
  API::IMDIterator *mditer = m_inputWS->createIterator();
  size_t nextindex = 1;
  bool scancell = true;
  // size_t currindex = 0;

  // Assuming that MDEvents are grouped by run number, there is no need to
  // loop up the map for peak center and monitor counts each time
  int current_run_number = -1;
  signal_t current_monitor_counts = 0;
  Kernel::V3D current_peak_center = m_peakCenter;

  // signal_t total_signal = 0;
  double min_distance = 10000000;
  double max_distance = -1;

  while (scancell) {
    // Go through all the MDEvents in one cell.
    size_t numeventincell = mditer->getNumEvents();

    for (size_t iev = 0; iev < numeventincell; ++iev) {
      // Get signal to add and skip if signal is zero
      signal_t signal = mditer->getInnerSignal(iev);
      if (signal <= THRESHOLD_SIGNAL)
        continue;

      uint16_t run_number = mditer->getInnerRunIndex(iev);
      int run_number_i = static_cast<int>(run_number);

      /* debug: record raw signals
      if (run_number_i % 1000 == testrunnumber)
      {
        total_signal += signal;
        ++ num_det;
      }
      // ... debug */

      // Check whether this detector is masked
      if (!vecMaskedDetID.empty()) {
        detid_t detid = mditer->getInnerDetectorID(iev);
        std::vector<detid_t>::const_iterator it;

        it = find(vecMaskedDetID.begin(), vecMaskedDetID.end(), detid);
        if (it != vecMaskedDetID.end()) {
          // The detector ID is found among masked detector IDs
          // Skip this event and move to next

          /* debug: record masked detectors
          if (run_number_i % 1000 == testrunnumber)
          {
            num_masked_det += 1;
            g_log.warning() << "Masked detector ID = " << detid << ", Signal = "
          << signal << "\n";
          }
          // ... debug */

          continue;
        }
      }

      /* debug: record unmasked detectors
      if (run_number_i % 1000 == testrunnumber)
        num_unmasked_det += 1;
      // ... debug */

      // Check whether to update monitor counts and peak center
      if (current_run_number != run_number_i) {
        // update run number
        current_run_number = run_number_i;
        // update monitor counts
        if (m_normalizeByMonitor) {
          std::map<int, signal_t>::const_iterator m_finder =
              run_monitor_map.find(current_run_number);
          if (m_finder != run_monitor_map.end())
            current_monitor_counts = m_finder->second;
          else {
            std::stringstream errss;
            errss << "Unable to find run number " << current_run_number
                  << " in monitor counts map";
            throw std::runtime_error(errss.str());
          }
        } else {
//.........这里部分代码省略.........
开发者ID:peterfpeterson,项目名称:mantid,代码行数:101,代码来源:IntegratePeaksCWSD.cpp

示例6: load

	registry load(const std::vector<char>& data)
	{
		registry result;

		// Hack for empty input (TODO)
		if (data.empty())
		{
			return result;
		}

		// Check size
		CHECK_ASSERTION(data.size() >= sizeof(header_t));
		CHECK_ASSERTION((std::uintptr_t)data.data() % 8 == 0);

		// Get header
		const header_t& header = reinterpret_cast<const header_t&>(data[0]);

		// Check magic and version
		CHECK_ASSERTION(header.magic == *(u32*)"\0PSF");
		CHECK_ASSERTION(header.version == 0x101);
		CHECK_ASSERTION(sizeof(header_t) + header.entries_num * sizeof(def_table_t) <= header.off_key_table);
		CHECK_ASSERTION(header.off_key_table <= header.off_data_table);
		CHECK_ASSERTION(header.off_data_table <= data.size());

		// Get indices (alignment should be fine)
		const def_table_t* indices = reinterpret_cast<const def_table_t*>(data.data() + sizeof(header_t));

		// Load entries
		for (u32 i = 0; i < header.entries_num; ++i)
		{
			CHECK_ASSERTION(indices[i].key_off < header.off_data_table - header.off_key_table);

			// Get key name range
			const auto name_ptr = data.begin() + header.off_key_table + indices[i].key_off;
			const auto name_end = std::find(name_ptr , data.begin() + header.off_data_table, '\0');

			// Get name (must be unique)
			std::string key(name_ptr, name_end);

			CHECK_ASSERTION(result.count(key) == 0);
			CHECK_ASSERTION(indices[i].param_len <= indices[i].param_max);
			CHECK_ASSERTION(indices[i].data_off < data.size() - header.off_data_table);
			CHECK_ASSERTION(indices[i].param_max < data.size() - indices[i].data_off);

			// Get data pointer
			const auto value_ptr = data.begin() + header.off_data_table + indices[i].data_off;

			if (indices[i].param_fmt == format::integer && indices[i].param_max == sizeof(u32) && indices[i].param_len == sizeof(u32))
			{
				// Integer data
				result.emplace(std::piecewise_construct,
					std::forward_as_tuple(std::move(key)),
					std::forward_as_tuple(reinterpret_cast<const le_t<u32>&>(*value_ptr)));
			}
			else if (indices[i].param_fmt == format::string || indices[i].param_fmt == format::array)
			{
				// String/array data
				std::string value;

				if (indices[i].param_fmt == format::string)
				{
					// Find null terminator
					value.assign(value_ptr, std::find(value_ptr, value_ptr + indices[i].param_len, '\0'));
				}
				else
				{
					value.assign(value_ptr, value_ptr + indices[i].param_len);
				}

				result.emplace(std::piecewise_construct,
					std::forward_as_tuple(std::move(key)),
					std::forward_as_tuple(indices[i].param_fmt, indices[i].param_max, std::move(value)));
			}
			else
			{
				// Possibly unsupported format, entry ignored
				log.error("Unknown entry format (key='%s', fmt=0x%x, len=0x%x, max=0x%x)", key, indices[i].param_fmt, indices[i].param_len, indices[i].param_max);
			}
		}

		return result;
	}
开发者ID:976717326,项目名称:rpcs3,代码行数:82,代码来源:PSF.cpp

示例7: doSelectbox


//.........这里部分代码省略.........

				case LEFT:
					if (selected > 0)
					{
						selected--;
						changed = SBA_SELECT;
					}
					mLastKeyAction = NONE;
					break;

				case RIGHT:
					if (selected + 1 < entries.size())
					{
						selected++;
						changed = SBA_SELECT;
					}
					mLastKeyAction = NONE;
					break;

				default:
					break;
			}
		}

		// React to mouse input.
		Vector2 mousepos = InputManager::getSingleton()->position();
		if (mousepos.x > pos1.x && mousepos.y > pos1.y && mousepos.x < pos2.x && mousepos.y < pos2.y)
		{
			obj.type = ACTIVESELECTBOX;
			if (InputManager::getSingleton()->click())
				mActiveButton = id;
		}
		//entries mouseclick:
		if (mousepos.x > pos1.x &&
			mousepos.y > pos1.y+5 &&
			mousepos.x < pos2.x-35 &&
			mousepos.y < pos1.y+5+FontSize*itemsPerPage)
		{
			if (InputManager::getSingleton()->click())
			{
				int tmp = (int)((mousepos.y - pos1.y - 5) / FontSize) + first;
				/// \todo well, it's not really a doulbe click...
				/// we need to do this in inputmanager
				if( selected == tmp && InputManager::getSingleton()->doubleClick() )
					changed = SBA_DBL_CLICK;

				if (tmp >= 0 && static_cast<unsigned int>(tmp) < entries.size())
					selected = tmp;

				mActiveButton = id;
			}
			if ((InputManager::getSingleton()->mouseWheelUp()) && (selected > 0))
			{
				selected--;
				changed = SBA_SELECT;
			}
			if ((InputManager::getSingleton()->mouseWheelDown()) && (selected + 1 < entries.size()))
			{
				selected++;
				changed = SBA_SELECT;
			}
		}
		//arrows mouseclick:
		if (mousepos.x > pos2.x-30 && mousepos.x < pos2.x-30+24 && InputManager::getSingleton()->click())
		{
			if (mousepos.y > pos1.y+3 && mousepos.y < pos1.y+3+24 && selected > 0)
			{
				selected--;
				changed = SBA_SELECT;
			}

			if (mousepos.y > pos2.y-27 && mousepos.y < pos2.y-27+24 && selected + 1 < entries.size())
			{
				selected++;
				changed = SBA_SELECT;
			}
		}
	}
	doImage(GEN_ID, Vector2(pos2.x-15, pos1.y+15), "gfx/pfeil_oben.bmp");
	doImage(GEN_ID, Vector2(pos2.x-15, pos2.y-15), "gfx/pfeil_unten.bmp");

	first = (selected / itemsPerPage)*itemsPerPage; //recalc first
	if ( !entries.empty() )
	{
		unsigned int last = first + itemsPerPage;
		if (last > entries.size())
			last = entries.size();

		obj.entries = std::vector<std::string>(entries.begin()+first, entries.begin()+last);
	}
	else
		obj.entries = std::vector<std::string>();

	obj.selected = selected-first;

	mLastWidget = id;
	mQueue->push(obj);

	return changed;
}
开发者ID:EliasOenal,项目名称:blobby,代码行数:101,代码来源:IMGUI.cpp

示例8: processString


//.........这里部分代码省略.........
  for (; ; c++) {
    if ((!buf[c]) ||
        ((buf[c] == buf[c+1]) &&
         ((buf[c] == '<') ||
          (buf[c] == '=') ||
          (buf[c] == '>') ||
          (buf[c] == '-') ||
          (buf[c] == '|')))) {
      if (title || label || separator || button) {
        chr = buf[c];
        buf[c] = 0;

        if (title) {
          setText(beg);
        }
        else if (label) {
          Label* label = new Label(beg);
          label->setAlign(align);
          labels.push_back(label);
        }
        else if (separator) {
          labels.push_back(new Separator("", HORIZONTAL));
        }
        else if (button) {
          char buttonId[256];
          Button* button_widget = new Button(beg);
          button_widget->setMinSize(gfx::Size(60*guiscale(), 0));
          buttons.push_back(button_widget);

          sprintf(buttonId, "button-%lu", buttons.size());
          button_widget->setId(buttonId);
          button_widget->Click.connect(Bind<void>(&Window::closeWindow, this, button_widget));
        }

        buf[c] = chr;
      }

      /* done */
      if (!buf[c])
        break;
      /* next widget */
      else {
        title = label = separator = button = false;
        beg = buf+c+2;
        align = 0;

        switch (buf[c]) {
          case '<': label=true; align=LEFT; break;
          case '=': label=true; align=CENTER; break;
          case '>': label=true; align=RIGHT; break;
          case '-': separator=true; break;
          case '|': button=true; break;
        }
        c++;
      }
    }
  }

  box1 = new Box(VERTICAL);
  box2 = new Box(VERTICAL);
  grid = new Grid(1, false);
  box3 = new Box(HORIZONTAL | HOMOGENEOUS);

  // To identify by the user
  box2->setId("labels");
  box3->setId("buttons");

  // Pseudo separators (only to fill blank space)
  box4 = new Box(0);
  box5 = new Box(0);
  m_progressPlaceholder = new Box(0);

  box4->setExpansive(true);
  box5->setExpansive(true);
  box4->noBorderNoChildSpacing();
  box5->noBorderNoChildSpacing();
  m_progressPlaceholder->noBorderNoChildSpacing();

  // Setup parent <-> children relationship

  addChild(box1);

  box1->addChild(box4); // Filler
  box1->addChild(box2); // Labels
  box1->addChild(m_progressPlaceholder);
  box1->addChild(box5); // Filler
  box1->addChild(grid); // Buttons

  grid->addChildInCell(box3, 1, 1, CENTER | BOTTOM);

  for (std::vector<Widget*>::iterator it = labels.begin(); it != labels.end(); ++it)
    box2->addChild(*it);

  for (std::vector<Widget*>::iterator it = buttons.begin(); it != buttons.end(); ++it)
    box3->addChild(*it);

  // Default button is the last one
  if (!buttons.empty())
    buttons[buttons.size()-1]->setFocusMagnet(true);
}
开发者ID:93i,项目名称:aseprite,代码行数:101,代码来源:alert.cpp

示例9: buildKdTreeNode_ALT

static void buildKdTreeNode_ALT(
    KDTreeNode* Node, const std::vector<SCollisionFace> &Faces, s32 ForkLevel, const EKDTreeBuildingConcepts Concept)
{
    if (!Node || Faces.empty())
        return;
    
    /* Check if tree node is a leaf */
    if (ForkLevel <= 0)
    {
        buildKdTreeNodeLeaf_ALT(Node, Faces);
        return;
    }
    
    const dim::aabbox3df BoundBox(Node->getBox());
    
    /* Compute average vertex position */
    dim::vector3df AvgVertPos;
    
    switch (Concept)
    {
        case KDTREECONCEPT_CENTER:
        {
            AvgVertPos = BoundBox.getCenter();
        }
        break;
        
        case KDTREECONCEPT_AVERAGE:
        {
            #if 0
            
            foreach (const SCollisionFace &Face, Faces)
                AvgVertPos += Face.Triangle.getCenter();
            
            AvgVertPos /= dim::vector3df(static_cast<f32>(Faces.size()));
            
            #else
            
            /* Compute median position */
            std::vector<f32> MedianPos[3];
            
            for (s32 i = 0; i < 3; ++i)
            {
                MedianPos[i].resize(Faces.size());
                
                u32 j = 0;
                foreach (const SCollisionFace &Face, Faces)
                    (MedianPos[i])[j++] = Face.Triangle.getCenter()[i];
                
                std::sort(MedianPos[i].begin(), MedianPos[i].end());
                
                AvgVertPos[i] = (MedianPos[i])[MedianPos[i].size()/2];
            }
            
            #endif
        }
        break;
    }
    
    /* Fill potentially sub triangle lists */
    s32 PotFaceCountNear[3], PotFaceCountFar[3];
    
    foreach (const SCollisionFace &Face, Faces)
    {
        for (s32 i = 0; i < 3; ++i)
        {
            if (Face.Triangle.PointA[i] < AvgVertPos[i] ||
                Face.Triangle.PointB[i] < AvgVertPos[i] ||
                Face.Triangle.PointC[i] < AvgVertPos[i])
            {
                ++PotFaceCountNear[i];
            }
            if (Face.Triangle.PointA[i] >= AvgVertPos[i] ||
                Face.Triangle.PointB[i] >= AvgVertPos[i] ||
                Face.Triangle.PointC[i] >= AvgVertPos[i])
            {
                ++PotFaceCountFar[i];
            }
        }
    }
    
    /* Search for optimal tree partitioning */
    EKDTreeAxles Axis = KDTREE_XAXIS;
    
    switch (Concept)
    {
        case KDTREECONCEPT_CENTER:
        {
            const dim::vector3df BoxSize(BoundBox.getSize());
            
            if (BoxSize.X >= BoxSize.Y && BoxSize.X >= BoxSize.Z)
                Axis = KDTREE_XAXIS;
            else if (BoxSize.Y >= BoxSize.X && BoxSize.Y >= BoxSize.Z)
                Axis = KDTREE_YAXIS;
            else
                Axis = KDTREE_ZAXIS;
        }
        break;
        
        case KDTREECONCEPT_AVERAGE:
        {
//.........这里部分代码省略.........
开发者ID:bekasov,项目名称:SoftPixelEngine,代码行数:101,代码来源:spTreeBuilder.cpp

示例10:

ssh_add_options &get_current_options() {
	if(on_demand_keys.empty()) return global_options;
	else return on_demand_keys.back().options;
}
开发者ID:JGRennison,项目名称:ssh-agent-utils,代码行数:4,代码来源:ssh-agent-on-demand.cpp

示例11: create_vehicle_markers

/**
 * @brief publish vehicle
 */
static void create_vehicle_markers( int num_rotors, float arm_len, float body_width, float body_height )
{
	if ( num_rotors <= 0 ) num_rotors = 2;

	/** Create markers only once for efficiency
	 *  TODO use visualization_msgs::MarkerArray?
	 */

	if ( !vehicle_markers.empty() )
		return;

	vehicle_markers.reserve( 2 * num_rotors + 1 );

	/** Hexacopter marker code adapted from libsfly_viz
	 *  thanks to Markus Achtelik.
	 */

	// rotor marker template
	visualization_msgs::Marker rotor;
	rotor.header.stamp = ros::Time();
	rotor.header.frame_id = child_frame_id;
	rotor.ns = "vehicle_rotor";
	rotor.action = visualization_msgs::Marker::ADD;
	rotor.type = visualization_msgs::Marker::CYLINDER;
	rotor.scale.x = 0.2 * marker_scale;
	rotor.scale.y = 0.2 * marker_scale;
	rotor.scale.z = 0.01 * marker_scale;
	rotor.color.r = 0.4;
	rotor.color.g = 0.4;
	rotor.color.b = 0.4;
	rotor.color.a = 0.8;
	rotor.pose.position.z = 0;

	// arm marker template
	visualization_msgs::Marker arm;
	arm.header.stamp = ros::Time();
	arm.header.frame_id = child_frame_id;
	arm.ns = "vehicle_arm";
	arm.action = visualization_msgs::Marker::ADD;
	arm.type = visualization_msgs::Marker::CUBE;
	arm.scale.x = arm_len * marker_scale;
	arm.scale.y = 0.02 * marker_scale;
	arm.scale.z = 0.01 * marker_scale;
	arm.color.r = 0.0;
	arm.color.g = 0.0;
	arm.color.b = 1.0;
	arm.color.a = 1.0;
	arm.pose.position.z = -0.015 * marker_scale;

	float angle_increment = 2 * M_PI / num_rotors;

	for ( float angle = angle_increment / 2; angle <= (2 * M_PI); angle += angle_increment )
	{
		rotor.pose.position.x = arm_len * cos(angle) * marker_scale;
		rotor.pose.position.y = arm_len * sin(angle) * marker_scale;
		rotor.id++;

		arm.pose.position.x = rotor.pose.position.x / 2;
		arm.pose.position.y = rotor.pose.position.y / 2;
		arm.pose.orientation = tf::createQuaternionMsgFromYaw(angle);
		arm.id++;

		vehicle_markers.push_back(rotor);
		vehicle_markers.push_back(arm);
	}

	// body marker template
	visualization_msgs::Marker body;
	body.header.stamp = ros::Time();
	body.header.frame_id = child_frame_id;
	body.ns = "vehicle_body";
	body.action = visualization_msgs::Marker::ADD;
	body.type = visualization_msgs::Marker::CUBE;
	body.scale.x = body_width * marker_scale;
	body.scale.y = body_width * marker_scale;
	body.scale.z = body_height * marker_scale;
	body.color.r = 0.0;
	body.color.g = 1.0;
	body.color.b = 0.0;
	body.color.a = 0.8;

	vehicle_markers.push_back(body);
}
开发者ID:bluerobotics,项目名称:mavros,代码行数:86,代码来源:copter_visualization.cpp

示例12: JSONRPCError

AsyncRPCOperation_mergetoaddress::AsyncRPCOperation_mergetoaddress(
    boost::optional<TransactionBuilder> builder,
    CMutableTransaction contextualTx,
    std::vector<MergeToAddressInputUTXO> utxoInputs,
    std::vector<MergeToAddressInputSproutNote> sproutNoteInputs,
    std::vector<MergeToAddressInputSaplingNote> saplingNoteInputs,
    MergeToAddressRecipient recipient,
    CAmount fee,
    UniValue contextInfo) :
    tx_(contextualTx), utxoInputs_(utxoInputs), sproutNoteInputs_(sproutNoteInputs),
    saplingNoteInputs_(saplingNoteInputs), recipient_(recipient), fee_(fee), contextinfo_(contextInfo)
{
    if (fee < 0 || fee > MAX_MONEY) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Fee is out of range");
    }

    if (utxoInputs.empty() && sproutNoteInputs.empty() && saplingNoteInputs.empty()) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "No inputs");
    }

    if (std::get<0>(recipient).size() == 0) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Recipient parameter missing");
    }

    if (sproutNoteInputs.size() > 0 && saplingNoteInputs.size() > 0) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot send from both Sprout and Sapling addresses using z_mergetoaddress");
    }

    if (sproutNoteInputs.size() > 0 && builder) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Sprout notes are not supported by the TransactionBuilder");
    }

    isUsingBuilder_ = false;
    if (builder) {
        isUsingBuilder_ = true;
        builder_ = builder.get();
    }

    toTaddr_ = DecodeDestination(std::get<0>(recipient));
    isToTaddr_ = IsValidDestination(toTaddr_);
    isToZaddr_ = false;

    if (!isToTaddr_) {
        auto address = DecodePaymentAddress(std::get<0>(recipient));
        if (IsValidPaymentAddress(address)) {
            isToZaddr_ = true;
            toPaymentAddress_ = address;
        } else {
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid recipient address");
        }
    }

    // Log the context info i.e. the call parameters to z_mergetoaddress
    if (LogAcceptCategory("zrpcunsafe")) {
        LogPrint("zrpcunsafe", "%s: z_mergetoaddress initialized (params=%s)\n", getId(), contextInfo.write());
    } else {
        LogPrint("zrpc", "%s: z_mergetoaddress initialized\n", getId());
    }

    // Lock UTXOs
    lock_utxos();
    lock_notes();

    // Enable payment disclosure if requested
    paymentDisclosureMode = fExperimentalMode && GetBoolArg("-paymentdisclosure", false);
}
开发者ID:bitcartel,项目名称:zcash,代码行数:66,代码来源:asyncrpcoperation_mergetoaddress.cpp

示例13: memset

std::vector<size_t> D_DoomWadReboot(
	const std::vector<std::string> &wadnames,
    const std::vector<std::string> &patch_files,
    std::vector<std::string> needhashes
)
{
	std::vector<size_t> fails;
	size_t i;


	// already loaded these?
 	if (lastWadRebootSuccess &&
		!wadhashes.empty() &&
			needhashes ==
				std::vector<std::string>(wadhashes.begin()+1, wadhashes.end()))
	{
		// fast track if files have not been changed // denis - todo - actually check the file timestamps
		Printf (PRINT_HIGH, "Currently loaded WADs match server checksum\n\n");
		return std::vector<size_t>();
	}

	// assume failure
	lastWadRebootSuccess = false;

	if (modifiedgame && (gameinfo.flags & GI_SHAREWARE))
		I_Error ("\nYou cannot switch WAD with the shareware version. Register!");

	if(gamestate == GS_LEVEL)
		G_ExitLevel(0, 0);

	AM_Stop();
	S_Stop();

	DThinker::DestroyAllThinkers();

	// Close all open WAD files
	W_Close();

	// [ML] 9/11/10: Reset custom wad level information from MAPINFO et al.
    // I have never used memset, I hope I am not invoking satan by doing this :(
	if (wadlevelinfos)
    {
		for (i = 0; i < numwadlevelinfos; i++)
			if (wadlevelinfos[i].snapshot)
			{
				delete wadlevelinfos[i].snapshot;
				wadlevelinfos[i].snapshot = NULL;
			}
        memset(wadlevelinfos,0,sizeof(wadlevelinfos));
        numwadlevelinfos = 0;
    }

    if (wadclusterinfos)
    {
        memset(wadclusterinfos,0,sizeof(wadclusterinfos));
        numwadclusterinfos = 0;
    }

	// Restart the memory manager
	Z_Init();

	gamestate_t oldgamestate = gamestate;
	gamestate = GS_STARTUP; // prevent console from trying to use nonexistant font

	wadfiles.clear();
	modifiedgame = false;

	std::string custwad;
	if(wadnames.empty() == false)
		custwad = wadnames[0];

	D_AddDefWads(custwad);

	for(i = 0; i < wadnames.size(); i++)
	{
		std::string tmp = wadnames[i];

		// strip absolute paths, as they present a security risk
		FixPathSeparator(tmp);
		size_t slash = tmp.find_last_of(PATHSEPCHAR);
		if(slash != std::string::npos)
			tmp = tmp.substr(slash + 1, tmp.length() - slash);

        // [Russell] - Generate a hash if it doesn't exist already
        if (needhashes[i].empty())
            needhashes[i] = W_MD5(tmp);

		std::string file = BaseFileSearch(tmp, ".wad", needhashes[i]);

		if(file.length())
			wadfiles.push_back(file);
		else
		{
			Printf (PRINT_HIGH, "could not find WAD: %s\n", tmp.c_str());
			fails.push_back(i);
		}
	}

	if(wadnames.size() > 1)
		modifiedgame = true;
//.........这里部分代码省略.........
开发者ID:JohnnyonFlame,项目名称:odamex,代码行数:101,代码来源:d_main.cpp

示例14: ApplyNonMaximumSuppresion

	void ApplyNonMaximumSuppresion(std::vector< LkTracker* >& in_out_source, float in_nms_threshold)
	{
		if (in_out_source.empty())
			return;

		unsigned int size = in_out_source.size();

		std::vector<float> area(size);
		std::vector<float> scores(size);
		std::vector<int> x1(size);
		std::vector<int> y1(size);
		std::vector<int> x2(size);
		std::vector<int> y2(size);
		std::vector<unsigned int> indices(size);
		std::vector<bool> is_suppresed(size);

		for(unsigned int i = 0; i< in_out_source.size(); i++)
		{
			ObjectDetection tmp = in_out_source[i]->GetTrackedObject();
			area[i] = tmp.rect.width * tmp.rect.height;
			if (area[i]>0)
				is_suppresed[i] = false;
			else
			{
				is_suppresed[i] = true;
				in_out_source[i]->NullifyLifespan();
			}
			indices[i] = i;
			scores[i] = tmp.score;
			x1[i] = tmp.rect.x;
			y1[i] = tmp.rect.y;
			x2[i] = tmp.rect.width + tmp.rect.x;
			y2[i] = tmp.rect.height + tmp.rect.y;
		}

		Sort(area, indices);//returns indices ordered based on scores

		for(unsigned int i=0; i< size; i++)
		{

			for(unsigned int j= i+1; j< size; j++)
			{
				if(is_suppresed[indices[i]] || is_suppresed[indices[j]])
					continue;
				int x1_max = std::max(x1[indices[i]], x1[indices[j]]);
				int x2_min = std::min(x2[indices[i]], x2[indices[j]]);
				int y1_max = std::max(y1[indices[i]], y1[indices[j]]);
				int y2_min = std::min(y2[indices[i]], y2[indices[j]]);
				int overlap_width = x2_min - x1_max + 1;
				int overlap_height = y2_min - y1_max + 1;
				if(overlap_width > 0 && overlap_height>0)
				{
					float overlap_part = (overlap_width*overlap_height)/area[indices[j]];
					if(overlap_part > in_nms_threshold)
					{
						is_suppresed[indices[j]] = true;
						in_out_source[indices[j]]->NullifyLifespan();
						if (in_out_source[indices[j]]->GetFrameCount() > in_out_source[indices[i]]->GetFrameCount())
						{
							in_out_source[indices[i]]->object_id = in_out_source[indices[j]]->object_id;
						}

					}
				}
			}
		}
		return ;
	}
开发者ID:Aand1,项目名称:Autoware,代码行数:68,代码来源:klt_track.cpp

示例15: if

unsigned CriticalAntiDepBreaker::
BreakAntiDependencies(const std::vector<SUnit>& SUnits,
                      MachineBasicBlock::iterator Begin,
                      MachineBasicBlock::iterator End,
                      unsigned InsertPosIndex,
                      DbgValueVector &DbgValues) {
  // The code below assumes that there is at least one instruction,
  // so just duck out immediately if the block is empty.
  if (SUnits.empty()) return 0;

  // Keep a map of the MachineInstr*'s back to the SUnit representing them.
  // This is used for updating debug information.
  //
  // FIXME: Replace this with the existing map in ScheduleDAGInstrs::MISUnitMap
  DenseMap<MachineInstr*,const SUnit*> MISUnitMap;

  // Find the node at the bottom of the critical path.
  const SUnit *Max = 0;
  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
    const SUnit *SU = &SUnits[i];
    MISUnitMap[SU->getInstr()] = SU;
    if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
      Max = SU;
  }

#ifndef NDEBUG
  {
    DEBUG(dbgs() << "Critical path has total latency "
          << (Max->getDepth() + Max->Latency) << "\n");
    DEBUG(dbgs() << "Available regs:");
    for (unsigned Reg = 0; Reg < TRI->getNumRegs(); ++Reg) {
      if (KillIndices[Reg] == ~0u)
        DEBUG(dbgs() << " " << TRI->getName(Reg));
    }
    DEBUG(dbgs() << '\n');
  }
#endif

  // Track progress along the critical path through the SUnit graph as we walk
  // the instructions.
  const SUnit *CriticalPathSU = Max;
  MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();

  // Consider this pattern:
  //   A = ...
  //   ... = A
  //   A = ...
  //   ... = A
  //   A = ...
  //   ... = A
  //   A = ...
  //   ... = A
  // There are three anti-dependencies here, and without special care,
  // we'd break all of them using the same register:
  //   A = ...
  //   ... = A
  //   B = ...
  //   ... = B
  //   B = ...
  //   ... = B
  //   B = ...
  //   ... = B
  // because at each anti-dependence, B is the first register that
  // isn't A which is free.  This re-introduces anti-dependencies
  // at all but one of the original anti-dependencies that we were
  // trying to break.  To avoid this, keep track of the most recent
  // register that each register was replaced with, avoid
  // using it to repair an anti-dependence on the same register.
  // This lets us produce this:
  //   A = ...
  //   ... = A
  //   B = ...
  //   ... = B
  //   C = ...
  //   ... = C
  //   B = ...
  //   ... = B
  // This still has an anti-dependence on B, but at least it isn't on the
  // original critical path.
  //
  // TODO: If we tracked more than one register here, we could potentially
  // fix that remaining critical edge too. This is a little more involved,
  // because unlike the most recent register, less recent registers should
  // still be considered, though only if no other registers are available.
  std::vector<unsigned> LastNewReg(TRI->getNumRegs(), 0);

  // Attempt to break anti-dependence edges on the critical path. Walk the
  // instructions from the bottom up, tracking information about liveness
  // as we go to help determine which registers are available.
  unsigned Broken = 0;
  unsigned Count = InsertPosIndex - 1;
  for (MachineBasicBlock::iterator I = End, E = Begin;
       I != E; --Count) {
    MachineInstr *MI = --I;
    if (MI->isDebugValue())
      continue;

    // Check if this instruction has a dependence on the critical path that
    // is an anti-dependence that we may be able to break. If it is, set
    // AntiDepReg to the non-zero register associated with the anti-dependence.
//.........这里部分代码省略.........
开发者ID:Abocer,项目名称:android-4.2_r1,代码行数:101,代码来源:CriticalAntiDepBreaker.cpp


注:本文中的std::vector::empty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。