blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
a3e63d66333069cc9d227ed5cc969ec6c7fbf020
1ea95c2ef59ac5d7a99548c3483db607965433df
/test/GeometryTest.cc
8fc7de37d0707e21304bb7f945bb09eb936f357f
[]
no_license
xyuan/CAFFE
59cba160b815f8588ee9a83c03bc59ab55fb96bb
ef89a89deacec14d675855e5c8c72080009a7379
refs/heads/master
2021-01-21T16:22:42.930929
2015-06-12T18:44:38
2015-06-12T18:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
830
cc
#include <iostream> #include <math.h> #include "../src/Math/Point3D.h" #include "../src/Math/Geometry.h" int main() { using namespace std; Point3D cubeVertices[8]; double dx(-0.2), dy(-0.3), dz(-0.423); cubeVertices[0] = Point3D(0., 0., 0.); cubeVertices[1] = Point3D(dx, 0., 0.); cubeVertices[2] = Point3D(dx, dy, 0.); cubeVertices[3] = Point3D(0., dy, 0.); cubeVertices[4] = Point3D(0., 0., dz); cubeVertices[5] = Point3D(dx, 0., dz); cubeVertices[6] = Point3D(dx, dy, dz); cubeVertices[7] = Point3D(0., dy, dz); cout << "Cube Volume: " << fabs(dx*dy*dz) << endl << "Computed: " << Geometry::computeHexahedronVolume(cubeVertices) << endl; cout << "XY-plane Area: " << fabs(dx*dy) << endl << "Computed: " << Geometry::computeQuadrilateralArea(cubeVertices) << endl; return 0; }
[ "roni511@gmail.com" ]
roni511@gmail.com
30a8c5986662191e4db6c5af9d83af63b1ad22aa
d63dab92eb520202dc014d2d194df070401a6458
/piklib/img/bti.cpp
0b6d3dc44b8d90fa3ddecf32aae3f29f69336037
[ "Unlicense" ]
permissive
intns/piklib
ada7f6978b17f497873ca49260b28ab46a4fa20a
44598a3e79e3ae5d3d935407f8c0f2362c76fda0
refs/heads/main
2023-07-16T09:47:47.131470
2021-08-20T22:51:04
2021-08-20T22:51:04
397,991,708
2
0
null
null
null
null
UTF-8
C++
false
false
1,302
cpp
#include "bti.hpp" #include <iostream> namespace piklib { void BTI::read(util::fstream_reader& reader) { m_format = reader.readS8(); m_alphaEnabled = reader.readS8(); m_dimensions.first = reader.readU16(); m_dimensions.second = reader.readU16(); m_wrapS = reader.readS8(); m_wrapT = reader.readS8(); m_unknown = reader.readS8(); m_paletteFormat = reader.readS8(); m_paletteEntryCount = reader.readU16(); m_paletteOffset = reader.readU32(); m_borderColor = reader.readU32(); m_minFilter = reader.readS8(); m_magFilter = reader.readS8(); m_unknown2 = reader.readS16(); m_mipCount = reader.readS8(); m_unknown3 = reader.readS8(); m_lodBias = reader.readS16(); m_dataOffset = reader.readU32(); reader.setPosition(m_dataOffset); const u32 fileSz = static_cast<u32>(reader.getFilesize()); const u32 imgSz = (!m_paletteOffset) ? fileSz - m_dataOffset : m_paletteOffset - m_dataOffset; m_imageData.resize(imgSz); reader.read_buffer(reinterpret_cast<s8*>(m_imageData.data()), imgSz); if (m_paletteOffset) { reader.setPosition(m_paletteOffset); m_paletteData.resize(m_paletteEntryCount * 2); reader.read_buffer(reinterpret_cast<s8*>(m_paletteData.data()), m_paletteData.size()); } } }
[ "84647527+intns@users.noreply.github.com" ]
84647527+intns@users.noreply.github.com
5d926ed144af0888cabe155ded265f002df49361
164aa6438207738e72a4aaec2c755d4248039744
/day12problemB.cpp
afae01e92eef515e1d0f393a984eff7a9d76f667
[]
no_license
O5-2/adventofcode2019
a3700fe8701b647a766a14f26151be6d3f75d934
27e269abac6a6f3104b1e00d8a0afd8a123764c8
refs/heads/master
2020-11-29T14:42:24.780106
2019-12-25T18:40:45
2019-12-25T18:40:45
230,140,895
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
cpp
#include <cstring> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <cmath> #include <iomanip> #include <array> using namespace std; long long int gcd(long long int a, long long int b) { if ((a == 0) || (b == 0)) { return a+b; } else if (a >= b) { return gcd(b, a % b); } return gcd(a, b % a); } long long int lcm(long long int a, long long int b) { return (a*b)/gcd(a, b); } bool unequal(array<int, 8> a, array<int, 8> b) { bool equal = true; for (int i = 0; i < 8; i++) { equal = equal && (a[i] == b[i]); } return not equal; } int main() { array<array<int, 8>, 3> input; input[0] = {5, -11, 0, -13, 0, 0, 0, 0}; input[1] = {4, -11, 7, 2, 0, 0, 0, 0}; input[2] = {4, -3, 0, 10, 0, 0, 0, 0}; long long int periods[3]; pair<int, int> pairs[6] = {pair<int, int>(0, 1), pair<int, int>(0, 2), pair<int, int>(0, 3), pair<int, int>(1, 2), pair<int, int>(1, 3), pair<int, int>(2, 3)}; for (int axis = 0; axis < 3; axis++) { int steps = 0; array<int, 8> state; for (int i = 0; i < 8; i++) { state[i] = input[axis][i]; } do { array<int, 8> newState; for (int i = 0; i < 4; i++) { newState[i+4] = state[i+4]; } for (int i = 0; i < 6; i++) { if (state[pairs[i].first] > state[pairs[i].second]) { newState[(pairs[i].first)+4] -= 1; newState[(pairs[i].second)+4] += 1; } else if (state[pairs[i].first] < state[pairs[i].second]) { newState[(pairs[i].first)+4] += 1; newState[(pairs[i].second)+4] -= 1; } } for (int i = 0; i < 4; i++) { newState[i] = state[i]+newState[i+4]; } for (int i = 0; i < 8; i++) { state[i] = newState[i]; } steps += 1; } while (unequal(input[axis], state)); periods[axis] = steps; } cout << lcm(lcm(periods[0], periods[1]), periods[2]) << "\n"; return 0; } // Done. Finally. Ugh.
[ "elijahkarp@gmail.com" ]
elijahkarp@gmail.com
f1397c6c1161062598188d1c8fa6fe55eac89dd9
e8eb4a4d87cdad3fc7d516b8410c12185d006ffb
/file1.cpp
15af2c1e5b0d5d2c63a43db822153054ba3528a8
[]
no_license
sasz1995/help
47d75cbd2f860872f8df0b9cee19160f95678c70
5cfa49b24d317275d2e45d59374d6670f85deca7
refs/heads/master
2020-06-15T22:43:11.438614
2019-07-05T14:49:36
2019-07-05T14:49:36
195,411,526
0
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
#include <iostream> #include <fstream> using namespace std; int main() { ifstream fin; fin.open("myfile.dat"); char ch; //fin>>ch; //cout<<ch; while(!fin.eof()) { fin>>ch; cout<<ch; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
e9230fa5f855d4dcecfcfa24a5dcb3e68a00ff7e
2f98c60a171b8f6df0f411255589ee6f26737cfb
/multimedia/WindowsAnimation/PriorityComparison/MainWindow.cpp
e8b5741f063b415c9c50fe5e2caa1fc4abc93cdb
[]
no_license
bbesbes/WindowsSDK7-Samples
4df1d7f2c6fae7bd84411b4c13751a4085144af9
14e1c3daff5927791c9e17083ea455ba3de84444
refs/heads/master
2021-09-23T10:05:42.764049
2021-09-16T19:45:25
2021-09-16T19:45:25
118,103,268
0
0
null
2018-01-19T09:12:39
2018-01-19T09:12:39
null
UTF-8
C++
false
false
24,239
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include "MainWindow.h" #include "ManagerEventHandler.h" #include "PriorityComparison.h" #include "UIAnimationSample.h" #include <strsafe.h> CMainWindow::CMainWindow() : m_hwnd(NULL), m_pD2DFactory(NULL), m_pRenderTarget(NULL), m_pBackgroundBrush(NULL), m_pAnimationManager(NULL), m_pAnimationTimer(NULL), m_pTransitionLibrary(NULL), m_uThumbCount(0), m_thumbs(NULL), m_pLayoutManager(NULL) { } CMainWindow::~CMainWindow() { // Layout Manager if (m_pLayoutManager != NULL) { delete m_pLayoutManager; } // Thumbnails if (m_thumbs != NULL) { delete [] m_thumbs; } // Animation SafeRelease(&m_pAnimationManager); SafeRelease(&m_pAnimationTimer); SafeRelease(&m_pTransitionLibrary); // D2D SafeRelease(&m_pD2DFactory); SafeRelease(&m_pRenderTarget); SafeRelease(&m_pBackgroundBrush); } // Creates the CMainWindow window and initializes // device-independent resources. HRESULT CMainWindow::Initialize( HINSTANCE hInstance ) { // Client area dimensions, in inches const FLOAT CLIENT_WIDTH = 7.0f; const FLOAT CLIENT_HEIGHT = 5.0f; WNDCLASSEX wcex; HRESULT hr; ATOM atom; // Initialize device-independent resources, such as the Direct2D factory hr = CreateDeviceIndependentResources(); if (SUCCEEDED(hr)) { // Register the window class wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = CMainWindow::WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = sizeof(LONG_PTR); wcex.hInstance = hInstance; wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = TEXT("WAMMainWindow"); wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); atom = RegisterClassEx(&wcex); hr = atom ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { // Because CreateWindow function takes its size in pixels, // obtain the DPI and use it to calculate the window size. // The D2D factory returns the current system DPI. This is // also the value it will use to create its own windows. FLOAT dpiX, dpiY; m_pD2DFactory->GetDesktopDpi( &dpiX, &dpiY ); // Create the CMainWindow window m_hwnd = CreateWindow( TEXT("WAMMainWindow"), TEXT("Windows Animation - Priority Comparison Demo"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, static_cast<UINT>(dpiX * CLIENT_WIDTH), static_cast<UINT>(dpiY * CLIENT_HEIGHT), NULL, NULL, hInstance, this ); hr = m_hwnd ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { // Initialize Animation hr = InitializeAnimation(); if (SUCCEEDED(hr)) { // Display the window ShowWindow(m_hwnd, SW_SHOWNORMAL); hr = UpdateWindow(m_hwnd); } } } } return hr; } // Invalidates the client area for redrawing HRESULT CMainWindow::Invalidate() { BOOL bResult = InvalidateRect( m_hwnd, NULL, FALSE ); HRESULT hr = bResult ? S_OK : E_FAIL; return hr; } // Creates and initializes the main animation components HRESULT CMainWindow::InitializeAnimation() { // Create Animation Manager HRESULT hr = CoCreateInstance( CLSID_UIAnimationManager, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pAnimationManager) ); if (SUCCEEDED(hr)) { // Create Animation Timer hr = CoCreateInstance( CLSID_UIAnimationTimer, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pAnimationTimer) ); if (SUCCEEDED(hr)) { // Create Animation Transition Library hr = CoCreateInstance( CLSID_UIAnimationTransitionLibrary, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_pTransitionLibrary) ); if (SUCCEEDED(hr)) { // Create and set the ManagerEventHandler to start updating when animations are scheduled IUIAnimationManagerEventHandler *pManagerEventHandler; hr = CManagerEventHandler::CreateInstance( this, &pManagerEventHandler ); if (SUCCEEDED(hr)) { hr = m_pAnimationManager->SetManagerEventHandler( pManagerEventHandler ); pManagerEventHandler->Release(); if (SUCCEEDED(hr)) { // Create the PriorityComparisons for canceling and trimming storyboards IUIAnimationPriorityComparison *pPriorityComparisonCancel; hr = CCancelPriorityComparison::CreateInstance( &pPriorityComparisonCancel ); if (SUCCEEDED(hr)) { hr = m_pAnimationManager->SetCancelPriorityComparison( pPriorityComparisonCancel ); pPriorityComparisonCancel->Release(); if (SUCCEEDED(hr)) { IUIAnimationPriorityComparison *pPriorityComparisonTrim; hr = CTrimPriorityComparison::CreateInstance( &pPriorityComparisonTrim ); if (SUCCEEDED(hr)) { hr = m_pAnimationManager->SetTrimPriorityComparison( pPriorityComparisonTrim ); pPriorityComparisonTrim->Release(); } } } } } } } } return hr; } // Creates resources which are not bound to any device. // Their lifetime effectively extends for the duration of the app. // These resources include the Direct2D factory. HRESULT CMainWindow::CreateDeviceIndependentResources() { // Create a Direct2D factory. HRESULT hr = D2D1CreateFactory( D2D1_FACTORY_TYPE_SINGLE_THREADED, &m_pD2DFactory ); return hr; } // Creates resources which are bound to a particular Direct3D device. // It's all centralized here, so the resources can be easily recreated // in the event of Direct3D device loss (e.g. display change, remoting, // removal of video card, etc). The resources will only be created // if necessary. HRESULT CMainWindow::CreateDeviceResources() { HRESULT hr = S_OK; if (m_pRenderTarget == NULL) { RECT rc; GetClientRect( m_hwnd, &rc ); D2D1_SIZE_U size = D2D1::SizeU( rc.right - rc.left, rc.bottom - rc.top ); // Create a Direct2D render target hr = m_pD2DFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties( m_hwnd, size ), &m_pRenderTarget ); if (SUCCEEDED(hr)) { // Create a gradient brush for the background static const D2D1_GRADIENT_STOP stops[] = { { 0.0f, { 0.75f, 0.75f, 0.75f, 1.0f } }, { 1.0f, { 0.25f, 0.25f, 0.25f, 1.0f } }, }; ID2D1GradientStopCollection *pGradientStops; hr = m_pRenderTarget->CreateGradientStopCollection( stops, ARRAY_SIZE(stops), &pGradientStops ); if (SUCCEEDED(hr)) { hr = m_pRenderTarget->CreateLinearGradientBrush( D2D1::LinearGradientBrushProperties( D2D1::Point2F( rc.bottom / 2.0f, 0.0f ), D2D1::Point2F( rc.bottom / 2.0f, rc.bottom / 2.0f + 1.0f ) ), D2D1::BrushProperties( ), pGradientStops, &m_pBackgroundBrush ); if (SUCCEEDED(hr)) { // Create a brush for outlining the thumbnails hr = m_pRenderTarget->CreateSolidColorBrush( D2D1::ColorF( D2D1::ColorF::White ), &m_pOutlineBrush ); if (SUCCEEDED(hr)) { m_pOutlineBrush->SetOpacity( 0.5f ); hr = FindImages(); } } } } } return hr; } // Discards device-specific resources that need to be recreated // when a Direct3D device is lost void CMainWindow::DiscardDeviceResources() { SafeRelease(&m_pRenderTarget); SafeRelease(&m_pBackgroundBrush); SafeRelease(&m_pOutlineBrush); } // Locates images in the Pictures library HRESULT CMainWindow::FindImages() { // Walk the Pictures library IShellItem *pShellItemPicturesLibrary; HRESULT hr = SHGetKnownFolderItem( FOLDERID_PicturesLibrary, KF_FLAG_CREATE, NULL, IID_PPV_ARGS(&pShellItemPicturesLibrary) ); if (SUCCEEDED(hr)) { INamespaceWalk *pNamespaceWalk; hr = CoCreateInstance( CLSID_NamespaceWalker, NULL, CLSCTX_INPROC, IID_PPV_ARGS(&pNamespaceWalk) ); if (SUCCEEDED(hr)) { hr = pNamespaceWalk->Walk( pShellItemPicturesLibrary, NSWF_NONE_IMPLIES_ALL, 1, NULL ); if (SUCCEEDED(hr)) { // Retrieve the array of PIDLs gathered in the walk PIDLIST_ABSOLUTE *ppidls; hr = pNamespaceWalk->GetIDArrayResult( &m_uThumbCount, &ppidls ); if (SUCCEEDED(hr)) { // Create the uninitialized thumbnails m_thumbs = new CThumbnail[m_uThumbCount]; // Get the bitmap for each item and initialize the corresponding thumbnail object for (UINT i = 0; i < m_uThumbCount; i++) { IShellItem *pShellItem; hr = SHCreateItemFromIDList( ppidls[i], IID_PPV_ARGS(&pShellItem) ); if (SUCCEEDED(hr)) { ID2D1Bitmap *pBitmap; hr = DecodeImageFromThumbCache( pShellItem, &pBitmap ); if (SUCCEEDED(hr)) { D2D1_SIZE_F size = pBitmap->GetSize(); hr = m_thumbs[i].Initialize( pBitmap, m_pAnimationManager, m_pRenderTarget->GetSize().width * 0.5, m_pRenderTarget->GetSize().height * 0.5 ); pBitmap->Release(); } pShellItem->Release(); } if (FAILED(hr)) { break; } } // The calling function is responsible for freeing the PIDL array for (UINT i = 0; i < m_uThumbCount; i++) { CoTaskMemFree(ppidls[i]); } // Free the array itself CoTaskMemFree(ppidls); if (SUCCEEDED(hr)) { // Arrange the images when they are first loaded m_pLayoutManager = new CLayoutManager(); hr = m_pLayoutManager->Initialize( m_pAnimationManager, m_pAnimationTimer, m_pTransitionLibrary, m_uThumbCount, m_thumbs ); if (SUCCEEDED(hr)) { hr = m_pLayoutManager->Resize( m_pRenderTarget->GetSize() ); } } } } pNamespaceWalk->Release(); } pShellItemPicturesLibrary->Release(); } return hr; } // Retrieves a bitmap from the thumbnail cache and converts it to // a D2D bitmap. HRESULT CMainWindow::DecodeImageFromThumbCache( IShellItem *pShellItem, ID2D1Bitmap **ppBitmap ) { const UINT THUMB_SIZE = 256; // Read the bitmap from the thumbnail cache IThumbnailCache *pThumbCache; HRESULT hr = CoCreateInstance( CLSID_LocalThumbnailCache, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pThumbCache) ); if (SUCCEEDED(hr)) { ISharedBitmap *pBitmap; hr = pThumbCache->GetThumbnail( pShellItem, THUMB_SIZE, WTS_SCALETOREQUESTEDSIZE, &pBitmap, NULL, NULL ); if (SUCCEEDED(hr)) { HBITMAP hBitmap; hr = pBitmap->GetSharedBitmap( &hBitmap ); if (SUCCEEDED(hr)) { // Create a WIC bitmap from the shared bitmap IWICImagingFactory *pFactory; hr = CoCreateInstance( CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pFactory) ); if (SUCCEEDED(hr)) { IWICBitmap *pWICBitmap; hr = pFactory->CreateBitmapFromHBITMAP( hBitmap, NULL, WICBitmapIgnoreAlpha, &pWICBitmap ); if (SUCCEEDED(hr)) { // Create a D2D bitmap from the WIC bitmap hr = m_pRenderTarget->CreateBitmapFromWicBitmap( pWICBitmap, NULL, ppBitmap ); pWICBitmap->Release(); } pFactory->Release(); } } pBitmap->Release(); } pThumbCache->Release(); } return hr; } // The window message handler LRESULT CALLBACK CMainWindow::WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { const int MESSAGE_PROCESSED = 0; if (uMsg == WM_CREATE) { LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam; CMainWindow *pMainWindow = (CMainWindow *)pcs->lpCreateParams; SetWindowLongPtrW( hwnd, GWLP_USERDATA, PtrToUlong(pMainWindow) ); return MESSAGE_PROCESSED; } CMainWindow *pMainWindow = reinterpret_cast<CMainWindow *>(static_cast<LONG_PTR>( GetWindowLongPtrW( hwnd, GWLP_USERDATA ))); if (pMainWindow != NULL) { switch (uMsg) { case WM_SIZE: { UINT width = LOWORD(lParam); UINT height = HIWORD(lParam); pMainWindow->OnResize( width, height ); } return MESSAGE_PROCESSED; case WM_PAINT: case WM_DISPLAYCHANGE: { PAINTSTRUCT ps; BeginPaint( hwnd, &ps ); pMainWindow->OnPaint( ps.hdc, ps.rcPaint ); EndPaint( hwnd, &ps ); } return MESSAGE_PROCESSED; case WM_KEYDOWN: { UINT uVirtKey = wParam; pMainWindow->OnKeyDown( uVirtKey ); } return MESSAGE_PROCESSED; case WM_DESTROY: { pMainWindow->OnDestroy(); PostQuitMessage( 0 ); } return MESSAGE_PROCESSED; } } return DefWindowProc( hwnd, uMsg, wParam, lParam ); } // Called whenever the client area needs to be drawn HRESULT CMainWindow::OnPaint( HDC hdc, const RECT &rcPaint ) { // Update the animation manager with the current time UI_ANIMATION_SECONDS secondsNow; HRESULT hr = m_pAnimationTimer->GetTime( &secondsNow ); if (SUCCEEDED(hr)) { hr = m_pAnimationManager->Update( secondsNow ); if (SUCCEEDED(hr)) { // Read the values of the animation variables and draw the client area hr = DrawClientArea(); if (SUCCEEDED(hr)) { // Continue redrawing the client area as long as there are animations scheduled UI_ANIMATION_MANAGER_STATUS status; hr = m_pAnimationManager->GetStatus( &status ); if (SUCCEEDED(hr)) { if (status == UI_ANIMATION_MANAGER_BUSY) { InvalidateRect( m_hwnd, NULL, FALSE ); } } } } } return hr; } // Resizes the render target in response to a change in client area size HRESULT CMainWindow::OnResize( UINT width, UINT height ) { HRESULT hr = S_OK; if (m_pRenderTarget) { D2D1_SIZE_U size; size.width = width; size.height = height; hr = m_pRenderTarget->Resize( size ); if (SUCCEEDED(hr)) { hr = m_pLayoutManager->Resize( m_pRenderTarget->GetSize() ); } } return hr; } // Moves the images in various ways depending on the key pressed HRESULT CMainWindow::OnKeyDown( UINT uVirtKey ) { HRESULT hr = S_OK; switch (uVirtKey) { case VK_UP: hr = m_pLayoutManager->Wave( UI_ANIMATION_SLOPE_DECREASING ); break; case VK_DOWN: hr = m_pLayoutManager->Wave( UI_ANIMATION_SLOPE_INCREASING ); break; case VK_RIGHT: hr = m_pLayoutManager->Next(); break; case VK_LEFT: hr = m_pLayoutManager->Previous(); break; case VK_SPACE: hr = m_pLayoutManager->Arrange(); break; default: break; } return hr; } // Prepares for window destruction void CMainWindow::OnDestroy() { if (m_pAnimationManager != NULL) { // Clear the manager event handler, to ensure that the one that points to this object is released (void)m_pAnimationManager->SetManagerEventHandler(NULL); } } // Draws the contents of the client area. // // Note that this function will not draw anything if the window // is occluded (e.g. obscured by other windows or off monitor). // Also, this function will automatically discard device-specific // resources if the Direct3D device disappears during execution, and // will recreate the resources the next time it's invoked. HRESULT CMainWindow::DrawClientArea() { // Begin drawing the client area HRESULT hr = CreateDeviceResources(); if (SUCCEEDED(hr)) { if (!(m_pRenderTarget->CheckWindowState() & D2D1_WINDOW_STATE_OCCLUDED)) { m_pRenderTarget->BeginDraw(); // Retrieve the size of the render target D2D1_SIZE_F sizeRenderTarget = m_pRenderTarget->GetSize(); // Paint the background m_pRenderTarget->FillRectangle( D2D1::RectF( 0.0f, 0.0f, sizeRenderTarget.width, sizeRenderTarget.height ), m_pBackgroundBrush ); // Paint all the thumbnails for (UINT i = 0; i < m_uThumbCount; i++) { hr = m_thumbs[i].Render( m_pRenderTarget, m_pOutlineBrush ); if (FAILED(hr)) { break; } } // Can only return one failure HRESULT HRESULT hrEndDraw = m_pRenderTarget->EndDraw(); if (SUCCEEDED(hr)) { hr = hrEndDraw; } } if (hr == D2DERR_RECREATE_TARGET) { DiscardDeviceResources(); } } return hr; }
[ "theonlylawislove@gmail.com" ]
theonlylawislove@gmail.com
704b2ae56be9d302ba35e708fc3ff35215fc7255
229116ff4296a824f50c40f222d953c4148c8024
/PCViewer/Elaboration/SINECO_Transformation.h
952bcae238268c0e8aa58c63b2f9233abb40de89
[]
no_license
xijunke/VisualInertialKinectFusion
51e22f234963b7343bdd8cfb98fe88ed3c39599b
610910dca00e9ffe6b0844411f9479d2a15a4b1b
refs/heads/master
2021-10-09T10:35:13.905499
2018-12-26T11:10:30
2018-12-26T11:10:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,894
h
#ifndef SINECO_TRANSFORM_H #define SINECO_TRANSFORM_H #include <QWidget> #include <define.h> #include <pcl/common/transforms.h> // transform point cloud #include <pcl/common/io.h> // copy point cloud #include <QUndoStack> namespace Ui { class SINECO_Transformation; } class SINECO_Transformation : public QWidget { Q_OBJECT public: explicit SINECO_Transformation(QWidget *parent = 0); ~SINECO_Transformation(); public slots: void setCurrentPC(PointCloudT::Ptr pc) { CurrentPC = pc; on_Transform_getMat_clicked();} void setCurrentPCList(QList<PointCloudT::Ptr> pcList) { CurrentPCList = pcList;} signals: void replace(PointCloudT::Ptr oldPC, PointCloudT::Ptr newPC, QString ElabName); private slots: void on_Transform_Rxneg_clicked(); void on_Transform_Rxpos_clicked(); void on_Transform_Ryneg_clicked(); void on_Transform_Rypos_clicked(); void on_Transform_Rzneg_clicked(); void on_Transform_Rzpos_clicked(); void on_Transform_Txneg_clicked(); void on_Transform_Txpos_clicked(); void on_Transform_Tyneg_clicked(); void on_Transform_Typos_clicked(); void on_Transform_Tzneg_clicked(); void on_Transform_Tzpos_clicked(); void on_Transform_getMat_clicked(); void on_Transform_setMat_clicked(); void on_Transform_reset_clicked(); void on_Transform_solidify_clicked(); void on_Transform_demean_clicked(); private: Ui::SINECO_Transformation *ui; PointCloudT::Ptr CurrentPC; QList<PointCloudT::Ptr> CurrentPCList; void Rotate(PointCloudT::Ptr input, PointCloudT::Ptr output, Eigen::Quaternionf quaternion); void Translate(PointCloudT::Ptr input, PointCloudT::Ptr output, Eigen::Vector3f translation); void ApplySINECO_Transformation(PointCloudT::Ptr input, PointCloudT::Ptr output, Eigen::Matrix4f SINECO_TransformationMatrix); }; #endif // SINECO_ TRANSFORM_H
[ "silvio.giancola@gmail.com" ]
silvio.giancola@gmail.com
33b1ddf4d742c0ddcf7ea4d319fdf1ec4397bda2
6a94f8c4adcd0e5108e52d4926179b3865617cb4
/els_channel/Connection.hpp
7dd50b29360347ce6d700cfee97b9e274d997597
[]
no_license
rage123450/hk
2bf8e047d22349a5cfb65dd3e01489738387d4ae
c938662ee1fee7a864e9258e37b37fb335c7e21d
refs/heads/master
2023-06-07T18:33:12.924676
2020-10-16T17:58:44
2020-10-16T17:58:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,285
hpp
#pragma once #include "boost/asio.hpp" #include "boost/enable_shared_from_this.hpp" #include "boost/shared_array.hpp" #include "Crypto.hpp" #include "Player.hpp" namespace els { class Connection : public boost::enable_shared_from_this<Connection> { private: Player m_player; int m_sequence; std::string m_accName; int m_accID; int m_port; std::string m_lastLogin; Crypto m_crypto; boost::shared_array<unsigned char> m_recvBuffer; boost::asio::ip::tcp::socket tcpSocket; public: Connection(boost::asio::io_service& iosvc) : tcpSocket(iosvc) { m_sequence = 1; } boost::asio::ip::tcp::socket& getSocket(); void start(); void startReadHeader(); void startReadBody(const boost::system::error_code& error); void handleRead(int size, const boost::system::error_code& error); void sendPacket(unsigned char* packet, int size); void sendPacket(std::vector<unsigned char> packet); void handleWrite(const boost::system::error_code& error, size_t bytes_transferred); std::string getAccName(); int getAccID(); void setAccName(std::string name); void setAccID(int id); void setPlayer(Player* player); Player* getPlayer(); std::string getLastLogin(); void Connection::setLastLogin(std::string lastlogin); }; }
[ "kaokaotw@gmail.com" ]
kaokaotw@gmail.com
c8af20427efa11c4a3fadf179e5d18d17ffbaade
3f3095dbf94522e37fe897381d9c76ceb67c8e4f
/Current/ITM_ResetFaction.hpp
82b3369575c7c0902a724bb4b19610757157e166
[]
no_license
DRG-Modding/Header-Dumps
763c7195b9fb24a108d7d933193838d736f9f494
84932dc1491811e9872b1de4f92759616f9fa565
refs/heads/main
2023-06-25T11:11:10.298500
2023-06-20T13:52:18
2023-06-20T13:52:18
399,652,576
8
7
null
null
null
null
UTF-8
C++
false
false
1,156
hpp
#ifndef UE4SS_SDK_ITM_ResetFaction_HPP #define UE4SS_SDK_ITM_ResetFaction_HPP class UITM_ResetFaction_C : public UUserWidget { FPointerToUberGraphFrame UberGraphFrame; class UBasic_ButtonScalable_C* Basic_ButtonScalable; class UBasic_Menu_MinimalWindow_C* Basic_Menu_MinimalWindow; class UTextBlock* CostTextBlock; class USizeBox* CurrentSizebox; class UImage* FactionLogo; class UTextBlock* FactionNameTextBlock; class UImage* Image_429; class UUI_GradientMasked_Image_C* UI_GradientMasked_Image; class UUI_ImageTinted_C* UI_ImageTinted; class UCommunityGoalFaction* CurrentFaction; int32 Cost; FITM_ResetFaction_CCheckState CheckState; void CheckState(); TArray<class UCommunityGoalFaction*> FactionArray; int32 CurrentFactionID(); void PreConstruct(bool IsDesignTime); void Set Faction(class UCommunityGoalFaction* Faction); void BndEvt__Basic_ButtonScalable_K2Node_ComponentBoundEvent_0_OnClicked__DelegateSignature(); void OnFactionSwitch(bool Changed); void ExecuteUbergraph_ITM_ResetFaction(int32 EntryPoint); void CheckState__DelegateSignature(); }; #endif
[ "bobby45900@gmail.com" ]
bobby45900@gmail.com
b5a0b552563e8d940e661a858435841c047ecfd4
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5744014401732608_0/C++/MommyCanCode/ideone_MiwLRs.cpp
5d2f2f8ca033b0633a29079aa4e491d8abd8ab4f
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
666
cpp
#include<stdio.h> int main() { int t; int T; int b; long long m, s; int a[60][60], i, j; scanf("%d", &T); for(t=1; t<=T; ++t) { scanf("%d %lld", &b, &m); s=1; for(i=1; i<=b-2; ++i) s*=2; if(m>s) { printf("Case #%d: IMPOSSIBLE\n", t); continue; } printf("Case #%d: POSSIBLE\n", t); for(i=1; i<=b; ++i) { for(j=1; j<=i; ++j) a[i][j]=0; for(j=i+1; j<b; ++j) a[i][j]=1; } if(m==s) { for(i=1; i<b; ++i) a[i][b]=1; } else { a[1][b]=0; for(i=2; i<b; ++i) { a[i][b]=(m%2); m/=2; } } for(i=1; i<=b; ++i) { for(j=1; j<=b; ++j) { printf("%d", a[i][j]); } printf("\n"); } } }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
ea2b375803a8193f583fbf731508a0ac631adfe9
2aec1f112729c691ac575c1e3578c5edb0682102
/include/moveit_msgs/ExecuteTrajectoryActionResult.h
f90dffc0ffbaec9025fa3bd71b79928d21fbd56f
[]
no_license
dlutguobin/RC
ec8cf676168dd96dc2cb16e42be2a1d7cad5caa9
9bdc2c08e9b29e514ff2858726b1ea5f44fb6ffe
refs/heads/master
2021-09-11T20:50:33.473288
2018-04-12T05:47:33
2018-04-12T05:47:33
129,187,049
0
0
null
null
null
null
UTF-8
C++
false
false
11,556
h
// Generated by gencpp from file moveit_msgs/ExecuteTrajectoryActionResult.msg // DO NOT EDIT! #ifndef MOVEIT_MSGS_MESSAGE_EXECUTETRAJECTORYACTIONRESULT_H #define MOVEIT_MSGS_MESSAGE_EXECUTETRAJECTORYACTIONRESULT_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> #include <actionlib_msgs/GoalStatus.h> #include <moveit_msgs/ExecuteTrajectoryResult.h> namespace moveit_msgs { template <class ContainerAllocator> struct ExecuteTrajectoryActionResult_ { typedef ExecuteTrajectoryActionResult_<ContainerAllocator> Type; ExecuteTrajectoryActionResult_() : header() , status() , result() { } ExecuteTrajectoryActionResult_(const ContainerAllocator& _alloc) : header(_alloc) , status(_alloc) , result(_alloc) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef ::actionlib_msgs::GoalStatus_<ContainerAllocator> _status_type; _status_type status; typedef ::moveit_msgs::ExecuteTrajectoryResult_<ContainerAllocator> _result_type; _result_type result; typedef boost::shared_ptr< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> const> ConstPtr; }; // struct ExecuteTrajectoryActionResult_ typedef ::moveit_msgs::ExecuteTrajectoryActionResult_<std::allocator<void> > ExecuteTrajectoryActionResult; typedef boost::shared_ptr< ::moveit_msgs::ExecuteTrajectoryActionResult > ExecuteTrajectoryActionResultPtr; typedef boost::shared_ptr< ::moveit_msgs::ExecuteTrajectoryActionResult const> ExecuteTrajectoryActionResultConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> & v) { ros::message_operations::Printer< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace moveit_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'shape_msgs': ['/opt/ros/kinetic/share/shape_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'moveit_msgs': ['/tmp/binarydeb/ros-kinetic-moveit-msgs-0.9.1/obj-x86_64-linux-gnu/devel/share/moveit_msgs/msg', '/tmp/binarydeb/ros-kinetic-moveit-msgs-0.9.1/msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'object_recognition_msgs': ['/opt/ros/kinetic/share/object_recognition_msgs/cmake/../msg'], 'octomap_msgs': ['/opt/ros/kinetic/share/octomap_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > { static const char* value() { return "8aaeab5c1cdb613e6a2913ebcc104c0d"; } static const char* value(const ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x8aaeab5c1cdb613eULL; static const uint64_t static_value2 = 0x6a2913ebcc104c0dULL; }; template<class ContainerAllocator> struct DataType< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > { static const char* value() { return "moveit_msgs/ExecuteTrajectoryActionResult"; } static const char* value(const ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > { static const char* value() { return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ Header header\n\ actionlib_msgs/GoalStatus status\n\ ExecuteTrajectoryResult result\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: actionlib_msgs/GoalStatus\n\ GoalID goal_id\n\ uint8 status\n\ uint8 PENDING = 0 # The goal has yet to be processed by the action server\n\ uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n\ uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n\ # and has since completed its execution (Terminal State)\n\ uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n\ uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n\ # to some failure (Terminal State)\n\ uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n\ # because the goal was unattainable or invalid (Terminal State)\n\ uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n\ # and has not yet completed execution\n\ uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n\ # but the action server has not yet confirmed that the goal is canceled\n\ uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n\ # and was successfully cancelled (Terminal State)\n\ uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n\ # sent over the wire by an action server\n\ \n\ #Allow for the user to associate a string with GoalStatus for debugging\n\ string text\n\ \n\ \n\ ================================================================================\n\ MSG: actionlib_msgs/GoalID\n\ # The stamp should store the time at which this goal was requested.\n\ # It is used by an action server when it tries to preempt all\n\ # goals that were requested before a certain time\n\ time stamp\n\ \n\ # The id provides a way to associate feedback and\n\ # result message with specific goal requests. The id\n\ # specified must be unique.\n\ string id\n\ \n\ \n\ ================================================================================\n\ MSG: moveit_msgs/ExecuteTrajectoryResult\n\ # ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ \n\ # Error code - encodes the overall reason for failure\n\ MoveItErrorCodes error_code\n\ \n\ \n\ ================================================================================\n\ MSG: moveit_msgs/MoveItErrorCodes\n\ int32 val\n\ \n\ # overall behavior\n\ int32 SUCCESS=1\n\ int32 FAILURE=99999\n\ \n\ int32 PLANNING_FAILED=-1\n\ int32 INVALID_MOTION_PLAN=-2\n\ int32 MOTION_PLAN_INVALIDATED_BY_ENVIRONMENT_CHANGE=-3\n\ int32 CONTROL_FAILED=-4\n\ int32 UNABLE_TO_AQUIRE_SENSOR_DATA=-5\n\ int32 TIMED_OUT=-6\n\ int32 PREEMPTED=-7\n\ \n\ # planning & kinematics request errors\n\ int32 START_STATE_IN_COLLISION=-10\n\ int32 START_STATE_VIOLATES_PATH_CONSTRAINTS=-11\n\ \n\ int32 GOAL_IN_COLLISION=-12\n\ int32 GOAL_VIOLATES_PATH_CONSTRAINTS=-13\n\ int32 GOAL_CONSTRAINTS_VIOLATED=-14\n\ \n\ int32 INVALID_GROUP_NAME=-15\n\ int32 INVALID_GOAL_CONSTRAINTS=-16\n\ int32 INVALID_ROBOT_STATE=-17\n\ int32 INVALID_LINK_NAME=-18\n\ int32 INVALID_OBJECT_NAME=-19\n\ \n\ # system errors\n\ int32 FRAME_TRANSFORM_FAILURE=-21\n\ int32 COLLISION_CHECKING_UNAVAILABLE=-22\n\ int32 ROBOT_STATE_STALE=-23\n\ int32 SENSOR_INFO_STALE=-24\n\ \n\ # kinematics errors\n\ int32 NO_IK_SOLUTION=-31\n\ "; } static const char* value(const ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.status); stream.next(m.result); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ExecuteTrajectoryActionResult_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::moveit_msgs::ExecuteTrajectoryActionResult_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "status: "; s << std::endl; Printer< ::actionlib_msgs::GoalStatus_<ContainerAllocator> >::stream(s, indent + " ", v.status); s << indent << "result: "; s << std::endl; Printer< ::moveit_msgs::ExecuteTrajectoryResult_<ContainerAllocator> >::stream(s, indent + " ", v.result); } }; } // namespace message_operations } // namespace ros #endif // MOVEIT_MSGS_MESSAGE_EXECUTETRAJECTORYACTIONRESULT_H
[ "liguobin@siasun.com" ]
liguobin@siasun.com
76cbb325138359fb0f41fa33b4cd7631ab52cef6
414d9b4e8d480fb66447c1a00549afaefdadb82b
/CHT on set.cpp
f5e31ddd3dfd759b9ae3020f0b61232d6190ca06
[]
no_license
danya090699/algo
a6a13a9051d740484d08c38c92360210855d3516
91874bb42118e6cfc0f73a455ab6c00b4e7a3d4b
refs/heads/main
2023-04-23T01:14:02.400396
2021-05-02T19:34:01
2021-05-02T19:34:01
312,794,420
0
0
null
null
null
null
UTF-8
C++
false
false
2,294
cpp
#include <bits/stdc++.h> #define int long long #define iter set <el, comp>::iterator using namespace std; const int inf=1e18; struct el { int l, r, k, b; }; struct comp { bool operator() (const el &a, const el &b) const { return a.k>b.k; } }; struct comp2 { bool operator() (const el &a, const el &b) const { return a.r<b.r; } }; set <el, comp> hull; set <el, comp2> hull2; int de(int a, int b){return a/b+(a%b>0);} int intersect(int k, int b, int k2, int b2) { if(k<k2) { swap(k, k2); swap(b, b2); } if(b<b2) return (b2-b)/(k-k2); else return -de(b-b2, k-k2); } void ins(el cu) { cu.l=-inf, cu.r=inf; iter it=hull.lower_bound(cu); vector <iter> ve; for(it; it!=hull.end(); it++) { el f=*it; int x; if(f.k==cu.k) { if(f.b<cu.b) x=-inf*2; else x=inf*2; } else x=intersect(cu.k, cu.b, f.k, f.b); if(x<f.r) { if(x>=f.l) { hull.erase(f); hull2.erase(f); f.l=x+1; hull.insert(f); hull2.insert(f); } cu.r=x; break; } else ve.push_back(it); } it=hull.lower_bound(cu); while(it!=hull.begin()) { it--; el f=*it; int x=intersect(cu.k, cu.b, f.k, f.b); if(x>=f.l) { if(x<f.r) { hull.erase(f); hull2.erase(f); f.r=x; hull.insert(f); hull2.insert(f); } cu.l=x+1; break; } else ve.push_back(it); } for(int a=0; a<ve.size(); a++) { hull.erase(ve[a]); hull2.erase(*ve[a]); } if(cu.l<=cu.r) { hull.insert(cu), hull2.insert(cu); } } int que(int x) { el f=*hull2.lower_bound({0, x, 0, 0}); return f.k*x+f.b; } main() { while(1) { int ty; cin>>ty; if(ty==1) { int k, b; cin>>k>>b; ins({0, 0, k, b}); } else { int x; cin>>x; cout<<que(x)<<"\n"; } } }
[ "noreply@github.com" ]
noreply@github.com
e282f347dc41dbd892c259e2ff4114d3ca3219aa
51a484c4885439799561dc5f6ab59e91d33d98fd
/src/service/SensorHistoryService.cpp
42654ba815cf206bdb803ee2356bc7af36d226ad
[ "BSD-3-Clause" ]
permissive
BeeeOn/server
7b22a4c7cbd551542a2bde5a128f09c02d597a99
c705503f6bc033f2014aaa675d1e29bfeed9f5eb
refs/heads/master
2020-12-29T02:31:55.089160
2019-01-29T22:08:50
2019-01-29T22:08:57
47,968,600
4
1
null
null
null
null
UTF-8
C++
false
false
118
cpp
#include "service/SensorHistoryService.h" using namespace BeeeOn; SensorHistoryService::~SensorHistoryService() { }
[ "iviktorin@fit.vutbr.cz" ]
iviktorin@fit.vutbr.cz
805f203428dfd5f8f282a09a7af09bf349674d7b
0531261aeabdf5556fd6af1f428cc95b04c76759
/PlayState.h
fa7bcba108d2962ce11cc7f55197dacd1138c4dc
[]
no_license
adryian/BaseCode
5d871857fbd00800e54ccb53a0e28095d3a33332
e0132887252de34ffa168ea9b0ed652bde3adc1a
refs/heads/master
2021-01-15T13:43:51.934959
2016-02-07T12:31:41
2016-02-07T12:31:41
43,768,326
0
0
null
2015-10-06T17:58:21
2015-10-06T17:58:20
null
UTF-8
C++
false
false
502
h
#pragma once #include "string" #include "GameState.h" #include "TileLayer.h" #ifndef PLAYSTATE_H #define PLAYSTATE_H class PlayState : public GameState { public: void update(); void render(); bool onEnter(); bool onExit(); std::string getStateID() const; private: static const std::string s_menuID; static void s_menuToPlay(); static void s_exitFromMenu(); std::vector<GameObject*> m_gobjects; std::vector<const char*> m_textureIDList; //TileLayer* tl; Level* lv; }; #endif PLAYSTATE_H
[ "adrian.gaston.perez@gmail.com" ]
adrian.gaston.perez@gmail.com
fb58880aa29ba4835734a00d6bbc7e0126992944
ec8a43705c755aeeb5bc51f05cfd2e7c151c3d79
/source/engine/AurMath.h
564a91a4fdb3c9eee54326418e29f6b78c27c4aa
[]
no_license
garudaxc/AuroraEngine
f055382fb7fafa3edc038c33b9f434b995f15a7c
a8d74d36080ea215fcfba9d39eb2ad4b2ff44b4a
refs/heads/master
2023-07-19T14:02:49.377307
2023-07-16T14:52:47
2023-07-16T14:52:47
245,835,428
1
1
null
null
null
null
UTF-8
C++
false
false
4,451
h
#ifndef GAMATH_H #define GAMATH_H #include <cmath> namespace Aurora { //----------------------------------------------------------- template<typename real> class Math { public: static inline real Abs(real value); static inline real Sin(real angle); static inline real Cos(real angle); static inline real Tan(real angle); static inline real ASin(real angle); static inline real ACos(real angle); static inline real ATan(real angle); static inline real ATan2(real x, real y); static inline real Sqrt(real value); static inline real Pow(real x, real y); static inline real Floor(real x); static inline real Ceil(real x); static inline real Mod(real x, real y); static inline real Exp(real value); static inline real Log(real value); static inline real Rand01(); static inline real Min(real val1, real val2); static inline real Max(real val1, real val2); static inline real Clamp(real val, real min, real max); static inline real GetLerp(real min, real max, real middle); static inline bool IsZero(real value); static const real ZERO_TOLERANCE; static const real MAX_VALUE; static const real PI; static const real HALF_PI; static const real DEG_TO_RAD; static const real RAD_TO_DEG; }; //----------------------------------------------------------- //-------------------------------------------------------- template<> inline float Math<float>::Abs(float value) { return fabsf(value); } //-------------------------------------------------------- template<> inline float Math<float>::Sin(float angle) { return sinf(angle); } //-------------------------------------------------------- template<> inline float Math<float>::Cos(float angle) { return cosf(angle); } //-------------------------------------------------------- template<> inline float Math<float>::Tan(float angle) { return tanf(angle); } //-------------------------------------------------------- template<> inline float Math<float>::ASin(float angle) { return asinf(angle); } //-------------------------------------------------------- template<> inline float Math<float>::ACos(float angle) { return acosf(angle); } //-------------------------------------------------------- template<> inline float Math<float>::ATan(float angle) { return atanf(angle); } //-------------------------------------------------------- template<> inline float Math<float>::ATan2(float x, float y) { return atan2f(x, y); } //-------------------------------------------------------- template<> inline float Math<float>::Sqrt(float value) { return sqrtf(value); } //-------------------------------------------------------- template<> inline float Math<float>::Pow(float x, float y) { return powf(x, y); } //-------------------------------------------------------- template<> inline float Math<float>::Floor(float x) { return floorf(x); } //-------------------------------------------------------- template<> inline float Math<float>::Ceil(float x) { return ceilf(x); } //-------------------------------------------------------- template<> inline float Math<float>::Mod(float x, float y) { return fmodf(x, y); } //-------------------------------------------------------- template<> inline float Math<float>::Exp(float value) { return expf(value); } //-------------------------------------------------------- template<> inline float Math<float>::Log(float value) { return logf(value); } template<> inline float Math<float>::Rand01() { return rand() / (float)RAND_MAX; } //-------------------------------------------------------- template<> inline float Math<float>::Min(float val1, float val2) { return val1 < val2 ? val1 : val2; } //-------------------------------------------------------- template<> inline float Math<float>::Max(float val1, float val2) { return val1 > val2 ? val1 : val2; } //-------------------------------------------------------- template<> inline float Math<float>::Clamp(float val, float min, float max) { return Math<float>::Min(Math<float>::Max(val, min), max); } //-------------------------------------------------------- template<> inline float Math<float>::GetLerp(float min, float max, float middle) { return (middle - min) / (max - min); } //-------------------------------------------------------- template<> inline bool Math<float>::IsZero(float value) { return (value >= -Math<float>::ZERO_TOLERANCE) && (value <= Math<float>::ZERO_TOLERANCE); } typedef Math<float> Mathf; }//namespace #endif
[ "181031952@qq.com" ]
181031952@qq.com
660d20f03af70d73b35ecdcf6aecfd4da1a05fd8
45e40a9965d45080d52b43810423eb9e847ab6aa
/src/zzScenes/zzSushiScene/zzSushiScene.cpp
5e42171b00fffce6b9d8c1da76be071d92f7a5cc
[ "MIT" ]
permissive
matthewjacobson/recoded
7e65481d02f3bd5c323824b92a2cf71394075cc2
9185ff2cbf0ba84c9d364a7018360b029d866ad8
refs/heads/master
2021-08-11T16:27:21.768393
2017-11-13T22:41:57
2017-11-13T22:41:57
110,148,623
0
0
null
2017-11-09T17:57:44
2017-11-09T17:57:44
null
UTF-8
C++
false
false
3,104
cpp
#include "zzSushiScene.h" void zzSushiScene::setup(){ // setup pramaters // if your original code use an ofxPanel instance dont use it here, instead // add your parameters to the "parameters" instance as follows. // param was declared in zzSushiScene.h parameters.add(imageScale.set("image scale", 0.0075, 0.005, 0.02)); parameters.add(widthScale.set("width scale", 0.8, 0.5, 1)); parameters.add(drawEvery.set("spacing", 4, 2, 20)); setAuthor("Put Your Name Here"); setOriginalArtist("Put the original Artist's name here"); loadCode("scenes/zzSushiScene/exampleCode.cpp"); center.set(dimensions.getCenter()); font.load("zzScenes/zzSushiScene/SF.otf", 200, true, true, true); ofBackground(0); string stringToUse = "sushi"; bounds = font.getStringBoundingBox(stringToUse, 0, 0); auto offset = ofPoint(-bounds.width/2, bounds.height/2); characters = font.getStringAsPoints(stringToUse); for (int i = 0; i < imageCount; i++) { char buf[30]; sprintf(buf, "zzScenes/zzSushiScene/%d.png", i); images[i].load(buf); } } void zzSushiScene::update(){ scale = (dimensions.width * widthScale) /bounds.width; sushiScale = dimensions.width / images[0].getWidth() * imageScale; } void zzSushiScene::draw(){ ofColor backgroundColor = ofColor::fromHsb(fmod(ofGetElapsedTimef() * 2.0, 255), 200, 255); ofBackground(backgroundColor); ofPushStyle(); ofPushMatrix(); ofTranslate(center.x - (bounds.width/2 + bounds.x) * scale, center.y + (bounds.height/2) * scale); ofScale(scale, scale); for (ofTTFCharacter shape : characters) { vector<ofPolyline> lines = shape.getOutline(); for (ofPolyline line : lines) { ofPolyline resampledLine = line.getResampledBySpacing(5); drawAlongLine(resampledLine); } } ofPopMatrix(); ofPopStyle(); } void zzSushiScene::drawAlongLine(ofPolyline &polyline) { float size = polyline.size(); float time = ofGetElapsedTimef() * 0.08; float length = polyline.getLengthAtIndex(polyline.size()-1); int numberOfPointsToDraw = size / drawEvery; // draw every x points float increment = 1.0/numberOfPointsToDraw; int count = 0; float pct = 0.0; while(pct < 0.98) { ofPushMatrix(); ofSetRectMode(OF_RECTMODE_CENTER); float offset = fmod(pct + time, 1.0); float findex = polyline.getIndexAtPercent(offset); float fangle = polyline.getAngleAtIndexInterpolated(findex); int i_m_1 = fmod(findex - 1 + size, size); int i_p_1 = fmod(findex + 1 + size, size); ofPoint diff = polyline[i_p_1] - polyline[i_m_1]; float angle = atan2(diff.y, diff.x); ofPoint point = polyline.getPointAtPercent(offset); ofTranslate(point.x, point.y); ofRotate(angle * RAD_TO_DEG); ofScale(sushiScale, sushiScale); // sushiImage.draw(0, 0); images[count].draw(0, 0); ofPopMatrix(); pct += increment; count = (count + 1) % imageCount; } }
[ "ying.quan.tan@gmail.com" ]
ying.quan.tan@gmail.com
75e37b5d8e78a7cfb2177ede70d6f40b98f53552
ae5845cf0850ba03805edcf0a4d4f796aea43c95
/SimperEncryption.cpp
2f6bf517d82539db30fd46cc168b99a2cb8b05e3
[]
no_license
T-PLAN/-v.1.0
d9a8e7b360736569fdc74eca22ca16f3abb1a48f
f54b0b3f2357c3d7a3757f5e9f97bec47b8a90f5
refs/heads/master
2022-11-24T02:41:06.246123
2020-07-23T07:06:59
2020-07-23T07:06:59
280,627,980
4
0
null
null
null
null
UTF-8
C++
false
false
3,239
cpp
#include <iostream> #include <string> #include <windows.h> #include <ctime> using namespace std; int body() { string a, c, d, e, f, g, m, n, p; int b, o; int num; int h = 0; string fuhao[10] = {")", "!", "@", "#", "$", "%", "^", "&", "*", "("}; string words[53] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "}; string ascii[53] = {"97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "32"}; int choose; cout << "请输入模式(1为加密,2为解密,3为关于此程序,4为退出):"; cin >> choose; if (choose == 1) { cout << "请输入明文(仅支持英文,不支持符号但支持空格,支持英文大小写):"; cin.get(); getline(cin, a); for (int i = 0; i < a.length(); ++i) { b = static_cast<int>(a[i]); c = c + to_string(b) + "/"; } for (int j = 0; j < c.length(); ++j) { d = c[j]; if (d == "/") { e = e + "/"; } else { num = atoi(d.c_str()); e = e + fuhao[num]; } } cout << e << endl; } else if (choose == 2) { cout << "请输入密文:"; cin >> a; for (int t1 = 0; t1 < a.length(); ++t1) { f = a[t1]; if (f == "/") { g = g + "/"; } else { h = 0; while (f != fuhao[h]) { h = h + 1; } g = g + to_string(h); } } for (int t3 = 0; t3 < g.length(); ++t3) { m = g[t3]; if (m == "/") { o = 0; while (n != ascii[o]) { o = o + 1; } p = p + words[o]; t3 = t3 + 1; m = g[t3]; n = ""; } n = n + m; } cout << p << endl; } else if (choose == 3) { cout << "此程序由T_PLAN制作,语言为c++,名称是简易明文加密解密器,版本号为1.0,共用时4小时" << endl; } else if (choose == 4) { cout << "感谢您的使用,goodbye" << endl; _sleep(900); exit(0); } else { cout << "输入有误" << endl; _sleep(800); } system("pause"); } int main() { while (1) { body(); system("cls"); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
fc52419e76ce2e2731eceaf56b303d2f19d30981
d6f12d4bde5ddff4ba1bd9393ea6cab118c44fa4
/Source/misc_utils/debug_layer.h
d4d1dc44c0635a0304e19a02b6fd7754957ef348
[]
no_license
gummikana/CardBackGenerator
211583c57d838b53568280bd2d51ce62e915d623
02f7bf1252ae0e3702ec9c15f052fc3310239ba4
refs/heads/master
2021-01-20T04:37:30.435833
2015-06-15T16:43:55
2015-06-15T16:43:55
37,427,383
0
0
null
null
null
null
UTF-8
C++
false
false
4,053
h
#ifndef INC_DEBUG_LAYER_H #define INC_DEBUG_LAYER_H #define DEBUG_LAYER_DONT_USE_COMPONENTS #include <memory> #include <string> #include <poro/ikeyboard_listener.h> #include "config_ui.h" #include "../gameplay_utils/game_mouse_listener.h" class ConfigSliders; class Screenshotter; class SimpleProfilerViewer; class ProfilerBars; namespace poro { class IGraphics; } namespace as { class Sprite; } namespace SGF { class Entity; class EventManager; class EntityManager; } //----------------------------------------------------------------------------- class DebugLayer : /*public poro::DefaultApplication, */ public SimpleUIListener, public IConfigSlidersListener, public GameMouseListener, public poro::IKeyboardListener { public: DebugLayer(); DebugLayer( SGF::EventManager* eventMgr, SGF::EntityManager* entityMgr ); ~DebugLayer(); void SetManagers( SGF::EventManager* eventMgr, SGF::EntityManager* entityMgr ); //------------------------------------------------------------------------- // Enables and disables CTRL + o keybind, that opens the entity dialog // also disables CTRL + s saving the entity void SetLoadEntity( bool enabled ); //------------------------------------------------------------------------- void Init(); void Exit(); //------------------------------------------------------------------------- void Update( float dt ); void Draw( poro::IGraphics* graphics ); //------------------------------------------------------------------------- // poro::IKeyboardListener virtual void OnKeyDown( int key, poro::types::charset unicode ); virtual void OnKeyUp( int key, poro::types::charset unicode ); // virtual void MouseMove( const poro::types::vec2& pos ); // virtual void MouseButtonDown( const poro::types::vec2& pos, int button ); // GameMouseListener virtual bool OnMouseMove( const types::vector2& screen_position ); virtual bool OnMouseDown( const types::vector2& screen_position, int button ); //------------------------------------------------------------------------- // Config stuff template< class TType > ConfigSliders* OpenConfig( TType& config ) { ConfigSliders* result = config.GetConfigSliders( this ); SetConfig( result ); return result; } // ........................................................................ void SetConfig( ConfigSliders* config ); ConfigSliders* GetConfig(); //------------------------------------------------------------------------- void SetEntity( SGF::Entity* entity ); SGF::Entity* GetEntity() const; //------------------------------------------------------------------------- // component related things virtual void OnSlideEnd( as::Sprite* sprite, float value ); virtual void OnSlideTo( as::Sprite* sprite, float value ); virtual void OnSliderChange(); virtual void OnRemoveComponent( void* extra_data ); virtual void OnAddComponent( const std::string& component_name ); //------------------------------------------------------------------------- void OpenProfilerViewer(); void CloseProfilerViewer(); void OpenProfilerBars(); void CloseProfilerBars(); types::vector2 mMousePositionInWorld; private: // all this for debugging? void RecreateInspector(); // component managers SGF::EventManager* mEventMgr; SGF::EntityManager* mEntityMgr; // ---------- as::Sprite* mDebugSprite; bool mLoadEntityEnabled; ConfigSliders* mConfigSliders; float mConfigSlidersSizeY; SimpleSlider* mConfigScrollbar; SGF::Entity* mInspectorEntity; float mInspectorTransformRotation; float mExInspectorTransformRotation; // mouse cursor bool mExCursorVisibility; std::auto_ptr< SimpleProfilerViewer > mProfilerViewer; std::auto_ptr< ProfilerBars > mProfilerBars; std::auto_ptr< Screenshotter > mScreenshotter; }; //----------------------------------------------------------------------------- inline void DebugLayer::SetLoadEntity( bool enabled ) { mLoadEntityEnabled = enabled; } //----------------------------------------------------------------------------- #endif
[ "petri.purho@gmail.com" ]
petri.purho@gmail.com
5be498ee5c4bfa0dd44247af379d4d720fe50dee
b7f1b4df5d350e0edf55521172091c81f02f639e
/components/signin/core/browser/profile_management_switches_unittest.cc
bc1f10317fa58ed0011785347b01b06a7a0c5d27
[ "BSD-3-Clause" ]
permissive
blusno1/chromium-1
f13b84547474da4d2702341228167328d8cd3083
9dd22fe142b48f14765a36f69344ed4dbc289eb3
refs/heads/master
2023-05-17T23:50:16.605396
2018-01-12T19:39:49
2018-01-12T19:39:49
117,339,342
4
2
NOASSERTION
2020-07-17T07:35:37
2018-01-13T11:48:57
null
UTF-8
C++
false
false
5,284
cc
// 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 "components/signin/core/browser/profile_management_switches.h" #include <memory> #include "base/bind.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "components/prefs/pref_member.h" #include "components/signin/core/browser/scoped_account_consistency.h" #include "components/signin/core/browser/signin_features.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h" namespace signin { #if BUILDFLAG(ENABLE_MIRROR) TEST(ProfileManagementSwitchesTest, GetAccountConsistencyMethodMirror) { // Mirror is enabled by default on some platforms. EXPECT_EQ(AccountConsistencyMethod::kMirror, GetAccountConsistencyMethod()); EXPECT_TRUE(IsAccountConsistencyMirrorEnabled()); EXPECT_FALSE(IsDiceMigrationEnabled()); EXPECT_FALSE(IsDiceFixAuthErrorsEnabled()); } #else TEST(ProfileManagementSwitchesTest, GetAccountConsistencyMethod) { SetGaiaOriginIsolatedCallback(base::Bind([] { return true; })); base::MessageLoop loop; sync_preferences::TestingPrefServiceSyncable pref_service; RegisterAccountConsistencyProfilePrefs(pref_service.registry()); std::unique_ptr<BooleanPrefMember> dice_pref_member = CreateDicePrefMember(&pref_service); // By default account consistency is disabled. EXPECT_EQ(AccountConsistencyMethod::kDisabled, GetAccountConsistencyMethod()); struct TestCase { AccountConsistencyMethod method; bool expect_mirror_enabled; bool expect_dice_fix_auth_errors; bool expect_dice_prepare_migration; bool expect_dice_prepare_migration_new_endpoint; bool expect_dice_migration; bool expect_dice_enabled_for_profile; } test_cases[] = { {AccountConsistencyMethod::kDisabled, false, false, false, false, false, false}, #if BUILDFLAG(ENABLE_DICE_SUPPORT) {AccountConsistencyMethod::kDiceFixAuthErrors, false, true, false, false, false, false}, {AccountConsistencyMethod::kDicePrepareMigration, false, true, true, false, false, false}, {AccountConsistencyMethod::kDicePrepareMigrationChromeSyncEndpoint, false, true, true, true, false, false}, {AccountConsistencyMethod::kDiceMigration, false, true, true, true, true, false}, {AccountConsistencyMethod::kDice, false, true, true, true, true, true}, #endif {AccountConsistencyMethod::kMirror, true, false, false, false, false, false} }; for (const TestCase& test_case : test_cases) { ScopedAccountConsistency scoped_method(test_case.method); EXPECT_EQ(test_case.method, GetAccountConsistencyMethod()); EXPECT_EQ(test_case.expect_mirror_enabled, IsAccountConsistencyMirrorEnabled()); EXPECT_EQ(test_case.expect_dice_fix_auth_errors, IsDiceFixAuthErrorsEnabled()); EXPECT_EQ(test_case.expect_dice_migration, IsDiceMigrationEnabled()); EXPECT_EQ(test_case.expect_dice_prepare_migration, IsDicePrepareMigrationEnabled()); EXPECT_EQ(test_case.expect_dice_prepare_migration_new_endpoint, IsDicePrepareMigrationChromeSyncEndpointEnabled()); EXPECT_EQ(test_case.expect_dice_enabled_for_profile, IsDiceEnabledForProfile(&pref_service)); EXPECT_EQ(test_case.expect_dice_enabled_for_profile, IsDiceEnabled(dice_pref_member.get())); } } #if BUILDFLAG(ENABLE_DICE_SUPPORT) TEST(ProfileManagementSwitchesTest, DiceMigration) { base::MessageLoop loop; sync_preferences::TestingPrefServiceSyncable pref_service; RegisterAccountConsistencyProfilePrefs(pref_service.registry()); std::unique_ptr<BooleanPrefMember> dice_pref_member = CreateDicePrefMember(&pref_service); { ScopedAccountConsistencyDiceMigration scoped_dice_migration; MigrateProfileToDice(&pref_service); } struct TestCase { AccountConsistencyMethod method; bool expect_dice_enabled_for_profile; } test_cases[] = { {AccountConsistencyMethod::kDisabled, false}, {AccountConsistencyMethod::kDiceFixAuthErrors, false}, {AccountConsistencyMethod::kDicePrepareMigration, false}, {AccountConsistencyMethod::kDicePrepareMigrationChromeSyncEndpoint, false}, {AccountConsistencyMethod::kDiceMigration, true}, {AccountConsistencyMethod::kDice, true}, {AccountConsistencyMethod::kMirror, false}}; for (const TestCase& test_case : test_cases) { ScopedAccountConsistency scoped_method(test_case.method); EXPECT_EQ(test_case.expect_dice_enabled_for_profile, IsDiceEnabledForProfile(&pref_service)); EXPECT_EQ(test_case.expect_dice_enabled_for_profile, IsDiceEnabled(dice_pref_member.get())); } } // Tests that Dice is disabled when site isolation is disabled. TEST(ProfileManagementSwitchesTest, GaiaSiteIsolation) { ScopedAccountConsistencyDicePrepareMigration scoped_dice; ASSERT_TRUE(IsDicePrepareMigrationEnabled()); SetGaiaOriginIsolatedCallback(base::Bind([] { return false; })); EXPECT_FALSE(IsDicePrepareMigrationEnabled()); } #endif // BUILDFLAG(ENABLE_DICE_SUPPORT) #endif // BUILDFLAG(ENABLE_MIRROR) } // namespace signin
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
92c54ec3a832a49b270e6560f9ad3b08ac0a7a10
e660125640388337437346a694b9db6ead70815d
/browser/vivaldi_webcontents_util.cc
c88116afadbf512357df9c29e589b36ea4a75fa8
[ "BSD-3-Clause" ]
permissive
mario2100/Vivaldi-browser
d20c0be7d3a3177b5ab99c98bd8c8629fad2c4a9
14495941bdcc786867fbec5418d5f39dc18e9370
refs/heads/master
2023-07-16T12:46:16.254620
2021-09-06T16:13:59
2021-09-06T16:13:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
715
cc
// Copyright (c) 2016 Vivaldi. All rights reserved. #include "browser/vivaldi_webcontents_util.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/guest_view/web_view/web_view_guest.h" namespace vivaldi { bool IsVivaldiMail(content::WebContents* web_contents) { extensions::WebViewGuest* web_view_guest = extensions::WebViewGuest::FromWebContents(web_contents); return web_view_guest && web_view_guest->IsVivaldiMail(); } bool IsVivaldiWebPanel(content::WebContents* web_contents) { extensions::WebViewGuest* web_view_guest = extensions::WebViewGuest::FromWebContents(web_contents); return web_view_guest && web_view_guest->IsVivaldiWebPanel(); } } // vivaldi
[ "mathieu.caroff@free.fr" ]
mathieu.caroff@free.fr
a39a55c715f086212102b1efa8983104867647a6
400fd356eb75d95ab35e8dcce2f5b03b3d272e83
/Smjy/src/common/logging/appender_file.cpp
1f15860189874f74ab3fb1efddced90e90a88e18
[]
no_license
shandaming/Martial_arts
4eba4c3856d0fbbcddc460790b4a06ba79a9c3ed
896f10a7c457a9f166e7991e54943d46b6a953b5
refs/heads/master
2022-11-11T08:05:21.439745
2022-10-22T05:55:23
2022-10-22T05:55:23
116,259,077
0
0
null
null
null
null
UTF-8
C++
false
false
2,799
cpp
/* * Copyright (C) 2018 */ #include <cstdio> #include <cstring> #include <algorithm> #include "appender_file.h" #include "log.h" appender_file::appender_file(uint8_t id, const std::string& name, log_level level, appender_flags flags, std::vector<const char*> extra_args) : appender(id, name, level, flags), logfile_(NULL), log_dir_(LOG->get_logs_dir()), max_file_size_(0), file_size_(0) { if (extra_args.empty()) throw invalid_appender_args_exception(string_format("log::create_appender_from_config: " "Missing file name for appender %s\n", name.c_str())); filename_ = extra_args[0]; char const* mode = "a"; if (extra_args.size() > 1) mode = extra_args[1]; if (flags & APPENDER_FLAGS_USE_TIMESTAMP) { size_t dot_pos = filename_.find_last_of("."); if (dot_pos != std::string::npos) filename_.insert(dot_pos, LOG->get_logs_timestamp()); else filename_ += LOG->get_logs_timestamp(); } if (extra_args.size() > 2) max_file_size_ = atoi(extra_args[2]); dynamic_name_ = std::string::npos != filename_.find("%s"); backup_ = (flags & APPENDER_FLAGS_MAKE_FILE_BACKUP) != 0; if (!dynamic_name_) logfile_ = open_file(filename_, mode, !strcmp(mode, "w") && backup_); } void appender_file::_write(const log_message* message) { bool exceed_max_size = max_file_size_ > 0 && (file_size_.load() + message->size()) > max_file_size_; if (dynamic_name_) { char namebuf[PATH_MAX]; snprintf(namebuf, PATH_MAX, filename_.c_str(), message->param1.c_str()); // always use "a" with dynamic name otherwise it could delete the log we wrote in last _write() call FILE* file = open_file(namebuf, "a", backup_ || exceed_max_size); if (!file) return; fprintf(file, "%s%s\n", message->prefix.c_str(), message->text.c_str()); fflush(file); file_size_ += uint64_t(message->size()); fclose(file); return; } else if (exceed_max_size) logfile_ = open_file(filename_, "w", true); if (!logfile_) return; fprintf(logfile_, "%s%s\n", message->prefix.c_str(), message->text.c_str()); fflush(logfile_); file_size_ += uint64_t(message->size()); } FILE* appender_file::open_file(const std::string& filename, const std::string& mode, bool backup) { std::string full_name(log_dir_ + filename); if (backup) { close_file(); std::string new_name(full_name); new_name.push_back('.'); new_name.append(log_message::get_time_str(time(NULL))); std::replace(new_name.begin(), new_name.end(), ':', '-'); // 没有错误处理...如果无法进行备份,只需忽略 rename(full_name.c_str(), new_name.c_str()); } if (FILE* ret = fopen(full_name.c_str(), mode.c_str())) { file_size_ = ftell(ret); return ret; } return nullptr; } void appender_file::close_file() { if (logfile_) { fclose(logfile_); logfile_ = nullptr; } }
[ "shandaming@hotmail.com" ]
shandaming@hotmail.com
855b62b62150f20959df7bdfd54ed0df476325bb
c0a6f68a03879dcd19d9fc7ab04af917f6044633
/src/test/compress_tests.cpp
5ed9b099c6b6ba7e53907a76ab535694552d9910
[ "MIT" ]
permissive
zzcasper/Joash-Coin-Sources
6738671b5777c4a1a868dc01ecfe736c5c3fbe83
f01c1dfe9659245d4ccebb4fa57177911f0e2aae
refs/heads/master
2020-04-27T02:38:01.151118
2019-03-06T18:44:38
2019-03-06T18:44:38
174,000,842
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compressor.h" #include "util.h" #include "test/test_joashcoin.h" #include <stdint.h> #include <boost/test/unit_test.hpp> // amounts 0.00000001 .. 0.00100000 #define NUM_MULTIPLES_UNIT 100000 // amounts 0.01 .. 100.00 #define NUM_MULTIPLES_CENT 10000 // amounts 1 .. 10000 #define NUM_MULTIPLES_1BTC 10000 // amounts 50 .. 21000000 #define NUM_MULTIPLES_50BTC 420000 BOOST_FIXTURE_TEST_SUITE(compress_tests, BasicTestingSetup) bool static TestEncode(uint64_t in) { return in == CTxOutCompressor::DecompressAmount(CTxOutCompressor::CompressAmount(in)); } bool static TestDecode(uint64_t in) { return in == CTxOutCompressor::CompressAmount(CTxOutCompressor::DecompressAmount(in)); } bool static TestPair(uint64_t dec, uint64_t enc) { return CTxOutCompressor::CompressAmount(dec) == enc && CTxOutCompressor::DecompressAmount(enc) == dec; } BOOST_AUTO_TEST_CASE(compress_amounts) { BOOST_CHECK(TestPair( 0, 0x0)); BOOST_CHECK(TestPair( 1, 0x1)); BOOST_CHECK(TestPair( CENT, 0x7)); BOOST_CHECK(TestPair( COIN, 0x9)); BOOST_CHECK(TestPair( 50*COIN, 0x32)); BOOST_CHECK(TestPair(150000000*COIN, 0x1406f40)); for (uint64_t i = 1; i <= NUM_MULTIPLES_UNIT; i++) BOOST_CHECK(TestEncode(i)); for (uint64_t i = 1; i <= NUM_MULTIPLES_CENT; i++) BOOST_CHECK(TestEncode(i * CENT)); for (uint64_t i = 1; i <= NUM_MULTIPLES_1BTC; i++) BOOST_CHECK(TestEncode(i * COIN)); for (uint64_t i = 1; i <= NUM_MULTIPLES_50BTC; i++) BOOST_CHECK(TestEncode(i * 50 * COIN)); for (uint64_t i = 0; i < 100000; i++) BOOST_CHECK(TestDecode(i)); } BOOST_AUTO_TEST_SUITE_END()
[ "ibo.casper@gmail.com" ]
ibo.casper@gmail.com
1ca3d7a605d839743821f7f712b3edb99dfabe0a
39286cb21ded262aa700894482992a10067212c2
/proj2_seetaface2/SeetaFace2/SeetaNet/src/include_inner/SeetaNetResource.h
b2a6930fd66fa2ea5c6244ee669bdac4035e0189
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
permissive
rbbernardino/face-recognition-eval
076e6e664101e111ae1ee8f554bd526dbbb90d82
a5a8f75a7e29f34a74077f205b4f0dceb731a15b
refs/heads/master
2021-09-10T06:02:36.279085
2020-04-11T03:17:46
2020-04-11T03:17:46
240,072,179
0
0
Apache-2.0
2021-09-08T01:55:37
2020-02-12T17:24:58
C++
UTF-8
C++
false
false
1,673
h
#ifndef _SEETANET_RESOURCE_H_ #define _SEETANET_RESOURCE_H_ #include <vector> #include <map> #include "SeetaNetMacro.h" #include "SeetaNetCommon.h" #include "SeetaNetBlobCpu.h" template<class T> struct SeetaNetShareParam { std::map<int, SeetaNetBlobCpu<T> > param_map; int m_refrence_counts = 0; int m_device; // type of SeetaNet_DEVICE_TYPE SeetaNetShareParam() { } ~SeetaNetShareParam() { } }; template<class T> struct SeetaNetResource { int max_batch_size; SeetaNetShareParam<T> *m_shared_param; std::map<std::string, int> blob_name_map; std::vector<int> layer_type_vector; std::vector<SeetaNetDataSize> feature_vector_size; /* saving resized input */ int m_new_width = -1; int m_new_height = -1; SeetaNetBlobCpu<T> col_buffer_; std::vector<int> col_buffer_shape_; int process_device_type; int process_max_batch_size; int current_process_size; int colbuffer_memory_size; int CaculateMemorySize( std::vector<int> shape_vector ) { int counts = 0; if( !shape_vector.empty() ) { counts = 1; for( int i = 0; i < shape_vector.size(); i++ ) { counts *= shape_vector[i]; } } return counts; }; int UpdateNetResourceMemory( std::vector<int> shape_vector ) { int new_memory_size = CaculateMemorySize( shape_vector ); if( new_memory_size > colbuffer_memory_size ) { col_buffer_shape_ = shape_vector; colbuffer_memory_size = new_memory_size; col_buffer_.Reshape( shape_vector ); } return 0; }; }; #endif
[ "rbbernardino@gmail.com" ]
rbbernardino@gmail.com
95c52c9069448f400ac94a98720bbdcccceb2f69
76556a8351f5438b81f9054fd2df067fc038d37a
/src/renderer.h
ac22afa0d649dd37de4eeb5391305702fd5e56a8
[]
no_license
harikrishnanum/SnakeGame
e638b47e4b3b60078ddae84f45d09a3c8b537c20
c421259ff4379a84ff25e48cdedf7f00eb950cd6
refs/heads/master
2023-04-27T21:36:19.429203
2020-04-20T05:29:55
2020-04-20T05:29:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#ifndef RENDERER_H #define RENDERER_H #include <vector> #include "SDL.h" #include "obstacles.h" #include "snake.h" #include <string> class Renderer { public: Renderer(const std::size_t screen_width, const std::size_t screen_height, const std::size_t grid_width, const std::size_t grid_height); ~Renderer(); void Render(Snake const snake, SDL_Point const &food); void UpdateWindowTitle(std::string diff, int level, int score, int fps); private: SDL_Window *sdl_window; SDL_Renderer *sdl_renderer; const std::size_t screen_width; const std::size_t screen_height; const std::size_t grid_width; const std::size_t grid_height; }; #endif
[ "hariknair77@gmail.com" ]
hariknair77@gmail.com
822873fe2534ab95c4f91e53236aeae3d1c770b1
7f237f107ae6e22a2c4c87b7bf25a2e5cdb05b75
/Source/Math/AvMath.cpp
f939afb39892c1ef3cac9bccc09b096167b4d720
[]
no_license
rshageev/Avalanche
9aecee505104cc0e8149837196c717d595b50e75
50e4316590cf2ebb1378390c8fb1256123abf948
refs/heads/master
2023-02-22T07:52:16.594639
2015-11-11T16:07:18
2015-11-11T16:07:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include "stdafx.h" #include <random> namespace math { static std::mt19937 rng(98934); template<class T> T random(T min_value, T max_value) { std::uniform_real_distribution<T> dist(min_value, max_value); return dist(rng); } }
[ "renatsh@playrix.com" ]
renatsh@playrix.com
4e7918cd191d5307d6c565a566e15279e146536a
3dea61864d9fd7dd05859862b1ebeec7f52b809f
/hw2/assignment2/assignment2/headers.h
e86c2ce596410420866ee5e906c5ca44c95de5db
[ "MIT" ]
permissive
jay16213/NCTU-2017-graphics
30b805241e45a243419b766015f9473a5c441077
09a07b4edb46bc95da484d86a5da28a65e8103e3
refs/heads/master
2021-03-22T02:06:17.750637
2017-12-17T15:45:27
2017-12-17T15:45:27
111,369,845
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
#ifndef HEADERS_H #define HEADERS_H #define _USE_MATH_DEFINES #include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <math.h> #include <cmath> #include <map> #include "FreeImage.h" #include "glew.h" #include "glut.h" #include "LightLoader.h" #include "SceneLoader.h" #include "ViewLoader.h" #include "Srcpath.h" #include "mesh.h" using namespace std; #define X 0 #define Y 1 #define Z 2 #define FRONT 10 #define BACK 20 void Display(); void ReShape(int w, int h); void objViewTransform(int depth); void lighting(int depth); void renderObj(mesh *obj, int depth); void drawMirror(Model *mirror, int dir, int depth); void drawScene(int dir, int depth); void setStencil(); void Keyboard(unsigned char key, int x, int y); #endif
[ "jay101630@gmail.com" ]
jay101630@gmail.com
c1d01371f4d7a6c073dbb858e695ecb5d4873b1e
51ced7a43318837fc11b81a934d3f6a989baf987
/SOURCE/allProjects/Book_Data_Base/Book_Data_Base/linkedListType.h
3f81c802569b89b9d1c5c2207addf9503011ca57
[ "MIT" ]
permissive
llanesjuan/AllMyProjects
6fcb3eeefc0740d3f3d8bed639a6c3e8f0534bf8
5944b248ae8f4f84cfea9fcf379f877909372551
refs/heads/master
2020-12-30T22:33:08.251247
2017-03-31T02:20:41
2017-03-31T02:20:41
86,514,030
0
0
null
null
null
null
UTF-8
C++
false
false
7,278
h
#pragma once #include <iostream> #include"linkedListIterator.h" using namespace std; template <class Type> class linkedListType { public: const linkedListType<Type>& operator=(const linkedListType<Type>&); //Overload the assignment operator. void initializeList(); //Initialize the list to an empty state. //Postcondition: first = NULL, last = NULL, count = 0; bool isEmptyList() const; //Function to determine whether the list is empty. //Postcondition: Returns true if the list is empty, // otherwise it returns false. void print() const; //Function to output the data contained in each node. //Postcondition: none int length() const; //Function to return the number of nodes in the list. //Postcondition: The value of count is returned. void destroyList(); //Function to delete all the nodes from the list. //Postcondition: first = NULL, last = NULL, count = 0; Type front() const; //Function to return the first element of the list. //Precondition: The list must exist and must not be // empty. //Postcondition: If the list is empty, the program // terminates; otherwise, the first // element of the list is returned. Type back() const; //Function to return the last element of the list. //Precondition: The list must exist and must not be // empty. //Postcondition: If the list is empty, the program // terminates; otherwise, the last // element of the list is returned virtual bool search(const Type& searchItem) const = 0; //Function to determine whether searchItem is in the list. //Postcondition: Returns true if searchItem is in the // list, otherwise the value false is // returned. virtual void insertFirst(const Type& newItem) = 0; //Function to insert newItem at the beginning of the list. //Postcondition: first points to the new list, newItem is // inserted at the beginning of the list, // last points to the last node in the list, // and count is incremented by 1. virtual void insertLast(const Type& newItem) = 0; //Function to insert newItem at the end of the list. //Postcondition: first points to the new list, newItem // is inserted at the end of the list, // last points to the last node in the list, // and count is incremented by 1. virtual void deleteNode(const Type& deleteItem) = 0; //Function to delete deleteItem from the list. //Postcondition: If found, the node containing // deleteItem is deleted from the list. // first points to the first node, last // points to the last node of the updated // list, and count is decremented by 1. linkedListIterator<Type> begin(); //Function to return an iterator at the begining of the //linked list. //Postcondition: Returns an iterator such that current is // set to first. linkedListIterator<Type> end(); //Function to return an iterator one element past the //last element of the linked list. //Postcondition: Returns an iterator such that current is // set to NULL. linkedListType(); //default constructor //Initializes the list to an empty state. //Postcondition: first = NULL, last = NULL, count = 0; linkedListType(const linkedListType<Type>& otherList); //copy constructor ~linkedListType(); //destructor //Deletes all the nodes from the list. //Postcondition: The list object is destroyed. protected: int count; //variable to store the number nodeType<Type> *first; //pointer to the first node of the list nodeType<Type> *last; //pointer to the last node of the list private: void copyList(const linkedListType<Type>& otherList); //Function to make a copy of otherList. //Postcondition: A copy of otherList is created and // assigned to this list. }; template <class Type> bool linkedListType<Type>::isEmptyList() const { return (first == NULL); } template <class Type> linkedListType<Type>::linkedListType() //default constructor { first = NULL; last = NULL; count = 0; } template <class Type> void linkedListType<Type>::destroyList() { nodeType<Type> *temp; //pointer to deallocate the memory //occupied by the node while (first != NULL) //while there are nodes in the list { temp = first; //set temp to the current node first = first->link; //advance first to the next node delete temp; //deallocate the memory occupied by temp } last = NULL; //initialize last to NULL; first has already //been set to NULL by the while loop count = 0; } template <class Type> void linkedListType<Type>::initializeList() { destroyList(); //if the list has any nodes, delete them } template <class Type> void linkedListType<Type>::print() const { nodeType<Type> *current; //pointer to traverse the list current = first; //set current so that it points to //the first node while (current != NULL) //while more data to print { cout << current->info << endl; current = current->link; } }// template <class Type> int linkedListType<Type>::length() const { return count; } template <class Type> Type linkedListType<Type>::front() const { assert(first != NULL); return first->info; //return the info of the first node }//end front template <class Type> Type linkedListType<Type>::back() const { assert(last != NULL); return last->info; //return the info of the last node }//end back template <class Type> linkedListIterator<Type> linkedListType<Type>::begin() { linkedListIterator<Type> temp(first); return temp; } template <class Type> linkedListIterator<Type> linkedListType<Type>::end() { linkedListIterator<Type> temp(NULL); return temp; } template <class Type> void linkedListType<Type>::copyList(const linkedListType<Type>& otherList) { nodeType<Type> *newNode; //pointer to create a node nodeType<Type> *current; //pointer to traverse the list if (first != NULL) //if the list is nonempty, make it empty destroyList(); if (otherList.first == NULL) //otherList is empty { first = NULL; last = NULL; count = 0; } else { current = otherList.first; //current points to the //list to be copied count = otherList.count; //copy the first node first = new nodeType<Type>; //create the node first->info = current->info; //copy the info first->link = NULL; //set the link field of //the node to NULL last = first; //make last point to the //first node current = current->link; //make current point to //the next node //copy the remaining list while (current != NULL) { newNode = new nodeType<Type>; //create a node newNode->info = current->info; //copy the info newNode->link = NULL; //set the link of //newNode to NULL last->link = newNode; //attach newNode after last last = newNode; //make last point to //the actual last node current = current->link; //make current point //to the next node }//end while }//end else }//end copyList template <class Type>linkedListType<Type>::~linkedListType() //destructor { destroyList(); } template <class Type> linkedListType<Type>::linkedListType(const linkedListType<Type>& otherList) { first = NULL; copyList(otherList); }//end copy constructor //overload the assignment operator template <class Type> const linkedListType<Type>& linkedListType<Type>::operator=(const linkedListType<Type>& otherList) { if (this != &otherList) //avoid self-copy { copyList(otherList); }//end else return *this; }
[ "llanes.juan@outlook.com" ]
llanes.juan@outlook.com
5e5211eb5c6543711317a480f86aa9cb191c5939
136690e17494e42a142602c46f13a6c89e42bfb9
/src/Utils.hpp
48c8719292ae750aaa5aaae784b5029ee6107897
[]
no_license
gregzb/gfx_02_line
67b77575fa67f3a9c78b1e868a3a1b912b75cf0d
c0a42ff106663de41f9514ebaf290f7929c037b4
refs/heads/master
2021-01-02T07:20:50.255880
2020-02-11T03:51:11
2020-02-11T03:51:11
239,545,715
0
0
null
null
null
null
UTF-8
C++
false
false
542
hpp
#pragma once #include "Vec.hpp" #include <vector> class Color { public: unsigned char r; unsigned char g; unsigned char b; unsigned char a; Color(); Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a); Color(int r, int g, int b, int a); }; namespace Utils { int sign(double x); double inverseLerp(double a, double b, double val); double lerp(double a, double b, double t); std::vector<Vec> linePixels(double x0, double y0, double x1, double y1, bool flipped = false); } // namespace Utils
[ "greg.zbo3@gmail.com" ]
greg.zbo3@gmail.com
75b6d3b4bdab3e2ed4d65b82990af8faceebfc14
bd6a267ff0b205b5b6749489a3f704486c1935ed
/CSCE-121/Project/Graph.h
d6bc774e18db571fbe68508c2a55b088c1f75d10
[]
no_license
rawrbyte/Code-Dump-TAMU
132e0aa1c2ed4ecfd62310c56604f3bc425b920b
18a90cbfd6968931e8a057092dd2e5f3efb5447e
refs/heads/master
2020-03-15T17:45:44.568661
2018-06-11T06:53:48
2018-06-11T06:53:48
132,269,006
1
0
null
null
null
null
UTF-8
C++
false
false
11,297
h
/* Graph.h Minimally revised for C++11 features of GCC 4.6.3 or later Walter C. Daugherity June 10, 2012 Walter C. Daugherity January 9, 2014 Walter C. Daugherity January 20, 2014 Walter C. Daugherity March 3, 2014 Walter C. Daugherity March 6, 2014 */ // // This is a GUI support code to the chapters 12-16 of the book // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // #ifndef GRAPH_GUARD #define GRAPH_GUARD 1 #include <FL/fl_draw.H> #include <FL/Fl_Image.H> #include "Point.h" #include "std_lib_facilities_4.h" namespace Graph_lib { // defense against ill-behaved Linux macros: #undef major #undef minor //------------------------------------------------------------------------------ // Color is the type we use to represent color. We can use Color like this: // grid.set_color(Color::red); struct Color { enum Color_type : unsigned char { red=FL_RED, blue=FL_BLUE, green=FL_GREEN, yellow=FL_YELLOW, white=FL_WHITE, black=FL_BLACK, magenta=FL_MAGENTA, cyan=FL_CYAN, dark_red=FL_DARK_RED, dark_green=FL_DARK_GREEN, dark_yellow=FL_DARK_YELLOW, dark_blue=FL_DARK_BLUE, dark_magenta=FL_DARK_MAGENTA, dark_cyan=FL_DARK_CYAN }; enum Transparency : unsigned char { invisible = 0, visible=255 }; Color(Color_type cc) :v(visible), c(Fl_Color(cc)) { } Color(Color_type cc, Transparency vv) :v(vv), c(Fl_Color(cc)) { } Color(int cc) :v(visible), c(Fl_Color(cc)) { } Color(Transparency vv) :v(vv), c(Fl_Color()) { } // default color int as_int() const { return c; } char visibility() const { return v; } void set_visibility(Transparency vv) { v=vv; } private: unsigned char v; // invisible and visible for now Fl_Color c; }; //------------------------------------------------------------------------------ struct Line_style { enum Line_style_type { solid=FL_SOLID, // ------- dash=FL_DASH, // - - - - dot=FL_DOT, // ....... dashdot=FL_DASHDOT, // - . - . dashdotdot=FL_DASHDOTDOT, // -..-.. }; Line_style(Line_style_type ss) :s(ss), w(0) { } Line_style(Line_style_type lst, int ww) :s(lst), w(ww) { } Line_style(int ss) :s(ss), w(0) { } int width() const { return w; } int style() const { return s; } private: int s; int w; }; //------------------------------------------------------------------------------ class Font { public: enum Font_type { helvetica=FL_HELVETICA, helvetica_bold=FL_HELVETICA_BOLD, helvetica_italic=FL_HELVETICA_ITALIC, helvetica_bold_italic=FL_HELVETICA_BOLD_ITALIC, courier=FL_COURIER, courier_bold=FL_COURIER_BOLD, courier_italic=FL_COURIER_ITALIC, courier_bold_italic=FL_COURIER_BOLD_ITALIC, times=FL_TIMES, times_bold=FL_TIMES_BOLD, times_italic=FL_TIMES_ITALIC, times_bold_italic=FL_TIMES_BOLD_ITALIC, symbol=FL_SYMBOL, screen=FL_SCREEN, screen_bold=FL_SCREEN_BOLD, zapf_dingbats=FL_ZAPF_DINGBATS }; Font(Font_type ff) :f(ff) { } Font(int ff) :f(ff) { } int as_int() const { return f; } private: int f; }; //------------------------------------------------------------------------------ template<class T> class Vector_ref { vector<T*> v; vector<T*> owned; public: Vector_ref() {} Vector_ref(T& a) { push_back(a); } Vector_ref(T& a, T& b); Vector_ref(T& a, T& b, T& c); Vector_ref(T* a, T* b = 0, T* c = 0, T* d = 0) { if (a) push_back(a); if (b) push_back(b); if (c) push_back(c); if (d) push_back(d); } ~Vector_ref() { for (int i=0; i<owned.size(); ++i) delete owned[i]; } void push_back(T& s) { v.push_back(&s); } void push_back(T* p) { v.push_back(p); owned.push_back(p); } T& operator[](int i) { return *v[i]; } const T& operator[](int i) const { return *v[i]; } int size() const { return v.size(); } private: // prevent copying Vector_ref(const Vector<T>&); Vector_ref& operator=(const Vector<T>&); }; //------------------------------------------------------------------------------ typedef double Fct(double); class Shape { // deals with color and style, and holds sequence of lines public: void draw() const; // deal with color and draw lines virtual void move(int dx, int dy); // move the shape +=dx and +=dy void set_color(Color col) { lcolor = col; } Color color() const { return lcolor; } void set_style(Line_style sty) { ls = sty; } Line_style style() const { return ls; } void set_fill_color(Color col) { fcolor = col; } Color fill_color() const { return fcolor; } Point point(int i) const { return points[i]; } // read only access to points int number_of_points() const { return int(points.size()); } virtual ~Shape() { } protected: Shape(); virtual void draw_lines() const; // draw the appropriate lines void add(Point p); // add p to points void set_point(int i,Point p); // points[i]=p; private: vector<Point> points; // not used by all shapes Color lcolor; // color for lines and characters Line_style ls; Color fcolor; // fill color Shape(const Shape&); // prevent copying Shape& operator=(const Shape&); }; //------------------------------------------------------------------------------ struct Function : Shape { // the function parameters are not stored Function(Fct f, double r1, double r2, Point orig, int count = 100, double xscale = 25, double yscale = 25); }; //------------------------------------------------------------------------------ struct Line : Shape { // a Line is a Shape defined by two Points Line(Point p1, Point p2); // construct a line from two points }; //------------------------------------------------------------------------------ struct Rectangle : Shape { Rectangle(Point xy, int ww, int hh) : h(hh), w(ww) { add(xy); if (h<=0 || w<=0) error("Bad rectangle: non-positive side"); } Rectangle(Point x, Point y) : h(y.y-x.y), w(y.x-x.x) { add(x); if (h<=0 || w<=0) error("Bad rectangle: non-positive width or height"); } void draw_lines() const; int height() const { return h; } int width() const { return w; } private: int h; // height int w; // width }; //------------------------------------------------------------------------------ struct Open_polyline : Shape { // open sequence of lines void add(Point p) { Shape::add(p); } void draw_lines() const; }; //------------------------------------------------------------------------------ struct Closed_polyline : Open_polyline { // closed sequence of lines void draw_lines() const; }; //------------------------------------------------------------------------------ struct Polygon : Closed_polyline { // closed sequence of non-intersecting lines void add(Point p); void draw_lines() const; }; //------------------------------------------------------------------------------ struct Lines : Shape { // related lines void draw_lines() const; void add(Point p1, Point p2); // add a line defined by two points }; //------------------------------------------------------------------------------ struct Text : Shape { // the point is the bottom left of the first letter Text(Point x, const string& s) : lab(s), fnt(fl_font()), fnt_sz((fl_size()<14)?14:fl_size()) { add(x); } void draw_lines() const; void set_label(const string& s) { lab = s; } string label() const { return lab; } void set_font(Font f) { fnt = f; } Font font() const { return Font(fnt); } void set_font_size(int s) { fnt_sz = s; } int font_size() const { return fnt_sz; } private: string lab; // label Font fnt; int fnt_sz; }; //------------------------------------------------------------------------------ struct Axis : Shape { enum Orientation { x, y, z }; Axis(Orientation d, Point xy, int length, int number_of_notches=0, string label = ""); void draw_lines() const; void move(int dx, int dy); void set_color(Color c); Text label; Lines notches; }; //------------------------------------------------------------------------------ struct Circle : Shape { Circle(Point p, int rr) // center and radius :r(rr) { add(Point(p.x-r,p.y-r)); } void draw_lines() const; Point center() const; void set_radius(int rr) { set_point(0,Point(center().x-rr,center().y-rr)); r=rr; } int radius() const { return r; } private: int r; }; //------------------------------------------------------------------------------ struct Ellipse : Shape { Ellipse(Point p, int ww, int hh) // center, min, and max distance from center :w(ww), h(hh) { add(Point(p.x-ww,p.y-hh)); } void draw_lines() const; Point center() const { return Point(point(0).x+w,point(0).y+h); } Point focus1() const { if (h<=w)// foci are on the x-axis: return Point(center().x+int(sqrt(double(w*w-h*h))),center().y); else // foci are on the y-axis: return Point(center().x,center().y+int(sqrt(double(h*h-w*w)))); } Point focus2() const { if (h<=w) return Point(center().x-int(sqrt(double(w*w-h*h))),center().y); else return Point(center().x,center().y-int(sqrt(double(h*h-w*w)))); } //Point focus2() const { return Point(center().x-int(sqrt(double(abs(w*w-h*h)))),center().y); } void set_major(int ww) { set_point(0,Point(center().x-ww,center().y-h)); w=ww; } int major() const { return w; } void set_minor(int hh) { set_point(0,Point(center().x-w,center().y-hh)); h=hh; } int minor() const { return h; } private: int w; int h; }; //------------------------------------------------------------------------------ struct Marked_polyline : Open_polyline { Marked_polyline(const string& m) :mark(m) { } void draw_lines() const; private: string mark; }; //------------------------------------------------------------------------------ struct Marks : Marked_polyline { Marks(const string& m) :Marked_polyline(m) { set_color(Color(Color::invisible)); } }; //------------------------------------------------------------------------------ struct Mark : Marks { Mark(Point xy, char c) : Marks(string(1,c)) { add(xy); } }; //------------------------------------------------------------------------------ struct Suffix { enum Encoding { none, jpg, gif }; }; Suffix::Encoding get_encoding(const string& s); //------------------------------------------------------------------------------ struct Image : Shape { Image(Point xy, string file_name, Suffix::Encoding e = Suffix::none); ~Image() { delete p; } void draw_lines() const; void set_mask(Point xy, int ww, int hh) { w=ww; h=hh; cx=xy.x; cy=xy.y; } private: int w,h; // define "masking box" within image relative to position (cx,cy) int cx,cy; Fl_Image* p; Text fn; }; //------------------------------------------------------------------------------ struct Bad_image : Fl_Image { Bad_image(int h, int w) : Fl_Image(h,w,0) { } void draw(int x,int y, int, int, int, int) { draw_empty(x,y); } }; //------------------------------------------------------------------------------ } // of namespace Graph_lib #endif
[ "rawrbyte@compute.cs.tamu.edu" ]
rawrbyte@compute.cs.tamu.edu
fa3f8c4218f09c39f011aeab3afb7d5b155e78e7
b511576b8be5f55a21a74c96480832910115a0c3
/core/src/Streaming/Stream.cpp
ea99e83341065a537597745ad5598df18bed3f4b
[ "BSD-3-Clause" ]
permissive
adamnemecek/crimild
c5fc3b2e130ed26cf3e54f76bb26bcc2d7a7dad1
3edc5965b05b2b6f6eb61ba9e727550a5ff25578
refs/heads/master
2021-07-06T21:46:46.803574
2017-09-03T22:20:37
2017-09-03T22:20:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,655
cpp
/* * Copyright (c) 2013, Hernan Saez * 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 <organization> 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 <COPYRIGHT HOLDER> 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 "Stream.hpp" #include "Foundation/Version.hpp" #include "Foundation/Log.hpp" #include "Rendering/VertexFormat.hpp" #include <algorithm> using namespace crimild; constexpr const char *Stream::FLAG_STREAM_START; constexpr const char *Stream::FLAG_STREAM_END; constexpr const char *Stream::FLAG_TOP_LEVEL_OBJECT; constexpr const char *Stream::FLAG_INNER_OBJECT; constexpr const char *Stream::FLAG_OBJECT_START; constexpr const char *Stream::FLAG_OBJECT_END; bool StreamObject::registerInStream( Stream &s ) { return s.registerObject( this ); } void StreamObject::save( Stream &s ) { s.write( getClassName() ); s.write( getUniqueIdentifier() ); } void StreamObject::load( Stream &s ) { } SharedPointer< StreamObject > StreamObjectFactory::buildObject( std::string className ) { if ( _builders[ className ] == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "No builder registred for StreamObject of class ", className ); return nullptr; } return _builders[ className ](); } Stream::Stream( void ) { } Stream::~Stream( void ) { } bool Stream::isTopLevel( SharedPointer< StreamObject > const &obj ) const { for ( const auto &other : _topLevelObjects ) { // double check if ( other == obj && other->getUniqueIdentifier() == obj->getUniqueIdentifier() ) { return true; } } return false; } bool Stream::registerObject( StreamObject *obj ) { return registerObject( obj->getUniqueIdentifier(), crimild::retain( obj ) ); } bool Stream::registerObject( StreamObject::StreamObjectId objId, SharedPointer< StreamObject > const &obj ) { if ( _objects[ objId ] != nullptr ) { // object already register, remove it so it will be reinserted // again with a higher priority _orderedObjects.remove( obj ); } _objects[ objId ] = obj; _orderedObjects.push_back( obj ); return true; } void Stream::addObject( SharedPointer< StreamObject > const &obj ) { if ( isTopLevel( obj ) ) { return; } _topLevelObjects.push_back( obj ); } bool Stream::flush( void ) { write( Stream::FLAG_STREAM_START ); write( _version.getDescription() ); for ( auto &obj : _topLevelObjects ) { if ( obj != nullptr ) { obj->registerInStream( *this ); } } for ( auto it = _orderedObjects.rbegin(); it != _orderedObjects.rend(); it++ ) { auto &obj = *it; if ( obj != nullptr ) { if ( isTopLevel( obj ) ) { write( Stream::FLAG_TOP_LEVEL_OBJECT ); } else { write( Stream::FLAG_INNER_OBJECT ); } write( Stream::FLAG_OBJECT_START ); obj->save( *this ); write( Stream::FLAG_OBJECT_END ); } } write( Stream::FLAG_STREAM_END ); return true; } bool Stream::load( void ) { std::string flag; read( flag ); if ( flag != Stream::FLAG_STREAM_START ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Invalid file format" ); return false; } std::string versionStr; read( versionStr ); _version.fromString( versionStr ); while ( true ) { read( flag ); if ( flag == Stream::FLAG_STREAM_END ) { break; } bool topLevel = ( flag == Stream::FLAG_TOP_LEVEL_OBJECT ); read( flag ); if ( flag != Stream::FLAG_OBJECT_START ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Invalid file format. Expected ", Stream::FLAG_OBJECT_START ); return false; } std::string className; read( className ); StreamObject::StreamObjectId objId; read( objId ); auto obj = StreamObjectFactory::getInstance()->buildObject( className ); if ( obj == nullptr ) { Log::debug( CRIMILD_CURRENT_CLASS_NAME, "Cannot build object of type ", className, " with id ", objId ); return false; } obj->load( *this ); if ( topLevel ) { addObject( obj ); } registerObject( objId, obj ); read( flag ); if ( flag != Stream::FLAG_OBJECT_END ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Invalid file format. Expected ", Stream::FLAG_OBJECT_END ); return false; } } return true; } void Stream::write( const std::string &str ) { write( str.c_str() ); } void Stream::write( const char *str ) { write( ( unsigned int ) strlen( str ) ); writeRawBytes( str, strlen( str ) ); } void Stream::write( const VertexFormat &vf ) { write( vf.getPositionComponents() ); write( vf.getColorComponents() ); write( vf.getNormalComponents() ); write( vf.getTangentComponents() ); write( vf.getTextureCoordComponents() ); write( vf.getBoneIdComponents() ); write( vf.getBoneWeightComponents() ); } void Stream::write( const Quaternion4f &q ) { write( q.getRawData() ); } void Stream::write( const Transformation &t ) { write( t.getTranslate() ); write( t.getRotate() ); write( t.getScale() ); } void Stream::write( char c ) { writeRawBytes( &c, sizeof( char ) ); } void Stream::write( unsigned char c ) { writeRawBytes( &c, sizeof( unsigned char ) ); } void Stream::write( short s ) { writeRawBytes( &s, sizeof( short ) ); } void Stream::write( unsigned short s ) { writeRawBytes( &s, sizeof( unsigned short ) ); } void Stream::write( int i ) { writeRawBytes( &i, sizeof( int ) ); } void Stream::write( unsigned int i ) { writeRawBytes( &i, sizeof( unsigned int ) ); } void Stream::write( long long ll ) { writeRawBytes( &ll, sizeof( long long ) ); } void Stream::write( unsigned long long ll ) { writeRawBytes( &ll, sizeof( unsigned long long ) ); } void Stream::write( float f ) { writeRawBytes( &f, sizeof( float ) ); } void Stream::read( std::string &str ) { unsigned int count = 0; read( count ); if ( count == 0 ) { str = ""; return; } std::vector< char > buffer( count + 1 ); readRawBytes( &buffer[ 0 ], count ); buffer[ count ] = '\0'; str = std::string( ( const char * ) &buffer[ 0 ] ); } void Stream::read( VertexFormat &vf ) { unsigned char positions; read( positions ); unsigned char colors; read( colors ); unsigned char normals; read( normals ); unsigned char tangents; read( tangents ); unsigned char textureCoords; read( textureCoords ); unsigned char boneIds; read( boneIds ); unsigned char boneWeights; read( boneWeights ); vf = VertexFormat( positions, colors, normals, tangents, textureCoords, boneIds, boneWeights ); } void Stream::read( Quaternion4f &q ) { Vector4f v; read( v ); q = Quaternion4f( v ); } void Stream::read( Transformation &t ) { read( t.translate() ); read( t.rotate() ); read( t.scale() ); } void Stream::read( char &c ) { readRawBytes( &c, sizeof( char ) ); } void Stream::read( unsigned char &c ) { readRawBytes( &c, sizeof( unsigned char ) ); } void Stream::read( short &s ) { readRawBytes( &s, sizeof( short ) ); } void Stream::read( unsigned short &s ) { readRawBytes( &s, sizeof( unsigned short ) ); } void Stream::read( int &i ) { readRawBytes( &i, sizeof( int ) ); } void Stream::read( unsigned int &i ) { readRawBytes( &i, sizeof( unsigned int ) ); } void Stream::read( long long &i ) { readRawBytes( &i, sizeof( long long ) ); } void Stream::read( unsigned long long &i ) { readRawBytes( &i, sizeof( unsigned long long ) ); } void Stream::read( float &f ) { readRawBytes( &f, sizeof( float ) ); }
[ "hhsaez@gmail.com" ]
hhsaez@gmail.com
52f86c5a6bddb70cd6fb92453b962ce271a9ce89
8e9c8f677cafbeadd7fc1ce3da9723189194c3d0
/chess.cpp
4fdf13a031c240e13fb7664c9a73369657f76b0e
[]
no_license
aizaz-shahid/university_projects
4b35d60f3ea86b121babd5e2d9e8cbb36738b01d
8d279d8478613fe54badf247f982702ac818ebea
refs/heads/master
2020-05-26T15:45:07.589239
2019-05-23T19:11:25
2019-05-23T19:11:25
188,291,894
0
0
null
null
null
null
UTF-8
C++
false
false
14,883
cpp
#include <iostream> #include <conio.h> #include <string> #include <typeinfo> using namespace std; class piece { string sign; public: piece() { sign = "___"; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; class king :public piece { string sign; public: king(string ch) { sign = ch; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; class queen :public piece { string sign; public: queen(string ch) { sign = ch; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; class ghora :public piece { string sign; public: ghora(string ch) { sign = ch; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; class feel :public piece { string sign; public: feel(string ch) { sign = ch; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; class Rooks :public piece { string sign; public: Rooks(string ch) { sign = ch; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; class pyada :public piece { string sign; public: pyada(string ch) { sign = ch; } virtual void setSign(string ch) { sign = ch; } virtual int getSign0() { int x=0; x=sign[0]; x=x-48; return x; } virtual char getSign1() { return sign[1]; } virtual void display() { cout << sign; } }; void display(piece *** ptr); bool playerSelection(piece *** ptr,int count,int i,int j); bool moveIsValid(piece *** ptr,int count,int i,int j,int k,int l); void initialize(piece *** ptr); void move(piece ***ptr, int count); int main() { bool gameOver = false; piece *** gb; gb = new piece **[8]; for (int i = 0; i < 8; i++) { gb[i] = new piece *[8]; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { gb[i][j] = new piece; } } initialize(gb); display(gb); int count = 0; while (gameOver != true) { if (count % 2 == 0) cout << "Player 1's turn" << endl; else cout << "Player 2's turn" << endl; move(gb, count); system("CLS"); display(gb); count++; } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { delete gb[i][j]; gb[i][j] = NULL; } delete[] gb[i]; gb[i] = NULL; } delete[] gb; gb = NULL; //getch(); return 0; } void display(piece *** ptr) { cout<<endl<<endl; cout<<"\t\t\t\t Guide Line"<<endl<<endl; cout<<"Use letters A-H for rows and numbers 0-7 for columns"<<endl<<endl<<endl<<endl<<endl<<endl; int cols[8]={0,1,2,3,4,5,6,7}; char rows[8]={'A','B','C','D','E','F','G','H'}; cout<<"\t"; for(int i=0;i<8;i++) { cout<<cols[i]<<"\t"; } cout<<endl<<endl; cout<<" _________________________________________________________________"<<endl<<endl; for (int i = 0; i < 8; i++) { cout<<rows[i]<<" | \t"; for (int j = 0; j < 8; j++) { ptr[i][j]->display(); cout << "\t"; } cout << endl << endl << endl; } } void move(piece ***ptr, int count) { bool moveMade; moveMade=false; string from, to; int i = 0, j = 0, k = 0, l = 0; do { cout << "enter the position of the piece you want to move" << endl; cin >> from; cout << "enter the position where you want to place the piece" << endl; cin >> to; if (from[0] == 'A' || from[0] == 'a') i = 0; else if (from[0] == 'B' || from[0] == 'b') i = 1; else if (from[0] == 'C' || from[0] == 'c') i = 2; else if (from[0] == 'D' || from[0] == 'd') i = 3; else if (from[0] == 'E' || from[0] == 'e') i = 4; else if (from[0] == 'F' || from[0] == 'f') i = 5; else if (from[0] == 'G' || from[0] == 'g') i = 6; else if (from[0] == 'H' || from[0] == 'h') i = 7; j = from[1]; j = j - 48; if (to[0] == 'A' || to[0] == 'a') k = 0; else if (to[0] == 'B' || to[0] == 'b') k = 1; else if (to[0] == 'C' || to[0] == 'c') k = 2; else if (to[0] == 'D' || to[0] == 'd') k = 3; else if (to[0] == 'E' || to[0] == 'e') k = 4; else if (to[0] == 'F' || to[0] == 'f') k = 5; else if (to[0] == 'G' || to[0] == 'g') k = 6; else if (to[0] == 'H' || to[0] == 'h') k = 7; l = to[1]; l = l - 48; if(playerSelection(ptr,count,i,j) && moveIsValid(ptr,count,i,j,k,l)) { if (typeid(*ptr[k][l]) == typeid(king)) { delete ptr[k][l]; ptr[k][l] = NULL; ptr[k][l] = ptr[i][j]; ptr[i][j] = new piece; moveMade=true; display(ptr); if (count % 2 == 0) cout << "Player 1 won the game" << endl; else cout << "Player 2 won the game" << endl; exit(0); } else { delete ptr[k][l]; ptr[k][l] = NULL; ptr[k][l] = ptr[i][j]; ptr[i][j] = new piece; moveMade=true; } } else { cout<<"Move is invalid"<<endl; } }while(!moveMade); } bool playerSelection(piece *** ptr,int count,int i,int j) { int x=0; x=ptr[i][j]->getSign0(); if (count % 2 == 0 && x == 1) return true; else if(count % 2 !=0 && x == 2) return true; else return false; } bool moveIsValid(piece *** ptr,int count,int i,int j,int k,int l) { if((i>7 || i<0) || (j>7 || j<0) || (k>7 || k<0) || (l>7 || l<0)) { return false; } else if(ptr[i][j]->getSign0() == ptr[k][l]->getSign0()) { return false; } else if(ptr[i][j]->getSign1() == 'P') { if (count % 2 == 0) { if(k!=(i+1) || l!=j) { if((k==(i+1) && l==(j+1)) || (k==(i+1) && l==(j-1))) { if(typeid(*ptr[k][l]) == typeid(piece)) { return false; } else { return true; } } else { return false; } } else { if(typeid(*ptr[k][l]) != typeid(piece)) { return false; } else { return true; } } } else { if(k!=(i-1) || l!=j) { if((k==(i-1) && l==(j+1)) || (k==(i-1) && l==(j-1))) { if(typeid(*ptr[k][l]) == typeid(piece)) { return false; } else { return true; } } else { return false; } } else { if(typeid(*ptr[k][l]) != typeid(piece)) { return false; } else { return true; } } } } else if(ptr[i][j]->getSign1() == 'G') { if((k==(i-2) && l==(j+1)) || (k==(i-2) && l==(j-1)) || (k==(i+2) && l==(j+1)) || (k==(i+2) && l==(j-1)) || (k==(i-1) && l==(j+2)) || (k==(i-1) && l==(j-2)) || (k==(i+1) && l==(j+2)) || (k==(i+1) && l==(j-2))) { return true; } else { return false; } } else if(ptr[i][j]->getSign1() == 'R') { for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++) { if(x==k && y==l) { for(int x=i+1,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--) { if(x==k && y==l) { for(int x=i-1,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y++) { if(x==k && y==l) { for(int x=i,y=j+1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y++) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y--) { if(x==k && y==l) { for(int x=i,y=j-1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y--) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } } else if(ptr[i][j]->getSign1() == 'K') { if(k!=(i+1) || l!=j) { if((k==(i+1) && l==(j+1)) || (k==(i+1) && l==(j-1))) { return true; } else { return false; } } else { return true; } } else if(ptr[i][j]->getSign1() == 'F') { for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y++) { if(x==k && y==l) { for(int x=i+1,y=j+1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y++) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y--) { if(x==k && y==l) { for(int x=i+1,y=j-1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y--) { if(x==k && y==l) { return true; } if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y++) { if(x==k && y==l) { for(int x=i-1,y=j+1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y++) { if(x==k && y==l) { return true; } if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y--) { if(x==k && y==l) { for(int x=i-1,y=j-1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y--) { if(x==k && y==l) { return true; } if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } return false; } else if(ptr[i][j]->getSign1() == 'Q') { for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++) { if(x==k && y==l) { for(int x=i+1,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--) { if(x==k && y==l) { for(int x=i-1,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y++) { if(x==k && y==l) { for(int x=i,y=j+1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y++) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y--) { if(x==k && y==l) { for(int x=i,y=j-1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; y--) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y++) { if(x==k && y==l) { for(int x=i+1,y=j+1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y++) { if(x==k && y==l) { return true; } else if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y--) { if(x==k && y==l) { for(int x=i+1,y=j-1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x++,y--) { if(x==k && y==l) { return true; } if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y++) { if(x==k && y==l) { for(int x=i-1,y=j+1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y++) { if(x==k && y==l) { return true; } if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } for(int x=i,y=j ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y--) { if(x==k && y==l) { for(int x=i-1,y=j-1 ; (x>=0 && x<=7) && (y>=0 && y<=7) ; x--,y--) { if(x==k && y==l) { return true; } if(typeid(*ptr[x][y]) != typeid(piece)) { return false; } } } } return false; } return true; } void initialize(piece *** gb) { delete gb[0][0]; delete gb[0][1]; delete gb[0][2]; delete gb[0][3]; delete gb[0][4]; delete gb[0][5]; delete gb[0][6]; delete gb[0][7]; delete gb[1][7]; delete gb[1][6]; delete gb[1][5]; delete gb[1][4]; delete gb[1][3]; delete gb[1][2]; delete gb[1][1]; delete gb[1][0]; delete gb[6][0]; delete gb[6][1]; delete gb[6][2]; delete gb[6][3]; delete gb[6][4]; delete gb[6][5]; delete gb[6][6]; delete gb[6][7]; delete gb[7][0]; delete gb[7][1]; delete gb[7][2]; delete gb[7][3]; delete gb[7][4]; delete gb[7][5]; delete gb[7][6]; delete gb[7][7]; gb[0][0] = NULL; gb[0][1] = NULL; gb[0][2] = NULL; gb[0][3] = NULL; gb[0][4] = NULL; gb[0][5] = NULL; gb[0][6] = NULL; gb[0][7] = NULL; gb[1][7] = NULL; gb[1][6] = NULL; gb[1][5] = NULL; gb[1][4] = NULL; gb[1][3] = NULL; gb[1][2] = NULL; gb[1][1] = NULL; gb[1][0] = NULL; gb[6][0] = NULL; gb[6][1] = NULL; gb[6][2] = NULL; gb[6][3] = NULL; gb[6][4] = NULL; gb[6][5] = NULL; gb[6][6] = NULL; gb[6][7] = NULL; gb[7][0] = NULL; gb[7][1] = NULL; gb[7][2] = NULL; gb[7][3] = NULL; gb[7][4] = NULL; gb[7][5] = NULL; gb[7][6] = NULL; gb[7][7] = NULL; gb[0][0] = new Rooks("1R"); gb[0][1] = new ghora("1G"); gb[0][2] = new feel("1F"); gb[0][3] = new king("1K"); gb[0][4] = new queen("1Q"); gb[0][5] = new feel("1F"); gb[0][6] = new ghora("1G"); gb[0][7] = new Rooks("1R"); gb[1][7] = new pyada("1P"); gb[1][6] = new pyada("1P"); gb[1][5] = new pyada("1P"); gb[1][4] = new pyada("1P"); gb[1][3] = new pyada("1P"); gb[1][2] = new pyada("1P"); gb[1][1] = new pyada("1P"); gb[1][0] = new pyada("1P"); gb[6][0] = new pyada("2P"); gb[6][1] = new pyada("2P"); gb[6][2] = new pyada("2P"); gb[6][3] = new pyada("2P"); gb[6][4] = new pyada("2P"); gb[6][5] = new pyada("2P"); gb[6][6] = new pyada("2P"); gb[6][7] = new pyada("2P"); gb[7][0] = new Rooks("2R"); gb[7][1] = new ghora("2G"); gb[7][2] = new feel("2F"); gb[7][3] = new king("2K"); gb[7][4] = new queen("2Q"); gb[7][5] = new feel("2F"); gb[7][6] = new ghora("2G"); gb[7][7] = new Rooks("2R"); }
[ "aizazshahid47@gmail.com" ]
aizazshahid47@gmail.com
2feec98adddf9d0cdae2b6aeca38b52ec02f18e0
0afb70bd608dc4740ed31769fc869b08303cbf6b
/MY C++ prog/array/matrix 4 by 3.cpp
3684dba19a5ba836ca21ee78acef47248ba46e0c
[]
no_license
Festusmastermind/ProgrammingC-
cb306b40c65d33b70f7362722fa4befa04f16af6
62ee28777165c14eb80b47e8a4d4573560e6258d
refs/heads/master
2020-07-25T14:07:40.278290
2019-09-14T01:49:57
2019-09-14T01:49:57
208,316,724
0
0
null
null
null
null
UTF-8
C++
false
false
1,225
cpp
#include <iostream> using namespace std; main() { // intitialization method int i,j; int mymatrix_A[3][4]={3,1,4,8, 5,2,6,7, 9,1,5,8}; int mymatrix_B[3][4]={2,3,4,5, 5,7,9,8, 1,4,3,2}; int mymatrix_C[3][4]; // this section is the processing section for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { mymatrix_C[i][j]=mymatrix_A[i][j]+mymatrix_B[i][j]; } } cout<<"\n\n"; //this section output the processing cout<<"\n\tMy Matrix_A\n\n"; for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { cout<<mymatrix_A[i][j]<<"\t"; } cout<<endl; } cout<<"\n\tMy Matrix_B\n\n"; for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { cout<<mymatrix_B[i][j]<<"\t"; } cout<<endl<<endl; } //note that this is the summation of the matrix cout<<"\n\tMy Matrix_C\n\n"; for(int i=0; i<3; i++) { for(int j=0; j<4; j++) { cout<<mymatrix_C[i][j]<<"\t"; } cout<<"\n\n"; } // this section captures and compute the transpose of matrix c cout<<"\tMatrix_C Transpose\n\n"; for(int i=0; i<4; i++) { for(int j=0; j<3; j++) { cout<<mymatrix_C[j][i]<<"\t"; } cout<<"\n\n"; } return 0; }
[ "adusunkanmi333@gmail.com" ]
adusunkanmi333@gmail.com
d06359f0b45e146ea0a0452f0bd07c9b72dc61c9
9ab460da5210fafc09a1b427bdacef4e82282857
/BS/BS7/src/bs7Setup.cpp
5acef84608ccbbb6bfe588c4119dbdf612bba692
[ "MIT" ]
permissive
paranumal/streamparanumal
a9768c33104b27855b5d1099ef6735bbfdb4e8d7
8c1e76189a8e782e9c3a0986f214070ef59c53a8
refs/heads/main
2023-07-06T16:53:58.351534
2023-07-05T16:24:01
2023-07-05T16:24:01
296,924,470
3
4
NOASSERTION
2023-07-05T16:24:02
2020-09-19T18:04:03
C++
UTF-8
C++
false
false
1,318
cpp
/* The MIT License (MIT) Copyright (c) 2017-2022 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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. */ #include "bs7.hpp" void bs7_t::Setup(platform_t &_platform, settings_t& _settings, mesh_t& _mesh){ platform = _platform; settings = _settings; mesh = _mesh; }
[ "noel.chalmers@gmail.com" ]
noel.chalmers@gmail.com
c4e6c36cbc0017df596508c7c01d7206e8259968
e1522f45a46820f6ddbfcc699379821e7eb660af
/mirea/cources/beginner/set-map-lower_bound-403337/B.cpp
09736d93bb1fde6a4065cc2d598c2984f6b78336
[]
no_license
dmkz/competitive-programming
1b8afa76eefbdfd9d5766d5347e99b1bfc50761b
8d02a5db78301cf34f5fdffd3fdf399c062961cb
refs/heads/master
2023-08-21T00:09:21.754596
2023-08-13T13:21:48
2023-08-13T13:21:48
130,999,150
21
12
null
2023-02-16T17:43:53
2018-04-25T11:54:48
C++
UTF-8
C++
false
false
1,133
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); // будем хранить оригинальное имя для каждого нового имени // и список активных имён int n; cin >> n; map<string, string> originalName; set<string> actualNames; while(n--) { string oldName, newName; cin >> oldName >> newName; // произошла замена имени: actualNames.erase(oldName); // старое выкидываем actualNames.insert(newName); // новое оставляем // инициализируем, если oldName ещё не было if(!originalName.count(oldName)) originalName[oldName] = oldName; // сохраняем оригинальное имя для нового имени originalName[newName] = originalName[oldName]; } // выводим ответ cout << actualNames.size() << '\n'; for (const auto &name : actualNames) cout << originalName[name] << ' ' << name << '\n'; }
[ "dmkozyrev@rambler.ru" ]
dmkozyrev@rambler.ru
43a09d971f58fd13f4b74eee1cc1246265abfc9c
6940836c6b426849b75f95ca5a75cb23f5a46bca
/Core/util/StringUtil.h
91d0c0200c48cc170b90cb25f2f963d58c28905a
[]
no_license
xhyangxianjun/MyEcho
6e82aceac85545e62923cd47877d70280dc7c8a9
0e63e44864e25a72b216c203d44c257f43c2596d
refs/heads/master
2021-05-29T22:27:28.963702
2015-11-04T03:04:10
2015-11-04T03:04:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
341
h
#pragma once #include <iostream> #include <vector> class StringUtil { public: static std::string RandomStringA(int nLength); static std::wstring RandomStringW(int nLength); static std::vector<std::string> SplitA(std::string str, std::string pattern); static std::vector<std::wstring> SplitW(std::wstring str, std::wstring pattern); };
[ "xiaotan@outlook.com" ]
xiaotan@outlook.com
6da2150f75bbef29e0b8db396dfe113ce5ef1bbf
1ef7f309bf775b45ee69e80b9db0d242184c3bc2
/v3d_main/neuron_annotator/gui/trees/EntityTreeView.cpp
76329e25db2c7687c192f4a383dd4c1b59c66aa8
[ "MIT" ]
permissive
Vaa3D/v3d_external
8eebb703b6bc7be5af73597fe0b2972d93e8490f
5405addd44bba9867eaa7037d6e985cc9ed311e7
refs/heads/master
2023-08-17T19:13:40.159258
2022-08-22T13:38:11
2022-08-22T13:38:11
50,527,479
43
48
MIT
2022-10-19T12:29:00
2016-01-27T18:12:19
C++
UTF-8
C++
false
false
1,449
cpp
#include "EntityTreeView.h" #include "EntityTreeModel.h" #include "../../entity_model/Entity.h" #include <QtGui> EntityTreeView::EntityTreeView(QWidget *parent) : QTreeView(parent) { setSelectionBehavior(QAbstractItemView::SelectRows); } void EntityTreeView::keyPressEvent(QKeyEvent *event) { // Ignore all key presses so that they can be captured by AnnotationWidget's event listener event->ignore(); } void EntityTreeView::selectEntity(const qint64 & entityId) { // Get the indexes EntityTreeModel *treeModel = static_cast<EntityTreeModel *>(model()); QModelIndex termIndex = treeModel->indexForId(entityId); QModelIndex beginIndex = treeModel->index(termIndex.row(), 0, termIndex.parent()); QModelIndex endIndex = treeModel->index(termIndex.row(), treeModel->columnCount() - 1, termIndex.parent()); // Select the indexes QItemSelectionModel *selection = selectionModel(); selection->clearSelection(); selection->select(QItemSelection(beginIndex, endIndex), QItemSelectionModel::Select); // Expand to the node expandTo(termIndex); scrollTo(termIndex); } void EntityTreeView::expandTo(const QModelIndex &index) { EntityTreeModel *treeModel = static_cast<EntityTreeModel *>(model()); QModelIndex curr = index; while (curr.isValid()) { setExpanded(model()->index(curr.row(), 0, treeModel->parent(curr)), true); curr = treeModel->parent(curr); } }
[ "rokickik@janelia.hhmi.org" ]
rokickik@janelia.hhmi.org
a942150abb9bfcfefa37d743118e177a030a63d5
e2b80c517b4b0ab3051bb95a3b695b424b80bf66
/剑指offer/翻转单词顺序列/main.cpp
8b8afd83667d6060de39273bb9d8375a55ed38ca
[]
no_license
TheBeatles1994/BlueBridge
738df4932d4c65a0c9bcd5e762645753f0a06430
10aa67a6b54a64a707b531d96f25a6b6b89f445f
refs/heads/master
2021-04-27T00:04:52.319108
2018-09-04T08:51:04
2018-09-04T08:51:04
123,747,735
7
3
null
null
null
null
UTF-8
C++
false
false
481
cpp
#include <iostream> #include <string> using namespace std; string ReverseSentence(string str) { string rst; size_t pos; while((pos = str.find_last_of(' '))!= string::npos) { rst.append(str.substr(pos+1)); rst.append(" "); str.erase(pos); } rst.append(str); return rst; } int main(int argc, char *argv[]) { string str = "student. a am I"; // while(cin>>str) // { cout<<ReverseSentence(str)<<endl; // } }
[ "479488209@qq.com" ]
479488209@qq.com
2e6c2add887d98193dd0e8ca233f8e8ca52768af
256f67e7af72d84090ee1c49fa3494c2fe856b34
/inVerify.cpp
8fe6d23a132b39529ed541f1396eae9179d69291
[ "MIT" ]
permissive
DanCSmugBug/House-Hunt
4ddb40957bcaf7c6f5d470b25ee2f72bdcf597dd
0b39c1cb42d4657b7be262166f9113f672bb5088
refs/heads/master
2020-06-10T04:55:04.483995
2019-06-25T02:23:18
2019-06-25T02:23:18
193,588,609
0
0
null
null
null
null
UTF-8
C++
false
false
907
cpp
/* * Project: Penguin Derby * File: inVerify.cpp * Author: Daniel Cole * Version: 1.0 * Version Date: 6/24/2019 * * Description: Implementation file for inVerify */ #include "inVerify.h" int inVerify::getGoodInt() { int value; cin >> value; if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); throw string("ERROR: BAD INPUT \n"); } else { return value; } } string inVerify::getGoodStr() { string word; cin >> word; if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); throw string("ERROR: BAD INPUT \n"); } else { return word; } } char inVerify::getGoodChar() { char letter; cin >> letter; if (cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); throw string("ERROR: BAD INPUT \n"); } else { return letter; } }
[ "noreply@github.com" ]
noreply@github.com
943e47c2fdcc4b774f08c3b88e32d04252ae3159
d7449e345451cfdb681e59ebaad9f0d8d6c1cd2c
/intelligent-agent/util/converter.cpp
777ed336989fc30eb07eca0d7b6206cca5d637e9
[]
no_license
kkalkidan/intelligent-agent
c39b51fb855d9d60a2ab0f4977cf974bdb3328b2
42b71242a02380ca71d058b00ee8aecc5c24bd95
refs/heads/master
2021-05-19T03:25:45.782012
2020-03-28T13:04:18
2020-03-28T13:04:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,753
cpp
#include <iostream> #include <string.h> #include <string> #include "converter.hpp" using namespace std; int top = -1, top1 = -1; char cont1[100]; char cont2[100]; void push(char num) { top++; cont1[top] = num; } void push1(char num1) { top1++; cont2[top1] = num1; } void pop() { cont1[top--]; } void pop1() { cont2[top1--]; } typedef char cont[100] ; char *main_converter(char x[100]) {; for (int i = 0; i < strlen(x); i++) { if (x[i] == '(') { while (x[i] != ')') { if (x[i] == '(') push1(x[i]); else if(x[i]=='-') { if(x[i+1]=='>'){ push1(x[i+1]); push1(x[i]); i++; } else { if (x[i] != '>') push(x[i]); } } else if (x[i] == '<'){ push1(x[i+2]); push1(x[i+1]); push1(x[i]); i=+2; } else if(x[i] =='^'){ push1(x[i]); } else if (x[i] == 'v') { push1(x[i]); } else { if (x[i] != '>') push(x[i]); } i++; } while (cont2[top1] != '(') { if (cont2[top1] != '(') { char o = cont2[top1]; push(o); pop1(); } else pop1(); } pop1(); } else if (x[i] == '-') { if (x[i + 1] == '>') { push1(x[i + 1]); push1(x[i]); i++; } else { push1(x[i]); } } else if (x[i] == '<') { push1(x[i + 2]); push1(x[i + 1]); push1(x[i]); i = +2; } else if (x[i] == '^') { push1(x[i]); } else if (x[i] == 'v') { push1(x[i]); } else { if (x[i] != '>') push(x[i]); } } while (top1 != -1) { if (cont2[top1] != '(') { char l = cont2[top1]; push(l); pop1(); } else pop1(); } return cont1; }
[ "bemhretgezahegn@gmail.com" ]
bemhretgezahegn@gmail.com
f700f5d0e9bf2521800f07fc4ebcefe076e52e85
2cf2200910b401efea09f0d597fd3b4fce0a4586
/Arcade/The_Core/C++/07_Book_Market/isMAC49Address.cpp
1ca878c965f87a2ff5b063ad0d37dc1cb9f2ab5e
[]
no_license
ldzzz/CodeSignal
c94abfdcc74c71670e91e37206667008adcbc159
f879d4622cada1d7561ecfef2dedeab991887b59
refs/heads/master
2020-03-26T22:17:33.366654
2018-09-14T21:48:13
2018-09-14T21:48:13
145,446,139
0
1
null
null
null
null
UTF-8
C++
false
false
169
cpp
bool isMAC48Address(std::string inputString) { std::regex myRegex ("([0-9A-F]{2}[\-]{1}){5}[0-9A-F]{2}"); return (std::regex_match (inputString, myRegex)); }
[ "eldinabdic47@gmail.com" ]
eldinabdic47@gmail.com
ff2e8b9d984a67507be13af6c9a302a0c4ecbf3a
6814e6556e620bbcbcf16f0dce7a15134b7830f1
/Projects/Skylicht/Collision/Source/Collision/CTriangleBB.cpp
0c98e49c20fbc15bc6f596be684fbb29cbf77b57
[ "MIT" ]
permissive
blizmax/skylicht-engine
1bfc506635a1e33b59ad0ce7b04183bcf87c7fc1
af99999f0a428ca8f3f144e662c1b23fd03b9ceb
refs/heads/master
2023-08-07T11:50:02.370130
2021-10-09T16:10:20
2021-10-09T16:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,362
cpp
/* !@ MIT License Copyright (c) 2021 Skylicht Technology CO., LTD 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. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #include "pch.h" #include "CTriangleBB.h" namespace Skylicht { CTriangleBB::CTriangleBB(CEntity* entity, const core::aabbox3df& bbox) : CTriangleSelector(entity) { m_triangles.set_used(12); m_bbox = bbox; } CTriangleBB::~CTriangleBB() { } void CTriangleBB::getTriangles(core::triangle3df* triangles, const core::matrix4* transform) { core::vector3df edges[8]; m_bbox.getEdges(edges); m_triangles[0].set(edges[3], edges[0], edges[2]); m_triangles[1].set(edges[3], edges[1], edges[0]); m_triangles[2].set(edges[3], edges[2], edges[7]); m_triangles[3].set(edges[7], edges[2], edges[6]); m_triangles[4].set(edges[7], edges[6], edges[4]); m_triangles[5].set(edges[5], edges[7], edges[4]); m_triangles[6].set(edges[5], edges[4], edges[0]); m_triangles[7].set(edges[5], edges[0], edges[1]); m_triangles[8].set(edges[1], edges[3], edges[7]); m_triangles[9].set(edges[1], edges[7], edges[5]); m_triangles[10].set(edges[0], edges[6], edges[2]); m_triangles[11].set(edges[0], edges[4], edges[6]); CTriangleSelector::getTriangles(triangles, transform); } const core::aabbox3df& CTriangleBB::getBBox() { return m_bbox; } }
[ "hongduc.pr@gmail.com" ]
hongduc.pr@gmail.com
08f5542fc3b51f13d0462de4371aa6f25b1b5866
cd385187124d24a8910729095c0ff50c26e1e3c4
/test/generators/BayesNetworkSinkTest.cpp
76732b94eaebd60937e0c66baac63ef2e2580024
[]
no_license
qiubix/DCL_BayesNetwork
c5c60c086b4130ac86fc8c149cc1a2bea63b02e2
0e69b1085cad3a217b1c66d6dffdaa91499c8c52
refs/heads/master
2020-12-18T22:25:48.340402
2016-11-22T13:42:30
2016-11-22T13:42:30
15,060,064
1
0
null
2016-11-22T13:27:24
2013-12-09T21:50:24
C++
UTF-8
C++
false
false
2,142
cpp
#include <gmock/gmock.h> #include <Components/BayesNetworkSink/BayesNetworkSink.hpp> #include <Types/BayesNetwork.hpp> using Sinks::Network::BayesNetworkSink; using Processors::Network::BayesNetwork; using namespace testing; class BayesNetworkSinkTest : public Test { public: BayesNetworkSink sink; }; TEST_F(BayesNetworkSinkTest, shouldCreateBayesNetworkSinkComponent) { ASSERT_THAT(sink.name(), Eq("BayesNetworkSink")); } TEST_F(BayesNetworkSinkTest, shouldInitializeStreams) { sink.prepareInterface(); ASSERT_THAT(sink.getStream("in_network"), NotNull()); } TEST_F(BayesNetworkSinkTest, shouldInitializeHandlers) { sink.prepareInterface(); ASSERT_THAT(sink.getHandler("onNewNetwork"), NotNull()); } TEST_F(BayesNetworkSinkTest, shouldImplementOnInitMethod) { ASSERT_THAT(sink.onInit(), Eq(true)); } TEST_F(BayesNetworkSinkTest, shouldImplementOnFinishMethod) { ASSERT_THAT(sink.onFinish(), Eq(true)); } TEST_F(BayesNetworkSinkTest, shouldImplementOnStartMethod) { ASSERT_THAT(sink.onStart(), Eq(true)); } TEST_F(BayesNetworkSinkTest, shouldImplementOnStopMethod) { ASSERT_THAT(sink.onStop(), Eq(true)); } //TEST_F(BayesNetworkSinkTest, shouldDisplayErrorIfNetworkIsNullOnNewNetwork) { // internal::CaptureStdout(); // // sink.onNewNetwork(); // // string output = internal::GetCapturedStdout(); // ASSERT_THAT(output, Eq("Error! Network is NULL.")); //} TEST_F(BayesNetworkSinkTest, shouldDisplayNetworkOnNewNetwork) { BayesNetwork network; network.addVoxelNode(0); network.addVoxelNode(1); network.addVoxelNode(2); network.addFeatureNode(0); network.addFeatureNode(1); network.connectNodes("F_0", "V_1"); network.connectNodes("F_1", "V_2"); network.connectNodes("V_1", "V_0"); network.connectNodes("V_2", "V_0"); sink.setNetwork(&network); internal::CaptureStdout(); sink.display(); string output = internal::GetCapturedStdout(); ASSERT_THAT(output, HasSubstr("Number of feature nodes: 2")); ASSERT_THAT(output, HasSubstr("Number of all nodes: 5")); //TODO: get more info about network // ASSERT_THAT(output, Eq("[1, 1, 1, 1;\n 1, 1, 1, 1;\n 1, 1, 1, 1]\n")); }
[ "qiubix@gmail.com" ]
qiubix@gmail.com
bb50c0351fe7bd0207fbc09dca2b21f64f59044c
e79fe203fecbdbd87f0c356e7d82695418fefb2d
/deps/gdal/ogr/ogrct.cpp
34f99ad2c0099ccbac0509f64672870659ca6fb6
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-warranty-disclaimer", "MIT", "SunPro", "LicenseRef-scancode-info-zip-2005-02", "BSD-3-Clause" ]
permissive
psandbrook/white-star
26ebac4321b0d0f3ee9e8acbed7041565fc8f609
e256bd262c0545d971569c7d1cd502eb5c94c62b
refs/heads/master
2023-07-04T05:34:30.681116
2021-08-03T19:54:52
2021-08-03T19:54:52
361,380,447
0
0
null
null
null
null
UTF-8
C++
false
false
78,632
cpp
/****************************************************************************** * * Project: OpenGIS Simple Features Reference Implementation * Purpose: The OGRSCoordinateTransformation class. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com> * * 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. ****************************************************************************/ #include "cpl_port.h" #include "ogr_spatialref.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstring> #include <limits> #include <list> #include "cpl_conv.h" #include "cpl_error.h" #include "cpl_string.h" #include "ogr_core.h" #include "ogr_srs_api.h" #include "ogr_proj_p.h" #include "proj.h" #include "proj_experimental.h" CPL_CVSID("$Id: ogrct.cpp 7294a96e7747b442cd7033280c2780cfd2bca572 2020-06-12 16:43:48 +0200 Even Rouault $") /************************************************************************/ /* OGRCoordinateTransformationOptions::Private */ /************************************************************************/ struct OGRCoordinateTransformationOptions::Private { bool bHasAreaOfInterest = false; double dfWestLongitudeDeg = 0.0; double dfSouthLatitudeDeg = 0.0; double dfEastLongitudeDeg = 0.0; double dfNorthLatitudeDeg = 0.0; CPLString osCoordOperation{}; bool bReverseCO = false; bool bHasSourceCenterLong = false; double dfSourceCenterLong = 0.0; bool bHasTargetCenterLong = false; double dfTargetCenterLong = 0.0; }; /************************************************************************/ /* OGRCoordinateTransformationOptions() */ /************************************************************************/ /** \brief Constructs a new OGRCoordinateTransformationOptions. * * @since GDAL 3.0 */ OGRCoordinateTransformationOptions::OGRCoordinateTransformationOptions(): d(new Private()) { } /************************************************************************/ /* OGRCoordinateTransformationOptions() */ /************************************************************************/ /** \brief Copy constructor * * @since GDAL 3.1 */ OGRCoordinateTransformationOptions::OGRCoordinateTransformationOptions( const OGRCoordinateTransformationOptions& other): d(new Private(*(other.d))) {} /************************************************************************/ /* operator =() */ /************************************************************************/ /** \brief Assignment operator * * @since GDAL 3.1 */ OGRCoordinateTransformationOptions& OGRCoordinateTransformationOptions::operator= (const OGRCoordinateTransformationOptions& other) { if( this != &other ) { *d = *(other.d); } return *this; } /************************************************************************/ /* OGRCoordinateTransformationOptions() */ /************************************************************************/ /** \brief Destroys a OGRCoordinateTransformationOptions. * * @since GDAL 3.0 */ OGRCoordinateTransformationOptions::~OGRCoordinateTransformationOptions() { } /************************************************************************/ /* OCTNewCoordinateTransformationOptions() */ /************************************************************************/ /** \brief Create coordinate transformation options. * * To be freed with OCTDestroyCoordinateTransformationOptions() * * @since GDAL 3.0 */ OGRCoordinateTransformationOptionsH OCTNewCoordinateTransformationOptions(void) { return new OGRCoordinateTransformationOptions(); } /************************************************************************/ /* OCTDestroyCoordinateTransformationOptions() */ /************************************************************************/ /** \brief Destroy coordinate transformation options. * * @since GDAL 3.0 */ void OCTDestroyCoordinateTransformationOptions( OGRCoordinateTransformationOptionsH hOptions) { delete hOptions; } /************************************************************************/ /* SetAreaOfInterest() */ /************************************************************************/ /** \brief Sets an area of interest. * * The west longitude is generally lower than the east longitude, except for * areas of interest that go across the anti-meridian. * * @param dfWestLongitudeDeg West longitude (in degree). Must be in [-180,180] * @param dfSouthLatitudeDeg South latitude (in degree). Must be in [-90,90] * @param dfEastLongitudeDeg East longitude (in degree). Must be in [-180,180] * @param dfNorthLatitudeDeg North latitude (in degree). Must be in [-90,90] * @return true in case of success. * * @since GDAL 3.0 */ bool OGRCoordinateTransformationOptions::SetAreaOfInterest( double dfWestLongitudeDeg, double dfSouthLatitudeDeg, double dfEastLongitudeDeg, double dfNorthLatitudeDeg) { if( std::fabs(dfWestLongitudeDeg) > 180 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid dfWestLongitudeDeg"); return false; } if( std::fabs(dfSouthLatitudeDeg) > 90 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid dfSouthLatitudeDeg"); return false; } if( std::fabs(dfEastLongitudeDeg) > 180 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid dfEastLongitudeDeg"); return false; } if( std::fabs(dfNorthLatitudeDeg) > 90 ) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid dfNorthLatitudeDeg"); return false; } if( dfSouthLatitudeDeg > dfNorthLatitudeDeg ) { CPLError(CE_Failure, CPLE_AppDefined, "dfSouthLatitudeDeg should be lower than dfNorthLatitudeDeg"); return false; } d->bHasAreaOfInterest = true; d->dfWestLongitudeDeg = dfWestLongitudeDeg; d->dfSouthLatitudeDeg = dfSouthLatitudeDeg; d->dfEastLongitudeDeg = dfEastLongitudeDeg; d->dfNorthLatitudeDeg = dfNorthLatitudeDeg; return true; } /************************************************************************/ /* OCTCoordinateTransformationOptionsSetAreaOfInterest() */ /************************************************************************/ /** \brief Sets an area of interest. * * See OGRCoordinateTransformationOptions::SetAreaOfInterest() * * @since GDAL 3.0 */ int OCTCoordinateTransformationOptionsSetAreaOfInterest( OGRCoordinateTransformationOptionsH hOptions, double dfWestLongitudeDeg, double dfSouthLatitudeDeg, double dfEastLongitudeDeg, double dfNorthLatitudeDeg) { return hOptions->SetAreaOfInterest( dfWestLongitudeDeg, dfSouthLatitudeDeg, dfEastLongitudeDeg, dfNorthLatitudeDeg); } /************************************************************************/ /* SetCoordinateOperation() */ /************************************************************************/ /** \brief Sets a coordinate operation. * * This is a user override to be used instead of the normally computed pipeline. * * The pipeline must take into account the axis order of the source and target * SRS. * * The pipeline may be provided as a PROJ string (single step operation or * multiple step string starting with +proj=pipeline), a WKT2 string describing * a CoordinateOperation, or a "urn:ogc:def:coordinateOperation:EPSG::XXXX" URN * * @param pszCO PROJ or WKT string describing a coordinate operation * @param bReverseCO Whether the PROJ or WKT string should be evaluated in the reverse path * @return true in case of success. * * @since GDAL 3.0 */ bool OGRCoordinateTransformationOptions::SetCoordinateOperation(const char* pszCO, bool bReverseCO) { d->osCoordOperation = pszCO ? pszCO : ""; d->bReverseCO = bReverseCO; return true; } /************************************************************************/ /* SetSourceCenterLong() */ /************************************************************************/ /*! @cond Doxygen_Suppress */ void OGRCoordinateTransformationOptions::SetSourceCenterLong(double dfCenterLong) { d->dfSourceCenterLong = dfCenterLong; d->bHasSourceCenterLong = true; } /*! @endcond */ /************************************************************************/ /* SetTargetCenterLong() */ /************************************************************************/ /*! @cond Doxygen_Suppress */ void OGRCoordinateTransformationOptions::SetTargetCenterLong(double dfCenterLong) { d->dfTargetCenterLong = dfCenterLong; d->bHasTargetCenterLong = true; } /*! @endcond */ /************************************************************************/ /* OCTCoordinateTransformationOptionsSetOperation() */ /************************************************************************/ /** \brief Sets a coordinate operation. * * See OGRCoordinateTransformationOptions::SetCoordinateTransformation() * * @since GDAL 3.0 */ int OCTCoordinateTransformationOptionsSetOperation( OGRCoordinateTransformationOptionsH hOptions, const char* pszCO, int bReverseCO) { return hOptions->SetCoordinateOperation(pszCO, CPL_TO_BOOL(bReverseCO)); } /************************************************************************/ /* OGRProjCT */ /************************************************************************/ //! @cond Doxygen_Suppress class OGRProjCT : public OGRCoordinateTransformation { OGRSpatialReference *poSRSSource = nullptr; bool bSourceLatLong = false; bool bSourceWrap = false; double dfSourceWrapLong = 0.0; OGRSpatialReference *poSRSTarget = nullptr; bool bTargetLatLong = false; bool bTargetWrap = false; double dfTargetWrapLong = 0.0; bool bWebMercatorToWGS84LongLat = false; int nErrorCount = 0; bool bCheckWithInvertProj = false; double dfThreshold = 0.0; PJ* m_pj = nullptr; bool m_bReversePj = false; int nMaxCount = 0; double *padfOriX = nullptr; double *padfOriY = nullptr; double *padfOriZ = nullptr; double *padfOriT = nullptr; double *padfTargetX = nullptr; double *padfTargetY = nullptr; double *padfTargetZ = nullptr; double *padfTargetT = nullptr; bool m_bEmitErrors = true; bool bNoTransform = false; enum class Strategy { PROJ, BEST_ACCURACY, FIRST_MATCHING }; #if PROJ_VERSION_MAJOR > 6 || PROJ_VERSION_MINOR >= 3 Strategy m_eStrategy = Strategy::PROJ; #else Strategy m_eStrategy = Strategy::BEST_ACCURACY; #endif bool ListCoordinateOperations(const char* pszSrcSRS, const char* pszTargetSRS, const OGRCoordinateTransformationOptions& options ); struct Transformation { double minx = 0.0; double miny = 0.0; double maxx = 0.0; double maxy = 0.0; PJ* pj = nullptr; CPLString osName{}; CPLString osProjString{}; double accuracy = 0.0; Transformation(double minxIn, double minyIn, double maxxIn, double maxyIn, PJ* pjIn, const CPLString& osNameIn, const CPLString& osProjStringIn, double accuracyIn): minx(minxIn), miny(minyIn), maxx(maxxIn), maxy(maxyIn), pj(pjIn), osName(osNameIn), osProjString(osProjStringIn), accuracy(accuracyIn) {} Transformation(const Transformation&) = delete; Transformation(Transformation&& other): minx(other.minx), miny(other.miny), maxx(other.maxx), maxy(other.maxy), pj(other.pj), osName(std::move(other.osName)), osProjString(std::move(other.osProjString)), accuracy(other.accuracy) { other.pj = nullptr; } Transformation& operator=(const Transformation&) = delete; ~Transformation() { if( pj ) { proj_assign_context(pj, OSRGetProjTLSContext()); proj_destroy(pj); } } }; std::vector<Transformation> m_oTransformations{}; int m_iCurTransformation = -1; OGRCoordinateTransformationOptions m_options{}; OGRProjCT(const OGRProjCT& other) { Initialize(other.poSRSSource, other.poSRSTarget, other.m_options); } OGRProjCT& operator= (const OGRProjCT& ) = delete; public: OGRProjCT(); ~OGRProjCT() override; int Initialize( const OGRSpatialReference *poSource, const OGRSpatialReference *poTarget, const OGRCoordinateTransformationOptions& options ); OGRSpatialReference *GetSourceCS() override; OGRSpatialReference *GetTargetCS() override; int Transform( int nCount, double *x, double *y, double *z, double *t, int *panSuccess ) override; bool GetEmitErrors() const override { return m_bEmitErrors; } void SetEmitErrors( bool bEmitErrors ) override { m_bEmitErrors = bEmitErrors; } OGRCoordinateTransformation* Clone() const override { return new OGRProjCT(*this); } }; //! @endcond /************************************************************************/ /* OCTDestroyCoordinateTransformation() */ /************************************************************************/ /** * \brief OGRCoordinateTransformation destructor. * * This function is the same as OGRCoordinateTransformation::DestroyCT() * * @param hCT the object to delete */ void CPL_STDCALL OCTDestroyCoordinateTransformation( OGRCoordinateTransformationH hCT ) { delete OGRCoordinateTransformation::FromHandle(hCT); } /************************************************************************/ /* DestroyCT() */ /************************************************************************/ /** * \brief OGRCoordinateTransformation destructor. * * This function is the same as * OGRCoordinateTransformation::~OGRCoordinateTransformation() * and OCTDestroyCoordinateTransformation() * * This static method will destroy a OGRCoordinateTransformation. It is * equivalent to calling delete on the object, but it ensures that the * deallocation is properly executed within the OGR libraries heap on * platforms where this can matter (win32). * * @param poCT the object to delete * * @since GDAL 1.7.0 */ void OGRCoordinateTransformation::DestroyCT( OGRCoordinateTransformation* poCT ) { delete poCT; } /************************************************************************/ /* OGRCreateCoordinateTransformation() */ /************************************************************************/ /** * Create transformation object. * * This is the same as the C function OCTNewCoordinateTransformation(). * * Input spatial reference system objects are assigned * by copy (calling clone() method) and no ownership transfer occurs. * * The delete operator, or OCTDestroyCoordinateTransformation() should * be used to destroy transformation objects. * * This will honour the axis order advertized by the source and target SRS, * as well as their "data axis to SRS axis mapping". * To have a behaviour similar to GDAL &lt; 3.0, the OGR_CT_FORCE_TRADITIONAL_GIS_ORDER * configuration option can be set to YES. * * @param poSource source spatial reference system. * @param poTarget target spatial reference system. * @return NULL on failure or a ready to use transformation object. */ OGRCoordinateTransformation* OGRCreateCoordinateTransformation( const OGRSpatialReference *poSource, const OGRSpatialReference *poTarget ) { return OGRCreateCoordinateTransformation( poSource, poTarget, OGRCoordinateTransformationOptions()); } /** * Create transformation object. * * This is the same as the C function OCTNewCoordinateTransformationEx(). * * Input spatial reference system objects are assigned * by copy (calling clone() method) and no ownership transfer occurs. * * The delete operator, or OCTDestroyCoordinateTransformation() should * be used to destroy transformation objects. * * This will honour the axis order advertized by the source and target SRS, * as well as their "data axis to SRS axis mapping". * To have a behaviour similar to GDAL &lt; 3.0, the OGR_CT_FORCE_TRADITIONAL_GIS_ORDER * configuration option can be set to YES. * * The source SRS and target SRS should generally not be NULL. This is only * allowed if a custom coordinate operation is set through the hOptions argument. * * Starting with GDAL 3.0.3, the OGR_CT_OP_SELECTION configuration option can be * set to PROJ (default if PROJ >= 6.3), BEST_ACCURACY or FIRST_MATCHING to decide * of the strategy to select the operation to use among candidates, whose area of * use is compatible with the points to transform. It is only taken into account * if no user defined coordinate transformation pipeline has been specified. * <ul> * <li>PROJ means the default behaviour used by PROJ proj_create_crs_to_crs(). * In particular the operation to use among several initial candidates is * evaluated for each point to transform.</li> * <li>BEST_ACCURACY means the operation whose accuracy is best. It should be * close to PROJ behaviour, except that the operation to select is decided * for the average point of the coordinates passed in a single Transform() call.</li> * <li>FIRST_MATCHING is the operation ordered first in the list of candidates: * it will not necessarily have the best accuracy, but generally a larger area of * use. It is evaluated for the average point of the coordinates passed in a * single Transform() call. This was the default behaviour for GDAL 3.0.0 to * 3.0.2</li> * </ul> * * If options contains a user defined coordinate transformation pipeline, it * will be unconditionally used. * If options has an area of interest defined, it will be used to research the * best fitting coordinate transformation (which will be used for all coordinate * transformations, even if they don't fall into the declared area of interest) * If no options are set, then a list of candidate coordinate operations will be * reseached, and at each call to Transform(), the best of those candidate * regarding the centroid of the coordinate set will be dynamically selected. * * @param poSource source spatial reference system. * @param poTarget target spatial reference system. * @param options Coordinate transformation options. * @return NULL on failure or a ready to use transformation object. * @since GDAL 3.0 */ OGRCoordinateTransformation* OGRCreateCoordinateTransformation( const OGRSpatialReference *poSource, const OGRSpatialReference *poTarget, const OGRCoordinateTransformationOptions& options ) { OGRProjCT *poCT = new OGRProjCT(); if( !poCT->Initialize( poSource, poTarget, options ) ) { delete poCT; return nullptr; } return poCT; } /************************************************************************/ /* OCTNewCoordinateTransformation() */ /************************************************************************/ /** * Create transformation object. * * This is the same as the C++ function OGRCreateCoordinateTransformation(const OGRSpatialReference *, const OGRSpatialReference *) * * Input spatial reference system objects are assigned * by copy (calling clone() method) and no ownership transfer occurs. * * OCTDestroyCoordinateTransformation() should * be used to destroy transformation objects. * * This will honour the axis order advertized by the source and target SRS, * as well as their "data axis to SRS axis mapping". * To have a behaviour similar to GDAL &lt; 3.0, the OGR_CT_FORCE_TRADITIONAL_GIS_ORDER * configuration option can be set to YES. * * @param hSourceSRS source spatial reference system. * @param hTargetSRS target spatial reference system. * @return NULL on failure or a ready to use transformation object. */ OGRCoordinateTransformationH CPL_STDCALL OCTNewCoordinateTransformation( OGRSpatialReferenceH hSourceSRS, OGRSpatialReferenceH hTargetSRS ) { return reinterpret_cast<OGRCoordinateTransformationH>( OGRCreateCoordinateTransformation( reinterpret_cast<OGRSpatialReference *>(hSourceSRS), reinterpret_cast<OGRSpatialReference *>(hTargetSRS))); } /************************************************************************/ /* OCTNewCoordinateTransformationEx() */ /************************************************************************/ /** * Create transformation object. * * This is the same as the C++ function OGRCreateCoordinateTransformation(const OGRSpatialReference *, const OGRSpatialReference *, const OGRCoordinateTransformationOptions& ) * * Input spatial reference system objects are assigned * by copy (calling clone() method) and no ownership transfer occurs. * * OCTDestroyCoordinateTransformation() should * be used to destroy transformation objects. * * The source SRS and target SRS should generally not be NULL. This is only * allowed if a custom coordinate operation is set through the hOptions argument. * * This will honour the axis order advertized by the source and target SRS, * as well as their "data axis to SRS axis mapping". * To have a behaviour similar to GDAL &lt; 3.0, the OGR_CT_FORCE_TRADITIONAL_GIS_ORDER * configuration option can be set to YES. * * If options contains a user defined coordinate transformation pipeline, it * will be unconditionally used. * If options has an area of interest defined, it will be used to research the * best fitting coordinate transformation (which will be used for all coordinate * transformations, even if they don't fall into the declared area of interest) * If no options are set, then a list of candidate coordinate operations will be * reseached, and at each call to Transform(), the best of those candidate * regarding the centroid of the coordinate set will be dynamically selected. * * @param hSourceSRS source spatial reference system. * @param hTargetSRS target spatial reference system. * @param hOptions Coordinate transformation options. * @return NULL on failure or a ready to use transformation object. * @since GDAL 3.0 */ OGRCoordinateTransformationH OCTNewCoordinateTransformationEx( OGRSpatialReferenceH hSourceSRS, OGRSpatialReferenceH hTargetSRS, OGRCoordinateTransformationOptionsH hOptions) { OGRCoordinateTransformationOptions defaultOptions; return reinterpret_cast<OGRCoordinateTransformationH>( OGRCreateCoordinateTransformation( reinterpret_cast<OGRSpatialReference *>(hSourceSRS), reinterpret_cast<OGRSpatialReference *>(hTargetSRS), hOptions ? *hOptions : defaultOptions)); } /************************************************************************/ /* OGRProjCT() */ /************************************************************************/ //! @cond Doxygen_Suppress OGRProjCT::OGRProjCT() { } /************************************************************************/ /* ~OGRProjCT() */ /************************************************************************/ OGRProjCT::~OGRProjCT() { if( poSRSSource != nullptr ) { poSRSSource->Release(); } if( poSRSTarget != nullptr ) { poSRSTarget->Release(); } if( m_pj ) { proj_assign_context(m_pj, OSRGetProjTLSContext()); proj_destroy(m_pj); } CPLFree(padfOriX); CPLFree(padfOriY); CPLFree(padfOriZ); CPLFree(padfOriT); CPLFree(padfTargetX); CPLFree(padfTargetY); CPLFree(padfTargetZ); CPLFree(padfTargetT); } /************************************************************************/ /* Initialize() */ /************************************************************************/ int OGRProjCT::Initialize( const OGRSpatialReference * poSourceIn, const OGRSpatialReference * poTargetIn, const OGRCoordinateTransformationOptions& options ) { m_options = options; if( poSourceIn == nullptr || poTargetIn == nullptr ) { if( options.d->osCoordOperation.empty() ) { CPLError(CE_Failure, CPLE_AppDefined, "OGRProjCT::Initialize(): if source and/or target CRS " "are null, a coordinate operation must be specified"); return FALSE; } } if( poSourceIn ) poSRSSource = poSourceIn->Clone(); if( poTargetIn ) poSRSTarget = poTargetIn->Clone(); // To easy quick&dirty compatibility with GDAL < 3.0 if( CPLTestBool(CPLGetConfigOption("OGR_CT_FORCE_TRADITIONAL_GIS_ORDER", "NO")) ) { if( poSRSSource ) poSRSSource->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); if( poSRSTarget ) poSRSTarget->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER); } if( poSRSSource ) bSourceLatLong = CPL_TO_BOOL(poSRSSource->IsGeographic()); if( poSRSTarget ) bTargetLatLong = CPL_TO_BOOL(poSRSTarget->IsGeographic()); /* -------------------------------------------------------------------- */ /* Setup source and target translations to radians for lat/long */ /* systems. */ /* -------------------------------------------------------------------- */ bSourceWrap = false; dfSourceWrapLong = 0.0; bTargetWrap = false; dfTargetWrapLong = 0.0; /* -------------------------------------------------------------------- */ /* Preliminary logic to setup wrapping. */ /* -------------------------------------------------------------------- */ if( CPLGetConfigOption( "CENTER_LONG", nullptr ) != nullptr ) { bSourceWrap = true; bTargetWrap = true; // coverity[tainted_data] dfSourceWrapLong = dfTargetWrapLong = CPLAtof(CPLGetConfigOption( "CENTER_LONG", "" )); CPLDebug( "OGRCT", "Wrap at %g.", dfSourceWrapLong ); } const char *pszCENTER_LONG; { CPLErrorStateBackuper oErrorStateBackuper; CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler); pszCENTER_LONG = poSRSSource ? poSRSSource->GetExtension( "GEOGCS", "CENTER_LONG" ) : nullptr; } if( pszCENTER_LONG != nullptr ) { dfSourceWrapLong = CPLAtof(pszCENTER_LONG); bSourceWrap = true; CPLDebug( "OGRCT", "Wrap source at %g.", dfSourceWrapLong ); } else if( bSourceLatLong && options.d->bHasSourceCenterLong) { dfSourceWrapLong = options.d->dfSourceCenterLong; bSourceWrap = true; CPLDebug( "OGRCT", "Wrap source at %g.", dfSourceWrapLong ); } { CPLErrorStateBackuper oErrorStateBackuper; CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler); pszCENTER_LONG = poSRSTarget ? poSRSTarget->GetExtension( "GEOGCS", "CENTER_LONG" ) : nullptr; } if( pszCENTER_LONG != nullptr ) { dfTargetWrapLong = CPLAtof(pszCENTER_LONG); bTargetWrap = true; CPLDebug( "OGRCT", "Wrap target at %g.", dfTargetWrapLong ); } else if( bTargetLatLong && options.d->bHasTargetCenterLong) { dfTargetWrapLong = options.d->dfTargetCenterLong; bTargetWrap = true; CPLDebug( "OGRCT", "Wrap target at %g.", dfTargetWrapLong ); } bCheckWithInvertProj = CPLTestBool(CPLGetConfigOption( "CHECK_WITH_INVERT_PROJ", "NO" )); // The threshold is experimental. Works well with the cases of ticket #2305. if( bSourceLatLong ) { // coverity[tainted_data] dfThreshold = CPLAtof(CPLGetConfigOption( "THRESHOLD", ".1" )); } else { // 1 works well for most projections, except for +proj=aeqd that // requires a tolerance of 10000. // coverity[tainted_data] dfThreshold = CPLAtof(CPLGetConfigOption( "THRESHOLD", "10000" )); } // Detect webmercator to WGS84 OGRAxisOrientation orientAxis0, orientAxis1; if( options.d->osCoordOperation.empty() && poSRSSource && poSRSTarget && poSRSSource->IsProjected() && poSRSTarget->IsGeographic() && poSRSTarget->GetAxis(nullptr, 0, &orientAxis0) != nullptr && poSRSTarget->GetAxis(nullptr, 1, &orientAxis1) != nullptr && ((orientAxis0 == OAO_North && orientAxis1 == OAO_East && poSRSTarget->GetDataAxisToSRSAxisMapping() == std::vector<int>{2,1}) || (orientAxis0 == OAO_East && orientAxis1 == OAO_North && poSRSTarget->GetDataAxisToSRSAxisMapping() == std::vector<int>{1,2})) ) { CPLPushErrorHandler(CPLQuietErrorHandler); char *pszSrcProj4Defn = nullptr; poSRSSource->exportToProj4( &pszSrcProj4Defn ); char *pszDstProj4Defn = nullptr; poSRSTarget->exportToProj4( &pszDstProj4Defn ); CPLPopErrorHandler(); if( pszSrcProj4Defn && pszDstProj4Defn ) { if( pszSrcProj4Defn[0] != '\0' && pszSrcProj4Defn[strlen(pszSrcProj4Defn)-1] == ' ' ) pszSrcProj4Defn[strlen(pszSrcProj4Defn)-1] = 0; if( pszDstProj4Defn[0] != '\0' && pszDstProj4Defn[strlen(pszDstProj4Defn)-1] == ' ' ) pszDstProj4Defn[strlen(pszDstProj4Defn)-1] = 0; char* pszNeedle = strstr(pszSrcProj4Defn, " "); if( pszNeedle ) memmove(pszNeedle, pszNeedle + 1, strlen(pszNeedle + 1)+1); pszNeedle = strstr(pszDstProj4Defn, " "); if( pszNeedle ) memmove(pszNeedle, pszNeedle + 1, strlen(pszNeedle + 1)+1); if( (strstr(pszDstProj4Defn, "+datum=WGS84") != nullptr || strstr(pszDstProj4Defn, "+ellps=WGS84 +towgs84=0,0,0,0,0,0,0 ") != nullptr) && strstr(pszSrcProj4Defn, "+nadgrids=@null ") != nullptr && strstr(pszSrcProj4Defn, "+towgs84") == nullptr ) { char* pszDst = strstr(pszDstProj4Defn, "+towgs84=0,0,0,0,0,0,0 "); if( pszDst != nullptr) { char* pszSrc = pszDst + strlen("+towgs84=0,0,0,0,0,0,0 "); memmove(pszDst, pszSrc, strlen(pszSrc)+1); } else { memcpy(strstr(pszDstProj4Defn, "+datum=WGS84"), "+ellps", 6); } pszDst = strstr(pszSrcProj4Defn, "+nadgrids=@null "); char* pszSrc = pszDst + strlen("+nadgrids=@null "); memmove(pszDst, pszSrc, strlen(pszSrc)+1); pszDst = strstr(pszSrcProj4Defn, "+wktext "); if( pszDst ) { pszSrc = pszDst + strlen("+wktext "); memmove(pszDst, pszSrc, strlen(pszSrc)+1); } bWebMercatorToWGS84LongLat = strcmp(pszDstProj4Defn, "+proj=longlat +ellps=WGS84 +no_defs") == 0 && (strcmp(pszSrcProj4Defn, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 " "+x_0=0.0 +y_0=0 +k=1.0 +units=m +no_defs") == 0 || strcmp(pszSrcProj4Defn, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 " "+x_0=0 +y_0=0 +k=1 +units=m +no_defs") == 0); } } CPLFree(pszSrcProj4Defn); CPLFree(pszDstProj4Defn); } const char* pszCTOpSelection = CPLGetConfigOption("OGR_CT_OP_SELECTION", nullptr); if( pszCTOpSelection ) { if( EQUAL(pszCTOpSelection, "PROJ") ) m_eStrategy = Strategy::PROJ; else if( EQUAL(pszCTOpSelection, "BEST_ACCURACY") ) m_eStrategy = Strategy::BEST_ACCURACY; else if( EQUAL(pszCTOpSelection, "FIRST_MATCHING") ) m_eStrategy = Strategy::FIRST_MATCHING; else CPLError(CE_Warning, CPLE_NotSupported, "OGR_CT_OP_SELECTION=%s not supported", pszCTOpSelection); } if( m_eStrategy == Strategy::PROJ ) { const char* pszUseApproxTMERC = CPLGetConfigOption("OSR_USE_APPROX_TMERC", nullptr); if( pszUseApproxTMERC && CPLTestBool(pszUseApproxTMERC) ) { CPLDebug("OSRCT", "Using OGR_CT_OP_SELECTION=BEST_ACCURACY as OSR_USE_APPROX_TMERC is set"); m_eStrategy = Strategy::BEST_ACCURACY; } } if( !options.d->osCoordOperation.empty() ) { auto ctx = OSRGetProjTLSContext(); m_pj = proj_create(ctx, options.d->osCoordOperation); if( !m_pj ) { CPLError( CE_Failure, CPLE_NotSupported, "Cannot instantiate pipeline %s", options.d->osCoordOperation.c_str() ); return FALSE; } m_bReversePj = options.d->bReverseCO; #ifdef DEBUG auto info = proj_pj_info(m_pj); CPLDebug("OGRCT", "%s %s(user set)", info.definition, m_bReversePj ? "(reversed) " : ""); #endif } else if( !bWebMercatorToWGS84LongLat && poSRSSource && poSRSTarget ) { const auto CanUseAuthorityDef = [](const OGRSpatialReference* poSRS1, OGRSpatialReference* poSRSFromAuth, const char* pszAuth) { if( EQUAL(pszAuth, "EPSG") && CPLTestBool(CPLGetConfigOption("OSR_CT_USE_DEFAULT_EPSG_TOWGS84", "NO")) ) { // We don't want by default to honour 'default' TOWGS84 terms that come with the EPSG code // because there might be a better transformation from that // Typical case if EPSG:31468 "DHDN / 3-degree Gauss-Kruger zone 4" // where the DHDN->TOWGS84 transformation can use the BETA2007.gsb grid // instead of TOWGS84[598.1,73.7,418.2,0.202,0.045,-2.455,6.7] // But if the user really wants it, it can set the // OSR_CT_USE_DEFAULT_EPSG_TOWGS84 configuration option to YES double adfTOWGS84_1[7]; double adfTOWGS84_2[7]; poSRSFromAuth->AddGuessedTOWGS84(); if( poSRS1->GetTOWGS84(adfTOWGS84_1) == OGRERR_NONE && poSRSFromAuth->GetTOWGS84(adfTOWGS84_2) == OGRERR_NONE && memcmp(adfTOWGS84_1, adfTOWGS84_2, sizeof(adfTOWGS84_1)) == 0 ) { return false; } } return true; }; const auto exportSRSToText = [&CanUseAuthorityDef](const OGRSpatialReference* poSRS) { char* pszText = nullptr; // If we have a AUTH:CODE attached, use it to retrieve the full // definition in case a trip to WKT1 has lost the area of use. const char* pszAuth = poSRS->GetAuthorityName(nullptr); const char* pszCode = poSRS->GetAuthorityCode(nullptr); if( pszAuth && pszCode ) { CPLString osAuthCode(pszAuth); osAuthCode += ':'; osAuthCode += pszCode; OGRSpatialReference oTmpSRS; oTmpSRS.SetFromUserInput(osAuthCode); oTmpSRS.SetDataAxisToSRSAxisMapping(poSRS->GetDataAxisToSRSAxisMapping()); if( oTmpSRS.IsSame(poSRS) ) { if( CanUseAuthorityDef(poSRS, &oTmpSRS, pszAuth) ) { pszText = CPLStrdup(osAuthCode); } } } if( pszText == nullptr ) { CPLErrorStateBackuper oErrorStateBackuper; CPLErrorHandlerPusher oErrorHandler(CPLQuietErrorHandler); const char* const apszOptionsWKT2_2018[] = { "FORMAT=WKT2_2018", nullptr }; // If there's a PROJ4 EXTENSION node in WKT1, then use // it. For example when dealing with "+proj=longlat +lon_wrap=180" if( poSRS->GetExtension(nullptr, "PROJ4", nullptr) ) { poSRS->exportToProj4(&pszText); if (strstr(pszText, " +type=crs") == nullptr ) { auto tmpText = std::string(pszText) + " +type=crs"; CPLFree(pszText); pszText = CPLStrdup(tmpText.c_str()); } } else poSRS->exportToWkt(&pszText, apszOptionsWKT2_2018); } return pszText; }; char* pszSrcSRS = exportSRSToText(poSRSSource); char* pszTargetSRS = exportSRSToText(poSRSTarget); #ifdef DEBUG CPLDebug("OGR_CT", "Source CRS: '%s'", pszSrcSRS); CPLDebug("OGR_CT", "Target CRS: '%s'", pszTargetSRS); #endif if( m_eStrategy == Strategy::PROJ ) { PJ_AREA* area = nullptr; if( options.d->bHasAreaOfInterest ) { area = proj_area_create(); proj_area_set_bbox(area, options.d->dfWestLongitudeDeg, options.d->dfSouthLatitudeDeg, options.d->dfEastLongitudeDeg, options.d->dfNorthLatitudeDeg); } auto ctx = OSRGetProjTLSContext(); m_pj = proj_create_crs_to_crs(ctx, pszSrcSRS, pszTargetSRS, area); if( area ) proj_area_destroy(area); if( m_pj == nullptr ) { CPLError( CE_Failure, CPLE_NotSupported, "Cannot find coordinate operations from `%s' to `%s'", pszSrcSRS, pszTargetSRS ); CPLFree( pszSrcSRS ); CPLFree( pszTargetSRS ); return FALSE; } } else if( !ListCoordinateOperations(pszSrcSRS, pszTargetSRS, options) ) { CPLError( CE_Failure, CPLE_NotSupported, "Cannot find coordinate operations from `%s' to `%s'", pszSrcSRS, pszTargetSRS ); CPLFree( pszSrcSRS ); CPLFree( pszTargetSRS ); return FALSE; } CPLFree(pszSrcSRS); CPLFree(pszTargetSRS); } if( options.d->osCoordOperation.empty() && poSRSSource && poSRSTarget ) { // Determine if we can skip the transformation completely. bNoTransform = !bSourceWrap && !bTargetWrap && CPL_TO_BOOL(poSRSSource->IsSame(poSRSTarget)); } return TRUE; } /************************************************************************/ /* op_to_pj() */ /************************************************************************/ static PJ* op_to_pj(PJ_CONTEXT* ctx, PJ* op, CPLString* osOutProjString = nullptr ) { // OSR_USE_ETMERC is here just for legacy bool bForceApproxTMerc = false; const char* pszUseETMERC = CPLGetConfigOption("OSR_USE_ETMERC", nullptr); if( pszUseETMERC && pszUseETMERC[0] ) { static bool bHasWarned = false; if( !bHasWarned ) { CPLError(CE_Warning, CPLE_AppDefined, "OSR_USE_ETMERC is a legacy configuration option, which " "now has only effect when set to NO (YES is the default). " "Use OSR_USE_APPROX_TMERC=YES instead"); bHasWarned = true; } bForceApproxTMerc = !CPLTestBool(pszUseETMERC); } else { const char* pszUseApproxTMERC = CPLGetConfigOption("OSR_USE_APPROX_TMERC", nullptr); if( pszUseApproxTMERC && pszUseApproxTMERC[0] ) { bForceApproxTMerc = CPLTestBool(pszUseApproxTMERC); } } const char* options[] = { bForceApproxTMerc ? "USE_APPROX_TMERC=YES" : nullptr, nullptr }; auto proj_string = proj_as_proj_string(ctx, op, PJ_PROJ_5, options); if( !proj_string) { return nullptr; } if( osOutProjString ) *osOutProjString = proj_string; if( proj_string[0] == '\0' ) { /* Null transform ? */ return proj_create(ctx, "proj=affine"); } else { return proj_create(ctx, proj_string); } } /************************************************************************/ /* ListCoordinateOperations() */ /************************************************************************/ bool OGRProjCT::ListCoordinateOperations(const char* pszSrcSRS, const char* pszTargetSRS, const OGRCoordinateTransformationOptions& options ) { auto ctx = OSRGetProjTLSContext(); auto src = proj_create(ctx, pszSrcSRS); if( !src ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot instantiate source_crs"); return false; } auto dst = proj_create(ctx, pszTargetSRS); if( !dst ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot instantiate target_crs"); proj_destroy(src); return false; } auto operation_ctx = proj_create_operation_factory_context(ctx, nullptr); if( !operation_ctx ) { proj_destroy(src); proj_destroy(dst); return false; } proj_operation_factory_context_set_spatial_criterion( ctx, operation_ctx, PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION); proj_operation_factory_context_set_grid_availability_use( ctx, operation_ctx, PROJ_GRID_AVAILABILITY_DISCARD_OPERATION_IF_MISSING_GRID); if( options.d->bHasAreaOfInterest ) { proj_operation_factory_context_set_area_of_interest( ctx, operation_ctx, options.d->dfWestLongitudeDeg, options.d->dfSouthLatitudeDeg, options.d->dfEastLongitudeDeg, options.d->dfNorthLatitudeDeg); } auto op_list = proj_create_operations(ctx, src, dst, operation_ctx); if( !op_list ) { proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); return false; } auto op_count = proj_list_get_count(op_list); if( op_count == 0 ) { proj_list_destroy(op_list); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); CPLDebug("OGRCT", "No operation found matching criteria"); return false; } if( op_count == 1 || options.d->bHasAreaOfInterest || proj_get_type(src) == PJ_TYPE_GEOCENTRIC_CRS || proj_get_type(dst) == PJ_TYPE_GEOCENTRIC_CRS ) { auto op = proj_list_get(ctx, op_list, 0); CPLAssert(op); m_pj = op_to_pj(ctx, op); CPLString osName; auto name = proj_get_name(op); if( name ) osName = name; proj_destroy(op); proj_list_destroy(op_list); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); if( !m_pj ) return false; #ifdef DEBUG auto info = proj_pj_info(m_pj); CPLDebug("OGRCT", "%s (%s)", info.definition, osName.c_str()); #endif return true; } // Create a geographic 2D long-lat degrees CRS that is related to the // source CRS auto geodetic_crs = proj_crs_get_geodetic_crs(ctx, src); if( !geodetic_crs ) { proj_list_destroy(op_list); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); CPLDebug("OGRCT", "Cannot find geodetic CRS matching source CRS"); return false; } auto geodetic_crs_type = proj_get_type(geodetic_crs); if( geodetic_crs_type == PJ_TYPE_GEOCENTRIC_CRS || geodetic_crs_type == PJ_TYPE_GEOGRAPHIC_2D_CRS || geodetic_crs_type == PJ_TYPE_GEOGRAPHIC_3D_CRS ) { auto datum = proj_crs_get_datum(ctx, geodetic_crs); if( datum ) { auto cs = proj_create_ellipsoidal_2D_cs( ctx, PJ_ELLPS2D_LONGITUDE_LATITUDE, nullptr, 0); auto temp = proj_create_geographic_crs_from_datum( ctx,"unnamed", datum, cs); proj_destroy(datum); proj_destroy(cs); proj_destroy(geodetic_crs); geodetic_crs = temp; geodetic_crs_type = proj_get_type(geodetic_crs); } } if( geodetic_crs_type != PJ_TYPE_GEOGRAPHIC_2D_CRS ) { // Shouldn't happen proj_list_destroy(op_list); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); proj_destroy(geodetic_crs); CPLDebug("OGRCT", "Cannot find geographic CRS matching source CRS"); return false; } // Create the transformation from this geographic 2D CRS to the source CRS auto op_list_to_geodetic = proj_create_operations( ctx, geodetic_crs, src, operation_ctx); proj_destroy(geodetic_crs); if( op_list_to_geodetic == nullptr || proj_list_get_count(op_list_to_geodetic) == 0 ) { CPLDebug("OGRCT", "Cannot compute transformation from geographic CRS to source CRS"); proj_list_destroy(op_list); proj_list_destroy(op_list_to_geodetic); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); return false; } auto opGeogToSrc = proj_list_get(ctx, op_list_to_geodetic, 0); CPLAssert(opGeogToSrc); proj_list_destroy(op_list_to_geodetic); auto pjGeogToSrc = op_to_pj(ctx, opGeogToSrc); proj_destroy(opGeogToSrc); if( !pjGeogToSrc ) { proj_list_destroy(op_list); proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); return false; } const auto addTransformation = [=](PJ* op, double west_lon, double south_lat, double east_lon, double north_lat) { double minx = -std::numeric_limits<double>::max(); double miny = -std::numeric_limits<double>::max(); double maxx = std::numeric_limits<double>::max(); double maxy = std::numeric_limits<double>::max(); if( !(west_lon == -180.0 && east_lon == 180.0 && south_lat == -90.0 && north_lat == 90.0) ) { minx = -minx; miny = -miny; maxx = -maxx; maxy = -maxy; double x[21 * 4], y[21 * 4]; for( int j = 0; j <= 20; j++ ) { x[j] = west_lon + j * (east_lon - west_lon) / 20; y[j] = south_lat; x[21+j] = west_lon + j * (east_lon - west_lon) / 20; y[21+j] = north_lat; x[21*2+j] = west_lon; y[21*2+j] = south_lat + j * (north_lat - south_lat) / 20; x[21*3+j] = east_lon; y[21*3+j] = south_lat + j * (north_lat - south_lat) / 20; } proj_trans_generic ( pjGeogToSrc, PJ_FWD, x, sizeof(double), 21 * 4, y, sizeof(double), 21 * 4, nullptr, 0, 0, nullptr, 0, 0); for( int j = 0; j < 21 * 4; j++ ) { if( x[j] != HUGE_VAL && y[j] != HUGE_VAL ) { minx = std::min(minx, x[j]); miny = std::min(miny, y[j]); maxx = std::max(maxx, x[j]); maxy = std::max(maxy, y[j]); } } } if( minx <= maxx ) { CPLString osProjString; const double accuracy = proj_coordoperation_get_accuracy(ctx, op); auto pj = op_to_pj(ctx, op, &osProjString); CPLString osName; auto name = proj_get_name(op); if( name ) osName = name; proj_destroy(op); op = nullptr; if( pj ) { m_oTransformations.emplace_back( minx, miny, maxx, maxy, pj, osName, osProjString, accuracy); } } return op; }; // Iterate over source->target candidate transformations and reproject // their long-lat bounding box into the source CRS. bool foundWorldTransformation = false; for( int i = 0; i < op_count; i++ ) { auto op = proj_list_get(ctx, op_list, i); CPLAssert(op); double west_lon = 0.0; double south_lat = 0.0; double east_lon = 0.0; double north_lat = 0.0; if( proj_get_area_of_use(ctx, op, &west_lon, &south_lat, &east_lon, &north_lat, nullptr) ) { if( west_lon <= east_lon ) { if( west_lon == -180 && east_lon == 180 && south_lat == -90 && north_lat == 90 ) { foundWorldTransformation = true; } op = addTransformation(op, west_lon, south_lat, east_lon, north_lat); } else { auto op_clone = proj_clone(ctx, op); op = addTransformation(op, west_lon, south_lat, 180, north_lat); op_clone = addTransformation(op_clone, -180, south_lat, east_lon, north_lat); proj_destroy(op_clone); } } proj_destroy(op); } proj_list_destroy(op_list); // Sometimes the user will operate even outside the area of use of the // source and target CRS, so if no global transformation has been returned // previously, trigger the computation of one. if( !foundWorldTransformation ) { proj_operation_factory_context_set_area_of_interest( ctx, operation_ctx, -180, -90, 180, 90); proj_operation_factory_context_set_spatial_criterion( ctx, operation_ctx, PROJ_SPATIAL_CRITERION_STRICT_CONTAINMENT); op_list = proj_create_operations(ctx, src, dst, operation_ctx); if( op_list ) { op_count = proj_list_get_count(op_list); for( int i = 0; i < op_count; i++ ) { auto op = proj_list_get(ctx, op_list, i); CPLAssert(op); double west_lon = 0.0; double south_lat = 0.0; double east_lon = 0.0; double north_lat = 0.0; if( proj_get_area_of_use(ctx, op, &west_lon, &south_lat, &east_lon, &north_lat, nullptr) && west_lon == -180 && east_lon == 180 && south_lat == -90 && north_lat == 90 ) { op = addTransformation(op, west_lon, south_lat, east_lon, north_lat); } proj_destroy(op); } } proj_list_destroy(op_list); } proj_operation_factory_context_destroy(operation_ctx); proj_destroy(src); proj_destroy(dst); proj_destroy(pjGeogToSrc); return !m_oTransformations.empty(); } /************************************************************************/ /* GetSourceCS() */ /************************************************************************/ OGRSpatialReference *OGRProjCT::GetSourceCS() { return poSRSSource; } /************************************************************************/ /* GetTargetCS() */ /************************************************************************/ OGRSpatialReference *OGRProjCT::GetTargetCS() { return poSRSTarget; } /************************************************************************/ /* Transform() */ /************************************************************************/ int OGRCoordinateTransformation::Transform( int nCount, double *x, double *y, double *z, int *pabSuccessIn ) { int *pabSuccess = pabSuccessIn ? pabSuccessIn : static_cast<int *>(CPLMalloc(sizeof(int) * nCount)); bool bOverallSuccess = CPL_TO_BOOL(Transform( nCount, x, y, z, nullptr, pabSuccess )); for( int i = 0; i < nCount; i++ ) { if( !pabSuccess[i] ) { bOverallSuccess = false; break; } } if( pabSuccess != pabSuccessIn ) CPLFree( pabSuccess ); return bOverallSuccess; } /************************************************************************/ /* Transform() */ /************************************************************************/ int OGRProjCT::Transform( int nCount, double *x, double *y, double *z, double *t, int *pabSuccess ) { if( nCount == 0 ) return TRUE; // Prevent any coordinate modification when possible if ( bNoTransform ) { if( pabSuccess ) { for( int i = 0; i < nCount; i++ ) { pabSuccess[i] = TRUE; } } return TRUE; } #ifdef DEBUG_VERBOSE bool bDebugCT = CPLTestBool(CPLGetConfigOption("OGR_CT_DEBUG", "NO")); if( bDebugCT ) { CPLDebug("OGRCT", "count = %d", nCount); for( int i = 0; i < nCount; ++i ) { CPLDebug("OGRCT", " x[%d] = %.16g y[%d] = %.16g", i, x[i], i, y[i]); } } #endif /* -------------------------------------------------------------------- */ /* Apply data axis to source CRS mapping. */ /* -------------------------------------------------------------------- */ if( poSRSSource ) { const auto& mapping = poSRSSource->GetDataAxisToSRSAxisMapping(); if( mapping.size() >= 2 && (mapping[0] != 1 || mapping[1] != 2) ) { for( int i = 0; i < nCount; i++ ) { double newX = (mapping[0] == 1) ? x[i] : (mapping[0] == -1) ? -x[i] : (mapping[0] == 2) ? y[i] : -y[i]; double newY = (mapping[1] == 2) ? y[i] : (mapping[1] == -2) ? -y[i] : (mapping[1] == 1) ? x[i] : -x[i]; x[i] = newX; y[i] = newY; if( z && mapping.size() >= 3 && mapping[2] == -3) z[i] = -z[i]; } } } /* -------------------------------------------------------------------- */ /* Potentially do longitude wrapping. */ /* -------------------------------------------------------------------- */ if( bSourceLatLong && bSourceWrap ) { OGRAxisOrientation orientation; assert( poSRSSource ); poSRSSource->GetAxis(nullptr, 0, &orientation); if( orientation == OAO_East ) { for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL && y[i] != HUGE_VAL ) { if( x[i] < dfSourceWrapLong - 180.0 ) x[i] += 360.0; else if( x[i] > dfSourceWrapLong + 180 ) x[i] -= 360.0; } } } else { for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL && y[i] != HUGE_VAL ) { if( y[i] < dfSourceWrapLong - 180.0 ) y[i] += 360.0; else if( y[i] > dfSourceWrapLong + 180 ) y[i] -= 360.0; } } } } /* -------------------------------------------------------------------- */ /* Optimized transform from WebMercator to WGS84 */ /* -------------------------------------------------------------------- */ bool bTransformDone = false; if( bWebMercatorToWGS84LongLat ) { constexpr double REVERSE_SPHERE_RADIUS = 1.0 / 6378137.0; if( poSRSSource ) { OGRAxisOrientation orientation; poSRSSource->GetAxis(nullptr, 0, &orientation); if( orientation != OAO_East ) { for( int i = 0; i < nCount; i++ ) { std::swap(x[i], y[i]); } } } double y0 = y[0]; for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL ) { x[i] = x[i] * REVERSE_SPHERE_RADIUS; if( x[i] > M_PI ) { if( x[i] < M_PI+1e-14 ) { x[i] = M_PI; } else if( bCheckWithInvertProj ) { x[i] = HUGE_VAL; y[i] = HUGE_VAL; y0 = HUGE_VAL; continue; } else { do { x[i] -= 2 * M_PI; } while( x[i] > M_PI ); } } else if( x[i] < -M_PI ) { if( x[i] > -M_PI-1e-14 ) { x[i] = -M_PI; } else if( bCheckWithInvertProj ) { x[i] = HUGE_VAL; y[i] = HUGE_VAL; y0 = HUGE_VAL; continue; } else { do { x[i] += 2 * M_PI; } while( x[i] < -M_PI ); } } constexpr double RAD_TO_DEG = 57.29577951308232; x[i] *= RAD_TO_DEG; // Optimization for the case where we are provided a whole line // of same northing. if( i > 0 && y[i] == y0 ) y[i] = y[0]; else { y[i] = M_PI / 2.0 - 2.0 * atan(exp(-y[i] * REVERSE_SPHERE_RADIUS)); y[i] *= RAD_TO_DEG; } } } if( poSRSTarget ) { OGRAxisOrientation orientation; poSRSTarget->GetAxis(nullptr, 0, &orientation); if( orientation != OAO_East ) { for( int i = 0; i < nCount; i++ ) { std::swap(x[i], y[i]); } } } bTransformDone = true; } /* -------------------------------------------------------------------- */ /* Select dynamically the best transformation for the data, if */ /* needed. */ /* -------------------------------------------------------------------- */ auto ctx = OSRGetProjTLSContext(); auto pj = m_pj; if( !bTransformDone && !pj ) { double avgX = 0.0; double avgY = 0.0; int nCountValid = 0; for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL && y[i] != HUGE_VAL ) { avgX += x[i]; avgY += y[i]; nCountValid ++; } } if( nCountValid != 0 ) { avgX /= nCountValid; avgY /= nCountValid; } constexpr int N_MAX_RETRY = 2; int iExcluded[N_MAX_RETRY] = {-1, -1}; const int nOperations = static_cast<int>(m_oTransformations.size()); PJ_COORD coord; coord.xyzt.x = avgX; coord.xyzt.y = avgY; coord.xyzt.z = z ? z[0] : 0; coord.xyzt.t = t ? t[0] : HUGE_VAL; // We may need several attempts. For example the point at // lon=-111.5 lat=45.26 falls into the bounding box of the Canadian // ntv2_0.gsb grid, except that it is not in any of the subgrids, being // in the US. We thus need another retry that will select the conus // grid. for( int iRetry = 0; iRetry <= N_MAX_RETRY; iRetry++ ) { int iBestTransf = -1; // Select transform whose BBOX match our data and has the best accuracy // if m_eStrategy == BEST_ACCURACY. Or just the first BBOX matching one, if // m_eStrategy == FIRST_MATCHING double dfBestAccuracy = std::numeric_limits<double>::infinity(); for( int i = 0; i < nOperations; i++ ) { if( i == iExcluded[0] || i == iExcluded[1] ) { continue; } const auto& transf = m_oTransformations[i]; if( avgX >= transf.minx && avgX <= transf.maxx && avgY >= transf.miny && avgY <= transf.maxy && (iBestTransf < 0 || (transf.accuracy >= 0 && transf.accuracy < dfBestAccuracy)) ) { iBestTransf = i; dfBestAccuracy = transf.accuracy; if( m_eStrategy == Strategy::FIRST_MATCHING ) break; } } if( iBestTransf < 0 ) { break; } const auto& transf = m_oTransformations[iBestTransf]; pj = transf.pj; proj_assign_context( pj, ctx ); if( iBestTransf != m_iCurTransformation ) { CPLDebug("OGRCT", "Selecting transformation %s (%s)", transf.osProjString.c_str(), transf.osName.c_str()); m_iCurTransformation = iBestTransf; } auto res = proj_trans(pj, m_bReversePj ? PJ_INV : PJ_FWD, coord); if( res.xyzt.x != HUGE_VAL ) { break; } pj = nullptr; CPLDebug("OGRCT", "Did not result in valid result. " "Attempting a retry with another operation."); if( iRetry == N_MAX_RETRY ) { break; } iExcluded[iRetry] = iBestTransf; } if( !pj ) { // In case we did not find an operation whose area of use is compatible // with the input coordinate, then goes through again the list, and // use the first operation that does not require grids. for( int i = 0; i < nOperations; i++ ) { const auto& transf = m_oTransformations[i]; if( proj_coordoperation_get_grid_used_count(ctx, transf.pj) == 0 ) { pj = transf.pj; proj_assign_context( pj, ctx ); if( i != m_iCurTransformation ) { CPLDebug("OGRCT", "Selecting transformation %s (%s)", transf.osProjString.c_str(), transf.osName.c_str()); m_iCurTransformation = i; } break; } } } if( !pj ) { if( m_bEmitErrors && ++nErrorCount < 20 ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find transformation for provided coordinates"); } else if( nErrorCount == 20 ) { CPLError( CE_Failure, CPLE_AppDefined, "Reprojection failed, further errors will be " "suppressed on the transform object."); } for( int i = 0; i < nCount; i++ ) { x[i] = HUGE_VAL; y[i] = HUGE_VAL; } if( pabSuccess ) memset( pabSuccess, 0, sizeof(int) * nCount ); return FALSE; } } if( pj ) { proj_assign_context( pj, ctx ); } /* -------------------------------------------------------------------- */ /* Do the transformation (or not...) using PROJ */ /* -------------------------------------------------------------------- */ int err = 0; if( bTransformDone ) { // err = 0; } else if( bCheckWithInvertProj ) { // For some projections, we cannot detect if we are trying to reproject // coordinates outside the validity area of the projection. So let's do // the reverse reprojection and compare with the source coordinates. if( nCount > nMaxCount ) { nMaxCount = nCount; padfOriX = static_cast<double*>( CPLRealloc(padfOriX, sizeof(double) * nCount)); padfOriY = static_cast<double*>( CPLRealloc(padfOriY, sizeof(double)*nCount)); padfOriZ = static_cast<double*>( CPLRealloc(padfOriZ, sizeof(double)*nCount)); padfOriT = static_cast<double*>( CPLRealloc(padfOriT, sizeof(double)*nCount)); padfTargetX = static_cast<double*>( CPLRealloc(padfTargetX, sizeof(double)*nCount)); padfTargetY = static_cast<double*>( CPLRealloc(padfTargetY, sizeof(double)*nCount)); padfTargetZ = static_cast<double*>( CPLRealloc(padfTargetZ, sizeof(double)*nCount)); padfTargetT = static_cast<double*>( CPLRealloc(padfTargetT, sizeof(double)*nCount)); } memcpy(padfOriX, x, sizeof(double) * nCount); memcpy(padfOriY, y, sizeof(double) * nCount); if( z ) { memcpy(padfOriZ, z, sizeof(double)*nCount); } if( t ) { memcpy(padfOriT, t, sizeof(double)*nCount); } size_t nRet = proj_trans_generic (pj, m_bReversePj ? PJ_INV : PJ_FWD, x, sizeof(double), nCount, y, sizeof(double), nCount, z, z ? sizeof(double) : 0, z ? nCount : 0, t, t ? sizeof(double) : 0, t ? nCount : 0); err = ( static_cast<int>(nRet) == nCount ) ? 0 : proj_context_errno(ctx); if( err == 0 ) { memcpy(padfTargetX, x, sizeof(double) * nCount); memcpy(padfTargetY, y, sizeof(double) * nCount); if( z ) { memcpy(padfTargetZ, z, sizeof(double) * nCount); } if( t ) { memcpy(padfTargetT, t, sizeof(double) * nCount); } nRet = proj_trans_generic (pj, m_bReversePj ? PJ_FWD : PJ_INV, padfTargetX, sizeof(double), nCount, padfTargetY, sizeof(double), nCount, z ? padfTargetZ : nullptr, z ? sizeof(double) : 0, z ? nCount : 0, t ? padfTargetT : nullptr, t ? sizeof(double) : 0, t ? nCount : 0); err = ( static_cast<int>(nRet) == nCount ) ? 0 : proj_context_errno(ctx); if( err == 0 ) { for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL && y[i] != HUGE_VAL && (fabs(padfTargetX[i] - padfOriX[i]) > dfThreshold || fabs(padfTargetY[i] - padfOriY[i]) > dfThreshold) ) { x[i] = HUGE_VAL; y[i] = HUGE_VAL; } } } } } else { size_t nRet = proj_trans_generic (pj, m_bReversePj ? PJ_INV : PJ_FWD, x, sizeof(double), nCount, y, sizeof(double), nCount, z, z ? sizeof(double) : 0, z ? nCount : 0, t, t ? sizeof(double) : 0, t ? nCount : 0); err = ( static_cast<int>(nRet) == nCount ) ? 0 : proj_context_errno(ctx); } /* -------------------------------------------------------------------- */ /* Try to report an error through CPL. Get proj error string */ /* if possible. Try to avoid reporting thousands of errors. */ /* Suppress further error reporting on this OGRProjCT if we */ /* have already reported 20 errors. */ /* -------------------------------------------------------------------- */ if( err != 0 ) { if( pabSuccess ) memset( pabSuccess, 0, sizeof(int) * nCount ); if( m_bEmitErrors && ++nErrorCount < 20 ) { const char *pszError = proj_errno_string(err); if( pszError == nullptr ) CPLError( CE_Failure, CPLE_AppDefined, "Reprojection failed, err = %d", err ); else CPLError( CE_Failure, CPLE_AppDefined, "%s", pszError ); } else if( nErrorCount == 20 ) { CPLError( CE_Failure, CPLE_AppDefined, "Reprojection failed, err = %d, further errors will be " "suppressed on the transform object.", err ); } return FALSE; } /* -------------------------------------------------------------------- */ /* Potentially do longitude wrapping. */ /* -------------------------------------------------------------------- */ if( bTargetLatLong && bTargetWrap ) { OGRAxisOrientation orientation; assert( poSRSTarget ); poSRSTarget->GetAxis(nullptr, 0, &orientation); if( orientation == OAO_East ) { for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL && y[i] != HUGE_VAL ) { if( x[i] < dfTargetWrapLong - 180.0 ) x[i] += 360.0; else if( x[i] > dfTargetWrapLong + 180 ) x[i] -= 360.0; } } } else { for( int i = 0; i < nCount; i++ ) { if( x[i] != HUGE_VAL && y[i] != HUGE_VAL ) { if( y[i] < dfTargetWrapLong - 180.0 ) y[i] += 360.0; else if( y[i] > dfTargetWrapLong + 180 ) y[i] -= 360.0; } } } } /* -------------------------------------------------------------------- */ /* Apply data axis to target CRS mapping. */ /* -------------------------------------------------------------------- */ if( poSRSTarget ) { const auto& mapping = poSRSTarget->GetDataAxisToSRSAxisMapping(); if( mapping.size() >= 2 && (mapping[0] != 1 || mapping[1] != 2) ) { for( int i = 0; i < nCount; i++ ) { double newX = (mapping[0] == 1) ? x[i] : (mapping[0] == -1) ? -x[i] : (mapping[0] == 2) ? y[i] : -y[i]; double newY = (mapping[1] == 2) ? y[i] : (mapping[1] == -2) ? -y[i] : (mapping[1] == 1) ? x[i] : -x[i]; x[i] = newX; y[i] = newY; if( z && mapping.size() >= 3 && mapping[2] == -3) z[i] = -z[i]; } } } #ifdef DEBUG_VERBOSE if( bDebugCT ) { CPLDebug("OGRCT", "Out:"); for( int i = 0; i < nCount; ++i ) { CPLDebug("OGRCT", " x[%d] = %.16g y[%d] = %.16g", i, x[i], i, y[i]); } } #endif /* -------------------------------------------------------------------- */ /* Establish error information if pabSuccess provided. */ /* -------------------------------------------------------------------- */ if( pabSuccess ) { for( int i = 0; i < nCount; i++ ) { if( x[i] == HUGE_VAL || y[i] == HUGE_VAL ) pabSuccess[i] = FALSE; else pabSuccess[i] = TRUE; } } return TRUE; } //! @endcond /************************************************************************/ /* OCTTransform() */ /************************************************************************/ /** Transform an array of points * * @param hTransform Transformation object * @param nCount Number of points * @param x Array of nCount x values. * @param y Array of nCount y values. * @param z Array of nCount z values. * @return TRUE or FALSE */ int CPL_STDCALL OCTTransform( OGRCoordinateTransformationH hTransform, int nCount, double *x, double *y, double *z ) { VALIDATE_POINTER1( hTransform, "OCTTransform", FALSE ); return OGRCoordinateTransformation::FromHandle(hTransform)-> Transform( nCount, x, y, z ); } /************************************************************************/ /* OCTTransformEx() */ /************************************************************************/ /** Transform an array of points * * @param hTransform Transformation object * @param nCount Number of points * @param x Array of nCount x values. * @param y Array of nCount y values. * @param z Array of nCount z values. * @param pabSuccess Output array of nCount value that will be set to TRUE/FALSE * @return TRUE or FALSE */ int CPL_STDCALL OCTTransformEx( OGRCoordinateTransformationH hTransform, int nCount, double *x, double *y, double *z, int *pabSuccess ) { VALIDATE_POINTER1( hTransform, "OCTTransformEx", FALSE ); return OGRCoordinateTransformation::FromHandle(hTransform)-> Transform( nCount, x, y, z, pabSuccess ); } /************************************************************************/ /* OCTTransform4D() */ /************************************************************************/ /** Transform an array of points * * @param hTransform Transformation object * @param nCount Number of points * @param x Array of nCount x values. Should not be NULL * @param y Array of nCount y values. Should not be NULL * @param z Array of nCount z values. Might be NULL * @param t Array of nCount time values. Might be NULL * @param pabSuccess Output array of nCount value that will be set to TRUE/FALSE. Might be NULL. * @since GDAL 3.0 * @return TRUE or FALSE */ int OCTTransform4D( OGRCoordinateTransformationH hTransform, int nCount, double *x, double *y, double *z, double *t, int *pabSuccess ) { VALIDATE_POINTER1( hTransform, "OCTTransform4D", FALSE ); return OGRCoordinateTransformation::FromHandle(hTransform)-> Transform( nCount, x, y, z, t, pabSuccess ); }
[ "paul.sandbrook.0@gmail.com" ]
paul.sandbrook.0@gmail.com
eb2e4c9706010be23aba6eb85bdad2137007ca73
1a20961af3b03b46c109b09812143a7ef95c6caa
/ZGame/DX11/hieroglyph3/trunk/Hieroglyph3/Include/RenderParameterDX11.h
eb2b144dde153eb5958a9a015bef8693046e279b
[ "MIT" ]
permissive
JetAr/ZNginx
eff4ae2457b7b28115787d6af7a3098c121e8368
698b40085585d4190cf983f61b803ad23468cdef
refs/heads/master
2021-07-16T13:29:57.438175
2017-10-23T02:05:43
2017-10-23T02:05:43
26,522,265
3
1
null
null
null
null
UTF-8
C++
false
false
3,463
h
//-------------------------------------------------------------------------------- // This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed // under the MIT License, available in the root of this distribution and // at the following URL: // // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) Jason Zink //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // RenderParameterDX11 // //-------------------------------------------------------------------------------- #ifndef RenderParameterDX11_h #define RenderParameterDX11_h //-------------------------------------------------------------------------------- #include "PCH.h" //-------------------------------------------------------------------------------- namespace Glyph3 { enum ParameterType { VECTOR, MATRIX, MATRIX_ARRAY, SHADER_RESOURCE, UNORDERED_ACCESS, CBUFFER, SAMPLER, ENTITY }; class RenderParameterDX11 { public: RenderParameterDX11(); RenderParameterDX11( RenderParameterDX11& copy ); virtual ~RenderParameterDX11(); void SetName( const std::wstring& name ); std::wstring& GetName(); // Each parameter type will implement this method for a simple way // to tell what kind of data it uses. This is important for handling // the parameters in a generic way, but still being able to perform // type checking. virtual const ParameterType GetParameterType() = 0; // Initializing parameter data sets all copies of this resource with // the provided data. Internally this calls the SetParameterData() // method on each thread's data copy, which is specialized by each // concrete subclass. The uninitialize method will reset the parameter // to a default value if the parameter's data matches the passed in data. void InitializeParameterData( void* pData ); //void UnInitializeParameterData( void* pData ); // Setting parameter data does what it sounds like - it takes a pointer // to the data and sets it in the data copy indicated by its thread ID. // Reset will default the data if the current data matches the passed in // data. virtual void SetParameterData( void* pData, unsigned int threadID = 0 ) = 0; //virtual void ResetParameterData( void* pData, unsigned int threadID = 0 ) = 0; // This update function is a convenience function to allow // RenderParameterDX11 subclasses to be referred to by their parent class // and automatically update the parameter stored in the parameter // manager. //virtual void UpdateValue( RenderParameterDX11* pParameter, unsigned int threadID = 0 ) = 0; // The value ID is used to efficiently determine when a parameter's value // has been changed. Each parameter type will increment the value ID // after it has been changed to indicate that it should be re-evaluated. // This is especially important for updating constant buffer contents // only when needed. unsigned int GetValueID( unsigned int threadID = 0 ); protected: std::wstring m_sParameterName; unsigned int m_auiValueID[NUM_THREADS+1]; }; }; //-------------------------------------------------------------------------------- #endif // RenderParameterDX11_h //--------------------------------------------------------------------------------
[ "126.org@gmail.com" ]
126.org@gmail.com
e799ec8230c86e96942a0896e8ac3d29305c8ea7
9f35bea3c50668a4205c04373da95195e20e5427
/chrome/browser/ui/views/profiles/profile_menu_view_base.cc
7c8fe816848e6a7258bc7cb7f8a48b69ce61fb7c
[ "BSD-3-Clause" ]
permissive
foolcodemonkey/chromium
5958fb37df91f92235fa8cf2a6e4a834c88f44aa
c155654fdaeda578cebc218d47f036debd4d634f
refs/heads/master
2023-02-21T00:56:13.446660
2020-01-07T05:12:51
2020-01-07T05:12:51
232,250,603
1
0
BSD-3-Clause
2020-01-07T05:38:18
2020-01-07T05:38:18
null
UTF-8
C++
false
false
37,893
cc
// Copyright 2019 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/browser/ui/views/profiles/profile_menu_view_base.h" #include <algorithm> #include <memory> #include <utility> #include "base/feature_list.h" #include "base/macros.h" #include "base/metrics/histogram_functions.h" #include "build/build_config.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/signin/signin_ui_util.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/hover_button.h" #include "chrome/browser/ui/views/profiles/incognito_menu_view.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/image/canvas_image_source.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/highlight_path_generator.h" #include "ui/views/controls/link.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/separator.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view_class_properties.h" #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/views/profiles/profile_menu_view.h" #include "chrome/browser/ui/views/sync/dice_signin_button_view.h" #endif namespace { ProfileMenuViewBase* g_profile_bubble_ = nullptr; // Helpers -------------------------------------------------------------------- constexpr int kMenuWidth = 288; constexpr int kIconSize = 16; constexpr int kIdentityImageSize = 64; constexpr int kMaxImageSize = kIdentityImageSize; constexpr int kDefaultVerticalMargin = 8; // If the bubble is too large to fit on the screen, it still needs to be at // least this tall to show one row. constexpr int kMinimumScrollableContentHeight = 40; // Spacing between the edge of the user menu and the top/bottom or left/right of // the menu items. constexpr int kMenuEdgeMargin = 16; SkColor GetDefaultIconColor() { return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_DefaultIconColor); } SkColor GetDefaultSeparatorColor() { return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_MenuSeparatorColor); } gfx::ImageSkia SizeImage(const gfx::ImageSkia& image, int size) { return gfx::ImageSkiaOperations::CreateResizedImage( image, skia::ImageOperations::RESIZE_BEST, gfx::Size(size, size)); } gfx::ImageSkia ColorImage(const gfx::ImageSkia& image, SkColor color) { return gfx::ImageSkiaOperations::CreateColorMask(image, color); } class CircleImageSource : public gfx::CanvasImageSource { public: CircleImageSource(int size, SkColor color) : gfx::CanvasImageSource(gfx::Size(size, size)), color_(color) {} ~CircleImageSource() override = default; void Draw(gfx::Canvas* canvas) override; private: SkColor color_; DISALLOW_COPY_AND_ASSIGN(CircleImageSource); }; void CircleImageSource::Draw(gfx::Canvas* canvas) { float radius = size().width() / 2.0f; cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setAntiAlias(true); flags.setColor(color_); canvas->DrawCircle(gfx::PointF(radius, radius), radius, flags); } gfx::ImageSkia CreateCircle(int size, SkColor color = SK_ColorWHITE) { return gfx::CanvasImageSource::MakeImageSkia<CircleImageSource>(size, color); } gfx::ImageSkia CropCircle(const gfx::ImageSkia& image) { DCHECK_EQ(image.width(), image.height()); return gfx::ImageSkiaOperations::CreateMaskedImage( image, CreateCircle(image.width())); } gfx::ImageSkia AddCircularBackground(const gfx::ImageSkia& image, SkColor bg_color, int size) { if (image.isNull()) return gfx::ImageSkia(); return gfx::ImageSkiaOperations::CreateSuperimposedImage( CreateCircle(size, bg_color), image); } std::unique_ptr<views::BoxLayout> CreateBoxLayout( views::BoxLayout::Orientation orientation, views::BoxLayout::CrossAxisAlignment cross_axis_alignment, gfx::Insets insets = gfx::Insets()) { auto layout = std::make_unique<views::BoxLayout>(orientation, insets); layout->set_cross_axis_alignment(cross_axis_alignment); return layout; } std::unique_ptr<views::Button> CreateCircularImageButton( views::ButtonListener* listener, const gfx::ImageSkia& image, const base::string16& text, bool show_border = false) { constexpr int kImageSize = 28; const int kBorderThickness = show_border ? 1 : 0; const SkScalar kButtonRadius = (kImageSize + 2 * kBorderThickness) / 2.0; auto button = std::make_unique<views::ImageButton>(listener); button->SetImage(views::Button::STATE_NORMAL, SizeImage(image, kImageSize)); button->SetTooltipText(text); button->SetInkDropMode(views::Button::InkDropMode::ON); button->SetFocusForPlatform(); button->set_ink_drop_base_color(GetDefaultIconColor()); if (show_border) { button->SetBorder(views::CreateRoundedRectBorder( kBorderThickness, kButtonRadius, GetDefaultSeparatorColor())); } InstallCircleHighlightPathGenerator(button.get()); return button; } } // namespace // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. // MenuItems-------------------------------------------------------------------- ProfileMenuViewBase::MenuItems::MenuItems() : first_item_type(ProfileMenuViewBase::MenuItems::kNone), last_item_type(ProfileMenuViewBase::MenuItems::kNone), different_item_types(false) {} ProfileMenuViewBase::MenuItems::MenuItems(MenuItems&&) = default; ProfileMenuViewBase::MenuItems::~MenuItems() = default; // ProfileMenuViewBase --------------------------------------------------------- // static void ProfileMenuViewBase::ShowBubble( profiles::BubbleViewMode view_mode, signin_metrics::AccessPoint access_point, views::Button* anchor_button, Browser* browser, bool is_source_keyboard) { if (IsShowing()) return; signin_ui_util::RecordProfileMenuViewShown(browser->profile()); ProfileMenuViewBase* bubble; if (view_mode == profiles::BUBBLE_VIEW_MODE_INCOGNITO) { DCHECK(browser->profile()->IsIncognitoProfile()); bubble = new IncognitoMenuView(anchor_button, browser); } else { DCHECK_EQ(profiles::BUBBLE_VIEW_MODE_PROFILE_CHOOSER, view_mode); #if !defined(OS_CHROMEOS) bubble = new ProfileMenuView(anchor_button, browser, access_point); #else NOTREACHED(); return; #endif } views::BubbleDialogDelegateView::CreateBubble(bubble)->Show(); if (is_source_keyboard) bubble->FocusButtonOnKeyboardOpen(); } // static bool ProfileMenuViewBase::IsShowing() { return g_profile_bubble_ != nullptr; } // static void ProfileMenuViewBase::Hide() { if (g_profile_bubble_) g_profile_bubble_->GetWidget()->Close(); } // static ProfileMenuViewBase* ProfileMenuViewBase::GetBubbleForTesting() { return g_profile_bubble_; } ProfileMenuViewBase::ProfileMenuViewBase(views::Button* anchor_button, Browser* browser) : BubbleDialogDelegateView(anchor_button, views::BubbleBorder::TOP_RIGHT), browser_(browser), anchor_button_(anchor_button), close_bubble_helper_(this, browser) { DCHECK(!g_profile_bubble_); g_profile_bubble_ = this; DialogDelegate::set_buttons(ui::DIALOG_BUTTON_NONE); // TODO(tluk): Remove when fixing https://crbug.com/822075 // The sign in webview will be clipped on the bottom corners without these // margins, see related bug <http://crbug.com/593203>. set_margins(gfx::Insets(2, 0)); DCHECK(anchor_button); anchor_button->AnimateInkDrop(views::InkDropState::ACTIVATED, nullptr); EnableUpDownKeyboardAccelerators(); GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenu); } ProfileMenuViewBase::~ProfileMenuViewBase() { // Items stored for menu generation are removed after menu is finalized, hence // it's not expected to have while destroying the object. DCHECK(g_profile_bubble_ != this); // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. DCHECK(menu_item_groups_.empty()); } void ProfileMenuViewBase::SetHeading(const base::string16& heading, const base::string16& tooltip_text, base::RepeatingClosure action) { constexpr int kInsidePadding = 8; const SkColor kBackgroundColor = ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_HighlightedMenuItemBackgroundColor); heading_container_->RemoveAllChildViews(/*delete_children=*/true); heading_container_->SetLayoutManager(std::make_unique<views::FillLayout>()); heading_container_->SetBackground( views::CreateSolidBackground(kBackgroundColor)); views::LabelButton* button = heading_container_->AddChildView( std::make_unique<HoverButton>(this, heading)); button->SetEnabledTextColors(views::style::GetColor( *this, views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY)); button->SetTooltipText(tooltip_text); button->SetHorizontalAlignment(gfx::ALIGN_CENTER); button->SetBorder(views::CreateEmptyBorder(gfx::Insets(kInsidePadding))); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::SetIdentityInfo(const gfx::ImageSkia& image, const gfx::ImageSkia& badge, const base::string16& title, const base::string16& subtitle) { constexpr int kTopMargin = kMenuEdgeMargin; constexpr int kBottomMargin = kDefaultVerticalMargin; constexpr int kHorizontalMargin = kMenuEdgeMargin; constexpr int kImageBottomMargin = kDefaultVerticalMargin; constexpr int kBadgeSize = 16; constexpr int kBadgePadding = 1; const SkColor kBadgeBackgroundColor = GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_BubbleBackground); identity_info_container_->RemoveAllChildViews(/*delete_children=*/true); identity_info_container_->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kVertical, views::BoxLayout::CrossAxisAlignment::kCenter, gfx::Insets(kTopMargin, kHorizontalMargin, kBottomMargin, kHorizontalMargin))); views::ImageView* image_view = identity_info_container_->AddChildView( std::make_unique<views::ImageView>()); // Fall back on |kUserAccountAvatarIcon| if |image| is empty. This can happen // in tests and when the account image hasn't been fetched yet. gfx::ImageSkia sized_image = image.isNull() ? gfx::CreateVectorIcon(kUserAccountAvatarIcon, kIdentityImageSize, GetDefaultIconColor()) : CropCircle(SizeImage(image, kIdentityImageSize)); gfx::ImageSkia sized_badge = AddCircularBackground(SizeImage(badge, kBadgeSize), kBadgeBackgroundColor, kBadgeSize + 2 * kBadgePadding); gfx::ImageSkia sized_badge_with_shadow = gfx::ImageSkiaOperations::CreateImageWithDropShadow( sized_badge, gfx::ShadowValue::MakeMdShadowValues(/*elevation=*/1, SK_ColorBLACK)); gfx::ImageSkia badged_image = gfx::ImageSkiaOperations::CreateIconWithBadge( sized_image, sized_badge_with_shadow); image_view->SetImage(badged_image); image_view->SetBorder(views::CreateEmptyBorder(0, 0, kImageBottomMargin, 0)); if (!title.empty()) { identity_info_container_->AddChildView(std::make_unique<views::Label>( title, views::style::CONTEXT_DIALOG_TITLE)); } if (!subtitle.empty()) { identity_info_container_->AddChildView(std::make_unique<views::Label>( subtitle, views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY)); } } void ProfileMenuViewBase::SetSyncInfo(const gfx::ImageSkia& icon, const base::string16& description, const base::string16& clickable_text, base::RepeatingClosure action) { constexpr int kIconSize = 16; const int kDescriptionIconSpacing = ChromeLayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_LABEL_HORIZONTAL); constexpr int kInsidePadding = 12; constexpr int kBorderThickness = 1; const int kBorderCornerRadius = views::LayoutProvider::Get()->GetCornerRadiusMetric(views::EMPHASIS_HIGH); sync_info_container_->RemoveAllChildViews(/*delete_children=*/true); sync_info_container_->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(), kInsidePadding)); if (description.empty()) { views::Button* button = sync_info_container_->AddChildView(std::make_unique<HoverButton>( this, SizeImage(icon, kIconSize), clickable_text)); RegisterClickAction(button, std::move(action)); return; } // Add padding, rounded border and margins. sync_info_container_->SetBorder(views::CreatePaddedBorder( views::CreateRoundedRectBorder(kBorderThickness, kBorderCornerRadius, GetDefaultSeparatorColor()), gfx::Insets(kInsidePadding))); sync_info_container_->SetProperty( views::kMarginsKey, gfx::Insets(kDefaultVerticalMargin, kMenuEdgeMargin)); // Add icon + description at the top. views::View* description_container = sync_info_container_->AddChildView(std::make_unique<views::View>()); views::BoxLayout* description_layout = description_container->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(), kDescriptionIconSpacing)); if (icon.isNull()) { // If there is no image, the description is centered. description_layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); } else { views::ImageView* icon_view = description_container->AddChildView( std::make_unique<views::ImageView>()); icon_view->SetImage(SizeImage(icon, kIconSize)); } views::Label* label = description_container->AddChildView( std::make_unique<views::Label>(description)); label->SetMultiLine(true); label->SetHandlesTooltips(false); // Add blue button at the bottom. views::Button* button = sync_info_container_->AddChildView( views::MdTextButton::CreateSecondaryUiBlueButton(this, clickable_text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::SetSyncInfoBackgroundColor(SkColor bg_color) { sync_info_container_->SetBackground(views::CreateRoundedRectBackground( bg_color, views::LayoutProvider::Get()->GetCornerRadiusMetric( views::EMPHASIS_HIGH))); } void ProfileMenuViewBase::AddShortcutFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { const int kButtonSpacing = ChromeLayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_BUTTON_HORIZONTAL); // Initialize layout if this is the first time a button is added. if (!shortcut_features_container_->GetLayoutManager()) { views::BoxLayout* layout = shortcut_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(/*top=*/kDefaultVerticalMargin / 2, 0, /*bottom=*/kMenuEdgeMargin, 0), kButtonSpacing)); layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); } views::Button* button = shortcut_features_container_->AddChildView( CreateCircularImageButton(this, icon, text, /*show_border=*/true)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddFeatureButton(const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kIconSize = 16; // Initialize layout if this is the first time a button is added. if (!features_container_->GetLayoutManager()) { features_container_->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } views::Button* button = features_container_->AddChildView(std::make_unique<HoverButton>( this, SizeImage(ColorImage(icon, GetDefaultIconColor()), kIconSize), text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::SetProfileManagementHeading( const base::string16& heading) { // Add separator before heading. profile_mgmt_separator_container_->RemoveAllChildViews( /*delete_children=*/true); profile_mgmt_separator_container_->SetLayoutManager( std::make_unique<views::FillLayout>()); profile_mgmt_separator_container_->SetBorder(views::CreateEmptyBorder( gfx::Insets(kDefaultVerticalMargin, /*horizontal=*/0))); profile_mgmt_separator_container_->AddChildView( std::make_unique<views::Separator>()); // Initialize heading layout. profile_mgmt_heading_container_->RemoveAllChildViews( /*delete_children=*/true); profile_mgmt_heading_container_->SetLayoutManager( std::make_unique<views::FillLayout>()); profile_mgmt_heading_container_->SetBorder(views::CreateEmptyBorder( gfx::Insets(kDefaultVerticalMargin, kMenuEdgeMargin))); // Add heading. views::Label* label = profile_mgmt_heading_container_->AddChildView( std::make_unique<views::Label>(heading, views::style::CONTEXT_LABEL, STYLE_HINT)); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetHandlesTooltips(false); } void ProfileMenuViewBase::AddSelectableProfile(const gfx::ImageSkia& image, const base::string16& name, base::RepeatingClosure action) { constexpr int kImageSize = 22; // Initialize layout if this is the first time a button is added. if (!selectable_profiles_container_->GetLayoutManager()) { selectable_profiles_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } gfx::ImageSkia sized_image = CropCircle(SizeImage(image, kImageSize)); views::Button* button = selectable_profiles_container_->AddChildView( std::make_unique<HoverButton>(this, sized_image, name)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddProfileManagementShortcutFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { // Initialize layout if this is the first time a button is added. if (!profile_mgmt_shortcut_features_container_->GetLayoutManager()) { profile_mgmt_shortcut_features_container_->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kHorizontal, views::BoxLayout::CrossAxisAlignment::kCenter, gfx::Insets(0, 0, 0, /*right=*/kMenuEdgeMargin))); } views::Button* button = profile_mgmt_shortcut_features_container_->AddChildView( CreateCircularImageButton(this, icon, text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddProfileManagementFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kIconSize = 22; // Initialize layout if this is the first time a button is added. if (!profile_mgmt_features_container_->GetLayoutManager()) { profile_mgmt_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } views::Button* button = profile_mgmt_features_container_->AddChildView( std::make_unique<HoverButton>(this, SizeImage(icon, kIconSize), text)); RegisterClickAction(button, std::move(action)); } gfx::ImageSkia ProfileMenuViewBase::ImageForMenu(const gfx::VectorIcon& icon, float icon_to_image_ratio) { const int padding = static_cast<int>(kMaxImageSize * (1.0 - icon_to_image_ratio) / 2.0); auto sized_icon = gfx::CreateVectorIcon(icon, kMaxImageSize - 2 * padding, GetDefaultIconColor()); return gfx::CanvasImageSource::CreatePadded(sized_icon, gfx::Insets(padding)); } gfx::ImageSkia ProfileMenuViewBase::ColoredImageForMenu( const gfx::VectorIcon& icon, SkColor color) { return gfx::CreateVectorIcon(icon, kMaxImageSize, color); } void ProfileMenuViewBase::RecordClick(ActionableItem item) { // TODO(tangltom): Separate metrics for incognito and guest menu. base::UmaHistogramEnumeration("Profile.Menu.ClickedActionableItem", item); } ax::mojom::Role ProfileMenuViewBase::GetAccessibleWindowRole() { // Return |ax::mojom::Role::kDialog| which will make screen readers announce // the following in the listed order: // the title of the dialog, labels (if any), the focused View within the // dialog (if any) return ax::mojom::Role::kDialog; } void ProfileMenuViewBase::OnThemeChanged() { views::BubbleDialogDelegateView::OnThemeChanged(); SetBackground(views::CreateSolidBackground(GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_DialogBackground))); } bool ProfileMenuViewBase::HandleContextMenu( content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) { // Suppresses the context menu because some features, such as inspecting // elements, are not appropriate in a bubble. return true; } void ProfileMenuViewBase::Init() { Reset(); BuildMenu(); // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. if (!base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) RepopulateViewFromMenuItems(); } void ProfileMenuViewBase::WindowClosing() { DCHECK_EQ(g_profile_bubble_, this); if (anchor_button()) anchor_button()->AnimateInkDrop(views::InkDropState::DEACTIVATED, nullptr); g_profile_bubble_ = nullptr; } void ProfileMenuViewBase::ButtonPressed(views::Button* button, const ui::Event& event) { OnClick(button); } void ProfileMenuViewBase::StyledLabelLinkClicked(views::StyledLabel* link, const gfx::Range& range, int event_flags) { OnClick(link); } void ProfileMenuViewBase::OnClick(views::View* clickable_view) { DCHECK(!click_actions_[clickable_view].is_null()); signin_ui_util::RecordProfileMenuClick(browser()->profile()); click_actions_[clickable_view].Run(); } int ProfileMenuViewBase::GetMaxHeight() const { gfx::Rect anchor_rect = GetAnchorRect(); gfx::Rect screen_space = display::Screen::GetScreen() ->GetDisplayNearestPoint(anchor_rect.CenterPoint()) .work_area(); int available_space = screen_space.bottom() - anchor_rect.bottom(); #if defined(OS_WIN) // On Windows the bubble can also be show to the top of the anchor. available_space = std::max(available_space, anchor_rect.y() - screen_space.y()); #endif return std::max(kMinimumScrollableContentHeight, available_space); } void ProfileMenuViewBase::Reset() { // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. if (!base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) { menu_item_groups_.clear(); return; } click_actions_.clear(); RemoveAllChildViews(/*delete_childen=*/true); auto components = std::make_unique<views::View>(); components->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); // Create and add new component containers in the correct order. // First, add the parts of the current profile. heading_container_ = components->AddChildView(std::make_unique<views::View>()); identity_info_container_ = components->AddChildView(std::make_unique<views::View>()); shortcut_features_container_ = components->AddChildView(std::make_unique<views::View>()); sync_info_container_ = components->AddChildView(std::make_unique<views::View>()); features_container_ = components->AddChildView(std::make_unique<views::View>()); profile_mgmt_separator_container_ = components->AddChildView(std::make_unique<views::View>()); // Second, add the profile management header. This includes the heading and // the shortcut feature(s) next to it. auto profile_mgmt_header = std::make_unique<views::View>(); views::BoxLayout* profile_mgmt_header_layout = profile_mgmt_header->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kHorizontal, views::BoxLayout::CrossAxisAlignment::kCenter)); profile_mgmt_heading_container_ = profile_mgmt_header->AddChildView(std::make_unique<views::View>()); profile_mgmt_header_layout->SetFlexForView(profile_mgmt_heading_container_, 1); profile_mgmt_shortcut_features_container_ = profile_mgmt_header->AddChildView(std::make_unique<views::View>()); profile_mgmt_header_layout->SetFlexForView( profile_mgmt_shortcut_features_container_, 0); components->AddChildView(std::move(profile_mgmt_header)); // Third, add the profile management buttons. selectable_profiles_container_ = components->AddChildView(std::make_unique<views::View>()); profile_mgmt_features_container_ = components->AddChildView(std::make_unique<views::View>()); // Create a scroll view to hold the components. auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->SetHideHorizontalScrollBar(true); // TODO(https://crbug.com/871762): it's a workaround for the crash. scroll_view->SetDrawOverflowIndicator(false); scroll_view->ClipHeightTo(0, GetMaxHeight()); scroll_view->SetContents(std::move(components)); // Create a grid layout to set the menu width. views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, kMenuWidth, kMenuWidth); layout->StartRow(1.0, 0); layout->AddView(std::move(scroll_view)); } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. int ProfileMenuViewBase::GetMarginSize(GroupMarginSize margin_size) const { switch (margin_size) { case kNone: return 0; case kTiny: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_CONTENT_LIST_VERTICAL_SINGLE); case kSmall: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_CONTROL_VERTICAL_SMALL); case kLarge: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_UNRELATED_CONTROL_VERTICAL_LARGE); } } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. void ProfileMenuViewBase::AddMenuGroup(bool add_separator) { if (add_separator && !menu_item_groups_.empty()) { DCHECK(!menu_item_groups_.back().items.empty()); menu_item_groups_.emplace_back(); } menu_item_groups_.emplace_back(); } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. void ProfileMenuViewBase::AddMenuItemInternal(std::unique_ptr<views::View> view, MenuItems::ItemType item_type) { DCHECK(!menu_item_groups_.empty()); auto& current_group = menu_item_groups_.back(); current_group.items.push_back(std::move(view)); if (current_group.items.size() == 1) { current_group.first_item_type = item_type; current_group.last_item_type = item_type; } else { current_group.different_item_types |= current_group.last_item_type != item_type; current_group.last_item_type = item_type; } } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. views::Button* ProfileMenuViewBase::CreateAndAddTitleCard( std::unique_ptr<views::View> icon_view, const base::string16& title, const base::string16& subtitle, base::RepeatingClosure action) { std::unique_ptr<HoverButton> title_card = std::make_unique<HoverButton>( this, std::move(icon_view), title, subtitle); if (action.is_null()) title_card->SetEnabled(false); views::Button* button_ptr = title_card.get(); RegisterClickAction(button_ptr, std::move(action)); AddMenuItemInternal(std::move(title_card), MenuItems::kTitleCard); return button_ptr; } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. views::Button* ProfileMenuViewBase::CreateAndAddButton( const gfx::ImageSkia& icon, const base::string16& title, base::RepeatingClosure action) { std::unique_ptr<HoverButton> button = std::make_unique<HoverButton>(this, icon, title); views::Button* pointer = button.get(); RegisterClickAction(pointer, std::move(action)); AddMenuItemInternal(std::move(button), MenuItems::kButton); return pointer; } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. views::Button* ProfileMenuViewBase::CreateAndAddBlueButton( const base::string16& text, bool md_style, base::RepeatingClosure action) { std::unique_ptr<views::LabelButton> button = md_style ? views::MdTextButton::CreateSecondaryUiBlueButton(this, text) : views::MdTextButton::Create(this, text); views::Button* pointer = button.get(); RegisterClickAction(pointer, std::move(action)); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(button)); AddMenuItemInternal(std::move(margined_view), MenuItems::kStyledButton); return pointer; } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. #if !defined(OS_CHROMEOS) DiceSigninButtonView* ProfileMenuViewBase::CreateAndAddDiceSigninButton( AccountInfo* account_info, gfx::Image* account_icon, base::RepeatingClosure action) { std::unique_ptr<DiceSigninButtonView> button = account_info ? std::make_unique<DiceSigninButtonView>(*account_info, *account_icon, this) : std::make_unique<DiceSigninButtonView>(this); DiceSigninButtonView* pointer = button.get(); RegisterClickAction(pointer->signin_button(), std::move(action)); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(GetMarginSize(kSmall), kMenuEdgeMargin))); margined_view->AddChildView(std::move(button)); AddMenuItemInternal(std::move(margined_view), MenuItems::kStyledButton); return pointer; } #endif // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. views::Label* ProfileMenuViewBase::CreateAndAddLabel(const base::string16& text, int text_context) { std::unique_ptr<views::Label> label = std::make_unique<views::Label>(text, text_context); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetMaximumWidth(kMenuWidth - 2 * kMenuEdgeMargin); views::Label* pointer = label.get(); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(label)); AddMenuItemInternal(std::move(margined_view), MenuItems::kLabel); return pointer; } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. views::StyledLabel* ProfileMenuViewBase::CreateAndAddLabelWithLink( const base::string16& text, gfx::Range link_range, base::RepeatingClosure action) { auto label_with_link = std::make_unique<views::StyledLabel>(text, this); label_with_link->SetDefaultTextStyle(views::style::STYLE_SECONDARY); label_with_link->AddStyleRange( link_range, views::StyledLabel::RangeStyleInfo::CreateForLink()); views::StyledLabel* pointer = label_with_link.get(); RegisterClickAction(pointer, std::move(action)); AddViewItem(std::move(label_with_link)); return pointer; } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. void ProfileMenuViewBase::AddViewItem(std::unique_ptr<views::View> view) { // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(view)); AddMenuItemInternal(std::move(margined_view), MenuItems::kGeneral); } void ProfileMenuViewBase::RegisterClickAction(views::View* clickable_view, base::RepeatingClosure action) { DCHECK(click_actions_.count(clickable_view) == 0); click_actions_[clickable_view] = std::move(action); } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. void ProfileMenuViewBase::RepopulateViewFromMenuItems() { RemoveAllChildViews(true); // Create a view to keep menu contents. auto contents_view = std::make_unique<views::View>(); contents_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets())); for (unsigned group_index = 0; group_index < menu_item_groups_.size(); group_index++) { MenuItems& group = menu_item_groups_[group_index]; if (group.items.empty()) { // An empty group represents a separator. contents_view->AddChildView(new views::Separator()); } else { views::View* sub_view = new views::View(); GroupMarginSize top_margin; GroupMarginSize bottom_margin; GroupMarginSize child_spacing; if (group.first_item_type == MenuItems::kTitleCard || group.first_item_type == MenuItems::kLabel) { top_margin = kTiny; } else { top_margin = kSmall; } if (group.last_item_type == MenuItems::kTitleCard) { bottom_margin = kTiny; } else if (group.last_item_type == MenuItems::kButton) { bottom_margin = kSmall; } else { bottom_margin = kLarge; } if (!group.different_item_types) { child_spacing = kNone; } else if (group.items.size() == 2 && group.first_item_type == MenuItems::kTitleCard && group.last_item_type == MenuItems::kButton) { child_spacing = kNone; } else { child_spacing = kLarge; } // Reduce margins if previous/next group is not a separator. if (group_index + 1 < menu_item_groups_.size() && !menu_item_groups_[group_index + 1].items.empty()) { bottom_margin = kTiny; } if (group_index > 0 && !menu_item_groups_[group_index - 1].items.empty()) { top_margin = kTiny; } sub_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(GetMarginSize(top_margin), 0, GetMarginSize(bottom_margin), 0), GetMarginSize(child_spacing))); for (std::unique_ptr<views::View>& item : group.items) sub_view->AddChildView(std::move(item)); contents_view->AddChildView(sub_view); } } menu_item_groups_.clear(); // Create a scroll view to hold contents view. auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->SetHideHorizontalScrollBar(true); // TODO(https://crbug.com/871762): it's a workaround for the crash. scroll_view->SetDrawOverflowIndicator(false); scroll_view->ClipHeightTo(0, GetMaxHeight()); scroll_view->SetContents(std::move(contents_view)); // Create a grid layout to set the menu width. views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, kMenuWidth, kMenuWidth); layout->StartRow(1.0, 0); layout->AddView(std::move(scroll_view)); if (GetBubbleFrameView()) { SizeToContents(); // SizeToContents() will perform a layout, but only if the size changed. Layout(); } } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. gfx::ImageSkia ProfileMenuViewBase::CreateVectorIcon( const gfx::VectorIcon& icon) { return gfx::CreateVectorIcon(icon, kIconSize, GetDefaultIconColor()); } // TODO(crbug.com/1021587): Remove after ProfileMenuRevamp. int ProfileMenuViewBase::GetDefaultIconSize() { return kIconSize; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e2b51ec4043f040c267cfade69df40689d5f0988
ca160b80111990159f0cb91d7cf867f80661d154
/src/aunit/Assertion.cpp
a47ecf0f2c8b1d6143adbfd4060cde9fb76fc046
[ "MIT" ]
permissive
ciband/AUnit
1c05e4d41769e35ed2ec8476fd95fdd51bc4906f
503b382219f2a23b79dc6f3a2b49eef2ed0af26f
refs/heads/develop
2020-03-13T08:15:21.991599
2018-04-25T17:23:26
2018-04-25T17:23:26
131,040,538
0
0
MIT
2018-11-29T16:44:58
2018-04-25T17:22:12
C++
UTF-8
C++
false
false
21,624
cpp
/* MIT License Copyright (c) 2018 Brian T. Park 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. */ #include <Arduino.h> // definition of Print #include "Flash.h" #include "Printer.h" #include "Assertion.h" namespace aunit { namespace { // This can be a template function because it is accessed only through the // various assertXxx() methods. Those assertXxx() methods are explicitly // overloaded for the various types that we want to support. // // Prints something like the following: // Assertion failed: (5) == (6), file Test.ino, line 820. // Assertion passed: (6) == (6), file Test.ino, line 820. template <typename A, typename B> void printAssertionMessage(bool ok, const char* file, uint16_t line, const A& lhs, const char *opName, const B& rhs) { // Don't use F() strings here because flash memory strings are not deduped by // the compiler, so each template instantiation of this method causes a // duplication of all the strings below. See // https://github.com/mmurdoch/arduinounit/issues/70 // for more info. Print* printer = Printer::getPrinter(); printer->print("Assertion "); printer->print(ok ? "passed" : "failed"); printer->print(": ("); printer->print(lhs); printer->print(") "); printer->print(opName); printer->print(" ("); printer->print(rhs); printer->print(')'); // reuse string in MataAssertion::printAssertionTestStatusMessage() printer->print(", file "); printer->print(file); printer->print(", line "); printer->print(line); printer->println('.'); } // Special version of (bool, bool) because Arduino Print.h converts // bool into int, which prints out "(1) == (0)", which isn't as useful. // This prints "(true) == (false)". void printAssertionMessage(bool ok, const char* file, uint16_t line, bool lhs, const char *opName, bool rhs) { // Don't use F() strings here. Same reason as above. Print* printer = Printer::getPrinter(); printer->print("Assertion "); printer->print(ok ? "passed" : "failed"); printer->print(": ("); printer->print(lhs ? "true" : "false"); printer->print(") "); printer->print(opName); printer->print(" ("); printer->print(rhs ? "true" : "false"); printer->print(')'); printer->print(", file "); printer->print(file); printer->print(", line "); printer->print(line); printer->println('.'); } // Special version for assertTrue(arg) and assertFalse(arg). // Prints: // "Assertion passed/failed: (arg) is true" // "Assertion passed/failed: (arg) is false" void printAssertionBoolMessage(bool ok, const char* file, uint16_t line, bool arg, bool value) { // Don't use F() strings here. Same reason as above. Print* printer = Printer::getPrinter(); printer->print("Assertion "); printer->print(ok ? "passed" : "failed"); printer->print(": ("); printer->print(arg ? "true" : "false"); printer->print(") is "); printer->print(value ? "true" : "false"); printer->print(", file "); printer->print(file); printer->print(", line "); printer->print(line); printer->println('.'); } } // namespace bool Assertion::isOutputEnabled(bool ok) { return (ok && isVerbosity(Verbosity::kAssertionPassed)) || (!ok && isVerbosity(Verbosity::kAssertionFailed)); } bool Assertion::assertionBool(const char* file, uint16_t line, bool arg, bool value) { if (isDone()) return false; bool ok = (arg == value); if (isOutputEnabled(ok)) { printAssertionBoolMessage(ok, file, line, arg, value); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, bool lhs, const char* opName, bool (*op)(bool lhs, bool rhs), bool rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, char lhs, const char* opName, bool (*op)(char lhs, char rhs), char rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, int lhs, const char* opName, bool (*op)(int lhs, int rhs), int rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, unsigned int lhs, const char* opName, bool (*op)(unsigned int lhs, unsigned int rhs), unsigned int rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, long lhs, const char* opName, bool (*op)(long lhs, long rhs), long rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, unsigned long lhs, const char* opName, bool (*op)(unsigned long lhs, unsigned long rhs), unsigned long rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, double lhs, const char* opName, bool (*op)(double lhs, double rhs), double rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const char* lhs, const char* opName, bool (*op)(const char* lhs, const char* rhs), const char* rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const char* lhs, const char *opName, bool (*op)(const char* lhs, const String& rhs), const String& rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const char* lhs, const char *opName, bool (*op)(const char* lhs, const __FlashStringHelper* rhs), const __FlashStringHelper* rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const String& lhs, const char *opName, bool (*op)(const String& lhs, const char* rhs), const char* rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const String& lhs, const char *opName, bool (*op)(const String& lhs, const String& rhs), const String& rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const String& lhs, const char *opName, bool (*op)(const String& lhs, const __FlashStringHelper* rhs), const __FlashStringHelper* rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const __FlashStringHelper* lhs, const char *opName, bool (*op)(const __FlashStringHelper* lhs, const char* rhs), const char* rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const __FlashStringHelper* lhs, const char *opName, bool (*op)(const __FlashStringHelper* lhs, const String& rhs), const String& rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } bool Assertion::assertion(const char* file, uint16_t line, const __FlashStringHelper* lhs, const char *opName, bool (*op)(const __FlashStringHelper* lhs, const __FlashStringHelper* rhs), const __FlashStringHelper* rhs) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessage(ok, file, line, lhs, opName, rhs); } setPassOrFail(ok); return ok; } namespace { // Verbose versions of above which accept the string arguments of the // assertXxx() macros, so that the error messages are more verbose. // // Prints something like the following: // Assertion failed: (x=5) == (y=6), file Test.ino, line 820. // Assertion passed: (x=6) == (y=6), file Test.ino, line 820. template <typename A, typename B> void printAssertionMessageVerbose(bool ok, const char* file, uint16_t line, const A& lhs, internal::FlashStringType lhsString, const char *opName, const B& rhs, internal::FlashStringType rhsString) { // Don't use F() strings here because flash memory strings are not deduped by // the compiler, so each template instantiation of this method causes a // duplication of all the strings below. See // https://github.com/mmurdoch/arduinounit/issues/70 // for more info. Print* printer = Printer::getPrinter(); printer->print("Assertion "); printer->print(ok ? "passed" : "failed"); printer->print(": ("); printer->print(lhsString); printer->print('='); printer->print(lhs); printer->print(") "); printer->print(opName); printer->print(" ("); printer->print(rhsString); printer->print('='); printer->print(rhs); printer->print(')'); // reuse string in MataAssertion::printAssertionTestStatusMessage() printer->print(", file "); printer->print(file); printer->print(", line "); printer->print(line); printer->println('.'); } // Special version of (bool, bool) because Arduino Print.h converts // bool into int, which prints out "(1) == (0)", which isn't as useful. // This prints "(x=true) == (y=false)". void printAssertionMessageVerbose(bool ok, const char* file, uint16_t line, bool lhs, internal::FlashStringType lhsString, const char *opName, bool rhs, internal::FlashStringType rhsString) { // Don't use F() strings here. Same reason as above. Print* printer = Printer::getPrinter(); printer->print("Assertion "); printer->print(ok ? "passed" : "failed"); printer->print(": ("); printer->print(lhsString); printer->print('='); printer->print(lhs ? "true" : "false"); printer->print(") "); printer->print(opName); printer->print(" ("); printer->print(rhsString); printer->print('='); printer->print(rhs ? "true" : "false"); printer->print(')'); printer->print(", file "); printer->print(file); printer->print(", line "); printer->print(line); printer->println('.'); } // Special version for assertTrue(arg) and assertFalse(arg). // Prints: // "Assertion passed/failed: (x=arg) is true" // "Assertion passed/failed: (x=arg) is false" void printAssertionBoolMessageVerbose(bool ok, const char* file, uint16_t line, bool arg, internal::FlashStringType argString, bool value) { // Don't use F() strings here. Same reason as above. Print* printer = Printer::getPrinter(); printer->print("Assertion "); printer->print(ok ? "passed" : "failed"); printer->print(": ("); printer->print(argString); printer->print('='); printer->print(arg ? "true" : "false"); printer->print(") is "); printer->print(value ? "true" : "false"); printer->print(", file "); printer->print(file); printer->print(", line "); printer->print(line); printer->println('.'); } } // namespace bool Assertion::assertionBoolVerbose(const char* file, uint16_t line, bool arg, internal::FlashStringType argString, bool value) { if (isDone()) return false; bool ok = (arg == value); if (isOutputEnabled(ok)) { printAssertionBoolMessageVerbose(ok, file, line, arg, argString, value); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, bool lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(bool lhs, bool rhs), bool rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, char lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(char lhs, char rhs), char rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, int lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(int lhs, int rhs), int rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, unsigned int lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(unsigned int lhs, unsigned int rhs), unsigned int rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, long lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(long lhs, long rhs), long rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, unsigned long lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(unsigned long lhs, unsigned long rhs), unsigned long rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, double lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(double lhs, double rhs), double rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const char* lhs, internal::FlashStringType lhsString, const char* opName, bool (*op)(const char* lhs, const char* rhs), const char* rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const char* lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const char* lhs, const String& rhs), const String& rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const char* lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const char* lhs, const __FlashStringHelper* rhs), const __FlashStringHelper* rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const String& lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const String& lhs, const char* rhs), const char* rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const String& lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const String& lhs, const String& rhs), const String& rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const String& lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const String& lhs, const __FlashStringHelper* rhs), const __FlashStringHelper* rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const __FlashStringHelper* lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const __FlashStringHelper* lhs, const char* rhs), const char* rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const __FlashStringHelper* lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const __FlashStringHelper* lhs, const String& rhs), const String& rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } bool Assertion::assertionVerbose(const char* file, uint16_t line, const __FlashStringHelper* lhs, internal::FlashStringType lhsString, const char *opName, bool (*op)(const __FlashStringHelper* lhs, const __FlashStringHelper* rhs), const __FlashStringHelper* rhs, internal::FlashStringType rhsString) { if (isDone()) return false; bool ok = op(lhs, rhs); if (isOutputEnabled(ok)) { printAssertionMessageVerbose(ok, file, line, lhs, lhsString, opName, rhs, rhsString); } setPassOrFail(ok); return ok; } }
[ "brian@xparks.net" ]
brian@xparks.net
e9895040dfe2f027c27cb65eae6b931b025bc2f1
3122ac39f1ce0a882b48293a77195476299c2a3b
/clients/cpp-pistache-server/generated/model/PipelineRunSteps.cpp
4d9ceeb2f921610b39963ba47ea4b85fe92a64ac
[ "MIT" ]
permissive
miao1007/swaggy-jenkins
4e6fe28470eda2428cbc584dcd365a21caa606ef
af79438c120dd47702b50d51c42548b4db7fd109
refs/heads/master
2020-08-30T16:50:27.474383
2019-04-10T13:47:17
2019-04-10T13:47:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
792
cpp
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 1.1.1 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "PipelineRunSteps.h" namespace org { namespace openapitools { namespace server { namespace model { PipelineRunSteps::PipelineRunSteps() { } PipelineRunSteps::~PipelineRunSteps() { } void PipelineRunSteps::validate() { // TODO: implement validation } nlohmann::json PipelineRunSteps::toJson() const { nlohmann::json val = nlohmann::json::object(); return val; } void PipelineRunSteps::fromJson(nlohmann::json& val) { } } } } }
[ "cliffano@gmail.com" ]
cliffano@gmail.com
edb0d44c8f4af7305db7fa5deab165a7736374af
f78b9a68f4da064a6388120498eac1e4b3b0348d
/build-Test-Desktop_Qt_5_6_0_MinGW_32bit-Debug/debug/moc_countdown.cpp
d8f5caf03facc1bef9a1f48cea88e470ed13f250
[]
no_license
Bisyuu/pd2-Taiko
fc170d33d3a1d02e983a31cc7aff619679b49b39
7209d932a587a16d500ab1003a2f6ba71f7fb5c1
refs/heads/master
2020-12-24T20:14:52.543493
2016-05-15T15:56:19
2016-05-15T15:56:19
58,869,601
0
0
null
null
null
null
UTF-8
C++
false
false
3,318
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'countdown.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../Test/countdown.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'countdown.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.6.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_countdown_t { QByteArrayData data[3]; char stringdata0[20]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_countdown_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_countdown_t qt_meta_stringdata_countdown = { { QT_MOC_LITERAL(0, 0, 9), // "countdown" QT_MOC_LITERAL(1, 10, 8), // "decrease" QT_MOC_LITERAL(2, 19, 0) // "" }, "countdown\0decrease\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_countdown[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 19, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, 0 // eod }; void countdown::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { countdown *_t = static_cast<countdown *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->decrease(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject countdown::staticMetaObject = { { &QGraphicsTextItem::staticMetaObject, qt_meta_stringdata_countdown.data, qt_meta_data_countdown, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *countdown::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *countdown::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_countdown.stringdata0)) return static_cast<void*>(const_cast< countdown*>(this)); return QGraphicsTextItem::qt_metacast(_clname); } int countdown::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QGraphicsTextItem::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
[ "jerrys1542@gmail.com" ]
jerrys1542@gmail.com
4446f1d02de1ed50eaf34008e8c74709ebe35303
82621767a8fffb6f5c1e0323879d4f2f7555e3b0
/fc_malloc/fc_heap.hpp
e47876c09e556bb015e592befaefbc5da0ee38db
[ "Zlib" ]
permissive
abelianwang/malloc-survey
40b46b1507ec8c5666157b53326d4a23e31ac88e
6da5aca6aa2720d64bff709c111a5d8a5fa7a1be
refs/heads/master
2023-03-18T09:16:13.401077
2016-07-06T15:11:27
2016-07-06T15:11:27
534,266,709
1
0
Zlib
2022-09-08T15:06:26
2022-09-08T15:06:26
null
UTF-8
C++
false
false
17,679
hpp
#pragma once #include "mmap_alloc.hpp" #include <iostream> #include <sstream> #include <assert.h> #include <string.h> #include <vector> #include <unordered_set> #define CHECK_SIZE( x ) assert(((x) != 0) && !((x) & ((x) - 1))) #define PAGE_SIZE (2*1024*1024) #define LOG2(X) ((unsigned) (8*sizeof (unsigned long long) - __builtin_clzll((X)) - 1)) #define LZERO(X) (__builtin_clzll((X)) ) #define NUM_BINS 32 // log2(PAGE_SIZE) class block_header { public: block_header() :_prev_size(0),_size(-PAGE_SIZE),_flags(0) { //fprintf( stderr, "constructor... size: %d\n", _size ); //memset( data(), 0, size() - 8 ); assert( page_size() == PAGE_SIZE ); } void* operator new (size_t s) { return malloc(PAGE_SIZE);/*mmap_alloc( PAGE_SIZE );*/ } void operator delete( void* p ) { free(p); /*mmap_free( p, PAGE_SIZE );*/ } void dump( const char* label ) { fprintf( stderr, "%s ] _prev_size: %d _size: %d\n", label, _prev_size, _size);//, int(_flags) ); } /** size of the block header including the header, data size is size()-8 */ uint32_t size()const { return abs(_size); } char* data() { return reinterpret_cast<char*>(((char*)this)+8); } block_header* next()const { return _size <= 0 ? nullptr : reinterpret_cast<block_header*>(((char*)this)+size()); } block_header* prev()const { return _prev_size <= 0 ? nullptr : reinterpret_cast<block_header*>(((char*)this)-_prev_size); } /** * creates a new block of size S at the end of this block. * * @pre size is a power of 2 * @return a pointer to the new block, or null if no split was possible */ block_header* split( uint32_t sz ) { assert( sz >= 32 ); assert( size() >= 32 ); assert( sz <= (size() - 32) ); assert( page_size() == PAGE_SIZE ); assert( _size != 0xbad ); CHECK_SIZE(sz); int32_t old_size = _size; block_header* old_nxt = next(); _size = size() - sz; assert( _size != 0 ); block_header* nxt = next(); assert( nxt != 0 ); nxt->_prev_size = _size; nxt->_size = old_size < 0 ? -sz : sz; assert( _size != 0 ); if( old_nxt ) old_nxt->_prev_size = nxt->_size; //memset( data(), 0, size()-8 ); assert( size() + nxt->size() == uint32_t(abs(old_size)) ); assert( nxt->next() == old_nxt ); assert( nxt->prev() == this ); assert( next() == nxt ); assert( page_size() == PAGE_SIZE ); assert( nxt->page_size() == PAGE_SIZE ); assert( nxt != this ); nxt->_flags = 0; return nxt; } /** * @return the merged node, if any */ block_header* merge_next() { assert( _size != 0xbad ); block_header* cur_next = next(); if( !cur_next ) return this; assert( cur_next->_size != 0xbad ); assert( cur_next->size() > 0 ); // if( !cur_next->is_idle() ) return this; auto s = size(); assert( _size > 0 ); _size += cur_next->size(); assert( _size != 0 ); if( cur_next->_size > 0 ) { block_header* new_next = next(); new_next->_prev_size = size(); } else { _size = -_size; // we are at the end. assert( _size != 0 ); } assert( cur_next->_size = 0xbad ); // memset( data(), 0, size()-8 ); assert( size() > s ); if( next() ) { assert( size()/8 == next() - this ); assert( next()->_prev_size == size() ); assert( page_size() == PAGE_SIZE ); } return this; } /** * @return the merged node, or this. */ block_header* merge_prev() { assert( page_size() == PAGE_SIZE ); block_header* pre = prev(); if( !pre ) return this; return prev()->merge_next(); } block_header* head() { if( !prev() ) return this; return prev()->head(); } block_header* tail() { if( !next() ) return this; return next()->tail(); } size_t page_size() { auto t = tail(); auto h = head(); return ((char*)t-(char*)h) + t->size(); } struct queue_state // the block is serving as a linked-list node { block_header* qnext; block_header* qprev; block_header** head; block_header** tail; }; enum flag_enum { queued = 1, idle = 2, active = 4 }; bool is_idle()const { return _flags & idle; } bool is_active()const { return _flags & active; } bool is_queued()const { return _flags & queued; } void set_active( bool s ) { if( s ) _flags |= active; else _flags &= ~active; } void set_queued( bool s ) { if( s ) _flags |= queued; else _flags &= ~queued; // anytime we change state it should be reset.. if( is_queued() ) { as_queue().qnext = nullptr; as_queue().qprev = nullptr; } } /** removes this node from any queue it is in */ void dequeue() { block_header* pre = as_queue().qprev; block_header* nxt = as_queue().qnext; if( pre ) pre->as_queue().qnext = nxt; if( nxt ) nxt->as_queue().qprev = pre; set_queued(false); } void set_idle( bool s ) { if( s ) _flags |= idle; else _flags &= ~idle; assert( is_idle() == s ); } queue_state& as_queue() { // assert( is_queued() ); return *reinterpret_cast<queue_state*>(data()); } // private: int32_t _prev_size; // size of previous header. int32_t _size:24; // offset to next, negitive indicates tail, 8 MB max, it could be neg int32_t _flags:8; // offset to next, negitive indicates tail }; static_assert( sizeof(block_header) == 8, "Compiler is not packing data" ); typedef block_header* block_header_ptr; struct block_stack { public: block_stack():_head(nullptr){} void push( block_header* h ) { h->as_queue().qnext = _head; if( _head ) _head->as_queue().qprev = h; _head = h; //_head.push_back(h); } void push_all( block_header* h ) { assert( h->is_queued() ); assert( _head == nullptr ); _head = h; } /* bool pop( block_header* h ) { if( _head == nullptr ) return null; return _head.erase(h) != 0; } */ /** returns all blocks */ block_header* pop_all() { block_header* h = _head; _head = nullptr; return h; } block_header* pop() { if( _head ) { auto tmp = _head; _head = _head->as_queue().qnext; if( _head ) _head->as_queue().qprev = nullptr; return tmp; } return nullptr; /* if( _head.size() == 0 ) return nullptr; auto f = _head.begin(); auto h = *f; _head.erase(f); return h; */ } block_header* head(){ return _head; } //int size() { return int(_head.size()); } private: //std::unordered_set<block_header*> _head; block_header* _head; }; /** * Single threaded heap implementation, foundation * for multi-threaded version; */ class fc_heap { public: block_header* alloc( size_t s ); void free( block_header* h ); fc_heap() { memset(_bins, 0, sizeof(_bins) ); _free_32_data = mmap_alloc( PAGE_SIZE ); _free_64_data = mmap_alloc( PAGE_SIZE ); _free_32_data_end = _free_32_data + PAGE_SIZE; _free_64_data_end = _free_64_data + PAGE_SIZE; _free_32_scan_end = &_free_32_state[PAGE_SIZE/32/64]; _free_64_scan_end = &_free_64_state[PAGE_SIZE/64/64]; _free_32_scan_pos = _free_32_state; _free_64_scan_pos = _free_64_state; memset( _free_32_state, 0xff, sizeof(_free_32_state ) ); memset( _free_64_state, 0xff, sizeof(_free_64_state ) ); } ~fc_heap() { mmap_free( _free_64_data, PAGE_SIZE ); mmap_free( _free_32_data, PAGE_SIZE ); } // private: char* alloc32() { uint32_t c = 0; while( 0 == *_free_32_scan_pos ) { ++_free_32_scan_pos; if( _free_32_scan_pos == _free_32_scan_end ) { _free_32_scan_pos = _free_32_state; } if( ++c == sizeof(_free_32_state)/sizeof(int64_t) ) { return alloc64(); } } int bit = LZERO(*_free_32_scan_pos); int offset = (_free_32_scan_pos - _free_32_state)*64; *_free_32_scan_pos ^= (1ll<<(63-bit)); // flip the bit // fprintf( stderr, "alloc offset: %d bit %d pos %d\n", offset,bit,(offset+bit) ); return _free_32_data + (offset+bit)*32; } char* alloc64() { uint32_t c = 0; while( 0 == *_free_64_scan_pos ) { ++_free_64_scan_pos; if( _free_64_scan_pos == _free_64_scan_end ) { _free_64_scan_pos = _free_64_state; } if( ++c == sizeof(_free_64_state)/sizeof(int64_t) ) { return nullptr; } } int bit = LZERO(*_free_64_scan_pos); int offset = (_free_64_scan_pos - _free_64_state)*64; *_free_64_scan_pos ^= (1ll<<(63-bit)); // flip the bit return _free_64_data + (offset+bit)*64; } bool free32( char* p ) { if( p >= _free_32_data && _free_32_data_end > p ) { uint32_t offset = (p - _free_32_data)/32; uint32_t bit = offset & (64-1); uint32_t idx = offset/64; _free_32_state[idx] ^= (1ll<<((63-bit))); return true; } return false; } bool free64( char* p ) { if( p >= _free_64_data && _free_64_data_end > p ) { uint32_t offset = (p - _free_64_data)/64; uint32_t bit = offset & (64-1); uint32_t idx = offset/64; _free_64_state[idx] ^= (1ll<<((63-bit))); return true; } return false; } char* _free_32_data; char* _free_64_data; char* _free_32_data_end; char* _free_64_data_end; uint64_t* _free_32_scan_pos; uint64_t* _free_64_scan_pos; uint64_t* _free_32_scan_end; uint64_t* _free_64_scan_end; uint64_t _free_32_state[PAGE_SIZE/32/64]; uint64_t _free_64_state[PAGE_SIZE/64/64]; block_stack _bins[NUM_BINS]; // anything less than 1024 bytes }; /** * Return a block of size s or greater * @pre size >= 32 * @pre size is power of 2 */ block_header* fc_heap::alloc( size_t s ) { assert( s >= 32 ); CHECK_SIZE( s ); // make sure it is a power of 2 uint32_t min_bin = LOG2(s); // find the min bin for it. while( min_bin < 32 ) { block_header* h = _bins[min_bin].pop(); if( h ) { assert( h->_size != 0 ); assert( h->_size != 0xbad ); assert( h->is_queued() ); h->set_queued(false); if( h->size() - 32 < s ) { h->set_active(true); return h; } block_header* tail = h->split(s); assert( h->_size != 0 ); h->set_active(true); this->free(h); tail->set_active(true); return tail; } ++min_bin; } // mmap a new page block_header* h = new block_header(); block_header* t = h->split(s); h->set_active(true); free(h); t->set_active(true); return t; } void fc_heap::free( block_header* h ) { assert( h != nullptr ); assert( h->is_active() ); assert( h->_size != 0 ); assert( h->size() < PAGE_SIZE ); auto pre = h->prev(); auto nxt = h->next(); if( nxt && !nxt->is_active() && nxt->is_queued() ) { auto nxt_bin = LOG2(nxt->size()); if( _bins[nxt_bin].head() == nxt ) { _bins[nxt_bin].pop(); nxt->set_queued(false); } else { nxt->dequeue(); } h = h->merge_next(); } if( pre && !pre->is_active() && pre->is_queued() ) { auto pre_bin = LOG2(pre->size()); if( _bins[pre_bin].head() == pre ) { _bins[pre_bin].pop(); pre->set_queued(false); } else { pre->dequeue(); } h = pre->merge_next(); } if( h->size() == PAGE_SIZE ) { delete h; return; } h->set_active(false); h->set_queued(true ); auto hbin = LOG2(h->size()); _bins[hbin].push(h); } class thread_heap; class garbage_thread { public: static garbage_thread& get(); uint64_t avail( int bin ); int64_t claim( int bin, int64_t num ); block_header* get_claim( int bin, int64_t pos ); protected: void register_thread_heap( thread_heap* h ); friend class thread_heap; static void run(); }; class thread_heap { public: static thread_heap& get(); block_header* allocate( size_t s ) { if( s >= PAGE_SIZE ) { // TODO: allocate special mmap region... } uint32_t min_bin = LOG2(s); // find the min bin for it. while( min_bin < NUM_BINS ) { block_header* h = cache_alloc(min_bin, s); if( h ) return h; garbage_thread& gc = garbage_thread::get(); if( auto av = gc.avail( min_bin ) ) { int64_t claim_num = std::min<int64_t>(4,av); int64_t claim = gc.claim( min_bin, claim_num ); int64_t end = claim + claim_num; while( claim < end ) { block_header* h = gc.get_claim(min_bin,claim); if( h ) { cache(h); } ++claim; } h = cache_alloc(min_bin, s); if( h ) return h; // else... we actually didn't get our claim } ++min_bin; } block_header* h = new block_header(); h->set_active(true); if( s <= PAGE_SIZE - 32 ) { block_header* t = h->split(s); t->set_active(true); cache( h ); return t; } return h; } block_header* cache_alloc( int bin, size_t s ) { block_header* c = pop_cache(bin); if( c && (c->size() - 32) > s ) { block_header* t = c->split(s); c->set_active(true); if( !cache( c ) ) { this->free(c); } t->set_active(true); return t; } return nullptr; } bool cache( block_header* h ) { uint32_t b = LOG2( h->size() ); if( _cache_size[b] < 4 ) { h->set_queued(true); _cache[b].push(h); _cache_size[b]++; return true; } return false; } block_header* pop_cache( int bin ) { block_header* h = _cache[bin].pop(); if( h ) { _cache_size[bin]--; h->set_queued(false); return h; } return nullptr; } void free( block_header* h ) { h->set_queued(true); _gc_on_deck.push( h ); if( !_gc_at_bat.head() ) _gc_at_bat.push_all( _gc_on_deck.pop_all() ); } private: thread_heap(); friend garbage_thread; block_stack _gc_at_bat; // waiting for gc to empty block_stack _gc_on_deck; // caching until gc pickups at bat block_stack _cache[NUM_BINS]; int16_t _cache_size[NUM_BINS]; }; static fc_heap static_heap; void* fc_malloc( size_t s ) { if( s <= 64 ) { if( s <= 32 ) return static_heap.alloc32(); else return static_heap.alloc64(); } // round up to nearest power of 2 > 32 s += 8; // room for header. if( s < 32 ) s = 32; // min size s = (1<<(LOG2(s-1)+1)); // round up to nearest power of 2 if( s < 24 ) s = 24; block_header* h = static_heap.alloc( s ); assert( h->is_active() ); // h->set_idle(false); // assert( h->page_size() == PAGE_SIZE ); return h->data(); } void fc_free( void* f ) { if( static_heap.free32((char*)f) || static_heap.free64((char*)f) ) return; block_header* bh = (block_header*)(((char*)f)-8); // fprintf( stderr, "fc_free(block: %p)\n", bh ); // assert( bh->is_active() ); //assert( bh->page_size() == PAGE_SIZE ); static_heap.free(bh); }
[ "rlyeh.2015@gmail.com" ]
rlyeh.2015@gmail.com
7378cc5bfc33938c299d2c4d4db494d351274015
754afb303d5b60fe50ba85e9c8f462814a2ccfa6
/tst/AvlTree.cpp
51ae42ef4c41b03822714d445e731cfc7011947e
[]
no_license
hmfrank/AuD
f5141fcd1543b4e8d859faf3a1022703d6ed1c59
bccd2740b5ef334bfc630628c3d30e6d4afb1f80
refs/heads/master
2021-05-02T04:06:50.804744
2017-02-21T15:42:49
2017-02-21T15:42:49
76,026,202
0
0
null
null
null
null
UTF-8
C++
false
false
1,121
cpp
#include <catch.hpp> extern "C" { #include <stddef.h> #include "../inc/AvlTree.h" } int compare(const void *a, const void *b) { ptrdiff_t d = (const char*)a - (const char *)b; if (d < 0) return -1; else return d > 0; } TEST_CASE("avl tree contains, delete, insert, is empty", "[inc/AvlTree.h/avlContains, inc/AvlTree.h/avlDelete, inc/AvlTree.h/avlInsert, inc/AvlTree.h/avlIsEmpty]") { struct AvlTree tree; // corner case arguments REQUIRE_NOTHROW(avlInit(NULL, NULL)); REQUIRE_NOTHROW(avlInit(NULL, compare)); avlInit(&tree, NULL); REQUIRE(tree.compare(NULL, NULL) == 0); REQUIRE_NOTHROW(avlFree(NULL)); avlFree(&tree); REQUIRE_FALSE(avlContains(NULL, (void *) 1)); REQUIRE_FALSE(avlInsert(NULL, (void *) 1)); REQUIRE(avlIsEmpty(NULL)); // actual tests avlInit(&tree, &compare); REQUIRE(avlIsEmpty(&tree)); for (int i = 0; i < 10; i++) REQUIRE(avlInsert(&tree, (void*)i)); for (int i = 0; i < 10; i++) REQUIRE(avlContains(&tree, (void*)i)); REQUIRE_FALSE(avlIsEmpty(&tree)); REQUIRE_FALSE(avlInsert(&tree, (void*)2)); REQUIRE_FALSE(avlContains(&tree, (void*)-1)); avlFree(&tree); }
[ "hannes.frank@online.de" ]
hannes.frank@online.de
3b875aca05d74c045e9f3c0b845c28eccf68a6ae
fd320551dc41cde5d5a361141876d7f003f97faf
/normal-pushdown/include/normal/pushdown/join/ATTIC/HashJoinProbeKernel.h
ccc465e2a3e978ecbe5bbcac6946de1acafb020d
[]
no_license
ergouy/FlexPushdownDB
e157daa8788f73d66cb6f3f8cc4b825b8e455fad
218705d5195db39bf3eb9457d69fa7759824dec7
refs/heads/master
2023-08-11T12:38:01.227056
2021-07-20T17:23:58
2021-07-20T17:23:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,017
h
// // Created by matt on 31/7/20. // #ifndef NORMAL_NORMAL_PUSHDOWN_INCLUDE_NORMAL_PUSHDOWN_JOIN_HASHJOINPROBEKERNEL_H #define NORMAL_NORMAL_PUSHDOWN_INCLUDE_NORMAL_PUSHDOWN_JOIN_HASHJOINPROBEKERNEL_H #include <memory> #include "normal/pushdown/join/JoinPredicate.h" #include "HashTable.h" #include <normal/tuple/TupleSet2.h> using namespace normal::tuple; namespace normal::pushdown::join { class HashJoinProbeKernel { public: explicit HashJoinProbeKernel(JoinPredicate pred); static HashJoinProbeKernel make(JoinPredicate pred); void putHashTable(const std::shared_ptr<HashTable>& hashTable); tl::expected<void, std::string> putTupleSet(const std::shared_ptr<TupleSet2>& tupleSet); tl::expected<std::shared_ptr<normal::tuple::TupleSet2>, std::string> join(); private: JoinPredicate pred_; std::optional<std::shared_ptr<HashTable>> hashTable_; std::optional<std::shared_ptr<TupleSet2>> tupleSet_; }; } #endif //NORMAL_NORMAL_PUSHDOWN_INCLUDE_NORMAL_PUSHDOWN_JOIN_HASHJOINPROBEKERNEL_H
[ "matt.youill@burnian.com" ]
matt.youill@burnian.com
0ac0af0af1a9fb1624e466bc5c952d6fc3ebdc36
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
/DboClient/Lib/NtlSimulation/NtlSobMerchantItemAttr.h
e840c93d27980c9b0bfba1354fc58246cc4b3221
[]
no_license
4l3dx/DBOGLOBAL
9853c49f19882d3de10b5ca849ba53b44ab81a0c
c5828b24e99c649ae6a2953471ae57a653395ca2
refs/heads/master
2022-05-28T08:57:10.293378
2020-05-01T00:41:08
2020-05-01T00:41:08
259,094,679
3
3
null
2020-04-29T17:06:22
2020-04-26T17:43:08
null
UHC
C++
false
false
1,110
h
/***************************************************************************** * * File : NtlSobMerchantItem.h * Author : Hong SungBock * Copyright : (주)NTL * Date : 2006. 8. 1 * Abstract : Simulation Merchant Item object attribute ***************************************************************************** * Desc : * *****************************************************************************/ #ifndef __NTL_SOB_MERCHANT_ITEM_ATTR_H__ #define __NTL_SOB_MERCHANT_ITEM_ATTR_H__ #include "NtlSobAttr.h" class CNtlSobMerchantAttr : public CNtlSobAttr { DECLEAR_MEMORY_POOL(CNtlSobMerchantAttr, NTL_DEFAULT_MEMORY_POOL) public: sMERCHANT_TBLDAT *m_pMerchantTbl; /** Merchant Item table data pointer */ public: CNtlSobMerchantAttr(); virtual ~CNtlSobMerchantAttr(); virtual RwBool Create(void) { SetClassID(SLCLASS_NPC); return TRUE; } virtual void Destroy(void) {} virtual void HandleEvents(RWS::CMsg &pMsg); public: sMERCHANT_TBLDAT* GetMerchantTbl(void) const; const WCHAR* GetTabName(void) const; ///< 물품들의 분류명( ex : 의복, 무기 ....) }; #endif
[ "64261665+dboguser@users.noreply.github.com" ]
64261665+dboguser@users.noreply.github.com
72b2ee277cf1aef77edde4d53d9276f923d5f087
bc517358a0701e88591683efe8b3b6b5952e55be
/include/Decima/Decima.hpp
c4bce8cd2619570d209660082ed83a1726ed2e19
[ "MIT" ]
permissive
ALEHACKsp/DecimaTools
f117cb947a6ae3c74849d61d2d07720e1e179d42
166c9d1d47b5c995bd51db86ba2ae0ac082faa28
refs/heads/master
2022-11-23T19:25:38.734139
2020-07-21T03:13:14
2020-07-21T03:13:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,341
hpp
#include <cstdint> #include <cstddef> #include <array> #include <vector> #include <memory> #include <optional> #include <unordered_map> #include <map> #include <filesystem> #include <ostream> #include <mio/mmap.hpp> namespace Decima { class Archive { public: ~Archive(); // Used for file headers, file table entries, Segment table entires static constexpr std::array<std::uint32_t, 4> MurmurSalt1 = { 0x0FA3A9443, 0x0F41CAB62, 0x0F376811C, 0x0D2A89E3E }; // Used for file data Segments static constexpr std::array<std::uint32_t, 4> MurmurSalt2 = { 0x06C084A37, 0x07E159D95, 0x03D5AF7E8, 0x018AA7D3F }; static constexpr std::uint32_t MurmurSeed = 42u; enum class ArchiveVersion : std::uint32_t { // Horizon Zero Dawn(PS4) Unencrypted = 0x20304050, // Death Stranding(PC) Encrypted = 0x21304050, }; #pragma pack(push,1) struct FileSpan { std::uint64_t Offset; std::uint32_t Size; // Used during Decryption, likely a checksum std::uint32_t Hash; }; // Thanks Jayveer for actually being open about these structs // https://github.com/Jayveer/Decima-Explorer/blob/master/archive/DecimaArchive.h struct FileHeader { ArchiveVersion Version; std::uint32_t Key; std::uint64_t FileSize; std::uint64_t DataSize; std::uint64_t FileTableCount; std::uint32_t SegmentTableCount; std::uint32_t MaxSegmentSize; void Decrypt(); }; static_assert(sizeof(FileHeader) == 0x28); struct FileEntry { std::uint32_t FileID; std::uint32_t Unknown04; std::uint64_t Unknown08; FileSpan Span; void Decrypt(); }; static_assert(sizeof(FileEntry) == 0x20); struct SegmentEntry { FileSpan UncompressedSpan; FileSpan CompressedSpan; void Decrypt(); }; static_assert(sizeof(SegmentEntry) == 0x20); #pragma pack(pop) inline bool Encrypted() const { return Header.Version == ArchiveVersion::Encrypted; } inline const FileHeader& GetHeader() const { return Header; } inline void IterateFileEntries( std::function<void(const FileEntry&)> Proc ) const { std::for_each(FileEntries.cbegin(), FileEntries.cend(), Proc); } inline void IterateSegmentEntries( std::function<void(const SegmentEntry&)> Proc ) const { std::for_each(SegmentEntries.cbegin(), SegmentEntries.cend(), Proc); } std::optional<std::reference_wrapper<const Archive::FileEntry>> GetFileEntry( std::uint32_t FileID ) const; // Given an offset, find out what segment we land in std::optional<std::reference_wrapper<const Archive::SegmentEntry>> GetSegmentCompressed( std::uint64_t Offset ) const; std::optional<std::reference_wrapper<const Archive::SegmentEntry>> GetSegmentUncompressed( std::uint64_t Offset ) const; bool ExtractFile(const FileEntry& FileEntry, std::ostream& OutStream) const; static std::unique_ptr<Archive> OpenArchive( const std::filesystem::path& Path ); private: Archive(); FileHeader Header; // Used to easily lookup an EntryID into an index into FileEntries std::unordered_map<std::uint32_t, std::size_t> FileEntryLut; std::vector<FileEntry> FileEntries; // Acceleration structure to map an offset into a Segment entry std::map<std::uint64_t,const SegmentEntry&> SegmentCompressedLut; std::map<std::uint64_t,const SegmentEntry&> SegmentUncompressedLut; std::vector<SegmentEntry> SegmentEntries; mio::ummap_source FileMapping; }; }
[ "Wunkolo@gmail.com" ]
Wunkolo@gmail.com
e17b41cbc358111a304ee30112c1606fa4ee95ab
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/abc071/A/4480274.cpp
3a35a0a53a8155a705f8424fb367d91eb344e554
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> int main(){ int x, a, b; std::cin >> x >> a >> b; int da = abs(x - a); int db = abs(x - b); if(da < db){ std::cout << "A" << std::endl; }else{ std::cout << "B" << std::endl; } return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
8efb0018ab30d70f15c4ad364795a9fab424a0ba
a5a8516791b8169253cdf9d3dc47edc7ad120a37
/src/perception/src/look_at/debug/servers/debug_images_publisher.cpp
509b21d18cf58eaf5256f972c2d170d579cd0e29
[]
no_license
Forrest-Z/Carbrain
fa0ce92f1c625b06bd100f2f788176acc57db3fb
bdba2a394f2e90f075118b960d46e63e88e395fe
refs/heads/master
2022-01-07T16:55:12.681919
2019-06-09T16:38:59
2019-06-09T16:38:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,994
cpp
#include "debug_images_publisher.h" #include "common/angle_conversions.h" THIRD_PARTY_HEADERS_BEGIN #include <perception_msgs/LookAtRegionsDebug.h> THIRD_PARTY_HEADERS_END namespace look_at { const ParameterString<double> DebugImagesPublisher::PIXEL_WIDTH("pixel_width"); const ParameterString<double> DebugImagesPublisher::OFFSET_BEFORE_CENTER( "offset_before_center"); const ParameterString<double> DebugImagesPublisher::OFFSET_AFTER_CENTER( "offset_after_center"); const ParameterString<double> DebugImagesPublisher::OFFSET_RIGHT_OF_CENTER( "offset_right_of_center"); const ParameterString<double> DebugImagesPublisher::OFFSET_LEFT_OF_CENTER( "offset_left_of_center"); DebugImagesPublisher::DebugImagesPublisher(const ros::NodeHandle &node_handle, ParameterInterface *parameters) : node_handle_(node_handle), parameters_ptr_(parameters) { parameters->registerParam(PIXEL_WIDTH); parameters->registerParam(OFFSET_BEFORE_CENTER); parameters->registerParam(OFFSET_AFTER_CENTER); parameters->registerParam(OFFSET_RIGHT_OF_CENTER); parameters->registerParam(OFFSET_LEFT_OF_CENTER); } void DebugImagesPublisher::advertise(const std::string &action_name) { rospub_img_debug_ = node_handle_.advertise<sensor_msgs::Image>(action_name + "_img_debug", 1); rospub_birdsview_debug_ = node_handle_.advertise<sensor_msgs::Image>( action_name + "_birdsview_debug", 1); rospub_canny_debug_ = node_handle_.advertise<sensor_msgs::Image>(action_name + "_canny_debug", 1); rospub_area_of_interest_ = node_handle_.advertise<perception_msgs::LookAtRegionsDebug>( action_name + "_areas_of_interest", 1); rospub_img_patch_ = node_handle_.advertise<sensor_msgs::Image>(action_name + "_img_patch", 1); ROS_DEBUG("advertising debug_images for %s-server.", action_name.c_str()); } void DebugImagesPublisher::shutdown() { rospub_img_debug_.shutdown(); rospub_birdsview_debug_.shutdown(); rospub_canny_debug_.shutdown(); rospub_area_of_interest_.shutdown(); } void DebugImagesPublisher::publishDebugImages(const RegionsToClassify &rois, const ros::Time &stamp) { ROS_DEBUG("debug_images size is (%d,%d)", debug_images.getCameraImage()->size().height, debug_images.getCameraImage()->size().width); cv_bridge::CvImage debug_msg; debug_msg.header = std_msgs::Header(); debug_msg.encoding = sensor_msgs::image_encodings::BGR8; debug_msg.image = *debug_images.getCameraImage(); rospub_img_debug_.publish(debug_msg.toImageMsg()); // compose birdsview patches double pixel_width = parameters_ptr_->getParam(PIXEL_WIDTH); // meters double offset_before_center = parameters_ptr_->getParam(OFFSET_BEFORE_CENTER); // meters double offset_after_center = parameters_ptr_->getParam(OFFSET_AFTER_CENTER); // meters double offset_right_of_center = parameters_ptr_->getParam(OFFSET_RIGHT_OF_CENTER); // meters double offset_left_of_center = parameters_ptr_->getParam(OFFSET_LEFT_OF_CENTER); // meters int height = static_cast<int>( std::round((offset_before_center + offset_after_center) / pixel_width)); int width = static_cast<int>( std::round((offset_left_of_center + offset_right_of_center) / pixel_width)); cv::Mat birdsviews = cv::Mat::zeros(height * 2, width * 3, CV_8UC3); for (unsigned int i = 0; i < debug_images.getBirdsviewPatches()->size() && i < 6; i++) { debug_images.getBirdsviewPatches()->at(i).copyTo( birdsviews(cv::Rect((i % 3) * width, (i / 3) * height, width, height))); } cv_bridge::CvImage birdsview_debug_msg; birdsview_debug_msg.header = std_msgs::Header(); birdsview_debug_msg.encoding = sensor_msgs::image_encodings::BGR8; birdsview_debug_msg.image = birdsviews; rospub_birdsview_debug_.publish(birdsview_debug_msg.toImageMsg()); // compose canny patches height = debug_images.getCameraImage()->rows / 2; width = debug_images.getCameraImage()->cols / 3; cv::Mat cannys = cv::Mat::zeros(height * 2, width * 3, CV_8UC3); for (unsigned int i = 0; i < debug_images.getCannyPatches()->size() && i < 6; i++) { const cv::Point p((i % 3) * width, (i / 3) * height); const cv::Rect debug_rect = cv::Rect(p, debug_images.getCannyPatches()->at(i).size()) & cv::Rect(cv::Point(0, 0), cannys.size()); cv::Mat from = debug_images.getCannyPatches()->at(i)( cv::Rect(cv::Point(0, 0), debug_rect.size())); from.copyTo(cannys(debug_rect)); } // publish canny image cv_bridge::CvImage canny_debug_msg; canny_debug_msg.header = std_msgs::Header(); canny_debug_msg.encoding = sensor_msgs::image_encodings::BGR8; canny_debug_msg.image = cannys; rospub_canny_debug_.publish(canny_debug_msg.toImageMsg()); // publish rois perception_msgs::LookAtRegionsDebug debug_rois; debug_rois.header.stamp = stamp; debug_rois.header.frame_id = "world"; debug_rois.regions.reserve(rois.size()); for (const auto &roi : rois) { perception_msgs::LookAtRegionDebug actual; actual.id = roi.id; std::array<cv::Point2f, 4> points = getROIInWorld(roi); for (const cv::Point2f &p : points) { geometry_msgs::Point32 p_msg; p_msg.x = p.x; p_msg.y = p.y; actual.polygon.points.push_back(p_msg); } debug_rois.regions.push_back(actual); } rospub_area_of_interest_.publish(debug_rois); // publish image patches height = debug_images.getCameraImage()->size().height / 2; width = debug_images.getCameraImage()->size().width / 3; ROS_DEBUG("width is %d", width); cv::Mat image_patches = cv::Mat::zeros(height * 2, width * 3, CV_8UC3); for (unsigned int i = 0; i < debug_images.getImagePatches()->size() && i < 6; i++) { const cv::Mat current = debug_images.getImagePatches()->at(i); const cv::Point p((i % 3) * width, (i / 3) * height); const cv::Rect debug_rect = cv::Rect(p.x, p.y, current.size().width, current.size().height); ROS_DEBUG("size of current debug_rect with id #%d is (%d,%d)", i, debug_rect.size().height, debug_rect.size().width); // hier debug rect size wenn gleich wie image dann nimm image cv::Mat from = debug_rect.size().width == current.size().width && debug_rect.size().height == current.size().height ? current : current(cv::Rect(cv::Point(0, 0), debug_rect.size())); ROS_DEBUG("width of from is %d", from.size().width); cv::Mat rescaled; const double scale = static_cast<double>(from.size().width) / static_cast<double>(width); ROS_DEBUG("scale is %f", scale); if (scale > 1) { cv::resize(from, rescaled, cv::Size(width, height)); ROS_DEBUG( "size of rescaled is (%d,%d)", rescaled.size().width, rescaled.size().height); const cv::Rect to(p, rescaled.size()); rescaled.copyTo(image_patches(to)); } else { from.copyTo(image_patches(cv::Rect(p, from.size()))); } } cv_bridge::CvImage image_patches_debug_msg; image_patches_debug_msg.header = std_msgs::Header(); image_patches_debug_msg.encoding = sensor_msgs::image_encodings::BGR8; image_patches_debug_msg.image = image_patches; rospub_img_patch_.publish(image_patches_debug_msg.toImageMsg()); } std::array<cv::Point2f, 4> look_at::DebugImagesPublisher::getROIInWorld( const RegionToClassify &roi_in_world) const { Eigen::Affine3f as_float = roi_in_world.pose.cast<float>(); const Eigen::Matrix3f rotation = as_float.linear(); const cv::RotatedRect roi_as_rect{ cv::Point2f{as_float.translation().x(), as_float.translation().y()}, cv::Size2f{static_cast<float>(roi_in_world.width), static_cast<float>(roi_in_world.height)}, common::toDegree(common::toYaw(rotation))}; std::array<cv::Point2f, 4> ret; roi_as_rect.points(ret.data()); return ret; }; } // namespace look_at
[ "fangnuaa@gmail.com" ]
fangnuaa@gmail.com
4965dc1428faeba5cf22ac5161cee67fcf34a6a2
9befe694264de9828ba9c04b79a418d0c0a653bc
/log_common.cpp
02d9304710e4edae6fa676d66cfaa48944784a3f
[]
no_license
qliang06/log-streamer
319245d8fcf93d9c098eaad4dde5719fc20a500f
5ee9dab99e3af932fb8f1cb3cbce3e2cb20478c3
refs/heads/main
2023-02-23T09:22:39.628777
2021-01-26T05:54:36
2021-01-26T05:54:36
332,985,878
0
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
#include <iostream> #include "log_common.h" namespace datadog_log_analytics { std::ostream& operator<< (std::ostream& os, const LogRecord& record) { os << "IP:" << record.ip << "|" << "rfc:" << record.rfc << "|" << "user:" << record.user << "|" << "timestamp:" << record.timestamp << "|" << "request:" << record.full_request << "|" << "status:" << record.status_code << "|" << "bytes:" << record.bytes; return os; } std::ostream& operator << (std::ostream& os, const AnalysisMeta& data) { os << "Section:" << data.section << "|" << "Section Count:" << data.section_cnt << "|" << "Traffic Bytes:" << data.traffic_bytes << "|" << "Error Count:" << data.error_cnt; return os; } } // namespace datadog_log_analytics
[ "qliang" ]
qliang
cea4348361cc84d0a55e16249a0c0f51c70fe25a
169e75df163bb311198562d286d37aad14677101
/tensorflow/tensorflow/compiler/xla/service/hlo_domain_remover.cc
e2e820002be77201b5bb237d90bbbc31ac178bb9
[ "Apache-2.0" ]
permissive
zylo117/tensorflow-gpu-macosx
e553d17b769c67dfda0440df8ac1314405e4a10a
181bc2b37aa8a3eeb11a942d8f330b04abc804b3
refs/heads/master
2022-10-19T21:35:18.148271
2020-10-15T02:33:20
2020-10-15T02:33:20
134,240,831
116
26
Apache-2.0
2022-10-04T23:36:22
2018-05-21T08:29:12
C++
UTF-8
C++
false
false
4,471
cc
/* Copyright 2018 The TensorFlow Authors. 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 "tensorflow/compiler/xla/service/hlo_domain_remover.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_domain_map.h" #include "tensorflow/compiler/xla/service/hlo_domain_verifier.h" #include "tensorflow/compiler/xla/service/hlo_graph_dumper.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/types.h" namespace xla { class HloDomainRemover::RunContext { public: RunContext(HloModule* module, HloDomainRemover* remover) : module_(module), remover_(remover) {} StatusOr<bool> Run(); private: // Verifies the consistency of the domain, and normalizes the instructions // within it. Status VerifyAndNormalizeDomain(const DomainMetadata::Domain& domain); HloModule* module_; HloDomainRemover* remover_; }; Status HloDomainRemover::RunContext::VerifyAndNormalizeDomain( const DomainMetadata::Domain& domain) { TF_ASSIGN_OR_RETURN(const DomainMetadata* ref_metadata, HloDomainVerifier::VerifyDomain(domain)); if (ref_metadata != nullptr) { VLOG(4) << "Applying domain normalization: " << ref_metadata->ToString(); TF_RETURN_IF_ERROR(ref_metadata->NormalizeInstructions(domain)); } else { // No kDomain instruction was present within this domain, so call the // generic normalization functions and have them apply their heuristic. VLOG(2) << "Applying domain-less normalization"; TF_RETURN_IF_ERROR(remover_->normalizer_(domain)); } return Status::OK(); } StatusOr<bool> HloDomainRemover::RunContext::Run() { VLOG(4) << "Processing metadata domain: '" << remover_->kind_ << "'"; hlo_graph_dumper::MaybeDumpHloModule(*module_, "Before Domain Remover"); int64 removed_domains = 0; for (HloComputation* computation : module_->computations()) { // First create the domain instruciton sets. A domain instruction set is // the set of instructions whose edges never cross a kDomain instruction. TF_ASSIGN_OR_RETURN(std::unique_ptr<HloDomainMap> domain_map, HloDomainMap::Create(computation, remover_->kind_)); // Verify and normalize every domain populated within the map. for (auto& domain : domain_map->GetDomains()) { TF_RETURN_IF_ERROR(VerifyAndNormalizeDomain(*domain)); } // Now remove all the kDomain instructions of the kind specified by the // remover, that are within the currently processed computation from the // graph. for (HloInstruction* instruction : computation->MakeInstructionPostOrder()) { for (HloInstruction* operand : instruction->unique_operands()) { if (domain_map->IsDomainInstruction(operand)) { VLOG(5) << "Removing " << operand->name(); TF_RETURN_IF_ERROR( operand->ReplaceAllUsesWith(operand->mutable_operand(0))); TF_RETURN_IF_ERROR(computation->RemoveInstruction(operand)); ++removed_domains; } } } HloInstruction* root = computation->root_instruction(); if (root != nullptr && domain_map->IsDomainInstruction(root)) { VLOG(5) << "Removing " << root->name(); computation->set_root_instruction(root->mutable_operand(0)); TF_RETURN_IF_ERROR(computation->RemoveInstruction(root)); ++removed_domains; } } VLOG(3) << "Removed " << removed_domains << " kDomain instructions of '" << remover_->kind_ << "' kind"; if (removed_domains > 0) { hlo_graph_dumper::MaybeDumpHloModule(*module_, "After Domain Remover"); } return removed_domains > 0; } StatusOr<bool> HloDomainRemover::Run(HloModule* module) { RunContext run_context(module, this); return run_context.Run(); } } // namespace xla
[ "thomas.warfel@pnnl.gov" ]
thomas.warfel@pnnl.gov
ff1e87f9452c6c2848176f40a57f8c2a70524bb8
2d4d8094dcc810bd01f1e11ff7f29b959f1ac8a6
/src/rttr/detail/variant_associative_view/variant_associative_view_private.h
ece2efa8295d6f0350d0d825e21023a45cefa3e7
[ "MIT" ]
permissive
goops17/rttr
715b980402ad5d2f9713c20b15989af22c69caec
29e6ff94cfd11e066cb00aed58544842534fc75b
refs/heads/master
2021-09-05T20:43:03.356303
2018-01-25T15:14:10
2018-01-25T15:14:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,927
h
/************************************************************************************ * * * Copyright (c) 2014, 2015 - 2017 Axel Menzel <info@rttr.org> * * * * This file is part of RTTR (Run Time Type Reflection) * * License: MIT License * * * * 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 RTTR_VARIANT_ASSOCIATIVE_VIEW_PRIVATE_H_ #define RTTR_VARIANT_ASSOCIATIVE_VIEW_PRIVATE_H_ #include "rttr/variant.h" #include "rttr/argument.h" #include "rttr/instance.h" #include "rttr/associative_mapper.h" namespace rttr { namespace detail { ///////////////////////////////////////////////////////////////////////////////////////// class RTTR_LOCAL variant_associative_view_private { public: variant_associative_view_private() RTTR_NOEXCEPT : m_type(get_invalid_type()), m_key_type(get_invalid_type()), m_value_type(get_invalid_type()), m_container(nullptr), m_get_is_empty_func(associative_container_empty::is_empty), m_get_size_func(associative_container_empty::get_size), m_begin_func(associative_container_empty::begin), m_end_func(associative_container_empty::begin), m_equal_func(associative_container_empty::equal), m_create_func(associative_container_empty::create), m_delete_func(associative_container_empty::destroy), m_get_key_func(associative_container_empty::get_key), m_get_value_func(associative_container_empty::get_value), m_advance_func(associative_container_empty::advance), m_find_func(associative_container_empty::find), m_erase_func(associative_container_empty::erase), m_clear_func(associative_container_empty::clear), m_equal_range_func(associative_container_empty::equal_range), m_insert_func_key(associative_container_empty::insert_key), m_insert_func_key_value(associative_container_empty::insert_key_value) { } template<typename T, typename RawType = raw_type_t<T>, typename ConstType = remove_pointer_t<T>> variant_associative_view_private(const T& container) RTTR_NOEXCEPT : m_type(type::get<RawType>()), m_key_type(type::get<typename associative_container_mapper<RawType>::key_t>()), m_value_type(type::get<conditional_t<std::is_void<typename associative_container_mapper<RawType>::value_t>::value, invalid_type, typename associative_container_mapper<RawType>::value_t>>()), m_container(as_void_ptr(container)), m_get_is_empty_func(associative_container_mapper_wrapper<RawType, ConstType>::is_empty), m_get_size_func(associative_container_mapper_wrapper<RawType, ConstType>::get_size), m_begin_func(associative_container_mapper_wrapper<RawType, ConstType>::begin), m_end_func(associative_container_mapper_wrapper<RawType, ConstType>::end), m_equal_func(associative_container_mapper_wrapper<RawType, ConstType>::equal), m_create_func(associative_container_mapper_wrapper<RawType, ConstType>::create), m_delete_func(associative_container_mapper_wrapper<RawType, ConstType>::destroy), m_get_key_func(associative_container_mapper_wrapper<RawType, ConstType>::get_key), m_get_value_func(associative_container_mapper_wrapper<RawType, ConstType>::get_value), m_advance_func(associative_container_mapper_wrapper<RawType, ConstType>::advance), m_find_func(associative_container_mapper_wrapper<RawType, ConstType>::find), m_erase_func(associative_container_mapper_wrapper<RawType, ConstType>::erase), m_clear_func(associative_container_mapper_wrapper<RawType, ConstType>::clear), m_equal_range_func(associative_container_mapper_wrapper<RawType, ConstType>::equal_range), m_insert_func_key(associative_container_mapper_wrapper<RawType, ConstType>::insert_key), m_insert_func_key_value(associative_container_mapper_wrapper<RawType, ConstType>::insert_key_value) { } RTTR_FORCE_INLINE variant_associative_view_private(const variant_associative_view_private& other) = default; RTTR_FORCE_INLINE ~variant_associative_view_private() { } RTTR_FORCE_INLINE type get_type() const RTTR_NOEXCEPT { return m_type; } RTTR_FORCE_INLINE type get_key_type() const RTTR_NOEXCEPT { return m_key_type; } RTTR_FORCE_INLINE type get_value_type() const RTTR_NOEXCEPT { return m_value_type; } RTTR_FORCE_INLINE void copy(iterator_data& itr_tgt, const iterator_data& itr_src) const { m_create_func(itr_tgt, itr_src); } RTTR_FORCE_INLINE void destroy(iterator_data& itr) const { m_delete_func(itr); } RTTR_FORCE_INLINE void begin(iterator_data& itr) const { m_begin_func(m_container, itr); } RTTR_FORCE_INLINE void end(iterator_data& itr) const { m_end_func(m_container, itr); } RTTR_FORCE_INLINE bool is_empty() const RTTR_NOEXCEPT { return m_get_is_empty_func(m_container); } RTTR_FORCE_INLINE std::size_t get_size() const RTTR_NOEXCEPT { return m_get_size_func(m_container); } RTTR_FORCE_INLINE bool equal(const iterator_data& lhs_itr, const iterator_data& rhs_itr) const RTTR_NOEXCEPT { return m_equal_func(lhs_itr, rhs_itr); } RTTR_INLINE const variant get_key(const iterator_data& itr) const { return m_get_key_func(itr); } RTTR_INLINE const variant get_value(const iterator_data& itr) const { return m_get_value_func(itr); } RTTR_INLINE const std::pair<variant, variant> get_key_value(const iterator_data& itr) const { return {m_get_key_func(itr), m_get_value_func(itr)}; } RTTR_FORCE_INLINE void advance(iterator_data& itr, std::ptrdiff_t index) const { m_advance_func(itr, index); } RTTR_FORCE_INLINE void find(iterator_data& itr, argument& key) { m_find_func(m_container, itr, key); } RTTR_FORCE_INLINE void equal_range(argument& key, iterator_data& itr_begin, detail::iterator_data& itr_end) { m_equal_range_func(m_container, key, itr_begin, itr_end); } RTTR_FORCE_INLINE void clear() { m_clear_func(m_container); } RTTR_INLINE std::size_t erase(argument& key) { return m_erase_func(m_container, key); } RTTR_INLINE bool insert(argument& key, iterator_data& itr) { return m_insert_func_key(m_container, key, itr); } RTTR_INLINE bool insert(argument& key, argument& value, iterator_data& itr) { return m_insert_func_key_value(m_container, key, value, itr); } private: static bool equal_cmp_dummy_func(const iterator_data& lhs_itr, const iterator_data& rhs_itr) RTTR_NOEXCEPT; using equality_func = decltype(&equal_cmp_dummy_func); // workaround because of 'noexcept' can only appear on function declaration using get_is_empty_func = bool(*)(void* container); using get_size_func = std::size_t(*)(void* container); using begin_func = void(*)(void* container, iterator_data& itr); using end_func = void(*)(void* container, iterator_data& itr); using advance_func = void(*)(iterator_data& itr, std::ptrdiff_t index); using create_func = void(*)(iterator_data& itr_tgt, const iterator_data& itr_src); using delete_func = void(*)(iterator_data& itr); using get_key_func = variant (*)(const iterator_data& itr); using get_value_func = variant (*)(const iterator_data& itr); using clear_func = void(*)(void* container); using erase_func = std::size_t(*)(void* container, argument& key); using find_func = void(*)(void* container, detail::iterator_data& itr, argument& key); using equal_range_func = void(*)(void* container, argument& key, detail::iterator_data& itr_begin, detail::iterator_data& itr_end); using insert_func_key = bool(*)(void* container, argument& key, detail::iterator_data& itr); using insert_func_key_value = bool(*)(void* container, argument& key, argument& value, detail::iterator_data& itr); type m_type; type m_key_type; type m_value_type; void* m_container; get_is_empty_func m_get_is_empty_func; get_size_func m_get_size_func; begin_func m_begin_func; end_func m_end_func; equality_func m_equal_func; create_func m_create_func; delete_func m_delete_func; get_key_func m_get_key_func; get_value_func m_get_value_func; advance_func m_advance_func; find_func m_find_func; erase_func m_erase_func; clear_func m_clear_func; equal_range_func m_equal_range_func; insert_func_key m_insert_func_key; insert_func_key_value m_insert_func_key_value; }; } // end namespace detail } // end namespace rttr #endif // RTTR_VARIANT_ASSOCIATIVE_VIEW_PRIVATE_H_
[ "info@axelmenzel.de" ]
info@axelmenzel.de
75d074129c65a6fed7ed7cfbdc024ef8abfb18b6
3b76b2980485417cb656215379b93b27d4444815
/7.Ung dung/Source code/Client/Client/MicPhone.h
819d3977c32b6d3197611fdd545ed9fb125b29d5
[]
no_license
hemprasad/lvmm-sc
48d48625b467b3756aa510b5586af250c3a1664c
7c68d1d3b1489787f5ec3d09bc15b4329b0c087a
refs/heads/master
2016-09-06T11:05:32.770867
2011-07-25T01:09:07
2011-07-25T01:09:07
38,108,101
0
0
null
null
null
null
UTF-8
C++
false
false
754
h
// MicPhone.h: interface for the MicPhone class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_MICPHONE_H__12303AA1_4AF2_11D6_8886_200654C10000__INCLUDED_) #define AFX_MICPHONE_H__12303AA1_4AF2_11D6_8886_200654C10000__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include<mmsystem.h> class MicPhone { public: HMIXER m_mixer; MIXERCAPS mixcap; DWORD mitems,mindex,mcontrolid,mcontype; CString micname,mixname,conname; CStdioFile log; void SetMicrophone(); BOOL openMixer(); BOOL getMicControl(); BOOL selectMic(int value); void closeMixer(); }; #endif // !defined(AFX_MICPHONE_H__12303AA1_4AF2_11D6_8886_200654C10000__INCLUDED_)
[ "funnyamauter@72c74e6c-5204-663f-ea46-ae2a288fd484" ]
funnyamauter@72c74e6c-5204-663f-ea46-ae2a288fd484
e937aa69a6272ed46815c72f07d2d4ec154c67f8
da5bb5e44b56f9c22e3bedb145aaff6a62cfa7b1
/Blob/Blob3/src/Edge.cpp
99ad292766a53d7e225e86dfd17207d1682bc8ea
[]
no_license
r21nomi/of-artwork
0abc1e18aa3c9aafa368d0180e21917c431fbd2d
6aef14cd40cc9e6a171caea3aec4296a3d0f4e49
refs/heads/master
2021-01-24T08:17:41.132581
2017-03-02T00:39:59
2017-03-02T00:39:59
68,909,172
9
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
// // Edge.cpp // Blob2_2 // // Created by 新家 亮太 on 2016/10/26. // // #include "Edge.hpp" Edge::Edge() { } void Edge::update() { } void Edge::draw() { }
[ "ryotakosu@gmail.com" ]
ryotakosu@gmail.com
7063d12c708fd34b0a89dc43c114a308fe838d5b
2e0472397ec7145d50081d4890eb0af2323eb175
/Code/src/OE/UI_OLD/Elements/TreeViewModel.cpp
622aeed364d31591cbc85e52d6b8abdcead77644
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mlomb/OrbitEngine
5c471a853ea555f0738427999dd9cef3a1c90a01
41f053626f05782e81c2e48f5c87b04972f9be2c
refs/heads/master
2021-09-09T01:27:31.097901
2021-08-28T16:07:16
2021-08-28T16:07:16
99,012,019
26
3
null
null
null
null
UTF-8
C++
false
false
154
cpp
#include "OE/UI/Elements/TreeViewModel.hpp" namespace OrbitEngine { namespace UI { Element* TreeViewModel::Build(int depth) { return nullptr; } } }
[ "mlombardo9@gmail.com" ]
mlombardo9@gmail.com
267e8f6e352fdfb19740a46c0bb5f0e2f0734c8e
ee080dbd8517ebc0b621dcb339a818b03749d77f
/head-first-design-pattern/cpp/singleton/chocolate/chocolate_controller.h
faf80852d017b834760a646fac2abad3b800cd5d
[]
no_license
chenjianlong/books-code
b01c92f0cd74861f315a65fa70ad0de729356978
bbbf379db7117d023f68aac1fd39b5846118159e
refs/heads/master
2023-07-21T14:43:46.951799
2023-05-09T03:23:59
2023-05-09T03:23:59
9,493,872
4
3
null
2023-09-07T11:57:37
2013-04-17T09:23:04
C
UTF-8
C++
false
false
427
h
/*! * \file chocolate_controller.h * \brief The Chocolate_Controller class implementation. * \author Jianlong Chen <jianlong99@gmail.com> * \date 2013-05-04 */ /* $Id$ */ #ifndef CHOCOLATE_CONTROLLER_H #define CHOCOLATE_CONTROLLER_H class Chocolate_Controller { public: Chocolate_Controller(); virtual ~Chocolate_Controller(); static int main(int argc, char *argv[]); }; #endif /* CHOCOLATE_CONTROLLER_H */
[ "jianlong99@gmail.com" ]
jianlong99@gmail.com
096e01107568a4a41fbd1fa10e2448e3d79951bc
7176368f9ead00f7e2b7b224d3c197282331b00d
/Test/Parser/DdsParserTest.cpp
9736e0ef76003a66fe3ac9350345338bb5c97629
[ "MIT", "CC-BY-4.0" ]
permissive
netwarm007/GameEngineFromScratch
8793aa1b9581fc0932e7e212c83b9b540ea5dcf5
3907778a1c543dfd38f660e5ffa7950d147c807c
refs/heads/master
2023-08-21T02:25:26.556984
2023-03-07T09:37:28
2023-03-07T09:37:28
100,656,491
1,647
346
NOASSERTION
2023-03-07T09:37:30
2017-08-18T00:28:20
C++
UTF-8
C++
false
false
654
cpp
#include <iostream> #include <string> #include "AssetLoader.hpp" #include "DDS.hpp" using namespace My; int main(int argc, const char** argv) { int error = 0; AssetLoader assetLoader; error = assetLoader.Initialize(); if (!error) { Buffer buf; if (argc >= 2) { buf = assetLoader.SyncOpenAndReadBinary(argv[1]); } else { buf = assetLoader.SyncOpenAndReadBinary( "Textures/hdr/PaperMill_posx.dds"); } DdsParser dds_parser; Image image = dds_parser.Parse(buf); std::cout << image; } assetLoader.Finalize(); return error; }
[ "chenwenli@chenwenli.com" ]
chenwenli@chenwenli.com
56d86fb670f8dd662165593f43037a9835fcf27d
b677894966f2ae2d0585a31f163a362e41a3eae0
/ns3/ns-3.26/src/internet/test/tcp-option-test.cc
2009e0e3825a86a125bd97c76d4bd6904200453a
[ "LicenseRef-scancode-free-unknown", "GPL-2.0-only", "Apache-2.0" ]
permissive
cyliustack/clusim
667a9eef2e1ea8dad1511fd405f3191d150a04a8
cbedcf671ba19fded26e4776c0e068f81f068dfd
refs/heads/master
2022-10-06T20:14:43.052930
2022-10-01T19:42:19
2022-10-01T19:42:19
99,692,344
7
3
Apache-2.0
2018-07-04T10:09:24
2017-08-08T12:51:33
Python
UTF-8
C++
false
false
4,129
cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2014 Natale Patriciello <natale.patriciello@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include "ns3/test.h" #include "ns3/core-module.h" #include "ns3/tcp-option.h" #include "ns3/private/tcp-option-winscale.h" #include "ns3/private/tcp-option-ts.h" #include <string.h> namespace ns3 { class TcpOptionWSTestCase : public TestCase { public: TcpOptionWSTestCase (std::string name, uint8_t scale); void TestSerialize (); void TestDeserialize (); private: virtual void DoRun (void); virtual void DoTeardown (void); uint8_t m_scale; Buffer m_buffer; }; TcpOptionWSTestCase::TcpOptionWSTestCase (std::string name, uint8_t scale) : TestCase (name) { m_scale = scale; } void TcpOptionWSTestCase::DoRun () { TestSerialize (); TestDeserialize (); } void TcpOptionWSTestCase::TestSerialize () { TcpOptionWinScale opt; opt.SetScale (m_scale); NS_TEST_EXPECT_MSG_EQ (m_scale, opt.GetScale (), "Scale isn't saved correctly"); m_buffer.AddAtStart (opt.GetSerializedSize ()); opt.Serialize (m_buffer.Begin ()); } void TcpOptionWSTestCase::TestDeserialize () { TcpOptionWinScale opt; Buffer::Iterator start = m_buffer.Begin (); uint8_t kind = start.PeekU8 (); NS_TEST_EXPECT_MSG_EQ (kind, TcpOption::WINSCALE, "Different kind found"); opt.Deserialize (start); NS_TEST_EXPECT_MSG_EQ (m_scale, opt.GetScale (), "Different scale found"); } void TcpOptionWSTestCase::DoTeardown () { } class TcpOptionTSTestCase : public TestCase { public: TcpOptionTSTestCase (std::string name); void TestSerialize (); void TestDeserialize (); private: virtual void DoRun (void); virtual void DoTeardown (void); uint32_t m_timestamp; uint32_t m_echo; Buffer m_buffer; }; TcpOptionTSTestCase::TcpOptionTSTestCase (std::string name) : TestCase (name) { } void TcpOptionTSTestCase::DoRun () { Ptr<UniformRandomVariable> x = CreateObject<UniformRandomVariable> (); for (uint32_t i = 0; i < 1000; ++i) { m_timestamp = x->GetInteger (); m_echo = x->GetInteger (); TestSerialize (); TestDeserialize (); } } void TcpOptionTSTestCase::TestSerialize () { TcpOptionTS opt; opt.SetTimestamp (m_timestamp); opt.SetEcho (m_echo); NS_TEST_EXPECT_MSG_EQ (m_timestamp, opt.GetTimestamp (), "TS isn't saved correctly"); NS_TEST_EXPECT_MSG_EQ (m_echo, opt.GetEcho (), "echo isn't saved correctly"); m_buffer.AddAtStart (opt.GetSerializedSize ()); opt.Serialize (m_buffer.Begin ()); } void TcpOptionTSTestCase::TestDeserialize () { TcpOptionTS opt; Buffer::Iterator start = m_buffer.Begin (); uint8_t kind = start.PeekU8 (); NS_TEST_EXPECT_MSG_EQ (kind, TcpOption::TS, "Different kind found"); opt.Deserialize (start); NS_TEST_EXPECT_MSG_EQ (m_timestamp, opt.GetTimestamp (), "Different TS found"); NS_TEST_EXPECT_MSG_EQ (m_echo, opt.GetEcho (), "Different echo found"); } void TcpOptionTSTestCase::DoTeardown () { } static class TcpOptionTestSuite : public TestSuite { public: TcpOptionTestSuite () : TestSuite ("tcp-option", UNIT) { for (uint8_t i = 0; i < 15; ++i) { AddTestCase (new TcpOptionWSTestCase ("Testing window " "scale value", i), TestCase::QUICK); } AddTestCase (new TcpOptionTSTestCase ("Testing serialization of random values for timestamp"), TestCase::QUICK); } } g_TcpOptionTestSuite; } // namespace ns3
[ "you@example.com" ]
you@example.com
643f56020cdf505a6e43518207756b785d81fdc0
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function13728/function13728_schedule_21/function13728_schedule_21.cpp
ba77ee2e39cc4fd9960b148cbc16a964b4d7ef0d
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,048
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function13728_schedule_21"); constant c0("c0", 256), c1("c1", 2048), c2("c2", 128); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i100("i100", 1, c0 - 1), i101("i101", 1, c1 - 1), i102("i102", 1, c2 - 1), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06"); input input0("input0", {i0, i1, i2}, p_int32); computation comp0("comp0", {i100, i101, i102}, (input0(i100, i101, i102) + input0(i100 + 1, i101, i102) - input0(i100 - 1, i101, i102))); comp0.tile(i100, i101, i102, 64, 32, 32, i01, i02, i03, i04, i05, i06); comp0.parallelize(i01); buffer buf00("buf00", {256, 2048, 128}, p_int32, a_input); buffer buf0("buf0", {256, 2048, 128}, p_int32, a_output); input0.store_in(&buf00); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf0}, "../data/programs/function13728/function13728_schedule_21/function13728_schedule_21.o"); return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
8b99f5c9182c7d1d64d90b4342f2d6c10aa00bee
1c53c58be8e0a57604b161a7a820001ed8b6e7b0
/Puzzle_Sliding_Animation/game.h
6253a205ca1dab801b7459ad01c1fe143bb6dfe4
[]
no_license
atomic/Sliding_Puzzle
747a6f19b6e9de2ddcc33d999cb8002d75fd48aa
a8edc5c009877412b598e53ac4c1f7259f5ce064
refs/heads/master
2020-06-03T05:52:12.227319
2015-03-24T20:08:44
2015-03-24T20:08:44
31,629,930
0
1
null
2015-03-24T08:18:46
2015-03-04T00:51:15
C++
UTF-8
C++
false
false
4,816
h
#ifndef GAME_H #define GAME_H #include <SFML/Graphics.hpp> #include <cstdlib> #include <iostream> enum Direction { Up = -3, Down = 3, Left = -1, Right = 1 }; using namespace std; class Game : private sf::NonCopyable { public: Game(); void run(); void reset(bool clearInput = true, bool clearSolution = true); private: void processEvents(); void update(sf::Time elapsedTime); bool prepareSolution(); /// input -> solution -> ready for animate void syncConfigInput(); /// sync display grid with input void activateAnimation(); /// setting up animation mode void changeSession(); /// A function to randomize, solve, and animate void prepareAnimation(sf::Time elapsedTime); /// render each iteration void render(); // inputs void handlePlayerInput(sf::Keyboard::Key key, bool isPressed); void handleNumberInput(sf::Keyboard::Key key); void getRandomInput(); // helper void arrangeGrid(); bool isSequenceComplete() { return mStep == mSolution.length(); }; void proceedSequence(); /// prepare for next animation sequence void updateNextGrid(); /// intersession between one animation to another void intSwap(int &A, int &B) { int temp = B; B = A; A = temp; } // Controller void switchContinous(); /** * @brief functio will takes a character and find out which position to move, * and what direction */ pair<int,Direction> getIndexBoxToMove(int &zero, const char &c) { switch (c) { case 'D': zero += 3; return pair<int, Direction>(zero, Up); break; case 'U': zero -= 3; return pair<int, Direction>(zero, Down); break; case 'L': zero -= 1; return pair<int, Direction>(zero, Right); break; case 'R': zero += 1; return pair<int, Direction>(zero, Left); break; default: break; } throw logic_error("ERROR: No index to move"); }; private: static const sf::Vector2f SCREENSIZE; static const int GDim; static const int GSIZE; sf::RenderWindow mWindow; // Resources sf::Font mFontGui; sf::Texture mTextureBox; // my sprite vector<sf::Sprite> mSpriteBoxes; // Shapes static const sf::Vector2f GridPos; static const int FrameThickness; sf::RectangleShape mBoxCombInput; sf::RectangleShape mBoxSolution; sf::RectangleShape mBoxPuzzleFrame; sf::RectangleShape mBoxOff; sf::RectangleShape mBoxOn; // direction notices does not need boxes sf::Text mTextInput; sf::Text mTextSolution; sf::Text mTextDirection; sf::Text mTextYekun; sf::Text mTextAlex; sf::Text mTextLoop; sf::Text mTextOnOff; // Animation static const sf::Time TimePerFrame; static const int AnimSpeed; sf::Transform mTranslateBox; float mFrameStepDone; // For one frame bool mIsAnimating; size_t mStep; // For iteration swapping size_t aStep; // For animation, ahead of mStep vector<pair<int,Direction>> mMovingSequence; vector<int> mZeroIndexes; // just to make swapping easier int mIndexToAnimate; Direction mIndexDirection; // Display int mDelayTime; // to make the delay for some color changes(number in terms of frames?) int mDelayPassed; // to make the delay for some color changes bool mIsResetingDone; int mPhaseCode; // this is used handle the phase in reseting new game // -1 : no reset session, else handle it by calling newSession(); // LOGIC Part string mStrInput; int ** mConfiguration; string mSolution; bool mYekunWay; // 2 different approaches bool mIsGettingInput; bool mHasSolutionReady; bool mIsContinous; // to make the puzzle randomize and run by itself }; #endif // GAME_H /// Notes: /// 1.Unvoled sequences /// 470586312 (28 steps) /// 2. Performance Comparison /// 427168035 (Yekun : 26 steps in ~4 seconds, 26 steps in ~7 seconds)
[ "atomictheorist@gmail.com" ]
atomictheorist@gmail.com
32f9ff2e07951ca094d9aef83cc1a1465ca37119
35edbf6c68b0a405cedd068311f39c293cf1f3a8
/Classes/Slide7.cpp
825971ffc618fea734cadc8a404a28bb9a50eb47
[]
no_license
Biswajit-MobileDeveloper/StoryBook
28375e52bdabd856f5e27e9884a6961403c4975c
24397973091f226bd7b0d180db3c857c0893f3f7
refs/heads/master
2021-01-13T00:59:14.247228
2015-11-25T10:38:11
2015-11-25T10:38:11
46,854,791
0
0
null
null
null
null
UTF-8
C++
false
false
4,745
cpp
// // Slide7.cpp // JoshEmma // // Created by Biswajit Paul on 04/11/15. // // #include "Slide7.h" #include "GameSettings.h" #include "GameConfig.h" #include "Slide6.h" #include "Slide8.h" #include "BridgeIOS.h" USING_NS_CC; CCScene* Slide7::scene() { CCScene *scene = CCScene::create(); Slide7 *layer = Slide7::create(); scene->addChild(layer); return scene; } bool Slide7::init() { if ( !CCLayer::init()) { return false; } this->setTouchEnabled(true); createBg(); createMenu(); return true; } void Slide7::createBg() { newSprite("slide07-background", G_SWIDTH/2, G_SHEIGHT/2, this, -1, RATIO_XY); joshandEmmaSprite = newSprite("slide07-joshemma", G_SWIDTH/2, getY(480), this, 0, RATIO_XY); lbFirst = newLabel("Now the train runs along the beach. Josh and Emma put their..", "Arial", 35, G_SWIDTH/2, getY(530), this, 1, RATIO_X); lbFirst->setOpacity(0); lbSecond = newLabel("hands up to feel the wind as they speed along.", "Arial", 35, G_SWIDTH/2, getY(580), this, 1, RATIO_X); lbSecond->setOpacity(0); labelBackgroundSprite = newSprite("white-1-pixel", G_SWIDTH/2, getY(530), this, 0, RATIO_XY); labelBackgroundSpriteForlabel2 = newSprite("white-1-pixel", G_SWIDTH/2, getY(580), this, 0, RATIO_XY); CCSize labelSize = lbFirst->getContentSize(); CCSize labelSize2 = lbSecond->getContentSize(); labelBackgroundSprite->setScaleX(labelSize.width); labelBackgroundSprite->setScaleY(35); // labelBackgroundSprite->setOpacity(30); labelBackgroundSpriteForlabel2->setScaleX(labelSize2.width); labelBackgroundSpriteForlabel2->setScaleY(35); // labelBackgroundSpriteForlabel2->setOpacity(30); labelBackgroundSpriteForlabel2->setVisible(false); labelBackgroundSprite->setVisible(false); lbFirst->runAction(CCSequence::create(CCDelayTime::create(1.0f), CCCallFunc::create(this,callfunc_selector(Slide7::playEffect1)), CCFadeIn::create(0.5f), CCCallFunc::create(this,callfunc_selector(Slide7::SetvisibilityForTextBackground1)), NULL)); lbSecond->runAction(CCSequence::create(CCDelayTime::create(5.0f), CCFadeIn::create(0.5f), CCCallFunc::create(this,callfunc_selector(Slide7::SetvisibilityForTextBackground2)), NULL)); } void Slide7::playEffect1() { SimpleAudioEngine::sharedEngine()->playBackgroundMusic("Train_07_a.mp3"); } void Slide7::playEffect2(){ SimpleAudioEngine::sharedEngine()->playBackgroundMusic("Train_02_b_whistle.mp3"); if(g_bAuto){ this->runAction(CCSequence::create(CCDelayTime::create(2.f),CCCallFunc::create(this, callfunc_selector(Slide7::onNext)),NULL)); } } void Slide7::SetvisibilityForTextBackground1() { labelBackgroundSprite->setVisible(true); } void Slide7::SetvisibilityForTextBackground2() { labelBackgroundSpriteForlabel2->setVisible(true); } void Slide7::createMenu() { btnBack = newButton("back", getX(100), getY(600), this, menu_selector(Slide7::onBack), false, RATIO_X); btnNext = newButton("next", G_SWIDTH - getX(100), getY(600), this, menu_selector(Slide7::onNext), false, RATIO_X); CCMenuItemImage *btnHome = newButton("home", getX(100), getY(70), this, menu_selector(Slide7::onHome), false, RATIO_X); // btnHome->setOpacity(120); menu = CCMenu::create(btnNext,btnBack, btnHome, NULL); menu->setPosition(ccp(0, 0)); this->addChild(menu, 0); } void Slide7::onHome() { BridgeIOS::showHomeAlert(); } void Slide7::onBack(){ SimpleAudioEngine::sharedEngine()->stopAllEffects(); SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(); SimpleAudioEngine::sharedEngine()->playEffect("page_flip.wav"); CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::create(1.0f,Slide6::scene(), true)); } void Slide7::onNext(){ SimpleAudioEngine::sharedEngine()->stopAllEffects(); SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(); SimpleAudioEngine::sharedEngine()->playEffect("page_flip.wav"); CCDirector::sharedDirector()->replaceScene(CCTransitionPageTurn::create(1.0f, Slide8::scene(), false)); } void Slide7::registerWithTouchDispatcher() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true); } bool Slide7::ccTouchBegan(cocos2d::CCTouch *touch, cocos2d::CCEvent *event) { CCPoint touchLocation = touch->getLocationInView(); touchLocation = CCDirector::sharedDirector()->convertToGL(touchLocation); if( joshandEmmaSprite->boundingBox().containsPoint(touchLocation)) { joshandEmmaSprite->stopAllActions(); SimpleAudioEngine::sharedEngine()->stopAllEffects(); SimpleAudioEngine::sharedEngine()->playEffect("laugh.wav"); } return false; }
[ "biswajit.p@digitalaptech.com" ]
biswajit.p@digitalaptech.com
2538ee6dbcb2f218b8571a7f594758e8801c0ced
800a248fb7532f90119b5d0c3516dc457df7d335
/day3_2/day3_2.cpp
a1ed0293e59cf168b0e134d4229d02a01b11d6b8
[]
no_license
Hyo-gyeong/C_special-lecture_Day3
0b10e0cc4247bbaa4acc441026ef4d2ba86b1d85
f91378420ac0a3ad7c00bc161cd6d1ccb68fb397
refs/heads/master
2020-06-22T11:08:24.082195
2019-07-19T04:55:12
2019-07-19T04:55:12
197,704,330
0
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
#include <stdio.h> int min (int num1, int num2); int getGCD(int num1, int num2, int num3); int main(void) { int n1, n2, n3; printf("Enter a number: "); scanf("%d", &n1); printf("Enter a number: "); scanf("%d", &n2); printf("Enter a number: "); scanf("%d", &n3); printf("GCD is %d\n", getGCD(n1, n2, n3)); } int min (int num1, int num2) { int bigger; bigger = (num1 > num2) ? num1 : num2; return bigger; } int getGCD(int num1, int num2, int num3) { int i, mini; int gcd; mini = min(min(num1,num2), num3); for (i = mini; i >= 1; i--) { if (num1 % i == 0 && num2 % i == 0 && num3 % i == 0) { gcd = i; break; } } return gcd; }
[ "cdkrcd8@gmail.com" ]
cdkrcd8@gmail.com
ea31861a007b413f48bab54438dfb37b1ac558e6
eb1fe618bf14cd50bf5de3bd075a1ebecd8392f7
/include/cppcoro/stdcoro.hpp
f7c0ff1dacd6a802f3a8190186edd3ca18a056a8
[ "MIT" ]
permissive
PazerOP/cppcoro
436dcb9a69f273ea0e1dda092ef674052b121d08
19c9e6801518554911fc34557b38304dfe62b99f
refs/heads/master
2023-01-10T12:17:26.785939
2020-11-16T06:03:05
2020-11-16T06:03:05
285,188,749
0
0
MIT
2020-08-05T05:30:49
2020-08-05T05:26:18
null
UTF-8
C++
false
false
490
hpp
#ifndef CPPCORO_STDCORO_HPP_INCLUDED #define CPPCORO_STDCORO_HPP_INCLUDED #include <filesystem> #ifdef HAS_STD_COROUTINE_HEADER #include <coroutine> namespace stdcoro = std; #else #include <experimental/coroutine> namespace stdcoro = std::experimental; #endif #ifdef HAS_STD_FILESYSTEM_HEADER #include <filesystem> namespace stdfs = std::filesystem; #else #include <experimental/filesystem> namespace stdfs = std::experimental::filesystem; #endif #endif // CPPCORO_STDCORO_HPP_INCLUDED
[ "garcia.6l20@gmail.com" ]
garcia.6l20@gmail.com
5e2a09af240b7d0e1c01613024cc6d4aa9cd0502
58038f168eec402024cc33594dcd395438af1d51
/chromeos/constants/chromeos_features.h
55803e354df3121fddd405aaa6ef649bf8ddde10
[ "BSD-3-Clause" ]
permissive
Esty12/chromium
ae08cff5869b634f8b4c1d11814c7807907d7eb0
ce25b7b60aa5f00ddc8f5a076c700e7fd5bd8a33
refs/heads/master
2022-11-25T12:34:56.698704
2020-08-19T08:51:26
2020-08-19T08:51:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,687
h
// Copyright 2018 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. #ifndef CHROMEOS_CONSTANTS_CHROMEOS_FEATURES_H_ #define CHROMEOS_CONSTANTS_CHROMEOS_FEATURES_H_ #include "base/component_export.h" #include "base/feature_list.h" namespace chromeos { namespace features { // All features in alphabetical order. The features should be documented // alongside the definition of their values in the .cc file. If a feature is // being rolled out via Finch, add a comment in the .cc file. COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAllowScrollSettings; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAmbientModeFeature; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAmbientModePhotoPreviewFeature; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kArcAdbSideloadingFeature; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kArcManagedAdbSideloadingSupport; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kArcPreImeKeyEventSupport; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAutoScreenBrightness; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAssistAutoCorrect; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAssistPersonalInfo; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kAvatarToolbarButton; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kBetterUpdateScreen; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kBluetoothAggressiveAppearanceFilter; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kBluetoothFixA2dpPacketSize; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kBluetoothPhoneFilter; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kBluetoothNextHandsfreeProfile; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCameraSystemWebApp; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCdmFactoryDaemon; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kChildSpecificSignin; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniPortForwarding; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniDiskResizing; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniUseBusterImage; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniGpuSupport; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniUsbAllowUnsupported; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniUseDlc; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kDisableCryptAuthV1DeviceSync; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCryptAuthV2DeviceActivityStatus; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCrostiniWebUIUpgrader; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCryptAuthV2DeviceSync; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kCryptAuthV2Enrollment; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kDisableOfficeEditingComponentApp; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kDiscoverApp; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kDriveFs; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kDriveFsBidirectionalNativeMessaging; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kDriveFsMirroring; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEmojiSuggestAddition; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEolWarningNotifications; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEduCoexistence; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEduCoexistenceConsentLog; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kExoPointerLock; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFilesNG; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFilesSWA; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFilesTransferDetails; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFilesZipMount; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFilesZipPack; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFilesZipUnpack; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kMojoDBusRelay; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kClipboardHistory; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kEnableImeSandbox; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFsNosymfollow; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kGaiaActionButtons; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kGamepadVibration; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kGesturePropertiesDBusService; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kHelpAppFirstRun; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kHelpAppReleaseNotes; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kHelpAppSearchServiceIntegration; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kImeInputLogicHmm; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kImeInputLogicFst; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kImeInputLogicMozc; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kImeOptionsInSettings; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kVirtualKeyboardFloatingDefault; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kInstantTethering; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kLacrosSupport; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kLanguageSettingsUpdate; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kLoginDeviceManagementDisclosure; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kLoginDisplayPasswordButton; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kMediaApp; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kMinimumChromeVersion; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kNativeRuleBasedTyping; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kNewOsSettingsSearch; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kOobeScreensPriority; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kOsSettingsDeepLinking; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kOsSettingsPolymer3; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kParentalControlsSettings; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kPhoneHub; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kPluginVmShowCameraPermissions; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kPluginVmShowMicrophonePermissions; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kPrintJobManagementApp; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kPrintSaveToDrive; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kPrinterStatus; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kQuickAnswers; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kQuickAnswersDogfood; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kQuickAnswersRichUi; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kQuickAnswersTextAnnotator; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kQuickAnswersSubToggle; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kQuickAnswersTranslation; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kReleaseNotes; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kReleaseNotesNotification; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFiltersInRecents; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kScanningUI; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSessionManagerLongKillTimeout; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kShelfHotseat; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kShowBluetoothDebugLogToggle; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kShowBluetoothDeviceBattery; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kShowPlayInDemoMode; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kShowStepsInDemoModeSetup; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSmartDimExperimentalComponent; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSmartDimNewMlAgent; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSmartDimModelV3; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSplitSettingsSync; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kSuggestedContentToggle; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kTelemetryExtension; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kUnifiedMediaView; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kUpdatedCellularActivationUi; // Visible for testing. Call UseBrowserSyncConsent() to check the flag. COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kUseBrowserSyncConsent; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kUseMessagesStagingUrl; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kUserActivityPrediction; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kUseSearchClickForRightClick; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kViewBasedMultiprofileLogin; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kVirtualKeyboardBorderedKey; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kVirtualKeyboardFloatingResizable; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kImeMozcProto; // Keep alphabetized. COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsAmbientModeEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsAmbientModePhotoPreviewEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsAssistantEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsBetterUpdateEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsChildSpecificSigninEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsDeepLinkingEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsEduCoexistenceEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsImeSandboxEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsInstantTetheringBackgroundAdvertisingSupported(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsLacrosSupportEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsLoginDeviceManagementDisclosureEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsLoginDisplayPasswordButtonEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsMinimumChromeVersionEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsClipboardHistoryEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsOobeScreensPriorityEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsParentalControlsSettingsEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsPhoneHubEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersDogfood(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersRichUiEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersSettingToggleEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersTextAnnotatorEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsQuickAnswersTranslationEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsSplitSettingsSyncEnabled(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool IsViewBasedMultiprofileLoginEnabled(); // TODO(michaelpg): Remove after M71 branch to re-enable Play Store by default. COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool ShouldShowPlayStoreInDemoMode(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool ShouldUseBrowserSyncConsent(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool ShouldUseV1DeviceSync(); COMPONENT_EXPORT(CHROMEOS_CONSTANTS) bool ShouldUseV2DeviceSync(); // Keep alphabetized. } // namespace features } // namespace chromeos #endif // CHROMEOS_CONSTANTS_CHROMEOS_FEATURES_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
af4f9bbf1efc2139f49b0fbb4478983813329595
a9e224a95e42a9a5eddddfada7843e518d75408f
/2357/main.cpp
5b2aab8a476fd05c825e207c7f958d8474dc06c8
[]
no_license
WoodJohn/Algorithm-Practice
6b39619ce34faf34be48d8e928a729f8739c6e9a
4e7f6e3b090d3492ed53d479d0672830912eca5f
refs/heads/master
2020-04-27T21:39:30.288108
2012-11-11T12:03:22
2012-11-11T12:03:22
4,083,583
1
0
null
null
null
null
UTF-8
C++
false
false
1,177
cpp
#include <iostream> #include <string.h> using namespace std; int n; char g[35][35]; bool v[35][35]; int sum; void ff(int x, int y) { v[x][y] = true; if (x > 0 && !v[x - 1][y] && g[x - 1][y] == '.') ff(x - 1, y); if (y > 0 && !v[x][y - 1] && g[x][y - 1] == '.') ff(x, y - 1); if (x < n - 1 && !v[x + 1][y] && g[x + 1][y] == '.') ff(x + 1, y); if (y < n - 1 && !v[x][y + 1] && g[x][y + 1] == '.') ff(x, y + 1); } void calc() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (v[i][j]) { if (i == 0 || g[i - 1][j] == '#') sum++; if (j == 0 || g[i][j - 1] == '#') sum++; if (i == n - 1 || g[i + 1][j] == '#') sum++; if (j == n - 1 || g[i][j + 1] == '#') sum++; } } } } int main() { cin >> n; for (int i = 0; i < n; i++) cin >> g[i]; memset(v, false, sizeof(v)); ff(0, 0); ff(n - 1, n - 1); sum = 0; calc(); cout << (sum - 4) * 9 << endl; return 0; }
[ "standingback@gmail.com" ]
standingback@gmail.com
3f908e1e286a54f062014a6c56272054bee78111
e1d6417b995823e507a1e53ff81504e4bc795c8f
/gbk/client/ClientLib/Tools/MrSmith/MrSmith/PacketHandle/GCPlayerRealMoveHandler.cpp
ee19223be57b19d4306ff5b827fa872674a2757a
[]
no_license
cjmxp/pap_full
f05d9e3f9390c2820a1e51d9ad4b38fe044e05a6
1963a8a7bda5156a772ccb3c3e35219a644a1566
refs/heads/master
2020-12-02T22:50:41.786682
2013-11-15T08:02:30
2013-11-15T08:02:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include "StdAfx.h" #include "GCPlayerRealMove.h" using namespace Packets; UINT GCPlayerRealMoveHandler::Execute(GCPlayerRealMove* pPacket, Player*) { return PACKET_EXE_CONTINUE; }
[ "viticm@126.com" ]
viticm@126.com
11259ad16ea45f5bba9da4e20a6412aa66168d80
099f2181439ba42a5fbeb774a182faf3db9bad8c
/problems/044-wildcard-matching.cpp
802b5dfc975ff63752be12dd10ef27724bfea9ef
[]
no_license
luchenqun/leet-code
76a9193e315975b094225d15f0281d0d462c2ee7
38b3f660e5173ad175b8451a730bf4ee3f03a66b
refs/heads/master
2021-07-09T09:49:36.068938
2019-01-15T07:15:22
2019-01-15T07:15:22
102,130,497
1
0
null
null
null
null
UTF-8
C++
false
false
1,521
cpp
/* * [44] Wildcard Matching * * https://leetcode-cn.com/problems/wildcard-matching/description/ * https://leetcode.com/problems/wildcard-matching/discuss/ * * algorithms * Hard (15.30%) * Total Accepted: 353 * Total Submissions: 2.3K * Testcase Example: '"aa"\n"a"' * * 给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。 * '?' 可以匹配任何单个字符。 * '*' 可以匹配任意字符串(包括空字符串)。 * 两个字符串完全匹配才算匹配成功。 * 说明: * s 可能为空,且只包含从 a-z 的小写字母。 * p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。 * 示例 1: * 输入: * s = "aa" * p = "a" * 输出: false * 解释: "a" 无法匹配 "aa" 整个字符串。 * 示例 2: * 输入: * s = "aa" * p = "*" * 输出: true * 解释: '*' 可以匹配任意字符串。 * 示例 3: * 输入: * s = "cb" * p = "?a" * 输出: false * 解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。 * 示例 4: * 输入: * s = "adceb" * p = "*a*b" * 输出: true * 解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce". * 示例 5: * 输入: * s = "acdcb" * p = "a*c?b" * 输入: false */ #include <iostream> #include <string> using namespace std; class Solution { public: bool isMatch(string s, string p) { } }; int main() { Solution s; return 0; }
[ "luchenqun@juzix.io" ]
luchenqun@juzix.io
0e593c8bbf721c0329da911aa68fe857a384f8e8
8f7f38b784c52f43e44973bdf58bed20b62e0ccd
/labs/lab3/lib/ArduinoJson/src/ArduinoJson/Data/JsonFloat.hpp
2d37a974f01cad000f8a51f13a043ac2b5ddd5c5
[ "MIT" ]
permissive
toolboc/particle-azure-workshop-2019
a2ced948ef945821198840271c5584d957ac59fb
b0ce4f0a9271e7bc0915b13f2f69298ed07852a2
refs/heads/master
2020-09-09T20:41:13.768591
2019-11-13T22:57:26
2019-11-13T22:57:26
221,563,547
1
0
MIT
2019-11-13T22:57:28
2019-11-13T22:27:42
null
UTF-8
C++
false
false
295
hpp
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #pragma once #include "../Configuration.hpp" namespace ArduinoJson { namespace Internals { #if ARDUINOJSON_USE_DOUBLE typedef double JsonFloat; #else typedef float JsonFloat; #endif } }
[ "bsatrom@gmail.com" ]
bsatrom@gmail.com
5b79a0ab0cd20b612572233144dbb173722d8850
c52d54c5a27e2829170edbd82ac74a8a22521b7a
/3rdParty/src/OpenGl/OpenGl_AspectText.cxx
98cc48430a0b3dee4109131e228a7d92b3713654
[]
no_license
ZHKang/NTU_OCCT_v2
a011c4799c3b6bbec7f339d46fefbaf858841ff7
6b2efc9ca9519ee5702d04ed843523e58c18f4da
refs/heads/master
2021-01-09T20:38:25.425411
2016-06-06T09:48:16
2016-06-06T09:48:16
60,387,611
0
0
null
null
null
null
UTF-8
C++
false
false
4,729
cxx
// Created on: 2011-07-13 // Created by: Sergey ZERCHANINOV // Copyright (c) 2011-2013 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #include <Graphic3d_ShaderProgram.hxx> #include <OpenGl_AspectText.hxx> #include <OpenGl_Context.hxx> #include <OpenGl_Workspace.hxx> #include <OpenGl_ShaderManager.hxx> #include <OpenGl_ShaderProgram.hxx> namespace { static const TEL_COLOUR TheDefaultColor = {{ 1.0F, 1.0F, 1.0F, 1.0F }}; static const TCollection_AsciiString THE_EMPTY_KEY; }; // ======================================================================= // function : OpenGl_AspectText // purpose : // ======================================================================= OpenGl_AspectText::OpenGl_AspectText() : myFont ("Courier") , myColor (TheDefaultColor), mySubtitleColor (TheDefaultColor), myAngle (0.0f), myStyleType (Aspect_TOST_NORMAL), myDisplayType (Aspect_TODT_NORMAL), myFontAspect (Font_FA_Regular), myZoomable (false), myShaderProgram() { // } // ======================================================================= // function : ~OpenGl_AspectText // purpose : // ======================================================================= OpenGl_AspectText::~OpenGl_AspectText() { // } // ======================================================================= // function : SetAspect // purpose : // ======================================================================= void OpenGl_AspectText::SetAspect (const CALL_DEF_CONTEXTTEXT& theAspect) { myFont = theAspect.Font; myColor.rgb[0] = (float )theAspect.Color.r; myColor.rgb[1] = (float )theAspect.Color.g; myColor.rgb[2] = (float )theAspect.Color.b; myColor.rgb[3] = 1.0f; mySubtitleColor.rgb[0] = (float )theAspect.ColorSubTitle.r; mySubtitleColor.rgb[1] = (float )theAspect.ColorSubTitle.g; mySubtitleColor.rgb[2] = (float )theAspect.ColorSubTitle.b; mySubtitleColor.rgb[3] = 1.0f; myAngle = (float )theAspect.TextAngle; myStyleType = (Aspect_TypeOfStyleText )theAspect.Style; myDisplayType = (Aspect_TypeOfDisplayText )theAspect.DisplayType; myFontAspect = (Font_FontAspect )theAspect.TextFontAspect; myZoomable = (theAspect.TextZoomable != 0); // update resource bindings myShaderProgram = theAspect.ShaderProgram; const TCollection_AsciiString& aShaderKey = myShaderProgram.IsNull() ? THE_EMPTY_KEY : myShaderProgram->GetId(); if (aShaderKey.IsEmpty() || myResources.ShaderProgramId != aShaderKey) { myResources.ResetShaderReadiness(); } } // ======================================================================= // function : Render // purpose : // ======================================================================= void OpenGl_AspectText::Render (const Handle(OpenGl_Workspace)& theWorkspace) const { theWorkspace->SetAspectText (this); } // ======================================================================= // function : Release // purpose : // ======================================================================= void OpenGl_AspectText::Release (OpenGl_Context* theContext) { if (!myResources.ShaderProgram.IsNull() && theContext) { theContext->ShaderManager()->Unregister (myResources.ShaderProgramId, myResources.ShaderProgram); } myResources.ShaderProgramId.Clear(); myResources.ResetShaderReadiness(); } // ======================================================================= // function : BuildShader // purpose : // ======================================================================= void OpenGl_AspectText::Resources::BuildShader (const Handle(OpenGl_Context)& theCtx, const Handle(Graphic3d_ShaderProgram)& theShader) { if (!theCtx->IsGlGreaterEqual (2, 0)) { return; } // release old shader program resources if (!ShaderProgram.IsNull()) { theCtx->ShaderManager()->Unregister (ShaderProgramId, ShaderProgram); ShaderProgramId.Clear(); ShaderProgram.Nullify(); } if (theShader.IsNull()) { return; } theCtx->ShaderManager()->Create (theShader, ShaderProgramId, ShaderProgram); }
[ "kzh7103@hotmail.com" ]
kzh7103@hotmail.com
492990e170f8efaca8eede2c686ee4a516768f52
a2207c02b1644a0092912d453547c3d78fd12454
/Project_03 Translate Python to Cpp/helpers.cpp
6db87481a181e9a6a3dec1e383f56b04bc160fef
[]
no_license
amdee/Intro-to-Self-Driving-Cars-Nanodegree-Udacity
a90b8c5dbbc4e44e2e32a09c48d909aa89e11491
1b75fbac288710f3d9cde49568850cef342ed9da
refs/heads/master
2020-05-21T07:54:32.980762
2019-05-10T10:29:03
2019-05-10T10:29:03
185,967,555
7
4
null
null
null
null
UTF-8
C++
false
false
6,701
cpp
/** helpers.cpp Purpose: helper functions which are useful when implementing a 2-dimensional histogram filter. This file is incomplete! Your job is to make the normalize and blur functions work. Feel free to look at helper.py for working implementations which are written in python. */ #include <vector> #include <iostream> #include <cmath> #include <string> #include <fstream> // #include "debugging_helpers.cpp" using namespace std; /** TODO - implement this function Normalizes a grid of numbers. @param grid - a two dimensional grid (vector of vectors of floats) where each entry represents the unnormalized probability associated with that grid cell. @return - a new normalized two dimensional grid where the sum of all probabilities is equal to one. */ vector<vector<float> >normalize(vector<vector<float> > grid) { float sum_ofgrid = 0.f; for(size_t i=0; i<grid.size(); ++i) { const vector<float> &cell = grid[i]; for(size_t j=0; j<cell.size(); ++j) { sum_ofgrid += cell[j]; } } if (sum_ofgrid == 0.f) { throw std::logic_error("division by zero error"); } const float mult_const = 1.f/sum_ofgrid; vector<vector<float> > newGrid; vector<float> newRow; for(size_t i=0; i<grid.size(); ++i) { const vector<float> &cell = grid[i]; for(size_t j=0; j<cell.size(); ++j) { newRow.push_back(cell[j]*mult_const); } // of cols newGrid.push_back(newRow); newRow.clear(); } // of rows return newGrid; } /** TODO - implement this function. Blurs (and normalizes) a grid of probabilities by spreading probability from each cell over a 3x3 "window" of cells. This function assumes a cyclic world where probability "spills over" from the right edge to the left and bottom to top. EXAMPLE - After blurring (with blurring=0.12) a localized distribution like this: 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 would look like this: 0.01 0.02 0.01 0.02 0.88 0.02 0.01 0.02 0.01 @param grid - a two dimensional grid (vector of vectors of floats) where each entry represents the unnormalized probability associated with that grid cell. @param blurring - a floating point number between 0.0 and 1.0 which represents how much probability from one cell "spills over" to it's neighbors. If it's 0.0, then no blurring occurs. @return - a new normalized two dimensional grid where probability has been blurred. */ vector<vector<float> > blur(vector<vector<float> > grid, float blurring) { const size_t rowCount = grid.size(), colCount = rowCount ? grid[0].size() : 0; if (colCount == 0 || rowCount == 0) { throw std::invalid_argument("Input Matrix containing data"); } const float centerProb = 1.f-blurring, cornerProb = blurring / 12.f, adjacentProb = blurring / 6.f; const float window[3][3] = { {cornerProb, adjacentProb, cornerProb}, {adjacentProb, centerProb, adjacentProb}, {cornerProb, adjacentProb, cornerProb}}; vector<vector<float> > newGrid(rowCount, vector<float>(colCount, 0.f)); for(size_t i=0; i<rowCount; ++i) { if (grid[i].size() != colCount) { throw std::invalid_argument("Check row lengths"); } const vector<float> &row = grid[i]; for(size_t j=0; j<colCount; ++j) { const float gridVal = row[j]; for(int dx=-1; dx<=1; ++dx) { for(int dy=-1; dy<=1; ++dy) { const float mult = window[dy+1][dx+1]; const int newI = ((int)i + dy + (int)rowCount) % rowCount, newJ = ((int)j + dx + (int)colCount) % colCount; newGrid[newI][newJ] += mult * gridVal; } } } } return normalize(newGrid); } /** ----------------------------------------------- # # # You do not need to modify any code below here. # # # ------------------------------------------------- */ /** Determines when two grids of floating point numbers are "close enough" that they should be considered equal. Useful for battling "floating point errors". @param g1 - a grid of floats @param g2 - a grid of floats @return - A boolean (True or False) indicating whether these grids are (True) or are not (False) equal. */ bool close_enough(vector < vector <float> > g1, vector < vector <float> > g2) { int i, j; float v1, v2; if (g1.size() != g2.size()) { return false; } if (g1[0].size() != g2[0].size()) { return false; } for (i=0; i<g1.size(); i++) { for (j=0; j<g1[0].size(); j++) { v1 = g1[i][j]; v2 = g2[i][j]; if (abs(v2-v1) > 0.0001 ) { return false; } } } return true; } bool close_enough(float v1, float v2) { if (abs(v2-v1) > 0.0001 ) { return false; } return true; } /** Helper function for reading in map data @param s - a string representing one line of map data. @return - A row of chars, each of which represents the color of a cell in a grid world. */ vector <char> read_line(string s) { vector <char> row; size_t pos = 0; string token; string delimiter = " "; char cell; while ((pos = s.find(delimiter)) != std::string::npos) { token = s.substr(0, pos); s.erase(0, pos + delimiter.length()); cell = token.at(0); row.push_back(cell); } return row; } /** Helper function for reading in map data @param file_name - The filename where the map is stored. @return - A grid of chars representing a map. */ vector < vector <char> > read_map(string file_name) { ifstream infile(file_name); vector < vector <char> > map; if (infile.is_open()) { char color; vector <char> row; string line; while (std::getline(infile, line)) { row = read_line(line); map.push_back(row); } } return map; } /** Creates a grid of zeros For example: zeros(2, 3) would return 0.0 0.0 0.0 0.0 0.0 0.0 @param height - the height of the desired grid @param width - the width of the desired grid. @return a grid of zeros (floats) */ vector < vector <float> > zeros(int height, int width) { int i, j; vector < vector <float> > newGrid; vector <float> newRow; for (i=0; i<height; i++) { newRow.clear(); for (j=0; j<width; j++) { newRow.push_back(0.0); } newGrid.push_back(newRow); } return newGrid; } // int main() { // vector < vector < char > > map = read_map("maps/m1.txt"); // show_grid(map); // return 0; // }
[ "noreply@github.com" ]
noreply@github.com
1595c0355c5b67e4a143e1042c6ff951eb973840
4fb2b5fe6052fc2e4c037007eb8f60ad8e51ab36
/Source/OverlordEngine/Prefabs/SkyBoxPrefab.h
2ed0ca4b41b66bfe4b12fcfb261da23f335d2385
[]
no_license
SaartjeCodde/GraphicsProgramming
7a067db90d4e9a51bb9b439082ceded27d16b1bf
89de3a5b3f67e1278b306c05d229ca7ad005389f
refs/heads/master
2021-01-10T15:31:35.301461
2015-12-11T13:48:23
2015-12-11T13:48:23
47,828,625
0
0
null
null
null
null
UTF-8
C++
false
false
594
h
#pragma once #include "..\Scenegraph\GameObject.h" #include "..\..\OverlordProject\Materials\SkyBoxMaterial.h" #include "..\Components\ModelComponent.h" class SkyBoxPrefab: public GameObject { public: SkyBoxPrefab(wstring assetFile); protected: virtual void Initialize(const GameContext& gameContext); private: wstring m_AssetFile; private: // ------------------------- // Disabling default copy constructor and default // assignment operator. // ------------------------- SkyBoxPrefab(const SkyBoxPrefab& yRef); SkyBoxPrefab& operator=(const SkyBoxPrefab& yRef); };
[ "Saartje.Codde@student.howest.be" ]
Saartje.Codde@student.howest.be
3f534855f59cbd130e301ab8781ad7a544ac1d9e
02f6798a3b497f12382ed6159db194af242ac23b
/include/diy/mqo/mqoFile.hpp
9bafce5c3d395f45dee8be30f2efbc0f6098b2fd
[]
no_license
SaulHP91/DIYlib
62fc2e32861bcbda760e42d72be796d49ffcd2b8
7f2c381f0d9a1e90f929a74987dcf0c85ed7f1fa
refs/heads/master
2020-12-25T18:22:38.390742
2015-04-26T09:00:30
2015-04-26T09:00:30
34,035,942
0
0
null
null
null
null
UTF-8
C++
false
false
611
hpp
#ifndef MQOFILE_HPP #define MQOFILE_HPP #include <diy/mqo/mqoScene.hpp> #include <fstream> #include <vector> #ifdef DIYLIB_EXPORTS #define DIYLIB_API __declspec(dllexport) #else #define DIYLIB_API __declspec(dllimport) #endif namespace diy { namespace mqo { class MqoMaterial; class MqoObject; class MqoFile { public: DIYLIB_API MqoFile(void); DIYLIB_API ~MqoFile(void); std::string Name; MqoScene Scene; std::vector<MqoMaterial> Materials; std::vector<MqoObject> Objects; DIYLIB_API void Clear(void); DIYLIB_API bool ParseFromFile(std::string path); }; } } #endif
[ "saulhp91@hotmail.com" ]
saulhp91@hotmail.com
a0ebf8d9d82ae23eb05a0b1fb8989254f9a9ab38
589b0867882798d0d92fa6acce99ce12be78b2ad
/types.h
d27be2b2063104a7c8a7734495813159d2c52eea
[]
no_license
pressureless/graphics101-pipeline
bcea5146e598a9f13dbf54f5135d646ea495e1f5
00094a6552f4216642b0725e5a28fcdcb7e023f3
refs/heads/master
2021-10-08T22:59:31.151802
2018-12-18T20:24:57
2018-12-18T20:24:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,713
h
#ifndef __types_h__ #define __types_h__ // OpenGL core profile // #include <GL/gl3w.h> // Just define the basic typedefs. This should be enough for headers. // The .cpp files can include <GL/gl3w.h> as needed. typedef void GLvoid; typedef unsigned int GLenum; typedef float GLfloat; typedef int GLint; typedef int GLsizei; typedef unsigned int GLbitfield; typedef double GLdouble; typedef unsigned int GLuint; typedef unsigned char GLboolean; typedef unsigned char GLubyte; // We do this to get everything glm supports. #include <glm/glm.hpp> // We could only include the subset we need to speed up compile times. /* #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> // glm::mat4 */ #include <cmath> // std::sqrt(), M_PI // Not all platforms define M_PI #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif #include <algorithm> // std::min(), std::max() // To fix a windows header incompatibility with C++11 // From: https://stackoverflow.com/questions/5004858/stdmin-gives-error #undef min #undef max #include <vector> #include <cassert> namespace graphics101 { typedef float real; typedef glm::vec2 vec2; typedef glm::vec3 vec3; typedef glm::vec4 vec4; typedef glm::ivec2 ivec2; typedef glm::ivec3 ivec3; typedef glm::ivec4 ivec4; typedef glm::mat2 mat2; typedef glm::mat3 mat3; typedef glm::mat4 mat4; struct ray3 { // point vec3 p; // direction vec3 d; ray3( const vec3& a_p, const vec3& a_d ) : p( a_p ), d( a_d ) {} }; typedef ivec3 Triangle; typedef std::vector< Triangle > TriangleVec; } #endif /* __types_h__ */
[ "yotam@yotamgingold.com" ]
yotam@yotamgingold.com
b0294b863f2620863a5cd381468ff440561ceefc
bff9ee7f0b96ac71e609a50c4b81375768541aab
/deps/src/boost_1_65_1/libs/geometry/test/algorithms/set_operations/sym_difference/sym_difference_areal_areal.cpp
749c9eb3a86d679849e5f889bfd306bcdeb483e2
[ "BSL-1.0", "BSD-3-Clause" ]
permissive
rohitativy/turicreate
d7850f848b7ccac80e57e8042dafefc8b949b12b
1c31ee2d008a1e9eba029bafef6036151510f1ec
refs/heads/master
2020-03-10T02:38:23.052555
2018-04-11T02:20:16
2018-04-11T02:20:16
129,141,488
1
0
BSD-3-Clause
2018-04-11T19:06:32
2018-04-11T19:06:31
null
UTF-8
C++
false
false
4,584
cpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2014-2015 Oracle and/or its affiliates. // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle #include <iostream> #ifndef BOOST_TEST_MODULE #define BOOST_TEST_MODULE test_sym_difference_areal_areal #endif #ifdef BOOST_GEOMETRY_TEST_DEBUG #define BOOST_GEOMETRY_DEBUG_TURNS #define BOOST_GEOMETRY_DEBUG_SEGMENT_IDENTIFIER #endif #include <boost/test/included/unit_test.hpp> #include <boost/geometry/geometries/linestring.hpp> #include <boost/geometry/geometries/multi_linestring.hpp> #include <boost/geometry/algorithms/sym_difference.hpp> #include "../difference/test_difference.hpp" #include <from_wkt.hpp> typedef bg::model::point<double,2,bg::cs::cartesian> point_type; typedef bg::model::ring<point_type> ring_type; // ccw, closed typedef bg::model::polygon<point_type> polygon_type; // ccw, closed typedef bg::model::multi_polygon<polygon_type> multi_polygon_type; double const default_tolerance = 0.0001; template < typename Areal1, typename Areal2, typename PolygonOut > struct test_sym_difference_of_areal_geometries { static inline void apply(std::string const& case_id, Areal1 const& areal1, Areal2 const& areal2, int expected_polygon_count, int expected_point_count, double expected_area, double tolerance = default_tolerance) { #ifdef BOOST_GEOMETRY_TEST_DEBUG bg::model::multi_polygon<PolygonOut> sdf; bg::sym_difference(areal1, areal2, sdf); std::cout << "Case ID: " << case_id << std::endl; std::cout << "Geometry #1: " << bg::wkt(areal1) << std::endl; std::cout << "Geometry #2: " << bg::wkt(areal2) << std::endl; std::cout << "Sym diff: " << bg::wkt(sdf) << std::endl; std::cout << "Polygon count: expected: " << expected_polygon_count << "; detected: " << sdf.size() << std::endl; std::cout << "Point count: expected: " << expected_point_count << "; detected: " << bg::num_points(sdf) << std::endl; std::cout << "Area: expected: " << expected_area << "; detected: " << bg::area(sdf) << std::endl; #endif ut_settings settings; settings.percentage = tolerance; test_difference < PolygonOut >(case_id, areal1, areal2, expected_polygon_count, expected_point_count, expected_area, true, settings); } }; //=========================================================================== //=========================================================================== //=========================================================================== BOOST_AUTO_TEST_CASE( test_sym_difference_ring_ring ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl << std::endl; std::cout << "*** RING / RING SYMMETRIC DIFFERENCE ***" << std::endl; std::cout << std::endl; #endif typedef ring_type R; typedef polygon_type PG; typedef test_sym_difference_of_areal_geometries<R, R, PG> tester; tester::apply("r-r-sdf00", from_wkt<R>("POLYGON((0 0,0 10,10 10,10 0,0 0))"), from_wkt<R>("POLYGON((10 0,10 20,20 20,20 0,10 0))"), 1, 8, 300); tester::apply("r-r-sdf01", from_wkt<R>("POLYGON((0 0,0 10,10 10,10 0,0 0))"), from_wkt<R>("POLYGON((9 0,9 20,20 20,20 0,9 0))"), 2, 12, 300); } BOOST_AUTO_TEST_CASE( test_sym_difference_polygon_multipolygon ) { #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << std::endl << std::endl << std::endl; std::cout << "*** POLYGON / MULTIPOLYGON SYMMETRIC DIFFERENCE ***" << std::endl; std::cout << std::endl; #endif typedef polygon_type PG; typedef multi_polygon_type MPG; typedef test_sym_difference_of_areal_geometries<PG, MPG, PG> tester; tester::apply ("pg-mpg-sdf00", from_wkt<PG>("POLYGON((10 0,10 10,20 10,20 0,10 0))"), from_wkt<MPG>("MULTIPOLYGON(((0 0,0 10,10 10,10 0,0 0)),\ ((20 0,20 10,30 10,30 0,20 0)))"), 1, 9, 300); }
[ "znation@apple.com" ]
znation@apple.com
7810c7e753b680cd4d21e59ea148c66861cff52f
492976adfdf031252c85de91a185bfd625738a0c
/src/Game/AI/Action/actionItemConductorDemoBind.cpp
be9381d696ffb8064cfe1ca9d33f4063ce8ab83a
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
1,063
cpp
#include "Game/AI/Action/actionItemConductorDemoBind.h" namespace uking::action { ItemConductorDemoBind::ItemConductorDemoBind(const InitArg& arg) : ksys::act::ai::Action(arg) {} ItemConductorDemoBind::~ItemConductorDemoBind() = default; void ItemConductorDemoBind::enter_(ksys::act::ai::InlineParamPack* params) { ksys::act::ai::Action::enter_(params); } void ItemConductorDemoBind::leave_() { ksys::act::ai::Action::leave_(); } void ItemConductorDemoBind::loadParams_() { getDynamicParam(&mRotOffsetX_d, "RotOffsetX"); getDynamicParam(&mRotOffsetY_d, "RotOffsetY"); getDynamicParam(&mRotOffsetZ_d, "RotOffsetZ"); getDynamicParam(&mTransOffsetX_d, "TransOffsetX"); getDynamicParam(&mTransOffsetY_d, "TransOffsetY"); getDynamicParam(&mTransOffsetZ_d, "TransOffsetZ"); getDynamicParam(&mActorName_d, "ActorName"); getDynamicParam(&mUniqueName_d, "UniqueName"); getDynamicParam(&mNodeName_d, "NodeName"); } void ItemConductorDemoBind::calc_() { ksys::act::ai::Action::calc_(); } } // namespace uking::action
[ "leo@leolam.fr" ]
leo@leolam.fr
c84209625432816502f315676745d968152d0b08
a74fe8e456939f2aff73d70e3ba6ddd0cf7dcc98
/deber_Wdt.ino
270b6a263a0fb5dd8a8c8b04ac6bf9965846c1a6
[]
no_license
cristianflorese/Micros
027955f0e2f654fe0bd24582ce9801086f90279c
56d3f200edeaf10add58c898f13d6c2a8d96facf
refs/heads/master
2020-09-04T16:04:13.432981
2020-02-05T02:39:06
2020-02-05T02:39:06
219,792,630
0
0
null
null
null
null
UTF-8
C++
false
false
1,440
ino
/* * Deber Wdt */ #include <avr/wdt.h> #include <EEPROM.h> #include <TimerOne.h> String letra; int numero=0; int contador=0; int encendido=0; int valor=0; void setup() { Serial.begin(9600); attachInterrupt(0,menu,LOW); attachInterrupt(1,submenu,LOW); Timer1.stop(); } void loop() { if (encendido == 1) { if (Serial.available() > 0 ) { letra=Serial.readString(); Timer1.initialize(1000000); Timer1.attachInterrupt(conteo); } } } void menu() { switch (encendido) { case 0: Serial.println("Letra/Tiempo:"); encendido++; break; case 1: Serial.println(' '); encendido=0; break; } } void conteo() { contador++; if(valor==1){ if(letra=='A'){ Serial.println(String(2-contador)); } if(letra=='B'){ Serial.println(String(3-contador)); } if(letra=='C'){ Serial.println(String(5-contador)); } if(letra=='D'){ Serial.println(String(9-contador)); } } } void submenu() { if (letra=='A'&&valor==1) { Serial.println("WDTO_1S"); wdt_enable(WDTO_1S); } if (letra=='B'&&valor==1) { Serial.println("WDTO_2S"); wdt_enable(WDTO_2S); } if (letra=='C'&&valor==1) { Serial.println("WDTO_4S"); wdt_enable(WDTO_4S); } if (letra=='D'&&valor==1) { Serial.println("WDTO_8S"); wdt_enable(WDTO_8S); } }
[ "noreply@github.com" ]
noreply@github.com
70002a1ce305120cde49d1e5d3b460c7a73e502d
502fdd5f3555c32afb782d344e5fc059f5e8ff47
/Rettroix3DEngine/Rettroix3DEngine/Game.h
1aba0ccd5e07da4b291b8a7e948bd275fcac3365
[]
no_license
Rettroix/Rettroix3D
b7ace1a142528f8a706f22b9163e915eb5633118
1a64d27c86ef7dfdafa9c179810facefead0220a
refs/heads/master
2021-01-19T18:30:37.250817
2017-04-19T23:12:31
2017-04-19T23:12:31
88,361,481
0
0
null
null
null
null
UTF-8
C++
false
false
159
h
using namespace std; #include <string> #include "stdafx.h" class Game { public: Game(); ~Game(); void input(); void update(); void render(); };
[ "drhoix@yahoo.co.uk" ]
drhoix@yahoo.co.uk
23439a1d39dbcf2a4b39716f7d434389c6be030b
3cb0708829a7d6d50165bcd14ae22ea8df2db3a1
/attiny/attinyPotLed/attinyPotLed.ino
c5c5a42a86c175df9c0f20794cb2f2a97c370eed
[]
no_license
gargshail/arduino
7db1eb928621ea35df671130352cecf633af96d4
fe58cdfd5a0ab1ab840c739f696a79d96aaa86f6
refs/heads/master
2020-04-19T09:03:23.130457
2016-10-22T15:59:04
2016-10-22T15:59:04
30,516,064
0
0
null
null
null
null
UTF-8
C++
false
false
384
ino
/* |1-- --8| -- VCC |2 7| pot-> A2 |3 6| GND-- |4------5| LED -- to --GND */ int led1 = 0; int input = A2; void setup() { pinMode(led1, OUTPUT); pinMode(input, INPUT); } void loop() { int val = analogRead(input); long brightness = map(val, 0,1023,0,255); analogWrite(led1, brightness); delay(50); }
[ "me@shailesh.com" ]
me@shailesh.com
70585317e065c81b362ca9514fa99e2b468cd16b
2e0a386ce035b5ab448b9f55c0e85abd68ee271b
/test/normalize_q_test.cpp
2e9748f8698a54ed516d7f6d27d4dc20a2bcf9f5
[ "BSL-1.0" ]
permissive
boostorg/qvm
c8f52a7d4919fb9b2cecb184ea8ee6b33805c3fa
fa272cb0b07ce85b5d8d53fb3dfade389e9cc4df
refs/heads/develop
2023-08-31T09:35:07.262248
2023-06-06T19:48:59
2023-06-06T19:48:59
37,782,744
80
42
BSL-1.0
2023-01-21T06:17:37
2015-06-20T19:23:29
C++
UTF-8
C++
false
false
1,673
cpp
// Copyright 2008-2022 Emil Dotchevski and Reverge Studios, Inc. // 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) #ifdef BOOST_QVM_TEST_SINGLE_HEADER # include BOOST_QVM_TEST_SINGLE_HEADER #else # include <boost/qvm/quat_operations.hpp> # include <boost/qvm/quat.hpp> #endif #include "test_qvm_quaternion.hpp" #include "gold.hpp" namespace { template <class T,class U> struct same_type_tester; template <class T> struct same_type_tester<T,T> { }; template <class T,class U> void test_same_type( T, U ) { same_type_tester<T,U>(); } void test() { using namespace boost::qvm::sfinae; { test_qvm::quaternion<Q1> const x(42,1); test_same_type(x,normalized(x)); test_qvm::quaternion<Q1> y=normalized(x); float m=sqrtf(test_qvm::dot<float>(x.a,x.a)); test_qvm::scalar_multiply_v(y.b,x.a,1/m); BOOST_QVM_TEST_CLOSE(y.a,y.b,0.000001f); } { test_qvm::quaternion<Q1> const x(42,1); test_qvm::quaternion<Q1> y=normalized(qref(x)); float m=sqrtf(test_qvm::dot<float>(x.a,x.a)); test_qvm::scalar_multiply_v(y.b,x.a,1/m); BOOST_QVM_TEST_CLOSE(y.a,y.b,0.000001f); } { test_qvm::quaternion<Q1> x(42,1); float m=sqrtf(test_qvm::dot<float>(x.a,x.a)); test_qvm::scalar_multiply_v(x.b,x.a,1/m); normalize(x); BOOST_QVM_TEST_CLOSE(x.a,x.b,0.000001f); } } } int main() { test(); return boost::report_errors(); }
[ "emildotchevski@gmail.com" ]
emildotchevski@gmail.com
89b0ce34938ee9a4ed5aad52ceb03b1ad753b363
b2c1fd0e4be3525edda9da1fea0609ea7bcb7415
/modules/gui/include/glbr/imgui/imgui_backend.hpp
0a1b312eb822909e0fb0f7789d2f613451b41600
[]
no_license
ivovandongen/globe-renderer
664c9a5458e4a5ac4904e68c20122eedfbe2d257
68764c955464fea1589795ce3cd29c319ed7c63e
refs/heads/master
2022-04-01T07:13:15.756308
2019-09-14T10:34:33
2019-10-04T09:09:43
175,590,394
0
0
null
2020-04-13T09:26:03
2019-03-14T09:33:10
C++
UTF-8
C++
false
false
578
hpp
#pragma once #include <glbr/core/events/event_handler.hpp> #include <glbr/core/events/event_producer.hpp> #include <memory> namespace glbr { namespace imgui { class ImGuiBackend : public core::EventHandler { public: static std::shared_ptr<ImGuiBackend> instance(core::EventProducer&); void operator()(core::Event& event) override; ~ImGuiBackend() override; private: explicit ImGuiBackend(core::EventProducer& eventProducer); private: std::unique_ptr<core::EventHandlerRegistration> _handlerRegistration; }; } // namespace imgui } // namespace glbr
[ "ivovandongen@users.noreply.github.com" ]
ivovandongen@users.noreply.github.com
d10f7663c151dbcb50cb108af62323e23257f02e
3c8cf4de6c08e21b2c10094ef20488e93d7a34be
/TktkGameProcessDxlibAppendLib/_TktkLibTestProject/src/GameObject/MeshTest/MeshTestState/ScaleState/SelfScaler.cpp
fee0bc8643706fb2a25276784c86ccb04ad288b7
[]
no_license
tktk2104/TktkLib
07762028c8a3a7378d7e82be8f1ed8c6a0cdc97c
2af549bfb8448ace9f9fee6c2225ea7d2e6329b8
refs/heads/master
2022-11-30T12:26:33.290941
2020-08-11T17:50:14
2020-08-11T17:50:14
213,307,835
0
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
#include "SelfScaler.h" #include <stdexcept> void SelfScaler::start() { auto transform = getComponent<tktk::Transform3D>(); if (transform.isNull()) { throw std::runtime_error("SelfMover not found Transform3D"); } m_transform = transform; } void SelfScaler::update() { if (tktk::Keyboard::getState(tktk::InputType::INPUT_PUSHING, tktk::KeyboardKeyType::KEYBOARD_UP)) { m_transform->addLocalScaleRate(Vector3::forwardLH * 0.1f); } if (tktk::Keyboard::getState(tktk::InputType::INPUT_PUSHING, tktk::KeyboardKeyType::KEYBOARD_DOWN)) { m_transform->addLocalScaleRate(Vector3::backwardLH * 0.1f); } if (tktk::Keyboard::getState(tktk::InputType::INPUT_PUSHING, tktk::KeyboardKeyType::KEYBOARD_LEFT)) { m_transform->addLocalScaleRate(Vector3::left * 0.1f); } if (tktk::Keyboard::getState(tktk::InputType::INPUT_PUSHING, tktk::KeyboardKeyType::KEYBOARD_RIGHT)) { m_transform->addLocalScaleRate(Vector3::right * 0.1f); } }
[ "taka.lalpedhuez@2104.gmail.com" ]
taka.lalpedhuez@2104.gmail.com
80f2fc1544e69312be3f49275ab6f17b31286c8d
4cbb866848c57fa103d198a27767bd817a9ab287
/project/section_mapping/referenceExtractor.cpp
f48731c0166f4a030304b7affa5155407d270495
[ "BSD-3-Clause" ]
permissive
TomasLesicko/Bachelor-Thesis
a13cdaa0b670a3e349e7c232bc84cc37dc732ffc
c30db33f35028395201dc07d47e1cd332132906d
refs/heads/master
2021-07-13T18:39:31.192562
2020-07-18T10:27:04
2020-07-18T10:27:04
159,676,294
0
0
null
null
null
null
UTF-8
C++
false
false
9,191
cpp
#include <experimental/filesystem> #include <fstream> #include <optional> #include <regex> #include <stdexcept> #include <string> #include <vector> #include <iostream> namespace fs = std::experimental::filesystem; struct Lines { int from; int to; }; std::ostream & operator<<(std::ostream &o, std::vector<Lines> const &lines) { bool first = true; for(Lines l : lines) { if(!first) o << ", "; o << R"({ "from": ")" << l.from; o << R"(", "to": ")" << l.to << R"(" })"; first = false; } return o; } std::ostream & operator<<(std::ostream &o, Lines const &lines) { o << R"({ "from": ")" << lines.from; o << R"(", "to": ")" << lines.to << R"(" })"; return o; } struct FileContext { std::string fileName; std::vector<Lines> lineNumbers; }; std::ostream & operator<<(std::ostream &o, FileContext const &fc) { o << R"({ "file": ")" << fc.fileName; o << R"(", "lines": [ )" << /*fc.lineNumber*/fc.lineNumbers << " ] }"; return o; } struct DocumentRef { std::string document; std::string section; bool isTodo; }; std::ostream & operator<<(std::ostream &o, DocumentRef const &ref) { o << R"({ "document": ")" << ref.document << '"'; o << R"(, "section": ")" << ref.section << "\""; o << R"(, "TODO": ")" << std::boolalpha << ref.isTodo << "\" }"; return o; } struct Entry { FileContext fileContext; DocumentRef documentRef; }; std::ostream & operator<<(std::ostream &o, Entry const &entry) { o << "{\n \"document\": " << entry.documentRef << ",\n"; o << " \"semantics\": " << entry.fileContext << "\n }"; return o; } using Entries = std::vector<Entry>; std::ostream & operator<<(std::ostream &o, Entries const &entries) { if (entries.empty()) { o << "[]"; return o; } o << "[\n"; for (size_t i = 0; i < entries.size(); i++) { o << " " << entries[i]; if (i < entries.size() - 1) o << ",\n"; } o << "\n]\n"; return o; } std::vector<std::string> splitRefSections(const std::string& s) { std::vector<std::string> sections; static const std::regex regex(R"((.*)([:\/])([\d\.]+)*(\d+)(?:-([\d\.]+)*(\d+))?)"); std::smatch result; if (std::regex_search(s, result, regex)) { // example 1.2:3.1-3.4 std::string chapter = result[1]; // 1.2 std::string delim = result[2]; // : std::string paragraphFromPrefix = result[3]; // 3. std::string paragraphFrom = result[4]; // 1 std::string paragraphToPrefix = result[5]; // 3. std::string paragraphTo = result[6]; // 4 int from = std::stoi(paragraphFrom); int to = paragraphTo.empty() ? from : std::stoi(paragraphTo); for (; from <= to; ++from) { std::string section; section.append(chapter).append(delim).append(paragraphFromPrefix).append(std::to_string(from)); sections.emplace_back(section); } } return sections; } void splitRefTags(const std::smatch& result, std::vector<DocumentRef>& refs) { std::vector<std::string> sections = splitRefSections(result[4]); for (const std::string& section : sections) { if (result[2] != "") { refs.emplace_back(DocumentRef{result[2], section, result[1] != ""}); } refs.emplace_back(DocumentRef{result[3], section, result[1] != ""}); } } std::vector<DocumentRef> refsFromLine(const std::string& line) { static const std::regex regex(R"((TODO)?(?:\S*)? (?:@ref )?(N\d{4})?(?:-)?(N\d{4}) ([A-Z0-9][\.\d]*[:\/][\d-\.]+))", std::regex_constants::icase); std::vector<DocumentRef> refs; /* * Capture groups * 1 "TODO" - if not empty, reference was marked as TODO * 2 Secondary tag revision group - if not empty, 2 revision tags in reference * 3 Primary tag revision group - can not be empty * 4 Section group - can not be empty */ std::smatch result; auto start = line.cbegin(); while (std::regex_search(start, line.cend(), result, regex)) { splitRefTags(result, refs); start = result.suffix().first; } return refs; } bool lineContainsComment(const std::string& line) { static const std::regex regex(R"(//)"); std::smatch result; return std::regex_search(line, result, regex); } void print(std::optional<DocumentRef> ref) { if (ref) std::cout << ref.value(); else std::cout << "empty"; } void addRefsToEntries(std::vector<Entry>& refs, Entries& entries) { auto it = std::next(refs.begin(), refs.size()); std::move(refs.begin(), it, std::back_inserter(entries)); refs.erase(refs.begin(), it); } std::string splitPath(const std::string& path) { static const std::regex regex(R"(c-semantics.*)"); std::smatch result; ; return std::regex_search(path, result, regex) ? result[0] : path; } void processLineReferences(std::vector<Entry>& commentBlockRefs, Entries& entries, const std::string& path, int lineNumber, std::vector<DocumentRef>& refs) { for (auto& ref : refs) { commentBlockRefs.push_back(Entry{FileContext{splitPath(path), {Lines{lineNumber, lineNumber}}}, std::move(ref)}); } } bool previousLineIsComment(const std::vector<Entry>& commentBlockRefs, int lineNumber) { return commentBlockRefs.back().fileContext.lineNumbers.back().to + 1 == lineNumber; } void updateCommentBlockRefLines(std::vector<Entry>& commentBlockRefs, int lineNumber) { if (!commentBlockRefs.empty()) { if (previousLineIsComment(commentBlockRefs, lineNumber)) { std::for_each(commentBlockRefs.begin(), commentBlockRefs.end(), [&lineNumber](Entry& e) { e.fileContext.lineNumbers.back().to = lineNumber; }); } else { std::for_each(commentBlockRefs.begin(), commentBlockRefs.end(), [&lineNumber](Entry& e) { e.fileContext.lineNumbers.emplace_back(Lines{lineNumber, lineNumber}); }); } } } void processCommentLine(const std::string& line, std::vector<Entry>& commentBlockRefs, Entries& entries, const std::string& path, int lineNumber) { std::vector<DocumentRef> refs = refsFromLine(line); if (!refs.empty()) { processLineReferences(commentBlockRefs, entries, path, lineNumber, refs); } else { updateCommentBlockRefLines(commentBlockRefs, lineNumber); } } void processNonCommentLine(const std::string& line, std::vector<Entry>& commentBlockRefs, Entries & entries) { ; } bool lineIsWhiteSpace(const std::string& line) { for (int c : line) { if (!isspace(c)) { return false; } } return true; } // assumes there's always a space between comment blocks and that // comment blocks start with a reference void addEntriesFromIstream(Entries & entries, const std::string& path, std::istream & is) { int lineNumber = 1; std::vector<Entry> commentBlockRefs; std::string line; while(std::getline(is, line)) { if (lineIsWhiteSpace(line)) { addRefsToEntries(commentBlockRefs, entries); } else if(lineContainsComment(line)) { processCommentLine(line, commentBlockRefs, entries, path, lineNumber); } else { processNonCommentLine(line, commentBlockRefs, entries); } ++lineNumber; } addRefsToEntries(commentBlockRefs, entries); } // expects "// @ref[...]" format bool isReference(const std::string& comment) { return comment.substr(0, 4) == "@ref"; } void addEntry(Entries & entries, FileContext & fc, DocumentRef & dr) { entries.push_back(Entry{fc, dr}); } DocumentRef createRef(const std::string& comment) { static const std::regex regex(R"(@ref (\S+) (\S+))"); std::smatch result; if (std::regex_search(comment, result, regex)) { return DocumentRef{result[1], result[2]}; } return {}; } void addEntriesFromRegularFile(Entries & entries, const fs::path& filepath) { // Ignore files not matching '*.k' if (filepath.extension() != ".k" && filepath.extension() != ".C") return; std::ifstream is(filepath); if (!is.is_open()) throw std::runtime_error(std::string("Cannot read file: ") + filepath.string()); addEntriesFromIstream(entries, filepath.string(), is); } void addEntriesFromDirectory(Entries & entries, const fs::path& dirpath) { for(auto& current: fs::recursive_directory_iterator(dirpath)) { addEntriesFromRegularFile(entries, current); } } void addEntriesFromPath(Entries & entries, const fs::path& p) { if (fs::is_regular_file(p)) return addEntriesFromRegularFile(entries, p); if (fs::is_directory(p)) return addEntriesFromDirectory(entries, p); } Entries entriesFromPath(const fs::path& path) { Entries entries; addEntriesFromPath(entries, path); return entries; } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <path>\n"; return 1; } try { std::ofstream references ("references.json"); references << entriesFromPath(argv[1]); } catch (std::exception const &e) { std::cerr << "Error: " << e.what() << '\n'; } }
[ "lesicko.tomas@gmail.com" ]
lesicko.tomas@gmail.com
69b6d90eab7e4e9b60ab889d23b843c75b8ccdc2
bf4aad167e0d664b7bdce197ee68eeb187bd2774
/view.h
7bf88278c416facf85026bd452ffc64a568aa697
[]
no_license
km93120/tanks-game
8d8b2c9772e029a18a5e4df8a15d2695822f7a29
4acd29407c1d9b88deff90d81b6bbe2529495b61
refs/heads/master
2020-04-17T11:29:30.938334
2019-01-19T12:17:35
2019-01-19T12:17:35
166,542,866
0
0
null
null
null
null
UTF-8
C++
false
false
803
h
#ifndef VIEW_H #define VIEW_H #include <QGraphicsView> #include <QGraphicsScene> #include <QPushButton> #include "control.h" class Control; class View : public QGraphicsView { Q_OBJECT protected: void keyPressEvent(QKeyEvent * event); QGraphicsScene * scene; QPushButton * button1; Control * control; Level * level; int index; public: View(); ~View(); void setControl(Control *); void setConnection(); void renderLevel(); QPushButton *getButton1() const; Level *getLevel() const; void setLevel(Level * level,int index ); QGraphicsScene *getScene() const; signals: void yaay(); public slots: void clearScene(); }; #endif // VIEW_H
[ "madadiatman@yahoo.fr" ]
madadiatman@yahoo.fr
9c0181e87f37a255d3eebe33180e454758f94e41
1825283527f5a479204708feeaf55f4ab6d1290b
/leetcode/word.cpp
620b6c3b60e48bbee47af28d243fc2f70653a88e
[]
no_license
frankieliu/problems
b82c61d3328ffcc1da2cbc95712563355f5d44b5
911c6622448a4be041834bcab25051dd0f9209b2
refs/heads/master
2023-01-06T14:41:58.044871
2019-11-24T03:47:22
2019-11-24T03:47:22
115,065,956
1
0
null
2023-01-04T07:25:52
2017-12-22T02:06:57
HTML
UTF-8
C++
false
false
7,130
cpp
#include<bits/stdc++.h> using namespace std; const int MIN_NO_OF_CHARS = 2, MAX_NO_OF_CHARS = 100000; // -------------------------- START -------------------------- // Each variable is explained in the code, where it is used first. int len, no_of_words; queue<int> bfs_q; vector<bool> visited; unordered_map<string, int> position; unordered_map<int, int> parent; // Check if str1 and str2 differs ar exactly one positon. bool only_one_char_difference(int len, string &str1, string &str2) { int difference = 0; for (int i = 0; i < len; i++) { if (str1[i] != str2[i]) { // If there is already one miss match, and now we have found another. if (difference == 1) { return false; } difference++; } } // If difference == 0, it means strings are same. So, difference == 1 is needed. return difference == 1; } // Update neighbours using O(len * len * 26) method. void add_neighbours_with_method2(string &cur_str, int idx) { // For each position. for (int i = 0; i < len; i++) { // For each possible character. for (char ch = 'a'; ch <= 'z'; ch++) { // We want to find string having one different character, so need to skip this. if (ch == cur_str[i]) { continue; } // Store the original character, this will help to backtrack the change. char original = cur_str[i]; // Set new character. cur_str[i] = ch; // Check if new string is in words array or not. auto it = position.find(cur_str); // If new string is in words array. if (it != position.end()) { int position_of_cur_str_in_words_array = it->second; // If neighbour string is not already visited. if (visited[position_of_cur_str_in_words_array] == false) { // Visit it. visited[position_of_cur_str_in_words_array] = true; /* This string is visited by idx th string. So, remember it. This will help us to construct the answer later. */ parent[position_of_cur_str_in_words_array] = idx; /* If we have reached the stop string. Do you remember we have pushed the stop string at the end of words array! */ if (position_of_cur_str_in_words_array == no_of_words - 1) { return; } bfs_q.push(position_of_cur_str_in_words_array); } } // Backtrack. cur_str[i] = original; } } } // Update neighbours using O(no_of_words * len) method. void add_neighbours_with_method1(vector<string> &words, string &cur_str, int idx) { // Iterate over all words. for (int i = 0; i < no_of_words; i++) { // If neighbour is not visited and has only one character different from current string. if (visited[i] == false && only_one_char_difference(len, cur_str, words[i])) { // Mark as visited. visited[i] = true; /* This string is visited by idx th string. So, remember it. This will help us to construct the answer later. */ parent[i] = idx; /* If we have reached the stop string. Do you remember we have pushed the stop string at the end of words array! */ if (i == no_of_words - 1) { return; } bfs_q.push(i); } } } void solution(vector<string> &words, string &start, string &stop) { /* When no_of_words > len * 26, we are going to use method2. So, we need to use hash map for faster search. For search if string is present in words array or not in O(len) time. */ if (no_of_words > len * 26) { for (int i = 0; i < no_of_words; i++) { position[words[i]] = i; } } // -1 means start string. bfs_q.push(-1); /* Visited array to track if string is visited or not, during BFS. visited[i] = true -> words[i] is visited in BFS. visited[i] = false -> words[i] is not visited in BFS till now. */ visited.assign(no_of_words, false); while (bfs_q.empty() == false) { int idx = bfs_q.front(); bfs_q.pop(); // Stores string that is at the front of queue. string cur_str; if (idx == -1) { cur_str = start; } else { cur_str = words[idx]; } // Call appropriate method to update the neighbours. if (no_of_words <= len * 26) { add_neighbours_with_method1(words, cur_str, idx); } else { add_neighbours_with_method2(cur_str, idx); } } } vector<string> string_transformation(vector<string> words, string start, string stop) { // Length of each string in input. len = start.length(); /* Add stop string in words. This is not necessary, but this will help to simplify the code. */ words.push_back(stop); // Total no of words. stop is also included. no_of_words = words.size(); // Do BFS. solution(words, start, stop); // From parent information gathered from BFS, construct the actual string transformation. vector<string> ans; /* Start from stop string. Go to its parent, then its parent's parent... till we reach start string. */ int stop_idx = no_of_words - 1; // If stop string is not reached in BFS. if (parent.find(stop_idx) == parent.end()) { ans.push_back("-1"); return ans; } /* Start from stop string. Go to its parent, then its parent's parent... till we reach start string. */ while (stop_idx != -1) { ans.push_back(words[stop_idx]); stop_idx = parent[stop_idx]; } // Add the start string. ans.push_back(start); // ans array contains strings in reverse order so reverse it. reverse(ans.begin(), ans.end()); return ans; } // -------------------------- STOP --------------------------- int main() { //freopen("..//test_cases//sample_test_cases_input.txt", "r", stdin); //freopen("..//test_cases//sample_test_cases_expected_output.txt", "w", stdout); //freopen("..//test_cases//handmade_test_cases_input.txt", "r", stdin); //freopen("..//test_cases//handmade_test_cases_expected_output.txt", "w", stdout); //freopen("..//test_cases//generated_small_test_cases_input.txt", "r", stdin); //freopen("..//test_cases//generated_small_test_cases_expected_output.txt", "w", stdout); freopen("..//test_cases//generated_big_test_cases_input.txt", "r", stdin); freopen("..//test_cases//generated_big_test_cases_expected_output.txt", "w", stdout); //freopen("..//test_cases//ignore.txt", "w", stdout); int test_cases; cin >> test_cases; assert(test_cases >= 0); while (test_cases--) { int n; cin >> n; vector<string> words(n); for (int i = 0; i < n; i++) { cin >> words[i]; } for (int i = 1; i < n; i++) { assert(words[i - 1].length() == words[i].length()); } string start, stop; cin >> start; if (n != 0) { assert(start.length() == words[0].length()); } cin >> stop; assert(start.length() == stop.length()); assert(MIN_NO_OF_CHARS <= (n + 2LL) * start.length()); assert((n + 2LL) * start.length() <= MAX_NO_OF_CHARS); while(bfs_q.empty() == false) { bfs_q.pop(); } position.clear(); parent.clear(); vector<string> ans = string_transformation(words, start, stop); int ans_size = ans.size(); if (ans_size != 1) { assert(ans[0] == start); assert(ans[ans_size - 1] == stop); } for (int i = 0; i < ans_size; i++) { if (i > 0) { assert(only_one_char_difference(len, ans[i - 1], ans[i])); } cout << ans[i] << endl; } cout << endl; } return 0; }
[ "frankie.y.liu@gmail.com" ]
frankie.y.liu@gmail.com
2019df958c5c803b251a84025e564c73c4f4b9db
6dadd3de14c2ff1d5ce63e9d52066efd3758ae17
/src/PmtSD.cpp
30320a5121161211da94a636582417c7eca112af
[]
no_license
Q-Pix/UTAH_GEANT4
902408989c8709088d65904beba46c5c0df48b1e
488315d3244bb944d06ae4b367cce532b4deecaa
refs/heads/master
2023-08-14T11:41:37.565933
2021-10-04T16:25:00
2021-10-04T16:25:00
413,492,345
0
1
null
null
null
null
UTF-8
C++
false
false
5,541
cpp
// ---------------------------------------------------------------------------- // nexus | PmtSD.cc // // This class is the sensitive detector that allows for the registration // of the charge detected by a photosensor. // // The NEXT Collaboration // ---------------------------------------------------------------------------- #include "PmtSD.h" #include "MCParticle.h" #include "MCTruthManager.h" #include <G4OpticalPhoton.hh> #include <G4SDManager.hh> #include <G4ProcessManager.hh> #include <G4OpBoundaryProcess.hh> #include <G4RunManager.hh> #include <G4RunManager.hh> PmtSD::PmtSD(G4String sdname, const G4String& hc_name): G4VSensitiveDetector(sdname), naming_order_(0), sensor_depth_(0), mother_depth_(0), boundary_(0) { // Register the name of the collection of hits collectionName.insert(GetCollectionUniqueName()); collectionName.insert(hc_name); } PmtSD::~PmtSD() { } G4String PmtSD::GetCollectionUniqueName() { return "PmtHitsCollection"; } // void PmtSD::Initialize(G4HCofThisEvent* HCE) // { // // for (int i=0; i<100; ++i){G4cout << "WHOOOO" << G4endl;} // // Create a new collection of PMT hits // HC_ = new PmtHitsCollection(this->GetName(), this->GetCollectionName(0)); // G4int HCID = G4SDManager::GetSDMpointer()-> // GetCollectionID(this->GetName()+"/"+this->GetCollectionName(0)); // HCE->AddHitsCollection(HCID, HC_); // } G4bool PmtSD::ProcessHits(G4Step* step, G4TouchableHistory*) { // for (int i=0; i<10; ++i){G4cout << "FKN WORK" << G4endl;} // G4cout << "FKN WORK" << G4endl; // Check whether the track is an optical photon G4ParticleDefinition* pdef = step->GetTrack()->GetDefinition(); // G4cout << pdef << G4endl; if (pdef != G4OpticalPhoton::Definition()) return false; // G4cout << "I is photon" << G4endl; // Retrieve the pointer to the optical boundary process, if it has // not been done yet (i.e., if the pointer is not defined) if (!boundary_) { // Get the list of processes defined for the optical photon // and loop through it to find the optical boundary process. G4ProcessVector* pv = pdef->GetProcessManager()->GetProcessList(); for (size_t i=0; i<pv->size(); i++) { if ((*pv)[i]->GetProcessName() == "OpBoundary") { boundary_ = (G4OpBoundaryProcess*) (*pv)[i]; break; } } } // Check if the photon has reached a geometry boundary if (step->GetPostStepPoint()->GetStepStatus() == fGeomBoundary) { // Check whether the photon has been detected in the boundary if (boundary_->GetStatus() == Detection) { const G4VTouchable* touchable = step->GetPostStepPoint()->GetTouchable(); // G4int pmt_id = FindPmtID(touchable); // PmtHit* hit = 0; // for (size_t i=0; i<HC_->entries(); i++) // { // if ((*HC_)[i]->GetPmtID() == pmt_id) // { // hit = (*HC_)[i]; // break; // } // } // // If no hit associated to this sensor exists already, // // create it and set main properties // if (!hit) // { // hit = new PmtHit(); // hit->SetPmtID(pmt_id); // hit->SetBinSize(timebinning_); // hit->SetPosition(touchable->GetTranslation()); // HC_->insert(hit); // } //--------------------------------------------------------------------------- // begin add hit to MCParticle //--------------------------------------------------------------------------- // get MC truth manager MCTruthManager * mc_truth_manager = MCTruthManager::Instance(); // get MC particle MCParticle * particle = mc_truth_manager->GetMCParticle(step->GetTrack()->GetTrackID()); // add hit to MC particle particle->AddPmtHit(step); // G4double time = step->GetPreStepPoint()->GetGlobalTime()/CLHEP::ns; // G4double MyX = step->GetPreStepPoint()->GetPosition().x()/CLHEP::cm; // G4double MyY = step->GetPreStepPoint()->GetPosition().y()/CLHEP::cm; // G4double MyZ = step->GetPreStepPoint()->GetPosition().z()/CLHEP::cm; // G4cout << "HIT TIME, " << time <<"\t"<< MyX <<"\t"<< MyY <<"\t"<< MyZ << G4endl; // time = step->GetPostStepPoint()->GetGlobalTime()/CLHEP::ns; // MyX = step->GetPostStepPoint()->GetPosition().x()/CLHEP::cm; // MyY = step->GetPostStepPoint()->GetPosition().y()/CLHEP::cm; // MyZ = step->GetPostStepPoint()->GetPosition().z()/CLHEP::cm; // G4cout << "HIT TIME, " << time <<"\t"<< MyX <<"\t"<< MyY <<"\t"<< MyZ << G4endl; // hit->Fill(time); } } return true; } G4int PmtSD::FindPmtID(const G4VTouchable* touchable) { G4int pmtid = touchable->GetCopyNumber(sensor_depth_); if (naming_order_ != 0) { G4int motherid = touchable->GetCopyNumber(mother_depth_); pmtid = naming_order_ * motherid + pmtid; } return pmtid; } void PmtSD::EndOfEvent(G4HCofThisEvent* /*HCE*/) { // int HCID = G4SDManager::GetSDMpointer()-> // GetCollectionID(this->GetCollectionName(0)); // // } // HCE->AddHitsCollection(HCID, HC_); }
[ "austin.mcdonald96@mavs.uta.edu" ]
austin.mcdonald96@mavs.uta.edu
ad8550be8a345031ecbc9b9aeed4820cf0005b8a
9598f48703820d9c2e263cb8864226eeb13332bf
/uri/principiante/Esfera.cpp
78108e4342dba975a56554522795bb6917712667
[]
no_license
leiverandres/programming-contest
4da6343119290b480757435788ff90d950492ff9
66cfb41326b0d35abbe70634976176446cb0fa63
refs/heads/master
2021-01-15T08:59:18.035112
2016-10-22T16:54:01
2016-10-22T16:54:20
45,351,990
0
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
#include <bits/stdc++.h> using namespace std; const double pi = 3.14159; int main() { double r; cin >> r; double ans = (4.0/3.0) * pi * (r*r*r); cout << fixed << setprecision(3) << "VOLUME = " << ans << endl; return 0; }
[ "leiverandres04p@hotmail.com" ]
leiverandres04p@hotmail.com
00f767d30c0f58724f9c3cf4c6efc7c5210920d8
6eeb2ace34ce205bf25cf99993a0972aa38859f3
/Assignments/Assignment_03_Pt_02/main.cpp
b4e1c6e413b84f740216348cedbae748a72fbce7
[]
no_license
mattjmoses/DataStructures
05020529bd6432a8d84ee687c01417c782ca623f
f4acbb664a705e3a60e1a3b1530117edfce31958
refs/heads/master
2021-05-13T11:54:45.142914
2018-04-16T23:18:59
2018-04-16T23:18:59
117,143,816
0
0
null
null
null
null
UTF-8
C++
false
false
1,100
cpp
#include <iostream> #include <string> #include <fstream> #include "ExternalMergeSort.h" using namespace std; int main() { ExternalMergeSort mergeSort; //Sample string array. string strArray[10] = {"lala","toop","zop","garpo","alphaghetti","tootson","borstche","voltzwagon","skiing","zzzzzzzzzzZ"}; //Doing some setup so we know how many entries are in the file //For NOW we're only inputting a single file ifstream readFile("phonebook.txt"); //Creating out output file ofstream writeFile("sorted.txt"); int numEntries = -1; //This only serves for looping purpose. Doesn't serve a function in the program at this point. string throwAway; if(readFile.is_open()) { while(getline(readFile,throwAway)) { numEntries ++; } } cout<<"Number of entries in file: " << numEntries << endl; //She sorts! string* newArr = mergeSort.FileSort("phonebook.txt","sorted.txt",numEntries); cout << strArray << endl; for(int i = 0; i < 10; i++) { cout<< newArr[i] << endl; } return 0; }
[ "mattjmoses@gmail.com" ]
mattjmoses@gmail.com
c87f94a8bfb6b9e99f685d9c49d0feeeccf9bfd3
8f3bfce01e310d1e39dac1155e78551b90c64712
/3_7_1_factorial.cpp
f2cb0d39d59e43ab7f8783a8c86b47e129ff2dcf
[]
no_license
Impulsation/game_institute
784bfda927e99202d7678e729b4b01fa794791b3
ea1e57bfb71bcc983be7d0769ce9d811fccd0bac
refs/heads/master
2021-01-18T14:05:51.063543
2013-09-13T18:22:52
2013-09-13T18:22:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
498
cpp
/* 3.7.1 Factorial http://www.gameinstitute.com Jason Lemons, 01/11/2013 */ #include <iostream> using namespace std; int Factorial(int n); int main() { cout << "5! = " << Factorial(5) << endl; cout << "0! = " << Factorial(0) << endl; cout << "9! = " << Factorial(9) << endl; cout << "3! = " << Factorial(3) << endl; return 0; } int Factorial(int n) { int answer = 1; for (int i = 0; i < n; i++) { answer = answer * (n - i); } return answer; };
[ "jasonlemons93@yahoo.com" ]
jasonlemons93@yahoo.com
b77465b133534a74e0cf8fbc3abd7aee59e3b38c
715e0f58e99325625ab5cbd6ed5d5938c6fde867
/Game/Code/Game/Starburst.cpp
b687a3bbbad62b63957ccff51feb6c7ca87e8c33
[]
no_license
RSWSMUGirl2016/A-Roids
62bb7ea938603e2e1277a6984296d1524ab7a909
372a4a394e4fb365c45b5515067a990bef953478
refs/heads/master
2021-05-09T14:57:39.299343
2018-01-26T16:55:47
2018-01-26T16:55:47
118,998,522
0
0
null
null
null
null
UTF-8
C++
false
false
3,047
cpp
#include "Game/Starburst.hpp" #include "Engine/Math/MathUtilities.hpp" #include "Game/GameCommon.hpp" #include "Engine/Renderer/SimpleRenderer.hpp" //******************************************************************* Starburst::Starburst() { m_position = Vector2(0.f, 0.f); m_velocity = Vector2(0.f, 0.f); m_acceleration = Vector2(0.f, 0.f); m_spinDegreesPerSecond = 0.f; m_orientationDegrees = 0.f; m_radius = 15.f; m_physicalRadius = Disc2D(m_position, m_radius*PERECENT_OF_M_RADIUS_FOR_PHYSICAL_RADIUS_FOR_STARBURST); m_liberalRadius = Disc2D(m_position, m_radius*PERECENT_OF_M_RADIUS_FOR_LIBERAL_RADIUS_FOR_STARBURST); for (int vertexNum = 0; vertexNum < NUM_VERTEXES_STARBURST; vertexNum+=2) { float paddingForPosition = 0.5; m_vertexes[vertexNum] = Vector2(paddingForPosition, paddingForPosition); } } //******************************************************************* Starburst::~Starburst() { } //******************************************************************* void Starburst::Update(float deltaSeconds) { m_orientationDegrees += (m_spinDegreesPerSecond * deltaSeconds); m_position.x += (m_velocity.x * deltaSeconds); m_position.y += (m_velocity.y * deltaSeconds); m_liberalRadius.center = m_position; m_physicalRadius.center = m_position; } //******************************************************************* void Starburst::Render() const { g_theSimpleRenderer->DrawSprite2DCentered(g_theGame->m_spaceShipsSpriteSheet->GetTexture2D(), g_theGame->m_starbustTextureCoords.m_mins, g_theGame->m_starbustTextureCoords.m_maxs, m_position, m_orientationDegrees, m_radius * 2.0f, m_radius * 2.0f, Rgba::WHITE); } //******************************************************************* void Starburst::WrapAround() { if (m_liberalRadius.center.y > (ORHTO_HEIGHT + m_liberalRadius.radius)) { m_liberalRadius.center.y = 0.f - m_liberalRadius.radius; m_position.y = m_liberalRadius.center.y; m_physicalRadius.center = m_position; } if (m_liberalRadius.center.y < (0.f - m_liberalRadius.radius)) { m_liberalRadius.center.y = ORHTO_HEIGHT + m_liberalRadius.radius; m_position.y = m_liberalRadius.center.y; m_physicalRadius.center = m_position; } if (m_liberalRadius.center.x > (ORHTO_WIDTH + m_liberalRadius.radius)) { m_liberalRadius.center.x = 0.f - m_liberalRadius.radius; m_position.x = m_liberalRadius.center.x; m_physicalRadius.center = m_position; } if (m_liberalRadius.center.x < (0.f - m_liberalRadius.radius)) { m_liberalRadius.center.x = ORHTO_WIDTH + m_liberalRadius.radius; m_position.x = m_liberalRadius.center.x; m_physicalRadius.center = m_position; } } //******************************************************************* void Starburst::SetCenterForPhysicalAndLiberalRadii() { m_physicalRadius.center = m_position; m_liberalRadius.center = m_position; } //******************************************************************* void Starburst::SetRadiiForPhysicalAndLiberalRadii() { m_physicalRadius.radius = m_radius; m_liberalRadius.radius = m_radius; }
[ "rsward@smu.edu" ]
rsward@smu.edu
31dbdac6fc4cfe3c15f9922bf809c0f7660d6280
dadc3bc4f5c05d7318bff26fc6068d1e9b468701
/include/kx_task.h
a06bb5e55fe92d79d17b4872dd2ec71ad44e2099
[]
no_license
mincore/kxlib
8f487efafaa0b1c3b00309e2769e851d5eaa4ece
3e0ac06d31e37b0d65419f68573f71c24186c118
refs/heads/master
2021-01-21T10:37:56.093329
2018-03-21T06:04:52
2018-03-21T06:04:52
91,700,618
0
0
null
null
null
null
UTF-8
C++
false
false
6,778
h
/* =================================================== * Copyright (C) 2018 chenshuangping All Right Reserved. * Author: mincore@163.com * Filename: kx_task.h * Created: 2014-02-04 14:48 * Description: * =================================================== */ #ifndef _KX_TASK_H #define _KX_TASK_H #include <string> #include <vector> #include <unordered_map> #include <chrono> #include <map> #include <atomic> #include <limits> #include <deque> #include <mutex> #include <condition_variable> #include <thread> #include <functional> typedef std::function<void(void)> Task; namespace kx { template<typename T> class Queue { public: void stop() { std::unique_lock<std::mutex> lk(m_mutex); m_stop = true; m_cond.notify_all(); } bool push(const T &t, size_t *size_before_push = NULL) { std::unique_lock<std::mutex> lk(m_mutex); if (m_stop) return false; if (size_before_push) *size_before_push = m_Queue.size(); m_Queue.emplace_back(t); m_cond.notify_one(); return true; } bool pop(T &t, size_t *size_after_pop = NULL) { std::unique_lock<std::mutex> lk(m_mutex); m_cond.wait(lk, [this]{ return m_stop || !m_Queue.empty(); }); if (m_stop) return false; t = m_Queue.front(); m_Queue.pop_front(); if (size_after_pop) *size_after_pop = m_Queue.size(); return true; } private: std::mutex m_mutex; std::condition_variable m_cond; std::deque<T> m_Queue; bool m_stop = false; }; template<class T> class Ring { public: Ring (size_t cap): m_data(cap) {} bool empty() { return m_count == 0; } bool full() { return m_count == m_data.size(); } bool push(const T &t) { if (full()) return false; m_data[m_next] = t; m_next = (m_next + 1) % m_data.size(); m_count++; return true; } bool pop(T &t) { if (empty()) return false; size_t index = (m_next - m_count + m_data.size()) % m_data.size(); m_count--; t = m_data[index]; return true; } private: std::vector<T> m_data; size_t m_count = 0; size_t m_next = 0; }; template<typename T> class Chan { public: Chan(size_t size = 1): m_ring(size) {} void push(const T &t) { std::unique_lock<std::mutex> lk(m_mutex); m_wcond.wait(lk, [this]{ return !m_ring.full(); }); m_ring.push(t); m_rcond.notify_one(); } T pop() { T t; std::unique_lock<std::mutex> lk(m_mutex); m_rcond.wait(lk, [this]{ return !m_ring.empty(); }); m_ring.pop(t); m_wcond.notify_one(); return t; } private: Chan(const Chan &Chan) = delete; const Chan& operator=(const Chan&) = delete; private: std::mutex m_mutex; std::condition_variable m_rcond; std::condition_variable m_wcond; Ring<T> m_ring; }; static inline long long now() { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now().time_since_epoch() ).count(); } class SpinLock { public: void lock() { while(m_flag.test_and_set(std::memory_order_acquire)){} } void unlock() { m_flag.clear(std::memory_order_release); } private: std::atomic_flag m_flag = ATOMIC_FLAG_INIT; }; class TaskPool { public: typedef Queue<Task> TaskQ; bool push(const Task &task, const char *name) { if (name == NULL || *name == 0) { return m_taskq.push(task); } TaskQ *q = get_taskq(name); size_t size_before_push; if (!q->push(task, &size_before_push)) { return false; } if (size_before_push == 0) { return m_taskq.push(std::bind(RunTaskQ, &m_taskq, q)); } return true; } bool pop(Task &task) { return m_taskq.pop(task); } void stop() { m_taskq.stop(); } private: static void RunTaskQ(TaskQ* holder, TaskQ *q) { Task task; size_t size_after_pop; if (!q->pop(task, &size_after_pop)) return; task(); if (size_after_pop > 0) { holder->push(std::bind(RunTaskQ, holder, q)); } } TaskQ *get_taskq(const std::string &name) { std::lock_guard<SpinLock> lk(m_spinlock); return &m_map[name]; } private: SpinLock m_spinlock; std::unordered_map<std::string, TaskQ> m_map; TaskQ m_taskq; }; class TaskTimer { public: bool push(const Task &task, long long delay) { std::unique_lock<std::mutex> lk(m_mutex); if (m_stop) return false; m_time_map.emplace(now() + delay, task); if (now() >= m_time_map.begin()->first) m_cond.notify_one(); return true; } bool pop(Task &task) { while (1) { std::unique_lock<std::mutex> lk(m_mutex); if (m_stop) { return false; } auto delay = m_time_map.empty() ? 1000 : m_time_map.begin()->first - now(); if (delay > 0) { m_cond.wait_for(lk, std::chrono::milliseconds(delay), [this]{ return m_stop || (!m_time_map.empty() && m_time_map.begin()->first >= now()); }); continue; } task = m_time_map.begin()->second; m_time_map.erase(m_time_map.begin()); return true; } } void stop() { std::unique_lock<std::mutex> lk(m_mutex); m_stop = true; m_cond.notify_all(); } private: std::mutex m_mutex; std::condition_variable m_cond; std::multimap<long long, Task> m_time_map; bool m_stop = false; }; template<typename T> class ThreadPool { public: ThreadPool(int nthread) { for (int i=0; i<nthread; i++) { m_threads.push_back(std::thread([this]{ Task task; while(m_t.pop(task)) { task(); } })); } } ~ThreadPool() { m_t.stop(); for (auto &thread : m_threads) { thread.join(); } } template<typename Arg> bool push(const Task &task, Arg arg) { return m_t.push(task, arg); } private: std::vector<std::thread> m_threads; T m_t; }; void RunTask(const Task &task, const char *queue_name = NULL) { static ThreadPool<TaskPool> threadpool(std::thread::hardware_concurrency()); threadpool.push(task, queue_name); } void RunTask(const Task &task, long long delay) { static ThreadPool<TaskTimer> threadpool(1); threadpool.push(task, delay); } } #endif
[ "chenshuangping@speed-clouds.com" ]
chenshuangping@speed-clouds.com
78362986317f581f463d9f2658d286d5cf90b0c5
afdc82729b1ae1e1a11fc0d63d4990a7972a9fd6
/micro/test/ccunit/micro/ops/nhwc/depthwise_conv_2d_opt_test.cc
1472c05c1b00c81a3b3c6e7ce291391761fd2196
[ "Apache-2.0" ]
permissive
gasgallo/mace
79e759ceb9548fa69d577dd28ca983f87a302a5e
96b4089e2323d9af119f9f2eda51976ac19ae6c4
refs/heads/master
2021-06-23T19:09:24.230126
2021-03-02T12:23:05
2021-03-02T12:23:05
205,080,233
1
0
Apache-2.0
2019-08-29T04:27:36
2019-08-29T04:27:35
null
UTF-8
C++
false
false
9,467
cc
// Copyright 2018 The MACE Authors. 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 "gtest/gtest.h" #include "micro/ops/gtest_utils.h" #include "micro/ops/nhwc/depthwise_conv_2d_kb1_s4.h" #include "micro/ops/nhwc/depthwise_conv_2d_kb2_s4.h" #include "micro/ops/nhwc/depthwise_conv_2d_kb3_s4.h" #include "micro/ops/nhwc/depthwise_conv_2d_kb4_s4.h" #include "micro/ops/substitute_op.h" #include "micro/ops/test_utils.h" namespace micro { namespace ops { namespace test { class DepthwiseConv2dOptOpTest : public ::testing::Test {}; namespace { void SimpleValidTest() { float input[18] = {1, 2, 2, 4, 3, 6, 4, 8, 5, 10, 6, 12, 7, 14, 8, 16, 9, 18}; int32_t input_dims[4] = {1, 3, 3, 2}; float filter[8] = {1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f}; int32_t filter_dims[4] = {1, 2, 2, 2}; float bias[2] = {0.1f, 0.2f}; int32_t bias_dims[1] = {2}; float output[8] = {0}; int32_t output_dims[4] = {0}; float expect[8] = {37.1f, 148.2f, 47.1f, 188.2f, 67.1f, 268.2f, 77.1f, 308.2f}; int32_t expect_dims[4] = {1, 2, 2, 2}; const int32_t strides[] = {1, 1}; const int32_t dilations[] = {1, 1}; DepthwiseConv2dKB1S4Op depthwise_conv_2d_op; framework::SubstituteOp substitude_op; substitude_op.AddInput(input, input_dims, 4) .AddInput(filter, filter_dims, 4) .AddInput(bias, bias_dims, 1) .AddRepeatArg("strides", strides, sizeof(strides) / sizeof(int32_t)) .AddArg("padding", Padding::VALID) .AddRepeatArg("dilations", dilations, sizeof(dilations) / sizeof(int32_t)) .AddOutput(output, output_dims, 4); depthwise_conv_2d_op.Init(NULL, reinterpret_cast<framework::OpContext *>( &substitude_op), NULL); depthwise_conv_2d_op.Run(); ExpectTensorNear<float>(output, output_dims, 4, expect, expect_dims, 4, 1e-5); } void MultiKB2ValidTest() { float input[18] = {1, 2, 2, 4, 3, 6, 4, 8, 5, 10, 6, 12, 7, 14, 8, 16, 9, 18}; int32_t input_dims[4] = {1, 3, 3, 2}; float filter[16] = {1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f}; int32_t filter_dims[4] = {2, 2, 2, 2}; float bias[4] = {0.1f, 0.1f, 0.2f, 0.2f}; int32_t bias_dims[1] = {4}; float output[16] = {0}; int32_t output_dims[4] = {0}; float expect[16] = {37.1f, 37.1f, 148.2f, 148.2f, 47.1f, 47.1f, 188.2f, 188.2f, 67.1f, 67.1f, 268.2f, 268.2f, 77.1f, 77.1f, 308.2f, 308.2f}; int32_t expect_dims[4] = {1, 2, 2, 4}; const int32_t strides[] = {1, 1}; const int32_t dilations[] = {1, 1}; DepthwiseConv2dKB2S4Op depthwise_conv_2d_op; framework::SubstituteOp substitude_op; substitude_op.AddInput(input, input_dims, 4) .AddInput(filter, filter_dims, 4) .AddInput(bias, bias_dims, 1) .AddRepeatArg("strides", strides, sizeof(strides) / sizeof(int32_t)) .AddArg("padding", Padding::VALID) .AddRepeatArg("dilations", dilations, sizeof(dilations) / sizeof(int32_t)) .AddOutput(output, output_dims, 4); depthwise_conv_2d_op.Init(NULL, reinterpret_cast<framework::OpContext *>( &substitude_op), NULL); depthwise_conv_2d_op.Run(); ExpectTensorNear<float>(output, output_dims, 4, expect, expect_dims, 4, 1e-5); } void MultiKB3ValidTest() { float input[18] = {1, 2, 2, 4, 3, 6, 4, 8, 5, 10, 6, 12, 7, 14, 8, 16, 9, 18}; int32_t input_dims[4] = {1, 3, 3, 2}; float filter[24] = {1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f}; int32_t filter_dims[4] = {3, 2, 2, 2}; float bias[6] = {0.1f, 0.1f, 0.1f, 0.2f, 0.2f, 0.2f}; int32_t bias_dims[1] = {6}; float output[24] = {0}; int32_t output_dims[4] = {0}; float expect[24] = {37.1f, 37.1f, 37.1f, 148.2f, 148.2f, 148.2f, 47.1f, 47.1f, 47.1f, 188.2f, 188.2f, 188.2f, 67.1f, 67.1f, 67.1f, 268.2f, 268.2f, 268.2f, 77.1f, 77.1f, 77.1f, 308.2f, 308.2f, 308.2f}; int32_t expect_dims[4] = {1, 2, 2, 6}; const int32_t strides[] = {1, 1}; const int32_t dilations[] = {1, 1}; DepthwiseConv2dKB3S4Op depthwise_conv_2d_op; framework::SubstituteOp substitude_op; substitude_op.AddInput(input, input_dims, 4) .AddInput(filter, filter_dims, 4) .AddInput(bias, bias_dims, 1) .AddRepeatArg("strides", strides, sizeof(strides) / sizeof(int32_t)) .AddArg("padding", Padding::VALID) .AddRepeatArg("dilations", dilations, sizeof(dilations) / sizeof(int32_t)) .AddOutput(output, output_dims, 4); depthwise_conv_2d_op.Init(NULL, reinterpret_cast<framework::OpContext *>( &substitude_op), NULL); depthwise_conv_2d_op.Run(); ExpectTensorNear<float>(output, output_dims, 4, expect, expect_dims, 4, 1e-5); } void MultiKB4ValidTest() { float input[18] = {1, 2, 2, 4, 3, 6, 4, 8, 5, 10, 6, 12, 7, 14, 8, 16, 9, 18}; int32_t input_dims[4] = {1, 3, 3, 2}; float filter[32] = {1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f}; int32_t filter_dims[4] = {4, 2, 2, 2}; float bias[8] = {0.1f, 0.1f, 0.1f, 0.1f, 0.2f, 0.2f, 0.2f, 0.2f}; int32_t bias_dims[1] = {8}; float output[32] = {0}; int32_t output_dims[4] = {0}; float expect[32] = { 37.1f, 37.1f, 37.1f, 37.1f, 148.2f, 148.2f, 148.2f, 148.2f, 47.1f, 47.1f, 47.1f, 47.1f, 188.2f, 188.2f, 188.2f, 188.2f, 67.1f, 67.1f, 67.1f, 67.1f, 268.2f, 268.2f, 268.2f, 268.2f, 77.1f, 77.1f, 77.1f, 77.1f, 308.2f, 308.2f, 308.2f, 308.2f}; int32_t expect_dims[4] = {1, 2, 2, 8}; const int32_t strides[] = {1, 1}; const int32_t dilations[] = {1, 1}; DepthwiseConv2dKB4S4Op depthwise_conv_2d_op; framework::SubstituteOp substitude_op; substitude_op.AddInput(input, input_dims, 4) .AddInput(filter, filter_dims, 4) .AddInput(bias, bias_dims, 1) .AddRepeatArg("strides", strides, sizeof(strides) / sizeof(int32_t)) .AddArg("padding", Padding::VALID) .AddRepeatArg("dilations", dilations, sizeof(dilations) / sizeof(int32_t)) .AddOutput(output, output_dims, 4); depthwise_conv_2d_op.Init(NULL, reinterpret_cast<framework::OpContext *>( &substitude_op), NULL); depthwise_conv_2d_op.Run(); ExpectTensorNear<float>(output, output_dims, 4, expect, expect_dims, 4, 1e-5); } void MultiKB5ValidTest() { float input[18] = {1, 2, 2, 4, 3, 6, 4, 8, 5, 10, 6, 12, 7, 14, 8, 16, 9, 18}; int32_t input_dims[4] = {1, 3, 3, 2}; float filter[40] = {1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f, 1.0f, 2.0f, 2.0f, 4.0f, 3.0f, 6.0f, 4.0f, 8.0f}; int32_t filter_dims[4] = {5, 2, 2, 2}; float bias[10] = {0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.2f, 0.2f, 0.2f, 0.2f, 0.2f}; int32_t bias_dims[1] = {10}; float output[40] = {0}; int32_t output_dims[4] = {0}; float expect[40] = { 37.1f, 37.1f, 37.1f, 37.1f, 37.1f, 148.2f, 148.2f, 148.2f, 148.2f, 148.2f, 47.1f, 47.1f, 47.1f, 47.1f, 47.1f, 188.2f, 188.2f, 188.2f, 188.2f, 188.2f, 67.1f, 67.1f, 67.1f, 67.1f, 67.1f, 268.2f, 268.2f, 268.2f, 268.2f, 268.2f, 77.1f, 77.1f, 77.1f, 77.1f, 77.1f, 308.2f, 308.2f, 308.2f, 308.2f, 308.2f }; int32_t expect_dims[4] = {1, 2, 2, 10}; const int32_t strides[] = {1, 1}; const int32_t dilations[] = {1, 1}; DepthwiseConv2dKB4S4Op depthwise_conv_2d_op; framework::SubstituteOp substitude_op; substitude_op.AddInput(input, input_dims, 4) .AddInput(filter, filter_dims, 4) .AddInput(bias, bias_dims, 1) .AddRepeatArg("strides", strides, sizeof(strides) / sizeof(int32_t)) .AddArg("padding", Padding::VALID) .AddRepeatArg("dilations", dilations, sizeof(dilations) / sizeof(int32_t)) .AddOutput(output, output_dims, 4); depthwise_conv_2d_op.Init(NULL, reinterpret_cast<framework::OpContext *>( &substitude_op), NULL); depthwise_conv_2d_op.Run(); ExpectTensorNear<float>(output, output_dims, 4, expect, expect_dims, 4, 1e-5); } } // namespace TEST_F(DepthwiseConv2dOptOpTest, MultiKB1CPU) { SimpleValidTest(); } TEST_F(DepthwiseConv2dOptOpTest, MultiKB2CPU) { MultiKB2ValidTest(); } TEST_F(DepthwiseConv2dOptOpTest, MultiKB3CPU) { MultiKB3ValidTest(); } TEST_F(DepthwiseConv2dOptOpTest, MultiKB4CPU) { MultiKB4ValidTest(); } TEST_F(DepthwiseConv2dOptOpTest, MultiKB5CPU) { MultiKB5ValidTest(); } } // namespace test } // namespace ops } // namespace micro
[ "luxuhui@xiaomi.com" ]
luxuhui@xiaomi.com
7e59cb7bca849ea401e4eac86610841cf1a01b7d
0abfb7f50ab237561b9cee7206e72032aaaaed39
/ch02/ex2.3.5.cc
474cc58c418119eacf34037b10781d1efece8b85
[]
no_license
scintillavoy/CLRS
bc48e9bdc4cc6acc4fd2ec37cccff1df0369a3dc
f2cfef49cde19eda94ad5c6569651586a046108b
refs/heads/main
2023-04-09T21:28:45.233131
2021-04-24T03:31:11
2021-04-24T03:31:11
332,082,198
1
0
null
null
null
null
UTF-8
C++
false
false
1,040
cc
#include <iostream> #include <vector> using namespace std; template <typename It, typename T> It BinarySearch(It first, It last, const T& val) { It last_ = last; // save last while (first != last) { It mid = first + (last - first) / 2; if (*mid == val) { return mid; // found } else if (*mid > val) { last = mid; } else { first = mid + 1; } } return last_; // not found } /* - Running Time * Worst-case: theta(lgn) * T(n) = T(n/2) + c * The worst case happens when the value it finds is not in the array. Letting * the length of the array is n, for each iteration, n becomes half * (rounded down) if the value is not found. The while loop terminates until n * becomes 0, which means there is only up to (lgn)th iteration. */ int main() { vector<int> vec{23, 29, 37, 41, 54, 62}; for (const auto &x : vec) { cout << *BinarySearch(vec.cbegin(), vec.cend(), x) << endl; } return 0; }
[ "scintillavoy@gmail.com" ]
scintillavoy@gmail.com
5bdc841709ce58474be273176c7c84e33a7d23cc
9dc1b6e4e50cc0625657e2954ae277bd727d7a4b
/BnsDLL/BnsFunction.cpp
7d6b9188986e872cbfd3cc38ce35e510c7b4df8f
[]
no_license
r2cn/AutoLoginByBnsChina
e01d7e462442ffed3b8fdf7717bf25df8b159d61
897987fffee1c385057eb6110da5c9e1fe380ef3
refs/heads/master
2020-04-06T04:44:26.910989
2016-12-06T12:53:02
2016-12-06T12:53:02
82,898,687
1
0
null
2017-02-23T07:37:17
2017-02-23T07:37:17
null
UTF-8
C++
false
false
3,274
cpp
#include "stdafx.h" #include "BnsFunction.h" #include <MyTools/CLSearchBase.h> #include <MyTools/CLHook.h> #include <MyTools/CLPublic.h> #include "LoginPlayer.h" #define _SELF L"BnsFunction.cpp" UINT CBnsFunction::GetLoginPlayerList(_Out_ std::vector<CLoginPlayer>& vlst) CONST throw() { DWORD dwPersonBase = CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Person); DWORD dwPersonOffset = CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_PersonOffset1); DWORD dwPlayerTraverseOffset = CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_PlayerTraverseOffset); DWORD dwAddr = ReadDWORD(ReadDWORD(dwPersonBase) + dwPersonOffset + 0x8) + dwPlayerTraverseOffset; UINT uPlayerCount = GetLoginPlayerCount(); for (UINT i = 0; i < uPlayerCount; ++i) vlst.push_back(CLoginPlayer(ReadDWORD(dwAddr) + i * 0x30, i)); return vlst.size(); } UINT CBnsFunction::GetLoginPlayerCount() CONST throw() { DWORD dwPersonBase = CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Person); DWORD dwPersonOffset = CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_PersonOffset1); DWORD dwPlayerTraverseOffset = CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_PlayerTraverseOffset); DWORD dwAddr = ReadDWORD(ReadDWORD(dwPersonBase) + dwPersonOffset + 0x8) + dwPlayerTraverseOffset; return static_cast<UINT>(ReadDWORD(dwAddr + 4) - ReadDWORD(dwAddr)) / 0x30; } static DWORD dwHookVolumeAddr = 0; __declspec(naked) VOID WINAPI HookVolume() { static CHAR* pszText = nullptr; _asm { MOV ECX, ESI; CALL EAX; MOV pszText, EAX; PUSHAD; } if (pszText != NULL) { if (CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Volume) == NULL) CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Volume) = static_cast<DWORD>(atoi(pszText)); } __asm POPAD; __asm TEST EAX, EAX; __asm PUSH dwHookVolumeAddr; __asm RETN; } UINT CBnsFunction::GetVolume() CONST throw() { // 8bceffd085c074186a006a0050e8????????8b4f54 dwHookVolumeAddr = CLSearchBase::FindAddr("8bceffd085c074186a006a0050e8????????8b4f54", 0x0, 0, L"StsMsgCli32.dll"); if (dwHookVolumeAddr == NULL) { LogMsgBox(LOG_LEVEL_EXCEPTION, L"GetVolume MachineCode Faild!"); return 0; } Log(LOG_LEVEL_NORMAL, L"dwHookVolumeAddr=%X", dwHookVolumeAddr); MYHOOK_CONTENT MC; MC.dwHookAddr = dwHookVolumeAddr; MC.dwFunAddr = (DWORD)HookVolume; MC.uNopCount = 0x1; CLHook::Hook_Fun_Jmp_MyAddr(&MC); dwHookVolumeAddr += 0x6; CLPublic::TimeOut_By_Condition(30 * 1000, [] { //CLPublic::SimulationKey(VK_F10, CGameVariable::GetInstance().GetAccShareInfo()->hGameWnd); ::SetWindowPos(CGameVariable::GetInstance().GetAccShareInfo()->hGameWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); ::SwitchToThisWindow(CGameVariable::GetInstance().GetAccShareInfo()->hGameWnd, TRUE); CLPublic::SendKey(VK_F10); ::Sleep(3 * 1000); return CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Volume) != NULL; }); Log(LOG_LEVEL_NORMAL, L"Value=%d", CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Volume)); CLHook::UnHook_Fun_Jmp_MyAddr(&MC); return static_cast<DWORD>(CGameVariable::GetInstance().GetRefValue_By_Id(em_Base::em_Base_Volume)); }
[ "648881240@qq.com" ]
648881240@qq.com
7502c170ee4274a817ca858752ddc62ef818edaf
b62f2c039b641d688176c17c468124b4c717f590
/ProceduralProject/Engine/Engine/soundclass.h
a411678e54d117703601cd6c64bc996eb4f22c20
[]
no_license
CanTinGit/ProceduralGeneration
9356773f6fc1232c261aea800d95bc5b5d1aa3f5
9f66c0f6a7a60c0a2f8e2ce39e60dca66a93b95e
refs/heads/master
2020-03-10T13:23:04.325253
2018-05-01T15:58:57
2018-05-01T15:58:57
129,397,611
0
0
null
null
null
null
UTF-8
C++
false
false
1,595
h
/////////////////////////////////////////////////////////////////////////////// // Filename: soundclass.h /////////////////////////////////////////////////////////////////////////////// #ifndef _SOUNDCLASS_H_ #define _SOUNDCLASS_H_ ///////////// // LINKING // ///////////// #pragma comment(lib, "dsound.lib") #pragma comment(lib, "dxguid.lib") #pragma comment(lib, "winmm.lib") ////////////// // INCLUDES // ////////////// #include <windows.h> #include <mmsystem.h> #include <dsound.h> #include <stdio.h> /////////////////////////////////////////////////////////////////////////////// // Class name: SoundClass /////////////////////////////////////////////////////////////////////////////// class SoundClass { private: struct WaveHeaderType { char chunkId[4]; unsigned long chunkSize; char format[4]; char subChunkId[4]; unsigned long subChunkSize; unsigned short audioFormat; unsigned short numChannels; unsigned long sampleRate; unsigned long bytesPerSecond; unsigned short blockAlign; unsigned short bitsPerSample; char dataChunkId[4]; unsigned long dataSize; }; public: SoundClass(); SoundClass(const SoundClass&); ~SoundClass(); bool Initialize(HWND, char*,bool); void Shutdown(); bool PlayWaveFile(); void PauseAndPlay(); private: bool InitializeDirectSound(HWND); void ShutdownDirectSound(); bool LoadWaveFile(char*, IDirectSoundBuffer8**); void ShutdownWaveFile(IDirectSoundBuffer8**); private: IDirectSound8* m_DirectSound; IDirectSoundBuffer* m_primaryBuffer; IDirectSoundBuffer8* m_secondaryBuffer1; bool isPlaying; }; #endif
[ "ctxx61@gmail.com" ]
ctxx61@gmail.com
9092d80dbbcf909b65e4383aa0447fef2f017027
1b0aadb6dc881bf363cbebbc59ac0c41a956ed5c
/xtk/Source/Controls/XTResizeGroupBox.h
58382c294f71f39e55e5af5cb01d695a9f7c2f93
[]
no_license
chinatiny/OSS
bc60236144d73ab7adcbe52cafbe610221292ba6
87b61b075f00b67fd34cfce557abe98ed6f5be70
refs/heads/master
2022-09-21T03:11:09.661243
2018-01-02T10:12:35
2018-01-02T10:12:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,963
h
// XTResizeGroupBox.h : header file // // This file is a part of the XTREME CONTROLS MFC class library. // (c)1998-2007 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTRESIZEGROUPBOX_H__) #define __XTRESIZEGROUPBOX_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 //--------------------------------------------------------------------------- // Summary: // CXTResizeGroupBox is a CButton derived class that can be used to display // a flicker free group box while resizing. This class is intended to only // be used as a group box and only used on a CXTResize window. You can // subclass or create this object the way you would any CButton. // // Note: // Do not use the transparent flag with this control, and make sure you // call SetFlag(xtResizeNoTransparentGroup); to disable the resize manager from // setting this for you. //--------------------------------------------------------------------------- class _XTP_EXT_CLASS CXTResizeGroupBox : public CButton { DECLARE_DYNAMIC(CXTResizeGroupBox) public: //----------------------------------------------------------------------- // Summary: // Constructs a CXTResizeGroupBox object //----------------------------------------------------------------------- CXTResizeGroupBox(); //----------------------------------------------------------------------- // Summary: // Destroys a CXTResizeGroupBox object, handles cleanup and // deallocation //----------------------------------------------------------------------- virtual ~CXTResizeGroupBox(); protected: //----------------------------------------------------------------------- // Summary: // Called during paint operations to exclude the control windows // that are grouped by this control. // Parameters: // pDC - Pointer to device context. // rcClient - Client area of group box. //----------------------------------------------------------------------- virtual void Exclude(CDC* pDC, CRect& rcClient); protected: //{{AFX_CODEJOCK_PRIVATE DECLARE_MESSAGE_MAP() //{{AFX_VIRTUAL(CXTResizeGroupBox) //}}AFX_VIRTUAL //{{AFX_MSG(CXTResizeGroupBox) afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnPaint(); //}}AFX_MSG //}}AFX_CODEJOCK_PRIVATE }; #endif // !defined(__XTRESIZEGROUPBOX_H__)
[ "w.z.y2006@163.com" ]
w.z.y2006@163.com