hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
0ab0e4296c8448eed643b8b691d1ad461c57b101
677
cpp
C++
Arrays/Rearrange the array in alternating positive and negative items.cpp
akshay-thummar/DSA-Busted
8194411555d978bcf9bd66f9e0da5e502a94a493
[ "MIT" ]
17
2021-12-03T14:29:01.000Z
2022-03-09T18:25:05.000Z
Arrays/Rearrange the array in alternating positive and negative items.cpp
riti2409/DSA-Busted
8194411555d978bcf9bd66f9e0da5e502a94a493
[ "MIT" ]
null
null
null
Arrays/Rearrange the array in alternating positive and negative items.cpp
riti2409/DSA-Busted
8194411555d978bcf9bd66f9e0da5e502a94a493
[ "MIT" ]
4
2022-01-29T14:03:48.000Z
2022-03-01T22:53:41.000Z
#include <bits/stdc++.h> using namespace std; void rearrange(int arr[], int n) { int i = -1, j = n; while (i < j) { while(i <= n - 1 and arr[i] > 0) i += 1; while (j >= 0 and arr[j] < 0) j -= 1; if (i < j) swap(arr[i], arr[j]); } if (i == 0 || i == n) return; int k = 0; while (k < n && i < n) { swap(arr[k], arr[i]); i = i + 1; k = k + 2; } } // Utility function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {2, 3, -4, -1, 6, -9}; int n = 6; cout << "Given array is \n"; printArray(arr, n); rearrange(arr, n); return 0; }
13.019231
37
0.472674
0ab16f352baed697459b0e8a44486f9a280441e2
34,465
cxx
C++
com/ole32/dcomss/olescm/launch.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/dcomss/olescm/launch.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/dcomss/olescm/launch.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1997. // // File: launch.cxx // // Contents: // // History: ?-??-?? ??? Created // 6-17-99 a-sergiv Added event log filtering // //-------------------------------------------------------------------------- #include "act.hxx" #include <winbasep.h> // For CreateProcessInternalW extern "C" { #include <execsrv.h> } #include "execclt.hxx" const ULONG MAX_SERVICE_ARGS = 16; const WCHAR REGEVENT_PREFIX[] = L"RPCSS_REGEVENT:"; const DWORD REGEVENT_PREFIX_STRLEN = sizeof(REGEVENT_PREFIX) / sizeof(WCHAR) - 1; const WCHAR INITEVENT_PREFIX[] = L"RPCSS_INITEVENT:"; const DWORD INITEVENT_PREFIX_STRLEN = sizeof(INITEVENT_PREFIX) / sizeof(WCHAR) - 1; HRESULT CClsidData::GetAAASaferToken( IN CToken *pClientToken, OUT HANDLE *pTokenOut ) /*++ Routine Description: Get the token that will be used in an Activate As Activator launch. This token is the more restricted of the incoming token and the configured safer level. Arguments: pClientToken - token of the user doing the activation pTokenOut - out parameter that will recieve the handle to use in the activation. Return Value: S_OK: Everything went fine. The caller owns a reference on pTokenOut and must close it. S_FALSE: Everything went fine. The caller does not own a reference on pToken out and does not need to close it. Anything else: An error occured. --*/ { HANDLE hSaferToken = NULL; HRESULT hr = S_OK; BOOL bStatus = TRUE; *pTokenOut = NULL; ASSERT(SaferLevel() && "Called GetAAASaferToken with SAFER disabled!"); if (!SaferLevel()) return E_UNEXPECTED; // Get the safer token for this configuration. bStatus = SaferComputeTokenFromLevel(SaferLevel(), pClientToken->GetToken(), &hSaferToken, 0, NULL); if (bStatus) { hr = pClientToken->CompareSaferLevels(hSaferToken); if (hr == S_OK) { CloseHandle(hSaferToken); hSaferToken = pClientToken->GetToken(); // Shared reference, return S_FALSE. hr = S_FALSE; } else { hr = S_OK; } } else { hr = HRESULT_FROM_WIN32(GetLastError()); } *pTokenOut = hSaferToken; return hr; } HRESULT CClsidData::LaunchActivatorServer( IN CToken * pClientToken, IN WCHAR * pEnvBlock, IN DWORD EnvBlockLength, IN BOOL fIsRemoteActivation, IN BOOL fClientImpersonating, IN WCHAR* pwszWinstaDesktop, IN DWORD clsctx, OUT HANDLE * phProcess, OUT DWORD * pdwProcessId ) { WCHAR * pwszCommandLine; WCHAR * pFinalEnvBlock; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo; SECURITY_ATTRIBUTES saProcess; PSECURITY_DESCRIPTOR psdNewProcessSD; HRESULT hr; DWORD CreateFlags; BOOL bStatus = FALSE; ULONG SessionId = 0; HANDLE hSaferToken = NULL; BOOL bCloseSaferToken = TRUE; *phProcess = NULL; *pdwProcessId = 0; if ( ! pClientToken ) return (E_ACCESSDENIED); pFinalEnvBlock = NULL; StartupInfo.cb = sizeof(StartupInfo); StartupInfo.lpReserved = NULL; // Choose desktop for new server: // client remote -> system chooses desktop // client local, not impersonating -> we pick client's desktop // client local, impersonating -> system chooses desktop StartupInfo.lpDesktop = (fIsRemoteActivation || fClientImpersonating) ? L"" : pwszWinstaDesktop; StartupInfo.lpTitle = (SERVERTYPE_SURROGATE == _ServerType) ? NULL : _pwszServer; StartupInfo.dwX = 40; StartupInfo.dwY = 40; StartupInfo.dwXSize = 80; StartupInfo.dwYSize = 40; StartupInfo.dwFlags = 0; StartupInfo.wShowWindow = SW_SHOWNORMAL; StartupInfo.cbReserved2 = 0; StartupInfo.lpReserved2 = NULL; ProcessInfo.hThread = 0; ProcessInfo.hProcess = 0; ProcessInfo.dwProcessId = 0; hr = GetLaunchCommandLine( &pwszCommandLine ); if ( hr != S_OK ) return (hr); if ( pEnvBlock ) { hr = AddAppPathsToEnv( pEnvBlock, EnvBlockLength, &pFinalEnvBlock ); if ( hr != S_OK ) { PrivMemFree( pwszCommandLine ); return (hr); } } CreateFlags = CREATE_NEW_CONSOLE; if ( pFinalEnvBlock ) CreateFlags |= CREATE_UNICODE_ENVIRONMENT; CAccessInfo AccessInfo( pClientToken->GetSid() ); // // Apply configured safer restrictions to the token we're using to launch. // SAFER might not be enabled at all, in which case we don't need to do this. // if ( gbSAFERAAAChecksEnabled && SaferLevel() ) { hr = GetAAASaferToken( pClientToken, &hSaferToken ); if ( FAILED(hr) ) goto LaunchServerEnd; if ( hr == S_FALSE ) { // GetAAASaferToken has returned a shared reference // to pClientToken. bCloseSaferToken = FALSE; hr = S_OK; } else bCloseSaferToken = TRUE; } else { hSaferToken = pClientToken->GetToken(); bCloseSaferToken = FALSE; } // // This should never fail here, but if it did that would be a really, // really bad security breach, so check it anyway. // if ( ! ImpersonateLoggedOnUser( hSaferToken ) ) { hr = E_ACCESSDENIED; goto LaunchServerEnd; } // // Initialize process security info (SDs). We need both SIDs to // do this, so here is the 1st time we can. We Delete the SD right // after the CreateProcess call, no matter what happens. // psdNewProcessSD = AccessInfo.IdentifyAccess( FALSE, PROCESS_ALL_ACCESS, PROCESS_SET_INFORMATION | // Allow primary token to be set PROCESS_TERMINATE | SYNCHRONIZE // Allow screen-saver control ); if ( ! psdNewProcessSD ) { RevertToSelf(); hr = E_OUTOFMEMORY; goto LaunchServerEnd; } saProcess.nLength = sizeof(SECURITY_ATTRIBUTES); saProcess.lpSecurityDescriptor = psdNewProcessSD; saProcess.bInheritHandle = FALSE; SessionId = fIsRemoteActivation ? 0 : pClientToken->GetSessionId(); if( SessionId != 0 ) { // // We must send the request to the remote WinStation // of the requestor // // NOTE: The current WinStationCreateProcessW() does not use // the supplied security descriptor, but creates the // process under the account of the logged on user. // // We do not stuff the security descriptor, so clear the suspend flag #if DBGX CairoleDebugOut((DEB_TRACE, "SCM: Sending CreateProcess to SessionId %d\n",SessionId)); #endif // Non-zero sessions have only one winstation/desktop which is // the default one. We will ignore the winstation/desktop passed // in and use the default one. // review: Figure this out TarunA 05/07/99 //StartupInfo.lpDesktop = L"WinSta0\\Default"; // jsimmons 4/6/00 -- note that if the client was impersonating, then we won't // launch the server under the correct identity. More work needed to determine // if we can fully support this. // // Stop impersonating before doing the WinStationCreateProcess. // The remote winstation exec thread will launch the app under // the users context. We must not be impersonating because this // call only lets SYSTEM request the remote execute. // RevertToSelf(); HANDLE hDuplicate = NULL; // We need to pass in the SAFER blessed token to TS so that the // server can use that token // TS code will call CreateProcessAsUser, so we need to get a primary token if (DuplicateTokenForSessionUse(hSaferToken, &hDuplicate)) { if (bCloseSaferToken) { CloseHandle(hSaferToken); } hSaferToken = hDuplicate; bCloseSaferToken = TRUE; bStatus = CreateRemoteSessionProcess( SessionId, hSaferToken, FALSE, // Run as Logged on USER ServerExecutable(), // application name pwszCommandLine, // command line &saProcess, // process sec attributes NULL, // default thread sec attributes // (this was &saThread, but isn't needed) FALSE, // dont inherit handles CreateFlags, // creation flags pFinalEnvBlock, // use same enviroment block as the client NULL, // use same directory &StartupInfo, // startup info &ProcessInfo // proc info returned ); } } else { HANDLE hPrimary = NULL; if (DuplicateTokenAsPrimary(hSaferToken, pClientToken->GetSid(), &hPrimary)) { if (bCloseSaferToken) { CloseHandle(hSaferToken); } hSaferToken = hPrimary; bCloseSaferToken = TRUE; // // Do the exec while impersonating so the file access gets ACL // checked correctly. // // bStatus = CreateProcessAsUser( hSaferToken, ServerExecutable(), pwszCommandLine, &saProcess, NULL, FALSE, CreateFlags, pFinalEnvBlock, NULL, &StartupInfo, &ProcessInfo); } RevertToSelf(); } if ( ! bStatus ) { hr = HRESULT_FROM_WIN32( GetLastError() ); LogServerStartError( &_Clsid, clsctx, pClientToken, pwszCommandLine ); goto LaunchServerEnd; } LaunchServerEnd: if ( pFinalEnvBlock && pFinalEnvBlock != pEnvBlock ) PrivMemFree( pFinalEnvBlock ); if ( ProcessInfo.hThread ) CloseHandle( ProcessInfo.hThread ); if ( ProcessInfo.hProcess && ! bStatus ) { CloseHandle( ProcessInfo.hProcess ); ProcessInfo.hProcess = 0; } if ( hSaferToken && bCloseSaferToken ) { CloseHandle( hSaferToken ); } *phProcess = ProcessInfo.hProcess; *pdwProcessId = ProcessInfo.dwProcessId; PrivMemFree( pwszCommandLine ); return (hr); } //+------------------------------------------------------------------------- // // LaunchRunAsServer // //-------------------------------------------------------------------------- HRESULT CClsidData::LaunchRunAsServer( IN CToken * pClientToken, IN BOOL fIsRemoteActivation, IN ActivationPropertiesIn *pActIn, IN DWORD clsctx, OUT HANDLE * phProcess, OUT DWORD * pdwProcessId, OUT void** ppvRunAsHandle ) { WCHAR * pwszCommandLine; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo = {0}; HANDLE hToken; SECURITY_ATTRIBUTES saProcess; PSECURITY_DESCRIPTOR psdNewProcessSD; PSID psidUserSid; HRESULT hr; BOOL bStatus = FALSE; ULONG ulSessionId; BOOL bFromRunAsCache = FALSE; hr = GetLaunchCommandLine( &pwszCommandLine ); if ( hr != S_OK ) return (hr); *phProcess = NULL; *pdwProcessId = 0; hToken = NULL; bStatus = FALSE; StartupInfo.cb = sizeof(STARTUPINFO); StartupInfo.lpReserved = NULL; StartupInfo.lpDesktop = NULL; StartupInfo.lpTitle = (SERVERTYPE_SURROGATE == _ServerType) ? NULL : _pwszServer; StartupInfo.dwFlags = 0; StartupInfo.cbReserved2 = 0; StartupInfo.lpReserved2 = NULL; ulSessionId = 0; if( IsInteractiveUser() ) { if (!fIsRemoteActivation) { // This code seems to be saying, "if the client is local then I // should always be able to impersonate him". Which is true under // normal circumstances, but we have seen a case (stress machine // shutdowns) where the client is local but came in un-authenticated. if (!pClientToken) return E_ACCESSDENIED; if ( !ImpersonateLoggedOnUser( pClientToken->GetToken() ) ) { PrivMemFree(pwszCommandLine); return E_ACCESSDENIED; } RevertToSelf(); } ASSERT(pActIn); LONG lSessIdTemp; // Query for incoming session GetSessionIDFromActParams(pActIn, &lSessIdTemp); if (lSessIdTemp != INVALID_SESSION_ID) { ulSessionId = lSessIdTemp; } // Right now force all complus to // session 0. Session based activation // is still ill defined for complus // servers. if (_ServerType == SERVERTYPE_COMPLUS) { ulSessionId = 0; } hToken = GetUserTokenForSession(ulSessionId); } else { hToken = GetRunAsToken( clsctx, AppidString(), RunAsDomain(), RunAsUser(), TRUE); if (hToken) { hr = RunAsGetTokenElem(&hToken, ppvRunAsHandle); if (SUCCEEDED(hr)) bFromRunAsCache = TRUE; else { ASSERT((*ppvRunAsHandle == NULL) && "RunAsGetTokenElem failed but *ppvRunAsHandle is non-NULL"); PrivMemFree( pwszCommandLine ); CloseHandle(hToken); return hr; } } } if ( ! hToken ) { PrivMemFree( pwszCommandLine ); return (CO_E_RUNAS_LOGON_FAILURE); } psdNewProcessSD = 0; psidUserSid = GetUserSid(hToken); CAccessInfo AccessInfo(psidUserSid); // We have to get past the CAccessInfo before we can use a goto. if ( psidUserSid ) { psdNewProcessSD = AccessInfo.IdentifyAccess( FALSE, PROCESS_ALL_ACCESS, PROCESS_SET_INFORMATION | // Allow primary token to be set PROCESS_TERMINATE | SYNCHRONIZE // Allow screen-saver control ); } if ( ! psdNewProcessSD ) { hr = E_OUTOFMEMORY; goto LaunchRunAsServerEnd; } saProcess.nLength = sizeof(SECURITY_ATTRIBUTES); saProcess.lpSecurityDescriptor = psdNewProcessSD; saProcess.bInheritHandle = FALSE; { // // Get the environment block of the user // LPVOID lpEnvBlock = NULL; bStatus = CreateEnvironmentBlock(&lpEnvBlock, hToken, FALSE); HANDLE hSaferToken = NULL; if(bStatus && SaferLevel()) { bStatus = SaferComputeTokenFromLevel(SaferLevel(), hToken, &hSaferToken, 0, NULL); } else { hSaferToken = hToken; } if (bStatus && (ulSessionId != 0)) { bStatus = SetTokenInformation(hSaferToken, TokenSessionId, &ulSessionId, sizeof(ulSessionId)); } if(bStatus) { // // This allows the process create to work with paths to remote machines. // (void) ImpersonateLoggedOnUser( hSaferToken ); bStatus = CreateProcessAsUser(hSaferToken, ServerExecutable(), pwszCommandLine, &saProcess, NULL, FALSE, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, lpEnvBlock, NULL, &StartupInfo, &ProcessInfo); (void) RevertToSelf(); } // // Free the environment block buffer // if (lpEnvBlock) DestroyEnvironmentBlock(lpEnvBlock); if (hSaferToken && SaferLevel()) CloseHandle(hSaferToken); } if ( ! bStatus ) { hr = HRESULT_FROM_WIN32( GetLastError() ); LogRunAsServerStartError( &_Clsid, clsctx, pClientToken, pwszCommandLine, RunAsUser(), RunAsDomain() ); goto LaunchRunAsServerEnd; } *phProcess = ProcessInfo.hProcess; *pdwProcessId = ProcessInfo.dwProcessId; NtClose( ProcessInfo.hThread ); LaunchRunAsServerEnd: if ( hToken ) { NtClose( hToken ); } if ( psidUserSid ) { PrivMemFree(psidUserSid); } PrivMemFree( pwszCommandLine ); if (!bFromRunAsCache) *ppvRunAsHandle = NULL; else if (!SUCCEEDED(hr)) { RunAsRelease(*ppvRunAsHandle); *ppvRunAsHandle = NULL; } return (hr); } //+------------------------------------------------------------------------- // // Member: LaunchService // //-------------------------------------------------------------------------- HRESULT CClsidData::LaunchService( IN CToken * pClientToken, IN DWORD clsctx, OUT SC_HANDLE * phService ) { WCHAR *pwszArgs = NULL; ULONG cArgs = 0; WCHAR *apwszArgs[MAX_SERVICE_ARGS]; BOOL bStatus; HRESULT hr; ASSERT(g_hServiceController); *phService = OpenService( g_hServiceController, _pAppid->Service(), GENERIC_EXECUTE | GENERIC_READ ); if ( ! *phService ) return (HRESULT_FROM_WIN32( GetLastError() )); // Formulate the arguments (if any) if ( ServiceArgs() ) { UINT k = 0; // Make a copy of the service arguments pwszArgs = (WCHAR *) PrivMemAlloc( (lstrlenW(ServiceArgs()) + 1) * sizeof(WCHAR)); if ( pwszArgs == NULL ) { CloseServiceHandle(*phService); *phService = 0; return (E_OUTOFMEMORY); } lstrcpyW(pwszArgs, ServiceArgs()); // Scan the arguments do { // Scan to the next non-whitespace character while ( pwszArgs[k] && (pwszArgs[k] == L' ' || pwszArgs[k] == L'\t') ) { k++; } // Store the next argument if ( pwszArgs[k] ) { apwszArgs[cArgs++] = &pwszArgs[k]; } // Scan to the next whitespace char while ( pwszArgs[k] && pwszArgs[k] != L' ' && pwszArgs[k] != L'\t' ) { k++; } // Null terminate the previous argument if ( pwszArgs[k] ) { pwszArgs[k++] = L'\0'; } } while ( pwszArgs[k] ); } bStatus = StartService( *phService, cArgs, cArgs > 0 ? (LPCTSTR *) apwszArgs : NULL); PrivMemFree(pwszArgs); if ( bStatus ) return (S_OK); DWORD dwErr = GetLastError(); hr = HRESULT_FROM_WIN32( dwErr ); if ( dwErr == ERROR_SERVICE_ALREADY_RUNNING ) return (hr); CairoleDebugOut((DEB_ERROR, "StartService %ws failed, error = %#x\n",_pAppid->Service(),GetLastError())); CloseServiceHandle(*phService); *phService = 0; LogServiceStartError( &_Clsid, clsctx, pClientToken, _pAppid->Service(), ServiceArgs(), dwErr ); return (hr); } //+------------------------------------------------------------------------- // // LaunchAllowed // //-------------------------------------------------------------------------- BOOL CClsidData::LaunchAllowed( IN CToken * pClientToken, IN DWORD clsctx ) { BOOL bStatus; ASSERT(pClientToken); #if DBG WCHAR wszUser[MAX_PATH]; ULONG cchSize = MAX_PATH; pClientToken->Impersonate(); GetUserName( wszUser, &cchSize ); pClientToken->Revert(); CairoleDebugOut((DEB_TRACE, "RPCSS : CClsidData::LaunchAllowed on %ws\n", wszUser)); #endif if ( LaunchPermission() ) bStatus = CheckForAccess( pClientToken, LaunchPermission() ); else { CSecDescriptor* pSD = GetDefaultLaunchPermissions(); if (pSD) { bStatus = CheckForAccess( pClientToken, pSD->GetSD() ); pSD->DecRefCount(); } else bStatus = FALSE; } if ( ! bStatus ) { LogLaunchAccessFailed( &_Clsid, clsctx, pClientToken, 0 == LaunchPermission() ); } return (bStatus); } HRESULT CClsidData::GetLaunchCommandLine( OUT WCHAR ** ppwszCommandLine ) { DWORD AllocBytes; *ppwszCommandLine = 0; if ( (SERVERTYPE_EXE16 == _ServerType) || (SERVERTYPE_EXE32 == _ServerType) ) { AllocBytes = ( 1 + lstrlenW( L"-Embedding" ) + 1 + lstrlenW( _pwszServer ) ) * sizeof(WCHAR); *ppwszCommandLine = (WCHAR *) PrivMemAlloc( AllocBytes ); if ( *ppwszCommandLine != NULL ) { lstrcpyW( *ppwszCommandLine, _pwszServer ); lstrcatW( *ppwszCommandLine, L" -Embedding" ); } } else { ASSERT( SERVERTYPE_SURROGATE == _ServerType || SERVERTYPE_COMPLUS == _ServerType || SERVERTYPE_DLLHOST == _ServerType ); AllocBytes = ( 1 + lstrlenW( DllSurrogate() ) ) * sizeof(WCHAR); *ppwszCommandLine = (WCHAR *) PrivMemAlloc( AllocBytes ); if ( *ppwszCommandLine != NULL ) { lstrcpyW( *ppwszCommandLine, DllSurrogate() ); } } return (*ppwszCommandLine ? S_OK : E_OUTOFMEMORY); } CNamedObject* CClsidData::ServerLaunchMutex() { WCHAR* pwszPath = NULL; WCHAR* pszPathBuf = NULL; if ( SERVERTYPE_SURROGATE == _ServerType ) { pwszPath = DllSurrogate(); // Will never be called any more, ever if ( ! pwszPath || ! *pwszPath ) { ASSERT(_pAppid); pwszPath = _pAppid->AppidString(); //pwszPath = L"dllhost.exe"; } } else if ( DllHostOrComPlusProcess() ) { ASSERT(_pAppid); pwszPath = _pAppid->AppidString(); //pwszPath = L"dllhost.exe"; } else { pwszPath = Server(); // Need to use the base .exe part of the file path here, // there are tests that move the registration of their // server from one dir to another and we need to handle // this while concurrent activations are happening. LPWSTR pszBaseExeName = NULL; // First see how much of a buffer we need DWORD dwRet = GetFullPathName(pwszPath, 0, NULL, NULL); ASSERT(dwRet != 0); pszPathBuf = (WCHAR*)PrivMemAlloc(dwRet * sizeof(WCHAR)); if (!pszPathBuf) return NULL; dwRet = GetFullPathName(pwszPath, dwRet, pszPathBuf, &pszBaseExeName); if ((dwRet == 0) || !pszBaseExeName) { ASSERT(!"Unexpected failure from GetFullPathName"); PrivMemFree(pszPathBuf); return NULL; } // Use the base exe name for the event name pwszPath = pszBaseExeName; } if ( !pwszPath ) { ASSERT(0); PrivMemFree(pszPathBuf); return (NULL); } CNamedObject* pObject = gpNamedObjectTable->GetNamedObject(pwszPath, CNamedObject::MUTEX); PrivMemFree(pszPathBuf); if (pObject) { WaitForSingleObject(pObject->Handle(), INFINITE); } return pObject; } // // CClsidData::ServerRegisterEvent // // Returns a handle to the appropriate register // event for the server in question. // CNamedObject* CClsidData::ServerRegisterEvent() { if ( DllHostOrComPlusProcess() ) { // For dllhost\com+ surrogates, we delegate to the appid ASSERT(_pAppid); return _pAppid->ServerRegisterEvent(); } // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(REGEVENT_PREFIX)]; memcpy(wszEventName, REGEVENT_PREFIX, sizeof(REGEVENT_PREFIX)); memcpy(wszEventName + REGEVENT_PREFIX_STRLEN, _wszClsid, sizeof(_wszClsid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } // // CClsidData::ServerInitializedEvent // // Returns a handle to the appropriate register // event for the server in question. This event is // signaled when initialization is finished. // CNamedObject* CAppidData::ServerInitializedEvent() { // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(INITEVENT_PREFIX)]; memcpy(wszEventName, INITEVENT_PREFIX, sizeof(INITEVENT_PREFIX)); memcpy(wszEventName + INITEVENT_PREFIX_STRLEN, _wszAppid, sizeof(_wszAppid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } // // CClsidData::ServerInitializedEvent // // Returns a handle to the appropriate register // event for the server in question. This event is // signaled when initialization is finished. // // NOTE: The non-DllHost path is currently not used here. // CNamedObject* CClsidData::ServerInitializedEvent() { if ( DllHostOrComPlusProcess() ) { // For dllhost\com+ surrogates, we delegate to the appid ASSERT(_pAppid); return _pAppid->ServerInitializedEvent(); } // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(INITEVENT_PREFIX)]; memcpy(wszEventName, INITEVENT_PREFIX, sizeof(INITEVENT_PREFIX)); memcpy(wszEventName + INITEVENT_PREFIX_STRLEN, _wszClsid, sizeof(_wszClsid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } // // CAppidData::ServerRegisterEvent // // Returns a handle to the appropriate register // event for the server in question. // CNamedObject* CAppidData::ServerRegisterEvent() { // Prefix the string with a special string; objects with guid // names are just a touch too common for me to feel comfortable // otherwise. WCHAR wszEventName[GUIDSTR_MAX + sizeof(REGEVENT_PREFIX)]; memcpy(wszEventName, REGEVENT_PREFIX, sizeof(REGEVENT_PREFIX)); memcpy(wszEventName + REGEVENT_PREFIX_STRLEN, _wszAppid, sizeof(_wszAppid)); return gpNamedObjectTable->GetNamedObject(wszEventName, CNamedObject::EVENT); } //+------------------------------------------------------------------------- // // CClsidData::AddAppPathsToEnv // // Constructs a new environment block with an exe's AppPath value from the // registry appended to the Path environment variable. Simply returns the // given environment block if the clsid's server is not a 32 bit exe or if // no AppPath is found for the exe. // //-------------------------------------------------------------------------- HRESULT CClsidData::AddAppPathsToEnv( IN WCHAR * pEnvBlock, IN DWORD EnvBlockLength, OUT WCHAR ** ppFinalEnvBlock ) { HKEY hAppKey; WCHAR * pwszExe; WCHAR * pwszExeEnd; WCHAR * pwszAppPath; WCHAR * pPath; WCHAR * pNewEnvBlock; WCHAR wszStr[8]; WCHAR wszKeyName[APP_PATH_LEN+MAX_PATH]; DWORD AppPathLength; DWORD EnvFragLength; DWORD Status; BOOL bFoundPath; pwszAppPath = 0; pNewEnvBlock = 0; *ppFinalEnvBlock = pEnvBlock; if ( _ServerType != SERVERTYPE_EXE32 ) return (S_OK); // // Find the exe name by looking for the first .exe sub string which // is followed by a space or null. Only servers registered with a // .exe binary are supported. Otherwise the parsing is ambiguous since // the LocalServer32 can contain paths with spaces as well as optional // arguments. // if ( ! FindExeComponent( _pwszServer, L" ", &pwszExe, &pwszExeEnd ) ) return (S_OK); // // pwszExe points to the beginning of the binary name // pwszExeEnd points to one char past the end of the binary name // memcpy( wszKeyName, APP_PATH, APP_PATH_LEN * sizeof(WCHAR) ); memcpy( &wszKeyName[APP_PATH_LEN], pwszExe, (ULONG) (pwszExeEnd - pwszExe) * sizeof(WCHAR) ); wszKeyName[APP_PATH_LEN + (pwszExeEnd - pwszExe)] = 0; Status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, wszKeyName, 0, KEY_READ, &hAppKey ); if ( ERROR_SUCCESS == Status ) { Status = ReadStringValue( hAppKey, L"Path", &pwszAppPath ); RegCloseKey( hAppKey ); } if ( Status != ERROR_SUCCESS ) return (S_OK); AppPathLength = lstrlenW(pwszAppPath); // New env block size includes space for a new ';' separator in the path. pNewEnvBlock = (WCHAR *) PrivMemAlloc( (EnvBlockLength + 1 + AppPathLength) * sizeof(WCHAR) ); if ( ! pNewEnvBlock ) { PrivMemFree( pwszAppPath ); return (E_OUTOFMEMORY); } pPath = pEnvBlock; bFoundPath = FALSE; for ( ; *pPath; ) { memcpy( wszStr, pPath, 5 * sizeof(WCHAR) ); wszStr[5] = 0; pPath += lstrlenW( pPath ) + 1; if ( lstrcmpiW( wszStr, L"Path=" ) == 0 ) { bFoundPath = TRUE; break; } } if ( bFoundPath ) { pPath--; EnvFragLength = (ULONG) (pPath - pEnvBlock); memcpy( pNewEnvBlock, pEnvBlock, EnvFragLength * sizeof(WCHAR) ); pNewEnvBlock[EnvFragLength] = L';'; memcpy( &pNewEnvBlock[EnvFragLength + 1], pwszAppPath, AppPathLength * sizeof(WCHAR) ); memcpy( &pNewEnvBlock[EnvFragLength + 1 + AppPathLength], pPath, (EnvBlockLength - EnvFragLength) * sizeof(WCHAR) ); *ppFinalEnvBlock = pNewEnvBlock; } else { PrivMemFree( pNewEnvBlock ); } PrivMemFree( pwszAppPath ); return (S_OK); }
30.554078
125
0.509125
0ab21f1f6a3c12d070a8c3a8429e872838c2f35a
1,670
hpp
C++
Oem/dbxml/dbxml/src/dbxml/NameID.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/dbxml/src/dbxml/NameID.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/dbxml/src/dbxml/NameID.hpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // See the file LICENSE for redistribution information. // // Copyright (c) 2002,2009 Oracle. All rights reserved. // // #ifndef __NAMEID_HPP #define __NAMEID_HPP #include <dbxml/XmlPortability.hpp> #include <iosfwd> #include <db.h> /** NameID * A class to encapsulate Name IDs, which are primary * keys into the DB RECNO dictionary database (32-bit) */ typedef u_int32_t nameId_t; namespace DbXml { class DbXmlDbt; class DbtOut; class DBXML_EXPORT NameID { public: NameID() : id_(0) {} NameID(nameId_t id) : id_(id) { } void reset() { id_ = 0; } nameId_t raw() const { return id_; } const void *rawPtr() const { return &id_; } void setThisFromDbt(const DbXmlDbt &dbt); void setDbtFromThis(DbtOut &dbt) const; void setThisFromDbtAsId(const DbXmlDbt &dbt); void setDbtFromThisAsId(DbtOut &dbt) const; u_int32_t unmarshal(const void *buf); u_int32_t marshal(void *buf) const; u_int32_t size() const { return sizeof(nameId_t); } u_int32_t marshalSize() const; bool operator==(const NameID &o) const { return id_ == o.id_; } bool operator==(nameId_t id) const { return id_ == id; } bool operator!=(const NameID &o) const { return id_ != o.id_; } bool operator!=(nameId_t id) const { return id_ != id; } bool operator<(const NameID &o) const { return id_ < o.id_; } bool operator>(const NameID &o) const { return id_ > o.id_; } static int compareMarshaled(const unsigned char *&p1, const unsigned char *&p2); // default implementation // NameID(const NameID&); // void operator=(const NameID &); private: nameId_t id_; }; std::ostream& operator<<(std::ostream& s, NameID id); } #endif
17.395833
56
0.682635
0ab923e2575c9df0a4a5a0d8c7646375cae8dd91
2,345
cc
C++
operator_cxx/contrib/decode_3d_bbox.cc
jie311/RangeDet
5078ce339c6d27a009aed1ca2790911ce4d10bc7
[ "Apache-2.0" ]
125
2021-08-09T02:14:04.000Z
2022-03-30T03:41:56.000Z
operator_cxx/contrib/decode_3d_bbox.cc
jie311/RangeDet
5078ce339c6d27a009aed1ca2790911ce4d10bc7
[ "Apache-2.0" ]
15
2021-08-31T06:12:31.000Z
2022-03-17T00:21:35.000Z
operator_cxx/contrib/decode_3d_bbox.cc
jie311/RangeDet
5078ce339c6d27a009aed1ca2790911ce4d10bc7
[ "Apache-2.0" ]
8
2021-08-10T03:08:10.000Z
2022-03-09T06:21:11.000Z
/*! * \file decode_3d_bbox.cc * \brief decode 3d bbox to laser frame * \author Lve Fan */ #include "./decode_3d_bbox-inl.h" #include <dmlc/parameter.h> #include "operator_common.h" namespace mxnet { namespace op { DMLC_REGISTER_PARAMETER(DecodeParam); NNVM_REGISTER_OP(_contrib_Decode3DBbox) .describe("Decode3DBbox foward.") .set_attr_parser(ParamParser<DecodeParam>) .set_num_inputs(2) .set_num_outputs(1) .set_attr<nnvm::FNumVisibleOutputs>("FNumVisibleOutputs", [](const NodeAttrs& attrs) { return 1; }) .set_attr<nnvm::FListInputNames>("FListInputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"bbox_deltas", "pc_laser_frame"}; }) .set_attr<nnvm::FListOutputNames>("FListOutputNames", [](const NodeAttrs& attrs) { return std::vector<std::string>{"decoded_bbox"}; }) .set_attr<mxnet::FInferShape>("FInferShape", [](const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_shape, mxnet::ShapeVector *out_shape){ using namespace mshadow; CHECK_EQ(in_shape->size(), 2) << "Input:[bbox_deltas, pc_laser_frame]"; mxnet::TShape dshape1 = in_shape->at(0); CHECK_EQ(dshape1.ndim(), 3) << "box deltas should be (b, n, 8)"; if (dshape1[2] != 8 && dshape1[2] != 7){ LOG_FATAL.stream() << "box deltas should be (b, n, 8), or (b, n, 7) when use bin loss"; } mxnet::TShape dshape2 = in_shape->at(1); CHECK_EQ(dshape2.ndim(), 3) << "point cloud in laser frame should be (b,n,3)"; if (dshape2[2] != 3){ LOG_FATAL.stream() << "point cloud in laser frame should be (b,n,3)"; } out_shape->clear(); out_shape->push_back(Shape3(dshape1[0], dshape1[1], 10)); return true; }) .set_attr<nnvm::FInferType>("FInferType", [](const nnvm::NodeAttrs& attrs, std::vector<int> *in_type, std::vector<int> *out_type) { CHECK_EQ(in_type->size(), 2); int dtype = (*in_type)[0]; // CHECK_EQ(dtype, (*in_type)[1]); CHECK_NE(dtype, -1) << "Input must have specified type"; out_type->clear(); out_type->push_back(dtype); return true; }) .set_attr<FCompute>("FCompute<cpu>", Decode3DBboxForward<cpu>) .set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes) .add_argument("bbox_deltas", "NDArray-or-Symbol", "2D boxes with rotation, 3D tensor") .add_argument("pc_laser_frame", "NDArray-or-Symbol", "2D boxes with rotation, 3D tensor") .add_arguments(DecodeParam::__FIELDS__()); } }
34.485294
92
0.695522
0abc9aafaf3e5f98171c88fc873d188176b666c0
7,865
cpp
C++
willow/src/subgraph/suffixtree.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/subgraph/suffixtree.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/subgraph/suffixtree.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. // ============================================================================= // Suffix Tree implementation based on: // http://llvm.org/doxygen/MachineOutliner_8cpp_source.html // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // NOTE: copyright for the code in the project may be held by contributors whose // names are not known. // ============================================================================= // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file has been modified by Graphcore Ltd. // ============================================================================= #include <limits> #include <map> #include <memory> #include <sstream> #include <tuple> #include <vector> #include <popart/subgraph/suffixtree.hpp> namespace fwtools { namespace subgraph { namespace suffixtree { namespace { const int emptyIdx = std::numeric_limits<int>::max(); struct Node { std::map<int, Node *> children; int startIdx = emptyIdx; int *endIdx = nullptr; Node *link = nullptr; bool isRoot() const { return startIdx == emptyIdx; } size_t size() const { if (isRoot()) { return 0; } return *endIdx - startIdx + 1; } Node(int sIn, int *eIn, Node *lIn) : startIdx(sIn), endIdx(eIn), link(lIn) {} int suffixIdx = emptyIdx; int concatLen = 0; // int nDescendents = 0; std::vector<int> descendantStartIndices = {}; int nChildrenWaitingFor = 0; Node *parent = nullptr; }; class SuffixTree { public: const std::vector<int> &sequence; std::map<int, std::unique_ptr<Node>> nodeMap; int nodeMapSize = 0; Node *root = nullptr; private: std::map<int, int> internalEndIdxAllocator; int internalEndIdxAllocatorSize = 0; int leafEndIdx = std::numeric_limits<int>::max(); struct ActiveState { Node *node; int Idx = emptyIdx; int Len = 0; }; ActiveState Active; Node *insertLeaf(Node &parent, int startIdx, int edge) { nodeMap[nodeMapSize] = std::unique_ptr<Node>(new Node(startIdx, &leafEndIdx, nullptr)); Node *N = nodeMap[nodeMapSize].get(); nodeMapSize++; parent.children[edge] = N; return N; } Node *insertInternalNode(Node *parent, int startIdx, int endIdx, int edge) { internalEndIdxAllocator[internalEndIdxAllocatorSize] = endIdx; int *E = &internalEndIdxAllocator[internalEndIdxAllocatorSize]; internalEndIdxAllocatorSize++; nodeMap[nodeMapSize] = std::unique_ptr<Node>(new Node(startIdx, E, root)); Node *N = nodeMap[nodeMapSize].get(); nodeMapSize++; if (parent) { parent->children[edge] = N; } return N; } void setSuffixIndices(Node &currNode, int currNodeLen) { bool isLeaf = currNode.children.size() == 0 && !currNode.isRoot(); currNode.concatLen = currNodeLen; for (auto &childPair : currNode.children) { setSuffixIndices(*childPair.second, currNodeLen + static_cast<int>(childPair.second->size())); } if (isLeaf) { currNode.suffixIdx = static_cast<int>(sequence.size()) - currNodeLen; } } void setNDescendents() { std::vector<Node *> ready; for (auto &nodePair : nodeMap) { Node *n = nodePair.second.get(); n->nChildrenWaitingFor = static_cast<int>(n->children.size()); for (auto &childPair : n->children) { Node *child = childPair.second; child->parent = n; } if (n->nChildrenWaitingFor == 0) { n->descendantStartIndices = {n->suffixIdx}; ready.push_back(n); } } while (ready.size() != 0) { Node *n = ready.back(); ready.resize(ready.size() - 1); if (n->parent) { n->parent->nChildrenWaitingFor--; for (auto &l : n->descendantStartIndices) { n->parent->descendantStartIndices.push_back(l); } if (n->parent->nChildrenWaitingFor == 0) { ready.push_back(n->parent); } } } } int extend(int endIdx, int nSuffixesToAdd) { Node *Needslink = nullptr; while (nSuffixesToAdd > 0) { if (Active.Len == 0) { Active.Idx = endIdx; } int FirstChar = sequence[Active.Idx]; if (Active.node->children.count(FirstChar) == 0) { insertLeaf(*Active.node, endIdx, FirstChar); if (Needslink) { Needslink->link = Active.node; Needslink = nullptr; } } else { Node *NextNode = Active.node->children[FirstChar]; int SubstringLen = static_cast<int>(NextNode->size()); if (Active.Len >= SubstringLen) { Active.Idx += SubstringLen; Active.Len -= SubstringLen; Active.node = NextNode; continue; } int LastChar = sequence[endIdx]; if (sequence[NextNode->startIdx + Active.Len] == LastChar) { if (Needslink && !Active.node->isRoot()) { Needslink->link = Active.node; Needslink = nullptr; } Active.Len++; break; } Node *SplitNode = insertInternalNode(Active.node, NextNode->startIdx, NextNode->startIdx + Active.Len - 1, FirstChar); insertLeaf(*SplitNode, endIdx, LastChar); NextNode->startIdx += Active.Len; SplitNode->children[sequence[NextNode->startIdx]] = NextNode; if (Needslink) Needslink->link = SplitNode; Needslink = SplitNode; } nSuffixesToAdd--; if (Active.node->isRoot()) { if (Active.Len > 0) { Active.Len--; Active.Idx = endIdx - nSuffixesToAdd + 1; } } else { Active.node = Active.node->link; } } return nSuffixesToAdd; } public: SuffixTree(const std::vector<int> &seq0) : sequence(seq0) { root = insertInternalNode(nullptr, emptyIdx, emptyIdx, 0); Active.node = root; int nSuffixesToAdd = 0; for (int PfxendIdx = 0, End = static_cast<int>(sequence.size()); PfxendIdx < End; PfxendIdx++) { nSuffixesToAdd++; leafEndIdx = PfxendIdx; nSuffixesToAdd = extend(PfxendIdx, nSuffixesToAdd); } setSuffixIndices(*root, 0); setNDescendents(); } }; } // namespace std::vector<Match> getInternal(const std::vector<int> &s) { SuffixTree tree(s); // matches[i] will be be all internal nodes with concatLen = i std::vector<std::vector<Match>> matches(s.size() + 1); for (auto &x : tree.nodeMap) { auto node = x.second.get(); // not a leaf, not the root if (node->children.size() != 0 && node->parent != nullptr) { matches[node->concatLen].push_back( {node->descendantStartIndices, node->concatLen}); } } std::vector<Match> final_matches; final_matches.reserve(s.size()); for (int i = static_cast<int>(s.size()); i >= 1; --i) { if (matches[i].size() > 0) { final_matches.insert( final_matches.end(), matches[i].begin(), matches[i].end()); } } return final_matches; } } // namespace suffixtree } // namespace subgraph } // namespace fwtools
29.791667
80
0.587413
0ac6e5afbba86fd00ebe35dbf33cba1369ea44d3
300
cpp
C++
Online Judges/URI/1174/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/1174/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/1174/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include "stdio.h" using namespace std; int main() { float vet[100]; for(int i = 0; i < 100; i++) cin >> vet[i]; for(int i = 0; i < 100; i++) { if(vet[i] <= 10) { printf("A[%d] = %.1f\n",i,vet[i]); } } return 0; }
13.043478
46
0.423333
0aca5a38a4d748d628d59c2cdefe5d6ed8b86d93
6,578
hpp
C++
integrations/near/include/marlin/near/OnRampNear.hpp
marlinprotocol/OpenWeaver
7a8c668cccc933d652fabe8a141e702b8a0fd066
[ "MIT" ]
60
2020-07-01T17:37:34.000Z
2022-02-16T03:56:55.000Z
integrations/near/include/marlin/near/OnRampNear.hpp
marlinpro/openweaver
0aca30fbda3121a8e507f48a52b718b5664a5bbc
[ "MIT" ]
5
2020-10-12T05:17:49.000Z
2021-05-25T15:47:01.000Z
integrations/near/include/marlin/near/OnRampNear.hpp
marlinpro/openweaver
0aca30fbda3121a8e507f48a52b718b5664a5bbc
[ "MIT" ]
18
2020-07-01T17:43:18.000Z
2022-01-09T14:29:08.000Z
#ifndef MARLIN_ONRAMP_NEAR_HPP #define MARLIN_ONRAMP_NEAR_HPP #include <marlin/multicast/DefaultMulticastClient.hpp> #include <marlin/near/NearTransportFactory.hpp> #include <marlin/near/NearTransport.hpp> #include <cryptopp/blake2.h> #include <libbase58.h> #include <boost/filesystem.hpp> #include <marlin/pubsub/attestation/SigAttester.hpp> using namespace marlin::near; using namespace marlin::core; using namespace marlin::multicast; using namespace marlin::pubsub; namespace marlin { namespace near { class OnRampNear { public: DefaultMulticastClient<OnRampNear, SigAttester> multicastClient; uint8_t static_sk[crypto_sign_SECRETKEYBYTES], static_pk[crypto_sign_PUBLICKEYBYTES]; // should be moved to DefaultMulticastClient and add a function there to sign a message. NearTransportFactory<OnRampNear, OnRampNear> f; std::unordered_set<NearTransport<OnRampNear>*> transport_set; void handle_handshake(NearTransport<OnRampNear> &, core::Buffer &&message); void handle_transaction(core::Buffer &&message); void handle_block(core::Buffer &&message); template<typename... Args> OnRampNear(DefaultMulticastClientOptions clop, SocketAddress listen_addr, Args&&... args): multicastClient(clop, std::forward<Args>(args)...) { multicastClient.delegate = this; if(sodium_init() == -1) { throw; } if(boost::filesystem::exists("./.marlin/keys/near_gateway")) { std::ifstream sk("./.marlin/keys/near_gateway", std::ios::binary); if(!sk.read((char *)static_sk, crypto_sign_SECRETKEYBYTES)) { throw; } crypto_sign_ed25519_sk_to_pk(static_pk, static_sk); } else { crypto_sign_keypair(static_pk, static_sk); boost::filesystem::create_directories("./.marlin/keys/"); std::ofstream sk("./.marlin/keys/near_gateway", std::ios::binary); sk.write((char *)static_sk, crypto_sign_SECRETKEYBYTES); } char b58[65]; size_t sz = 65; SPDLOG_DEBUG( "PrivateKey: {} \n PublicKey: {}", spdlog::to_hex(static_sk, static_sk + crypto_sign_SECRETKEYBYTES), spdlog::to_hex(static_pk, static_pk + crypto_sign_PUBLICKEYBYTES) ); if(b58enc(b58, &sz, static_pk, 32)) { SPDLOG_INFO( "Node identity: {}", b58 ); } else { SPDLOG_ERROR("Failed to create base 58 of public key."); } f.bind(listen_addr); f.listen(*this); } void did_recv(NearTransport <OnRampNear> &transport, Buffer &&message) { SPDLOG_DEBUG( "Message received from Near: {} bytes: {}", message.size(), spdlog::to_hex(message.data(), message.data() + message.size()) ); SPDLOG_INFO( "Message received from Near: {} bytes", message.size() ); if(message.data()[0] == 0x10 || message.data()[0] == 0x0) { handle_handshake(transport, std::move(message)); } else if(message.data()[0] == 0xc) { handle_transaction(std::move(message)); } else if(message.data()[0] == 0xb) { handle_block(std::move(message)); } else if(message.data()[0] == 0xd) { SPDLOG_DEBUG( "This is a RoutedMessage" ); } else { SPDLOG_WARN( "Unhandled: {}", message.data()[0] ); } } template<typename T> // TODO: Code smell, remove later void did_recv( DefaultMulticastClient<OnRampNear, SigAttester> &, Buffer &&bytes [[maybe_unused]], T, uint16_t, uint64_t ) { SPDLOG_DEBUG( "OnRampNear:: did_recv, forwarding message: {}", spdlog::to_hex(bytes.data(), bytes.data() + bytes.size()) ); // for(auto iter = transport_set.begin(); iter != transport_set.end(); iter++) { // Buffer buf(bytes.size()); // buf.write_unsafe(0, bytes.data(), bytes.size()); // (*iter)->send(std::move(buf)); // } } void did_send_message(NearTransport<OnRampNear> &, Buffer &&message [[maybe_unused]]) { SPDLOG_DEBUG( "Transport: Did send message: {} bytes", // transport.src_addr.to_string(), // transport.dst_addr.to_string(), message.size() ); } void did_dial(NearTransport<OnRampNear> &) { } bool should_accept(SocketAddress const &) { return true; } void did_subscribe( DefaultMulticastClient<OnRampNear, SigAttester> &, uint16_t ) {} void did_unsubscribe( DefaultMulticastClient<OnRampNear, SigAttester> &, uint16_t ) {} void did_close(NearTransport<OnRampNear> &transport, uint16_t) { transport_set.erase(&transport); } void did_create_transport(NearTransport <OnRampNear> &transport) { transport_set.insert(&transport); transport.setup(this); } }; void OnRampNear::handle_transaction(core::Buffer &&message) { SPDLOG_DEBUG( "Handling transaction: {}", spdlog::to_hex(message.data(), message.data() + message.size()) ); message.uncover_unsafe(4); CryptoPP::BLAKE2b blake2b((uint)8); blake2b.Update((uint8_t *)message.data(), message.size()); uint64_t message_id; blake2b.TruncatedFinal((uint8_t *)&message_id, 8); multicastClient.ps.send_message_on_channel( 1, message_id, message.data(), message.size() ); } void OnRampNear::handle_block(core::Buffer &&message) { SPDLOG_DEBUG("Handling block"); message.uncover_unsafe(4); CryptoPP::BLAKE2b blake2b((uint)8); blake2b.Update((uint8_t *)message.data(), message.size()); uint64_t message_id; blake2b.TruncatedFinal((uint8_t *)&message_id, 8); multicastClient.ps.send_message_on_channel( 0, message_id, message.data(), message.size() ); } void OnRampNear::handle_handshake(NearTransport <OnRampNear> &transport, core::Buffer &&message) { SPDLOG_DEBUG("Handshake replying"); uint8_t *buf = message.data(); uint32_t buf_size = message.size(); std::swap_ranges(buf + 9, buf + 42, buf + 42); uint8_t near_key_offset = 42, gateway_key_offset = 9; using namespace CryptoPP; CryptoPP::SHA256 sha256; uint8_t hashed_message[32]; int flag = std::memcmp(buf + near_key_offset, buf + gateway_key_offset, 33); if(flag < 0) { sha256.Update(buf + near_key_offset, 33); sha256.Update(buf + gateway_key_offset, 33); } else { sha256.Update(buf + gateway_key_offset, 33); sha256.Update(buf + near_key_offset, 33); } sha256.Update(buf + buf_size - 73, 8); sha256.TruncatedFinal(hashed_message, 32); uint8_t *near_node_signature = buf + buf_size - crypto_sign_BYTES; if(crypto_sign_verify_detached(near_node_signature, hashed_message, 32, buf + near_key_offset + 1) != 0) { SPDLOG_ERROR("Signature verification failed"); return; } else { SPDLOG_DEBUG("Signature verified successfully"); } uint8_t *mySignature = buf + buf_size - 64; crypto_sign_detached(mySignature, NULL, hashed_message, 32, static_sk); message.uncover_unsafe(4); transport.send(std::move(message)); } } // near } // marlin #endif // MARLIN_ONRAMP_NEAR_HPP
27.991489
175
0.710702
0acc0091c5b171f1dc9e5a815584daee9c772ba3
4,942
cpp
C++
src/mayaToCorona/src/shaders/coronaSkyShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
42
2015-01-03T15:07:25.000Z
2021-12-09T03:56:59.000Z
src/mayaToCorona/src/shaders/coronaSkyShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
66
2015-01-02T13:28:44.000Z
2022-03-16T14:00:57.000Z
src/mayaToCorona/src/shaders/coronaSkyShader.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
12
2015-02-07T05:02:17.000Z
2020-07-10T17:21:44.000Z
#include "CoronaSkyShader.h" #include <maya/MIOStream.h> #include <maya/MString.h> #include <maya/MPlug.h> #include <maya/MDataBlock.h> #include <maya/MDataHandle.h> #include <maya/MArrayDataHandle.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnLightDataAttribute.h> #include <maya/MFnEnumAttribute.h> #include <maya/MFnMessageAttribute.h> #include <maya/MFnGenericAttribute.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFloatVector.h> #include <maya/MGlobal.h> #include <maya/MDrawRegistry.h> #include <maya/MDGModifier.h> MTypeId CoronaSkyShader::id(0x0011CF46); MObject CoronaSkyShader::pSkyModel; MObject CoronaSkyShader::pSkyMultiplier; MObject CoronaSkyShader::pSkyHorizBlur; MObject CoronaSkyShader::pSkyGroundColor; MObject CoronaSkyShader::pSkyAffectGround; MObject CoronaSkyShader::pSkyPreethamTurb; MObject CoronaSkyShader::pSkySunFalloff; MObject CoronaSkyShader::pSkyZenith; MObject CoronaSkyShader::pSkyHorizon; MObject CoronaSkyShader::pSkySunGlow; MObject CoronaSkyShader::pSkySunSideGlow; MObject CoronaSkyShader::pSkySunBleed; MObject CoronaSkyShader::sunSizeMulti; MObject CoronaSkyShader::outColor; void CoronaSkyShader::postConstructor( ) { MStatus stat; setMPSafe( true ); this->setExistWithoutInConnections(true); } CoronaSkyShader::CoronaSkyShader() { } CoronaSkyShader::~CoronaSkyShader() { } void* CoronaSkyShader::creator() { return new CoronaSkyShader(); } MStatus CoronaSkyShader::initialize() { MFnNumericAttribute nAttr; MFnLightDataAttribute lAttr; MFnTypedAttribute tAttr; MFnGenericAttribute gAttr; MFnEnumAttribute eAttr; MFnMessageAttribute mAttr; MStatus stat; pSkyModel = eAttr.create("pSkyModel", "pSkyModel", 2, &stat); stat = eAttr.addField("Preetham", 0); stat = eAttr.addField("Rawafake", 1); stat = eAttr.addField("Hosek", 2); CHECK_MSTATUS(addAttribute(pSkyModel)); pSkyMultiplier = nAttr.create("pSkyMultiplier", "pSkyMultiplier", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.0001f); nAttr.setSoftMax(1.0f); CHECK_MSTATUS(addAttribute(pSkyMultiplier)); pSkyHorizBlur = nAttr.create("pSkyHorizBlur", "pSkyHorizBlur", MFnNumericData::kFloat, 0.1); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkyHorizBlur)); pSkyGroundColor = nAttr.createColor("pSkyGroundColor", "pSkyGroundColor"); nAttr.setDefault(0.25, 0.25, 0.25); CHECK_MSTATUS(addAttribute(pSkyGroundColor)); pSkyAffectGround = nAttr.create("pSkyAffectGround", "pSkyAffectGround", MFnNumericData::kBoolean, true); CHECK_MSTATUS(addAttribute(pSkyAffectGround)); pSkyPreethamTurb = nAttr.create("pSkyPreethamTurb", "pSkyPreethamTurb", MFnNumericData::kFloat, 2.5); nAttr.setMin(1.7f); nAttr.setMax(10.0f); CHECK_MSTATUS(addAttribute(pSkyPreethamTurb)); pSkySunFalloff = nAttr.create("pSkySunFalloff", "pSkySunFalloff", MFnNumericData::kFloat, 3.0); nAttr.setMin(0.0001f); nAttr.setSoftMax(10.0f); CHECK_MSTATUS(addAttribute(pSkySunFalloff)); pSkyZenith = nAttr.createColor("pSkyZenith", "pSkyZenith"); nAttr.setDefault(0.1, 0.1, 0.5); CHECK_MSTATUS(addAttribute(pSkyZenith)); pSkyHorizon = nAttr.createColor("pSkyHorizon", "pSkyHorizon"); nAttr.setDefault(0.25, 0.5, 0.5); CHECK_MSTATUS(addAttribute(pSkyHorizon)); pSkySunGlow = nAttr.create("pSkySunGlow", "pSkySunGlow", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkySunGlow)); pSkySunSideGlow = nAttr.create("pSkySunSideGlow", "pSkySunSideGlow", MFnNumericData::kFloat, 0.2); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkySunSideGlow)); pSkySunBleed = nAttr.create("pSkySunBleed", "pSkySunBleed", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.0f); nAttr.setMax(1.0f); CHECK_MSTATUS(addAttribute(pSkySunBleed)); sunSizeMulti = nAttr.create("sunSizeMulti", "sunSizeMulti", MFnNumericData::kFloat, 1.0); nAttr.setMin(0.1); nAttr.setSoftMax(64.0); CHECK_MSTATUS(addAttribute(sunSizeMulti)); outColor = nAttr.createColor("outColor", "outColor"); nAttr.setKeyable(false); nAttr.setStorable(false); nAttr.setReadable(true); nAttr.setWritable(false); CHECK_MSTATUS(addAttribute(outColor)); CHECK_MSTATUS(attributeAffects(pSkyMultiplier, outColor)); CHECK_MSTATUS(attributeAffects(pSkyHorizBlur, outColor)); CHECK_MSTATUS(attributeAffects(pSkyGroundColor, outColor)); CHECK_MSTATUS(attributeAffects(pSkyAffectGround, outColor)); CHECK_MSTATUS(attributeAffects(pSkyPreethamTurb, outColor)); CHECK_MSTATUS(attributeAffects(pSkySunFalloff, outColor)); CHECK_MSTATUS(attributeAffects(pSkyZenith, outColor)); CHECK_MSTATUS(attributeAffects(pSkyHorizon, outColor)); CHECK_MSTATUS(attributeAffects(pSkySunGlow, outColor)); CHECK_MSTATUS(attributeAffects(pSkySunBleed, outColor)); CHECK_MSTATUS(attributeAffects(sunSizeMulti, outColor)); return( MS::kSuccess ); } MStatus CoronaSkyShader::compute( const MPlug& plug, MDataBlock& block ) { return( MS::kSuccess ); }
32.090909
105
0.784298
0ace9a65a4c571ade034821a6875ff8836c32a7f
1,772
cpp
C++
llvm/tools/clang/test/SemaCXX/declspec-thread.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
58
2016-08-27T03:19:14.000Z
2022-01-05T17:33:44.000Z
llvm/tools/clang/test/SemaCXX/declspec-thread.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
14
2017-12-01T17:16:59.000Z
2020-12-21T12:16:35.000Z
llvm/tools/clang/test/SemaCXX/declspec-thread.cpp
oslab-swrc/juxta
481cd6f01e87790041a07379805968bcf57d75f4
[ "MIT" ]
22
2016-11-27T09:53:31.000Z
2021-11-22T00:22:53.000Z
// RUN: %clang_cc1 -triple i686-pc-win32 -std=c++11 -fms-extensions -verify %s __thread __declspec(thread) int a; // expected-error {{already has a thread-local storage specifier}} __declspec(thread) __thread int b; // expected-error {{already has a thread-local storage specifier}} __declspec(thread) int c(); // expected-warning {{only applies to variables}} __declspec(thread) int d; int foo(); __declspec(thread) int e = foo(); // expected-error {{must be a constant expression}} expected-note {{thread_local}} struct HasCtor { HasCtor(); int x; }; __declspec(thread) HasCtor f; // expected-error {{must be a constant expression}} expected-note {{thread_local}} struct HasDtor { ~HasDtor(); int x; }; __declspec(thread) HasDtor g; // expected-error {{non-trivial destruction}} expected-note {{thread_local}} struct HasDefaultedDefaultCtor { HasDefaultedDefaultCtor() = default; int x; }; __declspec(thread) HasDefaultedDefaultCtor h; struct HasConstexprCtor { constexpr HasConstexprCtor(int x) : x(x) {} int x; }; __declspec(thread) HasConstexprCtor i(42); int foo() { __declspec(thread) int a; // expected-error {{must have global storage}} static __declspec(thread) int b; } extern __declspec(thread) int fwd_thread_var; __declspec(thread) int fwd_thread_var = 5; extern int fwd_thread_var_mismatch; // expected-note {{previous declaration}} __declspec(thread) int fwd_thread_var_mismatch = 5; // expected-error-re {{thread-local {{.*}} follows non-thread-local}} extern __declspec(thread) int thread_mismatch_2; // expected-note {{previous declaration}} int thread_mismatch_2 = 5; // expected-error-re {{non-thread-local {{.*}} follows thread-local}} typedef __declspec(thread) int tls_int_t; // expected-warning {{only applies to variables}}
41.209302
121
0.743228
0ad04d8b69dc66dd4d445976f266f906996e366d
14,363
cc
C++
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-27T09:10:11.000Z
2018-09-27T09:10:11.000Z
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-16T07:17:29.000Z
2018-09-16T07:17:29.000Z
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
null
null
null
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "floyd/src/floyd_peer_thread.h" #include <google/protobuf/text_format.h> #include <algorithm> #include <climits> #include <vector> #include <string> #include "slash/include/env.h" #include "slash/include/slash_mutex.h" #include "slash/include/xdebug.h" #include "floyd/src/floyd_primary_thread.h" #include "floyd/src/floyd_context.h" #include "floyd/src/floyd_client_pool.h" #include "floyd/src/raft_log.h" #include "floyd/src/floyd.pb.h" #include "floyd/src/logger.h" #include "floyd/src/raft_meta.h" #include "floyd/src/floyd_apply.h" namespace floyd { Peer::Peer(std::string server, PeersSet* peers, FloydContext* context, FloydPrimary* primary, RaftMeta* raft_meta, RaftLog* raft_log, ClientPool* pool, FloydApply* apply, const Options& options, Logger* info_log) : peer_addr_(server), peers_(peers), context_(context), primary_(primary), raft_meta_(raft_meta), raft_log_(raft_log), pool_(pool), apply_(apply), options_(options), info_log_(info_log), next_index_(1), match_index_(0), peer_last_op_time(0), bg_thread_(1024 * 1024 * 256) { next_index_ = raft_log_->GetLastLogIndex() + 1; match_index_ = raft_meta_->GetLastApplied(); } int Peer::Start() { std::string name = "P" + std::to_string(options_.local_port) + ":" + peer_addr_.substr(peer_addr_.find(':')); bg_thread_.set_thread_name(name); LOGV(INFO_LEVEL, info_log_, "Peer::Start Start a peer thread to %s", peer_addr_.c_str()); return bg_thread_.StartThread(); } Peer::~Peer() { LOGV(INFO_LEVEL, info_log_, "Peer::~Peer peer thread %s exit", peer_addr_.c_str()); } int Peer::Stop() { return bg_thread_.StopThread(); } bool Peer::CheckAndVote(uint64_t vote_term) { if (context_->current_term != vote_term) { return false; } return (++context_->vote_quorum) > (options_.members.size() / 2); } void Peer::UpdatePeerInfo() { for (auto& pt : (*peers_)) { pt.second->set_next_index(raft_log_->GetLastLogIndex() + 1); pt.second->set_match_index(0); } } void Peer::AddRequestVoteTask() { /* * int timer_queue_size, queue_size; * bg_thread_.QueueSize(&timer_queue_size, &queue_size); * LOGV(INFO_LEVEL, info_log_, "Peer::AddRequestVoteTask peer_addr %s timer_queue size %d queue_size %d", * peer_addr_.c_str(),timer_queue_size, queue_size); */ bg_thread_.Schedule(&RequestVoteRPCWrapper, this); } void Peer::RequestVoteRPCWrapper(void *arg) { reinterpret_cast<Peer*>(arg)->RequestVoteRPC(); } void Peer::RequestVoteRPC() { uint64_t last_log_term; uint64_t last_log_index; CmdRequest req; { slash::MutexLock l(&context_->global_mu); raft_log_->GetLastLogTermAndIndex(&last_log_term, &last_log_index); req.set_type(Type::kRequestVote); CmdRequest_RequestVote* request_vote = req.mutable_request_vote(); request_vote->set_ip(options_.local_ip); request_vote->set_port(options_.local_port); request_vote->set_term(context_->current_term); request_vote->set_last_log_term(last_log_term); request_vote->set_last_log_index(last_log_index); LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC server %s:%d Send RequestVoteRPC message to %s at term %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term); } CmdResponse res; Status result = pool_->SendAndRecv(peer_addr_, req, &res); if (!result.ok()) { LOGV(DEBUG_LEVEL, info_log_, "Peer::RequestVoteRPC: RequestVote to %s failed %s", peer_addr_.c_str(), result.ToString().c_str()); return; } { slash::MutexLock l(&context_->global_mu); if (!result.ok()) { LOGV(WARN_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d SendAndRecv to %s failed %s", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), result.ToString().c_str()); return; } if (res.request_vote_res().term() > context_->current_term) { // RequestVote fail, maybe opposite has larger term, or opposite has // longer log. if opposite has larger term, this node will become follower // otherwise we will do nothing LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Become Follower, Candidate %s:%d vote request denied by %s," " request_vote_res.term()=%lu, current_term=%lu", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), res.request_vote_res().term(), context_->current_term); context_->BecomeFollower(res.request_vote_res().term()); raft_meta_->SetCurrentTerm(context_->current_term); raft_meta_->SetVotedForIp(context_->voted_for_ip); raft_meta_->SetVotedForPort(context_->voted_for_port); return; } if (context_->role == Role::kCandidate) { // kOk means RequestVote success, opposite vote for me if (res.request_vote_res().vote_granted() == true) { // granted LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d get vote from node %s at term %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term); // However, we need check whether this vote is vote for old term // we need ignore these type of vote if (CheckAndVote(res.request_vote_res().term())) { context_->BecomeLeader(); UpdatePeerInfo(); LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: %s:%d become leader at term %d", options_.local_ip.c_str(), options_.local_port, context_->current_term); primary_->AddTask(kHeartBeat, false); } } else { LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d deny vote from node %s at term %d, " "transfer from candidate to follower", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term); context_->BecomeFollower(res.request_vote_res().term()); raft_meta_->SetCurrentTerm(context_->current_term); raft_meta_->SetVotedForIp(context_->voted_for_ip); raft_meta_->SetVotedForPort(context_->voted_for_port); } } else if (context_->role == Role::kFollower) { LOGV(INFO_LEVEL, info_log_, "Peer::RequestVotePPC: Server %s:%d have transformed to follower when doing RequestVoteRPC, " "The leader is %s:%d, new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->leader_ip.c_str(), context_->leader_port, context_->current_term); } else if (context_->role == Role::kLeader) { LOGV(INFO_LEVEL, info_log_, "Peer::RequestVotePPC: Server %s:%d is already a leader at term %lu, " "get vote from node %s at term %d", options_.local_ip.c_str(), options_.local_port, context_->current_term, peer_addr_.c_str(), res.request_vote_res().term()); } } return; } uint64_t Peer::QuorumMatchIndex() { std::vector<uint64_t> values; std::map<std::string, Peer*>::iterator iter; for (iter = peers_->begin(); iter != peers_->end(); iter++) { if (iter->first == peer_addr_) { values.push_back(match_index_); continue; } values.push_back(iter->second->match_index()); } LOGV(DEBUG_LEVEL, info_log_, "Peer::QuorumMatchIndex: Get peers match_index %d %d %d %d", values[0], values[1], values[2], values[3]); std::sort(values.begin(), values.end()); return values.at(values.size() / 2); } // only leader will call AdvanceCommitIndex // follower only need set commit as leader's void Peer::AdvanceLeaderCommitIndex() { Entry entry; uint64_t new_commit_index = QuorumMatchIndex(); if (context_->commit_index < new_commit_index) { context_->commit_index = new_commit_index; raft_meta_->SetCommitIndex(context_->commit_index); } return; } void Peer::AddAppendEntriesTask() { /* * int timer_queue_size, queue_size; * bg_thread_.QueueSize(&timer_queue_size, &queue_size); * LOGV(INFO_LEVEL, info_log_, "Peer::AddAppendEntriesTask peer_addr %s timer_queue size %d queue_size %d", * peer_addr_.c_str(),timer_queue_size, queue_size); */ bg_thread_.Schedule(&AppendEntriesRPCWrapper, this); } void Peer::AppendEntriesRPCWrapper(void *arg) { reinterpret_cast<Peer*>(arg)->AppendEntriesRPC(); } void Peer::AppendEntriesRPC() { uint64_t prev_log_index = 0; uint64_t num_entries = 0; uint64_t prev_log_term = 0; uint64_t last_log_index = 0; uint64_t current_term = 0; CmdRequest req; CmdRequest_AppendEntries* append_entries = req.mutable_append_entries(); { slash::MutexLock l(&context_->global_mu); prev_log_index = next_index_ - 1; last_log_index = raft_log_->GetLastLogIndex(); /* * LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntriesRPC: next_index_ %d last_log_index %d peer_last_op_time %lu nowmicros %lu", * next_index_.load(), last_log_index, peer_last_op_time, slash::NowMicros()); */ if (next_index_ > last_log_index && peer_last_op_time + options_.heartbeat_us > slash::NowMicros()) { return; } peer_last_op_time = slash::NowMicros(); if (prev_log_index != 0) { Entry entry; if (raft_log_->GetEntry(prev_log_index, &entry) != 0) { LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntriesRPC: Get my(%s:%d) Entry index %llu " "not found", options_.local_ip.c_str(), options_.local_port, prev_log_index); } else { prev_log_term = entry.term(); } } current_term = context_->current_term; req.set_type(Type::kAppendEntries); append_entries->set_ip(options_.local_ip); append_entries->set_port(options_.local_port); append_entries->set_term(current_term); append_entries->set_prev_log_index(prev_log_index); append_entries->set_prev_log_term(prev_log_term); append_entries->set_leader_commit(context_->commit_index); } Entry *tmp_entry = new Entry(); for (uint64_t index = next_index_; index <= last_log_index; index++) { if (raft_log_->GetEntry(index, tmp_entry) == 0) { // TODO(ba0tiao) how to avoid memory copy here Entry *entry = append_entries->add_entries(); *entry = *tmp_entry; } else { LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntriesRPC: peer_addr %s can't get Entry " "from raft_log, index %lld", peer_addr_.c_str(), index); break; } num_entries++; if (num_entries >= options_.append_entries_count_once || (uint64_t)append_entries->ByteSize() >= options_.append_entries_size_once) { break; } } delete tmp_entry; LOGV(DEBUG_LEVEL, info_log_, "Peer::AppendEntriesRPC: peer_addr(%s)'s next_index_ %llu, my last_log_index %llu" " AppendEntriesRPC will send %d iterm", peer_addr_.c_str(), next_index_.load(), last_log_index, num_entries); // if the AppendEntries don't contain any log item if (num_entries == 0) { LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntryRpc server %s:%d Send pingpong appendEntries message to %s at term %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), current_term); } CmdResponse res; Status result = pool_->SendAndRecv(peer_addr_, req, &res); { slash::MutexLock l(&context_->global_mu); if (!result.ok()) { LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntries: Leader %s:%d SendAndRecv to %s failed, result is %s\n", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), result.ToString().c_str()); return; } // here we may get a larger term, and transfer to follower // so we need to judge the role here if (context_->role == Role::kLeader) { /* * receiver has higer term than myself, so turn from candidate to follower */ if (res.append_entries_res().term() > context_->current_term) { LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntriesRPC: %s:%d Transfer from Leader to Follower since get A larger term" "from peer %s, local term is %d, peer term is %d", options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term, res.append_entries_res().term()); context_->BecomeFollower(res.append_entries_res().term()); raft_meta_->SetCurrentTerm(context_->current_term); raft_meta_->SetVotedForIp(context_->voted_for_ip); raft_meta_->SetVotedForPort(context_->voted_for_port); } else if (res.append_entries_res().success() == true) { if (num_entries > 0) { match_index_ = prev_log_index + num_entries; // only log entries from the leader's current term are committed // by counting replicas if (append_entries->entries(num_entries - 1).term() == context_->current_term) { AdvanceLeaderCommitIndex(); apply_->ScheduleApply(); } next_index_ = prev_log_index + num_entries + 1; } } else { LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: peer_addr %s Send AppEntriesRPC failed," "peer's last_log_index %lu, peer's next_index_ %lu", peer_addr_.c_str(), res.append_entries_res().last_log_index(), next_index_.load()); uint64_t adjust_index = std::min(res.append_entries_res().last_log_index() + 1, next_index_ - 1); if (adjust_index > 0) { // Prev log don't match, so we retry with more prev one according to // response next_index_ = adjust_index; LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: peer_addr %s Adjust peer next_index_, Now next_index_ is %lu", peer_addr_.c_str(), next_index_.load()); AddAppendEntriesTask(); } } } else if (context_->role == Role::kFollower) { LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: Server %s:%d have transformed to follower when doing AppEntriesRPC, " "new leader is %s:%d, new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->leader_ip.c_str(), context_->leader_port, context_->current_term); } else if (context_->role == Role::kCandidate) { LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: Server %s:%d have transformed to candidate when doing AppEntriesRPC, " "new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->current_term); } } return; } } // namespace floyd
40.803977
128
0.695537
bd5b2d5cb6ca0b2532b797a3479224695baa811f
930
cpp
C++
Przyklady/05_tabliceDwuwymiarowe/TablicaSumaWWierszu.cpp
galursa/WSB_PodstawyProgramowania
4cc3d7f205c060bf8f676fbc3ed6030a9235d71a
[ "MIT" ]
null
null
null
Przyklady/05_tabliceDwuwymiarowe/TablicaSumaWWierszu.cpp
galursa/WSB_PodstawyProgramowania
4cc3d7f205c060bf8f676fbc3ed6030a9235d71a
[ "MIT" ]
null
null
null
Przyklady/05_tabliceDwuwymiarowe/TablicaSumaWWierszu.cpp
galursa/WSB_PodstawyProgramowania
4cc3d7f205c060bf8f676fbc3ed6030a9235d71a
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> using namespace std; // Pobieramy wartosci od uzytkownika i liczymy sume w wierszach i ja wyswietlamy int main() { int rozmiar = 3; int losowe[rozmiar][rozmiar]; cout<<"Liczymy sume w wierszach. Prosze podac wartosci do tablicy\n"; for(int i = 0; i<rozmiar; i++) { for (int j=0; j<rozmiar; j++) { cout<<i<<","<<j<<" : "; cin>>losowe[i][j]; } } cout<<" "; for(int j=0; j<rozmiar; j++) cout<<setw(3)<<j; cout<<"\n"<<" ";; for(int j=0; j<=rozmiar; j++) cout<<"---"; cout<<"\n"; int suma = 0; for(int i = 0; i<rozmiar; i++) { cout<<i<<" |"; for (int j=0; j<rozmiar; j++) { suma+=losowe[i][j]; cout<<setw(3)<<losowe[i][j]<<" "; } cout<<" : "<<suma; suma=0; cout<<"\n"; } return 0; }
22.682927
80
0.452688
bd5f7e448e051e5da5b259abf12f1f6241da3b02
1,471
cpp
C++
src/ros_can_nodes/src/CANSendQueue.cpp
bluesat/ros_can_nodes
879114dc082c63c5d743e87a6f29e15ca6728156
[ "BSD-3-Clause" ]
1
2020-07-13T02:15:23.000Z
2020-07-13T02:15:23.000Z
src/ros_can_nodes/src/CANSendQueue.cpp
bluesat/ros_can_nodes
879114dc082c63c5d743e87a6f29e15ca6728156
[ "BSD-3-Clause" ]
3
2018-12-04T21:12:15.000Z
2019-09-08T05:54:48.000Z
src/ros_can_nodes/src/CANSendQueue.cpp
bluesat/ros_can_nodes
879114dc082c63c5d743e87a6f29e15ca6728156
[ "BSD-3-Clause" ]
null
null
null
#include "CANSendQueue.hpp" #include "CANHelpers.hpp" #include <mutex> #include <condition_variable> #include <thread> #include <ros/console.h> //#define DEBUG CANSendQueue& CANSendQueue::instance() { static CANSendQueue instance; return instance; } void CANSendQueue::push(const can_frame& frame) { std::unique_lock<std::mutex> lock{mutex}; q.push(frame); lock.unlock(); cv.notify_one(); } CANSendQueue::CANSendQueue() { std::thread sender{[this]() { while (true) { std::unique_lock<std::mutex> lock{mutex}; cv.wait(lock, [this](){ return q.size() > 0; }); const auto frame = q.front(); q.pop(); lock.unlock(); #ifdef DEBUG // debug exit condition if (frame.__res0 == 8) { ROS_INFO("exit condition"); break; } char str[1000] = {0}; sprintf(str, "Sending header = %#08X, length = %d, data:", frame.can_id, frame.can_dlc); for (int i = 0; i < frame.can_dlc;++i) { sprintf(str, "%s %02x", str, frame.data[i]); } ROS_DEBUG("%s", str); #endif // DEBUG // CAN port is assumed to be open if (CANHelpers::send_frame(frame) < 0) { ROS_ERROR("send failed: frame could not be sent"); } } }}; sender.detach(); }
24.516667
100
0.511217
bd5f9fe5cad422e6b19dcfafae452e65e41f1db0
641
cpp
C++
leetcode/1318.cpp
raghavxk/Competitive-Programming
131c9fffc92b638834c33e0ee0933adcd1e0d92a
[ "MIT" ]
1
2021-09-29T13:10:03.000Z
2021-09-29T13:10:03.000Z
leetcode/1318.cpp
raghavxk/Competitive-Programming
131c9fffc92b638834c33e0ee0933adcd1e0d92a
[ "MIT" ]
null
null
null
leetcode/1318.cpp
raghavxk/Competitive-Programming
131c9fffc92b638834c33e0ee0933adcd1e0d92a
[ "MIT" ]
null
null
null
class Solution { public: int minFlips(int a, int b, int c) { int flips=0; for(int i=0;i<32;++i){ bool aCheck=(a&(1<<i)); bool bCheck=(b&(1<<i)); bool aOrB= (aCheck | bCheck); bool cCheck=(c&(1<<i)); if(aOrB!=cCheck){ if(cCheck==true){ ++flips; } else{ if(aCheck==true && bCheck==true) flips+=2; else ++flips; } } } return flips; } };
23.740741
52
0.316693
bd611ede16ba1b25fefb73a03009e0673751893e
6,975
hpp
C++
tools/IYFEditor/include/assetImport/ConverterState.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
5
2018-07-03T17:05:43.000Z
2020-02-03T00:23:46.000Z
tools/IYFEditor/include/assetImport/ConverterState.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
tools/IYFEditor/include/assetImport/ConverterState.hpp
manvis/IYFEngine
741a8d0dcc9b3e3ff8a8adb92850633523516604
[ "BSD-3-Clause" ]
null
null
null
// The IYFEngine // // Copyright (C) 2015-2018, Manvydas Šliamka // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY // WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef IYF_CONVERTER_STATE_HPP #define IYF_CONVERTER_STATE_HPP #include "core/Constants.hpp" #include "core/Platform.hpp" #include "io/interfaces/TextSerializable.hpp" #include "utilities/NonCopyable.hpp" #include "assetImport/ImportedAssetData.hpp" namespace iyf::editor { class Converter; class InternalConverterState { public: InternalConverterState(const Converter* converter) : converter(converter) { if (converter == nullptr) { throw std::logic_error("Converter cannot be nullptr"); } } virtual ~InternalConverterState() = 0; const Converter* getConverter() const { return converter; } private: const Converter* converter; }; inline InternalConverterState::~InternalConverterState() {} class ConverterState : private NonCopyable, public TextSerializable { public: ConverterState(PlatformIdentifier platformID, std::unique_ptr<InternalConverterState> internalState, const Path& sourcePath, FileHash sourceFileHash) : sourcePath(sourcePath), sourceFileHash(sourceFileHash), conversionComplete(false), debugOutputRequested(false), systemAsset(false), platformID(platformID), internalState(std::move(internalState)) {} /// If true, this represents a system asset inline bool isSystemAsset() const { return systemAsset; } /// \warning This should only be used internally (e.g., in SystemAssetPacker). Do not expose this in the editor inline void setSystemAsset(bool systemAsset) { this->systemAsset = systemAsset; } inline const std::vector<std::string>& getTags() const { return tags; } inline std::vector<std::string>& getTags() { return tags; } /// If true, some converters may export additional debug data. This parameter is not serialized inline void setDebugOutputRequested(bool requested) { debugOutputRequested = requested; } /// If true, some converters may export additional debug data. This parameter is not serialized inline bool isDebugOutputRequested() const { return debugOutputRequested; } /// \warning This value should only be modified by the ConverterManager, tests or in VERY special cases. inline void setConversionComplete(bool state) { conversionComplete = state; } inline bool isConversionComplete() const { return conversionComplete; } inline const InternalConverterState* getInternalState() const { return internalState.get(); } inline InternalConverterState* getInternalState() { return internalState.get(); } inline const Path& getSourceFilePath() const { return sourcePath; } virtual AssetType getType() const = 0; inline const std::vector<ImportedAssetData>& getImportedAssets() const { return importedAssets; } /// \warning The contents of this vector should only be modified by the ConverterManager, the Converters or in VERY special cases. inline std::vector<ImportedAssetData>& getImportedAssets() { return importedAssets; } inline FileHash getSourceFileHash() const { return sourceFileHash; } inline PlatformIdentifier getPlatformIdentifier() const { return platformID; } /// Derived classes should not create a root object in serializeJSON() virtual bool makesJSONRoot() const final override { return false; } /// Serializes the conversion settings stored in this ConverterState instance. virtual void serializeJSON(PrettyStringWriter& pw) const final override; /// Deserialized the conversion settings from the provided JSON object and into this one virtual void deserializeJSON(JSONObject& jo) final override; /// Obtain the preferred version for the serialized data. Derived classes should increment this whenever their /// serialization format changes. If an older format is provided, reasonable defaults should be set for data /// that is not present in it. virtual std::uint64_t getLatestSerializedDataVersion() const = 0; protected: virtual void serializeJSONImpl(PrettyStringWriter& pw, std::uint64_t version) const = 0; virtual void deserializeJSONImpl(JSONObject& jo, std::uint64_t version) = 0; private: std::vector<ImportedAssetData> importedAssets; std::vector<std::string> tags; Path sourcePath; FileHash sourceFileHash; bool conversionComplete; bool debugOutputRequested; bool systemAsset; PlatformIdentifier platformID; /// The internal state of the importer. Calling Converter::initializeConverter() typically loads the file /// into memory (to build initial metadata, importer settings, etc.). The contents of the said file can be /// stored in this variable and reused in Converter::convert() to avoid duplicate work. /// /// Moreover, by using an opaque pointer to a virtual base class, we allow the converters to safely store the /// state of external helper libraries while keeping their includes confined to the converters' cpp files. /// /// \warning This may depend on the context, Engine version, OS version, etc. and MUST NEVER BE SERIALIZED std::unique_ptr<InternalConverterState> internalState; }; } #endif // IYF_CONVERTER_STATE_HPP
39.40678
153
0.723441
bd6498ebcf6b3862846ab9fbc7cd8e06f8914bc6
1,887
cpp
C++
test/test.cpp
ern0/tabletenniscounter
1157b6882978e3af8e6769d3a1cefc2db1fe446d
[ "MIT" ]
null
null
null
test/test.cpp
ern0/tabletenniscounter
1157b6882978e3af8e6769d3a1cefc2db1fe446d
[ "MIT" ]
null
null
null
test/test.cpp
ern0/tabletenniscounter
1157b6882978e3af8e6769d3a1cefc2db1fe446d
[ "MIT" ]
null
null
null
# include <stdio.h> enum Beep { B_IDLE1 = 1, B_IDLE2 = 2 }; int score[2]; char gameMode; char firstPlayer; # include "ttc_selectIdleBeep.cpp" int pass = 0; int fail = 0; int total = 0; void check(char gm, int sc0, int sc1, int res) { gameMode = gm; score[0] = sc0; score[1] = sc1; int r = selectIdleBeep(); printf( "%s GM=%d SC=%02d:%02d R=%d -> %d \n" ,( r == res ? ". " : "F ") ,gm,sc0,sc1,res,r ); total++; if (r == res) { pass++; } else { fail++; } } // checkfp() void test21low() { check(21,0,0, B_IDLE1); check(21,1,0, B_IDLE1); check(21,0,1, B_IDLE1); check(21,4,0, B_IDLE1); check(21,0,4, B_IDLE1); check(21,5,0, B_IDLE2); check(21,3,2, B_IDLE2); check(21,5,4, B_IDLE2); check(21,6,4, B_IDLE1); check(21,14,0, B_IDLE1); check(21,15,0, B_IDLE2); check(21,16,0, B_IDLE2); check(21,15,5, B_IDLE1); check(21,15,10, B_IDLE2); check(21,15,15, B_IDLE1); check(21,20,15, B_IDLE2); check(21,20,20, B_IDLE1); } void test11low() { check(11,0,0, B_IDLE1); check(11,1,0, B_IDLE1); check(11,0,1, B_IDLE1); check(11,3,0, B_IDLE2); check(11,0,3, B_IDLE2); check(11,2,1, B_IDLE2); check(11,1,2, B_IDLE2); check(11,3,2, B_IDLE2); check(11,4,2, B_IDLE1); check(11,9,0, B_IDLE2); check(11,9,3, B_IDLE1); check(11,9,6, B_IDLE2); check(11,9,8, B_IDLE2); check(11,9,9, B_IDLE1); } void test21high() { check(21,20,20, B_IDLE1); check(21,21,20, B_IDLE2); check(21,21,21, B_IDLE1); check(21,22,21, B_IDLE2); check(21,22,22, B_IDLE1); } void test11high() { check(11,9,9, B_IDLE1); check(11,10,9, B_IDLE1); check(11,10,10, B_IDLE1); check(11,11,10, B_IDLE2); check(11,11,11, B_IDLE1); check(11,12,11, B_IDLE2); } int main() { test21low(); test11low(); test21high(); test11high(); printf( "--------------------------------\n" " total=%d passed=%d failed=%d \n" ,total,pass,fail ); return 0; }
14.97619
48
0.595654
bd67a931654ebe222ab68bf555e3de5159fcec5a
1,315
cpp
C++
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
wmaxey/libcudacxx
f6a1e6067d0ccaae1c2717aef751622033481590
[ "Apache-2.0" ]
null
null
null
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
wmaxey/libcudacxx
f6a1e6067d0ccaae1c2717aef751622033481590
[ "Apache-2.0" ]
null
null
null
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
wmaxey/libcudacxx
f6a1e6067d0ccaae1c2717aef751622033481590
[ "Apache-2.0" ]
1
2021-11-12T21:19:28.000Z
2021-11-12T21:19:28.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads, pre-sm-60 // UNSUPPORTED: windows && pre-sm-70 // <cuda/std/atomic> // typedef enum memory_order // { // memory_order_relaxed, memory_order_consume, memory_order_acquire, // memory_order_release, memory_order_acq_rel, memory_order_seq_cst // } memory_order; #include <cuda/std/atomic> #include <cuda/std/cassert> #include "test_macros.h" int main(int, char**) { assert(static_cast<int>(cuda::std::memory_order_relaxed) == 0); assert(static_cast<int>(cuda::std::memory_order_consume) == 1); assert(static_cast<int>(cuda::std::memory_order_acquire) == 2); assert(static_cast<int>(cuda::std::memory_order_release) == 3); assert(static_cast<int>(cuda::std::memory_order_acq_rel) == 4); assert(static_cast<int>(cuda::std::memory_order_seq_cst) == 5); cuda::std::memory_order o = cuda::std::memory_order_seq_cst; assert(static_cast<int>(o) == 5); return 0; }
33.717949
80
0.624335
bd717254f479e9cdd051a705e97758ca777a24b8
9,223
hpp
C++
include/targets/LPC81x/lpc81x_pin.hpp
hparracho/Xarmlib
4a7c08fde796b3487845c3a4beecc21ceafde67c
[ "MIT" ]
3
2018-03-21T18:04:42.000Z
2018-05-30T09:27:29.000Z
include/targets/LPC81x/lpc81x_pin.hpp
hparracho/Xarmlib
4a7c08fde796b3487845c3a4beecc21ceafde67c
[ "MIT" ]
2
2018-06-28T14:39:19.000Z
2018-07-04T02:07:02.000Z
include/targets/LPC81x/lpc81x_pin.hpp
hparracho/Xarmlib
4a7c08fde796b3487845c3a4beecc21ceafde67c
[ "MIT" ]
5
2018-05-24T10:59:32.000Z
2021-08-06T15:57:58.000Z
// ---------------------------------------------------------------------------- // @file lpc81x_pin.hpp // @brief NXP LPC81x pin class. // @date 28 February 2019 // ---------------------------------------------------------------------------- // // Xarmlib 0.1.0 - https://github.com/hparracho/Xarmlib // Copyright (c) 2018 Helder Parracho (hparracho@gmail.com) // // See README.md file for additional credits and acknowledgments. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // ---------------------------------------------------------------------------- #ifndef __XARMLIB_TARGETS_LPC81X_PIN_HPP #define __XARMLIB_TARGETS_LPC81X_PIN_HPP #include "targets/LPC81x/lpc81x_cmsis.hpp" #include "core/target_specs.hpp" #include <array> #include <cassert> namespace xarmlib { namespace targets { namespace lpc81x { class PinDriver { public: // -------------------------------------------------------------------- // PUBLIC DEFINITIONS // -------------------------------------------------------------------- // Pin names according to the target package enum class Name { // The following pins are present in all packages p0_0 = 0, p0_1, p0_2, p0_3, p0_4, p0_5, #if (TARGET_PACKAGE_PIN_COUNT >= 16) // The following pins are only present in // TSSOP16 / XSON16 / SO20 / TSSOP20 packages p0_6, p0_7, p0_8, p0_9, p0_10, p0_11, p0_12, p0_13, #endif // (TARGET_PACKAGE_PIN_COUNT >= 16) #if (TARGET_PACKAGE_PIN_COUNT == 20) // The following pins are only present in // SO20 / TSSOP20 packages p0_14, p0_15, p0_16, p0_17, #endif // (TARGET_PACKAGE_PIN_COUNT == 20) // Not connected nc }; // Function modes (defined to map the PIO register directly) enum class FunctionMode { hiz = (0 << 3), pull_down = (1 << 3), pull_up = (2 << 3), repeater = (3 << 3) }; // Input hysteresis (defined to map the PIO register directly) enum class InputHysteresis { disable = (0 << 5), enable = (1 << 5) }; // Input invert (defined to map the PIO register directly) enum class InputInvert { normal = (0 << 6), inverted = (1 << 6) }; // I2C mode (defined to map the PIO register directly) enum class I2cMode { standard_fast_i2c = (0 << 8), standard_gpio = (1 << 8), fast_plus_i2c = (2 << 8) }; // Open-drain mode (defined to map the PIO register directly) enum class OpenDrain { disable = (0 << 10), enable = (1 << 10) }; // Input filter samples (defined to map the PIO register directly) enum class InputFilter { bypass = (0 << 11), clocks_1_clkdiv0 = (1 << 11) | (0 << 13), clocks_1_clkdiv1 = (1 << 11) | (1 << 13), clocks_1_clkdiv2 = (1 << 11) | (2 << 13), clocks_1_clkdiv3 = (1 << 11) | (3 << 13), clocks_1_clkdiv4 = (1 << 11) | (4 << 13), clocks_1_clkdiv5 = (1 << 11) | (5 << 13), clocks_1_clkdiv6 = (1 << 11) | (6 << 13), clocks_2_clkdiv0 = (2 << 11) | (0 << 13), clocks_2_clkdiv1 = (2 << 11) | (1 << 13), clocks_2_clkdiv2 = (2 << 11) | (2 << 13), clocks_2_clkdiv3 = (2 << 11) | (3 << 13), clocks_2_clkdiv4 = (2 << 11) | (4 << 13), clocks_2_clkdiv5 = (2 << 11) | (5 << 13), clocks_2_clkdiv6 = (2 << 11) | (6 << 13), clocks_3_clkdiv0 = (3 << 11) | (0 << 13), clocks_3_clkdiv1 = (3 << 11) | (1 << 13), clocks_3_clkdiv2 = (3 << 11) | (2 << 13), clocks_3_clkdiv3 = (3 << 11) | (3 << 13), clocks_3_clkdiv4 = (3 << 11) | (4 << 13), clocks_3_clkdiv5 = (3 << 11) | (5 << 13), clocks_3_clkdiv6 = (3 << 11) | (6 << 13) }; // -------------------------------------------------------------------- // PUBLIC MEMBER FUNCTIONS // -------------------------------------------------------------------- // Set mode of normal pins static void set_mode(const Name pin_name, const FunctionMode function_mode, const OpenDrain open_drain = OpenDrain::disable, const InputFilter input_filter = InputFilter::bypass, const InputInvert input_invert = InputInvert::normal, const InputHysteresis input_hysteresis = InputHysteresis::enable) { // Exclude NC assert(pin_name != Name::nc); #if (TARGET_PACKAGE_PIN_COUNT >= 16) // Exclude true open-drain pins assert(pin_name != Name::p0_10 && pin_name != Name::p0_11); #endif const int32_t pin_index = m_pin_number_to_iocon[static_cast<int32_t>(pin_name)]; LPC_IOCON->PIO[pin_index] = static_cast<uint32_t>(function_mode) | static_cast<uint32_t>(input_hysteresis) | static_cast<uint32_t>(input_invert) | static_cast<uint32_t>(open_drain) | (1 << 7) // RESERVED | static_cast<uint32_t>(input_filter); } #if (TARGET_PACKAGE_PIN_COUNT >= 16) // Set mode of true open-drain pins (only available on P0_10 and P0_11) static void set_mode(const Name pin_name, const I2cMode i2c_mode, const InputFilter input_filter, const InputInvert input_invert) { // Available only on true open-drain pins assert(pin_name == Name::p0_10 || pin_name == Name::p0_11); const int32_t pin_index = m_pin_number_to_iocon[static_cast<int32_t>(pin_name)]; LPC_IOCON->PIO[pin_index] = static_cast<uint32_t>(input_invert) | (1 << 7) // RESERVED | static_cast<uint32_t>(i2c_mode) | static_cast<uint32_t>(input_filter); } #endif private: // -------------------------------------------------------------------- // PRIVATE DEFINITIONS // -------------------------------------------------------------------- // IOCON pin values static constexpr std::array<uint8_t, TARGET_GPIO_COUNT> m_pin_number_to_iocon { // The following pins are present in all packages // PORT0 0x11, // p0.0 0x0b, // p0.1 0x06, // p0.2 0x05, // p0.3 0x04, // p0.4 0x03, // p0.5 #if (TARGET_PACKAGE_PIN_COUNT >= 16) // The following pins are only present in // TSSOP16 / XSON16 / SO20 / TSSOP20 packages 0x10, // p0.6 0x0f, // p0.7 0x0e, // p0.8 0x0d, // p0.9 0x08, // p0.10 0x07, // p0.11 0x02, // p0.12 0x01, // p0.13 #endif // (TARGET_PACKAGE_PIN_COUNT >= 16) #if (TARGET_PACKAGE_PIN_COUNT == 20) // The following pins are only present in // SO20 / TSSOP20 packages 0x12, // p0.14 0x0a, // p0.15 0x09, // p0.16 0x00 // p0.17 #endif // (TARGET_PACKAGE_PIN_COUNT == 20) }; }; } // namespace lpc81x } // namespace targets } // namespace xarmlib #endif // __XARMLIB_TARGETS_LPC81X_PIN_HPP
35.748062
115
0.479996
bd7259cbf18f2a5279e6c1dfe77392674b0b55cd
3,804
cc
C++
qualitycheck/src/model/GetPrecisionTaskResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
qualitycheck/src/model/GetPrecisionTaskResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
qualitycheck/src/model/GetPrecisionTaskResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/qualitycheck/model/GetPrecisionTaskResult.h> #include <json/json.h> using namespace AlibabaCloud::Qualitycheck; using namespace AlibabaCloud::Qualitycheck::Model; GetPrecisionTaskResult::GetPrecisionTaskResult() : ServiceResult() {} GetPrecisionTaskResult::GetPrecisionTaskResult(const std::string &payload) : ServiceResult() { parse(payload); } GetPrecisionTaskResult::~GetPrecisionTaskResult() {} void GetPrecisionTaskResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["Name"].isNull()) data_.name = dataNode["Name"].asString(); if(!dataNode["Source"].isNull()) data_.source = std::stoi(dataNode["Source"].asString()); if(!dataNode["DataSetId"].isNull()) data_.dataSetId = std::stol(dataNode["DataSetId"].asString()); if(!dataNode["DataSetName"].isNull()) data_.dataSetName = dataNode["DataSetName"].asString(); if(!dataNode["TaskId"].isNull()) data_.taskId = dataNode["TaskId"].asString(); if(!dataNode["Duration"].isNull()) data_.duration = std::stoi(dataNode["Duration"].asString()); if(!dataNode["UpdateTime"].isNull()) data_.updateTime = dataNode["UpdateTime"].asString(); if(!dataNode["Status"].isNull()) data_.status = std::stoi(dataNode["Status"].asString()); if(!dataNode["TotalCount"].isNull()) data_.totalCount = std::stoi(dataNode["TotalCount"].asString()); if(!dataNode["VerifiedCount"].isNull()) data_.verifiedCount = std::stoi(dataNode["VerifiedCount"].asString()); if(!dataNode["IncorrectWords"].isNull()) data_.incorrectWords = std::stoi(dataNode["IncorrectWords"].asString()); auto allPrecisionsNode = dataNode["Precisions"]["Precision"]; for (auto dataNodePrecisionsPrecision : allPrecisionsNode) { Data::Precision precisionObject; if(!dataNodePrecisionsPrecision["ModelName"].isNull()) precisionObject.modelName = dataNodePrecisionsPrecision["ModelName"].asString(); if(!dataNodePrecisionsPrecision["ModelId"].isNull()) precisionObject.modelId = std::stol(dataNodePrecisionsPrecision["ModelId"].asString()); if(!dataNodePrecisionsPrecision["Precision"].isNull()) precisionObject.precision = std::stof(dataNodePrecisionsPrecision["Precision"].asString()); if(!dataNodePrecisionsPrecision["Status"].isNull()) precisionObject.status = std::stoi(dataNodePrecisionsPrecision["Status"].asString()); if(!dataNodePrecisionsPrecision["TaskId"].isNull()) precisionObject.taskId = dataNodePrecisionsPrecision["TaskId"].asString(); data_.precisions.push_back(precisionObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["Message"].isNull()) message_ = value["Message"].asString(); } std::string GetPrecisionTaskResult::getMessage()const { return message_; } GetPrecisionTaskResult::Data GetPrecisionTaskResult::getData()const { return data_; } std::string GetPrecisionTaskResult::getCode()const { return code_; } bool GetPrecisionTaskResult::getSuccess()const { return success_; }
34.581818
94
0.740799
bd75be9438489717135ee58ddca13deac6e3e5ae
444
cpp
C++
Diversos trabalhos/Matriz/novo vetor.cpp
ewertonpugliesi/Trabalhos-em-C-C--
fd6400ff1621ac00907adc531ac7ad38121c532c
[ "MIT" ]
null
null
null
Diversos trabalhos/Matriz/novo vetor.cpp
ewertonpugliesi/Trabalhos-em-C-C--
fd6400ff1621ac00907adc531ac7ad38121c532c
[ "MIT" ]
null
null
null
Diversos trabalhos/Matriz/novo vetor.cpp
ewertonpugliesi/Trabalhos-em-C-C--
fd6400ff1621ac00907adc531ac7ad38121c532c
[ "MIT" ]
null
null
null
//Escrever um novo vetor,atraves de dois outros,mutiplicando valores de mesmo indice, #include<stdio.h> #include<conio.h> main() { int cont,num[10],num2[10],resul[10]; for (cont=0 ; cont<=9 ; cont++) { printf("Digite um valor "); scanf("%i",&num[10]); } for(cont=0; cont<=9 ; cont++) { printf("Digite um outro valor "); scanf("%i",&num2[10]); } for(cont=0 ; cont<=9 ; cont++) { resul[10]=num[cont]*num2[cont]; printf("%i",&resul); } getch(); }
18.5
85
0.632883
bd77be1ca2fd4290387eaaa6f82f3284d0d1e165
3,856
cc
C++
src/bin/copy-and-trim-int-vector.cc
Shuang777/kaldi-2016
5373fe4bd80857b53134db566cad48b8445cf3b9
[ "Apache-2.0" ]
null
null
null
src/bin/copy-and-trim-int-vector.cc
Shuang777/kaldi-2016
5373fe4bd80857b53134db566cad48b8445cf3b9
[ "Apache-2.0" ]
null
null
null
src/bin/copy-and-trim-int-vector.cc
Shuang777/kaldi-2016
5373fe4bd80857b53134db566cad48b8445cf3b9
[ "Apache-2.0" ]
null
null
null
// bin/copy-and-trim-int-vector.cc // Copyright 2016 Hang Su // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "matrix/kaldi-vector.h" #include "transform/transform-common.h" int main(int argc, char *argv[]) { try { using namespace kaldi; const char *usage = "Copy and trim vectors of integers, according to feature length \n" "(e.g. alignments)\n" "\n" "Usage: copy-and-trim-int-vector [options] <length-in-rspecifier> <length-out-rspecifier> <utt-map> <vector-in-rspecifier> <vector-out-wspecifier>\n" " e.g.: copy-and-trim-int-vector \"ark:feat-to-len feats1.scp\" \"ark:feat-to-len feats2.scp\" ark:utt_map \"ark:gunzip -c ali.*.gz |\" \"ark:|gzip -c > ali.trim.gz\" "; bool trim_front = false; ParseOptions po(usage); po.Register("trim-front", &trim_front, "Trim int vector from front"); po.Read(argc, argv); if (po.NumArgs() != 5) { po.PrintUsage(); exit(1); } std::string length_in_rspecifier = po.GetArg(1), length_out_rspecifier = po.GetArg(2), uttmap_rspecifier = po.GetArg(3), int32vector_rspecifier = po.GetArg(4), int32vector_wspecifier = po.GetArg(5); RandomAccessInt32Reader length_in_reader(length_in_rspecifier); RandomAccessInt32Reader length_out_reader(length_out_rspecifier); RandomAccessTokenReader uttmap_reader(uttmap_rspecifier); SequentialInt32VectorReader vector_reader(int32vector_rspecifier); Int32VectorWriter vector_writer(int32vector_wspecifier); int32 num_done = 0, num_err = 0; for (; !vector_reader.Done(); vector_reader.Next()) { std::string utt = vector_reader.Key(); if (!uttmap_reader.HasKey(utt)) { KALDI_WARN << "utterance " << utt << " not found in uttmap"; num_err++; continue; } if (!length_in_reader.HasKey(utt)) { KALDI_WARN << "utterance " << utt << " not found in length-in-rspecifier"; num_err++; continue; } std::string utt_out = uttmap_reader.Value(utt); std::vector<int32> vector_in = vector_reader.Value(); int32 length_in = length_in_reader.Value(utt); int32 length_out = length_out_reader.Value(utt_out); KALDI_ASSERT(length_in == vector_in.size()); if (length_out == length_in) { vector_writer.Write(utt_out, vector_in); } else if (length_out > length_in) { KALDI_ERR << "utterance " << utt << " length " << length_in << " smaller than utterance " << utt_out << " (out) length " << length_out; num_err++; continue; } else { int32 to_trim = length_in - length_out; if (trim_front) { vector_in.erase(vector_in.begin(), vector_in.begin() + to_trim); } else { vector_in.erase(vector_in.end() - to_trim, vector_in.end()); } vector_writer.Write(utt_out, vector_in); } num_done++; } KALDI_LOG << "Done " << num_done << " files, " << num_err << " with errors"; return (num_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
34.428571
177
0.647822
bd7b938212717ab6beed501a09b3357878f69e54
22
cpp
C++
lib/StarAlign/starAlign.cpp
AndreiDiaconu97/tracket
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
[ "MIT" ]
null
null
null
lib/StarAlign/starAlign.cpp
AndreiDiaconu97/tracket
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
[ "MIT" ]
null
null
null
lib/StarAlign/starAlign.cpp
AndreiDiaconu97/tracket
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
[ "MIT" ]
null
null
null
#include "starAlign.h"
22
22
0.772727
bd7bea2902cbfee312dbb6683c1099205b7704f3
3,194
cpp
C++
Engine/src/Components/collider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
1
2019-01-02T15:35:05.000Z
2019-01-02T15:35:05.000Z
Engine/src/Components/collider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
2
2018-11-11T21:29:05.000Z
2019-01-02T15:34:10.000Z
Engine/src/Components/collider.cpp
SpectralCascade/ossium
f9d00de8313c0f91942eb311c20de8d74aa41735
[ "MIT" ]
null
null
null
#include "collider.h" namespace Ossium { REGISTER_COMPONENT(PhysicsBody); // Use OnLoadFinish() void PhysicsBody::OnLoadFinish() { ParentType::OnLoadFinish(); #ifndef OSSIUM_EDITOR // Update all attached collider shapes before building the body auto colliders = entity->GetComponents<Collider>(); for (auto collider : colliders) { collider->SetupShape(); } RebuildBody(); // TODO: update properties if body and fixture are already created. #endif // OSSIUM_EDITOR } void PhysicsBody::OnDestroy() { PhysicsBody::ParentType::OnDestroy(); if (body != nullptr) { Physics::PhysicsWorld* world = entity->GetService<Physics::PhysicsWorld>(); DEBUG_ASSERT(world != nullptr, "Physics world cannot be NULL"); // Body will cleanup any attached fixtures world->DestroyBody(body); body = nullptr; fixture = nullptr; } } void PhysicsBody::UpdatePhysics() { if (body != nullptr && bodyType != b2BodyType::b2_staticBody) { // Update location and rotation in-game. const b2Transform& b2t = body->GetTransform(); Transform* t = GetTransform(); t->SetLocalPosition(Vector2(MTP(b2t.p.x), MTP(b2t.p.y))); t->SetLocalRotation(Rotation(b2t.q)); } } void PhysicsBody::RebuildBody() { #ifndef OSSIUM_EDITOR Collider* collider = entity->GetComponent<Collider>(); if (collider == nullptr) { // Early out, no point. return; } Physics::PhysicsWorld* world = entity->GetService<Physics::PhysicsWorld>(); DEBUG_ASSERT(world != nullptr, "Physics world cannot be NULL"); if (body != nullptr) { world->DestroyBody(body); body = nullptr; fixture = nullptr; } // Define the body b2BodyDef bodyDef; bodyDef.position.Set(PTM(GetTransform()->GetWorldPosition().x), PTM(GetTransform()->GetWorldPosition().y)); bodyDef.angle = GetTransform()->GetWorldRotation().GetRadians(); bodyDef.type = bodyType; bodyDef.active = IsActiveAndEnabled(); bodyDef.awake = startAwake; bodyDef.allowSleep = allowSleep; bodyDef.angularDamping = angularDamping; bodyDef.angularVelocity = initialAngularVelocity; bodyDef.linearDamping = linearDamping; bodyDef.linearVelocity = initialLinearVelocity; bodyDef.bullet = bullet; bodyDef.fixedRotation = fixedRotation; bodyDef.gravityScale = gravityScale; // Create the body body = world->CreateBody(&bodyDef); // Define the fixture b2FixtureDef fixDef; fixDef.shape = &collider->GetShape(); fixDef.userData = (void*)collider; fixDef.density = density; fixDef.friction = friction; fixDef.isSensor = sensor; // Create the fixture fixture = body->CreateFixture(&fixDef); #endif // OSSIUM_EDITOR } REGISTER_ABSTRACT_COMPONENT(Collider); }
31.313725
115
0.599562
bd826e96b7ca6bb982bc927de9b14dc308537f1d
6,000
cpp
C++
generator/geo_objects/geo_objects.cpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
null
null
null
generator/geo_objects/geo_objects.cpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
1
2020-06-15T15:16:23.000Z
2020-06-15T15:59:19.000Z
generator/geo_objects/geo_objects.cpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
null
null
null
#include "generator/geo_objects/geo_objects.hpp" #include "generator/feature_builder.hpp" #include "generator/regions/region_base.hpp" #include "indexer/locality_index.hpp" #include "coding/mmap_reader.hpp" #include "base/geo_object_id.hpp" #include "base/logging.hpp" #include <cstdint> #include <fstream> #include <map> #include "3party/jansson/myjansson.hpp" namespace { using KeyValue = std::map<uint64_t, base::Json>; using IndexReader = ReaderPtr<Reader>; std::vector<FeatureBuilder1> ReadTmpMwm(std::string const & pathToGeoObjectsTmpMwm) { std::vector<FeatureBuilder1> geoObjects; auto const toDo = [&geoObjects](FeatureBuilder1 & fb, uint64_t /* currPos */) { geoObjects.emplace_back(std::move(fb)); }; feature::ForEachFromDatRawFormat(pathToGeoObjectsTmpMwm, toDo); return geoObjects; } KeyValue ReadRegionsKv(std::string const & pathToRegionsKv) { KeyValue regionKv; std::ifstream stream(pathToRegionsKv); std::string line; while (std::getline(stream, line)) { auto const pos = line.find(" "); if (pos == std::string::npos) { LOG(LWARNING, ("Cannot find separator.")); continue; } int64_t id; if (!strings::to_int64(line.substr(0, pos), id)) { LOG(LWARNING, ("Cannot parse id.")); continue; } base::Json json; try { json = base::Json(line.substr(pos + 1)); if (!json.get()) continue; } catch (base::Json::Exception const &) { LOG(LWARNING, ("Cannot create base::Json.")); continue; } regionKv.emplace(static_cast<uint64_t>(id), json); } return regionKv; } template <typename Index> std::vector<base::GeoObjectId> SearchObjectsInIndex(FeatureBuilder1 const & fb, Index const & index) { std::vector<base::GeoObjectId> ids; auto const fn = [&ids] (base::GeoObjectId const & osmid) { ids.emplace_back(osmid); }; auto const center = fb.GetLimitRect().Center(); auto const rect = MercatorBounds::RectByCenterXYAndSizeInMeters(center, 0 /* meters */); index.ForEachInRect(fn, rect); return ids; } int GetRankFromValue(base::Json const & json) { int rank; auto properties = json_object_get(json.get(), "properties"); FromJSONObject(properties, "rank", rank); return rank; } base::Json GetDeepestRegion(std::vector<base::GeoObjectId> const & ids, KeyValue const & regionKv) { base::Json deepest; int deepestRank = 0; for (auto const & id : ids) { base::Json temp; auto const it = regionKv.find(id.GetEncodedId()); if (it == std::end(regionKv)) { LOG(LWARNING, ("Id not found in region key-value:", id)); continue; } temp = it->second; if (!json_is_object(temp.get())) { LOG(LWARNING, ("Value is not a json object in region key-value:", id)); continue; } if (!deepest.get()) { deepestRank = GetRankFromValue(temp); deepest = temp; } else { int tempRank = GetRankFromValue(temp); if (deepestRank < tempRank) { deepest = temp; deepestRank = tempRank; } } } return deepest; } base::Json AddAddress(FeatureBuilder1 const & fb, base::Json const & regionJson) { base::Json result = regionJson.GetDeepCopy(); int const kHouseRank = 30; ToJSONObject(*result.get(), "rank", kHouseRank); auto properties = json_object_get(result.get(), "properties"); auto address = json_object_get(properties, "address"); ToJSONObject(*address, "house", fb.GetParams().house.Get()); auto const street = fb.GetParams().GetStreet(); if (!street.empty()) ToJSONObject(*address, "street", street); // auto locales = json_object_get(result.get(), "locales"); // auto en = json_object_get(result.get(), "en"); // todo(maksimandrianov): Add en locales. return result; } std::unique_ptr<char, JSONFreeDeleter> MakeGeoObjectValue(FeatureBuilder1 const & fb, typename indexer::RegionsIndexBox<IndexReader>::IndexType const & regionIndex, KeyValue const & regionKv) { auto const ids = SearchObjectsInIndex(fb, regionIndex); auto const json = GetDeepestRegion(ids, regionKv); auto const jsonWithAddress = AddAddress(fb, json); auto const cstr = json_dumps(jsonWithAddress.get(), JSON_COMPACT); std::unique_ptr<char, JSONFreeDeleter> buffer(cstr); return buffer; } bool GenerateGeoObjects(typename indexer::RegionsIndexBox<IndexReader>::IndexType const & regionIndex, KeyValue const & regionKv, std::vector<FeatureBuilder1> const & geoObjects, std::ostream & streamIdsWithoutAddress, std::ostream & streamGeoObjectsKv, bool verbose) { for (auto const & fb : geoObjects) { if (fb.GetParams().house.IsEmpty()) continue; auto const value = MakeGeoObjectValue(fb, regionIndex, regionKv); streamGeoObjectsKv << static_cast<int64_t>(fb.GetMostGenericOsmId().GetEncodedId()) << " " << value.get() << "\n"; } return true; } } // namespace namespace generator { namespace geo_objects { bool GenerateGeoObjects(std::string const & pathInRegionsIndx, std::string const & pathInRegionsKv, std::string const & pathInGeoObjectsTmpMwm, std::string const & pathOutIdsWithoutAddress, std::string const & pathOutGeoObjectsKv, bool verbose) { auto const index = indexer::ReadIndex<indexer::RegionsIndexBox<IndexReader>, MmapReader>(pathInRegionsIndx); auto const regionsKv = ReadRegionsKv(pathInRegionsKv); auto geoObjects = ReadTmpMwm(pathInGeoObjectsTmpMwm); std::ofstream streamIdsWithoutAddress(pathOutIdsWithoutAddress); std::ofstream streamGeoObjectsKv(pathOutGeoObjectsKv); return ::GenerateGeoObjects(index, regionsKv, geoObjects, streamIdsWithoutAddress, streamGeoObjectsKv, verbose); } } // namespace geo_objects } // namespace generator
29.126214
110
0.665
bd83c41cb6e725f59625eb34c8fce014d1f3f841
10,669
cpp
C++
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: ProgramGenerator.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLRenderer/Renderer/Renderer.h" #include "PLRenderer/Renderer/Program.h" #include "PLRenderer/Renderer/VertexShader.h" #include "PLRenderer/Renderer/FragmentShader.h" #include "PLRenderer/Renderer/ShaderLanguage.h" #include "PLRenderer/Renderer/ProgramGenerator.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLRenderer { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ ProgramGenerator::ProgramGenerator(Renderer &cRenderer, const String &sShaderLanguage, const String &sVertexShader, const String &sVertexShaderProfile, const String &sFragmentShader, const String &sFragmentShaderProfile) : EventHandlerDirty(&ProgramGenerator::OnDirty, this), m_pRenderer(&cRenderer), m_sShaderLanguage(sShaderLanguage), m_sVertexShader(sVertexShader), m_sVertexShaderProfile(sVertexShaderProfile), m_sFragmentShader(sFragmentShader), m_sFragmentShaderProfile(sFragmentShaderProfile) { } /** * @brief * Destructor */ ProgramGenerator::~ProgramGenerator() { // Clear the cache of the program generator ClearCache(); } /** * @brief * Returns a program */ ProgramGenerator::GeneratedProgram *ProgramGenerator::GetProgram(const Flags &cFlags) { // Get the unique vertex shader and fragment shader ID's, we're taking the flags for this :D const uint32 nVertexShaderID = cFlags.GetVertexShaderFlags(); const uint32 nFragmentShaderID = cFlags.GetFragmentShaderFlags(); // Combine the two ID's into an unique 64 bit integer we can use to reference the linked program const uint64 nProgramID = nVertexShaderID + static_cast<uint64>(static_cast<uint64>(nFragmentShaderID)<<32); // Is there already a generated program with the requested flags? GeneratedProgram *pGeneratedProgram = m_mapPrograms.Get(nProgramID); if (!pGeneratedProgram) { // Is there already a vertex shader with the requested flags? VertexShader *pVertexShader = m_mapVertexShaders.Get(nVertexShaderID); if (!pVertexShader) { // Get the shader language to use ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage); if (pShaderLanguage) { // Create a new vertex shader instance pVertexShader = pShaderLanguage->CreateVertexShader(); if (pVertexShader) { String sSourceCode; // When using GLSL, the profile is the GLSL version to use - #version must occur before any other statement in the program! if (m_sShaderLanguage == "GLSL" && m_sVertexShaderProfile.GetLength()) sSourceCode += "#version " + m_sVertexShaderProfile + '\n'; // Add flag definitions to the shader source code const Array<const char *> &lstVertexShaderDefinitions = cFlags.GetVertexShaderDefinitions(); const uint32 nNumOfVertexShaderDefinitions = lstVertexShaderDefinitions.GetNumOfElements(); for (uint32 i=0; i<nNumOfVertexShaderDefinitions; i++) { // Get the flag definition const char *pszDefinition = lstVertexShaderDefinitions[i]; if (pszDefinition) { sSourceCode += "#define "; sSourceCode += pszDefinition; sSourceCode += '\n'; } } // Add the shader source code sSourceCode += m_sVertexShader; // Set the combined shader source code pVertexShader->SetSourceCode(sSourceCode, m_sVertexShaderProfile); // Add the created shader to the cache of the program generator m_lstVertexShaders.Add(pVertexShader); m_mapVertexShaders.Add(nVertexShaderID, pVertexShader); } } } // If we have no vertex shader, we don't need to continue constructing a program... if (pVertexShader) { // Is there already a fragment shader with the requested flags? FragmentShader *pFragmentShader = m_mapFragmentShaders.Get(nFragmentShaderID); if (!pFragmentShader) { // Get the shader language to use ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage); if (pShaderLanguage) { // Create a new fragment shader instance pFragmentShader = pShaderLanguage->CreateFragmentShader(); if (pFragmentShader) { String sSourceCode; // When using GLSL, the profile is the GLSL version to use - #version must occur before any other statement in the program! if (m_sShaderLanguage == "GLSL" && m_sFragmentShaderProfile.GetLength()) sSourceCode += "#version " + m_sFragmentShaderProfile + '\n'; // Add flag definitions to the shader source code const Array<const char *> &lstFragmentShaderDefinitions = cFlags.GetFragmentShaderDefinitions(); const uint32 nNumOfFragmentShaderDefinitions = lstFragmentShaderDefinitions.GetNumOfElements(); for (uint32 i=0; i<nNumOfFragmentShaderDefinitions; i++) { // Get the flag definition const char *pszDefinition = lstFragmentShaderDefinitions[i]; if (pszDefinition) { sSourceCode += "#define "; sSourceCode += pszDefinition; sSourceCode += '\n'; } } // Add the shader source code sSourceCode += m_sFragmentShader; // Set the combined shader source code pFragmentShader->SetSourceCode(sSourceCode, m_sFragmentShaderProfile); // Add the created shader to the cache of the program generator m_lstFragmentShaders.Add(pFragmentShader); m_mapFragmentShaders.Add(nFragmentShaderID, pFragmentShader); } } } // If we have no fragment shader, we don't need to continue constructing a program... if (pFragmentShader) { // Get the shader language to use ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage); if (pShaderLanguage) { // Create a program instance and assign the created vertex and fragment shaders to it Program *pProgram = pShaderLanguage->CreateProgram(pVertexShader, pFragmentShader); if (pProgram) { // Create a generated program contained pGeneratedProgram = new GeneratedProgram; pGeneratedProgram->pProgram = pProgram; pGeneratedProgram->nVertexShaderFlags = cFlags.GetVertexShaderFlags(); pGeneratedProgram->nFragmentShaderFlags = cFlags.GetFragmentShaderFlags(); pGeneratedProgram->pUserData = nullptr; // Add our nark which will inform us as soon as the program gets dirty pProgram->EventDirty.Connect(EventHandlerDirty); // Add the created program to the cache of the program generator m_lstPrograms.Add(pGeneratedProgram); m_mapPrograms.Add(nProgramID, pGeneratedProgram); } } } } } // Return the program return pGeneratedProgram; } /** * @brief * Clears the cache of the program generator */ void ProgramGenerator::ClearCache() { // Destroy all generated program instances for (uint32 i=0; i<m_lstPrograms.GetNumOfElements(); i++) { GeneratedProgram *pGeneratedProgram = m_lstPrograms[i]; delete pGeneratedProgram->pProgram; if (pGeneratedProgram->pUserData) delete pGeneratedProgram->pUserData; delete pGeneratedProgram; } m_lstPrograms.Clear(); m_mapPrograms.Clear(); // Destroy all generated fragment shader instances for (uint32 i=0; i<m_lstFragmentShaders.GetNumOfElements(); i++) delete m_lstFragmentShaders[i]; m_lstFragmentShaders.Clear(); m_mapFragmentShaders.Clear(); // Destroy all generated vertex shader instances for (uint32 i=0; i<m_lstVertexShaders.GetNumOfElements(); i++) delete m_lstVertexShaders[i]; m_lstVertexShaders.Clear(); m_mapVertexShaders.Clear(); } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Copy constructor */ ProgramGenerator::ProgramGenerator(const ProgramGenerator &cSource) : m_pRenderer(nullptr) { // No implementation because the copy constructor is never used } /** * @brief * Copy operator */ ProgramGenerator &ProgramGenerator::operator =(const ProgramGenerator &cSource) { // No implementation because the copy operator is never used return *this; } /** * @brief * Called when a program became dirty */ void ProgramGenerator::OnDirty(Program *pProgram) { // Search for the generated program and destroy the user data for (uint32 i=0; i<m_lstPrograms.GetNumOfElements(); i++) { GeneratedProgram *pGeneratedProgram = m_lstPrograms[i]; if (pGeneratedProgram->pProgram == pProgram) { // Is there user data we can destroy? if (pGeneratedProgram->pUserData) { delete pGeneratedProgram->pUserData; pGeneratedProgram->pUserData = nullptr; } // We're done, get us out of the loop i = m_lstPrograms.GetNumOfElements(); } } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLRenderer
37.566901
151
0.667823
bd86280087c86bed9cc2a1f2459ef0297950c21d
1,350
hpp
C++
include/rua/callable.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
include/rua/callable.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
include/rua/callable.hpp
yulon/rua
acb14aa0e60b68f09e88c726965552f7f4f5ace0
[ "MIT" ]
null
null
null
#ifndef _RUA_CALLABLE_HPP #define _RUA_CALLABLE_HPP #include "types/traits.hpp" #include <functional> #include <vector> namespace rua { template <typename Callable> inline std::function<callable_prototype_t<decay_t<Callable>>> wrap_callable(Callable &&c) { return std::forward<Callable>(c); } //////////////////////////////////////////////////////////////////////////// template <typename Ret, typename... Args> class _callchain_base : public std::vector<std::function<Ret(Args...)>> { public: _callchain_base() = default; }; template <typename Callback, typename = void> class callchain; template <typename Ret, typename... Args> class callchain< Ret(Args...), enable_if_t<!std::is_convertible<Ret, bool>::value>> : public _callchain_base<Ret, Args...> { public: callchain() = default; void operator()(Args &&... args) const { for (auto &cb : *this) { cb(std::forward<Args>(args)...); } } }; template <typename Ret, typename... Args> class callchain< Ret(Args...), enable_if_t<std::is_convertible<Ret, bool>::value>> : public _callchain_base<Ret, Args...> { public: callchain() = default; Ret operator()(Args &&... args) const { for (auto &cb : *this) { auto &&r = cb(std::forward<Args>(args)...); if (static_cast<bool>(r)) { return std::move(r); } } return Ret(); } }; } // namespace rua #endif
20.769231
76
0.634074
bd879321d9b78defa9f3b6b25da6f5c29af8a2fc
1,571
hpp
C++
TicTacToe/Score.hpp
djanko1337/TicTacToe
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
[ "MIT" ]
1
2018-02-14T18:00:52.000Z
2018-02-14T18:00:52.000Z
TicTacToe/Score.hpp
djanko1337/TicTacToe
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
[ "MIT" ]
null
null
null
TicTacToe/Score.hpp
djanko1337/TicTacToe
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
[ "MIT" ]
null
null
null
#pragma once namespace TicTacToe { class Score { public: constexpr Score() noexcept; constexpr auto count() const noexcept -> int; constexpr auto increment() noexcept -> void; constexpr auto reset() noexcept -> void; private: int mCount; }; constexpr auto operator==(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator!=(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator<(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator>(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator<=(Score lhs, Score rhs) noexcept -> bool; constexpr auto operator>=(Score lhs, Score rhs) noexcept -> bool; constexpr Score::Score() noexcept : mCount(0) { } constexpr auto Score::count() const noexcept -> int { return mCount; } constexpr auto Score::increment() noexcept -> void { ++mCount; } constexpr auto Score::reset() noexcept -> void { mCount = 0; } constexpr auto operator==(Score lhs, Score rhs) noexcept -> bool { return lhs.count() == rhs.count(); } constexpr auto operator!=(Score lhs, Score rhs) noexcept -> bool { return !(lhs == rhs); } constexpr auto operator<(Score lhs, Score rhs) noexcept -> bool { return lhs.count() < rhs.count(); } constexpr auto operator>(Score lhs, Score rhs) noexcept -> bool { return lhs.count() > rhs.count(); } constexpr auto operator<=(Score lhs, Score rhs) noexcept -> bool { return !(lhs > rhs); } constexpr auto operator>=(Score lhs, Score rhs) noexcept -> bool { return !(lhs < rhs); } } // namespace TicTacToe
19.158537
65
0.674729
bd8c50deb2428e76a91e1731ad9a8523613d76dd
1,060
hpp
C++
libs/core/include/fcppt/enum/output.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/enum/output.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/enum/output.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_ENUM_OUTPUT_HPP_INCLUDED #define FCPPT_ENUM_OUTPUT_HPP_INCLUDED #include <fcppt/enum/to_string.hpp> #include <fcppt/io/ostream.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace enum_ { /** \brief Outputs an enum value to a stream. \ingroup fcpptenum Uses #fcppt::enum_::to_string to output \a _value to \a _stream. This function is useful to implement <code>operator<<</code> for an enum type. \tparam Enum Must be an enum type \return \a _stream */ template< typename Enum > fcppt::io::ostream & output( fcppt::io::ostream &_stream, Enum const _value ) { static_assert( std::is_enum< Enum >::value, "Enum must be an enum type" ); return _stream << fcppt::enum_::to_string( _value ); } } } #endif
17.096774
78
0.711321
bd8cd24fba3ddb9a267618809b3a6ad818b1339b
945
hpp
C++
src/include/XEEditor/Editor.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
src/include/XEEditor/Editor.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
src/include/XEEditor/Editor.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
2
2019-08-29T10:23:51.000Z
2020-04-03T06:08:34.000Z
#ifndef EDITOR_HPP #define EDITOR_HPP #include <XEngine.hpp> #include <XEEditor/Event/Event.h> namespace EI { class EditorCommand; enum ObjType { Physic = 0, GameEntity = 1, }; enum Status { Unknown = 0, OK = 1, Error = 2, }; class Editor { public: Editor(); inline XE::XEngine* getEngine() { return m_engine; } void* InitState(const char* stateName, int width, int height); unsigned char* consoleCmd(const char* command, unsigned char* data, int len); bool moveToState(const char* stateName); void renderTargetSize(const char* rtName, Ogre::Real x, Ogre::Real y); // void test(sf::String str, std::function<void()> fkttest); int pushEvent(const sfEvent& event); private : // std::unordered_map<std::string, std::function<void(std::string)>> command_map; XE::XEngine* m_engine; //todo #################### XE::OgreConsole* m_console; EditorCommand* mEditorCommand; }; } #endif //EDITOR_HPP
20.106383
82
0.674074
bd8f12d6d2ef16317d360b1060caa92b0319eacb
373
cpp
C++
src/learn/test_bitset.cpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
src/learn/test_bitset.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
1
2015-05-26T07:40:19.000Z
2015-05-26T07:40:19.000Z
src/learn/test_bitset.cpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
#include "stdafx.h" #include "test_bitset.h" void test_bitset() { std::bitset<32> bt32; bt32.set(); assert(bt32.all()); bt32.reset(); assert(bt32.none()); bt32.set(0); assert(bt32.any()); assert(bt32.size() == 32); bt32.flip(); assert(bt32.count() == 31); bt32 <<= 15; std::cout << bt32.to_string('X', 'O') << std::endl; }
18.65
55
0.544236
bd93b99635fd75bddeaaea5d7980b57d005a85c0
21,349
cc
C++
src/tpl/vx_str.cc
eedsp/tlx
2555853646920168570bd630850dc22bc2cb327d
[ "Apache-2.0" ]
null
null
null
src/tpl/vx_str.cc
eedsp/tlx
2555853646920168570bd630850dc22bc2cb327d
[ "Apache-2.0" ]
null
null
null
src/tpl/vx_str.cc
eedsp/tlx
2555853646920168570bd630850dc22bc2cb327d
[ "Apache-2.0" ]
null
null
null
// // Created by Shiwon Cho on 2005.10.27. // #include <iostream> #include "vx_str.h" #define UPDATE_UCS_offset(p_offset_utf8, p_offset_utf8_s, pSTR, pSTR_len, p_offset_ucs) { \ int32_t __v_idx_utf8 = p_offset_utf8; \ while (__v_idx_utf8 < p_offset_utf8_s && __v_idx_utf8 < pSTR_len) \ { \ UChar32 __c = 0; \ U8_NEXT (pSTR, __v_idx_utf8, pSTR_len, __c); \ p_offset_ucs++; \ } \ } #define UPDATE_UCS_len(pSTR, pSTR_len, p_len_ucs) { \ int32_t __v_idx_utf8 = 0; \ while (__v_idx_utf8 < pSTR_len) \ { \ UChar32 __c = 0; \ U8_NEXT (pSTR, __v_idx_utf8, pSTR_len, __c); \ p_len_ucs++; \ } \ } static const char *_TPL_DEFAULT_TAG = "_PHRASE_"; vx_str::vx_str (apr_pool_t *p_pool, const hx_shm_rec_t *p_shm_t) { v_pool = nullptr; vSTR = nullptr; vSTR_len = 0; v_number_of_codes = 0; v_list_of_codes = nullptr; v_ctx_general = nullptr; v_error_code = v_error_offset = 0; v_name_count = nullptr; v_name_entry_size = nullptr; v_name_table = nullptr; v_name_entry_max_size = 0; v_match_context = nullptr; v_jit_stack = nullptr; v_match_data = nullptr; v_out_vector = nullptr; v_token_list = nullptr; v_status = APR_SUCCESS; v_status = apr_pool_create (&v_pool, p_pool); is_attached = false; vDB = p_shm_t; if (vDB && vDB->v_ptr) { is_attached = true; } } vx_str::~vx_str () { vSTR_len = 0; if (v_token_list) { vtx_delete (v_token_list); } if (v_status == APR_SUCCESS && v_pool) { apr_pool_destroy(v_pool); v_pool = NULL; } } void *vx_str::ctx_malloc (PCRE2_SIZE pSIZE, void *pFUNC) { #if defined(USE_TCMALLOC) void *block = (void *)tc_malloc ((size_t)pSIZE); #elif defined(USE_JEMALLOC) void *block = (void *) je_malloc((size_t) pSIZE); #else void *block = (void *)malloc ((size_t)pSIZE); #endif (void) pFUNC; return block; } void vx_str::ctx_free (void *pBLOCK, void *pFUNC) { (void) pFUNC; #if defined(USE_TCMALLOC) tc_free ((void *)pBLOCK); #elif defined(USE_JEMALLOC) je_free((void *) pBLOCK); #else free ((void *)pBLOCK); #endif } void vx_str::context_create () { if (!vDB || !is_attached) { return; } if (!vDB->v_ptr) { return; } v_number_of_codes = pcre2_serialize_get_number_of_codes ((const uint8_t *)vDB->v_ptr); if (v_number_of_codes > 0) { v_ctx_general = pcre2_general_context_create(ctx_malloc, ctx_free, NULL); v_list_of_codes = (pcre2_code **) apr_palloc(v_pool, sizeof(pcre2_code *) * v_number_of_codes); v_name_count = (int32_t *) apr_palloc(v_pool, sizeof(int32_t) * v_number_of_codes); v_name_table = (PCRE2_SPTR *) apr_palloc(v_pool, sizeof(PCRE2_SPTR) * v_number_of_codes); v_name_entry_size = (int32_t *) apr_palloc(v_pool, sizeof(int32_t) * v_number_of_codes); v_match_context = (pcre2_match_context **) apr_palloc(v_pool, sizeof(pcre2_match_context *) * v_number_of_codes); v_jit_stack = (pcre2_jit_stack **) apr_palloc(v_pool, sizeof(pcre2_jit_stack *) * v_number_of_codes); v_match_data = (pcre2_match_data **) apr_palloc(v_pool, sizeof(pcre2_match_data *) * v_number_of_codes); v_out_vector = (PCRE2_SIZE **) apr_palloc(v_pool, sizeof(PCRE2_SIZE *) * v_number_of_codes); pcre2_serialize_decode(v_list_of_codes, v_number_of_codes, (const uint8_t *)vDB->v_ptr, v_ctx_general); for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++) { pcre2_code *v_re = v_list_of_codes[v_idx_code]; pcre2_jit_compile(v_re, PCRE2_JIT_COMPLETE); (void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMECOUNT, &v_name_count[v_idx_code]); (void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMETABLE, &v_name_table[v_idx_code]); (void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMEENTRYSIZE, &v_name_entry_size[v_idx_code]); if (v_name_entry_max_size < v_name_entry_size[v_idx_code]) { v_name_entry_max_size = v_name_entry_size[v_idx_code]; } v_match_context[v_idx_code] = pcre2_match_context_create(NULL); pcre2_set_match_limit (v_match_context[v_idx_code], -1); pcre2_set_recursion_limit (v_match_context[v_idx_code], 1); v_jit_stack[v_idx_code] = pcre2_jit_stack_create(32 * 1024, 512 * 1024, NULL); pcre2_jit_stack_assign(v_match_context[v_idx_code], NULL, v_jit_stack[v_idx_code]); v_match_data[v_idx_code] = pcre2_match_data_create_from_pattern(v_re, NULL); v_out_vector[v_idx_code] = pcre2_get_ovector_pointer(v_match_data[v_idx_code]); } #if 0 re = pcre2_compile( (PCRE2_SPTR) pPATTERN, /* the pattern */ (PCRE2_SIZE) PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ PCRE2_UCP | PCRE2_UTF | PCRE2_DUPNAMES | PCRE2_CASELESS | PCRE2_ALLOW_EMPTY_CLASS, /* Option bits */ &v_error_code, /* for error code */ &v_error_offset, /* for error offset */ v_ctx_compile); /* use default compile context */ if (re != NULL) { pcre2_jit_compile(re, PCRE2_JIT_COMPLETE); (void) pcre2_pattern_info(re, PCRE2_INFO_NAMECOUNT, &v_name_count); (void) pcre2_pattern_info(re, PCRE2_INFO_NAMETABLE, &v_name_table); (void) pcre2_pattern_info(re, PCRE2_INFO_NAMEENTRYSIZE, &v_name_entry_size); } else { PCRE2_UCHAR8 vBUF[512]; (void) pcre2_get_error_message(v_error_code, vBUF, 512); std::cout << _INFO (v_pool) << __func__ << ":" << vBUF << std::endl << std::flush; } #endif } } void vx_str::context_free () { for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++) { pcre2_code *v_re = v_list_of_codes[v_idx_code]; pcre2_code_free (v_re); pcre2_match_data_free(v_match_data[v_idx_code]); /* Release memory used for the match */ pcre2_match_context_free(v_match_context[v_idx_code]); pcre2_jit_stack_free(v_jit_stack[v_idx_code]); } if (v_ctx_general) { pcre2_general_context_free(v_ctx_general); } } #if 0 void vx_str::read (const char *pSTR, int32_t pSTR_len) { uSTR.remove(); uSTR_len = 0; apr_pool_clear(v_pool_token); vSTR = NULL; vSTR_len = 0; uSTR = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len)); uSTR_len = uSTR.length(); std::string szUTF8_tmp(""); uSTR.toLower().toUTF8String(szUTF8_tmp); vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str()); vSTR_len = (int32_t) szUTF8_tmp.length(); szUTF8_tmp.clear(); } void vx_str::Text_normalize (const char *pSTR, int32_t pSTR_len, bool toLower) { UErrorCode status = U_ZERO_ERROR; uSTR.remove(); uSTR_len = 0; apr_pool_clear(v_pool_token); vSTR = NULL; vSTR_len = 0; const Normalizer2 &nNFC = *Normalizer2::getNFCInstance(status); if (U_SUCCESS(status)) { UnicodeString uSTR_tmp = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len)); status = U_ZERO_ERROR; uSTR = nNFC.normalize((toLower) ? uSTR_tmp.toLower() : uSTR_tmp, status); if (U_SUCCESS(status)) { std::string szUTF8_tmp(""); uSTR.toUTF8String(szUTF8_tmp); uSTR_len = uSTR.length(); vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str()); vSTR_len = (int32_t) szUTF8_tmp.length(); szUTF8_tmp.clear(); } } } void vx_str::normalize (const char *pSTR, int32_t pSTR_len) { if (U_SUCCESS(v_error_code_normlzer)) { uSTR.remove(); uSTR_len = 0; apr_pool_clear(v_pool_token); vSTR = NULL; vSTR_len = 0; UnicodeString uSTR_raw = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len)); UErrorCode status = U_ZERO_ERROR; uSTR = v_NFC->normalize((opt_toLowerCase) ? uSTR_raw.toLower() : uSTR_raw, status); if (U_SUCCESS(status)) { std::string szUTF8_tmp(""); uSTR.toUTF8String(szUTF8_tmp); uSTR_len = uSTR.length(); vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str()); vSTR_len = (int32_t) szUTF8_tmp.length(); szUTF8_tmp.clear(); } } } #endif PCRE2_SPTR vx_str::proc_token_tag (int32_t p_idx_code, int32_t p_offset_utf8, int32_t p_len_utf8, const PCRE2_SIZE *p_vector) { PCRE2_SPTR v_name = nullptr; PCRE2_SPTR p_table = v_name_table[p_idx_code]; int32_t n = 0; int32_t v_offset_utf8_s = 0; // 2 * n int32_t v_offset_utf8_e = 0; // 2 * n + 1 int32_t v_len_utf8 = 0; for (int32_t vIDX = 0; !v_name && vIDX < v_name_count[p_idx_code]; vIDX+=2) { if (!v_name && vIDX < v_name_count[p_idx_code]) { n = (p_table[0] << 8) | p_table[1]; v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1 v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s); if (v_offset_utf8_s == p_offset_utf8 && (v_len_utf8 > 0 && v_len_utf8 == p_len_utf8)) { v_name = (PCRE2_SPTR) p_table + 2; break; } p_table += v_name_entry_size[p_idx_code]; } if (!v_name && (vIDX + 1) < v_name_count[p_idx_code]) { n = (p_table[0] << 8) | p_table[1]; v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1 v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s); if (v_offset_utf8_s == p_offset_utf8 && (v_len_utf8 > 0 && v_len_utf8 == p_len_utf8)) { v_name = (PCRE2_SPTR) p_table + 2; break; } p_table += v_name_entry_size[p_idx_code]; } } return v_name; } #if 0 PCRE2_SPTR vx_str::proc_token_tag_all (int32_t p_idx_token, int32_t p_idx_code, int32_t p_offset_utf8, int32_t p_len_utf8, int32_t p_offset_ucs_s, const PCRE2_SIZE *p_vector) { PCRE2_SPTR v_name = NULL; PCRE2_SPTR p_name = v_name_table[p_idx_code]; // int32_t v_offset_utf8 = p_offset_utf8; // int32_t v_offset_ucs = p_offset_ucs_s; int32_t vFLAG = 1; for (int32_t vIDX = 0; vFLAG && vIDX < v_name_count[p_idx_code]; vIDX++) { int32_t n = (p_name[0] << 8) | p_name[1]; int32_t v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n int32_t v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1 int32_t v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s); if (v_len_utf8 > 0) { if ( v_name == NULL && (v_offset_utf8_s == p_offset_utf8 && v_len_utf8 == p_len_utf8) ) { v_name = (PCRE2_SPTR) p_name + 2; vFLAG = 0; break; } int32_t v_offset_utf8 = p_offset_utf8; int32_t v_offset_ucs = p_offset_ucs_s; PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s; UPDATE_UCS_offset (v_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs); // update UCS offset int32_t v_len_ucs = 0; UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length // std::cout << apr_psprintf (v_pool, " (%d)", n); // std::cout << apr_psprintf (v_pool, "[%2d/%d]", vIDX + 1, v_name_count); std::cout << apr_psprintf(v_pool, "%6d %5d(%3d) %5d(%3d)", p_idx_token, (int32_t) v_offset_ucs, (int32_t) v_len_ucs, (int32_t) v_offset_utf8_s, (int32_t) v_len_utf8 ); std::cout << apr_psprintf(v_pool, " [%*s]", v_name_entry_max_size - 3, (char *) (p_name + 2)); std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) v_len_utf8, v_ptr); std::cout << std::endl; } p_name += v_name_entry_size[p_idx_code]; } return v_name; } #endif void vx_str::tokenize (const char *pSTR, size_t pSTR_len) { if (!v_ctx_general || !v_number_of_codes) { return; } int32_t v_idx_token = 0; int32_t v_offset_utf8 = 0; int32_t v_offset_ucs = 0; int32_t v_offset_ucs_prev = -1; int32_t v_idx_sgmt = 0; int32_t v_idx_elt = 0; int32_t vFLAG = 1; vSTR = pSTR; vSTR_len = pSTR_len; if (v_token_list) { vtx_clear(v_token_list); } else { v_token_list = vtx_create(v_pool); } int32_t vIDX_code = v_number_of_codes - 1; pcre2_code *v_re = v_list_of_codes[vIDX_code]; for (; vFLAG && v_offset_utf8 < (int32_t)vSTR_len;) { uint32_t v_options = 0; /* Normally no options */ int32_t rc = pcre2_jit_match( v_re, /* the compiled pattern */ (PCRE2_SPTR) vSTR, /* the subject string */ (size_t) vSTR_len, /* the length of the subject */ (size_t) v_offset_utf8, /* start at offset 0 in the subject */ v_options, /* default options */ v_match_data[vIDX_code], /* block for storing the result */ v_match_context[vIDX_code]); /* use default match context */ if (rc == PCRE2_ERROR_NOMATCH) { vFLAG = 0; break; } else if (rc > 0) { int32_t v_offset_utf8_s = (int32_t) v_out_vector[vIDX_code][0]; // 2 * vIDX int32_t v_offset_utf8_e = (int32_t) v_out_vector[vIDX_code][1]; // 2 * vIDX + 1 int32_t v_len_utf8 = v_offset_utf8_e - v_offset_utf8_s; if (v_offset_utf8_e > 0 && v_len_utf8 > 0) { PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s; int32_t v_offset_ucs_s = v_offset_ucs; int32_t v_len_ucs = 0; UPDATE_UCS_offset (v_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs_s); // update UCS offset v_offset_ucs = v_offset_ucs_s; v_offset_utf8 = v_offset_utf8_e; UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length v_offset_ucs += v_len_ucs; PCRE2_SPTR v_name = proc_token_tag(vIDX_code, v_offset_utf8_s, v_len_utf8, (const PCRE2_SIZE *) v_out_vector[vIDX_code]); if (v_offset_ucs_prev != -1 && v_offset_ucs_prev != v_offset_ucs_s) { v_idx_sgmt++; v_idx_elt = 0; } #if 0 std::cout << apr_psprintf(v_pool, "%6d [%6d] <%5d>%5d(%3d) %5d(%3d)", v_idx_sgmt, v_idx_token, v_offset_ucs_prev, (int32_t) v_offset_ucs_s, (int32_t) v_len_ucs, (int32_t) v_offset_utf8_s, (int32_t) v_len_utf8 ); std::cout << apr_psprintf(v_pool, " [%*s]", v_name_entry_max_size - 3, (v_name == NULL) ? (char *) _TPL_DEFAULT_TAG : (char *) v_name); std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) v_len_utf8, (char *) v_ptr); std::cout << std::endl; #endif vtx_push_back (v_token_list, v_idx_token, v_idx_sgmt, v_idx_elt, (const char *) v_ptr, v_len_utf8, v_offset_ucs_s, v_len_ucs, v_offset_utf8_s, v_len_utf8, (v_name == NULL) ? _TPL_DEFAULT_TAG : (const char *) v_name); v_offset_ucs_prev = v_offset_ucs; v_idx_token++; v_idx_elt++; } // if v_offset_utf8_e > 0 } // if else else { std::cout << ">>> " << __LINE__ << ":" << v_offset_utf8 << ":" << rc << std::endl; vFLAG = 0; break; } } // for } void vx_str::print () { if (v_token_list) { vtx_print(v_token_list); } } const char * vx_str::dumps_text () { const char *v_buffer = nullptr; if (vDB && is_attached && v_token_list) { v_buffer = vtx_text_print(v_token_list); } return v_buffer; } const char * vx_str::dumps_json () { const char *v_buffer = nullptr; if (vDB && is_attached && v_token_list) { v_buffer = vtx_json_print(v_token_list); } return v_buffer; } #if 0 void vx_str::tokenize_2 () { int32_t v_offset_utf8 = 0; int32_t v_offset_ucs = 0; int32_t vFLAG = 1; int32_t vIDX_ = v_number_of_codes - 1; int32_t *flag_code = new int32_t[vIDX_]; for (int32_t vIDX = 0; vIDX < vIDX_; vIDX++) { flag_code[vIDX] = 1; } while (vFLAG && v_offset_utf8 < vSTR_len) { // std::cout << _INFO (v_pool) << apr_psprintf(v_pool, "%4d/%d", v_offset_utf8, vSTR_len) << std::endl << std::flush; int32_t v_offset_last_utf8 = vSTR_len; int32_t l_idx = -1; int32_t l_offset_ucs_s = 0; int32_t l_offset_utf8_s = 0; int32_t l_len_ucs = 0; int32_t l_len_utf8 = 0; for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++) { if (flag_code[v_idx_code] == 0) { continue; } pcre2_code *v_re = v_list_of_codes[v_idx_code]; int32_t t_offset_utf8 = v_offset_utf8; uint32_t v_options = 0; /* Normally no options */ int32_t rc = pcre2_jit_match( v_re, /* the compiled pattern */ (PCRE2_SPTR) vSTR, /* the subject string */ (size_t) vSTR_len, /* the length of the subject */ (size_t) t_offset_utf8, /* start at offset 0 in the subject */ v_options, /* default options */ v_match_data[v_idx_code], /* block for storing the result */ v_match_context[v_idx_code]); /* use default match context */ if (rc == PCRE2_ERROR_NOMATCH) { flag_code[v_idx_code] = 0; continue; } else if (rc > 0) { int32_t v_offset_utf8_s = (int32_t) v_out_vector[v_idx_code][0]; // 2 * vIDX int32_t v_offset_utf8_e = (int32_t) v_out_vector[v_idx_code][1]; // 2 * vIDX + 1 int32_t v_len_utf8 = v_offset_utf8_e - v_offset_utf8_s; if (v_offset_utf8_e > 0 && v_len_utf8 > 0) { PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s; int32_t v_offset_ucs_s = v_offset_ucs; int32_t v_len_ucs = 0; UPDATE_UCS_offset (t_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs_s); // update UCS offset UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length if (t_offset_utf8 < v_offset_last_utf8) { l_idx = v_idx_code; v_offset_last_utf8 = v_offset_utf8_s; l_offset_utf8_s = v_offset_utf8_s; l_offset_ucs_s = v_offset_ucs_s; l_len_utf8 = v_len_utf8; l_len_ucs = v_len_ucs; //std::cout << _INFO (v_pool) << apr_psprintf(v_pool, "%4d/%d", v_offset_utf8_s, vSTR_len) << std::endl << std::flush; } } // if v_offset_utf8_e > 0 } // if else } // for v_offset_utf8 = l_offset_utf8_s + l_len_utf8; v_offset_ucs = l_offset_ucs_s + l_len_ucs; if (l_idx >= 0) { PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + l_offset_utf8_s; PCRE2_SPTR v_name = proc_token_tag(l_idx, l_offset_utf8_s, l_len_utf8, l_offset_ucs_s, (const PCRE2_SIZE *) v_out_vector[l_idx]); if (v_name == NULL) { std::cout << apr_psprintf(v_pool, "%5d(%3d) %5d(%3d)", (int32_t) l_offset_ucs_s, (int32_t) l_len_ucs, (int32_t) l_offset_utf8_s, (int32_t) l_len_utf8 ); std::cout << apr_psprintf(v_pool, " (%*s)", v_name_entry_max_size - 3, (v_name == NULL) ? (char *) "_PHRASE" : (char *) v_name); std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) l_len_utf8, (char *) v_ptr); std::cout << std::endl; } } else{ vFLAG = 0; break; } } // while delete flag_code; } #endif
33.357813
174
0.569582
bd9602f84054a426411444026889ab544892332a
16,137
cc
C++
deps/v8/src/flow-graph.cc
blazzy/node
127c5fcb905f31887a15554650de48c9bde8722d
[ "MIT" ]
1
2022-01-25T02:52:54.000Z
2022-01-25T02:52:54.000Z
deps/v8/src/flow-graph.cc
blazzy/node
127c5fcb905f31887a15554650de48c9bde8722d
[ "MIT" ]
null
null
null
deps/v8/src/flow-graph.cc
blazzy/node
127c5fcb905f31887a15554650de48c9bde8722d
[ "MIT" ]
null
null
null
// Copyright 2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "flow-graph.h" namespace v8 { namespace internal { void FlowGraph::AppendInstruction(AstNode* instruction) { // Add a (non-null) AstNode to the end of the graph fragment. ASSERT(instruction != NULL); if (exit()->IsExitNode()) return; if (!exit()->IsBlockNode()) AppendNode(new BlockNode()); BlockNode::cast(exit())->AddInstruction(instruction); } void FlowGraph::AppendNode(Node* node) { // Add a node to the end of the graph. An empty block is added to // maintain edge-split form (that no join nodes or exit nodes as // successors to branch nodes). ASSERT(node != NULL); if (exit()->IsExitNode()) return; if (exit()->IsBranchNode() && (node->IsJoinNode() || node->IsExitNode())) { AppendNode(new BlockNode()); } exit()->AddSuccessor(node); node->AddPredecessor(exit()); exit_ = node; } void FlowGraph::AppendGraph(FlowGraph* graph) { // Add a flow graph fragment to the end of this one. An empty block is // added to maintain edge-split form (that no join nodes or exit nodes as // successors to branch nodes). ASSERT(graph != NULL); if (exit()->IsExitNode()) return; Node* node = graph->entry(); if (exit()->IsBranchNode() && (node->IsJoinNode() || node->IsExitNode())) { AppendNode(new BlockNode()); } exit()->AddSuccessor(node); node->AddPredecessor(exit()); exit_ = graph->exit(); } void FlowGraph::Split(BranchNode* branch, FlowGraph* left, FlowGraph* right, JoinNode* join) { // Add the branch node, left flowgraph, join node. AppendNode(branch); AppendGraph(left); AppendNode(join); // Splice in the right flowgraph. right->AppendNode(join); branch->AddSuccessor(right->entry()); right->entry()->AddPredecessor(branch); } void FlowGraph::Loop(JoinNode* join, FlowGraph* condition, BranchNode* branch, FlowGraph* body) { // Add the join, condition and branch. Add join's predecessors in // left-to-right order. AppendNode(join); body->AppendNode(join); AppendGraph(condition); AppendNode(branch); // Splice in the body flowgraph. branch->AddSuccessor(body->entry()); body->entry()->AddPredecessor(branch); } void ExitNode::Traverse(bool mark, ZoneList<Node*>* preorder, ZoneList<Node*>* postorder) { preorder->Add(this); postorder->Add(this); } void BlockNode::Traverse(bool mark, ZoneList<Node*>* preorder, ZoneList<Node*>* postorder) { ASSERT(successor_ != NULL); preorder->Add(this); if (!successor_->IsMarkedWith(mark)) { successor_->MarkWith(mark); successor_->Traverse(mark, preorder, postorder); } postorder->Add(this); } void BranchNode::Traverse(bool mark, ZoneList<Node*>* preorder, ZoneList<Node*>* postorder) { ASSERT(successor0_ != NULL && successor1_ != NULL); preorder->Add(this); if (!successor1_->IsMarkedWith(mark)) { successor1_->MarkWith(mark); successor1_->Traverse(mark, preorder, postorder); } if (!successor0_->IsMarkedWith(mark)) { successor0_->MarkWith(mark); successor0_->Traverse(mark, preorder, postorder); } postorder->Add(this); } void JoinNode::Traverse(bool mark, ZoneList<Node*>* preorder, ZoneList<Node*>* postorder) { ASSERT(successor_ != NULL); preorder->Add(this); if (!successor_->IsMarkedWith(mark)) { successor_->MarkWith(mark); successor_->Traverse(mark, preorder, postorder); } postorder->Add(this); } void FlowGraphBuilder::Build(FunctionLiteral* lit) { global_exit_ = new ExitNode(); VisitStatements(lit->body()); if (HasStackOverflow()) return; // The graph can end with a branch node (if the function ended with a // loop). Maintain edge-split form (no join nodes or exit nodes as // successors to branch nodes). if (graph_.exit()->IsBranchNode()) graph_.AppendNode(new BlockNode()); graph_.AppendNode(global_exit_); // Build preorder and postorder traversal orders. All the nodes in // the graph have the same mark flag. For the traversal, use that // flag's negation. Traversal will flip all the flags. bool mark = graph_.entry()->IsMarkedWith(false); graph_.entry()->MarkWith(mark); graph_.entry()->Traverse(mark, &preorder_, &postorder_); } // This function peels off one iteration of a for-loop. The return value // is either a block statement containing the peeled loop or NULL in case // there is a stack overflow. static Statement* PeelForLoop(ForStatement* stmt) { // Mark this for-statement as processed. stmt->set_peel_this_loop(false); // Create new block containing the init statement of the for-loop and // an if-statement containing the peeled iteration and the original // loop without the init-statement. Block* block = new Block(NULL, 2, false); if (stmt->init() != NULL) { Statement* init = stmt->init(); // The init statement gets the statement position of the for-loop // to make debugging of peeled loops possible. init->set_statement_pos(stmt->statement_pos()); block->AddStatement(init); } // Copy the condition. CopyAstVisitor copy_visitor; Expression* cond_copy = stmt->cond() != NULL ? copy_visitor.DeepCopyExpr(stmt->cond()) : new Literal(Factory::true_value()); if (copy_visitor.HasStackOverflow()) return NULL; // Construct a block with the peeled body and the rest of the for-loop. Statement* body_copy = copy_visitor.DeepCopyStmt(stmt->body()); if (copy_visitor.HasStackOverflow()) return NULL; Statement* next_copy = stmt->next() != NULL ? copy_visitor.DeepCopyStmt(stmt->next()) : new EmptyStatement(); if (copy_visitor.HasStackOverflow()) return NULL; Block* peeled_body = new Block(NULL, 3, false); peeled_body->AddStatement(body_copy); peeled_body->AddStatement(next_copy); peeled_body->AddStatement(stmt); // Remove the duplicated init statement from the for-statement. stmt->set_init(NULL); // Create new test at the top and add it to the newly created block. IfStatement* test = new IfStatement(cond_copy, peeled_body, new EmptyStatement()); block->AddStatement(test); return block; } void FlowGraphBuilder::VisitStatements(ZoneList<Statement*>* stmts) { for (int i = 0, len = stmts->length(); i < len; i++) { stmts->at(i) = ProcessStatement(stmts->at(i)); } } Statement* FlowGraphBuilder::ProcessStatement(Statement* stmt) { if (FLAG_loop_peeling && stmt->AsForStatement() != NULL && stmt->AsForStatement()->peel_this_loop()) { Statement* tmp_stmt = PeelForLoop(stmt->AsForStatement()); if (tmp_stmt == NULL) { SetStackOverflow(); } else { stmt = tmp_stmt; } } Visit(stmt); return stmt; } void FlowGraphBuilder::VisitDeclaration(Declaration* decl) { UNREACHABLE(); } void FlowGraphBuilder::VisitBlock(Block* stmt) { VisitStatements(stmt->statements()); } void FlowGraphBuilder::VisitExpressionStatement(ExpressionStatement* stmt) { Visit(stmt->expression()); } void FlowGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) { // Nothing to do. } void FlowGraphBuilder::VisitIfStatement(IfStatement* stmt) { Visit(stmt->condition()); BranchNode* branch = new BranchNode(); FlowGraph original = graph_; graph_ = FlowGraph::Empty(); stmt->set_then_statement(ProcessStatement(stmt->then_statement())); FlowGraph left = graph_; graph_ = FlowGraph::Empty(); stmt->set_else_statement(ProcessStatement(stmt->else_statement())); if (HasStackOverflow()) return; JoinNode* join = new JoinNode(); original.Split(branch, &left, &graph_, join); graph_ = original; } void FlowGraphBuilder::VisitContinueStatement(ContinueStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitBreakStatement(BreakStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitWithEnterStatement(WithEnterStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitWithExitStatement(WithExitStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitWhileStatement(WhileStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitForStatement(ForStatement* stmt) { if (stmt->init() != NULL) stmt->set_init(ProcessStatement(stmt->init())); JoinNode* join = new JoinNode(); FlowGraph original = graph_; graph_ = FlowGraph::Empty(); if (stmt->cond() != NULL) Visit(stmt->cond()); BranchNode* branch = new BranchNode(); FlowGraph condition = graph_; graph_ = FlowGraph::Empty(); stmt->set_body(ProcessStatement(stmt->body())); if (stmt->next() != NULL) stmt->set_next(ProcessStatement(stmt->next())); if (HasStackOverflow()) return; original.Loop(join, &condition, branch, &graph_); graph_ = original; } void FlowGraphBuilder::VisitForInStatement(ForInStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitTryFinallyStatement(TryFinallyStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) { SetStackOverflow(); } void FlowGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitSharedFunctionInfoLiteral( SharedFunctionInfoLiteral* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitConditional(Conditional* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitSlot(Slot* expr) { UNREACHABLE(); } void FlowGraphBuilder::VisitVariableProxy(VariableProxy* expr) { graph_.AppendInstruction(expr); } void FlowGraphBuilder::VisitLiteral(Literal* expr) { graph_.AppendInstruction(expr); } void FlowGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitCatchExtensionObject(CatchExtensionObject* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitAssignment(Assignment* expr) { Variable* var = expr->target()->AsVariableProxy()->AsVariable(); Property* prop = expr->target()->AsProperty(); // Left-hand side can be a variable or property (or reference error) but // not both. ASSERT(var == NULL || prop == NULL); if (var != NULL) { if (expr->is_compound()) Visit(expr->target()); Visit(expr->value()); if (var->IsStackAllocated()) { // The first definition in the body is numbered n, where n is the // number of parameters and stack-allocated locals. expr->set_num(body_definitions_.length() + variable_count_); body_definitions_.Add(expr); } } else if (prop != NULL) { Visit(prop->obj()); if (!prop->key()->IsPropertyName()) Visit(prop->key()); Visit(expr->value()); } if (HasStackOverflow()) return; graph_.AppendInstruction(expr); } void FlowGraphBuilder::VisitThrow(Throw* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitProperty(Property* expr) { Visit(expr->obj()); if (!expr->key()->IsPropertyName()) Visit(expr->key()); if (HasStackOverflow()) return; graph_.AppendInstruction(expr); } void FlowGraphBuilder::VisitCall(Call* expr) { Visit(expr->expression()); ZoneList<Expression*>* arguments = expr->arguments(); for (int i = 0, len = arguments->length(); i < len; i++) { Visit(arguments->at(i)); } if (HasStackOverflow()) return; graph_.AppendInstruction(expr); } void FlowGraphBuilder::VisitCallNew(CallNew* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitCallRuntime(CallRuntime* expr) { SetStackOverflow(); } void FlowGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) { switch (expr->op()) { case Token::NOT: case Token::BIT_NOT: case Token::DELETE: case Token::TYPEOF: case Token::VOID: SetStackOverflow(); break; case Token::ADD: case Token::SUB: Visit(expr->expression()); if (HasStackOverflow()) return; graph_.AppendInstruction(expr); break; default: UNREACHABLE(); } } void FlowGraphBuilder::VisitCountOperation(CountOperation* expr) { Visit(expr->expression()); Variable* var = expr->expression()->AsVariableProxy()->AsVariable(); if (var != NULL && var->IsStackAllocated()) { // The first definition in the body is numbered n, where n is the number // of parameters and stack-allocated locals. expr->set_num(body_definitions_.length() + variable_count_); body_definitions_.Add(expr); } if (HasStackOverflow()) return; graph_.AppendInstruction(expr); } void FlowGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) { switch (expr->op()) { case Token::COMMA: case Token::OR: case Token::AND: SetStackOverflow(); break; case Token::BIT_OR: case Token::BIT_XOR: case Token::BIT_AND: case Token::SHL: case Token::SHR: case Token::ADD: case Token::SUB: case Token::MUL: case Token::DIV: case Token::MOD: case Token::SAR: Visit(expr->left()); Visit(expr->right()); if (HasStackOverflow()) return; graph_.AppendInstruction(expr); break; default: UNREACHABLE(); } } void FlowGraphBuilder::VisitCompareOperation(CompareOperation* expr) { switch (expr->op()) { case Token::EQ: case Token::NE: case Token::EQ_STRICT: case Token::NE_STRICT: case Token::INSTANCEOF: case Token::IN: SetStackOverflow(); break; case Token::LT: case Token::GT: case Token::LTE: case Token::GTE: Visit(expr->left()); Visit(expr->right()); if (HasStackOverflow()) return; graph_.AppendInstruction(expr); break; default: UNREACHABLE(); } } void FlowGraphBuilder::VisitThisFunction(ThisFunction* expr) { SetStackOverflow(); } } } // namespace v8::internal
27.397284
78
0.685939
bd97711b92e2f01bc90806429d49e045296546de
961
hpp
C++
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
leighgarbs/toolbox
fd9ceada534916fa8987cfcb5220cece2188b304
[ "MIT" ]
null
null
null
#if !defined CONFIGURATION_PARAMETER_TEMPLATE_BASE_TEST_HPP #define CONFIGURATION_PARAMETER_TEMPLATE_BASE_TEST_HPP #include "Test.hpp" #include "TestCases.hpp" #include "TestMacros.hpp" #include "ConfigurationParameterTemplateBase.hpp" namespace Configuration { TEST_CASES_BEGIN(ParameterTemplateBase_test) TEST_CASES_BEGIN(SetValue) TEST(Bool) TEST(String) TEST(Char) TEST(Double) TEST(Float) TEST(Int) TEST(Long) TEST(LongDouble) TEST(LongLong) TEST(Short) TEST(UnsignedChar) TEST(UnsignedInt) TEST(UnsignedLong) TEST(UnsignedLongLong) TEST(UnsignedShort) template <class T> static Test::Result test(const T& initial_value, const T& set_value); TEST_CASES_END(SetValue) TEST_CASES_END(ParameterTemplateBase_test) } #endif
23.439024
81
0.630593
bd98395a457e90264d2f4dca55fd2dea7fdec95d
133
cc
C++
gcc/libjava/include/jrate/sched/Runnable.cc
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
1
2021-06-15T05:43:22.000Z
2021-06-15T05:43:22.000Z
src/native/src/jrate/sched/Runnable.cc
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
null
null
null
src/native/src/jrate/sched/Runnable.cc
giraffe/jrate
764bbf973d1de4e38f93ba9b9c7be566f1541e16
[ "Xnet", "Linux-OpenIB", "X11" ]
null
null
null
#include <jrate/sched/Runnable.h> jrate::sched::Runnable jrate::sched::Runnable::NoAction; jrate::sched::Runnable::~Runnable() { }
22.166667
56
0.721805
bd9aa5fcefffa258da01289c607f52f9f3d35378
211
cpp
C++
DeSpeect/Test/View_idTest.cpp
matteo-rizzo/DeSpeect
843b74f00016538fd4a6a0ec9641a72f000998a2
[ "MIT" ]
null
null
null
DeSpeect/Test/View_idTest.cpp
matteo-rizzo/DeSpeect
843b74f00016538fd4a6a0ec9641a72f000998a2
[ "MIT" ]
null
null
null
DeSpeect/Test/View_idTest.cpp
matteo-rizzo/DeSpeect
843b74f00016538fd4a6a0ec9641a72f000998a2
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "id.h" TEST(Graph, VerifyId){ ID a("a","a"); ID b("b","b"); EXPECT_FALSE(a==b); } TEST(Graph, VerifyIdEq){ ID a("a","a"); ID b=a; EXPECT_TRUE(a==b); }
14.066667
24
0.521327
bd9b12228ccc2ec5a596febb0d777eee80ebcef0
1,052
cpp
C++
MonoDumperKit/src/main.cpp
MikaCybertron/MonoDumperKit
23fa6fa1b3af47abc4175fc2dedcf57078176fb5
[ "MIT" ]
2
2021-11-20T19:05:48.000Z
2021-12-02T21:34:23.000Z
MonoDumperKit/src/main.cpp
MikaCybertron/MonoDumperKit
23fa6fa1b3af47abc4175fc2dedcf57078176fb5
[ "MIT" ]
null
null
null
MonoDumperKit/src/main.cpp
MikaCybertron/MonoDumperKit
23fa6fa1b3af47abc4175fc2dedcf57078176fb5
[ "MIT" ]
2
2020-04-14T08:06:59.000Z
2022-01-26T06:33:52.000Z
// // main.cpp // // Created by MJ (Ruit) on 2/3/19. // #include <pthread.h> #include "Dumper.h" #include "Utils.h" void *mono_dump_thread(void *args); __attribute__((constructor)) void init() { LOGD("Hello cats from MonoDumperKit!"); pthread_t dumpTID; pthread_create(&dumpTID, NULL, mono_dump_thread, NULL); } void *mono_dump_thread(void *args){ LOGD("Looking for libmono.so"); ProcMap monoMap; do { monoMap = getLibraryMap("libmono.so"); sleep(1); } while (!monoMap.isValid()); LOGD("Initializing mono exports..."); Mono::initialize_exports(); LOGD("Creating dump folder..."); // dump to app's external files directory since it does't need storage permission or root std::string exStorage = getenv("EXTERNAL_STORAGE"); std::string dir = exStorage + "/Android/data/" + getProcName() + "/files/dumpDir"; mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); LOGD("Dump folder: %s", dir.c_str()); MonoDumper::Dump_DLLs(dir.c_str()); return NULL; }
22.382979
93
0.646388
bd9d4dc9dfce443023372e920c45c77eed31b9ad
1,743
cc
C++
vize/src/vize/factory/async_volume_document_factory.cc
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
47
2020-03-30T14:36:46.000Z
2022-03-06T07:44:54.000Z
vize/src/vize/factory/async_volume_document_factory.cc
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
null
null
null
vize/src/vize/factory/async_volume_document_factory.cc
oprogramadorreal/vize
042c16f96d8790303563be6787200558e1ec00b2
[ "MIT" ]
8
2020-04-01T01:22:45.000Z
2022-01-02T13:06:09.000Z
#include "vize/factory/async_volume_document_factory.hpp" #include "vize/factory/volume_factory.hpp" #include "vize/document/volume_document.hpp" namespace vize { AsyncVolumeDocumentFactory::AsyncVolumeDocumentFactory(VolumeDocument& document, std::unique_ptr<VolumeFactory> factory) : _document(document), _volumeFactory(std::move(factory)) { _volumeFactory.connectToVolumeBuiltSignal(std::bind(&AsyncVolumeDocumentFactory::_volumeBuilt, this, std::placeholders::_1, std::placeholders::_2)); } AsyncVolumeDocumentFactory::~AsyncVolumeDocumentFactory() = default; void AsyncVolumeDocumentFactory::run() { _volumeFactory.run(); } bool AsyncVolumeDocumentFactory::isRunning() const { return _volumeFactory.isRunning(); } void AsyncVolumeDocumentFactory::showProgressDialog(const std::string& progressDialogTitle) { _volumeFactory.showProgressDialog(progressDialogTitle); } void AsyncVolumeDocumentFactory::addVolumeImagesDirectory(const std::string& imagesDirectory) { _volumeFactory.addVolumeImagesDirectory(imagesDirectory); } void AsyncVolumeDocumentFactory::addVolumeImage(const std::string& imageFile) { _volumeFactory.addVolumeImage(imageFile); } void AsyncVolumeDocumentFactory::clearVolumeImages() { _volumeFactory.clearVolumeImages(); } void AsyncVolumeDocumentFactory::_volumeBuilt(const std::shared_ptr<Volume>& volume, const std::string& volumeName) { if (volume) { _document.setDocumentName(volumeName); _document.setVolume(volume); _documentBuilt(_document, *volume); } else { AYLA_DEBUG_MESSAGE("Unable to create volume."); } } boost::signals2::connection AsyncVolumeDocumentFactory::connectToDocumentBuiltSignal(DocumentBuiltSignalListener listener) { return _documentBuilt.connect(listener); } }
32.277778
149
0.815835
bd9ec24d3dab1b3d9fab7650571cb40639a1c1ec
61,331
cpp
C++
src/NLO_PL.cpp
gvita/RHEHpt
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
[ "MIT" ]
null
null
null
src/NLO_PL.cpp
gvita/RHEHpt
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
[ "MIT" ]
null
null
null
src/NLO_PL.cpp
gvita/RHEHpt
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
[ "MIT" ]
null
null
null
#include "NLO_PL.h" #include "cuba.h" #include <gsl/gsl_sf_dilog.h> /*double B2pp_ANALITIC(long double x, long double xp) { return(1./3.*3.*5.*(2.+3.*xp)/(xp*(1.+xp))*std::log(x)); }*/ //Used to cross-check the complete form above long double B2pp_ANALITICS(long double x, long double xp){ long double ymax=0.5*std::log((1.+std::sqrt(1.-4.*x*(1.+xp)/std::pow(1.+x,2)))/(1.-std::sqrt(1.-4.*x*(1.+xp)/std::pow(1.+x,2)))); long double wmax=std::exp(ymax); long double R1=1./12.*x*xp*(1./std::sqrt(x)*(1./wmax*(2.+3.*x)*std::sqrt(1.+xp)) -2.*std::pow(wmax,2)*x*(1.+xp)-8.*std::pow(x,5)*xp*xp*std::pow(1.+xp,3)/(3.*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),3)) +4.*x/(wmax*std::sqrt(x*(1.+xp))-x)+wmax*std::sqrt(1.+xp)*(2.+3.*x-8.*x*x*(1.+2.*xp))/std::sqrt(x) +2.*x*x*x*xp*std::pow(1.+xp,2)*(1.+x*x*(1.+7.*xp)-x*(4.+7.*xp))/((x-1.)*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),2)) -(4.*x*(2.*(1.+xp)+2.*x*xp*(1.+xp)+x*x*(-3.+4.*xp+18.*xp*xp+11.*xp*xp*xp)+x*x*x*x*(2.+9.*xp+18.*xp*xp+11.*xp*xp*xp)-x*x*x*(1.+15.*xp+36.*xp*xp+22.*xp*xp*xp))) /(std::pow(x-1.,2)*(x+x*xp-wmax*std::sqrt(x*(1.+xp)))) -(-2.+3.*x+x*x+2.*xp-3.*x*xp)*std::log(wmax*std::sqrt(x*(1.+xp)))/x -((2.+2.*xp-2.*xp*xp*xp+std::pow(x,6)*(2.+xp)-3.*std::pow(x,5)*(4.+3.*xp)+std::pow(x,4)*(30.+26.*xp+4.*xp*xp-3.*xp*xp*xp) -x*(12.+23.*xp+4.*xp*xp+3.*xp*xp*xp)-std::pow(x,3)*(40.+48.*xp+9.*xp*xp*xp)+x*x*(30.+51.*xp+9.*xp*xp*xp))*std::log(1.+xp-wmax*std::sqrt(x*(1.+xp)))) /(std::pow(x-1.,3)*x*(x-xp-1.)*xp) -1./(x*xp*(x-xp-1.))*(4.*x*x*x*x+x*x*x*(10.+xp)-2.*x*x*(3.+5.*xp)+2.*(1.-xp+xp*xp*xp)-x*(2.+7.*xp+3.*xp*xp*xp))*std::log(-x+wmax*std::sqrt(x*(1.+xp))) -1./(std::pow(x-1.,3)*x*xp)*4.*(-1.+2.*x*(2.+xp)-x*x*(5.+6.*xp+3.*xp*xp)-6.*std::pow(x,5)*xp*(2.+6.*xp+5.*xp*xp) -x*x*x*xp*(1.+8.*xp+10.*xp*xp)+std::pow(x,6)*(-1.+3.*xp+12.*xp*xp+10.*xp*xp*xp) +std::pow(x,4)*(3.+14.*xp+33.*xp*xp+30.*xp*xp*xp))*std::log(wmax*std::sqrt(x*(1.+xp))-x*(1.+xp))); ymax=std::log(((1.+x)-std::sqrt(std::pow(1.-x,2)-4.*x*xp))/(2.*std::sqrt(x*(1.+xp)))); wmax=std::exp(ymax); long double R2=1./12.*x*xp*(1./std::sqrt(x)*(1./wmax*(2.+3.*x)*std::sqrt(1.+xp)) -2.*std::pow(wmax,2)*x*(1.+xp)-8.*std::pow(x,5)*xp*xp*std::pow(1.+xp,3)/(3.*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),3)) +4.*x/(wmax*std::sqrt(x*(1.+xp))-x)+wmax*std::sqrt(1.+xp)*(2.+3.*x-8.*x*x*(1.+2.*xp))/std::sqrt(x) +2.*x*x*x*xp*std::pow(1.+xp,2)*(1.+x*x*(1.+7.*xp)-x*(4.+7.*xp))/((x-1.)*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),2)) -(4.*x*(2.*(1.+xp)+2.*x*xp*(1.+xp)+x*x*(-3.+4.*xp+18.*xp*xp+11.*xp*xp*xp)+x*x*x*x*(2.+9.*xp+18.*xp*xp+11.*xp*xp*xp)-x*x*x*(1.+15.*xp+36.*xp*xp+22.*xp*xp*xp))) /(std::pow(x-1.,2)*(x+x*xp-wmax*std::sqrt(x*(1.+xp)))) -(-2.+3.*x+x*x+2.*xp-3.*x*xp)*std::log(wmax*std::sqrt(x*(1.+xp)))/x -((2.+2.*xp-2.*xp*xp*xp+std::pow(x,6)*(2.+xp)-3.*std::pow(x,5)*(4.+3.*xp)+std::pow(x,4)*(30.+26.*xp+4.*xp*xp-3.*xp*xp*xp) -x*(12.+23.*xp+4.*xp*xp+3.*xp*xp*xp)-std::pow(x,3)*(40.+48.*xp+9.*xp*xp*xp)+x*x*(30.+51.*xp+9.*xp*xp*xp))*std::log(1.+xp-wmax*std::sqrt(x*(1.+xp)))) /(std::pow(x-1.,3)*x*(x-xp-1.)*xp) -1./(x*xp*(x-xp-1.))*(4.*x*x*x*x+x*x*x*(10.+xp)-2.*x*x*(3.+5.*xp)+2.*(1.-xp+xp*xp*xp)-x*(2.+7.*xp+3.*xp*xp*xp))*std::log(-x+wmax*std::sqrt(x*(1.+xp))) -1./(std::pow(x-1.,3)*x*xp)*4.*(-1.+2.*x*(2.+xp)-x*x*(5.+6.*xp+3.*xp*xp)-6.*std::pow(x,5)*xp*(2.+6.*xp+5.*xp*xp) -x*x*x*xp*(1.+8.*xp+10.*xp*xp)+std::pow(x,6)*(-1.+3.*xp+12.*xp*xp+10.*xp*xp*xp) +std::pow(x,4)*(3.+14.*xp+33.*xp*xp+30.*xp*xp*xp))*std::log(wmax*std::sqrt(x*(1.+xp))-x*(1.+xp))); long double R3=-1./6.*(1.+x*x-x*(2.+xp))*(std::log(x)+std::log(1.+xp)+2.*std::log(2)-2.*std::log(1.+x+std::sqrt((1.-x)*(1.-x)-4.*x*xp))); return(2./xp*(R1-R2+R3)); } //Delta contribution //gg channel long double NLOPL::NLO_PL_delta(double xp){ const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); const long double MUR=pow(_muR/_mH,2.); const long double MUF=pow(_muF/_mH,2.); const long double b0=11./6.*_Nc-1./3.*_Nf; const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc)); const long double delta=3./2.*b0*(std::log(MUR*x/(-t))+std::log(MUR*x/(-u)))+(67./18.*_Nc-5./9.*_Nf); const long double U=1./2.*std::pow(std::log(u/t),2.)+M_PIl*M_PIl/3.-std::log(x)*std::log(x/(-t))-std::log(x)*std::log(x/(-u)) -std::log(x/(-t))*std::log(x/(-u))+std::pow(std::log(x),2.)+std::pow(std::log(x/(x-t)),2.)+std::pow(std::log(x/(x-u)),2.) +2.*gsl_sf_dilog(1.-x)+2.*gsl_sf_dilog(x/(x-t))+2.*gsl_sf_dilog(x/(x-u)); const long double ris=x*(Delta+delta+_Nc*U)*_Nc*(pow(x,4)+1.+pow(t,4)+pow(u,4))/(u*t) +(_Nc-_Nf)*_Nc/3.*(x*x+(x*x/t)+(x*x/u)+x); const long double Jac1=-(1.-x-rad)/(2.*rad); const long double Jac2=(1.-x+rad)/(2.*rad); const long double Si5z1=1./t*(std::pow(x,4)+1.+std::pow(t,4)+std::pow(u,4))/(u*t)*std::log(x*MUF/(-t)); const long double Si5z2=1./u*(std::pow(x,4)+1.+std::pow(u,4)+std::pow(t,4))/(u*t)*std::log(x*MUF/(-u)); return (ris/rad*2.+2.*x*_Nc*b0*(Jac2*Si5z2-Jac1*Si5z1)+_Nc*_Nf*B2pp_ANALITICS(x,xp)); } //gq channel long double NLOPL::NLO_PL_delta_gq(double xp){ const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); const long double MUR=pow(_muR/_mH,2.); const long double MUF=pow(_muF/_mH,2.); const long double b0=11./6.*_Nc-1./3.*_Nf; const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc)); const long double V11=0.5*std::pow(std::log(u/t),2.)+0.5*std::pow(std::log(1./(-u)),2.)-0.5*std::pow(std::log(1./(-t)),2.) -std::log(x)*std::log((-t)/x)+std::log(x)*std::log((-u)/x)-std::log((-t)/x)*std::log((-u)/x) +2.*dilog_r(x/(x-u))+std::pow(std::log(x/(x-u)),2.)+M_PIl*M_PIl; const long double V21=std::pow(std::log(x),2)+std::pow(std::log(x/(x-t)),2)-2.*std::log(1./x)*std::log((-t)/x)+2.*dilog_r(1.-x) +2.*dilog_r(x/(x-t))-7./2.-2.*M_PIl*M_PIl/3.; const long double V31=b0*(2.*std::log(MUR*x/(-u))+std::log(MUR*x/(-t)))+(67./9.*_Nc-10./9.*_Nf); const long double V12=0.5*std::pow(std::log(t/u),2.)+0.5*std::pow(std::log(1./(-t)),2.)-0.5*std::pow(std::log(1./(-u)),2.) -std::log(x)*std::log((-u)/x)+std::log(x)*std::log((-t)/x)-std::log((-u)/x)*std::log((-t)/x) +2.*dilog_r(x/(x-t))+std::pow(std::log(x/(x-t)),2.)+M_PIl*M_PIl; const long double V22=std::pow(std::log(x),2)+std::pow(std::log(x/(x-u)),2)-2.*std::log(1./x)*std::log((-u)/x)+2.*dilog_r(1.-x) +2.*dilog_r(x/(x-u))-7./2.-2.*M_PIl*M_PIl/3.; const long double V32=b0*(2.*std::log(MUR*x/(-t))+std::log(MUR*x/(-u)))+(67./9.*_Nc-10./9.*_Nf); long double ris=0.; ris+=x*((Delta+_Nc*V11+_Cf*V21+V31)*_Cf*(1.+t*t)/(-u)+(_Nc-_Cf)*_Cf*((1.+t*t+u*u-u*x)/(-u))); ris+=x*((Delta+_Nc*V12+_Cf*V22+V32)*_Cf*(1.+u*u)/(-t)+(_Nc-_Cf)*_Cf*((1.+u*u+t*t-t*x)/(-t))); const long double Jac1=-(1.-x-rad)/(2.*rad); const long double Jac2=(1.-x+rad)/(2.*rad); const long double Sideltaz1=x/t*b0*std::log(MUF*x/(-t))*(1.+t*t)/(-x*xp/(t)); const long double Sideltaz2=x/u*b0*std::log(MUF*x/(-u))*(1.+u*u)/(-x*xp/(u)); const long double Sideltazb1=x/(t)*3./2.*_Cf*std::log(MUF*x/(-t))*_Cf*(1.+u*u)/(-t); const long double Sideltazb2=x/(u)*3./2.*_Cf*std::log(MUF*x/(-u))*_Cf*(1.+t*t)/(-u); return(ris/rad+Jac2*(Sideltaz2+Sideltazb2)-Jac1*(Sideltaz1+Sideltazb1)); // OK } //qqbar channel long double NLOPL::NLO_PL_delta_qqbar(double xp){ const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); const long double MUR=pow(_muR/_mH,2.); const long double MUF=pow(_muF/_mH,2.); const long double b0=11./6.*_Nc-1./3.*_Nf; const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc)); const long double W1=std::log(-u/x)*std::log(-t/x)-std::log(1./x)*std::log(-u/x)-std::log(1./x)*std::log(-t/x) +2.*dilog_r(1.-x)+std::pow(std::log(x),2)-0.5*std::pow(std::log(u/t),2)-5./3.*M_PIl*M_PIl; const long double W2=3./2.*(std::log(1./(-t))+std::log(1./(-u)))+std::pow(std::log(u/t),2)-2.*std::log(-u/x)*std::log(-t/x) +std::pow(std::log(x/(x-u)),2)+std::pow(std::log(x/(x-t)),2)+2.*dilog_r(x/(x-u))+2.*dilog_r(x/(x-t))-7.+2.*M_PIl*M_PIl; const long double W3=b0/2.*(4.*std::log(MUR*x)+std::log(MUR*x/(-u))+std::log(MUR*x/(-t)))+(67./6.*_Nc-5./3.*_Nf); const long double ris=x*((Delta+_Nc*W1+_Cf*W2+W3)*2.*_Cf*_Cf*(t*t+u*u)+(_Nc-_Cf)*2.*_Cf*_Cf*((t*t+u*u+1.-x))); const long double Jac1=-(1.-x-rad)/(2.*rad); const long double Jac2=(1.-x+rad)/(2.*rad); const long double Sidelta1=2.*x/(t)*_Cf*3./2.*std::log(MUF*x/(-t))*2.*_Cf*_Cf*(x*x*xp*xp/(t*t)+t*t); const long double Sidelta2=2.*x/(u)*_Cf*3./2.*std::log(MUF*x/(-u))*2.*_Cf*_Cf*(x*x*xp*xp/(u*u)+u*u); return (2.*ris/rad+Jac2*Sidelta2-Jac1*Sidelta1); //OK No Logs //return 0; } //Singular Part //gg channel long double NLOPL::NLO_PL_sing_doublediff(double xp, double zz) { long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable za const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double muF=_muF; const long double muR=_muR; const long double b0=11./6.*Nc-1./3.*Nf; const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); const long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); const long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); //Define and add the different singular parts const long double Si12=2.*xx/(-t2)*(1.+std::pow(z,4)+std::pow(1.-z,4))/(z)*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t2,4)+std::pow(xx*xp*z/t2,4))/(z*z*xx*xp); const long double Si11=2.*xx/(-t1)*(1.+std::pow(z,4)+std::pow(1.-z,4))/(z)*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t1,4)+std::pow(xx*xp*z/t1,4))/(z*z*xx*xp); const long double Si12z1=16.*Nc*Nc*(1.+std::pow(xx,4)-2.*xx*(1.+xp)-2*xx*xx*xx*(1.+xp)+xx*xx*(3.+4.*xp+xp*xp))/(xp*(1.-xx+sqrt(1.-2.*xx+xx*xx-4.*xx*xp))); const long double Si11z1=16.*Nc*Nc*(1.+std::pow(xx,4)-2.*xx*(1.+xp)-2*xx*xx*xx*(1.+xp)+xx*xx*(3.+4.*xp+xp*xp))/(xp*(1.-xx-sqrt(1.-2.*xx+xx*xx-4.*xx*xp))); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); const long double Si21=2.*xx*(z/(-t1))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1,4)+std::pow(t1,4))+z*zb1*(std::pow(xx,4) +1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1); const long double Si22=2.*xx*(z/(-t2))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2,4)+std::pow(t2,4))+z*zb2*(std::pow(xx,4) +1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2); const long double Si21z1=(8.*Nc*Nc*(-std::pow(1.+(xx-1.)*xx,2)+2.*std::pow(1.-xx,2)*xx*xp-xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si22z1=(8.*Nc*Nc*(-std::pow(1.+(xx-1.)*xx,2)+2.*std::pow(1.-xx,2)*xx*xp-xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); const long double Si31=2.*xx*(z/(-t1))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1,4)+std::pow(t1,4))+z*zb1*(std::pow(xx,4) +1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1)*(std::log(Qt1*z/(-t1))); const long double Si32=2.*xx*(z/(-t2))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2,4)+std::pow(t2,4))+z*zb2*(std::pow(xx,4) +1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2)*(std::log(Qt2*z/(-t2))); const long double Si31z1=-(8.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp))) *std::log(2.*xx*xp/(1.-xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si32z1=-(8.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp))) *std::log(2.*xx*xp/(1.-xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=-1./(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); const long double Si41=2.*xx*(z/t1)*b0*Nc/2.*(std::pow(xx,4)+1.+z*zb1*(std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1); const long double Si42=2.*xx*(z/t2)*b0*Nc/2.*(std::pow(xx,4)+1.+z*zb2*(std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2); const long double Si41z1=(4.*Nc*b0*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si42z1=(4.*Nc*b0*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=1./(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); const long double Si51=2.*xx/t1*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(muF*xx*z/(-t1))*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t1,4)+std::pow(xx*xp*z/t1,4))/(z*z*xx*xp); const long double Si52=2.*xx/t2*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(muF*xx*z/(-t2))*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t2,4)+std::pow(xx*xp*z/t2,4))/(z*z*xx*xp); const long double Si51z1=(16.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))*std::log(muF*2.*xx/(1.-xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); const long double Si52z1=(16.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))*std::log(muF*2.*xx/(1.-xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))); ris+=1./(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); ris*=(1.-zmin); return ris; } //gq channel long double NLOPL::NLO_PL_sing_doublediff_gq(double xp, double zz) { long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable za const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); const long double rad1=std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp); const long double t=0.5*(xx-1.+rad1); const long double u=0.5*(xx-1.-rad1); const long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); const long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); //Define and add the different singular parts const long double Si11=xx/(t1)*_Nc*_Cf*((1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(MUF*xx*z/(-t1)))*(z*z+t1*t1)/(-xx*xp*z/(t1)); const long double Si12=xx/(t2)*_Nc*_Cf*((1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(MUF*xx*z/(-t2)))*(z*z+t2*t2)/(-xx*xp*z/(t2)); const long double Si11z1=xx/(t)*_Nc*_Cf*(2.*std::log(MUF*xx/(-t)))*(1.+t*t)/(-xx*xp/(t)); const long double Si12z1=xx/(u)*_Nc*_Cf*(2.*std::log(MUF*xx/(-u)))*(1.+u*u)/(-xx*xp/(u)); ris+=1./(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); // OK 4 Nc Cf Log(x)^2/xp const long double Si21=xx/(-t1)*_Nc*_Cf*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*(z*z+t1*t1)/(-xx*xp*z/(t1)); const long double Si22=xx/(-t2)*_Nc*_Cf*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*(z*z+t2*t2)/(-xx*xp*z/(t2)); const long double Si21z1=xx/(-t)*_Nc*_Cf*(2.)*(1.+t*t)/(-xx*xp/(t)); const long double Si22z1=xx/(-u)*_Nc*_Cf*(2.)*(1.+u*u)/(-xx*xp*z/(u)); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); //OK no logs const long double Si31=xx/(t1)*(_Cf*(1.+z*z)*std::log(MUF*xx*z/(-t1)))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t1*t1))/(-t1); const long double Si32=xx/(t2)*(_Cf*(1.+z*z)*std::log(MUF*xx*z/(-t2)))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t2*t2))/(-t2); const long double Si31z1=xx/(t)*(_Cf*(2.)*std::log(MUF*xx/(-t)))*_Cf*(1.+xx*xx*xp*xp/(t*t))/(-t); const long double Si32z1=xx/(u)*(_Cf*(2.)*std::log(MUF*xx/(-u)))*_Cf*(1.+xx*xx*xp*xp/(u*u))/(-u); ris+=1./(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); //OK no logs const long double Si41=xx/(-t1)*(_Cf*(1.+z*z))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t1*t1))/(-t1); const long double Si42=xx/(-t2)*(_Cf*(1.+z*z))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t2*t2))/(-t2); const long double Si41z1=xx/(-t)*(_Cf*(2.))*_Cf*(1.+xx*xx*xp*xp/(t*t))/(-t); const long double Si42z1=xx/(-u)*(_Cf*(2.))*_Cf*(1.+xx*xx*xp*xp/(u*u))/(-u); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); //OK no logs const long double Si51=xx*z/(-t1)*_Nc*_Cf*((-t1-t1*t1*t1+Q1*Q1*Q1*t1+Q1*t1*t1*t1)/(u1*t1) +(z*zb1*(-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*(u1/zb1)-Q1*std::pow(u1/zb1,3)))/(u1*t1)); const long double Si52=xx*z/(-t2)*_Nc*_Cf*((-t2-t2*t2*t2+Q2*Q2*Q2*t2+Q2*t2*t2*t2)/(u2*t2) +(z*zb2*(-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*(u2/zb2)-Q2*std::pow(u2/zb2,3)))/(u2*t2)); const long double Si51z1=xx/(-t)*_Nc*_Cf*((-t-t*t*t)/(u*t)+(-(t)-std::pow(t,3))/(u*t)); const long double Si52z1=xx*z/(-u)*_Nc*_Cf*((-u-u*u*u)/(u*t)+(-(u)-std::pow(u,3))/(u*t)); ris+=std::log(1.-z)/(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); //OK +Nc*Cf*Log(x)^2/xp const long double Si61=xx*z/(t1)*std::log(Qt1*z/(-t1))*_Nc*_Cf*((-t1-t1*t1*t1+Q1*Q1*Q1*t1+Q1*t1*t1*t1)/(u1*t1) +(z*zb1*(-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*(u1/zb1)-Q1*std::pow(u1/zb1,3)))/(u1*t1)); const long double Si62=xx*z/(t2)*std::log(Qt2*z/(-t2))*_Nc*_Cf*((-t2-t2*t2*t2+Q2*Q2*Q2*t2+Q2*t2*t2*t2)/(u2*t2) +(z*zb2*(-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*(u2/zb2)-Q2*std::pow(u2/zb2,3)))/(u2*t2)); const long double Si61z1=xx/(t)*std::log(xx*xp/(-t))*_Nc*_Cf*((-t-t*t*t)/(u*t)+(-(t)-std::pow(t,3))/(u*t)); const long double Si62z1=xx/(u)*std::log(xx*xp/(-u))*_Nc*_Cf*((-u-u*u*u)/(u*t)+(-(u)-std::pow(u,3))/(u*t)); ris+=1./(1.-z)*(Jac2*Si62-Jac2z1*Si62z1-Jac1*Si61+Jac1z1*Si61z1); //OK -3Nc*Cf*Log(x)^2/xp const long double Si71=xx*z/(t1)*3./2.*_Cf*_Cf*(u1*u1+1.)/(-t1); const long double Si72=xx*z/(t2)*3./2.*_Cf*_Cf*(u2*u2+1.)/(-t2); const long double Si71z1=xx*z/(t)*3./2.*_Cf*_Cf*(u*u+1.)/(-t); const long double Si72z1=xx*z/(u)*3./2.*_Cf*_Cf*(t*t+1.)/(-u); ris+=1./(1.-z)*(Jac2*Si72-Jac2z1*Si72z1-Jac1*Si71+Jac1z1*Si71z1);//OK (Log semplice non Log squared) ris*=(1.-zmin); return ris; } //qqbar channel long double NLOPL::NLO_PL_sing_doublediff_qqbar(double xp, double zz) { long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable za const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); const long double rad1=std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp); const long double t=0.5*(xx-1.+rad1); const long double u=0.5*(xx-1.-rad1); const long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); const long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp)); //Define and add the different singular parts const long double Si11=xx/(-t1)*(-_Cf*(1.+z*z)*std::log(MUF*z*xx/(-t1)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t1*t1)*z*z+t1*t1)/z; const long double Si12=xx/(-t2)*(-_Cf*(1.+z*z)*std::log(MUF*z*xx/(-t2)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t2*t2)*z*z+t2*t2)/z; const long double Si11z1=xx/(-t)*(-_Cf*(2.)*std::log(MUF*xx/(-t)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t*t)+t*t); const long double Si12z1=xx/(-t2)*(-_Cf*(2.)*std::log(MUF*xx/(-u)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(u*u)+u*u); ris+=2./(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); //OK no Logs const long double Si21= xx/(-t1)*(_Cf*(1.+z*z))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t1*t1)*z*z+t1*t1)/z; const long double Si22=xx/(-t2)*(_Cf*(1.+z*z))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t2*t2)*z*z+t2*t2)/z; const long double Si21z1=xx/(-t)*(_Cf*(2.))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t*t)+t*t); const long double Si22z1=xx/(-u)*(_Cf*(2.))*2.*_Cf*_Cf*(xx*xx*xp*xp/(u*u)+u*u); ris+=2.*std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); //OK no Logs const long double Si31=xx*z/(-t1)*(2.*_Cf-_Nc)*_Cf*_Cf*((t1*t1+u1*u1+std::pow(t1/z,2)+std::pow(u1/zb1,2))); const long double Si32=xx*z/(-t2)*(2.*_Cf-_Nc)*_Cf*_Cf*((t2*t2+u2*u2+std::pow(t2/z,2)+std::pow(u2/zb1,2))); const long double Si31z1=xx/(-t)*(2.*_Cf-_Nc)*_Cf*_Cf*((t*t+u*u+std::pow(t,2)+std::pow(u,2))); const long double Si32z1=xx/(-u)*(2.*_Cf-_Nc)*_Cf*_Cf*((u*u+t*t+std::pow(u,2)+std::pow(t,2))); ris+=2.*std::log(1.-z)/(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); // OK no Logs const long double Si41=xx*z/(t1)*std::log(Qt1*z/(-t1))*(2.*_Cf-_Nc)*_Cf*_Cf*((t1*t1+u1*u1+std::pow(t1/z,2)+std::pow(u1/zb1,2))); const long double Si42=xx*z/(t2)*std::log(Qt2*z/(-t2))*(2.*_Cf-_Nc)*_Cf*_Cf*((t2*t2+u2*u2+std::pow(t2/z,2)+std::pow(u2/zb1,2))); const long double Si41z1=xx/t*std::log(xx*xp/(-t))*(2.*_Cf-_Nc)*_Cf*_Cf*((t*t+u*u+std::pow(t,2)+std::pow(u,2))); const long double Si42z1=xx/u*std::log(xx*xp/(-u))*(2.*_Cf-_Nc)*_Cf*_Cf*((u*u+t*t+std::pow(u,2)+std::pow(t,2))); ris+=2./(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); //OK no Logs const long double Si51=-xx*z/(-t1)*b0*_Cf*_Cf*((t1*t1+u1*u1)); const long double Si52=-xx*z/(-t2)*b0*_Cf*_Cf*((t2*t2+u2*u2)); const long double Si51z1=-xx/(-t)*b0*_Cf*_Cf*((t*t+u*u)); const long double Si52z1=-xx/(-u)*b0*_Cf*_Cf*((t*t+u*u)); ris+=2./(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); //OK no Logs ris*=(1.-zmin); //OK NO LOGS return ris; } //Not-Singular Part //gg channel long double NLOPL::NLO_PL_notsing_doublediff(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double muF=_muF; const long double muR=_muR; const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (paper Glover for definition of G2s) const long double Fi1_1=xx/(-t1)*(-2.*Nf*std::log(muF*xx/Q1)*0.5*(z*z+(1.-z)*(1.-z))+2.*Nf*z*(1.-z))*Cf*(z*z*xx*xx*xp*xp/(t1*t1)+z*z)/(-t1); const long double Fi1_2=xx/(-t2)*(-2.*Nf*std::log(muF*xx/Q2)*0.5*(z*z+(1.-z)*(1.-z))+2.*Nf*z*(1.-z))*Cf*(z*z*xx*xx*xp*xp/(t2*t2)+z*z)/(-t2); ris+=2.*(Jac2*Fi1_2-Jac1*Fi1_1); //Separate divergent part Q->0 (ref Grazzini) const long double tiny=1e-4; const long double Fi2_1 = (Q1 > tiny*(xx*xp) ) ? Nc*Nc*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4))*(Q1+Qt1)/(Q1*Qt1) +(2.*xx*xx*(std::pow(xx-t1,4)+std::pow(xx-u1,4)+std::pow(u1,4)+std::pow(t1,4)))/(u1*t1*(xx-u1)*(xx-t1)))*1./(xp) *std::log(xx*xp/Qt1) : -Nc*Nc*((std::pow(xx,4)+1.+std::pow(u1,4)+std::pow(t1,4))/(xx*xp*xp)); const long double Fi2_2 = ( Q2 > tiny*(xx*xp)) ? Nc*Nc*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4))*(Q2+Qt2)/(Q2*Qt2) +(2.*xx*xx*(std::pow(xx-t2,4)+std::pow(xx-u2,4)+std::pow(u2,4)+std::pow(t2,4)))/(u2*t2*(xx-u2)*(xx-t2)))*1./(xp) *std::log(xx*xp/Qt2) : -Nc*Nc*((std::pow(xx,4)+1.+std::pow(u2,4)+std::pow(t2,4))/(xx*xp*xp)); ris+=(Jac2*Fi2_2-Jac1*Fi2_1); //Define and add G2ns (paper Glover for definition of G2ns) //A1234 const long double A1234_1_1=-0.5*((pow(xx*xp/t1,4)+pow(xx*Q1/t1,4))*L1a1+pow(u1,4)*L1b1); const long double A1234_1_2=(pow(xx,2)*Q1*pow(u1,3))/(2.*t1*(u1-xx)*(t1-xx))*(L1a1+L1b1) +(xx*xp*Q1*pow(u1,3))/(2.*A1*(t1-xx))*(L2b1-L1b1) +(xx*xp*Q1*(pow(xx,4)+pow(u1-xx,4)))/(2.*A1*t1*(u1-xx))*(L2a1-L1a1); const long double A1234_1_3=pow(xx,2)*xp*Q1*(pow(u1,4)/(2.*pow(B1*t1,2))+pow(u1,2)/(2.*pow(B1,2))) +pow(xx,4)*pow(xp*Q1,2)*(-6./pow(B1,4)-4./pow(t1,4)+8./pow(B1*t1,2)); const long double A1234_1_4=L31*(xx*xp*pow(u1,3)*(u1+t1)/(B1*t1)+pow(xx,4)*pow(Q1*xp,2)*(3.*A1/pow(B1,5)-1./(A1*pow(B1,3))) -pow(xx,2)*xp*Q1*(1./(B1*t1)*(t1*t1+t1*u1+4.*pow(u1,2)-2.*xx*Q1) +A1/(2.*pow(B1,3))*(t1*t1+3.*t1*u1+3.*u1*u1-6*xx*Q1)+1./(2.*A1*B1)*(t1*t1+t1*u1+7.*u1*u1-2.*xx*Q1))); const long double A1234_2_1=-0.5*((pow(xx*xp/t2,4)+pow(xx*Q2/t2,4))*L1a2+pow(u2,4)*L1b2); const long double A1234_2_2=(pow(xx,2)*Q2*pow(u2,3))/(2.*t2*(u2-xx)*(t2-xx))*(L1a2+L1b2) +(xx*xp*Q2*pow(u2,3))/(2.*A2*(t2-xx))*(L2b2-L1b2) +(xx*xp*Q2*(pow(xx,4)+pow(u2-xx,4)))/(2.*A2*t2*(u2-xx))*(L2a2-L1a2); const long double A1234_2_3=pow(xx,2)*xp*Q2*(pow(u2,4)/(2.*pow(B2*t2,2))+pow(u2,2)/(2.*pow(B2,2))) +pow(xx,4)*pow(xp*Q2,2)*(-6./pow(B2,4)-4./pow(t2,4)+8./pow(B2*t2,2)); const long double A1234_2_4=L32*(xx*xp*pow(u2,3)*(u2+t2)/(B2*t2)+pow(xx,4)*pow(Q2*xp,2)*(3.*A2/pow(B2,5)-1./(A2*pow(B2,3))) -pow(xx,2)*xp*Q2*(1./(B2*t2)*(t2*t2+t2*u2+4.*pow(u2,2)-2.*xx*Q2) +A2/(2.*pow(B2,3))*(t2*t2+3.*t2*u2+3.*u2*u2-6*xx*Q2)+1./(2.*A2*B2)*(t2*t2+t2*u2+7.*u2*u2-2.*xx*Q2))); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A1234_2_1+A1234_2_2+A1234_2_3+A1234_2_4)-Jac1/(xp*Q1)*(A1234_1_1+A1234_1_2+A1234_1_3+A1234_1_4)); //A3412 const long double A3412_1_1=xx*xp*Q1*pow(A1,3)/(2.*t1*(u1-xx))*(L2a1+L1b1) +xx*xp*(u1+t1)/(16.*u1*t1*B1)*(pow(A1,4)+6.*pow(A1*B1,2)+pow(B1,4))*L31; const long double A3412_1_2=(-xx*xp/(2.*u1*t1)*(pow(1.-Q1,4)+pow(xx,4)+2.*Q1*A1*pow(1.-Q1,2)-2.*Q1*pow(xx,3)) -pow(xx,4)*pow(Q1*xp,2)/pow(u1,4)+(2.*pow(xx,2)*xp*Q1*(A1*A1-xx))/(u1*u1))*L1b1; const long double A3412_1_3=xx*xp*pow(Q1-u1,3)/(8.*u1*t1*(Q1-t1))*((Q1-t1)+Q1*u1)* (4./3.+2.*xx*xp/Qt1+4.*pow(xx*xp/Qt1,2)-44./3.*pow(xx*xp/Qt1,3)) +xx*xp*pow(Q1-t1,3)/(8.*u1*t1*(Q1-u1))*((Q1-u1)+Q1*t1)* (4./3.+2.*xx*xp/Qt1+4.*pow(xx*xp/Qt1,2)-44./3.*pow(xx*xp/Qt1,3)); const long double A3412_1_4=xx*xp*pow(Q1-u1,2)/(4.*u1*t1*(Q1-t1))* (-3.*(t1-xx)*((Q1-t1)+Q1*u1)-Q1*(xx*(t1-xx)+Q1*(u1-xx)))*(1.+2.*xx*xp/Qt1-6.*pow(xx*xp/Qt1,2)) +xx*xp*pow(Q1-t1,2)/(4.*u1*t1*(Q1-u1))* (-3.*(u1-xx)*((Q1-u1)+Q1*t1)+3.*Q1*(xx*(u1-xx)+Q1*(t1-xx))+4.*u1)*(1.+2.*xx*xp/Qt1-6.*pow(xx*xp/Qt1,2)); const long double A3412_1_5=xx*xp*(Q1-t1)/(2.*u1*t1*(Q1-u1))*(3.*pow(u1-xx,2)*((Q1-u1)+Q1*t1)+8.*u1*t1+2.*u1-2.*Q1*u1*pow(u1-Q1,2) -3.*xx*Q1*pow(t1-xx,2)-3.*Q1*(xx-Q1)*pow(t1,2)-Q1*u1*(4.*u1*t1-u1*xx-Q1*t1+2.*pow(t1,2)-4.*xx*xx)+3.*xx*pow(Q1,2)*(t1-xx) +xx*Q1*u1*(t1-Q1))*(1.-2.*xx*xp/Qt1)+xx*xp*(Q1-u1)/(2.*u1*t1*(Q1-t1))* (3.*pow(t1-xx,2)*((Q1-t1)+Q1*u1)+3.*(t1-xx)*Q1*(xx*(t1-xx)+Q1*(u1-xx))+Q1*u1*(xx*(t1-Q1)+Q1*(u1-xx)))*(1.-2.*xp*xx/Qt1); const long double A3412_1_6=-4.*pow(xx,4)*pow(Q1*xp,2)/pow(u1,4)+xp*Q1*pow(xx*B1,2)/(2.*u1*u1) +pow(xx,3)*xp/6.*((1.+Q1)/(u1*t1)+Q1/(u1*u1)+Q1/(t1*t1))+(2.*xp*pow(xx,3)*Q1)/(u1*u1)+pow(xx,3)*xp/u1 -xx*xp/(12.*t1*u1)*(30.*pow(xx,3)+54.*pow(Q1,2)*xx+8.*pow(Q1,3)) +xx*xp/(12*u1*t1)*(11.+17.*pow(xx,4)+Q1*(61.*u1*u1*t1+17.*pow(u1,3)+73.*u1*t1*t1+29.*pow(t1,3)) +xx*(24.*u1*u1*t1+6.*pow(u1,3)+36.*u1*t1*t1+18.*pow(t1,3))+Q1*Q1*(-21.*u1*u1-33.*t1*t1-52.*u1*t1) +xx*Q1*(-73.*u1*u1-109.*t1*t1-170.*u1*t1)+xx*xx*(-23.*u1*u1-35.*t1*t1-52.*u1*t1) +xx*xx*Q1*(134.*t1+110.*u1)+4.*pow(Q1,4)+52.*xx*pow(Q1,3)+20.*xx*xx*Q1*Q1-22.*pow(xx,3)*Q1); const long double A3412_2_1=xx*xp*Q2*pow(A2,3)/(2.*t2*(u2-xx))*(L2a2+L1b2) +xx*xp*(u2+t2)/(16.*u2*t2*B2)*(pow(A2,4)+6.*pow(A2*B2,2)+pow(B2,4))*L32; const long double A3412_2_2=(-xx*xp/(2.*u2*t2)*(pow(1.-Q2,4)+pow(xx,4)+2.*Q2*A2*pow(1.-Q2,2)-2.*Q2*pow(xx,3)) -pow(xx,4)*pow(Q2*xp,2)/pow(u2,4)+(2.*pow(xx,2)*xp*Q2*(A2*A2-xx))/(u2*u2))*L1b2; const long double A3412_2_3=xx*xp*pow(Q2-u2,3)/(8.*u2*t2*(Q2-t2))*((Q2-t2)+Q2*u2)* (4./3.+2.*xx*xp/Qt2+4.*pow(xx*xp/Qt2,2)-44./3.*pow(xx*xp/Qt2,3)) +xx*xp*pow(Q2-t2,3)/(8.*u2*t2*(Q2-u2))*((Q2-u2)+Q2*t2)* (4./3.+2.*xx*xp/Qt2+4.*pow(xx*xp/Qt2,2)-44./3.*pow(xx*xp/Qt2,3)); const long double A3412_2_4=xx*xp*pow(Q2-u2,2)/(4.*u2*t2*(Q2-t2))* (-3.*(t2-xx)*((Q2-t2)+Q2*u2)-Q2*(xx*(t2-xx)+Q2*(u2-xx)))*(1.+2.*xx*xp/Qt2-6.*pow(xx*xp/Qt2,2)) +xx*xp*pow(Q2-t2,2)/(4.*u2*t2*(Q2-u2))* (-3.*(u2-xx)*((Q2-u2)+Q2*t2)+3.*Q2*(xx*(u2-xx)+Q2*(t2-xx))+4.*u2)*(1.+2.*xx*xp/Qt2-6.*pow(xx*xp/Qt2,2)); const long double A3412_2_5=xx*xp*(Q2-t2)/(2.*u2*t2*(Q2-u2))*(3.*pow(u2-xx,2)*((Q2-u2)+Q2*t2)+8.*u2*t2+2.*u2-2.*Q2*u2*pow(u2-Q2,2) -3*xx*Q2*pow(t2-xx,2)-3.*Q2*(xx-Q2)*pow(t2,2)-Q2*u2*(4.*u2*t2-u2*xx-Q2*t2+2.*pow(t2,2)-4.*xx*xx)+3.*xx*pow(Q2,2)*(t2-xx) +xx*Q2*u2*(t2-Q2))*(1-2.*xx*xp/Qt2)+xx*xp*(Q2-u2)/(2.*u2*t2*(Q2-t2))* (3.*pow(t2-xx,2)*((Q2-t2)+Q2*u2)+3.*(t2-xx)*Q2*(xx*(t2-xx)+Q2*(u2-xx))+Q2*u2*(xx*(t2-Q2)+Q2*(u2-xx)))*(1-2.*xp*xx/Qt2); const long double A3412_2_6=-4.*pow(xx,4)*pow(Q2*xp,2)/pow(u2,4)+xp*Q2*pow(xx*B2,2)/(2.*u2*u2) +pow(xx,3)*xp/6.*((1.+Q2)/(u2*t2)+Q2/(u2*u2)+Q2/(t2*t2))+(2.*xp*pow(xx,3)*Q2)/(u2*u2)+pow(xx,3)*xp/u2 -xx*xp/(12.*t2*u2)*(30.*pow(xx,3)+54.*pow(Q2,2)*xx+8.*pow(Q2,3)) +xx*xp/(12*u2*t2)*(11.+17.*pow(xx,4)+Q2*(61.*u2*u2*t2+17.*pow(u2,3)+73.*u2*t2*t2+29.*pow(t2,3)) +xx*(24.*u2*u2*t2+6.*pow(u2,3)+36.*u2*t2*t2+18.*pow(t2,3))+Q2*Q2*(-21.*u2*u2-33.*t2*t2-52.*u2*t2) +xx*Q2*(-73.*u2*u2-109.*t2*t2-170.*u2*t2)+xx*xx*(-23.*u2*u2-35.*t2*t2-52.*u2*t2) +xx*xx*Q2*(134.*t2+110.*u2)+4.*pow(Q2,4)+52.*xx*pow(Q2,3)+20.*xx*xx*Q2*Q2-22.*pow(xx,3)*Q2); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A3412_2_1+A3412_2_2+A3412_2_3+A3412_2_4+A3412_2_5+A3412_2_6)-Jac1/(xp*Q1)*(A3412_1_1+A3412_1_2+A3412_1_3+A3412_1_4+A3412_1_5+A3412_1_6)); //A1324 const long double A1324_1_1=-0.5*((pow(xx*xp/t1,4)+pow(xx*Q1/t1,4))*L1a1+pow(u1,4)*L1b1) +pow(xx,3)*xp*Q1/(t1*t1)*L1a1+(pow(xx,2)*Q1*pow(u1,3)/(2.*t1*(u1-xx)*(t1-xx))+xx*xp*pow(u1,3)/(2.*t1)) *(L1a1+L1b1); const long double A1324_1_2=xx*xp*(1.-zb1)*pow(u1,3)/(2.*A1*(t1-xx))*(L2b1-L1b1) +(xx*xp*(1.-z)*(pow(xx,4)+pow(u1-xx,4)))/(2.*A1*t1*(u1-xx))*(L2a1-L1a1) +pow(xx,3)*xp*Q1/(A1*B1)*L31+xx*xx*xp*Q1/(2.*pow(t1,4))*(pow(xx*xp,2)-6.*xx*xx*xp*Q1+pow(xx*Q1,2)); const long double A1324_2_1=-0.5*((pow(xx*xp/t2,4)+pow(xx*Q2/t2,4))*L1a2+pow(u2,4)*L1b2) +pow(xx,3)*xp*Q2/(t2*t2)*L1a2+(pow(xx,2)*Q2*pow(u2,3)/(2.*t2*(u2-xx)*(t2-xx))+xx*xp*pow(u2,3)/(2.*t2)) *(L1a2+L1b2); const long double A1324_2_2=xx*xp*(1.-zb2)*pow(u2,3)/(2.*A2*(t2-xx))*(L2b2-L1b2) +(xx*xp*(1.-z)*(pow(xx,4)+pow(u2-xx,4)))/(2.*A2*t2*(u2-xx))*(L2a2-L1a2) +pow(xx,3)*xp*Q2/(A2*B2)*L32+xx*xx*xp*Q2/(2.*pow(t2,4))*(pow(xx*xp,2)-6.*xx*xx*xp*Q2+pow(xx*Q2,2)); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A1324_2_1+A1324_2_2)-Jac1/(xp*Q1)*(A1324_1_1+A1324_1_2)); //A3241 const long double A3241_1_1=xx*xp*pow(A1,3)*(1.-z)/(2.*t1*(u1-xx))*(L2a1-L1a1) +(-pow(xx,4)*pow(xp*Q1,2)/pow(t1,4)+pow(xx,3)*xp*pow(Q1,2)/(u1*t1) -xx*xx*xp*Q1*pow(A1,4)/(2.*u1*t1*(u1-xx)*(t1-xx))+xx*xx*xp*Q1*(u1+t1)*(2.*A1*A1-xx)/(u1*t1*t1))*L1a1; const long double A3241_1_2=xx*xp*Q1*pow(Q1-u1,2)/(2.*u1*t1*pow(Q1-t1,2))* (-u1*t1-pow(Q1-t1,2))*(-3.+10.*Q1/Qt1-6.*pow(Q1/Qt1,2)) +xx*xp*Q1*(Q1-u1)/(u1*t1*pow(Q1-t1,2))*(u1*t1*(Q1-u1)-pow(Q1-t1,3)-xx*pow(Q1-t1,2)-xx*(Q1-t1)*(Q1-u1)) *(-1.+2.*Q1/Qt1); const long double A3241_1_3=xx*xx*xp*Q1*(B1*B1/(2.*t1*t1)-2.*xx*Q1/(t1*t1)+(u1+t1)*(u1+t1)/(2.*u1*t1)) -4.*pow(xx,4)*pow(xp*Q1,2)/pow(t1,4)+xx*xp*Q1/(4.*u1*t1) *(pow(t1+u1,2)-(t1+u1)*(6.*Q1+4.*xx)+6.*Q1*Q1+8.*xx*Q1)+pow(xx,3)*xp*Q1*pow(t1+u1,2)/(4.*u1*u1*t1*t1); const long double A3241_2_1=xx*xp*pow(A2,3)*(1.-z)/(2.*t2*(u2-xx))*(L2a2-L1a2) +(-pow(xx,4)*pow(xp*Q2,2)/pow(t2,4)+pow(xx,3)*xp*pow(Q2,2)/(u2*t2) -xx*xx*xp*Q2*pow(A2,4)/(2.*u2*t2*(u2-xx)*(t2-xx))+xx*xx*xp*Q2*(u2+t2)*(2.*A2*A2-xx)/(u2*t2*t2))*L1a2; const long double A3241_2_2=xx*xp*Q2*pow(Q2-u2,2)/(2.*u2*t2*pow(Q2-t2,2))* (-u2*t2-pow(Q2-t2,2))*(-3.+10.*Q2/Qt2-6.*pow(Q2/Qt2,2)) +xx*xp*Q2*(Q2-u2)/(u2*t2*pow(Q2-t2,2))*(u2*t2*(Q2-u2)-pow(Q2-t2,3)-xx*pow(Q2-t2,2)-xx*(Q2-t2)*(Q2-u2)) *(-1.+2.*Q2/Qt2); const long double A3241_2_3=xx*xx*xp*Q2*(B2*B2/(2.*t2*t2)-2.*xx*Q2/(t2*t2)+(u2+t2)*(u2+t2)/(2.*u2*t2)) -4.*pow(xx,4)*pow(xp*Q2,2)/pow(t2,4)+xx*xp*Q2/(4.*u2*t2) *(pow(t2+u2,2)-(t2+u2)*(6.*Q2+4.*xx)+6.*Q2*Q2+8.*xx*Q2)+pow(xx,3)*xp*Q2*pow(t2+u2,2)/(4.*u2*u2*t2*t2); ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A3241_2_1+A3241_2_2+A3241_2_3)-Jac1/(xp*Q1)*(A3241_1_1+A3241_1_2+A3241_1_3)); //Aepsilon const long double Aepsilon_1=4.*pow(xx,4)*pow(xp*Q1,2)*(1./pow(t1,4)+1./pow(u1,4)); const long double Aepsilon_2=4.*pow(xx,4)*pow(xp*Q2,2)*(1./pow(t2,4)+1./pow(u2,4)); ris+=Nc*Nc*(Jac2/(xp*Q2)*(Aepsilon_2)-Jac1/(xp*Q1)*(Aepsilon_1)); //A0 const long double A0_1= (pow(t1/z,4)+pow(u1/zb1,4))*xx*xp/(Qt1*Qt1)*(5.-7.*Q1/Qt1+20./3.*pow(Q1/Qt1,2)) +xx*xp*(17./3.+4.*std::log(xx*xp/Qt1)); const long double A0_2=(pow(t2/z,4)+pow(u2/zb2,4))*xx*xp/(Qt2*Qt2)*(5.-7.*Q2/Qt2+20./3.*pow(Q2/Qt2,2)) +xx*xp*(17./3.+4.*std::log(xx*xp/Qt2)); ris+=Nc*Nc*(Jac2/(xp)*(A0_2)-Jac1/(xp)*(A0_1)); //B1pm const long double B1pm_1=xx*xp*z*pow(1.-z,3)/t1+pow(xx*xp*z/t1,3)*(1.-z) +4.*pow(xx*xp*z/t1*(1.-z),2)-xx*xp*Q1*(1.+std::log(xx*xp/Qt1)); const long double B1pm_2=xx*xp*z*pow(1.-z,3)/t2+pow(xx*xp*z/t2,3)*(1.-z) +4.*pow(xx*xp*z/t2*(1.-z),2)-xx*xp*Q2*(1.+std::log(xx*xp/Qt2)); ris+=2.*Nf*Cf*(Jac2/(xp*Q2)*B1pm_2-Jac1/(xp*Q1)*B1pm_1); //B2pm //FIXME? C'è una differenza con risultato mathematica ma non capisco da dove dipenda. Contributo completamente negiglible comunque const long double B2pm_1=1./3.*pow(t1/z,4.)*xx*xp/Qt1*(-3./Qt1+3.*Q1/(Qt1*Qt1)-2.*Q1*Q1/(Qt1*Qt1*Qt1)) -1./3.*xx*xp; const long double B2pm_2=1./3.*pow(t2/z,4.)*xx*xp/Qt2*(-3./Qt2+3.*Q1/(Qt2*Qt2)-2.*Q2*Q2/(Qt2*Qt2*Qt2)) -1./3.*xx*xp; ris+=2.*Nf*Nc*(Jac2/xp*B2pm_2-Jac1/xp*B2pm_1); //B1pp const long double B1pp_1=xx*xp*pow(z,3)*(1.-z)/t1+pow(xx*xp*(1.-z)/t1,3)*z +4.*pow(xx*xp*z*(1.-z)/t1,2)-xx*xp*Q1/(Qt1*Qt1*u1*t1)*(pow(u1*t1+xx*xp*Q1,2)+2.*xx*xp*Q1*Qt1) +xx*xp*Q1/(u1*t1)*(1.+Q1*Q1)*std::log(1.+(xx*xp/Q1)); const long double B1pp_2=xx*xp*pow(z,3)*(1.-z)/t2+pow(xx*xp*(1.-z)/t2,3)*z +4.*pow(xx*xp*z*(1.-z)/t2,2)-xx*xp*Q2/(Qt2*Qt2*u2*t2)*(pow(u2*t2+xx*xp*Q2,2)+2.*xx*xp*Q2*Qt2) +xx*xp*Q2/(u2*t2)*(1.+Q2*Q2)*std::log(1.+(xx*xp/Q2)); ris+=2.*Nf*Cf*(Jac2/(xp*Q2)*B1pp_2-Jac1/(xp*Q1)*B1pp_1); //B2pp const long double B2pp_1_1=-xx*xp*Q1/(2.*u1*t1)*(1.+Q1*Q1)*std::log(Qt1/Q1); const long double B2pp_1_2=+xx*xp*std::pow(Q1-u1,3.)/(2.*u1*t1*(Q1-t1))*((Q1-t1)+Q1*u1) *(2./3.+Q1/Qt1-19./3.*std::pow(Q1/Qt1,3.)) -xx*xp*std::pow(Q1-u1,2.)/(2.*u1*t1*std::pow(Q1-t1,2.)) *(3.*std::pow(Q1-t1,3.)*Q1+(Q1-t1)*Q1*(2.*u1*t1+xx*xx) +std::pow(Q1-t1,2.)*(1+4.*xx*Q1-u1*(Q1+xx))-u1*u1*Q1*Q1+u1*t1*t1*xx)*(1.-2.*Q1*Q1/(Qt1*Qt1)) +xx*xp*(Q1-u1)/(2.*u1*t1*(Q1-t1))*(3.*Q1*(Q1+1.)*(Q1-t1)-t1+xx*Q1+Q1*u1*(xx-Q1)*(xx-Q1))*(1.-2.*Q1/Qt1); const long double B2pp_1_3=xx*xp/(12.*u1*t1)*(-2.+6.*xx*t1*(t1-xx)+2.*xx*xx*xx+8.*Q1*(1.-Q1)*(1.-Q1) -2.*u1*t1*Q1+7.*xx*xp*Q1-2.*Q1*Q1*xx-xx*xx*xx*Q1+3.*xx*Q1*Q1*Q1-4.*u1*t1*xx*Q1) +11./6.*xx*xp*Q1*Q1/(u1*t1)-xx*xp*xx*xx*Q1/(3.*t1*t1); const long double B2pp_2_1=-xx*xp*Q2/(2.*u2*t2)*(1.+Q2*Q2)*std::log(Qt2/Q2); const long double B2pp_2_2=+xx*xp*std::pow(Q2-u2,3.)/(2.*u2*t2*(Q2-t2))*((Q2-t2)+Q2*u2) *(2./3.+Q2/Qt2-19./3.*std::pow(Q2/Qt2,3.)) -xx*xp*std::pow(Q2-u2,2.)/(2.*u2*t2*std::pow(Q2-t2,2.)) *(3.*std::pow(Q2-t2,3.)*Q2+(Q2-t2)*Q2*(2.*u2*t2+xx*xx) +std::pow(Q2-t2,2.)*(1+4.*xx*Q2-u2*(Q2+xx))-u2*u2*Q2*Q2+u2*t2*t2*xx)*(1.-2.*Q2*Q2/(Qt2*Qt2)) +xx*xp*(Q2-u2)/(2.*u2*t2*(Q2-t2))*(3.*Q2*(Q2+1.)*(Q2-t2)-t2+xx*Q2+Q2*u2*(xx-Q2)*(xx-Q2))*(1.-2.*Q2/Qt2); const long double B2pp_2_3=xx*xp/(12.*u2*t2)*(-2.+6.*xx*t2*(t2-xx)+2.*xx*xx*xx+8.*Q2*(1.-Q2)*(1.-Q2) -2.*u2*t2*Q2+7.*xx*xp*Q2-2.*Q2*Q2*xx-xx*xx*xx*Q2+3.*xx*Q2*Q2*Q2-4.*u2*t2*xx*Q2) +11./6.*xx*xp*Q2*Q2/(u2*t2)-xx*xp*xx*xx*Q2/(3.*t2*t2); //res[0]+=2.*Nc*Nf*(Jac2/(xp*Q2)*(B2pp_2_1+B2pp_2_2+B2pp_2_3)-Jac1/(xp*Q1)*(B2pp_1_1+B2pp_1_2+B2pp_1_3)); ris+=2.*Nc*Nf*(Jac2/(xp*Q2)*(B2pp_2_1)-Jac1/(xp*Q1)*(B2pp_1_1)); // Il resto è integrato analiticamente in B2pp_ANALITICS /*if (res[0]!=res[0]) { std::cout << "nan Yes \t z= " << z << " x= " << xx << std::endl; }*/ ris*=(1.-zmin); return ris; } //gq channel long double NLOPL::NLO_PL_notsing_doublediff_gq(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11=xx/(-t1)*(-0.5*(z*z+(1.-z)*(1.-z))*std::log(MUF*xx/Q1)+z*(1.-z)) *2.*_Cf*_Cf*(xx*xx*xp*xp*z*z/(t1*t1)+t1*t1)/(z)+xx/(-t1)*_Cf*(1.-z)*_Cf*(xx*xx*xp*xp*z*z/(t1*t1)+z*z)/(-t1) +xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z) *_Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(z*xx*xp/t1,4)+std::pow(t1,4))/(z*z*xx*xp); const long double Fi12=xx/(-t2)*(-0.5*(z*z+(1.-z)*(1.-z))*std::log(MUF*xx/Q2)+z*(1.-z)) *2.*_Cf*_Cf*(xx*xx*xp*xp*z*z/(t2*t2)+t2*t2)/(z)+xx/(-t2)*_Cf*(1.-z)*_Cf*(xx*xx*xp*xp*z*z/(t2*t2)+z*z)/(-t2) +xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z) *_Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(z*xx*xp/t2,4)+std::pow(t2,4))/(z*z*xx*xp); ris+=(Jac2*Fi12-Jac1*Fi11); // OK 6 Nc Cf Log(x)^2/xp //Separate Divergent part (Q^2->0) see Grazzini const long double tiny=1e-4; const long double Fi21=(Q1>tiny*xx*xp) ? xx* _Nc*_Cf*(((-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*u1/zb1-Q1*std::pow(u1/zb1,3))*(Q1+Qt1))/(Q1*Qt1) -(2.*xx*xx*((xx-t1)*(xx-t1)+t1*t1))/(u1*(xx-u1)))/(xx*xp)*std::log(xx*xp/Qt1) : (t1*t1*t1+t1*z*z)/(z*z*z*xx*xp*xp) ; const long double Fi22=(Q2>tiny*xx*xp) ? xx* _Nc*_Cf*(((-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*u2/zb2-Q2*std::pow(u2/zb2,3))*(Q2+Qt2))/(Q2*Qt2) -(2.*xx*xx*((xx-t2)*(xx-t2)+t2*t2))/(u2*(xx-u2)))/(xx*xp)*std::log(xx*xp/Qt2) : (t2*t2*t2+t2*z*z)/(z*z*z*xx*xp*xp) ; ris+=(Jac2*Fi22-Jac1*Fi21); // OK -10 Nc Cf Log(x)^2/xp const long double C1pm1=-2.*xx*gsl_sf_log(xx*xp/Qt1); const long double C1pm2=-2.*xx*gsl_sf_log(xx*xp/Qt2); ris+=_Cf*_Cf*(Jac2*(C1pm2)-Jac1*(C1pm1)); const long double C1mp1=xx*xp*Q1-3.*xx*xp*t1*t1/2./u1+xx*xp/(2.*Qt1)*(pow(Q1-t1,3)+Q1*pow(Q1-u1,3))*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1); const long double C1mp2=xx*xp*Q2-3.*xx*xp*t2*t2/2./u2+xx*xp/(2.*Qt2)*(pow(Q2-t2,3)+Q1*pow(Q2-u2,3))*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2); ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1mp2)-1./xp/Q1*Jac1*(C1mp1)); const long double C1pp1=-3.*xx*xp/(2.*u1)-xx*xp*Q1*A1*A1/u1*L2b1+xx*xp/(u1*t1*t1)*L1a1*((A1-xx)*(A1-xx)*t1*t1-2.*Q1*xx*u1*t1*A1-Q1*xx*xx*(Q1-t1)*u1) +xx*xp/(u1*B1)*L31*((1.+Q1-xx)*((A1-xx)*(A1-xx)+Q1*A1*A1)-4.*Q1*A1*(A1-xx))+1./2.*xx*xp*(Q1-t1)*(Q1-t1)*(1./(Q1-u1)-Q1/u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1) +1./2.*xx*xp*(Q1-u1)*(Q1-u1)*(Q1/(Q1-t1)+1./u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1)+xx*xp*(Q1-t1)/(u1*(Q1-u1))*(2.*u1*(1.+t1) -Q1*(4.*xx*Q1-Q1*t1-xx*u1-2.*u1*t1))*(-1.+2.*Q1/Qt1)+xx*xp*(Q1-u1)/(u1*(Q1-t1))*(t1-2.*u1*t1+2.*Q1*u1*(Q1-t1))*(-1.+2.*Q1/Qt1) +xx*xp*Q1*xx*(t1+u1)/t1-2.*xx*xp*Q1*Q1*xx*xx/(t1*t1)+xx*xp*Q1*xx*xx/(2.*u1*u1)+xx*xp/(2.*u1)*(-2.*(Q1+xx)*u1+2.*xx+xx*xx+xx*Q1*(2.*(1.-Q1)+3.*xx-u1)+5.*Q1*(1.-Q1)); const long double C1pp2=-3.*xx*xp/(2.*u2)-xx*xp*Q2*A2*A2/u2*L2b2+xx*xp/(u2*t2*t2)*L1a2*((A2-xx)*(A2-xx)*t2*t2-2.*Q2*xx*u2*t2*A2-Q2*xx*xx*(Q2-t2)*u2) +xx*xp/(u2*B2)*L32*((1.+Q2-xx)*((A2-xx)*(A2-xx)+Q2*A2*A2)-4.*Q2*A2*(A2-xx))+1./2.*xx*xp*(Q2-t2)*(Q2-t2)*(1./(Q2-u2)-Q2/u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2) +1./2.*xx*xp*(Q2-u2)*(Q2-u2)*(Q2/(Q2-t2)+1./u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2)+xx*xp*(Q2-t2)/(u2*(Q2-u2))*(2.*u2*(1.+t2) -Q2*(4.*xx*Q2-Q2*t2-xx*u2-2.*u2*t2))*(-1.+2.*Q2/Qt2)+xx*xp*(Q2-u2)/(u2*(Q2-t2))*(t2-2.*u2*t2+2.*Q2*u2*(Q2-t2))*(-1.+2.*Q2/Qt2) +xx*xp*Q2*xx*(t2+u2)/t2-2.*xx*xp*Q2*Q2*xx*xx/(t2*t2)+xx*xp*Q2*xx*xx/(2.*u2*u2)+xx*xp/(2.*u2)*(-2.*(Q2+xx)*u2+2.*xx+xx*xx+xx*Q2*(2.*(1.-Q2)+3.*xx-u2)+5.*Q2*(1.-Q2)); ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1pp2)-1./xp/Q1*Jac1*(C1pp1)); const long double C1mm1=xx*xp*t1*t1/u1*L1a1-xx*xp*Q1*(xx-t1)*(xx-t1)/u1*L2b1+xx*xp*xx*Q1/B1/B1*(t1*(u1+t1)-2.*xx*Q1) +xx*xp/(u1*B1)*(t1*t1*B1*B1-xx*t1*t1*(u1+t1)+2.*Q1*Q1*xx*xx+Q1*xx*xx*(3.*t1-u1)+Q1*xx*xx*u1/(B1*B1)*(-t1*(u1+t1)+2.*xx*Q1+Q1*(t1-u1)))*L31; const long double C1mm2=xx*xp*t2*t2/u2*L1a2-xx*xp*Q2*(xx-t2)*(xx-t2)/u2*L2b2+xx*xp*xx*Q2/B2/B2*(t2*(u2+t2)-2.*xx*Q2) +xx*xp/(u2*B2)*(t2*t2*B2*B2-xx*t2*t2*(u2+t2)+2.*Q2*Q2*xx*xx+Q2*xx*xx*(3.*t2-u2)+Q2*xx*xx*u2/(B2*B2)*(-t2*(u2+t2)+2.*xx*Q2+Q2*(t2-u2)))*L32; ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1mm2)-1./xp/Q1*Jac1*(C1mm1)); const long double C2mp1=xx*xp*Q1/Qt1/Qt1*(pow(Q1-t1,3)+Q1*pow(Q1-u1,3))*(-2.+3.*Q1/Qt1)+2.*xx*xp*Q1+4.*xx*xp*Q1*gsl_sf_log(xx*xp/Qt1); const long double C2mp2=xx*xp*Q2/Qt2/Qt2*(pow(Q2-t2,3)+Q2*pow(Q2-u2,3))*(-2.+3.*Q2/Qt2)+2.*xx*xp*Q2+4.*xx*xp*Q2*gsl_sf_log(xx*xp/Qt2); ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2mp2)-1./xp/Q1*Jac1*(C2mp1)); const long double C2pp1=1./2.*xx*xp*A1*A1*(1.-z)*(L2a1-L1a1)+(xx*xp*(xx-t1)*A1*A1*(1.-zb1))/(2.*u1)*(L1b1-L2b1) +xx*xp*pow(1.-Q1,3)/(2.*u1)*(L1b1-L1a1)+xx*xp*Q1*A1*A1/(xx-u1)*(L1b1+L2a1) +xx*xp*Q1/(u1*u1)*L1b1*(2.*u1*(1.-Q1)*(1.-Q1)+4.*xx*(xx-t1)*A1-2.*xx*xx*(Q1-t1)-xx*xx*xx) -1./2.*xx*xp*pow(Q1-t1,2)*(1./(Q1-u1)-Q1/u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1) -1./2.*xx*xp*pow(Q1-u1,2)*(Q1/(Q1-t1)+1./u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1) +xx*xp*(Q1-t1)/(2.*u1*(Q1-u1))*((-3.*xx*xp+u1*u1-Q1*Q1)*(1.+Q1)-xx*u1+2.*Q1*Q1*(Q1-u1))*(-1.+2.*Q1/Qt1) +xx*xp*(Q1-u1)/(2.*u1*(Q1-t1))*(3.*xx*xp*(1.+Q1)-u1*Q1*(Q1-t1)+3.*Q1*xx*(Q1-u1)+t1*(u1+1.))*(-1.+2.*Q1/Qt1) +xx*xp*xx*Q1/(2.*u1*u1)*(2.*(1.-Q1)*(1.-Q1)-2.*xx*(1.-xx)-u1*(Q1-u1)-4.*xx*Q1)+xx*xp*(u1-t1)*(xx+Q1)/(2.*u1) -8.*pow(xx*xx*xp*Q1,2)/pow(u1,4)-2.*pow(xx*xx*xp*Q1,2)/pow(u1,4)*L1b1; const long double C2pp2=1./2.*xx*xp*A2*A2*(1.-z)*(L2a2-L1a2)+(xx*xp*(xx-t2)*A2*A2*(1.-zb2))/(2.*u2)*(L1b2-L2b2) +xx*xp*pow(1.-Q2,3)/(2.*u2)*(L1b2-L1a2)+xx*xp*Q2*A2*A2/(xx-u2)*(L1b2+L2a2) +xx*xp*Q2/(u2*u2)*L1b2*(2.*u2*(1.-Q2)*(1.-Q2)+4.*xx*(xx-t2)*A2-2.*xx*xx*(Q2-t2)-xx*xx*xx) -1./2.*xx*xp*pow(Q2-t2,2)*(1./(Q2-u2)-Q2/u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2) -1./2.*xx*xp*pow(Q2-u2,2)*(Q2/(Q2-t2)+1./u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2) +xx*xp*(Q2-t2)/(2.*u2*(Q2-u2))*((-3.*xx*xp+u2*u2-Q2*Q2)*(1.+Q2)-xx*u2+2.*Q2*Q2*(Q2-u2))*(-1.+2.*Q2/Qt2) +xx*xp*(Q2-u2)/(2.*u2*(Q2-t2))*(3.*xx*xp*(1.+Q2)-u2*Q2*(Q2-t2)+3.*Q2*xx*(Q2-u2)+t2*(u2+1.))*(-1.+2.*Q2/Qt2) +xx*xp*xx*Q2/(2.*u2*u2)*(2.*(1.-Q2)*(1.-Q2)-2.*xx*(1.-xx)-u2*(Q2-u2)-4.*xx*Q2)+xx*xp*(u2-t2)*(xx+Q2)/(2.*u2) -8.*pow(xx*xx*xp*Q2,2)/pow(u2,4)-2.*pow(xx*xx*xp*Q2,2)/pow(u2,4)*L1b2; ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2pp2)-1./xp/Q1*Jac1*(C2pp1)); const long double C2mm1=xx*xp*t1*t1*Q1/(2.*u1)*(L1a1+3.*L1b1)+1./2.*xx*xp*t1*t1*(1.-z)*(L2a1-L1a1)+xx*xp*Q1*pow(xx-t1,3)*zb1/(2.*u1*u1)*(L2b1-L1b1)+xx*xp*t1*t1*Q1/(xx-u1)*(L1b1+L2a1) +xx*xp*t1*t1/(2.*u1)*(L1b1-L1a1)+xx*xp*xx*Q1/(u1*u1)*(4.*t1*(t1-xx)+xx*xx)*L1b1-2.*pow(xx*xx*xp*Q1,2)/pow(u1,4)*L1b1+xx*xp*t1*t1*xx*Q1/(u1*u1)-8.*pow(xx*xx*xp*Q1,2)/(pow(u1,4)); const long double C2mm2=xx*xp*t2*t2*Q2/(2.*u2)*(L1a2+3.*L1b2)+1./2.*xx*xp*t2*t2*(1.-z)*(L2a2-L1a2)+xx*xp*Q2*pow(xx-t2,3)*zb2/(2.*u2*u2)*(L2b2-L1b2)+xx*xp*t2*t2*Q2/(xx-u2)*(L1b2+L2a2) +xx*xp*t2*t2/(2.*u2)*(L1b2-L1a2)+xx*xp*xx*Q2/(u2*u2)*(4.*t2*(t2-xx)+xx*xx)*L1b2-2.*pow(xx*xx*xp*Q2,2)/pow(u2,4)*L1b2+xx*xp*t2*t2*xx*Q2/(u2*u2)-8.*pow(xx*xx*xp*Q2,2)/(pow(u2,4)); ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2mm2)-1./xp/Q1*Jac1*(C2mm1)); const long double C2epsilon1=4.*pow(xx*xx*xp*Q1,2)/(pow(u1,4)); const long double C2epsilon2=4.*pow(xx*xx*xp*Q2,2)/(pow(u2,4)); ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2epsilon2)-1./xp/Q1*Jac1*(C2epsilon1));// All C2's OK -2 Nc Cf Log(x)^2/xp ris*=(1.-zmin); return ris; } // qqbar channel long double NLOPL::NLO_PL_notsing_doublediff_qqbar(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11= xx/(-t1)*_Cf*(1.-z)*2.*_Cf*_Cf*(t1*t1+z*z*xx*xx*xp*xp/(t1*t1))/z + xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(z*z+t1*t1)/(-xx*xp*z/(t1)); const long double Fi12= xx/(-t2)*_Cf*(1.-z)*2.*_Cf*_Cf*(t2*t2+z*z*xx*xx*xp*xp/(t2*t2))/z + xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(z*z+t2*t2)/(-xx*xp*z/(t2)); ris+=2.*(Jac2*Fi12-Jac1*Fi11); const long double Fi21=1./xp*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+(u1+t1-2.*Q1)*(u1+t1-2.*Q1))*std::log(xx*xp/Qt1); const long double Fi22=1./xp*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+(u2+t2-2.*Q2)*(u2+t2-2.*Q2))*std::log(xx*xp/Qt2); ris+=(Jac2*Fi22-Jac1*Fi21); // OK Log squared cancel themselves with similar in Fi1 const long double D1pm1=-xx*xp*Q1*(1.+std::log(xx*xp/Qt1))-(xx*xp*xx*xp*z*(1.-z))/(t1)-xx*xp*(1.-z)*(1.-z); const long double D1pm2=-xx*xp*Q2*(1.+std::log(xx*xp/Qt2))-(xx*xp*xx*xp*z*(1.-z))/(t2)-xx*xp*(1.-z)*(1.-z); ris+=2.*2.*_Cf*_Cf*_Cf*(Jac2/xp/Q2*D1pm2-Jac1/xp/Q1*D1pm1); // OK no Logs const long double D2pm1=-1./3.*xx*xp*Q1-xx*xp*t1*t1/(6.*z*z)*(11.-12.*Q1/Qt1+3.*Q1*Q1/Qt1/Qt1)+11.*xx*xp*t1*t1/6.; const long double D2pm2=-1./3.*xx*xp*Q2-xx*xp*t2*t2/(6.*z*z)*(11.-12.*Q2/Qt2+3.*Q2*Q2/Qt2/Qt2)+11.*xx*xp*t2*t2/6.; ris+=2.*2.*_Nc*_Cf*_Cf*(Jac2/xp/Q2*D2pm2-Jac1/xp/Q1*D2pm1); //OK no Logs const long double D1pp1=xx*xp*u1*u1*(1.-zb1)/A1*(L2b1-L1b1)+xx*xp*(xx-u1)*(xx-u1)*(1.-z)/A1*(L2a1-L1a1) +xx*xp*xx*Q1*(xx*xp+u1*t1)/(t1*t1)*L1a1-2.*xx*xp*xx*xx*Q1/(A1*B1)*L31+xx*xp*xx*Q1*(2.*xx*xp-u1*t1)/(t1*t1); const long double D1pp2=xx*xp*u2*u2*(1.-zb2)/A2*(L2b2-L1b2)+xx*xp*(xx-u2)*(xx-u2)*(1.-z)/A2*(L2a2-L1a2) +xx*xp*xx*Q2*(xx*xp+u2*t2)/(t2*t2)*L1a2-2.*xx*xp*xx*xx*Q2/(A2*B2)*L32+xx*xp*xx*Q2*(2.*xx*xp-u2*t2)/(t2*t2); ris+=2.*2.*_Cf*_Cf*_Cf*(Jac2/xp/Q2*D1pp2-Jac1/xp/Q1*D1pp1); //OK no Logs const long double D2pp1=xx*xp*u1*u1*(xx-t1)*(1.-zb1)/(2.*A1)*(L1b1-L2b1)+xx*xp*std::pow(xx-u1,3)*(1.-z)/(2.*A1)*(L1a1-L2a1) -0.5*xx*xp*u1*u1*(L1a1+L1b1)+6.*std::pow(xx*xp*xx*Q1,2)/std::pow(B1,4)-xx*xp*xx*Q1*u1*u1/B1/B1 +L31*(xx*xp*u1*u1*(u1+t1)/B1+std::pow(xx*xp*xx*Q1,2)*(1./(A1*B1*B1*B1)-3.*A1/std::pow(B1,5)) +xx*xp*xx*Q1*((t1-3.*u1)/(2.*B1)+A1*(B1*B1+2.*u1*u1)/(4.*B1*B1*B1)+(t1*t1-6.*t1*u1+7.*u1+u1)/(4.*A1*B1))); const long double D2pp2=xx*xp*u2*u2*(xx-t2)*(1.-zb2)/(2.*A2)*(L1b2-L2b2)+xx*xp*std::pow(xx-u2,3)*(1.-z)/(2.*A2)*(L1a2-L2a2) -0.5*xx*xp*u2*u2*(L1a2+L1b2)+6.*std::pow(xx*xp*xx*Q2,2)/std::pow(B2,4)-xx*xp*xx*Q2*u2*u2/B2/B2 +L32*(xx*xp*u2*u2*(u2+t2)/B2+std::pow(xx*xp*xx*Q2,2)*(1./(A2*B2*B2*B2)-3.*A2/std::pow(B2,5)) +xx*xp*xx*Q2*((t2-3.*u2)/(2.*B2)+A2*(B2*B2+2.*u2*u2)/(4.*B2*B2*B2)+(t2*t2-6.*t2*u2+7.*u2+u2)/(4.*A2*B2))); ris+=2.*2.*_Nc*_Cf*_Cf*(Jac2/xp/Q2*D2pp2-Jac1/xp/Q1*D2pp1); //OK no Logs const long double E11=8./3.*xx-4./3.*xx*xx; ris+=_Nf*_Cf*_Cf*E11*(Jac2-Jac1); //OK no Logs const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx; const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx; ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21); const long double E31=-2.*xx*xp*(std::pow(u1+t1-2.*Q1,2)-2.*xx*xp)*std::log(xx*xp/Qt1) -xx*xp*Q1*(2.*Qt1+Q1)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))-6.*xp*xx*Q1; const long double E32=-2.*xx*xp*(std::pow(u2+t2-2.*Q2,2)-2.*xx*xp)*std::log(xx*xp/Qt2) -xx*xp*Q2*(2.*Qt2+Q2)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))-6.*xp*xx*Q2; ris+=_Cf*_Cf/_Nc*(Jac2/(xp*Q2)*E32-Jac1/(xp*Q1)*E31); //OK no Logs ris*=(1.-zmin); return ris; } //qq channel long double NLOPL::NLO_PL_notsing_doublediff_qq(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11=xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(t1*t1+z*z)/(-xx*xp*z/(t1)); const long double Fi12=xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(t2*t2+z*z)/(-xx*xp*z/(t2)); ris+=2.*(Jac2*Fi12-Jac1*Fi11); const long double Fi21=xx*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+std::pow(u1+t1-2.*Q1,2))/(xx*xp)*std::log(xx*xp/Qt1); const long double Fi22=xx*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+std::pow(u2+t2-2.*Q2,2))/(xx*xp)*std::log(xx*xp/Qt2); ris+=(Jac2*Fi22-Jac1*Fi21); const long double E41=2.*xx*(1.+Q1*Q1)/Qt1*std::log(x*xp/Q1)+4.*xx*std::log(xx*xp/Qt1); const long double E42=2.*xx*(1.+Q2*Q2)/Qt2*std::log(x*xp/Q2)+4.*xx*std::log(xx*xp/Qt2); ris+=_Cf*_Cf/_Nc*(Jac2*E42-Jac1*E41); const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx; const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx; ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21); ris*=(1.-zmin); return ris; } //qqprime channel long double NLOPL::NLO_PL_notsing_doublediff_qqprime(double xp, double zz){ long double ris=0.0; //Set Energy, Transverse Momentum, Integration variable z const long double xx=x; const long double Nc=_Nc; const long double Nf=_Nf; const long double MUF=std::pow(_muF/_mH,2); const long double MUR=std::pow(_muR/_mH,2); const long double b0=11./6.*Nc-1./3.*Nf; const long double Cf=(Nc*Nc-1.)/(2.*Nc); const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2); const long double z=zmin+(1.-zmin)*zz; //Set Mandelstam variable const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z); const long double t1=0.5*(xx-z+rad); const long double u1=xx-0.5/z*(xx+z+rad); long double Q1=1.+t1+u1-xx; const long double Qt1=Q1+xx*xp; const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad)); const long double Jac1=(xx-z+rad)/(2.*z*rad); const long double t2=0.5*(xx-z-rad); const long double u2=xx-0.5/z*(xx+z-rad); long double Q2=1.+t2+u2-xx; const long double Qt2=Q2+xx*xp; const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad)); const long double Jac2=-(xx-z-rad)/(2.*z*rad); const long double A1=1.+xx-Q1; const long double B1=std::sqrt(A1*A1-4.*xx); const long double L1a1=std::log(xx/(z*z)); const long double L1b1=std::log(xx/(zb1*zb1)); const long double L2a1=std::log(xx/std::pow(A1-z,2)); const long double L2b1=std::log(xx/std::pow(A1-zb1,2)); const long double L31=std::log((A1+B1)/(A1-B1)); const long double A2=1.+xx-Q2; const long double B2=std::sqrt(A2*A2-4.*xx); const long double L1a2=std::log(xx/(z*z)); const long double L1b2=std::log(xx/(zb2*zb2)); const long double L2a2=std::log(xx/std::pow(A2-z,2)); const long double L2b2=std::log(xx/std::pow(A2-zb2,2)); const long double L32=std::log((A2+B2)/(A2-B2)); //Define and add regular parts in G2s (refer to Glover paper for definition of G2s) const long double Fi11=xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(t1*t1+z*z)/(-xx*xp*z/(t1)); const long double Fi12=xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(t2*t2+z*z)/(-xx*xp*z/(t2)); ris+=2.*(Jac2*Fi12-Jac1*Fi11); const long double Fi21=xx*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+std::pow(u1+t1-2.*Q1,2))/(xx*xp)*std::log(xx*xp/Qt1); const long double Fi22=xx*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+std::pow(u2+t2-2.*Q2,2))/(xx*xp)*std::log(xx*xp/Qt2); ris+=(Jac2*Fi22-Jac1*Fi21); const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx; const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx; ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21); ris*=(1.-zmin); return ris; } long double NLOPL::NLO_PL_notsing_doublediff_qqbarprime(double xp, double zz) { return(NLO_PL_notsing_doublediff_qqprime(xp,zz)); } long double NLOPL::LO_PL(double xp){ //we have to multiply later for sigma0 normalization const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp); const long double t=0.5*(x-1.+rad); const long double u=0.5*(x-1.-rad); switch(_channel){ case(1):{ return (4.*_Nc*(std::pow(1.+(x-1.)*x,2)-2.*(x-1.)*(x-1.)*x*xp+x*x*xp*xp)/(xp*rad)*_as/(2.*M_PIl)); break; } case(2):{ return(_as/(2.*M_PIl)*_Cf*x/rad*((1.+u*u)/(-t)+(1.+t*t)/(-u))); break; } case(3):{ return(_as/(2.*M_PIl)*2.*_Cf*_Cf*x/rad*(u*u+t*t)); break; } case(4):{ return 0; break; } case(5):{ return 0; break; } case(6):{ return 0; break; } } }
58.466158
214
0.576788
bda211f32ff786c1408ba9af932215c7ce1c47a7
812
cpp
C++
Project/battleship.cpp
JonnyPugh/Battleship
4ff20bc9806224487a7ab413e695298bd330568e
[ "MIT" ]
null
null
null
Project/battleship.cpp
JonnyPugh/Battleship
4ff20bc9806224487a7ab413e695298bd330568e
[ "MIT" ]
null
null
null
Project/battleship.cpp
JonnyPugh/Battleship
4ff20bc9806224487a7ab413e695298bd330568e
[ "MIT" ]
null
null
null
#include "agent.h" #include "player.h" #include "cpu.h" #include <iostream> using std::cout; using std::endl; using std::cin; int main() { // Determine whether the game will be 0, 1, or 2 player. unsigned int num_players = 3; while (num_players != 0 && num_players != 1 && num_players != 2) { cout << "Specify number of human players (0, 1, or 2): "; cin >> num_players; cin.clear(); while (getchar() != '\n'); } // Set up the game. agent* p1; agent* p2; if (num_players == 0) { p1 = new cpu(); p2 = new cpu(); } else if (num_players == 1) { p1 = new player(); p2 = new cpu(); } else { p1 = new player(); p2 = new player(); } p1->initialize(p2); p2->initialize(p1); // Play the game until someone wins. while (!(p1->turn() || p2->turn())); delete p1; delete p2; }
16.571429
65
0.587438
bda5c0edf01f038f611d78c8ee2b7e90a0a7c0a1
9,628
cpp
C++
src/Game.cpp
M4T1A5/IndieSpeedRun2013
75b1adc4716c2e32f308289cce51a78a10681697
[ "Zlib" ]
null
null
null
src/Game.cpp
M4T1A5/IndieSpeedRun2013
75b1adc4716c2e32f308289cce51a78a10681697
[ "Zlib" ]
null
null
null
src/Game.cpp
M4T1A5/IndieSpeedRun2013
75b1adc4716c2e32f308289cce51a78a10681697
[ "Zlib" ]
null
null
null
#include <Game.h> #include <time.h> #include <stdlib.h> using namespace EGEMath; using namespace EGEMotor; Game::Game(Viewport& viewport, Input &input) : input(&input), viewport(&viewport), gameState(MENU), _clock(0), Difficulty(1) { font = new Font("square.ttf"); resourceText = new Text("", font); resourceText->setPosition(Vector(viewport.getWindowSize().x - 75, 0)); resourceText->setOriginPoint(9); resourceText->setLayer(295); resources = 6; health = 5; healthText = new Text("", font); healthText->setPosition(Vector(viewport.getWindowSize().x - 75, 30)); healthText->setOriginPoint(9); healthText->setLayer(295); activeButton[FOREST]=false; activeButton[SWAMP]=false; activeButton[HURRICANE]=false; activeButton[BUG]=false; activeButton[CAT]=false; activeButton[RIVER]=false; srand(time(NULL)); camera = new Camera(input, viewport, map.GetSize()); _townTexture.loadTexture("village.png"); _villageTexture.loadTexture("settlement.png"); _explorerTexture.loadTexture("arke_sheet.png"); _villages.push_back(new Village(&_townTexture,Vector(300,800))); // Menu menuTexture = new Texture("menu.png"); menu.setTexture(menuTexture); startTexture = new Texture("startbutton.png"); startButton = new GUIButton(startTexture, viewport.getWindowSize() / 2, Rectangle(Vector(), startTexture->getTextureSize()), &input); startButton->setOriginPoint(5); gameOverTexture = new Texture("game over.png"); gameOver.setTexture(gameOverTexture); gameOver.setPosition(startButton->getPosition()); gameOver.setOriginPoint(5); tutorialNumber = 0; for(int i = 0; i < 5; ++i) { char merkkijono[20]; sprintf(merkkijono, "tutorial-%d.png", i+1); tutorialTexture.push_back(new Texture(merkkijono)); tutorial.push_back(new GameObject(tutorialTexture[i])); tutorial[i]->setPosition(Vector(-1000,-1000)); tutorial[i]->setOriginPoint(5); } // Sidebar sidebarTexture = new Texture("sidebar2.png"); sidebar.setTexture(sidebarTexture); Vector sidebarPos = Vector(viewport.getWindowSize().x - sidebarTexture->getTextureSize().x, 0); sidebar.setPosition(sidebarPos); sidebar.setLayer(295); // Buttons buttonTexture = new Texture("buttons2.png"); for(int i = 0; i < 6; ++i) { Vector buttonPos = sidebarPos + Vector(0, i*120); Rectangle crop = Rectangle(Vector(i*75, 0), Vector(150,150)); auto button = new GUIButton(buttonTexture, buttonPos, crop, &input); button->setLayer(296); buttons.push_back(button); } buttons[0]->elementToSpawn = Forest; buttons[1]->elementToSpawn = Swamp; buttons[2]->hazardToSpawn = tornado; buttons[3]->hazardToSpawn = cat; buttons[4]->hazardToSpawn = bug; buttons[5]; particleEngine = new ParticleEngine(); } Game::~Game() { delete startTexture; delete startButton; delete menuTexture; delete sidebarTexture; delete buttonTexture; tutorialTexture.empty(); tutorial.empty(); buttons.empty(); } // Public void Game::Update(const double& dt) { char merkkijono[20]; Vector windowSize = viewport->getWindowSize(); Vector mousePos = input->getMousePosition(); switch (gameState) { case MENU: if (tutorialNumber == 0 && startButton->isPressed() ) { tutorial[tutorialNumber]->setPosition(startButton->getPosition()); tutorialNumber++; } if(tutorialNumber > 0 && tutorialNumber < tutorial.size()) { if(input->isButtonPressed(MouseLeft)) { tutorial[tutorialNumber]->setPosition(startButton->getPosition()); tutorialNumber++; } } if(tutorialNumber == tutorial.size()) { if(input->isButtonPressed(MouseLeft)) { for(int i = 0; i < tutorial.size(); ++i) tutorial[i]->setPosition(Vector(-1000,-1000)); gameState = WARMUP; } } break; case WARMUP: sprintf(merkkijono, "Resources: %d", resources); resourceText->setString(merkkijono); resourceText->updateOrigin(); sprintf(merkkijono, "Health: %d", health); healthText->setString(merkkijono); healthText->updateOrigin(); _clock += dt; if((windowSize.x - mousePos.x) < 5 || mousePos.x < 5) { camera->FollowMouse(dt); } else if((windowSize.y - mousePos.y) < 5 || mousePos.y < 5) { camera->FollowMouse(dt); } for(int i = 0; i < 2; ++i) { if(buttons[i]->isPressed()) spawnElement = buttons[i]->elementToSpawn; } if(spawnElement > 0 && input->isButtonPressed(Button::MouseLeft) && resources > 0) { map.AddElement(spawnElement, input->getMousePositionOnMap()); resources--; } if (_clock > 20) { _clock=0; gameState = PLAY; } break; case PLAY: sprintf(merkkijono, "Health: %d", health); healthText->setString(merkkijono); healthText->updateOrigin(); if((windowSize.x - mousePos.x) < 5 || mousePos.x < 5) { camera->FollowMouse(dt); } else if((windowSize.y - mousePos.y) < 5 || mousePos.y < 5) { camera->FollowMouse(dt); } for(int i = 2; i < 5; ++i) { if(buttons[i]->isPressed()) { spawnHazard = buttons[i]->hazardToSpawn; spawnElement = Background; } } if(spawnHazard >= 0 && input->isButtonPressed(Button::MouseLeft) ) { switch(spawnHazard) { case tornado: particleEngine->addTornado(input->getMousePositionOnMap(), Vector(1,1)); break; case cat: particleEngine->addCat(input->getMousePositionOnMap(), Vector(100,1)); break; case bug: particleEngine->addBug(input->getMousePositionOnMap(), Vector(100,1)); break; } } for (int i=0; i<_villages.size(); ++i) { _villages[i]->Update(dt); if (_villages[i]->Clock > _villages[i]->NextVillager) { _villages[i]->Clock -= _villages[i]->NextVillager; _villages[i]->NextVillager = (rand()%5)/Difficulty; _explorers.push_back(new Explorer(&_explorerTexture,16, _explorerTexture.getTextureSize().x/4.0f, _explorerTexture.getTextureSize().y/4.0f, 12,_villages[i]->getPosition())); } } for (int i=0; i<_explorers.size(); ++i) { _explorers[i]->Update(dt, map._mapElements[Volcano][0]->getPosition()); for (int j=0; j<map._mapElements.size();++j) { for (int k=0; k<map._mapElements[j].size();++k) { switch(j) { case Background: break; case River: if (map.GetPixel(_explorers[i]->getPosition()) != sf::Color::Transparent) { _explorers[i]->slowed=true; if (activeButton[RIVER]) { _explorers[i]->poison=true; } } break; case Forest: _explorers[i]->getPosition(); map._mapElements[j][k]->getPosition(); if ((_explorers[i]->getPosition()-map._mapElements[j][k]->getPosition()) .getLenght()< map._mapElementList[j]->Radius) { _explorers[i]->slowed=true; if (activeButton[FOREST]) { if(rand()%10000 > 9999-10000*dt); } } break; case Swamp: if ((_explorers[i]->getPosition()-map._mapElements[j][k]->getPosition()) .getLenght()< map._mapElementList[j]->Radius) { _explorers[i]->slowed=true; _explorers[i]->poison=true; if (activeButton[SWAMP]) { } } break; case Volcano: if(map._mapElements[j][k]-> getGlobalBounds().contains(_explorers[i]->getPosition())) { health--; _explorers.erase(_explorers.begin() + i); } break; } } } for (int j=0; j<particleEngine->m_TornadoParticles.size();++j) { if ((_explorers[i]->getPosition()-particleEngine->m_TornadoParticles[j]->m_position+Vector(0,-60)).getLenght() < particleEngine->m_TornadoParticles[j]->AreaOfEffect) { _explorers[i]->setPosition(particleEngine->m_TornadoParticles[j]->m_position+Vector(0,-10)); } } for (int j=0; j<particleEngine->m_BugParticles.size();++j) { if ((_explorers[i]->getPosition()-particleEngine->m_BugParticles[j]->m_position+Vector(0,80)).getLenght() < particleEngine->m_BugParticles[j]->AreaOfEffect) { _explorers[i]->poison = true; } } for (int j=0; j<particleEngine->m_CatParticles.size();++j) { if ((_explorers[i]->getPosition()-particleEngine->m_CatParticles[j]->m_position).getLenght() < particleEngine->m_CatParticles[j]->AreaOfEffect) { _explorers[i]->dead = true; } } if (_explorers[i]->dead) _explorers.erase(_explorers.begin() + i); } if(health == 0) gameState = GAMEOVER; break; case PAUSE: break; case GAMEOVER: if(input->isButtonPressed(MouseLeft)) exit(0); break; } for(size_t i = 0; i < buttons.size(); ++i) { if(buttons[i]->mouseOver()) buttons[i]->setColor(255,255,255,255); else buttons[i]->setColor(255,255,255,150); } map.Update(dt); particleEngine->Update(dt); } void Game::Draw(EGEMotor::Viewport& viewport) { switch (gameState) { case MENU: menu.Draw(viewport); startButton->draw(viewport); for(int i = 0; i < tutorial.size(); ++i) tutorial[i]->Draw(viewport); viewport.renderSprites(); break; case PAUSE: case WARMUP: case PLAY: map.Draw(viewport); for (int i=0;i<_villages.size();++i) _villages[i]->Draw(viewport); for (int i=0;i<_explorers.size();++i) _explorers[i]->Draw(viewport); for(size_t i = 0; i < buttons.size(); ++i) { buttons[i]->draw(viewport); } sidebar.Draw(viewport); viewport.draw(resourceText); viewport.draw(healthText); viewport.renderSprites(); break; case GAMEOVER: gameOver.Draw(viewport); viewport.renderSprites(); break; } particleEngine->Draw(&viewport); viewport.renderSprites(); } void Game::reset() { health = 5; resources = 6; gameState = MENU; _villages.empty(); _explorers.empty(); map.Reset(); }
24.498728
169
0.654342
bdaf2f711fbe5aed14096c7ac4c7304eeab8ab0b
2,988
hpp
C++
include/makeshift/experimental/mpark/variant.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
3
2020-04-03T14:06:41.000Z
2021-11-09T23:55:52.000Z
include/makeshift/experimental/mpark/variant.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
2
2020-04-03T14:21:09.000Z
2022-02-08T14:37:01.000Z
include/makeshift/experimental/mpark/variant.hpp
mbeutel/makeshift
68e6bdee79060f3b258c031c53ff641325d13411
[ "BSL-1.0" ]
null
null
null
#ifndef INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_ #define INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_ #include <utility> // for forward<>() #include <type_traits> // for remove_cv<>, remove_reference<> #include <gsl-lite/gsl-lite.hpp> // for gsl_Expects(), gsl_NODISCARD #include <mpark/variant.hpp> #include <makeshift/experimental/detail/variant.hpp> namespace makeshift { namespace gsl = ::gsl_lite; namespace mpark { // // Given an argument of type `mpark::variant<Ts...>`, this is `mpark::variant<::mpark::monostate, Ts...>`. // template <typename V> using with_monostate = typename detail::with_monostate_<::mpark::variant, ::mpark::monostate, V>::type; // // Given an argument of type `mpark::variant<::mpark::monostate, Ts...>`, this is `mpark::variant<Ts...>`. // template <typename V> using without_monostate = typename detail::without_monostate_<::mpark::variant, ::mpark::monostate, V>::type; // // Casts an argument of type `mpark::variant<Ts...>` to the given variant type. // template <typename DstV, typename SrcV> gsl_NODISCARD constexpr DstV variant_cast(SrcV&& variant) { #if !(defined(_MSC_VER) && defined(__INTELLISENSE__)) return ::mpark::visit( [](auto&& arg) -> DstV { return std::forward<decltype(arg)>(arg); }, std::forward<SrcV>(variant)); #endif // MAKESHIFT_INTELLISENSE } // // Converts an argument of type `mpark::variant<::mpark::monostate, Ts...>` to `std::optional<::mpark::variant<Ts...>>`. // //template <typename V> //gsl_NODISCARD constexpr decltype(auto) //variant_to_optional(V&& variantWithMonostate) //{ // using R = without_monostate<std::remove_cv_t<std::remove_reference_t<V>>>; // if (std::holds_alternative<::mpark::monostate>(variantWithMonostate)) // { // return std::optional<R>(std::nullopt); // } //#if !(defined(_MSC_VER) && defined(__INTELLISENSE__)) // return std::optional<R>(::mpark::visit( // detail::monostate_filtering_visitor<::mpark::monostate, R>{ }, // std::forward<V>(variantWithMonostate))); //#endif // MAKESHIFT_INTELLISENSE //} // // Converts an argument of type `std::optional<::mpark::variant<Ts...>>` to `mpark::variant<::mpark::monostate, Ts...>`. // //template <typename VO> //gsl_NODISCARD constexpr decltype(auto) //optional_to_variant(VO&& optionalVariant) //{ // using R = with_monostate<typename std::remove_cv_t<std::remove_reference_t<VO>>::value_type>; // if (!optionalVariant.has_value()) // { // return R{ ::mpark::monostate{ } }; // } // return variant_cast<R>(*std::forward<VO>(optionalVariant)); //} // // Concatenates the alternatives in the given variants. // template <typename... Vs> using variant_cat_t = typename detail::variant_cat_<::mpark::variant, Vs...>::type; } // namespace mpark } // namespace makeshift #endif // INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_
30.489796
131
0.670348
bdb13c44649bc17925bd720db8b399956d2d1e35
12,327
cpp
C++
src/main.x.cpp
gregbartell/mf83_solitaire_solver
3c02eb87c62bc9cde72bc3c5f4641648cc8fff2f
[ "Unlicense" ]
null
null
null
src/main.x.cpp
gregbartell/mf83_solitaire_solver
3c02eb87c62bc9cde72bc3c5f4641648cc8fff2f
[ "Unlicense" ]
null
null
null
src/main.x.cpp
gregbartell/mf83_solitaire_solver
3c02eb87c62bc9cde72bc3c5f4641648cc8fff2f
[ "Unlicense" ]
null
null
null
#include <algorithm> #include <array> #include <cassert> #include <cstdint> #include <deque> #include <iostream> #include <random> #include <unordered_map> #include <vector> class Card { public: // Takes char of number or T/J/Q/K/A Card(char kind) : m_kind{kind} { assert(m_kind == 'A' || (m_kind > '0' && m_kind <= '9') || m_kind == 'T' || m_kind == 'J' || m_kind == 'Q' || m_kind == 'K'); // Store aces as 1, since they are always low if (m_kind == 'A') { m_kind = '1'; } } bool operator==(const Card& other) const { return m_kind == other.m_kind; } bool operator!=(const Card& other) const { return !(*this == other); } unsigned int value() const { if (m_kind > '0' && m_kind <= '9') { return m_kind - '0'; } assert(m_kind == 'T' || m_kind == 'J' || m_kind == 'Q' || m_kind == 'K'); return 10; } auto kind() const { return m_kind; } private: char m_kind; }; class State { public: State(std::array<std::deque<Card>, 4> piles, std::vector<Card> stack = {}, unsigned int score = 0) : m_scores{score}, m_stacks{std::move(stack)}, m_piles{std::move(piles)} { } auto getScore() const { assert(m_scores.size() > 0); return m_scores.back(); } const auto& getStack() const { assert(m_stacks.size() > 0); return m_stacks.back(); } const auto& getPiles() const { return m_piles; } unsigned int getStackVal() const { unsigned int ret = 0; for (const auto& card : getStack()) { ret += card.value(); } return ret; } std::vector<size_t> getLegalMoves() const { std::vector<size_t> ret{}; auto stack_val = getStackVal(); for (size_t pile_idx = 0; pile_idx < m_piles.size(); pile_idx++) { const auto& pile = m_piles[pile_idx]; if (!pile.empty() && (stack_val + pile.front().value()) <= 31) { ret.emplace_back(pile_idx); } } return ret; } void makeMove(size_t pile_idx) { assert(pile_idx < m_piles.size()); assert(!m_piles[pile_idx].empty()); assert(getStackVal() + m_piles[pile_idx].front().value() <= 31); m_cards.emplace_back(m_piles[pile_idx].front(), pile_idx); const auto& card = m_cards.back().first; m_piles[pile_idx].pop_front(); // Copy the previous stack, adding our card m_stacks.emplace_back(m_stacks.back()); m_stacks.back().emplace_back(card); auto& stack = m_stacks.back(); // Copy the previous score; we'll increment it next m_scores.emplace_back(m_scores.back()); auto& score = m_scores.back(); // Scoring conditions: // First card is a Jack - 2 points if (stack.size() == 1 && card.kind() == 'J') { score += 2; } // Stack total is exactly 15 - 2 points // Stack total is exactly 31 - 2 points (and clear stack) if (auto stack_val = getStackVal(); stack_val == 15 || stack_val == 31) { score += 2; } // Doubles/Triples/Quads - 2/6/12 points size_t set_size = 0; for (auto rit = stack.rbegin(); rit != stack.rend(); rit++) { if (rit->kind() != card.kind()) { break; } set_size++; } switch (set_size) { case 1: break; case 2: score += 2; break; case 3: score += 6; break; case 4: score += 12; break; default: std::abort(); } // Runs of numbers, in any order - points equal to run length for (size_t run_size = std::min(size_t{7}, stack.size()); run_size >= 3; run_size--) { std::vector<unsigned int> run_set{}; for (auto rit = stack.rbegin(); static_cast<size_t>(rit - stack.rbegin()) < run_size; rit++) { if (rit->value() < 10) { run_set.emplace_back(rit->value()); } else { switch (rit->kind()) { case 'T': run_set.emplace_back(10); break; case 'J': run_set.emplace_back(11); break; case 'Q': run_set.emplace_back(12); break; case 'K': run_set.emplace_back(13); break; default: std::abort(); } } } std::sort(run_set.begin(), run_set.end()); bool is_run = true; unsigned int prev = run_set.front(); for (size_t i = 1; i < run_set.size(); i++) { if (run_set[i] != prev + 1) { is_run = false; break; } prev = run_set[i]; } if (is_run) { score += run_size; break; } } if (getLegalMoves().empty()) { stack.clear(); } } void undoMove() { // Can't undo before the initial state assert(m_scores.size() > 1); // Should have had the same number of moves made assert(m_scores.size() == m_stacks.size()); // We'll have one more score than card because the initial state has no // card moved yet assert(m_scores.size() == m_cards.size() + 1); // Remove any points added by the last move m_scores.pop_back(); // Put the last moved card back const auto& [card, pile_idx] = m_cards.back(); m_piles[pile_idx].emplace_front(card); m_cards.pop_back(); // Reset the stack to its previous state m_stacks.pop_back(); } private: // Store these as queues of every game state, with more recent states at the // back std::deque<unsigned int> m_scores{}; // Cards moved from a pile to a stack, and the pile idx std::deque<std::pair<Card, size_t>> m_cards{}; std::deque<std::vector<Card>> m_stacks{}; std::array<std::deque<Card>, 4> m_piles{}; }; class TranspositionTable { public: TranspositionTable() { std::uniform_int_distribution<size_t> dist{}; std::random_device rd{}; std::default_random_engine gen{rd()}; for (auto& card_pom_hash : m_stack_hashes) { for (auto& card_kind_hash : card_pom_hash) { card_kind_hash = dist(gen); } } for (auto& card_pom_hash : m_pile_hashes) { for (auto& card_kind_hash : card_pom_hash) { card_kind_hash = dist(gen); } } } void insert(const State& state, size_t best_move, unsigned int best_score) { auto key = getKey(state); m_map.emplace(key, std::make_pair(best_move, best_score - state.getScore())); } std::pair<size_t, unsigned int> getVal(const State& state) const { auto key = getKey(state); const auto search_ret = m_map.find(key); if (search_ret == m_map.end()) { return {std::numeric_limits<size_t>::max(), 0}; } return search_ret->second; } void clear() { m_map.clear(); } private: uint64_t getKey(const State& state) const { uint64_t key = 0; size_t card_idx = 0; for (const auto& card : state.getStack()) { key ^= m_stack_hashes[card_idx++][getCardKindIdx(card)]; } const auto& piles = state.getPiles(); for (size_t pile_idx = 0; pile_idx < 4; pile_idx++) { const auto& pile = piles[pile_idx]; card_idx = 0; for (const auto& card : pile) { key ^= m_pile_hashes[pile_idx * 13 + card_idx++] [getCardKindIdx(card)]; } } return key; } static size_t getCardKindIdx(const Card& card) { switch (card.kind()) { case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'T': return 10; case 'J': return 11; case 'Q': return 12; case 'K': return 13; default: std::abort(); } } // State key -> score std::unordered_map<uint64_t, std::pair<size_t, unsigned int>> m_map{}; std::array<std::array<uint64_t, 14>, 31> m_stack_hashes{}; std::array<std::array<uint64_t, 14>, 52> m_pile_hashes{}; }; class Searcher { public: Searcher(State state) : m_state{std::move(state)} {} // First = pile index to choose // Second = resultant score std::pair<size_t, unsigned int> getBestMove() { if (auto ret = m_transpo_table.getVal(m_state); ret.second != 0) { return {ret.first, ret.second + m_state.getScore()}; } auto legal_moves = m_state.getLegalMoves(); if (legal_moves.empty()) { return {std::numeric_limits<size_t>::max(), m_state.getScore()}; } size_t best_move = std::numeric_limits<size_t>::max(); unsigned int best_score = 0; for (const auto& move : legal_moves) { m_state.makeMove(move); auto move_result = getBestMove(); if (move_result.second > best_score) { best_move = move; best_score = move_result.second; } m_state.undoMove(); } m_transpo_table.insert(m_state, best_move, best_score); return {best_move, best_score}; } void makeMove(size_t pile_idx) { m_state.makeMove(pile_idx); } auto getLegalMoves() const { return m_state.getLegalMoves(); } const auto& getStack() const { return m_state.getStack(); } auto getScore() const { return m_state.getScore(); } private: State m_state; TranspositionTable m_transpo_table{}; }; int main() { std::array<std::deque<Card>, 4> piles{}; for (size_t i = 0; i < 52; i++) { unsigned int val = 0; std::cin >> val; if (val < 10) { piles[i / 13].emplace_front(val + '0'); } else { switch (val) { case 0: // A sentinel value meaning the card isn't there continue; case 10: piles[i / 13].emplace_front('T'); break; case 11: piles[i / 13].emplace_front('J'); break; case 12: piles[i / 13].emplace_front('Q'); break; case 13: piles[i / 13].emplace_front('K'); break; default: std::abort(); } } } Searcher searcher{piles}; while (!searcher.getLegalMoves().empty()) { const auto& [best_move, best_score] = searcher.getBestMove(); searcher.makeMove(best_move); std::cout << best_move << std::endl; if (searcher.getStack().empty() && !searcher.getLegalMoves().empty()) { std::cout << "-" << std::endl; } } return 0; }
27.151982
80
0.475298
bdb2cae06023da708310a9bf1a528329ad9e9245
1,554
cpp
C++
interface/src/graphics/RenderEventHandler.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
interface/src/graphics/RenderEventHandler.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
interface/src/graphics/RenderEventHandler.cpp
Darlingnotin/Antisocial_VR
f1debafb784ed5a63a40fe9b80790fbaccfedfce
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // RenderEventHandler.cpp // // Created by Bradley Austin Davis on 29/6/2018. // Copyright 2018 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "RenderEventHandler.h" #include "Application.h" #include <shared/GlobalAppProperties.h> #include <shared/QtHelpers.h> #include "CrashHandler.h" RenderEventHandler::RenderEventHandler(CheckCall checkCall, RenderCall renderCall) : _checkCall(checkCall), _renderCall(renderCall) { // Transfer to a new thread moveToNewNamedThread(this, "RenderThread", [this](QThread* renderThread) { hifi::qt::addBlockingForbiddenThread("Render", renderThread); _lastTimeRendered.start(); }, std::bind(&RenderEventHandler::initialize, this), QThread::HighestPriority); } void RenderEventHandler::initialize() { setObjectName("Render"); PROFILE_SET_THREAD_NAME("Render"); setCrashAnnotation("render_thread_id", std::to_string((size_t)QThread::currentThreadId())); } void RenderEventHandler::resumeThread() { _pendingRenderEvent = false; } void RenderEventHandler::render() { if (_checkCall()) { _lastTimeRendered.start(); _renderCall(); } } bool RenderEventHandler::event(QEvent* event) { switch ((int)event->type()) { case ApplicationEvent::Render: render(); _pendingRenderEvent.store(false); return true; default: break; } return Parent::event(event); }
26.338983
95
0.699485
bdb8301f9fe674aa624ee931f7f6bdc8dbd8aa25
1,832
cpp
C++
DigitalRoot.cpp
jb2020-super/kata
f6217d8b7c8854c89ff27d6bd70975b7aff85f89
[ "MIT" ]
null
null
null
DigitalRoot.cpp
jb2020-super/kata
f6217d8b7c8854c89ff27d6bd70975b7aff85f89
[ "MIT" ]
null
null
null
DigitalRoot.cpp
jb2020-super/kata
f6217d8b7c8854c89ff27d6bd70975b7aff85f89
[ "MIT" ]
null
null
null
/* Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer. 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2 */ /* best solution: A math guy here. Let me do my best to explain this code to anybody who does not yet understands it. The idea behind this trick is: sum of digits of a number 'n' is same as the number 'n' itself modulo 9. For example, 23 = 9*2+5 = 5 (modulo 9) = 2 + 3 (sum of digits modulo 9). If you don't believe it - try it with any number you come up with, I will leave a semiformal proof in the end. So, after any interchanging 'n' with a sum of digits of 'n' we have the same number modulo 9. And in the end we clearly have a one-digit number. I hope you got the gist of how we can figure the final number. //semiformal proof further //before further reading - be sure to understand why 9, 99, 999, 9999, etc are divisible by 9. Let us prove it for a number 7235. First, notice that 7000 = 7 (modulo 9). Why is that? Because 7000 - 7 = 7 * (1000 - 1) = 7 * 999 = 0 (modulo 9). Then, 200 = 2 (modulo 9). Again, 200 - 2 = 2 * (100-1) = 2 * 99 = 0(modulo 9) Hopefully, you see how this works. Now without my annoying comments: 7000 = 7(modulo 9) 200 = 2 (modulo 9) 30 = 3 (modulo 9) 5 = 5(modulo 9) all that is left to do is to add up these equations. */ int digital_root(int Z) { return --Z % 9 + 1; } int digital_root1(int n) { int sum = n; do { n = sum; sum = 0; while (n) { sum += n % 10; n /= 10; } } while (sum >= 10); return sum; }
38.166667
287
0.606441
bdb98f8b83fe9562eb64a33632de182e2f962789
1,525
cc
C++
chrome/services/printing/pdf_to_emf_converter_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/services/printing/pdf_to_emf_converter_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/services/printing/pdf_to_emf_converter_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/services/printing/pdf_to_emf_converter_factory.h" #include <utility> #include "chrome/services/printing/pdf_to_emf_converter.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" #include "mojo/public/cpp/system/platform_handle.h" namespace printing { PdfToEmfConverterFactory::PdfToEmfConverterFactory() = default; PdfToEmfConverterFactory::~PdfToEmfConverterFactory() = default; void PdfToEmfConverterFactory::CreateConverter( base::ReadOnlySharedMemoryRegion pdf_region, const PdfRenderSettings& render_settings, mojo::PendingRemote<mojom::PdfToEmfConverterClient> client, CreateConverterCallback callback) { auto converter = std::make_unique<PdfToEmfConverter>( std::move(pdf_region), render_settings, std::move(client)); uint32_t page_count = converter->total_page_count(); mojo::PendingRemote<mojom::PdfToEmfConverter> converter_remote; mojo::MakeSelfOwnedReceiver( std::move(converter), converter_remote.InitWithNewPipeAndPassReceiver()); std::move(callback).Run(std::move(converter_remote), page_count); } // static void PdfToEmfConverterFactory::Create( mojo::PendingReceiver<mojom::PdfToEmfConverterFactory> receiver) { mojo::MakeSelfOwnedReceiver(std::make_unique<PdfToEmfConverterFactory>(), std::move(receiver)); } } // namespace printing
37.195122
79
0.775082
bdba0a9c8a4aa4bb8f2faa7e5818dc3bc650d72b
1,256
cpp
C++
lib/code/widgets/single_child.cpp
leddoo/cpp-gui
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
[ "MIT" ]
null
null
null
lib/code/widgets/single_child.cpp
leddoo/cpp-gui
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
[ "MIT" ]
null
null
null
lib/code/widgets/single_child.cpp
leddoo/cpp-gui
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
[ "MIT" ]
null
null
null
#include <cpp-gui/core/gui.hpp> #include <cpp-gui/widgets/single_child.hpp> Single_Child_Def::~Single_Child_Def() { safe_delete(&this->child); } Widget* Single_Child_Def::on_get_widget(Gui* gui) { return gui->create_widget_and_match<Single_Child_Widget>(*this); } Single_Child_Widget::~Single_Child_Widget() { this->drop_maybe(this->child); this->child = nullptr; } void Single_Child_Widget::match(const Single_Child_Def& def) { this->child = this->reconcile(this->child, def.child); this->mark_for_layout(); } Bool Single_Child_Widget::on_try_match(Def* def) { return try_match_t<Single_Child_Def>(this, def); } void Single_Child_Widget::on_layout(Box_Constraints constraints) { // todo: sizing bias. if(this->child != nullptr) { this->child->layout(constraints); this->size = this->child->size; } else { this->size = { 0, 0 }; } } void Single_Child_Widget::on_paint(ID2D1RenderTarget* target) { if(this->child != nullptr) { this->child->paint(target); } } Bool Single_Child_Widget::visit_children_for_hit_testing(std::function<Bool(Widget* child)> visitor, V2f point) { UNUSED(point); return this->child != nullptr && visitor(this->child); }
22.836364
113
0.684713
bdbb708a347c590ef630a45f6f1b3ef678bc7ce5
253
cpp
C++
src/process.cpp
Matthew-Zimmer/Harpoon
81420c815f8930d20c9e082973442d9fe7a7ddea
[ "BSL-1.0" ]
1
2019-12-22T20:02:31.000Z
2019-12-22T20:02:31.000Z
src/process.cpp
Matthew-Zimmer/harpoon
81420c815f8930d20c9e082973442d9fe7a7ddea
[ "BSL-1.0" ]
null
null
null
src/process.cpp
Matthew-Zimmer/harpoon
81420c815f8930d20c9e082973442d9fe7a7ddea
[ "BSL-1.0" ]
null
null
null
#include "process.hpp" namespace Slate::Harpoon { Base_Process::Base_Process(std::string const& name) : name{ name } {} Memory::Block& Buffer<void, void>::Queues() { static Memory::Block queues; return queues; }; }
19.461538
71
0.608696
bdbf9abebcd92508f563e26a4b124f176142bb6b
21,051
hh
C++
src/exec/NodeImpl.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
1
2022-03-30T20:16:43.000Z
2022-03-30T20:16:43.000Z
src/exec/NodeImpl.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
src/exec/NodeImpl.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2006-2021, Universities Space Research Association (USRA). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Universities Space Research Association nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY USRA ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL USRA BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NODE_IMPL_HH #define NODE_IMPL_HH // *** For debug use only *** // Uncomment this if we don't trust the condition activation/deactivation logic // #define PARANOID_ABOUT_CONDITION_ACTIVATION 1 #include "Node.hh" #include "NodeVariables.hh" #include "Notifier.hh" #include <memory> // std::unique_ptr namespace PLEXIL { using ExpressionPtr = std::unique_ptr<Expression>; class Mutex; using MutexPtr = std::unique_ptr<Mutex>; class NodeVariableMap; using NodeVariableMapPtr = std::unique_ptr<NodeVariableMap>; class NodeTimepointValue; using NodeTimepointValuePtr = std::unique_ptr<NodeTimepointValue>; class NodeImpl; using NodeImplPtr = std::unique_ptr<NodeImpl>; /** * @class NodeImpl * @brief The innards shared between node implementation classes, * the XML parser, and external interfaces; also the * implementation class for empty nodes. */ class NodeImpl : public Node, public Notifier { public: // NOTE: this used to be 100000000, which somehow gets printed as // scientific notation in XML and doesn't parse correctly. static constexpr int32_t WORST_PRIORITY = 100000; static char const * const ALL_CONDITIONS[]; // N.B.: These need to match the order of ALL_CONDITIONS enum ConditionIndex { // Conditions on parent // N.B. Ancestor end/exit/invariant MUST come before // end/exit/invariant, respectively, because the former depend // on the latter and must be cleaned up first. ancestorExitIdx = 0, ancestorInvariantIdx, ancestorEndIdx, // User specified conditions skipIdx, startIdx, preIdx, exitIdx, invariantIdx, endIdx, postIdx, repeatIdx, // For all but Empty nodes actionCompleteIdx, // For all but Empty and Update nodes abortCompleteIdx, conditionIndexMax }; /** * @brief The constructor. * @param nodeId The name of this node. * @param parent The parent of this node (used for the ancestor conditions and variable lookup). */ NodeImpl(char const *nodeId, NodeImpl *parent = nullptr); /** * @brief Alternate constructor. Used only by Exec test module. */ NodeImpl(const std::string& type, const std::string& name, NodeState state, NodeImpl *parent = nullptr); virtual ~NodeImpl(); // // Listenable API // virtual bool isPropagationSource() const override { return true; } // Override Notifier method virtual bool isActive() const override { return true; } virtual void activate() override { } virtual void deactivate() override { } // // LinkedQueue API used by PlexilExec // virtual Node *next() const override { return static_cast<Node *>(m_next); } virtual Node **nextPtr() override { return static_cast<Node **>(&m_next); } // // NodeConnector API to expressions // virtual std::string const &getNodeId() const override { return m_nodeId; } /** * @brief Looks up a variable by name. * @param name Name of the variable. * @return The variable, or nullptr if not found. * @note Used only by XML parser. */ virtual Expression *findVariable(char const *name) override; // // ExpressionListener API // virtual void notifyChanged() override; // // Node API // // Make the node active. virtual void activateNode() override; //! Notify the node that something has changed. //! @param exec The PlexilExec instance. //! @note This is an optimization for cases where the change is //! the direct result of executive action. virtual void notifyChanged(PlexilExec *exec) override; /** * @brief Gets the destination state of this node, were it to transition, * based on the values of various conditions. * @return True if the new destination state is different from the last check, false otherwise. * @note Sets m_nextState, m_nextOutcome, m_nextFailureType as a side effect. */ virtual bool getDestState() override; /** * @brief Gets the previously calculated destination state of this node. * @return The destination state. */ virtual NodeState getNextState() const override { return (NodeState) m_nextState; } /** * @brief Commit a pending state transition based on the statuses of various conditions. * @param time The time of the transition. */ void transition(PlexilExec *exec, double time = 0.0) override; /** * @brief Get the priority of a node. * @return the priority of this node. */ virtual int32_t getPriority() const override { return m_priority; } /** * @brief Gets the current state of this node. * @return the current node state as a NodeState (enum) value. */ virtual NodeState getState() const override; /** * @brief Gets the outcome of this node. * @return the current outcome as an enum value. */ virtual NodeOutcome getOutcome() const override; /** * @brief Gets the failure type of this node. * @return the current failure type as an enum value. */ virtual FailureType getFailureType() const override; /** * @brief Accessor for an assignment node's assigned variable. * @note Default method, overridden by AssignmentNode. */ virtual Assignable *getAssignmentVariable() const override { return nullptr; } /** * @brief Gets the type of this node. * @return The type of this node. * @note Empty node method. */ virtual PlexilNodeType getType() const override { return NodeType_Empty; } /** * @brief Gets the parent of this node. */ virtual Node const *getParent() const override { return dynamic_cast<Node const *>(m_parent); } // // Resource conflict API // //! Does this node need to acquire resources before it can execute? //! @return true if resources must be acquired, false otherwise. virtual bool acquiresResources() const override; //! Reserve the resources needed by the node. //! On failure, add self to the resources' wait lists. //! @return true if successful, false if not. virtual bool tryResourceAcquisition() override; //! Remove the node from the pending queues of any resources //! it was trying to acquire. virtual void releaseResourceReservations() override; /** * @brief Notify that a resource on which we're pending is now available. */ virtual void notifyResourceAvailable() override; virtual QueueStatus getQueueStatus() const override { return m_queueStatus; } virtual void setQueueStatus(QueueStatus newval) override { m_queueStatus = newval; } virtual std::string toString(const unsigned int indent = 0) const override; virtual void print(std::ostream& stream, const unsigned int indent = 0) const override; // // Local to this class and derived classes // /** * @brief Set priority of a node. * @param prio The new priority. * @note Used by parser. */ void setPriority(int32_t prio) { m_priority = prio; } /** * @brief Accessor for the Node's parent. * @return This node's parent. */ NodeImpl *getParentNode() {return m_parent; } NodeImpl const *getParentNode() const {return m_parent; } //! Sets the state variable to the new state. //! @param exec The Exec to notify of the change. //! @param newValue The new node state. //! @param tym The time of transition. //! @note Virtual so it can be overridden by ListNode wrapper method. //! @note Only used by node implementation classes and unit tests. virtual void setState(PlexilExec *exec, NodeState newValue, double tym); // Used by unit tests void setNodeFailureType(FailureType f); /** * @brief Gets the time at which this node entered its current state. * @return Time value as a double. * @note Used by PlanDebugListener. */ double getCurrentStateStartTime() const; /** * @brief Gets the time at which this node entered the given state. * @param state The state. * @return Time value as a double. If not found, returns -DBL_MAX. * @note Used by PlanDebugListener. */ double getStateStartTime(NodeState state) const; /** * @brief Find the named variable in this node, ignoring its ancestors. * @param name Name of the variable. * @return The variable, or nullptr if not found. * @note Used only by XML parser. */ Expression *findLocalVariable(char const *name); virtual std::vector<NodeImplPtr> &getChildren(); virtual const std::vector<NodeImplPtr> &getChildren() const; virtual NodeImpl const *findChild(char const *childName) const; virtual NodeImpl *findChild(char const *childName); // // Utilities for plan parser and analyzer // // Pre-allocate local variable vector, variable map. void allocateVariables(size_t nVars); /** * @brief Add a named "variable" to the node, to be deleted with the node. * @param name The name * @param var The expression to associate with the name. * It will be deleted when the node is deleted. * @return true if successful, false if name is a duplicate */ bool addLocalVariable(char const *name, Expression *var); // Pre-allocate mutex vector. void allocateMutexes(size_t n); void allocateUsingMutexes(size_t n); // Add a mutex. void addMutex(Mutex *m); void addUsingMutex(Mutex *m); /** * @brief Looks up a mutex by name. Searches ancestors and globals. * @param name Name of the mutex. * @return The mutex, or nullptr if not found. */ Mutex *findMutex(char const *name) const; // May return nullptr. NodeVariableMap const *getVariableMap() const { return m_variablesByName.get(); } /** * @brief Add a condition expression to the node. * @param cname The name of the condition. * @param cond The expression. * @param isGarbage True if the expression should be deleted with the node. */ void addUserCondition(char const *cname, Expression *cond, bool isGarbage); /** * @brief Construct any internal conditions now that the node is complete. */ void finalizeConditions(); // Public only for plan analyzer static char const *getConditionName(size_t idx); /** * @brief Gets the state variable representing the state of this node. * @return the state variable. */ Expression *getStateVariable() { return &m_stateVariable; } Expression *getOutcomeVariable() { return &m_outcomeVariable; } Expression *getFailureTypeVariable() { return &m_failureTypeVariable; } // For use of plan parser. Expression *ensureTimepoint(NodeState st, bool isEnd); // May return nullptr. // Used by plan analyzer and plan parser module test only. const std::vector<ExpressionPtr> *getLocalVariables() const { return m_localVariables.get(); } // Condition accessors // These are public only to appease the module test // These conditions belong to the parent node. Expression *getAncestorEndCondition() { return getCondition(ancestorEndIdx); } Expression *getAncestorExitCondition() { return getCondition(ancestorExitIdx); } Expression *getAncestorInvariantCondition() { return getCondition(ancestorInvariantIdx); } // User conditions Expression *getSkipCondition() { return m_conditions[skipIdx]; } Expression *getStartCondition() { return m_conditions[startIdx]; } Expression *getEndCondition() { return m_conditions[endIdx]; } Expression *getExitCondition() { return m_conditions[exitIdx]; } Expression *getInvariantCondition() { return m_conditions[invariantIdx]; } Expression *getPreCondition() { return m_conditions[preIdx]; } Expression *getPostCondition() { return m_conditions[postIdx]; } Expression *getRepeatCondition() { return m_conditions[repeatIdx]; } // These are for specialized node types Expression *getActionCompleteCondition() { return m_conditions[actionCompleteIdx]; } Expression *getAbortCompleteCondition() { return m_conditions[abortCompleteIdx]; } // Abstracts out the issue of where the condition comes from. // Used internally, also by LuvListener. Non-const variant is protected. Expression const *getCondition(size_t idx) const; protected: friend class ListNode; Expression *getCondition(size_t idx); // Only used by Node, ListNode, LibraryCallNode. virtual NodeVariableMap const *getChildVariableMap() const; // *** Seems to be called only from NodeImpl constructor? void commonInit(); // Called from the transition handler void execute(PlexilExec *exec); void reset(); void deactivateExecutable(PlexilExec *exec); // Variables void activateLocalVariables(); void deactivateLocalVariables(); // Activate conditions // These are special because parent owns the condition expression void activateAncestorEndCondition(); void activateAncestorExitInvariantConditions(); // User conditions void activatePreSkipStartConditions(); void activateEndCondition(); void activateExitCondition(); void activateInvariantCondition(); void activatePostCondition(); void activateRepeatCondition(); // These are for specialized node types void activateActionCompleteCondition(); void activateAbortCompleteCondition(); // Deactivate a condition // These are special because parent owns the condition expression void deactivateAncestorEndCondition(); void deactivateAncestorExitInvariantConditions(); // User conditions void deactivatePreSkipStartConditions(); void deactivateEndCondition(); void deactivateExitCondition(); void deactivateInvariantCondition(); void deactivatePostCondition(); void deactivateRepeatCondition(); // These are for specialized node types void deactivateActionCompleteCondition(); void deactivateAbortCompleteCondition(); // Specific behaviors for derived classes virtual void specializedCreateConditionWrappers(); virtual void specializedActivate(); virtual void specializedHandleExecution(PlexilExec *exec); virtual void specializedDeactivateExecutable(PlexilExec *exec); // // State transition implementation methods // // Non-virtual member functions are common to all node types. // Virtual members are specialized by node type. // // getDestStateFrom... // Return true if the new destination state is different from the last check, false otherwise. // Set m_nextState, m_nextOutcome, m_nextFailureType as a side effect. bool getDestStateFromInactive(); bool getDestStateFromWaiting(); virtual bool getDestStateFromExecuting(); virtual bool getDestStateFromFinishing(); bool getDestStateFromFinished(); virtual bool getDestStateFromFailing(); bool getDestStateFromIterationEnded(); // // Transition out of the named current state. void transitionFromInactive(); void transitionFromWaiting(); virtual void transitionFromExecuting(PlexilExec *exec); virtual void transitionFromFinishing(PlexilExec *exec); void transitionFromFinished(); virtual void transitionFromFailing(PlexilExec *exec); void transitionFromIterationEnded(); void transitionToInactive(); void transitionToWaiting(); virtual void transitionToExecuting(); virtual void transitionToFinishing(); virtual void transitionToFinished(); virtual void transitionToFailing(PlexilExec *exec); virtual void transitionToIterationEnded(); // Phases of destructor // Not useful if called from base class destructor! virtual void cleanUpConditions(); void cleanUpVars(); virtual void cleanUpNodeBody(); // Printing utility virtual void printCommandHandle(std::ostream& stream, const unsigned int indent) const; // // Common state // Node *m_next; /*!< For LinkedQueue<Node> */ QueueStatus m_queueStatus; /*!< Which exec queue the node is in, if any. */ NodeState m_state; /*!< The current state of the node. */ NodeOutcome m_outcome; /*!< The current outcome. */ FailureType m_failureType; /*!< The current failure. */ bool m_pad; // to ensure 8 byte alignment NodeState m_nextState; /*!< The state returned by getDestState() the last time checkConditions() was called. */ NodeOutcome m_nextOutcome; /*!< The pending outcome. */ FailureType m_nextFailureType; /*!< The pending failure. */ NodeImpl *m_parent; /*!< The parent of this node.*/ Expression *m_conditions[conditionIndexMax]; /*!< The condition expressions. */ std::unique_ptr<std::vector<ExpressionPtr>> m_localVariables; /*!< Variables created in this node. */ std::unique_ptr<std::vector<MutexPtr>> m_localMutexes; /*!< Mutexes created in this node. */ std::unique_ptr<std::vector<Mutex *>> m_usingMutexes; /*!< Mutexes to be acquired by this node. */ StateVariable m_stateVariable; OutcomeVariable m_outcomeVariable; FailureVariable m_failureTypeVariable; NodeVariableMapPtr m_variablesByName; /*!< Locally declared variables or references to variables gotten through an interface. */ std::string m_nodeId; /*!< the NodeId from the xml.*/ int32_t m_priority; private: // Node transition history trace double m_currentStateStartTime; NodeTimepointValuePtr m_timepoints; protected: // Housekeeping details bool m_garbageConditions[conditionIndexMax]; /*!< Flags for conditions to delete. */ bool m_cleanedConditions, m_cleanedVars, m_cleanedBody; private: void createConditionWrappers(); // These should only be called from transition(). void setNodeOutcome(NodeOutcome o); void transitionFrom(PlexilExec *exec); void transitionTo(PlexilExec *exec, double tym); void logTransition(double time, NodeState newState); // // Internal versions // void printVariables(std::ostream& stream, const unsigned int indent = 0) const; void printMutexes(std::ostream& stream, const unsigned int indent = 0) const; }; } #endif // NODE_IMPL_HH
33.574163
132
0.663294
bdc49488d0957d4292661a5c6aba0fad298a3a78
8,344
cpp
C++
Project/Source/Components/UI/ComponentText.cpp
TBD-org/TBD-Engine
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
[ "MIT" ]
7
2021-04-26T21:32:12.000Z
2022-02-14T13:48:53.000Z
Project/Source/Components/UI/ComponentText.cpp
TBD-org/RealBugEngine
0131fde0abc2d86137500acd6f63ed8f0fc2835f
[ "MIT" ]
66
2021-04-24T10:08:07.000Z
2021-10-05T16:52:56.000Z
Project/Source/Components/UI/ComponentText.cpp
TBD-org/TBD-Engine
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
[ "MIT" ]
1
2021-07-13T21:26:13.000Z
2021-07-13T21:26:13.000Z
#include "ComponentText.h" #include "Application.h" #include "GameObject.h" #include "Modules/ModulePrograms.h" #include "Modules/ModuleCamera.h" #include "Modules/ModuleRender.h" #include "Modules/ModuleUserInterface.h" #include "Modules/ModuleResources.h" #include "Modules/ModuleEditor.h" #include "ComponentTransform2D.h" #include "Resources/ResourceTexture.h" #include "Resources/ResourceFont.h" #include "FileSystem/JsonValue.h" #include "Utils/ImGuiUtils.h" #include "GL/glew.h" #include "Math/TransformOps.h" #include "imgui_stdlib.h" #include "Utils/Leaks.h" #define JSON_TAG_TEXT_FONTID "FontID" #define JSON_TAG_TEXT_FONTSIZE "FontSize" #define JSON_TAG_TEXT_LINEHEIGHT "LineHeight" #define JSON_TAG_TEXT_LETTER_SPACING "LetterSpacing" #define JSON_TAG_TEXT_VALUE "Value" #define JSON_TAG_TEXT_ALIGNMENT "Alignment" #define JSON_TAG_COLOR "Color" ComponentText::~ComponentText() { App->resources->DecreaseReferenceCount(fontID); glDeleteVertexArrays(1, &vao); glDeleteBuffers(1, &vbo); } void ComponentText::Init() { App->resources->IncreaseReferenceCount(fontID); glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); Invalidate(); } void ComponentText::OnEditorUpdate() { if (ImGui::Checkbox("Active", &active)) { if (GetOwner().IsActive()) { if (active) { Enable(); } else { Disable(); } } } ImGui::Separator(); ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput; bool mustRecalculateVertices = false; if (ImGui::InputTextMultiline("Text input", &text, ImVec2(0.0f, ImGui::GetTextLineHeight() * 8), flags)) { SetText(text); } UID oldFontID = fontID; ImGui::ResourceSlot<ResourceFont>("Font", &fontID); if (oldFontID != fontID) { mustRecalculateVertices = true; } if (ImGui::DragFloat("Font Size", &fontSize, 2.0f, 0.0f, FLT_MAX)) { mustRecalculateVertices = true; } if (ImGui::DragFloat("Line height", &lineHeight, 2.0f, -FLT_MAX, FLT_MAX)) { mustRecalculateVertices = true; } if (ImGui::DragFloat("Letter spacing", &letterSpacing, 0.1f, -FLT_MAX, FLT_MAX)) { mustRecalculateVertices = true; } mustRecalculateVertices |= ImGui::RadioButton("Left", &textAlignment, 0); ImGui::SameLine(); mustRecalculateVertices |= ImGui::RadioButton("Center", &textAlignment, 1); ImGui::SameLine(); mustRecalculateVertices |= ImGui::RadioButton("Right", &textAlignment, 2); ImGui::ColorEdit4("Color##", color.ptr()); if (mustRecalculateVertices) { Invalidate(); } } void ComponentText::Save(JsonValue jComponent) const { jComponent[JSON_TAG_TEXT_FONTID] = fontID; jComponent[JSON_TAG_TEXT_FONTSIZE] = fontSize; jComponent[JSON_TAG_TEXT_LINEHEIGHT] = lineHeight; jComponent[JSON_TAG_TEXT_LETTER_SPACING] = letterSpacing; jComponent[JSON_TAG_TEXT_ALIGNMENT] = textAlignment; jComponent[JSON_TAG_TEXT_VALUE] = text.c_str(); JsonValue jColor = jComponent[JSON_TAG_COLOR]; jColor[0] = color.x; jColor[1] = color.y; jColor[2] = color.z; jColor[3] = color.w; } void ComponentText::Load(JsonValue jComponent) { fontID = jComponent[JSON_TAG_TEXT_FONTID]; fontSize = jComponent[JSON_TAG_TEXT_FONTSIZE]; lineHeight = jComponent[JSON_TAG_TEXT_LINEHEIGHT]; letterSpacing = jComponent[JSON_TAG_TEXT_LETTER_SPACING]; textAlignment = jComponent[JSON_TAG_TEXT_ALIGNMENT]; text = jComponent[JSON_TAG_TEXT_VALUE]; JsonValue jColor = jComponent[JSON_TAG_COLOR]; color.Set(jColor[0], jColor[1], jColor[2], jColor[3]); } void ComponentText::Draw(ComponentTransform2D* transform) { if (fontID == 0) { return; } ProgramTextUI* textUIProgram = App->programs->textUI; if (textUIProgram == nullptr) return; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glActiveTexture(GL_TEXTURE0); glBindVertexArray(vao); glUseProgram(textUIProgram->program); float4x4 model = transform->GetGlobalMatrix(); float4x4& proj = App->camera->GetProjectionMatrix(); float4x4& view = App->camera->GetViewMatrix(); if (App->userInterface->IsUsing2D()) { proj = float4x4::D3DOrthoProjLH(-1, 1, App->renderer->GetViewportSize().x, App->renderer->GetViewportSize().y); //near plane. far plane, screen width, screen height view = float4x4::identity; } ComponentCanvasRenderer* canvasRenderer = GetOwner().GetComponent<ComponentCanvasRenderer>(); if (canvasRenderer != nullptr) { float factor = canvasRenderer->GetCanvasScreenFactor(); view = view * float4x4::Scale(factor, factor, factor); } glUniformMatrix4fv(textUIProgram->viewLocation, 1, GL_TRUE, view.ptr()); glUniformMatrix4fv(textUIProgram->projLocation, 1, GL_TRUE, proj.ptr()); glUniformMatrix4fv(textUIProgram->modelLocation, 1, GL_TRUE, model.ptr()); glUniform4fv(textUIProgram->textColorLocation, 1, color.ptr()); RecalculateVertices(); for (size_t i = 0; i < text.size(); ++i) { if (text.at(i) != '\n') { Character character = App->userInterface->GetCharacter(fontID, text.at(i)); // render glyph texture over quad glBindTexture(GL_TEXTURE_2D, character.textureID); // update content of VBO memory glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(verticesText[i]), &verticesText[i].front()); glBindBuffer(GL_ARRAY_BUFFER, 0); // render quad glDrawArrays(GL_TRIANGLES, 0, 6); } } glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_BLEND); } void ComponentText::SetText(const std::string& newText) { text = newText; Invalidate(); } void ComponentText::SetFontSize(float newfontSize) { fontSize = newfontSize; Invalidate(); } void ComponentText::SetFontColor(const float4& newColor) { color = newColor; } float4 ComponentText::GetFontColor() const { return color; } void ComponentText::RecalculateVertices() { if (!dirty) { return; } if (fontID == 0) { return; } verticesText.resize(text.size()); ComponentTransform2D* transform = GetOwner().GetComponent<ComponentTransform2D>(); float x = -transform->GetSize().x * 0.5f; float y = 0; float dy = 0; // additional y shifting int j = 0; // index of row // FontSize / size of imported font. 48 is due to FontImporter default PixelSize float scale = (fontSize / 48); for (size_t i = 0; i < text.size(); ++i) { Character character = App->userInterface->GetCharacter(fontID, text.at(i)); float xpos = x + character.bearing.x * scale; float ypos = y - (character.size.y - character.bearing.y) * scale; float w = character.size.x * scale; float h = character.size.y * scale; switch (textAlignment) { case TextAlignment::LEFT: { // Default branch, could be deleted break; } case TextAlignment::CENTER: { xpos += (transform->GetSize().x - SubstringWidth(&text.c_str()[j], scale)) * 0.5f; break; } case TextAlignment::RIGHT: { xpos += transform->GetSize().x - SubstringWidth(&text.c_str()[j], scale); break; } } if (text.at(i) == '\n') { dy += lineHeight; // shifts to next line x = -transform->GetSize().x * 0.5f; // reset to initial position j = i + 1; // updated j variable in order to get the substringwidth of the following line in the next iteration } // clang-format off verticesText[i] = { xpos, ypos + h - dy, 0.0f, 0.0f, xpos, ypos - dy, 0.0f, 1.0f, xpos + w, ypos - dy, 1.0f, 1.0f, xpos, ypos + h - dy, 0.0f, 0.0f, xpos + w, ypos - dy, 1.0f, 1.0f, xpos + w, ypos + h - dy, 1.0f, 0.0f }; // clang-format on // now advance cursors for next glyph (note that advance is number of 1/64 pixels) if (text.at(i) != '\n') { x += ((character.advance >> 6) + letterSpacing) * scale; // bitshift by 6 to get value in pixels (2^6 = 64). Divides / 64 } } dirty = false; } void ComponentText::Invalidate() { dirty = true; } float ComponentText::SubstringWidth(const char* substring, float scale) { float subWidth = 0.f; for (int i = 0; substring[i] != '\0' && substring[i] != '\n'; ++i) { Character c = App->userInterface->GetCharacter(fontID, substring[i]); subWidth += ((c.advance >> 6) + letterSpacing) * scale; } subWidth -= letterSpacing * scale; return subWidth; }
28.094276
166
0.71081
bdca10dd283e3e72c5305613605227c50d78bb0f
1,062
cpp
C++
proj4/PongGame.cpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
proj4/PongGame.cpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
proj4/PongGame.cpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
// Our Pong Game #include <Game.hpp> #include <Vector2d.hpp> #include <Keyboard.hpp> #include <Color.hpp> #include "PongGame.h" #include "Ball.h" #include "Wall.h" using namespace vmi; // Create the game window PongGame::PongGame() : Game("Pong-ish", 640, 480), done(false) { // create the ball ball = new Ball(); // create the walls topWall = new Wall(Vector2d(0, 0), Vector2d(639, 1), Vector2d(0, 1)); bottomWall = new Wall(Vector2d(0, 478), Vector2d(639, 479), Vector2d(0, -1)); leftWall = new Wall(Vector2d(0, 1), Vector2d(1, 478), Vector2d(1, 0)); rightWall = new Wall(Vector2d(638, 1), Vector2d(639, 478), Vector2d(-1, 0)); // serve the ball ball->serve(Vector2d(100, 240), Vector2d(1, 0)); } PongGame::~PongGame() { delete ball; delete topWall; delete bottomWall; delete leftWall; delete rightWall; } // Per-frame update for game play void PongGame::update(double dt) { // intentionally blank } // Whether or not the game is over bool PongGame::isOver() const { return done; }
20.423077
79
0.645951
bdcc523c3973e8d9b3dd26d7cda0166aebdf59de
417
cpp
C++
sesion1/ejercicio_voltaje.cpp
dmateos-ugr/FP
6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e
[ "MIT" ]
1
2018-12-11T09:32:59.000Z
2018-12-11T09:32:59.000Z
sesion1/ejercicio_voltaje.cpp
dmateos-ugr/FP
6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e
[ "MIT" ]
null
null
null
sesion1/ejercicio_voltaje.cpp
dmateos-ugr/FP
6d3ec8eeccbb72582367c8cf97aecb2227cc7b9e
[ "MIT" ]
2
2018-11-13T12:32:35.000Z
2018-11-27T14:43:30.000Z
#include <iostream> using namespace std; int main(){ double intensidad; double resistencia; double voltaje; cout << "Introduzca el valor de la intensidad: "; cin >> intensidad; cout << "Introduzca el valor de la resistencia: "; cin >> resistencia; voltaje = resistencia*intensidad; cout << "El valor del voltaje resultante es " << voltaje << endl; return 0; }
20.85
69
0.628297
bdcec3aaad76d1523d63fd83248ea117a1eb3687
510
cc
C++
src/windows/BluetoothHelpers.cc
hojin-jeong/node-bluetooth-serial
a04a175e0faaa8961ee051389fd072f1901253ff
[ "BSD-2-Clause" ]
null
null
null
src/windows/BluetoothHelpers.cc
hojin-jeong/node-bluetooth-serial
a04a175e0faaa8961ee051389fd072f1901253ff
[ "BSD-2-Clause" ]
null
null
null
src/windows/BluetoothHelpers.cc
hojin-jeong/node-bluetooth-serial
a04a175e0faaa8961ee051389fd072f1901253ff
[ "BSD-2-Clause" ]
null
null
null
#include "BluetoothHelpers.h" bool BluetoothHelpers::Initialize() { WSADATA data; int startupError = WSAStartup(MAKEWORD(2, 2), &data); bool initializationSuccess = startupError == 0; if (initializationSuccess) { initializationSuccess = LOBYTE(data.wVersion) == 2 && HIBYTE(data.wVersion) == 2; if (!initializationSuccess) { BluetoothHelpers::Finalize(); } } return initializationSuccess; } void BluetoothHelpers::Finalize() { WSACleanup(); }
25.5
89
0.658824
bdd2332404ec0f7842784cdfe9c22d1b54510d48
8,558
hpp
C++
MadgwickFilter/Quaternion/Quaternion.hpp
calm0815/robotrack
c3aedfa1d76173fe2729972d5a94ebb3bd84e3a1
[ "MIT" ]
3
2018-11-03T15:58:49.000Z
2019-04-11T22:46:32.000Z
MadgwickFilter/Quaternion/Quaternion.hpp
calm0815/robotrack
c3aedfa1d76173fe2729972d5a94ebb3bd84e3a1
[ "MIT" ]
null
null
null
MadgwickFilter/Quaternion/Quaternion.hpp
calm0815/robotrack
c3aedfa1d76173fe2729972d5a94ebb3bd84e3a1
[ "MIT" ]
null
null
null
#ifndef _QUATERNION_HPP_ #define _QUATERNION_HPP_ #include "Vector3/Vector3.hpp" /** * クォータニオンの足し,引き,掛け算などを簡単にできるようになります. * @author Gaku MATSUMOTO * @bref クォータニオンを使えるクラスです. */ class Quaternion{ public: /** @bref Quaternionインスタンスを生成します */ Quaternion(){ w = 1.0f; x = 0.0f; y = 0.0f; z = 0.0f; }; /** * @bref Vector3クラスからクォータニオンを作ります */ Quaternion(Vector3 vector){ Set(vector); } /** * @bref クォータニオンを回転軸と回転角度によって初期化します。 * @param vec 回転軸となる3次元ベクトル * @param angle 回転角 [rad] */ Quaternion(Vector3 vec, float angle){ Set(vec, angle); } /** @bref 要素を代入しながら,インスタンスを生成します. @param[in] _w 実部wの初期値 @param[in] _x 虚部iの初期値 @param[in] _y 虚部jの初期値 @param[in] _z 虚部kの初期値 */ Quaternion(float _w, float _x, float _y, float _z){ w = _w; x = _x; y = _y; z = _z; }; public: float w; float x; float y; float z; public: /** @bref クォータニオンの要素をコピーします. @note 通常の数のように代入できます */ Quaternion operator=(Quaternion r){ w = r.w; x = r.x; y = r.y; z = r.z; return *this; }; /** @bref クォータニオンを足して代入します. @note 通常の数のように代入できます */ Quaternion operator+=(Quaternion r){ w += r.w; x += r.x; y += r.y; z += r.z; return *this; }; /** @bref クォータニオンを引いて代入します. @note 通常の数のように代入できます */ Quaternion operator-=(Quaternion r){ w -= r.w; x -= r.x; y -= r.y; z -= r.z; return *this; }; /** * @bref クォータニオンの掛け算をします. * @note この際も順序は重要です. */ Quaternion operator*=(Quaternion r){ static Quaternion QQ; QQ.w = w*r.w - x*r.x - y*r.y - z*r.z; QQ.x = x*r.w + w*r.x - z*r.y + y*r.z; QQ.y = y*r.w + z*r.x + w*r.y - x*r.z; QQ.z = z*r.w - y*r.x + x*r.y + w*r.z; w = QQ.w; x = QQ.x; y = QQ.y; z = QQ.z; return *this; }; /** @bref クォータニオンの複素共役を返します. @note 本当はアスタリスクが良かったのですが,ポインタと紛らわしいのでマイナスにしました. */ Quaternion operator-(){ Quaternion Q; Q.w = w; Q.x = -x; Q.y = -y; Q.z = -z; return Q; }; /** @bref クォータニオンを正規化して,単位クォータニオンにします. @note 掛け算などを行うたびに実行することをお勧めします. @note ただ、クォータニオンの時間微分は正規化してはいけません */ void Normalize(){ float norm = sqrt(w*w + x*x + y*y + z*z); if (norm != 0.0f){ w /= norm; x /= norm; y /= norm; z /= norm; return; } else{ return; } }; /** * @bref クォータニオンを初期化します */ template <typename T> void Set(T _w, T _x, T _y, T _z); /** * @bref クォータニオンをVector3クラスで初期化します。 */ void Set(Vector3 vec); /** * @bref クォータニオンを回転軸と回転角度によって初期化します。 * param vec 回転軸となる3次元ベクトル * param angle 回転角 [rad] */ void Set(Vector3 vec, float angle){ vec.Normalize(); float halfAngle = 0.5f * angle ; w = cosf(halfAngle); x = vec.x * sinf(halfAngle); y = vec.y * sinf(halfAngle); z = vec.z * sinf(halfAngle); } /** * @bref クォータニオンの各要素に配列のようにアクセスします */ float q(int i){ float ans = 0.0; switch (i){ case 1: ans = w; break; case 2: ans = x; break; case 3: ans = y; break; case 4: ans = z; break; } return ans; } /** * @bref クォータニオンのノルムを計算します */ float Norm(){ return fabsf(w*w + x*x + y*y + z*z); } /** クォータニオンとクォータニオンを比較して等しければtrue 等しくなければfalse*/ bool operator==(Quaternion Q){ if (w == Q.w && x == Q.x && y == Q.y && z == Q.z){ return true; } return false; } /** クォータニオンとクォータニオンを比較して等しくなければtrue 等しければfalse*/ bool operator!=(Quaternion Q){ if (w == Q.w && x == Q.x && y == Q.y && z == Q.z){ return false; } return true; } /** * @bref 2つの3次元ベクトルを一致させるクォータニオンを計算 * @param from 始点となるベクトルのインスタンス * @param to 終点となるベクトルのインスタンス */ void FromToRotation(Vector3 from, Vector3 to); /** @bref オイラー角で姿勢を取得します. @param val ロール,ピッチ,ヨーの順に配列に格納します.3つ以上の要素の配列を入れてください. @note 値は[rad]です.[degree]に変換が必要な場合は別途計算して下さい. */ void GetEulerAngle(float *val){ float q0q0 = w * w, q1q1q2q2 = x * x - y * y, q3q3 = z * z; val[0] = (atan2f(2.0f * (w * x + y * z), q0q0 - q1q1q2q2 + q3q3)); val[1] = (-asinf(2.0f * (x * z - w * y))); val[2] = (atan2f(2.0f * (x * y + w * z), q0q0 + q1q1q2q2 - q3q3)); } /** @bref オイラー角で姿勢を取得します. @param val ロール,ピッチ,ヨーの順に配列に格納します.3つ以上の要素の配列を入れてください. @note 値は[rad]です.[degree]に変換が必要な場合は別途計算して下さい. */ void GetEulerAngle(Vector3 *v) { float q0q0 = w * w, q1q1q2q2 = x * x - y * y, q3q3 = z * z; v->x = (atan2f(2.0f * (w * x + y * z), q0q0 - q1q1q2q2 + q3q3)); v->y = (-asinf(2.0f * (x * z - w * y))); v->z = (atan2f(2.0f * (x * y + w * z), q0q0 + q1q1q2q2 - q3q3)); } /** * @bref クォータニオンをVector3クラスに変換します * @note クォータニオンのx,y,z成分を持ったベクトルを作ります */ Vector3 ToVector3(){ Vector3 vec3(x, y, z); return vec3; } /** * @bref 3次元ベクトルを回転します * @param v 回転させたい3次元ベクトルのポインタ * @note 余計なオブジェクトを作りません */ void Rotation(Vector3* v) { if (v == NULL) return; static float ww = 0.0f; static float xx = 0.0f; static float yy = 0.0f; static float zz = 0.0f; static float vx = 0.0f, vy = 0.0f, vz = 0.0f; static float _wx, _wy, _wz, _xy, _zx, _yz; ww = w * w; xx = x * x; yy = y * y; zz = z * z; _wx = w * x; _wy = w * y; _wz = w * z; _xy = x * y; _zx = z * x; _yz = y * z; vx = (ww + xx - yy - zz) * v->x + 2.0f*(_xy - _wz)*v->y + 2.0f*(_zx + _wy) * v->z; vy = 2.0f * (_xy + _wz) * v->x + (ww - xx + yy - zz) * v->y + 2.0f*(_yz - _wx)*v->z; vz = 2.0f * (_zx - _wy) * v->x + 2.0f * (_wx + _yz)*v->y + (ww - xx - yy + zz)*v->z; v->x = vx; v->y = vy; v->z = vz; } /** * @bref 3次元ベクトルを回転します.ただし逆回転です * @param v 回転させたい3次元ベクトルのポインタ * @note 余計なオブジェクトを作りません */ void InvRotation(Vector3* v) { if (v == NULL) return; static float ww = 0.0f; static float xx = 0.0f; static float yy = 0.0f; static float zz = 0.0f; static float vx = 0.0f, vy = 0.0f, vz = 0.0f; static float _wx, _wy, _wz, _xy, _xz, _yz; ww = w * w; xx = x * x; yy = y * y; zz = z * z; _wx = w * x; _wy = w * y; _wz = w * z; _xy = x * y; _xz = x * z; _yz = y * z; vx = (ww + xx - yy - zz) * v->x + 2.0f*(_xy + _wz)*v->y + 2.0f*(_xz - _wy) * v->z; vy = 2.0f * (_xy - _wz) * v->x + (ww - xx + yy - zz) * v->y + 2.0f*(_yz + _wx)*v->z; vz = 2.0f * (_xz + _wy) * v->x + 2.0f * (-_wx + _yz)*v->y + (ww - xx - yy + zz)*v->z; v->x = vx; v->y = vy; v->z = vz; } }; void Quaternion::FromToRotation(Vector3 from, Vector3 to){ float halfTheta = 0.5f * from.Angle(to);//回転角度 0からpi/2 Vector3 axis = from * to; axis.Normalize(); w = cos(halfTheta); x = axis.x * sin(halfTheta); y = axis.y * sin(halfTheta); z = axis.z * sin(halfTheta); } template<typename T>void Quaternion::Set(T _w, T _x, T _y, T _z){ w = _w; x = _x; y = _y; z = _z; return; } void Quaternion::Set(Vector3 vec){ w = 0.0; x = vec.x; y = vec.y; z = vec.z; return; } /** * @fn Quaternion operator*(Quaternion l, Quaternion r) * @bref クォータニオンの掛け算をします.この際,順序が重要です. */ Quaternion operator*(Quaternion l, Quaternion r){ static Quaternion Q; Q.w = l.w*r.w - l.x*r.x - l.y*r.y - l.z*r.z; Q.x = l.x*r.w + l.w*r.x - l.z*r.y + l.y*r.z; Q.y = l.y*r.w + l.z*r.x + l.w*r.y - l.x*r.z; Q.z = l.z*r.w - l.y*r.x + l.x*r.y + l.w*r.z; return Q; }; /** * @fn Quaternion operator*(double s, Quaternion q) * @bref クォータニオンをスカラー倍します. */ Quaternion operator*(float s, Quaternion q){ static Quaternion Q; Q.w = q.w * s; Q.x = q.x * s; Q.y = q.y * s; Q.z = q.z * s; return Q; }; /** * @fn Quaternion operator*(Quaternion q, double s) * @bref クォータニオンをスカラー倍します. */ Quaternion operator*(Quaternion q, float s){ static Quaternion Q; Q.w = q.w * s; Q.x = q.x * s; Q.y = q.y * s; Q.z = q.z * s; return Q; }; /** */ Vector3 operator*(Quaternion q, Vector3 v) { static Vector3 ans; static float ww = 0.0f; static float xx = 0.0f; static float yy = 0.0f; static float zz = 0.0f; //static float vx = 0.0f, vy = 0.0f, vz = 0.0f; static float _wx, _wy, _wz, _xy, _zx, _yz; ww = q.w * q.w; xx = q.x * q.x; yy = q.y * q.y; zz = q.z * q.z; _wx = q.w * q.x; _wy = q.w * q.y; _wz = q.w * q.z; _xy = q.x * q.y; _zx = q.z * q.x; _yz = q.y * q.z; ans.x = (ww + xx - yy - zz) * v.x + 2.0f*(_xy - _wz)*v.y + 2.0f*(_zx + _wy) * v.z; ans.y = 2.0f * (_xy + _wz) * v.x + (ww - xx + yy - zz) * v.y + 2.0f*(_yz - _wx)*v.z; ans.z = 2.0f * (_zx - _wy) * v.x + 2.0f * (_wx + _yz)*v.y + (ww - xx - yy + zz)*v.z; return ans; } /** @bref クォータニオンの足し算をします. */ Quaternion operator+(Quaternion l, Quaternion r){ static Quaternion Q; Q.w = l.w + r.w; Q.x = l.x + r.x; Q.y = l.y + r.y; Q.z = l.z + r.z; return Q; } /** @bref クォータニオンの引き算をします. */ Quaternion operator-(Quaternion l, Quaternion r){ static Quaternion Q; Q.w = l.w - r.w; Q.x = l.x - r.x; Q.y = l.y - r.y; Q.z = l.z - r.z; return Q; } #endif
19.102679
87
0.550946
bdd3fc610582165f95b2ec03d5b299e7b69beedb
12,575
cc
C++
EventFilter/CSCTFRawToDigi/plugins/CSCTFUnpacker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
EventFilter/CSCTFRawToDigi/plugins/CSCTFUnpacker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
EventFilter/CSCTFRawToDigi/plugins/CSCTFUnpacker.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "EventFilter/CSCTFRawToDigi/interface/CSCTFUnpacker.h" //Framework stuff #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" //Digi #include "DataFormats/CSCDigi/interface/CSCCorrelatedLCTDigi.h" #include "DataFormats/L1CSCTrackFinder/interface/L1Track.h" #include "DataFormats/L1CSCTrackFinder/interface/L1CSCSPStatusDigi.h" #include "DataFormats/L1CSCTrackFinder/interface/TrackStub.h" //Digi collections #include "DataFormats/CSCDigi/interface/CSCCorrelatedLCTDigiCollection.h" #include "DataFormats/L1CSCTrackFinder/interface/L1CSCTrackCollection.h" #include "DataFormats/L1CSCTrackFinder/interface/L1CSCStatusDigiCollection.h" #include "DataFormats/L1CSCTrackFinder/interface/CSCTriggerContainer.h" //Unique key #include "DataFormats/MuonDetId/interface/CSCDetId.h" #include "DataFormats/MuonDetId/interface/DTChamberId.h" //Don't know what #include <EventFilter/CSCTFRawToDigi/interface/CSCTFMonitorInterface.h> #include "FWCore/ServiceRegistry/interface/Service.h" #include "CondFormats/CSCObjects/interface/CSCTriggerMappingFromFile.h" //#include <DataFormats/MuonDetId/interface/CSCTriggerNumbering.h> //#include <iostream> #include <sstream> CSCTFUnpacker::CSCTFUnpacker(const edm::ParameterSet& pset):edm::stream::EDProducer<>(),mapping(0){ LogDebug("CSCTFUnpacker|ctor")<<"Started ..."; // Edges of the time window, which LCTs are put into (unlike tracks, which are always centred around 0): m_minBX = pset.getParameter<int>("MinBX"); //3 m_maxBX = pset.getParameter<int>("MaxBX"); //9 // Swap: if(swapME1strips && me1b && !zplus) strip = 65 - strip; // 1-64 -> 64-1 : swapME1strips = pset.getParameter<bool>("swapME1strips"); // Initialize slot<->sector assignment slot2sector = pset.getParameter< std::vector<int> >("slot2sector"); LogDebug("CSCTFUnpacker|ctor")<<"Verifying slot<->sector map from 'vint32 slot2sector'"; for(int slot=0; slot<22; slot++) if( slot2sector[slot]<0 || slot2sector[slot]>12 ) throw cms::Exception("Invalid configuration")<<"CSCTFUnpacker: sector index is set out of range (slot2sector["<<slot<<"]="<<slot2sector[slot]<<", should be [0-12])"; // Just for safety (in case of bad data): slot2sector.resize(32); // As we use standard CSC digi containers, we have to initialize mapping: std::string mappingFile = pset.getParameter<std::string>("mappingFile"); if( mappingFile.length() ){ LogDebug("CSCTFUnpacker|ctor") << "Define ``mapping'' only if you want to screw up real geometry"; mapping = new CSCTriggerMappingFromFile(mappingFile); } else { LogDebug("CSCTFUnpacker|ctor") << "Generating default hw<->geometry mapping"; class M: public CSCTriggerSimpleMapping{ void fill(void) override{} }; mapping = new M(); for(int endcap=1; endcap<=2; endcap++) for(int station=1; station<=4; station++) for(int sector=1; sector<=6; sector++) for(int csc=1; csc<=9; csc++){ if( station==1 ){ mapping->addRecord(endcap,station,sector,1,csc,endcap,station,sector,1,csc); mapping->addRecord(endcap,station,sector,2,csc,endcap,station,sector,2,csc); } else mapping->addRecord(endcap,station,sector,0,csc,endcap,station,sector,0,csc); } } producer = pset.getParameter<edm::InputTag>("producer"); produces<CSCCorrelatedLCTDigiCollection>(); produces<L1CSCTrackCollection>(); produces<L1CSCStatusDigiCollection>(); produces<CSCTriggerContainer<csctf::TrackStub> >("DT"); Raw_token = consumes<FEDRawDataCollection>(producer); } CSCTFUnpacker::~CSCTFUnpacker(){ if( mapping ) delete mapping; } void CSCTFUnpacker::produce(edm::Event& e, const edm::EventSetup& c){ // Get a handle to the FED data collection edm::Handle<FEDRawDataCollection> rawdata; e.getByToken(Raw_token,rawdata); // create the collection of CSC wire and strip digis as well as of DT stubs, which we receive from DTTF auto LCTProduct = std::make_unique<CSCCorrelatedLCTDigiCollection>(); auto trackProduct = std::make_unique<L1CSCTrackCollection>(); auto statusProduct = std::make_unique<L1CSCStatusDigiCollection>(); auto dtProduct = std::make_unique<CSCTriggerContainer<csctf::TrackStub>>(); for(int fedid=FEDNumbering::MINCSCTFFEDID; fedid<=FEDNumbering::MAXCSCTFFEDID; fedid++){ const FEDRawData& fedData = rawdata->FEDData(fedid); if( fedData.size()==0 ) continue; //LogDebug("CSCTFUnpacker|produce"); //if( monitor ) monitor->process((unsigned short*)fedData.data()); unsigned int unpacking_status = tfEvent.unpack((unsigned short*)fedData.data(),fedData.size()/2); if( unpacking_status==0 ){ // There may be several SPs in event std::vector<const CSCSPEvent*> SPs = tfEvent.SPs_fast(); // Cycle over all of them for(std::vector<const CSCSPEvent *>::const_iterator spItr=SPs.begin(); spItr!=SPs.end(); spItr++){ const CSCSPEvent *sp = *spItr; L1CSCSPStatusDigi status; /// status.sp_slot = sp->header().slot(); status.l1a_bxn = sp->header().BXN(); status.fmm_status = sp->header().status(); status.track_cnt = sp->counters().track_counter(); status.orbit_cnt = sp->counters().orbit_counter(); // Finds central LCT BX // assumes window is odd number of bins int central_lct_bx = (m_maxBX + m_minBX)/2; // Find central SP BX // assumes window is odd number of bins int central_sp_bx = int(sp->header().nTBINs()/2); for(unsigned int tbin=0; tbin<sp->header().nTBINs(); tbin++){ status.se |= sp->record(tbin).SEs(); status.sm |= sp->record(tbin).SMs(); status.bx |= sp->record(tbin).BXs(); status.af |= sp->record(tbin).AFs(); status.vp |= sp->record(tbin).VPs(); for(unsigned int FPGA=0; FPGA<5; FPGA++) for(unsigned int MPClink=0; MPClink<3; ++MPClink){ std::vector<CSCSP_MEblock> lct = sp->record(tbin).LCT(FPGA,MPClink); if( lct.size()==0 ) continue; status.link_status[lct[0].spInput()] |= (1<<lct[0].receiver_status_frame1())| (1<<lct[0].receiver_status_frame2())| ((lct[0].aligment_fifo()?1:0)<<4); status.mpc_link_id |= (lct[0].link()<<2)|lct[0].mpc(); int station = ( FPGA ? FPGA : 1 ); int endcap=0, sector=0; if( slot2sector[sp->header().slot()] ){ endcap = slot2sector[sp->header().slot()]/7 + 1; sector = slot2sector[sp->header().slot()]; if( sector>6 ) sector -= 6; } else { endcap = (sp->header().endcap()?1:2); sector = sp->header().sector(); } int subsector = ( FPGA>1 ? 0 : FPGA+1 ); int cscid = lct[0].csc() ; try{ CSCDetId id = mapping->detId(endcap,station,sector,subsector,cscid,0); // corrlcts now have no layer associated with them LCTProduct->insertDigi(id, CSCCorrelatedLCTDigi( 0,lct[0].vp(),lct[0].quality(),lct[0].wireGroup(), (swapME1strips && cscid<=3 && station==1 && endcap==2 && lct[0].strip()<65 ? 65 - lct[0].strip() : lct[0].strip() ), lct[0].pattern(),lct[0].l_r(), (lct[0].tbin()+(central_lct_bx-central_sp_bx)), lct[0].link(), lct[0].BXN(), 0, cscid ) ); } catch(cms::Exception &e) { edm::LogInfo("CSCTFUnpacker|produce") << e.what() << "Not adding digi to collection in event " <<sp->header().L1A()<<" (endcap="<<endcap<<",station="<<station<<",sector="<<sector<<",subsector="<<subsector<<",cscid="<<cscid<<",spSlot="<<sp->header().slot()<<")"; } } std::vector<CSCSP_MBblock> mbStubs = sp->record(tbin).mbStubs(); for(std::vector<CSCSP_MBblock>::const_iterator iter=mbStubs.begin(); iter!=mbStubs.end(); iter++){ int endcap, sector; if( slot2sector[sp->header().slot()] ){ endcap = slot2sector[sp->header().slot()]/7 + 1; sector = slot2sector[sp->header().slot()]; if( sector>6 ) sector -= 6; } else { endcap = (sp->header().endcap()?1:2); sector = sp->header().sector(); } const unsigned int csc2dt[6][2] = {{2,3},{4,5},{6,7},{8,9},{10,11},{12,1}}; DTChamberId id((endcap==1?2:-2),1, csc2dt[sector-1][iter->id()-1]); CSCCorrelatedLCTDigi base(0,iter->vq(),iter->quality(),iter->cal(),iter->flag(),iter->bc0(),iter->phi_bend(),tbin+(central_lct_bx-central_sp_bx),iter->id(),iter->bxn(),iter->timingError(),iter->BXN()); csctf::TrackStub dtStub(base,id,iter->phi(),0); dtProduct->push_back(dtStub); } std::vector<CSCSP_SPblock> tracks = sp->record(tbin).tracks(); unsigned int trkNumber=0; for(std::vector<CSCSP_SPblock>::const_iterator iter=tracks.begin(); iter!=tracks.end(); iter++,trkNumber++){ L1CSCTrack track; if( slot2sector[sp->header().slot()] ){ track.first.m_endcap = slot2sector[sp->header().slot()]/7 + 1; track.first.m_sector = slot2sector[sp->header().slot()]; if( track.first.m_sector>6 ) track.first.m_sector -= 6; } else { track.first.m_endcap = (sp->header().endcap()?1:2); track.first.m_sector = sp->header().sector(); } track.first.m_lphi = iter->phi(); track.first.m_ptAddress = iter->ptLUTaddress(); track.first.m_fr = iter->f_r(); track.first.m_ptAddress|=(iter->f_r() << 21); track.first.setStationIds(iter->ME1_id(),iter->ME2_id(),iter->ME3_id(),iter->ME4_id(),iter->MB_id()); track.first.setTbins(iter->ME1_tbin(), iter->ME2_tbin(), iter->ME3_tbin(), iter->ME4_tbin(), iter->MB_tbin() ); track.first.setBx(iter->tbin()-central_sp_bx); track.first.setBits(iter->syncErr(), iter->bx0(), iter->bc0()); track.first.setLocalPhi(iter->phi()); track.first.setEtaPacked(iter->eta()); track.first.setChargePacked(iter->charge()); track.first.m_output_link = iter->id(); if( track.first.m_output_link ){ track.first.m_rank = (iter->f_r()?sp->record(tbin).ptSpy()&0x7F:(sp->record(tbin).ptSpy()&0x7F00)>>8); track.first.setChargeValidPacked((iter->f_r()?(sp->record(tbin).ptSpy()&0x80)>>8:(sp->record(tbin).ptSpy()&0x8000)>>15)); } else { track.first.m_rank = 0; track.first.setChargeValidPacked(0); } track.first.setFineHaloPacked(iter->halo()); track.first.m_winner = iter->MS_id()&(1<<trkNumber); std::vector<CSCSP_MEblock> lcts = iter->LCTs(); for(std::vector<CSCSP_MEblock>::const_iterator lct=lcts.begin(); lct!=lcts.end(); lct++){ int station = ( lct->spInput()>6 ? (lct->spInput()-1)/3 : 1 ); int subsector = ( lct->spInput()>6 ? 0 : (lct->spInput()-1)/3 + 1 ); try{ CSCDetId id = mapping->detId(track.first.m_endcap,station,track.first.m_sector,subsector,lct->csc(),0); track.second.insertDigi(id, CSCCorrelatedLCTDigi( 0,lct->vp(),lct->quality(),lct->wireGroup(), (swapME1strips && lct->csc()<=3 && station==1 && track.first.m_endcap==2 && lct[0].strip()<65 ? 65 - lct[0].strip() : lct[0].strip() ), lct->pattern(),lct->l_r(), (lct->tbin()+(central_lct_bx-central_sp_bx)), lct->link(), lct->BXN(), 0, lct->csc() ) ); } catch(cms::Exception &e) { edm::LogInfo("CSCTFUnpacker|produce") << e.what() << "Not adding track digi to collection in event" <<sp->header().L1A()<<" (endcap="<<track.first.m_endcap<<",station="<<station<<",sector="<<track.first.m_sector<<",subsector="<<subsector<<",cscid="<<lct->csc()<<",spSlot="<<sp->header().slot()<<")"; } } std::vector<CSCSP_MBblock> mbStubs = iter->dtStub(); for(std::vector<CSCSP_MBblock>::const_iterator iter=mbStubs.begin(); iter!=mbStubs.end(); iter++){ CSCDetId id = mapping->detId(track.first.m_endcap,1,track.first.m_sector,iter->id(),1,0); track.second.insertDigi(id, CSCCorrelatedLCTDigi(iter->phi(),iter->vq(),iter->quality()+100,iter->cal(),iter->flag(),iter->bc0(),iter->phi_bend(),tbin+(central_lct_bx-central_sp_bx),iter->id(),iter->bxn(),iter->timingError(),iter->BXN()) ); } trackProduct->push_back( track ); } } statusProduct->second.push_back( status ); } } else { edm::LogError("CSCTFUnpacker|produce")<<" problem of unpacking TF event: 0x"<<std::hex<<unpacking_status<<std::dec<<" code"; } statusProduct->first = unpacking_status; } //end of fed cycle e.put(std::move(dtProduct),"DT"); e.put(std::move(LCTProduct)); // put processed lcts into the event. e.put(std::move(trackProduct)); e.put(std::move(statusProduct)); }
44.910714
217
0.65169
bdd4533dbcf1e985c9bdb2b026299460f56eaf0f
1,545
cpp
C++
week2/Searching and Sorting/Search in a Rotated Array.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
9
2021-08-01T16:17:04.000Z
2022-01-22T19:51:18.000Z
week2/Searching and Sorting/Search in a Rotated Array.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
null
null
null
week2/Searching and Sorting/Search in a Rotated Array.cpp
rishabhrathore055/gfg-11-weeks-workshop-on-DSA
052039bfbe3ae261740fc73d50f32528ddd49e6a
[ "MIT" ]
1
2021-08-30T12:26:11.000Z
2021-08-30T12:26:11.000Z
#include<bits/stdc++.h> using namespace std; int Search(vector<int> , int); int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<int> v(n); for(int i=0;i<n;i++) cin>>v[i]; int target; cin>>target; cout<<Search(v,target)<<endl; } } int binary_search(vector<int>arr,int l , int h , int k) { if (h < l) return -1; int mid=(l+h)/2; if (k == arr[mid]) return mid; else if (k > arr[mid]) return binary_search(arr, (mid + 1), h, k); else return binary_search(arr, l, (mid - 1), k); } int findpivot(vector<int>arr, int low, int high) { if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid] > arr[mid + 1]) return mid; else if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); else if (arr[low] >= arr[mid]) return findpivot(arr, low, mid - 1); else return findpivot(arr, mid + 1, high); } int Search(vector<int>A, int target) { int n = A.size(); int pivot=findpivot(A,0,n-1); if(pivot==-1) { return binary_search(A,0,n-1,target); } if(A[pivot]==target) return pivot; else if(A[0]<=target) return binary_search(A,0,pivot-1,target); else return binary_search(A,pivot+1,n-1,target); }
22.071429
55
0.471845
bdd623ceed6f588f267e4b4bdf3f66365b2ca406
738
cc
C++
common/filesystem.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
common/filesystem.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
common/filesystem.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
// Normally we would #include drake/common/filesystem.h prior to this header // ("include yourself first"), but we can't do that given the way the ghc // library implements separate compilation. So, we have to NOLINT it below. // Keep this sequence in sync with drake/common/filesystem.h. #if __has_include(<filesystem>) && !defined(__APPLE__) // No compilation required for std::filesystem. #else // Compile ghc::filesystem into object code. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated" #pragma GCC diagnostic ignored "-Wold-style-cast" #define GHC_FILESYSTEM_IMPLEMENTATION #include "ghc/filesystem.hpp" // NOLINT(build/include) #undef GHC_FILESYSTEM_IMPLEMENTATION #pragma GCC diagnostic pop #endif
33.545455
76
0.775068
752a2a1c33f360e89df42e5b02fece2122c6b95c
26,965
cpp
C++
src/state_manager.cpp
cognicept-admin/rosrect_listener_Agent
d1fdc435e28d413379f6e7dd98fca4e72cf853f1
[ "BSD-3-Clause" ]
6
2020-05-07T14:26:23.000Z
2021-05-03T01:02:35.000Z
src/state_manager.cpp
cognicept-admin/error_resolution_diagnoser
6666b0597904a005ef90d0d82463544c88e6068c
[ "BSD-3-Clause" ]
1
2020-05-18T04:41:00.000Z
2020-06-04T07:03:17.000Z
src/state_manager.cpp
cognicept-admin/error_resolution_diagnoser
6666b0597904a005ef90d0d82463544c88e6068c
[ "BSD-3-Clause" ]
3
2020-09-23T03:54:39.000Z
2021-09-29T12:10:07.000Z
#include <error_resolution_diagnoser/state_manager.h> using namespace web::json; // JSON features using namespace web; // Common features like URIs. StateManager::StateManager() { // Boolean flag to decide whether to suppress a message or not this->suppress_flag = false; // Timeout parameter in minutes for alert timeout this->alert_timeout_limit = 5.0; } std::vector<std::string> StateManager::does_exist(std::string robot_code, std::string msg_text) { // Find if msg is already recorded for the given robot code std::vector<std::vector<std::string>>::const_iterator row; for (row = this->msg_data.begin(); row != this->msg_data.end(); row++) { if ((find(row->begin(), row->end(), msg_text) != row->end()) && (find(row->begin(), row->end(), robot_code) != row->end())) return *(row); } std::vector<std::string> emptyString; emptyString.push_back(""); return emptyString; } void StateManager::check_message(std::string agent_type, std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { if (agent_type == "ECS") { // std::cout << "Checking with ECS..." << std::endl; this->check_message_ecs(robot_code, data, telemetry); } else if ((agent_type == "ERT") || (agent_type == "DB")) { // std::cout << "Checking with ERT..." << std::endl; this->check_message_ert(robot_code, data, telemetry); } else { // std::cout << "Checking with ROS..." << std::endl; this->check_message_ros(robot_code, data, telemetry); } } void StateManager::check_message_ecs(std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { // Parse message to query-able format std::string msg_text = data->msg; // std::replace(msg_text.begin(), msg_text.end(), '/', ' '); // std::cout << "Querying: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // ECS has a hit, follow the message cycle // std::cout << "JSON parsed"; // msg_info = msg_info[0]; int error_level = (msg_info.at(utility::conversions::to_string_t("severity"))).as_integer(); // std::cout << "Level: " << error_level << std::endl; std::string error_msg = (msg_info.at(utility::conversions::to_string_t("error_text"))).as_string(); // std::cout << "Text: " << error_msg << std::endl; if ((error_level == 8) || (error_level == 16)) { // std::cout << "Error... " << data->msg << std::endl; // Check for suppression this->check_error(robot_code, error_msg); } else if (error_level == 4) { // std::cout << "Warning... " << data->msg << std::endl; // Check for suppression this->check_warning(robot_code, error_msg); } else { // std::cout << "Info... " << data->msg << std::endl; // Check for suppression this->check_info(robot_code, error_msg); } // Process result of event if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { // std::cout << "Not suppressed!" << std::endl; // If not suppressed, send it to event to update this->event_instance.update_log(data, msg_info, telemetry, "ECS"); // Push to stream this->api_instance.push_event_log(this->event_instance.get_log()); // Get compounding flag bool cflag = (msg_info.at(utility::conversions::to_string_t("compounding_flag"))).as_bool(); if (cflag == true) { // Nothing to do here unless it is a compounding error if ((error_level == 8) || (error_level == 16)) { // Push on ALL errors / One named Info msg // Clear only event log since this is compounding this->event_instance.clear_log(); } else { // Nothing to do } } else { // This is a compounding log, Clear everything this->clear(); } } } else { // ECS does not have a hit, normal operation resumes } } void StateManager::check_message_ert(std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { // Parse message to query-able format std::string msg_text = data->msg; // std::replace(msg_text.begin(), msg_text.end(), '/', ' '); // std::cout << "Querying: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // ECS has a hit, follow the message cycle // std::cout << "JSON parsed"; // msg_info = msg_info[0]; int error_level = (msg_info.at(utility::conversions::to_string_t("error_level"))).as_integer(); // std::cout << "Level: " << error_level << std::endl; std::string error_msg = (msg_info.at(utility::conversions::to_string_t("error_text"))).as_string(); // std::cout << "Text: " << error_msg << std::endl; if (error_level == 8) { // std::cout << "Error... " << data->msg << std::endl; // Check for suppression this->check_error(robot_code, error_msg); } else if (error_level == 4) { // std::cout << "Warning... " << data->msg << std::endl; // Check for suppression this->check_warning(robot_code, error_msg); } else { // std::cout << "Info... " << data->msg << std::endl; // Check for suppression this->check_info(robot_code, error_msg); } // Process result of event if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { // std::cout << "Not suppressed!" << std::endl; // If not suppressed, send it to event to update this->event_instance.update_log(data, msg_info, telemetry, "ERT"); // Push to stream this->api_instance.push_event_log(this->event_instance.get_log()); // Get compounding flag bool cflag = (msg_info.at(utility::conversions::to_string_t("compounding_flag"))).as_bool(); if (cflag == true) { // Nothing to do here unless it is a compounding error if (error_level == 8) { // Push on ALL errors / One named Info msg // Clear only event log since this is compounding this->event_instance.clear_log(); } else { // Nothing to do } } else { // This is a compounding log, Clear everything this->clear(); } } } else { // ECS does not have a hit, normal operation resumes } } void StateManager::check_message_ros(std::string robot_code, const rosgraph_msgs::Log::ConstPtr &data, json::value telemetry) { if (data->level == 8) { // std::cout << "Error... " << data->msg << std::endl; // Check for suppression this->check_error(robot_code, data->msg); } else if (data->level == 4) { // std::cout << "Warning... " << data->msg << std::endl; // Check for suppression this->check_warning(robot_code, data->msg); } else { // std::cout << "Info... " << data->msg << std::endl; // Check for suppression this->check_info(robot_code, data->msg); } // Process result of event if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { // std::cout << "Not suppressed!" << std::endl; // If not suppressed, send it to event to update this->event_instance.update_log(data, json::value::null(), telemetry, "ROS"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); if ((data->level == 8) || (data->msg == "Goal reached")) { // Clear everything, end of event this->clear(); } else { // Clear only log this->event_instance.clear_log(); } } } void StateManager::check_error(std::string robot_code, std::string msg_text) { std::vector<std::string> found = this->does_exist(robot_code, msg_text); bool exist; if (found[0] == "") { exist = false; } else { exist = true; } if (exist) { // Found, suppress this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> msg_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data msg_details.push_back(robot_code); msg_details.push_back(msg_text); msg_details.push_back(time_str); this->msg_data.push_back(msg_details); // Do not suppress this->suppress_flag = false; } } void StateManager::check_warning(std::string robot_code, std::string msg_text) { std::vector<std::string> found = this->does_exist(robot_code, msg_text); bool exist; if (found[0] == "") { exist = false; } else { exist = true; } if (exist) { // Found, check timeout limit - not implemented yet this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> msg_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data msg_details.push_back(robot_code); msg_details.push_back(msg_text); msg_details.push_back(time_str); this->msg_data.push_back(msg_details); // Do not suppress this->suppress_flag = false; } } void StateManager::check_info(std::string robot_code, std::string msg_text) { std::vector<std::string> found = this->does_exist(robot_code, msg_text); bool exist; if (found[0] == "") { exist = false; // std::cout << "Msg found status: False" << std::endl; } else { exist = true; // std::cout << "Msg found status: True" << std::endl; } if (exist) { // Found, suppress this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> msg_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data msg_details.push_back(robot_code); msg_details.push_back(msg_text); msg_details.push_back(time_str); this->msg_data.push_back(msg_details); // Do not suppress this->suppress_flag = false; } } void StateManager::check_heartbeat(bool status, json::value telemetry) { // Pass data to backend to push appropriate status this->api_instance.push_status(status, telemetry); } void StateManager::check_diagnostic(std::string agent_type, std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // this->check_diagnostic_ros(robot_code, current_diag, telemetry); if (agent_type == "ECS") { // std::cout << "Checking with ECS..." << std::endl; this->check_diagnostic_ecs(robot_code, current_diag, telemetry); } else if ((agent_type == "ERT") || (agent_type == "DB")) { // std::cout << "Checking with ERT..." << std::endl; this->check_diagnostic_ert(robot_code, current_diag, telemetry); } else { // std::cout << "Checking with ROS..." << std::endl; this->check_diagnostic_ros(robot_code, current_diag, telemetry); } } void StateManager::check_diagnostic_ros(std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // Check diagnostic data and if not suppressed, push it to the event // Variables to store diagnostic info for state management std::string diag_str; int diag_level; std::string diag_ident; for (unsigned int idx = 0; idx < current_diag.size(); idx++) { // Store diagnostics name+hardware_id in a single string for quick search diag_str = current_diag[idx].name + "_" + current_diag[idx].hardware_id; // Diagnostics level. Main determination for state suppression diag_level = static_cast<int>(current_diag[idx].level); // std::cout << "Checking: " << diag_level << " " << diag_str << std::endl; // Check if diagnostic needs to be suppressed. All diagnostics with the same str // and no change in level are suppressed. We process only when there is change in levels. this->check_diag_data(robot_code, diag_str, std::to_string(diag_level)); if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { std::string diag_name = current_diag[idx].name; std::string diag_hwid = current_diag[idx].hardware_id; if (!diag_name.empty()) { diag_ident = diag_name; } else if (!diag_hwid.empty()) { diag_ident = diag_hwid; } // If not suppressed, send it to event to update // Construct ROS log equivalent of diag rosgraph_msgs::Log rosmsg; rosmsg.name = diag_str; if (!diag_ident.empty()) { rosmsg.msg = diag_ident + "-->" + current_diag[idx].message; } else { rosmsg.msg = current_diag[idx].message; } if (diag_level == 2) { rosmsg.level = rosmsg.ERROR; rosmsg.msg = "[ERROR] " + rosmsg.msg; } else if ((diag_level == 1) || (diag_level == 3)) { rosmsg.level = rosmsg.WARN; rosmsg.msg = "[WARN] " + rosmsg.msg; } else { rosmsg.level = rosmsg.INFO; rosmsg.msg = "[INFO] " + rosmsg.msg; } std::cout << "Diagnostic Message State Change: " << rosmsg.msg << std::endl; rosgraph_msgs::Log::ConstPtr data(new rosgraph_msgs::Log(rosmsg)); this->event_instance.update_log(data, json::value::null(), telemetry, "ROS"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); // if (data->level == 8) // { // // Clear everything, end of event // this->clear(); // } // else // { // // Clear only log // this->event_instance.clear_log(); // } } } } void StateManager::check_diagnostic_ert(std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // Check diagnostic data and if not suppressed, push it to the event // Variables to store diagnostic info for state management std::string diag_str; int diag_level; std::string diag_ident; for (unsigned int idx = 0; idx < current_diag.size(); idx++) { // Store diagnostics name+hardware_id in a single string for quick search diag_str = current_diag[idx].name + "_" + current_diag[idx].hardware_id; // Diagnostics level. Main determination for state suppression diag_level = static_cast<int>(current_diag[idx].level); // Check if diagnostic needs to be suppressed. All diagnostics with the same str // and no change in level are suppressed. We process only when there is change in levels. this->check_diag_data(robot_code, diag_str, std::to_string(diag_level)); if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { std::string diag_name = current_diag[idx].name; std::string diag_hwid = current_diag[idx].hardware_id; if (!diag_name.empty()) { diag_ident = diag_name; } else if (!diag_hwid.empty()) { diag_ident = diag_hwid; } // If not suppressed, send it to event to update // Parse message to query-able format std::string msg_text; if (!diag_ident.empty()) { msg_text = diag_ident + "-->" + current_diag[idx].message; } else { msg_text = current_diag[idx].message; } if (diag_level == 2) { msg_text = "[ERROR] " + msg_text; } else if ((diag_level == 1) || (diag_level == 3)) { msg_text = "[WARN] " + msg_text; } else { msg_text = "[INFO] " + msg_text; } std::cout << "Diagnostic Message State Change: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // Construct ROS log equivalent of diag rosgraph_msgs::Log rosmsg; rosmsg.name = diag_str; rosmsg.msg = msg_text; if (diag_level == 2) { rosmsg.level = rosmsg.ERROR; } else if ((diag_level == 1) || (diag_level == 3)) { rosmsg.level = rosmsg.WARN; } else { rosmsg.level = rosmsg.INFO; } rosgraph_msgs::Log::ConstPtr data(new rosgraph_msgs::Log(rosmsg)); this->event_instance.update_log(data, msg_info, telemetry, "ERT"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); } else { // ECS does not have a hit, normal operation resumes } // if (data->level == 8) // { // // Clear everything, end of event // this->clear(); // } // else // { // // Clear only log // this->event_instance.clear_log(); // } } } } void StateManager::check_diagnostic_ecs(std::string robot_code, std::vector<diagnostic_msgs::DiagnosticStatus> current_diag, json::value telemetry) { // Check diagnostic data and if not suppressed, push it to the event // Variables to store diagnostic info for state management std::string diag_str; int diag_level; std::string diag_ident; for (unsigned int idx = 0; idx < current_diag.size(); idx++) { // Store diagnostics name+hardware_id in a single string for quick search diag_str = current_diag[idx].name + "_" + current_diag[idx].hardware_id; // Diagnostics level. Main determination for state suppression diag_level = static_cast<int>(current_diag[idx].level); // Check if diagnostic needs to be suppressed. All diagnostics with the same str // and no change in level are suppressed. We process only when there is change in levels. this->check_diag_data(robot_code, diag_str, std::to_string(diag_level)); if (this->suppress_flag) { // If suppressed, do nothing // std::cout << "Suppressed!" << std::endl; } else { std::string diag_name = current_diag[idx].name; std::string diag_hwid = current_diag[idx].hardware_id; if (!diag_name.empty()) { diag_ident = diag_name; } else if (!diag_hwid.empty()) { diag_ident = diag_hwid; } // If not suppressed, send it to event to update // Parse message to query-able format std::string msg_text; if (!diag_ident.empty()) { msg_text = diag_ident + "-->" + current_diag[idx].message; } else { msg_text = current_diag[idx].message; } if (diag_level == 2) { msg_text = "[ERROR] " + msg_text; } else if ((diag_level == 1) || (diag_level == 3)) { msg_text = "[WARN] " + msg_text; } else { msg_text = "[INFO] " + msg_text; } std::cout << "Diagnostic Message State Change: " << msg_text << std::endl; // Check error classification, ECS json::value msg_info = this->api_instance.check_error_classification(msg_text); bool ecs_hit = !(msg_info.is_null()); // std::cout << "ECS Hit: " << ecs_hit << std::endl; if (ecs_hit) { // Construct ROS log equivalent of diag rosgraph_msgs::Log rosmsg; rosmsg.name = diag_str; rosmsg.msg = msg_text; if (diag_level == 2) { rosmsg.level = rosmsg.ERROR; } else if ((diag_level == 1) || (diag_level == 3)) { rosmsg.level = rosmsg.WARN; } else { rosmsg.level = rosmsg.INFO; } rosgraph_msgs::Log::ConstPtr data(new rosgraph_msgs::Log(rosmsg)); this->event_instance.update_log(data, msg_info, telemetry, "ECS"); // Push log this->api_instance.push_event_log(this->event_instance.get_log()); } else { // ECS does not have a hit, normal operation resumes } // if (data->level == 8) // { // // Clear everything, end of event // this->clear(); // } // else // { // // Clear only log // this->event_instance.clear_log(); // } } } } void StateManager::check_diag_data(std::string robot_code, std::string diag_str, std::string level) { // Check if diagnostic already reported std::vector<std::string> found = this->does_diag_exist(robot_code, diag_str, level); bool exist; if (found[0] == "") { exist = false; } else { exist = true; } if (exist) { // Found, suppress this->suppress_flag = true; } else { // Not found, add to data std::vector<std::string> diag_details; // Get current time time_t now; time(&now); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now)); std::string time_str = std::string(buf); // Push details to data diag_details.push_back(robot_code); diag_details.push_back(diag_str); diag_details.push_back(level); diag_details.push_back(time_str); this->diag_data.push_back(diag_details); // Do not suppress this->suppress_flag = false; } } std::vector<std::string> StateManager::does_diag_exist(std::string robot_code, std::string diag_str, std::string level) { // Find if diagnostic is already recorded for the given robot code at the given level std::vector<std::vector<std::string>>::const_iterator row; std::vector<std::vector<std::vector<std::string>>::const_iterator> erase_list; for (row = this->diag_data.begin(); row != this->diag_data.end(); row++) { auto found_name = find(row->begin(), row->end(), diag_str); if (found_name != row->end()) { // Found name, check for other parameters if ((find(row->begin(), row->end(), level) != row->end()) && (find(row->begin(), row->end(), robot_code) != row->end())) { // Found level as well, just return the row since it is already reported return *(row); } else { // Level not found but name is. This means state has changed. // Add row to erase list. // Will add a new row with this name downstream. erase_list.push_back(row); } } } // Erase elements for (auto element : erase_list) { this->diag_data.erase(element); } // Return empty string if no match std::vector<std::string> emptyString; emptyString.push_back(""); return emptyString; } void StateManager::clear() { // Clears the state manager data for a new session this->suppress_flag = false; this->msg_data.clear(); this->event_instance.clear(); }
31.318235
167
0.531096
752db47227df30cc728e232d1b1026633ca70523
1,234
cpp
C++
bitbots_splines_extension/src/handle/position_handle.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
bitbots_splines_extension/src/handle/position_handle.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
bitbots_splines_extension/src/handle/position_handle.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
#include "handle/position_handle.h" namespace bitbots_splines { PositionHandle::PositionHandle(std::shared_ptr<Curve> x, std::shared_ptr<Curve> y, std::shared_ptr<Curve> z) : x_(std::move(x)), y_(std::move(y)), z_(std::move(z)) { } geometry_msgs::Point PositionHandle::get_geometry_msg_position(double time) { geometry_msgs::Point msg; tf2::Vector3 tf_vec = get_position(time); msg.x = tf_vec.x(); msg.y = tf_vec.y(); msg.z = tf_vec.z(); return msg; } tf2::Vector3 PositionHandle::get_position(double time) { tf2::Vector3 pos; pos[0] = x_->position(time); pos[1] = y_->position(time); pos[2] = z_->position(time); return pos; } tf2::Vector3 PositionHandle::get_velocity(double time) { tf2::Vector3 vel; vel[0] = x_->velocity(time); vel[1] = y_->velocity(time); vel[2] = z_->velocity(time); return vel; } tf2::Vector3 PositionHandle::get_acceleration(double time) { tf2::Vector3 acc; acc[0] = x_->acceleration(time); acc[1] = y_->acceleration(time); acc[2] = z_->acceleration(time); return acc; } std::shared_ptr<Curve> PositionHandle::x() { return x_; } std::shared_ptr<Curve> PositionHandle::y() { return y_; } std::shared_ptr<Curve> PositionHandle::z() { return z_; } }
22.851852
109
0.676661
752f29b5a05e379e520f0891f8209031df398cd3
1,130
cpp
C++
doubly_linked_list/doubly_linked_list.cpp
Khushmeet/dsa
580fcff399bf1950b7b1fd70838e091a63eac2a9
[ "MIT" ]
null
null
null
doubly_linked_list/doubly_linked_list.cpp
Khushmeet/dsa
580fcff399bf1950b7b1fd70838e091a63eac2a9
[ "MIT" ]
null
null
null
doubly_linked_list/doubly_linked_list.cpp
Khushmeet/dsa
580fcff399bf1950b7b1fd70838e091a63eac2a9
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; struct Node { int data; struct Node *next; struct Node *prev; }; struct Node *head = (struct Node *)malloc(sizeof(struct Node)); struct Node* get_new_node(int data) { Node *temp = new Node(); temp->data = data; temp->next = NULL; temp->prev = NULL; return temp; } void insert_at_0(int data) { Node *temp = get_new_node(data); if (head == NULL) { head = temp; return; } temp->next = head; head->prev = temp; head = temp; } void print() { Node *temp = head; cout << "List is "; while (temp != NULL) { cout << " " << temp->data; temp = temp->next; } cout << endl; } void print_reverse() { Node *temp = head; while(temp->next != NULL) { temp = temp->next; } cout << "List is "; while (temp != NULL) { cout << " " << temp->data; temp = temp->prev; } cout << endl; } int main() { head = NULL; insert_at_0(7); insert_at_0(0); insert_at_0(4); insert_at_0(1); print(); print_reverse(); }
15.479452
63
0.517699
752fff563ecb7483027347c994bc5304477725d1
258
cpp
C++
hackerrank/practice/mathematics/fundamentals/handshake.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
hackerrank/practice/mathematics/fundamentals/handshake.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
hackerrank/practice/mathematics/fundamentals/handshake.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
// https://www.hackerrank.com/challenges/handshake #include "common/stl/base.h" int main_handshake() { unsigned T; cin >> T; for (unsigned it = 0; it < T; ++it) { uint64_t n; cin >> n; cout << (n * (n - 1)) / 2 << endl; } return 0; }
17.2
50
0.550388
75393ebccbc3603325e492b4e136b3e73182bc82
2,387
cpp
C++
dataserver/src/storage/processor_data_sample.cpp
jimdb-org/jimdb
927e4447879189597dbe7f91a7fe0e8865107ef4
[ "Apache-2.0" ]
59
2020-01-10T06:27:12.000Z
2021-12-16T06:37:36.000Z
dataserver/src/storage/processor_data_sample.cpp
jimdb-org/jimdb
927e4447879189597dbe7f91a7fe0e8865107ef4
[ "Apache-2.0" ]
null
null
null
dataserver/src/storage/processor_data_sample.cpp
jimdb-org/jimdb
927e4447879189597dbe7f91a7fe0e8865107ef4
[ "Apache-2.0" ]
3
2020-02-13T05:04:20.000Z
2020-06-29T01:07:48.000Z
// Copyright 2019 The JIMDB Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. #include "processor_data_sample.h" #include <chrono> namespace jim { namespace ds { namespace storage { DataSample::DataSample(const dspb::DataSample & data_sample, const dspb::KeyRange & range_default, Store & s, bool gather_trace ) : str_last_key_(""), over_(false), range_default_(range_default), key_schema_( s.GetKeySchema()), row_fetcher_(new RowFetcher( s, data_sample, range_default.start_key(), range_default.end_key())) { gather_trace_ = gather_trace; for (const auto & col : data_sample.columns()) { col_ids.push_back(col.id()); } } DataSample::~DataSample() { } const std::string DataSample::get_last_key() { return str_last_key_; } Status DataSample::next( RowResult & row) { Status s; if (over_) { return Status( Status::kNoMoreData, " last key: ", EncodeToHexString(get_last_key()) ); } std::chrono::system_clock::time_point time_begin; if (gather_trace_) { time_begin = std::chrono::system_clock::now(); } s = row_fetcher_->Next( row, over_); if (over_ && s.ok()) { s = Status( Status::kNoMoreData, " last key: ", EncodeToHexString(get_last_key()) ); } if (s.ok()) { str_last_key_ = row.GetKey(); } if (gather_trace_) { ++rows_count_; time_processed_ns_ += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - time_begin).count(); } return s; } const std::vector<uint64_t> DataSample::get_col_ids() { return col_ids; } void DataSample::get_stats(std::vector<ProcessorStat> &stats) { stats.emplace_back(rows_count_, time_processed_ns_); } } /* namespace storage */ } /* namespace ds */ } /* namespace jim */
26.230769
138
0.661919
753a78fefd48383246b2b7bf9549887fa5cbb79d
32,746
cpp
C++
indra/newview/llcallingcard.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llcallingcard.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/newview/llcallingcard.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llcallingcard.cpp * @brief Implementation of the LLPreviewCallingCard class * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #if LL_WINDOWS #pragma warning( disable : 4800 ) // performance warning in <functional> #endif #include "llcallingcard.h" #include <algorithm> #include "indra_constants.h" //#include "llcachename.h" #include "llstl.h" #include "lltimer.h" #include "lluuid.h" #include "message.h" #include "llagent.h" #include "llavatarnamecache.h" #include "llinventoryobserver.h" #include "llinventorymodel.h" #include "llnotifications.h" #include "llslurl.h" #include "llimview.h" #include "lltrans.h" #include "llviewercontrol.h" #include "llviewerobjectlist.h" #include "llvoavatar.h" #include "llavataractions.h" // Firestorm includes #include "fscommon.h" #include "fsfloaternearbychat.h" #include "fskeywords.h" #include "lggcontactsets.h" #include "llfloaterreg.h" #include "llnotificationmanager.h" ///---------------------------------------------------------------------------- /// Local function declarations, constants, enums, and typedefs ///---------------------------------------------------------------------------- class LLTrackingData { public: LLTrackingData(const LLUUID& avatar_id, const std::string& name); bool haveTrackingInfo(); void setTrackedCoarseLocation(const LLVector3d& global_pos); void agentFound(const LLUUID& prey, const LLVector3d& estimated_global_pos); public: LLUUID mAvatarID; std::string mName; LLVector3d mGlobalPositionEstimate; bool mHaveInfo; bool mHaveCoarseInfo; LLTimer mCoarseLocationTimer; LLTimer mUpdateTimer; LLTimer mAgentGone; }; const F32 COARSE_FREQUENCY = 2.2f; const F32 FIND_FREQUENCY = 29.7f; // This results in a database query, so cut these back const F32 OFFLINE_SECONDS = FIND_FREQUENCY + 8.0f; // static LLAvatarTracker LLAvatarTracker::sInstance; static void on_avatar_name_cache_notify(const LLUUID& agent_id, const LLAvatarName& av_name, bool online, LLSD payload); ///---------------------------------------------------------------------------- /// Class LLAvatarTracker ///---------------------------------------------------------------------------- LLAvatarTracker::LLAvatarTracker() : mTrackingData(NULL), mTrackedAgentValid(false), mModifyMask(0x0), mIsNotifyObservers(FALSE) { } LLAvatarTracker::~LLAvatarTracker() { deleteTrackingData(); std::for_each(mObservers.begin(), mObservers.end(), DeletePointer()); mObservers.clear(); std::for_each(mBuddyInfo.begin(), mBuddyInfo.end(), DeletePairedPointer()); mBuddyInfo.clear(); } void LLAvatarTracker::track(const LLUUID& avatar_id, const std::string& name) { deleteTrackingData(); mTrackedAgentValid = false; mTrackingData = new LLTrackingData(avatar_id, name); findAgent(); // We track here because findAgent() is called on a timer (for now). if(avatar_id.notNull()) { LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_TrackAgent); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->nextBlockFast(_PREHASH_TargetData); msg->addUUIDFast(_PREHASH_PreyID, avatar_id); gAgent.sendReliableMessage(); } } void LLAvatarTracker::untrack(const LLUUID& avatar_id) { if (mTrackingData && mTrackingData->mAvatarID == avatar_id) { deleteTrackingData(); mTrackedAgentValid = false; LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_TrackAgent); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->nextBlockFast(_PREHASH_TargetData); msg->addUUIDFast(_PREHASH_PreyID, LLUUID::null); gAgent.sendReliableMessage(); } } void LLAvatarTracker::setTrackedCoarseLocation(const LLVector3d& global_pos) { if(mTrackingData) { mTrackingData->setTrackedCoarseLocation(global_pos); } } bool LLAvatarTracker::haveTrackingInfo() { if(mTrackingData) { return mTrackingData->haveTrackingInfo(); } return false; } LLVector3d LLAvatarTracker::getGlobalPos() { if(!mTrackedAgentValid || !mTrackingData) return LLVector3d(); LLVector3d global_pos; LLViewerObject* object = gObjectList.findObject(mTrackingData->mAvatarID); if(object && !object->isDead()) { global_pos = object->getPositionGlobal(); // HACK - for making the tracker point above the avatar's head // rather than its groin LLVOAvatar* av = (LLVOAvatar*)object; global_pos.mdV[VZ] += 0.7f * (av->mBodySize.mV[VZ] + av->mAvatarOffset.mV[VZ]); mTrackingData->mGlobalPositionEstimate = global_pos; } else { global_pos = mTrackingData->mGlobalPositionEstimate; } return global_pos; } void LLAvatarTracker::getDegreesAndDist(F32& rot, F64& horiz_dist, F64& vert_dist) { if(!mTrackingData) return; LLVector3d global_pos; LLViewerObject* object = gObjectList.findObject(mTrackingData->mAvatarID); if(object && !object->isDead()) { global_pos = object->getPositionGlobal(); mTrackingData->mGlobalPositionEstimate = global_pos; } else { global_pos = mTrackingData->mGlobalPositionEstimate; } LLVector3d to_vec = global_pos - gAgent.getPositionGlobal(); horiz_dist = sqrt(to_vec.mdV[VX] * to_vec.mdV[VX] + to_vec.mdV[VY] * to_vec.mdV[VY]); vert_dist = to_vec.mdV[VZ]; rot = F32(RAD_TO_DEG * atan2(to_vec.mdV[VY], to_vec.mdV[VX])); } const std::string& LLAvatarTracker::getName() { if(mTrackingData) { return mTrackingData->mName; } else { return LLStringUtil::null; } } const LLUUID& LLAvatarTracker::getAvatarID() { if(mTrackingData) { return mTrackingData->mAvatarID; } else { return LLUUID::null; } } S32 LLAvatarTracker::addBuddyList(const LLAvatarTracker::buddy_map_t& buds) { using namespace std; U32 new_buddy_count = 0; LLUUID agent_id; for(buddy_map_t::const_iterator itr = buds.begin(); itr != buds.end(); ++itr) { agent_id = (*itr).first; buddy_map_t::const_iterator existing_buddy = mBuddyInfo.find(agent_id); if(existing_buddy == mBuddyInfo.end()) { ++new_buddy_count; mBuddyInfo[agent_id] = (*itr).second; // pre-request name for notifications? LLAvatarName av_name; LLAvatarNameCache::get(agent_id, &av_name); addChangedMask(LLFriendObserver::ADD, agent_id); LL_DEBUGS() << "Added buddy " << agent_id << ", " << (mBuddyInfo[agent_id]->isOnline() ? "Online" : "Offline") << ", TO: " << mBuddyInfo[agent_id]->getRightsGrantedTo() << ", FROM: " << mBuddyInfo[agent_id]->getRightsGrantedFrom() << LL_ENDL; } else { LLRelationship* e_r = (*existing_buddy).second; LLRelationship* n_r = (*itr).second; LL_WARNS() << "!! Add buddy for existing buddy: " << agent_id << " [" << (e_r->isOnline() ? "Online" : "Offline") << "->" << (n_r->isOnline() ? "Online" : "Offline") << ", " << e_r->getRightsGrantedTo() << "->" << n_r->getRightsGrantedTo() << ", " << e_r->getRightsGrantedTo() << "->" << n_r->getRightsGrantedTo() << "]" << LL_ENDL; } } // do not notify observers here - list can be large so let it be done on idle. return new_buddy_count; } void LLAvatarTracker::copyBuddyList(buddy_map_t& buddies) const { buddy_map_t::const_iterator it = mBuddyInfo.begin(); buddy_map_t::const_iterator end = mBuddyInfo.end(); for(; it != end; ++it) { buddies[(*it).first] = (*it).second; } } void LLAvatarTracker::terminateBuddy(const LLUUID& id) { LL_DEBUGS() << "LLAvatarTracker::terminateBuddy()" << LL_ENDL; LLRelationship* buddy = get_ptr_in_map(mBuddyInfo, id); if(!buddy) return; mBuddyInfo.erase(id); LLMessageSystem* msg = gMessageSystem; msg->newMessage("TerminateFriendship"); msg->nextBlock("AgentData"); msg->addUUID("AgentID", gAgent.getID()); msg->addUUID("SessionID", gAgent.getSessionID()); msg->nextBlock("ExBlock"); msg->addUUID("OtherID", id); gAgent.sendReliableMessage(); addChangedMask(LLFriendObserver::REMOVE, id); delete buddy; } // get all buddy info const LLRelationship* LLAvatarTracker::getBuddyInfo(const LLUUID& id) const { if(id.isNull()) return NULL; return get_ptr_in_map(mBuddyInfo, id); } bool LLAvatarTracker::isBuddy(const LLUUID& id) const { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); return (info != NULL); } // online status void LLAvatarTracker::setBuddyOnline(const LLUUID& id, bool is_online) { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { info->online(is_online); addChangedMask(LLFriendObserver::ONLINE, id); LL_DEBUGS() << "Set buddy " << id << (is_online ? " Online" : " Offline") << LL_ENDL; } else { //<FS:LO> Fix possible log spam with a large friendslist when SL messes up. //LL_WARNS() << "!! No buddy info found for " << id LL_DEBUGS() << "!! No buddy info found for " << id << ", setting to " << (is_online ? "Online" : "Offline") << LL_ENDL; //</FS:LO> } } bool LLAvatarTracker::isBuddyOnline(const LLUUID& id) const { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { return info->isOnline(); } return false; } // empowered status void LLAvatarTracker::setBuddyEmpowered(const LLUUID& id, bool is_empowered) { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { info->grantRights(LLRelationship::GRANT_MODIFY_OBJECTS, 0); mModifyMask |= LLFriendObserver::POWERS; } } bool LLAvatarTracker::isBuddyEmpowered(const LLUUID& id) const { LLRelationship* info = get_ptr_in_map(mBuddyInfo, id); if(info) { return info->isRightGrantedTo(LLRelationship::GRANT_MODIFY_OBJECTS); } return false; } void LLAvatarTracker::empower(const LLUUID& id, bool grant) { // wrapper for ease of use in some situations. buddy_map_t list; /* list.insert(id); empowerList(list, grant); */ } void LLAvatarTracker::empowerList(const buddy_map_t& list, bool grant) { LL_WARNS() << "LLAvatarTracker::empowerList() not implemented." << LL_ENDL; /* LLMessageSystem* msg = gMessageSystem; const char* message_name; const char* block_name; const char* field_name; if(grant) { message_name = _PREHASH_GrantModification; block_name = _PREHASH_EmpoweredBlock; field_name = _PREHASH_EmpoweredID; } else { message_name = _PREHASH_RevokeModification; block_name = _PREHASH_RevokedBlock; field_name = _PREHASH_RevokedID; } std::string name; gAgent.buildFullnameAndTitle(name); bool start_new_message = true; buddy_list_t::const_iterator it = list.begin(); buddy_list_t::const_iterator end = list.end(); for(; it != end; ++it) { if(NULL == get_ptr_in_map(mBuddyInfo, (*it))) continue; setBuddyEmpowered((*it), grant); if(start_new_message) { start_new_message = false; msg->newMessageFast(message_name); msg->nextBlockFast(_PREHASH_AgentData); msg->addUUIDFast(_PREHASH_AgentID, gAgent.getID()); msg->addUUIDFast(_PREHASH_SessionID, gAgent.getSessionID()); msg->addStringFast(_PREHASH_GranterName, name); } msg->nextBlockFast(block_name); msg->addUUIDFast(field_name, (*it)); if(msg->isSendFullFast(block_name)) { start_new_message = true; gAgent.sendReliableMessage(); } } if(!start_new_message) { gAgent.sendReliableMessage(); } */ } void LLAvatarTracker::deleteTrackingData() { //make sure mTrackingData never points to freed memory LLTrackingData* tmp = mTrackingData; mTrackingData = NULL; delete tmp; } void LLAvatarTracker::findAgent() { if (!mTrackingData) return; if (mTrackingData->mAvatarID.isNull()) return; LLMessageSystem* msg = gMessageSystem; msg->newMessageFast(_PREHASH_FindAgent); // Request msg->nextBlockFast(_PREHASH_AgentBlock); msg->addUUIDFast(_PREHASH_Hunter, gAgentID); msg->addUUIDFast(_PREHASH_Prey, mTrackingData->mAvatarID); msg->addU32Fast(_PREHASH_SpaceIP, 0); // will get filled in by simulator msg->nextBlockFast(_PREHASH_LocationBlock); const F64 NO_LOCATION = 0.0; msg->addF64Fast(_PREHASH_GlobalX, NO_LOCATION); msg->addF64Fast(_PREHASH_GlobalY, NO_LOCATION); gAgent.sendReliableMessage(); } void LLAvatarTracker::addObserver(LLFriendObserver* observer) { if(observer) { mObservers.push_back(observer); } } void LLAvatarTracker::removeObserver(LLFriendObserver* observer) { mObservers.erase( std::remove(mObservers.begin(), mObservers.end(), observer), mObservers.end()); } void LLAvatarTracker::idleNotifyObservers() { if (mModifyMask == LLFriendObserver::NONE && mChangedBuddyIDs.size() == 0) { return; } notifyObservers(); } void LLAvatarTracker::notifyObservers() { if (mIsNotifyObservers) { // Don't allow multiple calls. // new masks and ids will be processed later from idle. return; } mIsNotifyObservers = TRUE; observer_list_t observers(mObservers); observer_list_t::iterator it = observers.begin(); observer_list_t::iterator end = observers.end(); for(; it != end; ++it) { (*it)->changed(mModifyMask); } for (changed_buddy_t::iterator it = mChangedBuddyIDs.begin(); it != mChangedBuddyIDs.end(); it++) { notifyParticularFriendObservers(*it); } mModifyMask = LLFriendObserver::NONE; mChangedBuddyIDs.clear(); mIsNotifyObservers = FALSE; } void LLAvatarTracker::addParticularFriendObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.notNull() && observer) mParticularFriendObserverMap[buddy_id].insert(observer); } void LLAvatarTracker::removeParticularFriendObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.isNull() || !observer) return; observer_map_t::iterator obs_it = mParticularFriendObserverMap.find(buddy_id); if(obs_it == mParticularFriendObserverMap.end()) return; obs_it->second.erase(observer); // purge empty sets from the map // AO: Remove below check as last resort to resolve a crash from dangling pointer. // TODO: clean up all observers and don't leave dangling pointers here. if (obs_it->second.size() == 0) mParticularFriendObserverMap.erase(obs_it); } void LLAvatarTracker::notifyParticularFriendObservers(const LLUUID& buddy_id) { observer_map_t::iterator obs_it = mParticularFriendObserverMap.find(buddy_id); if(obs_it == mParticularFriendObserverMap.end()) return; // Notify observers interested in buddy_id. // <FS:ND> FIRE-6077; FIRE-6227; FIRE-6431; SUP-9654; make a copy of observer_set. Just in case some implementation of changed() calls add/remove...Observer // observer_set_t& obs = obs_it->second; observer_set_t obs = obs_it->second; // </FS:ND: for (observer_set_t::iterator ob_it = obs.begin(); ob_it != obs.end(); ob_it++) { (*ob_it)->changed(mModifyMask); // <FS:ND/> Paranoia check. Of course someone could add x observer than add the same amount of x. That won't be found by comparing size alone, but it is good enough for a quick test llassert( obs.size() == obs_it->second.size() ); } } void LLAvatarTracker::addFriendPermissionObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.notNull() && observer) { mFriendPermissionObserverMap[buddy_id].insert(observer); } } void LLAvatarTracker::removeFriendPermissionObserver(const LLUUID& buddy_id, LLFriendObserver* observer) { if (buddy_id.isNull() || !observer) return; observer_map_t::iterator obs_it = mFriendPermissionObserverMap.find(buddy_id); if(obs_it == mFriendPermissionObserverMap.end()) return; obs_it->second.erase(observer); // purge empty sets from the map if (obs_it->second.size() == 0) mFriendPermissionObserverMap.erase(obs_it); } void LLAvatarTracker::notifyFriendPermissionObservers(const LLUUID& buddy_id) { observer_map_t::iterator obs_it = mFriendPermissionObserverMap.find(buddy_id); if(obs_it == mFriendPermissionObserverMap.end()) { return; } // Notify observers interested in buddy_id. // <FS:ND> FIRE-6077; FIRE-6227; FIRE-6431; SUP-9654; make a copy of observer_set. Just in case some implementation of changed() calls add/remove...Observer // observer_set_t& obs = obs_it->second; observer_set_t obs = obs_it->second; // </FS:ND> for (observer_set_t::iterator ob_it = obs.begin(); ob_it != obs.end(); ob_it++) { (*ob_it)->changed(LLFriendObserver::PERMS); // <FS:ND/> Paranoia check. Of course someone could add x observer than add the same amount of x. That won't be found by comparing size alone, but it is good enough for a quick test llassert( obs.size() == obs_it->second.size() ); } } // store flag for change // and id of object change applies to void LLAvatarTracker::addChangedMask(U32 mask, const LLUUID& referent) { mModifyMask |= mask; if (referent.notNull()) { mChangedBuddyIDs.insert(referent); } } void LLAvatarTracker::applyFunctor(LLRelationshipFunctor& f) { buddy_map_t::iterator it = mBuddyInfo.begin(); buddy_map_t::iterator end = mBuddyInfo.end(); for(; it != end; ++it) { f((*it).first, (*it).second); } } void LLAvatarTracker::registerCallbacks(LLMessageSystem* msg) { msg->setHandlerFuncFast(_PREHASH_FindAgent, processAgentFound); msg->setHandlerFuncFast(_PREHASH_OnlineNotification, processOnlineNotification); msg->setHandlerFuncFast(_PREHASH_OfflineNotification, processOfflineNotification); //msg->setHandlerFuncFast(_PREHASH_GrantedProxies, // processGrantedProxies); msg->setHandlerFunc("TerminateFriendship", processTerminateFriendship); msg->setHandlerFunc(_PREHASH_ChangeUserRights, processChangeUserRights); } // static void LLAvatarTracker::processAgentFound(LLMessageSystem* msg, void**) { LLUUID id; msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_Hunter, id); msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_Prey, id); // *FIX: should make sure prey id matches. LLVector3d estimated_global_pos; msg->getF64Fast(_PREHASH_LocationBlock, _PREHASH_GlobalX, estimated_global_pos.mdV[VX]); msg->getF64Fast(_PREHASH_LocationBlock, _PREHASH_GlobalY, estimated_global_pos.mdV[VY]); LLAvatarTracker::instance().agentFound(id, estimated_global_pos); } void LLAvatarTracker::agentFound(const LLUUID& prey, const LLVector3d& estimated_global_pos) { if(!mTrackingData) return; //if we get a valid reply from the server, that means the agent //is our friend and mappable, so enable interest list based updates LLAvatarTracker::instance().setTrackedAgentValid(true); mTrackingData->agentFound(prey, estimated_global_pos); } // static void LLAvatarTracker::processOnlineNotification(LLMessageSystem* msg, void**) { LL_DEBUGS() << "LLAvatarTracker::processOnlineNotification()" << LL_ENDL; instance().processNotify(msg, true); } // static void LLAvatarTracker::processOfflineNotification(LLMessageSystem* msg, void**) { LL_DEBUGS() << "LLAvatarTracker::processOfflineNotification()" << LL_ENDL; instance().processNotify(msg, false); } void LLAvatarTracker::processChange(LLMessageSystem* msg) { S32 count = msg->getNumberOfBlocksFast(_PREHASH_Rights); LLUUID agent_id, agent_related; S32 new_rights; msg->getUUIDFast(_PREHASH_AgentData, _PREHASH_AgentID, agent_id); for(int i = 0; i < count; ++i) { msg->getUUIDFast(_PREHASH_Rights, _PREHASH_AgentRelated, agent_related, i); msg->getS32Fast(_PREHASH_Rights,_PREHASH_RelatedRights, new_rights, i); if(agent_id == gAgent.getID()) { if(mBuddyInfo.find(agent_related) != mBuddyInfo.end()) { (mBuddyInfo[agent_related])->setRightsTo(new_rights); // I'm not totally sure why it adds the agents id to the changed list // nor why it doesn't add the friends's ID. // Add the friend's id to the changed list for contacts list -KC mChangedBuddyIDs.insert(agent_related); } } else { if(mBuddyInfo.find(agent_id) != mBuddyInfo.end()) { if((mBuddyInfo[agent_id]->getRightsGrantedFrom() ^ new_rights) & LLRelationship::GRANT_MODIFY_OBJECTS) { LLSD args; // <FS:Ansariel> Always show complete name in rights dialogs //args["NAME"] = LLSLURL("agent", agent_id, "displayname").getSLURLString(); args["NAME"] = LLSLURL("agent", agent_id, "completename").getSLURLString(); LLSD payload; payload["from_id"] = agent_id; if(LLRelationship::GRANT_MODIFY_OBJECTS & new_rights) { LLNotifications::instance().add("GrantedModifyRights",args, payload); } else { LLNotifications::instance().add("RevokedModifyRights",args, payload); } } // <FS:Ansariel> Online status right apparently only provided as part of login response in idle_startup (response["buddy-list"]), // so we can only keep current grant new_rights = new_rights | (mBuddyInfo[agent_id]->getRightsGrantedFrom() & LLRelationship::GRANT_ONLINE_STATUS); (mBuddyInfo[agent_id])->setRightsFrom(new_rights); } } } addChangedMask(LLFriendObserver::POWERS, agent_id); notifyObservers(); notifyFriendPermissionObservers(agent_related); } void LLAvatarTracker::processChangeUserRights(LLMessageSystem* msg, void**) { LL_DEBUGS() << "LLAvatarTracker::processChangeUserRights()" << LL_ENDL; instance().processChange(msg); } void LLAvatarTracker::processNotify(LLMessageSystem* msg, bool online) { S32 count = msg->getNumberOfBlocksFast(_PREHASH_AgentBlock); // <FS:PP> Attempt to speed up things a little // BOOL chat_notify = gSavedSettings.getBOOL("ChatOnlineNotification"); static LLCachedControl<bool> ChatOnlineNotification(gSavedSettings, "ChatOnlineNotification"); BOOL chat_notify = ChatOnlineNotification; // </FS:PP> LL_DEBUGS() << "Received " << count << " online notifications **** " << LL_ENDL; if(count > 0) { LLUUID agent_id; const LLRelationship* info = NULL; LLUUID tracking_id; if(mTrackingData) { tracking_id = mTrackingData->mAvatarID; } LLSD payload; for(S32 i = 0; i < count; ++i) { msg->getUUIDFast(_PREHASH_AgentBlock, _PREHASH_AgentID, agent_id, i); payload["FROM_ID"] = agent_id; info = getBuddyInfo(agent_id); if(info) { setBuddyOnline(agent_id,online); } else { LL_WARNS() << "Received online notification for unknown buddy: " << agent_id << " is " << (online ? "ONLINE" : "OFFLINE") << LL_ENDL; } if(tracking_id == agent_id) { // we were tracking someone who went offline deleteTrackingData(); } // *TODO: get actual inventory id gInventory.addChangedMask(LLInventoryObserver::CALLING_CARD, LLUUID::null); } //[FIX FIRE-3522 : SJ] Notify Online/Offline to Nearby Chat even if chat_notify isnt true // <FS:PP> Attempt to speed up things a little // if(chat_notify||LGGContactSets::getInstance()->notifyForFriend(agent_id)||gSavedSettings.getBOOL("OnlineOfflinetoNearbyChat")) static LLCachedControl<bool> OnlineOfflinetoNearbyChat(gSavedSettings, "OnlineOfflinetoNearbyChat"); if(chat_notify || LGGContactSets::getInstance()->notifyForFriend(agent_id) || OnlineOfflinetoNearbyChat) // </FS:PP> { // Look up the name of this agent for the notification LLAvatarNameCache::get(agent_id,boost::bind(&on_avatar_name_cache_notify,_1, _2, online, payload)); } mModifyMask |= LLFriendObserver::ONLINE; instance().notifyObservers(); gInventory.notifyObservers(); } } static void on_avatar_name_cache_notify(const LLUUID& agent_id, const LLAvatarName& av_name, bool online, LLSD payload) { // Popup a notify box with online status of this agent // Use display name only because this user is your friend LLSD args; // <FS:Ansariel> Make name clickable // args["NAME"] = av_name.getDisplayName(); std::string used_name = FSCommon::getAvatarNameByDisplaySettings(av_name); args["NAME"] = used_name; // </FS:Ansariel> args["STATUS"] = online ? LLTrans::getString("OnlineStatus") : LLTrans::getString("OfflineStatus"); args["AGENT-ID"] = agent_id; LLNotificationPtr notification; if (online) { make_ui_sound("UISndFriendOnline"); // <FS:PP> FIRE-2731: Online/offline sound alert for friends notification = LLNotifications::instance().add("FriendOnlineOffline", args, payload.with("respond_on_mousedown", TRUE), boost::bind(&LLAvatarActions::startIM, agent_id)); } else { make_ui_sound("UISndFriendOffline"); // <FS:PP> FIRE-2731: Online/offline sound alert for friends notification = LLNotifications::instance().add("FriendOnlineOffline", args, payload); } // If there's an open IM session with this agent, send a notification there too. LLUUID session_id = LLIMMgr::computeSessionID(IM_NOTHING_SPECIAL, agent_id); std::string notify_msg = notification->getMessage(); LLIMModel::instance().proccessOnlineOfflineNotification(session_id, notify_msg); // If desired, also send it to nearby chat, this allows friends' // online/offline times to be referenced in chat & logged. // [FIRE-3522 : SJ] Only show Online/Offline toast for groups which have enabled "Show notice for this set" and in the settingpage of CS is checked that the messages need to be in Toasts // or for groups which have enabled "Show notice for this set" and in the settingpage of CS is checked that the messages need to be in Nearby Chat static LLCachedControl<bool> OnlineOfflinetoNearbyChat(gSavedSettings, "OnlineOfflinetoNearbyChat"); static LLCachedControl<bool> FSContactSetsNotificationNearbyChat(gSavedSettings, "FSContactSetsNotificationNearbyChat"); if ((OnlineOfflinetoNearbyChat) || (FSContactSetsNotificationNearbyChat && LGGContactSets::getInstance()->notifyForFriend(agent_id))) { static LLCachedControl<bool> history_only(gSavedSettings, "OnlineOfflinetoNearbyChatHistory"); // LO - Adding a setting to show online/offline notices only in chat history. Helps prevent your screen from being filled with online notices on login. LLChat chat; chat.mText = (online ? LLTrans::getString("FriendOnlineNotification") : LLTrans::getString("FriendOfflineNotification")); chat.mSourceType = CHAT_SOURCE_SYSTEM; chat.mChatType = CHAT_TYPE_RADAR; chat.mFromID = agent_id; chat.mFromName = used_name; if (history_only) { FSFloaterNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<FSFloaterNearbyChat>("fs_nearby_chat", LLSD()); nearby_chat->addMessage(chat, true, LLSD()); } else { LLNotificationsUI::LLNotificationManager::instance().onChat(chat, args); } // <FS:PP> FIRE-10178: Keyword Alerts in group IM do not work unless the group is in the foreground (notification on receipt of IM) chat.mText = notify_msg; if (FSKeywords::getInstance()->chatContainsKeyword(chat, true)) { FSKeywords::notify(chat); } // </FS:PP> } } void LLAvatarTracker::formFriendship(const LLUUID& id) { if(id.notNull()) { LLRelationship* buddy_info = get_ptr_in_map(instance().mBuddyInfo, id); if(!buddy_info) { LLAvatarTracker& at = LLAvatarTracker::instance(); //The default for relationship establishment is to have both parties //visible online to each other. buddy_info = new LLRelationship(LLRelationship::GRANT_ONLINE_STATUS,LLRelationship::GRANT_ONLINE_STATUS, false); at.mBuddyInfo[id] = buddy_info; at.addChangedMask(LLFriendObserver::ADD, id); at.notifyObservers(); } } } void LLAvatarTracker::processTerminateFriendship(LLMessageSystem* msg, void**) { LLUUID id; msg->getUUID("ExBlock", "OtherID", id); if(id.notNull()) { LLAvatarTracker& at = LLAvatarTracker::instance(); LLRelationship* buddy = get_ptr_in_map(at.mBuddyInfo, id); if(!buddy) return; at.mBuddyInfo.erase(id); at.addChangedMask(LLFriendObserver::REMOVE, id); delete buddy; at.notifyObservers(); } } ///---------------------------------------------------------------------------- /// Tracking Data ///---------------------------------------------------------------------------- LLTrackingData::LLTrackingData(const LLUUID& avatar_id, const std::string& name) : mAvatarID(avatar_id), mHaveInfo(false), mHaveCoarseInfo(false) { mCoarseLocationTimer.setTimerExpirySec(COARSE_FREQUENCY); mUpdateTimer.setTimerExpirySec(FIND_FREQUENCY); mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); if(!name.empty()) { mName = name; } } void LLTrackingData::agentFound(const LLUUID& prey, const LLVector3d& estimated_global_pos) { if(prey != mAvatarID) { LL_WARNS() << "LLTrackingData::agentFound() - found " << prey << " but looking for " << mAvatarID << LL_ENDL; } mHaveInfo = true; mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); mGlobalPositionEstimate = estimated_global_pos; } bool LLTrackingData::haveTrackingInfo() { LLViewerObject* object = gObjectList.findObject(mAvatarID); if(object && !object->isDead()) { mCoarseLocationTimer.checkExpirationAndReset(COARSE_FREQUENCY); mUpdateTimer.setTimerExpirySec(FIND_FREQUENCY); mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); mHaveInfo = true; return true; } if(mHaveCoarseInfo && !mCoarseLocationTimer.checkExpirationAndReset(COARSE_FREQUENCY)) { // if we reach here, then we have a 'recent' coarse update mUpdateTimer.setTimerExpirySec(FIND_FREQUENCY); mAgentGone.setTimerExpirySec(OFFLINE_SECONDS); return true; } if(mUpdateTimer.checkExpirationAndReset(FIND_FREQUENCY)) { LLAvatarTracker::instance().findAgent(); mHaveCoarseInfo = false; } if(mAgentGone.checkExpirationAndReset(OFFLINE_SECONDS)) { mHaveInfo = false; mHaveCoarseInfo = false; } return mHaveInfo; } void LLTrackingData::setTrackedCoarseLocation(const LLVector3d& global_pos) { mCoarseLocationTimer.setTimerExpirySec(COARSE_FREQUENCY); mGlobalPositionEstimate = global_pos; mHaveInfo = true; mHaveCoarseInfo = true; } ///---------------------------------------------------------------------------- // various buddy functors ///---------------------------------------------------------------------------- bool LLCollectProxyBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { if(buddy->isRightGrantedFrom(LLRelationship::GRANT_MODIFY_OBJECTS)) { mProxy.insert(buddy_id); } return true; } bool LLCollectMappableBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { LLAvatarName av_name; LLAvatarNameCache::get( buddy_id, &av_name); buddy_map_t::value_type value(buddy_id, av_name.getDisplayName()); if(buddy->isOnline() && buddy->isRightGrantedFrom(LLRelationship::GRANT_MAP_LOCATION)) { // <FS:Ansariel> Friend names on worldmap should respect display name settings //mMappable.insert(value); // <FS:PP> Attempt to speed up things a little // if (LLAvatarNameCache::useDisplayNames() && gSavedSettings.getBOOL("NameTagShowUsernames")) static LLCachedControl<bool> NameTagShowUsernames(gSavedSettings, "NameTagShowUsernames"); if (LLAvatarName::useDisplayNames() && NameTagShowUsernames) // </FS:PP> { buddy_map_t::value_type value(buddy_id, av_name.getCompleteName()); mMappable.insert(value); } else { buddy_map_t::value_type value(buddy_id, av_name.getDisplayName()); mMappable.insert(value); } // </FS:Ansariel> } return true; } bool LLCollectOnlineBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { LLAvatarName av_name; LLAvatarNameCache::get(buddy_id, &av_name); mFullName = av_name.getUserName(); buddy_map_t::value_type value(buddy_id, mFullName); if(buddy->isOnline()) { mOnline.insert(value); } return true; } bool LLCollectAllBuddies::operator()(const LLUUID& buddy_id, LLRelationship* buddy) { LLAvatarName av_name; LLAvatarNameCache::get(buddy_id, &av_name); // <FS:Ansariel> FIRE-13756: Friends avatar picker only shows display name //mFullName = av_name.getDisplayName(); mFullName = FSCommon::getAvatarNameByDisplaySettings(av_name); // </FS:Ansariel> buddy_map_t::value_type value(buddy_id, mFullName); if(buddy->isOnline()) { mOnline.insert(value); } else { mOffline.insert(value); } return true; }
30.32037
248
0.719966
753acc92fb7bcfa2bc75b5a5260671e628e0ce24
8,866
cpp
C++
x86/vm/ops/store.cpp
zero-rp/ZVM
66319025a4dfff813e580f68a0183841de9a72cd
[ "MIT" ]
9
2019-03-08T07:56:12.000Z
2021-03-06T01:57:43.000Z
x86/vm/ops/store.cpp
zero-rp/ZVM
66319025a4dfff813e580f68a0183841de9a72cd
[ "MIT" ]
null
null
null
x86/vm/ops/store.cpp
zero-rp/ZVM
66319025a4dfff813e580f68a0183841de9a72cd
[ "MIT" ]
2
2019-03-16T12:47:05.000Z
2019-09-15T15:03:50.000Z
/** Copyright (c) 2007 - 2010 Jordan "Earlz/hckr83" Earls <http://www.Earlz.biz.tm> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file is part of the x86Lib project. **/ #include <x86lib.h> namespace x86Lib { using namespace std; void x86CPU::op_mov_r8_imm8() { //0xB0+r SetReg8(opbyte - 0xB0, ReadCode8(1)); eip++; } void x86CPU::op_mov_rW_immW() { //0xB8+r SetReg(opbyte - 0xB8, ReadCodeW(1)); eip += OperandSize(); } void x86CPU::op_mov_sr_rm16() { //0x8E ModRM rm(this); //need ModRM for parsing, but otherwise it's a no-op } void x86CPU::op_mov_rm16_sr() { //0x8C ModRM rm(this); rm.WriteWord(0); } void x86CPU::op_mov_rW_rmW() { ModRM rm(this); SetReg(rm.GetExtra(), rm.ReadW()); } void x86CPU::op_mov_rmW_rW() { ModRM rm(this); rm.WriteW(Reg(rm.GetExtra())); } void x86CPU::op_mov_al_m8() { SetReg8(AL, ReadByteA(DS, ImmA())); } void x86CPU::op_mov_axW_mW() { SetReg(AX, ReadWA(DS, ImmA())); } void x86CPU::op_mov_rm8_r8() { ModRM rm(this); rm.WriteByte(Reg8(rm.GetExtra())); } void x86CPU::op_mov_r8_rm8() { ModRM rm(this); SetReg8(rm.GetExtra(), rm.ReadByte()); } void x86CPU::op_mov_m8_al() { WriteByte(DS, ImmA(), Reg8(AL)); } void x86CPU::op_mov_mW_axW() { WriteWA(DS, ImmA(), Reg(AX)); } void x86CPU::op_mov_rm8_imm8() { ModRM rm(this); //eventually fix this so that if r is used, then invalid opcode... rm.WriteByte(ReadByte(cCS, eip + rm.GetLength())); eip++; } void x86CPU::op_mov_rmW_immW() { ModRM rm(this); rm.WriteW(ReadW(cCS, eip + rm.GetLength())); eip += OperandSize(); } void x86CPU::op_lds() { throw new CpuInt_excp(GPF_IEXCP); } void x86CPU::op_les() { throw new CpuInt_excp(GPF_IEXCP); } void x86CPU::op_lea() { ModRM rm(this); SetReg(rm.GetExtra(), rm.ReadOffset()); } void x86CPU::op_push_imm8() { Push(ReadCode8(1)); eip++; } void x86CPU::op_push_rmW(ModRM &rm) { Push(rm.ReadW()); } void x86CPU::op_push_immW() { //0x68 Push(ImmW()); } void x86CPU::op_push_rW() { //0x50+reg Push(Reg(opbyte - 0x50)); } void x86CPU::op_push_es() { Push(0); } void x86CPU::op_push_cs() { Push(0); } void x86CPU::op_push_ds() { Push(0); } void x86CPU::op_push_ss() { Push(0); } void x86CPU::op_push_fs() { Push(0); } void x86CPU::op_push_gs() { Push(0); } void x86CPU::op_pop_rmW(ModRM &rm) { rm.WriteW(Pop()); } void x86CPU::op_pop_rW() { //0x58+reg SetReg(opbyte - 0x58, Pop()); } void x86CPU::op_pop_es() { Pop(); } void x86CPU::op_pop_ss() { Pop(); } void x86CPU::op_pop_ds() { Pop(); } void x86CPU::op_pop_fs() { Pop(); } void x86CPU::op_pop_gs() { Pop(); } void x86CPU::op_out_imm8_al() { uint8_t tmp = Reg8(AL); Ports->Write(ReadCode8(1), 1, &tmp); eip++; } void x86CPU::op_out_imm8_axW() { uint32_t tmp = Reg(AX); if (OperandSize16) { Ports->Write(ReadCode8(1), 2, (void*)&tmp); } else { Ports->Write(ReadCode8(1), 4, (void*)&tmp); } eip++; } void x86CPU::op_out_dx_al() { uint8_t tmp = Reg8(AL); Ports->Write(Reg16(DX), 1, (void*)&tmp); } void x86CPU::op_out_dx_axW() { uint32_t tmp = Reg(AX); if (OperandSize16) { Ports->Write(Reg16(DX), 2, (void*)&tmp); } else { Ports->Write(Reg16(DX), 4, (void*)&tmp); } } void x86CPU::op_in_al_imm8() { uint8_t tmp; Ports->Read(ReadCode8(1), 1, (void*)&tmp); SetReg8(AL, tmp); eip++; } void x86CPU::op_in_axW_imm8() { uint32_t tmp; if (OperandSize16) { Ports->Read(ReadCode8(1), 2, (void*)&tmp); } else { Ports->Read(ReadCode8(1), 4, (void*)&tmp); } SetReg(AX, tmp); eip++; } void x86CPU::op_in_al_dx() { uint8_t tmp; Ports->Read(Reg16(DX), 1, (void*)&tmp); SetReg8(AL, tmp); } void x86CPU::op_in_axW_dx() { uint32_t tmp; if (OperandSize16) { Ports->Read(Reg16(DX), 2, (void*)&tmp); } else { Ports->Read(Reg16(DX), 4, (void*)&tmp); } SetReg(AX, tmp); } void x86CPU::op_xchg_rm8_r8() { #ifndef X86_MULTITHREADING if (IsLocked() == 1) { eip--; return; } #endif Lock(); ModRM rm(this); uint8_t tmp = Reg8(rm.GetExtra()); SetReg8(rm.GetExtra(), rm.ReadByte()); rm.WriteByte(tmp); Unlock(); } void x86CPU::op_xchg_rmW_rW() { #ifndef X86_MULTITHREADING if (IsLocked() == 1) { eip--; return; } #endif Lock(); ModRM rm(this); uint32_t tmp = Reg(rm.GetExtra()); SetReg(rm.GetExtra(), rm.ReadW()); rm.WriteW(tmp); Unlock(); } void x86CPU::op_xchg_axW_rW() { //0x90+r uint32_t tmp = Reg(AX); SetReg(AX, Reg(opbyte - 0x90)); SetReg(opbyte - 0x90, tmp); } void x86CPU::op_xlatb() { SetReg8(AL, ReadByteA(DS, RegA(BX) + (Reg8(AL)))); } void x86CPU::op_movzx_rW_rm8() { ModRM rm(this); SetReg(rm.GetExtra(), rm.ReadByte()); } void x86CPU::op_movzx_r32_rmW() { ModRM rm(this); regs32[rm.GetExtra()] = rm.ReadWord(); } void x86CPU::op_pushaW() { uint32_t tmp; tmp = Reg(SP); Push(Reg(AX)); Push(Reg(CX)); Push(Reg(DX)); Push(Reg(BX)); Push(tmp); Push(Reg(BP)); Push(Reg(SI)); Push(Reg(DI)); } void x86CPU::op_popaW() { uint32_t ofs = 0; if (OperandSize16) { ofs = 2; } else { ofs = 4; } SetReg(DI, Pop()); SetReg(SI, Pop()); SetReg(BP, Pop()); SetReg(SP, Reg(SP) + ofs); SetReg(BX, Pop()); SetReg(DX, Pop()); SetReg(CX, Pop()); SetReg(AX, Pop()); } void x86CPU::op_enter() { uint16_t size = ReadCode16(1); eip += 2; uint8_t nestingLevel = ReadCode8(1) % 32; eip += 1; Push(Reg(EBP)); uint32_t frameTemp = Reg(ESP); for (int i = 1; i < nestingLevel; ++i) { if (OperandSize16) { SetReg(EBP, Reg(EBP) - 2); } else { SetReg(EBP, Reg(EBP) - 4); } Push(Reg(EBP)); } if (nestingLevel > 0) { Push(frameTemp); } SetReg(EBP, frameTemp); SetReg(ESP, Reg(EBP) - size); } void x86CPU::op_leave() { SetReg(ESP, Reg(EBP)); SetReg(EBP, Pop()); } void x86CPU::op_movsx_rW_rm8() { ModRM rm(this); SetReg(rm.GetExtra(), SignExtend8to32(rm.ReadByte())); } void x86CPU::op_pushf() { Push(freg.data); } void x86CPU::op_popf() { freg.data = Pop(); } };
22.733333
80
0.533724
753bebc066f0f4bc0f6d4b49bfbc299d14e4cafe
8,167
cpp
C++
src/engine/map2d/map2disoobjectslayer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/map2d/map2disoobjectslayer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/map2d/map2disoobjectslayer.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file map2disoobjectslayer.cpp * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2001-12-25 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/map2d/map2disoobjectslayer.h" #include "o3d/engine/map2d/map2dvisibility.h" #include "o3d/engine/scene/scene.h" #include "o3d/engine/object/camera.h" #include "o3d/engine/context.h" #include <algorithm> using namespace o3d; O3D_IMPLEMENT_DYNAMIC_CLASS1(Map2dIsoObjectsLayer, ENGINE_MAP_2D_OBJECT_LAYER, Map2dLayer) Map2dIsoObjectsLayer::Map2dIsoObjectsLayer( BaseObject *parent, const Box2i &area, UInt32 maxDepth, UInt32 maxObjectsPerCell) : Map2dLayer(parent), m_sort(True), m_box(area), m_visibility(nullptr) { m_visibility = new Map2dVisibility( area.pos(), nextPow2(max(area.width(), area.height())), max((UInt32)1, maxDepth), maxObjectsPerCell); } Map2dIsoObjectsLayer::~Map2dIsoObjectsLayer() { m_visibility->clear(); IT_Map2dObjectList it = m_objects.begin(); while (it != m_objects.end()) { deletePtr(*it); ++it; } deletePtr(m_visibility); } Bool Map2dIsoObjectsLayer::deleteChild(BaseObject *child) { if (child) { if (child->getParent() != this) O3D_ERROR(E_InvalidParameter("The parent child differ from this")); else { // object should be type of Map2dObject Map2dObject *object = dynamicCast<Map2dObject*>(child); if (object) { IT_Map2dObjectList it = m_objects.begin(); for (; it != m_objects.end(); ++it) { if ((*it) == object) break; } // remove the object of the son list if (it != m_objects.end()) { // remove it from the quadtree if (m_visibility != nullptr) m_visibility->removeObject(object); m_sort = True; m_objects.erase(it); object->setNode(nullptr); } deletePtr(object); } else { // otherwise simply delete it deletePtr(child); } return True; } } return False; } UInt32 Map2dIsoObjectsLayer::getNumElt() const { return m_objects.size(); } const Transform *Map2dIsoObjectsLayer::getTransform() const { return nullptr; } Transform *Map2dIsoObjectsLayer::getTransform() { return nullptr; } void Map2dIsoObjectsLayer::update() { if (!getActivity()) return; clearUpdated(); Bool dirty = False; if (getNode() && getNode()->hasUpdated()) { // the parent has change so the child need to be updated dirty = True; } if (dirty) { setUpdated(); } // check if a sort is necessary at the next draw m_sort |= m_visibility->hasUpdated(); m_visibility->clearUpdated(); /* // update each son (recursively if necessary) TODO optimize that for (IT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { Map2dObject *object = (*it); if (object->getActivity()) { // compute object absolute matrix object->update(); if (object->hasUpdated()) { // only for drawable and dynamic objects if (object->hasDrawable()) { m_visibility->updateObject(object); m_sort = True; } } } }*/ } void Map2dIsoObjectsLayer::draw(const DrawInfo &drawInfo) { if (!m_capacities.getBit(STATE_ACTIVITY) || !m_capacities.getBit(STATE_VISIBILITY)) return; setUpModelView(); if (getScene()->getDrawObject(Scene::DRAW_MAP_2D_LAYER)) { // TODO Symbolics a quad in red } Camera *camera = getScene()->getActiveCamera(); // process to a sort on the visible area if necessary if (m_sort || camera->isCameraChanged()) { Vector3 camPos = camera->getAbsoluteMatrix().getTranslation(); Box2i viewport( camPos.x() - (-camera->getLeft() + camera->getRight()) / 2, camPos.y() - (camera->getBottom() - camera->getTop()) / 2, -camera->getLeft() + camera->getRight(), camera->getBottom() - camera->getTop()); m_drawList.clear(); /*UInt32 rejected = */m_visibility->checkVisibleObject(viewport); T_Map2dObjectList &drawList = m_visibility->getDrawList(); m_drawList.reserve(drawList.size()); // inject for sort for (Map2dObject *object : drawList) { m_drawList.push_back(object); } std::sort(m_drawList.begin(), m_drawList.end(), &Map2dObject::compare); m_sort = False; //System::print(String::print("rejected object=%u", rejected), ""); //System::print(m_visibility->getTreeView(), ""); } for (Map2dObject *object : m_drawList) { object->draw(drawInfo); } } UInt32 Map2dIsoObjectsLayer::getNumSon() const { return m_objects.size(); } Bool Map2dIsoObjectsLayer::hasSon(SceneObject *object) const { CIT_Map2dObjectList cit = m_objects.begin(); for (; cit != m_objects.cend(); ++cit) { if ((*cit) == object) return True; } return False; } SceneObject* Map2dIsoObjectsLayer::findSon(const String &name) { if (getName() == name) return this; for (IT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { SceneObject *object = (*it); if (object->isNodeObject()) { SceneObject *result = ((BaseNode*)object)->findSon(name); if (result) return result; } else if (object->getName() == name) return object; } return nullptr; } const SceneObject* Map2dIsoObjectsLayer::findSon(const String &name) const { if (getName() == name) return this; for (CIT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { const SceneObject *object = (*it); if (object->isNodeObject()) { const SceneObject *result = ((BaseNode*)object)->findSon(name); if (result) return result; } else if (object->getName() == name) return object; } return nullptr; } Bool Map2dIsoObjectsLayer::findSon(SceneObject *object) const { if (this == object) return True; for (CIT_Map2dObjectList it = m_objects.begin(); it != m_objects.end(); ++it) { const SceneObject *search = (*it); if (search->isNodeObject()) { Bool result = ((BaseNode*)search)->findSon(object); if (result) return True; } else if (search == object) return True; } return False; } const T_Map2dObjectList &Map2dIsoObjectsLayer::getObjects() { return m_objects; } const T_Map2dObjectList& Map2dIsoObjectsLayer::getVisiblesObjects() { return m_visibility->getDrawList(); } Bool Map2dIsoObjectsLayer::isObjectIntersect(const Box2i &box) const { return m_visibility->isObjectIntersect(box); } Bool Map2dIsoObjectsLayer::isObjectBaseIntersect(const Map2dObject *from) const { return m_visibility->isObjectBaseIntersect(from); } Map2dObject* Map2dIsoObjectsLayer::addObject( const String &name, const Vector2i &pos, const Rect2i &baseRect, Map2dTileSet *tileSet, UInt32 tileId) { Map2dObject *object = new Map2dObject(this); object->setName(name); object->setNode(this); object->setTile(tileSet, tileId); object->setBaseRect(baseRect); object->setPos(pos); m_objects.push_back(object); m_sort = True; m_visibility->addObject(object); return object; } // remove a specified son void Map2dIsoObjectsLayer::removeObject(Map2dObject *object) { IT_Map2dObjectList it = m_objects.begin(); for (; it != m_objects.end(); ++it) { if ((*it) == object) break; } if (it == m_objects.end()) { O3D_ERROR(E_InvalidParameter("Object not found")); } else { m_visibility->removeObject(object); // remove the object of the son list m_objects.erase(it); // no node object->setParent(getScene()); object->setNode(nullptr); object->setPersistant(False); m_sort = True; } } void Map2dIsoObjectsLayer::updateObject(Map2dObject *object) { } //void Map2dIsoObjectsLayer::moveObject(Map2dObject *object, const Vector2i &pos) //{ // if (object != nullptr) // { // object->setPos(pos); // m_visibility->updateObject(object); // } //} // Remove all sons (delete objects if no longer used) void Map2dIsoObjectsLayer::deleteAllObjects() { IT_Map2dObjectList it = m_objects.begin(); while (it != m_objects.end()) { deletePtr(*it); ++it; } m_objects.clear(); m_visibility->clear(); m_sort = True; }
20.623737
90
0.668177
753f1e0eb88b1ed2be6875a7cfba33cf116bbc4d
14,916
cpp
C++
addons/ofxCvGui/src/ofxCvGui/Controller.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxCvGui/src/ofxCvGui/Controller.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
addons/ofxCvGui/src/ofxCvGui/Controller.cpp
syeminpark/openFrame
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
[ "MIT" ]
null
null
null
#include "pch_ofxCvGui.h" //---------- OFXSINGLETON_DEFINE(ofxCvGui::Controller); namespace ofxCvGui { //---------- Controller::Controller() { this->maximised = false; this->chromeVisible = true; this->mouseOwner = nullptr; this->lastClickOwner = nullptr; this->lastMouseClick = pair<long long, ofMouseEventArgs>(std::numeric_limits<long long>::min(), ofMouseEventArgs()); this->cachedWidth = 0.0f; this->cachedHeight = 0.0f; } //---------- void Controller::init(shared_ptr<Panels::Groups::Base> rootGroup) { ofBackground(30); ofAddListener(ofEvents().update, this, &Controller::update); ofAddListener(ofEvents().draw, this, &Controller::draw); ofAddListener(ofEvents().mouseMoved, this, &Controller::mouseMoved); ofAddListener(ofEvents().mousePressed, this, &Controller::mousePressed); ofAddListener(ofEvents().mouseReleased, this, &Controller::mouseReleased); ofAddListener(ofEvents().mouseDragged, this, &Controller::mouseDragged); ofAddListener(ofEvents().mouseScrolled, this, &Controller::mouseScrolled); ofAddListener(ofEvents().keyPressed, this, &Controller::keyPressed); ofAddListener(ofEvents().keyReleased, this, &Controller::keyReleased); ofAddListener(ofEvents().fileDragEvent, this, &Controller::filesDragged); ofAddListener(ofEvents().windowResized, this, &Controller::windowResized); ofAddListener(ofEvents().exit, this, &Controller::exit, 0); ofxAssets::Register::X().addAddon("ofxCvGui"); rootGroup->setBounds(ofGetCurrentViewport()); this->rootGroup = rootGroup; this->currentPanel = PanelPtr(); this->currentPanelBounds = ofGetCurrentViewport(); //cache fonts ofxAssets::font("ofxCvGui::swisop3", 12); ofxAssets::font("ofxCvGui::swisop3", 14); ofxAssets::font("ofxCvGui::swisop3", 18); ofxAssets::font("ofxCvGui::swisop3", 24); } //---------- void Controller::add(PanelPtr panel) { if (!this->rootGroup) return; this->rootGroup->add(panel); } //---------- void Controller::remove(PanelPtr panel) { if (!this->rootGroup) return; this->rootGroup->remove(panel); } //---------- void Controller::clear() { if (!this->rootGroup) return; this->rootGroup->clear(); } //---------- void Controller::toggleFullscreen() { ofToggleFullscreen(); } //---------- void Controller::toggleMaximised() { if (!this->maximised) { //maximise current panel auto currentPanel = this->currentPanel.lock(); if (currentPanel) { this->setMaximised(currentPanel); currentPanel->setBounds(ofGetCurrentViewport()); } } else { //clear maximise this->clearMaximised(); } } //---------- void Controller::setMaximised(PanelPtr panel) { this->maximised = true; this->currentPanel = panel; this->currentPanelBounds = ofGetCurrentViewport(); panel->setBounds(ofRectangle(0, 0, ofGetScreenWidth(), ofGetScreenHeight())); } //---------- void Controller::clearMaximised() { this->maximised = false; rootGroup->setBounds(ofGetCurrentViewport()); this->updateCurrentPanel(); } //---------- void Controller::showChrome() { this->chromeVisible = true; } //---------- void Controller::hideChrome() { this->chromeVisible = false; } //---------- void Controller::setActiveDialog(PanelPtr panel) { if (panel) { auto bounds = ofGetCurrentViewport(); //first get a cached draw for the background this->activeDialogBackground.grabScreen(0, 0, ofGetWindowWidth(), ofGetWindowHeight()); //setup the active Dialog this->activeDialog = panel; //setup the size of the Dialog ofResizeEventArgs resizeArgs = { ofGetViewportWidth(), ofGetViewportHeight() }; this->windowResized(resizeArgs); } else { this->closeActiveDialog(); } } //---------- void Controller::closeActiveDialog() { if (this->activeDialog) { this->onDialogClose.notifyListeners(this->activeDialog); this->activeDialog.reset(); //setup the size of the root group ofResizeEventArgs resizeArgs = { ofGetViewportWidth(), ofGetViewportHeight() }; this->windowResized(resizeArgs); } } //---------- bool Controller::isDialogOpen() { return (this->activeDialog.get()); } //---------- void Controller::update(ofEventArgs& args) { if (!this->rootGroup) { return; } InspectController::X().update(); if (this->activeDialog) { this->activeDialog->update(); } else if (this->maximised) { this->currentPanel.lock()->update(); } else { rootGroup->update(); } } //---------- void Controller::draw(ofEventArgs& args) { if (!this->rootGroup) { return; } DrawArguments rootDrawArguments; rootDrawArguments.chromeEnabled = this->chromeVisible; rootDrawArguments.naturalBounds = ofGetCurrentViewport(); rootDrawArguments.globalTransform = glm::mat4(); rootDrawArguments.globalScale = 1.0f; rootDrawArguments.localBounds = ofRectangle(0, 0, rootDrawArguments.naturalBounds.getWidth(), rootDrawArguments.naturalBounds.getHeight()); rootDrawArguments.globalBounds = rootDrawArguments.naturalBounds; auto currentPanel = this->currentPanel.lock(); if (this->activeDialog) { this->activeDialogBackground.draw(rootDrawArguments.naturalBounds); ofPushStyle(); { //draw light box background ofEnableAlphaBlending(); ofSetColor(0, 200); ofDrawRectangle(rootDrawArguments.naturalBounds); //shadow for dialog ofFill(); ofSetColor(0, 100); ofPushMatrix(); { ofTranslate(5, 5); ofDrawRectangle(this->activeDialog->getBounds()); } ofPopMatrix(); //background for dialog ofSetColor(80); ofDrawRectangle(this->activeDialog->getBounds()); } ofPopStyle(); this->activeDialog->draw(rootDrawArguments); } else { if (this->maximised) { currentPanel->draw(rootDrawArguments); } else { //highlight panel if (currentPanel) { ofPushStyle(); ofEnableAlphaBlending(); ofSetColor(40, 40, 40, 100); ofDrawRectangle(this->currentPanelBounds); ofPopStyle(); } this->rootGroup->draw(rootDrawArguments); } } for (const auto & delayedDrawCommand : this->delayedDrawCommands) { delayedDrawCommand(); } this->delayedDrawCommands.clear(); } //---------- void Controller::exit(ofEventArgs & args) { this->rootGroup.reset(); ofRemoveListener(ofEvents().update, this, &Controller::update); ofRemoveListener(ofEvents().draw, this, &Controller::draw); ofRemoveListener(ofEvents().mouseMoved, this, &Controller::mouseMoved); ofRemoveListener(ofEvents().mousePressed, this, &Controller::mousePressed); ofRemoveListener(ofEvents().mouseReleased, this, &Controller::mouseReleased); ofRemoveListener(ofEvents().mouseDragged, this, &Controller::mouseDragged); ofRemoveListener(ofEvents().keyPressed, this, &Controller::keyPressed); ofRemoveListener(ofEvents().keyReleased, this, &Controller::keyReleased); ofRemoveListener(ofEvents().fileDragEvent, this, &Controller::filesDragged); ofRemoveListener(ofEvents().windowResized, this, &Controller::windowResized); } //---------- PanelGroupPtr Controller::getRootGroup() const { return this->rootGroup; } //---------- void Controller::setRootGroup(PanelGroupPtr rootGroup) { this->rootGroup = rootGroup; this->rootGroup->arrange(); } //---------- PanelPtr Controller::getPanelUnderCursor(const glm::vec2 & position) { if (this->maximised) { return currentPanel.lock(); } else { ofRectangle panelBounds = this->rootGroup->getBounds(); return this->findPanelUnderCursor(panelBounds, position); } } //---------- void Controller::drawDelayed(function<void()> && drawFunction) { this->delayedDrawCommands.emplace_back(drawFunction); } //---------- void Controller::mouseMoved(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); MouseArguments action(MouseArguments(args, MouseArguments::Moved, rootGroup->getBounds(), currentPanel, this->mouseOwner)); this->mouseAction(action); this->updateCurrentPanel(); } //---------- void Controller::mousePressed(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto thisMouseClick = pair<long long, ofMouseEventArgs>(ofGetElapsedTimeMillis(), args); bool isDoubleClick = (thisMouseClick.first - this->lastMouseClick.first) < OFXCVGUI_DOUBLECLICK_TIME_THRESHOLD_MS; auto distanceSinceLastClick = glm::distance( (glm::vec2) thisMouseClick.second, (glm::vec2) this->lastMouseClick.second ); isDoubleClick &= distanceSinceLastClick < OFXCVGUI_DOUBLECLICK_SPACE_THRESHOLD_PX; if (isDoubleClick) { this->mouseOwner = this->lastClickOwner; } auto currentPanel = this->currentPanel.lock(); auto action = MouseArguments(args, isDoubleClick ? MouseArguments::Action::DoubleClick : MouseArguments::Action::Pressed, rootGroup->getBounds(), currentPanel, this->mouseOwner); if (this->activeDialog && !this->activeDialog->getBounds().inside(action.local)) { this->closeActiveDialog(); } else { this->mouseAction(action); } this->mouseCached = action.global; this->mouseOwner = action.getOwner(); this->lastMouseClick = thisMouseClick; } //---------- void Controller::mouseReleased(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); MouseArguments action(args, MouseArguments::Released, rootGroup->getBounds(), currentPanel, this->mouseOwner); this->mouseAction(action); this->lastClickOwner = this->mouseOwner; this->mouseOwner = nullptr; } //---------- void Controller::mouseDragged(ofMouseEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); MouseArguments action(args, MouseArguments::Dragged, rootGroup->getBounds(), currentPanel, this->mouseOwner, mouseCached); this->mouseAction(action); this->mouseCached = action.global; } //---------- void Controller::mouseScrolled(ofMouseEventArgs& args) { if (!this->rootGroup) { return; } auto panelUnderCursor = this->getPanelUnderCursor(args); if (panelUnderCursor) { MouseArguments action(args, MouseArguments::Scrolled, rootGroup->getBounds(), panelUnderCursor, this->mouseOwner, mouseCached); this->mouseAction(action); } } //---------- void Controller::mouseAction(MouseArguments & action) { if (this->activeDialog) { this->activeDialog->mouseAction(action); } else { auto currentPanel = this->currentPanel.lock(); if (this->maximised) { currentPanel->mouseAction(action); } else { rootGroup->mouseAction(action); } } } //---------- void Controller::keyReleased(ofKeyEventArgs & args) { if (!this->rootGroup) { return; } auto currentPanel = this->currentPanel.lock(); KeyboardArguments action(args, KeyboardArguments::Released, currentPanel); if (this->activeDialog) { this->activeDialog->keyboardAction(action); } else { if (this->maximised) { //if something is maximised, only it get the key press currentPanel->keyboardAction(action); } else { //otherwise everything visible gets the key press rootGroup->keyboardAction(action); } } } void Controller::keyPressed(ofKeyEventArgs & args) { if (!this->rootGroup) { return; } if (args.key == 0) { // This sometimes happens with mouse button 4 return; } if (!this->activeDialog) { if (args.key == 'f') this->toggleFullscreen(); if (args.key == 'm') this->toggleMaximised(); } auto currentPanel = this->currentPanel.lock(); KeyboardArguments action(args, KeyboardArguments::Pressed, currentPanel); if (this->activeDialog) { if (args.key == OF_KEY_ESC) { this->closeActiveDialog(); } else { this->activeDialog->keyboardAction(action); } } else { if (this->maximised) { //if something is maximised, only it get the key press currentPanel->keyboardAction(action); } else { //otherwise everything visible gets the key press rootGroup->keyboardAction(action); } } } //---------- void Controller::filesDragged(ofDragInfo & args) { if (!this->rootGroup) { return; } auto rootBounds = this->rootGroup->getBounds(); auto panel = this->findPanelUnderCursor(rootBounds); if (panel != PanelPtr()) { auto panelBounds = panel->getBounds(); auto panelTopLeft = panelBounds.getTopLeft(); auto newArgs = FilesDraggedArguments((glm::vec2) args.position - panelTopLeft, (glm::vec2) args.position, args.files); panel->onFilesDragged(newArgs); } } //---------- void Controller::windowResized(ofResizeEventArgs & args) { if (!this->rootGroup) { return; } const auto viewportBounds = ofRectangle(0, 0, args.width, args.height); if (this->activeDialog) { const auto padding = 80.0f; ofRectangle bounds = viewportBounds; bounds.x += padding; bounds.y += padding; bounds.width -= padding * 2.0f; bounds.height -= padding * 2.0f; //if bounds are too small, use all of it if (bounds.width < 200 || bounds.height < 200) { bounds = viewportBounds; } this->activeDialog->setBounds(bounds); } else { auto currentPanel = this->currentPanel.lock(); if (this->maximised) { currentPanel->setBounds(viewportBounds); } else { this->rootGroup->setBounds(viewportBounds); } } } //---------- bool Controller::checkInitialised() { if (this->rootGroup) return true; else { ofLogError("ofxCvGui") << "cannot perform this action as gui is not initialised"; return false; } } //---------- PanelPtr Controller::findPanelUnderCursor(ofRectangle & panelBounds, const glm::vec2 & position) { if (!this->rootGroup) { return PanelPtr(); } if (this->activeDialog) { return activeDialog; } else if (this->maximised) { return this->currentPanel.lock(); } else { return rootGroup->findScreen(position, panelBounds); } } //---------- void Controller::updateCurrentPanel() { if (!this->maximised) { auto currentPanelBounds = this->rootGroup->getBounds(); this->currentPanel = this->findPanelUnderCursor(currentPanelBounds); this->currentPanelBounds = currentPanelBounds; } } //---------- ofxCvGui::PanelPtr Controller::getActiveDialog() { return this->activeDialog; } //---------- void openDialog(PanelPtr panel) { Controller::X().setActiveDialog(panel); } //---------- void closeDialog(Panels::Base * panel) { if (Controller::X().getActiveDialog().get() == panel) { Controller::X().closeActiveDialog(); } } //---------- void closeDialog() { Controller::X().closeActiveDialog(); } //---------- bool isDialogOpen() { return Controller::X().isDialogOpen(); } }
26.635714
180
0.669482
7541639e7eebe2db9694f668a355f034bb9fab99
370
cpp
C++
acmicpc.net/9461.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
4
2016-04-15T07:54:39.000Z
2021-01-11T09:02:16.000Z
acmicpc.net/9461.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
acmicpc.net/9461.cpp
kbu1564/SimpleAlgorithm
7e5b0d2fe19461417d88de0addd2235da55787d3
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> using namespace std; int t,n; long long int A[101] = { 1, 1, 1, 0 }; int main() { scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d", &n); for (int j = 3; j < n; j++) { A[j] = A[j-3] + A[j-2]; } printf("%lld\n", A[n-1]); } return 0; }
17.619048
38
0.486486
754603bd2a3852c0186f083b10dab76446692a11
3,847
cpp
C++
bgcc/nb_data_buffer.cpp
duzhanyuan/testbdrpc
da572ea2dcb81985d65214819a834ccfbc89262d
[ "BSD-3-Clause" ]
8
2018-01-31T05:20:46.000Z
2021-06-11T17:45:34.000Z
bgcc/nb_data_buffer.cpp
duzhanyuan/testbdrpc
da572ea2dcb81985d65214819a834ccfbc89262d
[ "BSD-3-Clause" ]
null
null
null
bgcc/nb_data_buffer.cpp
duzhanyuan/testbdrpc
da572ea2dcb81985d65214819a834ccfbc89262d
[ "BSD-3-Clause" ]
31
2017-05-10T19:32:40.000Z
2021-06-16T13:22:22.000Z
/*********************************************************************** * Copyright (c) 2012, Baidu Inc. All rights reserved. * * Licensed under the BSD License * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * license.txt *********************************************************************/ #ifndef _WIN32 #include <netinet/in.h> #endif #include <string.h> #include "nb_data_buffer.h" #include "byte_order.h" #include "bgcc_error.h" namespace bgcc { NBDataBuffer::NBDataBuffer() :_size(0), _maxsize(0), _data(NULL) { } NBDataBuffer::~NBDataBuffer() { clear(); } int32_t NBDataBuffer::append_bool(bool b) { uint8_t tmp = b ? 1 : 0; return append(&tmp, sizeof(uint8_t)); } int32_t NBDataBuffer::append_int8(int8_t i8) { return append(&i8, sizeof(int8_t)); } int32_t NBDataBuffer::append_int16(int16_t i16) { uint16_t tmp = htons((uint16_t)i16); return append(&tmp, sizeof(uint16_t)); } int32_t NBDataBuffer::append_int32(int32_t i32) { uint32_t tmp = htonl((uint32_t)i32); return append(&tmp, sizeof(uint32_t)); } int32_t NBDataBuffer::append_int64(int64_t i64) { uint64_t tmp = HTONLL((uint64_t)i64); return append(&tmp, sizeof(uint64_t)); } int32_t NBDataBuffer::append_float(float f) { uint32_t tmp = htonl(*(uint32_t*)&f); return append(&tmp, sizeof(uint32_t)); } int32_t NBDataBuffer::append_string(const std::string& str) { int32_t ret; int32_t len = (int32_t)str.length(); ret = append_int32(len); if (0 != ret) { return ret; } return append(str.data(), len); } int32_t NBDataBuffer::append_binary(const void* buffer, int32_t buflen) { int32_t ret; ret = append_int32(buflen); if (0 != ret) { return ret; } return append(buffer, buflen); } int32_t NBDataBuffer::append(const void* buffer, int32_t buflen) { if (NULL == buffer) { return E_BGCC_NULL_POINTER; } if (buflen < 0) { return E_BGCC_INVALID_PARAM; } else if (0 == buflen) { return 0; } if (_size + buflen > _maxsize) { int32_t newsize = (buflen + _maxsize) * 2; void *ptr; ptr = realloc(_data, newsize); if (NULL == ptr) { newsize = _size + buflen; ptr = realloc(_data, newsize); if (NULL == ptr) { return E_BGCC_NOMEM; } } _data = ptr; _maxsize = newsize; } memcpy((char*)_data + _size, buffer, buflen); _size += buflen; return 0; } int32_t NBDataBuffer::get_data(void** ppdata, int32_t& size) { if (NULL == ppdata) { return E_BGCC_NULL_POINTER; } *ppdata = _data; size = _size; return 0; } int32_t NBDataBuffer::get_data_copy(void** ppdata, int32_t& size) { if (NULL == ppdata) { return E_BGCC_NULL_POINTER; } if (0 == _size) { *ppdata = NULL; } else { *ppdata = malloc(_size); if (NULL == *ppdata) { return E_BGCC_NOMEM; } else { memcpy(*ppdata, _data, _size); } } size = _size; return 0; } int32_t NBDataBuffer::clear(bool keepAllocatedMem) { _size = 0; if (NULL != _data && !keepAllocatedMem) { free(_data); _data = NULL; _maxsize = 0; } return 0; } }
24.819355
77
0.505329
75464bec70a43a9e4d4ef45a6b757513d15e8a95
446
cpp
C++
src/test/main_victim_test.cpp
davitkalantaryan/wlac-sources
0878d97df0900b16f72c63f187be44ae9bef8949
[ "MIT" ]
null
null
null
src/test/main_victim_test.cpp
davitkalantaryan/wlac-sources
0878d97df0900b16f72c63f187be44ae9bef8949
[ "MIT" ]
4
2021-10-05T05:28:22.000Z
2021-12-28T22:48:21.000Z
src/test/main_victim_test.cpp
davitkalantaryan/wlac-sources
0878d97df0900b16f72c63f187be44ae9bef8949
[ "MIT" ]
null
null
null
// // file: main_victim_test.cpp // created on: 2018 Dec 18 // #ifndef CINTERFACE #define CINTERFACE #endif // !CINTERFACE #include <WinSock2.h> #include <WS2tcpip.h> #include <Windows.h> #include <stdio.h> static volatile int s_nRun = 1; int main() { int nPid = GetCurrentProcessId(); printf("pid=%d, lodaLibraryAddress=%p\n", nPid,&LoadLibraryA); s_nRun = 1; while(s_nRun){ SleepEx(INFINITE, TRUE); } }
15.928571
64
0.64574
754b36c3ba2e2753bd7467e45a79c0e7acad2213
723
cpp
C++
emerald/util/tests/test_vector_util.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
3
2020-08-16T17:56:25.000Z
2021-02-25T21:55:39.000Z
emerald/util/tests/test_vector_util.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
emerald/util/tests/test_vector_util.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
#include <emerald/util/format.h> #include <emerald/util/foundation.h> #include <emerald/util/random.h> #include <emerald/util/vector_util.h> #include <fmt/format.h> #include <gtest/gtest.h> #include <cstdio> #include <cstdlib> #include <vector> namespace emerald::util { TEST(Test_vector_util, Print_hash_key) { V3d g; set_zero(g); UniformRand rand; std::vector<float> v; for (int i = 0; i < 100; ++i) { v.push_back(static_cast<float>(rand())); } auto const* const vdata = v.data(); for (int i = 0; i < 100; ++i) { fmt::print("{}\n", vdata[i]); } auto const vkey = ComputeVectorHashKey(v); fmt::print("Vector hash key: {}\n", FormatHashKey(vkey)); } } // namespace emerald::util
24.1
78
0.648686
754c73ea5c5b7b8b0f39c1ccc23a51d1287a1455
2,878
hh
C++
include/introvirt/windows/kernel/nt/types/PEB.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
include/introvirt/windows/kernel/nt/types/PEB.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
include/introvirt/windows/kernel/nt/types/PEB.hh
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <introvirt/core/memory/guest_ptr.hh> #include <introvirt/windows/kernel/nt/fwd.hh> #include <cstdint> #include <memory> namespace introvirt { namespace windows { namespace nt { /** * Parser for the Windows Process Environment Block (PEB) */ class PEB { public: /** * @returns The base address of the executable image */ virtual guest_ptr<void> ImageBaseAddress() const = 0; /** * @returns The PEB_LDR_DATA, containing information about loaded libraries and the exe itself */ virtual const PEB_LDR_DATA* Ldr() const = 0; virtual PEB_LDR_DATA* Ldr() = 0; /** * @return Information about the process environment */ virtual const RTL_USER_PROCESS_PARAMETERS* ProcessParameters() const = 0; virtual RTL_USER_PROCESS_PARAMETERS* ProcessParameters() = 0; /** * @returns The major version of the OS */ virtual uint32_t OSMajorVersion() const = 0; /** * @returns The minor version of the OS */ virtual uint32_t OSMinorVersion() const = 0; /** * @returns The build number of the OS */ virtual uint16_t OSBuildNumber() const = 0; /** * @returns The CSD version of the OS, containing service pack information */ virtual uint16_t OSCSDVersion() const = 0; /** * @returns The platform ID of the OS */ virtual uint32_t OSPlatformId() const = 0; /** * @returns The service pack number of the OS */ virtual uint16_t ServicePackNumber() const = 0; /** * @returns The minor service pack number of the OS */ virtual uint16_t MinorServicePackNumber() const = 0; /** * @returns The number of physical processors */ virtual uint32_t NumberOfProcessors() const = 0; /** * @returns The virtual address of the PEB in-guest */ virtual guest_ptr<void> ptr() const = 0; /** * @returns The value of the BeingDebugged field */ virtual bool BeingDebugged() const = 0; /** * @returns The value of the BeingDebugged field */ virtual void BeingDebugged(bool BeingDebugged) = 0; virtual ~PEB() = default; }; } /* namespace nt */ } /* namespace windows */ } /* namespace introvirt */
25.927928
98
0.658443
754f7abed18f3aa4fab8496fa530f81fabe2815e
19,141
cc
C++
mfc_relay/mfc_relay_client.cc
venkatkakumani/netconf-polt
8c4a87368309a3a4a9afb8235bc70a8531d2be68
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
mfc_relay/mfc_relay_client.cc
venkatkakumani/netconf-polt
8c4a87368309a3a4a9afb8235bc70a8531d2be68
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
mfc_relay/mfc_relay_client.cc
venkatkakumani/netconf-polt
8c4a87368309a3a4a9afb8235bc70a8531d2be68
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include <iostream> #include <memory> #include <string> #include <unistd.h> #include <stdlib.h> #include <sstream> #include <iomanip> #include <grpc++/grpc++.h> #include "control_relay_service.grpc.pb.h" #include <mfc_relay_client.h> #include "../netconf_server/modules/bbf-xpon/bbf-types.h" using grpc::Server; using grpc::ServerWriter; using grpc::ServerBuilder; using grpc::ServerCompletionQueue; using grpc::ServerContext; using grpc::Status; using grpc::StatusCode; using grpc::Channel; using grpc::ClientWriter; using grpc::ClientReader; using grpc::ClientContext; using google::protobuf::Empty; using std::string; using namespace std; using control_relay_service::DeviceHello; using control_relay_service::HelloRequest; using control_relay_service::HelloResponse; using control_relay_service::ControlRelayPacket; using control_relay_service::ControlRelayHelloService; using control_relay_service::ControlRelayPacketService; extern "C" uint32_t find_flow_id_by_sub_interface (const char *name, const bbf_match_criteria *match); char ga1Ipaddressandport[25]={0}; char ga1Temp[25]={0}; int golt = 0; bool stopping; static bcm_mfc_grpc_client_connect_disconnect_cb mfc_client_conn_discon_cb; static void *mfc_client_conn_discon_cb_data; tGlobMfcConfig gGlobalMfcConfig; #define MFC_DEBUG_WANTED 0 void Mfc_tx(bcmolt_access_control_receive_eth_packet *eth_packet); STAILQ_HEAD(, MfcPacketEntry) mfc_ind_list; bcmos_sem mfc_ind_sem; bcmos_mutex mfc_ind_lock; bcmos_task gListen_task_; bcmos_task gTx_task_; class MfcPacketEntry: public ControlRelayPacket { public: STAILQ_ENTRY(MfcPacketEntry) next; }; class HelloServiceClient { public: std::unique_ptr<::control_relay_service::ControlRelayHelloService::Stub> hello_stub_; std::unique_ptr<::control_relay_service::ControlRelayPacketService::Stub> message_stub_; ClientContext *listen_context_; std::shared_ptr<Channel> channel_; void ListenForMfcRelayTx(); bcmos_errno mfc_tx_to_cp (ControlRelayPacket &pkt); void task(); void Disconnected(); bcmos_errno SayHello() { HelloRequest request; HelloResponse response; ClientContext context; DeviceHello *olt = new DeviceHello(); olt->set_device_name(gGlobalMfcConfig.DeviceName); request.set_allocated_device(olt); hello_stub_ = ::control_relay_service::ControlRelayHelloService::NewStub(channel_); Status status = hello_stub_->Hello(&context, request, &response); if (!status.ok()) { std::cout << status.error_message() << std::endl; std::cout << status.error_code() << std::endl; return BCM_ERR_IO; } return BCM_ERR_OK; } }; HelloServiceClient *gclient; static inline bcmos_bool is_vlan_tpid(uint16_t tpid) { return (tpid == 0x8100 || tpid == 0x88A8 || tpid == 0x9100); } void parse_packet (uint8_t *packet, uint32_t length, bbf_match_criteria *match, uint16_t *ethtype) { uint16_t p_tpid; uint16_t vlan; int offset = 12; memset(match, 0, sizeof(*match)); p_tpid = *(const uint16_t *)(packet + offset); if (is_vlan_tpid(ntohs(p_tpid))) { BBF_DOT1Q_TAG_PROP_SET(&match->vlan_tag_match.tags[0], tag_type, ntohs(*(const uint16_t *)(packet + offset))); offset += 2; vlan = ntohs(*(const uint16_t *)(packet + offset)); BBF_DOT1Q_TAG_PROP_SET(&match->vlan_tag_match.tags[0], vlan_id, (vlan & 0xfff)); BBF_DOT1Q_TAG_PROP_SET(&match->vlan_tag_match.tags[0], pbit, (vlan >> 13)); offset += 2; match->vlan_tag_match.num_tags = 1; match->vlan_tag_match.tag_match_types[0] = BBF_VLAN_TAG_MATCH_TYPE_VLAN_TAGGED; } if (is_vlan_tpid(ntohs(*(const uint16_t *)(packet + offset)))) { BBF_DOT1Q_TAG_PROP_SET(&match->vlan_tag_match.tags[1], tag_type, ntohs(*(const uint16_t *)(packet + offset))); offset += 2; vlan = ntohs(*(const uint16_t *)(packet + offset)); BBF_DOT1Q_TAG_PROP_SET(&match->vlan_tag_match.tags[1], vlan_id, (vlan & 0xfff)); BBF_DOT1Q_TAG_PROP_SET(&match->vlan_tag_match.tags[1], pbit, (vlan >> 13)); offset += 2; match->vlan_tag_match.num_tags = 2; match->vlan_tag_match.tag_match_types[1] = BBF_VLAN_TAG_MATCH_TYPE_VLAN_TAGGED; } *ethtype = ntohs(*(const uint16_t *)(packet + offset)); } bcmos_errno bcm_packet_grpc_to_olt(const ControlRelayPacket *grpc_packet, bcmolt_access_control_receive_eth_packet *bcm_packet) { char RxPkt[1500]={0}; char temp[2]; char sub_intf_name[100] = {0}; uint8_t RxPktInHex[1500]={0}; int u1Byte = 0,pktlen=0,len = 0; const uint8_t *ip_hdr; const uint8_t *payload = NULL; char *endptr = NULL; uint16_t flowtype = 0; uint16_t ethtype = 0; //const interface_info *iface = NULL; bbf_match_criteria match; bcmolt_flow_key flow_key = {}; bcmolt_flow_send_eth_packet packet_out; bcmolt_bin_str packet_out_buffer; bcmos_errno err; len = strlen(grpc_packet->packet().c_str()); strncpy (RxPkt, grpc_packet->packet().c_str(), len); flowtype = atoi(grpc_packet->originating_rule().c_str()); strcpy (sub_intf_name, grpc_packet->device_interface().c_str()); for (u1Byte = 0 ; u1Byte <= len-2; u1Byte = u1Byte+2) { sprintf(temp, "%c%c", RxPkt[u1Byte], RxPkt[u1Byte+1]); RxPktInHex[pktlen] = strtol(temp, NULL, 16); pktlen++; } packet_out_buffer.len = pktlen; packet_out_buffer.arr = RxPktInHex; parse_packet(RxPktInHex,grpc_packet->packet().size(), &match, &ethtype); flow_key.flow_id = find_flow_id_by_sub_interface (sub_intf_name, &match); if (flow_key.flow_id == 0) { #if MFC_DEBUG_WANTED printf("\n === No Matching Flow ID present === \n"); #endif return BCM_ERR_PARM; } if (flowtype == BCMOLT_FLOW_TYPE_DOWNSTREAM) flow_key.flow_type = BCMOLT_FLOW_TYPE_DOWNSTREAM; else flow_key.flow_type = BCMOLT_FLOW_TYPE_UPSTREAM; #if MFC_DEBUG_WANTED printf("\n ====== FLOW_ID %d interface %s Flow_type = %s ======\n",flow_key.flow_id, sub_intf_name, bcmolt_enum_stringval(bcmolt_flow_type_string_table, flow_key.flow_type)); #endif BCMOLT_OPER_INIT(&packet_out, flow, send_eth_packet, flow_key); BCMOLT_MSG_FIELD_SET(&packet_out, buffer, packet_out_buffer); BCMOLT_MSG_FIELD_SET(&packet_out, inject_type, BCMOLT_INJECT_TYPE_INJECT_AT_INGRESS); err = bcmolt_oper_submit(golt, &packet_out.hdr); if (err != BCM_ERR_OK) { #if MFC_DEBUG_WANTED printf("\n Failed to Forward the Packet\n"); #endif return err; } else { #if MFC_DEBUG_WANTED printf("\n Packet forwarded: %d bytes\n", pktlen); #endif } return BCM_ERR_OK; } bcmos_errno Mfc_Relay_Dispatch (const ControlRelayPacket &tx_packet) { bcmolt_access_control_receive_eth_packet bcm_mfc_msg; bcmos_errno err; err = bcm_packet_grpc_to_olt(&tx_packet, &bcm_mfc_msg); if (err != BCM_ERR_OK) return err; return BCM_ERR_OK; } void HelloServiceClient::ListenForMfcRelayTx() { bcmos_errno err; if (listen_context_ != nullptr) /*cancel if old call any*/ { listen_context_->TryCancel(); while (listen_context_ != nullptr) { bcmos_usleep(10000); } } listen_context_ = new ClientContext(); Empty request; ControlRelayPacket tx_packet; std::unique_ptr<::grpc::ClientReaderInterface< ::control_relay_service::ControlRelayPacket>> reader( message_stub_->ListenForPacketRx(listen_context_, request)); while (reader->Read(&tx_packet)) { #if MFC_DEBUG_WANTED printf("\n Recieved packet structure \n device %s \n interface %s \n rule %s \n pkt %s\n",tx_packet.device_name().c_str(),tx_packet.device_interface().c_str(),tx_packet.originating_rule().c_str(),tx_packet.mutable_packet()->c_str()); #endif err = Mfc_Relay_Dispatch(tx_packet); if(err != BCM_ERR_OK) { #if MFC_DEBUG_WANTED printf("\n Failed to forward packet. Error %s\n",bcmos_strerror(err)); #endif } } reader->Finish(); /* There appears to be a race-condition bug in grpc library. It sometimes crashes when attempty to destroy mutex that another grpc task still waiting on sleep a little here\ */ bcmos_usleep(10000); delete listen_context_; listen_context_ = nullptr; } bcmos_errno HelloServiceClient::mfc_tx_to_cp(ControlRelayPacket &pkt) { ClientContext context; ::google::protobuf::Empty response; Status status; status = message_stub_->PacketTx(&context, pkt, &response); return status.ok() ? BCM_ERR_OK: BCM_ERR_IO; } MfcPacketEntry* pop() { MfcPacketEntry *mfc_packet; bcmos_mutex_lock(&mfc_ind_lock); mfc_packet = STAILQ_FIRST(&mfc_ind_list); if (mfc_packet != nullptr) { STAILQ_REMOVE_HEAD(&mfc_ind_list, next); } bcmos_mutex_unlock(&mfc_ind_lock); return mfc_packet; } bcmos_errno waitforpacket() { uint32_t poll_timeout = 10000; return bcmos_sem_wait(&mfc_ind_sem, poll_timeout); } static int _client_tx_task_handler(long data) { bcmos_errno err; HelloServiceClient *tx = (HelloServiceClient *)data; while (1) { err = waitforpacket(); if (err != BCM_ERR_OK && err != BCM_ERR_TIMEOUT) { #if MFC_DEBUG_WANTED printf("\r\n ===== Failed or Timeout for waiting the packet =====\r\n"); #endif break; } MfcPacketEntry *pkt = pop(); if (pkt == nullptr) continue; if (gGlobalMfcConfig.bIsStarted == 1) { err = tx->mfc_tx_to_cp(*pkt); if (err != BCM_ERR_OK) { #if MFC_DEBUG_WANTED printf("\r\n==== packet transmission to the BAA failed ====\r\n"); #endif } } } return 0; } void HelloServiceClient::Disconnected() { if (!stopping) { stopping = true; if (listen_context_ != nullptr) { listen_context_->TryCancel(); while (listen_context_ != nullptr) { } } bcmos_task_destroy(&gTx_task_); if (mfc_client_conn_discon_cb != nullptr) { mfc_client_conn_discon_cb (mfc_client_conn_discon_cb_data, gGlobalMfcConfig.EndpointName, gGlobalMfcConfig.AccessName, 0); } } } void HelloServiceClient::task() { bcmos_errno err; bcmos_task_parm tp = {}; tp.name = "pkt_tx"; tp.priority = TASK_PRIORITY_TRANSPORT_PROXY; tp.handler = _client_tx_task_handler; tp.data = (long)this; err = bcmos_task_create(&gTx_task_, &tp); if (err != BCM_ERR_OK) { #if MFC_DEBUG_WANTED printf("\r\n==== Tast Creation of TX Failed ====\r\n"); #endif } } static int Listening_task_handler(long data) { bcmos_errno err = BCM_ERR_OK; bool ready = false; stopping = false; gGlobalMfcConfig.bIsStarted = 1; HelloServiceClient *client = new HelloServiceClient; client->listen_context_ = nullptr; gclient = client; do { do { while(!ready && !stopping) { memset (ga1Temp, 0, 25); sprintf (ga1Temp,"%s:%d",gGlobalMfcConfig.a1Ipaddress, gGlobalMfcConfig.port); #if MFC_DEBUG_WANTED printf ("\r\n IP and port = %s \r\n", ga1Temp); #endif client->channel_ = grpc::CreateChannel(ga1Temp, grpc::InsecureChannelCredentials()); if (client->channel_ == nullptr || client->channel_->GetState(true) == GRPC_CHANNEL_SHUTDOWN) { bcmos_usleep(1*1000000); ready =false; } else { ready = true; } } if (ready == true) { err = client->SayHello(); if (err != BCM_ERR_OK) { bcmos_usleep(1*1000000); } } } while (err != BCM_ERR_OK && !stopping); if (stopping) break; client->message_stub_ = ::control_relay_service::ControlRelayPacketService::NewStub(client->channel_); client->task(); client->ListenForMfcRelayTx(); client->Disconnected(); }while(!stopping); gGlobalMfcConfig.bIsStarted = 0; delete client; return BCM_ERR_OK; } void Mfc_tx(bcmolt_access_control_receive_eth_packet *eth_packet) { int u1Byte = 0; MfcPacketEntry *pkt = new MfcPacketEntry(); pkt->set_device_name(gGlobalMfcConfig.DeviceName); pkt->set_device_interface(to_string(eth_packet->data.interface_ref.intf_id)); //pkt->set_originating_rule("rule"); if (eth_packet->data.interface_ref.intf_type == BCMOLT_INTERFACE_TYPE_PON) { pkt->set_originating_rule(to_string(BCMOLT_FLOW_TYPE_UPSTREAM)); } else { pkt->set_originating_rule(to_string(BCMOLT_FLOW_TYPE_DOWNSTREAM)); } std::stringstream ss; ss << std::hex << std::setfill('0'); for (u1Byte=0; u1Byte < (eth_packet->data.buffer.len); u1Byte++) { ss << std::setw(2) << static_cast<unsigned>(eth_packet->data.buffer.arr[u1Byte]); } std::string StringBuffer = ss.str(); pkt->set_packet(StringBuffer); #if MFC_DEBUG_WANTED printf("\r\n interface %s \r\n",pkt->mutable_device_interface()->c_str()); printf("\r\n flow type %s \r\n",pkt->mutable_originating_rule()->c_str()); printf ("\r\n Packet After copying to GRPC structure = %s len = %d\r\n", pkt->mutable_packet()->c_str(), eth_packet->data.buffer.len); #endif bcmos_mutex_lock(&mfc_ind_lock); STAILQ_INSERT_TAIL(&mfc_ind_list, pkt, next); // Kick thread that unwinds the queue if the queue was empty if (STAILQ_FIRST(&mfc_ind_list) == pkt) { bcmos_sem_post(&mfc_ind_sem); } bcmos_mutex_unlock(&mfc_ind_lock); } static void bcmolt_Rx_Callback(bcmolt_oltid olt, bcmolt_msg *msg) { bcmolt_access_control_receive_eth_packet *eth_packet = (bcmolt_access_control_receive_eth_packet *)msg; /*Transmitting the packet from OLT to BAA*/ Mfc_tx(eth_packet); } bcmos_errno bcm_mfc_relay_init(int olt) { STAILQ_INIT(&mfc_ind_list); bcmos_mutex_create(&mfc_ind_lock, 0, "mfc_ind"); bcmos_sem_create(&mfc_ind_sem, 0, 0, "mfc_ind"); bcmos_task_parm tp = {}; bcmos_errno err; golt = olt; /*registering rx callback*/ bcmolt_rx_cfg rx_cfg = {}; rx_cfg.obj_type = BCMOLT_OBJ_ID_ACCESS_CONTROL; rx_cfg.rx_cb = bcmolt_Rx_Callback; rx_cfg.subgroup = BCMOLT_ACCESS_CONTROL_AUTO_SUBGROUP_RECEIVE_ETH_PACKET; err = bcmolt_ind_subscribe(olt, &rx_cfg); if (err != BCM_ERR_OK) { #if MFC_DEBUG_WANTED std::cout << "==== Subscription failed ====\n"; #endif return err; } bcm_mfc_relay_cli_init (); return BCM_ERR_OK; } bcmos_errno bcm_mfc_relay_start () { #if MFC_DEBUG_WANTED printf("====== bcm_mfc_relay_started ==============\n"); #endif bcmos_task_parm tp = {}; bcmos_errno err; tp.name = "polt_client_server"; tp.priority = TASK_PRIORITY_VOMCI_DOLT_CLIENT; tp.handler = Listening_task_handler; tp.data = (long)1; err = bcmos_task_create(&gListen_task_, &tp); if (err == BCM_ERR_OK) { if (mfc_client_conn_discon_cb != nullptr) { mfc_client_conn_discon_cb (mfc_client_conn_discon_cb_data, gGlobalMfcConfig.EndpointName, gGlobalMfcConfig.AccessName, 1); } } return err; } bcmos_errno bcm_mfc_relay_stop () { if (gGlobalMfcConfig.bIsStarted == 1) { gclient->Disconnected (); } return BCM_ERR_OK; } bcmos_errno bcm_mfc_grpc_client_enable_disable(bcmos_bool enable) { bcmos_errno err = BCM_ERR_OK; char a1TempIpAddress[50]={0}; if (enable) { if ((gGlobalMfcConfig.bIsStarted == 0) && (gGlobalMfcConfig.port != 0) && (strcmp (gGlobalMfcConfig.a1Ipaddress, a1TempIpAddress))) { /*start the session and update the value in the session start func*/ err = bcm_mfc_relay_start (); } } else { /* kill the sesion and dont clear params */ if (gGlobalMfcConfig.bIsStarted == 1) { bcm_mfc_relay_stop (); } } return err; } bcmos_errno bcm_mfc_grpc_client_edit_config (const char * endpoint_name, const char * access_point_name,uint16_t port,const char * host_name) { bool b1StartSession = 0; char a1TempIpAddress[50]={0}; bcmos_errno err = BCM_ERR_OK; if (gGlobalMfcConfig.bIsStarted == 1) { if ((strcmp (endpoint_name, gGlobalMfcConfig.EndpointName)) || (strcmp (access_point_name, gGlobalMfcConfig.AccessName))) { return err; } } else { if (endpoint_name != NULL) { strcpy (gGlobalMfcConfig.EndpointName, endpoint_name); } if (access_point_name != NULL) { strcpy (gGlobalMfcConfig.AccessName, access_point_name); } } if ((port != 0) && (gGlobalMfcConfig.port != port)) { gGlobalMfcConfig.port = port; b1StartSession = 1; } else if ((host_name != NULL) && (strcmp(gGlobalMfcConfig.a1Ipaddress, host_name))) { strcpy (gGlobalMfcConfig.a1Ipaddress, host_name); b1StartSession = 1; } if (b1StartSession == 1) { if (gGlobalMfcConfig.bIsStarted == 1) { /* stop the existing session and reset the start flag*/ bcm_mfc_relay_stop (); } /* Trigger the session */ if ((gGlobalMfcConfig.bIsStarted == 0) && (gGlobalMfcConfig.port != 0) && (strcmp (gGlobalMfcConfig.a1Ipaddress, a1TempIpAddress))) { err = bcm_mfc_relay_start (); } } return err; /* check if port != 0 and host name != NULL , based on that fill that value and disconnect and connect and before that compar e the endpoing name and access name if different return , if same proceed, if first store. */ } bcmos_errno Mfc_disconnect() { if (gGlobalMfcConfig.bIsStarted == 1) { /* stop the existing session */ bcm_mfc_relay_stop (); } return BCM_ERR_OK; } bcmos_errno bcm_mfc_grpc_client_delete (const char * endpoint_name) { /* clear the access name, endpoint name, and port and ip */ /* delete the session */ if (strcmp (endpoint_name, gGlobalMfcConfig.EndpointName)) { return BCM_ERR_OK; } if (gGlobalMfcConfig.bIsStarted == 1) { /* stop the existing session */ bcm_mfc_relay_stop (); } memset (&gGlobalMfcConfig, 0, sizeof (tGlobMfcConfig)); return BCM_ERR_OK; } bcmos_errno bcm_mfc_grpc_client_connect_disconnect_cb_register (bcm_mfc_grpc_client_connect_disconnect_cb cb, void *data) { mfc_client_conn_discon_cb = cb; mfc_client_conn_discon_cb_data = data; return BCM_ERR_OK; }
29.357362
245
0.652839
75504f62dadac215cd69a00917affe0e57447838
376
cpp
C++
game/server/entities/triggers/CTriggerTeleport.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
83
2016-06-10T20:49:23.000Z
2022-02-13T18:05:11.000Z
game/server/entities/triggers/CTriggerTeleport.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
26
2016-06-16T22:27:24.000Z
2019-04-30T19:25:51.000Z
game/server/entities/triggers/CTriggerTeleport.cpp
xalalau/HLEnhanced
f108222ab7d303c9ed5a8e81269f9e949508e78e
[ "Unlicense" ]
58
2016-06-10T23:52:33.000Z
2021-12-30T02:30:50.000Z
#include "extdll.h" #include "util.h" #include "cbase.h" #include "CTriggerTeleport.h" LINK_ENTITY_TO_CLASS( trigger_teleport, CTriggerTeleport ); //TODO: Consider making this its own class - Solokiller LINK_ENTITY_TO_CLASS( info_teleport_destination, CPointEntity ); void CTriggerTeleport::Spawn( void ) { InitTrigger(); SetTouch( &CTriggerTeleport::TeleportTouch ); }
22.117647
64
0.776596
755199317f3fade2b7ce3139ef6dba5776bbf8f3
14,130
cpp
C++
embeddedCNN/src/utils/check.cpp
yuehniu/embeddedCNN
1067867830300cc55b4573d633c9fa1226c64868
[ "MIT" ]
21
2018-07-10T07:47:51.000Z
2021-12-03T05:47:30.000Z
embeddedCNN/src/utils/check.cpp
honorpeter/embeddedCNN
1067867830300cc55b4573d633c9fa1226c64868
[ "MIT" ]
3
2018-09-05T03:09:40.000Z
2019-04-15T10:01:40.000Z
embeddedCNN/src/utils/check.cpp
honorpeter/embeddedCNN
1067867830300cc55b4573d633c9fa1226c64868
[ "MIT" ]
8
2018-06-10T02:04:09.000Z
2021-12-03T05:47:31.000Z
/* Desc: Result check function set. * Accurate data check (Dataflow). * Approximate data check (Compute result). Date: 06/05/2018 Author: Yue Niu */ #include <iostream> #include <fstream> #include <stdlib.h> #include "../../include/utils/check.h" extern const int SHAPE[]; extern const int CHNEL[]; bool dataflow_check(Dtype * Ref, Dtype * Res, int Cnt) { std::cout << "[INFO] " << __FUNCTION__ << ", " << __LINE__ << ": Check dataflow between DDR and FPGA" << std::endl; bool all_same = true; std::ofstream log("check_df.log"); for (int i = 0; i < Cnt; i++){ if (*(Res + i) != *(Ref + i)) { all_same = false; log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << i << "th data check fail" << std::endl; log << "[LOG] " << "Ref data: " << *(Ref + i) << ", Result data: " << *(Res + i) << std::endl; } else { log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << i << "th data check pass" << std::endl; log << "[LOG] " << "Ref data: " << *(Ref + i) << ", Result data: " << *(Res + i) << std::endl; } } log.close(); return all_same; } /* Check in_buf */ void conv_inbuf_check( Dtype *Ref, Dtype InBuf[ITILE][I_BUF_DEPTH], int Lyr, int RowsPre, int RowsRead, int RowsValid ) { static int til; if (1 == RowsPre) til = 0; else til += 1; std::ofstream log("check_InBuf.log", std::ios::app); int chnl_til_num = Lyr == 0 ? 3 : ITILE; int chnl_num = Lyr == 0 ? 3 : CHNEL[Lyr - 1]; int col_num = SHAPE[Lyr] + 2; Dtype *ref_ptr = Ref; log << "[INFO] " << __FUNCTION__ << ", " << __LINE__ << ": Check " << til << "th tile." << std::endl; for (int ch = 0; ch < chnl_til_num; ch++){ for (int row = 0; row < RowsPre+RowsValid; row++){ for (int col = 0; col < col_num; col++){ Dtype ref = 0.0; if ((0 == col) || (col_num-1 == col)) ref = 0.0; else { if (0 == row){ if (1 == RowsPre) ref = 0.0; else ref = *(ref_ptr - 2 * chnl_num * (col_num-2) + ch * (col_num-2) + col - 1); } else if (1 == row){ if (1 == RowsPre) ref = *(ref_ptr + ch * (col_num-2) + col - 1); else ref = *(ref_ptr - chnl_num * (col_num-2) + ch * (col_num-2) + col - 1); } else { ref = *(ref_ptr + (row - RowsPre) * chnl_num * (col_num-2) + ch * (col_num-2) + col - 1); } } Dtype inbuf = InBuf[ch][row * col_num + col]; if (ref == inbuf) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << ch << "th channel, " << row << "th row, " << col << "th col data check pass." << std::endl; else log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << ch << "th channel, " << row << "th row, " << col << "th col data check fail." << std::endl; log << "[LOG] " << "Ref data: " << ref << ", InBuf: " << inbuf << std::endl; } } } log.close(); return; } /* Check w_buf */ void conv_wbuf_check( Dtype *Param, Dtype WBuf[OTILE * ITILE][W_BUF_DEPTH], int IChnlTil, int OChnlTil, int Kern, int Sec ) { std::ofstream log("check_WBuf.log", std::ios::app); log << "[INFO] " << __FUNCTION__ << ", " << __LINE__ << ": Check " << Sec << "th sector." << std::endl; for(int och = 0; och < OChnlTil; och++){ for(int ich = 0; ich < ITILE; ich++) { for(int k = 0; k < Kern * Kern; k++){ if (ich < IChnlTil){ Dtype ref = *(Param + och * IChnlTil * Kern * Kern + ich * Kern * Kern + k); Dtype wbuf = WBuf[och * ITILE + ich][Sec * Kern * Kern + k]; if (ref == wbuf){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << Sec << "th sector, " << och << "th ochannel, " << ich << "th ichannel, " << k << "th weight check pass." << std::endl; } else{ log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << Sec << "th sector, " << och << "th ochannel, " << ich << "th ichannel, " << k << "th weight check fail." << std::endl; } log << "[LOG] " << "Ref weight: " << ref << ", WBuf: " << wbuf << std::endl; } } } } log.close(); return; } /* Check b_buf */ void conv_bias_check(Dtype *Param, Dtype BBuf[B_BUF_DEPTH], int OChnl) { std::ofstream log("check_BBuf.log", std::ios::app); for (int och = 0; och < OChnl; och++){ Dtype ref = *(Param + och); Dtype bbuf = BBuf[och]; if (ref == bbuf){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check pass." << std::endl; } else { log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check fail." << std::endl; } log << "[LOG] " << "Ref bias: " << ref << ", BBuf: " << bbuf << std::endl; } log.close(); return; } /* Check b_buf */ void onchip_check(Dtype *Ref, Dtype *Chip, int OChnl) { std::ofstream log("check_Onchip.log", std::ios::app); for (int och = 0; och < OChnl; och++){ Dtype ref = *(Ref + och); Dtype bbuf = *(Chip + och); if (ref == bbuf){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check pass." << std::endl; } else { log << "[ERR] " << __FUNCTION__ << ", " << __LINE__ << ": " << och << "th ochannel bias check fail." << std::endl; } log << "[LOG] " << "Ref bias: " << ref << ", BBuf: " << bbuf << std::endl; } log.close(); return; } /* Check computing result */ void conv_check(Dtype *Out, int Lyr, bool Pooling) { std::ofstream log("check_conv_result.log", std::ios::app); std::ifstream feature; if (0 == Lyr) feature.open("./data/conv1_1fp16.bin", std::ios::binary); else if (1 == Lyr){ if (Pooling) feature.open("./data/pool1fp16.bin", std::ios::binary); else feature.open("./data/conv1_2fp16.bin", std::ios::binary); } else if (2 == Lyr) feature.open("./data/conv2_1fp16.bin", std::ios::binary); else if (3 == Lyr){ if (Pooling) feature.open("./data/pool2fp16.bin", std::ios::binary); else feature.open("./data/conv2_2.bin", std::ios::binary); } else if (4 == Lyr) feature.open("./data/conv3_1fp16.bin", std::ios::binary); else if (5 == Lyr) feature.open("./data/conv3_2fp16.bin", std::ios::binary); else if (6 == Lyr){ if (Pooling) feature.open("./data/pool3fp16.bin", std::ios::binary); else feature.open("./data/conv3_3.bin", std::ios::binary); } else if (7 == Lyr) feature.open("./data/conv4_1fp16.bin", std::ios::binary); else if (8 == Lyr) feature.open("./data/conv4_2fp16.bin", std::ios::binary); else if (9 == Lyr){ if (Pooling) feature.open("./data/pool4fp16.bin", std::ios::binary); else feature.open("./data/conv4_3.bin", std::ios::binary); } else if (10 == Lyr) feature.open("./data/conv5_1fp16.bin", std::ios::binary); else if (11 == Lyr) feature.open("./data/conv5_2fp16.bin", std::ios::binary); else if (12 == Lyr){ if (Pooling) feature.open("./data/pool5fp16.bin", std::ios::binary); else feature.open("./data/conv5_3fp16.bin", std::ios::binary); } int r_size = 0; if (Pooling) r_size = CHNEL[Lyr] * SHAPE[Lyr] * SHAPE[Lyr] >> 2; else r_size = CHNEL[Lyr] * SHAPE[Lyr] * SHAPE[Lyr]; Dtype *ref_feat = (Dtype *) malloc(r_size * sizeof(Dtype)); char *ref_char = reinterpret_cast<char *>(ref_feat); feature.read(ref_char, r_size * sizeof(Dtype)); int row_num = Pooling ? SHAPE[Lyr] / 2 : SHAPE[Lyr]; int col_num = Pooling ? SHAPE[Lyr] / 2 : SHAPE[Lyr]; for (int row = 0; row < row_num; row++) { for (int och = 0; och < CHNEL[Lyr]; och++) { for (int col = 0; col < col_num; col++) { int pos = row * CHNEL[Lyr] * row_num + och * col_num + col; Dtype ref = *(ref_feat + pos); Dtype out = *(Out + pos); if (ref < 10.0){ float abs_err = ref - out; if (-ABS_ERR <= abs_err && abs_err <= ABS_ERR) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check pass." << std::endl; else log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check fail." << std::endl; } else{ float rel_err = (ref - out) / ref; if (-REL_ERR <= rel_err && rel_err <= REL_ERR) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check pass." << std::endl; else log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << row << "th row, " << och << "th channel, " << col << "th col data check fail." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref data, " << ref << "; Compute data, " << out << std::endl; } } } free(ref_feat); feature.close(); return; } /* Check output from FC */ void fc_check(Dtype *Out, int Lyr) { std::ofstream log("check_fc_result.log", std::ios::app); std::ifstream fc_out; if(0 == Lyr) fc_out.open("./data/fc6_1fp16.bin", std::ios::binary); else if(1 == Lyr) fc_out.open("./data/fc6_2fp16.bin", std::ios::binary); else if(2 == Lyr) fc_out.open("./data/fc7_1fp16.bin", std::ios::binary); else if(3 == Lyr) fc_out.open("./data/fc7_2fp16.bin", std::ios::binary); else if(4 == Lyr) fc_out.open("./data/fc8fp16.bin", std::ios::binary); int out_len = CHNEL[13 + Lyr]; Dtype *ref_out = (Dtype *)malloc(out_len * sizeof(Dtype)); char *ref_out_char = reinterpret_cast<char *>(ref_out); fc_out.read(ref_out_char, out_len * sizeof(Dtype)); log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Check " << Lyr << "th layer." << std::endl; for (int m = 0; m < out_len; m++){ Dtype ref = ref_out[m]; Dtype out = Out[m]; float rel_err = (ref - out)/ ref; if (-REL_ERR <= rel_err && rel_err <= REL_ERR) log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th data check pass." << std::endl; else log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th data check fail." << std::endl; log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref data, " << ref << "; Compute data, " << out << std::endl; } free(ref_out); fc_out.close(); return; } /* Check bias in FC layer */ void fc_bias_check(Dtype *Param, Dtype *BBuf, int Len) { std::ofstream log("check_fc_bias.log", std::ios::app); for (int n = 0; n < Len; n++){ Dtype ref = Param[n]; Dtype bias = BBuf[n]; if (ref == bias){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th bias check pass." << std::endl; } else{ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th bias check pass." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref, " << ref << "; On-chip, " << bias << std::endl; } return; } /* Check input in FC layer */ void fc_inbuf_check(Dtype *In, Dtype BufferA[BUFA_DEPTH], int Len) { std::ofstream log("check_fc_inbuf.log", std::ios::app); for (int n = 0; n < Len; n++){ Dtype ref = In[n]; Dtype data = BufferA[n]; if (ref == data){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th data check pass." << std::endl; } else{ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << n << "th data check pass." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref data, " << ref << "; On-chip data, " << data << std::endl; } return; } /* Check weight in FC layer */ void fc_weight_check(Dtype *Param, Dtype WBuf[128][1024], int ONum) { std::ofstream log("check_fc_weight.log", std::ios::app); for (int m = 0; m < ONum; m++){ for (int n = 0; n < 128; n++){ Dtype ref = *Param++; Dtype weight = WBuf[n][m]; if (ref == weight){ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th inchnl, " << n << "th ochnl weight check pass." << std::endl; } else{ log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": " << m << "th inchnl, " << n << "th ochnl weight check pass." << std::endl; } log << "[LOG] " << __FUNCTION__ << ", " << __LINE__ << ": Ref, " << ref << "; On-chip, " << weight << std::endl; } } return; }
31.752809
105
0.456688
7552f7572a0397d169d54e2bfa7693a0e087a7f6
9,359
cpp
C++
Productivity-Companion/InputTodo.cpp
Despicable-Us/Productivity-Companion
2a18e9cc8c01c88012030ed599805298239da497
[ "CC0-1.0" ]
12
2021-11-22T11:49:26.000Z
2022-03-04T03:31:17.000Z
Productivity-Companion/InputTodo.cpp
Despicable-Us/Productivity-Companion
2a18e9cc8c01c88012030ed599805298239da497
[ "CC0-1.0" ]
null
null
null
Productivity-Companion/InputTodo.cpp
Despicable-Us/Productivity-Companion
2a18e9cc8c01c88012030ed599805298239da497
[ "CC0-1.0" ]
null
null
null
#include "InputTodo.h" #include "Database.h" //default constructor extern std::vector<udh::inputField> textList; extern std::vector<udh::inputField> completed; extern udh::inputField sampletext; udh::inputField::inputField() { this->font.loadFromFile("Fonts/Roboto-Medium.ttf"); this->textdata.setFont(font); this->textdata.setFillColor(sf::Color(0,0,0)); this->textdata.setString(""); this->textdata.setCharacterSize(16); // Icon loading and setting this->loadIconTexture(); //assigning day when task was created std::time_t current; std::time (&current); struct tm* timecreated; timecreated = std::localtime(&current); this->creationDay = timecreated->tm_year * 365 + timecreated->tm_mon * 30 + timecreated->tm_mday; } void udh::inputField::loadIconTexture() { if (!del_tex.loadFromFile("Texture/dust-bin1.png")) throw "Error in loading the 'dust_bin.png'"; if (!edit_tex.loadFromFile("Texture/pencil.png")) throw "Error in loading the 'pencil.png'"; del_icon = Icon(del_tex); edit_icon = Icon(edit_tex); } void udh::inputField::setdata(std::string str) { text = str; textdata.setString(text); } void udh::inputField::drawtext(sf::RenderWindow* window) { window->draw(textdata); } std::string udh::inputField::getdata() { return this->text; } sf::Text udh::inputField::gettext() { return textdata; } void udh::inputField::setposition(sf::Vector2f position) { textdata.setPosition(position); } sf::Font udh::inputField::getfont() { return font; } void udh::inputField::setdone() { this->completed = true; } bool udh::inputField::getstatus() { return this->completed; } int udh::inputField::getDay() { return this->creationDay; } void udh::inputField::setday(int a) { this->creationDay = a; } void udh::inputField::setCreationTime() { time_t current; time(&current); struct tm* timecreated = localtime(&current); char timebuffer[40]; strftime(timebuffer, 40, "%a %b %d %Y\n",timecreated); } std::string udh::inputField::SanitizedData() { size_t pos = 0; std::string data=this->getdata(); while ((pos = data.find('\'', pos)) != std::string::npos) { data.replace(pos, 1, "''"); pos += 2; } return data; } void udh::drawlist(std::vector<udh::inputField>& textlist, std::vector<udh::inputField>& completed, sf::RenderWindow* window) { float i = 0; if (!textlist.empty()) { for (std::vector<udh::inputField>::iterator itr = textlist.begin(); itr < textlist.end(); itr++) { sf::CircleShape cL(15.f), cR(15.f); sf::RectangleShape Rect; Rect.setSize({700.f, 30.f}); Rect.setPosition({ 20.f,i }); cL.setPosition(5.f, i); cR.setPosition(705.f, i); Rect.setFillColor(sf::Color(200, 200, 200)); cL.setFillColor(sf::Color(200, 200, 200)); cR.setFillColor(sf::Color(200, 200, 200)); itr->setposition(sf::Vector2f(50.f, i+5)); //setting up mark done button itr->done.setBtnPosition(sf::Vector2f(20.f, i + 9)); itr->done.setBtnSize(sf::Vector2f(12.f, 12.f)); itr->done.setbtnRect(sf::FloatRect(20.f, i + 5, 18.f, 18.f)); itr->done.setoutline(sf::Color(150, 150, 150), 2); itr->del_icon.Set_Icon_Pos({630.f, i+15}); window->draw(Rect); window->draw(cL); window->draw(cR); itr->done.drawTo(*window); itr->del_icon.Draw_To(*window); itr->edit_icon.Set_Icon_Pos({ 680.f, i + 15 }); itr->edit_icon.Draw_To(*window); itr->drawtext(window); itr->done.setbtncolor(sf::Color(235, 235, 235)); itr->textdata.setFillColor(sf::Color::Black); i += 40; } } if (!completed.empty()) { sf::CircleShape cL(15.f), cR(15.f); sf::RectangleShape Rect; Rect.setSize({ 105.f, 30.f }); Rect.setPosition({ 20.f, i }); cL.setPosition(5.f, i); cR.setPosition(110.f, i); Rect.setFillColor(sf::Color(COMPLETED_C)); cL.setFillColor(sf::Color(COMPLETED_C)); cR.setFillColor(sf::Color(COMPLETED_C)); sf::Font roboto_font; roboto_font.loadFromFile("Fonts/Roboto-Medium.ttf"); sf::Text completed_text("Completed", roboto_font, 16); completed_text.setPosition({ 30.f, i + 5.f }); completed_text.setFillColor(sf::Color::White); window->draw(Rect); window->draw(cL); window->draw(cR); window->draw(completed_text); i += 40; for (std::vector<udh::inputField>::iterator itr = completed.begin(); itr < completed.end(); itr++) { sf::CircleShape cL(15.f), cR(15.f); sf::RectangleShape Rect; Rect.setSize({ 700.f, 30.f }); Rect.setPosition({ 20.f,i }); cL.setPosition(5.f, i); cR.setPosition(705.f, i); Rect.setFillColor(sf::Color(200, 200, 200)); cL.setFillColor(sf::Color(200, 200, 200)); cR.setFillColor(sf::Color(200, 200, 200)); itr->setposition(sf::Vector2f(50.f, i + 5)); //setting up mark done button itr->done.setBtnPosition(sf::Vector2f(20.f, i + 9)); itr->done.setBtnSize(sf::Vector2f(12.f, 12.f)); itr->done.setbtnRect(sf::FloatRect(20.f, i + 5, 18.f, 18.f)); itr->done.setoutline(sf::Color(150, 150, 150), 2); itr->del_icon.Set_Icon_Pos({ 630.f, i + 15 }); window->draw(Rect); window->draw(cL); window->draw(cR); itr->done.drawTo(*window); itr->del_icon.Draw_To(*window); itr->drawtext(window); itr->done.setbtncolor(sf::Color(40, 40, 40)); itr->crossline.setPosition(sf::Vector2f(50, i + 14)); itr->crossline.setFillColor(sf::Color(40, 40, 40)); itr->crossline.setSize({ itr->gettext().getGlobalBounds().width + 1, 3 }); itr->textdata.setFillColor(sf::Color(100, 100, 100)); window->draw(itr->crossline); i += 40; } } } void udh::checkAction(sf::Event event,std::vector<udh::inputField>&list, sf::RenderWindow* window, std::vector<udh::inputField>::iterator& itredit, udh::inputField& sample, udh::Button& textarea, bool &selected) { for (std::vector<udh::inputField>::iterator itr = list.begin(); itr < list.end(); itr++) { if (itr->done.ispressed(event, *window)) { if (!itr->completed) { itr->completed = true; std::string sql = "UPDATE TASKS SET Status = " + std::to_string(itr->getstatus()) + " WHERE Task = '" + itr->SanitizedData() + "';"; completed.push_back(*itr); list.erase(itr); udh::UpdateStatus(sql); selected = false; } else if(itr->completed) { itr->completed = false; std::string sql = "UPDATE TASKS SET Status = " + std::to_string(itr->getstatus()) + " WHERE Task = '" + itr->SanitizedData() + "';"; textList.push_back(*itr); list.erase(itr); udh::UpdateStatus(sql); selected = false; } break; } else if (itr->del_icon.Run_Outside_Event(*window, event)) { udh::DeleteTask(itr); list.erase(itr); break; } else if (itr->edit_icon.Run_Outside_Event(*window, event) && !itr->completed) { itredit = itr; itr->edit.setbtncolor(sf::Color(150, 140, 220)); sample.setdata(itr->getdata()); textarea.setEditing(); textarea.setbtntext(""); textarea.setpressed(); break; } } } void udh::editTask(udh::inputField& sampletext, std::string& a, sf::Event event, std::vector<udh::inputField>::iterator& edititr, udh::Button& textarea) { unsigned char b; a = sampletext.getdata(); a.pop_back(); a.push_back('_'); sampletext.setdata(a); if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (b == 8) { if (!a.empty()) { a.pop_back(); if (!a.empty()) a.pop_back(); a.push_back('_'); sampletext.setdata(a); } } else if (b == 13) { if (a.length() > 1) { a.pop_back(); a.push_back('\n'); sampletext.setdata(a); udh::updateTask(edititr); edititr->setdata(a); edititr->edit.setbtncolor(sf::Color(235, 235, 235)); sampletext.setdata(""); a.erase(); textarea.unsetEditing(); textarea.releasePressed(); edititr->edit_icon.Set_Unheld(); } } else if (sampletext.gettext().getGlobalBounds().width <= 560) { a.pop_back(); a.push_back(b); a.push_back('_'); sampletext.setdata(a); } } } } void udh::addTask(udh::inputField& sampletext, std::string& a, sf::Event event, std::vector<udh::inputField>& textlist, udh::Button textarea, bool is_planner_list) { unsigned char b; if (sampletext.getdata().empty() && textarea.getstate()) { if (a.empty()) a.push_back('_'); sampletext.setdata(a); } if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (event.type == sf::Event::TextEntered) { //take unicode and store into unsigned char b = event.text.unicode; if (b == 8) { if (!a.empty()) { a.pop_back(); if (!a.empty()) a.pop_back(); a.push_back('_'); sampletext.setdata(a); } } else if (b == 13) { if (a.length() > 1) { a.pop_back(); a.push_back('\n'); sampletext.setdata(a); sampletext.setCreationTime(); textlist.push_back(sampletext); if (!is_planner_list) { udh::AddTask(sampletext); } sampletext.setdata(""); a = ""; } } else if (sampletext.gettext().getGlobalBounds().width <= 560 && !a.empty()) { a.pop_back(); a.push_back(b); a.push_back('_'); sampletext.setdata(a); } } } }
24.628947
163
0.635752
7559227d53fb15d1087d9057fe94c213920a541c
4,404
cpp
C++
ProjectEuler+/euler-0278.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0278.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0278.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
1
2021-05-28T11:14:34.000Z
2021-05-28T11:14:34.000Z
// //////////////////////////////////////////////////////// // # Title // Linear Combinations of Semiprimes // // # URL // https://projecteuler.net/problem=278 // http://euler.stephan-brumme.com/278/ // // # Problem // Given the values of integers `1 < a_1 < a_2 < ... < a_n`, consider the linear combination // `q_1 a_1 + q_2 a_2 + ... + q_n a_n = b`, using only integer values `q_k >= 0`. // // Note that for a given set of `a_k`, it may be that not all values of `b` are possible. // For instance, if `a_1 = 5` and `a_2 = 7`, there are no `q_1 >= 0` and `q_2 >= 0` such that `b` could be // 1, 2, 3, 4, 6, 8, 9, 11, 13, 16, 18 or 23. // In fact, 23 is the largest impossible value of `b` for `a_1 = 5` and `a_2 = 7`. // We therefore call `f(5, 7) = 23`. // Similarly, it can be shown that `f(6, 10, 15) = 29` and `f(14, 22, 77) = 195`. // // Find `sum{f(pq,pr,qr)}`, where `p`, `q` and `r` are prime numbers and `p < q < r < 5000`. // // # Solved by // Stephan Brumme // July 2017 // // # Algorithm // Assume I have two numbers `x` and `y` where `gcd(x,y)=1`. // The value `m = xy - x - y` can't be represented with some coefficients `m = px + qy` because: // `xy - x - y = px + qy` // `xy = px + qy + x + y` // `xy = (p+1)x + (q+1)y` // // `xy` is a multiple of `x` and `(p+1)x` is a multiple of `x`, hence `(q+1)y` should be a multiple of `x`, too. // `xy` is a multiple of `y` and `(q+1)y` is a multiple of `y`, hence `(p+1)x` should be a multiple of `y`, too. // But `gcd(x,y)=1` so `y` can't be a multiple of `x` and therefore `q+1` should be a multiple of `x`. // And for the same reason `x` can't be a multiple of `y` and therefore `p+1` should be a multiple of `y`. // Possible values for `q+1` would be `x`, `2x`, `3x`, ... (and for `p+1`: `y`, `2y`, `3y`, ...) // If I assume the lowest value `p+1=y` and `q+1=x` then the equation becomes // `xy = y * x + x * y` // `xy = 2xy` ==> contradition ! // // Therefore `m = xy - x - y` actually can't be represented with some coefficients `m = px + qy`. // // With three numbers `x`,`y`,`z` and `gcd(x,y,z)=1` the idea is very similar: // if there would be some coefficients `p`, `q` and `r` such that `m = pxy + qxz + ryz` represents `m = 2xyz - xy - xz - yz` then // `(2xyz - xy - xz - yz) mod x = -yz` // `pxy + qxz + ryz = 2xyz - xy - xz - yz` // `2xyz = pxy + qxz + ryz + xy + xz + yz` // `2xyz = (py+qz+y+z)x + (rz + z)y` // Hence `rz + z = (r+1)z` must be a multiple of `x`. `z` can't be such a multiple (because of `gcd(x,y,z) = 1`). // The same idea for `y` and `z` gives that `p+1` must be a multiple of `z` and `q+1` a multiple of `y`. // As before - if I choose the smallest possible `p+1=z`, `q+1=y` and `r+1=x`: // `2xyz = zxy + yxz + xyz + xy + xz + yz` // `2xyz = 3xyz + xy + xz + yz` ==> contradiction // // I didn't come up with the full solution, I just know how to use search engines :-; // I found the problem in the 24th International Mathemtical Olympiad held 1983 in Paris, France // somewhat cryptic solution: http://www.cs.cornell.edu/~asdas/imo/imo/isoln/isoln833.html // I stumbled across it while reading the German Wikipedia https://de.wikipedia.org/wiki/M%C3%BCnzproblem // unfortunately, the English page misses that special case https://en.wikipedia.org/wiki/Coin_problem // but it can be derived from their `n=2` explanations (pretty much what I have done above) #include <iostream> #include <vector> int main() { unsigned int limit = 5000; std::cin >> limit; // simple prime sieve from my toolbox std::vector<unsigned long long> primes = { 2 }; for (unsigned int i = 3; i <= limit; i += 2) { bool isPrime = true; // test against all prime numbers we have so far (in ascending order) for (auto x : primes) { // prime is too large to be a divisor if (x*x > i) break; // divisible => not prime if (i % x == 0) { isPrime = false; break; } } // yes, we have a prime if (isPrime) primes.push_back(i); } // all combinations of primes unsigned long long sum = 0; for (size_t i = 0; i < primes.size(); i++) for (size_t j = i + 1; j < primes.size(); j++) for (size_t k = j + 1; k < primes.size(); k++) { auto p = primes[i]; auto q = primes[j]; auto r = primes[k]; sum += 2*p*q*r - p*q - p*r - q*r; } std::cout << sum << std::endl; return 0; }
39.321429
129
0.576067
75594f0eca0759b6efde094fb69d845c8d7336ae
2,501
cpp
C++
DecodeString.cpp
GolferChen/LeetCode
b502a57ff1ebe8daf670e7b068dd98cec0b9bf38
[ "MIT" ]
null
null
null
DecodeString.cpp
GolferChen/LeetCode
b502a57ff1ebe8daf670e7b068dd98cec0b9bf38
[ "MIT" ]
null
null
null
DecodeString.cpp
GolferChen/LeetCode
b502a57ff1ebe8daf670e7b068dd98cec0b9bf38
[ "MIT" ]
null
null
null
// // Created by Golfer on 2020/7/28. // #include <string> #include <stack> using namespace std; #include <cstdio> #include <iostream> // Version 1, Stack //class Solution { //public: // string decodeString(string s) { // stack<string> stack_string; // stack<int> stack_num; // int number = 0; // string result= ""; // for (char &c : s) { //// if ('0' <= c <= '9') { // wrong !!! //// number = number * 10 + c - '0'; //// } // if ('0' <= c && c <= '9') { // number = number * 10 + c - '0'; // } // else if (c == '[') { // stack_num.push(number); // number = 0; // stack_string.push(result); // result = ""; // } // else if (c == ']') { // int num = stack_num.top(); // stack_num.pop(); // string last_string = stack_string.top(); // stack_string.pop(); // string result_tmp = result; // for (int i = 0; i < num - 1; i++) { // result += result_tmp; // } // result = last_string + result; //// result = last_string + result // } // else { // result += c; // } // } // return result; // } //}; // Version 2, recrusive class Solution { public: string decodeString(string s) { return dfs(s, 0).second; } pair<int, string> dfs(string s, int i) { int number = 0; string result = ""; while (i < s.size()) { char c = s[i]; if (c >= '0' && c <= '9') { number = number * 10 + c - '0'; } else if (c == '[') { pair<int, string> dfs_call = dfs(s, i + 1); i = dfs_call.first; string tmp = dfs_call.second; for (int j = 0; j < number; j++) result += tmp; number = 0; } else if (c == ']') { return make_pair(i, result); } else { result += c; } ++i; } return make_pair(-1, result); } }; int main() { string s = "3[a]2[bc]"; Solution solution = Solution(); string decode_s = solution.decodeString(s); cout << decode_s << endl; return 0; }
26.606383
59
0.387845
7559e00fbea33a8739a688ccab89f9bb06122363
2,753
cpp
C++
MySpaceShooter/src/Gameplay/SpaceShip.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
MySpaceShooter/src/Gameplay/SpaceShip.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
MySpaceShooter/src/Gameplay/SpaceShip.cpp
TygoB-B5/OSCSpaceShooter
9a94fbbe4392c9283e47696d06a2866a7a8f1213
[ "Apache-2.0" ]
null
null
null
#include "SpaceShip.h" namespace Game { void SpaceShip::Update() { UpdateSpaceShipPosition(); UpdateSpaceShipRotation(); UpdateCameraPose(); UpdateSpaceshipGun(); } glm::vec3 SpaceShip::GetControllerIRotationnput() { // Calculate controller input with deadzone auto& cont = m_Controller; glm::vec3 rotation = glm::length(glm::vec3(cont->GetOrientation().z, -cont->GetOrientation().x, 0)) > DEADZONE ? glm::vec3(cont->GetOrientation().z, -cont->GetOrientation().x, 0) : glm::vec3(0, 0, 0); return rotation; } bool SpaceShip::GetControllerButtonInput() { std::cout << m_Controller->IsProximity() << "\n"; return m_Controller->IsProximity(); } void SpaceShip::UpdateSpaceShipRotation() { // Get rotation from spaceship glm::vec3 rot = m_Object->GetRotation(); // Corrent Angles if (m_Object->GetRotation().x > 180 || m_Object->GetRotation().x < -180) rot.x = -rot.x; if (m_Object->GetRotation().y > 180 || m_Object->GetRotation().y < -180) rot.y = -rot.y; if (m_Object->GetRotation().z > 180 || m_Object->GetRotation().z < -180) rot.z = -rot.z; m_Object->SetRotation(rot); // Correct controller input when upside down glm::vec3 input = GetControllerIRotationnput(); if (m_Object->GetRotation().x > 90 || m_Object->GetRotation().x < -90) input.y = -input.y; // Rotate spaceship m_Object->Rotate(input * Core::Time::GetDeltaTime()); } void SpaceShip::UpdateSpaceShipPosition() { // Move spaceship forward m_Object->Translate(m_Object->GetForward() * Core::Time::GetDeltaTime() * SPACESHIP_SPEED); // Move spaceship back if it goes out of bounds glm::vec3 pos = m_Object->GetPosition(); if (m_Object->GetPosition().x > PLAYFIELD_SIZE || m_Object->GetPosition().x < -PLAYFIELD_SIZE) pos.x = -pos.x; if (m_Object->GetPosition().y > PLAYFIELD_SIZE || m_Object->GetPosition().y < -PLAYFIELD_SIZE) pos.y = -pos.y; if (m_Object->GetPosition().z > PLAYFIELD_SIZE || m_Object->GetPosition().z < -PLAYFIELD_SIZE) pos.z = -pos.z; m_Object->SetPosition(pos); } void SpaceShip::UpdateCameraPose() { // Correct reverse rotation glm::vec3 rot = m_Object->GetRotation(); rot.y += 180; rot.x = -rot.x; rot.z = -rot.z; // Set camera rotation and position m_Camera->SetRotation(rot); m_Camera->SetPosition(m_Object->GetPosition() + m_Object->GetForward() * 800 + m_Object->GetUp() * 10); } void SpaceShip::UpdateSpaceshipGun() { // If button is held shoot at BULLET SHOOT SPEED rate if (GetControllerButtonInput() && m_ShootTime > BULLET_SHOOT_SPEED) { m_ShootTime = 0; m_BulletPool.SpawnBullet(m_Object->GetPosition(), m_Object->GetRotation()); } m_ShootTime += Core::Time::GetDeltaTime(); m_BulletPool.Update(); } }
28.091837
105
0.680349
755aaab5f9350ef704e1545ecd661418f70e1e57
389
hpp
C++
Hurrican/src/stdafx.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
21
2018-04-13T10:45:45.000Z
2022-03-29T14:53:43.000Z
Hurrican/src/stdafx.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
10
2021-06-30T14:29:36.000Z
2022-01-06T17:03:48.000Z
Hurrican/src/stdafx.hpp
s1eve-mcdichae1/Hurrican
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
[ "MIT" ]
3
2021-10-08T12:35:05.000Z
2022-03-03T06:03:49.000Z
#ifndef _STDAFX_HPP_ #define _STDAFX_HPP_ #include "Console.hpp" #include "DX8Font.hpp" #include "DX8Sound.hpp" #include "GUISystem.hpp" #include "Gameplay.hpp" #include "Globals.hpp" #include "HUD.hpp" #include "Logdatei.hpp" #include "Mathematics.hpp" #include "Partikelsystem.hpp" #include "Player.hpp" #include "Projectiles.hpp" #include "Tileengine.hpp" #include "Timer.hpp" #endif
19.45
29
0.758355
755db57e3190fddc30ff73cdb43146adb417b9e5
1,259
cpp
C++
LeetCode/C++/144_Binary_Tree_Preorder_Traversal.cpp
icgw/LeetCode
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
4
2018-09-12T09:32:17.000Z
2018-12-06T03:17:38.000Z
LeetCode/C++/144_Binary_Tree_Preorder_Traversal.cpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
LeetCode/C++/144_Binary_Tree_Preorder_Traversal.cpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
/* Given a binary tree, return the preorder traversal of its nodes' values. * * Example: * Input: [1, null, 2, 3] * 1 * \ * 2 * / * 3 * Output: [1, 2, 3] * * Follow up: Recursive solution is trivial, could you do it iteratively? */ #include <iostream> #include <vector> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: static vector<int> preorderTraversal(TreeNode* root){ vector<int> tra; if (!root) return tra; stack<TreeNode*> stk; stk.push(root); TreeNode *tmp; while (!stk.empty()){ tmp = stk.top(); stk.pop(); tra.push_back(tmp->val); if (tmp->right) stk.push(tmp->right); if (tmp->left) stk.push(tmp->left); } return tra; } }; int main(int argc, char *argv[]){ TreeNode* tree = new TreeNode(1); tree->left = new TreeNode(2); tree->right = new TreeNode(3); tree->left->left = new TreeNode(4); tree->left->right = new TreeNode(5); tree->right->left = new TreeNode(6); tree->right->right = new TreeNode(7); vector<int> ans = Solution::preorderTraversal(tree); for (auto& x : ans) cout << x << " "; cout << endl; return 0; }
21.706897
75
0.612391
755f00c26dd122d684c7a1211db67d8f9181ba13
9,419
cpp
C++
lepra/src/metafile.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
9
2019-09-03T18:33:31.000Z
2022-02-04T04:00:02.000Z
lepra/src/metafile.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
lepra/src/metafile.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
// Author: Jonas Byström // Copyright (c) Pixel Doctrine #include "pch.h" #include "../include/metafile.h" #include <algorithm> #include "../include/path.h" namespace lepra { MetaFile::MetaFile() : disk_file_(0), archive_file_(0), reader_(0), writer_(0), endian_(Endian::kTypeBigEndian) { } MetaFile::MetaFile(Reader* reader) : disk_file_(0), archive_file_(0), reader_(reader), writer_(0), endian_(Endian::kTypeBigEndian) { } MetaFile::MetaFile(Writer* writer) : disk_file_(0), archive_file_(0), reader_(0), writer_(writer), endian_(Endian::kTypeBigEndian) { } MetaFile::MetaFile(Reader* reader, Writer* writer) : disk_file_(0), archive_file_(0), reader_(reader), writer_(writer), endian_(Endian::kTypeBigEndian) { } MetaFile::~MetaFile() { Close(); } bool MetaFile::Open(const str& file_name, OpenMode mode, bool create_path, Endian::EndianType endian) { Close(); SetEndian(endian); bool ok = false; size_t _split_index = 0; str path; str file; bool do_continue = true; // Find a valid combination of archive and file... while (do_continue) { do_continue = SplitPath(file_name, path, file, _split_index); if (_split_index == 0) { ok = DiskFile::Exists(path); if (ok) { AllocDiskFile(); ok = disk_file_->Open(path, ToDiskFileMode(mode), create_path, endian); if (ok) { do_continue = false; } else { Close(); } } } else { str _archive_name; ok = FindValidArchiveName(path, _archive_name); if (ok) { AllocArchiveFile(_archive_name); ok = archive_file_->Open(file, ToArchiveMode(mode), endian); } if (ok) { do_continue = false; } else { Close(); } } _split_index++; } ok = (disk_file_ != 0 || archive_file_ != 0); return ok; } void MetaFile::Close() { if (disk_file_ != 0) { disk_file_->Close(); delete disk_file_; disk_file_ = 0; } else if (archive_file_ != 0) { archive_file_->Close(); delete archive_file_; archive_file_ = 0; } } void MetaFile::SetEndian(Endian::EndianType endian) { endian_ = endian; Parent::SetEndian(endian); if (disk_file_ != 0) { disk_file_->SetEndian(endian_); } else if (archive_file_ != 0) { archive_file_->SetEndian(endian_); } } Endian::EndianType MetaFile::GetEndian() { return endian_; } int64 MetaFile::GetSize() const { int64 _size = 0; if (disk_file_ != 0) { _size = disk_file_->GetSize(); } else if (archive_file_ != 0) { _size = archive_file_->GetSize(); } return _size; } int64 MetaFile::Tell() const { int64 pos = 0; if (disk_file_ != 0) { pos = disk_file_->Tell(); } else if (archive_file_ != 0) { pos = archive_file_->Tell(); } return pos; } int64 MetaFile::Seek(int64 offset, FileOrigin from) { int64 _offset = 0; if (disk_file_ != 0) { _offset = disk_file_->Seek(offset, from); } else if (archive_file_ != 0) { _offset = archive_file_->Seek(offset, from); } return _offset; } str MetaFile::GetFullName() const { if (disk_file_ != 0) { return disk_file_->GetFullName(); } else if (archive_file_ != 0) { return archive_file_->GetFullName(); } return ""; } str MetaFile::GetName() const { if (disk_file_ != 0) { return disk_file_->GetName(); } else if (archive_file_ != 0) { return archive_file_->GetName(); } return ""; } str MetaFile::GetPath() const { if (disk_file_ != 0) { return disk_file_->GetPath(); } else if (archive_file_ != 0) { return archive_file_->GetPath(); } return ""; } IOError MetaFile::ReadData(void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->ReadData(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->ReadData(buffer, size); } return error; } IOError MetaFile::WriteData(const void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->WriteData(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->WriteData(buffer, size); } return error; } int64 MetaFile::GetAvailable() const { int64 available = 0; if (disk_file_ != 0) { available = disk_file_->GetAvailable(); } else if (archive_file_ != 0) { available = archive_file_->GetAvailable(); } return available; } IOError MetaFile::ReadRaw(void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->ReadRaw(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->ReadRaw(buffer, size); } return error; } IOError MetaFile::Skip(size_t size) { return (Parent::Skip(size)); } IOError MetaFile::WriteRaw(const void* buffer, size_t size) { IOError error = kIoFileNotOpen; if (disk_file_ != 0) { error = disk_file_->WriteRaw(buffer, size); } else if (archive_file_ != 0) { error = archive_file_->WriteRaw(buffer, size); } return error; } void MetaFile::Flush() { if (disk_file_ != 0) { disk_file_->Flush(); } else if (archive_file_ != 0) { archive_file_->Flush(); } } void MetaFile::AllocDiskFile() { if(reader_ != 0 && writer_ != 0) { disk_file_ = new DiskFile(reader_, writer_); } else if(reader_ != 0) { disk_file_ = new DiskFile(reader_); } else if(writer_ != 0) { disk_file_ = new DiskFile(writer_); } else { disk_file_ = new DiskFile(); } disk_file_->SetEndian(endian_); } void MetaFile::AllocArchiveFile(const str& archive_name) { if(reader_ != 0 && writer_ != 0) { archive_file_ = new ArchiveFile(archive_name, reader_, writer_); } else if(reader_ != 0) { archive_file_ = new ArchiveFile(archive_name, reader_); } else if(writer_ != 0) { archive_file_ = new ArchiveFile(archive_name, writer_); } else { archive_file_ = new ArchiveFile(archive_name); } if (IsZipFile(Path::GetExtension(archive_name))) { archive_file_->SetArchiveType(ArchiveFile::kZip); } else { archive_file_->SetArchiveType(ArchiveFile::kUncompressed); } archive_file_->SetEndian(endian_); } DiskFile::OpenMode MetaFile::ToDiskFileMode(OpenMode mode) { DiskFile::OpenMode _mode = DiskFile::kModeRead; switch (mode) { case kReadOnly: { _mode = DiskFile::kModeRead; break; } case kWriteOnly: { _mode = DiskFile::kModeWrite; break; } case kWriteAppend: { _mode = DiskFile::kModeWriteAppend; break; } } return _mode; } ArchiveFile::OpenMode MetaFile::ToArchiveMode(OpenMode mode) { ArchiveFile::OpenMode _mode = ArchiveFile::kReadOnly; switch (mode) { case kReadOnly: { _mode = ArchiveFile::kReadOnly; break; } case kWriteOnly: { _mode = ArchiveFile::kWriteOnly; break; } case kWriteAppend: { _mode = ArchiveFile::kWriteAppend; break; } } return _mode; } bool MetaFile::IsZipFile(const str& extension) { bool ok = false; if (zip_extensions_ != 0) { ok = (std::find(zip_extensions_->begin(), zip_extensions_->end(), extension) != zip_extensions_->end()); } return ok; } bool MetaFile::IsUncompressedArchive(const str& extension) { bool ok = false; if (archive_extensions_ != 0) { ok = (std::find(archive_extensions_->begin(), archive_extensions_->end(), extension) != archive_extensions_->end()); } return ok; } void MetaFile::AddZipExtension(const str& extension) { if (zip_extensions_ == 0) { zip_extensions_ = new std::list<str>(); } zip_extensions_->push_back(extension); zip_extensions_->sort(); zip_extensions_->unique(); } void MetaFile::AddUncompressedExtension(const str& extension) { if (archive_extensions_ == 0) { archive_extensions_ = new std::list<str>(); } archive_extensions_->push_back(extension); archive_extensions_->sort(); archive_extensions_->unique(); } void MetaFile::ClearExtensions() { if (zip_extensions_) { zip_extensions_->clear(); delete zip_extensions_; zip_extensions_ = 0; } if (archive_extensions_) { archive_extensions_->clear(); delete archive_extensions_; archive_extensions_ = 0; } } std::list<str>* MetaFile::zip_extensions_; std::list<str>* MetaFile::archive_extensions_; bool MetaFile::SplitPath(const str& filename, str& left, str& right, size_t split_index) { bool ok = true; size_t _split_index = filename.length(); size_t i; for (i = 0; i < split_index; i++) { int index1 = (int)filename.rfind((char)'/', _split_index-1); int index2 = (int)filename.rfind((char)'\\', _split_index-1); if (index1 > index2) { _split_index = index1; } else if (index2 > index1) { _split_index = index2; } else if (index1 == -1 && index2 == -1) { _split_index = 0; ok = false; break; } } left = filename.substr(0, _split_index); right = filename.substr(_split_index); if (!right.empty() && (right[0] == '/' || right[0] == '\\')) { right.erase(0, 1); } return ok; } bool MetaFile::FindValidArchiveName(const str& archive_prefix, str& full_archive_name) { std::list<str>::iterator iter; bool ok = false; if (zip_extensions_ != 0) { for (iter = zip_extensions_->begin(); iter != zip_extensions_->end(); ++iter) { str _file_name(archive_prefix + (*iter)); if (DiskFile::Exists(_file_name) == true) { full_archive_name = _file_name; ok = true; break; } } } if (ok == false && archive_extensions_ != 0) { for (iter = archive_extensions_->begin(); iter != archive_extensions_->end(); ++iter) { str _file_name(archive_prefix + (*iter)); if (DiskFile::Exists(_file_name) == true) { full_archive_name = _file_name; ok = true; break; } } } return ok; } }
20.655702
118
0.669498
755f0257792b6d75a9c44b69ae9cf39ae2f5185b
4,172
cpp
C++
src/lib/lgui/widgets/wrapwidget.cpp
jacmoe/lgui
92f7e655832487b9ac29ef6043a79745329c90f6
[ "BSD-3-Clause" ]
4
2020-12-31T00:01:32.000Z
2021-11-20T15:39:46.000Z
src/lib/lgui/widgets/wrapwidget.cpp
jacmoe/lgui
92f7e655832487b9ac29ef6043a79745329c90f6
[ "BSD-3-Clause" ]
null
null
null
src/lib/lgui/widgets/wrapwidget.cpp
jacmoe/lgui
92f7e655832487b9ac29ef6043a79745329c90f6
[ "BSD-3-Clause" ]
1
2021-11-10T16:55:09.000Z
2021-11-10T16:55:09.000Z
/* _ _ * | | (_) * | | __ _ _ _ _ * | | / _` || | | || | * | || (_| || |_| || | * |_| \__, | \__,_||_| * __/ | * |___/ * * Copyright (c) 2015-20 frank256 * * License (BSD): * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "wrapwidget.h" #include "lgui/platform/graphics.h" #include "lgui/drawevent.h" namespace lgui { WrapWidget::WrapWidget(Widget* widget) : mcontent(widget) { if (widget) set_content(widget); } void WrapWidget::draw(const DrawEvent& de) const { if (mcontent) { // FIXME: draw backgr. when mcontent == nullptr? draw_background(de); de.gfx().push_draw_area(children_area(), false); mcontent->draw(DrawEvent(de.gfx(), de.draw_disabled() || mcontent->is_disabled(), de.opacity() * mcontent->effective_opacity())); de.gfx().pop_draw_area(); } } Rect WrapWidget::children_area() const { if (mcontent) return lgui::Rect(mpadding.left_top_offs(), mpadding.sub(size())); else return size_rect(); } Widget* WrapWidget::get_child_at(PointF) { // FIXME: check contains? return mcontent; } void WrapWidget::set_content(lgui::Widget* widget) { mcontent = widget; if (widget) { widget->set_pos(0, 0); configure_new_child(*widget); if (!widget->has_strong_style() && &widget->style() != &style()) widget->set_style(&style()); request_layout(); } } void WrapWidget::style_changed() { if (mcontent && !mcontent->has_strong_style()) mcontent->set_style(&style()); } void WrapWidget::resized(const Size& old_size) { (void) old_size; if (mcontent) { mcontent->layout(Rect({0, 0}, mpadding.sub(size()))); } } void WrapWidget::set_padding(const Padding& padding) { mpadding = padding; set_size(Size(width(), height())); // will set size of content } MeasureResults WrapWidget::measure(SizeConstraint wc, SizeConstraint hc) { if (!mcontent) return force_size_constraints(Size(mpadding.horz(), mpadding.vert()), wc, hc); else { MeasureResults r = mcontent->measure(wc.sub(mpadding.horz()), hc.sub(mpadding.vert())); return force_size_constraints(mpadding.add(r), wc, hc); } } Size WrapWidget::min_size_hint() { Size s; if (mcontent) s = mcontent->min_size_hint(); return mpadding.add(s); } void WrapWidget::visit_down(const std::function<void(Widget&)>& f) { f(*this); if (mcontent) mcontent->visit_down(f); } void WrapWidget::child_about_to_die(Widget& child) { if (&child == mcontent) set_content(nullptr); } }
31.368421
95
0.659156
7561738404c4724e9c0ea390ee747020e653f54a
654
cpp
C++
codechef/febLongChallenge20/ony.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
codechef/febLongChallenge20/ony.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
codechef/febLongChallenge20/ony.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
// vovuh.pb(temp);vovuh.pb(temp1);vovuh.pb(temp2);vovuh.pb(temp3); for(int tat = 0; tat <= 3; tat++) { auto x = adj[tat]; int sz = x.size(); if (sz > 0) { sort(x.begin(),x.end(),greater<int>()); if (x[0] > 0) vovuh.pb(x[0]); } } sort(vovuh.begin(), vovuh.end(),greater<int>()); // ll cnt = 0; cout << temp4 << " is the new ans" << endl; for (auto ss : vovuh) { cout << ss << " "; } ll lauda = 1, vovuhKaSize = vovuh.size(); temp4 -= 100*(4-vovuhKaSize); for (int i = 0; i < vovuhKaSize; i++) { temp4 +=(100-25*(lauda-1))*vovuh[i]; lauda++; } // ans = max(ans, temp4); if (temp4 > ans) { ans = temp4; cout << endl; }
21.8
66
0.529052
756286d348fbeee56dd518ef8d73d72403bdc748
476
cpp
C++
Project2/main.cpp
cpurev/CS311
c86bb0dc917ff98edf698adedb4c3f0f9745ce9f
[ "MIT" ]
null
null
null
Project2/main.cpp
cpurev/CS311
c86bb0dc917ff98edf698adedb4c3f0f9745ce9f
[ "MIT" ]
null
null
null
Project2/main.cpp
cpurev/CS311
c86bb0dc917ff98edf698adedb4c3f0f9745ce9f
[ "MIT" ]
1
2021-11-16T05:01:57.000Z
2021-11-16T05:01:57.000Z
#include "ssarray.h" #include <iostream> #include <utility> #include <string> class Count{ public: Count(){ ++_ctorCount; } ~Count(){ --_ctorCount; ++_DctorCount; } static size_t _ctorCount; static size_t _DctorCount; }; size_t Count::_ctorCount = size_t(0); size_t Count::_DctorCount = size_t(0); int main(){ SSArray<std::string> ss1; SSArray<int> ss2; std::cout << ((ss1 == ss2) ? "yes" : "no") << std::endl; return 1; }
15.354839
58
0.602941
75662c717c2d191852fb1b9030c03cedb4756939
2,696
cpp
C++
09-lcd/02-lcd-reg/lcd-reg.cpp
initdb/embedded-systems
7a716a22a045510a9cccded6c15a40ac3ed72858
[ "MIT" ]
3
2019-03-19T19:59:05.000Z
2019-11-22T19:02:56.000Z
09-lcd/02-lcd-reg/lcd-reg.cpp
initdb/embedded-systems
7a716a22a045510a9cccded6c15a40ac3ed72858
[ "MIT" ]
null
null
null
09-lcd/02-lcd-reg/lcd-reg.cpp
initdb/embedded-systems
7a716a22a045510a9cccded6c15a40ac3ed72858
[ "MIT" ]
1
2019-03-26T17:16:09.000Z
2019-03-26T17:16:09.000Z
#include "Arduino.h" #include <LiquidCrystal.h> #define RS 12 // controls RS pin of LCD (digital pin 12) #define E 11 // controls Enable pin to LCD (digital pin 11) // Note: Not need to control RW pin: it's set to GND by hardware since we always write and never read void enablePulse() { digitalWrite(E, LOW); delayMicroseconds(3); digitalWrite(E, HIGH); delayMicroseconds(3); // enable pulse must be > 450 ns, see p49 of HD44780 manual digitalWrite(E, LOW); delayMicroseconds(200); // commands need > 37 us to settle } // write an instruction, indicated by RS == LOW void writeInstruction(char instr) { digitalWrite(RS, LOW); PORTC = instr; enablePulse(); // commit command, short pulse on E pin PORTC = (instr << 4); enablePulse(); } // write character, indicated by RS == HIGH, automatically moves cursor void writeData(char data) { digitalWrite(RS, HIGH); PORTC = data; enablePulse(); // commit command, short pulse on E pin PORTC = (data << 4); enablePulse(); } void setup() { // set pins to output pinMode(RS, OUTPUT); pinMode(E, OUTPUT); DDRC = 0xF0; // data pins PC7 to PC4 // Set RS and E to Low to begin commands digitalWrite(RS, LOW); digitalWrite(E, LOW); // manual HD44780, p46, Figure 24: initialization specification for 4-bit mode // wait for more than 15 ms delay(30); // initialization sequence (Figure 24): sequence (0 0 0 0 1 1), then wait for > 4.1 ms PORTC = (0x03 << 4); enablePulse(); delay(5); // initialization sequence (Figure 24): sequence (0 0 0 0 1 1), then wait for > 100 us PORTC = (0x03 << 4); // only highest byte enablePulse(); delayMicroseconds(200); // initialization sequence: sequence (0 0 0 0 1 1) PORTC = (0x03 << 4); // only highest byte enablePulse(); delayMicroseconds(50); //finally, set to 4-bit interface: (0 0 0 0 1 1) PORTC = (0x02 << 4); enablePulse(); // TODO: Function Set, 4-bit, 2 line mode, 5x8 dots // TODO: Return Home, set cursor to beginning delayMicroseconds(2500); // TODO: Entry Mode Set, increment cursor, no display shift // clear display: 0x01 writeInstruction(0x01); delayMicroseconds(300); } void loop() { // set cursor to beginning if first line: command 0x80 (DDRAM address 0x00, see p11 of manual) writeInstruction(0x80); char line1[] = {"Embedded Systems "}; // TODO: Write line 1 // set cursor to beginning of 2nd line line: command 0xC0 (DDRAM address 0x40, see p11 of manual) writeInstruction(0xC0); char line2[] = {"macht Spass"}; // TODO: Write line 2 }
26.431373
101
0.640208
75681b4297eca4f3ba317ff88d40fde6acf4530a
272
cpp
C++
src/world/light.cpp
fiddleplum/ve
1e45de0488d593069032714ebe67725f468054f8
[ "MIT" ]
null
null
null
src/world/light.cpp
fiddleplum/ve
1e45de0488d593069032714ebe67725f468054f8
[ "MIT" ]
16
2016-12-27T16:57:09.000Z
2017-04-30T23:34:58.000Z
src/world/light.cpp
fiddleplum/ve
1e45de0488d593069032714ebe67725f468054f8
[ "MIT" ]
null
null
null
#include "world/light.hpp" namespace ve { namespace world { Light::Light() { color = {1, 1, 1}; } Light::~Light() { } Vector3f Light::getColor() const { return color; } void Light::setColor(Vector3f color_) { color = color_; } } }
9.714286
39
0.558824
7569b5deab37fa6f51deae6d8c8ce08e22136157
1,410
cpp
C++
Pingduino/Button.cpp
rubyist/pingduino
15dda1c6af7c742a0ec409b177a38e36ac42f7ed
[ "MIT" ]
6
2015-01-29T20:47:09.000Z
2018-08-01T11:01:29.000Z
Pingduino/Button.cpp
rubyist/pingduino
15dda1c6af7c742a0ec409b177a38e36ac42f7ed
[ "MIT" ]
1
2017-02-11T11:48:05.000Z
2017-02-11T11:48:05.000Z
Pingduino/Button.cpp
rubyist/pingduino
15dda1c6af7c742a0ec409b177a38e36ac42f7ed
[ "MIT" ]
null
null
null
#include "Arduino.h" #include "Button.h" #define PRESSTIME 500 #define LONGPRESSTIME 1000 enum ButtonState { Start, Waiting, PressCount, ReleaseWait, LongPressWait }; Button::Button(int pin) { pinMode(pin, INPUT); _pin = pin; _state = Start; } void Button::setPressCallback(buttonCallback cb) { _pressCallback = cb; } void Button::setDoublePressCallback(buttonCallback cb) { _doublePressCallback = cb; } void Button::setLongPressCallback(buttonCallback cb) { _longPressCallback = cb; } void Button::tick() { int button = digitalRead(_pin); unsigned long now = millis(); switch(_state) { case Start: if (button == HIGH) { _state = Waiting; _startTime = now; } break; case Waiting: if (button == LOW) { _state = PressCount; } else if ((button == HIGH) && (now > _startTime + LONGPRESSTIME)) { _state = LongPressWait; } break; case PressCount: if (now > _startTime + PRESSTIME) { if (_pressCallback) _pressCallback(); _state = Start; } else if (button == HIGH) { _state = ReleaseWait; } break; case ReleaseWait: if (button == LOW) { if (_doublePressCallback) _doublePressCallback(); _state = Start; } break; case LongPressWait: if (button == LOW) { if (_longPressCallback) _longPressCallback(); _state = Start; } break; } }
20.142857
85
0.628369
756ba6c9e52a7081be16b9be4f2173e1c55f0da0
1,270
cpp
C++
Source/Archiver/FileSerializer.cpp
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
Source/Archiver/FileSerializer.cpp
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
Source/Archiver/FileSerializer.cpp
frobro98/Musa
6e7dcd5d828ca123ce8f43d531948a6486428a3d
[ "MIT" ]
null
null
null
// Copyright 2020, Nathan Blane #include "FileSerializer.hpp" #include "Logging/CoreLogChannels.hpp" #include "Logging/LogFunctions.hpp" FileSerializer::FileSerializer(const Path& filePath) : pathToFile(filePath) { bool result = FileSystem::OpenFile(handle, pathToFile.GetString(), FileMode::Write); if (!result) { // TODO - GetLastError MUSA_ERR(SerializationLog, "Failed to open file {}", *pathToFile.GetFileName()); } } FileSerializer::~FileSerializer() { Flush(); auto result = FileSystem::CloseFile(handle); if (!result) { // TODO - GetLastError MUSA_ERR(SerializationLog, "Failed to close file {}", *pathToFile.GetFileName()); } } void FileSerializer::SerializeData(const void* data, size_t dataSize) { serializedData.Add(data, dataSize); } void FileSerializer::Flush() { // TODO - Using the low level file writing interface. Should consider not doing this sort of thing because of the limitations for loading large files auto result = FileSystem::WriteFile(handle, serializedData.Offset(bufferWriteIndex), (u32)serializedData.Size() - bufferWriteIndex); if (!result) { // TODO - GetLastError MUSA_ERR(SerializationLog, "Failed to write to file {}", *pathToFile.GetFileName()); } bufferWriteIndex = (u32)serializedData.Size(); }
27.608696
150
0.740157
756e3e110e56ec813d1c8c29b1be78995bbef5f2
1,737
hh
C++
dune/xt/common/numeric.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
2
2020-02-08T04:08:52.000Z
2020-08-01T18:54:14.000Z
dune/xt/common/numeric.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
35
2019-08-19T12:06:35.000Z
2020-03-27T08:20:39.000Z
dune/xt/common/numeric.hh
dune-community/dune-xt
da921524c6fff8d60c715cb4849a0bdd5f020d2b
[ "BSD-2-Clause" ]
1
2020-02-08T04:09:34.000Z
2020-02-08T04:09:34.000Z
// This file is part of the dune-xt project: // https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt // Copyright 2009-2021 dune-xt developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // René Fritze (2020) // Tobias Leibner (2019 - 2020) #ifndef DUNE_XT_COMMON_NUMERIC_HH #define DUNE_XT_COMMON_NUMERIC_HH #include <numeric> #if defined(__cpp_lib_parallel_algorithm) && __cpp_lib_parallel_algorithm >= 201603 # define CPP17_PARALLELISM_TS_SUPPORTED 1 #else # define CPP17_PARALLELISM_TS_SUPPORTED 0 #endif namespace Dune::XT::Common { // Uses std::reduce if available, and falls back to std::accumulate on older compilers. // The std::reduce versions with an execution policy as first argument are not supported. template <class... Args> decltype(auto) reduce(Args&&... args) { #if CPP17_PARALLELISM_TS_SUPPORTED return std::reduce(std::forward<Args>(args)...); #else return std::accumulate(std::forward<Args>(args)...); #endif } // Uses std::transform_reduce if available, and falls back to std::inner_product on older compilers. // The std::transform_reduce versions with an execution policy as first argument are not supported. template <class... Args> decltype(auto) transform_reduce(Args&&... args) { #if CPP17_PARALLELISM_TS_SUPPORTED return std::transform_reduce(std::forward<Args>(args)...); #else return std::inner_product(std::forward<Args>(args)...); #endif } } // namespace Dune::XT::Common #endif // DUNE_XT_COMMON_NUMERIC_HH
32.773585
100
0.745538
757109a8c12f857a049986a1b25b17804c53d25f
12,809
cpp
C++
src/c/HarmoniaInterface.cpp
Hiiragi/Harmonia
e47e811364e15a9bc7b2322c10d1e35fca041e2a
[ "MIT" ]
null
null
null
src/c/HarmoniaInterface.cpp
Hiiragi/Harmonia
e47e811364e15a9bc7b2322c10d1e35fca041e2a
[ "MIT" ]
null
null
null
src/c/HarmoniaInterface.cpp
Hiiragi/Harmonia
e47e811364e15a9bc7b2322c10d1e35fca041e2a
[ "MIT" ]
null
null
null
/** * Harmonia * * Copyright (c) 2018 Hiiragi * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ #include "HarmoniaInterface.h" #include "Harmonia.h" #include "ogg/ogg.h" #include <algorithm> #include <string> #include <sstream> // General #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_initialize(unsigned int bufferSize) { Harmonia::initialize(bufferSize); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_finalize() { Harmonia::finalize(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_register_sound(const char* id, unsigned char* binaryData, int size, unsigned int loopStartPoint, unsigned int loopLength) { Harmonia::register_sound(id, binaryData, size, loopStartPoint, loopLength); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_register_sounds(const char** idList, unsigned char** binaryDataList, int* sizeList, unsigned int* loopStartPointList, unsigned int* loopLengthList, unsigned int numRegister) { Harmonia::register_sounds(idList, binaryDataList, sizeList, loopStartPointList, loopLengthList, numRegister); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_unregister_sound(const char* id) { Harmonia::unregister_sound(id); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_pause_all() { Harmonia::pause(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_resume_all() { Harmonia::resume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_stop_all() { Harmonia::stop(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif float harmonia_get_master_volume() { SoundGroup* masterGroup = Harmonia::get_group(Harmonia::MASTER_GROUP_NAME.c_str()); return masterGroup->get_volume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_master_volume(float volume) { SoundGroup* masterGroup = Harmonia::get_group(Harmonia::MASTER_GROUP_NAME.c_str()); return masterGroup->set_volume(volume); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_mute_all() { Harmonia::mute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_unmute_all() { Harmonia::unmute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_start_capture_errors() { Harmonia::start_capture_errors(); } int _harmonia_capture_data_size; #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_errors() { std::list<HarmoniaErrorData*>* list = Harmonia::get_capture_errors(); if (list != NULL && list->size() > 0) { std::string jsonStr = "{\"errors\":["; std::for_each(list->begin(), list->end(), [&jsonStr](HarmoniaErrorData* data) { int type = static_cast<int>(data->get_error_type()); std::string typeStr; #if ANDROID || _ANDROID_ std::stringstream stream; stream << "" << type; typeStr = stream.str(); #else typeStr = std::to_string(type); #endif jsonStr += "{\"type\":" + typeStr + "},"; }); jsonStr = jsonStr.substr(0, jsonStr.size() - 1); jsonStr += "]}"; const char* str = jsonStr.c_str(); size_t length = strlen(str) + 1; char* returnChar = (char*)malloc(length); #if _WIN32 strcpy_s(returnChar, length, str); #else strcpy(returnChar, str); #endif _harmonia_capture_data_size = (int)length; return returnChar; } return NULL; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_errors_with_size(int* size) { char* result = harmonia_get_capture_errors(); if (result == NULL) { *size = 0; } else { *size = _harmonia_capture_data_size; } return result; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_stop_capture_errors() { Harmonia::stop_capture_errors(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_start_capture_events() { Harmonia::start_capture_events(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_events() { std::list<SoundEventData*>* list = Harmonia::get_captured_events(); if (list != NULL && list->size() > 0) { std::string jsonStr = "{\"events\":["; std::for_each(list->begin(), list->end(), [&jsonStr](SoundEventData* data) { jsonStr += "{\"rid\":\"" + std::string(data->get_rid()) + "\",\"sid\":\"" + std::string(data->get_sid()) + "\","; int type = static_cast<int>(data->get_type()); std::string typeStr; #if ANDROID || _ANDROID_ std::stringstream stream; stream << "" << type; typeStr = stream.str(); #else typeStr = std::to_string(type); #endif jsonStr += "\"type\":" + typeStr; jsonStr += "},"; delete data; }); jsonStr = jsonStr.substr(0, jsonStr.size() - 1); jsonStr += "]}"; delete list; const char* str = jsonStr.c_str(); size_t length = strlen(str) + 1; char* returnChar = (char*)malloc(length); #if _WIN32 strcpy_s(returnChar, length, str); #else strcpy(returnChar, str); #endif _harmonia_capture_data_size = (int)length; return returnChar; } return NULL; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif char* harmonia_get_capture_events_with_size(int* size) { char* result = harmonia_get_capture_events(); if (result == NULL) { *size = 0; } else { *size = _harmonia_capture_data_size; } return result; } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_stop_capture_events() { Harmonia::stop_capture_events(); } // Sound #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_play(const char* registeredId, const char* soundId, const char* targetGroupId) { Harmonia::play(registeredId, soundId, targetGroupId); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_pause(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->pause(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_resume(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->resume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_stop(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->stop(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_mute(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->mute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_sound_unmute(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->unmute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif float harmonia_get_sound_volume(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); return data->get_volume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_sound_volume(const char* playingDataId, float volume) { PlayingData* data = Harmonia::get_playing_data(playingDataId); data->set_volume(volume); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif unsigned int harmonia_get_sound_status(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); return data->get_status(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif unsigned int harmonia_get_sound_current_position(const char* playingDataId) { PlayingData* data = Harmonia::get_playing_data(playingDataId); return (unsigned int)data->get_current_position(); } // Group #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_create_group(const char* groupId, const char* parentGroupId, int maxPolyphony) { Harmonia::create_group(groupId, parentGroupId, maxPolyphony); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_delete_group(const char* groupId) { Harmonia::delete_group(groupId); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_pause(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->pause(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_resume(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->resume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_stop(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->stop(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_mute(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->mute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_group_unmute(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); group->unmute(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif float harmonia_get_group_volume(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); return group->get_volume(); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_group_volume(const char* groupId, float volume) { SoundGroup* group = Harmonia::get_group(groupId); group->set_volume(volume); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif void harmonia_set_ducker(const char* triggerGroupId, const char* targetGroupId, float ratio, float attackTimeByMS, float releaseTimeByMS) { SoundGroup* triggerGroup = Harmonia::get_group(triggerGroupId); SoundGroup* targetGroup = Harmonia::get_group(targetGroupId); targetGroup->set_ducker(triggerGroup, ratio, attackTimeByMS, releaseTimeByMS); } #if _WIN32 extern "C" _declspec(dllexport) #else extern "C" #endif unsigned int harmonia_get_group_status(const char* groupId) { SoundGroup* group = Harmonia::get_group(groupId); return group->get_status(); } /* #if _WIN32 extern "C" _declspec(dllexport) void initialize() { Harmonia::initialize(); } extern "C" _declspec(dllexport) unsigned int registerSound(unsigned char* binaryPointer, unsigned long size) { return Harmonia::registerSound(binaryPointer, size); } extern "C" _declspec(dllexport) int play(unsigned int registeredId) { return Harmonia::play(registeredId); } extern "C" _declspec(dllexport) ogg_int64_t getCurrentTimeInPlayer(unsigned int playerId) { return Harmonia::getCurrentTimeInPlayer(playerId); } extern "C" _declspec(dllexport) void finalize() { Harmonia::finalize(); } #elif (__ANDROID__ || ANDROID) extern "C" { void initialize() { Harmonia::initialize(); } void initializeForAndroid(int sampleRate, int bufferSize) { Harmonia::initializeForAndroid(sampleRate, bufferSize); } unsigned int registerSound(unsigned char* binaryPointer, unsigned int size) { return Harmonia::registerSound(binaryPointer, size); } int play(unsigned int registeredId) { return Harmonia::play(registeredId); } ogg_int64_t getCurrentTimeInPlayer(unsigned int playerId) { return Harmonia::getCurrentTimeInPlayer(playerId); } void harmonia_pause() { Harmonia::pause(); } void harmonia_resume() { Harmonia::resume(); } void finalize() { Harmonia::finalize(); } } #elif __APPLE__ #include "TargetConditionals.h" #if TARGET_OS_IPHONE || TARGET_OS_MAC #include <string.h> #include <stdlib.h> extern "C" { void initialize() { Harmonia::initialize(); } unsigned int registerSound(unsigned char* binaryPointer, unsigned int size) { return Harmonia::registerSound(binaryPointer, size); } int play(unsigned int registeredId) { return Harmonia::play(registeredId); } ogg_int64_t getCurrentTimeInPlayer(unsigned int playerId) { return Harmonia::getCurrentTimeInPlayer(playerId); } void finalize() { Harmonia::finalize(); } const char* aaaaa() { const char *str = "{\"e\":[{\"t\":1,\"v\":2},{\"t\":3,\"v\":4}]}"; char* retStr = (char*)malloc(strlen(str) + 1); strcpy(retStr, str); return retStr; } } #endif #endif */
18.672012
187
0.708408
75737379a402b92d7209b5a3668b3bd1f84577d8
53
hpp
C++
src/boost_numeric_odeint_util_unit_helper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_numeric_odeint_util_unit_helper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_numeric_odeint_util_unit_helper.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/numeric/odeint/util/unit_helper.hpp>
26.5
52
0.811321
7573bfef037cbe0664a1346c1ec5c5eecc9e9a9a
12,410
cpp
C++
Engine/Source/Runtime/ShaderCore/Private/VertexFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/ShaderCore/Private/VertexFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/ShaderCore/Private/VertexFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= VertexFactory.cpp: Vertex factory implementation =============================================================================*/ #include "VertexFactory.h" #include "Serialization/MemoryWriter.h" #include "UObject/DebugSerializationFlags.h" uint32 FVertexFactoryType::NextHashIndex = 0; bool FVertexFactoryType::bInitializedSerializationHistory = false; /** * @return The global shader factory list. */ TLinkedList<FVertexFactoryType*>*& FVertexFactoryType::GetTypeList() { static TLinkedList<FVertexFactoryType*>* TypeList = NULL; return TypeList; } /** * Finds a FVertexFactoryType by name. */ FVertexFactoryType* FVertexFactoryType::GetVFByName(const FString& VFName) { for(TLinkedList<FVertexFactoryType*>::TIterator It(GetTypeList()); It; It.Next()) { FString CurrentVFName = FString(It->GetName()); if (CurrentVFName == VFName) { return *It; } } return NULL; } void FVertexFactoryType::Initialize(const TMap<FString, TArray<const TCHAR*> >& ShaderFileToUniformBufferVariables) { if (!FPlatformProperties::RequiresCookedData()) { // Cache serialization history for each VF type // This history is used to detect when shader serialization changes without a corresponding .usf change for(TLinkedList<FVertexFactoryType*>::TIterator It(FVertexFactoryType::GetTypeList()); It; It.Next()) { FVertexFactoryType* Type = *It; GenerateReferencedUniformBuffers(Type->ShaderFilename, Type->Name, ShaderFileToUniformBufferVariables, Type->ReferencedUniformBufferStructsCache); for (int32 Frequency = 0; Frequency < SF_NumFrequencies; Frequency++) { // Construct a temporary shader parameter instance, which is initialized to safe values for serialization FVertexFactoryShaderParameters* Parameters = Type->CreateShaderParameters((EShaderFrequency)Frequency); if (Parameters) { // Serialize the temp shader to memory and record the number and sizes of serializations TArray<uint8> TempData; FMemoryWriter Ar(TempData, true); FShaderSaveArchive SaveArchive(Ar, Type->SerializationHistory[Frequency]); Parameters->Serialize(SaveArchive); delete Parameters; } } } } bInitializedSerializationHistory = true; } void FVertexFactoryType::Uninitialize() { for(TLinkedList<FVertexFactoryType*>::TIterator It(FVertexFactoryType::GetTypeList()); It; It.Next()) { FVertexFactoryType* Type = *It; for (int32 Frequency = 0; Frequency < SF_NumFrequencies; Frequency++) { Type->SerializationHistory[Frequency] = FSerializationHistory(); } } bInitializedSerializationHistory = false; } FVertexFactoryType::FVertexFactoryType( const TCHAR* InName, const TCHAR* InShaderFilename, bool bInUsedWithMaterials, bool bInSupportsStaticLighting, bool bInSupportsDynamicLighting, bool bInSupportsPrecisePrevWorldPos, bool bInSupportsPositionOnly, ConstructParametersType InConstructParameters, ShouldCacheType InShouldCache, ModifyCompilationEnvironmentType InModifyCompilationEnvironment, SupportsTessellationShadersType InSupportsTessellationShaders ): Name(InName), ShaderFilename(InShaderFilename), TypeName(InName), bUsedWithMaterials(bInUsedWithMaterials), bSupportsStaticLighting(bInSupportsStaticLighting), bSupportsDynamicLighting(bInSupportsDynamicLighting), bSupportsPrecisePrevWorldPos(bInSupportsPrecisePrevWorldPos), bSupportsPositionOnly(bInSupportsPositionOnly), ConstructParameters(InConstructParameters), ShouldCacheRef(InShouldCache), ModifyCompilationEnvironmentRef(InModifyCompilationEnvironment), SupportsTessellationShadersRef(InSupportsTessellationShaders), GlobalListLink(this) { // Make sure the format of the source file path is right. check(CheckVirtualShaderFilePath(InShaderFilename)); checkf(FPaths::GetExtension(InShaderFilename) == TEXT("ush"), TEXT("Incorrect virtual shader path extension for vertex factory shader header '%s': Only .ush files should be included."), InShaderFilename); for (int32 Platform = 0; Platform < SP_NumPlatforms; Platform++) { bCachedUniformBufferStructDeclarations[Platform] = false; } // This will trigger if an IMPLEMENT_VERTEX_FACTORY_TYPE was in a module not loaded before InitializeShaderTypes // Vertex factory types need to be implemented in modules that are loaded before that checkf(!bInitializedSerializationHistory, TEXT("VF type was loaded after engine init, use ELoadingPhase::PostConfigInit on your module to cause it to load earlier.")); // Add this vertex factory type to the global list. GlobalListLink.LinkHead(GetTypeList()); // Assign the vertex factory type the next unassigned hash index. HashIndex = NextHashIndex++; } FVertexFactoryType::~FVertexFactoryType() { GlobalListLink.Unlink(); } /** Calculates a Hash based on this vertex factory type's source code and includes */ const FSHAHash& FVertexFactoryType::GetSourceHash() const { return GetShaderFileHash(GetShaderFilename()); } FArchive& operator<<(FArchive& Ar,FVertexFactoryType*& TypeRef) { if(Ar.IsSaving()) { FName TypeName = TypeRef ? FName(TypeRef->GetName()) : NAME_None; Ar << TypeName; } else if(Ar.IsLoading()) { FName TypeName = NAME_None; Ar << TypeName; TypeRef = FindVertexFactoryType(TypeName); } return Ar; } FVertexFactoryType* FindVertexFactoryType(FName TypeName) { // Search the global vertex factory list for a type with a matching name. for(TLinkedList<FVertexFactoryType*>::TIterator VertexFactoryTypeIt(FVertexFactoryType::GetTypeList());VertexFactoryTypeIt;VertexFactoryTypeIt.Next()) { if(VertexFactoryTypeIt->GetFName() == TypeName) { return *VertexFactoryTypeIt; } } return NULL; } void FVertexFactory::Set(FRHICommandList& RHICmdList) const { check(IsInitialized()); for(int32 StreamIndex = 0;StreamIndex < Streams.Num();StreamIndex++) { const FVertexStream& Stream = Streams[StreamIndex]; if (!Stream.bSetByVertexFactoryInSetMesh) { if (!Stream.VertexBuffer) { RHICmdList.SetStreamSource(StreamIndex, nullptr, 0); } else { checkf(Stream.VertexBuffer->IsInitialized(), TEXT("Vertex buffer was not initialized! Stream %u, Stride %u, Name %s"), StreamIndex, Stream.Stride, *Stream.VertexBuffer->GetFriendlyName()); RHICmdList.SetStreamSource(StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset); } } } } void FVertexFactory::OffsetInstanceStreams(FRHICommandList& RHICmdList, uint32 FirstVertex) const { for(int32 StreamIndex = 0;StreamIndex < Streams.Num();StreamIndex++) { const FVertexStream& Stream = Streams[StreamIndex]; if (Stream.bUseInstanceIndex) { RHICmdList.SetStreamSource( StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset + Stream.Stride * FirstVertex); } } } void FVertexFactory::SetPositionStream(FRHICommandList& RHICmdList) const { check(IsInitialized()); // Set the predefined vertex streams. for(int32 StreamIndex = 0;StreamIndex < PositionStream.Num();StreamIndex++) { const FVertexStream& Stream = PositionStream[StreamIndex]; check(Stream.VertexBuffer->IsInitialized()); RHICmdList.SetStreamSource( StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset); } } void FVertexFactory::OffsetPositionInstanceStreams(FRHICommandList& RHICmdList, uint32 FirstVertex) const { for(int32 StreamIndex = 0;StreamIndex < PositionStream.Num();StreamIndex++) { const FVertexStream& Stream = PositionStream[StreamIndex]; if (Stream.bUseInstanceIndex) { RHICmdList.SetStreamSource( StreamIndex, Stream.VertexBuffer->VertexBufferRHI, Stream.Offset + Stream.Stride * FirstVertex); } } } void FVertexFactory::ReleaseRHI() { Declaration.SafeRelease(); PositionDeclaration.SafeRelease(); Streams.Empty(); PositionStream.Empty(); } /** * Fill in array of strides from this factory's vertex streams without shadow/light maps * @param OutStreamStrides - output array of # MaxVertexElementCount stream strides to fill */ int32 FVertexFactory::GetStreamStrides(uint32 *OutStreamStrides, bool bPadWithZeroes) const { int32 StreamIndex; for(StreamIndex = 0;StreamIndex < Streams.Num();++StreamIndex) { OutStreamStrides[StreamIndex] = Streams[StreamIndex].Stride; } if (bPadWithZeroes) { // Pad stream strides with 0's to be safe (they can be used in hashes elsewhere) for (;StreamIndex < MaxVertexElementCount;++StreamIndex) { OutStreamStrides[StreamIndex] = 0; } } return StreamIndex; } /** * Fill in array of strides from this factory's position only vertex streams * @param OutStreamStrides - output array of # MaxVertexElementCount stream strides to fill */ void FVertexFactory::GetPositionStreamStride(uint32 *OutStreamStrides) const { int32 StreamIndex; for(StreamIndex = 0;StreamIndex < PositionStream.Num();++StreamIndex) { OutStreamStrides[StreamIndex] = PositionStream[StreamIndex].Stride; } // Pad stream strides with 0's to be safe (they can be used in hashes elsewhere) for (;StreamIndex < MaxVertexElementCount;++StreamIndex) { OutStreamStrides[StreamIndex] = 0; } } FVertexElement FVertexFactory::AccessStreamComponent(const FVertexStreamComponent& Component,uint8 AttributeIndex) { FVertexStream VertexStream; VertexStream.VertexBuffer = Component.VertexBuffer; VertexStream.Stride = Component.Stride; VertexStream.Offset = 0; VertexStream.bUseInstanceIndex = Component.bUseInstanceIndex; VertexStream.bSetByVertexFactoryInSetMesh = Component.bSetByVertexFactoryInSetMesh; return FVertexElement(Streams.AddUnique(VertexStream),Component.Offset,Component.Type,AttributeIndex,VertexStream.Stride,Component.bUseInstanceIndex); } FVertexElement FVertexFactory::AccessPositionStreamComponent(const FVertexStreamComponent& Component,uint8 AttributeIndex) { FVertexStream VertexStream; VertexStream.VertexBuffer = Component.VertexBuffer; VertexStream.Stride = Component.Stride; VertexStream.Offset = 0; VertexStream.bUseInstanceIndex = Component.bUseInstanceIndex; VertexStream.bSetByVertexFactoryInSetMesh = Component.bSetByVertexFactoryInSetMesh; return FVertexElement(PositionStream.AddUnique(VertexStream),Component.Offset,Component.Type,AttributeIndex,VertexStream.Stride,Component.bUseInstanceIndex); } void FVertexFactory::InitDeclaration(FVertexDeclarationElementList& Elements) { // Create the vertex declaration for rendering the factory normally. Declaration = RHICreateVertexDeclaration(Elements); } void FVertexFactory::InitPositionDeclaration(const FVertexDeclarationElementList& Elements) { PositionDeclaration = RHICreateVertexDeclaration(Elements); } FVertexFactoryParameterRef::FVertexFactoryParameterRef(FVertexFactoryType* InVertexFactoryType,const FShaderParameterMap& ParameterMap, EShaderFrequency InShaderFrequency) : Parameters(NULL) , VertexFactoryType(InVertexFactoryType) , ShaderFrequency(InShaderFrequency) { Parameters = VertexFactoryType->CreateShaderParameters(InShaderFrequency); VFHash = GetShaderFileHash(VertexFactoryType->GetShaderFilename()); if(Parameters) { Parameters->Bind(ParameterMap); } } bool operator<<(FArchive& Ar,FVertexFactoryParameterRef& Ref) { bool bShaderHasOutdatedParameters = false; Ar << Ref.VertexFactoryType; uint8 ShaderFrequencyByte = Ref.ShaderFrequency; Ar << ShaderFrequencyByte; if(Ar.IsLoading()) { Ref.ShaderFrequency = (EShaderFrequency)ShaderFrequencyByte; } Ar << Ref.VFHash; if (Ar.IsLoading()) { delete Ref.Parameters; if (Ref.VertexFactoryType) { Ref.Parameters = Ref.VertexFactoryType->CreateShaderParameters(Ref.ShaderFrequency); } else { bShaderHasOutdatedParameters = true; Ref.Parameters = NULL; } } // Need to be able to skip over parameters for no longer existing vertex factories. int32 SkipOffset = Ar.Tell(); { FArchive::FScopeSetDebugSerializationFlags S(Ar, DSF_IgnoreDiff); // Write placeholder. Ar << SkipOffset; } if(Ref.Parameters) { Ref.Parameters->Serialize(Ar); } else if(Ar.IsLoading()) { Ar.Seek( SkipOffset ); } if( Ar.IsSaving() ) { int32 EndOffset = Ar.Tell(); Ar.Seek( SkipOffset ); Ar << EndOffset; Ar.Seek( EndOffset ); } return bShaderHasOutdatedParameters; } /** Returns the hash of the vertex factory shader file that this shader was compiled with. */ const FSHAHash& FVertexFactoryParameterRef::GetHash() const { return VFHash; }
31.497462
192
0.770749
75791efa4e695d9d48d0a8e9d3206221e16d6efc
1,157
cpp
C++
src/scheduler/FunctionCallClient.cpp
dgoltzsche/faabric
b1edd26d2b07102255491d7fbb661586d58970f5
[ "Apache-2.0" ]
null
null
null
src/scheduler/FunctionCallClient.cpp
dgoltzsche/faabric
b1edd26d2b07102255491d7fbb661586d58970f5
[ "Apache-2.0" ]
null
null
null
src/scheduler/FunctionCallClient.cpp
dgoltzsche/faabric
b1edd26d2b07102255491d7fbb661586d58970f5
[ "Apache-2.0" ]
null
null
null
#include <faabric/scheduler/FunctionCallClient.h> #include <grpcpp/create_channel.h> #include <grpcpp/security/credentials.h> #include <faabric/proto/macros.h> namespace faabric::scheduler { FunctionCallClient::FunctionCallClient(const std::string& hostIn) : host(hostIn) , channel(grpc::CreateChannel(host + ":" + std::to_string(FUNCTION_CALL_PORT), grpc::InsecureChannelCredentials())) , stub(faabric::FunctionRPCService::NewStub(channel)) {} void FunctionCallClient::shareFunctionCall(const faabric::Message& call) { ClientContext context; faabric::FunctionStatusResponse response; CHECK_RPC("function_share", stub->ShareFunction(&context, call, &response)); } void FunctionCallClient::sendFlush() { ClientContext context; faabric::Message call; faabric::FunctionStatusResponse response; CHECK_RPC("function_flush", stub->Flush(&context, call, &response)); } void FunctionCallClient::sendMPIMessage(const faabric::MPIMessage& msg) { ClientContext context; faabric::FunctionStatusResponse response; CHECK_RPC("mpi_message", stub->MPICall(&context, msg, &response)); } }
29.666667
80
0.737252
757ae3a25a167a19621dc9d620353e420d53ee7e
828
hpp
C++
tests/CellMLContextTest.hpp
metatoaster/cellml-api
d7baf9038e42859fa96117db6c9644f9f09ecf8b
[ "W3C" ]
1
2018-12-27T01:06:37.000Z
2018-12-27T01:06:37.000Z
tests/CellMLContextTest.hpp
metatoaster/cellml-api
d7baf9038e42859fa96117db6c9644f9f09ecf8b
[ "W3C" ]
1
2016-12-05T09:20:14.000Z
2016-12-05T18:08:05.000Z
tests/CellMLContextTest.hpp
metatoaster/cellml-api
d7baf9038e42859fa96117db6c9644f9f09ecf8b
[ "W3C" ]
14
2015-07-27T13:45:54.000Z
2022-02-02T05:19:53.000Z
#ifndef CELLMLCONTEXTTEST_H #define CELLMLCONTEXTTEST_H #include <cppunit/extensions/HelperMacros.h> #include "cda_config.h" #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #include "IfaceCellML_Context.hxx" class CellMLContextTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CellMLContextTest); CPPUNIT_TEST(testCellMLContext); CPPUNIT_TEST(testModelList); CPPUNIT_TEST(testModelNode); CPPUNIT_TEST_SUITE_END(); iface::cellml_context::CellMLContext* mContext; iface::cellml_api::DOMModelLoader* mModelLoader; iface::cellml_api::Model* mAchCascade; iface::cellml_api::Model* mBeelerReuter; public: void setUp(); void tearDown(); void loadAchCascade(); void loadBeelerReuter(); void testCellMLContext(); void testModelList(); void testModelNode(); }; #endif // CELLMLCONTEXTTEST_H
23.657143
53
0.780193
757af3258b0bd1de500a8bd36dfbb26c6060a56b
1,322
cpp
C++
src/pkg_exe/pkg_exe_service.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
src/pkg_exe/pkg_exe_service.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
src/pkg_exe/pkg_exe_service.cpp
naughtybikergames/pkg
9a78380c6cf82c95dec3968a7ed69000b349113d
[ "MIT" ]
null
null
null
#include <pkg/exe/pkg_exe_service.hpp> #include <pkg/exe/iscc.hpp> #include <pkg/exe/help.hpp> #include <pkg/exe/temp.hpp> #include <pkg/utils.hpp> #include <boost/algorithm/string/replace.hpp> #include <map> #include <iostream> using namespace std; using namespace pkg::exe; pkg_exe_service::pkg_exe_service(const PkgExeArgs &args) { if (args.needs_help()) { cout << help() << endl; return; } bf::path file_path(args.file()); string win_path = boost::replace_all_copy("Z:" + args.path(), "/", "\\"); map<string, string> overrides = { {"appName", args.name()}, {"appVersion", args.version()}, {"outputDir", win_path} }; bf::current_path(file_path.parent_path()); _overriden_file = override_file(file_path, Temp::uuid_str(), overrides); _win_overriden_file = boost::replace_all_copy("Z:" + _overriden_file.string(), "/", "\\"); _out = args.out(); bf::create_directories(Temp::path()); created = true; } pkg_exe_service::~pkg_exe_service() { bf::remove_all(Temp::path()); bf::remove(_overriden_file); } void pkg_exe_service::execute() { if (!created) return; cout << "Started exe packaging ..." << endl; iscc(_win_overriden_file, _out).execute(); cout << "done. out -> " << _out << endl; }
24.036364
94
0.630106
757ba4b1ba66acf6abd3e09aae9f73d82e55103d
637
cpp
C++
Sniper.cpp
snir1551/Ex8_C-
f226d73c18ef8011b90ee46048494a82c05f198a
[ "MIT" ]
1
2021-05-31T13:11:02.000Z
2021-05-31T13:11:02.000Z
Sniper.cpp
snir1551/Ex8_C-
f226d73c18ef8011b90ee46048494a82c05f198a
[ "MIT" ]
null
null
null
Sniper.cpp
snir1551/Ex8_C-
f226d73c18ef8011b90ee46048494a82c05f198a
[ "MIT" ]
null
null
null
#include "Sniper.hpp" #include "Board.hpp" namespace WarGame { Sniper::Sniper(int numPlayer): Soldier(numPlayer,100,50) { } Sniper::Sniper(int numPlayer, int health, int damage): Soldier(numPlayer,health,damage) { } int Sniper::maxHealth() const { return 100; } const char* Sniper::letter() const { return "SN"; } void Sniper::attack(Board& board) const { Soldier* target = board.mostCurrentHealth(this); if (target) { target->setHealth(target->getHealth() - this->getDamage()); board.removeDeadSoldiers(); } } }
19.30303
91
0.583987
757bdb569ae20630278ce6e737d4c38ec50d5560
9,906
cc
C++
examples/fontscan.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
7
2021-07-28T19:03:08.000Z
2022-02-02T23:17:11.000Z
examples/fontscan.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
2
2021-06-15T22:34:44.000Z
2021-11-10T04:27:21.000Z
examples/fontscan.cc
michaeljclark/glyb
5b302ded6061eea2098bc8e963adb09e5f1dab4e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdint> #include <cstdlib> #include <cstring> #include <climits> #include <cstdlib> #include <climits> #include <cctype> #include <map> #include <vector> #include <memory> #include <string> #include <algorithm> #include <atomic> #include <mutex> #include <ft2build.h> #include FT_FREETYPE_H #include FT_MODULE_H #include FT_GLYPH_H #include FT_OUTLINE_H #include "binpack.h" #include "image.h" #include "draw.h" #include "font.h" #include "glyph.h" #include "file.h" static font_manager_ft manager; static const char* font_dir = "fonts"; static bool print_font_list = false; static bool print_block_stats = false; static bool help_text = false; static float cover_min = 0.05; static int family_width = 80; void print_help(int argc, char **argv) { fprintf(stderr, "Usage: %s [options]\n" "\n" "Options:\n" " -d, --font-dir <name> font dir\n" " -l, --list list fonts\n" " -l, --stats show font stats (block)\n" " -h, --help command line help\n", argv[0]); } bool check_param(bool cond, const char *param) { if (cond) { printf("error: %s requires parameter\n", param); } return (help_text = cond); } bool match_opt(const char *arg, const char *opt, const char *longopt) { return strcmp(arg, opt) == 0 || strcmp(arg, longopt) == 0; } void parse_options(int argc, char **argv) { int i = 1; while (i < argc) { if (match_opt(argv[i], "-d", "--font-dir")) { if (check_param(++i == argc, "--font-dir")) break; font_dir = argv[i++]; } else if (match_opt(argv[i], "-c", "--cover-min")) { if (check_param(++i == argc, "--cover-min")) break; cover_min = atof(argv[i++]); } else if (match_opt(argv[i], "-w", "--family-width")) { if (check_param(++i == argc, "--family-width")) break; family_width = atoi(argv[i++]); } else if (match_opt(argv[i], "-b", "--block-stats")) { print_block_stats = true; i++; } else if (match_opt(argv[i], "-l", "--list")) { print_font_list = true; i++; } else if (match_opt(argv[i], "-h", "--help")) { help_text = true; i++; } else { fprintf(stderr, "error: unknown option: %s\n", argv[i]); help_text = true; break; } } if (help_text) { print_help(argc, argv); exit(1); } } static bool endsWith(std::string str, std::string ext) { size_t i = str.find(ext); return (i == str.size() - ext.size()); } void scanFontDir(std::string dir) { std::vector<std::string> dirs; std::vector<std::string> fontfiles; size_t i = 0; dirs.push_back(dir); while(i < dirs.size()) { std::string current_dir = dirs[i++]; for (auto &name : file::list(current_dir)) { if (file::dirExists(name)) { dirs.push_back(name); } else if (endsWith(name, ".ttf")) { fontfiles.push_back(name); } } } for (auto &name : fontfiles) { manager.scanFontPath(name); } } static std::vector<uint> allCodepoints(FT_Face ftface) { std::vector<uint> l; unsigned glyph, codepoint = FT_Get_First_Char(ftface, &glyph); do { l.push_back(codepoint); codepoint = FT_Get_Next_Char(ftface, codepoint, &glyph); } while (glyph); return l; } void do_print_font_list() { for (auto &font : manager.getFontList()) { printf("font[%d] -> %s\n", font->font_id, font->getFontData().toString().c_str()); } } static std::string ltrim(std::string s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); return s; } static std::string rtrim(std::string s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); return s; } struct block { uint start; uint end; std::string name; }; std::vector<block> read_blocks() { // # @missing: 0000..10FFFF; No_Block // 0000..007F; Basic Latin std::vector<block> blocks; FILE *f; char buf[128]; const char* p; if ((f = fopen("data/unicode/Blocks.txt", "r")) == nullptr) { fprintf(stderr, "fopen: %s\n", strerror(errno)); exit(1); } while((p = fgets(buf, sizeof(buf), f)) != nullptr) { auto l = ltrim(rtrim(std::string(p))); if (l.size() == 0) continue; if (l.find("#") != std::string::npos) continue; size_t d = l.find(".."); size_t s = l.find(";"); blocks.push_back({ (uint)strtoul(l.substr(0,d).c_str(),nullptr, 16), (uint)strtoul(l.substr(d+2,s-d-2).c_str(),nullptr, 16), l.substr(s+2) }); } fclose(f); return blocks; } uint find_block(std::vector<block> &blocks, uint32_t cp) { uint i = 0; for (auto &b: blocks) { if (cp >= b.start && cp <= b.end) return i; i++; } return blocks.size()-1; } template <typename K, typename V> void hist_add(std::map<K,V> &hist, K key, V val) { auto hci = hist.find(key); if (hci == hist.end()) { hist.insert(hist.end(),std::pair<K,V>(key,val)); } else { hci->second += val; } } template <typename K> struct id_map { uint id; std::map<K,uint> map; std::map<uint,K> rmap; id_map() : id(0), map() {} uint get_id(K key) { auto i = map.find(key); if (i == map.end()) { i = map.insert(map.end(), std::pair<K,uint>(key, id++)); rmap[i->second] = key; } return i->second; } K get_key(uint i) { return rmap[i]; } }; template <typename T, typename K, typename V> auto find_or_insert(T &map, K key, V def) { auto i = map.find(key); if (i == map.end()) { i = map.insert(map.end(), std::pair<K,V>(key, def)); } return i; } std::string truncate(std::string str, size_t sz) { if (str.length() < sz) return str; else return str.substr(0, sz) + "..."; } struct block_family_data { std::map<font_face*,uint> codes; }; struct block_data { std::map<uint,block_family_data> families; }; struct family_data { std::string family_name; std::string font_names; uint family_count; uint glyph_count; }; template <typename K, typename V, typename F> std::string to_string(std::map<K,V> &list, F fn, std::string sep = ", ") { std::string str; auto i = list.begin(); if (i == list.end()) goto out; str.append(fn(i)); if (++i == list.end()) goto out; for (; i != list.end(); i++) { str.append(sep); str.append(fn(i)); } out: return str; } std::string remove_prefix(std::string &str, std::string sep) { auto i = str.find(sep); return (i != std::string::npos) ? str.substr(i+1) : str; } void do_print_block_stats() { id_map<std::string> font_name_map; id_map<std::string> font_family_map; std::vector<block> blocks; std::map<uint,block_data> block_stats; blocks = read_blocks(); blocks.push_back({0,0xfffff,"Unknown"}); for (auto &font : manager.getFontList()) { FT_Face ftface = static_cast<font_face_ft*>(font.get())->ftface; uint font_name_id = font_name_map.get_id(font->path); uint font_family_id = font_family_map.get_id(font->fontData.familyName); FT_Select_Charmap(ftface, FT_ENCODING_UNICODE); auto cplist = allCodepoints(ftface); for (auto cp : cplist) { uint bc = find_block(blocks,cp); auto bsi = find_or_insert(block_stats, bc, block_data()); auto fsi = find_or_insert(bsi->second.families, font_family_id, block_family_data()); auto gsi = find_or_insert(fsi->second.codes, font.get(), 0); gsi->second++; } } for (size_t i = 0; i < blocks.size(); i++) { auto &b = blocks[i]; auto bsi = block_stats.find(i); if (bsi->second.families.size() == 0) continue; printf("%06x..%06x; %-80s\n", b.start, b.end, b.name.c_str()); std::vector<family_data> fam_data; for (auto &ent : bsi->second.families) { uint font_family_id = ent.first; block_family_data &block_family_data = ent.second; std::string family_name = font_family_map.get_key(font_family_id); std::string font_names = to_string(block_family_data.codes, [](auto i) { return remove_prefix(i->first->name, "-"); }); uint glyph_count = 0; for (auto ent : block_family_data.codes) glyph_count += ent.second; uint family_count = (uint)block_family_data.codes.size(); fam_data.push_back(family_data{family_name, font_names, family_count, glyph_count}); } std::sort(fam_data.begin(), fam_data.end(), [](auto a, auto b) { return a.glyph_count/a.family_count > b.glyph_count/b.family_count; }); for (auto &ent: fam_data) { uint glyph_avg = ent.glyph_count/ent.family_count; uint block_glyphs = (b.end - b.start); float cover = (float)glyph_avg/(float)block_glyphs; if (cover < cover_min) continue; printf("\t%5.2f %10u,%-10u %-20s %s\n", cover, ent.family_count, ent.glyph_count/ent.family_count, ent.family_name.c_str(), truncate(ent.font_names, family_width).c_str()); } } } int main(int argc, char **argv) { parse_options(argc, argv); scanFontDir(font_dir); if (print_font_list) do_print_font_list(); if (print_block_stats) do_print_block_stats(); }
27.289256
97
0.564304
757d05b94d787a75b21658024e4689120f2500d8
713
hpp
C++
source/rectangle.hpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
source/rectangle.hpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
source/rectangle.hpp
SVincent/programmiersprachen-aufgabenblatt-3.
4eeeec3973999e0bf57c81e7ae681930e259aa6b
[ "MIT" ]
null
null
null
#ifndef RECTANGLE_HPP #define RECTANGLE_HPP #include "vec2.hpp" #include "color.hpp" #include "window.hpp" class Rectangle { public: Rectangle(); Rectangle(Vec2 const& vec1, Vec2 const& vec2); Rectangle(Vec2 const& vec1, Vec2 const& vec2, Color const& col); // getter Vec2 getMax() const; Vec2 getMin() const; Color getColor() const; // setter void setMax(Vec2 const& vecmax); void setMin(Vec2 const& vecmin); void setColor(Color const& col); // methods float circumference() const; void draw(Window const& window); void draw(Window const& window, Color const& color); bool is_inside(Vec2 const& vec); private: Vec2 max_; Vec2 min_; Color colour_; }; #endif
19.805556
68
0.687237
757de7f894579fe556a75aca8069431c8e9df4f6
855
hpp
C++
50_su2mesh/inc/SU2meshparser.hpp
nishiys/CFDbasics
638372956e31f8392f20b0d2027762cc4f9ef10b
[ "MIT" ]
1
2020-06-19T10:17:17.000Z
2020-06-19T10:17:17.000Z
50_su2mesh/inc/SU2meshparser.hpp
nishiys/CFDbasics
638372956e31f8392f20b0d2027762cc4f9ef10b
[ "MIT" ]
null
null
null
50_su2mesh/inc/SU2meshparser.hpp
nishiys/CFDbasics
638372956e31f8392f20b0d2027762cc4f9ef10b
[ "MIT" ]
1
2020-06-19T10:22:36.000Z
2020-06-19T10:22:36.000Z
#pragma once #include <string> #include <vector> #include "CellQuad4.hpp" #include "Face2d.hpp" #include "Node2d.hpp" namespace su2mesh { class SU2meshparser { public: SU2meshparser(std::string meshfilename); ~SU2meshparser(); void LoadData(); void WriteVtkFile(std::string vtkfilename); private: std::string meshfilename_; void ReadFile(); void CreateQuadArray(); std::vector<CellQuad4> cellarray_; // std::vector<Face2d> facearray_; std::vector<Node2d> nodearray_; unsigned int DIM_; unsigned int NElement_; unsigned int NPoint_; unsigned int NMarker_; const unsigned int LINE = 3; const unsigned int QUAD4 = 9; std::vector<std::vector<unsigned int>> element_table_; std::vector<std::vector<std::string>> marker_table_; void PrintDebug(); }; } // namespace su2mesh
19.431818
58
0.687719
757fdcd03e7aa69d58068e1e383dcbaf0140708b
4,549
cpp
C++
init/init_xt897.cpp
chakaponden/android_device_motorola_xt897-lineage
d85dca38801ea4a4309411d1f17434124403169e
[ "FTL" ]
null
null
null
init/init_xt897.cpp
chakaponden/android_device_motorola_xt897-lineage
d85dca38801ea4a4309411d1f17434124403169e
[ "FTL" ]
null
null
null
init/init_xt897.cpp
chakaponden/android_device_motorola_xt897-lineage
d85dca38801ea4a4309411d1f17434124403169e
[ "FTL" ]
null
null
null
/* Copyright (c) 2013, The Linux Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of The Linux Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdio.h> #define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_ #include <sys/_system_properties.h> #include <android-base/properties.h> #include <android-base/logging.h> #include "vendor_init.h" #include "property_service.h" #include "log.h" #include "util.h" void property_override(char const prop[], char const value[]) { prop_info *pi; pi = (prop_info*) __system_property_find(prop); if (pi) __system_property_update(pi, value, strlen(value)); else __system_property_add(prop, strlen(prop), value, strlen(value)); } void vendor_load_properties() { std::string carrier, device, modelno, platform; char hardware_variant[92]; FILE *fp; platform = android::base::GetProperty("ro.board.platform", ""); if (platform != ANDROID_TARGET) return; modelno = android::base::GetProperty("ro.boot.modelno", ""); carrier = android::base::GetProperty("ro.boot.carrier", ""); fp = popen("/system/xbin/sed -n '/Hardware/,/Revision/p' /proc/cpuinfo | /system/xbin/cut -d ':' -f2 | /system/xbin/head -1", "r"); fgets(hardware_variant, sizeof(hardware_variant), fp); pclose(fp); property_override("ro.product.device", "asanti_c"); property_override("ro.product.model", "PHOTON Q"); if (modelno == "XT897") { /* xt897 CSpire */ property_override("ro.build.description", "asanti_c_cspire-user 4.1.2 9.8.2Q-122_XT897_FFW-7 8 release-keys"); property_override("ro.build.fingerprint", "motorola/XT897_us_csp/asanti_c:4.1.2/9.8.2Q-122_XT897_FFW-7/8:user/release-keys"); android::init::property_set("ro.cdma.home.operator.alpha", "Cspire"); android::init::property_set("ro.cdma.home.operator.numeric", "311230"); } else if (carrier == "sprint") { /* xt897 Sprint */ property_override("ro.build.description", "XT897_us_spr-user 4.1.2 9.8.2Q-122_XT897_FFW-5 6 release-keys"); property_override("ro.build.fingerprint", "motorola/XT897_us_spr/asanti_c:4.1.2/9.8.2Q-122_XT897_FFW-5/6:user/release-keys"); android::init::property_set("ro.cdma.international.eri", "2,74,124,125,126,157,158,159,193,194,195,196,197,198,228,229,230,231,232,233,234,235"); android::init::property_set("ro.cdma.home.operator.alpha", "Sprint"); android::init::property_set("ro.cdma.home.operator.numeric", "310120"); android::init::property_set("ro.com.google.clientidbase.ms", "android-sprint-us"); android::init::property_set("ro.com.google.clientidbase.am", "android-sprint-us"); android::init::property_set("ro.com.google.clientidbase.yt", "android-sprint-us"); } device = android::base::GetProperty("ro.product.device", ""); LOG(INFO) << "Found carrier id: " << carrier.c_str() << " " << "hardware: " << hardware_variant << " " << "model no: " << modelno.c_str() << " " << "Setting build properties for " << device.c_str() << " device"; }
47.884211
153
0.697516
7582140c15c0c274c42fdd5cf142baf443e87a21
11,685
cpp
C++
openreil/libasmir/src/stmt.cpp
aeveris/openreil-sys
47a89248dfdfba88c4040cff77fc3efcde6f80e9
[ "MIT" ]
3
2017-06-27T22:33:16.000Z
2017-06-28T23:11:44.000Z
openreil/libasmir/src/stmt.cpp
aeveris/openreil-sys
47a89248dfdfba88c4040cff77fc3efcde6f80e9
[ "MIT" ]
null
null
null
openreil/libasmir/src/stmt.cpp
aeveris/openreil-sys
47a89248dfdfba88c4040cff77fc3efcde6f80e9
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <fstream> #include <stdlib.h> #include <string.h> #include <assert.h> using namespace std; #include "stmt.h" Stmt *Stmt::clone(Stmt *s) { return s->clone(); } void Stmt::destroy(Stmt *s) { Move *move = NULL; Jmp *jmp = NULL; CJmp *cjmp = NULL; ExpStmt *expstmt = NULL; Call *call = NULL; Return *ret = NULL; Func *fun = NULL; switch (s->stmt_type) { case MOVE: move = (Move *)s; Exp::destroy(move->lhs); Exp::destroy(move->rhs); break; case JMP: jmp = (Jmp *)s; Exp::destroy(jmp->target); break; case CJMP: cjmp = (CJmp *)s; Exp::destroy(cjmp->cond); Exp::destroy(cjmp->t_target); Exp::destroy(cjmp->f_target); break; case EXPSTMT: expstmt = (ExpStmt *)s; Exp::destroy(expstmt->exp); break; case CALL: call = (Call *)s; if (call->lval_opt != NULL) { Exp::destroy(call->lval_opt); } for (vector<Exp *>::iterator i = call->params.begin(); i != call->params.end(); i++) { Exp::destroy(*i); } break; case RETURN: ret = (Return *)s; if (ret->exp_opt != NULL) { Exp::destroy(ret->exp_opt); } break; case FUNCTION: fun = (Func *)s; for (vector<VarDecl *>::iterator i = fun->params.begin(); i != fun->params.end(); i++) { Stmt::destroy(*i); } for (vector<Stmt *>::iterator i = fun->body.begin(); i != fun->body.end(); i++) { Stmt::destroy(*i); } break; case COMMENT: case SPECIAL: case LABEL: case VARDECL: case ASSERT: break; } delete s; } VarDecl::VarDecl(string n, reg_t t, address_t asm_ad, address_t ir_ad) : Stmt(VARDECL, asm_ad, ir_ad), name(n), typ(t) { } VarDecl::VarDecl(const VarDecl &other) : Stmt(VARDECL, other.asm_address, other.ir_address), name(other.name), typ(other.typ) { } VarDecl::VarDecl(Temp *t) : Stmt(VARDECL, 0x0, 0x0), name(t->name), typ(t->typ) { } string VarDecl::tostring() { string ret = "var " + name + ":" + Exp::string_type(this->typ) + ";"; return ret; } VarDecl *VarDecl::clone() const { return new VarDecl(*this); } string Move::tostring() { return lhs->tostring() + " = " + rhs->tostring() + ";"; } Move::Move(const Move &other) : Stmt(MOVE, other.asm_address, other.ir_address) { this->lhs = other.lhs->clone(); this->rhs = other.rhs->clone(); } Move::Move(Exp *l, Exp *r, address_t asm_addr, address_t ir_addr) : Stmt(MOVE, asm_addr, ir_addr), lhs(l), rhs(r) { } Move *Move::clone() const { return new Move(*this); } Label::Label(const Label &other) : Stmt(LABEL, other.asm_address, other.ir_address) { this->label = string(other.label); } Label::Label(string l, address_t asm_addr, address_t ir_addr) : Stmt(LABEL, asm_addr, ir_addr) { label = l; } Label *Label::clone() const { return new Label(*this); } string Label::tostring() { return "label " + label + ":"; } Jmp::Jmp(Exp *e, address_t asm_addr, address_t ir_addr) : Stmt(JMP, asm_addr, ir_addr), target(e) { } Jmp::Jmp(const Jmp &other) : Stmt(JMP, other.asm_address, other.ir_address) { target = other.target->clone(); } Jmp *Jmp::clone() const { return new Jmp(*this); } string Jmp::tostring() { string ret = "jmp(" + target->tostring() + ");"; return ret; } CJmp::CJmp(Exp *c, Exp *t, Exp *f, address_t asm_addr, address_t ir_addr) : Stmt(CJMP, asm_addr, ir_addr), cond(c), t_target(t), f_target(f) { } CJmp::CJmp(const CJmp &other) : Stmt(CJMP, other.asm_address, other.ir_address) { cond = other.cond->clone(); f_target = other.f_target->clone(); t_target = other.t_target->clone(); } CJmp *CJmp::clone() const { return new CJmp(*this); } string CJmp::tostring() { string ret = "cjmp(" + cond->tostring() + "," + t_target->tostring() + "," + f_target->tostring() + ");"; return ret; } Special::Special(string s, address_t asm_addr, address_t ir_addr) : Stmt(SPECIAL, asm_addr, ir_addr), special(s) { } Special::Special(const Special &other) : Stmt(SPECIAL, other.asm_address, other.ir_address) { special = other.special; } Special *Special::clone() const { return new Special(*this); } string Special::tostring() { string ret = "special(\"" + special + "\");"; return ret; } Comment::Comment(string s, address_t asm_addr, address_t ir_addr) : Stmt(COMMENT, asm_addr, ir_addr) { comment = s; } Comment::Comment(const Comment &other) : Stmt(COMMENT, other.asm_address, other.ir_address) { comment = other.comment; } Comment *Comment::clone() const { return new Comment(*this); } string Comment::tostring() { string s = "// " + string(comment); return s; } ExpStmt::ExpStmt(Exp *e, address_t asm_addr, address_t ir_addr) : Stmt(EXPSTMT, asm_addr, ir_addr) { exp = e; } ExpStmt::ExpStmt(const ExpStmt &other) : Stmt(EXPSTMT, other.asm_address, other.ir_address) { exp = other.exp->clone(); } ExpStmt *ExpStmt::clone() const { return new ExpStmt(*this); } string ExpStmt::tostring() { string s = exp->tostring() + ";"; return s; } Call::Call(Exp *lval_opt, string fnname, vector<Exp *> params, address_t asm_ad, address_t ir_ad) : Stmt(CALL, asm_ad, ir_ad) { this->lval_opt = lval_opt; this->callee = new Name(fnname); this->params = params; } Call::Call(Exp *lval_opt, Exp *callee, vector<Exp *> params, address_t asm_ad, address_t ir_ad) : Stmt(CALL, asm_ad, ir_ad) { this->lval_opt = lval_opt; this->callee = callee; this->params = params; } Call::Call(const Call &other) : Stmt(CALL, other.asm_address, other.ir_address) { this->lval_opt = (other.lval_opt == NULL) ? NULL : other.lval_opt->clone(); assert(other.callee); this->callee = other.callee->clone(); this->params.clear(); for (vector<Exp *>::const_iterator i = other.params.begin(); i != other.params.end(); i++) { this->params.push_back((*i)->clone()); } } string Call::tostring() { ostringstream ostr; Name *name; if (this->lval_opt != NULL) { ostr << this->lval_opt->tostring() << " = "; } if (this->callee->exp_type == NAME) { name = (Name *) this->callee; ostr << name->name; } else { ostr << "call " << this->callee->tostring(); } ostr << "("; for (vector<Exp *>::iterator i = this->params.begin(); i != this->params.end(); i++) { ostr << (*i)->tostring(); if ((i + 1) != this->params.end()) { ostr << ", "; } } ostr << ");"; string str = ostr.str(); return str; } Call *Call::clone() const { return new Call(*this); } Return::Return(Exp *exp_opt, address_t asm_ad, address_t ir_ad) : Stmt(RETURN, asm_ad, ir_ad) { this->exp_opt = exp_opt; } Return::Return(const Return &other) : Stmt(RETURN, other.asm_address, other.ir_address) { this->exp_opt = (other.exp_opt == NULL) ? NULL : other.exp_opt->clone(); } string Return::tostring() { ostringstream ostr; ostr << "return"; if (this->exp_opt != NULL) { ostr << " " << this->exp_opt->tostring(); } ostr << ";"; return ostr.str(); } Return *Return::clone() const { return new Return(*this); } Func::Func(string fnname, bool has_rv, reg_t rt, vector<VarDecl *> params, bool external, vector<Stmt *> body, address_t asm_ad, address_t ir_ad) : Stmt(FUNCTION, asm_ad, ir_ad) { this->fnname = fnname; this->has_rv = has_rv; this->rt = rt; this->params = params; this->external = external; this->body = body; } Func::Func(const Func &other) : Stmt(FUNCTION, other.asm_address, other.ir_address) { this->fnname = other.fnname; this->has_rv = other.has_rv; this->rt = other.rt; this->params.clear(); for (vector<VarDecl *>::const_iterator i = other.params.begin(); i != other.params.end(); i++) { this->params.push_back((*i)->clone()); } this->external = other.external; this->body.clear(); for (vector<Stmt *>::const_iterator i = other.body.begin(); i != other.body.end(); i++) { this->body.push_back((*i)->clone()); } } string Func::tostring() { ostringstream ostr; if (external) { ostr << "extern "; } if (has_rv) { ostr << Exp::string_type(rt) << " "; } else { ostr << "void "; } ostr << this->fnname << "("; for (vector<VarDecl *>::iterator i = this->params.begin(); i != this->params.end(); i++) { ostr << (*i)->tostring(); if ((i + 1) != this->params.end()) { ostr << ", "; } } ostr << ")"; if (this->body.empty()) { ostr << ";"; } else { ostr << "\n"; ostr << "{\n"; for (vector<Stmt *>::iterator i = this->body.begin(); i != this->body.end(); i++) { ostr << "\t" << (*i)->tostring() << endl; } ostr << "}"; } return ostr.str(); } Func *Func::clone() const { return new Func(*this); } Assert::Assert(Exp *cond, address_t asm_ad, address_t ir_ad) : Stmt(ASSERT, asm_ad, ir_ad), cond(cond) { } Assert::Assert(const Assert &other) : Stmt(ASSERT, other.asm_address, other.ir_address) { cond = other.cond->clone(); } string Assert::tostring() { return "assert(" + cond->tostring() + ");"; } Internal::Internal(int type, int size, address_t asm_addr, address_t ir_addr) : Stmt(INTERNAL, asm_addr, ir_addr) { this->type = type; this->size = size; if (size > 0) { this->data = malloc(size); assert(this->data); memset(this->data, 0, size); } else { this->data = NULL; } } Internal::Internal(const Internal &other) : Stmt(INTERNAL, other.asm_address, other.ir_address) { this->type = other.type; this->size = other.size; if (other.data) { this->data = malloc(other.size); assert(this->data); memcpy(this->data, other.data, other.size); } else { this->data = NULL; } } Internal::~Internal() { if (this->data) { free(this->data); } } Internal *Internal::clone() const { return new Internal(*this); } string Internal::tostring() { string s = ""; return s; } //---------------------------------------------------------------------- // Convert int to std::string in decimal form //---------------------------------------------------------------------- string int_to_str(int i) { ostringstream stream; stream << i << flush; return (stream.str()); } //---------------------------------------------------------------------- // Convert int to std::string in hex form //---------------------------------------------------------------------- string int_to_hex(int i) { ostringstream stream; stream << hex << i << flush; return (stream.str()); } //---------------------------------------------------------------------- // Generate a unique label, this is done using a static counter // internal to the function. //---------------------------------------------------------------------- Label *mk_label() { static int label_counter = 0; return new Label("L_" + int_to_str(label_counter++)); }
19.638655
113
0.543004
7582297e43ee942e00e602f4e8cb642d4a4bdcf6
407
cpp
C++
Wonderland/Wonderland/Old Files/Source/Engine/Common/Containers/List/TLinkedList.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
3
2018-04-09T13:01:07.000Z
2021-03-18T12:28:48.000Z
Wonderland/Wonderland/Old Files/Source/Engine/Common/Containers/List/TLinkedList.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
null
null
null
Wonderland/Wonderland/Old Files/Source/Engine/Common/Containers/List/TLinkedList.cpp
RodrigoHolztrattner/Wonderland
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
[ "MIT" ]
1
2021-03-18T12:28:50.000Z
2021-03-18T12:28:50.000Z
/////////////////////////////////////////////////////////////////////////////// // Filename: TLinkedList.cpp /////////////////////////////////////////////////////////////////////////////// #include "TLinkedList.h" /* TLinkedList::TLinkedList() { } TLinkedList::TLinkedList(const TLinkedList& other) { } TLinkedList::~TLinkedList() { } bool TLinkedList::Initialize() { bool result; return true; } */
15.074074
79
0.425061