Esempio n. 1
0
void Daemon::detachFromParent()
{
    // Clone ourselves to make a child
    pid_t pid = fork();

    // If the pid is less than zero, something went wrong when forking
    if (pid < 0) {
        throw DaemonException(StringBuilder("Forking went wrong : ")
                              .add(strerror(errno)).str());
    }
    // If the pid we got back was greater than zero, then the clone was
    // successful and we are the parent
    else if (pid > 0) {
        exit(EXIT_SUCCESS);
    }
    // If execution reaches this point we are the child.

    // Because we are a clone of our parent we’ve inherited its umask.
    // Set the umask to zero
    umask(0);

    // Create our own process group
    pid_t sid = setsid();
    if (sid < 0) {
        throw DaemonException(StringBuilder("Can't create own process group : ")
                              .add(strerror(errno)).str());
    }
    mPid = sid;
    syslog(LOG_INFO, "Process has been detached from parent process, PID = %d.",
           mPid);
}
Esempio n. 2
0
bool Texture::LoadFromFile(const string & file) {
	D3DXIMAGE_INFO imgInfo;

	int slashPos = file.find_last_of('/');
	int dotPos = file.find_last_of('.');
	string ext = file.substr(dotPos + 1, file.size() - dotPos);
	string name = file.substr(slashPos + 1, dotPos - slashPos - 1);

	// cache lookup
	string cacheFileName = "./cache/" + name + ".dds";
	FILE * pFile = fopen(cacheFileName.c_str(), "r");
	bool genericTex = file.find("textures/generic") != string::npos;
	if(pFile && genericTex) {
		fclose(pFile);
		if(FAILED(D3DXCreateTextureFromFileExA(pD3D, cacheFileName.c_str(), D3DX_DEFAULT_NONPOW2, D3DX_DEFAULT_NONPOW2, D3DX_FROM_FILE, 0, D3DFMT_FROM_FILE, D3DPOOL_DEFAULT, D3DX_FILTER_NONE, D3DX_FILTER_NONE, 0, &imgInfo, NULL, &mTexture))) {
			Log::Write(StringBuilder("WARNING: Unable to load ") << file << " texture!");
			return false;
		} else {
			Log::Write(StringBuilder("Texture successfully loaded from DDS cache: ") << cacheFileName);
		}
	} else {
		if(FAILED(D3DXCreateTextureFromFileExA(pD3D, file.c_str(), D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, &imgInfo, 0, &mTexture))) {
			Log::Write(StringBuilder("WARNING: Unable to load ") << file << " texture!");
			return false;
		} else {
			Log::Write(StringBuilder("Texture successfully loaded: ") << file);
		}
	}
	mWidth = imgInfo.Width;
	mHeight = imgInfo.Height;
	mColorDepth = 32;
	return true;
}
Esempio n. 3
0
void Daemon::savePidToPidfile()
{
    const char* buffer = StringBuilder(mPid).add("\n").c_str();
    if (-1 == write(mPidfilefd, buffer, strlen(buffer))) {
        throw DaemonException(StringBuilder("Can't save the pid to pidfile : ")
                              .add(strerror(errno)).str());
    }
}
Esempio n. 4
0
void Daemon::destroyPidfile()
{
    // Unlock pidfile
    if( -1 == flock(mPidfilefd, LOCK_UN) ) {
        throw DaemonException(StringBuilder("Can't unlock pidfile : ")
                              .add(strerror(errno)).str());
    }
    // Remove pidfile
    if( -1 == remove(mPidfile.c_str()) ) {
        throw DaemonException(StringBuilder("Can't remove pidfile")
                              .add(strerror(errno)).str());
    }
    syslog(LOG_INFO, "Pidfile has been destroyed.");
}
Esempio n. 5
0
static LineInfo GetFileInfo(SourceLocation loc) {
  std::ifstream stream(loc.filename);

  if (!stream.good()) {
    throw InternalCompilerError(StringBuilder(
        "Can't reopen file '", loc.filename, "' after error found in it."));
  }

  // We need to iterate through the file to get the line number information.
  // Can't store this in SourceLocation because it needs to be as small as
  // possible. This is fine, because we would only need to do it once for bad
  // input in a compilation pass, and we are already at *at least* O(n) on the
  // file length
  int lineCount = 0;
  std::array<char, 256> lineArray;

  while (stream.tellg() < loc.offset) {
    lineCount++;
    stream.getline(&lineArray[0], 256);
  }

  std::string line(&lineArray[0]);

  int lineOffset = line.size() - (stream.tellg() - loc.offset);
  return LineInfo(loc.filename, line, lineCount, lineOffset);
}
Esempio n. 6
0
File: Menu.cpp Progetto: mrDIMAS/src
void Menu::ReadConfig() {
	// small lambda to reduce casting bullshit
	auto ReadKey = [this](const string & param) { return static_cast<IInput::Key>(static_cast<int>(mConfig.GetNumber(param))); };
	mMasterVolume->SetValue(mConfig.GetNumber("masterVolume"));
	mMusicVolume->SetValue(mConfig.GetNumber("musicVolume"));
	mGame->SetMusicVolume(mMusicVolume->GetValue());
	mMouseSensivity->SetValue(mConfig.GetNumber("mouseSens"));
	mFXAAButton->SetEnabled(mConfig.GetBoolean("fxaaEnabled"));
	mMoveForwardKey->SetSelected(ReadKey("keyMoveForward"));
	mMoveBackwardKey->SetSelected(ReadKey("keyMoveBackward"));
	mStrafeLeftKey->SetSelected(ReadKey("keyStrafeLeft"));
	mStrafeRightKey->SetSelected(ReadKey("keyStrafeRight"));
	mJumpKey->SetSelected(ReadKey("keyJump"));
	mRunKey->SetSelected(ReadKey("keyRun"));
	mFlashLightKey->SetSelected(ReadKey("keyFlashLight"));
	mInventoryKey->SetSelected(ReadKey("keyInventory"));
	mUseKey->SetSelected(ReadKey("keyUse"));
	mQuickSaveKey->SetSelected(ReadKey("keyQuickSave"));
	mGame->SetQuickSaveKey(mQuickSaveKey->GetSelectedKey());
	mQuickLoadKey->SetSelected(ReadKey("keyQuickLoad"));
	mGame->SetQuickLoadKey(mQuickLoadKey->GetSelectedKey());
	mStealthKey->SetSelected(ReadKey("keyStealth"));
	mSpotShadowsButton->SetEnabled(mConfig.GetBoolean("spotShadowsEnabled"));
	mMusic->SetVolume(mMusicVolume->GetValue() / 100.0f);
	mHDRButton->SetEnabled(mConfig.GetBoolean("hdrEnabled"));
	mParallaxButton->SetEnabled(mConfig.GetBoolean("parallax"));
	mTextureFiltering->SetCurrentValue(mConfig.GetNumber("textureFiltering"));
	mLookLeftKey->SetSelected(ReadKey("keyLookLeft"));
	mLookRightKey->SetSelected(ReadKey("keyLookRight"));
	mFPSButton->SetEnabled(mConfig.GetBoolean("showFPS"));
	mGame->ShowFPS(mFPSButton->IsChecked());
	mFOVSlider->SetValue(mConfig.GetNumber("fov"));
	mVolumetricFogButton->SetEnabled(mConfig.GetBoolean("volumetricFog"));
	mSpotLightShadowMapSize->SetCurrentValue(mConfig.GetNumber("spotLightShadowMapSize"));
	mPointLightShadowMapSize->SetCurrentValue(mConfig.GetNumber("pointLightShadowMapSize"));
	mDirectionalLightShadowMapSize->SetCurrentValue(mConfig.GetNumber("directionalLightShadowMapSize"));
	mDynamicDirectionalLightShadows->SetEnabled(mConfig.GetBoolean("dynamicDirectionalLightShadows"));
	mBloom->SetEnabled(mConfig.GetBoolean("bloom"));
	mWindowMode->SetCurrentValue(mConfig.GetNumber("windowMode"));
	mVSync->SetEnabled(mConfig.GetBoolean("vsync"));
	mPointShadowsButton->SetEnabled(mConfig.GetBoolean("pointShadowsEnabled"));
	mSoftParticles->SetEnabled(mConfig.GetBoolean("softParticles"));
	mMouseInversionX->SetEnabled(mConfig.GetBoolean("mouseInvX"));
	mMouseInversionY->SetEnabled(mConfig.GetBoolean("mouseInvY"));

	// read resolution and verify
	{
		string resolution = StringBuilder() << mGame->GetEngine()->GetRenderer()->GetResolutionWidth() << "x" << mGame->GetEngine()->GetRenderer()->GetResolutionHeight() << "@60";

		int num = 0;
		for(auto res : mResolutionList->GetValues()) {
			if(res == resolution) {
				mResolutionList->SetCurrentValue(num);
			}
			++num;
		}
	}
	// apply
	ApplySettings();
}
Esempio n. 7
0
VCNModel* D3DConverter::ConvertD3DModel(const D3DModel& d3dmodel, LPDIRECT3DDEVICE9 device)
{
	VCNNode* root = 0;
	
	if ( d3dmodel.m_MeshContainers.size() > 1 ) 
	{
		root = VCNNodeCore::GetInstance()->CreateNode<VCNNode>();
	}

	for (auto it = d3dmodel.m_MeshContainers.begin(),end = d3dmodel.m_MeshContainers.end(); it != end; ++it)
	{
		LPD3DXMESHCONTAINER meshContainer = *it;
		std::wstring name = StringBuilder() << d3dmodel.m_Name << "_Mesh_" << meshContainer->Name;
		VCNNode* nodepart = ConvertMesh(name, meshContainer, d3dmodel.m_FrameRoot, d3dmodel.m_AnimController, device);

		if ( d3dmodel.m_MeshContainers.size() > 1 ) 
		{
			root->AttachChild( nodepart->GetNodeID() );
		}
		else
		{
			root = nodepart;
		}
	}

	VCNModel* model = new VCNModel( root );
	model->SetName( d3dmodel.m_Name );
	model->SetVersion( 1.0f );
	VCNResourceCore::GetInstance()->AddResource( d3dmodel.m_Name, model );

	return model;
}
Esempio n. 8
0
void Daemon::createPidfile()
{
    // Open or create pidfile
    mPidfilefd = open(mPidfile.c_str(), O_CREAT | O_RDWR, 0666);
    if( -1 == mPidfilefd ) {
        throw DaemonException(StringBuilder("Can't open/create the pidfile : ")
                              .add(strerror(errno)).str());
    }
    // Try to lock pidfile
    if( flock(mPidfilefd, LOCK_EX | LOCK_NB) ) {
        // pidfile is locked, it means that another instance is running
        throw DaemonException(StringBuilder("Can't lock the pidfile : ")
                              .add(strerror(errno)).str());
    }
    syslog(LOG_INFO, "Pidfile has been created.");
}
Esempio n. 9
0
    System::Object^ VowpalWabbitDynamicPredictionFactory::Create(vw* vw, example* ex)
    {
        if (ex == nullptr)
            throw gcnew ArgumentNullException("ex");

        switch (vw->l->pred_type)
        {
        case prediction_type::scalar:
            return VowpalWabbitPredictionType::Scalar->Create(vw, ex);
        case prediction_type::scalars:
            return VowpalWabbitPredictionType::Scalars->Create(vw, ex);
        case prediction_type::multiclass:
            return VowpalWabbitPredictionType::Multiclass->Create(vw, ex);
        case prediction_type::multilabels:
            return VowpalWabbitPredictionType::Multilabel->Create(vw, ex);
        case prediction_type::action_scores:
            return VowpalWabbitPredictionType::ActionScore->Create(vw, ex);
        case prediction_type::prob:
            return VowpalWabbitPredictionType::Probability->Create(vw, ex);
        case prediction_type::multiclassprobs:
            return VowpalWabbitPredictionType::MultiClassProbabilities->Create(vw, ex);
        default:
        {
            auto sb = gcnew StringBuilder();
            sb->Append("Unsupported prediction type: ");
            sb->Append(gcnew String(prediction_type::to_string(vw->l->pred_type)));
            throw gcnew ArgumentException(sb->ToString());
        }
        }
    }
Esempio n. 10
0
	ManagedFasm::ManagedFasm()
	{
		m_AssemblyString = gcnew StringBuilder("use32\n");
		m_ThreadHandles = gcnew List<IntPtr>();

		m_MemorySize = DEFAULT_MEMORY_SIZE;
		m_PassLimit = DEFAULT_PASS_LIMIT;
	}
Esempio n. 11
0
void Daemon::changeWorkingDirectory()
{
    // Change the current working directory
    if (!mDir.empty() && chdir(mDir.c_str()) < 0) {
        throw DaemonException(
                    StringBuilder("Can't change the working directory to ")
                    .add(mDir).str());
    }
    syslog(LOG_INFO, "Process has changed the working directory.");
}
Esempio n. 12
0
  std::string generateReport(std::string msg) {
    auto report = StringBuilder(filename, ':', lineNumber, ':', offset,
                                " Error: ", msg, '\n', line, '\n');
    for (int i = 1; i < offset; ++i)
      report += ' ';

    report += '^';

    return report;
  }
Esempio n. 13
0
File: Menu.cpp Progetto: mrDIMAS/src
void Menu::OnLoadSaveClick() {
	SetPage(Page::Main, false);
	for(int i = 0; i < mSaveLoadSlotCount; ++i) {
		if(mLoadGameSlot[i]->IsHit()) {
			mLoadSaveGameName = mSaveFilesList[i];
		}
	}
	mModalWindow->Ask(StringBuilder() << mLocalization.GetString("youSelect") << mLoadSaveGameName << "." << mLocalization.GetString("loadSaveQuestion"));
	mModalWindow->SetYesAction([this] { CameraStartFadeOut([this] { mGame->LoadState(mLoadSaveGameName); Hide(); }); });
}
Esempio n. 14
0
File: Menu.cpp Progetto: mrDIMAS/src
void Menu::OnCreateSaveClick() {
	SetPage(Page::Main, false);
	for(int i = 0; i < mSaveLoadSlotCount; ++i) {
		if(mSaveGameSlot[i]->IsHit()) {
			mSaveGameSlotName = mSaveFilesList[i];
		}
	}
	mModalWindow->Ask(StringBuilder() << mLocalization.GetString("youSelect") << mSaveGameSlotName << "." << mLocalization.GetString("rewriteSaveQuestion"));
	mModalWindow->SetYesAction([this] { mGame->SaveState(mSaveGameSlotName); SetPage(Page::Main); });
}
Esempio n. 15
0
	// 通过P/Invoke调用函数ReverseString
	void WrapperClass::ReverseString_PInvoke()
	{
		// 创建StringBuilder作为字符串缓冲区
		String^ rawString = L"String_PInvoke";
		StringBuilder^ buf  = gcnew StringBuilder(rawString->Length);
		int bufferSize = buf->Capacity + 1;
		
		// P/Invoke调用ReverseString函数
		PInvokeReverseString(rawString, buf, bufferSize);
		Console::WriteLine("翻转字符串结果(P/Invoke):{0} -> {1}", rawString, buf->ToString());
	}
Esempio n. 16
0
string TimeStamp::SecondCountToString(int secondCount)
{
	if (secondCount < 0)
		return "0:00";
	else
	{
		int min = secondCount / 60;
		int sec = secondCount % 60;
		return StringBuilder() + min + ":" + (sec > 9 ? "" : "0") + sec;
	}
}
Esempio n. 17
0
static utf8 * LegacyScriptWrite(TitleSequence * seq)
{
    utf8 buffer[128];
    auto sb = StringBuilder(128);

    sb.Append("# SCRIPT FOR ");
    sb.Append(seq->Name);
    sb.Append("\n");
    for (size_t i = 0; i < seq->NumCommands; i++)
    {
        const TitleCommand * command = &seq->Commands[i];
        switch (command->Type) {
        case TITLE_SCRIPT_LOAD:
            if (command->SaveIndex == 0xFF)
            {
                sb.Append("LOAD <No save file>");
            } else
            {
                sb.Append("LOAD ");
                sb.Append(seq->Saves[command->SaveIndex]);
            }
            break;
        case TITLE_SCRIPT_LOCATION:
            String::Format(buffer, sizeof(buffer), "LOCATION %u %u", command->X, command->Y);
            sb.Append(buffer);
            break;
        case TITLE_SCRIPT_ROTATE:
            String::Format(buffer, sizeof(buffer), "ROTATE %u", command->Rotations);
            sb.Append(buffer);
            break;
        case TITLE_SCRIPT_ZOOM:
            String::Format(buffer, sizeof(buffer), "ZOOM %u", command->Zoom);
            sb.Append(buffer);
            break;
        case TITLE_SCRIPT_SPEED:
            String::Format(buffer, sizeof(buffer), "SPEED %u", command->Speed);
            sb.Append(buffer);
            break;
        case TITLE_SCRIPT_WAIT:
            String::Format(buffer, sizeof(buffer), "WAIT %u", command->Seconds);
            sb.Append(buffer);
            break;
        case TITLE_SCRIPT_RESTART:
            sb.Append("RESTART");
            break;
        case TITLE_SCRIPT_END:
            sb.Append("END");
        }
        sb.Append("\n");
    }

    utf8 * result = sb.StealString();
    return result;
}
Esempio n. 18
0
File: HUD.cpp Progetto: mrDIMAS/src
void HUD::SetAction(IInput::Key keyCode, const string & action) {
	string text;

	if(keyCode == IInput::Key::None) {
		text = action;
	} else {
		text = StringBuilder() << "[" << mGame->GetEngine()->GetInput()->GetKeyName(keyCode) << "] - " << action;
	}

	mGUIActionText->SetText(text);
	mGUIActionText->SetVisible(true);
}
Esempio n. 19
0
LanguagePack::LanguagePack(uint16 id, const utf8 * text)
{
    assert(text != nullptr);

    _id = id;
    _stringData = nullptr;
    _currentGroup = nullptr;
    _currentObjectOverride = nullptr;
    _currentScenarioOverride = nullptr;

    auto reader = UTF8StringReader(text);
    while (reader.CanRead())
    {
        ParseLine(&reader);
    }

    _stringData = _stringDataSB.GetString();

    size_t stringDataBaseAddress = (size_t)_stringData;
    for (size_t i = 0; i < _strings.size(); i++)
    {
        if (_strings[i] != nullptr)
        {
            _strings[i] = (utf8*)(stringDataBaseAddress + (size_t)_strings[i]);
        }
    }
    for (size_t i = 0; i < _objectOverrides.size(); i++)
    {
        for (int j = 0; j < ObjectOverrideMaxStringCount; j++)
        {
            const utf8 * * strPtr = &(_objectOverrides[i].strings[j]);
            if (*strPtr != nullptr)
            {
                *strPtr = (utf8*)(stringDataBaseAddress + (size_t)*strPtr);
            }
        }
    }
    for (size_t i = 0; i < _scenarioOverrides.size(); i++)
    {
        for (int j = 0; j < ScenarioOverrideMaxStringCount; j++)
        {
            const utf8 **strPtr = &(_scenarioOverrides[i].strings[j]);
            if (*strPtr != nullptr)
            {
                *strPtr = (utf8*)(stringDataBaseAddress + (size_t)*strPtr);
            }
        }
    }

    // Destruct the string builder to free memory
    _stringDataSB = StringBuilder();
}
Esempio n. 20
0
	LexerLine::LexerLine()
		: _sb(gcnew StringBuilder())
		, _foldStarts(0)
		, _foldEnds(0)
		, _lineStart(NULL)
		, _lineEnd(NULL)
		, _codePage(0)
		, _lineText(nullptr)
		, _styles(NULL)
		, _stylesLen(0)
		, _charLen(-1)
	{
	}
 // static
 StatusWith<int> LiteParsedQuery::parseMaxTimeMS(const BSONElement& maxTimeMSElt) {
     if (!maxTimeMSElt.eoo() && !maxTimeMSElt.isNumber()) {
         return StatusWith<int>(ErrorCodes::BadValue,
                                (StringBuilder()
                                    << maxTimeMSElt.fieldNameStringData()
                                    << " must be a number").str());
     }
     long long maxTimeMSLongLong = maxTimeMSElt.safeNumberLong(); // returns 0 on EOO
     if (maxTimeMSLongLong < 0 || maxTimeMSLongLong > INT_MAX) {
         return StatusWith<int>(ErrorCodes::BadValue,
                                (StringBuilder()
                                    << maxTimeMSElt.fieldNameStringData()
                                    << " is out of range").str());
     }
     double maxTimeMSDouble = maxTimeMSElt.numberDouble();
     if (maxTimeMSElt.type() == mongo::NumberDouble
         && floor(maxTimeMSDouble) != maxTimeMSDouble) {
         return StatusWith<int>(ErrorCodes::BadValue,
                                (StringBuilder()
                                    << maxTimeMSElt.fieldNameStringData()
                                    << " has non-integral value").str());
     }
     return StatusWith<int>(static_cast<int>(maxTimeMSLongLong));
 }
Esempio n. 22
0
void LanguagePack::ParseGroupObject(IStringReader * reader)
{
    auto sb = StringBuilder();
    codepoint_t codepoint;

    // Should have already deduced that the next codepoint is a [
    reader->Skip();

    // Read string up to ] or line end
    bool closedCorrectly = false;
    while (reader->TryPeek(&codepoint))
    {
        if (IsNewLine(codepoint)) break;

        reader->Skip();
        if (codepoint == ']')
        {
            closedCorrectly = true;
            break;
        }
        sb.Append(codepoint);
    }

    if (closedCorrectly)
    {
        SafeFree(_currentGroup);

        while (sb.GetLength() < 8)
        {
            sb.Append(' ');
        }
        if (sb.GetLength() == 8)
        {
            _currentGroup = sb.GetString();
            _currentObjectOverride = GetObjectOverride(_currentGroup);
            _currentScenarioOverride = nullptr;
            if (_currentObjectOverride == nullptr)
            {
                _objectOverrides.push_back(ObjectOverride());
                _currentObjectOverride = &_objectOverrides[_objectOverrides.size() - 1];
                memset(_currentObjectOverride, 0, sizeof(ObjectOverride));
                memcpy(_currentObjectOverride->name, _currentGroup, 8);
            }
        }
    }
}
Esempio n. 23
0
	String^ LexerLine::Text::get()
	{
		if (_lineText == nullptr)
		{
			if (_codePage == SC_CP_UTF8)
			{
				StringBuilder^	sb = gcnew StringBuilder();
				const char*		pos = _lineStart;
				while (pos < _lineEnd)
				{
					sb->Append(ReadUtf8Char(&pos));
				}
				_lineText = sb->ToString();
			}
			else
			{
				_lineText = gcnew String(_lineStart, 0, _lineEnd - _lineStart);
			}
		}
		return _lineText;
	}
void WebPageSerializerImpl::encodeAndFlushBuffer(
    WebPageSerializerClient::PageSerializationStatus status,
    SerializeDomParam* param,
    FlushOption flushOption)
{
    // Data buffer is not full nor do we want to force flush.
    if (flushOption != ForceFlush && m_dataBuffer.length() <= dataBufferCapacity)
        return;

    String content = m_dataBuffer.toString();
    m_dataBuffer = StringBuilder();

    // Convert the unicode content to target encoding
    CString encodedContent = param->textEncoding.encode(
        content.characters(), content.length(), EntitiesForUnencodables);

    // Send result to the client.
    m_client->didSerializeDataForFrame(param->url,
                                       WebCString(encodedContent.data(), encodedContent.length()),
                                       status);
}
Esempio n. 25
0
void LanguagePack::ParseGroupScenario(IStringReader * reader)
{
    auto sb = StringBuilder();
    codepoint_t codepoint;

    // Should have already deduced that the next codepoint is a <
    reader->Skip();

    // Read string up to > or line end
    bool closedCorrectly = false;
    while (reader->TryPeek(&codepoint))
    {
        if (IsNewLine(codepoint)) break;

        reader->Skip();
        if (codepoint == '>')
        {
            closedCorrectly = true;
            break;
        }
        sb.Append(codepoint);
    }

    if (closedCorrectly)
    {
        SafeFree(_currentGroup);

        _currentGroup = sb.GetString();
        _currentObjectOverride = nullptr;
        _currentScenarioOverride = GetScenarioOverride(_currentGroup);
        if (_currentScenarioOverride == nullptr)
        {
            _scenarioOverrides.push_back(ScenarioOverride());
            _currentScenarioOverride = &_scenarioOverrides[_scenarioOverrides.size() - 1];
            Memory::Set(_currentScenarioOverride, 0, sizeof(ScenarioOverride));
            _currentScenarioOverride->filename = sb.GetString();
        }
    }
}
Esempio n. 26
0
void AuthorizedObject::_GetPictureConnection(const std::string &id, PictureSize size, ResponseBlob *blob) const
{
	LIBFACEBOOKCPP_CHKARG(size >= PS_SQUARE && size <= PS_LARGE);
	LIBFACEBOOKCPP_CHKARG(blob);

	Uri uri;
	request_->GetUri(&uri);

	uri.base_uri = StringBuilder() << "https://graph.facebook.com/" << HttpUtils::Escape(id) << "/picture";

	static const char *s_sizeType[] = {
		{ "square"}, // PS_SQUARE
		{ "small" }, // PS_SMALL
		{ "large" }, // PS_LARGE
	};

	LIBFACEBOOKCPP_CASSERT(PS_SQUARE == 0);
	LIBFACEBOOKCPP_CASSERT(LIBFACEBOOKCPP_NUMELMS(s_sizeType) == PS_COUNT);

	uri.query_params["type"] = s_sizeType[size];

	request_->GetResponse(uri.GetUri(), blob);
}
Move AspirationSearch::chooseMove(GameState& gameState)
{
	transpositionTable.clear();	// clean up data from previous searches

#ifdef GATHER_STATISTICS
	nodesVisited = 0;
	Timer timer;
	timer.start();
	Move moveToPlay = startAspirationSearch(gameState);
	timer.stop();

#ifdef LOG_STATS_PER_TURN
	if(gameState.getCurrentPlayer() == EPlayerColors::Type::BLACK_PLAYER)
	{
		LOG_MESSAGE(StringBuilder() << "Aspiration Search engine searching move for Black Player")
	}
	else
	{
		LOG_MESSAGE(StringBuilder() << "Aspiration Search engine searching move for White Player")
	}

	LOG_MESSAGE(StringBuilder() << "Search depth:					" << searchDepth)
	LOG_MESSAGE(StringBuilder() << "Number of nodes visited:			" << nodesVisited)
	LOG_MESSAGE(StringBuilder() << "Time spent:					" << timer.getElapsedTimeInMilliSec() << " ms")
	LOG_MESSAGE(StringBuilder() << "% of Transposition Table entries used:		" << ((double)transpositionTable.getNumEntriesUsed() / (TRANSPOSITION_TABLE_NUM_ENTRIES * 2.0)))
	LOG_MESSAGE(StringBuilder() << "% of Transposition Table entries replaced:	" << ((double)transpositionTable.getNumReplacementsRequired() / (TRANSPOSITION_TABLE_NUM_ENTRIES * 2.0)))
	LOG_MESSAGE("")
#endif // LOG_STATS_PER_TURN

#ifdef LOG_STATS_END_OF_MATCH
	totalNodesVisited += nodesVisited;
	totalTimeSpent += timer.getElapsedTimeInMilliSec();
	++turnsPlayed;
#endif // LOG_STATS_END_OF_MATCH

	return moveToPlay;
#else
	return startAspirationSearch(gameState);
#endif // GATHER_STATISTICS
}
Esempio n. 28
0
bool LanguagePack::ParseToken(IStringReader * reader, uint32 * token, bool * isByte)
{
    auto sb = StringBuilder();
    codepoint_t codepoint;

    // Skip open brace
    reader->Skip();

    while (reader->TryPeek(&codepoint))
    {
        if (IsNewLine(codepoint)) return false;
        if (IsWhitespace(codepoint)) return false;

        reader->Skip();

        if (codepoint == '}') break;

        sb.Append(codepoint);
    }

    const utf8 * tokenName = sb.GetBuffer();
    *token = format_get_code(tokenName);
    *isByte = false;

    // Handle explicit byte values
    if (*token == 0)
    {
        int number;
        if (sscanf(tokenName, "%d", &number) == 1)
        {
            *token = Math::Clamp(0, number, 255);
            *isByte = true;
        }
    }

    return true;
}
Esempio n. 29
0
//! Time formatted like 11:27
std::string TimeStamp::GetTime(void)
{
	return StringBuilder() + GetHour() + ":" + GetMinute();
}
Esempio n. 30
0
//! Date, formatted like 14/02/2012
std::string TimeStamp::GetDate(void)
{	
	return StringBuilder() + GetDay() + "/" + GetMonth() + "/" + GetYear();
}