bool TaskRecorderManagerClient::getInfo(const task_recorder2_msgs::Description& description,
                                        std::string& abs_file_name)
{
  if(!servicesAreReady())
  {
    waitForServices();
  }
  task_recorder2::GetInfo::Request get_info_request;
  get_info_request.description = description;
  task_recorder2::GetInfo::Response get_info_response;
  if(!get_info_service_client_.call(get_info_request, get_info_response))
  {
    ROS_ERROR("Problems when calling >%s<.", get_info_service_client_.getService().c_str());
    return false;
  }
  if(get_info_response.return_code != task_recorder2::GetInfo::Response::SERVICE_CALL_SUCCESSFUL)
  {
    ROS_ERROR("Service >%s< was not successful: %s (%i)", get_info_service_client_.getService().c_str(),
              get_info_response.info.c_str(), get_info_response.return_code);
    return false;
  }
  abs_file_name.assign(get_info_response.file_name);
  return true;
}
Пример #2
0
std::string CSysInfo::GetManufacturerName(void)
{
  static std::string manufName;
  static bool inited = false;
  if (!inited)
  {
#if defined(TARGET_ANDROID)
    char deviceCStr[PROP_VALUE_MAX];
    int propLen = __system_property_get("ro.product.manufacturer", deviceCStr);
    manufName.assign(deviceCStr, (propLen > 0 && propLen <= PROP_VALUE_MAX) ? propLen : 0);
#elif defined(TARGET_DARWIN)
    manufName = CDarwinUtils::GetManufacturer();
#elif defined(TARGET_WINDOWS_STORE)
    auto eas = EasClientDeviceInformation();
    auto manufacturer = eas.SystemManufacturer();
    g_charsetConverter.wToUTF8(std::wstring(manufacturer.c_str()), manufName);
#elif defined(TARGET_WINDOWS)
    // We just don't care, might be useful on embedded
#endif
    inited = true;
  }

  return manufName;
}
Пример #3
0
std::string CSysInfo::GetKernelName(bool emptyIfUnknown /*= false*/)
{
  static std::string kernelName;
  if (kernelName.empty())
  {
#if defined(TARGET_WINDOWS)
    OSVERSIONINFOEXW osvi;
    if (sysGetVersionExWByRef(osvi) && osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
      kernelName = "Windows NT";
#elif defined(TARGET_POSIX)
    struct utsname un;
    if (uname(&un) == 0)
      kernelName.assign(un.sysname);
#endif // defined(TARGET_POSIX)

    if (kernelName.empty())
      kernelName = "Unknown kernel"; // can't detect
  }

  if (emptyIfUnknown && kernelName == "Unknown kernel")
    return "";

  return kernelName;
}
static void xml_decode(const char *str, std::string& decoded)
{
	static const char raw_entrs[] = { 
		'<',   '>',   '&',    '\'',    '\"',    0 
	};
	static const char* xml_entrs[] = { 
		"lt;", "gt;", "amp;", "apos;", "quot;", 0 
	};
	static const int xml_ent_len[] = { 
		3,     3,     4,      5,       5 
	};
	int ient;
        const char *amp = strchr(str, '&');

        if (amp == NULL) {
		decoded = str;
                return;
        }
        decoded.assign(str, amp - str);
        
        while (*amp)
                if (*amp == '&') {
                        for (ient = 0; xml_entrs[ient] != 0; ++ient)
                                if (strncmp(amp + 1, xml_entrs[ient],
					    xml_ent_len[ient]) == 0) {
                                        decoded += raw_entrs[ient];
                                        amp += xml_ent_len[ient]+1;
                                        break;
                                }
                        if (xml_entrs[ient] == 0)    // unrecognized sequence
                                decoded += *amp++;

                } else {
                        decoded += *amp++;
                }        
}
Пример #5
0
void
Compressor::compress(std::string & in, std::string & out)
{
    switch (m_compression_codec) {
    case CompressionCodec::UNCOMPRESSED:
        {
            // Just swap the input and output collections ...
            out.swap(in);
        }
        break;

    case CompressionCodec::SNAPPY:
        {
            size_t compressed_size;
            m_tmp.resize(snappy::MaxCompressedLength(in.size()));
            snappy::RawCompress((char const *) in.data(),
                                in.size(),
                                (char *) m_tmp.data(),
                                &compressed_size);
            m_tmp.resize(compressed_size);
            out.assign(m_tmp.begin(), m_tmp.end());
        }
        break;
        
    case CompressionCodec::GZIP:
        {
            int window_bits = 15 + 16; // maximum window + GZIP
            z_stream stream;
            memset(&stream, '\0', sizeof(stream));
            int rv = deflateInit2(&stream,
                                  Z_DEFAULT_COMPRESSION,
                                  Z_DEFLATED,
                                  window_bits,
                                  9,
                                  Z_DEFAULT_STRATEGY);
            if (rv != Z_OK) {
                cerr << "deflateInit2 failed: " << rv;
                exit(1);
            }
            m_tmp.resize(deflateBound(&stream, in.size()));
            stream.next_in =
                const_cast<Bytef*>(reinterpret_cast<const Bytef*>(in.data()));
            stream.avail_in = in.size();
            stream.next_out = (Bytef*) m_tmp.data();
            stream.avail_out = m_tmp.size();
            rv = deflate(&stream, Z_FINISH);
            if (rv != Z_STREAM_END) {
                cerr << "gzip deflate failed: " << rv;
                exit(1);
            }

            out.assign(m_tmp.begin(), m_tmp.begin() + stream.total_out);
            deflateEnd(&stream);
        }
        break;

    default:
        cerr << "unsupported compression codec: " << int(m_compression_codec);
        exit(1);
        break;
    }
}
Пример #6
0
 option& set_default_value( const Value& _value ) {
     check_option_necessity();
     value = boost::lexical_cast< std::string >( _value );
     default_value.assign( value.begin(), value.end() );
     return *this;
 }
BOOL LLNetMap::handleToolTip( S32 x, S32 y, std::string& msg, LLRect* sticky_rect_screen )
{
	BOOL handled = FALSE;
	if (gDisconnected)
	{
		return FALSE;
	}
	LLViewerRegion*	region = LLWorld::getInstance()->getRegionFromPosGlobal(viewPosToGlobal(x, y, gSavedSettings.getBOOL( "MiniMapRotate" )));
	if( region )
	{
		msg.assign("");
		std::string fullname;
		if(mClosestAgentToCursor.notNull() && gCacheName->getFullName(mClosestAgentToCursor, fullname))
		{
			//msg.append(fullname);
// [RLVa:KB] - Version: 1.23.4 | Checked: 2009-07-08 (RLVa-1.0.0e) | Modified: RLVa-0.2.0b
            // [Ansariel: Display name support]
			// msg.append( (!gRlvHandler.hasBehaviour(RLV_BHVR_SHOWNAMES)) ? fullname : RlvStrings::getAnonym(fullname) );
            if (gRlvHandler.hasBehaviour(RLV_BHVR_SHOWNAMES))
            {
                msg.append(RlvStrings::getAnonym(fullname));
            }
            else
            {
				if (LLAvatarNameCache::useDisplayNames())
    			{
					LLAvatarName avatar_name;
					if (LLAvatarNameCache::get(mClosestAgentToCursor, &avatar_name))
					{
						static const LLCachedControl<S32> phoenix_name_system("PhoenixNameSystem", 0);
						if (phoenix_name_system == 2 || (phoenix_name_system == 1 && avatar_name.mIsDisplayNameDefault))
						{
							fullname = avatar_name.mDisplayName;
						}
						else
						{
							fullname = avatar_name.getCompleteName(true);
						}
					}
				}
                msg.append(fullname);
            }
            // [/Ansariel: Display name support]
// [/RLVa:KB]
			msg.append("\n");

			LLVector3d mypos = gAgent.getPositionGlobal();
			LLVector3d position = mClosestAgentPosition;

			if ( LLFloaterAvatarList::instanceExists() )
			{
				LLAvatarListEntry *ent = LLFloaterAvatarList::getInstance()->getAvatarEntry(mClosestAgentToCursor);
				if ( NULL != ent )
				{
					//position = LLFloaterAvatarList::AvatarPosition(mClosestAgentToCursor);
					position = ent->getPosition();
				}
			}
			LLVector3d delta = position - mypos;
			F32 distance = (F32)delta.magVec();


			//llinfos << distance << " - " << position << llendl;

			msg.append( llformat("\n(Distance: %.02fm)\n\n",distance) );
		}
// [RLVa:KB] - Version: 1.23.4 | Checked: 2009-07-04 (RLVa-1.0.0a) | Modified: RLVa-0.2.0b
		msg.append( (!gRlvHandler.hasBehaviour(RLV_BHVR_SHOWLOC)) ? region->getName() : RlvStrings::getString(RLV_STRING_HIDDEN) );
// [/RLVa:KB]
		//msg.append( region->getName() );

//#ifndef LL_RELEASE_FOR_DOWNLOAD
		std::string buffer;
		msg.append("\n");
		buffer = region->getHost().getHostName();
		msg.append(buffer);
		msg.append("\n");
		buffer = region->getHost().getString();
		msg.append(buffer);
//#endif
		msg.append("\n");
		msg.append(getToolTip());

		S32 SLOP = 4;
		localPointToScreen( 
			x - SLOP, y - SLOP, 
			&(sticky_rect_screen->mLeft), &(sticky_rect_screen->mBottom) );
		sticky_rect_screen->mRight = sticky_rect_screen->mLeft + 2 * SLOP;
		sticky_rect_screen->mTop = sticky_rect_screen->mBottom + 2 * SLOP;
		handled = TRUE;
	}
	if(!handled)
	{
		return LLPanel::handleToolTip(x, y, msg, sticky_rect_screen);
	}
	return handled;
}
Пример #8
0
void ProviderTestBasic::EchoBinary(IDvInvocationStd& /*aInvocation*/, const std::string& aValue, std::string& aResult)
{
    aResult.assign(aValue);
}
Пример #9
0
int main(int argc,char *argv[])
{
	


	{
#ifdef MULTITHREAD_STDLOCALE_WORKAROUND
		// Note: there's a known threading bug regarding std::locale with MSVC according to
		// http://connect.microsoft.com/VisualStudio/feedback/details/492128/std-locale-constructor-modifies-global-locale-via-setlocale
		int iPreviousFlag = ::_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
#endif
		using std::locale;
		locale::global(locale(locale::classic(), "", locale::collate | locale::ctype));

#ifdef MULTITHREAD_STDLOCALE_WORKAROUND
		if (iPreviousFlag > 0 )
			::_configthreadlocale(iPreviousFlag);
#endif
	}

	TASPlayer::Init();

	SetThreadAffinityMask(GetCurrentThread(),1);

	//printf("%08x",opsize); //AGAIN?!

	char *t;

	initArchiveSystem();

	if(timeBeginPeriod(1) != TIMERR_NOERROR)
	{
		AddLogText("Error setting timer granularity to 1ms.", DO_ADD_NEWLINE);
	}

	InitCommonControls();
	debugSystem = new DebugSystem();

	if(!FCEUI_Initialize())
	{
		do_exit();
		return 1;
	}

	ApplyDefaultCommandMapping();

	fceu_hInstance = GetModuleHandle(0);
	fceu_hAccel = LoadAccelerators(fceu_hInstance,MAKEINTRESOURCE(IDR_ACCELERATOR1));

	// Get the base directory
	GetBaseDirectory();

	// load fceux.cfg
	sprintf(TempArray,"%s\\%s",BaseDirectory.c_str(),cfgFile.c_str());
	LoadConfig(TempArray);
	//initDirectories();

	// Parse the commandline arguments
	t = ParseArgies(argc, argv);

	int saved_pal_setting = !!pal_emulation;

	if (ConfigToLoad)
	{
		// alternative config file specified
		cfgFile.assign(ConfigToLoad);
		// Load the config information
		sprintf(TempArray,"%s\\%s",BaseDirectory.c_str(),cfgFile.c_str());
		LoadConfig(TempArray);
	}

	//Bleh, need to find a better place for this.
	{
        FCEUI_SetGameGenie(genie!=0);

        fullscreen = !!fullscreen;
        soundo = !!soundo;
        frame_display = !!frame_display;
        allowUDLR = !!allowUDLR;
        pauseAfterPlayback = !!pauseAfterPlayback;
        closeFinishedMovie = !!closeFinishedMovie;
        EnableBackgroundInput = !!EnableBackgroundInput;

		KeyboardSetBackgroundAccess(EnableBackgroundInput!=0);
		JoystickSetBackgroundAccess(EnableBackgroundInput!=0);

        FCEUI_SetSoundVolume(soundvolume);
		FCEUI_SetSoundQuality(soundquality);
		FCEUI_SetTriangleVolume(soundTrianglevol);
		FCEUI_SetSquare1Volume(soundSquare1vol);
		FCEUI_SetSquare2Volume(soundSquare2vol);
		FCEUI_SetNoiseVolume(soundNoisevol);
		FCEUI_SetPCMVolume(soundPCMvol);
	}

	//Since a game doesn't have to be loaded before the GUI can be used, make
	//sure the temporary input type variables are set.
	ParseGIInput(NULL);

	// Initialize default directories
	CreateDirs();
	SetDirs();

	DoVideoConfigFix();
	DoTimingConfigFix();

	if(eoptions & EO_CPALETTE)
	{
		FCEUI_SetPaletteArray(cpalette);
	}

	if(!t)
	{
		fullscreen=0;
	}

	CreateMainWindow();

	// Do single instance coding, since we now know if the user wants it,
	// and we have a source window to send from
	// http://wiki.github.com/ffi/ffi/windows-examples
	if (SingleInstanceOnly) {
		// Checks window names / hWnds, decides if there's going to be a conflict.
		EnumDesktopWindows(NULL, EnumCallbackFCEUXInstantiated, (LPARAM)0);

		if (DoInstantiatedExit) {

			if(t)
			{
				COPYDATASTRUCT cData;
				DATA tData;

				sprintf(tData.strFilePath,"%s",t);

				cData.dwData = 1;
				cData.cbData = sizeof ( tData );
				cData.lpData = &tData;

				SendMessage(DoInstantiatedExitWindow,WM_COPYDATA,(WPARAM)(HWND)hAppWnd, (LPARAM)(LPVOID) &cData);
				do_exit();
				return 0;
			}
		}
	}

	if(!InitDInput())
	{
		do_exit();
		return 1;
	}

	if(!DriverInitialize())
	{
		do_exit();
		return 1;
	}

	InitSpeedThrottle();

	if (t)
	{
		ALoad(t);
	} else
	{
		if (AutoResumePlay && romNameWhenClosingEmulator && romNameWhenClosingEmulator[0])
			ALoad(romNameWhenClosingEmulator, 0, true);
		if (eoptions & EO_FOAFTERSTART)
			LoadNewGamey(hAppWnd, 0);
	}

	if (pal_setting_specified)
	{
		// Force the PAL setting specified in the command line
        pal_emulation = saved_pal_setting;
        FCEUI_SetVidSystem(pal_emulation);
	}

	if(PaletteToLoad)
	{
		SetPalette(PaletteToLoad);
		free(PaletteToLoad);
		PaletteToLoad = NULL;
	}

	if(GameInfo && MovieToLoad)
	{
		//switch to readonly mode if the file is an archive
		if(FCEU_isFileInArchive(MovieToLoad))
				replayReadOnlySetting = true;

		FCEUI_LoadMovie(MovieToLoad, replayReadOnlySetting, replayStopFrameSetting != 0);
		FCEUX_LoadMovieExtras(MovieToLoad);
		free(MovieToLoad);
		MovieToLoad = NULL;
	}
	if(GameInfo && StateToLoad)
	{
		FCEUI_LoadState(StateToLoad);
		free(StateToLoad);
		StateToLoad = NULL;
	}
	if(GameInfo && LuaToLoad)
	{
		FCEU_LoadLuaCode(LuaToLoad);
		free(LuaToLoad);
		LuaToLoad = NULL;
	}

	//Initiates AVI capture mode, will set up proper settings, and close FCUEX once capturing is finished
	if(AVICapture && AviToLoad)	//Must be used in conjunction with AviToLoad
	{
		//We want to disable flags that will pause the emulator
		PauseAfterLoad = 0;
		pauseAfterPlayback = 0;
		KillFCEUXonFrame = AVICapture;
	}

	if(AviToLoad)
	{
		FCEUI_AviBegin(AviToLoad);
		free(AviToLoad);
		AviToLoad = NULL;
	}

	TASPlayer::Init_Loaded();

	if (MemWatchLoadOnStart) CreateMemWatch();
	if (PauseAfterLoad) FCEUI_ToggleEmulationPause();
	SetAutoFirePattern(AFon, AFoff);
	UpdateCheckedMenuItems();
doloopy:
	UpdateFCEUWindow();
	if(GameInfo)
	{
		while(GameInfo)
		{
	        uint8 *gfx=0; ///contains framebuffer
			int32 *sound=0; ///contains sound data buffer
			int32 ssize=0; ///contains sound samples count

			if (turbo)
			{
				if (!frameSkipCounter)
				{
					frameSkipCounter = frameSkipAmt;
					skippy = 0;
				}
				else
				{
					frameSkipCounter--;
					if (muteTurbo) skippy = 2;	//If mute turbo is on, we want to bypass sound too, so set it to 2
						else skippy = 1;				//Else set it to 1 to just frameskip
				}

			}
			else skippy = 0;

			TASPlayer::Run(&gfx, &sound, &ssize, skippy);
			//FCEUI_Emulate(&gfx, &sound, &ssize, skippy); //emulate a single frame -- THIS IS NOW HANDLED BY TASPLAYER
			//FCEUD_Update(gfx, sound, ssize); //update displays and debug tools -- THIS IS NOW HANDLED BY TASPLAYER

			//mbg 6/30/06 - close game if we were commanded to by calls nested in FCEUI_Emulate()
			if (closeGame)
			{
				FCEUI_CloseGame();
				GameInfo = NULL;
			}

		}
		//xbsave = NULL;
		RedrawWindow(hAppWnd,0,0,RDW_ERASE|RDW_INVALIDATE);
	}
  else
    UpdateRawInputAndHotkeys();
	if(!TASPlayer::SimulMode) {
		Sleep(50);
	}

	if(!exiting)
		goto doloopy;

	DriverKill();
	timeEndPeriod(1);
	FCEUI_Kill();

	delete debugSystem;

	return(0);
}
Пример #10
0
 void
 prepare_string(
     const char* input,
     size_t      size) {
   _prepare.assign(input, size);
 }
Пример #11
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPTSTR lpstrCmdLine, int nCmdShow) {
    g_hInstance = hInstance;
    json_value* appSettings = GetApplicationSettings();
    if (GetApplicationSettingsError().length()) {
        std::string error = GetApplicationSettingsError();
        error.append("\nApplication will terminate immediately. ");
        FatalError(NULL, error);
    }

    // Debugging options.
    bool show_console = (*appSettings)["debugging"]["show_console"];
    bool subprocess_show_console = (*appSettings)["debugging"]["subprocess_show_console"];
    std::string log_level = (*appSettings)["debugging"]["log_level"];
    std::string log_file = (*appSettings)["debugging"]["log_file"];
    log_file = GetAbsolutePath(log_file);
    
    // Initialize logging.
    if (std::wstring(lpstrCmdLine).find(L"--type=") != std::string::npos) {
        // This is a subprocess.
        InitializeLogging(subprocess_show_console, log_level, log_file);
    } else {
        // Main browser process.
        InitializeLogging(show_console, log_level, log_file);
    }

    // Command line arguments
    LPWSTR *argv;
    int argc;
    argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if (argv) {
        for (int i = 0; i < argc; i++) {
            std::string argument = WideToUtf8(std::wstring(argv[i]));
            size_t pos = argument.find("=");
            if (pos != std::string::npos) {
                std::string name = argument.substr(0, pos);
                std::string value = argument.substr(pos+1, std::string::npos);
                if (name == "--cgi-environment" && value.length()) {
                    g_cgiEnvironmentFromArgv.assign(value);
                }
            }
        }
    } else {
        LOG_WARNING << "CommandLineToArgvW() failed";
    }

    // CEF subprocesses.
    CefMainArgs main_args(hInstance);
    CefRefPtr<App> app(new App);
    int exit_code = CefExecuteProcess(main_args, app.get(), NULL);
    if (exit_code >= 0) {
        ShutdownLogging();
        return exit_code;
    }

    LOG_INFO << "--------------------------------------------------------";
    LOG_INFO << "Started application";

    if (log_file.length())
        LOG_INFO << "Logging to: " << log_file;
    else
        LOG_INFO << "No logging file set";
    LOG_INFO << "Log level = "
             << FILELog::ToString(FILELog::ReportingLevel());

    // Main window title option.
    std::string main_window_title = (*appSettings)["main_window"]["title"];
    if (main_window_title.empty())
        main_window_title = GetExecutableName();

    // Single instance guid option.
    const char* single_instance_guid =
            (*appSettings)["application"]["single_instance_guid"];
    if (single_instance_guid && single_instance_guid[0] != 0) {
        int guidSize = strlen(single_instance_guid) + 1;
        g_singleInstanceApplicationGuid = new wchar_t[guidSize];
        Utf8ToWide(single_instance_guid, g_singleInstanceApplicationGuid,
                   guidSize);
    }
    if (g_singleInstanceApplicationGuid
            && g_singleInstanceApplicationGuid[0] != 0) {
        g_singleInstanceApplication.Initialize(
                g_singleInstanceApplicationGuid);
	    if (g_singleInstanceApplication.IsRunning()) {
            HWND hwnd = FindWindow(g_singleInstanceApplicationGuid, NULL);
            if (hwnd) {
                if (IsIconic(hwnd))
                    ShowWindow(hwnd, SW_RESTORE);
                SetForegroundWindow(hwnd);
                return 0;
            }
        }
    }

    // Window class name.
    if (g_singleInstanceApplicationGuid) {
        swprintf_s(g_windowClassName, _countof(g_windowClassName), L"%s",
                   g_singleInstanceApplicationGuid);
    } else {
        swprintf_s(g_windowClassName, _countof(g_windowClassName), L"%s",
                   Utf8ToWide(GetExecutableName()).c_str());
    }

    if (!StartWebServer()) {
        FatalError(NULL, "Error while starting an internal local server.\n"
                   "Application will terminate immediately.");
    }

    CefSettings cef_settings;

    // log_file
    std::string chrome_log_file = (*appSettings)["chrome"]["log_file"];
    chrome_log_file = GetAbsolutePath(chrome_log_file);
    CefString(&cef_settings.log_file) = chrome_log_file;

    // log_severity
    std::string chrome_log_severity = (*appSettings)["chrome"]["log_severity"];
    cef_log_severity_t log_severity = LOGSEVERITY_DEFAULT;
    if (chrome_log_severity == "verbose") {
        log_severity = LOGSEVERITY_VERBOSE;
    } else if (chrome_log_severity == "info") {
        log_severity = LOGSEVERITY_INFO;
    } else if (chrome_log_severity == "warning") {
        log_severity = LOGSEVERITY_WARNING;
    } else if (chrome_log_severity == "error") {
        log_severity = LOGSEVERITY_ERROR;
    } else if (chrome_log_severity == "error-report") {
        log_severity = LOGSEVERITY_ERROR_REPORT;
    } else if (chrome_log_severity == "disable") {
        log_severity = LOGSEVERITY_DISABLE;
    }
    cef_settings.log_severity = log_severity;

    // cache_path
    std::string cache_path = (*appSettings)["chrome"]["cache_path"];
    cache_path = GetAbsolutePath(cache_path);
    CefString(&cef_settings.cache_path) = cache_path;

    // remote_debugging_port
    // A value of -1 will disable remote debugging.
    int remote_debugging_port = static_cast<long>(
            (*appSettings)["chrome"]["remote_debugging_port"]);
    if (remote_debugging_port == 0) {
        remote_debugging_port = random(49152, 65535+1);
        int i = 100;
        while (((i--) > 0) && remote_debugging_port == GetWebServerPort()) {
            remote_debugging_port = random(49152, 65535+1);
        }
    }
    if (remote_debugging_port > 0) {
        LOG_INFO << "remote_debugging_port = " << remote_debugging_port;
        cef_settings.remote_debugging_port = remote_debugging_port;
    }

    // Sandbox support
    cef_settings.no_sandbox = true;

    CefInitialize(main_args, cef_settings, app.get(), NULL);
    CreateMainWindow(hInstance, nCmdShow, main_window_title);
    CefRunMessageLoop();
    CefShutdown();

    LOG_INFO << "Ended application";
    LOG_INFO << "--------------------------------------------------------";

    ShutdownLogging();

    return 0;
}
//--------------------------------------------------------------------------
/// Write a trace's metadata file and return the contenst through the out-param.
/// \param inFullResponseString The full response string for a collected linked trace request.
/// \param outMetadataXML The XML metadata string to return to the client.
/// \returns True if writing the metadata file was successful.
//--------------------------------------------------------------------------
bool MultithreadedTraceAnalyzerLayer::WriteTraceAndMetadataFiles(const std::stringstream& inFullResponseString, std::string& outMetadataXML)
{
    bool bWrittenSuccessfully = false;

    // Empty out the incoming path to the metadata file. We'll know the exact path later.
    outMetadataXML.assign("");

    osModuleArchitecture moduleArchitecture;
    osRuntimePlatform currentPlatform;
    gtString executablePath;
    gtString commandLine;
    gtString workingDirectory;

    // Retrieve the name of the instrumented application. Construct a metadata filename which references it.
    if (osGetProcessLaunchInfo(osGetCurrentProcessId(), moduleArchitecture, currentPlatform, executablePath, commandLine, workingDirectory) == true)
    {
        osFilePath executableFilepath;
        executableFilepath.setFullPathFromString(executablePath);

        gtString appName;
        if (executableFilepath.getFileName(appName) == true)
        {
            osTime currentTime;
            currentTime.setFromCurrentTime();
            tm timeStruct;
            currentTime.timeAsTmStruct(timeStruct, osTime::LOCAL);

            // Need to add 1900, since tm contains "years since 1900".
            int year = timeStruct.tm_year + 1900;

            // Need to add 1, since tm contains "months since January".
            int month = timeStruct.tm_mon + 1;
            int day = timeStruct.tm_mday;

            int hour = timeStruct.tm_hour;
            int minute = timeStruct.tm_min;
            int second = timeStruct.tm_sec;

            gtASCIIString metadataFilename;

            // ExecutableFilename-YEAR-MM-DD-HOUR-MINUTE-SECOND
            metadataFilename.appendFormattedString("description-%s-%d-%d-%d-%d-%d-%d.xml",
                appName.asASCIICharArray(),
                year, month, day,
                hour, minute, second);

            // Build a path to the GPS folder within the Temp directory.
            osFilePath systemTempDirectory;
            systemTempDirectory.setPath(osFilePath::OS_TEMP_DIRECTORY);


            gtString toolDirectory;
#ifdef CODEXL_GRAPHICS
            toolDirectory.fromASCIIString("CodeXL");
#else
            toolDirectory.fromASCIIString(GetPerfStudioDirName());
#endif
            // @TODO: Construct a path from the temp + tool directory.
            systemTempDirectory.appendSubDirectory(toolDirectory);

            gtList<osFilePath> toolDirectoryPaths;
            osDirectory d;
            d.setDirectoryPath(systemTempDirectory);

            // @TODO: Find a better way to create the "Session" directory. We shouldn't need to search through existing session directories.
            int maxSessionIndex = 0;
            bool bGotSubDirectories = d.getSubDirectoriesPaths(osDirectory::SORT_BY_NAME_DESCENDING, toolDirectoryPaths);
            if (bGotSubDirectories)
            {
                // Step through each directory, and look for "Session" folders.
                gtList<osFilePath>::iterator subdirectoryIter;
                for (subdirectoryIter = toolDirectoryPaths.begin(); subdirectoryIter != toolDirectoryPaths.end(); ++subdirectoryIter)
                {
                    gtString subdirString;
                    osFilePath subdir = *subdirectoryIter;
                    subdir.getFileName(subdirString);

                    if (subdir.isDirectory() && subdirString.startsWith(L"Session"))
                    {
                        // Remove the "Session" part of the string. We're only interested in the number at the end.
                        subdirString.replace(L"Session", L"", true);

                        const char* sessionIndexAsString = subdirString.asASCIICharArray();
                        int thisSessionId = atoi(sessionIndexAsString);

                        if (thisSessionId > maxSessionIndex)
                        {
                            maxSessionIndex = thisSessionId;
                        }
                    }

                }
            }


            gtASCIIString pathToDataDirectory = systemTempDirectory.asString().asASCIICharArray();

            // Metadata files will be saved to the temp directory with the following filename scheme:
            // "%TEMP%/ToolDirectory/Session[Index]/ApplicationBinaryName/Frame[Index]/description.xml"

            int frameIndex = GetInterceptor()->GetParentLayerManager()->GetFrameCount();

            // Generate a "Session" folder with a number at the end. Compute the correct number by looking at the
            // Session folders that already exist
            gtASCIIString sessionString;
            sessionString.appendFormattedString("Session%d", maxSessionIndex + 1);

            pathToDataDirectory.appendFormattedString("\\%s\\%s\\Frame%d\\", sessionString.asCharArray(), appName.asASCIICharArray(), frameIndex);

            // Create the data directory if it doesn't already exist.
            gtString fullPathToDataDirectoryAsGTString;
            fullPathToDataDirectoryAsGTString.fromASCIIString(pathToDataDirectory.asCharArray());

            osDirectory dir;
            dir.setDirectoryFullPathFromString(fullPathToDataDirectoryAsGTString);
            if (!dir.exists())
            {
                bool bDirectoryCreated = dir.create();
                if (!bDirectoryCreated)
                {
                    Log(logERROR, "Failed to create data directory for traced frame: '%s'.\n", fullPathToDataDirectoryAsGTString.asASCIICharArray());
                }
            }

            gtASCIIString pathToMetadataFile = pathToDataDirectory;
            pathToMetadataFile.appendFormattedString("%s", metadataFilename.asCharArray());

            gtString fullMetadataFilepathAsGTString;
            fullMetadataFilepathAsGTString.fromASCIIString(pathToMetadataFile.asCharArray());

            osFile metadataFile(fullMetadataFilepathAsGTString);
            bool bMetadataFileOpened = metadataFile.open(osChannel::OS_ASCII_TEXT_CHANNEL, osFile::OS_OPEN_TO_WRITE);

            // If we've successfully opened the metadata file, we'll also attempt to write the trace file.
            if (bMetadataFileOpened)
            {
                osFilePath traceFileDirectory;
                traceFileDirectory.setPath(osFilePath::OS_TEMP_DIRECTORY);

                traceFileDirectory.appendSubDirectory(toolDirectory);

                // Construct a filename for the cached trace response.
                gtASCIIString fullTraceFilename;
                fullTraceFilename.appendFormattedString("LinkedTrace-%s-%d-%d-%d-%d-%d-%d.ltr", appName.asASCIICharArray(), year, month, day, hour, minute, second);

                gtASCIIString fullTraceFilePath = pathToDataDirectory;
                fullTraceFilePath.appendFormattedString("%s", fullTraceFilename.asCharArray());

                gtString fullTraceResponseFilepathGTString;
                fullTraceResponseFilepathGTString.fromASCIIString(fullTraceFilePath.asCharArray());

                // Write the contents of the trace response file.
                osFile traceResponseFile(fullTraceResponseFilepathGTString);
                bool bTraceResponseFileOpened = traceResponseFile.open(osChannel::OS_ASCII_TEXT_CHANNEL, osFile::OS_OPEN_TO_WRITE);
                if (bTraceResponseFileOpened)
                {
                    // Dump the response into an ASCII string.
                    std::string responseAsString = inFullResponseString.str();

                    // Now put the ASCII string into a gtString so we can write it to the open file.
                    gtString gtStringResponse;
                    std::wstring wideString;
                    wideString.assign(responseAsString.begin(), responseAsString.end());
                    gtStringResponse.appendFormattedString(L"%s", wideString.c_str());
                    traceResponseFile.writeString(gtStringResponse);
                    traceResponseFile.close();
                }
                else
                {
                    Log(logERROR, "Failed to write trace response to file: '%s'\n", fullTraceResponseFilepathGTString.asASCIICharArray());
                }

                // Write the filename for the associated trace response that was just collected.
                std::string traceFilepathAsString;
                traceFilepathAsString.assign(fullTraceResponseFilepathGTString.asASCIICharArray());

                TraceMetadata metadata;

                // Insert the location of the metadata file being written out.
                metadata.mMetadataFilepath = pathToMetadataFile.asCharArray();

                // Insert the path to the cached trace file.
                metadata.mPathToTraceFile = fullTraceFilePath.asCharArray();

                // @TODO: When we have a framebuffer image system working, assign the path-to-image here.
                metadata.mPathToFrameBufferImage = "UNKNOWNPATH";

                ModernAPILayerManager* layerManager = GetInterceptor()->GetParentLayerManager();

                FrameInfo frameInfo;

                layerManager->GetFrameInfo(frameInfo);

                // Populate the metadata structure with the values stored in the LayerManager.
                metadata.mFrameInfo = frameInfo;
                metadata.mFrameIndex = frameIndex;
                metadata.mArchitecture = moduleArchitecture;

                // Write the metadata xml into the output file.
                gtASCIIString metadataXMLString;
                metadata.WriteToXML(metadataXMLString);
                gtString metadataXMLAsGTString;
                metadataXMLAsGTString.fromASCIIString(metadataXMLString.asCharArray());

                // Write the metadata XML into the file, and close.
                metadataFile.writeString(metadataXMLAsGTString);
                metadataFile.close();

                // The client will receive the full metadata XML string to parse.
                outMetadataXML.assign(metadataXMLString.asCharArray());

                bWrittenSuccessfully = true;
            }
            else
            {
                Log(logERROR, "Failed to open trace metadata file for writing: '%s'\n", metadataFilename);
            }
        }
        else
        {
            Log(logERROR, "Failed to retrieve the instrumented process's application filename.\n");
        }
    }
    else
    {
        Log(logERROR, "Failed to retrieve process launch info for target application.\n");
    }

    return bWrittenSuccessfully;
}
Пример #13
0
/*++
* @method: oAuth::getSignature
*
* @description: this method calculates HMAC-SHA1 signature of OAuth header
*
* @input: eType - HTTP request type
*         rawUrl - raw url of the HTTP request
*         rawKeyValuePairs - key-value pairs containing OAuth headers and HTTP data
*
* @output: oAuthSignature - base64 and url encoded signature
*
* @remarks: internal method
*
*--*/
bool oAuth::getSignature( const eOAuthHttpRequestType eType,
                          const std::string& rawUrl,
                          const oAuthKeyValuePairs& rawKeyValuePairs,
                          std::string& oAuthSignature )
{
    std::string rawParams;
    std::string paramsSeperator;
    std::string sigBase;

    /* Initially empty signature */
    oAuthSignature.assign( "" );

    /* Build a string using key-value pairs */
    paramsSeperator = "&";
    getStringFromOAuthKeyValuePairs( rawKeyValuePairs, rawParams, paramsSeperator );

    /* Start constructing base signature string. Refer http://dev.twitter.com/auth#intro */
    switch( eType )
    {
    case eOAuthHttpGet:
        {
            sigBase.assign( "GET&" );
        }
        break;

    case eOAuthHttpPost:
        {
            sigBase.assign( "POST&" );
        }
        break;

    case eOAuthHttpDelete:
        {
            sigBase.assign( "DELETE&" );
        }
        break;

    default:
        {
            return false;
        }
        break;
    }
    sigBase.append( urlencode( rawUrl ) );
    sigBase.append( "&" );
    sigBase.append( urlencode( rawParams ) );

    /* Now, hash the signature base string using HMAC_SHA1 class */
    CHMAC_SHA1 objHMACSHA1;
    std::string secretSigningKey;
    unsigned char strDigest[oAuthLibDefaults::OAUTHLIB_BUFFSIZE_LARGE];

    memset( strDigest, 0, oAuthLibDefaults::OAUTHLIB_BUFFSIZE_LARGE );

    /* Signing key is composed of consumer_secret&token_secret */
    secretSigningKey.assign( m_consumerSecret );
    secretSigningKey.append( "&" );
    if( m_oAuthTokenSecret.length() )
    {
        secretSigningKey.append( m_oAuthTokenSecret );
    }
  
    objHMACSHA1.HMAC_SHA1( (unsigned char*)sigBase.c_str(),
                           sigBase.length(),
                           (unsigned char*)secretSigningKey.c_str(),
                           secretSigningKey.length(),
                           strDigest ); 

    /* Do a base64 encode of signature */
    std::string base64Str = base64_encode( strDigest, 20 /* SHA 1 digest is 160 bits */ );

    /* Do an url encode */
    oAuthSignature = urlencode( base64Str );

    return ( oAuthSignature.length() ) ? true : false;
}
Пример #14
0
bool CScraperUrl::Get(const SUrlEntry& scrURL, std::string& strHTML, XFILE::CCurlFile& http, const CStdString& cacheContext)
{
  CURL url(scrURL.m_url);
  http.SetReferer(scrURL.m_spoof);
  CStdString strCachePath;

  if (scrURL.m_isgz)
    http.SetContentEncoding("gzip");

  if (!scrURL.m_cache.empty())
  {
    strCachePath = URIUtils::AddFileToFolder(g_advancedSettings.m_cachePath,
                              "scrapers/" + cacheContext + "/" + scrURL.m_cache);
    if (XFILE::CFile::Exists(strCachePath))
    {
      XFILE::CFile file;
      XFILE::auto_buffer buffer;
      if (file.LoadFile(strCachePath, buffer))
      {
        strHTML.assign(buffer.get(), buffer.length());
        return true;
      }
    }
  }

  CStdString strHTML1(strHTML);

  if (scrURL.m_post)
  {
    CStdString strOptions = url.GetOptions();
    strOptions = strOptions.substr(1);
    url.SetOptions("");

    if (!http.Post(url.Get(), strOptions, strHTML1))
      return false;
  }
  else
    if (!http.Get(url.Get(), strHTML1))
      return false;

  strHTML = strHTML1;

  std::string mimeType(http.GetMimeType());
  CMime::EFileType ftype = CMime::GetFileTypeFromMime(mimeType);
  if (ftype == CMime::FileTypeUnknown)
    ftype = CMime::GetFileTypeFromContent(strHTML);

  if (ftype == CMime::FileTypeZip || ftype == CMime::FileTypeGZip)
  {
    XFILE::CZipFile file;
    std::string strBuffer;
    int iSize = file.UnpackFromMemory(strBuffer,strHTML,scrURL.m_isgz); // FIXME: use FileTypeGZip instead of scrURL.m_isgz?
    if (iSize > 0)
    {
      strHTML = strBuffer;
      CLog::Log(LOGDEBUG, "%s: Archive \"%s\" was unpacked in memory", __FUNCTION__, scrURL.m_url.c_str());
    }
    else
      CLog::Log(LOGWARNING, "%s: \"%s\" looks like archive, but cannot be unpacked", __FUNCTION__, scrURL.m_url.c_str());
  }

  std::string reportedCharset(http.GetServerReportedCharset());
  if (ftype == CMime::FileTypeHtml)
  {
    std::string realHtmlCharset, converted;
    if (!CCharsetDetection::ConvertHtmlToUtf8(strHTML, converted, reportedCharset, realHtmlCharset))
      CLog::Log(LOGWARNING, "%s: Can't find precise charset for HTML \"%s\", using \"%s\" as fallback", __FUNCTION__, scrURL.m_url.c_str(), realHtmlCharset.c_str());
    else
      CLog::Log(LOGDEBUG, "%s: Using \"%s\" charset for HTML \"%s\"", __FUNCTION__, realHtmlCharset.c_str(), scrURL.m_url.c_str());

    strHTML = converted;
  }
  else if (ftype == CMime::FileTypeXml)
  {
    CXBMCTinyXML xmlDoc;
    xmlDoc.Parse(strHTML, reportedCharset);
    
    std::string realXmlCharset(xmlDoc.GetUsedCharset());
    if (!realXmlCharset.empty())
    {
      CLog::Log(LOGDEBUG, "%s: Using \"%s\" charset for XML \"%s\"", __FUNCTION__, realXmlCharset.c_str(), scrURL.m_url.c_str());
      std::string converted;
      g_charsetConverter.ToUtf8(realXmlCharset, strHTML, converted);
      strHTML = converted;
    }
  }
  else if (ftype == CMime::FileTypePlainText || StringUtils::CompareNoCase(mimeType.substr(0, 5), "text/") == 0)
  {
    std::string realTextCharset, converted;
    CCharsetDetection::ConvertPlainTextToUtf8(strHTML, converted, reportedCharset, realTextCharset);
    strHTML = converted;
    if (reportedCharset != realTextCharset)
      CLog::Log(LOGWARNING, "%s: Using \"%s\" charset for plain text \"%s\" instead of server reported \"%s\" charset", __FUNCTION__, realTextCharset.c_str(), scrURL.m_url.c_str(), reportedCharset.c_str());
    else
      CLog::Log(LOGDEBUG, "%s: Using \"%s\" charset for plain text \"%s\"", __FUNCTION__, realTextCharset.c_str(), scrURL.m_url.c_str());
  }
  else if (!reportedCharset.empty())
  {
    CLog::Log(LOGDEBUG, "%s: Using \"%s\" charset for \"%s\"", __FUNCTION__, reportedCharset.c_str(), scrURL.m_url.c_str());
    if (reportedCharset != "UTF-8")
    {
      std::string converted;
      g_charsetConverter.ToUtf8(reportedCharset, strHTML, converted);
      strHTML = converted;
    }
  }
  else
    CLog::Log(LOGDEBUG, "%s: Using content of \"%s\" as binary or text with \"UTF-8\" charset", __FUNCTION__, scrURL.m_url.c_str());

  if (!scrURL.m_cache.empty())
  {
    CStdString strCachePath = URIUtils::AddFileToFolder(g_advancedSettings.m_cachePath,
                              "scrapers/" + cacheContext + "/" + scrURL.m_cache);
    XFILE::CFile file;
    if (file.OpenForWrite(strCachePath,true))
      file.Write(strHTML.data(),strHTML.size());
    file.Close();
  }
  return true;
}
Пример #15
0
// virtual
BOOL LLViewerTextEditor::handleDragAndDrop(S32 x, S32 y, MASK mask,
					  BOOL drop, EDragAndDropType cargo_type, void *cargo_data,
					  EAcceptance *accept,
					  std::string& tooltip_msg)
{
	BOOL handled = FALSE;
	
	LLToolDragAndDrop::ESource source = LLToolDragAndDrop::getInstance()->getSource();
	if (LLToolDragAndDrop::SOURCE_NOTECARD == source)
	{
		// We currently do not handle dragging items from one notecard to another
		// since items in a notecard must be in Inventory to be verified. See DEV-2891.
		return FALSE;
	}
	
	if (getEnabled() && acceptsTextInput())
	{
		switch( cargo_type )
		{
			case DAD_CALLINGCARD:
			case DAD_TEXTURE:
			case DAD_SOUND:
			case DAD_LANDMARK:
			case DAD_SCRIPT:
			case DAD_CLOTHING:
			case DAD_OBJECT:
			case DAD_NOTECARD:
			case DAD_BODYPART:
			case DAD_ANIMATION:
			case DAD_GESTURE:
			case DAD_MESH:
			{
				LLInventoryItem *item = (LLInventoryItem *)cargo_data;
				if( item && allowsEmbeddedItems() )
				{
					U32 mask_next = item->getPermissions().getMaskNextOwner();
					if((mask_next & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED)
					{
						if( drop )
						{
							deselect();
							S32 old_cursor = mCursorPos;
							setCursorAtLocalPos( x, y, TRUE );
							S32 insert_pos = mCursorPos;
							setCursorPos(old_cursor);
							BOOL inserted = insertEmbeddedItem( insert_pos, item );
							if( inserted && (old_cursor > mCursorPos) )
							{
								setCursorPos(mCursorPos + 1);
							}

							needsReflow();
							
						}
						*accept = ACCEPT_YES_COPY_MULTI;
					}
					else
					{
						*accept = ACCEPT_NO;
						if (tooltip_msg.empty())
						{
							// *TODO: Translate
							tooltip_msg.assign("Only items with unrestricted\n"
												"'next owner' permissions \n"
												"can be attached to notecards.");
						}
					}
				}
				else
				{
					*accept = ACCEPT_NO;
				}
				break;
			}

		default:
			*accept = ACCEPT_NO;
			break;
		}
	}
	else
	{
		// Not enabled
		*accept = ACCEPT_NO;
	}

	handled = TRUE;
	LL_DEBUGS("UserInput") << "dragAndDrop handled by LLViewerTextEditor " << getName() << LL_ENDL;

	return handled;
}
Пример #16
0
 void ValueImpl::getString(std::string& ret) const
 {
   if (null)
     throw NullValue();
   ret.assign(data);
 }
Пример #17
0
static bool find_include_file(std::string &srcincpath, int srcrootlen, int dstrootlen, std::string &srcfile, std::string &dstfile, std::string &filename)
{
	// iterate over include paths and find the file
	for (include_path *curpath = incpaths; curpath != nullptr; curpath = curpath->next)
	{
		// a '.' include path is specially treated
		if (curpath->path.compare(".") == 0)
			srcincpath.assign(srcfile.substr(0, srcfile.find_last_of(PATH_SEPARATOR[0])));
		else
			srcincpath.assign(srcfile.substr(0, srcrootlen + 1)).append(curpath->path);

		// append the filename piecemeal to account for directories
		int lastsepindex = 0;
		int sepindex;
		while ((sepindex = filename.find_first_of('/', lastsepindex)) != -1)
		{
			// handle .. by removing a chunk from the incpath
			std::string pathpart(filename, lastsepindex, sepindex - lastsepindex);
			if (pathpart.compare("..")==0)
			{
				sepindex = srcincpath.find_last_of(PATH_SEPARATOR[0]);
				if (sepindex != -1)
					srcincpath.substr(0, sepindex);
			}

			// otherwise, append a path separator and the pathpart
			else
				srcincpath.append(PATH_SEPARATOR).append(pathpart);

			// advance past the previous index
			lastsepindex = sepindex + 1;
		}

		// now append the filename
		srcincpath.append(PATH_SEPARATOR).append(filename.substr(lastsepindex, -1));

		// see if we can open it
		util::core_file::ptr testfile;
		if (util::core_file::open(srcincpath, OPEN_FLAG_READ, testfile) == osd_file::error::NONE)
		{
			// close the file
			testfile.reset();

			// find the longest matching directory substring between the include and source file
			lastsepindex = 0;
			while ((sepindex = srcincpath.find_first_of(PATH_SEPARATOR[0], lastsepindex)) != -1)
			{
				// get substrings up to the current directory
				std::string tempfile(srcfile, 0, sepindex);
				std::string tempinc(srcincpath, 0, sepindex);

				// if we don't match, stop
				if (tempfile.compare(tempinc)!=0)
					break;
				lastsepindex = sepindex + 1;
			}

			// chop off the common parts of the paths
			std::string tempfile(srcfile, lastsepindex, -1);
			srcincpath = srcincpath.substr(lastsepindex, -1);
			strreplacechr(srcincpath, PATH_SEPARATOR[0], '/');

			// for each directory left in the filename, we need to prepend a "../"
			while ((sepindex = tempfile.find_first_of(PATH_SEPARATOR[0])) != -1)
			{
				tempfile.substr(sepindex + 1, -1);
				srcincpath.insert(0, "../");
			}
			srcincpath.append(".html");

			// free the strings and return the include path
			return true;
		}
	}
	return false;
}
void DvProviderAvOpenhomeOrgExakt2Cpp::GetPropertyVersion(std::string& aValue)
{
    ASSERT(iPropertyVersion != NULL);
    const Brx& val = iPropertyVersion->Value();
    aValue.assign((const char*)val.Ptr(), val.Bytes());
}
int main(int argc, char **argv)
{
    bool try_flip = false;
    std::string scale_param = "--scale=";
    size_t scale_param_length = scale_param.length();
    std::string cascade_param = "--cascade=";
    size_t cascade_param_length = cascade_param.length();
    std::string nested_cascade_param = "--nested-cascade=";
    size_t nested_cascade_param_length =  nested_cascade_param.length();
    std::string try_flip_param = "--try-flip=";
    size_t try_flip_param_length = try_flip_param.length();
    std::string name_input;
    double scale = 1.0;
    cv::Mat frame;
    cv::Mat frame_copy;
    cv::Mat image;
    cv::CascadeClassifier cascade;
    cv::CascadeClassifier nested_cascade;
    CvCapture *capture = 0;

    g_face_recognition.getUseHelp();

    // Load trained model.
    g_model = cv::createLBPHFaceRecognizer();
    g_model->load(g_save_model_path);

    std::cout << "*************************" << std::endl
              << "   Load model finished   " << std::endl
              << "*************************" << std::endl
              << std::endl;

    // Load command line parameters.
    for (int i = 1; i < argc; i++) {
        std::cout << "Processing " << i << " " << argv[i] << std::endl;
        if (cascade_param.compare(0,
                                  cascade_param_length,
                                  argv[i],
                                  cascade_param_length) == 0) {
            g_name_cascade.assign(argv[i] + cascade_param_length);
            std::cout << "Cascade name: " << g_name_cascade
                      << std::endl;
        }
        else if (nested_cascade_param.compare(0,
                                              nested_cascade_param_length,
                                              argv[i],
                                              nested_cascade_param_length) == 0) {
            if (argv[i][nested_cascade_param.length()] == '=') {
               g_name_nested_cascade.assign(argv[i] +
                                            nested_cascade_param.length() + 1);
            }
            if (!nested_cascade.load(g_name_nested_cascade)) {
                std::cerr << "Load nested cascade classifier failed!"
                          << std::endl;
            }
        }
        else if (scale_param.compare(0,
                                     scale_param_length,
                                     argv[i],
                                     scale_param_length) == 0) {
            if(!sscanf(argv[i] + scale_param.length(), "%lf", &scale) ||
                scale < 1) {
                scale = 1;
            }
            std::cout << "Scale: " << scale << std::endl;
        }
        else if (try_flip_param.compare(0,
                                        try_flip_param_length,
                                        argv[i],
                                        try_flip_param_length) == 0) {
            try_flip = true;
            std::cout << " Try to flip image horizontally."
                      << std::endl;
        }
        else if (argv[i][0] == '-') {
            std::cerr << "Unknown option %s" << argv[i] << std::endl;
        }
        else {
            name_input.assign(argv[i]);
        }
    }

    if (!cascade.load(g_name_cascade)) {
        std::cerr << "Load cascade classifier failed!" << std::endl;
        g_face_recognition.getUseHelp();
        return -1;
    }

    if (name_input.empty() || (isdigit(name_input.c_str()[0]) &&
        name_input.c_str()[1]) == '\0') {
        capture = cvCaptureFromCAM(name_input.empty() ? 0 :
                                   name_input.c_str()[0] - '0');
        int camera = name_input.empty() ? 0 : name_input.c_str()[0] - '0';
        if (!capture) {
            std::cerr << "Capture from CAM " << camera << "doesn't work!"
                      << std::endl;
        }
    }
    else if (name_input.size()) {
        image = cv::imread(name_input, 1);
        if (image.empty()) {
            capture = cvCaptureFromAVI(name_input.c_str());
            if (!capture) {
                std::cerr << "Capture from AVI doesn't work!" << std::endl;
            }
        }
    }
    else {
        image = cv::imread("lena.jpg", 1);
        if (image.empty()) {
            std::cerr << "Read lena.jpg failed!" << std::endl;
        }
    }

    cvNamedWindow("Face Recognition", 1);

    if (capture) {
        std::cout << "In capture..." << std::endl;
        for (;;) {
            IplImage *ipl_image = cvQueryFrame(capture);
            frame = ipl_image;
            while (frame.dims == 0) {
                ipl_image = cvQueryFrame(capture);
                frame = ipl_image;
            }
            if (frame.empty()) {
                break;
            }
            if (ipl_image->origin == IPL_ORIGIN_TL) {
                frame.copyTo(frame_copy);
            }
            else {
                cv::flip(frame, frame_copy, 0);
            }

            g_face_recognition.detectAndDraw(frame_copy,
                                             cascade,
                                             nested_cascade,
                                             scale,
                                             try_flip);

            // Press any keys to close the camera and exit.
            if (cv::waitKey(10) > 0) {
                goto cleanup;
            }
        }
        cv::waitKey(0);
cleanup:
        cvReleaseCapture(&capture);
    }
    else {
        std::cout << "In image read..." << std::endl;
        if (!image.empty()) {
            g_face_recognition.detectAndDraw(image,
                                             cascade,
                                             nested_cascade,
                                             scale,
                                             try_flip);
            cv::waitKey(0);
        }
        else if (!name_input.empty()) {
            FILE *file = fopen(name_input.c_str(), "rt");
            if (file) {
                char buffer[1000 + 1];
                while (fgets(buffer, 1000, file)) {
                    int length = (int)strlen(buffer);
                    int key = 0;
                    while (length > 0 && isspace(buffer[length - 1])) {
                        length--;
                    }
                    buffer[length] = '\0';
                    std::cout << "File " << buffer << std::endl;
                    image = cv::imread(buffer, 1);
                    if (!image.empty()) {
                        g_face_recognition.detectAndDraw(image,
                                                         cascade,
                                                         nested_cascade,
                                                         scale,
                                                         try_flip);
                        key = cv::waitKey(0);
                        if (key == 27 || key == 'q' || key == 'Q') {
                            break;
                        }
                    }
                    else {
                        std::cerr << "Read image failed!" << std::endl;
                    }
                }
                fclose(file);
            }
        }
    }
    cvDestroyWindow("Face Detection");
    return 0;
}
Пример #20
0
 void unpack_string(std::string& str) {
   str.assign(reinterpret_cast<char *>(data()), size());
 }
Пример #21
0
//    - read (and dequeue) all available data
//    returns false when nothing is present
bool serialPoll_t :: read( std::string &s )
{
   s.assign( inData_, inLength_ );
   inLength_ = 0 ;
   return ( 0 != s.size() );
}
Пример #22
0
/*++
* \fn OAuth::getSignature
*
* \brief this method calculates HMAC-SHA1 signature of OAuth header
*
* \param eType - HTTP request type
*         rawUrl - raw url of the HTTP request
*         rawKeyValuePairs - key-value pairs containing OAuth headers and HTTP data
*
* \return oAuthSignature - base64 and url encoded signature
*
* @remarks: internal method
*
*--*/
bool OAuth::getSignature( const e_HTTP_request_type method,
                          const std::string& rawUrl,
                          const std::map<std::string, std::string>& rawKeyValuePairs,
                          std::string& oAuthSignature ) {

    std::string rawParams;
    std::string paramsSeperator;
    std::string sigBase;

    /* Initially empty signature */
    oAuthSignature.assign( "" );

    /* Build a string using key-value pairs */
    paramsSeperator = "&";
    getStringFromOAuthKeyValuePairs( rawKeyValuePairs, rawParams, paramsSeperator );

    /* Start constructing base signature string. Refer http://dev.twitter.com/auth#intro */
    switch( method ) {

        case GET:
            sigBase.assign( "GET&" );
            break;

        case POST:
            sigBase.assign( "POST&" );
            break;

        case DELETE:
            sigBase.assign( "DELETE&" );
            break;

        default:
            return false;
            break;

    }

    sigBase.append( urlencode( rawUrl ) );
    sigBase.append( "&" );
    sigBase.append( urlencode( rawParams ) );

    /* Now, hash the signature base string using HMAC_SHA1 class */
    CHMAC_SHA1 objHMACSHA1;
    std::string secretSigningKey;
    unsigned char strDigest[OAuthConsts::BUFFSIZE_LARGE];

    memset( strDigest, 0, OAuthConsts::BUFFSIZE_LARGE );

    /* Signing key is composed of consumer_secret&token_secret */
    secretSigningKey.assign( _consumer_secret );
    secretSigningKey.append( "&" );

    if( _token_secret.length() ) {
        secretSigningKey.append( _token_secret );
    }
  
    objHMACSHA1.HMAC_SHA1( (unsigned char*)sigBase.c_str(),
                           sigBase.length(),
                           (unsigned char*)secretSigningKey.c_str(),
                           secretSigningKey.length(),
                           strDigest ); 

    /* Do a base64 encode of signature */
    std::string base64Str = base64_encode( strDigest, 20 /* SHA 1 digest is 160 bits */ );

    /* Do an url encode */
    oAuthSignature = urlencode( base64Str );

    return ( oAuthSignature.length() ) ? true : false;
}
Пример #23
0
  uint32_t Reader::ReadRecord(string &record, std::string &scratch, uint32_t &blockid) {
    if (!SkipToInitialBlock()) {
        return 0;
    }
    initial_offset_ = 0;
    scratch.clear();
    record.clear();
    bool in_fragmented_record = false;
    // Record offset of the logical record that we're reading
    // 0 is a dummy value to make compilers happy
    uint64_t prospective_record_offset = 0;

    string fragment;
    fragment.clear();
    while (true) {
  	uint64_t physical_record_offset = end_of_buffer_offset_ - buffer_.size();
  	uint32_t id;
      const unsigned int record_type = ReadPhysicalRecord(fragment, id, blockid);
      //cout << "record_type: " << record_type << endl;
      switch (record_type) {
        case kFullType:
          if (in_fragmented_record) {
            // Handle bug in earlier versions of log::Writer where
            // it could emit an empty kFirstType record at the tail end
            // of a block followed by a kFullType or kFirstType record
            // at the beginning of the next block.
            if (scratch.empty()) {
              in_fragmented_record = false;
            } else {
              ReportCorruption(scratch.size(), "partial record without end(1)");
            }
          }
          prospective_record_offset = physical_record_offset;
          scratch.clear();
          record = fragment;
          last_record_offset_ = prospective_record_offset;
          last_record_end_offset_ = kBlockSize - buffer_.size();
  		if(read_block_num_ != -1) {
  			real_read_block_num_ = read_block_num_;
  		}
  		//Version::Instance()->SetBlockInterId();
          //cout << "kFullType: " << last_record_end_offset_ << endl;
          return id;

        case kFirstType:
          if (in_fragmented_record) {
            // Handle bug in earlier versions of log::Writer where
            // it could emit an empty kFirstType record at the tail end
            // of a block followed by a kFullType or kFirstType record
            // at the beginning of the next block.
            if (scratch.empty()) {
              in_fragmented_record = false;
            } else {
              ReportCorruption(scratch.size(), "partial record without end(2)");
            }
          }
          prospective_record_offset = physical_record_offset;
          scratch.assign(fragment.data(), fragment.size());
          in_fragmented_record = true;
          break;

        case kMiddleType:
          if (!in_fragmented_record) {
            ReportCorruption(fragment.size(),
                             "missing start of fragmented record(1)");
          } else {
            scratch.append(fragment.data(), fragment.size());
          }
          break;

        case kLastType:
          if (!in_fragmented_record) {
            ReportCorruption(fragment.size(),
                             "missing start of fragmented record(2)");
          } else {
            scratch.append(fragment.data(), fragment.size());
            record = scratch;
            last_record_offset_ = prospective_record_offset;
            last_record_end_offset_ = kBlockSize - buffer_.size();
  		  if(read_block_num_ != -1) {
  			real_read_block_num_ = read_block_num_;
  		  }
  		  //Version::Instance()->SetBlockInterId();	
            return id;
          }
          break;

        case kEof:
          if (in_fragmented_record) {
            ReportCorruption(scratch.size(), "partial record without end(3)");
            scratch.clear();
          }
          return 0;

        case kBadRecord:
          if (in_fragmented_record) {
            ReportCorruption(scratch.size(), "error in middle of record");
            in_fragmented_record = false;
            scratch.clear();
          }
          break;

        default: {
          char buf[40];
          snprintf(buf, sizeof(buf), "unknown record type %u", record_type);
          ReportCorruption(
              (fragment.size() + (in_fragmented_record ? scratch.size() : 0)),
              buf);
          in_fragmented_record = false;
          scratch.clear();
          break;
        }
      }
    }
    return 0;
  }
Пример #24
0
    bool parseCommandLine(int argc, char **argv)
    {
        for (int i = 1; i < argc; ++i) {
            if (!std::strcmp(argv[i],"-ip") && i + 1 < argc)
                d_hosts.push_back(argv[++i]);
            else if (!std::strcmp(argv[i],"-p") && i + 1 < argc)
                d_port = std::atoi(argv[++i]);
            else if (!std::strcmp(argv[i],"-s") && i + 1 < argc)
                d_securities.push_back(argv[++i]);
            else if (!std::strcmp(argv[i],"-f") && i + 1 < argc)
                d_fields.push_back(argv[++i]);
            else if (!std::strcmp(argv[i],"-r") && i + 1 < argc) {
                ++ i;
                if (!std::strcmp(argv[i], "server")) {
                    d_role = SERVER;
                }
                else if (!std::strcmp(argv[i], "client")) {
                    d_role = CLIENT;
                }
                else if (!std::strcmp(argv[i], "both")) {
                    d_role = BOTH;
                }
                else {
                    printUsage();
                    return false;
                }
            }
            else if (!std::strcmp(argv[i], "-auth") && i + 1 < argc) {
                ++ i;
                if (!std::strcmp(argv[i], AUTH_OPTION_NONE)) {
                    d_authOptions.clear();
                }
                else if (strncmp(argv[i], AUTH_OPTION_APP, strlen(AUTH_OPTION_APP)) == 0) {
                    d_authOptions.clear();
                    d_authOptions.append(AUTH_APP_PREFIX);
                    d_authOptions.append(argv[i] + strlen(AUTH_OPTION_APP));
                }
                else if (strncmp(argv[i], AUTH_OPTION_USER_APP, strlen(AUTH_OPTION_USER_APP)) == 0) {
                    d_authOptions.clear();
                    d_authOptions.append(AUTH_USER_APP_PREFIX);
                    d_authOptions.append(argv[i] + strlen(AUTH_OPTION_USER_APP));
                }
                else if (strncmp(argv[i], AUTH_OPTION_DIR, strlen(AUTH_OPTION_DIR)) == 0) {
                    d_authOptions.clear();
                    d_authOptions.append(AUTH_DIR_PREFIX);
                    d_authOptions.append(argv[i] + strlen(AUTH_OPTION_DIR));
                }
                else if (!std::strcmp(argv[i], AUTH_OPTION_USER)) {
                    d_authOptions.assign(AUTH_USER);
                }
                else {
                    printUsage();
                    return false;
                }
            }
            else {
                printUsage();
                return false;
            }
        }

        if (d_hosts.size() == 0) {
            d_hosts.push_back("localhost");
        }
        if (d_securities.size() == 0) {
            d_securities.push_back("IBM US Equity");
        }

        if (d_fields.size() == 0) {
            d_fields.push_back("PX_LAST");
        }
        return true;
    }
Пример #25
0
 option& set_location( const std::string& _location ) {
     location.assign( _location.begin(), _location.end() );
     detail::string_it end_it = boost::find_last( location, "::" ).begin();
     section.assign( location.begin(), end_it );
     return *this;
 }
// Allow calling cards to be dropped onto text fields.  Append the name and
// a carriage return.
// virtual
BOOL LLViewerTextEditor::handleDragAndDrop(S32 x, S32 y, MASK mask,
					  BOOL drop, EDragAndDropType cargo_type, void *cargo_data,
					  EAcceptance *accept,
					  std::string& tooltip_msg)
{
	BOOL handled = FALSE;
	
	LLToolDragAndDrop::ESource source = LLToolDragAndDrop::getInstance()->getSource();
	if (LLToolDragAndDrop::SOURCE_NOTECARD == source)
	{
		// We currently do not handle dragging items from one notecard to another
		// since items in a notecard must be in Inventory to be verified. See DEV-2891.
		return FALSE;
	}
	
	if (mTakesNonScrollClicks)
	{
		if (getEnabled() && acceptsTextInput())
		{
			switch( cargo_type )
			{
			// <edit>
			// This does not even appear to be used maybe
			// Throwing it out so I can embed calling cards
			/*
			case DAD_CALLINGCARD:
				if(acceptsCallingCardNames())
				{
					if (drop)
					{
						LLInventoryItem *item = (LLInventoryItem *)cargo_data;
						std::string name = item->getName();
						appendText(name, true, true);
					}
					*accept = ACCEPT_YES_COPY_SINGLE;
				}
				else
				{
					*accept = ACCEPT_NO;
				}
				break;
			*/
			case DAD_CALLINGCARD:
			// </edit>
			case DAD_TEXTURE:
			case DAD_SOUND:
			case DAD_LANDMARK:
			case DAD_SCRIPT:
			case DAD_CLOTHING:
			case DAD_OBJECT:
			case DAD_NOTECARD:
			case DAD_BODYPART:
			case DAD_ANIMATION:
			case DAD_GESTURE:
				{
					LLInventoryItem *item = (LLInventoryItem *)cargo_data;
					// <edit>
					if((item->getPermissions().getMaskOwner() & PERM_ITEM_UNRESTRICTED) != PERM_ITEM_UNRESTRICTED)
					{
						if(gSavedSettings.getBOOL("ForceNotecardDragCargoPermissive"))
						{
							item = new LLInventoryItem((LLInventoryItem *)cargo_data);
							LLPermissions old = item->getPermissions();
							LLPermissions perm;
							perm.init(old.getCreator(), old.getOwner(), old.getLastOwner(), old.getGroup());
							perm.setMaskBase(PERM_ITEM_UNRESTRICTED);
							perm.setMaskEveryone(PERM_ITEM_UNRESTRICTED);
							perm.setMaskGroup(PERM_ITEM_UNRESTRICTED);
							perm.setMaskNext(PERM_ITEM_UNRESTRICTED);
							perm.setMaskOwner(PERM_ITEM_UNRESTRICTED);
							item->setPermissions(perm);
						}
					}
					// </edit>
					if( item && allowsEmbeddedItems() )
					{
						U32 mask_next = item->getPermissions().getMaskNextOwner();
						// <edit>
						//if((mask_next & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED)
						if(((mask_next & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED) || gSavedSettings.getBOOL("ForceNotecardDragCargoAcceptance"))
						{
							if( drop )
							{
								deselect();
								S32 old_cursor = mCursorPos;
								setCursorAtLocalPos( x, y, TRUE );
								S32 insert_pos = mCursorPos;
								setCursorPos(old_cursor);
								BOOL inserted = insertEmbeddedItem( insert_pos, item );
								if( inserted && (old_cursor > mCursorPos) )
								{
									setCursorPos(mCursorPos + 1);
								}

								updateLineStartList();
							}
							*accept = ACCEPT_YES_COPY_MULTI;
						}
						else
						{
							*accept = ACCEPT_NO;
							if (tooltip_msg.empty())
							{
								tooltip_msg.assign("Only items with unrestricted\n"
													"'next owner' permissions \n"
													"can be attached to notecards.");
							}
						}
					}
					else
					{
						*accept = ACCEPT_NO;
					}
					break;
				}

			default:
				*accept = ACCEPT_NO;
				break;
			}
		}
		else
		{
			// Not enabled
			*accept = ACCEPT_NO;
		}

		handled = TRUE;
		LL_DEBUGS("UserInput") << "dragAndDrop handled by LLViewerTextEditor " << getName() << LL_ENDL;
	}

	return handled;
}
Пример #27
0
 option& set_default_value( const char* _value ) {
     check_option_necessity();
     value.assign( _value );
     default_value.assign( value.begin(), value.end() );
     return *this;
 }
Пример #28
0
/** Handle /KILL
 */
CmdResult CommandKill::Handle (const std::vector<std::string>& parameters, User *user)
{
	/* Allow comma seperated lists of users for /KILL (thanks w00t) */
	if (CommandParser::LoopCall(user, this, parameters, 0))
	{
		// If we got a colon delimited list of nicks then the handler ran for each nick,
		// and KILL commands were broadcast for remote targets.
		return CMD_FAILURE;
	}

	User *u = ServerInstance->FindNick(parameters[0]);
	if ((u) && (!IS_SERVER(u)))
	{
		/*
		 * Here, we need to decide how to munge kill messages. Whether to hide killer, what to show opers, etc.
		 * We only do this when the command is being issued LOCALLY, for remote KILL, we just copy the message we got.
		 *
		 * This conditional is so that we only append the "Killed (" prefix ONCE. If killer is remote, then the kill
		 * just gets processed and passed on, otherwise, if they are local, it gets prefixed. Makes sense :-) -- w00t
		 */

		if (IS_LOCAL(user))
		{
			/*
			 * Moved this event inside the IS_LOCAL check also, we don't want half the network killing a user
			 * and the other half not. This would be a bad thing. ;p -- w00t
			 */
	 		ModResult MOD_RESULT;
			FIRST_MOD_RESULT(OnKill, MOD_RESULT, (user, u, parameters[1]));

			if (MOD_RESULT == MOD_RES_DENY)
				return CMD_FAILURE;

			killreason = "Killed (";
			if (!ServerInstance->Config->HideKillsServer.empty())
			{
				// hidekills is on, use it
				killreason += ServerInstance->Config->HideKillsServer;
			}
			else
			{
				// hidekills is off, do nothing
				killreason += user->nick;
			}

			killreason += " (" + parameters[1] + "))";
		}
		else
		{
			/* Leave it alone, remote server has already formatted it */
			killreason.assign(parameters[1], 0, ServerInstance->Config->Limits.MaxQuit);
		}

		/*
		 * Now we need to decide whether or not to send a local or remote snotice. Currently this checking is a little flawed.
		 * No time to fix it right now, so left a note. -- w00t
		 */
		if (!IS_LOCAL(u))
		{
			// remote kill
			if (!user->server->IsULine())
				ServerInstance->SNO->WriteToSnoMask('K', "Remote kill by %s: %s (%s)", user->nick.c_str(), u->GetFullRealHost().c_str(), parameters[1].c_str());
			this->lastuuid = u->uuid;
		}
		else
		{
			// local kill
			/*
			 * XXX - this isn't entirely correct, servers A - B - C, oper on A, client on C. Oper kills client, A and B will get remote kill
			 * snotices, C will get a local kill snotice. this isn't accurate, and needs fixing at some stage. -- w00t
			 */
			if (!user->server->IsULine())
			{
				if (IS_LOCAL(user))
					ServerInstance->SNO->WriteGlobalSno('k',"Local Kill by %s: %s (%s)", user->nick.c_str(), u->GetFullRealHost().c_str(), parameters[1].c_str());
				else
					ServerInstance->SNO->WriteToSnoMask('k',"Local Kill by %s: %s (%s)", user->nick.c_str(), u->GetFullRealHost().c_str(), parameters[1].c_str());
			}

			ServerInstance->Logs->Log("KILL", LOG_DEFAULT, "LOCAL KILL: %s :%s!%s!%s (%s)", u->nick.c_str(), ServerInstance->Config->ServerName.c_str(), user->dhost.c_str(), user->nick.c_str(), parameters[1].c_str());

			u->Write(":%s KILL %s :%s!%s!%s (%s)", ServerInstance->Config->HideKillsServer.empty() ? user->GetFullHost().c_str() : ServerInstance->Config->HideKillsServer.c_str(),
					u->nick.c_str(),
					ServerInstance->Config->ServerName.c_str(),
					user->dhost.c_str(),
					ServerInstance->Config->HideKillsServer.empty() ? user->nick.c_str() : ServerInstance->Config->HideKillsServer.c_str(),
					parameters[1].c_str());

			this->lastuuid.clear();
		}

		// send the quit out
		ServerInstance->Users->QuitUser(u, killreason);
	}
	else
	{
		user->WriteNumeric(ERR_NOSUCHNICK, "%s :No such nick/channel", parameters[0].c_str());
		return CMD_FAILURE;
	}

	return CMD_SUCCESS;
}
Пример #29
0
void message::get(std::string& string, size_t const& part) const
{
	string.assign( get(part) );
}
Пример #30
0
void msx_slot_cartridge_device::get_default_card_software(std::string &result)
{
	if (open_image_file(mconfig().options()))
	{
		const char *slot_string = "nomapper";
		UINT32 length = core_fsize(m_file);
		dynamic_buffer rom(length);
		int type = NOMAPPER;

		// Check if there's some mapper related information in the hashfiles
		std::string extrainfo;
		if (hashfile_extrainfo(*this, extrainfo))
		{
			int extrainfo_type = -1;
			if (1 == sscanf(extrainfo.c_str(), "%d", &extrainfo_type))
			{
				static const struct { int extrainfo; int mapper; } extrainfo_map[] = {
					//{ 0, NOMAPPER },
					{ 1, MSXDOS2 },
					{ 2, KONAMI_SCC },
					{ 3, KONAMI },
					{ 4, ASCII8 },
					{ 5, ASCII16 },
					{ 6, GAMEMASTER2 },
					{ 7, ASCII8_SRAM },
					{ 8, ASCII16_SRAM },
					{ 9, RTYPE },
					{ 10, MAJUTSUSHI },
					{ 11, FMPAC },
					{ 12, SUPERLODERUNNER },
					{ 13, SYNTHESIZER },
					{ 14, CROSSBLAIM },
					{ 15, DISK_ROM },
					{ 16, KOREAN_80IN1 },
					{ 17, KOREAN_126IN1 }
				};

				for (int i = 0; i < ARRAY_LENGTH(extrainfo_map); i++)
				{
					if (extrainfo_map[i].extrainfo == extrainfo_type)
					{
						type = extrainfo_map[i].mapper;
					}
				}
			}
		}

		if (type == NOMAPPER)
		{
			// Not identified through hashfile, try automatic detection
			type = get_cart_type(&rom[0], length);
		}

		if (type > NOMAPPER)
		{
			slot_string = msx_cart_get_slot_option(type);
		}

		result.assign(slot_string);
		return;
	}
	software_get_default_slot(result, "nomapper");
}