Exemple #1
0
void DoUnregistration()
{
    OutputConsole(L"Removing Service...\n");

    SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
    if (!scm)
    {
        OutputError(L"OpenSCManager fails! (%d)\n", GetLastError());
        return;
    }

    SC_HANDLE myService = NULL;
    BOOL success;

    do
    {
        OutputConsole(L"Opened Service Control Manager...\n");
        myService = OpenService(scm, SERVICE_NAME, SERVICE_ALL_ACCESS | DELETE);

        if (!myService)
        {
            DWORD dwResult = GetLastError();
            if (dwResult = ERROR_SERVICE_DOES_NOT_EXIST)
            {
                OutputConsole(L"Service doesn't exist!\n");
                break;
            }

            OutputError(L"OpenService fails! (%d)\n", dwResult);
            break;
        }

        if (DoStopService() == FALSE)
        {
            break;
        }

        success = DeleteService(myService);
        if (success)
        {
            OutputConsole(L"Service successfully removed.\n");
        }
        else
        {
            OutputError(L"DeleteService Fails! (%d)\n", GetLastError());
            break;
        }

    } while (false);

    if (myService != NULL)
    {
        CloseServiceHandle(myService);
    }

    if (scm != NULL)
    {
        CloseServiceHandle(scm);
    }
}
/*
 * DetermineAdapter
 * 
 * NOTE:
 *   
 *    This code retrieves the Adapter Name to use for the DHCP Client API 
 *    using the IPHelper API.
 *   
 *    NT has a name for the adapter that through this API has device 
 *    information in front of it followed by a {GUID}, 98 does not and 
 *    the Index is used instead. So if the string is set to ?? (what it is 
 *    in 98) we revert to using the string representation of the index.
 *     
 */
LPSTR DetermineAdapter()
{
  DWORD dwResult;                            // result of API calls
  IP_INTERFACE_INFO * pInfo = NULL;          // adapter information structure
  DWORD dwSize = 0;                          // size of required buffer
  CHAR szAdapter[MAX_ADAPTER_NAME] = {0};    // the adapter to use 
  char * ptr;                                // pointer to adapter name

  // get buffer size
  dwResult = GetInterfaceInfo(NULL, &dwSize);     
  if (dwResult == ERROR_INSUFFICIENT_BUFFER)
    {
    // allocate buffer
    pInfo = (IP_INTERFACE_INFO *) LocalAlloc(LPTR, dwSize);
    if (!pInfo)
      {
      OutputError(GetLastError());
      exit(1);
      }

    // make the actual call
    dwResult = GetInterfaceInfo(pInfo, &dwSize);
    if (dwResult != ERROR_SUCCESS)
      {
      OutputError(GetLastError());
      exit(2);
      }
    }
  else
    {
    OutputError(GetLastError());
    exit(3);
    }
  
  // convert, parse, and convert back
  ptr = NULL;
  WideCharToMultiByte(0, 0, pInfo->Adapter[0].Name, 
                            lstrlenW(pInfo->Adapter[0].Name), 
                            szAdapter, MAX_ADAPTER_NAME, NULL, NULL);
  if (szAdapter[0] != '?')
    {
    // find the GUID
    ptr = strchr(szAdapter, '{'); 
    }

  // use index if the pointer is not set
  if (!ptr)
    {
    sprintf_s(szAdapter, MAX_ADAPTER_NAME, "%ld\0", pInfo->Adapter[0].Index);            
    ptr = szAdapter;
    }

  // free what was allocated
  if (pInfo)
    LocalFree(pInfo);

  return ptr;
}
Exemple #3
0
void DoStartService()
{
    SC_HANDLE scm = OpenSCManager(0, 0, SC_MANAGER_ALL_ACCESS | GENERIC_WRITE);
    if (!scm)
    {
        OutputError(L"OpenSCManager fails! (%d)\n", GetLastError());
        return;
    }

    SC_HANDLE myService = NULL;
    BOOL success;
    SERVICE_STATUS status;

    do
    {
        OutputConsole(L"Opened Service Control Manager...\n");
        myService = OpenService(scm, SERVICE_NAME, SERVICE_ALL_ACCESS);

        if (!myService)
        {
            OutputError(L"OpenService fails! (%d)\n", GetLastError());
            break;
        }

        success = QueryServiceStatus(myService, &status);
        if (!success)
        {
            OutputError(L"QueryServiceStatus fails! (%d)\n", GetLastError());
            break;
        }

        if (status.dwCurrentState != SERVICE_STOPPED && status.dwCurrentState != SERVICE_STOP_PENDING)
        {
            OutputError(L"Cannot start the service because it is already running\n");
            break;
        }

        success = StartService(myService, 0, NULL);
        if (!success)
        {
            OutputError(L"StartService fails! (%d)\n", GetLastError());
            break;
        }

        OutputConsole(L"Service started successfully!\n");

    } while (false);

    if (myService != NULL)
    {
        CloseServiceHandle(myService);
    }

    if (scm != NULL)
    {
        CloseServiceHandle(scm);
    }
}
void
ErrorReporter::OutputError(uint32_t aLineNumber, uint32_t aLineOffset)
{
  mErrorLineNumber = aLineNumber;
  mErrorColNumber = aLineOffset;
  OutputError();
}
BOOL
mmWriteProfileInt(LPCTSTR appname, LPCTSTR valuename, INT Value)
{
    // If we would write the same as already there... return.
    if (mmGetProfileInt(appname, valuename, !Value) == ((UINT)Value)) {
        return TRUE;
    }

    {
        TCHAR achName[MAX_PATH];
        HKEY hkey;

        HRESULT hr = StringCchCopy(achName, MAX_PATH, KEYNAME);
		if (FAILED(hr))
			OutputError(hr, IDS_SAFE_COPY);
        
        if (RegCreateKey(ROOTKEY, achName, &hkey) == ERROR_SUCCESS) {
            RegSetValueEx(
                hkey,
                valuename,
                0,
                REG_DWORD,
                (PBYTE) &Value,
                sizeof(Value)
            );

            RegCloseKey(hkey);
        }
    }
    return TRUE;
}
Exemple #6
0
/* insert an item into the plist */
BOOL APIENTRY
StatusAddItem(
              HANDLE hmem,
              int itemnr,
              int type,
              int flags,
              int id,
              int width,
              LPSTR text
              )
{
    PILIST pilist;
    PSTATEL pel;
	HRESULT hr;

    pilist = (PILIST) hmem;
    if ((pilist == NULL) || (itemnr >= pilist->nitems)) {
        return(FALSE);
    }
    pel = &pilist->statels[itemnr];
    pel->type = type;
    pel->flags = flags;
    pel->id = id;
    pel->width = width;
    if (text == NULL) {
        pel->text[0] = '\0';
    } else {
        hr = StringCchCopy(pel->text,(SF_MAXLABEL+1), text);
		if (FAILED(hr))
			OutputError(hr, IDS_SAFE_COPY);
    }

    return(TRUE);
}
/* Dump the internals to the debugger. */
void
APIENTRY
List_Dump(
         LPSTR Header,
         LIST lst
         )
{
    LIST pit;
	HRESULT hr;
    char X_msg[250] = {0};

    OutputDebugString(Header);  OutputDebugString("\n");
    pit = lst;
    do {
        hr = StringCchPrintf(X_msg, sizeof(X_msg)-1, "%8p %8p %8p %ld %s "
                 , pit, pit->pitNext, pit->pitPrev, pit->iLen
                 , (pit->bAnchor ? "Anchor" : "Data")
                );
		if (FAILED(hr))
			OutputError(hr, IDS_SAFE_PRINTF);
        OutputDebugString(X_msg);
        if (pit->pitNext->pitPrev != pit)
            OutputDebugString(" Next Prev error!!");
        if (pit->pitPrev->pitNext != pit)
            OutputDebugString(" Prev Next error!!");
        OutputDebugString("\n");
        pit = pit->pitNext;
    } while (pit!=lst);
    OutputDebugString("End of list dump\n");
}
void
list_Free(
         PBLOCK pBlock,
         LPVOID p
         )
{
    HANDLE hMem;
	HRESULT hr;

    EnterCriticalSection(&CritSec);
    --pBlock->iInUse;
    if (pBlock->iInUse<=0) {if (pBlock->iInUse<0) {
			hr = StringCchPrintf(msg, sizeof(msg),"List block allocation negative (%d)", pBlock->iInUse);
			if (FAILED(hr))
				OutputError(hr, IDS_SAFE_PRINTF);
            TRACE_ERROR(msg, FALSE);
        }
        if (pCurrent==pBlock) pCurrent = pBlock->PrevBlock; /* defend the invariant */
        /* loop it out of the chain */
        if (pBlock->PrevBlock!=NULL) pBlock->PrevBlock->NextBlock = pBlock->NextBlock;
        if (pBlock->NextBlock!=NULL) pBlock->NextBlock->PrevBlock = pBlock->PrevBlock;
        hMem = pBlock->hMem;
        HeapFree(GetProcessHeap(), NULL, hMem);
    }
    LeaveCriticalSection(&CritSec);
}
Exemple #9
0
void NativeFile::set(Offset at, Byte const *values, Size count)
{
    DENG2_GUARD(this);

    QFile &out = output();
    if (at > size())
    {
        /// @throw IByteArray::OffsetError  @a at specified a position beyond the
        /// end of the file.
        throw OffsetError("NativeFile::set", "Cannot write past end of file");
    }
    out.seek(at);
    out.write(reinterpret_cast<char const *>(values), count);
    if (out.error() != QFile::NoError)
    {
        /// @throw OutputError  Failure to write to the native file.
        throw OutputError("NativeFile::set", "Error writing to file:" +
                          out.errorString());
    }
    // Update status.
    Status st = status();
    st.size = max(st.size, at + count);
    st.modifiedAt = Time();
    setStatus(st);
}
Exemple #10
0
void Matchmaker::GetMOTD()
{
#ifdef DLLSAMPLE
	WONIPAddress proxyServer;
	WONIPAddressSetFromStringAndPort(&proxyServer, ADDR_MOTDSERVER, PORT_MOTDSERVER);
	WONError aError = WONHTTPGetFile(&proxyServer, ADDR_MOTDSERVER, PORT_MOTDSERVER, "/motd/sample/motd.txt", "motd.txt", NULL, NULL, TRUE, NULL, NULL, gRequestTimeout);
#else
	Error aError = HTTPGet(ADDR_MOTDSERVER, PORT_MOTDSERVER, "/motd/sample/motd.txt", "motd.txt", NULL, NULL, true, NULL, NULL, gRequestTimeout, false);
#endif // DLLSAMPLE

	switch (aError)
	{
		case StatusCommon_Success:
		{
			struct stat aStatStruct;
			stat("motd.txt", &aStatStruct);
			char timebuf[22];
			strftime(timebuf, 22, "%b %d, %Y %H:%M:%S", localtime(&aStatStruct.st_mtime));
			OutputStringF("Message of the Day (%s)", timebuf);
			OutputFile("motd.txt");
			break;
		}
		default:
			OutputError("Failed to download Message of the Day", aError);
	}
}
//同步创建默认的Model资源
GameBuildList::Build *GameBuildList::LoadBuild(WORD wID,bool bAsyn)
{
	Build *pBuild = NULL;
	char pszPath[MAX_PATH],szName[_MAX_PATH];
	_snprintf(pszPath,_MAX_PATH,"model\\build\\%1.1d\\%3.3d",(wID & 0xf000) >> 12 , wID & 0x0fff);	
	_snprintf(szName,_MAX_PATH,"%s\\build",pszPath);
	if (! CClientResource::GetInstance()->IsFileExist(szName) )
	{
		OutputError("error:建筑文件不存在 \"%s\"\n",szName);
		MessageBox(NULL,szName,"错误:建筑文件不存在",MB_OK);
		return pBuild;
	}
	pBuild = new Build();
	pBuild->SetLoadState(Load_Not);
	pBuild->SetFilePath(pszPath);
	if(bAsyn)
	{
		rfAsynOpen(szName,ReadBuilCallBack,(void*)wID);
		pBuild->SetLoadState(Load_Doing);
	}
	else
	{
		CRFile *pFile = rfOpen(szName);
		if(pFile)
		{
			pBuild->Create(pFile,false);
			rfClose(pFile);
		}
		pBuild->SetLoadState(Load_Did);
	}
	return pBuild;
}
Exemple #12
0
int _tmain(int argc, _TCHAR* argv[])
{
    g_isConsoleApp = IsConsoleApp();

    g_argc = argc;
    g_argv = argv;

    if (g_isConsoleApp == TRUE)
    {
        return ServiceExecutionThread(NULL);
    }
    else
    {
        SERVICE_TABLE_ENTRY serviceTable[] =
        {
            { SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain },
            { NULL, NULL }
        };

        BOOL success;
        success = StartServiceCtrlDispatcher(serviceTable);
        if (!success)
        {
            OutputError(L"StartServiceCtrlDispatcher fails! (%d)", GetLastError());
        }
    }
}
Exemple #13
0
double RNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Evaluate(const arma::mat& /* unused */,
            const size_t i,
            const bool deterministic)
{
  this->deterministic = deterministic;

  arma::mat input = arma::mat(predictors.colptr(i), predictors.n_rows,
      1, false, true);
  arma::mat target = arma::mat(responses.colptr(i), responses.n_rows,
      1, false, true);

  // Initialize the activation storage only once.
  if (activations.empty())
    InitLayer(input, target, network);

  double networkError = 0;
  seqLen = input.n_rows / inputSize;
  ResetParameter(network);

  error = arma::mat(outputSize, outputSize < target.n_elem ? seqLen : 1);

  // Iterate through the input sequence and perform the feed forward pass.
  for (seqNum = 0; seqNum < seqLen; seqNum++)
  {
    // Perform the forward pass and save the activations.
    Forward(input.rows(seqNum * inputSize, (seqNum + 1) * inputSize - 1),
        network);
    SaveActivations(network);

    // Retrieve output error of the subsequence.
    if (seqOutput)
    {
      arma::mat seqError = error.unsafe_col(seqNum);
      arma::mat seqTarget = target.submat(seqNum * outputSize, 0,
          (seqNum + 1) * outputSize - 1, 0);
      networkError += OutputError(seqTarget, seqError, network);
    }
  }

  // Retrieve output error of the complete sequence.
  if (!seqOutput)
    return OutputError(target, error, network);

  return networkError;
}
Exemple #14
0
void FireRestartCommand()
{
    if (g_isConsoleApp == false)
    {
        return;
    }

    if (g_modulePath.size() == 0)
    {
        OutputError(L"No modulePath");
        return;
    }

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

#if defined(_WIN64)
    int platformId = 64;
#else
    int platformId = 32;
#endif

    wchar_t filePath[_MAX_PATH];
    HRESULT hr = StringCchPrintf(filePath, _MAX_PATH, L"%sic%d.exe", g_modulePath.c_str(), platformId);
    if (FAILED(hr) == TRUE)
    {
        OutputError(L"Error in composing file path");
        return;
    }

    wchar_t restartCmd[] = L"-restart";
    if (::CreateProcess(filePath, restartCmd, NULL, NULL, FALSE,
        0, NULL, NULL, &si, &pi) == 0)
    {
        OutputError(L"FAIL: %s %s", filePath, restartCmd);
        return;
    }
}
DWORD
mmGetProfileString(
    LPCTSTR appname,
    LPCTSTR valuename,
    LPCTSTR pDefault,
    LPTSTR pResult,
    int cbResult
)
{
    DWORD dwType;
    BOOL fCloseKey;
	HRESULT hr;

    HKEY key = GetKey(appname, &fCloseKey, FALSE);

    if (key) {

        cbResult = cbResult * sizeof(TCHAR);
        if (RegQueryValueEx(
            key,
            (LPTSTR)valuename,
            NULL,
            &dwType,
            (LPBYTE)pResult,
            (LPDWORD)&cbResult) == ERROR_SUCCESS) {

                if (dwType == REG_SZ) {
                    // cbResult is set to the size including null
                    // we return the number of characters

                    // close key if we did not cache it
                    if (fCloseKey) {
                        RegCloseKey(key);
                    }
                    return(cbResult/sizeof(TCHAR) - 1);
                }
        }

        // close open key if we did not cache it
        if (fCloseKey) {
            RegCloseKey(key);
        }
    }

    // if we got here, we didn't find it, or it was the wrong type - return
    // the default string
    hr = StringCchCopy(pResult, cbResult, pDefault);
	if (FAILED(hr)) {
		OutputError(hr, IDS_SAFE_COPY);
		return NULL;
	}
    return(lstrlen(pDefault));
}
/* Dump hex representation of handle to debugger */
void
APIENTRY
List_Show(
         LIST lst
         )
{
    char X_msg[50] = {0};    
	HRESULT hr = StringCchPrintf(X_msg, sizeof(X_msg)-1, "%p", lst);
	if (FAILED(hr))
		OutputError(hr, IDS_SAFE_PRINTF);
    OutputDebugString(X_msg);
}
Exemple #17
0
bool CUSBDevice::ConnectDevice()//, HIDP_CAPS Capabilities)
{

	if(m_hDevice != INVALID_HANDLE_VALUE)
	{
		//port is apparently already openned, abort this operation
		TRACE("openPort called with non INVALID_HANDLE_VALUE value for USB port handle\n");
		return false;
	}
	ResetEvent(m_rxOv.hEvent);
	ResetEvent(m_txOv.hEvent);
	ResetEvent(m_hTxUpdateEvent);

	m_hDevice = CreateFile(m_pPath,
					GENERIC_WRITE | GENERIC_READ, 
					FILE_SHARE_READ | FILE_SHARE_WRITE,
					NULL, 
					OPEN_EXISTING,
					FILE_FLAG_OVERLAPPED,
					NULL);

	if (m_hDevice == INVALID_HANDLE_VALUE)
   	{
		// error opening port; abort
		
		OutputError("Error connecting to USB device, ",GetLastError());
		return false;
	}
	else
	{
		TRACE("Successfully opened port %s\n",m_pPath);
	}
	m_bConnected = true;
	if(!(m_rxThread = AfxBeginThread(USBThreadRxFunc, new USBmessage(this, 0, m_serialNumString))))
	{
		TRACE("Unable to start helper rx thread\n");
		CloseDevice();
		//PrivateClosePort();
		return FALSE;
	}
	m_rxThread->m_bAutoDelete=false;
	TRACE("Rx Thread started\n");
	if(!(m_txThread = AfxBeginThread(USBThreadTxFunc, new USBmessage(this, 0, m_serialNumString))))
	{
		TRACE("Unable to start helper tx thread\n");
		CloseDevice();
		return FALSE;
	}
	m_txThread->m_bAutoDelete=false;
	TRACE("Tx Thread started\n");
	
	return TRUE;
}
static HKEY GetKeyA(LPCSTR appname, BOOL * closekey, BOOL fCreate)
{
    HKEY key = 0;
    char achName[MAX_PATH];
	HRESULT hr;
#if !MMPROFILECACHE
    *closekey = TRUE;
#else
    UINT n;
    ATOM atm;

    *closekey = FALSE;
    //
    // See if we have already used this key
    //
    atm = FindAtomA(appname);

    if (atm != 0) {
	// Atom exists... search the table for it.
        for (n=0; n<keyscached; ++n) {
            if (akeyatoms[n] == atm) {
                DPF2(("Found existing key for %s\n", appname));
                return ahkey[n];
            }
        }
    }
    DPF2(("No key found for %s", appname));
#endif

    hr = StringCchCopyA(achName, MAX_PATH, KEYNAMEA);
	if (FAILED(hr))
		OutputError(hr, IDS_SAFE_COPY);

    if ((!fCreate && RegOpenKeyA(ROOTKEY, achName, &key) == ERROR_SUCCESS)
        || (fCreate && RegCreateKeyA(ROOTKEY, achName, &key) == ERROR_SUCCESS)) {
#if MMPROFILECACHE
        if ((keyscached < KEYSCACHED)
	  && (atm = AddAtomA(appname))) {
            // Add this key to the cache array
            akeyatoms[keyscached] = atm;
            ahkey[keyscached] = key;
            DPF1(("Adding key %s to cache array in position %d\n", appname, keyscached));
            ++keyscached;
        } else {
            DPF2(("Not adding key %s to cache array\n", appname));
            *closekey = TRUE;
        }
#endif
    }

    return(key);
}
Exemple #19
0
void Matchmaker::CreateWONAccount(const char* theUserName, const char* thePassword)
{
#ifdef DLLSAMPLE
	WONError aError;
	if (mAuthH) { WONAuthCloseHandle(mAuthH); mAuthH = NULL; }
	mAuthH = WONAuthLoginNewAccountA(&aError, mAuthServers, mNumAuthServers, theUserName, COMMUNITY_SAMPLE, thePassword, "", gRequestTimeout);
#else
	mIdentity = Identity(theUserName, COMMUNITY_SAMPLE, thePassword, "", mAuthServers, mNumAuthServers);
	Error aError = mIdentity.AuthenticateNewAccount(gRequestTimeout);
#endif // DLLSAMPLE

	switch (aError)
	{
		case StatusCommon_Success:
			OutputError("Successfully created new account and logged in");

#ifdef DLLSAMPLE
			WONProfileCreate(mAuthH, mProfileServers, mNumProfileServers, "*****@*****.**", gRequestTimeout);
#else
			CreateProfile(&mIdentity, mProfileServers, mNumProfileServers, "*****@*****.**", gRequestTimeout);
#endif

			ListRooms();
			break;
		case StatusAuth_CDKeyInUse:
			OutputError("CD key is already in use");
			break;
		case StatusAuth_CRCFailed:
			OutputError("Invalid version of game");
			break;
		case StatusAuth_UserExists:
			OutputError("User already exists");
			break;
		default:
			OutputError("Account creation failed!", aError);
			break;
	}
}
Exemple #20
0
double CNN<
LayerTypes, OutputLayerType, InitializationRuleType, PerformanceFunction
>::Evaluate(const arma::mat& /* unused */,
            const size_t i,
            const bool deterministic)
{
  this->deterministic = deterministic;

  ResetParameter(network);
  Forward(predictors.slices(i, (i + 1) * sampleSize - 1), network);

  return OutputError(arma::mat(responses.colptr(i), responses.n_rows, 1, false,
      true), error, network);
}
bool IfConversionPass2::ConvertIf(IfStatement* toConvert)
{
  // First, verify that this if statement is in the correct format or not

  if (!VerifyIf(toConvert))
  {
    return false ;
  }

  // This should be in the right format, but I need to decide what to do
  Statement* thenPart = toConvert->get_then_part() ;
  Statement* elsePart = toConvert->get_else_part() ;
  thenPart = Denormalize(thenPart) ;
  elsePart = Denormalize(elsePart) ;
  
  if (dynamic_cast<StoreVariableStatement*>(thenPart) != NULL && 
      dynamic_cast<StoreVariableStatement*>(elsePart) != NULL)
  {
    return ConvertStoreVariableIf(toConvert) ;
  }
  else if (dynamic_cast<StoreStatement*>(thenPart) != NULL)
  {
    return ConvertStoreIf(toConvert) ;
  } 
  else if (dynamic_cast<CallStatement*>(thenPart) != NULL &&
	   dynamic_cast<CallStatement*>(elsePart) != NULL)
  {
    return ConvertCallsIf(toConvert) ;
  }
  else if (dynamic_cast<CallStatement*>(thenPart) != NULL &&
	   dynamic_cast<StoreVariableStatement*>(elsePart) != NULL)
  {
    return ConvertCallStoreVarIf(toConvert) ;
  }
  else if (dynamic_cast<StoreVariableStatement*>(thenPart) != NULL &&
	   dynamic_cast<CallStatement*>(elsePart) != NULL)
  {
    return ConvertStoreVarCall(toConvert) ;
  }
  else
  {
    OutputError("Unknown if format caused a problem!") ;
    FormattedText tmpText ;
    toConvert->print(tmpText) ;
    std::cout << tmpText.get_value() << std::endl ;
    assert(0) ;
  }
  return false ;
}
/**
* Função que obtém o erro médio quadrático de um conjunto de amostras fornecido.
*/
int BKPNeuralNet::RMS_error( float**inMatrix, float **outMatrix, int inSize, int outSize, int nSamples, float* retRMS_Error )
{
  // Casos de retorno:
  if( (!inMatrix) || (!outMatrix) || (inSize!=_nLayers[0]) || (_nLayers[_layers-1]!=outSize) )
    return -1;

  float thisOutput = 0;  
  float RMS_Error_Acum = 0;
  // Executando os treinamentos obrigatórios:
  for( int thisSample=0 ; thisSample<nSamples ; thisSample++ )
  {
    Use( inSize, inMatrix[thisSample] );
    thisOutput += OutputError(outMatrix[thisSample], outSize);
  }
  *retRMS_Error = (thisOutput/nSamples);
  return 0;
}
///////////////////////////////////////////////////////////////////////////////
//    RESUME SCRIPT
//    Runs or resumes a Lua script.  Executes until a yield is encountered or
//    the script terminates.
//
//    The parameter to this function is pushed on the stack as the return value
//    of the previous yield.
///////////////////////////////////////////////////////////////////////////////
void CLuaScript::ResumeScript(float param)
{
	int status;

    // we're about to run/resume the thread, so set the global
    m_State  = LSS_RUNNING;

    // param is treated as a return value from the function that yielded
    lua_pushnumber(m_pThreadState, param);

    status = lua_resume(m_pThreadState, 1);

    if (status)
	{
        FormatError();
        OutputError("Runtime Error:");
	}
}
Exemple #24
0
/* ------------------------------------------------------------------------------------------------
 * Flush queued messages to the console output.
*/
void FlushMessages()
{
    // Acquire a global lock
    std::lock_guard< std::mutex > lock(g_Mutex);
    // Output any queued messages
    while (!g_Messages.empty())
    {
        // Identify the message type and send it
        if (g_Messages.front().second)
        {
            OutputMessage("%s", g_Messages.front().first.c_str());
        }
        else
        {
            OutputError("%s", g_Messages.front().first.c_str());
        }
        // Pop the message from the queue
        g_Messages.pop();
    }
}
BOOL GameSkybox::Create(DWORD ModelID)
{
	m_dwModelID = 0;
	// 从文件读取图像数据
	char pszFileName[_MAX_PATH];
	sprintf(pszFileName,"model/skybox/%03d/model", ModelID);
	CGameModelManager* pModelManager = CGameModelManager::GetInstance();
	string strTempt(pszFileName);
	CheckRFileStr(strTempt);
	bool bFlag = CClientResource::GetInstance()->IsFileExist(strTempt.c_str());
	if(bFlag==false)
	{
		bFlag = CheckFile(pszFileName);
	}
	if (!bFlag)
	{
		char strError[512]="";
		sprintf(strError,"model file(%s) not exist。",pszFileName);
		PutDebugString(strError);
		OutputError("Model ID : skybox %d not exist。",ModelID);
		return FALSE;
	}
	m_dwModelID = ModelID;
	if(m_pDisplayModel)
	{
		//如果相同则退出
		if(m_pDisplayModel->GetGameModelID() ==
			pModelManager->GetGameModelID(pszFileName))
			return TRUE;
	}
	//释放
	pModelManager->ReleaseDisplayModel(m_pDisplayModel);
	//创建
	m_pDisplayModel = pModelManager->CreateDisplayModel(pszFileName,false);

	m_pDisplayModel->ShowAllGroup(false);



	return TRUE;
}
		bool Lua::Loadfile(const string& _strFileName, LuaStatePtr _pState)
		{
			FilePtr pFile = FS::GetRoot()->OpenFile(_strFileName, FS::EOpenMode_READTEXT);
			bool bResult = (NULL != pFile);
			if (false != bResult)
			{
				int sSize = pFile->Size();
				char* pSourceCode = new char[sSize + 1];
				sSize = pFile->Read(pSourceCode, sSize);
				FS::GetRoot()->CloseFile(pFile);
				pSourceCode[sSize] = '\0';
				_pState = (NULL == _pState) ? s_pState : _pState;
				const int sResult = _pState->DoString(pSourceCode);
				bResult = (0 == sResult);
				delete[] pSourceCode;
				if (false == bResult)
				{
					OutputError(sResult, _pState);
				}
			}
			return bResult;
		}
bool IfConversionPass2::ConvertStoreIf(IfStatement* toConvert)
{
  Statement* thenPart = Denormalize(toConvert->get_then_part()) ;
  StoreStatement* thenStore = dynamic_cast<StoreStatement*>(thenPart) ;
  assert(thenStore != NULL) ;

  Expression* destination = thenStore->get_destination_address() ;
  
  if (dynamic_cast<FieldAccessExpression*>(destination) != NULL)
  {
    return ConvertStructStoreIf(toConvert) ;    
  }
  else if (dynamic_cast<ArrayReferenceExpression*>(destination) != NULL)
  {
    return ConvertArrayStoreIf(toConvert) ;
  }
  else
  {
    OutputError("Unsupported if detected!") ;
    assert(0) ;
    return false ; // To avoid a warning
  }  
}
void ScalarReplacementPass2::VerifyArrayReferences()
{
  assert(procDef != NULL) ;
  ClearArrayIndicies() ;
  list<ArrayReferenceExpression*>* allRefs = 
    collect_objects<ArrayReferenceExpression>(procDef->get_body()) ;
  list<ArrayReferenceExpression*>::iterator refIter = allRefs->begin() ;
  while (refIter != allRefs->end())
  {
    // If not the topmost array reference, skip it
    if (dynamic_cast<ArrayReferenceExpression*>((*refIter)->get_parent()) != NULL)
    {
      ++refIter ;
      continue ;
    }
    VariableSymbol* currentArrayVar = GetArrayVariable(*refIter) ;
    // Don't process lookup tables
    if (IsLookupTable(currentArrayVar))
    {
      ++refIter ;
      continue ;
    }
    if (arrayIndicies[currentArrayVar] == NULL)
    {
      arrayIndicies[currentArrayVar] = UsedIndicies(*refIter) ;
    }
    else
    {
      list<VariableSymbol*>* approvedIndicies = arrayIndicies[currentArrayVar];
      assert(approvedIndicies != NULL) ;
      list<VariableSymbol*>* usedIndicies = UsedIndicies(*refIter) ;
      list<VariableSymbol*>::iterator usedIter = usedIndicies->begin() ;
      while (usedIter != usedIndicies->end())
      {
	bool approved = false ;
	list<VariableSymbol*>::iterator approvedIter = 
	  approvedIndicies->begin() ;
	while (approvedIter != approvedIndicies->end())
	{
	  if (*approvedIter == *usedIter)
	  {
	    approved = true ;
	    break ;
	  }
	  ++approvedIter ;
	}
	if (approved == false)
	{
	  OutputError("Error: You cannot access a stream with different index"
		      " variables!") ;
	  assert(0) ;
	}
	++usedIter ;
      }
      delete usedIndicies ;
    }
    ++refIter ;
  }
  delete allRefs ;
  ClearArrayIndicies() ;
}
Exemple #29
0
void Matchmaker::GetTitanServerList()
{
#ifdef DLLSAMPLE
	mNewAuthServers.clear();
	mNewContestServers.clear();
	mNewEventServers.clear();
	mNewFirewallServers.clear();
	mNewProfileServers.clear();
	
	HWONDATAOBJECT aDataObjectH = WONDataObjectCreate(OBJ_VALIDVERSIONS.c_str(), OBJ_VALIDVERSIONS.size(), NULL, 0);
	WONError aError = WONDirGetDirectoryW(NULL, mDirServers, mNumDirServers,
	                                      DIR_TITANSERVER, NULL, NULL,
	                                      WONDir_GF_DECOMPROOT | WONDir_GF_DECOMPRECURSIVE | WONDir_GF_DECOMPSERVICES | WONDir_GF_ADDTYPE | WONDir_GF_SERVADDNAME | WONDir_GF_SERVADDNETADDR | WONDir_GF_ADDDOTYPE | WONDir_GF_ADDDODATA,
	                                      &aDataObjectH, 1, TitanServerEntityCallback, this, gRequestTimeout);

	CopySTLAddressListToArray(mNewAuthServers,     &mAuthServers,     &mNumAuthServers);
	CopySTLAddressListToArray(mNewContestServers,  &mContestServers,  &mNumContestServers);
	CopySTLAddressListToArray(mNewEventServers,    &mEventServers,    &mNumEventServers);
	CopySTLAddressListToArray(mNewFirewallServers, &mFirewallServers, &mNumFirewallServers);
	CopySTLAddressListToArray(mNewProfileServers,  &mProfileServers,  &mNumProfileServers);
#else
	DataObjectTypeSet aDataObjectSet;
	aDataObjectSet.insert(WONCommon::DataObject(OBJ_VALIDVERSIONS));
	WONMsg::DirEntityList entityList;
	Error aError = GetDirectory(NULL, // no identity needed to get TitanServers (after all, the AuthServers are listed in there)
								mDirServers, mNumDirServers,
								NULL,
								DIR_TITANSERVER, 
								&entityList,
								WONMsg::GF_DECOMPROOT | WONMsg::GF_DECOMPRECURSIVE | WONMsg::GF_DECOMPSERVICES | WONMsg::GF_ADDTYPE | WONMsg::GF_SERVADDNAME | WONMsg::GF_SERVADDNETADDR | WONMsg::GF_ADDDOTYPE | WONMsg::GF_ADDDODATA,
								aDataObjectSet,
								0, 0,
								gRequestTimeout);

	switch(aError) 
	{
		case Error_Success:
		{
			delete[] mAuthServers; mNumAuthServers = 0;
			mAuthServers = new IPSocket::Address[entityList.size()];
			delete[] mContestServers; mNumContestServers = 0;
			mContestServers = new IPSocket::Address[entityList.size()];
			delete[] mEventServers; mNumEventServers = 0;
			mEventServers = new IPSocket::Address[entityList.size()];
			delete[] mFirewallServers; mNumFirewallServers = 0;
			mFirewallServers = new IPSocket::Address[entityList.size()];
			delete[] mProfileServers; mNumProfileServers = 0;
			mProfileServers = new IPSocket::Address[entityList.size()];

			DirEntityList::const_iterator aDirEntityListItr = entityList.begin();
			for( ; aDirEntityListItr != entityList.end(); ++aDirEntityListItr)
			{
				if (aDirEntityListItr->mType == WONMsg::DirEntity::ET_DIRECTORY)
				{
					DataObjectTypeSet::const_iterator aDataObjectSetItr = aDirEntityListItr->mDataObjects.begin();
					for( ; aDataObjectSetItr != aDirEntityListItr->mDataObjects.end(); ++aDataObjectSetItr)
					{
						if (aDataObjectSetItr->GetDataType() == OBJ_VALIDVERSIONS)
							mValidVersions = reinterpret_cast<const char*>(aDataObjectSetItr->GetData().c_str());
					}
				}
				else if (aDirEntityListItr->mName == SERVERNAME_AUTH)
					mAuthServers[mNumAuthServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_CONTEST)
					mContestServers[mNumContestServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_EVENT)
					mEventServers[mNumEventServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_FIREWALL)
					mFirewallServers[mNumFirewallServers++] = IPSocket::Address(*aDirEntityListItr);
				else if (aDirEntityListItr->mName == SERVERNAME_PROFILE)
					mProfileServers[mNumProfileServers++] = IPSocket::Address(*aDirEntityListItr);
			}
			break;
		}

		case StatusDir_DirNotFound:
			OutputError("Directory containing Titan servers not found");
			break;
		default:
			OutputError("Failed to get list of Titan servers!", aError);
			break;
	}
#endif // DLLSAMPLE
}
/*
 * return the text associated with a given column of a given row.
 * Return a pointer that does not need to be freed after use - ie
 * a pointer into our data somewhere, not a copy
 */
LPSTR
view_gettext(VIEW view, long row, int col)
{
    int line;
    int state;
    LPSTR pstr;
    HRESULT hr;

    pstr = NULL;   /* kill spurious diagnostic */
    if (view == NULL) {
        return(NULL);
    }

    ViewEnter();

    if ((0 > row) || (row >= view->rows)) {
        ViewLeave();
        return(NULL);
    }

    if (view->bExpand) {
        /* we are in expand mode */

        state = section_getstate(view->pLines[row].section);

        switch (col) {
        case 0:
            /* row nr */

            /* line numbers can be from either original file
             * this is a menu-selectable option
             */
            line = 0;
            switch (line_numbers) {
            case IDM_NONRS:
                pstr = NULL;
                break;

            case IDM_LNRS:
                line = view->pLines[row].nr_left;
                if (state == STATE_MOVEDRIGHT
                    || state == STATE_SIMILARRIGHT) {
                    line = -line;
                }
                break;

            case IDM_RNRS:
                line = view->pLines[row].nr_right;
                if (state == STATE_MOVEDLEFT
                    || state == STATE_SIMILARLEFT) {
                    line = -line;
                }
                break;
            }
            if (line == 0) {
                ViewLeave();
                return(NULL);
            }

            if (line < 0) {
                /* lines that are moved appear twice.
                 * show the correct-sequence line nr
                 * for the out-of-seq. copy in brackets.
                 */
                hr = StringCchPrintf(view->nrtext, 12, "(%d)", abs(line));
                if (FAILED(hr)) {
                    OutputError(hr, IDS_SAFE_PRINTF);
                    return(NULL);
                }

            } else {
                hr = StringCchPrintf(view->nrtext, 12, "%d", line);
                if (FAILED(hr)) {
                    OutputError(hr, IDS_SAFE_PRINTF);
                    return(NULL);
                }
            }
            pstr = view->nrtext;
            break;

        case 1:
            /* tag text - represents the state of the line */


            switch (state) {
            case STATE_SAME:
                pstr = "    ";
                break;

            case STATE_LEFTONLY:
            case STATE_SIMILARLEFT:
                pstr = " <! ";
                break;

            case STATE_RIGHTONLY:
            case STATE_SIMILARRIGHT:
                pstr = " !> ";
                break;

            case STATE_MOVEDLEFT:
                pstr = " <- ";
                break;

            case STATE_MOVEDRIGHT:
                pstr = " -> ";
                break;
            }
            break;

        case 2:
            /* main text - line */
            pstr = line_gettext(view->pLines[row].line);
            break;
        }
    } else {
        /* outline mode */
        switch (col) {
        case 0:
            /* row number - just the line number */
            hr = StringCchPrintf(view->nrtext, 12, "%d", row+1);
            if (FAILED(hr)) {
                OutputError(hr, IDS_SAFE_PRINTF);
                return(NULL);
            }
            pstr = view->nrtext;
            break;

        case 1:
            /* tag */
            pstr = compitem_gettext_tag(view->pItems[row]);
            break;

        case 2:
            /* result text */
            pstr = compitem_gettext_result(view->pItems[row]);
            break;
        }
    }
    ViewLeave();
    return(pstr);
}