hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ace12c280abf35b3c6b629e7028cb13918ba0e24
397
cpp
C++
2017.3.17/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.3.17/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2017.3.17/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<string> #include<vector> #include<stack> #include<set> #include<map> #include<queue> #include<algorithm> using namespace std; char s[1000]; int main(){ cout<<"I"<<endl<<" "<<endl<<"L"<<endl<<"o"<<endl<<"v"<<endl<<"e"<<endl<<" "<<endl<<"G"<<endl<<"P"<<endl<<"L"<<endl<<"T"<<endl; return 0; }
19.85
130
0.632242
1980744819
ace3575cd6f7c290e3fabfbd45b8ec90796ade9d
14,287
cpp
C++
Samples/threadMigration/threadMigration.cpp
rob-opsi/cuda-samples
32943424ed7023f9168266d9fb7b76e8566fd054
[ "BSD-3-Clause" ]
1,947
2018-05-21T23:16:35.000Z
2022-03-31T15:29:23.000Z
Samples/threadMigration/threadMigration.cpp
rob-opsi/cuda-samples
32943424ed7023f9168266d9fb7b76e8566fd054
[ "BSD-3-Clause" ]
96
2018-07-12T18:51:46.000Z
2022-03-26T19:09:32.000Z
Samples/threadMigration/threadMigration.cpp
rob-opsi/cuda-samples
32943424ed7023f9168266d9fb7b76e8566fd054
[ "BSD-3-Clause" ]
756
2018-05-21T23:16:47.000Z
2022-03-31T20:01:29.000Z
/* Copyright (c) 2021, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /****************************************************************************** * * Module: threadMigration.cpp * * Description: * Simple sample demonstrating multi-GPU/multithread functionality using * the CUDA Context Management API. This API allows the a CUDA context to * be associated with a CPU process. A host thread may have only one device * context current at a time. * * Refer to the CUDA programming guide 4.5.3.3 on Context Management * ******************************************************************************/ #define MAXTHREADS 256 #define NUM_INTS 32 #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) // Windows threads use different data structures #include <windows.h> DWORD rgdwThreadIds[MAXTHREADS]; HANDLE rghThreads[MAXTHREADS]; CRITICAL_SECTION g_cs; #define ENTERCRITICALSECTION EnterCriticalSection(&g_cs); #define LEAVECRITICALSECTION LeaveCriticalSection(&g_cs); #define STRICMP stricmp #else // Includes POSIX thread headers for Linux thread support #include <pthread.h> #include <stdint.h> pthread_t rghThreads[MAXTHREADS]; pthread_mutex_t g_mutex; #define ENTERCRITICALSECTION pthread_mutex_lock(&g_mutex); #define LEAVECRITICALSECTION pthread_mutex_unlock(&g_mutex); #define STRICMP strcasecmp #endif #include <stdlib.h> #include <stdio.h> #include <cuda.h> #include <cuda_runtime_api.h> #include <helper_cuda_drvapi.h> #include <iostream> #include <cstring> using namespace std; int NumThreads; int ThreadLaunchCount; typedef struct _CUDAContext_st { CUcontext hcuContext; CUmodule hcuModule; CUfunction hcuFunction; CUdeviceptr dptr; int deviceID; int threadNum; } CUDAContext; CUDAContext g_ThreadParams[MAXTHREADS]; // define input fatbin file #ifndef FATBIN_FILE #define FATBIN_FILE "threadMigration_kernel64.fatbin" #endif bool gbAutoQuit = false; //////////////////////////////////////////////////////////////////////////////// // declaration, forward bool runTest(int argc, char **argv); #define CLEANUP_ON_ERROR(dptr, hcuModule, hcuContext, status) \ if (dptr) cuMemFree(dptr); \ if (hcuModule) cuModuleUnload(hcuModule); \ if (hcuContext) cuCtxDestroy(hcuContext); \ return status; #define THREAD_QUIT \ printf("Error\n"); \ return 0; // This sample uses the Driver API interface. The CUDA context needs // to be setup and the CUDA module (CUBIN) is built by NVCC static CUresult InitCUDAContext(CUDAContext *pContext, CUdevice hcuDevice, int deviceID, char **argv) { CUcontext hcuContext = 0; CUmodule hcuModule = 0; CUfunction hcuFunction = 0; CUdeviceptr dptr = 0; // cuCtxCreate: Function works on floating contexts and current context CUresult status = cuCtxCreate(&hcuContext, 0, hcuDevice); if (CUDA_SUCCESS != status) { fprintf(stderr, "cuCtxCreate for <deviceID=%d> failed %d\n", deviceID, status); CLEANUP_ON_ERROR(dptr, hcuModule, hcuContext, status); } status = CUDA_ERROR_INVALID_IMAGE; string module_path, ptx_source; std::ostringstream fatbin; if (!findFatbinPath(FATBIN_FILE, module_path, argv, fatbin)) { exit(EXIT_FAILURE); } else { printf("> initCUDA loading module: <%s>\n", module_path.c_str()); } if (!fatbin.str().size()) { printf("fatbin file empty. exiting..\n"); exit(EXIT_FAILURE); } // Create module from binary file (FATBIN) checkCudaErrors(cuModuleLoadData(&hcuModule, fatbin.str().c_str())); status = cuModuleGetFunction(&hcuFunction, hcuModule, "kernelFunction"); if (CUDA_SUCCESS != status) { fprintf(stderr, "cuModuleGetFunction failed %d\n", status); CLEANUP_ON_ERROR(dptr, hcuModule, hcuContext, status); } // Here we must release the CUDA context from the thread context status = cuCtxPopCurrent(NULL); if (CUDA_SUCCESS != status) { fprintf(stderr, "cuCtxPopCurrent failed %d\n", status); CLEANUP_ON_ERROR(dptr, hcuModule, hcuContext, status); } pContext->hcuContext = hcuContext; pContext->hcuModule = hcuModule; pContext->hcuFunction = hcuFunction; pContext->deviceID = deviceID; return CUDA_SUCCESS; } // ThreadProc launches the CUDA kernel on a CUDA context. // We have more than one thread that talks to a CUDA context #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) DWORD WINAPI ThreadProc(CUDAContext *pParams) #else void *ThreadProc(CUDAContext *pParams) #endif { int wrong = 0; int *pInt = 0; printf("<CUDA Device=%d, Context=%p, Thread=%d> - ThreadProc() Launched...\n", pParams->deviceID, pParams->hcuContext, pParams->threadNum); // cuCtxPushCurrent: Attach the caller CUDA context to the thread context. CUresult status = cuCtxPushCurrent(pParams->hcuContext); if (CUDA_SUCCESS != status) { THREAD_QUIT; } checkCudaErrors(cuMemAlloc(&pParams->dptr, NUM_INTS * sizeof(int))); // There are two ways to launch CUDA kernels via the Driver API. // In this CUDA Sample, we illustrate both ways to pass parameters // and specify parameters. By default we use the simpler method. if (1) { // This is the new CUDA 4.0 API for Kernel Parameter passing and Kernel // Launching (simpler method) void *args[5] = {&pParams->dptr}; // new CUDA 4.0 Driver API Kernel launch call status = cuLaunchKernel(pParams->hcuFunction, 1, 1, 1, 32, 1, 1, 0, NULL, args, NULL); if (CUDA_SUCCESS != status) { fprintf(stderr, "cuLaunch failed %d\n", status); THREAD_QUIT; } } else { // This is the new CUDA 4.0 API for Kernel Parameter passing and Kernel // Launching (advanced method) int offset = 0; char argBuffer[256]; // pass in launch parameters (not actually de-referencing CUdeviceptr). // CUdeviceptr is storing the value of the parameters *((CUdeviceptr *)&argBuffer[offset]) = pParams->dptr; offset += sizeof(CUdeviceptr); void *kernel_launch_config[5] = {CU_LAUNCH_PARAM_BUFFER_POINTER, argBuffer, CU_LAUNCH_PARAM_BUFFER_SIZE, &offset, CU_LAUNCH_PARAM_END}; // new CUDA 4.0 Driver API Kernel launch call status = cuLaunchKernel(pParams->hcuFunction, 1, 1, 1, 32, 1, 1, 0, 0, NULL, (void **)&kernel_launch_config); if (CUDA_SUCCESS != status) { fprintf(stderr, "cuLaunch failed %d\n", status); THREAD_QUIT; } } pInt = (int *)malloc(NUM_INTS * sizeof(int)); if (!pInt) return 0; if (CUDA_SUCCESS == cuMemcpyDtoH(pInt, pParams->dptr, NUM_INTS * sizeof(int))) { for (int i = 0; i < NUM_INTS; i++) { if (pInt[i] != 32 - i) { printf("<CUDA Device=%d, Context=%p, Thread=%d> error [%d]=%d!\n", pParams->deviceID, pParams->hcuContext, pParams->threadNum, i, pInt[i]); wrong++; } } ENTERCRITICALSECTION if (!wrong) ThreadLaunchCount += 1; LEAVECRITICALSECTION } free(pInt); fflush(stdout); checkCudaErrors(cuMemFree(pParams->dptr)); // cuCtxPopCurrent: Detach the current CUDA context from the calling thread. checkCudaErrors(cuCtxPopCurrent(NULL)); printf("<CUDA Device=%d, Context=%p, Thread=%d> - ThreadProc() Finished!\n\n", pParams->deviceID, pParams->hcuContext, pParams->threadNum); return 0; } bool FinalErrorCheck(CUDAContext *pContext, int NumThreads, int deviceCount) { if (ThreadLaunchCount != NumThreads * deviceCount) { printf("<Expected=%d, Actual=%d> ThreadLaunchCounts(s)\n", NumThreads * deviceCount, ThreadLaunchCount); return false; } else { for (int iDevice = 0; iDevice < deviceCount; iDevice++) { // cuCtxDestroy called on current context or a floating context if (CUDA_SUCCESS != cuCtxDestroy(pContext[iDevice].hcuContext)) return false; } return true; } } int main(int argc, char **argv) { printf("Starting threadMigration\n"); bool bTestResult = runTest(argc, argv); exit(bTestResult ? EXIT_SUCCESS : EXIT_FAILURE); } bool runTest(int argc, char **argv) { printf("[ threadMigration ] API test...\n"); #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) InitializeCriticalSection(&g_cs); #else pthread_mutex_init(&g_mutex, NULL); #endif // By default, we will launch 2 CUDA threads for each device NumThreads = 2; if (argc > 1) { // If we are doing the QAtest or automated testing, we quit without // prompting if (checkCmdLineFlag(argc, (const char **)argv, "qatest") || checkCmdLineFlag(argc, (const char **)argv, "noprompt")) { gbAutoQuit = true; } if (checkCmdLineFlag(argc, (const char **)argv, "numthreads")) { NumThreads = getCmdLineArgumentInt(argc, (const char **)argv, "numthreads"); if (NumThreads < 1 || NumThreads > 15) { printf( "Usage: \"threadMigration -n=<threads>\", <threads> ranges 1-15\n"); return 1; } } } int deviceCount; int hcuDevice = 0; CUresult status; status = cuInit(0); if (CUDA_SUCCESS != status) return false; status = cuDeviceGetCount(&deviceCount); if (CUDA_SUCCESS != status) return false; printf("> %d CUDA device(s), %d Thread(s)/device to launched\n\n", deviceCount, NumThreads); if (deviceCount == 0) { return false; } int ihThread = 0; int ThreadIndex = 0; CUDAContext *pContext = (CUDAContext *)malloc(sizeof(CUDAContext) * deviceCount); for (int iDevice = 0; iDevice < deviceCount; iDevice++) { char szName[256]; status = cuDeviceGet(&hcuDevice, iDevice); if (CUDA_SUCCESS != status) return false; status = cuDeviceGetName(szName, 256, hcuDevice); if (CUDA_SUCCESS != status) return false; { int major = 0, minor = 0; checkCudaErrors(cuDeviceGetAttribute( &major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, hcuDevice)); checkCudaErrors(cuDeviceGetAttribute( &minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, hcuDevice)); int sharedMemPerBlock; checkCudaErrors(cuDeviceGetAttribute( &sharedMemPerBlock, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, hcuDevice)); int totalConstantMemory; checkCudaErrors(cuDeviceGetAttribute( &totalConstantMemory, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, hcuDevice)); int regsPerBlock; checkCudaErrors(cuDeviceGetAttribute( &regsPerBlock, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, hcuDevice)); int clockRate; checkCudaErrors(cuDeviceGetAttribute( &clockRate, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, hcuDevice)); printf("Device %d: \"%s\" (Compute %d.%d)\n", iDevice, szName, major, minor); printf("\tsharedMemPerBlock: %d\n", sharedMemPerBlock); printf("\tconstantMemory : %d\n", totalConstantMemory); printf("\tregsPerBlock : %d\n", regsPerBlock); printf("\tclockRate : %d\n", clockRate); printf("\n"); } if (CUDA_SUCCESS != InitCUDAContext(&pContext[iDevice], hcuDevice, iDevice, argv)) { return FinalErrorCheck(pContext, NumThreads, deviceCount); } else { for (int iThread = 0; iThread < NumThreads; iThread++, ihThread++) { g_ThreadParams[ThreadIndex].hcuContext = pContext[iDevice].hcuContext; g_ThreadParams[ThreadIndex].hcuModule = pContext[iDevice].hcuModule; g_ThreadParams[ThreadIndex].hcuFunction = pContext[iDevice].hcuFunction; g_ThreadParams[ThreadIndex].deviceID = pContext[iDevice].deviceID; g_ThreadParams[ThreadIndex].threadNum = iThread; // Launch (NumThreads) for each CUDA context #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) rghThreads[ThreadIndex] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, &g_ThreadParams[ThreadIndex], 0, &rgdwThreadIds[ThreadIndex]); #else // Assume we are running linux pthread_create(&rghThreads[ThreadIndex], NULL, (void *(*)(void *))ThreadProc, &g_ThreadParams[ThreadIndex]); #endif ThreadIndex += 1; } } } // Wait until all workers are done #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) WaitForMultipleObjects(ThreadIndex, rghThreads, TRUE, INFINITE); #else for (int i = 0; i < ThreadIndex; i++) { pthread_join(rghThreads[i], NULL); } #endif bool ret_status = FinalErrorCheck(pContext, NumThreads, deviceCount); free(pContext); return ret_status; }
33.148492
80
0.67208
rob-opsi
ace411b3a3f20ac6879fbaa863a943dedd909894
1,362
hh
C++
include/Activia/ActGuiRun.hh
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
1
2020-11-04T08:32:23.000Z
2020-11-04T08:32:23.000Z
include/Activia/ActGuiRun.hh
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
null
null
null
include/Activia/ActGuiRun.hh
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
1
2020-11-04T08:32:30.000Z
2020-11-04T08:32:30.000Z
#ifdef ACT_USE_QT #ifndef ACT_GUI_RUN_HH #define ACT_GUI_RUN_HH #include "Activia/ActAbsRun.hh" #include "Activia/ActGuiWindow.hh" #include "QtGui/qdialog.h" #include "QtGui/qmenubar.h" #include "QtGui/qprogressbar.h" /// \brief Run all of the isotope production code using a GUI /// /// All relevent input and output classes as well as the /// cross-section and isotope yield calculations will be called /// here using the abstract ActAbsRun interface. class ActGuiRun : public QDialog, public ActAbsRun { Q_OBJECT public: /// Constructor ActGuiRun(); /// Destructor virtual ~ActGuiRun(); /// Define how the input to the calculations are obtained. virtual void defineInput(); /// Make the GUI and run the calculations void makeGui(); public slots: /// Run the calculations void runCode(); /// Stop the calculations void stopCode(); /// Create pop-up window with brief description about the software void about(); /// Create pop-up window showing the usage license for the code void license(); /// Clear all GUI inputs void clearInput(); /// Save the GUI inputs void saveInput(); /// Load the GUI inputs void loadInput(); protected: private: QProgressBar* _progressBar; ActGuiWindow* _guiWindow; /// Create the top menu bar for the GUI QMenuBar* createMenu(); }; #endif #endif
19.457143
68
0.707048
UniversityofWarwick
ace45f838efefc721e7e28f82d34c4a06ce2b73d
9,652
cc
C++
processors/IA32/bochs/cpu/bit32.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
445
2016-06-30T08:19:11.000Z
2022-03-28T06:09:49.000Z
processors/IA32/bochs/cpu/bit32.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
439
2016-06-29T20:14:36.000Z
2022-03-17T19:59:58.000Z
processors/IA32/bochs/cpu/bit32.cc
pavel-krivanek/opensmalltalk-vm
694dfe3ed015e16f5b8e9cf17d37e4bdd32bea16
[ "MIT" ]
137
2016-07-02T17:32:07.000Z
2022-03-20T11:17:25.000Z
///////////////////////////////////////////////////////////////////////// // $Id: bit32.cc,v 1.14 2008/08/11 18:53:23 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ///////////////////////////////////////////////////////////////////////// #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #include "cpu.h" #define LOG_THIS BX_CPU_THIS_PTR #if BX_CPU_LEVEL >= 3 void BX_CPP_AttrRegparmN(1) BX_CPU_C::BSF_GdEdR(bxInstruction_c *i) { Bit32u op2_32 = BX_READ_32BIT_REG(i->rm()); if (op2_32 == 0) { assert_ZF(); /* op1_32 undefined */ } else { Bit32u op1_32 = 0; while ((op2_32 & 0x01) == 0) { op1_32++; op2_32 >>= 1; } SET_FLAGS_OSZAPC_LOGIC_32(op1_32); clear_ZF(); /* now write result back to destination */ BX_WRITE_32BIT_REGZ(i->nnn(), op1_32); } } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BSR_GdEdR(bxInstruction_c *i) { Bit32u op2_32 = BX_READ_32BIT_REG(i->rm()); if (op2_32 == 0) { assert_ZF(); /* op1_32 undefined */ } else { Bit32u op1_32 = 31; while ((op2_32 & 0x80000000) == 0) { op1_32--; op2_32 <<= 1; } SET_FLAGS_OSZAPC_LOGIC_32(op1_32); clear_ZF(); /* now write result back to destination */ BX_WRITE_32BIT_REGZ(i->nnn(), op1_32); } } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BT_EdGdM(bxInstruction_c *i) { bx_address op1_addr; Bit32u op1_32, op2_32, index; Bit32s displacement32; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); op2_32 = BX_READ_32BIT_REG(i->nnn()); index = op2_32 & 0x1f; displacement32 = ((Bit32s) (op2_32&0xffffffe0)) / 32; op1_addr = eaddr + 4 * displacement32; if (! i->as32L()) op1_addr = (Bit16u) op1_addr; #if BX_SUPPORT_X86_64 else if (! i->as64L()) op1_addr = (Bit32u) op1_addr; #endif /* pointer, segment address pair */ op1_32 = read_virtual_dword(i->seg(), op1_addr); set_CF((op1_32 >> index) & 0x01); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BT_EdGdR(bxInstruction_c *i) { Bit32u op1_32, op2_32; op1_32 = BX_READ_32BIT_REG(i->rm()); op2_32 = BX_READ_32BIT_REG(i->nnn()); op2_32 &= 0x1f; set_CF((op1_32 >> op2_32) & 0x01); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTS_EdGdM(bxInstruction_c *i) { bx_address op1_addr; Bit32u op1_32, op2_32, index; Bit32s displacement32; bx_bool bit_i; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); op2_32 = BX_READ_32BIT_REG(i->nnn()); index = op2_32 & 0x1f; displacement32 = ((Bit32s) (op2_32&0xffffffe0)) / 32; op1_addr = eaddr + 4 * displacement32; if (! i->as32L()) op1_addr = (Bit16u) op1_addr; #if BX_SUPPORT_X86_64 else if (! i->as64L()) op1_addr = (Bit32u) op1_addr; #endif /* pointer, segment address pair */ op1_32 = read_RMW_virtual_dword(i->seg(), op1_addr); bit_i = (op1_32 >> index) & 0x01; op1_32 |= (((Bit32u) 1) << index); write_RMW_virtual_dword(op1_32); set_CF(bit_i); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTS_EdGdR(bxInstruction_c *i) { Bit32u op1_32, op2_32; op1_32 = BX_READ_32BIT_REG(i->rm()); op2_32 = BX_READ_32BIT_REG(i->nnn()); op2_32 &= 0x1f; set_CF((op1_32 >> op2_32) & 0x01); op1_32 |= (((Bit32u) 1) << op2_32); /* now write result back to the destination */ BX_WRITE_32BIT_REGZ(i->rm(), op1_32); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTR_EdGdM(bxInstruction_c *i) { bx_address op1_addr; Bit32u op1_32, op2_32, index; Bit32s displacement32; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); op2_32 = BX_READ_32BIT_REG(i->nnn()); index = op2_32 & 0x1f; displacement32 = ((Bit32s) (op2_32&0xffffffe0)) / 32; op1_addr = eaddr + 4 * displacement32; if (! i->as32L()) op1_addr = (Bit16u) op1_addr; #if BX_SUPPORT_X86_64 else if (! i->as64L()) op1_addr = (Bit32u) op1_addr; #endif /* pointer, segment address pair */ op1_32 = read_RMW_virtual_dword(i->seg(), op1_addr); bx_bool temp_cf = (op1_32 >> index) & 0x01; op1_32 &= ~(((Bit32u) 1) << index); /* now write back to destination */ write_RMW_virtual_dword(op1_32); set_CF(temp_cf); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTR_EdGdR(bxInstruction_c *i) { Bit32u op1_32, op2_32; op1_32 = BX_READ_32BIT_REG(i->rm()); op2_32 = BX_READ_32BIT_REG(i->nnn()); op2_32 &= 0x1f; set_CF((op1_32 >> op2_32) & 0x01); op1_32 &= ~(((Bit32u) 1) << op2_32); /* now write result back to the destination */ BX_WRITE_32BIT_REGZ(i->rm(), op1_32); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTC_EdGdM(bxInstruction_c *i) { bx_address op1_addr; Bit32u op1_32, op2_32, index_32; Bit32s displacement32; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); op2_32 = BX_READ_32BIT_REG(i->nnn()); index_32 = op2_32 & 0x1f; displacement32 = ((Bit32s) (op2_32 & 0xffffffe0)) / 32; op1_addr = eaddr + 4 * displacement32; if (! i->as32L()) op1_addr = (Bit16u) op1_addr; #if BX_SUPPORT_X86_64 else if (! i->as64L()) op1_addr = (Bit32u) op1_addr; #endif op1_32 = read_RMW_virtual_dword(i->seg(), op1_addr); bx_bool temp_CF = (op1_32 >> index_32) & 0x01; op1_32 ^= (((Bit32u) 1) << index_32); /* toggle bit */ set_CF(temp_CF); write_RMW_virtual_dword(op1_32); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTC_EdGdR(bxInstruction_c *i) { Bit32u op1_32, op2_32; op1_32 = BX_READ_32BIT_REG(i->rm()); op2_32 = BX_READ_32BIT_REG(i->nnn()); op2_32 &= 0x1f; bx_bool temp_CF = (op1_32 >> op2_32) & 0x01; op1_32 ^= (((Bit32u) 1) << op2_32); /* toggle bit */ set_CF(temp_CF); BX_WRITE_32BIT_REGZ(i->rm(), op1_32); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BT_EdIbM(bxInstruction_c *i) { bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); Bit32u op1_32 = read_virtual_dword(i->seg(), eaddr); Bit8u op2_8 = i->Ib() & 0x1f; set_CF((op1_32 >> op2_8) & 0x01); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BT_EdIbR(bxInstruction_c *i) { Bit32u op1_32 = BX_READ_32BIT_REG(i->rm()); Bit8u op2_8 = i->Ib() & 0x1f; set_CF((op1_32 >> op2_8) & 0x01); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTS_EdIbM(bxInstruction_c *i) { Bit8u op2_8 = i->Ib() & 0x1f; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); Bit32u op1_32 = read_RMW_virtual_dword(i->seg(), eaddr); bx_bool temp_CF = (op1_32 >> op2_8) & 0x01; op1_32 |= (((Bit32u) 1) << op2_8); write_RMW_virtual_dword(op1_32); set_CF(temp_CF); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTS_EdIbR(bxInstruction_c *i) { Bit8u op2_8 = i->Ib() & 0x1f; Bit32u op1_32 = BX_READ_32BIT_REG(i->rm()); bx_bool temp_CF = (op1_32 >> op2_8) & 0x01; op1_32 |= (((Bit32u) 1) << op2_8); BX_WRITE_32BIT_REGZ(i->rm(), op1_32); set_CF(temp_CF); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTC_EdIbM(bxInstruction_c *i) { Bit8u op2_8 = i->Ib() & 0x1f; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); Bit32u op1_32 = read_RMW_virtual_dword(i->seg(), eaddr); bx_bool temp_CF = (op1_32 >> op2_8) & 0x01; op1_32 ^= (((Bit32u) 1) << op2_8); /* toggle bit */ write_RMW_virtual_dword(op1_32); set_CF(temp_CF); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTC_EdIbR(bxInstruction_c *i) { Bit8u op2_8 = i->Ib() & 0x1f; Bit32u op1_32 = BX_READ_32BIT_REG(i->rm()); bx_bool temp_CF = (op1_32 >> op2_8) & 0x01; op1_32 ^= (((Bit32u) 1) << op2_8); /* toggle bit */ BX_WRITE_32BIT_REGZ(i->rm(), op1_32); set_CF(temp_CF); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTR_EdIbM(bxInstruction_c *i) { Bit8u op2_8 = i->Ib() & 0x1f; bx_address eaddr = BX_CPU_CALL_METHODR(i->ResolveModrm, (i)); Bit32u op1_32 = read_RMW_virtual_dword(i->seg(), eaddr); bx_bool temp_CF = (op1_32 >> op2_8) & 0x01; op1_32 &= ~(((Bit32u) 1) << op2_8); write_RMW_virtual_dword(op1_32); set_CF(temp_CF); } void BX_CPP_AttrRegparmN(1) BX_CPU_C::BTR_EdIbR(bxInstruction_c *i) { Bit8u op2_8 = i->Ib() & 0x1f; Bit32u op1_32 = BX_READ_32BIT_REG(i->rm()); bx_bool temp_CF = (op1_32 >> op2_8) & 0x01; op1_32 &= ~(((Bit32u) 1) << op2_8); BX_WRITE_32BIT_REGZ(i->rm(), op1_32); set_CF(temp_CF); } /* 0F B8 */ void BX_CPP_AttrRegparmN(1) BX_CPU_C::POPCNT_GdEdR(bxInstruction_c *i) { #if BX_SUPPORT_POPCNT || (BX_SUPPORT_SSE > 4) || (BX_SUPPORT_SSE >= 4 && BX_SUPPORT_SSE_EXTENSION > 0) Bit32u op2_32 = BX_READ_32BIT_REG(i->rm()); Bit32u op1_32 = 0; while (op2_32 != 0) { if (op2_32 & 1) op1_32++; op2_32 >>= 1; } Bit32u flags = op1_32 ? 0 : EFlagsZFMask; setEFlagsOSZAPC(flags); /* now write result back to destination */ BX_WRITE_32BIT_REGZ(i->nnn(), op1_32); #else BX_INFO(("POPCNT_GdEd: required POPCNT support, use --enable-popcnt option")); exception(BX_UD_EXCEPTION, 0, 0); #endif } #endif // (BX_CPU_LEVEL >= 3)
26.228261
102
0.657688
pavel-krivanek
ace4a50850d5f4d87cbe2a154f3840bcdccfc00b
17,895
cpp
C++
YGO3_Decoder/YGO3_Decoder.cpp
xan1242/ygo3_decoder
ed2344021c7a9ee92efbd2059ce7da245705ac1a
[ "MIT" ]
null
null
null
YGO3_Decoder/YGO3_Decoder.cpp
xan1242/ygo3_decoder
ed2344021c7a9ee92efbd2059ce7da245705ac1a
[ "MIT" ]
null
null
null
YGO3_Decoder/YGO3_Decoder.cpp
xan1242/ygo3_decoder
ed2344021c7a9ee92efbd2059ce7da245705ac1a
[ "MIT" ]
null
null
null
// Yu-Gi-Oh! Online 3 File Codec // #include "stdafx.h" #include "DecodeKeys.h" #include <stdlib.h> #include <string.h> char DecodeKeys1[0x48] = DECODE_KEYS_1; char DecodeKeys2[0x1000] = DECODE_KEYS_2; char* OutputFileName; char FileExt[16]; unsigned int KeyPointers[2]; struct stat st = { 0 }; void __declspec(naked) sub_10E2640() { _asm { push ebx push ebp push esi mov esi, eax mov edx, [esi + 4] mov eax, [esp + 0x10] push edi mov edi, [esi] mov ecx, [edi + 0x44] xor ecx, [eax] mov eax, ecx shr eax, 0x10 and eax, 0xFF mov eax, [edx + eax * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add eax, [edx + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor eax, [edx + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add eax, [edx + ebx * 4 + 0xC00] mov ebx, [esp + 0x18] xor eax, [edi + 0x40] xor eax, [ebx] mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x3C] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, ecx shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, ecx and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x38] xor eax, ebx mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x34] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, ecx shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, ecx and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] mov esi, edx xor ebx, [edi + 0x30] xor eax, ebx mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x2C] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, ecx shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, ecx and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x28] xor eax, ebx mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x24] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov edx, ecx shr edx, 8 and edx, 0xFF xor ebx, [esi + edx * 4 + 0x800] mov edx, ecx and edx, 0xFF add ebx, [esi + edx * 4 + 0xC00] xor ebx, [edi + 0x20] xor eax, ebx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x1C] xor ecx, edx mov edx, ecx shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x18] xor eax, edx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x14] xor ecx, edx mov edx, ecx shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x10] xor eax, edx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0xC] xor ecx, edx mov edx, ecx shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 8] xor eax, edx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 4] xor ecx, edx mov edx, [edi] xor edx, eax mov eax, [esp + 0x14] pop edi pop esi mov[eax], edx mov edx, [esp + 0x10] pop ebp mov[edx], ecx pop ebx retn } } void __declspec(naked) sub_10E2210() { _asm { push ebx push ebp push esi mov esi, eax mov edx, [esi + 4] mov eax, [esp + 0x10] mov ecx, [eax] push edi mov edi, [esi] xor ecx, [edi] mov eax, ecx shr eax, 0x10 and eax, 0xFF mov eax, [edx + eax * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add eax, [edx + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor eax, [edx + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add eax, [edx + ebx * 4 + 0xC00] mov ebx, [esp + 0x18] xor eax, [edi + 4] xor eax, [ebx] mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 8] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, ecx shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, ecx and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0xC] xor eax, ebx mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x10] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, ecx shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, ecx and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] mov esi, edx xor ebx, [edi + 0x14] xor eax, ebx mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x18] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, ecx shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, ecx and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x1C] xor eax, ebx mov ebx, eax shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, eax shr ebp, 0x18 add ebx, [edx + ebp * 4] mov ebp, eax shr ebp, 8 and ebp, 0xFF xor ebx, [edx + ebp * 4 + 0x800] mov ebp, eax and ebp, 0xFF add ebx, [edx + ebp * 4 + 0xC00] xor ebx, [edi + 0x20] xor ecx, ebx mov ebx, ecx shr ebx, 0x10 and ebx, 0xFF mov ebx, [edx + ebx * 4 + 0x400] mov ebp, ecx shr ebp, 0x18 add ebx, [edx + ebp * 4] mov edx, ecx shr edx, 8 and edx, 0xFF xor ebx, [esi + edx * 4 + 0x800] mov edx, ecx and edx, 0xFF add ebx, [esi + edx * 4 + 0xC00] xor ebx, [edi + 0x24] xor eax, ebx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x28] xor ecx, edx mov edx, ecx shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x2C] xor eax, edx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x30] xor ecx, edx mov edx, ecx shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x34] xor eax, edx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x38] xor ecx, edx mov edx, ecx shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, ecx shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, ecx shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, ecx and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x3C] xor eax, edx mov edx, eax shr edx, 0x10 and edx, 0xFF mov edx, [esi + edx * 4 + 0x400] mov ebx, eax shr ebx, 0x18 add edx, [esi + ebx * 4] mov ebx, eax shr ebx, 8 and ebx, 0xFF xor edx, [esi + ebx * 4 + 0x800] mov ebx, eax xor eax, [edi + 0x44] and ebx, 0xFF add edx, [esi + ebx * 4 + 0xC00] xor edx, [edi + 0x40] pop edi xor ecx, edx mov edx, [esp + 0x14] pop esi mov[edx], ecx mov ecx, [esp + 0xC] pop ebp mov[ecx], eax pop ebx retn 8 } } int YGO3Encoder(int Length, int XORKeys, int InputBuffer) { int v4; int v6; int v7; unsigned int v8; int result; int v10; int v15; unsigned int v16; unsigned int something; v4 = Length; v6 = InputBuffer; v7 = Length; if (Length & 7) { v7 = Length - (Length & 7) + 8; v15 = Length - (Length & 7) + 8; } else { v15 = Length; } v8 = 0; v16 = 0; if (v7) { while (1) { v10 = v4 - 7; if (v8 >= v10) { if (v7 - v4 > 0) memset((void *)(v6 + v4), 0, v7 - v4); something = v6 + 4; _asm { push something push v6 mov eax, XORKeys call sub_10E2210 } v6 += 8; } else { something = v6 + 4; _asm { push something push v6 mov eax, XORKeys call sub_10E2210 } v6 += 8; } v8 += 8; v16 = v8; if (v8 >= v15) break; v7 = v15; } result = v15; } else { result = 0; } return result; } int YGO3Decoder(int Length, int XORKeys, int InputBuffer) { int v4; unsigned int v6; unsigned int something; v4 = InputBuffer; if (Length) { v6 = ((unsigned int)(Length - 1) >> 3) + 1; do { something = v4 + 4; _asm { push something push v4 mov eax, XORKeys call sub_10E2640 add esp, 8 } v4 += 8; --v6; } while (v6); } return 0; } int EncodeYGO3File(char* InFilename, char* OutFilename) { FILE* fin = fopen(InFilename, "rb"); unsigned int FileLength = 0; void* InBuffer = NULL; if (fin == NULL) { printf("ERROR: Can't open file for reading: %s\n", InFilename); perror("ERROR"); return -1; } stat(InFilename, &st); InBuffer = malloc(st.st_size); fread(InBuffer, st.st_size, 1, fin); KeyPointers[0] = (int)DecodeKeys1; KeyPointers[1] = (int)DecodeKeys2; YGO3Encoder(st.st_size, (int)KeyPointers, (int)InBuffer); FILE* fout = fopen(OutFilename, "wb"); if (fout == NULL) { printf("ERROR: Can't open file for writing: %s\n", OutFilename); perror("ERROR"); return -1; } FileLength = _byteswap_ulong(st.st_size ^ 0x77777777); fwrite(&FileLength, sizeof(int), 1, fout); fwrite(InBuffer, st.st_size, 1, fout); fclose(fout); fclose(fin); return 0; } int DecodeYGO3File(char* InFilename, char* OutFilename) { FILE* fin = fopen(InFilename, "rb"); unsigned int FileLength = 0; void* InBuffer = NULL; if (fin == NULL) { printf("ERROR: Can't open file for reading: %s\n", InFilename); perror("ERROR"); return -1; } fread(&FileLength, sizeof(int), 1, fin); FileLength = _byteswap_ulong(FileLength); FileLength ^= 0x77777777; InBuffer = malloc(FileLength); fread(InBuffer, FileLength, 1, fin); KeyPointers[0] = (int)DecodeKeys1; KeyPointers[1] = (int)DecodeKeys2; YGO3Decoder(FileLength, (int)KeyPointers, (int)InBuffer); FILE* fout = fopen(OutFilename, "wb"); if (fout == NULL) { printf("ERROR: Can't open file for writing: %s\n", OutFilename); perror("ERROR"); return -1; } fwrite(InBuffer, FileLength, 1, fout); fclose(fout); fclose(fin); return 0; } int main(int argc, char *argv[]) { printf("Yu-Gi-Oh! Online 3 File Codec\n"); if (argc < 2) { printf("USAGE (decode): %s InFileName [OutFileName]\n", argv[0]); printf("USAGE (encode): %s -e InFileName [OutFileName]\n", argv[0]); return -1; } if (argv[1][0] == '-' && argv[1][1] == 'e') // encoding mode { if (argc == 3) { char* PatchPoint; OutputFileName = (char*)calloc(strlen(argv[2]), sizeof(char) + 8); strcpy(OutputFileName, argv[2]); PatchPoint = strrchr(OutputFileName, '.'); strcpy(FileExt, PatchPoint); sprintf(PatchPoint, "_encoded%s", FileExt); } else OutputFileName = argv[3]; return EncodeYGO3File(argv[2], OutputFileName); } if (argc == 2) { char* PatchPoint; OutputFileName = (char*)calloc(strlen(argv[1]), sizeof(char) + 8); strcpy(OutputFileName, argv[1]); PatchPoint = strrchr(OutputFileName, '.'); strcpy(FileExt, PatchPoint); sprintf(PatchPoint, "_decoded%s", FileExt); } else OutputFileName = argv[2]; return DecodeYGO3File(argv[1], OutputFileName); }
21.984029
71
0.501481
xan1242
ace4ff0b3f45dcf59d65921a5707091c2f87a03b
14,919
cpp
C++
Orbit/src/Render/VulkanBase.cpp
JusticesHand/orbit-engine
fd9bd160f6e54fb49a9e720f0c409ae5deb6e676
[ "MIT" ]
null
null
null
Orbit/src/Render/VulkanBase.cpp
JusticesHand/orbit-engine
fd9bd160f6e54fb49a9e720f0c409ae5deb6e676
[ "MIT" ]
8
2017-09-05T04:12:03.000Z
2017-10-26T03:17:07.000Z
Orbit/src/Render/VulkanBase.cpp
JusticesHand/orbit-engine
fd9bd160f6e54fb49a9e720f0c409ae5deb6e676
[ "MIT" ]
null
null
null
/*! @file Render/VulkanBase.cpp */ #include "Render/VulkanBase.h" #include "Input/Window.h" #include <iostream> #if defined(USE_WIN32) #error Win32Window not implemented yet! #elif defined(USE_XWINDOW) #error XWindow is not implemented yet! #elif defined(USE_WAYLAND) #error WaylandWindow is not implemented yet! #else #include <GLFW/glfw3.h> #endif namespace { constexpr bool UseValidation = true; constexpr std::array<const char*, 1> RequiredDeviceExtensions{ VK_KHR_SWAPCHAIN_EXTENSION_NAME }; constexpr std::array<const char*, 1> ValidationLayers{ "VK_LAYER_LUNARG_standard_validation" }; /*! @brief Debug callback function to be run by Vulkan in case of errors. @param flags The flags of the debug error. @param objType The type of the object that triggered the error. @param obj The handle of the object that triggered the error. @param location The location of the object that triggered the error. @param code The error code. @param layerPrefix The prefix of the layer that triggered the error. @param msg The actual message of the error. @param userData User data for the error. @return Whether the error should abort the call or not. For the same behaviour as without debugging layers enabled, it should return VK_FALSE (which it does). */ VKAPI_ATTR VkBool32 VKAPI_CALL debugCallbackFunc( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char* layerPrefix, const char* msg, void* userData) { std::cerr << "validation layer (" << layerPrefix << "): " << msg << std::endl; return VK_FALSE; } } using namespace Orbit; bool VulkanBase::QueueFamilyIndices::completed() const { return transferQueueFamily != std::numeric_limits<uint32_t>::max() && graphicsQueueFamily != std::numeric_limits<uint32_t>::max() && presentQueueFamily != std::numeric_limits<uint32_t>::max(); } std::set<uint32_t> VulkanBase::QueueFamilyIndices::uniqueQueues() const { return std::set<uint32_t>{ transferQueueFamily, graphicsQueueFamily, presentQueueFamily }; } VulkanBase::VulkanBase(std::nullptr_t) { } VulkanBase::VulkanBase(const Window* window) { std::vector<const char*> extensions; std::vector<const char*> layers; if (UseValidation)// if constexpr { extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); layers.insert(layers.end(), ValidationLayers.begin(), ValidationLayers.end()); } #if defined(USE_WIN32) #error Win32Window not implemented yet #elif defined(USE_XWINDOW) #error XWindow not implemented yet #elif defined(USE_WAYLAND) #error WaylandWindow not implemented yet #else uint32_t glfwExtensionCount = 0; const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); for (uint32_t i = 0; i < glfwExtensionCount; i++) extensions.push_back(glfwExtensions[i]); #endif _instance = createInstance(extensions, layers); _debugCallback = createDebugReportCallback(_instance); _surface = createSurface(window->handle(), _instance); _physicalDevice = pickPhysicalDevice(_instance, _surface); _indices = retrieveQueueFamilyIndices(_physicalDevice, _surface); _device = createDevice(_physicalDevice, _indices); _transferCommandPool = createCommandPool(_device, _indices.transferQueueFamily); _graphicsCommandPool = createCommandPool(_device, _indices.graphicsQueueFamily); } VulkanBase::VulkanBase(VulkanBase&& rhs) : _instance(rhs._instance), _debugCallback(rhs._debugCallback), _surface(rhs._surface), _physicalDevice(rhs._physicalDevice), _device(rhs._device), _indices(rhs._indices), _transferCommandPool(rhs._transferCommandPool), _graphicsCommandPool(rhs._graphicsCommandPool) { rhs._instance = nullptr; rhs._debugCallback = nullptr; rhs._surface = nullptr; rhs._physicalDevice = nullptr; rhs._device = nullptr; rhs._transferCommandPool = nullptr; rhs._graphicsCommandPool = nullptr; } VulkanBase& VulkanBase::operator=(VulkanBase&& rhs) { _instance = rhs._instance; _debugCallback = rhs._debugCallback; _surface = rhs._surface; _physicalDevice = rhs._physicalDevice; _device = rhs._device; _indices = rhs._indices; _transferCommandPool = rhs._transferCommandPool; _graphicsCommandPool = rhs._graphicsCommandPool; rhs._instance = nullptr; rhs._debugCallback = nullptr; rhs._surface = nullptr; rhs._physicalDevice = nullptr; rhs._device = nullptr; rhs._transferCommandPool = nullptr; rhs._graphicsCommandPool = nullptr; return *this; } VulkanBase::~VulkanBase() { if (_graphicsCommandPool) _device.destroyCommandPool(_graphicsCommandPool); if (_transferCommandPool) _device.destroyCommandPool(_transferCommandPool); if (_device) _device.destroy(); if (_surface) _instance.destroySurfaceKHR(_surface); if (_debugCallback) destroyDebugCallback(_instance, _debugCallback); if (_instance) _instance.destroy(); } vk::Instance VulkanBase::instance() const { return _instance; } vk::SurfaceKHR VulkanBase::surface() const { return _surface; } vk::PhysicalDevice VulkanBase::physicalDevice() const { return _physicalDevice; } vk::Device VulkanBase::device() const { return _device; } vk::Queue VulkanBase::transferQueue() const { return _device.getQueue(_indices.transferQueueFamily, 0); } vk::Queue VulkanBase::graphicsQueue() const { return _device.getQueue(_indices.graphicsQueueFamily, 0); } vk::Queue VulkanBase::presentQueue() const { return _device.getQueue(_indices.presentQueueFamily, 0); } vk::CommandPool VulkanBase::transferCommandPool() const { return _transferCommandPool; } vk::CommandPool VulkanBase::graphicsCommandPool() const { return _graphicsCommandPool; } VulkanBase::QueueFamilyIndices VulkanBase::indices() const { return _indices; } uint32_t VulkanBase::getMemoryTypeIndex(uint32_t filter, vk::MemoryPropertyFlags flags) const { vk::PhysicalDeviceMemoryProperties memoryProperties = _physicalDevice.getMemoryProperties(); for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) { bool memorySuitable = static_cast<bool>(filter & (1 << i)); bool hasCorrectProperties = (memoryProperties.memoryTypes[i].propertyFlags & flags) == flags; if (memorySuitable && hasCorrectProperties) return i; } return std::numeric_limits<uint32_t>::max(); } void VulkanBase::getLayoutParameters(vk::ImageLayout layout, vk::PipelineStageFlags& stage, vk::AccessFlags& accessFlags) { if (layout == vk::ImageLayout::eUndefined) { stage = vk::PipelineStageFlagBits::eTopOfPipe; accessFlags = vk::AccessFlags(); } else if (layout == vk::ImageLayout::eTransferDstOptimal) { stage = vk::PipelineStageFlagBits::eTransfer; accessFlags = vk::AccessFlagBits::eTransferWrite; } else if (layout == vk::ImageLayout::eShaderReadOnlyOptimal) { stage = vk::PipelineStageFlagBits::eFragmentShader; accessFlags = vk::AccessFlagBits::eShaderRead; } else if (layout == vk::ImageLayout::eDepthStencilAttachmentOptimal) { stage = vk::PipelineStageFlagBits::eEarlyFragmentTests; accessFlags = vk::AccessFlagBits::eDepthStencilAttachmentRead | vk::AccessFlagBits::eDepthStencilAttachmentWrite; } else { throw std::runtime_error("Could not get layout parameters for a layout!"); } } vk::Instance VulkanBase::createInstance(const std::vector<const char*>& extensions, const std::vector<const char*>& layers) { vk::ApplicationInfo appInfo = vk::ApplicationInfo() .setApiVersion(VK_API_VERSION_1_0) .setPApplicationName("Orbit Engine") .setApplicationVersion(VK_MAKE_VERSION(1, 0, 0)) .setPEngineName("Orbit Engine") .setEngineVersion(VK_MAKE_VERSION(1, 0, 0)); vk::InstanceCreateInfo createInfo = vk::InstanceCreateInfo() .setEnabledExtensionCount(static_cast<uint32_t>(extensions.size())) .setPpEnabledExtensionNames(extensions.data()) .setEnabledLayerCount(static_cast<uint32_t>(layers.size())) .setPpEnabledLayerNames(layers.data()) .setPApplicationInfo(&appInfo); return vk::createInstance(createInfo); } vk::DebugReportCallbackEXT VulkanBase::createDebugReportCallback(const vk::Instance& instance) { if (!UseValidation)//if constexpr return nullptr; PFN_vkCreateDebugReportCallbackEXT func = (PFN_vkCreateDebugReportCallbackEXT)_instance.getProcAddr("vkCreateDebugReportCallbackEXT"); if (!func) throw std::runtime_error("Attempted to create a debug callback, but the extension is not present!"); vk::DebugReportCallbackCreateInfoEXT createInfo = vk::DebugReportCallbackCreateInfoEXT() .setFlags(vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::eWarning | vk::DebugReportFlagBitsEXT::ePerformanceWarning) .setPfnCallback(debugCallbackFunc); VkDebugReportCallbackCreateInfoEXT cCreateInfo = static_cast<VkDebugReportCallbackCreateInfoEXT>(createInfo); VkDebugReportCallbackEXT debugReportCallback = nullptr; if (VK_SUCCESS != func(static_cast<VkInstance>(_instance), &cCreateInfo, nullptr, &debugReportCallback)) throw std::runtime_error("There was an error createing the debug report callback!"); return debugReportCallback; } vk::SurfaceKHR VulkanBase::createSurface(void* windowHandle, const vk::Instance& instance) { VkSurfaceKHR surface = nullptr; #if defined(USE_WIN32) #error Win32Window not implemented yet #elif defined(USE_XWINDOW) #error XWindow not implemented yet #elif defined(USE_WAYLAND) #error WaylandWindow not implemented yet #else glfwCreateWindowSurface( static_cast<VkInstance>(_instance), static_cast<GLFWwindow*>(windowHandle), nullptr, &surface); #endif return surface; } vk::PhysicalDevice VulkanBase::pickPhysicalDevice(const vk::Instance& instance, const vk::SurfaceKHR& surface) { std::vector<vk::PhysicalDevice> systemDevices = instance.enumeratePhysicalDevices(); if (systemDevices.empty()) throw std::runtime_error("Could not find a physical device that supports Vulkan!"); vk::PhysicalDevice bestDevice = nullptr; for (const vk::PhysicalDevice& device : systemDevices) { vk::PhysicalDeviceProperties deviceProperties = device.getProperties(); vk::PhysicalDeviceFeatures deviceFeatures = device.getFeatures(); std::vector<vk::ExtensionProperties> extensionProperties = device.enumerateDeviceExtensionProperties(); // TODO: More checks here to get a more suitable device if applicable as the renderer becomes // more complex. // Check if the device can handle sampler anisotropy. Otherwise ignore it. if (!deviceFeatures.samplerAnisotropy) continue; // Check whether or not the device can actually render on our surface, which is pretty important // considering we're attempting to do some rendering. // Applying negative logic here saves simplifies code. std::set<std::string> requiredExtensions{ VK_KHR_SWAPCHAIN_EXTENSION_NAME }; for (const vk::ExtensionProperties& extension : extensionProperties) requiredExtensions.erase(extension.extensionName); if (!requiredExtensions.empty()) continue; // Now we know that we have the required extensions, but do we have the required swap chain support? std::vector<vk::SurfaceFormatKHR> formats = device.getSurfaceFormatsKHR(surface); std::vector<vk::PresentModeKHR> presentModes = device.getSurfacePresentModesKHR(surface); if (formats.empty() || presentModes.empty()) continue; // Check for device queues - there should at least be graphics, present and transfer queues // (which might overlap, and that doesn't really matter). QueueFamilyIndices queueFamilies = retrieveQueueFamilyIndices(device, surface); if (!queueFamilies.completed()) continue; // Always prefer discrete GPUs over integrated (or virtual). if (deviceProperties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) return device; if (deviceProperties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu || deviceProperties.deviceType == vk::PhysicalDeviceType::eVirtualGpu) bestDevice = device; } if (!bestDevice) throw std::runtime_error("Could not choose a suitable physical device that support Vulkan!"); return bestDevice; } vk::Device VulkanBase::createDevice(const vk::PhysicalDevice& device, const QueueFamilyIndices& queueFamilies) { std::set<uint32_t> uniqueQueues{ queueFamilies.uniqueQueues() }; std::vector<vk::DeviceQueueCreateInfo> queueCreateInfos; queueCreateInfos.reserve(uniqueQueues.size()); for (uint32_t queueFamily : uniqueQueues) { const float queuePriority = 1.f; queueCreateInfos.push_back(vk::DeviceQueueCreateInfo() .setQueueFamilyIndex(queueFamily) .setQueueCount(1) .setPQueuePriorities(&queuePriority)); } vk::PhysicalDeviceFeatures deviceFeatures = vk::PhysicalDeviceFeatures() .setSamplerAnisotropy(VK_TRUE); std::vector<const char*> validationLayers; if (UseValidation)//if constexpr validationLayers.insert(validationLayers.end(), ValidationLayers.begin(), ValidationLayers.end()); vk::DeviceCreateInfo createInfo{ vk::DeviceCreateFlags(), static_cast<uint32_t>(queueCreateInfos.size()), queueCreateInfos.data(), static_cast<uint32_t>(validationLayers.size()), validationLayers.data(), static_cast<uint32_t>(RequiredDeviceExtensions.size()), RequiredDeviceExtensions.data(), &deviceFeatures }; return device.createDevice(createInfo); } vk::CommandPool VulkanBase::createCommandPool(const vk::Device& device, uint32_t queueFamilyIndex) { vk::CommandPoolCreateInfo createInfo = vk::CommandPoolCreateInfo() .setFlags(vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer) .setQueueFamilyIndex(queueFamilyIndex); return device.createCommandPool(createInfo); } void VulkanBase::destroyDebugCallback(const vk::Instance& instance, vk::DebugReportCallbackEXT& callback) { PFN_vkDestroyDebugReportCallbackEXT func = (PFN_vkDestroyDebugReportCallbackEXT)instance.getProcAddr("vkDestroyDebugReportCallbackEXT"); if (!func) throw std::runtime_error("Could not find the function to destroy a debug callback!"); func(static_cast<VkInstance>(_instance), static_cast<VkDebugReportCallbackEXT>(callback), nullptr); callback = nullptr; } VulkanBase::QueueFamilyIndices VulkanBase::retrieveQueueFamilyIndices(const vk::PhysicalDevice& physicalDevice, const vk::SurfaceKHR& surface) { QueueFamilyIndices families; std::vector<vk::QueueFamilyProperties> queueFamilyProperties = physicalDevice.getQueueFamilyProperties(); for (size_t i = 0; i < queueFamilyProperties.size(); i++) { const vk::QueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i]; if (queueFamilyProperty.queueCount == 0) continue; uint32_t familyIndex = static_cast<uint32_t>(i); if (queueFamilyProperty.queueFlags & vk::QueueFlagBits::eGraphics) families.graphicsQueueFamily = familyIndex; if (physicalDevice.getSurfaceSupportKHR(familyIndex, surface)) families.presentQueueFamily = familyIndex; if (queueFamilyProperty.queueFlags & vk::QueueFlagBits::eTransfer) families.transferQueueFamily = familyIndex; if (families.completed()) break; } return families; }
31.742553
142
0.779878
JusticesHand
acedb20355f4007776c6263e6fce78f9bd456669
726
cpp
C++
src/InterruptHandler.cpp
Code-Log/UmikoBot
985dc422eadea06464e6610db17d726da9bbcef3
[ "MIT" ]
28
2019-11-15T14:43:48.000Z
2021-12-20T00:48:16.000Z
src/InterruptHandler.cpp
Code-Log/UmikoBot
985dc422eadea06464e6610db17d726da9bbcef3
[ "MIT" ]
22
2019-12-13T11:00:22.000Z
2021-09-29T09:06:10.000Z
src/InterruptHandler.cpp
Code-Log/UmikoBot
985dc422eadea06464e6610db17d726da9bbcef3
[ "MIT" ]
26
2020-02-21T16:28:11.000Z
2021-09-09T09:39:30.000Z
#include "InterruptHandler.h" #include <QtWidgets/QApplication> #if defined(Q_OS_WIN32) #include <windows.h> #elif defined(Q_OS_UNIX) #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #endif #if defined(Q_OS_WIN32) static BOOL WINAPI HandlerRoutine(DWORD sig) { QApplication::quit(); return TRUE; } #elif defined(Q_OS_UNIX) static void HandlerRoutine(int sig) { QApplication::quit(); } #endif void InterruptHandler::Init() { #if defined(Q_OS_WIN32) SetConsoleCtrlHandler(&HandlerRoutine, TRUE); #elif defined(Q_OS_UNIX) struct sigaction sigIntHandler{}; sigIntHandler.sa_handler = &HandlerRoutine; sigemptyset(&sigIntHandler.sa_mask); sigaction(SIGINT, &sigIntHandler, NULL); #endif }
19.105263
46
0.764463
Code-Log
acef8a783993b913184fc0b58bab11983ffca7cf
821
hh
C++
include/khmer/_cpy_countgraph.hh
wltrimbl/khmer
ff95776eabee96420f1ae43d0eff562682cbb17b
[ "CNRI-Python" ]
null
null
null
include/khmer/_cpy_countgraph.hh
wltrimbl/khmer
ff95776eabee96420f1ae43d0eff562682cbb17b
[ "CNRI-Python" ]
null
null
null
include/khmer/_cpy_countgraph.hh
wltrimbl/khmer
ff95776eabee96420f1ae43d0eff562682cbb17b
[ "CNRI-Python" ]
null
null
null
#ifndef _CPY_COUNTGRAPH_HH #define _CPY_COUNTGRAPH_HH #include <Python.h> #include "_cpy_utils.hh" #include "_cpy_hashgraph.hh" namespace khmer { typedef struct { khmer_KHashgraph_Object khashgraph; oxli::Countgraph * countgraph; } khmer_KCountgraph_Object; extern PyTypeObject khmer_KCountgraph_Type CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF("khmer_KCountgraph_Object"); extern PyMethodDef khmer_countgraph_methods[]; PyObject* khmer_countgraph_new(PyTypeObject * type, PyObject * args, PyObject * kwds); void khmer_countgraph_dealloc(khmer_KCountgraph_Object * obj); PyObject * count_get_raw_tables(khmer_KCountgraph_Object * self, PyObject * args); PyObject * count_do_subset_partition_with_abundance(khmer_KCountgraph_Object * me, PyObject * args); } #endif
22.805556
71
0.771011
wltrimbl
acf5a4d1c5bada979452ea50c9d6fd52e3b599d6
3,554
cpp
C++
experiments/Experiment08/M8E8_apw5450.cpp
austinmwhaley/cmps121
d2ae8bad2f5cc6aee50e13f2b5b1a98f041de088
[ "MIT" ]
null
null
null
experiments/Experiment08/M8E8_apw5450.cpp
austinmwhaley/cmps121
d2ae8bad2f5cc6aee50e13f2b5b1a98f041de088
[ "MIT" ]
null
null
null
experiments/Experiment08/M8E8_apw5450.cpp
austinmwhaley/cmps121
d2ae8bad2f5cc6aee50e13f2b5b1a98f041de088
[ "MIT" ]
null
null
null
//Author: Austin Whaley, APW5450, 2019-03-03 //Class: CMPSC 121 //Experiment: 08 //File: cmpsc121/experiments/Experiment08/M7A15_apw5450.cpp //Purpose: Develop Confidence with random numbers /********************************************************************\ * Academic Integrity Affidavit: * * I certify that, this program code is my work. Others may have * * assisted me with planning and concepts, but the code was written, * * solely, by me. * * I understand that submitting code which is totally or partially * * the product of other individuals is a violation of the Academic * * Integrity Policy and accepted ethical precepts. Falsified * * execution results are also results of improper activities. Such * * violations may result in zero credit for the assignment, reduced * * credit for the assignment, or course failure. * \********************************************************************/ /* Out = 58.0 Walk = 9.70 Single = 22.0 Double = 6.1 Triple = 2.5 Home Run = 1.7 - Based on the above percentages, write a program to simulate Casey stepping up to the plate 1000 times and count and display the number of categories. - Then calculate and display his batting average - Enclose login in a do-while loop asking the user if they want to continue <Y or N> (run another simulation) - Run and capture at least 2 simulations */ #include <iostream> #include <cstdlib> // srand & rand function #include <ctime> // time function using namespace std; int main() { unsigned seed = time(0); srand(seed); double batting_avg; int min_val=0, max_val=1000, s, out, walk, single, doubl, triple, homerun; char conf; // Simulation do { // Reset initial values out =0; walk =0; single =0; doubl =0; triple =0; homerun =0; for (int i=0; i < 1000; i++) { s = (rand() % (max_val - min_val + 1)) + min_val; if (s >= 0 && s <= 580) { out += 1; } else if (s > 580 && s <= 677) { walk += 1; } else if (s > 677 && s <= 897) { single += 1; } else if (s > 897 && s <= 958) { doubl += 1; } else if (s > 958 && s <= 983) { triple += 1; } else { homerun += 1; } // end if-tree } // end for-loop batting_avg = static_cast<float>(single + doubl + triple + homerun)/ static_cast<float>(1000 - walk); cout << "Outs = " << out << endl; cout << "Walks = " << walk << endl; cout << "Singles = " << single << endl; cout << "Doubles = " << doubl << endl; cout << "Triples = " << triple << endl; cout << "Home Runs = " << homerun << endl; cout << "Batting AVG = " << batting_avg << endl; cout << "Do you have another purchase to enter? <Y or N> " << endl; cin >> conf; } while (conf == 'Y'); // end do-while loop return 0; } // end main /* Execution Sample Outs = 607 Walks = 105 Singles = 192 Doubles = 58 Triples = 24 Home Runs = 14 Batting AVG = 0.321788 Do you have another purchase to enter? <Y or N> Y Outs = 589 Walks = 95 Singles = 217 Doubles = 61 Triples = 24 Home Runs = 14 Batting AVG = 0.349171 Do you have another purchase to enter? <Y or N> Y Outs = 561 Walks = 85 Singles = 235 Doubles = 82 Triples = 20 Home Runs = 17 Batting AVG = 0.386885 Do you have another purchase to enter? <Y or N> N */
26.132353
79
0.558244
austinmwhaley
acf7955cb0c8b46ddd741c48115b776920fd3a1e
3,518
cpp
C++
B2G/gecko/other-licenses/7zstub/src/Windows/PropVariantConversions.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/other-licenses/7zstub/src/Windows/PropVariantConversions.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/other-licenses/7zstub/src/Windows/PropVariantConversions.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
// PropVariantConversions.cpp #include "StdAfx.h" #include <stdio.h> #include "PropVariantConversions.h" #include "Windows/Defs.h" #include "Common/StringConvert.h" #include "Common/IntToString.h" static UString ConvertUInt64ToString(UInt64 value) { wchar_t buffer[32]; ConvertUInt64ToString(value, buffer); return buffer; } static UString ConvertInt64ToString(Int64 value) { wchar_t buffer[32]; ConvertInt64ToString(value, buffer); return buffer; } /* static void UIntToStringSpec(UInt32 value, char *s, int numPos) { char s2[32]; ConvertUInt64ToString(value, s2); int len = strlen(s2); int i; for (i = 0; i < numPos - len; i++) s[i] = '0'; for (int j = 0; j < len; j++, i++) s[i] = s2[j]; s[i] = '\0'; } */ bool ConvertFileTimeToString(const FILETIME &ft, char *s, bool includeTime, bool includeSeconds) { s[0] = '\0'; SYSTEMTIME st; if(!BOOLToBool(FileTimeToSystemTime(&ft, &st))) return false; /* UIntToStringSpec(st.wYear, s, 4); strcat(s, "-"); UIntToStringSpec(st.wMonth, s + strlen(s), 2); strcat(s, "-"); UIntToStringSpec(st.wDay, s + strlen(s), 2); if (includeTime) { strcat(s, " "); UIntToStringSpec(st.wHour, s + strlen(s), 2); strcat(s, ":"); UIntToStringSpec(st.wMinute, s + strlen(s), 2); if (includeSeconds) { strcat(s, ":"); UIntToStringSpec(st.wSecond, s + strlen(s), 2); } } */ sprintf(s, "%04d-%02d-%02d", st.wYear, st.wMonth, st.wDay); if (includeTime) { sprintf(s + strlen(s), " %02d:%02d", st.wHour, st.wMinute); if (includeSeconds) sprintf(s + strlen(s), ":%02d", st.wSecond); } return true; } UString ConvertFileTimeToString(const FILETIME &fileTime, bool includeTime, bool includeSeconds) { char s[32]; ConvertFileTimeToString(fileTime, s, includeTime, includeSeconds); return GetUnicodeString(s); } UString ConvertPropVariantToString(const PROPVARIANT &propVariant) { switch (propVariant.vt) { case VT_EMPTY: return UString(); case VT_BSTR: return propVariant.bstrVal; case VT_UI1: return ConvertUInt64ToString(propVariant.bVal); case VT_UI2: return ConvertUInt64ToString(propVariant.uiVal); case VT_UI4: return ConvertUInt64ToString(propVariant.ulVal); case VT_UI8: return ConvertUInt64ToString(propVariant.uhVal.QuadPart); case VT_FILETIME: return ConvertFileTimeToString(propVariant.filetime, true, true); /* case VT_I1: return ConvertInt64ToString(propVariant.cVal); */ case VT_I2: return ConvertInt64ToString(propVariant.iVal); case VT_I4: return ConvertInt64ToString(propVariant.lVal); case VT_I8: return ConvertInt64ToString(propVariant.hVal.QuadPart); case VT_BOOL: return VARIANT_BOOLToBool(propVariant.boolVal) ? L"1" : L"0"; default: #ifndef _WIN32_WCE throw 150245; #else return UString(); #endif } } UInt64 ConvertPropVariantToUInt64(const PROPVARIANT &propVariant) { switch (propVariant.vt) { case VT_UI1: return propVariant.bVal; case VT_UI2: return propVariant.uiVal; case VT_UI4: return propVariant.ulVal; case VT_UI8: return (UInt64)propVariant.uhVal.QuadPart; default: #ifndef _WIN32_WCE throw 151199; #else return 0; #endif } }
24.09589
97
0.633883
wilebeast
acf90af34b816b8823c4e40426c066c2e9223c46
1,239
cpp
C++
Application/source/db/migrations/6_RemoveImages.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
106
2020-11-01T09:58:37.000Z
2022-03-26T10:44:26.000Z
Application/source/db/migrations/6_RemoveImages.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
30
2020-11-01T11:21:48.000Z
2022-02-01T23:09:47.000Z
Application/source/db/migrations/6_RemoveImages.cpp
RoutineFree/TriPlayer
4e5ee19c992eba033b57444b7f4b312acf339163
[ "MIT" ]
15
2020-11-02T12:06:03.000Z
2021-08-05T14:22:39.000Z
#include "db/migrations/6_RemoveImages.hpp" namespace Migration { std::string migrateTo6(SQLite * db) { // Add triggers to delete images when a relevant row is deleted bool ok = db->prepareAndExecuteQuery("CREATE TRIGGER deleteAlbumImage AFTER DELETE ON Albums WHEN removeImage(OLD.image_path) BEGIN SELECT 0 WHERE 1; END;"); if (!ok) { return "Failed to create 'deleteAlbumImage' trigger"; } ok = db->prepareAndExecuteQuery("CREATE TRIGGER deleteArtistImage AFTER DELETE ON Artists WHEN removeImage(OLD.image_path) BEGIN SELECT 0 WHERE 1; END;"); if (!ok) { return "Failed to create 'deleteArtistImage' trigger"; } ok = db->prepareAndExecuteQuery("CREATE TRIGGER deletePlaylistImage AFTER DELETE ON Playlists WHEN removeImage(OLD.image_path) BEGIN SELECT 0 WHERE 1; END;"); if (!ok) { return "Failed to create 'deletePlaylistImage' trigger"; } // Bump up version number (only done if everything passes) ok = db->prepareAndExecuteQuery("UPDATE Variables SET value = 6 WHERE name = 'version';"); if (!ok) { return "Unable to set version to 6"; } return ""; } };
45.888889
166
0.649718
RoutineFree
acfb66918f9c2725bb3c91b819491bd3004fd4a3
3,783
cpp
C++
src/Plugins/GOAPPlugin/Tasks/TaskAnimatablePlayWait.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
null
null
null
src/Plugins/GOAPPlugin/Tasks/TaskAnimatablePlayWait.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
null
null
null
src/Plugins/GOAPPlugin/Tasks/TaskAnimatablePlayWait.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
null
null
null
#include "TaskAnimatablePlayWait.h" #include "Interface/AnimationInterface.h" #include "Kernel/Logger.h" #include "Kernel/Assertion.h" #include "Kernel/DocumentHelper.h" #include "TaskAnimatablePlayReceiver.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// TaskAnimatablePlayWait::TaskAnimatablePlayWait( GOAP::Allocator * _allocator, const AnimatablePtr & _animatable, const EventablePtr & _eventable, const DocumentPtr & _doc ) : GOAP::TaskInterface( _allocator ) , m_animatable( _animatable ) , m_eventable( _eventable ) #if MENGINE_DOCUMENT_ENABLE , m_doc( _doc ) #endif { MENGINE_UNUSED( _doc ); } ////////////////////////////////////////////////////////////////////////// TaskAnimatablePlayWait::~TaskAnimatablePlayWait() { } ////////////////////////////////////////////////////////////////////////// bool TaskAnimatablePlayWait::_onRun( GOAP::NodeInterface * _node ) { AnimationInterface * animation = m_animatable->getAnimation(); if( animation == nullptr ) { return true; } animation->play( 0.f ); EventationInterface * eventation = m_eventable->getEventation(); if( eventation == nullptr ) { return true; } TaskAnimatablePlayReceiverPtr receiver = Helper::makeFactorableUnique<TaskAnimatablePlayReceiver>( MENGINE_DOCUMENT_VALUE( m_doc, nullptr ) ); EventReceiverInterfacePtr oldreceiver_end = eventation->addEventReceiver( EVENT_ANIMATION_END, receiver ); EventReceiverInterfacePtr oldreceiver_stop = eventation->addEventReceiver( EVENT_ANIMATION_STOP, receiver ); EventReceiverInterfacePtr oldreceiver_interrupt = eventation->addEventReceiver( EVENT_ANIMATION_INTERRUPT, receiver ); MENGINE_ASSERTION_FATAL( oldreceiver_end == nullptr, "event EVENT_ANIMATION_END override" ); MENGINE_ASSERTION_FATAL( oldreceiver_stop == nullptr, "event EVENT_ANIMATION_STOP override" ); MENGINE_ASSERTION_FATAL( oldreceiver_interrupt == nullptr, "event EVENT_ANIMATION_INTERRUPT override" ); receiver->setGOAPNode( _node ); m_receiver = receiver; return false; } ////////////////////////////////////////////////////////////////////////// bool TaskAnimatablePlayWait::_onSkipable() const { return true; } ////////////////////////////////////////////////////////////////////////// void TaskAnimatablePlayWait::_onSkip() { AnimationInterface * animation = m_animatable->getAnimation(); animation->setLastFrame(); animation->stop(); } ////////////////////////////////////////////////////////////////////////// void TaskAnimatablePlayWait::_onFinally() { EventationInterface * eventation = m_eventable->getEventation(); if( eventation == nullptr ) { return; } EventReceiverInterfacePtr delreceiver_end = eventation->removeEventReceiver( EVENT_ANIMATION_END ); EventReceiverInterfacePtr delreceiver_stop = eventation->removeEventReceiver( EVENT_ANIMATION_STOP ); EventReceiverInterfacePtr delreceiver_interrupt = eventation->removeEventReceiver( EVENT_ANIMATION_INTERRUPT ); MENGINE_ASSERTION_FATAL( m_receiver == delreceiver_end, "event EVENT_ANIMATION_END miss remove" ); MENGINE_ASSERTION_FATAL( m_receiver == delreceiver_stop, "event EVENT_ANIMATION_STOP miss remove" ); MENGINE_ASSERTION_FATAL( m_receiver == delreceiver_interrupt, "event EVENT_ANIMATION_INTERRUPT miss remove" ); m_receiver = nullptr; m_animatable = nullptr; m_eventable = nullptr; } }
38.602041
176
0.613534
Terryhata6
acfe52437cdad9d506c58b9f9d051007341c2bee
2,791
cpp
C++
2018_11_04/src/main.cpp
dafer45/SecondTech
262dda0c3599d182bf4bf51df595078c93b19b20
[ "Apache-2.0" ]
3
2018-10-29T04:33:16.000Z
2019-07-10T18:28:27.000Z
2018_11_04/src/main.cpp
dafer45/SecondTech
262dda0c3599d182bf4bf51df595078c93b19b20
[ "Apache-2.0" ]
null
null
null
2018_11_04/src/main.cpp
dafer45/SecondTech
262dda0c3599d182bf4bf51df595078c93b19b20
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 Kristofer Björnson * * 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 "TBTK/Array.h" #include "TBTK/Model.h" #include "TBTK/PropertyExtractor/Diagonalizer.h" #include "TBTK/Solver/Diagonalizer.h" #include "TBTK/Streams.h" #include "TBTK/TBTK.h" using namespace std; using namespace TBTK; int main(int argc, char **argv){ //Initialize TBTK. Initialize(); //Parameters. const int SIZE_X = 4; const int SIZE_Y = 3; double t = 1; //Create the Model. Model model; for(unsigned int x = 0; x < SIZE_X; x++){ for(unsigned int y = 0; y < SIZE_Y; y++){ model << HoppingAmplitude( 4*t, {x, y}, {x, y} ); if(x + 1 < SIZE_X){ model << HoppingAmplitude( -t, {x + 1, y}, {x, y} ) + HC; } if(y + 1 < SIZE_Y){ model << HoppingAmplitude( -t, {x, y + 1}, {x, y} ) + HC; } } } model.construct(); //Get the HoppingAmplitudeSet from the Model and extract the basis //size. const HoppingAmplitudeSet &hoppingAmplitudeSet = model.getHoppingAmplitudeSet(); unsigned int basisSize = hoppingAmplitudeSet.getBasisSize(); //Initialize the Hamiltonian on a format most suitable for the //algorithm at hand. Array<complex<double>> hamiltonian({basisSize, basisSize}, 0.); //Iterate over the HoppingAmplitudes. for( HoppingAmplitudeSet::ConstIterator iterator = hoppingAmplitudeSet.cbegin(); iterator != hoppingAmplitudeSet.cend(); ++iterator ){ //Extract the amplitude and physical indices from the //HoppingAmplitude. complex<double> amplitude = (*iterator).getAmplitude(); const Index &toIndex = (*iterator).getToIndex(); const Index &fromIndex = (*iterator).getFromIndex(); //Convert the physical indices to linear indices. unsigned int row = hoppingAmplitudeSet.getBasisIndex(toIndex); unsigned int column = hoppingAmplitudeSet.getBasisIndex( fromIndex ); //Write the amplitude to the Hamiltonian that will be used in //this algorithm. hamiltonian[{row, column}] += amplitude; } //Print the Hamiltonian. for(unsigned int row = 0; row < basisSize; row++){ for(unsigned int column = 0; column < basisSize; column++){ Streams::out << real(hamiltonian[{row, column}]) << "\t"; } Streams::out << "\n"; } return 0; }
26.084112
75
0.681834
dafer45
4a00f6a8c140aa42075347ce520ba22e120383c0
1,003
cpp
C++
core/source/detail/string_view.cpp
GremSnoort/actor-zeta
ec9f5624871f1fe3b844bb727e80388ba6c0557e
[ "BSD-3-Clause" ]
null
null
null
core/source/detail/string_view.cpp
GremSnoort/actor-zeta
ec9f5624871f1fe3b844bb727e80388ba6c0557e
[ "BSD-3-Clause" ]
null
null
null
core/source/detail/string_view.cpp
GremSnoort/actor-zeta
ec9f5624871f1fe3b844bb727e80388ba6c0557e
[ "BSD-3-Clause" ]
null
null
null
#include <actor-zeta/detail/string_view.hpp> #if CPP17_OR_GREATER #elif CPP14_OR_GREATER or CPP11_OR_GREATER #include <ostream> namespace std { std::ostream &operator<<(std::ostream &out, actor_zeta::detail::string_view str) { for (auto ch : str) out.put(ch); return out; } string to_string(actor_zeta::detail::string_view v) { return string(v.begin(), v.end()); /// TODO: } } namespace actor_zeta { namespace detail { int string_view::compare(actor_zeta::detail::string_view str) const noexcept { auto s0 = size(); auto s1 = str.size(); auto fallback = [](int x, int y) { return x == 0 ? y : x; }; if (s0 == s1) return strncmp(data(), str.data(), s0); else if (s0 < s1) return fallback(strncmp(data(), str.data(), s0), -1); return fallback(strncmp(data(), str.data(), s1), 1); } }} #endif
26.394737
86
0.54337
GremSnoort
4a02c2e670b5085f6cbe172f79925b143a31ae7e
2,159
hpp
C++
include/rrl/cm/cm_no_reset.hpp
umbreensabirmain/readex-rrl
0cb73b3a3c6948a8dbdce96c240b24d8e992c2fe
[ "BSD-3-Clause" ]
1
2019-10-09T09:15:47.000Z
2019-10-09T09:15:47.000Z
include/rrl/cm/cm_no_reset.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
null
null
null
include/rrl/cm/cm_no_reset.hpp
readex-eu/readex-rrl
ac8722c44f84d65668e2a60e4237ebf51b298c9b
[ "BSD-3-Clause" ]
1
2018-07-13T11:31:05.000Z
2018-07-13T11:31:05.000Z
/* * config_manager.hpp * * Created on: 06.06.2017 * Author: marcel */ #ifndef INCLUDE_CM_NO_RESET_HPP_ #define INCLUDE_CM_NO_RESET_HPP_ #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <mutex> #include <sstream> #include <string> #include <utility> #include <vector> #include <rrl/cm/cm_base.hpp> #include <tmm/parameter_tuple.hpp> #include <util/log.hpp> namespace rrl { namespace cm { /** This class controls the settings stack. * * Only the current configuration will be stored on the stack. When creating the configuration * manager the default configuration is stored. If a new configuration is set the current one will * be modified. If unset is called the current configuration will be returned without removing. * */ class cm_no_reset : public cm_base { public: /** * Constructor * * @brief Constructor * * Initializes the configuration manager with the default configuration. * * @param default_configs default configuration * **/ cm_no_reset(setting default_configs); /** * Destructor * * @brief Destructor * Deletes the configuration manager * **/ ~cm_no_reset(); /** sets parameter * * It compares current with new configuration. If the parameter exists with the same value a *debug * message is printed. If the parameter value differs the new one will be set. If the parameter * doesn't exist it won't be touched. * If the new configuration contains parameters that don't exist in the current configuration *they * will be saved in the settings stack. * * @param new_configs new configuration * **/ void set(setting configs) override; /** returns a copy of the current configuration. * * @return returns a copy of the current configuration. * */ setting unset() override; void atp_add(tmm::parameter_tuple hash) override; setting get_current_config() override; private: setting settings; /**< settings stack with configurations consisting of parameter tuples*/ }; } } #endif /* INCLUDE_CM_NO_RESET_HPP_ */
23.467391
99
0.691524
umbreensabirmain
4a04a4fc080162297ab1faa9e7d1e1ca936e9c20
245
cpp
C++
04. Recursion/taylorseriesiterative.cpp
pratik8696/DSA
049a76b6e2445bb5de2e87f3755038609006c06a
[ "MIT" ]
2
2021-09-27T14:12:28.000Z
2021-09-28T03:35:46.000Z
04. Recursion/taylorseriesiterative.cpp
pratik8696/DSA
049a76b6e2445bb5de2e87f3755038609006c06a
[ "MIT" ]
2
2021-09-30T09:07:11.000Z
2021-10-17T18:42:34.000Z
04. Recursion/taylorseriesiterative.cpp
pratik8696/DSA
049a76b6e2445bb5de2e87f3755038609006c06a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int iterative(int x,int n) { static int s=1; for(;n>0;n--) { s=1+x/n*s; } return s; } int main() { int x,n; cin>>x>>n; cout<<iterative(x,n); return 0; }
11.666667
26
0.493878
pratik8696
4a053aadc637d67124c9c9c6854b80eb6d5d96f8
790
cpp
C++
codes/UVA/10001-19999/uva10115.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/10001-19999/uva10115.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/10001-19999/uva10115.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<iostream> #include<string.h> using namespace std; #define N 15 #define M 85 #define K 260 int main() { char before[N][M], after[N][M]; char str[K], tem[K]; int n; while (cin >> n, n) { getchar(); // Init. memset(before, 0, sizeof(before)); memset(after, 0, sizeof(after)); memset(str, 0, sizeof(str)); // Read. for (int i = 0; i < n; i++) { gets(before[i]); gets(after[i]); } gets(str); // Judge. for (int i = 0; i < n; i++) { int t = strlen(before[i]); int k = strlen(after[i]); do{ char *move = NULL; move = strstr(str, before[i]); if (move == NULL) break; strcpy(tem, move + t); strcpy(move, after[i]); strcpy(move + k, tem); }while (1); } puts(str); } return 0; }
14.90566
36
0.534177
JeraKrs
4a07af97299eb23ec1169cd59022da232c736bf9
1,446
hpp
C++
src/TypeInfo.hpp
MustafaSabur/RobotWereld
e696e6e7ad890abb719a78fc1a0c111a680d27e0
[ "BSD-2-Clause" ]
null
null
null
src/TypeInfo.hpp
MustafaSabur/RobotWereld
e696e6e7ad890abb719a78fc1a0c111a680d27e0
[ "BSD-2-Clause" ]
null
null
null
src/TypeInfo.hpp
MustafaSabur/RobotWereld
e696e6e7ad890abb719a78fc1a0c111a680d27e0
[ "BSD-2-Clause" ]
null
null
null
#ifndef TYPEINFO_HPP_ #define TYPEINFO_HPP_ /* * Copyright (c) 1997 - 2013 Askesis B.V. See license.txt for details. * For information, bug reports and additions send an e-mail to Danu@Askesis.nl. * * Author: jkr */ #include <cstdlib> #include <typeinfo> #include <cxxabi.h> #include <string> /** * @return The demangled (human readable) version of the name() string for std::type_info */ inline std::string demangleTypeInfo(const std::type_info& aTypeInfo) { int status; char* realname; realname = abi::__cxa_demangle(aTypeInfo.name(), 0, 0, &status); std::string result(realname); std::free(realname); return result; } /** * @return The demangled (human readable) version of aTypeInfoString which should contain the name() string for std::type_info */ inline std::string demangleTypeInfo(const std::string& aTypeInfoString) { int status; char* realname; realname = abi::__cxa_demangle(aTypeInfoString.c_str(), 0, 0, &status); std::string result(realname); std::free(realname); return result; } /** * @return The demangled (human readable) version of the name() string for type T */ template<typename T> inline std::string typeinfoFor(const T& x) { return demangleTypeInfo(typeid(x)); } /** * @return The demangled (human readable) version of the name() string for type T */ template<typename T> inline std::string typeinfoFor(T const* & x) { return demangleTypeInfo(typeid(x)); } #endif // DANU_TYPEINFO_HPP_
23.322581
126
0.722683
MustafaSabur
4a096696d26a6a4fc08ed47839971e5973952e5f
11,793
cpp
C++
common/beerocks/hostapd/source/configuration.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
null
null
null
common/beerocks/hostapd/source/configuration.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
null
null
null
common/beerocks/hostapd/source/configuration.cpp
SWRT-dev/easymesh
12d902edde77599e074c0535f7256499b08f7494
[ "BSD-3-Clause", "BSD-2-Clause-Patent", "MIT" ]
null
null
null
/* SPDX-License-Identifier: BSD-2-Clause-Patent * * SPDX-FileCopyrightText: 2016-2020 the prplMesh contributors (see AUTHORS.md) * * This code is subject to the terms of the BSD+Patent license. * See LICENSE file for more details. */ #include <algorithm> #include <easylogging++.h> #include <fstream> #include <hostapd/configuration.h> namespace prplmesh { namespace hostapd { Configuration::Configuration(const std::string &file_name) : m_configuration_file(file_name) {} Configuration::operator bool() const { return m_ok; } bool Configuration::load(const std::set<std::string> &vap_indications) { // please take a look at README.md (common/beerocks/hostapd/README.md) for // the expected format of hostapd configuration file. // loading the file relies on the expected format // otherwise the load fails // for cases when load is called more than once, we // first clear internal data m_hostapd_config_head.clear(); m_hostapd_config_vaps.clear(); // start reading std::ifstream ifs(m_configuration_file); std::string line; bool parsing_vaps = false; std::string cur_vap; // go over line by line in the file while (getline(ifs, line)) { // skip empty lines if (std::all_of(line.begin(), line.end(), isspace)) { continue; } // check if the string belongs to a vap config part and capture which one. auto end_comment = line.find_first_not_of('#'); auto end_key = line.find_first_of('='); std::string current_key(line, end_comment, end_key + 1); auto vap_iterator = vap_indications.find(current_key); if (vap_iterator != vap_indications.end()) { // from now on we are in the vaps area, all // key/value pairs belongs to vaps parsing_vaps = true; // copy the vap value cur_vap = std::string(line, end_key + 1); m_hostapd_config_vaps.push_back(std::make_pair(cur_vap, std::vector<std::string>())); } // if not a vap line store it in the header part of the config, // otherwise add to the currently being parsed vap storage. if (!parsing_vaps) { m_hostapd_config_head.push_back(line); } else { // we always adding to the last vap that was inserted m_hostapd_config_vaps.back().second.push_back(line); } } std::stringstream load_message; load_message << "load() final message: os - " << strerror(errno) << "; existing vaps - " << parsing_vaps; m_last_message = load_message.str(); // if we've got to parsing vaps and no read errors, assume all is good m_ok = parsing_vaps && !ifs.bad(); // return this as bool return *this; } bool Configuration::store() { std::ofstream out_file(m_configuration_file, std::ofstream::out | std::ofstream::trunc); // store the head for (const auto &line : m_hostapd_config_head) { out_file << line << "\n"; } // store the next ones ('bss=') for (auto &vap : m_hostapd_config_vaps) { // add empty line for readability out_file << "\n"; for (auto &line : vap.second) { out_file << line << "\n"; } } m_ok = true; m_last_message = m_configuration_file + " was stored"; // close the file out_file.close(); if (out_file.fail()) { m_last_message = strerror(errno); m_ok = false; } return *this; } bool Configuration::set_create_head_value(const std::string &key, const std::string &value) { // search for the key std::string key_eq(key + "="); auto line_iter = std::find_if( m_hostapd_config_head.begin(), m_hostapd_config_head.end(), [&key_eq, this](const std::string &line) -> bool { return is_key_in_line(line, key_eq); }); // we first delete the key, and if the requested value is non empty // we push it to the end of the array // delete the key-value if found if (line_iter != m_hostapd_config_head.end()) { line_iter = m_hostapd_config_head.erase(line_iter); } else { m_last_message = std::string(__FUNCTION__) + " the key '" + key + "' for head was not found"; } // when the new value is provided add the key back with that new value if (value.length() != 0) { m_hostapd_config_head.push_back(key_eq + value); m_last_message = std::string(__FUNCTION__) + " the key '" + key + "' was (re)added to head"; } else { m_last_message = std::string(__FUNCTION__) + " the key '" + key + "' was deleted from head"; } m_ok = true; return *this; } bool Configuration::set_create_head_value(const std::string &key, const int value) { return set_create_head_value(key, std::to_string(value)); } std::string Configuration::get_head_value(const std::string &key) { std::string key_eq(key + "="); auto line_iter = std::find_if( m_hostapd_config_head.begin(), m_hostapd_config_head.end(), [&key_eq, this](const std::string &line) -> bool { return is_key_in_line(line, key_eq); }); if (line_iter == m_hostapd_config_head.end()) { m_last_message = std::string(__FUNCTION__) + " couldn't find requested key in head: " + key; return ""; } // return from just after the '=' sign to the end of the string return line_iter->substr(line_iter->find('=') + 1); } bool Configuration::set_create_vap_value(const std::string &vap, const std::string &key, const std::string &value) { // search for the requested vap auto find_vap = get_vap(std::string(__FUNCTION__) + " key/value: " + key + '/' + value, vap); if (!std::get<0>(find_vap)) { return false; } auto existing_vap = std::get<1>(find_vap); bool existing_vap_commented = existing_vap->front()[0] == '#'; std::string key_eq(key + "="); auto line_iter = std::find_if( existing_vap->begin(), existing_vap->end(), [&key_eq, this](const std::string &line) -> bool { return is_key_in_line(line, key_eq); }); // we first delete the key, and if the requested value is non empty // we push it to the end of the array // delete the key-value if found if (line_iter != existing_vap->end()) { line_iter = existing_vap->erase(line_iter); } else { m_last_message = std::string(__FUNCTION__) + " the key '" + key + "' for vap " + vap + " was not found"; } // when the new value is provided add the key back with that new value if (value.length() != 0) { if (existing_vap_commented) { existing_vap->push_back('#' + key_eq + value); } else { existing_vap->push_back(key_eq + value); } m_last_message = std::string(__FUNCTION__) + " the key '" + key + "' for vap " + vap + " was (re)added"; } else { m_last_message = std::string(__FUNCTION__) + " the key '" + key + "' for vap " + vap + " was deleted"; } m_ok = true; return *this; } bool Configuration::set_create_vap_value(const std::string &vap, const std::string &key, const int value) { return set_create_vap_value(vap, key, std::to_string(value)); } std::string Configuration::get_vap_value(const std::string &vap, const std::string &key) { // search for the requested vap auto find_vap = get_vap(std::string(__FUNCTION__), vap); if (!std::get<0>(find_vap)) { return ""; } const auto &existing_vap = std::get<1>(find_vap); // from now on this function is ok with all situations // (e.g. not finding the requested key) m_ok = true; std::string key_eq(key + "="); auto line_iter = std::find_if( existing_vap->begin(), existing_vap->end(), [&key_eq, this](const std::string &line) -> bool { return is_key_in_line(line, key_eq); }); if (line_iter == existing_vap->end()) { m_last_message = std::string(__FUNCTION__) + " couldn't find requested key for vap: " + vap + "; requested key: " + key; return ""; } // return from the just after the '=' sign to the end of the string return line_iter->substr(line_iter->find('=') + 1); } bool Configuration::disable_vap(const std::string &vap) { if (!set_create_vap_value(vap, "start_disabled", "1")) { LOG(ERROR) << "Unable to set start_disabled on vap '" << vap << "'."; return false; } if (!set_create_vap_value(vap, "ssid", "")) { LOG(ERROR) << "Unable to remove ssid on vap '" << vap << "'."; return false; } if (!set_create_vap_value(vap, "multi_ap", "0")) { LOG(ERROR) << "Unable to set multi_ap on vap '" << vap << "'."; return false; } if (!set_create_vap_value(vap, "multi_ap_backhaul_ssid", "")) { LOG(ERROR) << "Unable to remove multi_ap_backhaul_ssid on vap '" << vap << "'."; return false; } if (!set_create_vap_value(vap, "multi_ap_backhaul_wpa_passphrase", "")) { LOG(ERROR) << "Unable to remove multi_ap_backhaul_wpa_passphrase on vap '" << vap << "'."; return false; } return true; } const std::string &Configuration::get_last_message() const { return m_last_message; } std::tuple<bool, std::vector<std::string> *> Configuration::get_vap(const std::string &calling_function, const std::string &vap) { // search for the requested vap - ignore comments // by searching from the back of the saved vap (rfind) auto existing_vap = std::find_if(m_hostapd_config_vaps.begin(), m_hostapd_config_vaps.end(), [&vap](const std::pair<std::string, std::vector<std::string>> &current_vap) { return current_vap.first.rfind(vap) != std::string::npos; }); if (existing_vap == m_hostapd_config_vaps.end()) { m_last_message = calling_function + " couldn't find requested vap: " + vap; m_ok = false; return std::make_tuple(false, nullptr); } m_ok = true; return std::make_tuple(true, &existing_vap->second); } bool Configuration::is_key_in_line(const std::string &line, const std::string &key) const { // we need to make sure when searching for example // for "ssid", to ignore cases like: // multi_ap_backhaul_ssid="Multi-AP-24G-2" // ^^^^^ // bssid=02:9A:96:FB:59:11 // ^^^^^ // and we need to take into consideration // that the key might be or might not be commented. // so the search algorithm is: // - find the requested key and // - make sure it is either on the first position // or it has a comment sign just before it auto found_pos = line.rfind(key); bool ret = found_pos != std::string::npos && (found_pos == 0 || line.at(found_pos - 1) == '#'); return ret; } std::ostream &operator<<(std::ostream &os, const Configuration &conf) { os << "== configuration details ==\n" << "= ok: " << conf.m_ok << '\n' << "= last message: " << conf.m_last_message << '\n' << "= file: " << conf.m_configuration_file << '\n' << "= head: " << '\n'; for (const auto &line : conf.m_hostapd_config_head) { os << line << '\n'; } os << "== vaps (total of: " << conf.m_hostapd_config_vaps.size() << " vaps) ==\n"; for (const auto &vap : conf.m_hostapd_config_vaps) { os << " vap: " << vap.first << "\n"; for (const auto &line : vap.second) { os << line << '\n'; } } return os; } } // namespace hostapd } // namespace prplmesh
34.381924
100
0.603239
SWRT-dev
4a0a579c6cecb6ea87c59a31994edfdfe79eb966
2,222
cpp
C++
src/cv_tdmap_cell_image_frame_delegate.cpp
filipecosta90/im2model
ed43ed236c5a62b3af095fb949c517f680986ac5
[ "Apache-2.0" ]
7
2017-05-30T12:30:07.000Z
2017-09-07T08:35:26.000Z
src/cv_tdmap_cell_image_frame_delegate.cpp
filipecosta90/im2model_app
ed43ed236c5a62b3af095fb949c517f680986ac5
[ "Apache-2.0" ]
null
null
null
src/cv_tdmap_cell_image_frame_delegate.cpp
filipecosta90/im2model_app
ed43ed236c5a62b3af095fb949c517f680986ac5
[ "Apache-2.0" ]
null
null
null
/* * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * Partialy financiated as part of the protocol between UTAustin I Portugal - UTA-P. * [2017] - [2018] University of Minho, Filipe Costa Oliveira * All Rights Reserved. */ #include "cv_tdmap_cell_image_frame_delegate.h" void CvTDMapImageFrameDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { // save the painter's state painter->save(); painter->setRenderHint(QPainter::Antialiasing); if ( shouldBeSelected(index) ){ painter->setPen(QPen(QColor(255,0,0),1)); painter->setBrush(QBrush(QColor(255, 0, 0))); } if ( shouldBeBest(index) ){ painter->setPen(QPen(QColor(0,255,0),1)); painter->setBrush(QBrush(QColor(0, 255, 0))); } QStyleOptionViewItem itemOption(option); painter->drawRect(itemOption.rect ); // restore the painter's state painter->restore(); } /* Loggers */ bool CvTDMapImageFrameDelegate::set_application_logger( ApplicationLog::ApplicationLog* app_logger ){ logger = app_logger; _flag_logger = true; BOOST_LOG_FUNCTION(); logger->logEvent( ApplicationLog::notification, "Application logger setted for CvTDMapImageFrameDelegate class." ); return true; } bool CvTDMapImageFrameDelegate::shouldBeSelected(const QModelIndex &index) const { bool result = false; if( (index.row() == _selected_row) && (index.column() == _selected_col) && (_selected_defined) ){ result = true; } return result; } bool CvTDMapImageFrameDelegate::shouldBeBest(const QModelIndex &index) const { bool result = false; if( (index.row() == _best_row) && (index.column() == _best_col) && (_best_defined) ){ result = true; } return result; } void CvTDMapImageFrameDelegate::set_selected( int row, int col ){ _selected_row = row; _selected_col = col; _selected_defined = true; } void CvTDMapImageFrameDelegate::clean_selected( ){ _selected_defined = false; } void CvTDMapImageFrameDelegate::set_best( int row, int col ){ _best_row = row; _best_col = col; _best_defined = true; } void CvTDMapImageFrameDelegate::clean_best( ){ _best_defined = false; }
28.487179
140
0.721872
filipecosta90
4a0fb6af2475730dce42a50393476e1f7252e3a6
1,591
cpp
C++
BlueBerry/Bundles/org.blueberry.ui/src/guitk/berryGuiTkIControlListener.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
BlueBerry/Bundles/org.blueberry.ui/src/guitk/berryGuiTkIControlListener.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
BlueBerry/Bundles/org.blueberry.ui/src/guitk/berryGuiTkIControlListener.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryGuiTkIControlListener.h" namespace berry { namespace GuiTk { IControlListener::~IControlListener() { } void IControlListener::Events ::AddListener(IControlListener::Pointer l) { if (l.IsNull()) return; Types types = l->GetEventTypes(); if (types & MOVED) movedEvent += Delegate(l.GetPointer(), &IControlListener::ControlMoved); if (types & RESIZED) resizedEvent += Delegate(l.GetPointer(), &IControlListener::ControlResized); if (types & ACTIVATED) activatedEvent += Delegate(l.GetPointer(), &IControlListener::ControlActivated); if (types & DESTROYED) destroyedEvent += Delegate(l.GetPointer(), &IControlListener::ControlDestroyed); } void IControlListener::Events ::RemoveListener(IControlListener::Pointer l) { if (l.IsNull()) return; movedEvent -= Delegate(l.GetPointer(), &IControlListener::ControlMoved); resizedEvent -= Delegate(l.GetPointer(), &IControlListener::ControlResized); activatedEvent -= Delegate(l.GetPointer(), &IControlListener::ControlActivated); destroyedEvent -= Delegate(l.GetPointer(), &IControlListener::ControlDestroyed); } } }
26.516667
84
0.688875
danielknorr
4a102fb074013495ac392f71b3eb68e1426ac871
11,244
cpp
C++
test-suite/generated-src/cwrapper/cw__foo_receiver.cpp
trafi/trafi-djinni
47cd2c849782e2ab4b38e5dc6a5a3104cc87f673
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/cwrapper/cw__foo_receiver.cpp
trafi/trafi-djinni
47cd2c849782e2ab4b38e5dc6a5a3104cc87f673
[ "Apache-2.0" ]
null
null
null
test-suite/generated-src/cwrapper/cw__foo_receiver.cpp
trafi/trafi-djinni
47cd2c849782e2ab4b38e5dc6a5a3104cc87f673
[ "Apache-2.0" ]
null
null
null
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from foo_receiver.djinni #include <iostream> // for debugging #include <cassert> #include "wrapper_marshal.hpp" #include "foo_receiver.hpp" #include "cw__foo_listener.hpp" #include "cw__foo_listener_bf.hpp" #include "cw__foo_receiver.hpp" #include "dh__foo_some_other_record.hpp" #include <chrono> #include <experimental/optional> #include <vector> std::shared_ptr<::testsuite::FooReceiver> DjinniWrapperFooReceiver::get(djinni::WrapperRef<DjinniWrapperFooReceiver> dw) { if (dw) { return dw->wrapped_obj; } return nullptr; } void foo_receiver___wrapper_add_ref(DjinniWrapperFooReceiver * dh) { dh->ref_count.fetch_add(1); } void foo_receiver___wrapper_dec_ref(DjinniWrapperFooReceiver * dh) { const size_t ref = dh->ref_count.fetch_sub(1); if (ref == 1) {// value before sub is returned delete dh; } } djinni::Handle<DjinniWrapperFooReceiver> DjinniWrapperFooReceiver::wrap(std::shared_ptr<::testsuite::FooReceiver> obj) { if (obj) return djinni::Handle<DjinniWrapperFooReceiver>(new DjinniWrapperFooReceiver{ std::move(obj) }, foo_receiver___wrapper_dec_ref); return nullptr; } DjinniString * cw__foo_receiver_set_private_string(DjinniWrapperFooReceiver * djinni_this, DjinniString * private_string) { std::unique_ptr<DjinniString> _private_string(private_string); try { return DjinniString::fromCpp(djinni_this->wrapped_obj->set_private_string(DjinniString::toCpp(std::move(_private_string)))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniString * cw__foo_receiver_get_private_string(DjinniWrapperFooReceiver * djinni_this) { try { return DjinniString::fromCpp(djinni_this->wrapped_obj->get_private_string()).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniString * cw__foo_receiver_cause_changes_string_returned(DjinniWrapperFooReceiver * djinni_this, int32_t i, float f, DjinniString * s, DjinniBinary * binar, bool b, uint64_t d) { std::unique_ptr<DjinniString> _s(s); std::unique_ptr<DjinniBinary> _binar(binar); try { return DjinniString::fromCpp(djinni_this->wrapped_obj->cause_changes_string_returned(i, f, DjinniString::toCpp(std::move(_s)), DjinniBinary::toCpp(std::move(_binar)), b, DjinniDate::toCpp(d))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniBinary * cw__foo_receiver_cause_changes_binary_returned(DjinniWrapperFooReceiver * djinni_this, int32_t i, float f, DjinniString * s, DjinniBinary * binar, bool b, uint64_t d) { std::unique_ptr<DjinniString> _s(s); std::unique_ptr<DjinniBinary> _binar(binar); try { return DjinniBinary::fromCpp(djinni_this->wrapped_obj->cause_changes_binary_returned(i, f, DjinniString::toCpp(std::move(_s)), DjinniBinary::toCpp(std::move(_binar)), b, DjinniDate::toCpp(d))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } uint64_t cw__foo_receiver_cause_changes_date_returned(DjinniWrapperFooReceiver * djinni_this, int32_t i, float f, DjinniString * s, DjinniBinary * binar, bool b, uint64_t d) { std::unique_ptr<DjinniString> _s(s); std::unique_ptr<DjinniBinary> _binar(binar); try { return DjinniDate::fromCpp(djinni_this->wrapped_obj->cause_changes_date_returned(i, f, DjinniString::toCpp(std::move(_s)), DjinniBinary::toCpp(std::move(_binar)), b, DjinniDate::toCpp(d))); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } int32_t cw__foo_receiver_cause_changes_int_returned(DjinniWrapperFooReceiver * djinni_this, int32_t i, float f, DjinniString * s, DjinniBinary * binar, bool b, uint64_t d) { std::unique_ptr<DjinniString> _s(s); std::unique_ptr<DjinniBinary> _binar(binar); try { return djinni_this->wrapped_obj->cause_changes_int_returned(i, f, DjinniString::toCpp(std::move(_s)), DjinniBinary::toCpp(std::move(_binar)), b, DjinniDate::toCpp(d)); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniRecordHandle * cw__foo_receiver_cause_changes_record_returned(DjinniWrapperFooReceiver * djinni_this, int32_t n1, int32_t n2) { try { return DjinniFooSomeOtherRecord::fromCpp(djinni_this->wrapped_obj->cause_changes_record_returned(n1, n2)).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniString * cw__foo_receiver_cause_changes_string_optional_returned(DjinniWrapperFooReceiver * djinni_this, DjinniBoxedI32 * i, float f, DjinniString * s, DjinniBinary * binar, bool b, uint64_t d) { std::unique_ptr<DjinniBoxedI32> _i(i); std::unique_ptr<DjinniString> _s(s); std::unique_ptr<DjinniBinary> _binar(binar); try { return DjinniOptionalString::fromCpp(djinni_this->wrapped_obj->cause_changes_string_optional_returned(DjinniBoxedI32::toCpp(std::move(_i)), f, DjinniOptionalString::toCpp(std::move(_s)), DjinniBinary::toCpp(std::move(_binar)), b, DjinniDate::toCpp(d))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniBoxedI32 * cw__foo_receiver_cause_changes_int_optional_returned(DjinniWrapperFooReceiver * djinni_this, DjinniBoxedI32 * i, float f, DjinniString * s, DjinniBinary * binar, bool b, uint64_t d) { std::unique_ptr<DjinniBoxedI32> _i(i); std::unique_ptr<DjinniString> _s(s); std::unique_ptr<DjinniBinary> _binar(binar); try { return DjinniBoxedI32::fromCpp(djinni_this->wrapped_obj->cause_changes_int_optional_returned(DjinniBoxedI32::toCpp(std::move(_i)), f, DjinniOptionalString::toCpp(std::move(_s)), DjinniBinary::toCpp(std::move(_binar)), b, DjinniDate::toCpp(d))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } void cw__foo_receiver_cause_cpp_exception(DjinniWrapperFooReceiver * djinni_this, DjinniString * exception_arg) { std::unique_ptr<DjinniString> _exception_arg(exception_arg); try { djinni_this->wrapped_obj->cause_cpp_exception(DjinniString::toCpp(std::move(_exception_arg))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } void cw__foo_receiver_cause_py_exception(DjinniWrapperFooReceiver * djinni_this, DjinniString * exception_arg) { std::unique_ptr<DjinniString> _exception_arg(exception_arg); try { djinni_this->wrapped_obj->cause_py_exception(DjinniString::toCpp(std::move(_exception_arg))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } void cw__foo_receiver_cause_zero_division_error(DjinniWrapperFooReceiver * djinni_this) { try { djinni_this->wrapped_obj->cause_zero_division_error(); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } void cw__foo_receiver_add_listener(DjinniWrapperFooReceiver * djinni_this, DjinniWrapperFooListener * listener) { djinni::Handle<DjinniWrapperFooListener> _listener(listener, foo_listener___wrapper_dec_ref); try { djinni_this->wrapped_obj->add_listener(DjinniWrapperFooListener::get(std::move(_listener))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } void cw__foo_receiver_add_optional_listener(DjinniWrapperFooReceiver * djinni_this, DjinniWrapperFooListener * listener) { djinni::Handle<DjinniWrapperFooListener> _listener(listener, foo_listener___wrapper_dec_ref); try { djinni_this->wrapped_obj->add_optional_listener(DjinniWrapperFooListener::get(std::move(_listener))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } DjinniWrapperFooListener * cw__foo_receiver_get_optional_listener(DjinniWrapperFooReceiver * djinni_this) { try { return DjinniWrapperFooListener::wrap(std::move(djinni_this->wrapped_obj->get_optional_listener())).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniString * cw__foo_receiver_set_private_bf_string(DjinniWrapperFooReceiver * djinni_this, DjinniString * private_string) { std::unique_ptr<DjinniString> _private_string(private_string); try { return DjinniString::fromCpp(djinni_this->wrapped_obj->set_private_bf_string(DjinniString::toCpp(std::move(_private_string)))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } void cw__foo_receiver_add_listener_bf(DjinniWrapperFooReceiver * djinni_this, DjinniWrapperFooListenerBf * listener) { djinni::Handle<DjinniWrapperFooListenerBf> _listener(listener, foo_listener_bf___wrapper_dec_ref); try { djinni_this->wrapped_obj->add_listener_bf(DjinniWrapperFooListenerBf::get(std::move(_listener))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } DjinniWrapperFooListenerBf * cw__foo_receiver_get_foo_listener_bf(DjinniWrapperFooReceiver * djinni_this) { try { return DjinniWrapperFooListenerBf::wrap(std::move(djinni_this->wrapped_obj->get_foo_listener_bf())).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniString * cw__foo_receiver_get_listener_bf_string(DjinniWrapperFooReceiver * djinni_this) { try { return DjinniString::fromCpp(djinni_this->wrapped_obj->get_listener_bf_string()).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } void cw__foo_receiver_set_listener_bf_in_listener_bf(DjinniWrapperFooReceiver * djinni_this, DjinniWrapperFooListenerBf * listener) { djinni::Handle<DjinniWrapperFooListenerBf> _listener(listener, foo_listener_bf___wrapper_dec_ref); try { djinni_this->wrapped_obj->set_listener_bf_in_listener_bf(DjinniWrapperFooListenerBf::get(std::move(_listener))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } DjinniWrapperFooListenerBf * cw__foo_receiver_get_listener_bf_in_listener_bf(DjinniWrapperFooReceiver * djinni_this) { try { return DjinniWrapperFooListenerBf::wrap(std::move(djinni_this->wrapped_obj->get_listener_bf_in_listener_bf())).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } void cw__foo_receiver_set_binary_in_listener_bf_in_listener_bf(DjinniWrapperFooReceiver * djinni_this, DjinniBinary * b) { std::unique_ptr<DjinniBinary> _b(b); try { djinni_this->wrapped_obj->set_binary_in_listener_bf_in_listener_bf(DjinniBinary::toCpp(std::move(_b))); } CW_TRANSLATE_EXCEPTIONS_RETURN(); } DjinniBinary * cw__foo_receiver_get_binary_in_listener_bf_in_listener_bf(DjinniWrapperFooReceiver * djinni_this) { try { return DjinniBinary::fromCpp(djinni_this->wrapped_obj->get_binary_in_listener_bf_in_listener_bf()).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniWrapperFooListenerBf * cw__foo_receiver_send_return(DjinniWrapperFooReceiver * djinni_this, DjinniWrapperFooListenerBf * fl_bf) { djinni::Handle<DjinniWrapperFooListenerBf> _fl_bf(fl_bf, foo_listener_bf___wrapper_dec_ref); try { return DjinniWrapperFooListenerBf::wrap(std::move(djinni_this->wrapped_obj->send_return(DjinniWrapperFooListenerBf::get(std::move(_fl_bf))))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniWrapperFooListenerBf * cw__foo_receiver_in_listener_bf_send_return(DjinniWrapperFooReceiver * djinni_this, DjinniWrapperFooListenerBf * fl_bf) { djinni::Handle<DjinniWrapperFooListenerBf> _fl_bf(fl_bf, foo_listener_bf___wrapper_dec_ref); try { return DjinniWrapperFooListenerBf::wrap(std::move(djinni_this->wrapped_obj->in_listener_bf_send_return(DjinniWrapperFooListenerBf::get(std::move(_fl_bf))))).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); } DjinniWrapperFooReceiver * cw__foo_receiver_create() { try { return DjinniWrapperFooReceiver::wrap(std::move(::testsuite::FooReceiver::create())).release(); } CW_TRANSLATE_EXCEPTIONS_RETURN(0); }
51.577982
271
0.779171
trafi
4a11c773803aa6b0a1bfa392299e4058f70bfae3
4,658
cpp
C++
src/base/encoder.cpp
umichan0621/P2P-File-Share-System
3025dcde37c9fe4988f993ec2fa5bfe2804eaedb
[ "MIT" ]
null
null
null
src/base/encoder.cpp
umichan0621/P2P-File-Share-System
3025dcde37c9fe4988f993ec2fa5bfe2804eaedb
[ "MIT" ]
null
null
null
src/base/encoder.cpp
umichan0621/P2P-File-Share-System
3025dcde37c9fe4988f993ec2fa5bfe2804eaedb
[ "MIT" ]
null
null
null
#include "encoder.h" #include <windows.h> #include <wchar.h> namespace base { static uint8_t AlphabetMap[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static uint8_t ReverseMap[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255 }; //转换成base64编码 int32_t base64_encode(const uint8_t* pSrc, int32_t SrcLen, uint8_t* pDes) { int32_t i, j; for (i = 0, j = 0; i + 3 <= SrcLen; i += 3) { //取出第一个字符的前6位并找出对应的结果字符 pDes[j++] = AlphabetMap[pSrc[i] >> 2]; //将第一个字符的后2位与第二个字符的前4位进行组合并找到对应的结果字符 pDes[j++] = AlphabetMap[((pSrc[i] << 4) & 0x30) | (pSrc[i + 1] >> 4)]; //将第二个字符的后4位与第三个字符的前2位组合并找出对应的结果字符 pDes[j++] = AlphabetMap[((pSrc[i + 1] << 2) & 0x3c) | (pSrc[i + 2] >> 6)]; //取出第三个字符的后6位并找出结果字符 pDes[j++] = AlphabetMap[pSrc[i + 2] & 0x3f]; } if (i < SrcLen) { int32_t Tail = SrcLen - i; if (Tail == 1) { pDes[j++] = AlphabetMap[pSrc[i] >> 2]; pDes[j++] = AlphabetMap[(pSrc[i] << 4) & 0x30]; pDes[j++] = '='; pDes[j++] = '='; } else //tail==2 { pDes[j++] = AlphabetMap[pSrc[i] >> 2]; pDes[j++] = AlphabetMap[((pSrc[i] << 4) & 0x30) | (pSrc[i + 1] >> 4)]; pDes[j++] = AlphabetMap[(pSrc[i + 1] << 2) & 0x3c]; pDes[j++] = '='; } } return j; } int32_t base64_encode(const char* pSrc, int32_t SrcLen, char* pDes) { return base64_encode((const uint8_t*)pSrc, SrcLen, (uint8_t*)pDes); } int32_t base64_encode(const std::string& strSrc, char* pDes) { return base64_encode(strSrc.c_str(), strSrc.size(), pDes); } //转换成base64编码 //解析base64编码 int32_t base64_decode(const uint8_t* pSrc, int32_t SrcLen, uint8_t* pDes) { //如果它的条件返回错误,则终止程序执行。4的倍数。 if ((SrcLen & 0x03) != 0) { return -1; } int32_t i, j = 0; int8_t Temp[4]; for (i = 0; i < SrcLen; i += 4) { for (int32_t k = 0; k < 4; ++k) { //分组,每组四个分别依次转换为base64表内的十进制数 Temp[k] = ReverseMap[pSrc[i + k]]; } if (Temp[0] >= 64 || Temp[1] >= 64) { return -1; } //assert(Temp[0] < 64 && Temp[1] < 64); //取出第一个字符对应base64表的十进制数的前6位与第二个字符对应base64表的十进制数的前2位进行组合 pDes[j++] = (Temp[0] << 2) | (Temp[1] >> 4); if (Temp[2] >= 64) break; else if (Temp[3] >= 64) { //取出第二个字符对应base64表的十进制数的后4位与第三个字符对应base64表的十进制数的前4位进行组合 pDes[j++] = (Temp[1] << 4) | (Temp[2] >> 2); break; } else { pDes[j++] = (Temp[1] << 4) | (Temp[2] >> 2); //取出第三个字符对应base64表的十进制数的后2位与第4个字符进行组合 pDes[j++] = (Temp[2] << 6) | Temp[3]; } } return j; } int32_t base64_decode(const char* pSrc, int32_t SrcLen, char* pDes) { return base64_decode((const uint8_t*)pSrc, SrcLen, (uint8_t*)pDes); } int32_t base64_decode(const std::string& strSrc, char* pDes) { return base64_decode(strSrc.c_str(), strSrc.size(), pDes); } //解析base64编码 //utf8编码转换 std::string string_to_utf8(const std::string& strSrc) { int32_t Len1 = ::MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), -1, NULL, 0); wchar_t* pwBuf = new wchar_t[Len1 + 1];//一定要加1,不然会出现尾巴 ZeroMemory(pwBuf, Len1 * 2 + 2); ::MultiByteToWideChar(CP_ACP, 0, strSrc.c_str(), strSrc.length(), pwBuf, Len1); int Len2 = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL); char* pBuf = new char[Len2 + 1]; ZeroMemory(pBuf, Len2 + 1); ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, Len1, pBuf, Len2, NULL, NULL); std::string strDes(pBuf); delete[]pwBuf; delete[]pBuf; pwBuf = NULL; pBuf = NULL; return strDes; } std::string utf8_to_string(const std::string& strSrc) { int32_t Len1 = MultiByteToWideChar(CP_UTF8, 0, strSrc.c_str(), -1, NULL, 0); wchar_t* pwBuf = new wchar_t[Len1 + 1];//一定要加1,不然会出现尾巴 memset(pwBuf, 0, Len1 * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, strSrc.c_str(), strSrc.length(), pwBuf, Len1); int32_t Len2 = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL); char* pBuf = new char[Len2 + 1]; memset(pBuf, 0, Len2 + 1); WideCharToMultiByte(CP_ACP, 0, pwBuf, Len1, pBuf, Len2, NULL, NULL); std::string strDes = pBuf; delete[]pBuf; delete[]pwBuf; pBuf = NULL; pwBuf = NULL; return strDes; } //utf8编码转换 }
26.022346
99
0.597252
umichan0621
4a12bef02a73ba8fbc5f46e0dc69754b06740074
7,721
cpp
C++
Engine/gkDebugFps.cpp
gamekit-developers/gamekit
74c896af5826ebe8fb72f2911015738f38ab7bb2
[ "Zlib", "MIT" ]
241
2015-01-04T00:36:58.000Z
2022-01-06T19:19:23.000Z
Engine/gkDebugFps.cpp
slagusev/gamekit
a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d
[ "MIT" ]
10
2015-07-10T18:27:17.000Z
2019-06-26T20:59:59.000Z
Engine/gkDebugFps.cpp
slagusev/gamekit
a6e97fcf2a9c3b9b9799bc12c3643818503ffc7d
[ "MIT" ]
82
2015-01-25T18:02:35.000Z
2022-03-05T12:28:17.000Z
/* ------------------------------------------------------------------------------- This file is part of OgreKit. http://gamekit.googlecode.com/ Copyright (c) 2006-2013 Xavier T. Contributor(s): Charlie C. ------------------------------------------------------------------------------- This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "gkDebugFps.h" #include "gkLogger.h" #include "gkWindowSystem.h" #include "gkWindow.h" #include "gkEngine.h" #include "gkScene.h" #include "gkDynamicsWorld.h" #include "gkStats.h" #include "OgreOverlayManager.h" #include "OgreOverlayElement.h" #include "OgreOverlayContainer.h" #include "OgreFont.h" #include "OgreFontManager.h" #include "OgreTextAreaOverlayElement.h" #include "OgreRenderWindow.h" #include "OgreRenderTarget.h" #define PROP_SIZE 14 gkDebugFps::gkDebugFps() : m_isInit(false), m_isShown(false), m_over(0), m_cont(0), m_key(0), m_val(0) { m_keys = ""; m_keys += "FPS:\n"; m_keys += "Average:\n"; m_keys += "Best:\n"; m_keys += "Worst:\n"; m_keys += "\n"; m_keys += "Triangles:\n"; m_keys += "Batch count:\n"; m_keys += "\n"; m_keys += "DBVT:\n"; m_keys += "\n"; m_keys += "Total:\n"; m_keys += "Render:\n"; m_keys += "Physics:\n"; m_keys += "LogicBricks:\n"; m_keys += "LogicNodes:\n"; m_keys += "Sound:\n"; m_keys += "DBVT:\n"; m_keys += "Bufferswap&LOD:\n"; m_keys += "Animations:\n"; } gkDebugFps::~gkDebugFps() { } void gkDebugFps::initialize(void) { if (m_isInit) return; try { // always initialize after gkDebugScreen! Ogre::OverlayManager& mgr = Ogre::OverlayManager::getSingleton(); m_over = mgr.create("<gkBuiltin/gkDebugFps>"); m_key = mgr.createOverlayElement("TextArea", "<gkBuiltin/gkDebugFps/Keys>"); m_val = mgr.createOverlayElement("TextArea", "<gkBuiltin/gkDebugFps/Vals>"); m_cont = (Ogre::OverlayContainer*)mgr.createOverlayElement("Panel", "<gkBuiltin/gkDebugFps/Containter1>"); m_cont->setMetricsMode(Ogre::GMM_PIXELS); m_cont->setVerticalAlignment(Ogre::GVA_TOP); m_cont->setHorizontalAlignment(Ogre::GHA_RIGHT); m_cont->setLeft(-16 * PROP_SIZE); m_cont->setTop(10); m_key->setMetricsMode(Ogre::GMM_PIXELS); m_key->setVerticalAlignment(Ogre::GVA_TOP); m_key->setHorizontalAlignment(Ogre::GHA_LEFT); m_val->setMetricsMode(Ogre::GMM_PIXELS); m_val->setVerticalAlignment(Ogre::GVA_TOP); m_val->setHorizontalAlignment(Ogre::GHA_LEFT); m_val->setLeft(8 * PROP_SIZE); Ogre::TextAreaOverlayElement* textArea; textArea = static_cast<Ogre::TextAreaOverlayElement*>(m_key); textArea->setFontName("<gkBuiltin/Font>"); textArea->setCharHeight(PROP_SIZE); textArea->setColour(Ogre::ColourValue::White); textArea = static_cast<Ogre::TextAreaOverlayElement*>(m_val); textArea->setFontName("<gkBuiltin/Font>"); textArea->setCharHeight(PROP_SIZE); textArea->setColour(Ogre::ColourValue::White); m_over->setZOrder(500); m_cont->addChild(m_key); m_cont->addChild(m_val); m_over->add2D(m_cont); } catch (Ogre::Exception& e) { gkPrintf("%s", e.getDescription().c_str()); return; } m_isInit = true; } void gkDebugFps::show(bool v) { if (m_over != 0 && m_isShown != v) { m_isShown = v; if (m_isShown) m_over->show(); else m_over->hide(); } } void gkDebugFps::draw(void) { if (!m_over || !m_key || !m_val) return; Ogre::RenderWindow* window = gkWindowSystem::getSingleton().getMainWindow()->getRenderWindow(); const Ogre::RenderTarget::FrameStats& ogrestats = window->getStatistics(); gkVariable* dbvtVal = 0; gkDynamicsWorld* wo = gkEngine::getSingleton().getActiveScene()->getDynamicsWorld(); if (wo) dbvtVal = wo->getDBVTInfo(); float swap = gkStats::getSingleton().getLastTotalMicroSeconds() / 1000.0f; float render = gkStats::getSingleton().getLastRenderMicroSeconds() / 1000.0f; float phys = gkStats::getSingleton().getLastPhysicsMicroSeconds() / 1000.0f; float logicb = gkStats::getSingleton().getLastLogicBricksMicroSeconds() / 1000.0f; float logicn = gkStats::getSingleton().getLastLogicNodesMicroSeconds() / 1000.0f; float sound = gkStats::getSingleton().getLastSoundMicroSeconds() / 1000.0f; float dbvt = gkStats::getSingleton().getLastDbvtMicroSeconds() / 1000.0f; float bufswaplod = gkStats::getSingleton().getLastBufSwapLodMicroSeconds() / 1000.0f; float animations = gkStats::getSingleton().getLastAnimationsMicroSeconds() / 1000.0f; #ifdef OGREKIT_USE_PROCESSMANAGER float process = gkStats::getSingleton().getLastProcessMicroSeconds() / 1000.0f; #endif gkString vals = ""; vals += Ogre::StringConverter::toString(ogrestats.lastFPS) + '\n'; vals += Ogre::StringConverter::toString(ogrestats.avgFPS) + '\n'; vals += Ogre::StringConverter::toString(ogrestats.bestFPS) + '\n'; vals += Ogre::StringConverter::toString(ogrestats.worstFPS) + '\n'; vals += '\n'; vals += Ogre::StringConverter::toString(ogrestats.triangleCount) + '\n'; vals += Ogre::StringConverter::toString(ogrestats.batchCount) + '\n'; vals += '\n'; if (dbvtVal) vals += dbvtVal->getValueString(); else vals += "Not Enabled\n"; vals += '\n'; vals += Ogre::StringConverter::toString(swap, 3, 7, '0', std::ios::fixed) + "ms 100%\n"; vals += Ogre::StringConverter::toString(render, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * render / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(phys, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * phys / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(logicb, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * logicb / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(logicn, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * logicn / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(sound, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * sound / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(dbvt, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * dbvt / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(bufswaplod, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * bufswaplod / swap), 3 ) + "%\n"; vals += Ogre::StringConverter::toString(animations, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * animations / swap), 3 ) + "%\n"; #ifdef OGREKIT_USE_PROCESSMANAGER vals += Ogre::StringConverter::toString(process, 3, 7, '0', std::ios::fixed) + "ms "; vals += Ogre::StringConverter::toString( int(100 * process / swap), 3 ) + "%\n"; #endif if (!m_keys.empty() && !vals.empty()) { m_key->setCaption(m_keys); m_val->setCaption(vals); } }
32.995726
109
0.669732
gamekit-developers
4a1759c248922b0c08e7c47f9a1625f62e46fecc
7,106
cc
C++
archival/lzip-1.19/file_index.cc
myzhang1029/zmymingw
4c6b6088fb8a03248a1e6d9d6126dfaf225ffa56
[ "CC0-1.0" ]
null
null
null
archival/lzip-1.19/file_index.cc
myzhang1029/zmymingw
4c6b6088fb8a03248a1e6d9d6126dfaf225ffa56
[ "CC0-1.0" ]
null
null
null
archival/lzip-1.19/file_index.cc
myzhang1029/zmymingw
4c6b6088fb8a03248a1e6d9d6126dfaf225ffa56
[ "CC0-1.0" ]
null
null
null
/* Lzip - LZMA lossless data compressor Copyright (C) 2008-2017 Antonio Diaz Diaz. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. 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, see <http://www.gnu.org/licenses/>. */ #define _FILE_OFFSET_BITS 64 #include <algorithm> #include <cerrno> #include <cstdio> #include <cstring> #include <string> #include <vector> #include <stdint.h> #include <unistd.h> #include "lzip.h" #include "file_index.h" namespace { int seek_read( const int fd, uint8_t * const buf, const int size, const long long pos ) { if( lseek( fd, pos, SEEK_SET ) == pos ) return readblock( fd, buf, size ); return 0; } } // end namespace void File_index::set_errno_error( const char * const msg ) { error_ = msg; error_ += std::strerror( errno ); retval_ = 1; } void File_index::set_num_error( const char * const msg, unsigned long long num ) { char buf[80]; snprintf( buf, sizeof buf, "%s%llu", msg, num ); error_ = buf; retval_ = 2; } // If successful, push last member and set pos to member header. bool File_index::skip_trailing_data( const int fd, long long & pos ) { enum { block_size = 16384, buffer_size = block_size + File_trailer::size - 1 + File_header::size }; uint8_t buffer[buffer_size]; if( pos < min_member_size ) return false; int bsize = pos % block_size; // total bytes in buffer if( bsize <= buffer_size - block_size ) bsize += block_size; int search_size = bsize; // bytes to search for trailer int rd_size = bsize; // bytes to read from file unsigned long long ipos = pos - rd_size; // aligned to block_size while( true ) { if( seek_read( fd, buffer, rd_size, ipos ) != rd_size ) { set_errno_error( "Error seeking member trailer: " ); return false; } const uint8_t max_msb = ( ipos + search_size ) >> 56; for( int i = search_size; i >= File_trailer::size; --i ) if( buffer[i-1] <= max_msb ) // most significant byte of member_size { File_trailer & trailer = *(File_trailer *)( buffer + i - File_trailer::size ); const unsigned long long member_size = trailer.member_size(); if( member_size == 0 ) { while( i > File_trailer::size && buffer[i-9] == 0 ) --i; continue; } if( member_size < min_member_size || member_size > ipos + i ) continue; File_header header; if( seek_read( fd, header.data, File_header::size, ipos + i - member_size ) != File_header::size ) { set_errno_error( "Error reading member header: " ); return false; } const unsigned dictionary_size = header.dictionary_size(); if( !header.verify_magic() || !header.verify_version() || !isvalid_ds( dictionary_size ) ) continue; if( (*(File_header *)( buffer + i )).verify_prefix( bsize - i ) ) { error_ = "Last member in input file is truncated or corrupt."; retval_ = 2; return false; } pos = ipos + i - member_size; member_vector.push_back( Member( 0, trailer.data_size(), pos, member_size, dictionary_size ) ); return true; } if( ipos <= 0 ) { set_num_error( "Member size in trailer is corrupt at pos ", pos - 8 ); return false; } bsize = buffer_size; search_size = bsize - File_header::size; rd_size = block_size; ipos -= rd_size; std::memcpy( buffer + rd_size, buffer, buffer_size - rd_size ); } } File_index::File_index( const int infd, const bool ignore_trailing ) : isize( lseek( infd, 0, SEEK_END ) ), retval_( 0 ) { if( isize < 0 ) { set_errno_error( "Input file is not seekable: " ); return; } if( isize < min_member_size ) { error_ = "Input file is too short."; retval_ = 2; return; } if( isize > INT64_MAX ) { error_ = "Input file is too long (2^63 bytes or more)."; retval_ = 2; return; } File_header header; if( seek_read( infd, header.data, File_header::size, 0 ) != File_header::size ) { set_errno_error( "Error reading member header: " ); return; } if( !header.verify_magic() ) { error_ = bad_magic_msg; retval_ = 2; return; } if( !header.verify_version() ) { error_ = bad_version( header.version() ); retval_ = 2; return; } if( !isvalid_ds( header.dictionary_size() ) ) { error_ = bad_dict_msg; retval_ = 2; return; } long long pos = isize; // always points to a header or to EOF while( pos >= min_member_size ) { File_trailer trailer; if( seek_read( infd, trailer.data, File_trailer::size, pos - File_trailer::size ) != File_trailer::size ) { set_errno_error( "Error reading member trailer: " ); break; } const unsigned long long member_size = trailer.member_size(); if( member_size < min_member_size || member_size > (unsigned long long)pos ) { if( !member_vector.empty() ) set_num_error( "Member size in trailer is corrupt at pos ", pos - 8 ); else if( skip_trailing_data( infd, pos ) ) { if( ignore_trailing ) continue; error_ = trailing_msg; retval_ = 2; return; } break; } if( seek_read( infd, header.data, File_header::size, pos - member_size ) != File_header::size ) { set_errno_error( "Error reading member header: " ); break; } const unsigned dictionary_size = header.dictionary_size(); if( !header.verify_magic() || !header.verify_version() || !isvalid_ds( dictionary_size ) ) { if( !member_vector.empty() ) set_num_error( "Bad header at pos ", pos - member_size ); else if( skip_trailing_data( infd, pos ) ) { if( ignore_trailing ) continue; error_ = trailing_msg; retval_ = 2; return; } break; } pos -= member_size; member_vector.push_back( Member( 0, trailer.data_size(), pos, member_size, dictionary_size ) ); } if( pos != 0 || member_vector.empty() ) { member_vector.clear(); if( retval_ == 0 ) { error_ = "Can't create file index."; retval_ = 2; } return; } std::reverse( member_vector.begin(), member_vector.end() ); for( unsigned long i = 0; i < member_vector.size() - 1; ++i ) { const long long end = member_vector[i].dblock.end(); if( end < 0 || end > INT64_MAX ) { member_vector.clear(); error_ = "Data in input file is too long (2^63 bytes or more)."; retval_ = 2; return; } member_vector[i+1].dblock.pos( end ); } }
36.818653
81
0.622854
myzhang1029
4a194049b6d19720ba1bf16da44ae734487318ef
1,020
cpp
C++
kernel/arch/x86_64/com.cpp
jasonwer/WingOS
1e3b8b272bc93542fda48ed1cf3226e63c923f39
[ "BSD-2-Clause" ]
1
2021-03-27T13:40:21.000Z
2021-03-27T13:40:21.000Z
kernel/arch/x86_64/com.cpp
jasonwer/WingOS
1e3b8b272bc93542fda48ed1cf3226e63c923f39
[ "BSD-2-Clause" ]
null
null
null
kernel/arch/x86_64/com.cpp
jasonwer/WingOS
1e3b8b272bc93542fda48ed1cf3226e63c923f39
[ "BSD-2-Clause" ]
null
null
null
#include <arch.h> #include <com.h> #include <kernel.h> #include <process.h> #include <stdarg.h> #include <utility.h> char temp_buffer[17]; uint64_t last_count = 17; bool com_device::echo_out(const char *data, uint64_t data_length) { for (uint64_t i = 0; i < data_length; i++) { write(data[i]); } return true; } bool com_device::echo_out(const char *data) { uint64_t i = 0; while (data[i] != 0) { write(data[i]); i++; } return true; } void com_device::init(COM_PORT this_port) { port = this_port; outb(port + 2, 0); outb(port + 3, 1 << 7); outb(port + 0, 3); outb(port + 1, 0); outb(port + 3, 0x03); outb(port + 2, 0xC7); outb(port + 4, 0x0B); add_device(this); } void com_device::wait() const { int timeout = 0; while ((inb(port + 5) & 0x20) == 0) { if (timeout++ > 10000) { break; } } } inline void com_device::write(char c) const { wait(); outb(port, c); }
17
65
0.545098
jasonwer
4a1cf84fdc287c42f1dad8fa81015e3bc12e2db8
13,119
cpp
C++
src/Private/Resources/PlayingHudResource.cpp
heltena/KYEngine
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
[ "MIT" ]
null
null
null
src/Private/Resources/PlayingHudResource.cpp
heltena/KYEngine
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
[ "MIT" ]
null
null
null
src/Private/Resources/PlayingHudResource.cpp
heltena/KYEngine
4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e
[ "MIT" ]
null
null
null
#include <KYEngine/AddFaceViewParam.h> #include <KYEngine/AddMapViewParam.h> #include <KYEngine/AddProgressViewParam.h> #include <KYEngine/AddJoystickButtonParam.h> #include <KYEngine/AddPushButtonParam.h> #include <KYEngine/Core.h> #include <KYEngine/Private/Resources/PlayingHudResource.h> #include <KYEngine/Utility/TiXmlHelper.h> #include <iostream> #include <stdexcept> const std::string PlayingHudResource::XML_NODE = "playing-hud"; PlayingHudResource::PlayingHudResource() : m_listener(NULL) , m_layer(NULL) { } PlayingHudResource::~PlayingHudResource() { } PlayingHudResource* PlayingHudResource::readFromXml(TiXmlElement* node) { PlayingHudResource* result = new PlayingHudResource(); const std::string name = TiXmlHelper::readString(node, "name", true); const std::string layerName = TiXmlHelper::readString(node, "layer-name", true); double zOrder = TiXmlHelper::readDouble(node, "z-order", true); result->setName(name); result->setLayerName(layerName); result->setZOrder(zOrder); TiXmlElement* curr = node->FirstChildElement(); while (curr) { std::string prefix = Core::resourceManager().prefixOfNode(curr); Core::resourceManager().factory(prefix)->readFromXml(prefix, curr, result); curr = curr->NextSiblingElement(); } return result; } void PlayingHudResource::preload() { } void PlayingHudResource::unloadFromPreloaded() { } void PlayingHudResource::load() { for(std::list<AddFaceViewParam*>::const_iterator it = m_faceViewParams.begin(); it != m_faceViewParams.end(); it++) { AddFaceViewParam* faceViewParam = *it; HudFaceView* view = faceViewParam->generateFaceView(); addFaceView(faceViewParam->id(), view); } for(std::list<AddMapViewParam*>::const_iterator it = m_mapViewParams.begin(); it != m_mapViewParams.end(); it++) { AddMapViewParam* mapViewParam = *it; HudMapView* view = mapViewParam->generateMapView(); addMapView(mapViewParam->id(), view); } for(std::list<AddProgressViewParam*>::const_iterator it = m_progressViewParams.begin(); it != m_progressViewParams.end(); it++) { AddProgressViewParam* progressViewParam = *it; HudProgressView* view = progressViewParam->generateProgressView(); addProgressView(progressViewParam->id(), view); } for(std::list<AddJoystickButtonParam*>::const_iterator it = m_joystickButtonParams.begin(); it != m_joystickButtonParams.end(); it++) { AddJoystickButtonParam* joystickButtonParam = *it; HudJoystickButton* button = joystickButtonParam->generateJoystickButton(); addJoystickButton(joystickButtonParam->id(), button); } for(std::list<AddPushButtonParam*>::const_iterator it = m_pushButtonParams.begin(); it != m_pushButtonParams.end(); it++) { AddPushButtonParam* pushButtonParam = *it; HudPushButton* button = pushButtonParam->generatePushButton(); addPushButton(pushButtonParam->id(), button); } for(std::list<AddTextLabelParam*>::const_iterator it = m_textLabelParams.begin(); it != m_textLabelParams.end(); it++) { AddTextLabelParam* textLabelParam = *it; HudTextLabel* textLabel = textLabelParam->generateTextLabel(); addTextLabel(textLabelParam->id(), textLabel); } } void PlayingHudResource::unload() { m_listener = NULL; if (m_layer) { Core::renderManager().removeLayer(m_layerName); m_layer = NULL; } for(std::map<int, HudFaceView*>::const_iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) delete it->second; m_faceViews.clear(); for(std::map<int, HudMapView*>::const_iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) delete it->second; m_joystickButtons.clear(); for(std::map<int, HudProgressView*>::const_iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) delete it->second; m_mapViews.clear(); for(std::map<int, HudJoystickButton*>::const_iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) delete it->second; m_progressViews.clear(); for(std::map<int, HudPushButton*>::const_iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) delete it->second; m_pushButtons.clear(); for(std::map<int, HudTextLabel*>::const_iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) delete it->second; m_textLabels.clear(); } void PlayingHudResource::appear(PlayingHudListener* listener) { if (m_layer == NULL) m_layer = Core::renderManager().createLayer(m_layerName, m_zOrder); m_listener = listener; for (std::map<int, HudFaceView*>::iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) { it->second->appear(); m_layer->addEntity(it->second); } for (std::map<int, HudMapView*>::iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) { it->second->appear(); m_layer->addEntity(it->second); } for (std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) { it->second->appear(NULL); m_layer->addEntity(it->second); } for (std::map<int, HudProgressView*>::iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) { it->second->appear(); m_layer->addEntity(it->second); } for (std::map<int, HudPushButton*>::iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) { it->second->appear(this); m_layer->addEntity(it->second); } for(std::map<int, HudTextLabel*>::iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) { it->second->appear(); m_layer->addEntity(it->second); } } bool PlayingHudResource::isAppeared() const { for (std::map<int, HudFaceView*>::const_iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) { if (! it->second->isAppeared()) return false; } for (std::map<int, HudMapView*>::const_iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) { if (! it->second->isAppeared()) return false; } for (std::map<int, HudJoystickButton*>::const_iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) { if (! it->second->isAppeared()) return false; } for (std::map<int, HudProgressView*>::const_iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) { if (! it->second->isAppeared()) return false; } for (std::map<int, HudPushButton*>::const_iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) { if (! it->second->isAppeared()) return false; } for(std::map<int, HudTextLabel*>::const_iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) { if (! it->second->isAppeared()) return false; } return true; } void PlayingHudResource::disappear() { m_listener = NULL; for (std::map<int, HudFaceView*>::iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) { it->second->disappear(); } for (std::map<int, HudMapView*>::iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) { it->second->disappear(); } for (std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) { it->second->disappear(); } for (std::map<int, HudProgressView*>::iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) { it->second->disappear(); } for (std::map<int, HudPushButton*>::iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) { it->second->disappear(); } for(std::map<int, HudTextLabel*>::iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) { it->second->disappear(); } m_listener = NULL; } bool PlayingHudResource::isDisappeared() const { for (std::map<int, HudFaceView*>::const_iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) { if (! it->second->isDisappeared()) return false; } for (std::map<int, HudMapView*>::const_iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) { if (! it->second->isDisappeared()) return false; } for (std::map<int, HudJoystickButton*>::const_iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) { if (! it->second->isDisappeared()) return false; } for (std::map<int, HudProgressView*>::const_iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) { if (! it->second->isDisappeared()) return false; } for (std::map<int, HudPushButton*>::const_iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) { if (! it->second->isDisappeared()) return false; } for(std::map<int, HudTextLabel*>::const_iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) { if (! it->second->isDisappeared()) return false; } return true; } void PlayingHudResource::abort() { if (m_layer != NULL) { Core::renderManager().removeLayer(m_layerName); m_layer = NULL; } } void PlayingHudResource::setListener(PlayingHudListener* listener) { m_listener = listener; } const Vector4 PlayingHudResource::direction(int id) { std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.find(id); if (it == m_joystickButtons.end()) return Vector4(); return it->second->direction(); } void PlayingHudResource::setFaceValue(int id, double value) { std::map<int, HudFaceView*>::iterator it = m_faceViews.find(id); if (it == m_faceViews.end()) throw std::runtime_error("PlayingHud: faceView not found " + id); it->second->setCurrentValue(value); } void PlayingHudResource::setMapItems(int id, const std::list<HudMapViewItem>& items) { std::map<int, HudMapView*>::iterator it = m_mapViews.find(id); if (it == m_mapViews.end()) throw std::runtime_error("PlayingHud: mapView not found " + id); it->second->setItems(items); } void PlayingHudResource::setProgressValue(int id, double value) { std::map<int, HudProgressView*>::iterator it = m_progressViews.find(id); if (it == m_progressViews.end()) throw std::runtime_error("PlayingHud: progressView not found " + id); it->second->setCurrentValue(value); } void PlayingHudResource::setTextLabel(int id, const std::string& value) { std::map<int, HudTextLabel*>::iterator it = m_textLabels.find(id); if (it == m_textLabels.end()) throw std::runtime_error("PlayingHud: textLabel not found " + id); it->second->setText(value); } void PlayingHudResource::update(const double elapsedTime) { if (m_layer == NULL) return; if (isDisappeared()) { if (m_layer != NULL) { Core::renderManager().removeLayer(m_layerName); m_layer = NULL; } } else { for (std::map<int, HudFaceView*>::iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) it->second->update(elapsedTime); for (std::map<int, HudMapView*>::iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) it->second->update(elapsedTime); for (std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) it->second->update(elapsedTime); for (std::map<int, HudProgressView*>::iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) it->second->update(elapsedTime); for (std::map<int, HudPushButton*>::iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) it->second->update(elapsedTime); for (std::map<int, HudTextLabel*>::iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) it->second->update(elapsedTime); } } void PlayingHudResource::addFaceView(int id, HudFaceView* view) { m_faceViews[id] = view; } void PlayingHudResource::addJoystickButton(int id, HudJoystickButton* button) { m_joystickButtons[id] = button; } void PlayingHudResource::addMapView(int id, HudMapView* view) { m_mapViews[id] = view; } void PlayingHudResource::addProgressView(int id, HudProgressView* view) { m_progressViews[id] = view; } void PlayingHudResource::addPushButton(int id, HudPushButton* button) { m_pushButtons[id] = button; } void PlayingHudResource::addTextLabel(int id, HudTextLabel* textLabel) { m_textLabels[id] = textLabel; } void PlayingHudResource::hudButtonPressed(int id) { if (m_listener) m_listener->hudButtonPressed(direction(), id); } void PlayingHudResource::hudButtonReleased(int id) { if (m_listener) m_listener->hudButtonReleased(direction(), id); }
35.649457
139
0.647991
heltena
4a211385c55ec7464c20bc86d74449970d0c0d31
217
cpp
C++
CC/hello_world.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
1
2020-10-12T08:03:20.000Z
2020-10-12T08:03:20.000Z
CC/hello_world.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
null
null
null
CC/hello_world.cpp
MrRobo24/Codes
9513f42b61e898577123d5b996e43ba7a067a019
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { long long a = 2992; long long b = 192; int prod = a * b; cout << "Product of " << a <<" and " << b << " is = " << prod << "\n"; return 0; }
24.111111
74
0.488479
MrRobo24
4a2904fda2c70d52ed7767a3317284c589584fdb
782
cpp
C++
leetcode/src/0142-detectCycle.cpp
Wasikowska/go-typebyname
460c50de881508f340c4785c18cee47232095a50
[ "MIT" ]
null
null
null
leetcode/src/0142-detectCycle.cpp
Wasikowska/go-typebyname
460c50de881508f340c4785c18cee47232095a50
[ "MIT" ]
null
null
null
leetcode/src/0142-detectCycle.cpp
Wasikowska/go-typebyname
460c50de881508f340c4785c18cee47232095a50
[ "MIT" ]
null
null
null
#include <iostream> #include <unordered_set> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *detectCycle(ListNode *head) { if (!head) { return nullptr; } // floyd's cycle finding algorithm ListNode* n1{head}; ListNode* n2{head->next}; while (n1 && n2) { if (n1 == n2) { // find a cycle std::unordered_set<ListNode*> cycle; while (n1) { if (cycle.find(n1) != cycle.end()) { break; } cycle.insert(n1); n1 = n1->next; } ListNode* n{head}; while (n) { if (cycle.find(n) != cycle.end()) { return n; } n = n->next; } } n1 = n1->next; n2 = n2->next ? n2->next->next : nullptr; } return nullptr; } };
16.291667
47
0.543478
Wasikowska
4a2bf58675380c45030695db57d420ccd8cd67f1
2,286
cpp
C++
src/tests/test_rdtree_select.cpp
rvianello/chemicalite
0feb0d122e2f38730e2033e76681699c12eb1b23
[ "BSD-3-Clause" ]
29
2015-03-07T14:40:35.000Z
2022-02-05T21:17:42.000Z
src/tests/test_rdtree_select.cpp
rvianello/chemicalite
0feb0d122e2f38730e2033e76681699c12eb1b23
[ "BSD-3-Clause" ]
3
2015-11-18T05:04:48.000Z
2020-12-16T22:37:25.000Z
src/tests/test_rdtree_select.cpp
rvianello/chemicalite
0feb0d122e2f38730e2033e76681699c12eb1b23
[ "BSD-3-Clause" ]
3
2020-05-13T19:02:07.000Z
2021-08-02T10:45:32.000Z
#include "test_common.hpp" TEST_CASE("rdtree select", "[rdtree]") { sqlite3 * db = nullptr; test_db_open(&db); int rc = sqlite3_exec( db, "CREATE VIRTUAL TABLE xyz USING rdtree(id integer primary key, s bits(1024))", NULL, NULL, NULL); REQUIRE(rc == SQLITE_OK); // insert some binary fingerprints sqlite3_stmt *pStmt = nullptr; rc = sqlite3_prepare(db, "INSERT INTO xyz(id, s) VALUES(?1, bfp_dummy(1024, ?2))", -1, &pStmt, 0); REQUIRE(rc == SQLITE_OK); for (int i=0; i < 256; ++i) { rc = sqlite3_bind_int(pStmt, 1, i+1); REQUIRE(rc == SQLITE_OK); rc = sqlite3_bind_int(pStmt, 2, i); REQUIRE(rc == SQLITE_OK); rc = sqlite3_step(pStmt); REQUIRE(rc == SQLITE_DONE); rc = sqlite3_reset(pStmt); REQUIRE(rc == SQLITE_OK); } SECTION("select matching simple subset constraints") { // if we use 0x01 as subset match constraint, it will return all the dummy bfp // records generated by an odd number. we therefore expect the number of these // records to be a half of the total test_select_value( db, "SELECT COUNT(*) FROM xyz WHERE id MATCH rdtree_subset(bfp_dummy(1024, 1))", 128); // if we instead use 0x0f, the fingerprints matching this pattern as subset are those // that vary in value of the more significant nibble (0x0f, 0x1f, ... 0xff). there should // be 16 such fingerprints test_select_value( db, "SELECT COUNT(*) FROM xyz WHERE id MATCH rdtree_subset(bfp_dummy(1024, 0x0f))", 16); } SECTION("select matching simple similarity constraints") { // if we use 0x01 as similarity match constraint, with a threshold of at least 0.5 // we should get 0x01 (perfect match) and the bfps with two bits set per byte where // one of the bits is 0x01 (7 more values). the expected number of returned values // is therefore 8 test_select_value( db, "SELECT COUNT(*) FROM xyz WHERE bfp_tanimoto(bfp_dummy(1024, 1), s) >= 0.5", 8); test_select_value( db, "SELECT COUNT(*) FROM xyz WHERE id MATCH rdtree_tanimoto(bfp_dummy(1024, 1), .5)", 8); } sqlite3_finalize(pStmt); rc = sqlite3_exec(db, "DROP TABLE xyz", NULL, NULL, NULL); REQUIRE(rc == SQLITE_OK); test_db_close(db); }
31.75
100
0.653981
rvianello
4a30d03c7eb0777c467f15599aebad9a2b02e6eb
2,894
cpp
C++
src/graphics/ressources/buffers.cpp
guillaume-haerinck/learn-vulkan
30acd5b477866f7454a3c89bf10a7bfffc11c9a1
[ "MIT" ]
null
null
null
src/graphics/ressources/buffers.cpp
guillaume-haerinck/learn-vulkan
30acd5b477866f7454a3c89bf10a7bfffc11c9a1
[ "MIT" ]
null
null
null
src/graphics/ressources/buffers.cpp
guillaume-haerinck/learn-vulkan
30acd5b477866f7454a3c89bf10a7bfffc11c9a1
[ "MIT" ]
null
null
null
#include "buffers.h" #include <chrono> #include <glm/gtc/matrix_transform.hpp> #include "graphics/setup/devices.h" VertexBuffer::VertexBuffer(LogicalDevice& device, MemoryAllocator& memoryAllocator, const std::vector<Vertex>& vertices) : m_vertices(vertices), IBuffer(device, memoryAllocator) { vk::BufferCreateInfo info( vk::BufferCreateFlags(), sizeof(m_vertices.at(0)) * m_vertices.size(), vk::BufferUsageFlagBits::eVertexBuffer, vk::SharingMode::eExclusive ); m_buffers.push_back(m_device.get().createBufferUnique(info)); m_bufferMemories.push_back(m_memoryAllocator.allocateAndBindBuffer(*this)); } IndexBuffer::IndexBuffer(LogicalDevice& device, MemoryAllocator& memoryAllocator, const Model& model) : IBuffer(device, memoryAllocator) { m_elementCount = model.indicesCount; m_byteSize = sizeof(model.indicesData.at(0)) * model.indicesData.size(); m_indices_data = model.indicesData; vk::BufferCreateInfo info( vk::BufferCreateFlags(), m_byteSize, vk::BufferUsageFlagBits::eIndexBuffer, vk::SharingMode::eExclusive ); m_buffers.push_back(m_device.get().createBufferUnique(info)); m_bufferMemories.push_back(m_memoryAllocator.allocateAndBindBuffer(*this)); } UniformBuffer::UniformBuffer(LogicalDevice& device, MemoryAllocator& memoryAllocator, unsigned int swapChainImagesCount) : IBuffer(device, memoryAllocator) { m_ubo.world = glm::mat4(1); m_ubo.viewProj = glm::mat4(1); vk::DeviceSize bufferSize = sizeof(PerFrameUB); vk::BufferCreateInfo info( vk::BufferCreateFlags(), bufferSize, vk::BufferUsageFlagBits::eUniformBuffer, vk::SharingMode::eExclusive ); for (size_t i = 0; i < swapChainImagesCount; i++) { m_buffers.push_back(m_device.get().createBufferUnique(info)); m_bufferMemories.push_back(m_memoryAllocator.allocateAndBindBuffer(*this, i)); } } UniformBuffer::~UniformBuffer() { } void UniformBuffer::updateBuffer(unsigned int currentImage, const glm::mat4x4& viewProj) { static auto startTime = std::chrono::high_resolution_clock::now(); auto currentTime = std::chrono::high_resolution_clock::now(); float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); // m_ubo.world = glm::rotate(glm::mat4(1), time * glm::radians(90.0f), glm::vec3(0, 0, 1)); m_ubo.viewProj = viewProj; // Copy data vk::MemoryRequirements memoryRequirements = m_device.get().getBufferMemoryRequirements(m_buffers.at(currentImage).get()); unsigned int* pData = static_cast<unsigned int*>(m_device.get().mapMemory(m_bufferMemories.at(currentImage).get(), 0, memoryRequirements.size)); memcpy(pData, &m_ubo, sizeof(m_ubo)); m_device.get().unmapMemory(m_bufferMemories.at(currentImage).get()); }
35.728395
148
0.715619
guillaume-haerinck
4a3198d1b97e8de48fe4a53eea560a25f3d8c27f
1,565
cpp
C++
Algorithm important/search in almost sorted array.cpp
shauryauppal/Algo-DS-StudyMaterial
1c481f066d21b33ec2533156e75f45fa9b6a7606
[ "Apache-2.0" ]
3
2020-12-03T14:52:23.000Z
2021-12-19T09:26:50.000Z
Algorithm important/search in almost sorted array.cpp
shauryauppal/Algo-DS-StudyMaterial
1c481f066d21b33ec2533156e75f45fa9b6a7606
[ "Apache-2.0" ]
null
null
null
Algorithm important/search in almost sorted array.cpp
shauryauppal/Algo-DS-StudyMaterial
1c481f066d21b33ec2533156e75f45fa9b6a7606
[ "Apache-2.0" ]
null
null
null
/*Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1]. For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position. Example: Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40 Output: 2 Output is index of 40 in given array Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90 Output: -1 -1 is returned to indicate element is not present */ #include <bits/stdc++.h> using namespace std; int binarysearch(int A[],int n,int key) { int low=0,high=n-1,mid; while(low<=high) { mid=(low+high)/2; if(A[mid]==key) return mid; if(A[mid+1]==key ) return mid+1; if(A[mid-1]==key) return mid-1; if(key>A[mid]) { low=mid+2; } else high=mid-2; } return -1; } int main() { int n; cout<<"\nEnter number of elements->"; cin>>n; int A[n]; for(int i=0;i<n;i++) cin>>A[i]; int key; cout<<"\nEnter the element u want to search->"; cin>>key; int index=binarysearch(A,n,key); if(index==-1) { cout<<"\nNot found!!!!!!"; exit(0); } cout<<'\n'<<key<<"Found at->"<<index; return 0; }
26.083333
313
0.53738
shauryauppal
4a32688bc6ba34f96da03103f07dc211f948f8b8
529
cpp
C++
aula10092020/retangulo.cpp
imdcode/imd0030_t02_2020
9c08e159752fa3d1169518fcc4a1046c045d7cec
[ "MIT" ]
3
2020-09-23T00:59:43.000Z
2020-10-06T22:27:00.000Z
aula10092020/retangulo.cpp
imdcode/imd0030_t02_2020
9c08e159752fa3d1169518fcc4a1046c045d7cec
[ "MIT" ]
null
null
null
aula10092020/retangulo.cpp
imdcode/imd0030_t02_2020
9c08e159752fa3d1169518fcc4a1046c045d7cec
[ "MIT" ]
4
2020-10-05T05:36:25.000Z
2020-12-08T02:47:32.000Z
#include <iostream> #include "retangulo.hpp" using std::cout; using std::endl; int Retangulo::getLargura() { return largura; } void Retangulo::setLargura(int largura_) { if (largura_ < 0) { cout << "O valor da largura deve ser maior ou igual a zero." << endl; } else { largura = largura_; } } int Retangulo::getAltura() { return altura; } void Retangulo::setAltura(int altura_) { altura = altura_; } int Retangulo::area() { return altura*largura; } int Retangulo::perimetro() { return (2*altura + 2*largura); }
16.53125
71
0.678639
imdcode
4a37d96cf9d056243d71c788eb078d88ef78a570
497
hpp
C++
src/loader/mod_package_loader.hpp
LeoCodes21/ModLoader
be2827f52390d77d7bf01b5f345092761b8f234d
[ "MIT" ]
4
2020-07-05T15:13:35.000Z
2021-02-04T00:03:01.000Z
src/loader/mod_package_loader.hpp
LeoCodes21/ModLoader
be2827f52390d77d7bf01b5f345092761b8f234d
[ "MIT" ]
1
2020-11-25T03:14:37.000Z
2020-11-25T03:14:37.000Z
src/loader/mod_package_loader.hpp
LeoCodes21/ModLoader
be2827f52390d77d7bf01b5f345092761b8f234d
[ "MIT" ]
5
2020-03-22T19:22:27.000Z
2021-02-21T15:22:58.000Z
// // Created by coder on 3/17/2020. // #ifndef MODLOADER_MOD_PACKAGE_LOADER_HPP #define MODLOADER_MOD_PACKAGE_LOADER_HPP #include <filesystem> #include "mod_package.hpp" namespace fs = std::filesystem; class mod_package_loader { public: mod_package_loader(std::string &server_id, fs::path &path); ~mod_package_loader() = default; std::shared_ptr<mod_package> load(); private: fs::path &m_path_; std::string &m_server_id_; }; #endif //MODLOADER_MOD_PACKAGE_LOADER_HPP
17.75
63
0.738431
LeoCodes21
4a3997dd491fbc0f82d3a9540674e0dde872efae
6,512
hpp
C++
libs/Core/include/argos-Core/Support/SyntaxPool.hpp
henrikfroehling/argos
821ea18335838bcb2e88187adc12b59c51cd3522
[ "MIT" ]
null
null
null
libs/Core/include/argos-Core/Support/SyntaxPool.hpp
henrikfroehling/argos
821ea18335838bcb2e88187adc12b59c51cd3522
[ "MIT" ]
2
2022-02-16T23:58:02.000Z
2022-03-16T20:53:15.000Z
libs/Core/include/argos-Core/Support/SyntaxPool.hpp
henrikfroehling/argos
821ea18335838bcb2e88187adc12b59c51cd3522
[ "MIT" ]
null
null
null
#ifndef ARGOS_CORE_SUPPORT_SYNTAXPOOL_H #define ARGOS_CORE_SUPPORT_SYNTAXPOOL_H #include <memory> #include <unordered_map> #include <vector> #include "argos-Core/argos_global.hpp" #include "argos-Core/Syntax/ISyntaxNode.hpp" #include "argos-Core/Syntax/ISyntaxToken.hpp" #include "argos-Core/Syntax/ISyntaxTrivia.hpp" #include "argos-Core/Syntax/ISyntaxTriviaList.hpp" #include "argos-Core/Syntax/SyntaxMissingToken.hpp" #include "argos-Core/Syntax/SyntaxToken.hpp" #include "argos-Core/Syntax/SyntaxTrivia.hpp" #include "argos-Core/Syntax/SyntaxTriviaList.hpp" #include "argos-Core/Types.hpp" namespace argos::Core::Support { /** * @brief Storage container for all created syntax elements. */ class ARGOS_CORE_API SyntaxPool final { public: /** * @brief Creates a <code>SyntaxPool</code> instance. */ SyntaxPool() noexcept = default; /** * @brief Creates a new <code>ISyntaxToken</code> with the given arguments. * @param args The arguments for the <code>ISyntaxToken</code>s constructor. */ template <typename... TokenArgs> const Syntax::ISyntaxToken* createSyntaxToken(TokenArgs&&... args) noexcept; /** * @brief Creates a new <code>ISyntaxMissingToken</code> with the given arguments. * @param args The arguments for the <code>ISyntaxMissingToken</code>s constructor. */ template <typename... TokenArgs> const Syntax::ISyntaxToken* createMissingSyntaxToken(TokenArgs&&... args) noexcept; // TODO Change return type to ISyntaxMissingToken /** * @brief Creates a new leading <code>ISyntaxTrivia</code> with the given arguments. * @param args The arguments for the leading <code>ISyntaxTrivia</code>s constructor. */ template <typename... TriviaArgs> const Syntax::ISyntaxTrivia* createLeadingTrivia(TriviaArgs&&... args) noexcept; /** * @brief Creates a new trailing <code>ISyntaxTrivia</code> with the given arguments. * @param args The arguments for the trailing <code>ISyntaxTrivia</code>s constructor. */ template <typename... TriviaArgs> const Syntax::ISyntaxTrivia* createTrailingTrivia(TriviaArgs&&... args) noexcept; /** * @brief Creates a new leading <code>ISyntaxTriviaList</code> for the <code>Token</code> at the given <code>tokenIndex</code>. * @param tokenIndex The index of the <code>Token</code> for which the leading <code>ISyntaxTriviaList</code> will be created. * @param args The arguments for the leading <code>ISyntaxTriviaList</code>s constructor. */ template <typename... TriviaListArgs> void createLeadingTriviaList(argos_size tokenIndex, TriviaListArgs&&... args) noexcept; /** * @brief Creates a new trailing <code>ISyntaxTriviaList</code> for the <code>Token</code> at the given <code>tokenIndex</code>. * @param tokenIndex The index of the <code>Token</code> for which the trailing <code>ISyntaxTriviaList</code> will be created. * @param args The arguments for the trailing <code>ISyntaxTriviaList</code>s constructor. */ template <typename... TriviaListArgs> void createTrailingTriviaList(argos_size tokenIndex, TriviaListArgs&&... args) noexcept; /** * @brief Creates a new <code>ISyntaxNode</code> with the given arguments. * @param args The arguments for the <code>ISyntaxNode</code>s constructor. */ template <typename NodeType, typename... NodeTypeArgs> const NodeType* createSyntaxNode(NodeTypeArgs&&... args) noexcept; const Syntax::ISyntaxTriviaList* leadingTriviaList(argos_size tokenIndex) const noexcept; const Syntax::ISyntaxTriviaList* trailingTriviaList(argos_size tokenIndex) const noexcept; private: std::vector<std::shared_ptr<Syntax::ISyntaxToken>> _syntaxTokens{}; std::vector<std::shared_ptr<Syntax::ISyntaxNode>> _syntaxNodes{}; std::vector<std::shared_ptr<Syntax::ISyntaxTrivia>> _leadingSyntaxTrivia{}; std::vector<std::shared_ptr<Syntax::ISyntaxTrivia>> _trailingSyntaxTrivia{}; std::unordered_map<argos_size, std::shared_ptr<Syntax::ISyntaxTriviaList>> _leadingSyntaxTriviaLists{}; std::unordered_map<argos_size, std::shared_ptr<Syntax::ISyntaxTriviaList>> _trailingSyntaxTriviaLists{}; }; template <typename... TokenArgs> const Syntax::ISyntaxToken* SyntaxPool::createSyntaxToken(TokenArgs&&... args) noexcept { _syntaxTokens.emplace_back(std::make_shared<Syntax::SyntaxToken>(std::forward<TokenArgs>(args)...)); return _syntaxTokens.back().get(); } template <typename... TokenArgs> const Syntax::ISyntaxToken* SyntaxPool::createMissingSyntaxToken(TokenArgs&&... args) noexcept { _syntaxTokens.emplace_back(std::make_shared<Syntax::SyntaxMissingToken>(std::forward<TokenArgs>(args)...)); return _syntaxTokens.back().get(); } template <typename... TriviaArgs> const Syntax::ISyntaxTrivia* SyntaxPool::createLeadingTrivia(TriviaArgs&&... args) noexcept { _leadingSyntaxTrivia.emplace_back(std::make_shared<Syntax::SyntaxTrivia>(std::forward<TriviaArgs>(args)...)); return _leadingSyntaxTrivia.back().get(); } template <typename... TriviaArgs> const Syntax::ISyntaxTrivia* SyntaxPool::createTrailingTrivia(TriviaArgs&&... args) noexcept { _trailingSyntaxTrivia.emplace_back(std::make_shared<Syntax::SyntaxTrivia>(std::forward<TriviaArgs>(args)...)); return _trailingSyntaxTrivia.back().get(); } template <typename... TriviaListArgs> void SyntaxPool::createLeadingTriviaList(argos_size tokenIndex, TriviaListArgs&&... args) noexcept { _leadingSyntaxTriviaLists.try_emplace(tokenIndex, std::make_shared<Syntax::SyntaxTriviaList>(std::forward<TriviaListArgs>(args)...)); } template <typename... TriviaListArgs> void SyntaxPool::createTrailingTriviaList(argos_size tokenIndex, TriviaListArgs&&... args) noexcept { _trailingSyntaxTriviaLists.try_emplace(tokenIndex, std::make_shared<Syntax::SyntaxTriviaList>(std::forward<TriviaListArgs>(args)...)); } template <typename NodeType, typename... NodeTypeArgs> const NodeType* SyntaxPool::createSyntaxNode(NodeTypeArgs&&... args) noexcept { auto syntaxNode = std::make_shared<NodeType>(std::forward<NodeTypeArgs>(args)...); auto returnValue = syntaxNode.get(); _syntaxNodes.push_back(std::move(syntaxNode)); return returnValue; } } // end namespace argos::Core::Support #endif // ARGOS_CORE_SUPPORT_SYNTAXPOOL_H
42.285714
138
0.724355
henrikfroehling
6654c3d3a8690609b115e250c82c4b8bfa8c4ef1
7,848
cpp
C++
src/base64.cpp
abbyssoul/libsolace
390c3094af1837715787c33297720bf514f04710
[ "Apache-2.0" ]
18
2016-05-30T23:46:27.000Z
2022-01-11T18:20:28.000Z
src/base64.cpp
abbyssoul/libsolace
390c3094af1837715787c33297720bf514f04710
[ "Apache-2.0" ]
4
2017-09-12T13:32:28.000Z
2019-10-21T10:36:18.000Z
src/base64.cpp
abbyssoul/libsolace
390c3094af1837715787c33297720bf514f04710
[ "Apache-2.0" ]
5
2017-11-24T19:34:06.000Z
2019-10-18T14:24:12.000Z
/* * Copyright 2017 Ivan Ryabov * * 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. */ /******************************************************************************* * libSolace * @file base64.cpp * @brief Implementation of Base64 encoder and decoder. ******************************************************************************/ #include "solace/base64.hpp" #include "solace/posixErrorDomain.hpp" #include <climits> using namespace Solace; static constexpr byte kBase64Alphabet[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static constexpr byte kBase64UrlAlphabet[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; Result<void, Error> base64encode(ByteWriter& dest, MemoryView const& src, byte const alphabet[65]) { MemoryView::size_type i = 0; for (; i + 2 < src.size(); i += 3) { byte const encoded[] = { alphabet[ (src[i] >> 2) & 0x3F], alphabet[((src[i] & 0x3) << 4) | (static_cast<int>(src[i + 1] & 0xF0) >> 4)], alphabet[((src[i + 1] & 0xF) << 2) | (static_cast<int>(src[i + 2] & 0xC0) >> 6)], alphabet[ src[i + 2] & 0x3F] }; auto res = dest.write(wrapMemory(encoded)); if (!res) return res.moveError(); } if (i < src.size()) { byte encoded[4]; encoded[0] = alphabet[(src[i] >> 2) & 0x3F]; if (i + 1 == src.size()) { encoded[1] = alphabet[((src[i] & 0x3) << 4)]; encoded[2] = '='; } else { encoded[1] = alphabet[((src[i] & 0x3) << 4) | (static_cast<int>(src[i + 1] & 0xF0) >> 4)]; encoded[2] = alphabet[((src[i + 1] & 0xF) << 2)]; } encoded[3] = '='; auto res = dest.write(wrapMemory(encoded)); if (!res) return res.moveError(); } return Ok(); } /* aaaack but it's fast and const should make it shared text page. */ static const byte pr2six[256] = { /* ASCII table */ // 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 00..0F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 10..1F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, // 20..2F 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 30..3F 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40..4F 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, // 50..5F 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60..6F 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 70..7F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 80..8F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 90..9F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // A0..AF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // B0..BF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // C0..CF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // D0..DF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // E0..EF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 // F0..FF }; static const byte prUrl2six[256] = { /* ASCII table */ // 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 00..0F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 10..1F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, // 20..2F 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 30..3F 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40..4F 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 63, // 50..5F 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60..6F 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 70..7F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 80..8F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 90..9F 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // A0..AF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // B0..BF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // C0..CF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // D0..DF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // E0..EF 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 // F0..FF }; Result<void, Error> base64decode(ByteWriter& dest, MemoryView src, byte const* decodingTable) { if (src.empty()) { return makeError(SystemErrors::NODATA, "base64decode"); } byte const* bufin = src.begin(); while (decodingTable[*(bufin++)] <= 63) // Count decodable bytes {} auto nprbytes = (bufin - src.begin()) - 1; bufin = src.begin(); while (nprbytes > 4) { byte const encoded[] = { static_cast<byte>(decodingTable[bufin[0]] << 2 | decodingTable[bufin[1]] >> 4), static_cast<byte>(decodingTable[bufin[1]] << 4 | decodingTable[bufin[2]] >> 2), static_cast<byte>(decodingTable[bufin[2]] << 6 | decodingTable[bufin[3]]) }; auto res = dest.write(wrapMemory(encoded)); if (!res) return res.moveError(); bufin += 4; nprbytes -= 4; } /* Note: (nprbytes == 1) would be an error, so just ingore that case */ if (nprbytes > 1) { auto res = dest.write(static_cast<byte>(decodingTable[bufin[0]] << 2 | decodingTable[bufin[1]] >> 4)); if (!res) return res.moveError(); } if (nprbytes > 2) { auto res = dest.write(static_cast<byte>(decodingTable[bufin[1]] << 4 | decodingTable[bufin[2]] >> 2)); if (!res) return res.moveError(); } if (nprbytes > 3) { auto res = dest.write(static_cast<byte>(decodingTable[bufin[2]] << 6 | decodingTable[bufin[3]])); if (!res) return res.moveError(); } return Ok(); } Base64Encoder::size_type Base64Encoder::encodedSize(size_type len) { return ((4 * len / 3) + 3) & ~3; } Base64Decoder::size_type Base64Decoder::decodedSize(MemoryView data) { if (data.empty()) { return 0; } if (data.size() % 4) { return 0; // FIXME: Probably throw! } size_type nprbytes = 0; for (const auto& b : data) { if (pr2six[b] <= 63) { ++nprbytes; } else { break; } } return (nprbytes * 3 / 4); } Base64Decoder::size_type Base64Decoder::encodedSize(MemoryView data) const { return decodedSize(data); } Result<void, Error> Base64Encoder::encode(MemoryView src) { return base64encode(*getDestBuffer(), src, kBase64Alphabet); } Result<void, Error> Base64UrlEncoder::encode(MemoryView src) { return base64encode(*getDestBuffer(), src, kBase64UrlAlphabet); } Result<void, Error> Base64Decoder::encode(MemoryView src) { return base64decode(*getDestBuffer(), src, pr2six); } Result<void, Error> Base64UrlDecoder::encode(MemoryView src) { return base64decode(*getDestBuffer(), src, prUrl2six); }
35.192825
114
0.541157
abbyssoul
665538034c76f7fbc9c98fc4defb37da81ee5eb2
347
cpp
C++
Online Judges/URI/2343/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/2343/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/2343/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> using namespace std; int main() { int t, x, y, flag = false, vet[1000][1000] = {0}; cin >> t; while(t--) { cin >> x >> y; if(!flag && vet[x][y] == 1) flag = true; vet[x][y] = 1; } if(flag) cout << 1 << endl; else cout << 0 << endl; return 0; }
15.772727
53
0.409222
AnneLivia
665a99b19c8f938f1889a8d7480d84add7512067
1,413
cpp
C++
src/omplapp/graphics/RenderGeometry.cpp
SZanlongo/omplapp
c56679337e2a71d266359450afbe63d700c0a666
[ "BSD-3-Clause" ]
null
null
null
src/omplapp/graphics/RenderGeometry.cpp
SZanlongo/omplapp
c56679337e2a71d266359450afbe63d700c0a666
[ "BSD-3-Clause" ]
null
null
null
src/omplapp/graphics/RenderGeometry.cpp
SZanlongo/omplapp
c56679337e2a71d266359450afbe63d700c0a666
[ "BSD-3-Clause" ]
1
2019-07-01T09:30:45.000Z
2019-07-01T09:30:45.000Z
/********************************************************************* * Rice University Software Distribution License * * Copyright (c) 2010, Rice University * All Rights Reserved. * * For a full description see the file named LICENSE. * *********************************************************************/ /* Author: Ioan Sucan */ #include "omplapp/graphics/RenderGeometry.h" #include "omplapp/graphics/detail/assimpGUtil.h" #include "omplapp/graphics/detail/RenderPlannerData.h" int ompl::app::RenderGeometry::renderEnvironment(void) const { const GeometrySpecification &gs = rbg_.getGeometrySpecification(); return scene::assimpRender(gs.obstacles, gs.obstaclesShift); } int ompl::app::RenderGeometry::renderRobot(void) const { const GeometrySpecification &gs = rbg_.getGeometrySpecification(); return scene::assimpRender(gs.robot, gs.robotShift); } int ompl::app::RenderGeometry::renderRobotPart(unsigned int index) const { const GeometrySpecification &gs = rbg_.getGeometrySpecification(); if (index >= gs.robot.size()) return 0; return scene::assimpRender(gs.robot[index], gs.robotShift.size() > index ? gs.robotShift[index] : aiVector3D(0.0, 0.0, 0.0)); } int ompl::app::RenderGeometry::renderPlannerData(const base::PlannerData &pd) const { return RenderPlannerData(pd, aiVector3D(0.0, 0.0, 0.0), rbg_.getMotionModel(), se_, rbg_.getLoadedRobotCount()); }
34.463415
129
0.669498
SZanlongo
665aeb9b094f370b68541d7d69904a7aacd9eda9
22,967
hpp
C++
backend/BplusTree/Bptree.hpp
XunZhiyang/TTRS
c417dc46a198ee248c1b712dc8a0780b55482358
[ "MIT" ]
null
null
null
backend/BplusTree/Bptree.hpp
XunZhiyang/TTRS
c417dc46a198ee248c1b712dc8a0780b55482358
[ "MIT" ]
3
2020-07-17T04:22:52.000Z
2021-10-05T22:11:08.000Z
backend/BplusTree/Bptree.hpp
XunZhiyang/TTRS
c417dc46a198ee248c1b712dc8a0780b55482358
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <cstdio> #include <cstring> #include <deque> #include <cassert> #include "./utility.hpp" #include "./exceptions.hpp" #ifndef BPTREE_HPP #define BPTREE_HPP namespace sjtu { /* * Attention : In this file I use std::pair & std::map * replace them with sjtu:pair when finishing development. */ template< class Key, class T, class Compare = std::less<Key>, int IndexSize = 5, int PageSize = 5 > class Bptree { public: class node; class block; private: node *root; int CurrentLen; public: typedef std::pair<Key, T> value_type; bool Fewer(Key a, Key b, Compare C = Compare()) { return C(a, b); } bool Equal(Key a, Key b) { return !(Fewer(a, b) || Fewer(b, a)); } class node { /* * type = 0 { * it's an index page, it stores the address of its (NumChild) children * as well as (NumChild - 1) index to redirect to its children * prev&next are not needed in this type * } * type = 1 { * it's a leaf page, it stores (PageSize) values in data, and it has prev&next * } */ friend class Bptree; /* * Children array could be changed to deque ? which is much faster */ node *Children[IndexSize + 1], *father; std::deque<value_type> data; int NumChild, type; node *prev, *next; /* * Insert value into a leaf page not considering it's full or not * TODO: improve to binary search */ void BinInsert(value_type value) { if (type == 1) { data.push_back(value); for (int i = NumChild; i >= 1; i--) { if (data[i] < data[i - 1]) { std::swap(data[i], data[i - 1]); } else break; } NumChild++; } } /* * Erase key of node p. * If it's p->data[0] in the indexpage like p->father * then add p->data[1] to indexpage in place of the formal p->data[0] * TODO: improve to binary search */ void BinErase(Key key) { int pos = BinSearch(key); data.erase(data.begin() + pos); if (pos == 0 && father != nullptr) { pos = father->BinSearch(key); if(pos != -1) father->data[pos] = data[0]; } NumChild--; } /* * return which pos does key holds on data * if it's index page, it could be used as p->BinSearch(p->data.front()); * if p is the first child, return -1; * or key does not exist */ int BinSearch(Key key) { if (type) { for (int i = 0; i < NumChild; i++) { if (Equal(key, data[i].first)) return i; } } else { for (int i = 0; i < NumChild - 1; i++) { if (Equal(key, data[i].first)) return i; } return -1; } } void UpdateFather(int pos){ father->data[pos] = data.front(); return; } void DeleteChild(int pos){ data.erase(data.begin() + pos); for (int i = pos + 1; i < NumChild - 1; i++) { Children[i] = Children[i + 1]; } NumChild--; } node(int t, node *f = nullptr, node *p = nullptr, node *n = nullptr) : type(t), father(f), prev(p), next(n) { NumChild = 0; } bool Fewer(Key a, Key b, Compare C = Compare()) { return C(a, b); } bool Equal(Key a, Key b) { return !(Fewer(a, b) || Fewer(b, a)); } }; Bptree() { root = nullptr; CurrentLen = 0; } Bptree &operator=(const Bptree &other) {} ~Bptree() {} T &at(const Key &key) { if (CurrentLen == 0) throw (container_is_empty()); node *p = Search(key); for (int i = 0; i < p->NumChild; i++) { if (p->data[i].first == key) { return p->data[i].second; } } throw (runtime_error()); } T &operator[](const Key &key) {} bool empty() const { return (CurrentLen == 0); } size_t size() const { return CurrentLen; } void clear() { ClearNode(root); CurrentLen = 0; } void ClearNode(node *p) { for (int i = 0; i < p->NumChild; i++) { ClearNode(p->Children[i]); } delete p; } /* * the most shitty function * there're 3 cases in total */ bool insert(const value_type &value) { //if (root != nullptr) PrintNode(root); CurrentLen++; /* * Insert first element */ if (root == nullptr) { node *Leaf = new node(1); Leaf->data.push_back(value); Leaf->NumChild++; root = Leaf; return true; } node *p = Search(value.first); /* * Case 1: the leaf page isn't full yet * insert directly */ if (p->NumChild + 1 < PageSize) { p->BinInsert(value); return true; } else { /* * Case 2: the leaf page is full * But the index page above is not full * SubCase 1: leaf page is root * SubCase 2: else */ if (p == root) { p->BinInsert(value); SplitLeafRoot(value, p); return true; } else if (p->father->NumChild < IndexSize) { p->BinInsert(value); SplitLeaf(p); /* * TODO : if p->prev not full, then rotate p */ return true; } else { /* * Case 3: both the leaf page & the index page are full * we should balance the tree recursively */ p->BinInsert(value); SplitLeaf(p); if (p->father == root) SplitIndexRoot(p->father); else SplitIndex(p->father); return true; } } } /* * Also 3 cases; * Consider Fillfactor = LeafSize/2 or IndexSize/2 */ node *erase(const Key key) { if (CurrentLen == 0) throw(container_is_empty()); node *p = Search(key); if (p == nullptr) throw(invalid_iterator()); CurrentLen--; if (p == root) { p->BinErase(key); return p; } if (p->NumChild - 1 >= PageSize / 2) { /* * Case 1: LeafPageSize > FillFactor; * Just erase (and update data of Indexpage) */ p->BinErase(key); return p; } else { if (p->father->NumChild - 1 > IndexSize / 2) { /* * Case 2: else if IndexPageSize > FillFactor; * Get data from brother if brother is larger then fillfactor * else Merge Leaf p and its brother */ p->BinErase(key); LendMergeLeaf(p); } else { /* * Case 3: IndexPageSize & LeafPageSize <= FillFactor * Lend and merge recursively */ p->BinErase(key); if( !LendMergeLeaf(p) ) { LendMergeIndex(p->father); } } } } /* * Used to Debug: * print all the inserted element from left to right */ void Print(){ node * p = root; while(p->type != 1) { p = p->Children[0]; } while(p != nullptr) { PrintNode(p); p = p->next; } std::cout << std::endl; } size_t count(const Key &key) const { return CurrentLen; } private: /* * Find the block that key might be at * If there is no block, return root */ node *Search(Key key) { if (root == nullptr) return nullptr; node *p = root; int flag; while (p->type != 1) { flag = 0; for (int i = 0; i < p->NumChild - 1; i++) { if (Fewer(key, p->data[i].first)) { p = p->Children[i]; flag = 1; break; } } if (!flag) p = p->Children[p->NumChild - 1]; } return p; } /* * SplitLeaf a max-size node p into 2 nodes * and link them with their father (maintain index !) */ void SplitLeaf(node * p) { /* * TODO Debug */ node *NewLeaf = new node(1); node *fa = p->father; for (int i = PageSize / 2; i <= PageSize - 1; i++) { NewLeaf->data.push_back(p->data[i]); } p->NumChild = PageSize / 2; NewLeaf->NumChild = PageSize - PageSize / 2; NewLeaf->father = fa; fa->Children[fa->NumChild] = NewLeaf; fa->NumChild++; fa->data.push_back(NewLeaf->data[0]); //fa->data[p->father->NumChild - 3] = p->data[0]; node *nextp = p->next; p->next = NewLeaf; NewLeaf->prev = p; if (nextp != nullptr) { nextp->prev = NewLeaf; NewLeaf->next = nextp; } for (int i = PageSize / 2; i <= PageSize - 1; i++) p->data.erase(p->data.begin() + i); } /* * Split a index-page into 2 index-pages, then create a * link to their father index page. * For example, index page holds (3, 6, 9, 12, 15) which connect 6 leaf pages * it turns to * 9 * / \ * (3, 6) (12, 15) */ void SplitIndex(node *p) { /* * Case 1: p is not root * do it recursively; */ while (p != root) { if (p->NumChild > IndexSize) { node *brother = GetBrother(p); p->NumChild = IndexSize / 2 + 1; p->data.pop_back(); p->father->data.push_back(p->data[IndexSize / 2]); //push_back???? p->father->Children[p->father->NumChild] = brother; //p->father->Numchild ???? brother->father = p->father; p->father->NumChild++; p = p->father; } else break; } if (p == root && p->NumChild > IndexSize) { SplitIndexRoot(p); } } /* * Split index page while it's root */ inline void SplitIndexRoot(node *p) { /* * Case 2: p is root of the tree */ node *fa = new node(0); fa->NumChild = 2; node *brother = GetBrother(p); p->NumChild = IndexSize / 2 + 1; fa->data.push_back(p->data[IndexSize / 2]); for (int i = IndexSize / 2; i < IndexSize; i++) p->data.erase(p->data.begin() + i); fa->Children[0] = p; p->father = fa; fa->Children[1] = brother; brother->father = fa; root = fa; } /* * Serve for SplitIndexRoot. * Do not use REFERENCE!! */ node *GetBrother(node *p) { node *brother = new node(0); for (int i = IndexSize / 2 + 1; i <= IndexSize; i++) { brother->Children[i - IndexSize / 2 - 1] = p->Children[i]; p->Children[i]->father = brother; } brother->NumChild = IndexSize - IndexSize / 2; for (int i = IndexSize / 2 + 1; i < IndexSize; i++) { brother->data.push_back(p->data[i]); } for (int i = IndexSize / 2 + 1; i < IndexSize; i++) { p->data.pop_back(); } return brother; } /* * Initial situation that leafpage is root * Insert and develop new root */ inline void SplitLeafRoot(const value_type &value, node *&p) { node *NewLeaf = new node(1); for (int i = PageSize / 2; i <= PageSize - 1; i++) { NewLeaf->data.push_back(p->data[i]); } for (int i = PageSize / 2; i <= PageSize - 1; i++) p->data.erase(p->data.begin() + i); p->NumChild = PageSize / 2; NewLeaf->NumChild = PageSize - PageSize / 2; node *fa = new node(0); fa->NumChild = 2; fa->data.push_back(NewLeaf->data[0]); fa->Children[0] = p; fa->Children[1] = NewLeaf; p->father = fa; NewLeaf->father = fa; p->next = NewLeaf; NewLeaf->prev = p; //TODO p->next->prev = NewLeaf root = fa; } /* * When leaf page p is full, we can use space from it's brother * by rotation otherwise there'll be too much split and leaf page is not always full */ void RotateLeafPage(node *p) { } /* * To keep LeafPageSize larger then fillfactor * we consider 3 cases * Case 1: prev is large enough, then take one data of prev to p; * Case 2: next is large(if there is one), then do the same * Case 3: both are not enough, merge prev and p; * if lend is successful return true; * else return false, * and we need to check if the tree is still balanced or p->father is root */ bool LendMergeLeaf(node *p) { int sit = 0; if (p->prev != nullptr) { if (p->prev->NumChild > PageSize / 2) sit = 1; } if (sit == 0){ if (p->next != nullptr) { if (p->next->NumChild > PageSize / 2) sit = 2; else sit = 3; } } switch (sit) { case 1: { node *pre = p->prev; p->BinInsert(pre->data.back()); pre->data.pop_back(); pre->NumChild--; return true; } case 2: { node * nxt = p->next; p->BinInsert(nxt->data.front()); int pos = nxt->father->BinSearch(nxt->data.front().first); nxt->data.pop_front(); nxt->UpdateFather(pos); nxt->NumChild--; return true; } case 3: { if (p->prev != nullptr) MergeLeafPage(p->prev); else MergeLeafPage(p); return false; } } } /* * Merge leaf page p and p->next * and update p->father->data as well as p->father->Children */ void MergeLeafPage(node *p){ node * nxt = p->next; node * fa = p->father; for (int i = p->NumChild; i < p->NumChild + nxt->NumChild; i++){ p->data.push_back(nxt->data[i - p->NumChild]); } p->NumChild += nxt->NumChild; int pos = fa->BinSearch(nxt->data.front().first); fa->DeleteChild(pos); p->next = nullptr; if (nxt->next != nullptr) { p->next = nxt->next; nxt->next->prev = p; } delete nxt; } /* * Most of the time, just lend from brother * else merge node p with brother * Case 0: Merge * Case 1: Lend from left brother * Case 2: Lend from right brother */ void LendMergeIndex(node * p) { if (p == root) { /* * Special case: leaf page is right under root */ if (p->NumChild != 2) return; else { if (p->Children[0]->NumChild == 2 && p->Children[1]->NumChild == 2){ EraseRoot(); } } return; } node * fa = p->father; int sit = 0; int pos = fa->BinSearch(p->data.front().first); if (pos >= 0) { if (fa->Children[pos]->NumChild - 1 > IndexSize / 2) sit = 1; } if (!sit) { if (pos + 1 < fa->NumChild - 1) { if (fa->Children[pos + 2]->NumChild - 1 > IndexSize / 2) sit = 2; } } switch (sit){ case 0: { if (fa == root && fa->NumChild == 2) { EraseRoot(); return; } if (fa->Children[pos + 1] != nullptr) MergeIndexPage(p, pos); else MergeIndexPage(fa->Children[pos - 1], pos - 1); if (fa->NumChild < IndexSize / 2) { LendMergeIndex(fa); } break; } case 1: { /* * This case is not complete yet... */ node * brother = fa->Children[pos - 1]; node * grandson = p->Children[0]->prev; grandson->father = p; for (int i = 1; i < p->NumChild; i++) { } p->Children[0] = grandson; p->data.push_front(grandson->data.front()); brother->data.pop_back(); brother->NumChild--; p->NumChild--; int pos_p = fa->BinSearch(grandson->Children[0]->data.front().first); break; } case 2: { /* * Lend from right brother */ node * brother = fa->Children[pos + 2]; node * grandson = brother->Children[0]; grandson->father = p; p->Children[p->NumChild] = grandson; p->NumChild++; p->data.push_back(grandson->data.front()); brother->data.pop_front(); for (int i = 0; i < brother->NumChild - 1; i++) { brother->Children[i] = brother->Children[i + 1]; } brother->NumChild--; int pos_p = fa->BinSearch(grandson->data.front().first); fa->data[pos_p] = grandson->next->data.front(); break; } } } /* * p & p->next are both Indexsize / 2 * Merge them and update the value f their father. */ void MergeIndexPage(node * p, int pos){ node * fa = p->father; node * brother = fa->Children[pos + 2]; for (int i = p->NumChild; i < p->NumChild + brother->NumChild; i++) { p->Children[i] = brother->Children[i - p->NumChild]; brother->Children[i - p->NumChild]->father = p; } p->data.push_back(fa->data[pos]); for (int i = 0; i < brother->NumChild; i++) { p->data.push_back(brother->data[i]); } fa->DeleteChild(pos); p->NumChild += brother->NumChild; fa->NumChild--; } /* * Root only has 2 children, and they are both less then IndexSize / 2 * So we can merge them to a new root * And this is the only situation that a bptree's height becomes lower */ void EraseRoot(){ if (root->Children[0]->type == 1) { node * p = root->Children[0]; node * bro = root->Children[1]; for (int i = 0; i < bro->NumChild; i++) { p->data.push_back(bro->data[i]); } p->NumChild += bro->NumChild; delete root; delete bro; root = p; return; } node * p = root->Children[0]; node * brother = root ->Children[1]; p->father = nullptr; p->data.push_back(root->data.front()); for (int i = 0; i < brother->NumChild - 1; i++) { p->data.push_back(brother->data[i]); } for (int i = p->NumChild; i < p->NumChild + brother->NumChild; i++) { p->Children[i] = brother->Children[i - p->NumChild]; p->Children[i]->father = p; } p->NumChild += brother->NumChild; delete brother; delete root; root = p; } void PrintNode(node *p) { //std::cout << CurrentLen << ": "; for (int i = 0; i < p->NumChild; i++) { std::cout << p->data[i].first << " "; } //std::cout << "\n"; } }; } #endif
33.725404
98
0.399704
XunZhiyang
665d31b97ead22c6052fe619466bf238dc418496
7,990
cc
C++
CalibTracker/SiPixelESProducers/src/SiPixelROCsStatusAndMappingWrapper.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CalibTracker/SiPixelESProducers/src/SiPixelROCsStatusAndMappingWrapper.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CalibTracker/SiPixelESProducers/src/SiPixelROCsStatusAndMappingWrapper.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// C++ includes #include <algorithm> #include <iomanip> #include <iostream> #include <vector> // CUDA includes #include <cuda_runtime.h> // CMSSW includes #include "CUDADataFormats/SiPixelCluster/interface/gpuClusteringConstants.h" #include "CalibTracker/SiPixelESProducers/interface/SiPixelROCsStatusAndMappingWrapper.h" #include "CondFormats/SiPixelObjects/interface/SiPixelFedCablingMap.h" #include "CondFormats/SiPixelObjects/interface/SiPixelFedCablingTree.h" #include "CondFormats/SiPixelObjects/interface/SiPixelQuality.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "Geometry/CommonDetUnit/interface/GeomDetType.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "HeterogeneousCore/CUDAUtilities/interface/cudaCheck.h" #include "HeterogeneousCore/CUDAUtilities/interface/device_unique_ptr.h" #include "HeterogeneousCore/CUDAUtilities/interface/host_unique_ptr.h" SiPixelROCsStatusAndMappingWrapper::SiPixelROCsStatusAndMappingWrapper(SiPixelFedCablingMap const& cablingMap, TrackerGeometry const& trackerGeom, SiPixelQuality const* badPixelInfo) : cablingMap_(&cablingMap), modToUnpDefault(pixelgpudetails::MAX_SIZE), hasQuality_(badPixelInfo != nullptr) { cudaCheck(cudaMallocHost(&cablingMapHost, sizeof(SiPixelROCsStatusAndMapping))); std::vector<unsigned int> const& fedIds = cablingMap.fedIds(); std::unique_ptr<SiPixelFedCablingTree> const& cabling = cablingMap.cablingTree(); unsigned int startFed = *(fedIds.begin()); unsigned int endFed = *(fedIds.end() - 1); sipixelobjects::CablingPathToDetUnit path; int index = 1; for (unsigned int fed = startFed; fed <= endFed; fed++) { for (unsigned int link = 1; link <= pixelgpudetails::MAX_LINK; link++) { for (unsigned int roc = 1; roc <= pixelgpudetails::MAX_ROC; roc++) { path = {fed, link, roc}; const sipixelobjects::PixelROC* pixelRoc = cabling->findItem(path); cablingMapHost->fed[index] = fed; cablingMapHost->link[index] = link; cablingMapHost->roc[index] = roc; if (pixelRoc != nullptr) { cablingMapHost->rawId[index] = pixelRoc->rawId(); cablingMapHost->rocInDet[index] = pixelRoc->idInDetUnit(); modToUnpDefault[index] = false; if (badPixelInfo != nullptr) cablingMapHost->badRocs[index] = badPixelInfo->IsRocBad(pixelRoc->rawId(), pixelRoc->idInDetUnit()); else cablingMapHost->badRocs[index] = false; } else { // store some dummy number cablingMapHost->rawId[index] = gpuClustering::invalidModuleId; cablingMapHost->rocInDet[index] = gpuClustering::invalidModuleId; cablingMapHost->badRocs[index] = true; modToUnpDefault[index] = true; } index++; } } } // end of FED loop // Given FedId, Link and idinLnk; use the following formula // to get the rawId and idinDU // index = (FedID-1200) * MAX_LINK* MAX_ROC + (Link-1)* MAX_ROC + idinLnk; // where, MAX_LINK = 48, MAX_ROC = 8 for Phase1 as mentioned Danek's email // FedID varies between 1200 to 1338 (In total 108 FED's) // Link varies between 1 to 48 // idinLnk varies between 1 to 8 for (int i = 1; i < index; i++) { if (cablingMapHost->rawId[i] == gpuClustering::invalidModuleId) { cablingMapHost->moduleId[i] = gpuClustering::invalidModuleId; } else { /* std::cout << cablingMapHost->rawId[i] << std::endl; */ auto gdet = trackerGeom.idToDetUnit(cablingMapHost->rawId[i]); if (!gdet) { LogDebug("SiPixelROCsStatusAndMapping") << " Not found: " << cablingMapHost->rawId[i] << std::endl; continue; } cablingMapHost->moduleId[i] = gdet->index(); } LogDebug("SiPixelROCsStatusAndMapping") << "----------------------------------------------------------------------------" << std::endl; LogDebug("SiPixelROCsStatusAndMapping") << i << std::setw(20) << cablingMapHost->fed[i] << std::setw(20) << cablingMapHost->link[i] << std::setw(20) << cablingMapHost->roc[i] << std::endl; LogDebug("SiPixelROCsStatusAndMapping") << i << std::setw(20) << cablingMapHost->rawId[i] << std::setw(20) << cablingMapHost->rocInDet[i] << std::setw(20) << cablingMapHost->moduleId[i] << std::endl; LogDebug("SiPixelROCsStatusAndMapping") << i << std::setw(20) << (bool)cablingMapHost->badRocs[i] << std::setw(20) << std::endl; LogDebug("SiPixelROCsStatusAndMapping") << "----------------------------------------------------------------------------" << std::endl; } cablingMapHost->size = index - 1; } SiPixelROCsStatusAndMappingWrapper::~SiPixelROCsStatusAndMappingWrapper() { cudaCheck(cudaFreeHost(cablingMapHost)); } const SiPixelROCsStatusAndMapping* SiPixelROCsStatusAndMappingWrapper::getGPUProductAsync( cudaStream_t cudaStream) const { const auto& data = gpuData_.dataForCurrentDeviceAsync(cudaStream, [this](GPUData& data, cudaStream_t stream) { // allocate cudaCheck(cudaMalloc(&data.cablingMapDevice, sizeof(SiPixelROCsStatusAndMapping))); // transfer cudaCheck(cudaMemcpyAsync( data.cablingMapDevice, this->cablingMapHost, sizeof(SiPixelROCsStatusAndMapping), cudaMemcpyDefault, stream)); }); return data.cablingMapDevice; } const unsigned char* SiPixelROCsStatusAndMappingWrapper::getModToUnpAllAsync(cudaStream_t cudaStream) const { const auto& data = modToUnp_.dataForCurrentDeviceAsync(cudaStream, [this](ModulesToUnpack& data, cudaStream_t stream) { cudaCheck(cudaMalloc((void**)&data.modToUnpDefault, pixelgpudetails::MAX_SIZE_BYTE_BOOL)); cudaCheck(cudaMemcpyAsync(data.modToUnpDefault, this->modToUnpDefault.data(), this->modToUnpDefault.size() * sizeof(unsigned char), cudaMemcpyDefault, stream)); }); return data.modToUnpDefault; } cms::cuda::device::unique_ptr<unsigned char[]> SiPixelROCsStatusAndMappingWrapper::getModToUnpRegionalAsync( std::set<unsigned int> const& modules, cudaStream_t cudaStream) const { auto modToUnpDevice = cms::cuda::make_device_unique<unsigned char[]>(pixelgpudetails::MAX_SIZE, cudaStream); auto modToUnpHost = cms::cuda::make_host_unique<unsigned char[]>(pixelgpudetails::MAX_SIZE, cudaStream); std::vector<unsigned int> const& fedIds = cablingMap_->fedIds(); std::unique_ptr<SiPixelFedCablingTree> const& cabling = cablingMap_->cablingTree(); unsigned int startFed = *(fedIds.begin()); unsigned int endFed = *(fedIds.end() - 1); sipixelobjects::CablingPathToDetUnit path; int index = 1; for (unsigned int fed = startFed; fed <= endFed; fed++) { for (unsigned int link = 1; link <= pixelgpudetails::MAX_LINK; link++) { for (unsigned int roc = 1; roc <= pixelgpudetails::MAX_ROC; roc++) { path = {fed, link, roc}; const sipixelobjects::PixelROC* pixelRoc = cabling->findItem(path); if (pixelRoc != nullptr) { modToUnpHost[index] = (not modules.empty()) and (modules.find(pixelRoc->rawId()) == modules.end()); } else { // store some dummy number modToUnpHost[index] = true; } index++; } } } cudaCheck(cudaMemcpyAsync(modToUnpDevice.get(), modToUnpHost.get(), pixelgpudetails::MAX_SIZE * sizeof(unsigned char), cudaMemcpyHostToDevice, cudaStream)); return modToUnpDevice; } SiPixelROCsStatusAndMappingWrapper::GPUData::~GPUData() { cudaCheck(cudaFree(cablingMapDevice)); } SiPixelROCsStatusAndMappingWrapper::ModulesToUnpack::~ModulesToUnpack() { cudaCheck(cudaFree(modToUnpDefault)); }
46.453488
118
0.658698
ckamtsikis
6662d1f125d58e10c0535921002a78a797923a68
1,147
cpp
C++
BTTH05/01/PS.cpp
MiMi-Yup/sharing
1a04a4fdd5e179bd5491725004931d0f71923262
[ "BSD-4-Clause-UC" ]
null
null
null
BTTH05/01/PS.cpp
MiMi-Yup/sharing
1a04a4fdd5e179bd5491725004931d0f71923262
[ "BSD-4-Clause-UC" ]
null
null
null
BTTH05/01/PS.cpp
MiMi-Yup/sharing
1a04a4fdd5e179bd5491725004931d0f71923262
[ "BSD-4-Clause-UC" ]
null
null
null
#include "PS.h" PS::PS(int tuso, int mauso) { this->tuso = tuso; this->mauso = mauso; } PS::PS(const PS& ps) { this->tuso = ps.tuso; this->mauso = ps.mauso; } int PS::UCLN(int a, int b) { while (a * b != 0) { if (a > b) { a %= b; } else { b %= a; } } return a + b; } istream& operator>>(istream& is, PS& ps) { do { cout << "Nhap tu so: "; is >> ps.tuso; cout << "Nhap mau so khac 0: "; is >> ps.mauso; if (ps.mauso == 0)cout << "Phan so khong hop le, nhap lai.\n"; } while (ps.mauso == 0); return is; } ostream& operator<<(ostream& os, PS ps) { os << ps.getTu() << "/" << ps.getMau() << "\n"; return os; } int PS::getTu() { return this->tuso; } int PS::getMau() { return this->mauso; } void PS::setTu(int tuso) { this->tuso = tuso; } void PS::setMau(int tuso) { if (tuso != 0) { this->tuso = tuso; } else { cout << "Cap nhap that bai.\n"; } } void PS::Shorter() { int uc = UCLN(tuso, mauso); tuso /= uc; mauso /= uc; } PS& PS::operator++() { this->tuso += mauso; this->Shorter(); return *this; } PS PS::operator++(int) { PS temp(*this); this->tuso += mauso; this->Shorter(); return temp; }
16.867647
64
0.543156
MiMi-Yup
6665430965fdfd0db578199d98aacd16a0af9933
3,211
hpp
C++
fon9/io/SocketConfig.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
21
2019-01-29T14:41:46.000Z
2022-03-11T00:22:56.000Z
fon9/io/SocketConfig.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
null
null
null
fon9/io/SocketConfig.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
9
2019-01-27T14:19:33.000Z
2022-03-11T06:18:24.000Z
/// \file fon9/io/SocketConfig.hpp /// \author fonwinz@gmail.com #ifndef __fon9_io_SocketConfig_hpp__ #define __fon9_io_SocketConfig_hpp__ #include "fon9/io/IoBase.hpp" #include "fon9/io/SocketAddress.hpp" namespace fon9 { namespace io { fon9_WARN_DISABLE_PADDING; /// \ingroup io /// Socket 基本參數. struct fon9_API SocketOptions { /// 使用 "TcpNoDelay=N" 關閉 TCP_NODELAY. /// 預設為 Y. int TCP_NODELAY_; /// 使用 "SNDBUF=size" 設定. /// SO_SNDBUF_ < 0: 使用系統預設值, 否則使用 SO_SNDBUF_ 的設定. int SO_SNDBUF_; /// 使用 "RCVBUF=size" 設定. /// SO_RCVBUF_ < 0: 使用系統預設值, 否則使用 SO_RCVBUF_ 的設定. int SO_RCVBUF_; /// 使用 "ReuseAddr=Y" 設定: 請參閱 SO_REUSEADDR 的說明. int SO_REUSEADDR_; /// 使用 "ReusePort=Y" 設定: 請參閱 SO_REUSEPORT 的說明 (Windows沒有此選項). int SO_REUSEPORT_; /// 請參閱 SO_LINGER 的說明. /// 使用 "Linger=N" 設定(開啟linger,但等候0秒): Linger_.l_onoff=1; Linger_.l_linger=0; 避免 TIME_WAIT. /// |Linger_.l_onoff | Linger_.l_linger | /// |:--------------:|:--------------------------------------------------------| /// | 0 | 系統預設, close()立即返回, 但仍盡可能將剩餘資料送給對方.| /// | 非0 | 0: 放棄未送出的資料,並送RST給對方,可避免 TIME_WAIT 狀態 | /// | 非0 | 非0: close()等候秒數,或所有資料已送給對方,且正常結束連線| struct linger Linger_; /// 使用 "KeepAlive=n" 設定. /// - <=0: 不使用 KEEPALIVE 選項(預設). /// - ==1: 使用 SO_KEEPALIVE 設為 true, 其餘(間隔時間)為系統預設值. /// - >1: TCP_KEEPIDLE,TCP_KEEPINTVL 的間隔秒數, 此時 TCP_KEEPCNT 一律設為 3. int KeepAliveInterval_; void SetDefaults(); ConfigParser::Result OnTagValue(StrView tag, StrView& value); }; /// \ingroup io /// Socket 設定. struct fon9_API SocketConfig { /// 綁定的 local address. /// - Tcp Server: listen address & port. /// - Tcp Client: local address & port. SocketAddress AddrBind_; /// 目的地位置. /// - Tcp Server: 一般無此參數, 若有提供[專用Server]則可設定此參數, 收到連入連線後判斷是否是正確的來源. /// - Tcp Client: 遠端Server的 address & port. SocketAddress AddrRemote_; SocketOptions Options_; /// 取得 Address family: 透過 AddrBind_ 的 sa_family. AddressFamily GetAF() const { return static_cast<AddressFamily>(AddrBind_.Addr_.sa_family); } void SetDefaults(); /// - 如果沒有設定 AddrBind_ family 則使用 AddrRemote_ 的 sa_family; /// - 如果沒有設定 AddrRemote_ family 則使用 AddrBind_ 的 sa_family; void SetAddrFamily(); /// - "Bind=address:port" or "Bind=port" /// - "Remote=address:port" /// - 其餘轉給 this->Options_ 處理. ConfigParser::Result OnTagValue(StrView tag, StrView& value); struct fon9_API Parser : public ConfigParser { fon9_NON_COPY_NON_MOVE(Parser); SocketConfig& Owner_; SocketAddress* AddrDefault_; Parser(SocketConfig& owner, SocketAddress& addrDefault) : Owner_(owner) , AddrDefault_{&addrDefault} { } /// 解構時呼叫 this->Owner_.SetAddrFamily(); ~Parser(); /// - 第一個沒有「=」的欄位(value.IsNull()): 將該值填入 *this->AddrDefault_; /// 然後將 this->AddrDefault_ = nullptr; /// 也就是只有第一個沒有「=」的欄位會填入 *this->AddrDefault_, 其餘視為錯誤. /// - 其餘轉給 this->Owner_.OnTagValue() 處理. Result OnTagValue(StrView tag, StrView& value) override; }; }; fon9_WARN_POP; } } // namespaces #endif//__fon9_io_SocketConfig_hpp__
32.434343
93
0.628153
fonwin
666608b573eaf85c06b6e48c804cd76e24ba1785
1,543
cxx
C++
Code/Dashboard/bmScriptDashboardKeyAction.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
Code/Dashboard/bmScriptDashboardKeyAction.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
Code/Dashboard/bmScriptDashboardKeyAction.cxx
NIRALUser/BatchMake
1afeb15fa5bd18be6e4a56f4349eb6368a91441e
[ "Unlicense" ]
null
null
null
/*========================================================================= Program: BatchMake Module: bmScriptDashboardKeyAction.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2005 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "bmScriptDashboardKeyAction.h" #include "bmScriptError.h" #include "bmScriptActionManager.h" namespace bm { /** */ ScriptDashboardKeyAction::ScriptDashboardKeyAction() : ScriptAction() { } /** */ ScriptDashboardKeyAction::~ScriptDashboardKeyAction() { } /** */ bool ScriptDashboardKeyAction::TestParam(ScriptError* error,int linenumber) { if (m_Parameters.size() <1) { error->SetError(MString("No enough parameter for DashboardKey"),linenumber); return false; } m_Manager->SetTestVariable(m_Parameters[0]); for (unsigned int i=1;i<m_Parameters.size();i++) { m_Manager->TestConvert(m_Parameters[i],linenumber); } return true; } /** */ MString ScriptDashboardKeyAction::Help() { return "DashboardKey('Password')"; } /** */ void ScriptDashboardKeyAction::Execute() { m_Manager->SetDashboardKey(m_Parameters[0].toChar()); return; } } // end namespace bm
23.738462
80
0.646792
NIRALUser
6669dc244a2317eda8e4323d4e94150abb79e048
12,095
cpp
C++
Source/spells.cpp
nomdenom/devilution
98a0692d14f338dc8f509c8424cab1ee6067a950
[ "Unlicense" ]
4
2018-09-24T17:02:21.000Z
2021-05-27T08:42:50.000Z
Source/spells.cpp
nomdenom/devilution
98a0692d14f338dc8f509c8424cab1ee6067a950
[ "Unlicense" ]
null
null
null
Source/spells.cpp
nomdenom/devilution
98a0692d14f338dc8f509c8424cab1ee6067a950
[ "Unlicense" ]
null
null
null
//HEADER_GOES_HERE #include "../types.h" SpellData spelldata[MAX_SPELLS] = { { 0, 0, 0, NULL, NULL, 0, 0, FALSE, FALSE, 0, 0, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_FIREBOLT, 6, STYPE_FIRE, "Firebolt", "Firebolt", 1, 1, TRUE, FALSE, 15, IS_CAST2, { MIS_FIREBOLT, 0, 0 }, 1, 3, 40, 80, 1000, 50 }, { SPL_HEAL, 5, STYPE_MAGIC, "Healing", NULL, 1, 1, FALSE, TRUE, 17, IS_CAST8, { MIS_HEAL, 0, 0 }, 3, 1, 20, 40, 1000, 50 }, { SPL_LIGHTNING, 10, STYPE_LIGHTNING, "Lightning", NULL, 4, 3, TRUE, FALSE, 20, IS_CAST4, { MIS_LIGHTCTRL, 0, 0 }, 1, 6, 20, 60, 3000, 150 }, { SPL_FLASH, 30, STYPE_LIGHTNING, "Flash", NULL, 5, 4, FALSE, FALSE, 33, IS_CAST4, { MIS_FLASH, MIS_FLASH2, 0 }, 2, 16, 20, 40, 7500, 500 }, { SPL_IDENTIFY, 13, STYPE_MAGIC, "Identify", "Identify", -1, -1, FALSE, TRUE, 23, IS_CAST6, { MIS_IDENTIFY, 0, 0 }, 2, 1, 8, 12, 0, 100 }, { SPL_FIREWALL, 28, STYPE_FIRE, "Fire Wall", NULL, 3, 2, TRUE, FALSE, 27, IS_CAST2, { MIS_FIREWALLC, 0, 0 }, 2, 16, 8, 16, 6000, 400 }, { SPL_TOWN, 35, STYPE_MAGIC, "Town Portal", NULL, 3, 3, TRUE, FALSE, 20, IS_CAST6, { MIS_TOWN, 0, 0 }, 3, 18, 8, 12, 3000, 200 }, { SPL_STONE, 60, STYPE_MAGIC, "Stone Curse", NULL, 6, 5, TRUE, FALSE, 51, IS_CAST2, { MIS_STONE, 0, 0 }, 3, 40, 8, 16, 12000, 800 }, { SPL_INFRA, 40, STYPE_MAGIC, "Infravision", NULL, -1, -1, FALSE, FALSE, 36, IS_CAST8, { MIS_INFRA, 0, 0 }, 5, 20, 0, 0, 0, 600 }, { SPL_RNDTELEPORT, 12, STYPE_MAGIC, "Phasing", NULL, 7, 6, FALSE, FALSE, 39, IS_CAST2, { MIS_RNDTELEPORT, 0, 0 }, 2, 4, 40, 80, 3500, 200 }, { SPL_MANASHIELD, 33, STYPE_MAGIC, "Mana Shield", NULL, 6, 5, FALSE, FALSE, 25, IS_CAST2, { MIS_MANASHIELD, 0, 0 }, 0, 33, 4, 10, 16000, 1200 }, { SPL_FIREBALL, 16, STYPE_FIRE, "Fireball", NULL, 8, 7, TRUE, FALSE, 48, IS_CAST2, { MIS_FIREBALL, 0, 0 }, 1, 10, 40, 80, 8000, 300 }, { SPL_GUARDIAN, 50, STYPE_FIRE, "Guardian", NULL, 9, 8, TRUE, FALSE, 61, IS_CAST2, { MIS_GUARDIAN, 0, 0 }, 2, 30, 16, 32, 14000, 950 }, { SPL_CHAIN, 30, STYPE_LIGHTNING, "Chain Lightning", NULL, 8, 7, FALSE, FALSE, 54, IS_CAST2, { MIS_CHAIN, 0, 0 }, 1, 18, 20, 60, 11000, 750 }, { SPL_WAVE, 35, STYPE_FIRE, "Flame Wave", NULL, 9, 8, TRUE, FALSE, 54, IS_CAST2, { MIS_WAVE, 0, 0 }, 3, 20, 20, 40, 10000, 650 }, { SPL_DOOMSERP, 0, STYPE_LIGHTNING, "Doom Serpents", NULL, -1, -1, FALSE, FALSE, 0, IS_CAST2, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_BLODRIT, 0, STYPE_MAGIC, "Blood Ritual", NULL, -1, -1, FALSE, FALSE, 0, IS_CAST2, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_NOVA, 60, STYPE_MAGIC, "Nova", NULL, -1, 10, FALSE, FALSE, 87, IS_CAST4, { MIS_NOVA, 0, 0 }, 3, 35, 16, 32, 21000, 1300 }, { SPL_INVISIBIL, 0, STYPE_MAGIC, "Invisibility", NULL, -1, -1, FALSE, FALSE, 0, IS_CAST2, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_FLAME, 11, STYPE_FIRE, "Inferno", NULL, 3, 2, TRUE, FALSE, 20, IS_CAST2, { MIS_FLAMEC, 0, 0 }, 1, 6, 20, 40, 2000, 100 }, { SPL_GOLEM, 100, STYPE_FIRE, "Golem", NULL, 11, 9, FALSE, FALSE, 81, IS_CAST2, { MIS_GOLEM, 0, 0 }, 6, 60, 16, 32, 18000, 1100 }, { SPL_BLODBOIL, 0, STYPE_LIGHTNING, "Blood Boil", NULL, -1, -1, TRUE, FALSE, 0, IS_CAST8, { 0, 0, 0 }, 0, 0, 0, 0, 0, 0 }, { SPL_TELEPORT, 35, STYPE_MAGIC, "Teleport", NULL, 14, 12, TRUE, FALSE, 105, IS_CAST6, { MIS_TELEPORT, 0, 0 }, 3, 15, 16, 32, 20000, 1250 }, { SPL_APOCA, 150, STYPE_FIRE, "Apocalypse", NULL, -1, 15, FALSE, FALSE, 149, IS_CAST2, { MIS_APOCA, 0, 0 }, 6, 90, 8, 12, 30000, 2000 }, { SPL_ETHEREALIZE, 100, STYPE_MAGIC, "Etherealize", NULL, -1, -1, FALSE, FALSE, 93, IS_CAST2, { MIS_ETHEREALIZE, 0, 0 }, 0, 100, 2, 6, 26000, 1600 }, { SPL_REPAIR, 0, STYPE_MAGIC, "Item Repair", "Item Repair", -1, -1, FALSE, TRUE, -1, IS_CAST6, { MIS_REPAIR, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_RECHARGE, 0, STYPE_MAGIC, "Staff Recharge", "Staff Recharge", -1, -1, FALSE, TRUE, -1, IS_CAST6, { MIS_RECHARGE, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_DISARM, 0, STYPE_MAGIC, "Trap Disarm", "Trap Disarm", -1, -1, FALSE, FALSE, -1, IS_CAST6, { MIS_DISARM, 0, 0 }, 0, 0, 40, 80, 0, 0 }, { SPL_ELEMENT, 35, STYPE_FIRE, "Elemental", NULL, 8, 6, FALSE, FALSE, 68, IS_CAST2, { MIS_ELEMENT, 0, 0 }, 2, 20, 20, 60, 10500, 700 }, { SPL_CBOLT, 6, STYPE_LIGHTNING, "Charged Bolt", NULL, 1, 1, TRUE, FALSE, 25, IS_CAST2, { MIS_CBOLT, 0, 0 }, 1, 6, 40, 80, 1000, 50 }, { SPL_HBOLT, 7, STYPE_MAGIC, "Holy Bolt", NULL, 1, 1, TRUE, FALSE, 20, IS_CAST2, { MIS_HBOLT, 0, 0 }, 1, 3, 40, 80, 1000, 50 }, { SPL_RESURRECT, 20, STYPE_MAGIC, "Resurrect", NULL, -1, 5, FALSE, TRUE, 30, IS_CAST8, { MIS_RESURRECT, 0, 0 }, 0, 20, 4, 10, 4000, 250 }, { SPL_TELEKINESIS, 15, STYPE_MAGIC, "Telekinesis", NULL, 2, 2, FALSE, FALSE, 33, IS_CAST2, { MIS_TELEKINESIS, 0, 0 }, 2, 8, 20, 40, 2500, 200 }, { SPL_HEALOTHER, 5, STYPE_MAGIC, "Heal Other", NULL, 1, 1, FALSE, TRUE, 17, IS_CAST8, { MIS_HEALOTHER, 0, 0 }, 3, 1, 20, 40, 1000, 50 }, { SPL_FLARE, 25, STYPE_MAGIC, "Blood Star", NULL, 14, 13, FALSE, FALSE, 70, IS_CAST2, { MIS_FLARE, 0, 0 }, 2, 14, 20, 60, 27500, 1800 }, { SPL_BONESPIRIT, 24, STYPE_MAGIC, "Bone Spirit", NULL, 9, 7, FALSE, FALSE, 34, IS_CAST2, { MIS_BONESPIRIT, 0, 0 }, 1, 12, 20, 60, 11500, 800 } }; int __fastcall GetManaAmount(int id, int sn) { int i; // "raw" mana cost int ma; // mana amount // mana adjust int adj = 0; // spell level int sl = plr[id]._pSplLvl[sn] + plr[id]._pISplLvlAdd - 1; if (sl < 0) { sl = 0; } if (sl > 0) { adj = sl * spelldata[sn].sManaAdj; } if (sn == SPL_FIREBOLT) { adj >>= 1; } if (sn == SPL_RESURRECT && sl > 0) { adj = sl * (spelldata[SPL_RESURRECT].sManaCost / 8); } if (spelldata[sn].sManaCost == 255) // TODO: check sign { i = (BYTE)plr[id]._pMaxManaBase; } else { i = spelldata[sn].sManaCost; } ma = (i - adj) << 6; if (sn == SPL_HEAL) { ma = (spelldata[SPL_HEAL].sManaCost + 2 * plr[id]._pLevel - adj) << 6; } if (sn == SPL_HEALOTHER) { ma = (spelldata[SPL_HEAL].sManaCost + 2 * plr[id]._pLevel - adj) << 6; } if (plr[id]._pClass == PC_ROGUE) { ma -= ma >> 2; } if (spelldata[sn].sMinMana > ma >> 6) { ma = spelldata[sn].sMinMana << 6; } return ma * (100 - plr[id]._pISplCost) / 100; } void __fastcall UseMana(int id, int sn) { int ma; // mana cost if (id == myplr) { switch (plr[id]._pSplType) { case RSPLTYPE_SPELL: #ifdef _DEBUG if (!debug_mode_key_inverted_v) { #endif ma = GetManaAmount(id, sn); plr[id]._pMana -= ma; plr[id]._pManaBase -= ma; drawmanaflag = TRUE; #ifdef _DEBUG } #endif break; case RSPLTYPE_SCROLL: RemoveScroll(id); break; case RSPLTYPE_CHARGES: UseStaffCharge(id); break; } } } BOOL __fastcall CheckSpell(int id, int sn, BYTE st, BOOL manaonly) { #ifdef _DEBUG if (debug_mode_key_inverted_v) return TRUE; #endif BOOL result = TRUE; if (!manaonly && pcurs != 1) { result = FALSE; } else { if (st != RSPLTYPE_SKILL) { if (GetSpellLevel(id, sn) <= 0) { result = FALSE; } else { result = plr[id]._pMana >= GetManaAmount(id, sn); } } } return result; } void __fastcall CastSpell(int id, int spl, int sx, int sy, int dx, int dy, BOOL caster, int spllvl) { int dir; // missile direction // ugly switch, but generates the right code switch (caster) { case TRUE: dir = monster[id]._mdir; break; case FALSE: // caster must be 0 already in this case, but oh well, // it's needed to generate the right code caster = 0; dir = plr[id]._pdir; if (spl == SPL_FIREWALL) { dir = plr[id]._pVar3; } break; } for (int i = 0; spelldata[spl].sMissiles[i] != MIS_ARROW && i < 3; i++) { AddMissile(sx, sy, dx, dy, dir, spelldata[spl].sMissiles[i], caster, id, 0, spllvl); } if (spelldata[spl].sMissiles[0] == MIS_TOWN) { UseMana(id, SPL_TOWN); } if (spelldata[spl].sMissiles[0] == MIS_CBOLT) { UseMana(id, SPL_CBOLT); for (int i = 0; i < (spllvl >> 1) + 3; i++) { AddMissile(sx, sy, dx, dy, dir, MIS_CBOLT, caster, id, 0, spllvl); } } } // pnum: player index // rid: target player index void __fastcall DoResurrect(int pnum, int rid) { if ((char)rid != -1) { AddMissile(plr[rid].WorldX, plr[rid].WorldY, plr[rid].WorldX, plr[rid].WorldY, 0, MIS_RESURRECTBEAM, 0, pnum, 0, 0); } if (pnum == myplr) { NewCursor(CURSOR_HAND); } if ((char)rid != -1 && plr[rid]._pHitPoints == 0) { if (rid == myplr) { deathflag = FALSE; gamemenu_off(); drawhpflag = TRUE; drawmanaflag = TRUE; } ClrPlrPath(rid); plr[rid].destAction = ACTION_NONE; plr[rid]._pInvincible = 0; PlacePlayer(rid); int hp = 640; if (plr[rid]._pMaxHPBase < 640) { hp = plr[rid]._pMaxHPBase; } SetPlayerHitPoints(rid, hp); plr[rid]._pMana = 0; plr[rid]._pHPBase = plr[rid]._pHitPoints + (plr[rid]._pMaxHPBase - plr[rid]._pMaxHP); plr[rid]._pManaBase = plr[rid]._pMaxManaBase - plr[rid]._pMaxMana; CalcPlrInv(rid, TRUE); if (plr[rid].plrlevel == currlevel) { StartStand(rid, plr[rid]._pdir); } else { plr[rid]._pmode = 0; } } } void __fastcall PlacePlayer(int pnum) { int nx; int ny; if (plr[pnum].plrlevel == currlevel) { for (DWORD i = 0; i < 8; i++) { nx = plr[pnum].WorldX + plrxoff2[i]; ny = plr[pnum].WorldY + plryoff2[i]; if (PosOkPlayer(pnum, nx, ny)) { break; } } if (!PosOkPlayer(pnum, nx, ny)) { BOOL done = FALSE; for (int max = 1, min = -1; min > -50 && !done; max++, min--) { for (int y = min; y <= max && !done; y++) { ny = plr[pnum].WorldY + y; for (int x = min; x <= max && !done; x++) { nx = plr[pnum].WorldX + x; if (PosOkPlayer(pnum, nx, ny)) { done = TRUE; } } } } } plr[pnum].WorldX = nx; plr[pnum].WorldY = ny; dPlayer[nx][ny] = pnum + 1; if (pnum == myplr) { ViewX = nx; ViewY = ny; } } } void __fastcall DoHealOther(int pnum, int rid) { if (pnum == myplr) { NewCursor(CURSOR_HAND); } if ((char)rid != -1 && (plr[rid]._pHitPoints >> 6) > 0) { int hp = (random(57, 10) + 1) << 6; for (int i = 0; i < plr[pnum]._pLevel; i++) { hp += (random(57, 4) + 1) << 6; } for (int j = 0; j < GetSpellLevel(pnum, SPL_HEALOTHER); ++j) { hp += (random(57, 6) + 1) << 6; } if (plr[pnum]._pClass == PC_WARRIOR) { hp <<= 1; } if (plr[pnum]._pClass == PC_ROGUE) { hp += hp >> 1; } plr[rid]._pHitPoints += hp; if (plr[rid]._pHitPoints > plr[rid]._pMaxHP) { plr[rid]._pHitPoints = plr[rid]._pMaxHP; } plr[rid]._pHPBase += hp; if (plr[rid]._pHPBase > plr[rid]._pMaxHPBase) { plr[rid]._pHPBase = plr[rid]._pMaxHPBase; } drawhpflag = TRUE; } }
38.275316
154
0.518561
nomdenom
666b7b7e6178d193ed53e9af879004db7faf907d
3,228
hpp
C++
engine/src/utility/command.hpp
Sidharth-S-S/cloe
974ef649e7dc6ec4e6869e4cf690c5b021e5091e
[ "Apache-2.0" ]
20
2020-07-07T18:28:35.000Z
2022-03-21T04:35:28.000Z
engine/src/utility/command.hpp
Sidharth-S-S/cloe
974ef649e7dc6ec4e6869e4cf690c5b021e5091e
[ "Apache-2.0" ]
46
2021-01-20T10:13:09.000Z
2022-03-29T12:27:19.000Z
engine/src/utility/command.hpp
Sidharth-S-S/cloe
974ef649e7dc6ec4e6869e4cf690c5b021e5091e
[ "Apache-2.0" ]
12
2021-01-25T08:01:24.000Z
2021-07-27T10:09:53.000Z
/* * Copyright 2020 Robert Bosch GmbH * * 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. * * SPDX-License-Identifier: Apache-2.0 */ /** * \file utility/command.hpp * \see utility/command.cpp * * This file contains several types that make use of cloe::Command. */ #pragma once #include <string> // for string #include <system_error> // for system_error #include <vector> // for vector<> #include <boost/optional.hpp> // for optional<> #include <boost/process/child.hpp> // for child #include <cloe/core.hpp> // for Logger, Json, Conf, ... #include <cloe/trigger.hpp> // for Action, ActionFactory, ... #include <cloe/utility/command.hpp> // for Command namespace engine { struct CommandResult { std::string name; std::string command; boost::optional<boost::process::child> child; boost::optional<int> exit_code; boost::optional<std::system_error> error; std::vector<std::string> output; }; class CommandExecuter { public: explicit CommandExecuter(cloe::Logger logger, bool enabled = true) : logger_(logger), enabled_(enabled) {} bool is_enabled() const { return enabled_; } void set_enabled(bool v) { enabled_ = v; } CommandResult run_and_release(const cloe::Command&) const; void run(const cloe::Command&); void run_all(const std::vector<cloe::Command>& cmds); void wait(CommandResult&) const; void wait_all(); std::vector<CommandResult> release_all(); cloe::Logger logger() const { return logger_; } private: std::vector<CommandResult> handles_; cloe::Logger logger_{nullptr}; bool enabled_{false}; }; namespace actions { class Command : public cloe::Action { public: Command(const std::string& name, const cloe::Command& cmd, CommandExecuter* exec) : Action(name), command_(cmd), executer_(exec) { assert(executer_ != nullptr); } cloe::ActionPtr clone() const override { return std::make_unique<Command>(name(), command_, executer_); } void operator()(const cloe::Sync&, cloe::TriggerRegistrar&) override; protected: void to_json(cloe::Json& j) const override; private: cloe::Command command_; CommandExecuter* executer_{nullptr}; }; class CommandFactory : public cloe::ActionFactory { public: using ActionType = Command; explicit CommandFactory(CommandExecuter* exec) : cloe::ActionFactory("command", "run a system command"), executer_(exec) { assert(executer_ != nullptr); } cloe::TriggerSchema schema() const override; cloe::ActionPtr make(const cloe::Conf& c) const override; cloe::ActionPtr make(const std::string& s) const override; private: CommandExecuter* executer_{nullptr}; }; } // namespace actions } // namespace engine
27.827586
83
0.701673
Sidharth-S-S
6672b3d702a814770de7ce50c8eab0494da22fe4
575
cpp
C++
C Programming/Insertion Sort/main.cpp
NanoCode012/ITStep
21807b6bcd564c9ed490e4af70954bff9a5d698d
[ "MIT" ]
5
2019-10-23T13:22:18.000Z
2022-02-04T18:36:00.000Z
C Programming/Insertion Sort/main.cpp
NanoCode012/ITStep
21807b6bcd564c9ed490e4af70954bff9a5d698d
[ "MIT" ]
null
null
null
C Programming/Insertion Sort/main.cpp
NanoCode012/ITStep
21807b6bcd564c9ed490e4af70954bff9a5d698d
[ "MIT" ]
3
2018-05-23T04:16:52.000Z
2021-12-19T14:56:00.000Z
#include <iostream> using namespace std; int main(){ const int length = 6; int nums[length] = { 6, 0, 10, 33, 7, 2}; /* 6, 0, 10 */ int x, j; for (int i = 0; i < length; i++) { x = nums[i]; j = i - 1;//0 while(j >= 0) { if (nums[j] > x) { nums[j + 1] = nums[j]; nums[j] = x; j--; }else break; } } for (int k = 0; k < length; k++) { cout << nums[k] << " "; } cout << endl; return 0; }
16.911765
45
0.333913
NanoCode012
6677b144cba7b00227dccdf458f7ea20eb83da56
2,245
cpp
C++
LayerManagerBase/tests/ShaderProgramTest.cpp
SanctuaryComponents/layer_management
d3927a6ae5e6c9230d55b6ba4195d434586521c1
[ "Apache-2.0" ]
1
2020-10-21T05:24:10.000Z
2020-10-21T05:24:10.000Z
LayerManagerBase/tests/ShaderProgramTest.cpp
SanctuaryComponents/layer_management
d3927a6ae5e6c9230d55b6ba4195d434586521c1
[ "Apache-2.0" ]
null
null
null
LayerManagerBase/tests/ShaderProgramTest.cpp
SanctuaryComponents/layer_management
d3927a6ae5e6c9230d55b6ba4195d434586521c1
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * * Copyright 2010,2011 BMW Car IT GmbH * * * 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 "ShaderProgram.h" #include "ShaderProgramFactory.h" #include <string> using std::string; class ShaderProgramTest : public ::testing::Test { public: void SetUp() { string vertShaderPath(""); string fragShaderPath(""); m_pShaderProgram = ShaderProgramFactory::createProgram(vertShaderPath, fragShaderPath); ASSERT_TRUE(m_pShaderProgram); } void TearDown() { if (m_pShaderProgram) { delete m_pShaderProgram; m_pShaderProgram = 0; } } ShaderProgram* m_pShaderProgram; }; TEST_F(ShaderProgramTest, DISABLED_obtain) { } TEST_F(ShaderProgramTest, DISABLED_use) { } TEST_F(ShaderProgramTest, DISABLED_loadCommonUniforms) { } TEST_F(ShaderProgramTest, DISABLED_getVertexName) { } TEST_F(ShaderProgramTest, DISABLED_getFragmentName) { } TEST_F(ShaderProgramTest, DISABLED_ref) { } TEST_F(ShaderProgramTest, DISABLED_unref) { } TEST_F(ShaderProgramTest, DISABLED_getUniformLocation) { } TEST_F(ShaderProgramTest, DISABLED_uniform1iv) { } TEST_F(ShaderProgramTest, DISABLED_uniform1fv) { } TEST_F(ShaderProgramTest, DISABLED_uniform2fv) { } TEST_F(ShaderProgramTest, DISABLED_uniform3fv) { } TEST_F(ShaderProgramTest, DISABLED_uniform4fv) { } TEST_F(ShaderProgramTest, DISABLED_uniformMatrix2fv) { } TEST_F(ShaderProgramTest, DISABLED_uniformMatrix3fv) { } TEST_F(ShaderProgramTest, DISABLED_uniformMatrix4fv) { }
17.539063
95
0.679733
SanctuaryComponents
6678da66a2f24c7fc81b1bfb93c40b0ad6139e3f
1,742
cpp
C++
Dialogs/blurdialog.cpp
kalpanki/ocvGUI
9fc1f2278b414c316f091e1de5a4b1c4e3695ee9
[ "BSD-2-Clause" ]
2
2019-08-21T13:37:51.000Z
2019-10-18T01:39:53.000Z
Dialogs/blurdialog.cpp
kalpanki/ocvGUI
9fc1f2278b414c316f091e1de5a4b1c4e3695ee9
[ "BSD-2-Clause" ]
null
null
null
Dialogs/blurdialog.cpp
kalpanki/ocvGUI
9fc1f2278b414c316f091e1de5a4b1c4e3695ee9
[ "BSD-2-Clause" ]
null
null
null
#include "blurdialog.h" #include "ui_blurdialog.h" #include <iostream> using namespace std; BlurDialog::BlurDialog(QWidget *parent) : QDialog(parent), ui(new Ui::BlurDialog) { ui->setupUi(this); this->currentIndex = ui->BlurComboBox->currentIndex(); this->kernelH = ui->kernelHeightSpinBox->value(); this->kernelL = ui->KernelLenspinBox->value(); this->sigmaX = ui->sigmaXSpinBox->value(); this->sigmaY = ui->sigmaYSpinBox->value(); this->medianKernel = ui->medianKernelSpinBox->value(); } BlurDialog::~BlurDialog() { delete ui; } void BlurDialog::on_BlurComboBox_currentIndexChanged(int index) { this->currentIndex = index; emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel); } void BlurDialog::on_KernelLenspinBox_valueChanged(int val) { this->kernelL = val; cout << "going to emit L" << endl; emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel); } void BlurDialog::on_kernelHeightSpinBox_valueChanged(int val) { this->kernelH = val; emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel); } void BlurDialog::on_sigmaXSpinBox_valueChanged(double val) { this->sigmaX = val; emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel); } void BlurDialog::on_sigmaYSpinBox_valueChanged(double val) { this->sigmaY = val; emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel); } void BlurDialog::on_medianKernelSpinBox_valueChanged(int val) { this->medianKernel = val; emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel); } void BlurDialog::on_BlurCloseButton_clicked() { this->close(); }
26.393939
83
0.730195
kalpanki
667976e24f139ddb0d10d6c3f056d5374a2ccee1
5,484
hpp
C++
test/test-200-types/include/test-develop.hpp
Kartonagnick/tools-types
4b3a697e579050eade081b82f9b96309fea8f5e7
[ "MIT" ]
null
null
null
test/test-200-types/include/test-develop.hpp
Kartonagnick/tools-types
4b3a697e579050eade081b82f9b96309fea8f5e7
[ "MIT" ]
49
2021-02-20T12:08:15.000Z
2021-05-07T19:59:08.000Z
test/test-200-types/include/test-develop.hpp
Kartonagnick/tools-types
4b3a697e579050eade081b82f9b96309fea8f5e7
[ "MIT" ]
null
null
null
// [2021y-03m-10d][12:46:41] Idrisov Denis R. #pragma once #ifndef dTEST_DEVELOP_USED_ #define dTEST_DEVELOP_USED_ 1 #define CODE_GENERATION_ON #define INCLUDE_AUTO_GENERATED // #define INCLUDE_STRESS_TESTS #define INCLUDE_LONG_LONG_TESTS #define INCLUDE_LONG_TESTS //============================================================================== //===== tools/types/traits =================================||================== #define TEST_IS_FLOATING // ready! #define TEST_IS_SIGNED // ready! #define TEST_IS_INTEGRAL // ready! #define TEST_REMOVE_CV // ready! #define TEST_CONDITIONAL // ready! #define TEST_IS_SAME // ready! #define TEST_ENABLE_IF // ready! #define TEST_REMOVE_REFERENCE // ready! #define TEST_DECAY // ready! #define TEST_IS_CLASS // ready! #define TEST_IS_CONST // ready! #define TEST_IS_VOLATILE // ready! #define TEST_IS_POINTER // ready! #define TEST_IS_REFERENCE // ready! #define TEST_REMOVE_POINTER // ready! #define TEST_IS_FUNCTION // ready! #define TEST_IS_ARRAY // ready! #define TEST_IS_BASE_OF // ready! #define TEST_IS_CONVERTIBLE // ready! #define TEST_REMOVE_EXTENSION // ready! #define TEST_REMOVE_ALL_EXTENSION // ready! #define TEST_ADD_POINTER // ready! #define TEST_IS_UNSIGNED // ready! //============================================================================== //===== tools/types/common =================================||================== #define TEST_TOOLS_DEGRADATE // ready! #define TEST_TOOLS_FOR_LVALUE // ready! #define TEST_TOOLS_FOR_RVALUE // ready! #define TEST_TOOLS_FIND_TYPE // ready! #define TEST_TOOLS_IS_ZERO_ARRAY // ready! #define TEST_TOOLS_SIZE_ARRAY // ready! #define TEST_TOOLS_SMALL_ARRAY // ready! #define TEST_TYPE_OF_ENUM // ready! #define TEST_TOOLS_VARIADIC // ready! #define TEST_TOOLS_IS_VOLATILE_DATA // ready! #define TEST_TOOLS_IS_CONST_DATA // ready! #define TEST_TOOLS_ADD_CONST_DATA // ready! #define TEST_TOOLS_ENABLE_FOR // ready! //============================================================================== //===== tools/types/sfinae =================================||================== #define TEST_TOOLS_SFINAE_DEREFERENCE // ready! #define TEST_TOOLS_SFINAE_ACCESS // ready! #define TEST_TOOLS_SFINAE_CALL // in progress... #define TEST_TOOLS_SFINAE_BEGIN // ready! #define TEST_TOOLS_SFINAE_END // ready! //============================================================================== //===== tools/types/sfinae =================================||================== // #define TEST_TOOLS_DEREF_AVAILABLE // in progress... #define TEST_TOOLS_SFINAE_CONCEPT // ready! // #define TEST_TOOLS_IS_LAMBDA // in progress... // #define TEST_TOOLS_IS_DEREFERENCABLE // in progress... // #define TEST_TOOLS_HAS_OPERATOR_ACCESS // in progress... // #define TEST_TOOLS_IS_INCREMENTABLE // in progress... // #define TEST_TOOLS_IS_DECREMENTABLE // in progress... // #define TEST_TOOLS_IS_ITERABLE // in progress... // #define TEST_TOOLS_IS_ITERATOR // in progress... // #define TEST_TOOLS_HAS_VALUE_TYPE // in progress... // #define TEST_TOOLS_HAS_MAPPED_TYPE // in progress... // #define TEST_TOOLS_HAS_BEGIN // in progress... // #define TEST_TOOLS_HAS_END // in progress... //============================================================================== //===== tools/types ========================================||================== #define TEST_TOOLS_FIXED // ready! #define TEST_TOOLS_LIMIT // ready! #define TEST_TOOLS_DEMANGLE // ready! #define TEST_TOOLS_VOID_T // ready! //============================================================================== //============================================================================== // in progress... #endif // !dTEST_DEVELOP_USED_
58.340426
80
0.398432
Kartonagnick
6679f862eee8a9781371e0560ee2865749dd8c06
5,707
cpp
C++
Program Launcher/CCategory.cpp
barty32/program-launcher
f29277dda09f753e39258ff17af3b8c15d2504dc
[ "MIT" ]
null
null
null
Program Launcher/CCategory.cpp
barty32/program-launcher
f29277dda09f753e39258ff17af3b8c15d2504dc
[ "MIT" ]
null
null
null
Program Launcher/CCategory.cpp
barty32/program-launcher
f29277dda09f753e39258ff17af3b8c15d2504dc
[ "MIT" ]
null
null
null
// // _ // ___ __ _| |_ ___ __ _ ___ _ __ _ _ ___ _ __ _ __ // / __/ _` | __/ _ \/ _` |/ _ \| '__| | | | / __| '_ \| '_ \ // | (_| (_| | || __/ (_| | (_) | | | |_| || (__| |_) | |_) | // \___\__,_|\__\___|\__, |\___/|_| \__, (_)___| .__/| .__/ // |___/ |___/ |_| |_| // // This file contains functions related to Program Launcher's categories (in tab control) // // Functions included in this file: // // Copyright ©2021, barty12 // #include "LICENSE" // #include "pch.h" #include "Program Launcher.h" CCategory::CCategory(CProgramLauncher* ptrParent, const UINT parentIndex, const wstring& wsName) : ptrParent(ptrParent), parentIndex(parentIndex), wsCategoryName(wsName) { imSmall.Create(SMALL_ICON_SIZE, SMALL_ICON_SIZE, ILC_COLOR32, 0, 0); imLarge.Create(Launcher->options.IconSize, Launcher->options.IconSize, ILC_COLOR32, 0, 0); //CFile file(L"iconcache.db", CFile::modeRead); //CArchive ar(&file, CArchive::load); //imLarge.Read(&ar); } int CCategory::LoadElements(){ vItems.clear(); ElementProps props; UINT j = 0; for(; GetElementProperties(wsCategoryName, j, props); ++j){ vItems.push_back(make_shared<CLauncherItem>(this, j, props)); imLarge.Add(vItems[j]->LoadIcon(Launcher->options.IconSize)); imSmall.Add(vItems[j]->LoadIcon(SMALL_ICON_SIZE)); if(parentIndex == Launcher->GetCurrentCategoryIndex()){ vItems[j]->InsertIntoListView(); CMainWnd->m_statusBar.GetStatusBarCtrl().SetText(wstring(to_wstring(j) + L" items, loading...").c_str(), 255, 0); //CMainWnd->m_statusBar.Invalidate(); } } CMainWnd->m_statusBar.GetStatusBarCtrl().SetText(wstring(to_wstring(j) + L" items").c_str(), 255, 0); return j; } bool CCategory::Rename(){ CUserInputDlg dlg(wsCategoryName); if(dlg.DoModal() == 1){ TCITEMW tie = {0}; tie.mask = TCIF_TEXT; tie.pszText = wsCategoryName.data(); tie.cchTextMax = wsCategoryName.size(); CMainWnd->CTab.SetItem(parentIndex, &tie); CMainWnd->Invalidate(false); return true; } return false; } bool CCategory::Remove(bool bAsk, bool bKeepItems){ if(!bAsk || CMainWnd->MessageBoxW(std::format(GetString(IDS_REMOVE_CATEGORY_PROMPT), wsCategoryName).c_str(), GetString(IDS_REMOVE_CATEGORY).c_str(), MB_YESNO | MB_ICONEXCLAMATION) == IDYES){ UINT index = parentIndex; Launcher->vCategories.erase(Launcher->vCategories.begin() + index); Launcher->ReindexCategories(index); CMainWnd->CTab.DeleteItem(index); if(Launcher->vCategories.size() == 0){ CMainWnd->UpdateListView(); return true; } CMainWnd->CTab.SetCurSel(CMainWnd->CTab.GetItemCount() - 1); CMainWnd->UpdateListView(); Launcher->bRebuildIconCache = true; return true; } return false; } bool CCategory::Move(UINT newPos, bool bRelative){ if(bRelative){ newPos += parentIndex; } shared_ptr<CCategory> temp = ptrParent->vCategories[parentIndex]; if(parentIndex == newPos){ return true; } else if(newPos >= ptrParent->vCategories.size()){ return false; } else if(parentIndex < newPos){ for(UINT i = parentIndex; i < newPos; ++i){ ptrParent->vCategories[i] = ptrParent->vCategories[i + 1]; } } else{ for(UINT i = parentIndex; i > newPos; --i){ ptrParent->vCategories[i] = ptrParent->vCategories[i - 1]; } } ptrParent->vCategories[newPos] = temp; ptrParent->ReindexCategories(); CMainWnd->UpdateListView(true); Launcher->bRebuildIconCache = true; return true; } bool CCategory::MoveTab(UINT newPos, bool bRelative){ if(bRelative){ newPos += parentIndex; } CMainWnd->CTab.ReorderTab(parentIndex, newPos); return true; } void CCategory::ReindexItems(UINT iStart){ for(size_t i = iStart; i < vItems.size(); ++i){ vItems[i]->parentIndex = i; } } CLauncherItem* CCategory::GetItem(UINT index){ return vItems.at(index).get(); } CLauncherItem* CCategory::GetSelectedItem(){ return vItems.at(Launcher->GetSelectedItemIndex()).get(); } // CUserInputDlg dialog IMPLEMENT_DYNAMIC(CUserInputDlg, CDialog) CUserInputDlg::CUserInputDlg(wstring& pName, CWnd* pParent /*=nullptr*/) : CDialog(IDD_USERINPUTDLG, pParent), m_wsName(pName){ } CUserInputDlg::~CUserInputDlg(){} void CUserInputDlg::DoDataExchange(CDataExchange* pDX){ CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CUserInputDlg, CDialog) ON_COMMAND(IDC_USERINPUTDLGEDIT, &CUserInputDlg::OnUserInput) END_MESSAGE_MAP() // CUserInputDlg message handlers BOOL CUserInputDlg::OnInitDialog(){ CDialog::OnInitDialog(); //center the dialog this->CenterWindow(); //set maximum number of characters to CATEGORY_NAME_LEN this->SendDlgItemMessageW(IDC_USERINPUTDLGEDIT, EM_SETLIMITTEXT, CATEGORY_NAME_LEN); if(!m_wsName.empty()){ this->SetWindowTextW(GetString(IDS_RENAME_CATEGORY).c_str()); this->GetDlgItem(IDC_USERINPUTDLGEDIT)->SetWindowTextW(m_wsName.c_str()); } return true; } void CUserInputDlg::OnUserInput(){ // Set the default push button to "OK" when the user enters text. //if(HIWORD(wParam) == EN_CHANGE){ this->SendMessageW(DM_SETDEFID, IDOK); //} } void CUserInputDlg::OnOK(){ //CDialog::OnOK(); try{ CString name; this->GetDlgItem(IDC_USERINPUTDLGEDIT)->GetWindowTextW(name); if(name.GetLength() >= CATEGORY_NAME_LEN){ throw IDS_NAME_TOO_LONG; } if(name.GetLength() <= 0){ throw IDS_ENTER_VALID_NAME; } if(name.Find(CATEGORY_NAME_DELIM) != -1 || name == L"general" || name == L"appereance" || name == L"categories"){ throw IDS_NAME_INVALID_CHARACTERS; } m_wsName = name; this->EndDialog(true); return; } catch(int code){ ErrorMsg(code); return; } catch(...){ ErrorMsg(IDS_ERROR); ErrorHandlerDebug(); return; } }
25.823529
192
0.686175
barty32
6681d9c5ac2bcd7d2b0e12df0c49bf20e41d3d09
8,724
cpp
C++
Jx3Full/Source/Source/Tools/SceneEditor/KSceneDataFlowEditorDefineDialog.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
2
2021-07-31T15:35:01.000Z
2022-02-28T05:54:54.000Z
Jx3Full/Source/Source/Tools/SceneEditor/KSceneDataFlowEditorDefineDialog.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
null
null
null
Jx3Full/Source/Source/Tools/SceneEditor/KSceneDataFlowEditorDefineDialog.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
// KSceneDataFlowEditorDefineDialog.cpp : implementation file // #include "stdafx.h" #include "SceneEditor.h" #include "KSceneDataFlowEditorDefineDialog.h" #include "IEEditor.h" // KSceneDataFlowEditorDefineDialog dialog IMPLEMENT_DYNAMIC(KSceneDataFlowEditorDefineDialog, CDialog) KSceneDataFlowEditorDefineDialog::KSceneDataFlowEditorDefineDialog(CWnd* pParent /*=NULL*/) : CDialog(KSceneDataFlowEditorDefineDialog::IDD, pParent) , m_szDefineName(_T("")) , m_dwNumVariable(0) , m_szVariableName(_T("")) { m_lpEditor = NULL; m_uCurrentSelectedDefine = 0; m_nCurrentSelectedVariable = 0; } KSceneDataFlowEditorDefineDialog::~KSceneDataFlowEditorDefineDialog() { m_uCurrentSelectedDefine = 0; m_nCurrentSelectedVariable = 0; } void KSceneDataFlowEditorDefineDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_DEFINE, m_ListDefine); DDX_Text(pDX, IDC_EDIT_DEFINENAME, m_szDefineName); DDX_Text(pDX, IDC_EDIT_NUMVARIABLE, m_dwNumVariable); DDX_Control(pDX, IDC_LIST_VARIABLE, m_ListVariable); DDX_Text(pDX, IDC_EDIT_VARIABLENAME, m_szVariableName); DDX_Control(pDX, IDC_COMBO_VARIABLETYPE, m_ComboVariableType); } BEGIN_MESSAGE_MAP(KSceneDataFlowEditorDefineDialog, CDialog) ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST_DEFINE, &KSceneDataFlowEditorDefineDialog::OnLvnItemchangedListDefine) ON_BN_CLICKED(IDC_BUTTON_ADDDEFINE, &KSceneDataFlowEditorDefineDialog::OnBnClickedButtonAdddefine) ON_BN_CLICKED(IDC_BUTTON_DELETEDEFINE, &KSceneDataFlowEditorDefineDialog::OnBnClickedButtonDeletedefine) ON_EN_CHANGE(IDC_EDIT_DEFINENAME, &KSceneDataFlowEditorDefineDialog::OnEnChangeEditDefinename) ON_EN_CHANGE(IDC_EDIT_NUMVARIABLE, &KSceneDataFlowEditorDefineDialog::OnEnChangeEditNumvariable) ON_LBN_SELCHANGE(IDC_LIST_VARIABLE, &KSceneDataFlowEditorDefineDialog::OnLbnSelchangeListVariable) ON_EN_CHANGE(IDC_EDIT_VARIABLENAME, &KSceneDataFlowEditorDefineDialog::OnEnChangeEditVariablename) ON_CBN_SELCHANGE(IDC_COMBO_VARIABLETYPE, &KSceneDataFlowEditorDefineDialog::OnCbnSelchangeComboVariabletype) ON_BN_CLICKED(IDC_BUTTON_SETNUMVARIABLE, &KSceneDataFlowEditorDefineDialog::OnBnClickedButtonSetnumvariable) END_MESSAGE_MAP() // KSceneDataFlowEditorDefineDialog message handlers void KSceneDataFlowEditorDefineDialog::OnLvnItemchangedListDefine(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: Add your control notification handler code here //m_uCurrentSelectedDefine = 0; if(!m_lpEditor) return; POSITION ps = m_ListDefine.GetFirstSelectedItemPosition(); while (ps) { int nIndex = m_ListDefine.GetNextSelectedItem(ps); if(nIndex>=0) { m_uCurrentSelectedDefine = (UINT)m_ListDefine.GetItemData(nIndex); } } if(m_uCurrentSelectedDefine) { TCHAR Name[MAX_PATH]; if(SUCCEEDED(m_lpEditor->GetDataDefineName(Name,m_uCurrentSelectedDefine))) { DWORD dwNum = 0; m_lpEditor->GetNumVariableofDataDefine(&dwNum,m_uCurrentSelectedDefine); m_szDefineName.Format("%s",Name); m_dwNumVariable = dwNum; UpdateData(FALSE); } FillListVariable(); } *pResult = 0; } void KSceneDataFlowEditorDefineDialog::OnBnClickedButtonAdddefine() { KGLOG_PROCESS_ERROR(m_lpEditor); UINT uHandle = 0; m_lpEditor->NewOneDataDefine(&uHandle); FillListDefine(); Exit0: ; } void KSceneDataFlowEditorDefineDialog::OnBnClickedButtonDeletedefine() { // TODO: Add your control notification handler code here } void KSceneDataFlowEditorDefineDialog::OnEnChangeEditDefinename() { UpdateData(TRUE); if(!m_lpEditor) return; if (m_uCurrentSelectedDefine) { m_lpEditor->SetDataDefineName(m_szDefineName,m_uCurrentSelectedDefine); } FillListDefine(); } void KSceneDataFlowEditorDefineDialog::OnEnChangeEditNumvariable() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here } void KSceneDataFlowEditorDefineDialog::OnLbnSelchangeListVariable() { if(!m_lpEditor) return; if(m_uCurrentSelectedDefine) { int nIndex = m_ListVariable.GetCurSel(); if(nIndex>=0 ) { m_nCurrentSelectedVariable = nIndex; KG3DDATAFLOWVARIABLETYPE eType; TCHAR Name[MAX_PATH]; if(SUCCEEDED(m_lpEditor->GetVariableofDataDefine(m_nCurrentSelectedVariable,&eType,Name,m_uCurrentSelectedDefine))) { m_szVariableName.Format("%s",Name); m_ComboVariableType.SetCurSel(eType); UpdateData(FALSE); } } } } void KSceneDataFlowEditorDefineDialog::OnEnChangeEditVariablename() { if(!m_lpEditor) return; UpdateData(TRUE); if(m_uCurrentSelectedDefine) { if(m_nCurrentSelectedVariable>=0) { KG3DDATAFLOWVARIABLETYPE eType; TCHAR Name[MAX_PATH]; if(SUCCEEDED(m_lpEditor->GetVariableofDataDefine(m_nCurrentSelectedVariable,&eType,Name,m_uCurrentSelectedDefine))) { m_lpEditor->SetVariableofDataDefine(m_nCurrentSelectedVariable,eType,m_szVariableName,m_uCurrentSelectedDefine); FillListVariable(); } } } } void KSceneDataFlowEditorDefineDialog::OnCbnSelchangeComboVariabletype() { if(!m_lpEditor) return; UpdateData(TRUE); if(m_uCurrentSelectedDefine) { if(m_nCurrentSelectedVariable>=0) { KG3DDATAFLOWVARIABLETYPE eType; TCHAR Name[MAX_PATH]; if(SUCCEEDED(m_lpEditor->GetVariableofDataDefine(m_nCurrentSelectedVariable,&eType,Name,m_uCurrentSelectedDefine))) { eType = (KG3DDATAFLOWVARIABLETYPE)m_ComboVariableType.GetCurSel(); m_lpEditor->SetVariableofDataDefine(m_nCurrentSelectedVariable,eType,m_szVariableName,m_uCurrentSelectedDefine); FillListVariable(); } } } } HRESULT KSceneDataFlowEditorDefineDialog::FillListDefine() { vector<UINT>vecDefine; m_ListDefine.DeleteAllItems(); KGLOG_PROCESS_ERROR(m_lpEditor); m_lpEditor->GetAllDataDefine(&vecDefine); for (size_t i=0;i<vecDefine.size();i++) { UINT uHandle = vecDefine[i]; TCHAR name[MAX_PATH]; m_lpEditor->GetDataDefineName(name,uHandle); int nIndex = m_ListDefine.InsertItem(0,name); m_ListDefine.SetItemData(nIndex,uHandle); } return S_OK; Exit0: return E_FAIL; } HRESULT KSceneDataFlowEditorDefineDialog::FillListVariable() { if(!m_lpEditor) return E_FAIL; { m_ListVariable.SetCurSel(-1); int nCount = m_ListVariable.GetCount(); for (int i=0;i<nCount;i++) { m_ListVariable.DeleteString(0); } } if(m_uCurrentSelectedDefine) { DWORD dwNum = 0; if(FAILED(m_lpEditor->GetNumVariableofDataDefine(&dwNum,m_uCurrentSelectedDefine))) return E_FAIL; for (DWORD i=0;i<dwNum;i++) { KG3DDATAFLOWVARIABLETYPE eType; TCHAR Name[MAX_PATH]; TCHAR TotalName[MAX_PATH]; TCHAR typeName[MAX_PATH]; m_lpEditor->GetVariableofDataDefine(i,&eType,Name,m_uCurrentSelectedDefine); m_lpEditor->GetVariableType(&eType,typeName,(DWORD)eType); wsprintf(TotalName,"%s : %s",Name,typeName); m_ListVariable.AddString(TotalName); } } return S_OK; } HRESULT KSceneDataFlowEditorDefineDialog::FillComboVariable() { if(!m_lpEditor) return E_FAIL; { int nCount = m_ComboVariableType.GetCount(); for (int i=0;i<nCount;i++) { m_ComboVariableType.DeleteString(0); } } DWORD dwNumType = 0; m_lpEditor->GetNumVariableType(&dwNumType); for (DWORD i=0;i<dwNumType;i++) { KG3DDATAFLOWVARIABLETYPE eType; TCHAR Name[MAX_PATH]; if (SUCCEEDED(m_lpEditor->GetVariableType(&eType,Name,i))) { int nIndex = m_ComboVariableType.AddString(Name); m_ComboVariableType.SetItemData(nIndex,eType); } ; } return S_OK; } BOOL KSceneDataFlowEditorDefineDialog::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here m_ListDefine.InsertColumn(0, _T("Name"), LVCFMT_CENTER, 200); m_ListDefine.SetExtendedStyle( m_ListDefine.GetExtendedStyle() | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES ); FillComboVariable(); FillListDefine(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void KSceneDataFlowEditorDefineDialog::OnBnClickedButtonSetnumvariable() { if(!m_lpEditor) return ; if (m_uCurrentSelectedDefine) { UpdateData(TRUE); m_lpEditor->SetNumVariableofDataDefine(m_dwNumVariable,m_uCurrentSelectedDefine); FillListVariable(); } }
26.436364
119
0.755273
RivenZoo
6682ad244c2bee9a0251cff2761fa395fef5ab07
1,529
hpp
C++
Parallel/OMPFor.hpp
DLancer999/SPHSimulator
4f2f3a29d9769e62a9cae3d036b3e09dac99e305
[ "MIT" ]
null
null
null
Parallel/OMPFor.hpp
DLancer999/SPHSimulator
4f2f3a29d9769e62a9cae3d036b3e09dac99e305
[ "MIT" ]
null
null
null
Parallel/OMPFor.hpp
DLancer999/SPHSimulator
4f2f3a29d9769e62a9cae3d036b3e09dac99e305
[ "MIT" ]
1
2022-02-03T08:21:46.000Z
2022-02-03T08:21:46.000Z
/*************************************************************************\ License Copyright (c) 2018 Kavvadias Ioannis. This file is part of SPHSimulator. Licensed under the MIT License. See LICENSE file in the project root for full license information. Description Utility functions for ranges SourceFiles - \************************************************************************/ #ifndef ParallelOMPFor_H #define ParallelOMPFor_H #include <cstdio> #include <fstream> #include <thread> #include <iostream> #include <string> #include <omp.h> #include "ParallelImpl.hpp" #include <boost/program_options.hpp> struct OMPFor : private ParallelImpl<OMPFor> { template <typename Functor> static void For(size_t rangeSize, Functor f) { #pragma omp parallel for for (size_t i=0; i<rangeSize; ++i) { f(i); } } static void readSettings() { int nThreads = 0; std::ifstream Config_File("ParallelConfig.ini"); using namespace boost::program_options; options_description SimSet("Settings"); SimSet.add_options() ("ParallelSettings.nThreads", value<int>(&nThreads)); variables_map vm; store(parse_config_file(Config_File, SimSet), vm); notify(vm); if (!nThreads) { nThreads = static_cast<int>(std::thread::hardware_concurrency()); if (!nThreads) { std::cerr<<"Hardware_concurrency method failed!!"<<std::endl; nThreads = 1; } } omp_set_num_threads(nThreads); } }; #endif
22.485294
77
0.606279
DLancer999
66859ef16719a2f95515aca56dac0dbb358934ab
9,563
cc
C++
src/libraries/JANA/Engine/JArrowProcessingController.cc
andrea-celentano/JANA2
84a07a432a3d216bfc45ebf9b391b572bf88addf
[ "Apache-2.0" ]
null
null
null
src/libraries/JANA/Engine/JArrowProcessingController.cc
andrea-celentano/JANA2
84a07a432a3d216bfc45ebf9b391b572bf88addf
[ "Apache-2.0" ]
null
null
null
src/libraries/JANA/Engine/JArrowProcessingController.cc
andrea-celentano/JANA2
84a07a432a3d216bfc45ebf9b391b572bf88addf
[ "Apache-2.0" ]
null
null
null
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Jefferson Science Associates LLC Copyright Notice: // // Copyright 251 2014 Jefferson Science Associates LLC All Rights Reserved. Redistribution // and use in source and binary forms, with or without modification, are permitted as a // licensed user provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products derived // from this software without specific prior written permission. // This material resulted from work developed under a United States Government Contract. // The Government retains a paid-up, nonexclusive, irrevocable worldwide license in such // copyrighted data to reproduce, distribute copies to the public, prepare derivative works, // perform publicly and display publicly and to permit others to do so. // THIS SOFTWARE IS PROVIDED BY JEFFERSON SCIENCE ASSOCIATES LLC "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 // JEFFERSON SCIENCE ASSOCIATES, LLC OR THE U.S. GOVERNMENT BE LIABLE TO LICENSEE OR ANY // THIRD PARTES 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. //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // // Author: Nathan Brei // #include <JANA/Engine/JArrowProcessingController.h> #include <JANA/Engine/JArrowPerfSummary.h> #include <JANA/Utils/JCpuInfo.h> #include <JANA/JLogger.h> #include <memory> using millisecs = std::chrono::duration<double, std::milli>; using secs = std::chrono::duration<double>; void JArrowProcessingController::acquire_services(JServiceLocator * sl) { auto ls = sl->get<JLoggingService>(); _logger = ls->get_logger("JArrowProcessingController"); _worker_logger = ls->get_logger("JWorker"); _scheduler_logger = ls->get_logger("JScheduler"); } void JArrowProcessingController::initialize() { _scheduler = new JScheduler(_topology->arrows); _scheduler->logger = _scheduler_logger; LOG_INFO(_logger) << _topology->mapping << LOG_END; } void JArrowProcessingController::run(size_t nthreads) { _topology->set_active(true); scale(nthreads); } void JArrowProcessingController::scale(size_t nthreads) { bool pin_to_cpu = (_topology->mapping.get_affinity() != JProcessorMapping::AffinityStrategy::None); size_t next_worker_id = _workers.size(); while (next_worker_id < nthreads) { size_t next_cpu_id = _topology->mapping.get_cpu_id(next_worker_id); size_t next_loc_id = _topology->mapping.get_loc_id(next_worker_id); auto worker = new JWorker(_scheduler, next_worker_id, next_cpu_id, next_loc_id, pin_to_cpu); worker->logger = _worker_logger; _workers.push_back(worker); next_worker_id++; } for (size_t i=0; i<nthreads; ++i) { _workers.at(i)->start(); }; for (size_t i=nthreads; i<next_worker_id; ++i) { _workers.at(i)->request_stop(); } for (size_t i=nthreads; i<next_worker_id; ++i) { _workers.at(i)->wait_for_stop(); } _topology->metrics.reset(); _topology->metrics.start(nthreads); } void JArrowProcessingController::request_stop() { for (JWorker* worker : _workers) { worker->request_stop(); } // Tell the topology to stop timers and deactivate arrows _topology->set_active(false); } void JArrowProcessingController::wait_until_stopped() { for (JWorker* worker : _workers) { worker->request_stop(); } for (JWorker* worker : _workers) { worker->wait_for_stop(); } } bool JArrowProcessingController::is_stopped() { for (JWorker* worker : _workers) { if (worker->get_runstate() != JWorker::RunState::Stopped) { return false; } } // We have determined that all Workers have actually stopped return true; } bool JArrowProcessingController::is_finished() { return !_topology->is_active(); } JArrowProcessingController::~JArrowProcessingController() { request_stop(); wait_until_stopped(); for (JWorker* worker : _workers) { delete worker; } delete _topology; delete _scheduler; } void JArrowProcessingController::print_report() { auto metrics = measure_internal_performance(); jout << "Running" << *metrics << jendl; } void JArrowProcessingController::print_final_report() { auto metrics = measure_internal_performance(); jout << "Final Report" << *metrics << jendl; } std::unique_ptr<const JArrowPerfSummary> JArrowProcessingController::measure_internal_performance() { // Measure perf on all Workers first, as this will prompt them to publish // any ArrowMetrics they have collected _perf_summary.workers.clear(); for (JWorker* worker : _workers) { WorkerSummary summary; worker->measure_perf(summary); _perf_summary.workers.push_back(summary); } size_t monotonic_event_count = 0; for (JArrow* arrow : _topology->sinks) { monotonic_event_count += arrow->get_metrics().get_total_message_count(); } // Uptime _topology->metrics.split(monotonic_event_count); _topology->metrics.summarize(_perf_summary); double worst_seq_latency = 0; double worst_par_latency = 0; _perf_summary.arrows.clear(); for (JArrow* arrow : _topology->arrows) { JArrowMetrics::Status last_status; size_t total_message_count; size_t last_message_count; size_t total_queue_visits; size_t last_queue_visits; duration_t total_latency; duration_t last_latency; duration_t total_queue_latency; duration_t last_queue_latency; arrow->get_metrics().get(last_status, total_message_count, last_message_count, total_queue_visits, last_queue_visits, total_latency, last_latency, total_queue_latency, last_queue_latency); auto total_latency_ms = millisecs(total_latency).count(); auto total_queue_latency_ms = millisecs(total_queue_latency).count(); ArrowSummary summary; summary.arrow_type = arrow->get_type(); summary.is_parallel = arrow->is_parallel(); summary.is_active = arrow->is_active(); summary.thread_count = arrow->get_thread_count(); summary.arrow_name = arrow->get_name(); summary.chunksize = arrow->get_chunksize(); summary.messages_pending = arrow->get_pending(); summary.is_upstream_active = !arrow->is_upstream_finished(); summary.threshold = arrow->get_threshold(); summary.status = arrow->get_status(); summary.total_messages_completed = total_message_count; summary.last_messages_completed = last_message_count; summary.queue_visit_count = total_queue_visits; summary.avg_queue_latency_ms = (total_queue_visits == 0) ? std::numeric_limits<double>::infinity() : total_queue_latency_ms / total_queue_visits; summary.avg_queue_overhead_frac = total_queue_latency_ms / (total_queue_latency_ms + total_latency_ms); summary.avg_latency_ms = (total_message_count == 0) ? std::numeric_limits<double>::infinity() : summary.avg_latency_ms = total_latency_ms/total_message_count; summary.last_latency_ms = (last_message_count == 0) ? std::numeric_limits<double>::infinity() : millisecs(last_latency).count()/last_message_count; if (arrow->is_parallel()) { worst_par_latency = std::max(worst_par_latency, summary.avg_latency_ms); } else { worst_seq_latency = std::max(worst_seq_latency, summary.avg_latency_ms); } _perf_summary.arrows.push_back(summary); } // bottlenecks _perf_summary.avg_seq_bottleneck_hz = 1e3 / worst_seq_latency; _perf_summary.avg_par_bottleneck_hz = 1e3 * _perf_summary.thread_count / worst_par_latency; auto tighter_bottleneck = std::min(_perf_summary.avg_seq_bottleneck_hz, _perf_summary.avg_par_bottleneck_hz); _perf_summary.avg_efficiency_frac = (tighter_bottleneck == 0) ? std::numeric_limits<double>::infinity() : _perf_summary.avg_throughput_hz/tighter_bottleneck; return std::unique_ptr<JArrowPerfSummary>(new JArrowPerfSummary(_perf_summary)); } std::unique_ptr<const JPerfSummary> JArrowProcessingController::measure_performance() { return measure_internal_performance(); }
39.680498
122
0.685977
andrea-celentano
6686952c1868d5c1fb0527d6e7e8644b65d4a8a1
162
cpp
C++
Samples/exception.cpp
mahdialikhasi/Advanced-Programming
0ece123e6442e5e844f657e5ea2ca9de00d5c734
[ "CC0-1.0" ]
null
null
null
Samples/exception.cpp
mahdialikhasi/Advanced-Programming
0ece123e6442e5e844f657e5ea2ca9de00d5c734
[ "CC0-1.0" ]
null
null
null
Samples/exception.cpp
mahdialikhasi/Advanced-Programming
0ece123e6442e5e844f657e5ea2ca9de00d5c734
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; int main(){ try{ throw 100; }catch(int a){ }catch(double b){ }catch(type1 c){ throw; //rethrow } return 0; }
10.8
20
0.623457
mahdialikhasi
668e69b9e9b7359e1b7cfa83bc97c3e5e3de540c
11,307
cpp
C++
symbol_utf8/symbol_utf8.cpp
xloem/Blessings
7ac5021fea2bbe30bd1f358eec1983edb4405bde
[ "MIT" ]
null
null
null
symbol_utf8/symbol_utf8.cpp
xloem/Blessings
7ac5021fea2bbe30bd1f358eec1983edb4405bde
[ "MIT" ]
null
null
null
symbol_utf8/symbol_utf8.cpp
xloem/Blessings
7ac5021fea2bbe30bd1f358eec1983edb4405bde
[ "MIT" ]
null
null
null
#include "symbol_utf8.hpp" #include "symbol_utf8_impl.hpp" #include <string> #include <iostream> #include <cstring> #include <cstdio> #include <cstdint> using namespace std; namespace blessings { const SymbolUTF8 SymbolUTF8::space({static_cast<char>(0x20)}); SymbolUTF8::SymbolUTF8(char c) noexcept { if (c&0b10000000) { arr_[0]=0b11000000|(c>>6); arr_[1]=0b10000000|(c&0b00111111); size_=2; } else { arr_[0]=c; size_=1; } } SymbolUTF8::SymbolUTF8(char32_t x) { if (x&0xff000000) size_=4; else if (x&0x00ff0000) size_=3; else if (x&0x0000ff00) size_=2; else size_=1; Converter conv; conv.ch=x; switch(size_) { case 1: arr_[0]=conv.arr_[0]; if (arr_[0]&0b10000000) throw InitError(); break; case 2: arr_[0]=conv.arr_[1]; arr_[1]=conv.arr_[0]; if ((arr_[0]&0b11100000)^0b11000000) throw InitError(); if ((arr_[1]&0b11000000)^0b10000000) throw InitError(); break; case 3: arr_[0]=conv.arr_[2]; arr_[1]=conv.arr_[1]; arr_[2]=conv.arr_[0]; if ((arr_[0]&0b11110000)^0b11100000) throw InitError(); if ((arr_[1]&0b11000000)^0b10000000) throw InitError(); if ((arr_[2]&0b11000000)^0b10000000) throw InitError(); break; case 4: arr_[0]=conv.arr_[3]; arr_[1]=conv.arr_[2]; arr_[2]=conv.arr_[1]; arr_[3]=conv.arr_[0]; if ((arr_[0]&0b11111000)^0b11110000) throw InitError(); if ((arr_[1]&0b11000000)^0b10000000) throw InitError(); if ((arr_[2]&0b11000000)^0b10000000) throw InitError(); if ((arr_[3]&0b11000000)^0b10000000) throw InitError(); } } SymbolUTF8::SymbolUTF8(const char* sym) { if (sym==nullptr) throw InitError(); if (*sym=='\0') throw InitError(); if (!(sym[0]&0b10000000)) size_=1; else if (!((sym[0]&0b11100000)^0b11000000)) size_=2; else if (!((sym[0]&0b11110000)^0b11100000)) size_=3; else if (!((sym[0]&0b11111000)^0b11110000)) size_=4; else throw InitError(); if (strlen(sym)!=static_cast<size_t>(size_)) throw InitError(); switch(size_) { case 4: if (((sym[3]&0b11000000)^0b10000000)) throw InitError(); case 3: if (((sym[2]&0b11000000)^0b10000000)) throw InitError(); case 2: if (((sym[1]&0b11000000)^0b10000000)) throw InitError(); } for (int8_t i=0; i<size_; ++i) arr_[i]=sym[i]; } SymbolUTF8::SymbolUTF8(const char* sym, int givenSize) { if (sym==nullptr) throw InitError(); if (givenSize==0) throw InitError(); if (!(sym[0]&0b10000000)) size_=1; else if (!((sym[0]&0b11100000)^0b11000000)) size_=2; else if (!((sym[0]&0b11110000)^0b11100000)) size_=3; else if (!((sym[0]&0b11111000)^0b11110000)) size_=4; else throw InitError(); if (givenSize!=static_cast<int>(size_)) throw InitError(); switch(size_) { case 4: if (((sym[3]&0b11000000)^0b10000000)) throw InitError(); case 3: if (((sym[2]&0b11000000)^0b10000000)) throw InitError(); case 2: if (((sym[1]&0b11000000)^0b10000000)) throw InitError(); } for (int8_t i=0; i<size_; ++i) arr_[i]=sym[i]; } SymbolUTF8::SymbolUTF8(const std::string& sym) { if(sym.size()==0) throw InitError(); if (!(sym[0]&0b10000000)) size_=1; else if (!((sym[0]&0b11100000)^0b11000000)) size_=2; else if (!((sym[0]&0b11110000)^0b11100000)) size_=3; else if (!((sym[0]&0b11111000)^0b11110000)) size_=4; else throw InitError(); if (sym.size()!=static_cast<size_t>(size_)) throw InitError(); switch(size_) { case 4: if (((sym[3]&0b11000000)^0b10000000)) throw InitError(); case 3: if (((sym[2]&0b11000000)^0b10000000)) throw InitError(); case 2: if (((sym[1]&0b11000000)^0b10000000)) throw InitError(); } for (int8_t i=0; i<size_; ++i) arr_[i]=sym[i]; } SymbolUTF8::SymbolUTF8(const std::initializer_list<char>& sym) { if(sym.size()==0) throw InitError(); if (!(*sym.begin()&0b10000000)) size_=1; else if (!((*sym.begin()&0b11100000)^0b11000000)) size_=2; else if (!((*sym.begin()&0b11110000)^0b11100000)) size_=3; else if (!((*sym.begin()&0b11111000)^0b11110000)) size_=4; else throw InitError(); if (sym.size()!=static_cast<size_t>(size_)) throw InitError(); switch(size_) { case 4: if (((*(sym.begin()+3)&0b11000000)^0b10000000)) throw InitError(); case 3: if (((*(sym.begin()+2)&0b11000000)^0b10000000)) throw InitError(); case 2: if (((*(sym.begin()+1)&0b11000000)^0b10000000)) throw InitError(); } auto it=sym.begin(); for (int8_t i=0; i<size_; ++i, ++it) arr_[i]=*it; } SymbolUTF8::SymbolUTF8(uint32_t x) { if (x<0x7F) size_=1; else if (x<0x7FF) size_=2; else if (x<0xFFFF) size_=3; else if (x<0x1FFFFF) size_=4; else throw InitError(); Converter conv; conv.ui=x; switch(size_) { case 1: arr_[0]=conv.arr_[0]; break; case 2: arr_[1]=(conv.arr_[0]&0b00111111)|0b10000000; conv.ui>>=6; arr_[0]=(conv.arr_[0]&0b00011111)|0b11000000; break; case 3: arr_[2]=(conv.arr_[0]&0b00111111)|0b10000000; conv.ui>>=6; arr_[1]=(conv.arr_[0]&0b00111111)|0b10000000; conv.ui>>=6; arr_[0]=(conv.arr_[0]&0b00001111)|0b11100000; break; case 4: arr_[3]=(conv.arr_[0]&0b00111111)|0b10000000; conv.ui>>=6; arr_[2]=(conv.arr_[0]&0b00111111)|0b10000000; conv.ui>>=6; arr_[1]=(conv.arr_[0]&0b00111111)|0b10000000; conv.ui>>=6; arr_[0]=(conv.arr_[0]&0b00000111)|0b11110000; } } SymbolUTF8::SymbolUTF8(const SymbolUTF8& sym) { for (int i=0; i<4; ++i) arr_[i]=sym.arr_[i]; size_=sym.size_; } const SymbolUTF8& SymbolUTF8::operator=(const SymbolUTF8& sym) { if (*this==sym) return *this; for (int i=0; i<4; ++i) arr_[i]=sym.arr_[i]; size_=sym.size_; return (*this); } char SymbolUTF8::operator()(int i) const { if(i<0 || i>3) throw AccessError(); return arr_[i]; } std::ostream& operator<<(std::ostream& stream, const SymbolUTF8& sym) { for (int i=0; i<sym.size_; ++i) { try { stream << sym.arr_[i]; } catch (...) { throw SymbolUTF8::WriteError(); } } return stream; } std::pair<SymbolUTF8, const char*> SymbolUTF8::getSymbol(const char* str) { if(str==nullptr) throw InitError(); return getSymbol(str, str+strlen(str)); } SymbolUTF8 SymbolUTF8::getSymbol(const char* str,\ size_t n) { if(n==0) throw InitError(); else if(str==nullptr) throw InitError(); int size; if (!(str[0]&0b10000000)) size=1; else if (!((str[0]&0b11100000)^0b11000000)) size=2; else if (!((str[0]&0b11110000)^0b11100000)) size=3; else size=4; if(n<static_cast<size_t>(size)) throw InitError(); return SymbolUTF8(str, size); } std::istream& operator>>(std::istream& stream, SymbolUTF8& sym) { SymbolUTF8 ret; try { stream.get(ret.arr_[0]); } catch (...) { throw SymbolUTF8::ReadError(); } if(stream.eof()) throw SymbolUTF8::EndOfFile(); if (!(ret.arr_[0]&0b10000000)) ret.size_=1; else if (!((ret.arr_[0]&0b11100000)^0b11000000)) ret.size_=2; else if (!((ret.arr_[0]&0b11110000)^0b11100000)) ret.size_=3; else if (!((ret.arr_[0]&0b11111000)^0b11110000)) ret.size_=4; else throw SymbolUTF8::BadEncodingStreamGiven(); for (int8_t i=1; i<ret.size_; ++i) { try { stream.get(ret.arr_[i]); } catch (...) { throw SymbolUTF8::ReadError(); } if(stream.eof()) throw SymbolUTF8::EndOfFile(); } switch(ret.size_) { case 4: if (((ret.arr_[3]&0b11000000)^0b10000000)) throw SymbolUTF8::BadEncodingStreamGiven(); case 3: if (((ret.arr_[2]&0b11000000)^0b10000000)) throw SymbolUTF8::BadEncodingStreamGiven(); case 2: if (((ret.arr_[1]&0b11000000)^0b10000000)) throw SymbolUTF8::BadEncodingStreamGiven(); } sym=ret; return stream; } std::string SymbolUTF8::toString() const { return std::string(arr_, size_); } bool operator==(const SymbolUTF8& a, const SymbolUTF8& b) { int aSize=a.size_; int bSize=b.size_; if(aSize!=bSize) return false; bool ret=true; for (int i=0; i<aSize; ++i) { if (a.arr_[i]!=b.arr_[i]) { ret=false; break; } } return ret; } bool operator!=(const SymbolUTF8& a, const SymbolUTF8& b) { int aSize=a.size_; int bSize=b.size_; if(aSize!=bSize) return true; bool ret=false; for (int i=0; i<aSize; ++i) { if (a.arr_[i]!=b.arr_[i]) { ret=true; break; } } return ret; } void SymbolUTF8::writeToFile(FILE* file) const { for (int8_t i=0; i<size_; ++i) { int temp=fputc(static_cast<int>(arr_[i]), file); if (temp==EOF) throw SymbolUTF8::WriteError(); } } SymbolUTF8 SymbolUTF8::readFromFile(FILE* file) { int temp=getc(file); if (temp==EOF) { if(feof(file)) throw SymbolUTF8::EndOfFile(); else throw SymbolUTF8::ReadError(); } SymbolUTF8 ret; ret.arr_[0]=static_cast<char>(temp); if (!(ret.arr_[0]&0b10000000)) ret.size_=1; else if (!((ret.arr_[0]&0b11100000)^0b11000000)) ret.size_=2; else if (!((ret.arr_[0]&0b11110000)^0b11100000)) ret.size_=3; else if (!((ret.arr_[0]&0b11111000)^0b11110000)) ret.size_=4; else throw SymbolUTF8::BadEncodingStreamGiven(); for (int8_t i=1; i<ret.size_; ++i) { temp=getc(file); if (temp==EOF) { if(feof(file)) throw SymbolUTF8::EndOfFile(); else throw SymbolUTF8::ReadError(); } ret.arr_[i]=static_cast<char>(temp); if ((ret.arr_[i]&0b11000000)^0b10000000) throw SymbolUTF8::BadEncodingStreamGiven(); } return ret; } SymbolUTF8::operator char32_t() const { Converter conv; conv.ch=0; const char* ch=arr_; uint8_t size=size_; while (size) { conv.ch<<=8; conv.arr_[0]=*ch; --size; ++ch; } return conv.ch; } uint32_t SymbolUTF8::unicode() const { Converter conv; conv.ui=0; switch(size_) { case 1: conv.arr_[0]=arr_[0]; return conv.ui; case 2: conv.arr_[0]=arr_[0]&0b00011111; conv.ui<<=6; conv.arr_[0]|=arr_[1]&0b00111111; return conv.ui; case 3: conv.arr_[0]=arr_[0]&0b00001111; conv.ui<<=6; conv.arr_[0]|=arr_[1]&0b00111111; conv.ui<<=6; conv.arr_[0]|=arr_[2]&0b00111111; return conv.ui; case 4: conv.arr_[0]=arr_[0]&0b00000111; conv.ui<<=6; conv.arr_[0]|=arr_[1]&0b00111111; conv.ui<<=6; conv.arr_[0]|=arr_[2]&0b00111111; conv.ui<<=6; conv.arr_[0]|=arr_[3]&0b00111111; return conv.ui; } } bool operator<=(const SymbolUTF8& a, const SymbolUTF8& b) { return a.unicode()<=b.unicode(); } bool operator<(const SymbolUTF8& a, const SymbolUTF8& b) { return a.unicode()<b.unicode(); } bool operator>=(const SymbolUTF8& a, const SymbolUTF8& b) { return a.unicode()>=b.unicode(); } bool operator>(const SymbolUTF8& a, const SymbolUTF8& b) { return a.unicode()>b.unicode(); } }
25.933486
92
0.592819
xloem
668ef2606a04d1775e3bb6ee94354c5af262c4d4
14,595
hpp
C++
3rdparty/GPSTk/core/lib/GNSSCore/TropModel.hpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/lib/GNSSCore/TropModel.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/lib/GNSSCore/TropModel.hpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file TropModel.hpp * Base class for tropospheric models, plus implementations * of several published models */ #ifndef TROP_MODEL_HPP #define TROP_MODEL_HPP #include "Exception.hpp" #include "ObsEpochMap.hpp" #include "WxObsMap.hpp" #include "Xvt.hpp" #include "Position.hpp" #include "Matrix.hpp" #include "GNSSconstants.hpp" #define THROW_IF_INVALID() {if (!valid) {InvalidTropModel e("Invalid model");GPSTK_THROW(e);}} // Model of the troposphere, used to compute non-dispersive delay of // satellite signal as function of satellite elevation as seen at the // receiver. Both wet and hydrostatic (dry) components are computed. // // The default model (implemented here) is a simple Black model. // // In this model (and many others), the wet and hydrostatic (dry) components are // independent, the zenith delays depend only on the weather // (temperature, pressure and humidity), and the mapping functions // depend only on the elevation of the satellite as seen at the // receiver. In general, this is not true; other models depend on, // for example, latitude or day of year. // // Other models may be implemented by inheriting this class and // redefining the virtual functions, and (perhaps) adding other // 'set...()' routines as needed. namespace gpstk { /** @addtogroup GPSsolutions */ //@{ /** Abstract base class for tropospheric models. * The wet and hydrostatic (dry) components of the tropospheric delay are each * the product of a zenith delay and a mapping function. Usually the zenith * delay depends only on the weather (temperature, pressure and humidity), * while the mapping function depends only on the satellite elevation, i.e. * the geometry of satellite and receiver. This may not be true in complex * models. * The full tropospheric delay is the sum of the wet and hydrostatic (dry) * components. A TropModel is valid only when all the necessary information * (weather + whatever else the model requires) is specified; * An InvalidTropModel exception will be thrown when any correction() * or zenith_delay() or mapping_function() routine is called for * an invalid TropModel. */ /// Thrown when attempting to use a model for which all necessary /// parameters have not been specified. /// @ingroup exceptiongroup NEW_EXCEPTION_CLASS(InvalidTropModel, gpstk::Exception); class TropModel { public: static const double CELSIUS_TO_KELVIN; /// Destructor virtual ~TropModel() {} /// Return validity of model bool isValid(void) { return valid; } /// Return the name of the model virtual std::string name(void) { return std::string("Undefined"); } /// Compute and return the full tropospheric delay /// @param elevation Elevation of satellite as seen at receiver, in degrees virtual double correction(double elevation) const throw(InvalidTropModel); /** * Compute and return the full tropospheric delay, given the positions of * receiver and satellite and the time tag. This version is most useful * within positioning algorithms, where the receiver position and timetag * may vary; it computes the elevation (and other receiver location * information) and passes them to appropriate set...() routines and the * correction(elevation) routine. * @param RX Receiver position * @param SV Satellite position * @param tt Time tag of the signal */ virtual double correction(const Position& RX, const Position& SV, const CommonTime& tt) throw(InvalidTropModel); /** \deprecated * Compute and return the full tropospheric delay, given the positions of * receiver and satellite and the time tag. This version is most useful * within positioning algorithms, where the receiver position and timetag * may vary; it computes the elevation (and other receiver location * information) and passes them to appropriate set...() routines and the * correction(elevation) routine. * @param RX Receiver position in ECEF cartesian coordinates (meters) * @param SV Satellite position in ECEF cartesian coordinates (meters) * @param tt Time tag of the signal */ virtual double correction(const Xvt& RX, const Xvt& SV, const CommonTime& tt) throw(InvalidTropModel) { Position R(RX),S(SV); return TropModel::correction(R,S,tt); } /// Compute and return the zenith delay for hydrostatic (dry) /// component of the troposphere virtual double dry_zenith_delay(void) const throw(InvalidTropModel) = 0; /// Compute and return the zenith delay for wet component of the troposphere virtual double wet_zenith_delay(void) const throw(InvalidTropModel) = 0; /// Compute and return the mapping function for hydrostatic (dry) /// component of the troposphere. /// @param elevation Elevation of satellite as seen at receiver, in degrees virtual double dry_mapping_function(double elevation) const throw(InvalidTropModel) = 0; /// Compute and return the mapping function for wet component of /// the troposphere. /// @param elevation Elevation of satellite as seen at receiver, in degrees virtual double wet_mapping_function(double elevation) const throw(InvalidTropModel) = 0; /// Re-define the tropospheric model with explicit weather data. /// Typically called just before correction(). /// @param T temperature in degrees Celsius /// @param P atmospheric pressure in millibars /// @param H relative humidity in percent virtual void setWeather(const double& T, const double& P, const double& H) throw(InvalidParameter); /// Re-define the tropospheric model with explicit weather data. /// Typically called just before correction(). /// @param wx the weather to use for this correction virtual void setWeather(const WxObservation& wx) throw(InvalidParameter); /// Define the receiver height; this required by some models before calling /// correction() or any of the zenith_delay or mapping_function routines. /// @param ht Height of the receiver in meters. virtual void setReceiverHeight(const double& ht) {}; /// Define the latitude of the receiver; this is required by some models /// before calling correction() or any of the zenith_delay or /// mapping_function routines. /// @param lat Latitude of the receiver in degrees. virtual void setReceiverLatitude(const double& lat) {}; /// Define the receiver longitude; this is required by some models /// before calling correction() or any of the zenith_delay routines. /// @param lat Longitude of receiver, in degrees East. virtual void setReceiverLongitude(const double& lon) {}; /// Define the day of year; this is required by some models before calling /// correction() or any of the zenith_delay or mapping_function routines. /// @param d Day of year. virtual void setDayOfYear(const int& d) {}; /// Saastamoinen hydrostatic zenith delay as modified by Davis for gravity. /// Used by multiple models. /// Ref. Leick, 3rd ed, pg 197, Leick, 4th ed, pg 482, and /// Saastamoinen 1973 Atmospheric correction for the troposphere and /// stratosphere in radio ranging of satellites. The use of artificial /// satellites for geodesy, Geophys. Monogr. Ser. 15, Amer. Geophys. Union, /// pp. 274-251, 1972. /// Davis, J.L, T.A. Herring, I.I. Shapiro, A.E.E. Rogers, and G. Elgered, /// Geodesy by Radio Interferometry: Effects of Atmospheric Modeling Errors /// on Estimates of Baseline Length, Radio Science, Vol. 20, No. 6, /// pp. 1593-1607, 1985. /// @param press pressure in millibars /// @param lat latitude in degrees /// @param height ellipsoid height in meters double SaasDryDelay(const double pr, const double lat, const double ht) const { return (0.0022768*pr/(1-0.00266*::cos(2*lat*DEG_TO_RAD)-0.00028*ht/1000.)); } /// get weather data by a standard atmosphere model /// reference to white paper of Bernese 5.0, P243 /// @param ht height of the receiver in meters. /// @param T temperature in degrees Celsius /// @param P atmospheric pressure in millibars /// @param H relative humidity in percent static void weatherByStandardAtmosphereModel( const double& ht, double& T, double& P, double& H); protected: bool valid; // true only if current model parameters are valid double temp; // latest value of temperature (kelvin or celsius) double press; // latest value of pressure (millibars) double humid; // latest value of relative humidity (percent) }; // end class TropModel //--------------------------------------------------------------------------------- /// The 'zero' trop model, meaning it always returns zero. class ZeroTropModel : public TropModel { public: /// Return the name of the model virtual std::string name(void) { return std::string("Zero"); } /// Compute and return the full tropospheric delay /// @param elevation Elevation of satellite as seen at receiver, in degrees virtual double correction(double elevation) const throw(InvalidTropModel) { return 0.0; } /** * Compute and return the full tropospheric delay, given the positions of * receiver and satellite and the time tag. This version is most useful * within positioning algorithms, where the receiver position and timetag * may vary; it computes the elevation (and other receiver location * information) and passes them to appropriate set...() routines and the * correction(elevation) routine. * @param RX Receiver position * @param SV Satellite position * @param tt Time tag of the signal */ virtual double correction(const Position& RX, const Position& SV, const CommonTime& tt) throw(InvalidTropModel) { return 0.0; } /** \deprecated * Compute and return the full tropospheric delay, given the positions of * receiver and satellite and the time tag. This version is most useful * within positioning algorithms, where the receiver position and timetag * may vary; it computes the elevation (and other receiver location * information) and passes them to appropriate set...() routines and the * correction(elevation) routine. * @param RX Receiver position in ECEF cartesian coordinates (meters) * @param SV Satellite position in ECEF cartesian coordinates (meters) * @param tt Time tag of the signal */ virtual double correction(const Xvt& RX, const Xvt& SV, const CommonTime& tt) throw(InvalidTropModel) { return 0.0; } /// Compute and return the zenith delay for hydrostatic (dry) /// component of the troposphere virtual double dry_zenith_delay(void) const throw(InvalidTropModel) { return 0.0; } /// Compute and return the zenith delay for wet component of the troposphere virtual double wet_zenith_delay(void) const throw(InvalidTropModel) { return 0.0; } /// Compute and return the mapping function for hydrostatic (dry) /// component of the troposphere. /// @param elevation Elevation of satellite as seen at receiver, in degrees virtual double dry_mapping_function(double elevation) const throw(InvalidTropModel) { return 0.0; } /// Compute and return the mapping function for wet component of /// the troposphere. /// @param elevation Elevation of satellite as seen at receiver, in degrees virtual double wet_mapping_function(double elevation) const throw(InvalidTropModel) { return 0.0; } }; // end class ZeroTropModel //@} } #endif
44.769939
94
0.631381
mfkiwl
66918d61796c614b40c09fb2f4acc3bec8467315
13,225
cpp
C++
modules/variants/discovery/branch.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
16
2021-07-14T23:32:31.000Z
2022-03-24T16:25:15.000Z
modules/variants/discovery/branch.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-20T20:39:47.000Z
2021-09-16T20:57:59.000Z
modules/variants/discovery/branch.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-15T19:38:35.000Z
2022-01-31T19:24:56.000Z
#include "modules/variants/discovery/branch.h" #include "modules/variants/discovery/path.h" #include "modules/variants/discovery/rejoin.h" #include "modules/variants/discovery/view.h" namespace variants { namespace discovery { static constexpr bool k_dbg = false; search_result branch_search_entry::search(branch* br) { return search_internal(br); } struct branch_search_entry_comparer { bool operator()(const branch_search_entry_ptr& lhs, const branch_search_entry_ptr& rhs) const { // Returns true if rhs is better than lhs. // Exhaust all push and rejoin searches first before trying POP searches. const auto& akey = lhs->get_key(); const auto& bkey = rhs->get_key(); return (*this)(akey, bkey); } bool operator()(const search_entry_key& akey, const search_entry_key& bkey) const { return akey < bkey; } }; void branch::check_invariants() const { unsigned tracable_count = 0; if (!m_trace.empty()) { for (const auto& e : m_search_entries) { if (trace_enabled_for_entry(e.get())) { ++tracable_count; } e->check_invariants(this); } } CHECK_EQ(tracable_count, m_tracable_entry_count); // Make sure we really do split off of reference, and in a valid offset. auto splits = push_view()->get_scaffold().split_extent_at(m_right_offset); auto left_of_anchor = splits.first; if (!left_of_anchor.empty()) { CHECK_NE(m_first_base, left_of_anchor[left_of_anchor.size() - 1]); } } std::string branch::describe() const { std::stringstream out; if (m_push_view->is_rev_comp()) { out << "Branch " << opts().scaffold_name << ":" << left_pop_view_offset() << "(rev=" << right_push_view_offset() << ") -> " << m_first_base.complement(); } else { out << "Branch " << m_first_base << " -> " << opts().scaffold_name << ":" << right_push_view_offset() << "(rev=" << left_pop_view_offset() << ")"; } out << ", " << m_search_entries.size() << " entries\n"; constexpr bool k_display_all_search_entries = false; if (k_display_all_search_entries) { for (const auto& e : m_search_entries) { out << " " << e->describe(this) << "\n"; } } return out.str(); } view_t* branch::push_view() const { return m_push_view; } view_t* branch::pop_view() const { return m_push_view->reverse_view(); } state* branch::get_state() const { return m_push_view->get_state(); } branch::branch(view_t* push_view, dna_base first_base, aoffset_t right_offset) : m_push_view(push_view), m_first_base(first_base), m_right_offset(right_offset) { m_steps_left = opts().bidir_max_branch_steps; } bool branch::update_ploids_remaining() { offset_info oi = push_view()->get_offset_info(m_right_offset, false /* !fwd */); if (oi.ploids_remaining <= 0) { m_ref_remaining = std::numeric_limits<aoffset_t>::max(); return false; } m_ref_remaining = oi.ref_remaining_limit; return true; } void branch::notify_rejoin(branch* other_br, branch_search_entry* other_e) { update_ploids_remaining(); // If we got a rejoin, discard all our intermediate searches. if (m_tracable_entry_count) { std::cout << "Clearing branch " << *this << " because of " << other_e->describe(other_br) << "\n"; } clear(); } search_result branch::search(boost::optional<search_entry_key> limit_key) { if (m_search_entries.empty()) { return search_result::STOP_SEARCHING; } if (!update_ploids_remaining()) { if (m_tracable_entry_count) { std::cout << "Clearing branch " << *this << " due to no ploids remaining\n"; } clear(); return search_result::STOP_SEARCHING; } auto start_time = std::chrono::high_resolution_clock::now(); while (!m_search_entries.empty()) { if (limit_key && m_search_entries.front()->get_key() < *limit_key) { break; } execute_one_search_internal(); } auto end_time = std::chrono::high_resolution_clock::now(); m_time_spent += end_time - start_time; return search_result::SEARCH_MORE; } void branch::execute_search_for_testing(branch_search_entry_ptr e) { update_ploids_remaining(); execute_search_internal(std::move(e)); } bool branch::trace_enabled_for_entry(const branch_search_entry* e) const { if (m_trace.empty()) { return false; } if (dynamic_cast<const rejoin_search_entry*>(e)) { return true; } if (trace_enabled(e->get_path())) { return true; } return false; } void branch::execute_search_internal(branch_search_entry_ptr e) { bool needs_trace = trace_enabled_for_entry(e.get()); if (k_dbg || needs_trace) { std::cout << "Branch executing search (" << m_steps_left << " steps left) on: " << e->describe(this) << " (" << m_search_entries.size() << " searches left)\n"; } unsigned orig_tracable_entry_count = m_tracable_entry_count; if (needs_trace) { CHECK_GT(m_tracable_entry_count, 0); --m_tracable_entry_count; } if (e->pair_match_count() < m_max_pair_match_count / 2) { if (needs_trace) { std::cout << "TRACE had too few pair matches\n"; } e->notify_discard(this); return; } switch (e->search(this)) { case search_result::STOP_SEARCHING: if (needs_trace && m_tracable_entry_count < orig_tracable_entry_count) { std::cout << "LOST TRACE, returned STOP_SEARCHING\n"; } break; case search_result::SEARCH_MORE: if (needs_trace && !trace_enabled_for_entry(e.get())) { std::cout << "DIVERGED FROM TRACE, wanting SEARCH_MORE: " << e->describe(this) << "\n"; } add_search_entry(std::move(e)); break; default: LOG(FATAL) << "Invalid search result"; } } void branch::execute_one_search_for_testing() { update_ploids_remaining(); execute_one_search_internal(); } void branch::execute_one_search_internal() { CHECK(!m_search_entries.empty()); std::pop_heap(m_search_entries.begin(), m_search_entries.end(), branch_search_entry_comparer()); branch_search_entry_ptr e = std::move(m_search_entries.back()); m_search_entries.pop_back(); if (m_steps_left == 0) { if (trace_enabled_for_entry(e.get())) { std::cout << "DISCARD TRACED ENTRY: " << e->describe(this) << " due to out of steps\n"; CHECK_GT(m_tracable_entry_count, 0); --m_tracable_entry_count; } e->notify_discard(this); } else { --m_steps_left; execute_search_internal(std::move(e)); } }; void branch::add_search_entry(branch_search_entry_ptr e) { if (trace_enabled_for_entry(e.get())) { ++m_tracable_entry_count; std::cout << "Added search entry that needs trace: " << e->describe(this) << "\n"; } if (e->pair_match_count() > m_max_pair_match_count) { unsigned new_pair_matches = e->pair_match_count() - m_max_pair_match_count; m_steps_left += new_pair_matches * opts().bidir_branch_steps_per_pair; if (m_steps_left > opts().bidir_max_branch_steps) { m_steps_left = opts().bidir_max_branch_steps; } m_max_pair_match_count = e->pair_match_count(); } m_search_entries.emplace_back(std::move(e)); std::push_heap(m_search_entries.begin(), m_search_entries.end(), branch_search_entry_comparer()); } void branch::check_path_invariants(const path& p) const { unsigned actual_anchor_len = push_view()->shared_ref_bases_to_left(right_push_view_offset() + p.anchor_len(), p.seq()); CHECK_EQ(p.anchor_len(), actual_anchor_len) << "Right offset: " << right_push_view_offset() << " seq: " << p.seq() << "push search entry: " << *this << " scaffold: " << push_view()->opts().scaffold_name; if (push_view()->opts().bidir_validate_trace_state > 1) { p.check_invariants(); } } void branch::clear() { // If we used all our steps getting here, free some up for potential // additional alleles. But don't free up all of it... m_max_pair_match_count = 0; m_steps_left = opts().bidir_max_branch_steps; if (m_search_entries.empty()) { CHECK_EQ(0, m_tracable_entry_count); } else { std::vector<branch_search_entry_ptr> to_discard; std::swap(m_search_entries, to_discard); for (const auto& e : to_discard) { if (trace_enabled_for_entry(e.get())) { std::cout << "DISCARD TRACED ENTRY: " << e->describe(this) << " due to branch clearing\n"; CHECK_GT(m_tracable_entry_count, 0); --m_tracable_entry_count; } e->notify_discard(this); } CHECK_EQ(m_tracable_entry_count, 0); CHECK(m_search_entries.empty()); } } std::string branch_search_entry::describe(const branch* br) const { std::stringstream result; result << "BrSearch(" << m_key << "):" << describe_internal(br); return result.str(); } bool branch::try_rejoin(aoffset_t outer_left_offset, dna_slice left_seq, const path& p, unsigned pair_match_count) { if (k_dbg) { std::cout << "\nBranch considering rejoin at " << outer_left_offset << ":\n" << "Seq: " << left_seq << "\n" // << "Path: " << p << "\n"; } if (outer_left_offset < m_ref_remaining) { if (k_dbg) { std::cout << "Outer left " << outer_left_offset << " < ref remaining " << m_ref_remaining << "; cannot rejoin\n"; } return false; } if (outer_left_offset >= right_push_view_offset()) { if (k_dbg) { std::cout << "Outer left " << outer_left_offset << " > right offset " << m_right_offset << "; cannot rejoin\n"; } return false; } aoffset_t ref_distance = m_right_offset - outer_left_offset; if (ref_distance > aoffset_t(opts().read_ahead_distance)) { if (k_dbg) { std::cout << "ref distance " << ref_distance << " too far for readahead; cannot rejoin\n"; } return false; } auto ext = push_view()->get_scaffold().split_extent_at(outer_left_offset); dna_slice ref_seq = ext.second; unsigned left_anchor_len = ref_seq.shared_prefix_length(left_seq); if (left_anchor_len == left_seq.size()) { left_anchor_len += ref_seq.subseq(left_anchor_len, ext.second.size() - left_anchor_len) .shared_prefix_length(p.seq()); } if (k_dbg) { std::cout << "Left anchor shares " << left_anchor_len << " bases with reference\nRef:\n" << ref_seq.subseq(0, left_anchor_len) << "\nLeft seq: " << left_seq << "\nPath: " << p << "\n"; std::cout << "Ref continues: " << ref_seq.subseq(left_anchor_len, 30) << "\n"; } if (left_anchor_len >= (left_seq.size() + p.size())) { if (k_dbg) { std::cout << "Left anchor is whole sequence; cannot rejoin\n"; } return false; } CHECK_GE(left_anchor_len, opts().bidir_min_anchor_len) << "Left anchor only has " << left_anchor_len << " bases in common with reference; cannot rejoin\n"; aoffset_t left_offset = outer_left_offset + left_anchor_len; path rejoin_path = p; rejoin_path.push_front_drop(left_seq); unsigned path_overlap = rejoin_path.path_overlap(); path_overlap = std::min<unsigned>(path_overlap, left_anchor_len); if (k_dbg) { std::cout << "Rejoin path: " << rejoin_path << "\n"; } if (left_offset >= right_push_view_offset() + p.anchor_len()) { return false; } std::unique_ptr<rejoin_search_entry> e = make_unique<rejoin_search_entry>( path_overlap, left_offset, left_anchor_len, std::move(rejoin_path), pair_match_count); if (opts().bidir_validate_trace_state) { e->check_invariants(this); } if (k_dbg) { std::cout << "Rejoin try successful; saving rejoin search entry:\n" << e->describe(this) << "\n"; } add_search_entry(std::move(e)); return true; } branch_search_entry::branch_search_entry(const search_entry_key& key) : m_key(key) {} void branch::enable_trace(dna_slice seq) { CHECK_EQ(seq.rev_comp()[0].complement(), m_first_base); m_trace.emplace(seq.rev_comp()); } bool branch::trace_enabled(dna_slice seq) const { if (m_trace.empty()) { return false; } dna_slice rc_seq = seq.rev_comp(); auto it = m_trace.lower_bound(dna_sequence(rc_seq)); if (it != m_trace.end()) { unsigned shared1 = rc_seq.shared_prefix_length(*it); CHECK_GE(shared1, 1); if (shared1 == rc_seq.size() || shared1 == it->size()) { return true; } } if (it == m_trace.begin()) { return false; } --it; unsigned shared2 = rc_seq.shared_prefix_length(*it); CHECK_GE(shared2, 1); if (shared2 == rc_seq.size() || shared2 == it->size()) { return true; } return false; } bool branch::trace_enabled(const path& p) const { if (m_trace.empty()) { return false; } dna_slice seq = p.seq(); seq = seq.subseq(0, seq.size() - p.anchor_len()); return trace_enabled(seq); } bool branch::explore(const seqset_range& r) { return m_explored.insert(r).second; } std::ostream& operator<<(std::ostream& os, const branch& br) { return os << br.describe(); } boost::optional<search_entry_key> branch::best_search_entry_key() const { if (m_search_entries.empty()) { return boost::none; } return m_search_entries.front()->get_key(); } void branch::note_output(dna_slice seq) { if (opts().bidir_report_slow_branches) { m_outputs.emplace(seq); } } } // namespace discovery } // namespace variants
31.264775
100
0.664726
spiralgenetics
66965d15808e8f0b412b06866e9adb3e76a5d424
1,352
hpp
C++
include/cmn/rect.hpp
InsaneHamster/ihamster
0f09e7eec3dff68ba7c2e899b03fd75940d3e242
[ "MIT" ]
1
2018-01-28T14:10:26.000Z
2018-01-28T14:10:26.000Z
include/cmn/rect.hpp
InsaneHamster/ihamster
0f09e7eec3dff68ba7c2e899b03fd75940d3e242
[ "MIT" ]
null
null
null
include/cmn/rect.hpp
InsaneHamster/ihamster
0f09e7eec3dff68ba7c2e899b03fd75940d3e242
[ "MIT" ]
null
null
null
#pragma once #include "point.hpp" namespace cmn { template< typename T, int D > struct rect_tt { typedef T value_type; static int const dimension = D; typedef point_tt<T,D> point_t; point_t origin; point_t size; }; template<typename T> struct rect_tt<T, 2> { typedef T value_type; static int const dimension = 2; typedef point_tt<T,dimension> point_t; point_t origin; point_t size; rect_tt(){} rect_tt( point_t const & _origin, point_t const & _size ) : origin(_origin), size(_size){} rect_tt( T const & x, T const & y, T const & width, T const & height ) : origin(x,y), size(width, height){} bool operator == (rect_tt const & other) const { return origin == other.origin && size == other.size; } bool operator != (rect_tt const & other) const { return origin != other.origin || size != other.size; } //will fail on unsigned bool is_inside( point_t const & pt ) const { point_t s = pt - origin; if( s.x < 0 || s.y < 0 || s.x >= size.x || s.y >= size.y ) return false; else return true; }; }; typedef rect_tt< int, 2 > rect2i_t; typedef rect_tt< float, 2 > rect2f_t; };
30.727273
171
0.545118
InsaneHamster
669bafa4c0de44b6196066a110b025bed518d007
33
cpp
C++
src/Qt5Sql/QSqlDriverCreator.cpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
128
2015-01-07T19:47:09.000Z
2022-01-22T19:42:14.000Z
src/Qt5Sql/QSqlDriverCreator.cpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
null
null
null
src/Qt5Sql/QSqlDriverCreator.cpp
dafrito/luacxx
278bf8a7c6664536ea7f1dd1f59d35b6fb8d2dad
[ "MIT" ]
24
2015-01-07T19:47:10.000Z
2022-01-25T17:42:37.000Z
#include "QSqlDriverCreator.hpp"
16.5
32
0.818182
dafrito
669cbac0cbdd5507c183a99e9fda1953d9dae3ef
776
cpp
C++
src/algorithms/warmup/plus_minus/plus_minus.cpp
bmgandre/hackerrank-cpp
f4af5777afba233c284790e02c0be7b82108c677
[ "MIT" ]
null
null
null
src/algorithms/warmup/plus_minus/plus_minus.cpp
bmgandre/hackerrank-cpp
f4af5777afba233c284790e02c0be7b82108c677
[ "MIT" ]
null
null
null
src/algorithms/warmup/plus_minus/plus_minus.cpp
bmgandre/hackerrank-cpp
f4af5777afba233c284790e02c0be7b82108c677
[ "MIT" ]
null
null
null
#include "plus_minus.h" #include <iostream> #include <iomanip> #include <string> using namespace hackerrank::bmgandre::algorithms::warmup; /// Practice>Algorithms>Warmup>Plus Minus /// /// https://www.hackerrank.com/challenges/plus-minus void plus_minus::solve() { auto count = 0; std::cin >> count; auto negatives = .0, positives = .0, zeros = .0, current = .0; for (auto i = 0; i < count; i++) { std::cin >> current; if (current < 0) { ++negatives; } else if (current > 0) { ++positives; } else { ++zeros; } } std::cout << std::setprecision(6) << std::fixed << positives / count << std::endl << std::setprecision(6) << std::fixed << negatives / count << std::endl << std::setprecision(6) << std::fixed << zeros / count << std::endl; }
24.25
82
0.614691
bmgandre
669cc5e4f3a9e7f8e4f12deff9f86a68bb64a9c6
6,403
cpp
C++
cpp/oneapi/dal/table/backend/interop/host_csr_table_adapter.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
188
2016-04-16T12:11:48.000Z
2018-01-12T12:42:55.000Z
cpp/oneapi/dal/table/backend/interop/host_csr_table_adapter.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
1,198
2020-03-24T17:26:18.000Z
2022-03-31T08:06:15.000Z
cpp/oneapi/dal/table/backend/interop/host_csr_table_adapter.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
93
2018-01-23T01:59:23.000Z
2020-03-16T11:04:19.000Z
/******************************************************************************* * Copyright 2021 Intel Corporation * * 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 "oneapi/dal/table/backend/interop/host_csr_table_adapter.hpp" namespace oneapi::dal::backend::interop { static daal::data_management::features::FeatureType get_daal_feature_type(feature_type t) { namespace daal_dm = daal::data_management; switch (t) { case feature_type::nominal: return daal_dm::features::DAAL_CATEGORICAL; case feature_type::ordinal: return daal_dm::features::DAAL_ORDINAL; case feature_type::interval: return daal_dm::features::DAAL_CONTINUOUS; case feature_type::ratio: return daal_dm::features::DAAL_CONTINUOUS; default: throw dal::internal_error(detail::error_messages::unsupported_feature_type()); } } static void convert_feature_information_to_daal( const table_metadata& src, daal::data_management::NumericTableDictionary& dst) { ONEDAL_ASSERT(std::size_t(src.get_feature_count()) == dst.getNumberOfFeatures()); for (std::int64_t i = 0; i < src.get_feature_count(); i++) { auto& daal_feature = dst[i]; daal_feature.featureType = get_daal_feature_type(src.get_feature_type(i)); } } template <typename Data> auto host_csr_table_adapter<Data>::create(const detail::csr_table& table) -> ptr_t { status_t internal_stat; auto result = ptr_t{ new host_csr_table_adapter(table, internal_stat) }; status_to_exception(internal_stat); return result; } template <typename Data> auto host_csr_table_adapter<Data>::getSparseBlock(std::size_t vector_idx, std::size_t vector_num, rw_mode_t rwflag, block_desc_t<double>& block) -> status_t { return read_sparse_values_impl(vector_idx, vector_num, rwflag, block); } template <typename Data> auto host_csr_table_adapter<Data>::getSparseBlock(std::size_t vector_idx, std::size_t vector_num, rw_mode_t rwflag, block_desc_t<float>& block) -> status_t { return read_sparse_values_impl(vector_idx, vector_num, rwflag, block); } template <typename Data> auto host_csr_table_adapter<Data>::getSparseBlock(std::size_t vector_idx, std::size_t vector_num, rw_mode_t rwflag, block_desc_t<int>& block) -> status_t { return read_sparse_values_impl(vector_idx, vector_num, rwflag, block); } template <typename Data> auto host_csr_table_adapter<Data>::releaseSparseBlock(block_desc_t<double>& block) -> status_t { block.reset(); return status_t(); } template <typename Data> auto host_csr_table_adapter<Data>::releaseSparseBlock(block_desc_t<float>& block) -> status_t { block.reset(); return status_t(); } template <typename Data> auto host_csr_table_adapter<Data>::releaseSparseBlock(block_desc_t<int>& block) -> status_t { block.reset(); return status_t(); } template <typename Data> std::size_t host_csr_table_adapter<Data>::getDataSize() { return base::getDataSize(); } template <typename Data> void host_csr_table_adapter<Data>::freeDataMemoryImpl() { base::freeDataMemoryImpl(); original_table_ = detail::csr_table{}; } template <typename Data> template <typename BlockData> auto host_csr_table_adapter<Data>::read_sparse_values_impl(std::size_t vector_idx, std::size_t vector_num, rw_mode_t rwflag, block_desc_t<BlockData>& block) -> status_t { if (rwflag != daal::data_management::readOnly) { return daal::services::ErrorMethodNotImplemented; } return base::getSparseBlock(vector_idx, vector_num, rwflag, block); } template <typename Data> host_csr_table_adapter<Data>::host_csr_table_adapter(const detail::csr_table& table, status_t& stat) // The following const_cast is safe only when this class is used for read-only // operations. Use on write leads to undefined behaviour. : base(ptr_data_t{ const_cast<Data*>(table.get_data<Data>()), daal_object_owner(table) }, ptr_index_t{ const_cast<std::size_t*>( reinterpret_cast<const std::size_t*>(table.get_column_indices())), daal_object_owner(table) }, ptr_index_t{ const_cast<std::size_t*>( reinterpret_cast<const std::size_t*>(table.get_row_indices())), daal_object_owner(table) }, table.get_column_count(), table.get_row_count(), daal::data_management::CSRNumericTableIface::CSRIndexing::oneBased, stat) { if (!stat.ok()) { return; } else if (!table.has_data()) { stat.add(daal::services::ErrorIncorrectParameter); return; } original_table_ = table; this->_memStatus = daal::data_management::NumericTableIface::userAllocated; this->_layout = daal::data_management::NumericTableIface::csrArray; auto& daal_dictionary = *this->getDictionarySharedPtr(); convert_feature_information_to_daal(original_table_.get_metadata(), daal_dictionary); } template class host_csr_table_adapter<std::int32_t>; template class host_csr_table_adapter<float>; template class host_csr_table_adapter<double>; } // namespace oneapi::dal::backend::interop
41.309677
100
0.634702
cmsxbc
66a043db9a0fe52d8c8ab13abe86d1b9e0e5c8ad
3,648
cpp
C++
src/GUI/FileIO.cpp
davidgreisler/four-in-a-line
a21014e926df30359365d76510c64665e49096e3
[ "MIT" ]
4
2015-01-18T09:33:30.000Z
2019-02-28T12:00:09.000Z
src/GUI/FileIO.cpp
davidgreisler/four-in-a-line
a21014e926df30359365d76510c64665e49096e3
[ "MIT" ]
null
null
null
src/GUI/FileIO.cpp
davidgreisler/four-in-a-line
a21014e926df30359365d76510c64665e49096e3
[ "MIT" ]
null
null
null
#include "FileIO.hpp" #include <QFile> #include <QTextStream> #include <QFileDialog> #include <QMessageBox> namespace GUI { /** * Opens the file with the given filename, reads the whole file and stores it in content. * * @param parentWidget Parent widget. * @param fileName File name/path of the file. * @param content Reference to a string where the file's content is stored. * @return When the file has been read successfully true, otherwise false. */ bool FileIO::GetFileContent(QWidget* parentWidget, QString fileName, QByteArray& content) { QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); content.append(stream.readAll()); return true; } else { QString errorMessage = QObject::tr("Failed to open the file '%1' for reading."); QMessageBox::critical(parentWidget, QObject::tr("Failed to open file"), errorMessage.arg(fileName), QMessageBox::Abort); } return false; } /** * Opens the file with the given filename for writing, truncates it and then writes content into the * file. * * @param parentWidget Parent widget. * @param fileName File name/path of the file. * @param content Content to write into the file. * @return When the content was written into the file successfully true, otherwise false. */ bool FileIO::SetFileContent(QWidget* parentWidget, QString fileName, const QByteArray& content) { QFile file(fileName); if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QTextStream stream(&file); stream << content; stream.flush(); return true; } else { QString errorMessage = QObject::tr("Failed to open the file '%1' for writing."); QMessageBox::critical(parentWidget, QObject::tr("Failed to open file"), errorMessage.arg(fileName), QMessageBox::Abort); } return false; } /** * Shows an open file dialog asking the user for one existing file and returns the specified * filename. * * @param parentWidget Parent widget. * @param fileName Reference to a string where the filename is stored. * @param nameFilter Name filter for the open file dialog. * @return When the user specified an existing file name true, otherwise false. */ bool FileIO::GetExistingFileName(QWidget* parentWidget, QString& fileName, QString nameFilter) { QFileDialog fileDialog(parentWidget); fileDialog.setFileMode(QFileDialog::ExistingFile); fileDialog.setNameFilter(nameFilter); if (fileDialog.exec()) { QStringList selectedFiles = fileDialog.selectedFiles(); if (!selectedFiles.empty()) { fileName = selectedFiles.at(0); return true; } } return false; } /** * Shows a save file dialog asking the user for one filename and returns the specified filename. * * @param parentWidget Parent widget. * @param fileName Reference to a string where the filename is stored. * @param defaultSuffix The default suffix to use. * @param nameFilter Name filter for the save file dialog. * @return When the user specified a file name true, otherwise false. */ bool FileIO::GetSaveFileName(QWidget* parentWidget, QString& fileName, QString defaultSuffix, QString nameFilter) { QFileDialog fileDialog(parentWidget); fileDialog.setFileMode(QFileDialog::AnyFile); fileDialog.setAcceptMode(QFileDialog::AcceptSave); fileDialog.setDefaultSuffix(defaultSuffix); fileDialog.setNameFilter(nameFilter); if (fileDialog.exec()) { QStringList selectedFiles = fileDialog.selectedFiles(); if (!selectedFiles.empty()) { fileName = selectedFiles.at(0); return true; } } return false; } }
26.627737
100
0.714638
davidgreisler
66a3907f117317eee1f35f0f5fb23e9a043976ce
12,026
cpp
C++
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_util.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_util.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_util.d3d12.cpp
nagakagachi/sample_projct
300fcdaf65a009874ce1964a64682aeb6a6ef82e
[ "MIT" ]
null
null
null
 #include "rhi_util.d3d12.h" namespace ngl { namespace rhi { DXGI_FORMAT ConvertResourceFormat(ResourceFormat v) { static DXGI_FORMAT table[] = { DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_R32G32B32A32_TYPELESS, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_UINT, DXGI_FORMAT_R32G32B32A32_SINT, DXGI_FORMAT_R32G32B32_TYPELESS, DXGI_FORMAT_R32G32B32_FLOAT, DXGI_FORMAT_R32G32B32_UINT, DXGI_FORMAT_R32G32B32_SINT, DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_UNORM, DXGI_FORMAT_R16G16B16A16_UINT, DXGI_FORMAT_R16G16B16A16_SNORM, DXGI_FORMAT_R16G16B16A16_SINT, DXGI_FORMAT_R32G32_TYPELESS, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32_UINT, DXGI_FORMAT_R32G32_SINT, DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_D32_FLOAT_S8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UINT, DXGI_FORMAT_R11G11B10_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB, DXGI_FORMAT_R8G8B8A8_UINT, DXGI_FORMAT_R8G8B8A8_SNORM, DXGI_FORMAT_R8G8B8A8_SINT, DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_UNORM, DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R16G16_SNORM, DXGI_FORMAT_R16G16_SINT, DXGI_FORMAT_R32_TYPELESS, DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R32_SINT, DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_D24_UNORM_S8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UINT, DXGI_FORMAT_R8G8_SNORM, DXGI_FORMAT_R8G8_SINT, DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_D16_UNORM, DXGI_FORMAT_R16_UNORM, DXGI_FORMAT_R16_UINT, DXGI_FORMAT_R16_SNORM, DXGI_FORMAT_R16_SINT, DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UINT, DXGI_FORMAT_R8_SNORM, DXGI_FORMAT_R8_SINT, DXGI_FORMAT_A8_UNORM, DXGI_FORMAT_R1_UNORM, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, DXGI_FORMAT_R8G8_B8G8_UNORM, DXGI_FORMAT_G8R8_G8B8_UNORM, DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM_SRGB, DXGI_FORMAT_BC2_TYPELESS, DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM_SRGB, DXGI_FORMAT_BC3_TYPELESS, DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM_SRGB, DXGI_FORMAT_BC4_TYPELESS, DXGI_FORMAT_BC4_UNORM, DXGI_FORMAT_BC4_SNORM, DXGI_FORMAT_BC5_TYPELESS, DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC5_SNORM, DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_B8G8R8X8_UNORM, DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM, DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB, DXGI_FORMAT_B8G8R8X8_TYPELESS, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB, DXGI_FORMAT_BC6H_TYPELESS, DXGI_FORMAT_BC6H_UF16, DXGI_FORMAT_BC6H_SF16, DXGI_FORMAT_BC7_TYPELESS, DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_BC7_UNORM_SRGB, DXGI_FORMAT_AYUV, DXGI_FORMAT_Y410, DXGI_FORMAT_Y416, DXGI_FORMAT_NV12, DXGI_FORMAT_P010, DXGI_FORMAT_P016, DXGI_FORMAT_420_OPAQUE, DXGI_FORMAT_YUY2, DXGI_FORMAT_Y210, DXGI_FORMAT_Y216, DXGI_FORMAT_NV11, DXGI_FORMAT_AI44, DXGI_FORMAT_IA44, DXGI_FORMAT_P8, DXGI_FORMAT_A8P8, DXGI_FORMAT_B4G4R4A4_UNORM }; static_assert(std::size(table) == static_cast<size_t>(ResourceFormat::_MAX), ""); // 現状はDXGIと一対一の対応 return table[static_cast<u32>(v)]; } D3D12_RESOURCE_STATES ConvertResourceState(ResourceState v) { D3D12_RESOURCE_STATES ret = {}; switch (v) { case ResourceState::Common: { ret = D3D12_RESOURCE_STATE_COMMON; break; } case ResourceState::General: { ret = D3D12_RESOURCE_STATE_GENERIC_READ; break; } case ResourceState::ConstatnBuffer: { ret = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; break; } case ResourceState::VertexBuffer: { ret = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; break; } case ResourceState::IndexBuffer: { ret = D3D12_RESOURCE_STATE_INDEX_BUFFER; break; } case ResourceState::RenderTarget: { ret = D3D12_RESOURCE_STATE_RENDER_TARGET; break; } case ResourceState::ShaderRead: { ret = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; break; } case ResourceState::UnorderedAccess: { ret = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; break; } case ResourceState::DepthWrite: { ret = D3D12_RESOURCE_STATE_DEPTH_WRITE; break; } case ResourceState::DepthRead: { ret = D3D12_RESOURCE_STATE_DEPTH_READ; break; } case ResourceState::IndirectArgument: { ret = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; break; } case ResourceState::CopyDst: { ret = D3D12_RESOURCE_STATE_COPY_DEST; break; } case ResourceState::CopySrc: { ret = D3D12_RESOURCE_STATE_COPY_SOURCE; break; } case ResourceState::Present: { ret = D3D12_RESOURCE_STATE_PRESENT; break; } default: { std::cout << "ERROR : Invalid Resource State" << std::endl; } } return ret; } D3D12_BLEND_OP ConvertBlendOp(BlendOp v) { switch (v) { case BlendOp::Add: { return D3D12_BLEND_OP_ADD; } case BlendOp::Subtract: { return D3D12_BLEND_OP_SUBTRACT; } case BlendOp::RevSubtract: { return D3D12_BLEND_OP_REV_SUBTRACT; } case BlendOp::Min: { return D3D12_BLEND_OP_MIN; } case BlendOp::Max: { return D3D12_BLEND_OP_MAX; } default: { return D3D12_BLEND_OP_ADD; } } } D3D12_BLEND ConvertBlendFactor(BlendFactor v) { switch (v) { case BlendFactor::Zero: { return D3D12_BLEND_ZERO; } case BlendFactor::One: { return D3D12_BLEND_ONE; } case BlendFactor::SrcColor: { return D3D12_BLEND_SRC_COLOR; } case BlendFactor::InvSrcColor: { return D3D12_BLEND_INV_SRC_COLOR; } case BlendFactor::SrcAlpha: { return D3D12_BLEND_SRC_ALPHA; } case BlendFactor::InvSrcAlpha: { return D3D12_BLEND_INV_SRC_ALPHA; } case BlendFactor::DestAlpha: { return D3D12_BLEND_DEST_ALPHA; } case BlendFactor::InvDestAlpha: { return D3D12_BLEND_INV_DEST_ALPHA; } case BlendFactor::DestColor: { return D3D12_BLEND_DEST_COLOR; } case BlendFactor::InvDestColor: { return D3D12_BLEND_INV_DEST_COLOR; } case BlendFactor::SrcAlphaSat: { return D3D12_BLEND_SRC_ALPHA_SAT; } case BlendFactor::BlendFactor: { return D3D12_BLEND_BLEND_FACTOR; } case BlendFactor::InvBlendFactor: { return D3D12_BLEND_INV_BLEND_FACTOR; } case BlendFactor::Src1Color: { return D3D12_BLEND_SRC1_COLOR; } case BlendFactor::InvSrc1Color: { return D3D12_BLEND_INV_SRC1_COLOR; } case BlendFactor::Src1Alpha: { return D3D12_BLEND_SRC1_ALPHA; } case BlendFactor::InvSrc1Alpha: { return D3D12_BLEND_INV_SRC1_ALPHA; } default: { return D3D12_BLEND_ONE; } } } D3D12_CULL_MODE ConvertCullMode(CullingMode v) { switch (v) { case CullingMode::Front: return D3D12_CULL_MODE_FRONT; case CullingMode::Back: return D3D12_CULL_MODE_BACK; default: return D3D12_CULL_MODE_NONE; } } D3D12_FILL_MODE ConvertFillMode(FillMode v) { switch (v) { case FillMode::Wireframe: return D3D12_FILL_MODE_WIREFRAME; case FillMode::Solid: return D3D12_FILL_MODE_SOLID; default: return D3D12_FILL_MODE_SOLID; } } D3D12_STENCIL_OP ConvertStencilOp(StencilOp v) { switch (v) { case StencilOp::Keep: return D3D12_STENCIL_OP_KEEP; case StencilOp::Zero: return D3D12_STENCIL_OP_ZERO; case StencilOp::Replace: return D3D12_STENCIL_OP_REPLACE; case StencilOp::IncrSat: return D3D12_STENCIL_OP_INCR_SAT; case StencilOp::DecrSat: return D3D12_STENCIL_OP_DECR_SAT; case StencilOp::Invert: return D3D12_STENCIL_OP_INVERT; case StencilOp::Incr: return D3D12_STENCIL_OP_INCR; case StencilOp::Decr: return D3D12_STENCIL_OP_DECR; default: return D3D12_STENCIL_OP_KEEP; } } D3D12_COMPARISON_FUNC ConvertComparisonFunc(CompFunc v) { switch (v) { case CompFunc::Never: return D3D12_COMPARISON_FUNC_NEVER; case CompFunc::Less: return D3D12_COMPARISON_FUNC_LESS; case CompFunc::Equal: return D3D12_COMPARISON_FUNC_EQUAL; case CompFunc::LessEqual: return D3D12_COMPARISON_FUNC_LESS_EQUAL; case CompFunc::Greater: return D3D12_COMPARISON_FUNC_GREATER; case CompFunc::NotEqual: return D3D12_COMPARISON_FUNC_NOT_EQUAL; case CompFunc::GreaterEqual: return D3D12_COMPARISON_FUNC_GREATER_EQUAL; case CompFunc::Always: return D3D12_COMPARISON_FUNC_ALWAYS; default: return D3D12_COMPARISON_FUNC_ALWAYS; } } D3D12_PRIMITIVE_TOPOLOGY_TYPE ConvertPrimitiveTopologyType(PrimitiveTopologyType v) { switch (v) { case PrimitiveTopologyType::Point: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT; case PrimitiveTopologyType::Line: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE; case PrimitiveTopologyType::Triangle: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; case PrimitiveTopologyType::Patch: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH; default: return D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED; } } D3D_PRIMITIVE_TOPOLOGY ConvertPrimitiveTopology(ngl::rhi::PrimitiveTopology v) { switch (v) { case PrimitiveTopology::PointList: return D3D_PRIMITIVE_TOPOLOGY_POINTLIST; case PrimitiveTopology::LineList: return D3D_PRIMITIVE_TOPOLOGY_LINELIST; case PrimitiveTopology::LineStrip: return D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; case PrimitiveTopology::TriangleList: return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; case PrimitiveTopology::TriangleStrip: return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; default: assert(false); return D3D_PRIMITIVE_TOPOLOGY_UNDEFINED; } } D3D12_FILTER ConvertTextureFilter(TextureFilterMode v) { static constexpr D3D12_FILTER table[] = { D3D12_FILTER_MIN_MAG_MIP_POINT, D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR, D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR, D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT, D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, D3D12_FILTER_MIN_MAG_MIP_LINEAR, D3D12_FILTER_ANISOTROPIC, D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT, D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, D3D12_FILTER_COMPARISON_ANISOTROPIC }; assert(std::size(table) > static_cast<size_t>(v)); return table[static_cast<size_t>(v)]; } D3D12_TEXTURE_ADDRESS_MODE ConvertTextureAddressMode(TextureAddressMode v) { static constexpr D3D12_TEXTURE_ADDRESS_MODE table[] = { D3D12_TEXTURE_ADDRESS_MODE_WRAP, D3D12_TEXTURE_ADDRESS_MODE_MIRROR, D3D12_TEXTURE_ADDRESS_MODE_CLAMP, D3D12_TEXTURE_ADDRESS_MODE_BORDER, D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE }; assert(std::size(table) > static_cast<size_t>(v)); return table[static_cast<size_t>(v)]; } } }
23.580392
85
0.741144
nagakagachi
66a8a7065e80701be0a3391c258ec0d71bbec9f2
1,219
cpp
C++
Sources/Graphics/GUILib/Qt5Example/QtJsonTree.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
27
2017-12-19T09:15:36.000Z
2021-07-30T13:02:00.000Z
Sources/Graphics/GUILib/Qt5Example/QtJsonTree.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
null
null
null
Sources/Graphics/GUILib/Qt5Example/QtJsonTree.cpp
wurui1994/test
027cef75f98dbb252b322113dacd4a9a6997d84f
[ "MIT" ]
29
2018-04-10T13:25:54.000Z
2021-12-24T01:51:03.000Z
#include <QtCore> class JsonTree:public QJsonObject { public: JsonTree(QJsonDocument const& doc) { object = doc.object(); } JsonTree(QJsonObject const& obj) { object = obj; } JsonTree(QString const& str) { string = str; object = QJsonDocument::fromJson(str.toUtf8()).object(); } JsonTree operator[](QString key) { if (object[key].isObject()) { return object[key].toObject(); } else { return JsonTree(object[key].toVariant().toString()); } } QString toString() { return string; } bool isObject() { return !object.isEmpty(); } void print() { if (object.isEmpty()) qDebug() << string; else qDebug() << object; } private: QString string; QJsonObject object; }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QByteArray json_bytes = "{\"name\": {\"test\":234},\"str\" : 34,\"enemy\" : \"Loki\"}"; //auto json_doc = QJsonDocument::fromJson(json_bytes); JsonTree tree(json_bytes); qDebug() << tree.isObject(); qDebug() << tree["name"]["test"].isObject(); qDebug() << tree["name"]["test"].toString(); tree["name"].print(); tree["name"]["test"].print(); }
17.414286
89
0.589828
wurui1994
66b1d6d3b8ea244167c0ceea8f4c35246154bd61
1,071
cc
C++
epi/tree_with_parent_inorder.cc
Vasniktel/interview-problems
ab901397194c81debe8c964fca097287466c9c27
[ "MIT" ]
null
null
null
epi/tree_with_parent_inorder.cc
Vasniktel/interview-problems
ab901397194c81debe8c964fca097287466c9c27
[ "MIT" ]
null
null
null
epi/tree_with_parent_inorder.cc
Vasniktel/interview-problems
ab901397194c81debe8c964fca097287466c9c27
[ "MIT" ]
null
null
null
#include <vector> #include "binary_tree_with_parent_prototype.h" #include "test_framework/generic_test.h" using std::vector; vector<int> InorderTraversal(const unique_ptr<BinaryTreeNode<int>>& tree) { if (!tree) return {}; vector<int> result; for (auto node = tree.get();;) { if (node->left) node = node->left.get(); else { while (node && !node->right) { result.push_back(node->data); auto parent = node->parent; while (parent && parent->right.get() == node) { node = parent; parent = node->parent; } node = parent; } if (!node) break; result.push_back(node->data); node = node->right.get(); } } return result; } int main(int argc, char* argv[]) { std::vector<std::string> args{argv + 1, argv + argc}; std::vector<std::string> param_names{"tree"}; return GenericTestMain(args, "tree_with_parent_inorder.cc", "tree_with_parent_inorder.tsv", &InorderTraversal, DefaultComparator{}, param_names); }
26.121951
75
0.594771
Vasniktel
66b67c2affc8a6f7db4583a13eaf253b5d9edb44
943
cpp
C++
BMCP/Coloring.cpp
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
2
2019-11-04T15:09:52.000Z
2022-01-12T05:41:16.000Z
BMCP/Coloring.cpp
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
null
null
null
BMCP/Coloring.cpp
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
1
2020-09-09T12:24:35.000Z
2020-09-09T12:24:35.000Z
// ======================================== // ======= Created by Tomasz Rewak ======== // ======================================== // ==== https://github.com/TomaszRewak ==== // ======================================== #include "Coloring.h" namespace BMCP { size_t Coloring::size() { return genotype.size(); } Coloring::Coloring(Graph& graph) { genotype.resize(graph.nodes.size()); for (size_t i = 0; i < graph.nodes.size(); i++) genotype[i] = std::vector<int>(graph.nodes[i].weight, 0); } void Coloring::sortNode(int i) { std::sort(genotype[i].begin(), genotype[i].end()); } void Coloring::sort() { for (int i = 0; i < genotype.size(); i++) sortNode(i); } std::ostream& operator<<(std::ostream& stream, Coloring& specimen) { for (int i = 0; i < specimen.size(); i++) { stream << (i + 1); for (int g : specimen.genotype[i]) stream << " " << g; stream << std::endl; } return stream; } }
20.955556
69
0.498409
TomaszRewak
66b6c0c945523ad16100001e06698e0eeed87762
3,496
hpp
C++
src/includes/utils.hpp
WillBlack403/ZKP-onehot
42119353c6dfe3970267de1cb53d537854671f14
[ "MIT" ]
null
null
null
src/includes/utils.hpp
WillBlack403/ZKP-onehot
42119353c6dfe3970267de1cb53d537854671f14
[ "MIT" ]
null
null
null
src/includes/utils.hpp
WillBlack403/ZKP-onehot
42119353c6dfe3970267de1cb53d537854671f14
[ "MIT" ]
null
null
null
/*Author: William Black, * Ryan Henry *Email: william.black@ucalgary.ca, * ryan.henry@ucalgary.ca *Date: 2019/06/28 *Project: Proof Of Concept for: There are 10 Types of Vectors (and Polynomials) *File:utils.hpp * Contains function declations of utility functions used in this project. */ #ifndef __horners_hpp__ #define __horners_hpp__ #include<gmpxx.h> #include<NTL/ZZ_p.h> #include<NTL/ZZ_pX.h> extern"C"{ #include<relic/relic_core.h> } #include"pedersen.hpp" #include<vector> using namespace NTL; using namespace std; /* Function: horners_method * * Computes the evaluation of a polynomial with coefficients as commitments, done using horners method for evaluation of polynomials. * * vector<Pedersen_Commitments>: coefficients of the polynomial * size_t: number of coefficients * bn_t: value to evaluate the polynomail at. * * Returns: Pedersen_Commitment to the evaluation. */ Pedersen_Commitment horners_method(vector<Pedersen_Commitment>,size_t,bn_t); /* Function: horners_method * * Computes the evaluation of a polynomial with coefficients in Zp, done using NTL's polynomial evaluation. * * vector<ZZ_p>: coefficients of the polynomial * ZZ_p: Value ot evaluate the polynomial at. * * Return: ZZ_p, the evaluation of the polynomail at set value. */ ZZ_p horners_method(vector<ZZ_p>,ZZ_p); /*Function: multi_exp * * Computes the value defined by commitments[1]^exponents[1]*...*commitment[n]^exponents[n]. * * Pedersen P: Used to create Pedersen_Commitments. * vector<Pederesen_Commitment> commitments: The vector of commitments to be raised to exponents, * vector<ZZ_p> exponents: The vector of ZZ_p used to raise the commitment to. * const uint window_size: The the size of the preoccupation step reasonable values are between [1-8] * * Returns: Result of the computation. */ Pedersen_Commitment multi_exp(Pedersen& P,vector<Pedersen_Commitment> commitments,vector<ZZ_p> exponents, const uint window_size); /*Function: multi_exp_sub -- multi-exponentiation-subcomputation * * Call multi_exp on subsets of the larges computation; this should be used if ram is exceeded. * * const int chunks: number of descrete disjoint subsets to call multiexp on. * * Returns: result */ Pedersen_Commitment multi_exp_sub(Pedersen& P, vector<Pedersen_Commitment> commitments, vector<ZZ_p> exponents,const int window_size, const int chucks); /*Function: conv * * Converts between NTL and RELIC-Toolkit * * bn_t out: Relic big integer * ZZ_p in: NTL big integer subject to prime p */ void conv(bn_t out, ZZ_p in); /*Function: conv * * Converts between NTL and RELIC-Toolkit * * bn_t in: Relic big integer * ZZ_p out: NTL big integer subject to prime p */ void conv(ZZ_p& out, bn_t in); /*Function: conv * * Converts between NTL and RELIC-Toolkit * * bn_t in: Relic big integer * ZZ out: NTL big integer */ void conv(ZZ& out,bn_t in); /* Function: genRandomT * * Creates a random value subject to the defined security parameters. * * uint lambda: desired security such that soundness is 2^{-lambda} * uint bitlength: bitlength=lg(N) such that N is the length of the vector in the ZKP * * Returns: random value. */ ZZ_p genRandomT(uint lambda, uint bitlength); /* Function: genRandom * * Creates random value subject ot defined security parameter * * unint lambda: desired security such that soundness is 2^{-lambda} * * Returns: random value. */ ZZ_p genRandom(uint lambda); #endif
29.880342
152
0.741419
WillBlack403
66ba586ba3c57343ffa3c0dd543a2a312e372c85
2,362
cpp
C++
Sources/Sound/AudioWorld/audio_world.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
248
2015-01-08T05:21:40.000Z
2022-03-20T02:59:16.000Z
Sources/Sound/AudioWorld/audio_world.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
39
2015-01-14T17:37:07.000Z
2022-03-17T12:59:26.000Z
Sources/Sound/AudioWorld/audio_world.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
82
2015-01-11T13:23:49.000Z
2022-02-19T03:17:24.000Z
#include "Sound/precomp.h" #include "API/Sound/AudioWorld/audio_world.h" #include "API/Sound/AudioWorld/audio_object.h" #include "API/Sound/soundbuffer.h" #include "API/Core/Math/cl_math.h" #include "audio_world_impl.h" #include "audio_object_impl.h" namespace clan { AudioWorld::AudioWorld(const ResourceManager &resources) : impl(std::make_shared<AudioWorld_Impl>(resources)) { } void AudioWorld::set_listener(const Vec3f &position, const Quaternionf &orientation) { impl->listener_position = position; impl->listener_orientation = orientation; } bool AudioWorld::is_ambience_enabled() const { return impl->play_ambience; } void AudioWorld::enable_reverse_stereo(bool enable) { impl->reverse_stereo = enable; } bool AudioWorld::is_reverse_stereo_enabled() const { return impl->reverse_stereo; } void AudioWorld::update() { for (auto it = impl->objects.begin(); it != impl->objects.end(); ++it) { impl->update_session(*it); } for (auto it = impl->active_objects.begin(); it != impl->active_objects.end();) { if (it->impl->session.is_playing()) { ++it; } else { it = impl->active_objects.erase(it); } } } ///////////////////////////////////////////////////////////////////////////// AudioWorld_Impl::AudioWorld_Impl(const ResourceManager &resources) : play_ambience(true), reverse_stereo(false), resources(resources) { } AudioWorld_Impl::~AudioWorld_Impl() { } void AudioWorld_Impl::update_session(AudioObject_Impl *obj) { if (obj->attenuation_begin != obj->attenuation_end) { // Calculate volume from distance float distance = obj->position.distance(listener_position); float t = 1.0f - smoothstep(obj->attenuation_begin, obj->attenuation_end, distance); // Calculate pan from ear angle Vec3f sound_direction = Vec3f::normalize(obj->position - listener_position); Vec3f ear_vector = listener_orientation.rotate_vector(Vec3f(1.0f, 0.0f, 0.0f)); float pan = Vec3f::dot(ear_vector, sound_direction); if (reverse_stereo) pan = -pan; // Final volume needs to stay the same no matter the panning direction float volume = (0.5f + std::abs(pan) * 0.5f) * t * obj->volume; obj->session.set_volume(volume); obj->session.set_pan(pan); } else { obj->session.set_volume(obj->volume); obj->session.set_pan(0.0f); } } }
24.350515
87
0.680779
xctan
66bb66a9cf268215f33f68579a760896dacc4bca
7,093
cpp
C++
file_util.cpp
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
2
2020-03-12T19:11:56.000Z
2020-05-01T03:11:03.000Z
file_util.cpp
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
null
null
null
file_util.cpp
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
1
2020-12-11T22:04:56.000Z
2020-12-11T22:04:56.000Z
#include "file_util.h" #include "ifind.h" #include <algorithm> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <string.h> #include <unistd.h> using namespace std; // Return true if the directory exists or if we can // create it. Return false otherwise. bool make_dir(const std::string &m_dirname) { struct stat dir_info; // Read, write and execute for the owner, read-only for all others const mode_t default_mode = S_IRWXU | S_IRGRP | S_IROTH; if(stat(m_dirname.c_str(), &dir_info) != 0){ // Try to create the directory if(mkdir(m_dirname.c_str(), default_mode) != 0){ return false; } return true; } // The path exists, make sure it is a directory if( S_ISDIR(dir_info.st_mode) ){ return true; } return false; } bool is_dir(const std::string &m_dirname) { struct stat dir_info; if(stat(m_dirname.c_str(), &dir_info) != 0){ return false; } // The path exists, make sure it is a directory return S_ISDIR(dir_info.st_mode); } bool is_file(const std::string &m_filename) { struct stat file_info; if(stat(m_filename.c_str(), &file_info) != 0){ return false; } // The path exists, make sure it is a file return S_ISREG(file_info.st_mode); } bool is_path(const string &m_name) { struct stat path_info; if(stat(m_name.c_str(), &path_info) != 0){ return false; } // The path exists, make sure it is a file return ( S_ISDIR(path_info.st_mode) || S_ISREG(path_info.st_mode) ); } size_t file_size(const string &m_filename) { struct stat file_info; if(stat(m_filename.c_str(), &file_info) != 0){ return 0; } // The path exists, make sure it is a file if( S_ISREG(file_info.st_mode) ){ return file_info.st_size; } return 0; } bool find_file_extension(const string &m_path, const char** m_ext) { // For extension matching, we need case-insensitive string matching for(const char** ptr = m_ext;*ptr != NULL;++ptr){ if( find_file_extension(m_path, *ptr) ){ return true; } } return false; } bool find_file_extension(const string &m_path, const char* m_ext) { // For extension matching, we need case-insensitive string matching size_t loc = ifind(m_path, m_ext); if(loc != string::npos){ if( (strlen(m_ext) + loc) == m_path.size() ){ return true; } } return false; } string strip_trailing_path_separator(const string &m_str) { string ret(m_str); // Some older C++ compilers do not have string::pop_back() const size_t init_len = ret.size(); size_t len = init_len; while( (len > 0) && ( ret[len - 1] == PATH_SEPARATOR ) ){ --len; } if(len != init_len){ ret = ret.substr(0, len); } return ret; } bool match_extension(const string &m_input, const string &m_ext) { const size_t len = m_input.size(); const size_t ext_len = m_ext.size(); if(len < ext_len){ return false; } return ( m_input.find(m_ext) == (len - ext_len) ); } size_t count_subdirectories(const string &m_dir) { size_t ret = 0; // Is the input path a directory? struct stat dir_info; if( stat(m_dir.c_str(), &dir_info) != 0){ throw __FILE__ ":count_subdirectories: Unable to stat path"; } // Is this a directory if( !S_ISDIR(dir_info.st_mode) ){ throw __FILE__ ":count_subdirectories: Path is not a directory"; } // Read the contents of the directory DIR *dp = opendir( m_dir.c_str() ); if(dp == NULL){ throw __FILE__ ":count_subdirectories: Unable to open directory for reading"; } struct dirent *d = NULL; while( ( d = readdir(dp) ) ){ // Skip any removed files or diretories if(d->d_ino == 0){ continue; } // Skip the special directories "." and ".." if( (strcmp(d->d_name, ".") == 0) || (strcmp(d->d_name, "..") == 0) ){ continue; } const std::string name = m_dir + PATH_SEPARATOR + d->d_name; if( stat(name.c_str(), &dir_info) != 0){ throw __FILE__ ":count_subdirectories: Unable to stat entry (2)"; } if( S_ISDIR(dir_info.st_mode) ){ ++ret; } } closedir(dp); return ret; } // If the filename has a path separator in it (i.e. "/"), return all characters // *before* the last path separator as the directory and *after* the last path // separator as the filename. pair<string /*dir*/, string /*file*/> split_dir_and_file(const string &m_filename) { const size_t loc = m_filename.find_last_of(PATH_SEPARATOR); if(loc == string::npos){ return pair<string, string>(string("."), m_filename); } return pair<string, string>( m_filename.substr(0, loc), m_filename.substr(loc + 1, m_filename.size() - (loc + 1) ) ); } string parent_dir(const string &m_filename) { return split_dir_and_file(m_filename).first; } // /This/is/an/arbitrary/././example/path/foo.txt // ^^^^^^^ // leaf string leaf_path_name(const string &m_path) { size_t end = m_path.size(); if(end == 0){ throw __FILE__ ":leaf_path_name: Empty path string (1)"; } // Skip any terminal path separators while( (end > 0) && (m_path[end - 1] == PATH_SEPARATOR) ){ --end; } if(end == 0){ throw __FILE__ ":leaf_path_name: Empty path string (2)"; } size_t begin = end - 1; while( (begin > 0) && (m_path[begin - 1] != PATH_SEPARATOR) ){ --begin; } return m_path.substr(begin, end - begin); } // Return true if we were successfull in removing all files and directories, // false otherwise bool remove_all(const string &m_dir) { bool ret = true; FindFiles ff(m_dir); deque<string> del_dir; while( ff.next() ){ if(unlink( ff.name().c_str() ) != 0){ ret = false; } del_dir.push_back( ff.dir() ); } del_dir.push_back(m_dir); // Make the list of directories to delete unique sort( del_dir.begin(), del_dir.end() ); del_dir.erase( unique( del_dir.begin(), del_dir.end() ), del_dir.end() ); sort( del_dir.begin(), del_dir.end(), sort_by_length() ); for(deque<string>::const_reverse_iterator i = del_dir.rbegin();i != del_dir.rend();++i){ if(rmdir( i->c_str() ) != 0){ ret = false; } } return ret; } bool move_files(const string &m_src, const string &m_dst, const bool &m_rm_src) { bool ret = true; FindFiles ff(m_src); while( ff.next() ){ // Use rename to move files. This requires that both the source and destination // directories belong to the same file system. If this ends up being too restrictive, // we will need to use a system call (or write our own using read/write, etc)! const string dst_name = m_dst + PATH_SEPARATOR + split_dir_and_file( ff.name() ).second; if(rename( ff.name().c_str(), dst_name.c_str() ) != 0){ ret = false; } } if(m_rm_src){ if(rmdir( m_src.c_str() ) != 0){ ret = false; } } return ret; } // Create any directories that do not already exist bool create_path(const string &m_path) { size_t loc = 0; while( ( loc = m_path.find(PATH_SEPARATOR, loc) ) != string::npos ){ const string sub_path = m_path.substr(0, loc); if( !is_dir(sub_path) ){ if( !make_dir(sub_path) ){ return false; } } ++loc; } return true; }
20.55942
90
0.649514
LANL-Bioinformatics
66bc56f7df16843d341047d9847c3515a847edd2
2,887
cc
C++
daemon/runtime.cc
cgvarela/memcached
493a2ed939e87d18eb368f17bec5b948701e9d2d
[ "BSD-3-Clause" ]
null
null
null
daemon/runtime.cc
cgvarela/memcached
493a2ed939e87d18eb368f17bec5b948701e9d2d
[ "BSD-3-Clause" ]
null
null
null
daemon/runtime.cc
cgvarela/memcached
493a2ed939e87d18eb368f17bec5b948701e9d2d
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "runtime.h" #include "memcached.h" #include "settings.h" #include "ssl_utils.h" #include <atomic> #include <string> #include <mutex> #include <memcached/openssl.h> static std::atomic<bool> server_initialized; bool is_server_initialized(void) { return server_initialized.load(std::memory_order_acquire); } void set_server_initialized(bool enable) { server_initialized.store(enable, std::memory_order_release); } static std::string ssl_cipher_list; static std::mutex ssl_cipher_list_mutex; void set_ssl_cipher_list(const std::string& list) { std::lock_guard<std::mutex> lock(ssl_cipher_list_mutex); if (list.empty()) { ssl_cipher_list.resize(0); } else { ssl_cipher_list.assign(list); } } void set_ssl_ctx_cipher_list(SSL_CTX *ctx) { std::lock_guard<std::mutex> lock(ssl_cipher_list_mutex); if (ssl_cipher_list.length()) { if (SSL_CTX_set_cipher_list(ctx, ssl_cipher_list.c_str()) == 0) { LOG_WARNING(NULL, "Failed to select any of the " "requested ciphers (%s)", ssl_cipher_list.c_str()); } } } static std::atomic_long ssl_protocol_mask; void set_ssl_protocol_mask(const std::string& mask) { try { ssl_protocol_mask.store(decode_ssl_protocol(mask), std::memory_order_release); if (!mask.empty()) { LOG_NOTICE(nullptr, "Setting SSL minimum protocol to: %s", mask.c_str()); } } catch (std::invalid_argument& e) { LOG_WARNING(nullptr, "Invalid SSL protocol specified: %s", mask.c_str()); } catch (...) { LOG_WARNING(nullptr, "An error occured while decoding the SSL protocol: %s", mask.c_str()); } } void set_ssl_ctx_protocol_mask(SSL_CTX* ctx) { SSL_CTX_set_options(ctx, ssl_protocol_mask.load(std::memory_order_acquire)); } static std::atomic<Audit*> auditHandle { nullptr }; void set_audit_handle(Audit* handle) { auditHandle.store(handle); } Audit* get_audit_handle(void) { return auditHandle.load(std::memory_order_relaxed); }
29.459184
80
0.66124
cgvarela
66bf1efd3a0bed608491a19bc7320a774df752dd
2,732
cpp
C++
RUNETag/WinNTL/tests/LLLTest.cpp
vshesh/RUNEtag
800e93fb7c0560ea5a6261ffc60c02638a8cc8c9
[ "MIT" ]
null
null
null
RUNETag/WinNTL/tests/LLLTest.cpp
vshesh/RUNEtag
800e93fb7c0560ea5a6261ffc60c02638a8cc8c9
[ "MIT" ]
null
null
null
RUNETag/WinNTL/tests/LLLTest.cpp
vshesh/RUNEtag
800e93fb7c0560ea5a6261ffc60c02638a8cc8c9
[ "MIT" ]
null
null
null
#include <NTL/LLL.h> NTL_CLIENT int main() { mat_ZZ B; long s; #if 1 cin >> B; #else long i, j; long n; cerr << "n: "; cin >> n; long m; cerr << "m: "; cin >> m; long k; cerr << "k: "; cin >> k; B.SetDims(n, m); for (i = 1; i <= n; i++) for (j = 1; j <= m; j++) { RandomLen(B(i,j), k); if (RandomBnd(2)) negate(B(i,j), B(i,j)); } #endif mat_ZZ U, B0, B1, B2; B0 = B; double t; ZZ d; B = B0; cerr << "LLL_FP..."; t = GetTime(); s = LLL_FP(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "LLL_QP..."; t = GetTime(); s = LLL_QP(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "LLL_XD..."; t = GetTime(); s = LLL_XD(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "LLL_RR..."; t = GetTime(); s = LLL_RR(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "G_LLL_FP..."; t = GetTime(); s = G_LLL_FP(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "G_LLL_QP..."; t = GetTime(); s = G_LLL_QP(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "G_LLL_XD..."; t = GetTime(); s = G_LLL_XD(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "G_LLL_RR..."; t = GetTime(); s = G_LLL_RR(B, U, 0.99); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); LLL(d, B, 90, 100); if (B1 != B) Error("bad LLLTest (2)"); B = B0; cerr << "LLL..."; t = GetTime(); s = LLL(d, B, U); cerr << (GetTime()-t) << "\n"; mul(B1, U, B0); if (B1 != B) Error("bad LLLTest (1)"); cout << "rank = " << s << "\n"; cout << "det = " << d << "\n"; cout << "B = " << B << "\n"; cout << "U = " << U << "\n"; }
19.514286
50
0.424597
vshesh
66c21c06dc026017e81dd6afcfd53b9af551b1f6
1,147
cpp
C++
lib/io/src/swap.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
lib/io/src/swap.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
lib/io/src/swap.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2018 Sylko Olzscher * */ #include <cyng/io/swap.h> namespace cyng { std::uint16_t swap_num(std::uint16_t val) { return (val << 8) | (val >> 8); } std::int16_t swap_num(std::int16_t val) { return (val << 8) | ((val >> 8) & 0xFF); } std::uint32_t swap_num(std::uint32_t val) { val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF); return (val << 16) | (val >> 16); } std::int32_t swap_num(std::int32_t val) { val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF); return (val << 16) | ((val >> 16) & 0xFFFF); } std::int64_t swap_num(std::int64_t val) { val = ((val << 8) & 0xFF00FF00FF00FF00ULL) | ((val >> 8) & 0x00FF00FF00FF00FFULL); val = ((val << 16) & 0xFFFF0000FFFF0000ULL) | ((val >> 16) & 0x0000FFFF0000FFFFULL); return (val << 32) | ((val >> 32) & 0xFFFFFFFFULL); } std::uint64_t swap_num(std::uint64_t val) { val = ((val << 8) & 0xFF00FF00FF00FF00ULL) | ((val >> 8) & 0x00FF00FF00FF00FFULL); val = ((val << 16) & 0xFFFF0000FFFF0000ULL) | ((val >> 16) & 0x0000FFFF0000FFFFULL); return (val << 32) | (val >> 32); } }
22.94
86
0.571055
solosTec
66c246c4647f2dbd2187208abb958a23893de699
22,785
cpp
C++
rqt_gps_rtk_plugin/src/rqt_gps_rtk_plugin/GpsRtkPlugin.cpp
fm-uulm/ethz_piksi_ros
a228dc3bfb29266897c2bb38bdfb098ac475ffa0
[ "BSD-3-Clause" ]
65
2018-01-03T21:58:56.000Z
2022-03-09T22:02:33.000Z
rqt_gps_rtk_plugin/src/rqt_gps_rtk_plugin/GpsRtkPlugin.cpp
fm-uulm/ethz_piksi_ros
a228dc3bfb29266897c2bb38bdfb098ac475ffa0
[ "BSD-3-Clause" ]
138
2017-11-30T15:46:26.000Z
2022-02-22T06:57:53.000Z
rqt_gps_rtk_plugin/src/rqt_gps_rtk_plugin/GpsRtkPlugin.cpp
fm-uulm/ethz_piksi_ros
a228dc3bfb29266897c2bb38bdfb098ac475ffa0
[ "BSD-3-Clause" ]
86
2017-12-06T19:32:55.000Z
2022-03-29T17:57:26.000Z
#include <rqt_gps_rtk_plugin/GpsRtkPlugin.hpp> #include <rqt_gps_rtk_plugin/GpsRtkPluginThreads.hpp> // Qt #include <QStringList> // std #include <math.h> #include <pthread.h> #include <functional> #include <memory> GpsRtkPlugin::GpsRtkPlugin() : rqt_gui_cpp::Plugin(), widget_(0), timeFirstSampleMovingWindow_(0), wifiCorrectionsAvgHz_(0), numCorrectionsFirstSampleMovingWindow_(0), maxTimeout_(5) { // Constructor is called first before initPlugin function, needless to say. // give QObjects reasonable names setObjectName("GpsRtkPlugin"); } void GpsRtkPlugin::initPlugin(qt_gui_cpp::PluginContext& context) { // access standalone command line arguments QStringList argv = context.argv(); // create QWidget widget_ = new QWidget(); // extend the widget with all attributes and children from UI file ui_.setupUi(widget_); // add widget to the user interface context.addWidget(widget_); readParameters(); initLabels(); initSubscribers(); //Init variables timeFirstSampleMovingWindow_ = ros::Time::now().sec; wifiCorrectionsAvgHz_ = 5; numCorrectionsFirstSampleMovingWindow_ = 0; altitudes_.erase(altitudes_.begin(), altitudes_.end()); // initialize timer ros::NodeHandle nh("~"); timer_ = nh.createTimer(ros::Duration(1.0), std::bind(&GpsRtkPlugin::timerCallback, this, std::placeholders::_1)); //init stamps lastMsgStamps_.setGlobalStamp(ros::Time::now().toSec()); ROS_INFO("[GpsRtkPlugin] Initialized."); } void GpsRtkPlugin::shutdownPlugin() { } void GpsRtkPlugin::saveSettings(qt_gui_cpp::Settings& plugin_settings, qt_gui_cpp::Settings& instance_settings) const { } void GpsRtkPlugin::restoreSettings(const qt_gui_cpp::Settings& plugin_settings, const qt_gui_cpp::Settings& instance_settings) { } void GpsRtkPlugin::readParameters() { getNodeHandle().param<std::string>("piksiReceiverStateTopic", piksiReceiverStateTopic_, "piksi/debug/receiver_state"); ROS_INFO_STREAM( "[GpsRtkPlugin] piksiReceiverStateTopic: " << piksiReceiverStateTopic_); getNodeHandle().param<std::string>("piksiBaselineNedTopic", piksiBaselineNedTopic_, "piksi/baseline_ned"); ROS_INFO_STREAM( "[GpsRtkPlugin] piksiBaselineNedTopic: " << piksiBaselineNedTopic_); getNodeHandle().param<std::string>("piksiWifiCorrectionsTopic", piksiWifiCorrectionsTopic_, "piksi/debug/wifi_corrections"); ROS_INFO_STREAM("[GpsRtkPlugin] piksiWifiCorrectionsTopic: " << piksiWifiCorrectionsTopic_); getNodeHandle().param<std::string>("piksiNavsatfixRtkFixTopic", piksiNavsatfixRtkFixTopic_, "piksi/navsatfix_rtk_fix"); ROS_INFO_STREAM("[GpsRtkPlugin] piksiNavsatfixRtkFixTopic: " << piksiNavsatfixRtkFixTopic_); getNodeHandle().param<std::string>("piksiTimeTopic", piksiTimeTopic_, "piksi/utc_time"); ROS_INFO_STREAM("[GpsRtkPlugin] piksiTimeTopic: " << piksiTimeTopic_); getNodeHandle().param<std::string>("piksiAgeOfCorrectionsTopic", piksiAgeOfCorrectionsTopic_, "piksi/age_of_corrections"); ROS_INFO_STREAM("[GpsRtkPlugin] piksiAgeOfCorrectionsTopic: " << piksiAgeOfCorrectionsTopic_); } void GpsRtkPlugin::initLabels() { // Tab "Status" ui_.label_nodeStatus->setText("N/A"); ui_.label_baseline->setText("N/A"); ui_.label_fixType->setText("N/A"); ui_.label_navsatFixAlt->setText("N/A"); ui_.label_numRtkSatellites->setText("N/A"); ui_.label_numRtkSatellites_indicator->setText(""); ui_.label_numSatellites->setText("N/A"); ui_.label_numWifiCorrections->setText("N/A"); ui_.label_pingBaseStation->setText("N/A"); ui_.label_rateWifiCorrections->setText("N/A"); ui_.label_ageOfCorrections->setText("N/A"); // Tab "Debug" ui_.label_gpsSatellites->setText("N/A"); ui_.label_gpsStrength->setText("N/A"); ui_.label_sbasSatellites->setText("N/A"); ui_.label_sbasStrength->setText("N/A"); ui_.label_glonassSatellites->setText("N/A"); ui_.label_glonassStrength->setText("N/A"); ui_.label_beidouSatellites->setText("N/A"); ui_.label_beidouStrength->setText("N/A"); ui_.label_galileoSatellites->setText("N/A"); ui_.label_galileoStrength->setText("N/A"); ui_.label_ageOfCorrections->setText("N/A"); // Tab UART sniffer ui_.txt_uart->setText("/dev/ttyUSB0"); ui_.txt_uart_data->setText("N/A"); ui_.cmb_uart_rate->addItem("115200", B115200); ui_.cmb_uart_rate->addItem("230400", B230400); ui_.cmb_uart_rate->addItem("921600", B921600); ui_.cmb_uart_rate->addItem("1000000", B1000000); ui_.cmb_uart_rate->addItem("57600", B57600); ui_.cmb_uart_rate->addItem("38400", B38400); ui_.cmb_uart_rate->addItem("9600", B9600); connect(ui_.btn_uart_start, SIGNAL(clicked()), this, SLOT(clickStartUARTButton())); // Tab UDP Sniffer ui_.txt_udp_data->setPlainText("N/A"); connect(ui_.btn_udp_start, SIGNAL(clicked()), this, SLOT(clickStartUDPButton())); } void GpsRtkPlugin::initSubscribers() { piksiReceiverStateSub_ = getNodeHandle().subscribe(piksiReceiverStateTopic_, 10, &GpsRtkPlugin::piksiReceiverStateCb, this); piksiBaselineNedSub_ = getNodeHandle().subscribe(piksiBaselineNedTopic_, 10, &GpsRtkPlugin::piksiBaselineNedCb, this); piksiWifiCorrectionsSub_ = getNodeHandle().subscribe(piksiWifiCorrectionsTopic_, 10, &GpsRtkPlugin::piksiWifiCorrectionsCb, this); piksiNavsatfixRtkFixSub_ = getNodeHandle().subscribe(piksiNavsatfixRtkFixTopic_, 10, &GpsRtkPlugin::piksiNavsatfixRtkFixCb, this); piksiHeartbeatSub_ = getNodeHandle().subscribe(piksiTimeTopic_, 10, &GpsRtkPlugin::piksiTimeCb, this); piksiAgeOfCorrectionsSub_ = getNodeHandle().subscribe(piksiAgeOfCorrectionsTopic_, 10, &GpsRtkPlugin::piksiAgeOfCorrectionsCb, this); } void GpsRtkPlugin::timerCallback(const ros::TimerEvent& e) { double currentStamp = ros::Time::now().toSec(); QString na = QString::fromStdString("N/A"); QString color = QString::fromStdString( "QLabel {background-color: rgb(152, 152, 152); color: rgb(92, 92, 92);}"); if (currentStamp - lastMsgStamps_.receiverStateStamp_ > maxTimeout_) { QMetaObject::invokeMethod(ui_.label_fixType, "setText", Q_ARG(QString, na)); QMetaObject::invokeMethod(ui_.label_fixType, "setStyleSheet", Q_ARG(QString, color)); // Number of satellites QMetaObject::invokeMethod(ui_.label_numSatellites, "setText", Q_ARG(QString, na)); // GPS number of satellites QMetaObject::invokeMethod(ui_.label_gpsSatellites, "setText", Q_ARG(QString, na)); // GPS signal strength QMetaObject::invokeMethod(ui_.label_gpsStrength, "setText", Q_ARG(QString, na)); // SBAS number of satellites QMetaObject::invokeMethod(ui_.label_sbasSatellites, "setText", Q_ARG(QString, na)); // SBAS signal strength QMetaObject::invokeMethod(ui_.label_sbasStrength, "setText", Q_ARG(QString, na)); // GLONASS number of satellites QMetaObject::invokeMethod(ui_.label_glonassSatellites, "setText", Q_ARG(QString, na)); // GLONASS signal strength QMetaObject::invokeMethod(ui_.label_glonassStrength, "setText", Q_ARG(QString, na)); // BEIDOU number of satellites QMetaObject::invokeMethod(ui_.label_beidouSatellites, "setText", Q_ARG(QString, na)); // BEIDOU signal strength QMetaObject::invokeMethod(ui_.label_beidouStrength, "setText", Q_ARG(QString, na)); // GALILEO number of satellites QMetaObject::invokeMethod(ui_.label_galileoSatellites, "setText", Q_ARG(QString, na)); // GALILEO signal strength QMetaObject::invokeMethod(ui_.label_galileoStrength, "setText", Q_ARG(QString, na)); } if (currentStamp - lastMsgStamps_.baselineNedStamp_ > maxTimeout_) { QMetaObject::invokeMethod(ui_.label_numRtkSatellites_indicator, "setText", Q_ARG(QString, na)); QMetaObject::invokeMethod(ui_.label_numRtkSatellites_indicator, "setStyleSheet", Q_ARG(QString, color)); QMetaObject::invokeMethod(ui_.label_baseline, "setText", Q_ARG(QString, na)); } if (currentStamp - lastMsgStamps_.wifiCorrectionsStamp_ > maxTimeout_) { QMetaObject::invokeMethod(ui_.label_numWifiCorrections, "setText", Q_ARG(QString, na)); QMetaObject::invokeMethod(ui_.label_rateWifiCorrections, "setText", Q_ARG(QString, na)); QMetaObject::invokeMethod(ui_.label_pingBaseStation, "setText", Q_ARG(QString, na)); } if (currentStamp - lastMsgStamps_.navsatfixRtkFixStamp_ > maxTimeout_) { QMetaObject::invokeMethod(ui_.label_navsatFixAlt, "setText", Q_ARG(QString, na)); } } void GpsRtkPlugin::piksiReceiverStateCb(const piksi_rtk_msgs::ReceiverState_V2_4_1& msg) { // Type of fix const QString fix_mode = QString::fromStdString(msg.fix_mode); QString color_fix_mode(""); // Choose color for type of fix if (msg.fix_mode == msg.STR_FIX_MODE_INVALID) { color_fix_mode = "QLabel {background-color: rgb(239, 41, 41); color: rgb(92, 92, 92);}"; } else if (msg.fix_mode == msg.STR_FIX_MODE_SPP) { color_fix_mode = "QLabel {background-color: rgb(255, 255, 255); color: rgb(2, 2, 255);}"; } else if (msg.fix_mode == msg.STR_FIX_MODE_DGNSS) { color_fix_mode = "QLabel {background-color: rgb(255, 255, 255); color: rgb(5, 181, 255);}"; } else if (msg.fix_mode == msg.STR_FIX_MODE_FLOAT_RTK) { color_fix_mode = "QLabel {background-color: rgb(255, 138, 138); color: rgb(191, 0, 191);}"; } else if (msg.fix_mode == msg.STR_FIX_MODE_FIXED_RTK) { color_fix_mode = "QLabel {background-color: lime; color: rgb(255, 166, 2);}"; } else if (msg.fix_mode == msg.STR_FIX_MODE_DEAD_RECKONING) { color_fix_mode = "QLabel {background-color: rgb(255, 255, 255); color: rgb(51, 0, 102);}"; } else if (msg.fix_mode == msg.STR_FIX_MODE_SBAS) { color_fix_mode = "QLabel {background-color: rgb(255, 255, 255); color: rgb(43, 255, 223);}"; } else { // Unknown color_fix_mode = "QLabel {background-color: rgb(152, 152, 152); color: rgb(92, 92, 92);}"; } QMetaObject::invokeMethod(ui_.label_fixType, "setText", Q_ARG(QString, fix_mode)); /* * use 'best' available rtk state for the label if (msg.fix_mode == msg.STR_FIX_MODE_SPP or msg.fix_mode == msg.STR_FIX_MODE_SBAS or msg.fix_mode == msg.STR_FIX_MODE_FLOAT_RTK or msg.fix_mode == msg.STR_FIX_MODE_FIXED_RTK) { double currentStamp = ros::Time::now().toSec(); if (currentStamp - lastMsgStamps_.rtkFixStamp_ < 2.0) { color_fix_mode = "QLabel {background-color: lime; color: rgb(255, 166, 2);}"; } else if (currentStamp - lastMsgStamps_.rtkFloatStamp_ < 2.0) { color_fix_mode = "QLabel {background-color: rgb(255, 138, 138); color: rgb(191, 0, 191);}"; } else if (currentStamp - lastMsgStamps_.rtkSbasStamp_ < 2.0) { color_fix_mode = "QLabel {background-color: rgb(255, 255, 255); color: rgb(43, 255, 223);}"; } else { color_fix_mode = "QLabel {background-color: rgb(255, 255, 255); color: rgb(2, 2, 255);}"; } } */ QMetaObject::invokeMethod(ui_.label_fixType, "setStyleSheet", Q_ARG(QString, color_fix_mode)); // Number of satellites QMetaObject::invokeMethod(ui_.label_numSatellites, "setText", Q_ARG(QString, QString::number(msg.num_sat))); // GPS number of satellites QMetaObject::invokeMethod(ui_.label_gpsSatellites, "setText", Q_ARG(QString, QString::number(msg.num_gps_sat))); // GPS signal strength QString signal_strength; vectorToString(scaleSignalStrength(msg.cn0_gps), &signal_strength); QMetaObject::invokeMethod(ui_.label_gpsStrength, "setText", Q_ARG(QString, signal_strength)); // SBAS number of satellites QMetaObject::invokeMethod(ui_.label_sbasSatellites, "setText", Q_ARG(QString, QString::number(msg.num_sbas_sat))); // SBAS signal strength vectorToString(scaleSignalStrength(msg.cn0_sbas), &signal_strength); QMetaObject::invokeMethod(ui_.label_sbasStrength, "setText", Q_ARG(QString, signal_strength)); // GLONASS number of satellites QMetaObject::invokeMethod(ui_.label_glonassSatellites, "setText", Q_ARG(QString, QString::number(msg.num_glonass_sat))); // GLONASS signal strength vectorToString(scaleSignalStrength(msg.cn0_glonass), &signal_strength); QMetaObject::invokeMethod(ui_.label_glonassStrength, "setText", Q_ARG(QString, signal_strength)); // BEIDOU number of satellites QMetaObject::invokeMethod(ui_.label_beidouSatellites, "setText", Q_ARG(QString, QString::number(msg.num_bds_sat))); // BEIDOU signal strength vectorToString(scaleSignalStrength(msg.cn0_bds), &signal_strength); QMetaObject::invokeMethod(ui_.label_beidouStrength, "setText", Q_ARG(QString, signal_strength)); // GALILEO number of satellites QMetaObject::invokeMethod(ui_.label_galileoSatellites, "setText", Q_ARG(QString, QString::number(msg.num_gal_sat))); // GALILEO signal strength vectorToString(scaleSignalStrength(msg.cn0_gal), &signal_strength); QMetaObject::invokeMethod(ui_.label_galileoStrength, "setText", Q_ARG(QString, signal_strength)); //update last msg stamp lastMsgStamps_.receiverStateStamp_ = msg.header.stamp.toSec(); } void GpsRtkPlugin::piksiBaselineNedCb(const piksi_rtk_msgs::BaselineNed& msg) { // Number of satellites used for RTK QMetaObject::invokeMethod(ui_.label_numRtkSatellites, "setText", Q_ARG(QString, QString::number(msg.n_sats))); std::string strStyle; std::string strText; if (msg.n_sats < 5) { strStyle = "QLabel {background-color: red;}"; strText = "bad"; } else if (msg.n_sats >= 5 and msg.n_sats <= 6) { strStyle = "QLabel {background-color: orange;}"; strText = "ok"; } else if (msg.n_sats > 6) { strStyle = "QLabel {background-color: rgb(78, 154, 6);}"; strText = "good"; } QMetaObject::invokeMethod(ui_.label_numRtkSatellites_indicator, "setText", Q_ARG(QString, QString::fromStdString(strText))); QMetaObject::invokeMethod(ui_.label_numRtkSatellites_indicator, "setStyleSheet", Q_ARG(QString, QString::fromStdString(strStyle))); // Baseline NED status double n = msg.n / 1e3; double e = msg.e / 1e3; double d = msg.d / 1e3; QString baseline; // = "[" + QString::fromStdString(std::to_string(roundf(n*100)/100)) + ", " + QString::fromStdString(std::to_string(roundf(e*100)/100)) + ", " + QString::fromStdString(std::to_string(roundf(d*100)/100)) + "]"; baseline.sprintf("[%.2f, %.2f, %.2f]", roundf(n * 100) / 100, roundf(e * 100) / 100, roundf(d * 100) / 100); QMetaObject::invokeMethod(ui_.label_baseline, "setText", Q_ARG(QString, baseline)); //update last msg stamp lastMsgStamps_.baselineNedStamp_ = msg.header.stamp.toSec(); } void GpsRtkPlugin::piksiWifiCorrectionsCb(const piksi_rtk_msgs::InfoWifiCorrections& msg) { // Number of received corrections QMetaObject::invokeMethod(ui_.label_numWifiCorrections, "setText", Q_ARG(QString, QString::number(msg.received_corrections))); // Compute rate corrections double widthTimeWindow = ros::Time::now().sec - timeFirstSampleMovingWindow_; if (widthTimeWindow >= wifiCorrectionsAvgHz_) { int samplesInTimeWindow = msg.received_corrections - numCorrectionsFirstSampleMovingWindow_; double avgCorrectionsHz = samplesInTimeWindow / widthTimeWindow; QMetaObject::invokeMethod(ui_.label_rateWifiCorrections, "setText", Q_ARG(QString, QString::number(std::round(avgCorrectionsHz), 'g', 2))); // reset and start anew numCorrectionsFirstSampleMovingWindow_ = msg.received_corrections; timeFirstSampleMovingWindow_ = ros::Time::now().sec; } // Ping base station QMetaObject::invokeMethod(ui_.label_pingBaseStation, "setText", Q_ARG(QString, QString::number(std::round(msg.latency), 'g', 2))); //update last msg stamp lastMsgStamps_.wifiCorrectionsStamp_ = msg.header.stamp.toSec(); } void GpsRtkPlugin::piksiNavsatfixRtkFixCb(const sensor_msgs::NavSatFix& msg) { altitudes_.push_back(msg.altitude); double altitudeAvg = 0; for (std::vector<double>::iterator it = altitudes_.begin(); it != altitudes_.end(); it++) { altitudeAvg += *it; } altitudeAvg /= altitudes_.size(); QString text; text.sprintf("%.2f", altitudeAvg); QMetaObject::invokeMethod(ui_.label_navsatFixAlt, "setText", Q_ARG(QString, text)); //update last msg stamp lastMsgStamps_.navsatfixRtkFixStamp_ = msg.header.stamp.toSec(); } void GpsRtkPlugin::piksiTimeCb(const piksi_rtk_msgs::UtcTimeMulti& msg) { //std::string time; QString time; time.sprintf("%02d:%02d:%02d", msg.hours, msg.minutes, msg.seconds); //time = std::to_string(msg.hours) + ":" + std::to_string(msg.minutes) + ":" + std::to_string(msg.seconds); QMetaObject::invokeMethod(ui_.label_nodeStatus, "setText", Q_ARG(QString, time)); } void GpsRtkPlugin::piksiAgeOfCorrectionsCb(const piksi_rtk_msgs::AgeOfCorrections& msg) { double age_of_corrections = msg.age / 10.0; QString text; text.sprintf("%.1f", age_of_corrections); QMetaObject::invokeMethod(ui_.label_ageOfCorrections, "setText", Q_ARG(QString, text)); } void GpsRtkPlugin::clickStartUARTButton() { if (!uart_thread_) { uart_thread_.reset(new UARTThread()); // no make_unique in this c++ ver. connect(uart_thread_.get(), &UARTThread::resultReady, this, &GpsRtkPlugin::uartResultsHandler); } if (uart_thread_->isRunning()) { uart_thread_->stop(); ui_.btn_uart_start->setText("Start"); } else { uart_thread_->setPort(ui_.txt_uart->displayText().toUtf8().constData(), ui_.cmb_uart_rate->currentData().toUInt()); uart_thread_->start(); ui_.btn_uart_start->setText("Stop"); } } void GpsRtkPlugin::clickStartUDPButton() { if (!udp_thread_) { udp_thread_.reset(new UDPThread()); // no make_unique in this c++ ver. connect(udp_thread_.get(), &UDPThread::resultReady, this, &GpsRtkPlugin::udpResultsHandler); } if (udp_thread_->isRunning()) { udp_thread_->stop(); ui_.btn_udp_start->setText("Start"); } else { udp_thread_->start(); ui_.btn_udp_start->setText("Stop"); } } void GpsRtkPlugin::uartResultsHandler(const QString& data) { ui_.txt_uart_data->setText(data); // in case an error happens. if (!uart_thread_->isRunning()) { ui_.btn_uart_start->setText("Start"); } } void GpsRtkPlugin::udpResultsHandler(const QString& data) { ui_.txt_udp_data->setPlainText(data); if (!udp_thread_->isRunning()) { ui_.btn_udp_start->setText("Start"); } } /*bool hasConfiguration() const { return true; } void triggerConfiguration() { // Usually used to open a dialog to offer the user a set of configuration }*/ #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(GpsRtkPlugin, rqt_gui_cpp::Plugin)
39.903678
226
0.592188
fm-uulm
66c338b089efe6c614fb526cd5fa0e7984738317
51
cpp
C++
src/RefCore/Var.cpp
sppp/TheoremProver
efd583bc78e8fa93f6946def5f6af77001d01763
[ "BSD-3-Clause" ]
null
null
null
src/RefCore/Var.cpp
sppp/TheoremProver
efd583bc78e8fa93f6946def5f6af77001d01763
[ "BSD-3-Clause" ]
null
null
null
src/RefCore/Var.cpp
sppp/TheoremProver
efd583bc78e8fa93f6946def5f6af77001d01763
[ "BSD-3-Clause" ]
null
null
null
#include "RefCore.h" namespace RefCore { }
8.5
21
0.607843
sppp
66c889f150ecfffe511b6cd69f485e795db892a1
1,342
cpp
C++
server/homeserver/network/json/JsonApi.Core.cpp
williamkoehler/home-server
ce99af73ea2e53fea3939fe0c4442433e65ac670
[ "MIT" ]
1
2021-07-05T21:11:59.000Z
2021-07-05T21:11:59.000Z
server/homeserver/network/json/JsonApi.Core.cpp
williamkoehler/home-server
ce99af73ea2e53fea3939fe0c4442433e65ac670
[ "MIT" ]
null
null
null
server/homeserver/network/json/JsonApi.Core.cpp
williamkoehler/home-server
ce99af73ea2e53fea3939fe0c4442433e65ac670
[ "MIT" ]
null
null
null
#include "JsonApi.hpp" #include "../../Core.hpp" #include "../../tools/EMail.hpp" namespace server { // Core void JsonApi::BuildJsonSettings(const Ref<User>& user, rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator) { assert(output.IsObject()); // Core settings { rapidjson::Value coreJson = rapidjson::Value(rapidjson::kObjectType); Ref<Core> core = Core::GetInstance(); assert(core != nullptr); boost::lock_guard lock(core->mutex); coreJson.AddMember("name", rapidjson::Value(core->name.c_str(), core->name.size(), allocator), allocator); output.AddMember("core", coreJson, allocator); } // EMail settings { rapidjson::Value emailJson = rapidjson::Value(rapidjson::kObjectType); Ref<EMail> email = EMail::GetInstance(); assert(email != nullptr); boost::lock_guard lock(email->mutex); rapidjson::Value recipientListJson = rapidjson::Value(rapidjson::kArrayType); for (std::string& recipient : email->recipients) recipientListJson.PushBack(rapidjson::Value(recipient.c_str(), recipient.size(), allocator), allocator); emailJson.AddMember("recipients", recipientListJson, allocator); output.AddMember("email", emailJson, allocator); } // User settings { //rapidjson::Value userJson = rapidjson::Value(rapidjson::kObjectType); } } }
24.851852
128
0.697466
williamkoehler
66c9e7bb67a6e27cfea4b72d827ad9fc7ce1b116
6,210
cpp
C++
src/base/ossimCsvFile.cpp
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
src/base/ossimCsvFile.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
src/base/ossimCsvFile.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
#include <ossim/base/ossimCsvFile.h> #include <iostream> #include <iterator> static const ossim_uint32 DEFAULT_BUFFER_SIZE = 1024; ossim_int32 ossimCsvFile::INVALID_INDEX = -1; static std::istream& csvSkipWhiteSpace(std::istream& in) { int c = in.peek(); while(!in.fail()&& ( (c == ' ')||(c == '\t')||(c == '\n')||(c == '\r') ) ) { in.ignore(1); c = in.peek(); } return in; } ossimCsvFile::Record::Record(ossimCsvFile* csvFile) :theCsvFile(csvFile) { } bool ossimCsvFile::Record::valueAt(const ossimString& fieldName, ossimString& value)const { bool result = false; if(theCsvFile) { ossim_int32 idx = theCsvFile->indexOfField(fieldName); if((idx > 0)&&(idx < (ossim_int32)theValues.size())) { value = theValues[idx]; result = true; } } return result; } bool ossimCsvFile::Record::valueAt(ossim_uint32 idx, ossimString& value)const { bool result = false; if(idx < theValues.size()) { value = theValues[idx]; result = true; } return result; } ossimString& ossimCsvFile::Record::operator [](const ossimString& fieldName) { if(theCsvFile) { ossim_int32 idx = theCsvFile->indexOfField(fieldName); if((idx >= 0)&&(idx < (ossim_int32)theValues.size())) { return theValues[idx]; } } return theDummyValue; } const ossimString& ossimCsvFile::Record::operator [](const ossimString& fieldName)const { if(theCsvFile) { ossim_int32 idx = theCsvFile->indexOfField(fieldName); if((idx >= 0)&&(idx < (ossim_int32)theValues.size())) { return theValues[idx]; } } return theDummyValue; } ossimString& ossimCsvFile::Record::operator [](ossim_uint32 idx) { if(idx < theValues.size()) { return theValues[idx]; } return theDummyValue; } const ossimString& ossimCsvFile::Record::operator [](ossim_uint32 idx)const { if(idx < theValues.size()) { return theValues[idx]; } return theDummyValue; } ossimCsvFile::ossimCsvFile(const ossimString& separatorList) :theInputStream(0), theSeparatorList(separatorList), theOpenFlag(false) { } ossimCsvFile::~ossimCsvFile() { close(); } bool ossimCsvFile::readCsvLine(std::istream& inStream, ossimCsvFile::StringListType& tokens)const { tokens.clear(); bool done = false; char c; const char quote = '\"'; bool inQuotedString = false; bool inDoubleQuote = false; ossimString currentToken; inStream >> csvSkipWhiteSpace; while(!done&&inStream.get(c)&&inStream.good()) { if(c > 0x7e ) { return false; } if((c!='\n')&& (c!='\r')) { // check to see if we are quoted and check to see if double quoted if(c == quote) { // check if at a double quote if(inStream.peek() == quote) { currentToken += quote; inStream.ignore(1); if(!inDoubleQuote) { inDoubleQuote = true; } else { inDoubleQuote = false; } } else { if(!inQuotedString) { inQuotedString = true; } else { inQuotedString = false; } } } // if we are at a separator then check to see if we are inside a quoted string else if(theSeparatorList.contains(c)) { // ignore token separator if quoted if(inQuotedString||inDoubleQuote) { currentToken += c; } else { // push the current token. currentToken = currentToken.trim(); tokens.push_back(currentToken); currentToken = ""; inStream >> csvSkipWhiteSpace; } } else { currentToken += c; } } else if(!inQuotedString||inDoubleQuote) { currentToken = currentToken.trim(); tokens.push_back(currentToken); done = true; } else { currentToken += c; } } return (inStream.good()&&(tokens.size()>0)); } bool ossimCsvFile::open(const ossimFilename& file, const ossimString& flags) { close(); if((*flags.begin()) == 'r') { theInputStream = new std::ifstream(file.c_str(), std::ios::in|std::ios::binary); theOpenFlag = true; theRecordBuffer = new ossimCsvFile::Record(this); } else { return theOpenFlag; } return theOpenFlag; } bool ossimCsvFile::readHeader() { if(theOpenFlag) { theFieldHeaderList.clear(); return readCsvLine(*theInputStream, theFieldHeaderList); } return false; } void ossimCsvFile::close() { if(theOpenFlag) { theFieldHeaderList.clear(); if(theInputStream) { delete theInputStream; theInputStream = 0; } theOpenFlag = false; theRecordBuffer = 0; } } ossimRefPtr<ossimCsvFile::Record> ossimCsvFile::nextRecord() { if(!theOpenFlag) return ossimRefPtr<ossimCsvFile::Record>(0); if(theFieldHeaderList.empty()) { if(!readHeader()) { return ossimRefPtr<ossimCsvFile::Record>(); } } if(!readCsvLine(*theInputStream, theRecordBuffer->values())) { return ossimRefPtr<ossimCsvFile::Record>(); } return theRecordBuffer; } const ossimCsvFile::StringListType& ossimCsvFile::fieldHeaderList()const { return theFieldHeaderList; } ossim_int32 ossimCsvFile::indexOfField(const ossimString& fieldName)const { ossim_int32 result = ossimCsvFile::INVALID_INDEX; ossim_uint32 idx = 0; for(;idx < theFieldHeaderList.size(); ++idx) { if(theFieldHeaderList[idx] == fieldName) { result = (ossim_int32)idx; break; } } return result; }
22.099644
87
0.554267
vladislav-horbatiuk
66cb1a9278851d2d9dc166e3c1f28165679a8dbc
309
hpp
C++
r0 - hardware testing code/src/aqua_inputs.hpp
Tassany/projeto_aquaponia_fablab
1973b9a74fd929ac445f95d1dda4cf0381c0c1cf
[ "MIT" ]
null
null
null
r0 - hardware testing code/src/aqua_inputs.hpp
Tassany/projeto_aquaponia_fablab
1973b9a74fd929ac445f95d1dda4cf0381c0c1cf
[ "MIT" ]
null
null
null
r0 - hardware testing code/src/aqua_inputs.hpp
Tassany/projeto_aquaponia_fablab
1973b9a74fd929ac445f95d1dda4cf0381c0c1cf
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <SPI.h> #include <aqua_pins.hpp> uint8_t aqua_inputs() { digitalWrite(AQ_PIN_PL, true); SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE2)); uint8_t data = SPI.transfer(0); SPI.endTransaction(); digitalWrite(AQ_PIN_PL, false); return data; }
23.769231
68
0.705502
Tassany
66cbb6525540e5091d6eb0ed00a16e7753948acc
10,463
cc
C++
src/vt/vrt/collection/balance/stats_restart_reader.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
26
2019-11-26T08:36:15.000Z
2022-02-15T17:13:21.000Z
src/vt/vrt/collection/balance/stats_restart_reader.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
1,215
2019-09-09T14:31:33.000Z
2022-03-30T20:20:14.000Z
src/vt/vrt/collection/balance/stats_restart_reader.cc
rbuch/vt
74c2e0cae3201dfbcbfda7644c354703ddaed6bb
[ "BSD-3-Clause" ]
12
2019-09-08T00:03:05.000Z
2022-02-23T21:28:35.000Z
/* //@HEADER // ***************************************************************************** // // stats_restart_reader.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // 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 copyright holder nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #if !defined INCLUDED_VT_VRT_COLLECTION_BALANCE_STATS_RESTART_READER_CC #define INCLUDED_VT_VRT_COLLECTION_BALANCE_STATS_RESTART_READER_CC #include "vt/config.h" #include "vt/vrt/collection/balance/stats_restart_reader.h" #include "vt/objgroup/manager.h" #include "vt/vrt/collection/balance/stats_data.h" #include "vt/utils/json/json_reader.h" #include "vt/utils/json/decompression_input_container.h" #include "vt/utils/json/input_iterator.h" #include <cinttypes> #include <nlohmann/json.hpp> namespace vt { namespace vrt { namespace collection { namespace balance { void StatsRestartReader::setProxy( objgroup::proxy::Proxy<StatsRestartReader> in_proxy ) { proxy_ = in_proxy; } /*static*/ std::unique_ptr<StatsRestartReader> StatsRestartReader::construct() { auto ptr = std::make_unique<StatsRestartReader>(); auto proxy = theObjGroup()->makeCollective<StatsRestartReader>(ptr.get()); proxy.get()->setProxy(proxy); return ptr; } void StatsRestartReader::startup() { auto const file_name = theConfig()->getLBStatsFileIn(); readStats(file_name); } std::vector<ElementIDType> const& StatsRestartReader::getMoveList(PhaseType phase) const { vtAssert(proc_move_list_.size() > phase, "Phase must exist"); return proc_move_list_.at(phase); } void StatsRestartReader::clearMoveList(PhaseType phase) { if (proc_move_list_.size() > phase) { proc_move_list_.at(phase).clear(); } } bool StatsRestartReader::needsLB(PhaseType phase) const { if (proc_phase_runs_LB_.size() > phase) { return proc_phase_runs_LB_.at(phase); } else { return false; } } std::deque<std::vector<ElementIDType>> const& StatsRestartReader::getMigrationList() const { return proc_move_list_; } std::deque<std::set<ElementIDType>> StatsRestartReader::readIntoElementHistory( StatsData const& sd ) { std::deque<std::set<ElementIDType>> element_history; for (PhaseType phase = 0; phase < sd.node_data_.size(); phase++) { std::set<ElementIDType> buffer; for (auto const& obj : sd.node_data_.at(phase)) { if (obj.first.isMigratable()) { buffer.insert(obj.first.id); } } element_history.emplace_back(std::move(buffer)); } return element_history; } void StatsRestartReader::readStatsFromStream(std::stringstream stream) { using vt::util::json::DecompressionInputContainer; using vt::vrt::collection::balance::StatsData; using json = nlohmann::json; auto c = DecompressionInputContainer( DecompressionInputContainer::AnyStreamTag{}, std::move(stream) ); json j = json::parse(c); auto sd = StatsData(j); auto element_history = readIntoElementHistory(sd); constructMoveList(std::move(element_history)); } void StatsRestartReader::readStats(std::string const& fileName) { // Read the input files auto elements_history = inputStatsFile(fileName); constructMoveList(std::move(elements_history)); } void StatsRestartReader::constructMoveList( std::deque<std::set<ElementIDType>> element_history ) { if (element_history.empty()) { vtWarn("No element history provided"); return; } auto const num_iters = element_history.size() - 1; proc_move_list_.resize(num_iters); proc_phase_runs_LB_.resize(num_iters, true); if (theContext()->getNode() == 0) { msgsReceived.resize(num_iters, 0); totalMove.resize(num_iters); } // Communicate the migration information createMigrationInfo(element_history); } std::deque<std::set<ElementIDType>> StatsRestartReader::inputStatsFile(std::string const& fileName) { using vt::util::json::Reader; using vt::vrt::collection::balance::StatsData; Reader r{fileName}; auto json = r.readFile(); auto sd = StatsData(*json); return readIntoElementHistory(sd); } void StatsRestartReader::createMigrationInfo( std::deque<std::set<ElementIDType>>& element_history ) { const auto num_iters = element_history.size() - 1; const auto myNodeID = static_cast<ElementIDType>(theContext()->getNode()); for (size_t ii = 0; ii < num_iters; ++ii) { auto& elms = element_history[ii]; auto& elmsNext = element_history[ii + 1]; std::set<ElementIDType> diff; std::set_difference(elmsNext.begin(), elmsNext.end(), elms.begin(), elms.end(), std::inserter(diff, diff.begin())); const size_t qi = diff.size(); const size_t pi = elms.size() - (elmsNext.size() - qi); auto& myList = proc_move_list_[ii]; myList.reserve(3 * (pi + qi) + 1); //--- Store the iteration number myList.push_back(static_cast<ElementIDType>(ii)); //--- Store partial migration information (i.e. nodes moving in) for (auto iEle : diff) { myList.push_back(iEle); //--- permID to receive myList.push_back(no_element_id); // node moving from myList.push_back(myNodeID); // node moving to } diff.clear(); //--- Store partial migration information (i.e. nodes moving out) std::set_difference(elms.begin(), elms.end(), elmsNext.begin(), elmsNext.end(), std::inserter(diff, diff.begin())); for (auto iEle : diff) { myList.push_back(iEle); //--- permID to send myList.push_back(myNodeID); // node migrating from myList.push_back(no_element_id); // node migrating to } // // Create a message storing the vector // proxy_[0].send<VecMsg, &StatsRestartReader::gatherMsgs>(myList); // // Clear old distribution of elements // elms.clear(); } } void StatsRestartReader::gatherMsgs(VecMsg *msg) { auto sentVec = msg->getTransfer(); vtAssert(sentVec.size() % 3 == 1, "Expecting vector of length 3n+1"); ElementIDType const phaseID = sentVec[0]; // // --- Combine the different pieces of information // msgsReceived[phaseID] += 1; auto& migrate = totalMove[phaseID]; for (size_t ii = 1; ii < sentVec.size(); ii += 3) { auto const permID = sentVec[ii]; auto const nodeFrom = static_cast<NodeType>(sentVec[ii + 1]); auto const nodeTo = static_cast<NodeType>(sentVec[ii + 2]); auto iptr = migrate.find(permID); if (iptr == migrate.end()) { migrate.insert(std::make_pair(permID, std::make_pair(nodeFrom, nodeTo))); } else { auto &nodePair = iptr->second; nodePair.first = std::max(nodePair.first, nodeFrom); nodePair.second = std::max(nodePair.second, nodeTo); } } // // --- Check whether all the messages have been received // const NodeType numNodes = theContext()->getNumNodes(); if (msgsReceived[phaseID] < static_cast<std::size_t>(numNodes)) return; // //--- Distribute the information when everything has been received // size_t const header = 2; for (NodeType in = 0; in < numNodes; ++in) { size_t iCount = 0; for (auto iNode : migrate) { if (iNode.second.first == in) iCount += 1; } std::vector<ElementIDType> toMove(2 * iCount + header); iCount = 0; toMove[iCount++] = phaseID; toMove[iCount++] = static_cast<ElementIDType>(migrate.size()); for (auto iNode : migrate) { if (iNode.second.first == in) { toMove[iCount++] = iNode.first; toMove[iCount++] = static_cast<ElementIDType>(iNode.second.second); } } if (in > 0) { proxy_[in].send<VecMsg, &StatsRestartReader::scatterMsgs>(toMove); } else { proc_phase_runs_LB_[phaseID] = (!migrate.empty()); auto& myList = proc_move_list_[phaseID]; myList.resize(toMove.size() - header); std::copy(&toMove[header], toMove.data() + toMove.size(), myList.begin()); } } migrate.clear(); } void StatsRestartReader::scatterMsgs(VecMsg *msg) { const size_t header = 2; auto recvVec = msg->getTransfer(); vtAssert((recvVec.size() -header) % 2 == 0, "Expecting vector of length 2n+2"); //--- Get the iteration number associated with the message const ElementIDType phaseID = recvVec[0]; //--- Check whether some migration will be done proc_phase_runs_LB_[phaseID] = static_cast<bool>(recvVec[1] > 0); auto &myList = proc_move_list_[phaseID]; if (!proc_phase_runs_LB_[phaseID]) { myList.clear(); return; } //--- Copy the migration information myList.resize(recvVec.size() - header); std::copy(&recvVec[header], recvVec.data()+recvVec.size(), myList.begin()); } }}}} /* end namespace vt::vrt::collection::balance */ #endif /*INCLUDED_VT_VRT_COLLECTION_BALANCE_STATS_RESTART_READER_CC*/
34.531353
81
0.684985
rbuch
66cc0f3b846b4a8720da090292c610a1779841ca
6,876
cc
C++
lite/kernels/arm/box_coder_compute.cc
shentanyue/Paddle-Lite
c6baab724c9047c3e9809db3fc24b7a2b5ca26a2
[ "Apache-2.0" ]
1
2022-01-27T07:34:50.000Z
2022-01-27T07:34:50.000Z
lite/kernels/arm/box_coder_compute.cc
shentanyue/Paddle-Lite
c6baab724c9047c3e9809db3fc24b7a2b5ca26a2
[ "Apache-2.0" ]
1
2021-05-26T05:19:38.000Z
2021-05-26T05:19:38.000Z
lite/kernels/arm/box_coder_compute.cc
shentanyue/Paddle-Lite
c6baab724c9047c3e9809db3fc24b7a2b5ca26a2
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle 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 "lite/kernels/arm/box_coder_compute.h" #include <algorithm> #include <string> #include <vector> #include "lite/backends/arm/math/funcs.h" #ifdef ENABLE_ARM_FP16 #include "lite/backends/arm/math/fp16/box_coder_fp16.h" #endif namespace paddle { namespace lite { namespace kernels { namespace arm { void BoxCoderCompute::Run() { auto& param = Param<operators::BoxCoderParam>(); auto* prior_box = param.prior_box; auto* prior_box_var = param.prior_box_var; auto* target_box = param.target_box; auto* output_box = param.proposals; std::vector<float> variance = param.variance; std::string code_type = param.code_type; bool normalized = param.box_normalized; auto row = target_box->dims()[0]; auto col = prior_box->dims()[0]; if (code_type == "decode_center_size") { col = target_box->dims()[1]; } auto len = prior_box->dims()[1]; // 4 output_box->Resize({row, col, len}); // N x M x 4 auto* output = output_box->mutable_data<float>(); auto axis = param.axis; const float* target_box_data = target_box->data<float>(); const float* prior_box_data = prior_box->data<float>(); bool var_len4 = false; int var_size = 0; const float* variance_data; if (prior_box_var != nullptr) { var_size = 2; variance_data = prior_box_var->data<float>(); var_len4 = false; } else { var_size = 1; variance_data = param.variance.data(); var_len4 = true; } if (code_type == "encode_center_size") { lite::arm::math::encode_bbox_center_kernel(row, target_box_data, prior_box_data, variance_data, var_len4, col, output); } else if (code_type == "decode_center_size") { if (axis == 0) { lite::arm::math::decode_bbox_center_kernel(row, target_box_data, prior_box_data, variance_data, var_len4, col, normalized, output); } else { auto prior_box_var_data = prior_box_var ? prior_box_var->data<float>() : nullptr; lite::arm::math::decode_center_size_axis_1(var_size, row, col, len, target_box_data, prior_box_data, prior_box_var_data, normalized, variance, output); } } else { LOG(FATAL) << "box_coder don't support this code_type: " << code_type; } } #ifdef ENABLE_ARM_FP16 void BoxCoderFp16Compute::Run() { auto& param = Param<operators::BoxCoderParam>(); auto* prior_box = param.prior_box; auto* prior_box_var = param.prior_box_var; auto* target_box = param.target_box; auto* output_box = param.proposals; std::vector<float16_t> variance(param.variance.size()); std::transform(param.variance.begin(), param.variance.end(), variance.begin(), [](float x) { return static_cast<float16_t>(x); }); std::string code_type = param.code_type; bool normalized = param.box_normalized; auto row = target_box->dims()[0]; auto col = prior_box->dims()[0]; if (code_type == "decode_center_size") { col = target_box->dims()[1]; } auto len = prior_box->dims()[1]; output_box->Resize({row, col, len}); auto* output = output_box->mutable_data<float16_t>(); const float16_t* loc_data = target_box->data<float16_t>(); const float16_t* prior_data = prior_box->data<float16_t>(); const float16_t* variance_data; bool var_len4 = false; if (param.prior_box_var != nullptr) { variance_data = prior_box_var->data<float16_t>(); var_len4 = false; } else { variance_data = variance.data(); var_len4 = true; } lite::arm::math::fp16::decode_bboxes(row, param.axis, loc_data, prior_data, variance_data, var_len4, code_type, normalized, col, output); } #endif } // namespace arm } // namespace kernels } // namespace lite } // namespace paddle #ifdef ENABLE_ARM_FP16 REGISTER_LITE_KERNEL(box_coder, kARM, kFP16, kNCHW, paddle::lite::kernels::arm::BoxCoderFp16Compute, def) .BindInput("PriorBox", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))}) .BindInput("PriorBoxVar", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))}) .BindInput("TargetBox", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))}) .BindOutput("OutputBox", {LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))}) .Finalize(); #endif // ENABLE_ARM_FP16 REGISTER_LITE_KERNEL(box_coder, kARM, kFloat, kNCHW, paddle::lite::kernels::arm::BoxCoderCompute, def) .BindInput("PriorBox", {LiteType::GetTensorTy(TARGET(kARM))}) .BindInput("PriorBoxVar", {LiteType::GetTensorTy(TARGET(kARM))}) .BindInput("TargetBox", {LiteType::GetTensorTy(TARGET(kARM))}) .BindOutput("OutputBox", {LiteType::GetTensorTy(TARGET(kARM))}) .Finalize();
36.967742
75
0.528069
shentanyue
66cd92d9c1b1ace237ff434e25da5c806856994f
17,832
cc
C++
third_party/blink/renderer/core/exported/prerendering_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/exported/prerendering_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/exported/prerendering_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <functional> #include <list> #include <memory> #include "base/memory/ptr_util.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/common/prerender/prerender_rel_type.h" #include "third_party/blink/public/mojom/prerender/prerender.mojom-blink.h" #include "third_party/blink/public/platform/web_cache.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/web/web_frame.h" #include "third_party/blink/public/web/web_prerenderer_client.h" #include "third_party/blink/public/web/web_script_source.h" #include "third_party/blink/public/web/web_view.h" #include "third_party/blink/public/web/web_view_client.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/node_traversal.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/html_element_type_helpers.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" namespace blink { namespace { class TestWebPrerendererClient : public WebPrerendererClient { public: TestWebPrerendererClient() = default; virtual ~TestWebPrerendererClient() = default; private: bool IsPrefetchOnly() override { return false; } }; class MockPrerender : public mojom::blink::PrerenderHandle { public: explicit MockPrerender( mojom::blink::PrerenderAttributesPtr attributes, mojo::PendingRemote<mojom::blink::PrerenderHandleClient> client, mojo::PendingReceiver<mojom::blink::PrerenderHandle> handle) : attributes_(std::move(attributes)), client_(std::move(client)), receiver_(this, std::move(handle)) {} ~MockPrerender() override = default; const KURL& Url() const { return attributes_->url; } uint32_t RelTypes() const { return attributes_->rel_types; } // Returns the number of times |Cancel| was called. size_t CancelCount() const { return cancel_count_; } // Returns the number of times |Abandon| was called. size_t AbandonCount() const { return abandon_count_; } // Used to simulate state changes of the mock prerendered web page. These // calls spin the message loop so that the client's receiver side gets a // chance to run. void NotifyDidStartPrerender() { client_->OnPrerenderStart(); test::RunPendingTasks(); } void NotifyDidSendDOMContentLoadedForPrerender() { client_->OnPrerenderDomContentLoaded(); test::RunPendingTasks(); } void NotifyDidSendLoadForPrerender() { client_->OnPrerenderStopLoading(); test::RunPendingTasks(); } void NotifyDidStopPrerender() { client_->OnPrerenderStop(); test::RunPendingTasks(); } // mojom::blink::PrerenderHandle implementation void Cancel() override { cancel_count_++; } void Abandon() override { abandon_count_++; } private: mojom::blink::PrerenderAttributesPtr attributes_; mojo::Remote<mojom::blink::PrerenderHandleClient> client_; mojo::Receiver<mojom::blink::PrerenderHandle> receiver_; size_t cancel_count_ = 0; size_t abandon_count_ = 0; }; class MockPrerenderProcessor : public mojom::blink::PrerenderProcessor { public: MockPrerenderProcessor() = default; ~MockPrerenderProcessor() override = default; // Returns the number of times |AddPrerender| was called. size_t AddCount() const { return add_count_; } std::unique_ptr<MockPrerender> ReleasePrerender() { std::unique_ptr<MockPrerender> rv; if (!prerenders_.empty()) { rv = std::move(prerenders_.front()); prerenders_.pop(); } return rv; } void Bind(mojo::ScopedMessagePipeHandle message_pipe_handle) { receiver_set_.Add(this, mojo::PendingReceiver<mojom::blink::PrerenderProcessor>( std::move(message_pipe_handle))); } // mojom::blink::PrerenderProcessor implementation void AddPrerender( mojom::blink::PrerenderAttributesPtr attributes, mojo::PendingRemote<mojom::blink::PrerenderHandleClient> client, mojo::PendingReceiver<mojom::blink::PrerenderHandle> handle) override { prerenders_.push(std::make_unique<MockPrerender>( std::move(attributes), std::move(client), std::move(handle))); add_count_++; } private: mojo::ReceiverSet<mojom::blink::PrerenderProcessor> receiver_set_; std::queue<std::unique_ptr<MockPrerender>> prerenders_; size_t add_count_ = 0; }; class PrerenderingTest : public testing::Test { public: ~PrerenderingTest() override { if (web_view_helper_.GetWebView()) UnregisterMockPrerenderProcessor(); url_test_helpers::UnregisterAllURLsAndClearMemoryCache(); } void Initialize(const char* base_url, const char* file_name) { // TODO(crbug.com/751425): We should use the mock functionality // via |web_view_helper_|. url_test_helpers::RegisterMockedURLLoadFromBase( WebString::FromUTF8(base_url), blink::test::CoreTestDataPath(), WebString::FromUTF8(file_name)); web_view_helper_.Initialize(); web_view_helper_.GetWebView()->SetPrerendererClient(&prerenderer_client_); web_view_helper_.LocalMainFrame() ->GetFrame() ->GetBrowserInterfaceBroker() .SetBinderForTesting( mojom::blink::PrerenderProcessor::Name_, WTF::BindRepeating(&MockPrerenderProcessor::Bind, WTF::Unretained(&mock_prerender_processor_))); frame_test_helpers::LoadFrame( web_view_helper_.GetWebView()->MainFrameImpl(), std::string(base_url) + file_name); } void NavigateAway() { frame_test_helpers::LoadFrame( web_view_helper_.GetWebView()->MainFrameImpl(), "about:blank"); test::RunPendingTasks(); } void Close() { UnregisterMockPrerenderProcessor(); web_view_helper_.LocalMainFrame()->CollectGarbageForTesting(); web_view_helper_.Reset(); WebCache::Clear(); test::RunPendingTasks(); } Element& Console() { Document* document = web_view_helper_.LocalMainFrame()->GetFrame()->GetDocument(); Element* console = document->getElementById("console"); DCHECK(IsA<HTMLUListElement>(console)); return *console; } unsigned ConsoleLength() { return Console().CountChildren() - 1; } WebString ConsoleAt(unsigned i) { DCHECK_GT(ConsoleLength(), i); Node* item = NodeTraversal::ChildAt(Console(), 1 + i); DCHECK(item); DCHECK(IsA<HTMLLIElement>(item)); DCHECK(item->hasChildren()); return item->textContent(); } void ExecuteScript(const char* code) { web_view_helper_.LocalMainFrame()->ExecuteScript( WebScriptSource(WebString::FromUTF8(code))); test::RunPendingTasks(); } TestWebPrerendererClient* PrerendererClient() { return &prerenderer_client_; } MockPrerenderProcessor* PrerenderProcessor() { return &mock_prerender_processor_; } private: void UnregisterMockPrerenderProcessor() { web_view_helper_.LocalMainFrame() ->GetFrame() ->GetBrowserInterfaceBroker() .SetBinderForTesting(mojom::blink::PrerenderProcessor::Name_, {}); } TestWebPrerendererClient prerenderer_client_; MockPrerenderProcessor mock_prerender_processor_; frame_test_helpers::WebViewHelper web_view_helper_; }; } // namespace TEST_F(PrerenderingTest, SinglePrerender) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(KURL("http://prerender.com/"), prerender->Url()); EXPECT_EQ(static_cast<unsigned>(kPrerenderRelTypePrerender), prerender->RelTypes()); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); prerender->NotifyDidStartPrerender(); EXPECT_EQ(1u, ConsoleLength()); EXPECT_EQ("webkitprerenderstart", ConsoleAt(0)); prerender->NotifyDidSendDOMContentLoadedForPrerender(); EXPECT_EQ(2u, ConsoleLength()); EXPECT_EQ("webkitprerenderdomcontentloaded", ConsoleAt(1)); prerender->NotifyDidSendLoadForPrerender(); EXPECT_EQ(3u, ConsoleLength()); EXPECT_EQ("webkitprerenderload", ConsoleAt(2)); prerender->NotifyDidStopPrerender(); EXPECT_EQ(4u, ConsoleLength()); EXPECT_EQ("webkitprerenderstop", ConsoleAt(3)); } TEST_F(PrerenderingTest, CancelPrerender) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); ExecuteScript("removePrerender()"); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(1u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); } TEST_F(PrerenderingTest, AbandonPrerender) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); NavigateAway(); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(1u, prerender->AbandonCount()); // Check that the prerender does not emit an extra cancel when // garbage-collecting everything. Close(); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(1u, prerender->AbandonCount()); } TEST_F(PrerenderingTest, TwoPrerenders) { Initialize("http://www.foo.com/", "prerender/multiple_prerenders.html"); std::unique_ptr<MockPrerender> first_prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(first_prerender); EXPECT_EQ(KURL("http://first-prerender.com/"), first_prerender->Url()); std::unique_ptr<MockPrerender> second_prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(first_prerender); EXPECT_EQ(KURL("http://second-prerender.com/"), second_prerender->Url()); EXPECT_EQ(2u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, first_prerender->CancelCount()); EXPECT_EQ(0u, first_prerender->AbandonCount()); EXPECT_EQ(0u, second_prerender->CancelCount()); EXPECT_EQ(0u, second_prerender->AbandonCount()); first_prerender->NotifyDidStartPrerender(); EXPECT_EQ(1u, ConsoleLength()); EXPECT_EQ("first_webkitprerenderstart", ConsoleAt(0)); second_prerender->NotifyDidStartPrerender(); EXPECT_EQ(2u, ConsoleLength()); EXPECT_EQ("second_webkitprerenderstart", ConsoleAt(1)); } TEST_F(PrerenderingTest, TwoPrerendersRemovingFirstThenNavigating) { Initialize("http://www.foo.com/", "prerender/multiple_prerenders.html"); std::unique_ptr<MockPrerender> first_prerender = PrerenderProcessor()->ReleasePrerender(); std::unique_ptr<MockPrerender> second_prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_EQ(2u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, first_prerender->CancelCount()); EXPECT_EQ(0u, first_prerender->AbandonCount()); EXPECT_EQ(0u, second_prerender->CancelCount()); EXPECT_EQ(0u, second_prerender->AbandonCount()); ExecuteScript("removeFirstPrerender()"); EXPECT_EQ(2u, PrerenderProcessor()->AddCount()); EXPECT_EQ(1u, first_prerender->CancelCount()); EXPECT_EQ(0u, first_prerender->AbandonCount()); EXPECT_EQ(0u, second_prerender->CancelCount()); EXPECT_EQ(0u, second_prerender->AbandonCount()); NavigateAway(); EXPECT_EQ(2u, PrerenderProcessor()->AddCount()); EXPECT_EQ(1u, first_prerender->CancelCount()); EXPECT_EQ(0u, first_prerender->AbandonCount()); EXPECT_EQ(0u, second_prerender->CancelCount()); EXPECT_EQ(1u, second_prerender->AbandonCount()); } TEST_F(PrerenderingTest, TwoPrerendersAddingThird) { Initialize("http://www.foo.com/", "prerender/multiple_prerenders.html"); std::unique_ptr<MockPrerender> first_prerender = PrerenderProcessor()->ReleasePrerender(); std::unique_ptr<MockPrerender> second_prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_EQ(2u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, first_prerender->CancelCount()); EXPECT_EQ(0u, first_prerender->AbandonCount()); EXPECT_EQ(0u, second_prerender->CancelCount()); EXPECT_EQ(0u, second_prerender->AbandonCount()); ExecuteScript("addThirdPrerender()"); std::unique_ptr<MockPrerender> third_prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_EQ(3u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, first_prerender->CancelCount()); EXPECT_EQ(0u, first_prerender->AbandonCount()); EXPECT_EQ(0u, second_prerender->CancelCount()); EXPECT_EQ(0u, second_prerender->AbandonCount()); EXPECT_EQ(0u, third_prerender->CancelCount()); EXPECT_EQ(0u, third_prerender->AbandonCount()); } TEST_F(PrerenderingTest, ShortLivedClient) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); NavigateAway(); Close(); // This test passes if this next line doesn't crash. prerender->NotifyDidStartPrerender(); } TEST_F(PrerenderingTest, FastRemoveElement) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); // Race removing & starting the prerender against each other, as if the // element was removed very quickly. ExecuteScript("removePrerender()"); prerender->NotifyDidStartPrerender(); // The page should be totally disconnected from the Prerender at this point, // so the console should not have updated. EXPECT_EQ(0u, ConsoleLength()); } TEST_F(PrerenderingTest, MutateTarget) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(KURL("http://prerender.com/"), prerender->Url()); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); // Change the href of this prerender, make sure this is treated as a remove // and add. ExecuteScript("mutateTarget()"); std::unique_ptr<MockPrerender> mutated_prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_EQ(KURL("http://mutated.com/"), mutated_prerender->Url()); EXPECT_EQ(2u, PrerenderProcessor()->AddCount()); EXPECT_EQ(1u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); EXPECT_EQ(0u, mutated_prerender->CancelCount()); EXPECT_EQ(0u, mutated_prerender->AbandonCount()); } TEST_F(PrerenderingTest, MutateRel) { Initialize("http://www.foo.com/", "prerender/single_prerender.html"); std::unique_ptr<MockPrerender> prerender = PrerenderProcessor()->ReleasePrerender(); EXPECT_TRUE(prerender); EXPECT_EQ(KURL("http://prerender.com/"), prerender->Url()); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(0u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); // Change the rel of this prerender, make sure this is treated as a remove. ExecuteScript("mutateRel()"); EXPECT_EQ(1u, PrerenderProcessor()->AddCount()); EXPECT_EQ(1u, prerender->CancelCount()); EXPECT_EQ(0u, prerender->AbandonCount()); } } // namespace blink
35.310891
80
0.737775
sarang-apps
66cdc42eaeffa61eb5f56d5a8dcdc6272bf062c7
3,438
hpp
C++
Kernel/include/generic_symbolicator_factory.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Kernel/include/generic_symbolicator_factory.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Kernel/include/generic_symbolicator_factory.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
#ifndef FLAPJACKOS_COMMON_INCLUDE_GENERIC_SYMBOLICATOR_FACTORY_HPP #define FLAPJACKOS_COMMON_INCLUDE_GENERIC_SYMBOLICATOR_FACTORY_HPP #include <symbolicator.hpp> #include <hardware_memory_management_unit.hpp> #include <multiboot.h> #include <common/elf.hpp> #include <common/vector.hpp> #include <common/logger.hpp> template<typename ElfSectionHeader, typename ElfSymbol> class GenericSymbolicatorFactory { public: GenericSymbolicatorFactory(HardwareMemoryManagementUnit& mmu, multiboot_info_t* mb_info) : mmu_(mmu), mb_info_(mb_info), shdr_table_count_(0), shdr_table_(nullptr) { assert(mb_info); } Symbolicator make_symbolicator() { multiboot_elf_section_header_table_t& elf_sec = mb_info_->u.elf_sec; assert(sizeof(ElfSectionHeader) == elf_sec.size); shdr_table_count_ = elf_sec.num; shdr_table_ = new ElfSectionHeader[shdr_table_count_]; ElfSectionHeader* shdr_table = get_shdr_pointer(elf_sec.addr); memmove(shdr_table_, shdr_table, elf_sec.num * elf_sec.size); register_all_symbols(); return std::move(symbolicator_); } protected: virtual bool is_elf_symbol_a_function(const ElfSymbol& elf_symbol) = 0; private: HardwareMemoryManagementUnit& mmu_; multiboot_info_t* mb_info_; size_t shdr_table_count_; ElfSectionHeader* shdr_table_; Symbolicator symbolicator_; ElfSectionHeader* get_shdr_pointer(uintptr_t physical_address) { return reinterpret_cast<ElfSectionHeader*>(mmu_.convert_physical_to_logical_address(physical_address)); } void register_all_symbols() { auto& shdr = get_symbol_table_shdr(); const ElfSymbol* elf_symbols = reinterpret_cast<const ElfSymbol*>(mmu_.convert_physical_to_logical_address(shdr.sh_addr)); for (size_t i = 0, n = (shdr.sh_size / sizeof(ElfSymbol)); i < n; ++i){ const ElfSymbol& elf_symbol = elf_symbols[i]; if (is_elf_symbol_a_function(elf_symbol)) { register_elf_symbol(elf_symbol); } } } const ElfSectionHeader& get_symbol_table_shdr() { return get_shdr_of_type(Elf::SHT_SYMTAB); } const ElfSectionHeader& get_shdr_of_type(unsigned type) { const ElfSectionHeader* shdr = &shdr_table_[0]; for (size_t i = 0; i < shdr_table_count_; ++i) { if (shdr_table_[i].sh_type == type) { shdr = &shdr_table_[i]; break; } } return *shdr; } void register_elf_symbol(const ElfSymbol& elf_symbol) { assert(is_elf_symbol_a_function(elf_symbol)); Symbolicator::Symbol symbol_to_register; symbol_to_register.address = elf_symbol.st_value; symbol_to_register.name = SharedPointer(strdup(get_string(elf_symbol.st_name))); symbolicator_.register_symbol(symbol_to_register); } const char* get_string(size_t index) { return get_string_table() + index; } const char* get_string_table() { auto& shdr = get_string_table_shdr(); return reinterpret_cast<const char*>(mmu_.convert_physical_to_logical_address(shdr.sh_addr)); } const ElfSectionHeader& get_string_table_shdr() { return get_shdr_of_type(Elf::SHT_STRTAB); } }; #endif // FLAPJACKOS_COMMON_INCLUDE_GENERIC_SYMBOLICATOR_FACTORY_HPP
32.742857
130
0.690809
foxostro
66ce205f534e4c27baf0fd5499fe0227fcbd0125
806
cpp
C++
ICPC_Mirrors/Nitc_9.0/nwerc2019all/gnollhypothesis/submissions/accepted/bjarki_n2.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_9.0/nwerc2019all/gnollhypothesis/submissions/accepted/bjarki_n2.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
ICPC_Mirrors/Nitc_9.0/nwerc2019all/gnollhypothesis/submissions/accepted/bjarki_n2.cpp
Shahraaz/CP_P_S5
b068ad02d34338337e549d92a14e3b3d9e8df712
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i,a,b) for (auto i=(a); i<(b); ++i) #define iter(it,c) for (auto it = (c).begin(); it != (c).end(); ++it) typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef long long ll; const int INF = 2147483647; long double bin(int n, int k) { if (k > n) return 0; long double res = 1.0; rep(i,1,k+1) { res = res * (n - (k - i)) / i; } return res; } int main() { int n, k; cin >> n >> k; vector<double> p(n); rep(i,0,n) cin >> p[i]; rep(i,0,n) { long double s = p[i] * bin(n-1,k-1); rep(j,1,n) { s += p[(i+n-j)%n] * bin(n-1-j,k-1); } cout << setprecision(12) << s / bin(n,k) << endl; } return 0; }
20.15
69
0.496278
Shahraaz
66cf9089ab7fe6895fd8c6c6cf77830b0ef44b51
2,298
cpp
C++
EpicForceTools/bin2c/main.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
1
2021-03-30T06:28:32.000Z
2021-03-30T06:28:32.000Z
EpicForceTools/bin2c/main.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
null
null
null
EpicForceTools/bin2c/main.cpp
MacgyverLin/MagnumEngine
975bd4504a1e84cb9698c36e06bd80c7b8ced0ff
[ "MIT" ]
null
null
null
// bin2c.c // // convert a binary file into a C source vector // // THE "BEER-WARE LICENSE" (Revision 3.1415): // sandro AT sigala DOT it wrote this file. As long as you retain this notice you can do // whatever you want with this stuff. If we meet some day, and you think this stuff is // worth it, you can buy me a beer in return. Sandro Sigala // // syntax: bin2c [-c] [-z] <input_file> <output_file> // // -c add the "const" keyword to definition // -z terminate the array with a zero (useful for embedded C strings) // // examples: // bin2c -c myimage.png myimage_png.cpp // bin2c -z sometext.txt sometext_txt.cpp #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef PATH_MAX #define PATH_MAX 1024 #endif int useconst = 0; int zeroterminated = 0; int myfgetc(FILE *f) { int c = fgetc(f); if (c == EOF && zeroterminated) { zeroterminated = 0; return 0; } return c; } void process(const char *ifname, const char *ofname) { FILE *ifile, *ofile; ifile = fopen(ifname, "rb"); if (ifile == NULL) { fprintf(stderr, "cannot open %s for reading\n", ifname); exit(1); } ofile = fopen(ofname, "wb"); if (ofile == NULL) { fprintf(stderr, "cannot open %s for writing\n", ofname); exit(1); } char buf[PATH_MAX], *p; const char *cp; if ((cp = strrchr(ifname, '/')) != NULL) { ++cp; } else { if ((cp = strrchr(ifname, '\\')) != NULL) ++cp; else cp = ifname; } strcpy(buf, cp); for (p = buf; *p != '\0'; ++p) { if (!isalnum(*p)) *p = '_'; } fprintf(ofile, "static %sunsigned char %s[] = {\n", useconst ? "const " : "", buf); int c, col = 1; while ((c = myfgetc(ifile)) != EOF) { if (col >= 78 - 6) { fputc('\n', ofile); col = 1; } fprintf(ofile, "0x%.2x, ", c); col += 6; } fprintf(ofile, "\n};\n"); fclose(ifile); fclose(ofile); } void usage(void) { fprintf(stderr, "usage: bin2c [-cz] <input_file> <output_file>\n"); exit(1); } int main(int argc, char **argv) { while (argc > 3) { if (!strcmp(argv[1], "-c")) { useconst = 1; --argc; ++argv; } else if (!strcmp(argv[1], "-z")) { zeroterminated = 1; --argc; ++argv; } else { usage(); } } if (argc != 3) { usage(); } process(argv[1], argv[2]); return 0; }
18.836066
88
0.578329
MacgyverLin
66d0c623ced4a3cdc08098f980bdcbe61dd1de4f
15,962
cpp
C++
c++/Date/Date/date.cpp
daviddicken/data-structures-and-algorithms
9d56194aaf6b8ceed048c5cdd646b4c3e59b1dfe
[ "MIT" ]
1
2020-12-11T22:31:52.000Z
2020-12-11T22:31:52.000Z
c++/Date/Date/date.cpp
daviddicken/data-structures-and-algorithms
9d56194aaf6b8ceed048c5cdd646b4c3e59b1dfe
[ "MIT" ]
19
2020-10-20T05:29:37.000Z
2021-02-24T22:06:53.000Z
c++/Date/Date/date.cpp
daviddicken/data-structures-and-algorithms
9d56194aaf6b8ceed048c5cdd646b4c3e59b1dfe
[ "MIT" ]
1
2020-09-14T19:07:39.000Z
2020-09-14T19:07:39.000Z
/* Filename: Date (Chapter 5 Programming Project 7) Author: David Dicken Description: This is a program that takes a date input from the user and outputs what day off the week it falls on Date last modified: 2/6/16 Algorithm: get date from user (has to be a pass by refernce function named getInput) write switch statement functions for month codes and century codes write a function to calculate year code write a function that uses year code month code and calander date to figure a day code write a function to test if year is a leap year if it is and month is jan or feb then subtract 1 from day code write a function that takes the day code and runs it through a switch statment to determine what day of the week */ #include<iostream> #include<string> using namespace std; // Function calls void getInput (int& day, int& month, int& year); // Input: empty variable to be changed to user input. Output variables with user input int dayCode (int day); // Input: day int between 1-31. Output daycode int monthCode (int month); // Input: month int between 1-12 Output: monthcode int yearcode (int year); // Input: year int between 100 - 9999 Output: yearcode int leapYear (int year, int month); // Input year int between 100-9999 and month int between 1-12. Output: Leapyear 0 if no or -1 if yes int calculate (int dayNum, int monthNum, int yearNum, int leapYear); // Input: daycode, monthcode, yearcode, and leapyear // Output: int between 0-6 representing a day of the week string whatDay (int weekNum); // Input: int between 0-6 representing a day of the week. Output: string with day of week spelled out void output(int month, int day, int year, string dayOfweek);// input: date user originally enter (int month 1-12, day 1-41, year 100-9999) // and a string with day of week. Output: cout to user int centuryCode (int century); // Input: century code (int between 1 - 99) Output: year cade (int 5,3,1, or 0) // Program Main int main() { int dayIn(0), monthIn(0), yearIn(0), dayNum(0), monthNum(0), yearNum(0), leapNum(0), weekNum(0); string dayOfweek(" "); getInput (dayIn, monthIn, yearIn); dayNum = dayCode (dayIn); monthNum = monthCode (monthIn); yearNum = yearcode (yearIn); leapNum = leapYear (yearIn, monthIn); weekNum = calculate (dayNum, monthNum, yearNum, leapNum); dayOfweek = whatDay (weekNum); output(monthIn, dayIn, yearIn, dayOfweek); return 0; } //**************************************************************** // FUNCTIONS //**************************************************************** //********************* Get Input Function************************ // Input: int day, month, and year variables // Output: int day, month and year variables are changed by function to users input // Algorithm: input day, month and year variables // ask user for a date between 1/1/100 and 12/31/9999 // test to make sure user entered a valid date // pass user input to programs variables //**************************************************************** void getInput (int& day, int& month, int& year) { #include<iostream> using namespace std; const int MONTHSnYEAR(12),minMONTH(1), minDAY(1), DAYSnMONTH(31), minYEAR(100), maxYEAR(9999); char valid('f'); while(valid == 'f') { cout << "Welcome to the What Day Is It program. \n" << "You give me a date and I'll tell you what day of the week it falls on. \n\n" << "Please enter a date between " << minMONTH << " " << minDAY << " " << minYEAR << " and " << MONTHSnYEAR << " " << DAYSnMONTH << " " << maxYEAR << endl << "in mm dd yyyy format: \n \n" << "Please just use a space between month and day, and between day and year. \n"; cin >> month; cin >> day; cin >> year; // Test if user entered a valid date if(month <= MONTHSnYEAR && month >= minMONTH) { if(day <= DAYSnMONTH && day >= minDAY) { if(year >= minYEAR && year <= maxYEAR) { valid = 't'; } } } else { cout << "Invalid Date. \n"; } } } //********************* Day Code Function ************************ // Input: day (calender date from user int between 1 - 31) // Output: day code ( int between 0 - 6) // Algorithm: Input day date entered by user // Mod the day date by the numer of days in a week for day code // return day code //**************************************************************** int dayCode (int day) { const int DAYSnWEEK(7); day = day % DAYSnWEEK; return(day); } //********************* Month Code Function ********************** // Input: month (int between 1 - 12) // Output: month code (int between 0-6) // Algorithm: input month // write variable to hold month code // write a switch statement determine what month it is // change month code variable to hold proper value depending on what month it is // return month code //**************************************************************** int monthCode (int month) { int mc(0); switch(month) { case 1: mc = 6; break; case 2: mc = 2; break; case 3: mc = 2; break; case 4: mc = 5; break; case 5: mc = 0; break; case 6: mc = 3; break; case 7: mc = 5; break; case 8: mc = 1; break; case 9: mc = 4; break; case 10: mc = 6; break; case 11: mc = 2; break; case 12: mc = 4; break; default: break; } return(mc); } //********************* Year code Function *********************** // Input: year (int entered by user between 100 - 9999) // Output: year code (int 5,3,1, or 0) // Alorithm: input year enter by user // write variables to hold output, century, year code(from century switch), and last 2 digits of year // divide year by 100 to get the century // run century through switch statement // assign proper value to year code variable // mod year to seperate the last two digits // return (last two digits of year % 7) + (last two digits / 4) + year code from century switch //**************************************************************** int yearcode (int year) { const int MODby(7), DIVby(4); int output(0), yc(0), century(0),twoDigit(0); century = year / 100; twoDigit = year % 100; yc = centuryCode(century); output = (twoDigit % MODby) + (twoDigit / DIVby) + yc; return(output); } //********************* Leap Year Function *********************** // Input: int year between 100 - 9999 and int month between 1 - 12 // Output: int 0 or -1 // Algorithm: Input year and month that user entered // write constants for moding every 4 years and moding every 400 years // write constant for days to subtract -1 (DAYSlost) // check to see if the month is either jan or feb // if yes divide year by 100 // if that number is 0 check and see if year can be divided by 400 evenly // if so change days DAyslost to -1 // else if that num was not a 0 and can be divided by 4 evenly // change DAYSlost to -1 // return days lost //**************************************************************** int leapYear (int year, int month) { const int LEAPYEAR(4), LEAPhundreds(400), DAYSlost(-1); int output(0), digits(0); if(month == 1 || month == 2) { digits = year / 100; if(digits == 0) { if(year % LEAPhundreds == 0) { output = DAYSlost; } } else if(digits % LEAPYEAR == 0) { output = DAYSlost; } } return(output); } //********************* Calculate Function *********************** // Input: day code (int between 0 - 6), month code (int between 0-6), year code (int 5,3,1, or 0), leap year (int 0, or -1) // Output: int between 0-6 that represents what day of the week // Algorithm: input daycode, monthcode, yearcode, and leapyear // write a constant for days in a week // write variable for output // add daycode, monthcode, yearcode, and leapyear together // mod that number by days in a week (7) // return that number //**************************************************************** int calculate (int dayNum, int monthNum, int yearNum, int leapYear) { const int DAYSnWEEK(7); int output(0); output = dayNum + monthNum + yearNum + leapYear; output = output % DAYSnWEEK; return(output); } //********************* What Day Function ************************ // Input: int between 0 -6 // Output: string name of day that matches the inout number // Algorithm: Input number from calculation function // make string variable to hold the day of the week // write a switch statement to determine what day of the week if is // change string variable to hold day of the week // return day of the week string //**************************************************************** string whatDay (int weekNum) { #include<string> string day(" "); switch(weekNum) { case 0: day = " Sunday "; break; case 1: day = " Monday "; break; case 2: day = " Tuesday "; break; case 3: day = " Wednesday "; break; case 4: day = " Thursday "; break; case 5: day = " Friday "; break; case 6: day = " Saturday "; break; default: break; } return(day); } //********************* Output Function ************************** //Input: month (int between 1 -12), day (int between 1 -31), year (int between 100 - 9999), string (day of the week) // Output: cout a string // Algorithm: cout date entered by user and what day it falls on //**************************************************************** void output(int month, int day, int year, string dayOfweek) { #include<iostream> #include<string> using namespace std; cout << "\n" << month << "/" << day << "/" << year << " falls on a " << dayOfweek << endl; } //********************* Century Code ***************************** // Input: 1 or 2 digit century int between 1 - 99 // Output: century code (int 5, 3, 1, 0) // Algorithm: get century digits from the year code function // create a variable to hold year code // run through a rediculously long switch statement to find out what the year code for century is // (I know there is a pattern here and I probably could have come up with a math equation to do // this for me. But I have spent over 20 hrs this week on homework for this class and // I am falling behind on homework for my other classes) // return year code //**************************************************************** int centuryCode (int century) { int yc(0); century = century % 4; switch(century) { case 1: yc = 5; // 29 % 4 = 1 == yc 5 ---> 1 % 4 = 1 break; case 2: yc = 3; //30 % 4 = 2 == yc 3 ---> 2 % 4 = 2 break; case 3: yc = 1; // 31 % 4 = 3 == yc 1 ---> 3 % 4 = 3 break; case 4: yc = 0; // 28 % 4 = 0 = yc = 0 break; // case 5: // yc = 5; // break; // case 6: // yc = 3; // break; // case 7: // yc = 1; // break; // case 8: // yc = 0; // break; // case 9: // yc = 5; // break; // case 10: // yc = 3; // break; // case 11: // yc = 1; // break; // case 12: // yc = 0; // break; // case 13: // yc = 5; // break; // case 14: // yc = 3; // break; // case 15: // yc = 1; // break; // case 16: // yc = 0; // break; // case 17: // yc = 5; // break; // case 18: // yc = 3; // break; // case 19: // yc = 1; // break; // case 20: // yc = 0; // break; // case 21: // yc = 5; // break; // case 22: // yc = 3; // 22%4 = 2 ==yc3 // break; // case 23: // yc = 1; // break; // case 24: // yc = 0; // break; // case 25: // yc = 5; // break; // case 26: // yc = 3; // break; // case 27: // yc = 1; // break; // case 28: // 28 % 4 = 0 = yc = 0 // yc = 0; // break; // case 29: // yc = 5; // 29 % 4 = 1 == yc 5 // break; // case 30: //30 % 4 = 2 == yc 3 // yc = 3; // break; // case 31: // 31 % 4 = 3 == yc 1 // yc = 1; // break; // case 32: // yc = 0; // break; // case 33: // yc = 5; // break; // case 34: // yc = 3; // mod 4 =2 yc=3 // break; // case 35: // yc = 1; // break; // case 36: // yc = 0; // break; // case 37: // yc = 5; // mod 4 = 1 // break; // case 38: // yc = 3; // break; // case 39: // mod 4 = 3 // yc = 1; // break; // case 40: // yc = 0; // break; // case 41: // yc = 5; // break; // case 42: // yc = 3; // break; // case 43: // yc = 1; // break; // case 44: // yc = 0; // break; // case 45: // yc = 5; // break; // case 46: // yc = 3; // break; // case 47: // yc = 1; // break; // case 48: // yc = 0; // break; // case 49: // yc = 5; // break; // case 50: // yc = 3; // break; // case 51: // yc = 1; // break; // case 52: // yc = 0; // break; // case 53: // yc = 5; // break; // case 54: // yc = 3; // break; // case 55: // yc = 1; // break; // case 56: // yc = 0; // break; // case 57: // yc = 5; // break; // case 58: // yc = 3; // break; // case 59: // yc = 1; // break; // case 60: // yc = 0; // break; // case 61: // yc = 5; // break; // case 62: // yc = 3; // break; // case 63: // yc = 1; // break; // case 64: // yc = 0; // break; // case 65: // yc = 5; // break; // case 66: // yc = 3; // break; // case 67: // yc = 1; // break; // case 68: // yc = 0; // break; // case 69: // yc = 5; // break; // case 70: // yc = 3; // break; // case 71: // yc = 1; // break; // case 72: // yc = 0; // break; // case 73: // yc = 5; // break; // case 74: // yc = 3; // break; // case 75: // yc = 1; // break; // case 76: // yc = 0; // break; // case 77: // yc = 5; // break; // case 78: // yc = 3; // break; // case 79: // yc = 1; // break; // case 80: // yc = 0; // break; // case 81: // yc = 5; // break; // case 82: // yc = 3; // break; // case 83: // yc = 1; // break; // case 84: // yc = 0; // break; // case 85: // yc = 5; // break; // case 86: // yc = 3; // break; // case 87: // yc = 1; // break; // case 88: // yc = 0; // break; // case 89: // yc = 5; // break; // case 90: // yc = 3; // break; // case 91: // yc = 1; // break; // case 92: // yc = 0; // break; // case 93: // yc = 5; // break; // case 94: // yc = 3; // break; // case 95: // yc = 1; // break; // case 96: // yc = 0; // break; // case 97: // yc = 5; // break; // case 98: //mod 4 = 2 yc==3 // yc = 3; // break; // case 99: // yc = 1; // break; // default: // break; } return(yc); }
24.785714
139
0.480328
daviddicken
66d1495d6e7c9674a7968bce91ca036371a3116a
1,756
cc
C++
all-nodes-distance-k-in-binary-tree.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
all-nodes-distance-k-in-binary-tree.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
all-nodes-distance-k-in-binary-tree.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include <vector> class Solution { public: void travel_down(TreeNode *start, int k, std::vector<int> &res) { if (!start) return; if (!k) res.push_back(start->val); else { travel_down(start->left, k - 1, res); travel_down(start->right, k - 1, res); } } void find(TreeNode *node, TreeNode *target, int &k, bool &has_find, std::vector<int> &res) { if (!node) return; if (node == target) { has_find = true; travel_down(node, k, res); k--; return; } find(node->left, target, k, has_find, res); if (has_find) { if (k > 0) travel_down(node->right, k - 1, res); else if (!k) res.push_back(node->val); k--; return; } find(node->right, target, k, has_find, res); if (has_find) { if (k > 0) travel_down(node->left, k - 1, res); else if (!k) res.push_back(node->val); k--; return; } } std::vector<int> distanceK(TreeNode *root, TreeNode *target, int k) { std::vector<int> res; bool has_find = false; find(root, target, k, has_find, res); return res; } };
21.95
94
0.460706
ArCan314
66d159a07d7c1db5a2034ce136cf06dddcbb6e11
5,967
cpp
C++
test/collision/vector.cpp
neboat/cilktools
7065c4f3281f133f2fd1a2e94b83c7326396ef7e
[ "MIT" ]
3
2017-01-30T22:44:33.000Z
2021-03-06T16:37:18.000Z
test/collision/vector.cpp
neboat/cilktools
7065c4f3281f133f2fd1a2e94b83c7326396ef7e
[ "MIT" ]
null
null
null
test/collision/vector.cpp
neboat/cilktools
7065c4f3281f133f2fd1a2e94b83c7326396ef7e
[ "MIT" ]
5
2015-06-17T14:12:11.000Z
2017-10-19T12:17:19.000Z
//========================================================================// // Copyright 1994 (Unpublished Material) // // SolidWorks Inc. // //========================================================================// // // File Name: vector.cpp // // Application: Math/Geometry utilities // // Contents: methods for classes for simple 3d geometry elements // //========================================================================// // Include this set first to get PCH efficiency #define MATHGEOM_FILE #include "stdafx.h" // end pch efficiency set static const mgVector_c NullVec( 0, 0, 0 ); mgVector_c::mgVector_c( double x, double y, double z ) { iComp[0] = x; iComp[1] = y; iComp[2] = z; } mgVector_c::mgVector_c( const double v[ 3 ] ) { iComp[0] = v[0]; iComp[1] = v[1]; iComp[2] = v[2]; } mgVector_c::mgVector_c( ) { iComp[0] = 0.0; iComp[1] = 0.0; iComp[2] = 0.0; } mgVector_c::mgVector_c( const mgVector_c& v ) { iComp[0] = (v.iComp)[0]; iComp[1] = (v.iComp)[1]; iComp[2] = (v.iComp)[2]; } mgVector_c const& mgVector_c::operator=(const mgVector_c& v) { iComp[0] = (v.iComp)[0]; iComp[1] = (v.iComp)[1]; iComp[2] = (v.iComp)[2]; return *this; } mgVector_c::~mgVector_c() { } void mgVector_c::set_x( double new_x ) { iComp[0] = new_x; } void mgVector_c::set_y( double new_y ) { iComp[1] = new_y; } void mgVector_c::set_z( double new_z ) { iComp[2] = new_z; } void mgVector_c::set( double compIn[3] ) { memcpy( iComp, compIn, 3 * sizeof( double ) ); } void mgVector_c::set( double new_x, double new_y, double new_z) { iComp[0] = new_x; iComp[1] = new_y; iComp[2] = new_z; } mgVector_c operator-( mgVector_c const &v ) { return mgVector_c ( -(v.iComp[0]), -(v.iComp[1]), -(v.iComp[2]) ); } mgVector_c operator+( mgVector_c const &v1, mgVector_c const &v2 ) { return mgVector_c ( ( v1.iComp[0] + v2.iComp[0] ), ( v1.iComp[1] + v2.iComp[1] ), ( v1.iComp[2] + v2.iComp[2] ) ); } mgVector_c const &mgVector_c::operator+=( mgVector_c const &v ) { iComp[0] += (v.iComp)[0]; iComp[1] += (v.iComp)[1]; iComp[2] += (v.iComp)[2]; return *this; } mgVector_c operator-( mgVector_c const &v1, mgVector_c const &v2 ) { return mgVector_c ( ( v1.iComp[0] - v2.iComp[0] ), ( v1.iComp[1] - v2.iComp[1] ), ( v1.iComp[2] - v2.iComp[2] ) ); } mgVector_c operator*( double s, mgVector_c const &v ) { return mgVector_c ( s * ( v.iComp[0] ), s * ( v.iComp[1] ), s * ( v.iComp[2] ) ); } mgVector_c operator*( mgVector_c const &v, double s ) { return mgVector_c ( s * ( v.iComp[0] ), s * ( v.iComp[1] ), s * ( v.iComp[2] ) ); } mgVector_c const &mgVector_c::operator*=( double s ) { iComp[0] *= s; iComp[1] *= s; iComp[2] *= s; return *this; } double operator%( mgVector_c const &v1, mgVector_c const &v2 ) { // Dot product return ( ( v1.iComp[0] * v2.iComp[0] ) + ( v1.iComp[1] * v2.iComp[1] ) + ( v1.iComp[2] * v2.iComp[2] ) ); } mgVector_c operator*( mgVector_c const &v1, mgVector_c const &v2 ) { // Cross product double components[3]; components[0] = ( (v1.iComp )[1] * (v2.iComp )[2] ) - ( (v1.iComp )[2] * (v2.iComp )[1] ); components[1] = ( (v1.iComp )[2] * (v2.iComp )[0] ) - ( (v1.iComp )[0] * (v2.iComp )[2] ); components[2] = ( (v1.iComp )[0] * (v2.iComp )[1] ) - ( (v1.iComp )[1] * (v2.iComp )[0] ); return mgVector_c ( components ); } mgVector_c operator/( mgVector_c const &v, double s) { if ( fabs(s) < gcLengthTolerance ) return mgVector_c( 0.0, 0.0, 0.0 ); else return mgVector_c ( ( v.iComp[0] ) / s, ( v.iComp[1] ) / s, ( v.iComp[2] ) / s ); } BOOL mgVector_c::isNotNull() const { if ( fabs ( iComp[0] ) <gcLengthTolerance && fabs ( iComp[1] ) <gcLengthTolerance && fabs ( iComp[2] ) < gcLengthTolerance ) { return FALSE; } return TRUE; } BOOL mgVector_c::isNull() const { if ( fabs ( iComp[0] ) <gcLengthTolerance && fabs ( iComp[1] ) <gcLengthTolerance && fabs ( iComp[2] ) < gcLengthTolerance ) { return TRUE; } return FALSE; } BOOL operator==(mgVector_c const &v1, mgVector_c const &v2) { return ( ( fabs ( (v1.iComp[0] ) - ( v2.iComp[0] ) ) < gcLengthTolerance ) && ( fabs ( (v1.iComp[1] ) - ( v2.iComp[1] ) ) < gcLengthTolerance ) && ( fabs ( (v1.iComp[2] ) - ( v2.iComp[2] ) ) < gcLengthTolerance ) ); } BOOL operator!=(mgVector_c const &v1, mgVector_c const &v2) { return ( ( fabs ( (v1.iComp[0] ) - ( v2.iComp[0] ) ) > gcLengthTolerance ) || ( fabs ( (v1.iComp[1] ) - ( v2.iComp[1] ) ) > gcLengthTolerance ) || ( fabs ( (v1.iComp[2] ) - ( v2.iComp[2] ) ) > gcLengthTolerance ) ); } mgVector_c mg_Normalise( mgVector_c const &v ) { double denominator = v.x()*v.x() + v.y()*v.y() + v.z()*v.z(); if (denominator < gcDoubleTolerance) return mgVector_c( 0.0, 0.0, 0.0 ); return mgVector_c( v.x()/denominator, v.y()/denominator, v.z()/denominator ); } double vol(mgVector_c const &v1, mgVector_c const &v2, mgVector_c const &v3) { mgVector_c vect = v1*v2; return(vect % v3); } BOOL mgVector_c::isOrthogonal () { if ( fabs( x() ) < gcLengthTolerance && fabs( y() ) < gcLengthTolerance && fabs( z() ) < gcLengthTolerance ) return FALSE; // everything zero if ( fabs( x() ) < gcLengthTolerance && fabs( y() ) < gcLengthTolerance ) return TRUE; // has a Z only if ( fabs( x() ) < gcLengthTolerance && fabs( z() ) < gcLengthTolerance ) return TRUE; // has a Y only if ( fabs( y() ) < gcLengthTolerance && fabs( z() ) < gcLengthTolerance ) return TRUE; // has a X only return FALSE; } // cast operator to conveniently pass the list to parasolid mgVector_c::operator double* () { return iComp; } BOOL mgVector_c::normalise() { if (isNull()) return FALSE; *this = mg_Normalise(*this); return TRUE; }
22.516981
127
0.558405
neboat
202d141e7b3a212670d12c7ca4d95c82af4d46c6
1,576
cpp
C++
src/rfilters/catmullrom.cpp
tizian/layer-laboratory
008cc94b76127e9eb74227fcd3d0145da8ddec30
[ "CNRI-Python" ]
7
2020-07-24T03:19:59.000Z
2022-03-30T10:56:12.000Z
src/rfilters/catmullrom.cpp
tizian/layer-laboratory
008cc94b76127e9eb74227fcd3d0145da8ddec30
[ "CNRI-Python" ]
1
2021-04-07T22:30:23.000Z
2021-04-08T00:55:36.000Z
src/rfilters/catmullrom.cpp
tizian/layer-laboratory
008cc94b76127e9eb74227fcd3d0145da8ddec30
[ "CNRI-Python" ]
2
2020-06-08T08:25:09.000Z
2021-04-05T22:13:08.000Z
#include <mitsuba/core/rfilter.h> #include <mitsuba/render/fwd.h> NAMESPACE_BEGIN(mitsuba) /**! .. _rfilter-catmullrom: Catmull-Rom filter (:monosp:`catmullrom`) ----------------------------------------- Special version of the Mitchell-Netravali filter with constants B and C configured to match the Catmull-Rom spline. It usually does a better job at at preserving sharp features at the cost of more ringing. */ template <typename Float, typename Spectrum> class CatmullRomFilter final : public ReconstructionFilter<Float, Spectrum> { public: MTS_IMPORT_BASE(ReconstructionFilter, init_discretization, m_radius) CatmullRomFilter(const Properties &props) : Base(props) { m_radius = 2.f; init_discretization(); } Float eval(Float x, mask_t<Float> /* active */) const override { x = abs(x); Float x2 = sqr(x), x3 = x2*x, B = 0.f, C = .5f; Float result = (1.f / 6.f) * select( x < 1, (12.f - 9.f * B - 6.f * C) * x3 + (-18.f + 12.f * B + 6.f * C) * x2 + (6.f - 2.f * B), (-B - 6.f * C) * x3 + (6.f * B + 30.f * C) * x2 + (-12.f * B - 48.f * C) * x + (8.f * B + 24.f * C) ); return select(x < 2.f, result, 0.f); } std::string to_string() const override { return tfm::format("CatmullRomFilter[radius=%f]", m_radius); } MTS_DECLARE_CLASS() }; MTS_IMPLEMENT_CLASS_VARIANT(CatmullRomFilter, ReconstructionFilter) MTS_EXPORT_PLUGIN(CatmullRomFilter, "Catmull-Rom filter"); NAMESPACE_END(mitsuba)
28.142857
84
0.594543
tizian
202d45e38a36b90376523fe8e8129b6bf0cd7b7e
10,782
cpp
C++
src/math/matrix/matrix3x3.cpp
Gotatang/DadEngine_2.0
1e97e86996571c8ba1efec72b0f0e914d86533d3
[ "MIT" ]
2
2018-03-12T13:59:13.000Z
2018-11-27T20:13:57.000Z
src/math/matrix/matrix3x3.cpp
Gotatang/DadEngine_2.0
1e97e86996571c8ba1efec72b0f0e914d86533d3
[ "MIT" ]
5
2018-12-22T10:43:28.000Z
2019-01-17T22:02:16.000Z
src/math/matrix/matrix3x3.cpp
ladevieq/dadengine
1e97e86996571c8ba1efec72b0f0e914d86533d3
[ "MIT" ]
null
null
null
#include "matrix/matrix3x3.hpp" #include "constants.hpp" #include "vector/vector2.hpp" #include "vector/vector3.hpp" #include <limits> namespace DadEngine { Matrix3x3::Matrix3x3(std::array<Vector3, 3> _vectors) { m_11 = _vectors[0U].x, m_12 = _vectors[1U].x, m_13 = _vectors[2U].x; m_21 = _vectors[0U].y, m_22 = _vectors[1U].y, m_23 = _vectors[2U].y; m_31 = _vectors[0U].z, m_32 = _vectors[1U].z, m_33 = _vectors[2U].z; } Matrix3x3::Matrix3x3( float _11, float _12, float _13, float _21, float _22, float _23, float _31, float _32, float _33) { m_11 = _11, m_12 = _12, m_13 = _13; m_21 = _21, m_22 = _22, m_23 = _23; m_31 = _31, m_32 = _32, m_33 = _33; } Matrix3x3::Matrix3x3(std::array<float, 9> _data) { m_11 = _data[0U], m_12 = _data[1U], m_13 = _data[2U]; m_21 = _data[3U], m_22 = _data[4U], m_23 = _data[5U]; m_31 = _data[6U], m_32 = _data[7U], m_33 = _data[8U]; } // Standard matrix functions void Matrix3x3::SetIdentity() { m_11 = 1.f, m_12 = 0.f, m_13 = 0.f; m_21 = 0.f, m_22 = 1.f, m_23 = 0.f; m_31 = 0.f, m_32 = 0.f, m_33 = 1.f; } void Matrix3x3::Transpose() { Matrix3x3 temp = *this; m_12 = m_21; m_13 = m_31; m_23 = m_32; m_21 = temp.m_12; m_31 = temp.m_13; m_32 = temp.m_23; } void Matrix3x3::Inverse() { float cof11 = (m_22 * m_33 - m_23 * m_32); float cof12 = -(m_21 * m_33 - m_23 * m_31); float cof13 = (m_21 * m_32 - m_22 * m_31); float determinant = m_11 * cof11 + m_12 * cof12 + m_13 * cof13; if (determinant > std::numeric_limits<decltype(determinant)>::epsilon() || determinant < std::numeric_limits<decltype(determinant)>::epsilon()) { determinant = 1.f / determinant; float cof21 = -(m_12 * m_33 - m_13 * m_32); float cof22 = (m_11 * m_33 - m_13 * m_31); float cof23 = -(m_11 * m_32 - m_12 * m_31); float cof31 = (m_12 * m_23 - m_13 * m_22); float cof32 = -(m_11 * m_23 - m_13 * m_21); float cof33 = (m_11 * m_22 - m_12 * m_21); m_11 = cof11 * determinant, m_12 = cof12 * determinant, m_13 = cof13 * determinant; m_21 = cof21 * determinant, m_22 = cof22 * determinant, m_23 = cof23 * determinant; m_31 = cof31 * determinant, m_32 = cof32 * determinant, m_33 = cof33 * determinant; // Transpose(); } } float Matrix3x3::Determinant() const { float cof11 = (m_22 * m_33 - m_23 * m_32); float cof12 = -(m_21 * m_33 - m_23 * m_31); float cof13 = (m_21 * m_32 - m_22 * m_31); return m_11 * cof11 + m_12 * cof12 + m_13 * cof13; } void Matrix3x3::RotationX(float _angle) { float cos = std::cos(_angle); float sin = std::sin(_angle); m_11 = 1.f, m_12 = 0.f, m_13 = 0.f; m_21 = 0.f, m_22 = cos, m_23 = -sin; m_31 = 0.f, m_32 = sin, m_33 = cos; } void Matrix3x3::RotationY(float _angle) { float cos = std::cos(_angle); float sin = std::sin(_angle); m_11 = cos, m_12 = 0.f, m_13 = sin; m_21 = 0.f, m_22 = 1.f, m_23 = 0.f; m_31 = -sin, m_32 = 0.f, m_33 = cos; } void Matrix3x3::RotationZ(float _angle) { float cos = std::cos(_angle); float sin = std::sin(_angle); m_11 = cos, m_12 = -sin, m_13 = 0.f; m_21 = sin, m_22 = cos, m_23 = 0.f; m_31 = 0.f, m_32 = 0.f, m_33 = 1.f; } void Matrix3x3::Rotation(float _angle, Vector3 _axis) { float cos = std::cos(_angle); float sin = std::sin(_angle); float cosLessOne = 1 - cos; m_11 = cos + (cosLessOne * _axis.x * _axis.x), m_12 = (cosLessOne * _axis.x * _axis.y) - (sin * _axis.z), m_13 = (cosLessOne * _axis.x * _axis.z) + (sin * _axis.y); m_21 = (cosLessOne * _axis.x * _axis.y) + (sin * _axis.z), m_22 = cos + (cosLessOne * _axis.y * _axis.y), m_23 = (cosLessOne * _axis.y * _axis.z) - (sin * _axis.x); m_31 = (cosLessOne * _axis.x * _axis.z) - (sin * _axis.y), m_32 = (cosLessOne * _axis.y * _axis.z) + (sin * _axis.x), m_33 = cos + (cosLessOne * _axis.z * _axis.z); } void Matrix3x3::Scale(float _scaleX, float _scaleY, float _scaleZ) { m_11 = _scaleX, m_12 = 0.f, m_13 = 0.f; m_21 = 0.f, m_22 = _scaleY, m_23 = 0.f; m_31 = 0.f, m_32 = 0.f, m_33 = _scaleZ; } void Matrix3x3::Translation(Vector2 _translation) { m_11 = 0.f, m_12 = 0.f, m_13 = _translation.x; m_21 = 0.f, m_22 = 0.f, m_23 = _translation.y; m_31 = 0.f, m_32 = 0.f, m_33 = 1.f; } // Binary math operators Matrix3x3 Matrix3x3::operator+(Matrix3x3 &_matrix) const { Matrix3x3 result; result.m_11 = m_11 + _matrix.m_11, result.m_12 = m_12 + _matrix.m_12, result.m_13 = m_13 + _matrix.m_13; result.m_21 = m_21 + _matrix.m_21, result.m_22 = m_22 + _matrix.m_22, result.m_23 = m_23 + _matrix.m_23; result.m_31 = m_31 + _matrix.m_31, result.m_32 = m_32 + _matrix.m_32, result.m_33 = m_33 + _matrix.m_33; return result; } Matrix3x3 Matrix3x3::operator-(Matrix3x3 &_matrix) const { Matrix3x3 result; result.m_11 = m_11 - _matrix.m_11, result.m_12 = m_12 - _matrix.m_12, result.m_13 = m_13 - _matrix.m_13; result.m_21 = m_21 - _matrix.m_21, result.m_22 = m_22 - _matrix.m_22, result.m_23 = m_23 - _matrix.m_23; result.m_31 = m_31 - _matrix.m_31, result.m_32 = m_32 - _matrix.m_32, result.m_33 = m_33 - _matrix.m_33; return result; } Matrix3x3 Matrix3x3::operator*(float &_factor) const { Matrix3x3 result; result.m_11 = m_11 * _factor, result.m_12 = m_12 * _factor, result.m_13 = m_13 * _factor; result.m_21 = m_21 * _factor, result.m_22 = m_22 * _factor, result.m_23 = m_23 * _factor; result.m_31 = m_31 * _factor, result.m_32 = m_32 * _factor, result.m_33 = m_33 * _factor; return result; } Vector3 Matrix3x3::operator*(Vector3 &_vector) const { return Vector3(m_11 * _vector.x + m_12 * _vector.y + m_13 * _vector.z, m_21 * _vector.x + m_22 * _vector.y + m_23 * _vector.z, m_31 * _vector.x + m_32 * _vector.y + m_33 * _vector.z); } Matrix3x3 Matrix3x3::operator*(Matrix3x3 &_matrix) const { Matrix3x3 result; result.m_11 = m_11 * _matrix.m_11 + m_12 * _matrix.m_21 + m_13 * _matrix.m_31; result.m_12 = m_11 * _matrix.m_12 + m_12 * _matrix.m_22 + m_13 * _matrix.m_32; result.m_13 = m_11 * _matrix.m_13 + m_12 * _matrix.m_23 + m_13 * _matrix.m_33; result.m_21 = m_21 * _matrix.m_11 + m_22 * _matrix.m_21 + m_23 * _matrix.m_31; result.m_22 = m_21 * _matrix.m_12 + m_22 * _matrix.m_22 + m_23 * _matrix.m_32; result.m_23 = m_21 * _matrix.m_13 + m_22 * _matrix.m_23 + m_23 * _matrix.m_33; result.m_31 = m_31 * _matrix.m_11 + m_32 * _matrix.m_21 + m_33 * _matrix.m_31; result.m_32 = m_31 * _matrix.m_12 + m_32 * _matrix.m_22 + m_33 * _matrix.m_32; result.m_33 = m_31 * _matrix.m_13 + m_32 * _matrix.m_23 + m_33 * _matrix.m_33; return result; } Matrix3x3 Matrix3x3::operator/(float &_factor) const { Matrix3x3 result; result.m_11 = m_11 / _factor, result.m_12 = m_12 / _factor, result.m_13 = m_13 / _factor; result.m_21 = m_21 / _factor, result.m_22 = m_22 / _factor, result.m_23 = m_23 / _factor; result.m_31 = m_31 / _factor, result.m_32 = m_32 / _factor, result.m_33 = m_33 / _factor; return result; } Matrix3x3 Matrix3x3::operator/(Matrix3x3 &_matrix) const { Matrix3x3 result; _matrix.Inverse(); result = *this * _matrix; return result; } // Binary assignement math operators void Matrix3x3::operator+=(Matrix3x3 &_matrix) { m_11 += _matrix.m_11, m_12 += _matrix.m_12, m_13 += _matrix.m_13; m_21 += _matrix.m_21, m_22 += _matrix.m_22, m_23 += _matrix.m_23; m_31 += _matrix.m_31, m_32 += _matrix.m_32, m_33 += _matrix.m_33; } void Matrix3x3::operator-=(Matrix3x3 &_matrix) { m_11 -= _matrix.m_11, m_12 -= _matrix.m_12, m_13 -= _matrix.m_13; m_21 -= _matrix.m_21, m_22 -= _matrix.m_22, m_23 -= _matrix.m_23; m_31 -= _matrix.m_31, m_32 -= _matrix.m_32, m_33 -= _matrix.m_33; } void Matrix3x3::operator*=(float &_factor) { m_11 *= _factor, m_12 *= _factor, m_13 *= _factor; m_21 *= _factor, m_22 *= _factor, m_23 *= _factor; m_31 *= _factor, m_32 *= _factor, m_33 *= _factor; } Vector3 Matrix3x3::operator*=(Vector3 &_vector) const { return Vector3(m_11 * _vector.x + m_12 * _vector.y + m_13 * _vector.z, m_21 * _vector.x + m_22 * _vector.y + m_23 * _vector.z, m_31 * _vector.x + m_32 * _vector.y + m_33 * _vector.z); } void Matrix3x3::operator*=(Matrix3x3 &_matrix) { Matrix3x3 temp = *this; m_11 = temp.m_11 * _matrix.m_11 + temp.m_12 * _matrix.m_21 + temp.m_13 * _matrix.m_31; m_12 = temp.m_11 * _matrix.m_12 + temp.m_12 * _matrix.m_22 + temp.m_13 * _matrix.m_32; m_13 = temp.m_11 * _matrix.m_13 + temp.m_12 * _matrix.m_23 + temp.m_13 * _matrix.m_33; m_21 = temp.m_21 * _matrix.m_11 + temp.m_22 * _matrix.m_21 + temp.m_23 * _matrix.m_31; m_22 = temp.m_21 * _matrix.m_12 + temp.m_22 * _matrix.m_22 + temp.m_23 * _matrix.m_32; m_23 = temp.m_21 * _matrix.m_13 + temp.m_22 * _matrix.m_23 + temp.m_23 * _matrix.m_33; m_31 = temp.m_31 * _matrix.m_11 + temp.m_32 * _matrix.m_21 + temp.m_33 * _matrix.m_31; m_32 = temp.m_31 * _matrix.m_12 + temp.m_32 * _matrix.m_22 + temp.m_33 * _matrix.m_32; m_33 = temp.m_31 * _matrix.m_13 + temp.m_32 * _matrix.m_23 + temp.m_33 * _matrix.m_33; } void Matrix3x3::operator/=(float &_factor) { m_11 /= _factor, m_12 /= _factor, m_13 /= _factor; m_21 /= _factor, m_22 /= _factor, m_23 /= _factor; m_31 /= _factor, m_32 /= _factor, m_33 /= _factor; } void Matrix3x3::operator/=(Matrix3x3 &_matrix) { _matrix.Inverse(); *this *= _matrix; } } // namespace DadEngine
34.557692
106
0.560286
Gotatang
2032531a2a5b2ff52b3ce301a1007240bd5e3ba0
781
cc
C++
leet_code/Check_If_Word_Is_Valid_After_Substitutions/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
leet_code/Check_If_Word_Is_Valid_After_Substitutions/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
leet_code/Check_If_Word_Is_Valid_After_Substitutions/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { private : const int windowSize = 3; const char invalid = -1; public: bool isValid(string S) { string& in = S; for (bool isChange = true; isChange;) { string data; for (int i = 0; i < in.length(); ++i) { if (in[i] != invalid) { data += in[i]; } } isChange = false; for (string::size_type idx = data.find("abc", 0); idx != string::npos; idx = data.find("abc", idx)) { data[idx] = data[idx + 1] = data[idx + 2] = invalid; isChange = true; } in = data; } return (in.length() == 0); } };
26.033333
68
0.386684
ldy121
20336bb91326e6df27c8ebf0790a01ef49d9b053
729
cpp
C++
cpp_alkeet/2_Harjoitukset_190912/fourth.cpp
Diapolo10/TAMK-Exercises
904958cc41b253201eef182f17e43d95cf4f7c89
[ "MIT" ]
null
null
null
cpp_alkeet/2_Harjoitukset_190912/fourth.cpp
Diapolo10/TAMK-Exercises
904958cc41b253201eef182f17e43d95cf4f7c89
[ "MIT" ]
null
null
null
cpp_alkeet/2_Harjoitukset_190912/fourth.cpp
Diapolo10/TAMK-Exercises
904958cc41b253201eef182f17e43d95cf4f7c89
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using std::vector; double mass_sum(vector<double> nums) { double result = .0; for (auto num : nums) { result += num; } return result; } vector<double>& get_passenger_masses(int n=4) { vector<double> masses; for (int i = 1; i <= n; ++i) { double mass; std::cout << "Passenger #" << i << ": "; std::cin >> mass; masses.push_back(mass); } return masses; } int main(void) { double max_mass; vector<double> people; std::cout << "Elevator's maximum supported mass: "; std::cin >> max_mass; people = get_passenger_masses(); std::cout << ((mass_sum(people) > max_mass) ? "Overweight, elevator not usable!" : "Elevator at your service!") << "\n"; return 0; }
16.2
121
0.628258
Diapolo10
20340ce7bf2c6ad38ec67191873ec6f8706fdbfc
1,879
cpp
C++
2-YellowBelt/FinalProject/node.cpp
mamoudmatook/CPlusPlusInRussian
ef1f92e4880f24fe16fbcbef8dba3a2658d2208e
[ "MIT" ]
null
null
null
2-YellowBelt/FinalProject/node.cpp
mamoudmatook/CPlusPlusInRussian
ef1f92e4880f24fe16fbcbef8dba3a2658d2208e
[ "MIT" ]
null
null
null
2-YellowBelt/FinalProject/node.cpp
mamoudmatook/CPlusPlusInRussian
ef1f92e4880f24fe16fbcbef8dba3a2658d2208e
[ "MIT" ]
null
null
null
#include "node.h" EmptyNode::EmptyNode() {} bool EmptyNode::Evaluate(const Date& date, const std::string& event) const { return true; } DateComparisonNode::DateComparisonNode(const Comparison& comprs, const Date& date) : cmpr(comprs), dt(date) {} bool DateComparisonNode::Evaluate(const Date& date, const std::string& event) const { switch (cmpr) { case Comparison::Less: return date < dt; case Comparison::LessOrEqual: return date <= dt; case Comparison::Greater: return date > dt; case Comparison::GreaterOrEqual: return date >= dt; case Comparison::Equal: return date == dt; case Comparison::NotEqual: return date != dt; default: return 0; break; } } EventComparisonNode::EventComparisonNode(const Comparison& comprs, const std::string& event) : cmpr(comprs), evnt(event) {} bool EventComparisonNode::Evaluate(const Date& date, const std::string& event) const { switch (cmpr) { case Comparison::Less: return event < evnt; case Comparison::LessOrEqual: return event <= evnt; case Comparison::Greater: return event > evnt; case Comparison::GreaterOrEqual: return event >= evnt; case Comparison::Equal: return event == evnt; case Comparison::NotEqual: return event != evnt; default: return 0; break; } } LogicalOperationNode::LogicalOperationNode(const LogicalOperation& logical_operation, const std::shared_ptr<Node>& lhs, const std::shared_ptr<Node>& rhs) : lgc_op(logical_operation), lhs_node(lhs), rhs_node(rhs) { } bool LogicalOperationNode::Evaluate(const Date& date, const std::string& event) const { switch (lgc_op) { case LogicalOperation::Or: return lhs_node->Evaluate(date, event) || rhs_node->Evaluate(date, event); case LogicalOperation::And: return lhs_node->Evaluate(date, event) && rhs_node->Evaluate(date, event); default: return false; break; } }
26.464789
123
0.711016
mamoudmatook
2035f9c617a2c5660a1e1a416b52124a7f622c40
3,188
cpp
C++
test/test_optimizers.cpp
AvocadoML/CudaBackend
314413c12efa7cb12a1ff0c2572c8aad9190d419
[ "Apache-2.0" ]
2
2022-03-14T07:13:37.000Z
2022-03-16T00:16:33.000Z
test/test_optimizers.cpp
AvocadoML/CudaBackend
314413c12efa7cb12a1ff0c2572c8aad9190d419
[ "Apache-2.0" ]
null
null
null
test/test_optimizers.cpp
AvocadoML/CudaBackend
314413c12efa7cb12a1ff0c2572c8aad9190d419
[ "Apache-2.0" ]
1
2022-03-14T07:13:44.000Z
2022-03-14T07:13:44.000Z
/* * test_optimizers.cpp * * Created on: Jan 27, 2022 * Author: Maciej Kozarzewski */ #include <testing/testing_helpers.hpp> #include <gtest/gtest.h> namespace avocado { namespace backend { TEST(TestOptimizer, float32_sgd) { if (not supportsType(AVOCADO_DTYPE_FLOAT32)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32); data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.0, 0., 0.0, 0.0 }, { false, false, false, false }); float alpha = 1.1f, beta = 0.1f; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float32_sgd_momentum) { if (not supportsType(AVOCADO_DTYPE_FLOAT32)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32); data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, false, false, false }); float alpha = 1.1f, beta = 0.1f; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float32_sgd_nesterov) { if (not supportsType(AVOCADO_DTYPE_FLOAT32)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32); data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, true, false, false }); float alpha = 1.1f, beta = 0.1f; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float32_adam) { if (not supportsType(AVOCADO_DTYPE_FLOAT32)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32); data.set(AVOCADO_OPTIMIZER_ADAM, 0.01, { 0.01, 0.001, 0.0, 0.0 }, { false, false, false, false }); float alpha = 1.1f, beta = 0.1f; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float64_sgd) { if (not supportsType(AVOCADO_DTYPE_FLOAT64)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64); data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.0, 0., 0.0, 0.0 }, { false, false, false, false }); double alpha = 1.1, beta = 0.1; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float64_sgd_momentum) { if (not supportsType(AVOCADO_DTYPE_FLOAT64)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64); data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, false, false, false }); double alpha = 1.1, beta = 0.1; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float64_sgd_nesterov) { if (not supportsType(AVOCADO_DTYPE_FLOAT64)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64); data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, true, false, false }); double alpha = 1.1, beta = 0.1; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } TEST(TestOptimizer, float64_adam) { if (not supportsType(AVOCADO_DTYPE_FLOAT64)) GTEST_SKIP(); OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64); data.set(AVOCADO_OPTIMIZER_ADAM, 0.01, { 0.01, 0.001, 0.0, 0.0 }, { false, false, false, false }); double alpha = 1.1, beta = 0.1; EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4); } } /* namespace backend */ } /* namespace avocado */
34.27957
101
0.663425
AvocadoML
2039ba4370d7625f068debb573eb3548460aabea
744
cpp
C++
Arrays/miscellaneous/k_divisible_elements_subarray.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Arrays/miscellaneous/k_divisible_elements_subarray.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
Arrays/miscellaneous/k_divisible_elements_subarray.cpp
khushisinha20/Data-Structures-and-Algorithms
114d365d03f7ba7175eefeace281972820a7fc76
[ "Apache-2.0" ]
null
null
null
//leetcode.com/problems/k-divisible-elements-subarrays/ #include <bits/stdc++.h> using namespace std; class Solution { public: int countDistinct(vector<int>& nums, int k, int p) { set<vector<int>> distinct_subarrays; int multiples_of_p = 0; for (int i = 0; i < nums.size(); ++i) { multiples_of_p = 0; vector<int> subarray; for (int j = i; j < nums.size(); ++j) { subarray.push_back(nums[j]); if (nums[j] % p == 0) ++multiples_of_p; if (multiples_of_p > k) break; distinct_subarrays.insert(subarray); } } return distinct_subarrays.size(); } };
29.76
56
0.508065
khushisinha20
203a102f86509c20df7e82f0cec3a908a06547bf
2,459
hpp
C++
INCLUDE/json.hpp
n-mam/cpp-osl
44f32d9e0670b30ff08f08f540e0f161f7d62965
[ "MIT" ]
null
null
null
INCLUDE/json.hpp
n-mam/cpp-osl
44f32d9e0670b30ff08f08f540e0f161f7d62965
[ "MIT" ]
null
null
null
INCLUDE/json.hpp
n-mam/cpp-osl
44f32d9e0670b30ff08f08f540e0f161f7d62965
[ "MIT" ]
null
null
null
#ifndef JSON_HPP #define JSON_HPP #include <map> #include <regex> #include <string> #include <vector> #include <sstream> #include <string.hpp> class Json { public: Json() { } Json(const std::string& s) { iJsonString = s; Parse(); } ~Json() { } bool IsOk() { return false; } std::string GetKey(const std::string& key) { return iMap[key]; } void SetKey(const std::string& key, const std::string& value) { iMap[key] = std::regex_replace(value, std::regex(R"(\\)"), R"(\\)"); } bool HasKey(const std::string& key) { auto fRet = iMap.find(key); if (fRet != iMap.end()) { return true; } else { return false; } } std::string Stringify(void) { std::string js; js += "{"; for (const auto &element : iMap) { if (js.length() > 1) { js += ", "; } js += "\"" + element.first + "\"" + ": "; if ((element.second)[0] != '[') { js += "\"" + element.second + "\""; } else { js += element.second; } } js += "}"; return js; } static std::string JsonListToArray(std::vector<Json>& list) { std::string value = "["; for(auto& j : list) { value += j.Stringify(); value += ","; } value = trim(value, ","); value += "]"; return value; } /* * This assumes that the json has been stringifie'd and has only * string kv pairs, otherwise this would fail miserably * {"service":"ftp","request":"connect","list":"/","id":"0","host":"w","port":"w","user":"w","pass":"w"} */ void Parse(void) { ltrim(iJsonString, "{\""); rtrim(iJsonString, "\"}"); auto pp = split(iJsonString, "\",\""); for (auto& p : pp) { auto kv = split(p, "\":\""); if (kv.size() == 2) { iMap.insert( std::make_pair(kv[0], kv[1]) ); } } } void Dump(void) { } private: std::string iJsonString; std::map<std::string, std::string> iMap; }; #endif //JSON_HPP
16.727891
109
0.413176
n-mam
203a3fb00b88e7e7bac33472923c81858d9ec485
1,705
cpp
C++
Editor/Sources/o2Editor/Core/Properties/Basic/EnumProperty.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
181
2015-12-09T08:53:36.000Z
2022-03-26T20:48:39.000Z
Editor/Sources/o2Editor/Core/Properties/Basic/EnumProperty.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
29
2016-04-22T08:24:04.000Z
2022-03-06T07:06:28.000Z
Editor/Sources/o2Editor/Core/Properties/Basic/EnumProperty.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
13
2018-04-24T17:12:04.000Z
2021-11-12T23:49:53.000Z
#include "o2Editor/stdafx.h" #include "EnumProperty.h" #include "o2/Scene/UI/Widgets/DropDown.h" namespace Editor { EnumProperty::EnumProperty() {} EnumProperty::EnumProperty(const EnumProperty& other) : TPropertyField<int>(other) { InitializeControls(); } EnumProperty& EnumProperty::operator=(const EnumProperty& other) { TPropertyField<int>::operator=(other); InitializeControls(); return *this; } void EnumProperty::InitializeControls() { mDropDown = FindChildByType<DropDown>(); if (mDropDown) { mDropDown->onSelectedText = THIS_FUNC(OnSelectedItem); mDropDown->SetState("undefined", true); } } const Type* EnumProperty::GetValueType() const { return mEnumType; } void EnumProperty::SpecializeType(const Type* type) { if (type->GetUsage() == Type::Usage::Property) mEnumType = dynamic_cast<const EnumType*>(((const PropertyType*)type)->GetValueType()); else mEnumType = dynamic_cast<const EnumType*>(type); if (mEnumType) { mEntries = &mEnumType->GetEntries(); for (auto& kv : *mEntries) mDropDown->AddItem(kv.second); } } const Type* EnumProperty::GetValueTypeStatic() { return nullptr; } void EnumProperty::UpdateValueView() { mUpdatingValue = true; if (mValuesDifferent) { mDropDown->value = (*mEntries).Get(mCommonValue); mDropDown->SetState("undefined", true); } else { mDropDown->value = (*mEntries).Get(mCommonValue); mDropDown->SetState("undefined", false); } mUpdatingValue = false; } void EnumProperty::OnSelectedItem(const WString& name) { if (mUpdatingValue) return; SetValueByUser(mEntries->FindValue(name).first); } } DECLARE_CLASS(Editor::EnumProperty);
19.375
90
0.70088
zenkovich
203ae6d848b59e2bdcc89ce0d41f1f886bb6007b
643
cpp
C++
Firmware/src/Buzzer/Buzzer.cpp
FERRERDEV/Mila
80e9a0ba9e8d5e318a659f17523e3ab3a1d15dd4
[ "MIT" ]
null
null
null
Firmware/src/Buzzer/Buzzer.cpp
FERRERDEV/Mila
80e9a0ba9e8d5e318a659f17523e3ab3a1d15dd4
[ "MIT" ]
null
null
null
Firmware/src/Buzzer/Buzzer.cpp
FERRERDEV/Mila
80e9a0ba9e8d5e318a659f17523e3ab3a1d15dd4
[ "MIT" ]
1
2021-02-22T00:54:07.000Z
2021-02-22T00:54:07.000Z
// Buzzer #include "Buzzer.h" // Arduino #include "Arduino.h" // Mila #include "Mila.h" Buzzer::Buzzer(int buzzerPin) { // Assign the buzzer pin. this->buzzerPin = buzzerPin; } void Buzzer::playAlarm(alarm alarmToPlay, int loops) { bInfiniteAlarm = loops == -1; while (bInfiniteAlarm) { for (int loop = loops; loop - loops >= 0; loop--) { if (bInfiniteAlarm) loop++; for (int i = 0; i < alarmToPlay.Lenght; i++) { tone(buzzerPin, alarmToPlay.Cue[i].Tone, alarmToPlay.Cue[i].Duration); delay(alarmToPlay.Time); } delay(alarmToPlay.Time); } } } void Buzzer::stopAlarm() { bInfiniteAlarm = false; }
15.682927
74
0.642302
FERRERDEV
203d7e2a78cc55216f2452d82f56b547523ba228
4,345
hh
C++
psdaq/psdaq/eb/EbLfLink.hh
slac-lcls/pdsdata2
6e2ad4f830cadfe29764dbd280fa57f8f9edc451
[ "BSD-3-Clause-LBNL" ]
null
null
null
psdaq/psdaq/eb/EbLfLink.hh
slac-lcls/pdsdata2
6e2ad4f830cadfe29764dbd280fa57f8f9edc451
[ "BSD-3-Clause-LBNL" ]
null
null
null
psdaq/psdaq/eb/EbLfLink.hh
slac-lcls/pdsdata2
6e2ad4f830cadfe29764dbd280fa57f8f9edc451
[ "BSD-3-Clause-LBNL" ]
null
null
null
#ifndef Pds_Eb_EbLfLink_hh #define Pds_Eb_EbLfLink_hh #include "Endpoint.hh" #include <stdint.h> #include <cstddef> #include <vector> namespace Pds { namespace Eb { int setupMr(Fabrics::Fabric* fabric, void* region, size_t size, Fabrics::MemoryRegion** mr, const unsigned& verbose); class EbLfLink { public: EbLfLink(Fabrics::Endpoint*, int depth, const unsigned& verbose); public: int recvU32(uint32_t* u32, const char* peer, const char* name); int sendU32(uint32_t u32, const char* peer, const char* name); int sendMr(Fabrics::MemoryRegion*, const char* peer); int recvMr(Fabrics::RemoteAddress&, const char* peer); public: void* lclAdx(size_t offset) const; size_t lclOfs(const void* buffer) const; uintptr_t rmtAdx(size_t offset) const; size_t rmtOfs(uintptr_t buffer) const; public: Fabrics::Endpoint* endpoint() const { return _ep; } unsigned id() const { return _id; } const uint64_t& tmoCnt() const { return _timedOut; } public: int post(const void* buf, size_t len, uint64_t immData); int post(uint64_t immData); int poll(uint64_t* data); int poll(uint64_t* data, int msTmo); public: ssize_t postCompRecv(); ssize_t postCompRecv(unsigned count); protected: enum { _BegSync = 0x11111111, _EndSync = 0x22222222, _SvrSync = 0x33333333, _CltSync = 0x44444444 }; protected: // Arranged in order of access frequency unsigned _id; // ID of peer Fabrics::Endpoint* _ep; // Endpoint Fabrics::MemoryRegion* _mr; // Memory Region Fabrics::RemoteAddress _ra; // Remote address descriptor const unsigned& _verbose; // Print some stuff if set uint64_t _timedOut; public: int _depth; }; class EbLfSvrLink : public EbLfLink { public: EbLfSvrLink(Fabrics::Endpoint*, int rxDepth, const unsigned& verbose); public: int prepare(unsigned id, const char* peer); int prepare(unsigned id, size_t* size, const char* peer); int setupMr(void* region, size_t size, const char* peer); private: int _synchronizeBegin(); int _synchronizeEnd(); }; class EbLfCltLink : public EbLfLink { public: EbLfCltLink(Fabrics::Endpoint*, int rxDepth, const unsigned& verbose, volatile uint64_t& pending); public: int prepare(unsigned id, const char* peer); int prepare(unsigned id, void* region, size_t lclSize, size_t rmtSize, const char* peer); int prepare(unsigned id, void* region, size_t size, const char* peer); int setupMr(void* region, size_t size); public: int post(const void* buf, size_t len, uint64_t offset, uint64_t immData, void* ctx = nullptr); private: int _synchronizeBegin(); int _synchronizeEnd(); private: // Arranged in order of access frequency volatile uint64_t& _pending; // Bit list of IDs currently posting }; }; }; inline void* Pds::Eb::EbLfLink::lclAdx(size_t offset) const { return static_cast<char*>(_mr->start()) + offset; } inline size_t Pds::Eb::EbLfLink::lclOfs(const void* buffer) const { return static_cast<const char*>(buffer) - static_cast<const char*>(_mr->start()); } inline uintptr_t Pds::Eb::EbLfLink::rmtAdx(size_t offset) const { return _ra.addr + offset; } inline size_t Pds::Eb::EbLfLink::rmtOfs(uintptr_t buffer) const { return buffer - _ra.addr; } inline ssize_t Pds::Eb::EbLfLink::postCompRecv(unsigned count) { ssize_t rc = 0; for (unsigned i = 0; i < count; ++i) { rc = postCompRecv(); if (rc) break; } return rc; } #endif
28.585526
104
0.560184
slac-lcls
203e80f0620ee2e5c2eaa63de1aea61ab20e64ea
2,597
hpp
C++
example/resnet/model.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
93
2017-10-25T07:48:42.000Z
2022-02-02T15:18:11.000Z
example/resnet/model.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
null
null
null
example/resnet/model.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
20
2018-02-06T10:01:36.000Z
2019-07-07T09:26:40.000Z
/** * the model define by resnet */ #include "licon/licon.hpp" using namespace std; using namespace licon; nn::NodePtr BasicBlock(int in_channel, int out_channel, int stride=1) { auto basic_block = nn::Squential::CreateSquential(); auto conv_block = nn::Squential::CreateSquential(); conv_block->Add(nn::Conv::CreateConv(in_channel, out_channel, 3, stride, 1)); conv_block->Add(nn::BatchNorm::CreateBatchNorm(out_channel)); conv_block->Add(nn::Relu::CreateRelu()); conv_block->Add(nn::Conv::CreateConv(out_channel, out_channel, 3, 1, 1)); conv_block->Add(nn::BatchNorm::CreateBatchNorm(out_channel)); if(stride == 1 && in_channel == out_channel) { auto identity = nn::EltWiseSum::CreateEltWiseSum(true); identity->Add(std::move(conv_block)); basic_block->Add(std::move(identity)); basic_block->Add(nn::Relu::CreateRelu()); } else { auto identity = nn::EltWiseSum::CreateEltWiseSum(false); auto short_cut = nn::Squential::CreateSquential(); short_cut->Add(nn::Conv::CreateConv(in_channel, out_channel, 1, stride)); short_cut->Add(nn::BatchNorm::CreateBatchNorm(out_channel)); identity->Add(std::move(conv_block)); identity->Add(std::move(short_cut)); basic_block->Add(std::move(identity)); basic_block->Add(nn::Relu::CreateRelu()); } return basic_block; } nn::Model ResNet(const std::vector<int>& num_blocks, int num_classes=10) { auto model = nn::Squential::CreateSquential(); int in_channel = 32; auto _make_layer = [&in_channel](int out_channel, int num_blocks, int stride) { vector<int> strides = {stride}; for(int i = 0; i < num_blocks - 1; ++i) strides.emplace_back(1); auto layers = nn::Squential::CreateSquential(); for(auto s : strides) { layers->Add(BasicBlock(in_channel, out_channel, s)); in_channel = out_channel * 1; } return layers; }; model->Add(nn::Conv::CreateConv(3, 32, 3, 1, 1)); model->Add(nn::BatchNorm::CreateBatchNorm(32)); model->Add(nn::Relu::CreateRelu()); model->Add(_make_layer(32, num_blocks[0], 1)); model->Add(_make_layer(64, num_blocks[1], 2)); //16 model->Add(_make_layer(128, num_blocks[2], 2)); //8 model->Add(_make_layer(256, num_blocks[3], 2)); //4 model->Add(nn::AvePool::CreateAvePool(4)); //512 * 1 * 1 model->Add(nn::Linear::CreateLinear(256, num_classes)); model->Add(nn::Softmax::CreateSoftmax()); return model; } nn::Model ResNet18() { return ResNet({2, 2, 2, 2}); }
38.761194
83
0.644975
wzppengpeng
2040523da9fbf8fa9a4f9488a0b88c808831f963
655
cpp
C++
383.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
383.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
383.cpp
pengzhezhe/LeetCode
305ec0c5b4cb5ea7cd244b3308132dee778138bc
[ "Apache-2.0" ]
null
null
null
// // Created by pzz on 2021/10/20. // #include <iostream> #include <algorithm> #include <string> using namespace std; class Solution { public: bool canConstruct(string ransomNote, string magazine) { int record[26] = {0}; for (char c: ransomNote) record[c - 'a']++; for (char c: magazine) record[c - 'a']--; for (int i: record) { if (i > 0) return false; } return true; } }; int main() { string ransomNote = "a"; string magazine = "ab"; Solution solution; cout << solution.canConstruct(ransomNote, magazine); return 0; }
18.194444
59
0.538931
pengzhezhe
204162dacd7d6099609d23ddb4a3b6737485e432
5,423
cpp
C++
TouchGFXPortTo_ILI9341_XPT2046_basic_yt_tut2/TouchGFX/generated/images/src/BitmapDatabase.cpp
trteodor/TouchGFX_Test
cd1abdef7e5a6f161ad35754fd951ea5de076021
[ "MIT" ]
1
2022-02-25T07:20:23.000Z
2022-02-25T07:20:23.000Z
TouchGFXPortTo_ILI9341_XPT2046_basic_yt_tut2/TouchGFX/generated/images/src/BitmapDatabase.cpp
trteodor/TouchGFX_Test
cd1abdef7e5a6f161ad35754fd951ea5de076021
[ "MIT" ]
null
null
null
TouchGFXPortTo_ILI9341_XPT2046_basic_yt_tut2/TouchGFX/generated/images/src/BitmapDatabase.cpp
trteodor/TouchGFX_Test
cd1abdef7e5a6f161ad35754fd951ea5de076021
[ "MIT" ]
1
2021-12-26T22:11:21.000Z
2021-12-26T22:11:21.000Z
// 4.16.1 0x3fe153e6 // Generated by imageconverter. Please, do not edit! #include <BitmapDatabase.hpp> #include <touchgfx/Bitmap.hpp> extern const unsigned char image_blue_radio_buttons_radio_button_active[]; // BITMAP_BLUE_RADIO_BUTTONS_RADIO_BUTTON_ACTIVE_ID = 0, Size: 44x44 pixels extern const unsigned char image_blue_radio_buttons_radio_button_inactive[]; // BITMAP_BLUE_RADIO_BUTTONS_RADIO_BUTTON_INACTIVE_ID = 1, Size: 44x44 pixels extern const unsigned char image_butterflysmaller[]; // BITMAP_BUTTERFLYSMALLER_ID = 2, Size: 64x64 pixels extern const unsigned char image_diodes[]; // BITMAP_DIODES_ID = 3, Size: 32x32 pixels extern const unsigned char image_hor_therm_bg_scale[]; // BITMAP_HOR_THERM_BG_SCALE_ID = 4, Size: 280x77 pixels extern const unsigned char image_hor_therm_progress[]; // BITMAP_HOR_THERM_PROGRESS_ID = 5, Size: 244x18 pixels extern const unsigned char image_ledoff_scaled[]; // BITMAP_LEDOFF_SCALED_ID = 6, Size: 64x64 pixels extern const unsigned char image_ledon_sclaed[]; // BITMAP_LEDON_SCLAED_ID = 7, Size: 64x64 pixels extern const unsigned char image_menuscaled[]; // BITMAP_MENUSCALED_ID = 8, Size: 64x64 pixels extern const unsigned char image_menuscaledwhite[]; // BITMAP_MENUSCALEDWHITE_ID = 9, Size: 64x64 pixels extern const unsigned char image_mp3future[]; // BITMAP_MP3FUTURE_ID = 10, Size: 64x64 pixels extern const unsigned char image_mp3futurepressed[]; // BITMAP_MP3FUTUREPRESSED_ID = 11, Size: 64x64 pixels extern const unsigned char image_tempoff[]; // BITMAP_TEMPOFF_ID = 12, Size: 64x64 pixels extern const unsigned char image_temponn[]; // BITMAP_TEMPONN_ID = 13, Size: 64x64 pixels extern const unsigned char image_tictactoeoff[]; // BITMAP_TICTACTOEOFF_ID = 14, Size: 64x64 pixels extern const unsigned char image_tictactoeon[]; // BITMAP_TICTACTOEON_ID = 15, Size: 64x64 pixels extern const unsigned char image_trashszary[]; // BITMAP_TRASHSZARY_ID = 16, Size: 64x64 pixels extern const unsigned char image_watchblack[]; // BITMAP_WATCHBLACK_ID = 17, Size: 64x64 pixels extern const unsigned char image_watchwhite[]; // BITMAP_WATCHWHITE_ID = 18, Size: 64x64 pixels extern const unsigned char image_whitetrash[]; // BITMAP_WHITETRASH_ID = 19, Size: 64x64 pixels const touchgfx::Bitmap::BitmapData bitmap_database[] = { { image_blue_radio_buttons_radio_button_active, 0, 44, 44, 3, 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_blue_radio_buttons_radio_button_inactive, 0, 44, 44, 3, 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_butterflysmaller, 0, 64, 64, 50, 34, 2, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 20, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_diodes, 0, 32, 32, 0, 0, 32, (uint8_t)(touchgfx::Bitmap::RGB565) >> 3, 32, (uint8_t)(touchgfx::Bitmap::RGB565) & 0x7 }, { image_hor_therm_bg_scale, 0, 280, 77, 27, 25, 226, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 24, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_hor_therm_progress, 0, 244, 18, 9, 0, 226, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 18, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_ledoff_scaled, 0, 64, 64, 16, 11, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_ledon_sclaed, 0, 64, 64, 16, 11, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_menuscaled, 0, 64, 64, 20, 20, 24, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 4, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_menuscaledwhite, 0, 64, 64, 20, 20, 24, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 4, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_mp3future, 0, 64, 64, 10, 9, 44, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 46, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_mp3futurepressed, 0, 64, 64, 10, 9, 44, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 46, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_tempoff, 0, 64, 64, 21, 6, 13, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 56, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_temponn, 0, 64, 64, 21, 6, 13, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 56, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_tictactoeoff, 0, 64, 64, 11, 27, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 36, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_tictactoeon, 0, 64, 64, 11, 27, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 36, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_trashszary, 0, 64, 64, 8, 9, 48, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 10, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_watchblack, 0, 64, 64, 8, 11, 21, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_watchwhite, 0, 64, 64, 8, 11, 21, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }, { image_whitetrash, 0, 64, 64, 8, 9, 48, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 10, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 } }; namespace BitmapDatabase { const touchgfx::Bitmap::BitmapData* getInstance() { return bitmap_database; } uint16_t getInstanceSize() { return (uint16_t)(sizeof(bitmap_database) / sizeof(touchgfx::Bitmap::BitmapData)); } }
84.734375
169
0.717868
trteodor