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
dd9a19698deae1729c3f357c3c054c787efda000
2,605
hpp
C++
Source/ReplicantHook/ReplicantHook.hpp
Asiern/ReplicantHook
63cbfd361d738dc37177c8fcf6e2657dc20bd9aa
[ "MIT" ]
11
2021-04-25T15:29:29.000Z
2022-02-27T09:49:54.000Z
Source/ReplicantHook/ReplicantHook.hpp
Asiern/ReplicantHook
63cbfd361d738dc37177c8fcf6e2657dc20bd9aa
[ "MIT" ]
6
2021-04-26T07:39:52.000Z
2021-10-06T14:12:09.000Z
Source/ReplicantHook/ReplicantHook.hpp
Asiern/ReplicantHook
63cbfd361d738dc37177c8fcf6e2657dc20bd9aa
[ "MIT" ]
1
2021-08-28T22:13:50.000Z
2021-08-28T22:13:50.000Z
#pragma once #include <Windows.h> #include <TlHelp32.h> #include <string> #include "Offsets.hpp" #include <map> class ReplicantHook { private: DWORD _pID; uintptr_t _baseAddress; uintptr_t actorPlayable; bool _hooked; offsets _offsets; int _version; std::map<std::string, uintptr_t> _inventory; int gold; std::string zone; std::string name; int health; float magic; int level; double playtime; float x; float y; float z; DWORD _getProcessID(void); uintptr_t _getModuleBaseAddress(DWORD procId, const wchar_t* modName); void _hook(void); void _unHook(void); void _patch(BYTE* destination, BYTE* src, unsigned int size); template <typename T> T readMemory(uintptr_t address); template <typename T> void writeMemory(uintptr_t address, T value); std::string readMemoryString(uintptr_t address); void writeMemoryString(uintptr_t address, std::string value); void loadInventory(); uintptr_t getItemAddress(std::string name); public: ReplicantHook(int version); ~ReplicantHook(); DWORD getProcessID(void); uintptr_t getBaseAddress(void); void start(void); void stop(void); void hookStatus(void); void update(); //Getters bool isHooked(void); int getGold(); std::string getZone(); std::string getName(); int getHealth(); float getMagic(); int getLevel(); double getPlaytime(); float getX(); float getY(); float getZ(); //Setters void setGold(int value); void setZone(std::string value); void setName(std::string value); void setHealth(int value); void setMagic(float value); void setLevel(int value); void setPlaytime(double value); void setX(float value); void setY(float value); void setZ(float value); void setPosition(float x, float y, float z); //Cheats void InfiniteHealth(bool enabled); void InfiniteMagic(bool enabled); //Models void setActorModel(std::string model); std::string getActorModel(); //Inventory std::map<std::string, uintptr_t> getInventory(void); int addItem(std::string name, int quantity); int removeItem(std::string name); }; template<typename T> inline T ReplicantHook::readMemory(uintptr_t address) { T value; HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, this->_pID); ReadProcessMemory(pHandle, (LPCVOID)(address), &value, sizeof(value), NULL); CloseHandle(pHandle); //Close handle to prevent memory leaks return value; } template<typename T> inline void ReplicantHook::writeMemory(uintptr_t address, T value) { HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, NULL, this->_pID); WriteProcessMemory(pHandle, (LPVOID)(address), &value, sizeof(value), NULL); CloseHandle(pHandle); }
23.053097
77
0.74357
Asiern
dd9df012e1a640f25433cf2e364c3ebc8b1c7482
4,275
hpp
C++
src/stm32/registers/cpu_registers.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
null
null
null
src/stm32/registers/cpu_registers.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
2
2021-04-01T21:31:55.000Z
2021-04-06T07:35:04.000Z
src/stm32/registers/cpu_registers.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> #include "../utils/general.hpp" namespace stm32::rg { /** * The special-purpose program status registers, xPSR */ DEFINE_REG(ApplicationProgramStatusRegister, { RESERVE(27); ///< bits[26:0] bool Q : 1; ///< bit[27] ///< Set to 1 if a SSAT or USAT instruction changes the input value for the signed or unsigned range ///< of the result. In a processor that implements the DSP extension, the processor sets this bit ///< to 1 to indicate an overflow on some multiplies. Setting this bit to 1 is called saturation. bool V : 1; ///< overflow, bit[28] ///< Overflow condition code flag. Set to 1 if the instruction results in an overflow condition, for ///< example a signed overflow on an addition. bool C : 1; ///< carry, bit[29] ///< Carry condition code flag. Set to 1 if the instruction results in a carry condition, for example an ///< unsigned overflow on an addition. bool Z : 1; ///< zero, bit[30] ///< Zero condition code flag. Set to 1 if the result of the instruction is zero, and to 0 otherwise. A ///< result of zero often indicates an equal result from a comparison. bool N : 1; ///< negative, bit[31] ///< Negative condition code flag. Set to bit[31] of the result of the instruction. If the result is ///< regarded as a two's complement signed integer, then N == 1 if the result is negative and N == 0 if ///< it is positive or zero. }); DEFINE_REG(InterruptProgramStatusRegister, { uint16_t exceptionNumber : 9; ///< bits[8:0] ///< When the processor is executing an exception handler, holds the exception number ///< of the exception being processed. Otherwise, the IPSR value is zero. RESERVE(23); ///< bits[31:9] }); DEFINE_REG(ExecutionProgramStatusRegister, { RESERVE(10); ///< bits[9:0] uint8_t ITlo : 6; ///< bits[15:10] ///< high 6 bits of IT bool T : 1; ///< bit[24] ///< T bit, that is set to 1 to indicate that the processor executes Thumb instructions uint8_t IThi : 2; ///< bits[26:25] ///< low two bits of ITd RESERVE(5); ///< bits[31:27] }); /** * The special-purpose mask registers */ DEFINE_REG(ExceptionMaskRegister, { bool PM : 1; ///< bit[0] ///< Setting PRIMASK to 1 raises the execution priority to 0. RESERVE(31); ///< bits[31:1] }); DEFINE_REG(BasePriorityMaskRegister, { uint8_t level : 8; ///< bit[7:0] ///< Changes the priority level required for exception preemption. It has an effect only when ///< it has a lower value than the unmasked priority level of the currently executing software. RESERVE(24); ///< bits[31:8] }); DEFINE_REG(FaultMaskRegister, { bool FM : 1; ///< bit[0] ///< Setting FM to 1 raises the execution priority to -1, the priority of HardFault. Only ///< privileged software executing at a priority below -1 can set FM to 1. This means ///< HardFault and NMI handlers cannot set FM to 1. Returning from any exception except NMI ///< clears FM to 0. RESERVE(31); ///< bits[31:1] }); /** * The special-purpose CONTROL 2-bit register */ struct __attribute__((__packed__)) ControlRegister { bool nPRIV : 1; ///< bit[0] ///< Defines the execution privilege in Thread mode ///< ///< false - Thread mode has privileged access. ///< ///< true - Thread mode has unprivileged access. bool SPSEL : 1; ///< bit[1] ///< Defines the stack to be used ///< ///< false - Use SP_main as the current stack. ///< ///< true - In Thread mode, use SP_process as the current stack. ///< In Handler mode, this value is reserved }; } // namespace stm32::rg
38.863636
121
0.56
Rexagon
dd9ee85db0caffeef07daeaec74107f9f0614fd0
23,906
cpp
C++
saber/funcs/impl/arm/neon/saber_softmax.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
533
2018-05-18T06:14:04.000Z
2022-03-23T11:46:30.000Z
saber/funcs/impl/arm/neon/saber_softmax.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
100
2018-05-26T08:32:48.000Z
2022-03-17T03:26:25.000Z
saber/funcs/impl/arm/neon/saber_softmax.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
167
2018-05-18T06:14:35.000Z
2022-02-14T01:44:20.000Z
#include "saber/funcs/impl/arm/saber_softmax.h" #include "saber/funcs/impl/arm/neon/impl/neon_mathfun.h" namespace anakin{ namespace saber{ void softmax_basic(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size) { #pragma omp parallel for for (int i = 0; i < compute_size; ++i) { int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_channel_in8(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size){ int cmp_cnt = compute_size >> 3; int remain = compute_size % 8; float32x4_t vone = vdupq_n_f32(1.0f); #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 8; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; //! get max axis_size == 4 const float* din_ptr = din + real_index; const float* din_ptr1 = din_ptr + inner_num; const float* din_ptr2 = din_ptr1 + inner_num; const float* din_ptr3 = din_ptr2 + inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr1); float32x4_t vdata2 = vld1q_f32(din_ptr2); float32x4_t vdata3 = vld1q_f32(din_ptr3); float32x4_t vdata01 = vld1q_f32(din_ptr + 4); float32x4_t vdata11 = vld1q_f32(din_ptr1 + 4); float32x4_t vdata21 = vld1q_f32(din_ptr2 + 4); float32x4_t vdata31 = vld1q_f32(din_ptr3 + 4); float* dout_ptr0 = dout + real_index; float* dout_ptr1 = dout_ptr0 + inner_num; float32x4_t vmax1 = vmaxq_f32(vdata0, vdata1); float32x4_t vmax2 = vmaxq_f32(vdata2, vdata3); float32x4_t vmax11 = vmaxq_f32(vdata01, vdata11); float32x4_t vmax21 = vmaxq_f32(vdata21, vdata31); float* dout_ptr2 = dout_ptr1 + inner_num; float* dout_ptr3 = dout_ptr2 + inner_num; float32x4_t vmax = vmaxq_f32(vmax1, vmax2); float32x4_t vmax_1 = vmaxq_f32(vmax11, vmax21); //! sub, exp and sum float32x4_t vsum0 = exp_ps(vsubq_f32(vdata0, vmax)); float32x4_t vsum1 = exp_ps(vsubq_f32(vdata1, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax)); float32x4_t vsum3 = exp_ps(vsubq_f32(vdata3, vmax)); float32x4_t vsum01 = exp_ps(vsubq_f32(vdata01, vmax_1)); float32x4_t vsum11 = exp_ps(vsubq_f32(vdata11, vmax_1)); float32x4_t vsum21 = exp_ps(vsubq_f32(vdata21, vmax_1)); float32x4_t vsum31 = exp_ps(vsubq_f32(vdata31, vmax_1)); float32x4_t vsum_1 = vaddq_f32(vsum0, vsum1); float32x4_t vsum_2 = vaddq_f32(vsum2, vsum3); float32x4_t vsum_11 = vaddq_f32(vsum01, vsum11); float32x4_t vsum_21 = vaddq_f32(vsum21, vsum31); float32x4_t vsum = vaddq_f32(vsum_1, vsum_2); float32x4_t vsum111 = vaddq_f32(vsum_11, vsum_21); float32x4_t vinf = div_ps(vone, vsum); float32x4_t vinf1 = div_ps(vone, vsum111); vsum0 = vmulq_f32(vsum0, vinf); vsum1 = vmulq_f32(vsum1, vinf); vsum2 = vmulq_f32(vsum2, vinf); vsum3 = vmulq_f32(vsum3, vinf); vsum01 = vmulq_f32(vsum01, vinf1); vsum11 = vmulq_f32(vsum11, vinf1); vsum21 = vmulq_f32(vsum21, vinf1); vsum31 = vmulq_f32(vsum31, vinf1); vst1q_f32(dout_ptr0, vsum0); vst1q_f32(dout_ptr1, vsum1); vst1q_f32(dout_ptr2, vsum2); vst1q_f32(dout_ptr3, vsum3); vst1q_f32(dout_ptr0 + 4, vsum01); vst1q_f32(dout_ptr1 + 4, vsum11); vst1q_f32(dout_ptr2 + 4, vsum21); vst1q_f32(dout_ptr3 + 4, vsum31); } int i = cmp_cnt * 8; if (remain > 4){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; //! get max axis_size == 4 const float* din_ptr = din + real_index; const float* din_ptr1 = din_ptr + inner_num; const float* din_ptr2 = din_ptr1 + inner_num; const float* din_ptr3 = din_ptr2 + inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr1); float32x4_t vdata2 = vld1q_f32(din_ptr2); float32x4_t vdata3 = vld1q_f32(din_ptr3); float* dout_ptr0 = dout + real_index; float* dout_ptr1 = dout_ptr0 + inner_num; float32x4_t vmax1 = vmaxq_f32(vdata0, vdata1); float32x4_t vmax2 = vmaxq_f32(vdata2, vdata3); float* dout_ptr2 = dout_ptr1 + inner_num; float* dout_ptr3 = dout_ptr2 + inner_num; float32x4_t vmax = vmaxq_f32(vmax1, vmax2); //! sub, exp and sum float32x4_t vsum0 = exp_ps(vsubq_f32(vdata0, vmax)); float32x4_t vsum1 = exp_ps(vsubq_f32(vdata1, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax)); float32x4_t vsum3 = exp_ps(vsubq_f32(vdata3, vmax)); float32x4_t vsum_1 = vaddq_f32(vsum0, vsum1); float32x4_t vsum_2 = vaddq_f32(vsum2, vsum3); float32x4_t vsum = vaddq_f32(vsum_1, vsum_2); float32x4_t vone = vdupq_n_f32(1.0f); float32x4_t vinf = div_ps(vone, vsum); vsum0 = vmulq_f32(vsum0, vinf); vsum1 = vmulq_f32(vsum1, vinf); vsum2 = vmulq_f32(vsum2, vinf); vsum3 = vmulq_f32(vsum3, vinf); vst1q_f32(dout_ptr0, vsum0); vst1q_f32(dout_ptr1, vsum1); vst1q_f32(dout_ptr2, vsum2); vst1q_f32(dout_ptr3, vsum3); i += 4; } for (; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_channel_in4(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size){ int cmp_cnt = compute_size >> 2; int remain = compute_size % 4; float32x4_t vone = vdupq_n_f32(1.0f); #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 4; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; //! get max axis_size == 4 const float* din_ptr = din + real_index; const float* din_ptr1 = din_ptr + inner_num; const float* din_ptr2 = din_ptr1 + inner_num; const float* din_ptr3 = din_ptr2 + inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr1); float32x4_t vdata2 = vld1q_f32(din_ptr2); float32x4_t vdata3 = vld1q_f32(din_ptr3); float* dout_ptr0 = dout + real_index; float* dout_ptr1 = dout_ptr0 + inner_num; float32x4_t vmax1 = vmaxq_f32(vdata0, vdata1); float32x4_t vmax2 = vmaxq_f32(vdata2, vdata3); float* dout_ptr2 = dout_ptr1 + inner_num; float* dout_ptr3 = dout_ptr2 + inner_num; float32x4_t vmax = vmaxq_f32(vmax1, vmax2); //! sub, exp and sum float32x4_t vsum0 = exp_ps(vsubq_f32(vdata0, vmax)); float32x4_t vsum1 = exp_ps(vsubq_f32(vdata1, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax)); float32x4_t vsum3 = exp_ps(vsubq_f32(vdata3, vmax)); float32x4_t vsum_1 = vaddq_f32(vsum0, vsum1); float32x4_t vsum_2 = vaddq_f32(vsum2, vsum3); float32x4_t vsum = vaddq_f32(vsum_1, vsum_2); float32x4_t vinf = div_ps(vone, vsum); vsum0 = vmulq_f32(vsum0, vinf); vsum1 = vmulq_f32(vsum1, vinf); vsum2 = vmulq_f32(vsum2, vinf); vsum3 = vmulq_f32(vsum3, vinf); vst1q_f32(dout_ptr0, vsum0); vst1q_f32(dout_ptr1, vsum1); vst1q_f32(dout_ptr2, vsum2); vst1q_f32(dout_ptr3, vsum3); } int i = cmp_cnt * 8; for (; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; // printf("real_index: %d, din: %x\n", real_index, din); float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_in8(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size) { int cmp_cnt = compute_size >> 3; #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 8; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; const float* din_ptr = din + real_index; float32x4_t vmax = vld1q_f32(din_ptr); float32x4_t vmax2 = vld1q_f32(din_ptr + 4); //! get max for (int j = 1; j < axis_size; ++j) { din_ptr += inner_num; float32x4_t vdata = vld1q_f32(din_ptr); float32x4_t vdata2 = vld1q_f32(din_ptr + 4); vmax = vmaxq_f32(vmax, vdata); vmax2 = vmaxq_f32(vmax2, vdata2); } //! sub, exp and sum // dout[real_index] = expf(din[real_index] - max_data); din_ptr = din + real_index; float* dout_ptr = dout + real_index; float32x4_t vdata = vld1q_f32(din_ptr); float32x4_t vdata2 = vld1q_f32(din_ptr + 4); float32x4_t vsum = exp_ps(vsubq_f32(vdata, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax2)); din_ptr += inner_num; vst1q_f32(dout_ptr, vsum); vst1q_f32(dout_ptr + 4, vsum2); dout_ptr += inner_num; //float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { // real_index += inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr + 4); vdata0 = exp_ps(vsubq_f32(vdata0, vmax)); vdata1 = exp_ps(vsubq_f32(vdata1, vmax2)); din_ptr += inner_num; vsum = vaddq_f32(vsum, vdata0); vsum2 = vaddq_f32(vsum2, vdata1); vst1q_f32(dout_ptr, vdata0); vst1q_f32(dout_ptr + 4, vdata1); dout_ptr += inner_num; } // float sum_inv = 1.f / sum_data; float32x4_t vone = vdupq_n_f32(1.0f); float32x4_t vinf = div_ps(vone, vsum); float32x4_t vinf2 = div_ps(vone, vsum2); dout_ptr = dout + real_index; //printf("real_index: %d, dout: %x, dout_ptr: %x \n", real_index, dout, dout_ptr); // real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { float32x4_t vdata0 = vld1q_f32(dout_ptr); float32x4_t vdata1 = vld1q_f32(dout_ptr + 4); vdata0 = vmulq_f32(vdata0, vinf); vdata1 = vmulq_f32(vdata1, vinf2); vst1q_f32(dout_ptr, vdata0); vst1q_f32(dout_ptr + 4, vdata1); dout_ptr += inner_num; } } for (int i = cmp_cnt * 8; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; // printf("real_index: %d, din: %x\n", real_index, din); float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_in4(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size) { int cmp_cnt = compute_size >> 2; #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 4; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; const float* din_ptr = din + real_index; float32x4_t vmax = vld1q_f32(din_ptr); //! get max for (int j = 1; j < axis_size; ++j) { din_ptr += inner_num; float32x4_t vdata = vld1q_f32(din_ptr); vmax = vmaxq_f32(vmax, vdata); } //! sub, exp and sum // dout[real_index] = expf(din[real_index] - max_data); din_ptr = din + real_index; float* dout_ptr = dout + real_index; float32x4_t vdata = vld1q_f32(din_ptr); float32x4_t vsum = exp_ps(vsubq_f32(vdata, vmax)); din_ptr += inner_num; vst1q_f32(dout_ptr, vsum); dout_ptr += inner_num; //float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { // real_index += inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); vdata0 = exp_ps(vsubq_f32(vdata0, vmax)); din_ptr += inner_num; vsum = vaddq_f32(vsum, vdata0); vst1q_f32(dout_ptr, vdata0); dout_ptr += inner_num; } // float sum_inv = 1.f / sum_data; float32x4_t vone = vdupq_n_f32(1.0f); float32x4_t vinf = div_ps(vone, vsum); dout_ptr = dout + real_index; //! get softmax result for (int j = 0; j < axis_size; ++j) { float32x4_t vdata0 = vld1q_f32(dout_ptr); vdata0 = vmulq_f32(vdata0, vinf); vst1q_f32(dout_ptr, vdata0); dout_ptr += inner_num; } } for (int i = cmp_cnt * 4; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } //! for inner size == 1 void softmax_inner1(const float* din, float* dout, \ const int outer_size, const int axis_size) { #pragma omp parallel for for (int i = 0; i < outer_size; ++i) { const float* din_ptr = din + i * axis_size; float* dout_ptr = dout + i * axis_size; const float* din_max_ptr = din_ptr; int nn = axis_size >> 2; //! get max float32x4_t vmax = vld1q_f32(din_max_ptr); din_max_ptr += 4; int j = 1; for (; j < nn; ++j) { vmax = vmaxq_f32(vmax, vld1q_f32(din_max_ptr)); din_max_ptr += 4; } float32x2_t vhmax = vmax_f32(vget_high_f32(vmax), vget_low_f32(vmax)); float max_data = std::max(vget_lane_f32(vhmax, 0), vget_lane_f32(vhmax, 1)); for (j = 4 * j; j < axis_size; ++j) { max_data = std::max(max_data, din_max_ptr[0]); din_max_ptr++; } //printf("max data: %.2f\n", max_data); //! sub, exp and sum const float* din_sum_ptr = din_ptr; float* dout_sum_ptr = dout_ptr; vmax = vdupq_n_f32(max_data); float32x4_t vsub_exp = exp_ps(vsubq_f32(vld1q_f32(din_sum_ptr), vmax)); float32x4_t vsum = vsub_exp; vst1q_f32(dout_sum_ptr, vsub_exp); din_sum_ptr += 4; dout_sum_ptr += 4; j = 1; for (; j < nn; ++j) { vsub_exp = exp_ps(vsubq_f32(vld1q_f32(din_sum_ptr), vmax)); vst1q_f32(dout_sum_ptr, vsub_exp); vsum = vaddq_f32(vsum, vsub_exp); din_sum_ptr += 4; dout_sum_ptr += 4; } float32x2_t vhsum = vadd_f32(vget_high_f32(vsum), vget_low_f32(vsum)); float sum_data = vget_lane_f32(vhsum, 0) + vget_lane_f32(vhsum, 1); for (j = 4 * j; j < axis_size; ++j) { dout_sum_ptr[0] = expf(din_sum_ptr[0] - max_data); sum_data += dout_sum_ptr[0]; din_sum_ptr++; dout_sum_ptr++; } //printf("sum data: %.2f\n", sum_data); float sum_inv = 1.f / sum_data; float* dout_res_ptr = dout_ptr; float32x4_t vinv = vdupq_n_f32(sum_inv); //! get softmax result j = 0; for (; j < nn; ++j) { float32x4_t vout = vld1q_f32(dout_res_ptr); float32x4_t vres= vmulq_f32(vout, vinv); vst1q_f32(dout_res_ptr, vres); dout_res_ptr += 4; } for (j = nn * 4; j < axis_size; ++j) { dout_ptr[j] *= sum_inv; } } } //! for inner size == 1 aixs_size < 4 void softmax_inner1_s(const float* din, float* dout, \ const int outer_size, const int axis_size) { #pragma omp parallel for for (int i = 0; i < outer_size; ++i) { const float* din_ptr = din + i * axis_size; float* dout_ptr = dout + i * axis_size; //! get max float max_data = din_ptr[0]; for (int j =1; j < axis_size; ++j) { max_data = std::max(max_data, din_ptr[j]); } //printf("max data: %.2f\n", max_data); //! sub, exp and sum float sum_data = 0.f; for (int j = 0; j < axis_size; ++j) { dout_ptr[j] = expf(din_ptr[j] - max_data); sum_data += dout_ptr[j]; } //printf("sum data: %.2f\n", sum_data); float sum_inv = 1.f / sum_data; for (int j = 0; j < axis_size; ++j) { dout_ptr[j] *= sum_inv; } } } template <> SaberStatus SaberSoftmax<ARM, AK_FLOAT>::dispatch(\ const std::vector<Tensor<ARM> *>& inputs, std::vector<Tensor<ARM> *>& outputs, SoftmaxParam<ARM> &param) { #ifdef ENABLE_OP_TIMER this->_timer.clear(); this->_timer.start(*this->_ctx); #endif float* dout = static_cast<float*>(outputs[0]->mutable_data()); const float* din = static_cast<const float*>(inputs[0]->data()); if (this->_inner_num == 1) { if (_axis_size >= 4){ softmax_inner1(din, dout, _outer_num, _axis_size); }else{ softmax_inner1_s(din, dout, _outer_num, _axis_size); } } else { int compute_size = inputs[0]->valid_size() / _axis_size; // softmax_basic(din, dout, _axis_size, _inner_num, _outer_num, compute_size); if (_axis_size == 4 && _inner_num % 8 == 0){ softmax_arm_lite_channel_in8(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else if (_axis_size == 4 && _inner_num % 4 == 0){ softmax_arm_lite_channel_in4(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else{ if (this->_inner_num % 8 == 0){ softmax_arm_lite_in8(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else if (this->_inner_num % 4 == 0){ softmax_arm_lite_in4(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else{ softmax_basic(din, dout, _axis_size, _inner_num, _outer_num, compute_size); } } } #ifdef ENABLE_OP_TIMER this->_timer.end(*this->_ctx); float ts = this->_timer.get_average_ms(); LOG(INFO) << "Softmax : " << this->_op_name.c_str() << " : time: " << ts; GOPS ops; float op_macs = 2.f * inputs[0]->valid_size() * 3; //fixme ops.ops = op_macs; ops.ts = ts; OpTimer::add_timer("Softmax", ops); OpTimer::add_timer("total", ops); #endif return SaberSuccess; } DEFINE_OP_TEMPLATE(SaberSoftmax, SoftmaxParam, ARM, AK_HALF); DEFINE_OP_TEMPLATE(SaberSoftmax, SoftmaxParam, ARM, AK_INT8); } //namespace anakin } //namespace anakin
36.609495
102
0.582364
baajur
dda1d5424118961cb5c53d2751a15a6381c31ee2
1,259
cpp
C++
UCF HSPT Documents/2007/Solutions/zero.cpp
p473lr/i-urge-mafia-gear
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
[ "Apache-2.0" ]
null
null
null
UCF HSPT Documents/2007/Solutions/zero.cpp
p473lr/i-urge-mafia-gear
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
[ "Apache-2.0" ]
null
null
null
UCF HSPT Documents/2007/Solutions/zero.cpp
p473lr/i-urge-mafia-gear
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
[ "Apache-2.0" ]
null
null
null
// Guitar Zero solution // Written in C++ by Jobby Johns // UCF 2007 High School Programming Contest /* The solution is very simple. Get the number of score changes. Start the * score at 0. Then, get each score change one at a time and adjust the score * accordingly. Once all the score changes are done, output the result * ("Shreddin" if score is positive, "Guitar Zero" otherwise). */ #include <iostream> #include <fstream> using namespace std; int main() { // open the file ifstream infile("zero.in", ios::in); // variables int n; int songNum = 1; char c; // get the input value for each song and solve (stop if 0) while (infile >> n && n != 0) { // start the score and adjust it based on the input int score = 0; for (int i = 0; i < n; ++i) { infile >> c; if (c == '+') { score++; } else if (c == '-') { score--; } } // output the result cout << "Song " << songNum << ": "; if (score > 0) { cout << "Shreddin" << endl; } else { cout << "Guitar Zero" << endl; } // increment song number for next possible song songNum++; } //close the file and quit infile.close(); return 0; }
19.984127
79
0.560763
p473lr
dda483d94ce9cfa55a437bb7b8b995b0db566d45
358
hpp
C++
src/engineModules/eFont.hpp
psjuan97/JamEngine
20d98e6f3e962a518cc519fecd90205a52aba249
[ "MIT" ]
3
2019-09-30T08:23:03.000Z
2020-07-18T09:09:56.000Z
src/engineModules/eFont.hpp
psjuan97/JamEngine
20d98e6f3e962a518cc519fecd90205a52aba249
[ "MIT" ]
1
2019-09-28T14:17:05.000Z
2019-09-28T14:17:05.000Z
src/engineModules/eFont.hpp
psjuan97/JamEngine
20d98e6f3e962a518cc519fecd90205a52aba249
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <SDL2/SDL_ttf.h> ///////// /// TODO /// liberar la fuente en el destructor class eFont{ public: eFont(const char* str, int size); ~eFont(); inline TTF_Font* getSDLFont() const { return sdl_font; }; private: TTF_Font* sdl_font = nullptr; };
16.272727
45
0.539106
psjuan97
dda5c67804d14f06cabfc9360bcb4c7d47d84892
286
hpp
C++
astronomy/solar_system_fingerprints.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
astronomy/solar_system_fingerprints.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
astronomy/solar_system_fingerprints.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> namespace principia { namespace astronomy { constexpr std::uint64_t KSPStockSystemFingerprint = 0x54B6323B3376D6F3; constexpr std::uint64_t KSPStabilizedSystemFingerprint = 0xB57B58F9CF757C62; } // namespace astronomy } // namespace principia
22
76
0.793706
madman2003
dda802b3b39ca7770bd99d0241c745b1a170b539
21,721
cpp
C++
ExternalSource/myOptimizer/ConicSolver/src/solver/optimizer/IPSolver.cpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
1
2020-05-04T22:36:54.000Z
2020-05-04T22:36:54.000Z
ExternalSource/myOptimizer/ConicSolver/src/solver/optimizer/IPSolver.cpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
null
null
null
ExternalSource/myOptimizer/ConicSolver/src/solver/optimizer/IPSolver.cpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
null
null
null
/* * * ECOS - Embedded Conic Solver * Copyright (C) [2012-2015] A. Domahidi [domahidi@embotech.com], * Automatic Control Lab, ETH Zurich & embotech GmbH, Zurich, Switzerland. * * Copyright [2017] Max Planck Society. All rights reserved. * * 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 3 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/>. */ #include <ExternalSource/myOptimizer/ConicSolver/include/solver/optimizer/IPSolver.hpp> namespace solver { inline double dotProduct(int n, double* x, double* y) { double z = 0; int i; for( i=0; i<n; i++ ){ z += x[i]*y[i]; } return z; } void InteriorPointSolver::initialize(SolverStorage& stg, Cone& cone, SolverSetting& stgs) { // setup problem stg_ = &stg; stgs_ = &stgs; cone_ = &cone; this->internalInitialization(); } void InteriorPointSolver::internalInitialization() { // setup message printer this->getPrinter().initialize(this->getStgs()); // equilibration of problem data this->getEqRoutine().setEquilibration(this->getCone(), this->getStgs(), this->getStg()); this->getStg().At() = this->getStg().A().transpose(); this->getStg().Gt() = this->getStg().G().transpose(); this->getLinSolver().initialize(this->getCone(), this->getStgs(), this->getStg()); // initialize problem variables rho_.initialize(this->getCone()); opt_.initialize(this->getCone()); res_.initialize(this->getCone()); RHS1_.initialize(this->getCone()); RHS2_.initialize(this->getCone()); lbar_.initialize(this->getCone()); dopt1_.initialize(this->getCone()); dopt2_.initialize(this->getCone()); sigma_.initialize(this->getCone()); lambda_.initialize(this->getCone()); best_opt_.initialize(this->getCone()); ds_combined_.initialize(this->getCone()); dz_combined_.initialize(this->getCone()); ds_affine_by_W_.initialize(this->getCone()); W_times_dz_affine_.initialize(this->getCone()); } ExitCode InteriorPointSolver::initializeVariables() { // get scalings of problem data inires_x_ = std::max(1.0, this->getStg().c().norm()); inires_y_ = std::max(1.0, this->getStg().b().norm()); inires_z_ = std::max(1.0, this->getStg().h().norm()); // initialize KKT matrix and perform numeric factorization this->getLinSolver().initializeMatrix(); if ( this->getLinSolver().numericFactorization() != FactStatus::Optimal ){ this->getPrinter().display(Msg::MatrixFactorization, this->getInfo()); return ExitCode::Indeterminate; } // initialize primal variables int* invPerm = this->getLinSolver().invPerm().indices().data(); for (int i=0; i<this->getCone().numVars(); i++) { RHS1_[invPerm[i]] = 0; } for (int i=0; i<this->getCone().numLeq(); i++ ) { RHS1_[invPerm[this->getCone().numVars()+i]] = this->getStg().b()[i]; } for (int i=0; i<this->getCone().sizeLpc(); i++) { RHS1_[invPerm[this->getCone().lpConeStart()+i]] = this->getStg().h()[i]; } for (int l=0; l<this->getCone().numSoc(); l++ ){ for (int i=0; i<this->getCone().sizeSoc(l); i++) RHS1_[invPerm[this->getCone().extStartSoc(l)+i]] = this->getStg().cbh()[this->getCone().optStartSoc(l)+i]; } this->getInfo().get(SolverIntParam_NumRefsLinSolve) = this->getLinSolver().solve(RHS1_, dopt2_, true); opt_.x() = dopt2_.x(); opt_.s() = -dopt2_.z(); this->getCone().conicProjection(opt_.s()); // initialize dual variables for (int i=0; i<this->getCone().numVars(); i++){ RHS2_[invPerm[i]] = -this->getStg().c()[i]; } this->getInfo().get(SolverIntParam_NumRefsLinSolveAffine) = this->getLinSolver().solve(RHS2_, dopt1_, true); opt_.y() = dopt1_.y(); opt_.z() = dopt1_.z(); this->getCone().conicProjection(opt_.z()); // initialize variables for optimization for (int i=0; i<this->getCone().numVars(); i++) { RHS1_[invPerm[i]] = -this->getStg().c()[i]; } opt_.kappa() = opt_.tau() = 1.0; this->getInfo().get(SolverDoubleParam_StepLength) = this->getInfo().get(SolverDoubleParam_AffineStepLength) = 0.0; return ExitCode::Optimal; } void InteriorPointSolver::computeResiduals() { this->getLinSolver().matrixTransposeTimesVector(this->getStg().A(), opt_.y(), res_.x(), false, true); this->getLinSolver().matrixTransposeTimesVector(this->getStg().G(), opt_.z(), res_.x(), false, false); residual_x_ = res_.x().norm(); this->getLinSolver().matrixTransposeTimesVector(this->getStg().At(), opt_.x(), res_.y(), true, true); residual_y_ = res_.y().norm(); this->getLinSolver().matrixTransposeTimesVector(this->getStg().Gt(), opt_.x(), res_.z(), true, true); res_.z() += opt_.s(); residual_z_ = res_.z().norm(); cx_ = this->getStg().c().dot(opt_.x()); by_ = this->getStg().b().dot(opt_.y()); hz_ = this->getStg().h().dot(opt_.z()); res_ -= opt_.tau()*this->getStg().cbh(); residual_t_ = opt_.kappa() + cx_ + by_ + hz_; } double InteriorPointSolver::lineSearch(const Eigen::Ref<const Eigen::VectorXd>& dsvec, const Eigen::Ref<const Eigen::VectorXd>& dzvec, double tau, double dtau, double kappa, double dkappa) { int conestart, conesize; const double *lk, *dsk, *dzk; double *lkbar, *rhok, *sigmak; const double* ds = dsvec.data(); const double* dz = dzvec.data(); const double* lambda = lambda_.data(); double conicres_lk, conicres_ds, conicres_dz, inv_conicres, factor1, factor2; // Linear cone double rhomin = ds[0]/lambda[0]; double sigmamin = dz[0]/lambda[0]; for (int i=1; i<this->getCone().sizeLpc(); i++){ if (ds[i]/lambda[i]<rhomin) { rhomin = ds[i]/lambda[i]; } if (dz[i]/lambda[i]<sigmamin) { sigmamin = dz[i]/lambda[i]; } } double alpha = std::min(sigmamin,rhomin)<0.0 ? -1.0/std::min(sigmamin,rhomin) : 1.0/this->getStgs().get(SolverDoubleParam_DynamicRegularizationThresh); // Tau and kappa if (-tau/dtau>0 && -tau/dtau<alpha) { alpha = -tau/dtau; } if (-kappa/dkappa>0 && -kappa/dkappa<alpha) { alpha = -kappa/dkappa; } // Second order cone for (int i=0; i<this->getCone().numSoc(); i++) { // indices conesize = this->getCone().sizeSoc(i); conestart = this->getCone().startSoc(i); dsk = ds + conestart; dzk = dz + conestart; lk = lambda + conestart; lkbar = lbar_.data() + conestart; rhok = rho_.data() + conestart; sigmak = sigma_.data() + conestart; Eigen::Map<const Eigen::VectorXd> eig_lk(lk,conesize); Eigen::Map<const Eigen::VectorXd> eig_rhok(rhok, conesize); Eigen::Map<const Eigen::VectorXd> eig_sigmak(sigmak, conesize); // find residuals conicres_lk = this->getCone().conicResidual(eig_lk); if (conicres_lk <= 0.0) { continue; } for (int j=0; j<conesize; j++) { lkbar[j] = lk[j]/std::sqrt(conicres_lk); } conicres_ds = lkbar[0]*dsk[0]; for (int j=1; j<conesize; j++) { conicres_ds -= lkbar[j]*dsk[j]; } conicres_dz = lkbar[0]*dzk[0]; for (int j=1; j<conesize; j++) { conicres_dz -= lkbar[j]*dzk[j]; } // construct rhok and sigmak inv_conicres = 1.0/std::sqrt(conicres_lk); factor1 = (conicres_ds+dsk[0])/(lkbar[0]+1); factor2 = (conicres_dz+dzk[0])/(lkbar[0]+1); rhok[0] = inv_conicres * conicres_ds; sigmak[0] = inv_conicres * conicres_dz; for (int j=1; j<conesize; j++) { rhok[j] = inv_conicres*(dsk[j]-factor1*lkbar[j]); } for (int j=1; j<conesize; j++) { sigmak[j] = inv_conicres*(dzk[j]-factor2*lkbar[j]); } // update alpha alpha = std::min(alpha,1.0/std::max(std::max(eig_rhok.tail(conesize-1).norm()-rhok[0],eig_sigmak.tail(conesize-1).norm()-sigmak[0]),0.0)); } return std::max(std::min(alpha,this->getStgs().get(SolverDoubleParam_MaximumStepLength)),this->getStgs().get(SolverDoubleParam_MinimumStepLength)); } void InteriorPointSolver::updateStatistics() { this->getInfo().get(SolverDoubleParam_PrimalCost) = cx_ / opt_.tau(); this->getInfo().get(SolverDoubleParam_DualityGap) = opt_.s().dot(opt_.z()); this->getInfo().get(SolverDoubleParam_DualCost) = -(hz_ + by_) / opt_.tau(); this->getInfo().get(SolverDoubleParam_KappaOverTau) = opt_.kappa() / opt_.tau(); this->getInfo().get(SolverDoubleParam_MeritFunction) = (this->getInfo().get(SolverDoubleParam_DualityGap) + opt_.kappa()*opt_.tau()) / (this->getCone().sizeCone()+1); // relative duality gap if (this->getInfo().get(SolverDoubleParam_PrimalCost) < 0.0) { this->getInfo().get(SolverDoubleParam_RelativeDualityGap) = this->getInfo().get(SolverDoubleParam_DualityGap) / (-this->getInfo().get(SolverDoubleParam_PrimalCost)); } else if (this->getInfo().get(SolverDoubleParam_DualCost) > 0.0) { this->getInfo().get(SolverDoubleParam_RelativeDualityGap) = this->getInfo().get(SolverDoubleParam_DualityGap) / this->getInfo().get(SolverDoubleParam_DualCost); } else { this->getInfo().get(SolverDoubleParam_RelativeDualityGap) = SolverSetting::nan; } // residuals this->getInfo().get(SolverDoubleParam_PrimalResidual) = std::max(res_.y().norm()/std::max(inires_y_+opt_.x().norm(),1.0), res_.z().norm()/std::max(inires_z_+opt_.x().norm()+opt_.s().norm(),1.0)) / opt_.tau(); this->getInfo().get(SolverDoubleParam_DualResidual) = res_.x().norm()/std::max(inires_x_+opt_.y().norm()+opt_.z().norm(),1.0) / opt_.tau(); // infeasibility measures this->getInfo().get(SolverDoubleParam_PrimalInfeasibility) = (hz_ + by_)/std::max(opt_.y().norm()+opt_.z().norm(),1.0) < -this->getStgs().get(SolverDoubleParam_DualityGapRelTol) ? residual_x_ / std::max(opt_.y().norm()+opt_.z().norm(),1.0) : SolverSetting::nan; this->getInfo().get(SolverDoubleParam_DualInfeasibility) = cx_/std::max(opt_.x().norm(),1.0) < -this->getStgs().get(SolverDoubleParam_DualityGapRelTol) ? std::max(residual_y_/std::max(opt_.x().norm(),1.0), residual_z_/std::max(opt_.x().norm()+opt_.s().norm(),1.0)) : SolverSetting::nan; } ExitCode InteriorPointSolver::convergenceCheck(const PrecisionConvergence& mode) { this->getInfo().mode() = mode; double feastol, abstol, reltol; ExitCode exitcode = ExitCode::NotConverged; // set accuracy if ( mode == PrecisionConvergence::Full) { feastol = this->getStgs().get(SolverDoubleParam_FeasibilityTol); abstol = this->getStgs().get(SolverDoubleParam_DualityGapAbsTol); reltol = this->getStgs().get(SolverDoubleParam_DualityGapRelTol); } else { feastol = this->getStgs().get(SolverDoubleParam_FeasibilityTolInacc); abstol = this->getStgs().get(SolverDoubleParam_DualityGapAbsTolInacc); reltol = this->getStgs().get(SolverDoubleParam_DualityGapRelTolInacc); } // Optimality if ( (cx_<0.0 || by_+hz_<=abstol) && (this->getInfo().get(SolverDoubleParam_PrimalResidual)<feastol && this->getInfo().get(SolverDoubleParam_DualResidual)<feastol) && (this->getInfo().get(SolverDoubleParam_DualityGap)<abstol || this->getInfo().get(SolverDoubleParam_RelativeDualityGap)<reltol)) { this->getPrinter().display(Msg::OptimalityReached, this->getInfo()); (mode==PrecisionConvergence::Full ? exitcode=ExitCode::Optimal : exitcode=ExitCode::OptimalInacc); } // Dual infeasible else if( (this->getInfo().get(SolverDoubleParam_DualInfeasibility)!=SolverSetting::nan) && (this->getInfo().get(SolverDoubleParam_DualInfeasibility)<feastol) && (opt_.tau()<opt_.kappa()) ){ this->getPrinter().display(Msg::DualInfeasibility, this->getInfo()); (mode==PrecisionConvergence::Full ? exitcode=ExitCode::DualInf : exitcode=ExitCode::DualInfInacc); } // Primal infeasible else if( ((this->getInfo().get(SolverDoubleParam_PrimalInfeasibility)!=SolverSetting::nan && this->getInfo().get(SolverDoubleParam_PrimalInfeasibility)<feastol) && (opt_.tau()<opt_.kappa())) || (opt_.tau()<feastol && opt_.kappa()<feastol && this->getInfo().get(SolverDoubleParam_PrimalInfeasibility)<feastol)) { this->getPrinter().display(Msg::PrimalInfeasibility, this->getInfo()); (mode==PrecisionConvergence::Full ? exitcode=ExitCode::PrimalInf : exitcode=ExitCode::PrimalInfInacc); } return exitcode; } void InteriorPointSolver::saveIterateAsBest() { best_opt_ = opt_; this->getBestInfo() = this->getInfo(); this->getBestInfo().get(SolverIntParam_NumIter) = this->getInfo().get(SolverIntParam_NumIter); } void InteriorPointSolver::restoreBestIterate() { opt_ = best_opt_; this->getInfo() = this->getBestInfo(); } void InteriorPointSolver::rhsAffineStep() { const int* invPerm = this->getLinSolver().invPerm().indices().data(); for (int i=0; i<this->getCone().numVars(); i++ ) { RHS2_[invPerm[i]] = res_.x()[i]; } for (int i=0; i<this->getCone().numLeq(); i++ ) { RHS2_[invPerm[this->getCone().numVars()+i]] = -res_.y()[i]; } for (int i=0; i<this->getCone().sizeLpc(); i++ ) { RHS2_[invPerm[this->getCone().lpConeStart()+i]] = opt_.s()[i] - res_.z()[i]; } for (int l=0; l<this->getCone().numSoc(); l++) { for (int i=0; i < this->getCone().sizeSoc(l); i++ ) RHS2_[invPerm[this->getCone().extStartSoc(l)+i]] = opt_.s()[this->getCone().startSoc(l)+i] - res_.z()[this->getCone().startSoc(l)+i]; } } void InteriorPointSolver::rhsCenteringPredictorStep() { double* dz_combined_ptr = dz_combined_.data(); const int* invPerm = this->getLinSolver().invPerm().indices().data(); double factor = 1.0 - this->getInfo().get(SolverDoubleParam_CorrectionStepLength); for (int i=0; i<this->getCone().numVars(); i++) { RHS2_[invPerm[i]] *= factor; } for (int i=0; i<this->getCone().numLeq(); i++ ) { RHS2_[invPerm[this->getCone().numVars()+i]] *= factor; } for (int i=0; i<this->getCone().sizeLpc(); i++) { RHS2_[invPerm[this->getCone().lpConeStart()+i]] = dz_combined_ptr[i]; } for (int l=0; l < this->getCone().numSoc(); l++ ){ for (int i=0; i<this->getCone().sizeSoc(l); i++) RHS2_[invPerm[this->getCone().extStartSoc(l)+i]] = dz_combined_ptr[this->getCone().startSoc(l)+i]; } } ExitCode InteriorPointSolver::optimize() { prev_pres_ = SolverSetting::nan; exitcode_ = ExitCode::Indeterminate; if (initializeVariables() == ExitCode::Indeterminate) return ExitCode::Indeterminate; for (this->getInfo().get(SolverIntParam_NumIter)=0; this->getInfo().get(SolverIntParam_NumIter)<=this->getStgs().get(SolverIntParam_SolverMaxIters); this->getInfo().get(SolverIntParam_NumIter)++) { computeResiduals(); updateStatistics(); this->getPrinter().display(Msg::OptimizationProgress, this->getInfo()); // SAFEGUARD: Bad update or DualityGap became negative if (this->getInfo().get(SolverIntParam_NumIter)>0 && (this->getInfo().get(SolverDoubleParam_PrimalResidual)>this->getStgs().get(SolverDoubleParam_SafeGuard)*prev_pres_ || this->getInfo().get(SolverDoubleParam_DualityGap)<0)) { this->getPrinter().display(Msg::SearchDirection, best_info_); restoreBestIterate(); exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { this->getPrinter().display(Msg::NumericalProblem, info_); exitcode_ = ExitCode::PrSearchDirection; } break; } prev_pres_ = this->getInfo().get(SolverDoubleParam_PrimalResidual); // Check termination to full precision, mininum stepLength and maxNumIters reached exitcode_ = convergenceCheck(PrecisionConvergence::Full); if (exitcode_ == ExitCode::NotConverged) { // Mininum stepLength if (this->getInfo().get(SolverIntParam_NumIter)>0 && this->getInfo().get(SolverDoubleParam_StepLength)==this->getStgs().get(SolverDoubleParam_MinimumStepLength)*this->getStgs().get(SolverDoubleParam_StepLengthScaling)) { this->getPrinter().display(Msg::LineSearchStagnation, this->getBestInfo()); restoreBestIterate(); exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { exitcode_ = ExitCode::PrSearchDirection; this->getPrinter().display(Msg::NumericalProblem, this->getInfo()); } break; } // Reached maxNumIters else if (this->getInfo().get(SolverIntParam_NumIter)==this->getStgs().get(SolverIntParam_SolverMaxIters)) { if (!this->getInfo().isBetterThan(this->getBestInfo())) { restoreBestIterate(); } exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { exitcode_ = ExitCode::ReachMaxIters; this->getPrinter().display(Msg::MaxItersReached, this->getInfo()); } break; } } else { break; } // SAFEGUARD: Compare statistics if (this->getInfo().get(SolverIntParam_NumIter)==0) { saveIterateAsBest(); } else if (this->getInfo().isBetterThan(this->getBestInfo())) { saveIterateAsBest(); } // update NTscalings, numeric factorization and solve linear system if (this->getCone().updateNTScalings(this->opt_.s(), this->opt_.z(), this->lambda_)==ConeStatus::Outside) { this->getPrinter().display(Msg::VariablesLeavingCone, this->getBestInfo()); restoreBestIterate(); exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { this->getPrinter().display(Msg::NumericalProblem, this->getInfo()); return ExitCode::PrSlacksLeaveCone; } else { break; } } this->getLinSolver().updateMatrix(); if (this->getLinSolver().numericFactorization()!=FactStatus::Optimal) { this->getPrinter().display(Msg::MatrixFactorization, this->getInfo()); return ExitCode::Indeterminate; } this->getInfo().get(SolverIntParam_NumRefsLinSolve) = this->getLinSolver().solve(RHS1_, dopt2_); // Affine Step rhsAffineStep(); this->getInfo().get(SolverIntParam_NumRefsLinSolveAffine) = this->getLinSolver().solve(RHS2_, dopt1_); dt_denom_ = opt_.kappa()/opt_.tau() - dotProduct(this->getCone().numVars(), this->getStg().c().data(), dopt2_.x().data()) - dotProduct(this->getCone().numLeq(), this->getStg().b().data(), dopt2_.y().data()) - dotProduct(this->getCone().sizeCone(), this->getStg().h().data(), dopt2_.z().data()); dt_affine_ = (residual_t_ - opt_.kappa() + dotProduct(this->getCone().numVars(), this->getStg().c().data(), dopt1_.x().data()) + dotProduct(this->getCone().numLeq(), this->getStg().b().data(), dopt1_.y().data()) + dotProduct(this->getCone().sizeCone(), this->getStg().h().data(), dopt1_.z().data())) / dt_denom_; dk_affine_ = -this->opt_.kappa() - this->opt_.kappa()/this->opt_.tau()*dt_affine_; for (int i=0; i<this->getCone().sizeCone(); i++) { dopt1_.z()[i] += dt_affine_*dopt2_.z()[i]; } W_times_dz_affine_ = this->getCone().W()*dopt1_.z(); for (int i=0; i<this->getCone().sizeCone(); i++) { ds_affine_by_W_[i] = -W_times_dz_affine_[i] - lambda_[i]; } this->getInfo().get(SolverDoubleParam_AffineStepLength) = lineSearch(ds_affine_by_W_, W_times_dz_affine_, this->opt_.tau(), dt_affine_, this->opt_.kappa(), dk_affine_); this->getInfo().get(SolverDoubleParam_CorrectionStepLength) = std::max(std::min(std::pow(1.0-this->getInfo().get(SolverDoubleParam_AffineStepLength),3.0),this->getStgs().get(SolverDoubleParam_MaximumCenteringStep)),this->getStgs().get(SolverDoubleParam_MinimumCenteringStep)); // Centering and Corrector Step ds_combined_ = lambda_*lambda_ + ds_affine_by_W_*W_times_dz_affine_- (this->getInfo().get(SolverDoubleParam_CorrectionStepLength)*this->getInfo().get(SolverDoubleParam_MeritFunction)); ds_affine_by_W_ = lambda_/ds_combined_; dz_combined_ = (this->getInfo().get(SolverDoubleParam_CorrectionStepLength)-1.0)*res_.z() + this->getCone().W()*ds_affine_by_W_; dk_combined_ = this->opt_.kappa()*this->opt_.tau() + dk_affine_*dt_affine_ - this->getInfo().get(SolverDoubleParam_CorrectionStepLength)*this->getInfo().get(SolverDoubleParam_MeritFunction); rhsCenteringPredictorStep(); this->getInfo().get(SolverIntParam_NumRefsLinSolveCorrector) = this->getLinSolver().solve(RHS2_, dopt1_); dopt1_.tau() = ((1-this->getInfo().get(SolverDoubleParam_CorrectionStepLength))*this->residual_t_ - dk_combined_/this->opt_.tau() + dotProduct(this->getCone().numVars(), this->getStg().c().data(), dopt1_.x().data()) + dotProduct(this->getCone().numLeq(), this->getStg().b().data(), dopt1_.y().data()) + dotProduct(this->getCone().sizeCone(), this->getStg().h().data(), dopt1_.z().data())) / dt_denom_; dopt1_.xyz() += dopt1_.tau()*dopt2_.xyz(); W_times_dz_affine_ = this->getCone().W()*dopt1_.z(); for (int i=0; i<this->getCone().sizeCone(); i++) { ds_affine_by_W_[i] = -(ds_affine_by_W_[i] + W_times_dz_affine_[i]); } dopt1_.kappa() = -(dk_combined_ + this->opt_.kappa()*dopt1_.tau())/this->opt_.tau(); this->getInfo().get(SolverDoubleParam_StepLength) = lineSearch(ds_affine_by_W_, W_times_dz_affine_, this->opt_.tau(), dopt1_.tau(), this->opt_.kappa(), dopt1_.kappa()) * this->getStgs().get(SolverDoubleParam_StepLengthScaling); dopt1_.s() = this->getCone().W()*ds_affine_by_W_; // Update variables opt_ += this->getInfo().get(SolverDoubleParam_StepLength) * dopt1_; } this->getEqRoutine().scaleVariables(opt_); return exitcode_; } }
51.716667
404
0.676718
shbang91
ddad148892cd9abc74175c5f961396e5081ce719
14,159
cpp
C++
sources/tests/clone_generation_tests.cpp
greati/logicantsy
11d1f33f57df6fc77c3c18b506fc98f9b9a88794
[ "MIT" ]
2
2022-01-22T13:18:35.000Z
2022-02-12T22:56:34.000Z
sources/tests/clone_generation_tests.cpp
greati/logicantsy
11d1f33f57df6fc77c3c18b506fc98f9b9a88794
[ "MIT" ]
27
2020-06-06T18:32:02.000Z
2021-05-02T22:16:49.000Z
sources/tests/clone_generation_tests.cpp
greati/logicantsy
11d1f33f57df6fc77c3c18b506fc98f9b9a88794
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "core/common.h" #include "core/utils.h" #include "core/parser/fmla/fmla_parser.h" #include "apps/clones/clone_generation.h" namespace { TEST(CloneGen, GenerateCloneGodel) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("q"); auto neg_p = parser.parse("neg p"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto p_to_q = parser.parse("p -> q"); auto tt_neg = ltsy::TruthTable<std::set<int>>(3, { {{0},{2}}, {{1},{0}}, {{2},{0}}, }, neg_p); auto tt_and = ltsy::TruthTable<std::set<int>>(3, { {{0,0},{0}}, {{0,1},{0}}, {{0,2},{0}}, {{1,0},{0}}, {{1,1},{1}}, {{1,2},{1}}, {{2,0},{0}}, {{2,1},{1}}, {{2,2},{2}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(3, { {{0,0},{0}}, {{0,1},{1}}, {{0,2},{2}}, {{1,0},{1}}, {{1,1},{1}}, {{1,2},{2}}, {{2,0},{2}}, {{2,1},{2}}, {{2,2},{2}}, }, p_or_q); auto tt_to = ltsy::TruthTable<std::set<int>>(3, { {{0,0},{2}}, {{0,1},{2}}, {{0,2},{2}}, {{1,0},{0}}, {{1,1},{2}}, {{1,2},{2}}, {{2,0},{0}}, {{2,1},{1}}, {{2,2},{2}}, }, p_to_q); //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_frown, tt_smile, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_and, tt_or}}; ltsy::CloneGenerator generator {3, {tt_to,tt_and,tt_or,tt_neg}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateCloneDeterministicTeamFour) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("p"); auto smile_p = parser.parse("s(p)"); auto frown_p = parser.parse("f(p)"); auto csmile_p = parser.parse("cs(p)"); auto cfrown_p = parser.parse("cf(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto tt_and = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{1}}, {{0,2},{2}}, {{0,3},{3}}, {{1,0},{1}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{3}}, {{2,0},{2}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{3}}, {{3,0},{3}}, {{3,1},{3}}, {{3,2},{3}}, {{3,3},{3}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{0}}, {{0,2},{0}}, {{0,3},{0}}, {{1,0},{0}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{1}}, {{2,0},{0}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{2}}, {{3,0},{0}}, {{3,1},{1}}, {{3,2},{2}}, {{3,3},{3}}, }, p_or_q); auto tt_smile = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{1}}, {{2},{0}}, {{3},{0}}, }, smile_p); auto tt_frown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{3}}, {{2},{2}}, {{3},{0}}, }, frown_p); auto tt_csmile = ltsy::TruthTable<std::set<int>>(4, { {{0},{0}}, {{1},{3}}, {{2},{1}}, {{3},{0}}, }, csmile_p); auto tt_cfrown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{2}}, {{2},{0}}, {{3},{3}}, }, cfrown_p); //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_frown, tt_smile, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_and, tt_or}}; ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_cfrown, tt_and, tt_or}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateCloneDeterministicFDE) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("p"); auto smile_p = parser.parse("s(p)"); auto frown_p = parser.parse("f(p)"); auto csmile_p = parser.parse("cs(p)"); auto cfrown_p = parser.parse("cf(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto tt_and = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{1}}, {{0,2},{2}}, {{0,3},{3}}, {{1,0},{1}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{3}}, {{2,0},{2}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{3}}, {{3,0},{3}}, {{3,1},{3}}, {{3,2},{3}}, {{3,3},{3}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{0}}, {{0,2},{0}}, {{0,3},{0}}, {{1,0},{0}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{1}}, {{2,0},{0}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{2}}, {{3,0},{0}}, {{3,1},{1}}, {{3,2},{2}}, {{3,3},{3}}, }, p_or_q); auto tt_dmneg = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{1}}, {{2},{2}}, {{3},{0}}, }, smile_p); auto tt_smile = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{1}}, {{2},{0}}, {{3},{0}}, }, smile_p); auto tt_frown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{3}}, {{2},{2}}, {{3},{0}}, }, frown_p); auto tt_csmile = ltsy::TruthTable<std::set<int>>(4, { {{0},{0}}, {{1},{3}}, {{2},{1}}, {{3},{0}}, }, csmile_p); auto tt_cfrown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{2}}, {{2},{0}}, {{3},{3}}, }, cfrown_p); ltsy::CloneGenerator generator {4, {tt_or, tt_dmneg, tt_and}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateClone) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("q"); auto neg_p = parser.parse("neg p"); auto conf_p = parser.parse("conf(p)"); auto conv_p = parser.parse("conv(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto tt_neg = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3}}, {{3},{2,4}}, {{4},{2,4}}, }, neg_p); auto tt_conf = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3}}, {{3},{2,4}}, {{4},{2,}}, }, conf_p); auto tt_conv = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3,2}}, {{3},{2,4}}, {{4},{2,4}}, }, conv_p); ltsy::CloneGenerator generator {5, {tt_neg, tt_conv, tt_conf}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateUnaryCloneMci) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("q"); auto neg_p = parser.parse("neg p"); auto conf_p = parser.parse("o(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto p_to_q = parser.parse("p -> q"); auto tt_neg = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3}}, {{3},{2,4}}, {{4},{2,4}}, }, neg_p); auto tt_conf = ltsy::TruthTable<std::set<int>>(5, { {{0},{0}}, {{1},{0}}, {{2},{0}}, {{3},{0}}, {{4},{1}}, }, conf_p); auto tt_and = ltsy::TruthTable<std::set<int>>(5, { {{0,0},{2,4}}, {{1,0},{3}}, {{2,0},{2,4}}, {{3,0},{3}}, {{4,0},{2,4}}, {{0,1},{3}}, {{1,1},{3}}, {{2,1},{3}}, {{3,1},{3}}, {{4,1},{3}}, {{0,2},{2,4}}, {{1,2},{3}}, {{2,2},{2,4}}, {{3,2},{3}}, {{4,2},{2,4}}, {{0,3},{3}}, {{1,3},{3}}, {{2,3},{3}}, {{3,3},{3}}, {{4,3},{3}}, {{0,4},{2,4}}, {{1,4},{3}}, {{2,4},{2,4}}, {{3,4},{3}}, {{4,4},{2,4}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(5, { {{0,0},{2,4}}, {{1,0},{2,4}}, {{2,0},{2,4}}, {{3,0},{2,4}}, {{4,0},{2,4}}, {{0,1},{2,4}}, {{1,1},{3}}, {{2,1},{2,4}}, {{3,1},{3}}, {{4,1},{2,4}}, {{0,2},{2,4}}, {{1,2},{2,4}}, {{2,2},{2,4}}, {{3,2},{2,4}}, {{4,2},{2,4}}, {{0,3},{2,4}}, {{1,3},{3}}, {{2,3},{2,4}}, {{3,3},{3}}, {{4,3},{2,4}}, {{0,4},{2,4}}, {{1,4},{2,4}}, {{2,4},{2,4}}, {{3,4},{2,4}}, {{4,4},{2,4}}, }, p_or_q); auto tt_to = ltsy::TruthTable<std::set<int>>(5, { {{0,0},{2,4}}, {{1,0},{2,4}}, {{2,0},{2,4}}, {{3,0},{2,4}}, {{4,0},{2,4}}, {{0,1},{3}}, {{1,1},{2,4}}, {{2,1},{3}}, {{3,1},{2,4}}, {{4,1},{3}}, {{0,2},{2,4}}, {{1,2},{2,4}}, {{2,2},{2,4}}, {{3,2},{2,4}}, {{4,2},{2,4}}, {{0,3},{3}}, {{1,3},{2,4}}, {{2,3},{3}}, {{3,3},{2,4}}, {{4,3},{3}}, {{0,4},{2,4}}, {{1,4},{2,4}}, {{2,4},{2,4}}, {{3,4},{2,4}}, {{4,4},{2,4}}, }, p_to_q); ltsy::CloneGenerator generator {5, {tt_neg, tt_and, tt_or, tt_to, tt_conf}}; std::set<int> D = {0,2,4}; std::set<int> U = {1,3}; const auto unary_clone = generator.generate(1, {p, q}, std::nullopt, std::make_pair<>([&](ltsy::NDTruthTable tt) -> bool { auto A = tt.at({0}); auto B = tt.at({2}); return (ltsy::utils::is_subset(A, D) and ltsy::utils::is_subset(B, U)) or (ltsy::utils::is_subset(B, D) and ltsy::utils::is_subset(A, U)); }, 2) ); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } }
32.106576
104
0.322127
greati
ddb127e79811d14f6a32686dfbc2d5d990d73fbc
15,108
cpp
C++
frontends/common/resolveReferences/resolveReferences.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
frontends/common/resolveReferences/resolveReferences.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
frontends/common/resolveReferences/resolveReferences.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
/* Copyright 2013-present Barefoot Networks, 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 "resolveReferences.h" #include <sstream> namespace P4 { std::vector<const IR::IDeclaration*>* ResolutionContext::resolve(IR::ID name, P4::ResolutionType type, bool previousOnly) const { static std::vector<const IR::IDeclaration*> empty; std::vector<const IR::INamespace*> toTry; toTry = stack; toTry.insert(toTry.end(), globals.begin(), globals.end()); for (auto it = toTry.rbegin(); it != toTry.rend(); ++it) { const IR::INamespace* current = *it; LOG2("Trying to resolve in " << current->toString()); if (current->is<IR::IGeneralNamespace>()) { auto gen = current->to<IR::IGeneralNamespace>(); Util::Enumerator<const IR::IDeclaration*>* decls = gen->getDeclsByName(name); switch (type) { case P4::ResolutionType::Any: break; case P4::ResolutionType::Type: { std::function<bool(const IR::IDeclaration*)> kindFilter = [](const IR::IDeclaration* d) { return d->is<IR::Type>(); }; decls = decls->where(kindFilter); break; } case P4::ResolutionType::TypeVariable: { std::function<bool(const IR::IDeclaration*)> kindFilter = [](const IR::IDeclaration* d) { return d->is<IR::Type_Var>(); }; decls = decls->where(kindFilter); break; } default: BUG("Unexpected enumeration value %1%", static_cast<int>(type)); } if (previousOnly) { std::function<bool(const IR::IDeclaration*)> locationFilter = [name](const IR::IDeclaration* d) { Util::SourceInfo nsi = name.srcInfo; Util::SourceInfo dsi = d->getNode()->srcInfo; bool before = dsi <= nsi; LOG2("\tPosition test:" << dsi << "<=" << nsi << "=" << before); return before; }; decls = decls->where(locationFilter); } auto vector = decls->toVector(); if (!vector->empty()) { LOG2("Resolved in " << current->getNode()); return vector; } else { continue; } } else { auto simple = current->to<IR::ISimpleNamespace>(); auto decl = simple->getDeclByName(name); if (decl == nullptr) continue; switch (type) { case P4::ResolutionType::Any: break; case P4::ResolutionType::Type: { if (!decl->is<IR::Type>()) continue; break; } case P4::ResolutionType::TypeVariable: { if (!decl->is<IR::Type_Var>()) continue; break; } default: BUG("Unexpected enumeration value %1%", static_cast<int>(type)); } if (previousOnly) { Util::SourceInfo nsi = name.srcInfo; Util::SourceInfo dsi = decl->getNode()->srcInfo; bool before = dsi <= nsi; LOG2("\tPosition test:" << dsi << "<=" << nsi << "=" << before); if (!before) continue; } LOG2("Resolved in " << current->getNode()); auto result = new std::vector<const IR::IDeclaration*>(); result->push_back(decl); return result; } } return &empty; } void ResolutionContext::done() { pop(rootNamespace); if (!stack.empty()) BUG("ResolutionContext::stack not empty"); } const IR::IDeclaration* ResolutionContext::resolveUnique(IR::ID name, P4::ResolutionType type, bool previousOnly) const { auto decls = resolve(name, type, previousOnly); if (decls->empty()) { ::error("Could not find declaration for %1%", name); return nullptr; } if (decls->size() > 1) { ::error("Multiple matching declarations for %1%", name); for (auto a : *decls) ::error("Candidate: %1%", a); return nullptr; } return decls->at(0); } void ResolutionContext::dbprint(std::ostream& out) const { out << "Context stack[" << stack.size() << "]" << std::endl; for (auto it = stack.begin(); it != stack.end(); it++) { const IR::INamespace* ns = *it; const IR::Node* node = ns->getNode(); node->dbprint(out); out << std::endl; } out << "Globals[" << stack.size() << "]" << std::endl; for (auto it = globals.begin(); it != globals.end(); it++) { const IR::INamespace* ns = *it; const IR::Node* node = ns->getNode(); node->dbprint(out); out << std::endl; } out << "----------" << std::endl; } ///////////////////////////////////////////////////// ResolveReferences::ResolveReferences(ReferenceMap* refMap, bool checkShadow) : refMap(refMap), context(nullptr), rootNamespace(nullptr), anyOrder(false), checkShadow(checkShadow) { CHECK_NULL(refMap); setName("ResolveReferences"); visitDagOnce = false; } void ResolveReferences::addToContext(const IR::INamespace* ns) { LOG1("Adding to context " << ns); if (context == nullptr) BUG("No resolution context; did not start at P4Program?"); context->push(ns); } void ResolveReferences::addToGlobals(const IR::INamespace* ns) { if (context == nullptr) BUG("No resolution context; did not start at P4Program?"); context->addGlobal(ns); } void ResolveReferences::removeFromContext(const IR::INamespace* ns) { LOG1("Removing from context " << ns); if (context == nullptr) BUG("No resolution context; did not start at P4Program?"); context->pop(ns); } ResolutionContext* ResolveReferences::resolvePathPrefix(const IR::PathPrefix* prefix) const { ResolutionContext* result = context; if (prefix == nullptr) return result; if (prefix->absolute) result = new ResolutionContext(rootNamespace); for (IR::ID id : prefix->components) { const IR::IDeclaration* decl = result->resolveUnique(id, ResolutionType::Any, !anyOrder); if (decl == nullptr) return nullptr; const IR::Node* node = decl->getNode(); if (!node->is<IR::INamespace>()) { ::error("%1%: %2% is not a namespace", prefix, decl); return nullptr; } result = new ResolutionContext(node->to<IR::INamespace>()); } return result; } void ResolveReferences::resolvePath(const IR::Path* path, bool isType) const { LOG1("Resolving " << path << " " << (isType ? "as type" : "as identifier")); ResolutionContext* ctx = resolvePathPrefix(path->prefix); ResolutionType k = isType ? ResolutionType::Type : ResolutionType::Any; if (resolveForward.empty()) BUG("Empty resolveForward"); bool allowForward = resolveForward.back(); const IR::IDeclaration* decl = ctx->resolveUnique(path->name, k, !allowForward); if (decl == nullptr) { refMap->usedName(path->name.name); return; } refMap->setDeclaration(path, decl); } void ResolveReferences::checkShadowing(const IR::INamespace*ns) const { if (!checkShadow) return; auto e = ns->getDeclarations(); while (e->moveNext()) { const IR::IDeclaration* decl = e->getCurrent(); const IR::Node* node = decl->getNode(); auto prev = context->resolve(decl->getName(), ResolutionType::Any, !anyOrder); if (prev->empty()) continue; for (auto p : *prev) { const IR::Node* pnode = p->getNode(); if (pnode == node) continue; if (pnode->is<IR::Type_Method>() && node->is<IR::Type_Method>()) { auto md = node->to<IR::Type_Method>(); auto mp = pnode->to<IR::Type_Method>(); if (md->parameters->size() != mp->parameters->size()) continue; } ::warning("%1% shadows %2%", decl->getName(), p->getName()); } } } Visitor::profile_t ResolveReferences::init_apply(const IR::Node* node) { anyOrder = refMap->isV1(); if (!refMap->checkMap(node)) refMap->clear(); return Inspector::init_apply(node); } void ResolveReferences::end_apply(const IR::Node* node) { refMap->updateMap(node); } /////////////////// visitor methods //////////////////////// // visitor should be invoked here bool ResolveReferences::preorder(const IR::P4Program* program) { if (refMap->checkMap(program)) return false; if (!resolveForward.empty()) BUG("Expected empty resolvePath"); resolveForward.push_back(anyOrder); if (rootNamespace != nullptr) BUG("Root namespace already set"); rootNamespace = program; context = new ResolutionContext(rootNamespace); return true; } void ResolveReferences::postorder(const IR::P4Program*) { rootNamespace = nullptr; context->done(); resolveForward.pop_back(); if (!resolveForward.empty()) BUG("Expected empty resolvePath"); context = nullptr; LOG1("Reference map " << refMap); } bool ResolveReferences::preorder(const IR::PathExpression* path) { resolvePath(path->path, false); return true; } bool ResolveReferences::preorder(const IR::Type_Name* type) { resolvePath(type->path, true); return true; } bool ResolveReferences::preorder(const IR::P4Control *c) { refMap->usedName(c->name.name); addToContext(c); addToContext(c->type->typeParameters); addToContext(c->type->applyParams); addToContext(c->constructorParams); return true; } void ResolveReferences::postorder(const IR::P4Control *c) { removeFromContext(c->constructorParams); removeFromContext(c->type->applyParams); removeFromContext(c->type->typeParameters); removeFromContext(c); checkShadowing(c); } bool ResolveReferences::preorder(const IR::P4Parser *c) { refMap->usedName(c->name.name); addToContext(c); addToContext(c->type->typeParameters); addToContext(c->type->applyParams); addToContext(c->constructorParams); return true; } void ResolveReferences::postorder(const IR::P4Parser *c) { removeFromContext(c->constructorParams); removeFromContext(c->type->applyParams); removeFromContext(c->type->typeParameters); removeFromContext(c); checkShadowing(c); } bool ResolveReferences::preorder(const IR::Function* function) { refMap->usedName(function->name.name); addToContext(function->type->parameters); return true; } void ResolveReferences::postorder(const IR::Function* function) { removeFromContext(function->type->parameters); } bool ResolveReferences::preorder(const IR::P4Table* t) { refMap->usedName(t->name.name); addToContext(t->parameters); return true; } void ResolveReferences::postorder(const IR::P4Table* t) { removeFromContext(t->parameters); } bool ResolveReferences::preorder(const IR::TableProperties *p) { addToContext(p); return true; } void ResolveReferences::postorder(const IR::TableProperties *p) { removeFromContext(p); } bool ResolveReferences::preorder(const IR::P4Action *c) { refMap->usedName(c->name.name); addToContext(c); addToContext(c->parameters); return true; } void ResolveReferences::postorder(const IR::P4Action *c) { removeFromContext(c->parameters); removeFromContext(c); checkShadowing(c); } bool ResolveReferences::preorder(const IR::Type_Method *t) { // Function return values in generic functions may depend on the type arguments: // T f<T>() // where T is declared *after* its first use resolveForward.push_back(true); if (t->typeParameters != nullptr) addToContext(t->typeParameters); addToContext(t->parameters); return true; } void ResolveReferences::postorder(const IR::Type_Method *t) { removeFromContext(t->parameters); if (t->typeParameters != nullptr) removeFromContext(t->typeParameters); resolveForward.pop_back(); } bool ResolveReferences::preorder(const IR::Type_Extern *t) { refMap->usedName(t->name.name); addToContext(t->typeParameters); return true; } void ResolveReferences::postorder(const IR::Type_Extern *t) { removeFromContext(t->typeParameters); } bool ResolveReferences::preorder(const IR::ParserState *s) { refMap->usedName(s->name.name); // State references may be resolved forward resolveForward.push_back(true); addToContext(s); return true; } void ResolveReferences::postorder(const IR::ParserState *s) { removeFromContext(s); resolveForward.pop_back(); checkShadowing(s); } bool ResolveReferences::preorder(const IR::Declaration_Errors *d) { addToGlobals(d); return true; } bool ResolveReferences::preorder(const IR::Declaration_MatchKind *d) { addToGlobals(d); return true; } bool ResolveReferences::preorder(const IR::Type_ArchBlock *t) { resolveForward.push_back(anyOrder); addToContext(t->typeParameters); return true; } void ResolveReferences::postorder(const IR::Type_ArchBlock *t) { refMap->usedName(t->name.name); removeFromContext(t->typeParameters); resolveForward.pop_back(); } bool ResolveReferences::preorder(const IR::Type_StructLike *t) { refMap->usedName(t->name.name); addToContext(t); return true; } void ResolveReferences::postorder(const IR::Type_StructLike *t) { removeFromContext(t); } bool ResolveReferences::preorder(const IR::BlockStatement *b) { addToContext(b); return true; } void ResolveReferences::postorder(const IR::BlockStatement *b) { removeFromContext(b); checkShadowing(b); } bool ResolveReferences::preorder(const IR::Declaration_Instance *decl) { refMap->usedName(decl->name.name); if (decl->initializer != nullptr) addToContext(decl->initializer); return true; } void ResolveReferences::postorder(const IR::Declaration_Instance *decl) { if (decl->initializer != nullptr) removeFromContext(decl->initializer); } #undef PROCESS_NAMESPACE } // namespace P4
32.560345
97
0.60458
pierce-m
ddb19031941d6712f7139733b6aaeda26c2f1e09
1,552
cpp
C++
Depth_Estimation_Pipeline/app/driver.cpp
jasonpilbrough/Mesh-Based-Depth-Estimation
fe82eab3b064c3fa6a543fa83f626e7d948d2335
[ "MIT" ]
null
null
null
Depth_Estimation_Pipeline/app/driver.cpp
jasonpilbrough/Mesh-Based-Depth-Estimation
fe82eab3b064c3fa6a543fa83f626e7d948d2335
[ "MIT" ]
null
null
null
Depth_Estimation_Pipeline/app/driver.cpp
jasonpilbrough/Mesh-Based-Depth-Estimation
fe82eab3b064c3fa6a543fa83f626e7d948d2335
[ "MIT" ]
null
null
null
#include "pipeline.h" //#include "colourmap.h" //#include <opencv2/viz.hpp> int main(int argc, char* argv[]) { // ######### EuRoC ######### //std::string dataset_path_left = "data/EuRoC/MH1/cam0/data/%10d.png"; //std::string dataset_path_right = "data/EuRoC/MH1/cam1/data/%10d.png"; // ######### ETH3D ######### std::string dataset_path_left = "data/ETH3D/delivery_area/cam4_brighter/%10d.png"; std::string dataset_path_right = "data/ETH3D/delivery_area/cam5_brighter/%10d.png"; std::string dataset_path_gnd = "data/ETH3D/delivery_area/gnd/%10d.png"; // ######### OXFORD ######### (This is actually MVSEC) //std::string dataset_path_left = "data/Oxford/indoor_flying1/cam0/%10d.png"; //std::string dataset_path_right = "data/Oxford/indoor_flying1/cam1/%10d.png"; //std::string dataset_path_gnd = "data/Oxford/indoor_flying1/gnd/%10d.png"; sandbox::Pipeline p(dataset_path_left,dataset_path_right,dataset_path_gnd); p.run(); return 0; } // ######### KITTI ######### //std::string dataset_path_left = "data/KITTI/2011_09_26_drive_0002_sync/image_00/data/%10d.png"; //std::string dataset_path_right = "data/KITTI/2011_09_26_drive_0002_sync/image_01/data/%10d.png"; //std::string dataset_path_left = "data/KITTI/data_stereo_flow/image_00/%10d.png"; //std::string dataset_path_right = "data/KITTI/data_stereo_flow/image_01/%10d.png"; //std::string dataset_path_gnd = "data/KITTI/data_stereo_flow/disp_noc/%10d.png"; //sandbox::Pipeline p(dataset_path_left,dataset_path_right);
36.093023
98
0.691366
jasonpilbrough
ddb1bc6b58aa8666fe1bd5ef983591fbeb7c216d
1,181
cpp
C++
test/ext/std/integral_constant/bug_datatype_inheritance.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
test/ext/std/integral_constant/bug_datatype_inheritance.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
test/ext/std/integral_constant/bug_datatype_inheritance.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/ext/std/integral_constant.hpp> #include <boost/hana/core/datatype.hpp> #include <type_traits> using namespace boost::hana; struct inherit_simple : std::integral_constant<int, 3> { }; struct inherit_no_default : std::integral_constant<int, 3> { inherit_no_default() = delete; }; struct incomplete; struct empty { }; struct non_pod { virtual ~non_pod() { } }; int main() { static_assert(std::is_same<datatype_t<inherit_simple>, StdIntegralConstant>{}, ""); static_assert(std::is_same<datatype_t<inherit_no_default>, StdIntegralConstant>{}, ""); static_assert(std::is_same<datatype_t<std::is_pointer<int*>>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<incomplete>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<empty>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<non_pod>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<void>, StdIntegralConstant>{}, ""); }
34.735294
94
0.730737
rbock
ddb25dd6ff068f1ee904f061f903794d46277de1
878
cpp
C++
examples/test.cpp
EBoespflug/multi_array
61ce2540bf5e4c3c9b7266ae5958eaad433481a4
[ "CC0-1.0" ]
null
null
null
examples/test.cpp
EBoespflug/multi_array
61ce2540bf5e4c3c9b7266ae5958eaad433481a4
[ "CC0-1.0" ]
null
null
null
examples/test.cpp
EBoespflug/multi_array
61ce2540bf5e4c3c9b7266ae5958eaad433481a4
[ "CC0-1.0" ]
null
null
null
#include "../multi_array.hpp" #include <iostream> #include <numeric> template<typename Container> void print(Container c) { std::cout << c.size() << '\n'; for(auto&& v : c) std::cout << v << ' '; std::cout << '\n'; } int main() { eb::multi_array<int, 3, 2, 2> arr1{0}; eb::multi_array<int, 3, 2, 2> arr2{0}; std::iota(arr1.begin(), arr1.end(), 1); print(arr1); print(arr2); arr2(0, 0, 0) = 0; arr2(0, 0, 1) = 1; arr2(0, 1, 0) = 2; arr2(0, 1, 1) = 3; arr2(1, 0, 0) = 4; arr2(1, 0, 1) = 5; arr2(1, 1, 0) = 6; arr2(1, 1, 1) = 7; arr2(2, 0, 0) = 8; arr2(2, 0, 1) = 9; arr2(2, 1, 0) = 10; arr2(2, 1, 1) = 11; for(auto& i : arr1) --i; print(arr1); print(arr2); if(arr1 == arr2) std::cout << "Equals !\n"; else std::cout << "Not equals !\n"; }
17.918367
43
0.458998
EBoespflug
ddb41032afaac83ba298fd4710593472b69f5ec3
27,241
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgscreencapture/osgscreencapture.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgscreencapture/osgscreencapture.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgscreencapture/osgscreencapture.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application 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. */ #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> #include <osg/Switch> #include <osgText/Text> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <iostream> #include <sstream> #include <string.h> class WindowCaptureCallback : public osg::Camera::DrawCallback { public: enum Mode { READ_PIXELS, SINGLE_PBO, DOUBLE_PBO, TRIPLE_PBO }; enum FramePosition { START_FRAME, END_FRAME }; struct ContextData : public osg::Referenced { ContextData(osg::GraphicsContext* gc, Mode mode, GLenum readBuffer, const std::string& name): _gc(gc), _mode(mode), _readBuffer(readBuffer), _fileName(name), _pixelFormat(GL_BGRA), _type(GL_UNSIGNED_BYTE), _width(0), _height(0), _currentImageIndex(0), _currentPboIndex(0), _reportTimingFrequency(100), _numTimeValuesRecorded(0), _timeForReadPixels(0.0), _timeForFullCopy(0.0), _timeForMemCpy(0.0) { _previousFrameTick = osg::Timer::instance()->tick(); if (gc->getTraits()) { if (gc->getTraits()->alpha) { osg::notify(osg::NOTICE)<<"Select GL_BGRA read back format"<<std::endl; _pixelFormat = GL_BGRA; } else { osg::notify(osg::NOTICE)<<"Select GL_BGR read back format"<<std::endl; _pixelFormat = GL_BGR; } } getSize(gc, _width, _height); std::cout<<"Window size "<<_width<<", "<<_height<<std::endl; // single buffered image _imageBuffer.push_back(new osg::Image); // double buffer PBO. switch(_mode) { case(READ_PIXELS): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with out PixelBufferObject."<<std::endl; break; case(SINGLE_PBO): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with a single PixelBufferObject."<<std::endl; _pboBuffer.push_back(0); break; case(DOUBLE_PBO): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with a double buffer PixelBufferObject."<<std::endl; _pboBuffer.push_back(0); _pboBuffer.push_back(0); break; case(TRIPLE_PBO): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with a triple buffer PixelBufferObject."<<std::endl; _pboBuffer.push_back(0); _pboBuffer.push_back(0); _pboBuffer.push_back(0); break; default: break; } } void getSize(osg::GraphicsContext* gc, int& width, int& height) { if (gc->getTraits()) { width = gc->getTraits()->width; height = gc->getTraits()->height; } } void updateTimings(osg::Timer_t tick_start, osg::Timer_t tick_afterReadPixels, osg::Timer_t tick_afterMemCpy, unsigned int dataSize); void read() { osg::BufferObject::Extensions* ext = osg::BufferObject::getExtensions(_gc->getState()->getContextID(),true); if (ext->isPBOSupported() && !_pboBuffer.empty()) { if (_pboBuffer.size()==1) { singlePBO(ext); } else { multiPBO(ext); } } else { readPixels(); } } void readPixels(); void singlePBO(osg::BufferObject::Extensions* ext); void multiPBO(osg::BufferObject::Extensions* ext); typedef std::vector< osg::ref_ptr<osg::Image> > ImageBuffer; typedef std::vector< GLuint > PBOBuffer; osg::GraphicsContext* _gc; Mode _mode; GLenum _readBuffer; std::string _fileName; GLenum _pixelFormat; GLenum _type; int _width; int _height; unsigned int _currentImageIndex; ImageBuffer _imageBuffer; unsigned int _currentPboIndex; PBOBuffer _pboBuffer; unsigned int _reportTimingFrequency; unsigned int _numTimeValuesRecorded; double _timeForReadPixels; double _timeForFullCopy; double _timeForMemCpy; osg::Timer_t _previousFrameTick; }; WindowCaptureCallback(Mode mode, FramePosition position, GLenum readBuffer): _mode(mode), _position(position), _readBuffer(readBuffer) { } FramePosition getFramePosition() const { return _position; } ContextData* createContextData(osg::GraphicsContext* gc) const { std::stringstream filename; filename << "test_"<<_contextDataMap.size()<<".jpg"; return new ContextData(gc, _mode, _readBuffer, filename.str()); } ContextData* getContextData(osg::GraphicsContext* gc) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::ref_ptr<ContextData>& data = _contextDataMap[gc]; if (!data) data = createContextData(gc); return data.get(); } virtual void operator () (osg::RenderInfo& renderInfo) const { glReadBuffer(_readBuffer); osg::GraphicsContext* gc = renderInfo.getState()->getGraphicsContext(); osg::ref_ptr<ContextData> cd = getContextData(gc); cd->read(); } typedef std::map<osg::GraphicsContext*, osg::ref_ptr<ContextData> > ContextDataMap; Mode _mode; FramePosition _position; GLenum _readBuffer; mutable OpenThreads::Mutex _mutex; mutable ContextDataMap _contextDataMap; }; void WindowCaptureCallback::ContextData::updateTimings(osg::Timer_t tick_start, osg::Timer_t tick_afterReadPixels, osg::Timer_t tick_afterMemCpy, unsigned int dataSize) { if (!_reportTimingFrequency) return; double timeForReadPixels = osg::Timer::instance()->delta_s(tick_start, tick_afterReadPixels); double timeForFullCopy = osg::Timer::instance()->delta_s(tick_start, tick_afterMemCpy); double timeForMemCpy = osg::Timer::instance()->delta_s(tick_afterReadPixels, tick_afterMemCpy); _timeForReadPixels += timeForReadPixels; _timeForFullCopy += timeForFullCopy; _timeForMemCpy += timeForMemCpy; ++_numTimeValuesRecorded; if (_numTimeValuesRecorded==_reportTimingFrequency) { timeForReadPixels = _timeForReadPixels/double(_numTimeValuesRecorded); timeForFullCopy = _timeForFullCopy/double(_numTimeValuesRecorded); timeForMemCpy = _timeForMemCpy/double(_numTimeValuesRecorded); double averageFrameTime = osg::Timer::instance()->delta_s(_previousFrameTick, tick_afterMemCpy)/double(_numTimeValuesRecorded); double fps = 1.0/averageFrameTime; _previousFrameTick = tick_afterMemCpy; _timeForReadPixels = 0.0; _timeForFullCopy = 0.0; _timeForMemCpy = 0.0; _numTimeValuesRecorded = 0; double numMPixels = double(_width * _height) / 1000000.0; double numMb = double(dataSize) / (1024*1024); int prec = osg::notify(osg::NOTICE).precision(5); if (timeForMemCpy==0.0) { osg::notify(osg::NOTICE)<<"fps = "<<fps<<", full frame copy = "<<timeForFullCopy*1000.0f<<"ms rate = "<<numMPixels / timeForFullCopy<<" Mpixel/sec, copy speed = "<<numMb / timeForFullCopy<<" Mb/sec"<<std::endl; } else { osg::notify(osg::NOTICE)<<"fps = "<<fps<<", full frame copy = "<<timeForFullCopy*1000.0f<<"ms rate = "<<numMPixels / timeForFullCopy<<" Mpixel/sec, "<<numMb / timeForFullCopy<< " Mb/sec "<< "time for memcpy = "<<timeForMemCpy*1000.0<<"ms memcpy speed = "<<numMb / timeForMemCpy<<" Mb/sec"<<std::endl; } osg::notify(osg::NOTICE).precision(prec); } } void WindowCaptureCallback::ContextData::readPixels() { // std::cout<<"readPixels("<<_fileName<<" image "<<_currentImageIndex<<" "<<_currentPboIndex<<std::endl; unsigned int nextImageIndex = (_currentImageIndex+1)%_imageBuffer.size(); unsigned int nextPboIndex = _pboBuffer.empty() ? 0 : (_currentPboIndex+1)%_pboBuffer.size(); int width=0, height=0; getSize(_gc, width, height); if (width!=_width || _height!=height) { std::cout<<" Window resized "<<width<<", "<<height<<std::endl; _width = width; _height = height; } osg::Image* image = _imageBuffer[_currentImageIndex].get(); osg::Timer_t tick_start = osg::Timer::instance()->tick(); #if 1 image->readPixels(0,0,_width,_height, _pixelFormat,_type); #endif osg::Timer_t tick_afterReadPixels = osg::Timer::instance()->tick(); updateTimings(tick_start, tick_afterReadPixels, tick_afterReadPixels, image->getTotalSizeInBytes()); if (!_fileName.empty()) { // osgDB::writeImageFile(*image, _fileName); } _currentImageIndex = nextImageIndex; _currentPboIndex = nextPboIndex; } void WindowCaptureCallback::ContextData::singlePBO(osg::BufferObject::Extensions* ext) { // std::cout<<"singelPBO( "<<_fileName<<" image "<<_currentImageIndex<<" "<<_currentPboIndex<<std::endl; unsigned int nextImageIndex = (_currentImageIndex+1)%_imageBuffer.size(); int width=0, height=0; getSize(_gc, width, height); if (width!=_width || _height!=height) { std::cout<<" Window resized "<<width<<", "<<height<<std::endl; _width = width; _height = height; } GLuint& pbo = _pboBuffer[0]; osg::Image* image = _imageBuffer[_currentImageIndex].get(); if (image->s() != _width || image->t() != _height) { osg::notify(osg::NOTICE)<<"Allocating image "<<std::endl; image->allocateImage(_width, _height, 1, _pixelFormat, _type); if (pbo!=0) { osg::notify(osg::NOTICE)<<"deleting pbo "<<pbo<<std::endl; ext->glDeleteBuffers (1, &pbo); pbo = 0; } } if (pbo==0) { ext->glGenBuffers(1, &pbo); ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pbo); ext->glBufferData(GL_PIXEL_PACK_BUFFER_ARB, image->getTotalSizeInBytes(), 0, GL_STREAM_READ); osg::notify(osg::NOTICE)<<"Generating pbo "<<pbo<<std::endl; } else { ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pbo); } osg::Timer_t tick_start = osg::Timer::instance()->tick(); #if 1 glReadPixels(0, 0, _width, _height, _pixelFormat, _type, 0); #endif osg::Timer_t tick_afterReadPixels = osg::Timer::instance()->tick(); GLubyte* src = (GLubyte*)ext->glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { memcpy(image->data(), src, image->getTotalSizeInBytes()); ext->glUnmapBuffer(GL_PIXEL_PACK_BUFFER_ARB); } ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, 0); osg::Timer_t tick_afterMemCpy = osg::Timer::instance()->tick(); updateTimings(tick_start, tick_afterReadPixels, tick_afterMemCpy, image->getTotalSizeInBytes()); if (!_fileName.empty()) { // osgDB::writeImageFile(*image, _fileName); } _currentImageIndex = nextImageIndex; } void WindowCaptureCallback::ContextData::multiPBO(osg::BufferObject::Extensions* ext) { // std::cout<<"multiPBO( "<<_fileName<<" image "<<_currentImageIndex<<" "<<_currentPboIndex<<std::endl; unsigned int nextImageIndex = (_currentImageIndex+1)%_imageBuffer.size(); unsigned int nextPboIndex = (_currentPboIndex+1)%_pboBuffer.size(); int width=0, height=0; getSize(_gc, width, height); if (width!=_width || _height!=height) { std::cout<<" Window resized "<<width<<", "<<height<<std::endl; _width = width; _height = height; } GLuint& copy_pbo = _pboBuffer[_currentPboIndex]; GLuint& read_pbo = _pboBuffer[nextPboIndex]; osg::Image* image = _imageBuffer[_currentImageIndex].get(); if (image->s() != _width || image->t() != _height) { osg::notify(osg::NOTICE)<<"Allocating image "<<std::endl; image->allocateImage(_width, _height, 1, _pixelFormat, _type); if (read_pbo!=0) { osg::notify(osg::NOTICE)<<"deleting pbo "<<read_pbo<<std::endl; ext->glDeleteBuffers (1, &read_pbo); read_pbo = 0; } if (copy_pbo!=0) { osg::notify(osg::NOTICE)<<"deleting pbo "<<copy_pbo<<std::endl; ext->glDeleteBuffers (1, &copy_pbo); copy_pbo = 0; } } bool doCopy = copy_pbo!=0; if (copy_pbo==0) { ext->glGenBuffers(1, &copy_pbo); ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, copy_pbo); ext->glBufferData(GL_PIXEL_PACK_BUFFER_ARB, image->getTotalSizeInBytes(), 0, GL_STREAM_READ); osg::notify(osg::NOTICE)<<"Generating pbo "<<read_pbo<<std::endl; } if (read_pbo==0) { ext->glGenBuffers(1, &read_pbo); ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, read_pbo); ext->glBufferData(GL_PIXEL_PACK_BUFFER_ARB, image->getTotalSizeInBytes(), 0, GL_STREAM_READ); osg::notify(osg::NOTICE)<<"Generating pbo "<<read_pbo<<std::endl; } else { ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, read_pbo); } osg::Timer_t tick_start = osg::Timer::instance()->tick(); #if 1 glReadPixels(0, 0, _width, _height, _pixelFormat, _type, 0); #endif osg::Timer_t tick_afterReadPixels = osg::Timer::instance()->tick(); if (doCopy) { ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, copy_pbo); GLubyte* src = (GLubyte*)ext->glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { memcpy(image->data(), src, image->getTotalSizeInBytes()); ext->glUnmapBuffer(GL_PIXEL_PACK_BUFFER_ARB); } if (!_fileName.empty()) { // osgDB::writeImageFile(*image, _fileName); } } ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, 0); osg::Timer_t tick_afterMemCpy = osg::Timer::instance()->tick(); updateTimings(tick_start, tick_afterReadPixels, tick_afterMemCpy, image->getTotalSizeInBytes()); _currentImageIndex = nextImageIndex; _currentPboIndex = nextPboIndex; } void addCallbackToViewer(osgViewer::ViewerBase& viewer, WindowCaptureCallback* callback) { if (callback->getFramePosition()==WindowCaptureCallback::START_FRAME) { osgViewer::ViewerBase::Windows windows; viewer.getWindows(windows); for(osgViewer::ViewerBase::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) { osgViewer::GraphicsWindow* window = *itr; osg::GraphicsContext::Cameras& cameras = window->getCameras(); osg::Camera* firstCamera = 0; for(osg::GraphicsContext::Cameras::iterator cam_itr = cameras.begin(); cam_itr != cameras.end(); ++cam_itr) { if (firstCamera) { if ((*cam_itr)->getRenderOrder() < firstCamera->getRenderOrder()) { firstCamera = (*cam_itr); } if ((*cam_itr)->getRenderOrder() == firstCamera->getRenderOrder() && (*cam_itr)->getRenderOrderNum() < firstCamera->getRenderOrderNum()) { firstCamera = (*cam_itr); } } else { firstCamera = *cam_itr; } } if (firstCamera) { osg::notify(osg::NOTICE)<<"First camera "<<firstCamera<<std::endl; firstCamera->setInitialDrawCallback(callback); } else { osg::notify(osg::NOTICE)<<"No camera found"<<std::endl; } } } else { osgViewer::ViewerBase::Windows windows; viewer.getWindows(windows); for(osgViewer::ViewerBase::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) { osgViewer::GraphicsWindow* window = *itr; osg::GraphicsContext::Cameras& cameras = window->getCameras(); osg::Camera* lastCamera = 0; for(osg::GraphicsContext::Cameras::iterator cam_itr = cameras.begin(); cam_itr != cameras.end(); ++cam_itr) { if (lastCamera) { if ((*cam_itr)->getRenderOrder() > lastCamera->getRenderOrder()) { lastCamera = (*cam_itr); } if ((*cam_itr)->getRenderOrder() == lastCamera->getRenderOrder() && (*cam_itr)->getRenderOrderNum() >= lastCamera->getRenderOrderNum()) { lastCamera = (*cam_itr); } } else { lastCamera = *cam_itr; } } if (lastCamera) { osg::notify(osg::NOTICE)<<"Last camera "<<lastCamera<<std::endl; lastCamera->setFinalDrawCallback(callback); } else { osg::notify(osg::NOTICE)<<"No camera found"<<std::endl; } } } } int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); osgViewer::Viewer viewer(arguments); unsigned int helpType = 0; if ((helpType = arguments.readHelpType())) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); ++keyForAnimationPath; } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // add the record camera path handler viewer.addEventHandler(new osgViewer::RecordCameraPathHandler); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); GLenum readBuffer = GL_BACK; WindowCaptureCallback::FramePosition position = WindowCaptureCallback::END_FRAME; WindowCaptureCallback::Mode mode = WindowCaptureCallback::DOUBLE_PBO; while (arguments.read("--start-frame")) { position = WindowCaptureCallback::START_FRAME; readBuffer = GL_FRONT; } while (arguments.read("--end-frame")) position = WindowCaptureCallback::END_FRAME; while (arguments.read("--front")) readBuffer = GL_FRONT; while (arguments.read("--back")) readBuffer = GL_BACK; while (arguments.read("--no-pbo")) mode = WindowCaptureCallback::READ_PIXELS; while (arguments.read("--single-pbo")) mode = WindowCaptureCallback::SINGLE_PBO; while (arguments.read("--double-pbo")) mode = WindowCaptureCallback::DOUBLE_PBO; while (arguments.read("--triple-pbo")) mode = WindowCaptureCallback::TRIPLE_PBO; unsigned int width=1280; unsigned int height=1024; bool pbufferOnly = false; osg::ref_ptr<osg::GraphicsContext> pbuffer; if (arguments.read("--pbuffer",width,height) || (pbufferOnly = arguments.read("--pbuffer-only",width,height))) { osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->red = 8; traits->green = 8; traits->blue = 8; traits->alpha = 8; traits->windowDecoration = false; traits->pbuffer = true; traits->doubleBuffer = true; traits->sharedContext = 0; pbuffer = osg::GraphicsContext::createGraphicsContext(traits.get()); if (pbuffer.valid()) { osg::notify(osg::NOTICE)<<"Pixel buffer has been created successfully."<<std::endl; } else { osg::notify(osg::NOTICE)<<"Pixel buffer has not been created successfully."<<std::endl; } } // load the data osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); viewer.setSceneData( loadedModel.get() ); if (pbuffer.valid()) { osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(pbuffer.get()); camera->setViewport(new osg::Viewport(0,0,width,height)); GLenum buffer = pbuffer->getTraits()->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); camera->setFinalDrawCallback(new WindowCaptureCallback(mode, position, readBuffer)); if (pbufferOnly) { viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd()); viewer.realize(); } else { viewer.realize(); viewer.stopThreading(); pbuffer->realize(); viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd()); viewer.startThreading(); } } else { viewer.realize(); addCallbackToViewer(viewer, new WindowCaptureCallback(mode, position, readBuffer)); } return viewer.run(); }
34.395202
222
0.562645
UM-ARM-Lab
ddb4b869c05f3c26a91225833baa2ebffa91a990
2,823
cc
C++
cc/whocc-scan-titers.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/whocc-scan-titers.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/whocc-scan-titers.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
#include <string> #include "acmacs-base/argv.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/factory-import.hh" // ---------------------------------------------------------------------- void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files); void scan_titers(const fs::path& filename, std::set<acmacs::chart::Titer>& titers); // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } argument<str> source_dir{*this, arg_name{"source-dir"}, mandatory}; }; int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); std::vector<fs::path> ace_files; find_ace_files(fs::path(*opt.source_dir), ace_files); fmt::print("Total .ace files found: {}\n", ace_files.size()); std::set<acmacs::chart::Titer> titers; for (const auto& filename : ace_files) scan_titers(filename, titers); fmt::print("{}\n", titers); } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files) { if (!fs::is_directory(source_dir)) throw std::runtime_error(source_dir.string() + " is not a directory"); for (const auto& dirent: fs::directory_iterator(source_dir)) { if (fs::is_directory(dirent.status())) find_ace_files(dirent.path(), ace_files); else if (is_regular_file(dirent.status()) && dirent.path().extension().string() == ".ace") ace_files.push_back(dirent.path()); } } // find_ace_files // ---------------------------------------------------------------------- void scan_titers(const fs::path& filename, std::set<acmacs::chart::Titer>& titers) { auto chart = acmacs::chart::import_from_file(filename, acmacs::chart::Verify::None, report_time::no); auto chart_titers = chart->titers(); const auto number_of_antigens = chart_titers->number_of_antigens(), number_of_sera = chart_titers->number_of_sera(); for (size_t antigen_no = 0; antigen_no < number_of_antigens; ++antigen_no) { for (size_t serum_no = 0; serum_no < number_of_sera; ++serum_no) { titers.insert(chart_titers->titer(antigen_no, serum_no)); } } } // scan_titers // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
36.662338
129
0.569607
acorg
ddb8c1a668ae4b09afe226003e27e8d7b3fb0006
34,652
cpp
C++
Gunz/xpsupport/xpcrt.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
Gunz/xpsupport/xpcrt.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
Gunz/xpsupport/xpcrt.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
/* Copyright (c) 2012 Mike Ryan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // XPSupport CRT Wrappers // Written by Mike Ryan (aka Ted.) // http://tedwvc.wordpress.com // see also http://connect.microsoft.com/VisualStudio/feedback/details/690617/ // Version history // 2012-03-11 1.0 initial release // 2012-03-13 1.01 Added msvcp110 stuff (InitializeCriticalSectionEx, CreateSymbolicLink(A/W) // 2012-03-15 1.02 (MFC updates) // 2012-03-15 1.03 Added fix for ConCRT runtime resource manager initialization (so std::thread can now be used) // 2012-03-15 1.04 (MFC updates) // 2012-03-29 1.05 added wrapper for EnumSystemLocalesEx // 2012-05-05 1.06 added wrapper for GetLogicalProcessorInformation (allows unofficial XP SP2 support) - thanks to Michael Chourdakis for this implementation // 2012-05-09 1.07 added wrapper for InitOnceExecuteOnce // 2012-05-26 1.08 added XP/2003 x64 edition support (in xpcrtwrap64.asm) // - thanks to Antony Vennard (https://vennard.org.uk) for testing and correcting several errors in my initial test x64 release // 2012-05-27 1.09 fixed non-Unicode (MBCS) builds (thanks to Latency for suggesting and helping with this fix) // 2012-06-28 1.10 added support for Vista threadpooling functions (added to pre-RTM version of CRT), added MIT license #include "stdafx.h" #ifndef _UNICODE #include <io.h> #include <stdio.h> #endif // we'll be using ntdll.dll so pull in a reference here #pragma comment (lib, "ntdll.lib") static BOOL IsVista = ((BYTE)::GetVersion() >= 6); // GetTickCount64 implementation for XP (32 bit) // IMPORTANT NOTE: this is the only undocumented part of the solution - if you're uncomfortable with this part, // please substitute it with an alternative of your choice! // For XP, we will use some undocumented features of Windows to emulate GetTickCount64 // see also: http://uninformed.org/index.cgi?v=7&a=2&p=12 for formula explanation and the offset used below #define CONST_SCALING_FACTOR 78 // see #include "winternl.h" in SDK headers for documented parts of these structures and enums // NOTE: only tested on XP 32 bit OS. 64 bit structures may differ!! // expanded from Microsoft's winternl.h - documented as size 48 typedef struct _SYSTEM_TIMEOFDAY_INFORMATION { LARGE_INTEGER TimeOfBoot; BYTE unused[40]; } SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION; // copied from Microsoft's winternl.h typedef enum _SYSTEM_INFORMATION_CLASS { SystemTimeOfDayInformation = 3, } SYSTEM_INFORMATION_CLASS; extern "C" __kernel_entry LONG NTAPI NtQuerySystemInformation ( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL); extern "C" __kernel_entry LONG NTAPI NtQuerySystemTime (OUT PLARGE_INTEGER SystemTime); static ULONGLONG UndocumentedGetTickCount64ImplementationForXP32() { static ULONGLONG StartTimeOfServer = static_cast<ULONGLONG>(-1); if (StartTimeOfServer == -1) { // undocumented - before using, please see comment above SYSTEM_TIMEOFDAY_INFORMATION timeofDayInfo = {0}; // see http://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx NtQuerySystemInformation (SystemTimeOfDayInformation, &timeofDayInfo, sizeof(timeofDayInfo), 0); StartTimeOfServer = timeofDayInfo.TimeOfBoot.QuadPart; } // NtQuerySystemTime documented by Microsoft // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724512(v=vs.85).aspx LARGE_INTEGER now; NtQuerySystemTime( &now ); return (ULONGLONG)(((now.QuadPart - StartTimeOfServer) / 10000.0) + CONST_SCALING_FACTOR); } typedef ULONGLONG (WINAPI *pGetTickCount64)(void); extern "C" ULONGLONG WINAPI AfxGetTickCount64(void) { static pGetTickCount64 GetTickCount64_p = NULL; if (IsVista) { // Vista or higher if (!GetTickCount64_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetTickCount64_p = (pGetTickCount64) GetProcAddress(mod, "GetTickCount64"); } return GetTickCount64_p(); } else return UndocumentedGetTickCount64ImplementationForXP32(); // see above } // the following two functions wrap LCIDToLocaleName/LocaleNameToLCID // we wrap them here so several locale name based APIs can convert back and forth to LCIDs on XP (which doesn't support LCIDs) // Note: this requires the use of NLSDL.DLL which ships with Internet Explorer 7 or later // if you really need to support XP3 + IE6 then please use the redistributable download available here: // http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=25241 // the above installs nlsdl to the windows system32 folder // or alternatively, modify the functions below to use MLANG instead (older technology but should work for the most part) // see: http://qualapps.blogspot.com/2011/10/convert-locale-name-to-lcid-in-c.html for an MLANG implementation typedef int (WINAPI *pLCIDToLocaleName)(__in LCID Locale, __out_opt LPWSTR lpName, int cchName,__in DWORD dwFlags); int WINAPI AfxLCIDToLocaleName( __in LCID Locale, __out_opt LPWSTR lpName, int cchName,__in DWORD dwFlags ) { static pLCIDToLocaleName LCIDToLocaleName_p = NULL ; LCID lcid = GetUserDefaultLCID() ; if( LCIDToLocaleName_p == NULL ){ HMODULE mod = NULL ; if( IsVista ){ // for Vista and up mod = GetModuleHandle( _T( "KERNEL32.dll" ) ) ; if( mod ){ LCIDToLocaleName_p = ( pLCIDToLocaleName ) GetProcAddress( mod, "LCIDToLocaleName" ) ; } } else{ // for XP and below - only support nlsdl.dll in system32 folder (comes with IE7 or nlsdl redist) TCHAR systempath[_MAX_PATH]; GetSystemDirectory(systempath , _countof(systempath)); TCHAR FullPath[_MAX_PATH] ; wsprintf(FullPath, _T( "%s\\%s" ) , systempath,_T( "nlsdl.dll" ) ) ; if (_taccess(FullPath, 00) == 0) mod = LoadLibrary( FullPath ) ; if( mod ){ LCIDToLocaleName_p = ( pLCIDToLocaleName ) GetProcAddress( mod, "DownlevelLCIDToLocaleName" ) ; } } } if( LCIDToLocaleName_p ){ // call function lcid = LCIDToLocaleName_p( Locale, lpName, cchName, dwFlags ) ; } return lcid ; } typedef LCID (WINAPI *pLocaleNameToLCID)(__in LPCWSTR lpName,__in DWORD dwFlags); LCID WINAPI AfxLocaleNameToLCID( __in LPCWSTR lpName, __in DWORD dwFlags ) { static pLocaleNameToLCID LocaleNameToLCID_p = NULL ; LCID lcid = GetUserDefaultLCID() ; if( LocaleNameToLCID_p == NULL ){ HMODULE mod = NULL ; if( IsVista ){ // for Vista and up mod = GetModuleHandle( _T( "KERNEL32.dll" ) ) ; if( mod ){ LocaleNameToLCID_p = ( pLocaleNameToLCID ) GetProcAddress( mod, "LocaleNameToLCID" ) ; } } else{ // for XP and below - only support nlsdl.dll in system32 folder (comes with IE7) TCHAR systempath[_MAX_PATH] = {0}; GetSystemDirectory(systempath , _countof(systempath)); TCHAR FullPath[_MAX_PATH] = {0}; wsprintf(FullPath, _T( "%s\\%s" ) , systempath,_T( "nlsdl.dll" ) ) ; if (_taccess(FullPath, 00) == 0) mod = LoadLibrary( FullPath ) ; if( mod ){ LocaleNameToLCID_p = ( pLocaleNameToLCID ) GetProcAddress( mod, "DownlevelLocaleNameToLCID" ) ; } } } if( LocaleNameToLCID_p ){ // call function lcid = LocaleNameToLCID_p( lpName, dwFlags ) ; } return lcid ; } typedef BOOL (WINAPI *pIsValidLocaleName)(LPCWSTR lpLocaleName); extern "C" BOOL WINAPI AfxIsValidLocaleName(_In_ LPCWSTR lpLocaleName) { static pIsValidLocaleName IsValidLocaleName_p = NULL; if (IsVista) { // Vista or higher if (!IsValidLocaleName_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) IsValidLocaleName_p = (pIsValidLocaleName) GetProcAddress(mod, "IsValidLocaleName"); } return IsValidLocaleName_p(lpLocaleName); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else return TRUE; // assume valid return IsValidLocale(lcid, 0); } } typedef int (WINAPI *pLCMapStringEx)( LPCWSTR lpLocaleName, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM sortHandle ); extern "C" int WINAPI AfxLCMapStringEx( LPCWSTR lpLocaleName, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM sortHandle ) { static pLCMapStringEx LCMapStringEx_p = NULL; if (IsVista) { // Vista or higher if (!LCMapStringEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) LCMapStringEx_p = (pLCMapStringEx) GetProcAddress(mod, "LCMapStringEx"); } return LCMapStringEx_p(lpLocaleName, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest, lpVersionInformation, lpReserved, sortHandle); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return LCMapStringW(lcid, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest); } } typedef int (WINAPI *pCompareStringEx)( LPCWSTR lpLocaleName, DWORD dwCmpFlags, LPCWSTR lpString1, int cchCount1, LPCWSTR lpString2, int cchCount2, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM lParam ); extern "C" int WINAPI AfxCompareStringEx( LPCWSTR lpLocaleName, DWORD dwCmpFlags, LPCWSTR lpString1, int cchCount1, LPCWSTR lpString2, int cchCount2, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM lParam ) { static pCompareStringEx CompareStringEx_p = NULL; if (IsVista) { // Vista or higher if (!CompareStringEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CompareStringEx_p = (pCompareStringEx) GetProcAddress(mod, "CompareStringEx"); } return CompareStringEx_p(lpLocaleName, dwCmpFlags, lpString1, cchCount1, lpString2, cchCount2, lpVersionInformation, lpReserved, lParam); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return CompareStringW(lcid, dwCmpFlags,lpString1, cchCount1, lpString2, cchCount2); } } typedef int (WINAPI *pGetLocaleInfoEx)(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData); extern "C" int WINAPI AfxGetLocaleInfoEx(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData) { static pGetLocaleInfoEx GetLocaleInfoEx_p = NULL; if (IsVista) { // Vista or higher if (!GetLocaleInfoEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetLocaleInfoEx_p = (pGetLocaleInfoEx) GetProcAddress(mod, "GetLocaleInfoEx"); } return GetLocaleInfoEx_p(lpLocaleName, LCType, lpLCData, cchData); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return GetLocaleInfoW(lcid, LCType, lpLCData, cchData); } } typedef int (WINAPI *pGetUserDefaultLocaleName)( __out LPWSTR lpLocaleName, __in int cchLocaleName); extern "C" int WINAPI AfxGetUserDefaultLocaleName( __out LPWSTR lpLocaleName, __in int cchLocaleName) { static pGetUserDefaultLocaleName GetUserDefaultLocaleName_p = NULL; if (IsVista) { // Vista or higher if (!GetUserDefaultLocaleName_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetUserDefaultLocaleName_p = (pGetUserDefaultLocaleName) GetProcAddress(mod, "GetUserDefaultLocaleName"); } return GetUserDefaultLocaleName_p(lpLocaleName, cchLocaleName); } else { LCID lcid = GetUserDefaultLCID(); return AfxLCIDToLocaleName(lcid, lpLocaleName, cchLocaleName, 0); } } typedef BOOL (WINAPI *pEnumSystemLocalesEx)(__in LOCALE_ENUMPROCEX lpLocaleEnumProcEx,__in DWORD dwFlags, __in LPARAM lParam, __in_opt LPVOID lpReserved); LOCALE_ENUMPROCEX pLocaleEnumProcEx = 0; BOOL CALLBACK EnumLocalesProcWrapper (LPWSTR lpLocaleString) { LCID localeID = 0; wchar_t localeName[100] = {0}; swscanf_s( lpLocaleString, L"%x", &localeID ); AfxLCIDToLocaleName(localeID, localeName, _countof(localeName), 0); return pLocaleEnumProcEx(localeName, 0, 0); } extern "C" BOOL WINAPI AfxEnumSystemLocalesEx(__in LOCALE_ENUMPROCEX lpLocaleEnumProcEx,__in DWORD dwFlags, __in LPARAM lParam, __in_opt LPVOID lpReserved) { static pEnumSystemLocalesEx EnumSystemLocalesEx_p = NULL; if (IsVista) { // Vista or higher if (!EnumSystemLocalesEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) EnumSystemLocalesEx_p = (pEnumSystemLocalesEx) GetProcAddress(mod, "EnumSystemLocalesEx"); } return EnumSystemLocalesEx_p(lpLocaleEnumProcEx, dwFlags, lParam, lpReserved); } else { // fallback to EnumSystemLocales on XP // not even close to being thread-safe (left as exercise for reader) pLocaleEnumProcEx = lpLocaleEnumProcEx; // global variable return EnumSystemLocalesW(EnumLocalesProcWrapper, LCID_INSTALLED); } } // FLS functions - idea borrowed from VC9 and below's CRT source code (this is how they handle it) typedef DWORD (WINAPI *pFlsAlloc) (IN PFLS_CALLBACK_FUNCTION lpCallback OPTIONAL); typedef PVOID (WINAPI *pFlsGetValue) (IN DWORD dwFlsIndex); typedef BOOL (WINAPI *pFlsSetValue) (IN DWORD dwFlsIndex,IN PVOID lpFlsData); typedef BOOL (WINAPI *pFlsFree) ( IN DWORD dwFlsIndex); pFlsAlloc gpFlsAlloc = NULL; pFlsGetValue gpFlsGetValue = NULL; pFlsSetValue gpFlsSetValue = NULL; pFlsFree gpFlsFree = NULL; DWORD WINAPI __noParamTlsAlloc( PFLS_CALLBACK_FUNCTION ) { return TlsAlloc(); } static BOOL FlsInited = FALSE; void FlsInit() { HINSTANCE hKernel32 = GetModuleHandle(_T("kernel32.dll")); if (hKernel32) { gpFlsAlloc = (pFlsAlloc)GetProcAddress(hKernel32, "FlsAlloc"); if (gpFlsAlloc) { // if first one is missing don't bother with the others. gpFlsGetValue = (pFlsGetValue)GetProcAddress(hKernel32,"FlsGetValue"); gpFlsSetValue = (pFlsSetValue)GetProcAddress(hKernel32, "FlsSetValue"); gpFlsFree = (pFlsFree)GetProcAddress(hKernel32, "FlsFree"); } } if (!gpFlsAlloc) { gpFlsAlloc = (pFlsAlloc)__noParamTlsAlloc; gpFlsGetValue = (pFlsGetValue)TlsGetValue; gpFlsSetValue = (pFlsSetValue)TlsSetValue; gpFlsFree = (pFlsFree)TlsFree; } FlsInited = TRUE; } extern "C" DWORD WINAPI AfxFlsAlloc(__in PFLS_CALLBACK_FUNCTION lpCallback) { // this function is called by CRT before any globals are initialized so we have to call the initialization of the function pointers here if (!FlsInited) FlsInit(); return gpFlsAlloc(lpCallback); } extern "C" PVOID WINAPI AfxFlsGetValue( __in DWORD dwFlsIndex) { return gpFlsGetValue(dwFlsIndex); } extern "C" BOOL WINAPI AfxFlsSetValue(__in DWORD dwFlsIndex, __in_opt PVOID lpFlsData) { return gpFlsSetValue(dwFlsIndex, lpFlsData); } extern "C" BOOL WINAPI AfxFlsFree(__in DWORD dwFlsIndex) { return gpFlsFree(dwFlsIndex); } // miscellaneous functions // this helper function copied from http://www.scss.tcd.ie/Jeremy.Jones/GetCurrentProcessorNumberXP.htm DWORD GetCurrentProcessorNumberXP(void) { #ifndef _WIN64 _asm {mov eax, 1} _asm {cpuid} _asm {shr ebx, 24} _asm {mov eax, ebx} #else return 0; #endif } typedef DWORD (WINAPI *pGetCurrentProcessorNumber)(void); extern "C" DWORD WINAPI AfxGetCurrentProcessorNumber() { static pGetCurrentProcessorNumber GetCurrentProcessorNumber_p = NULL; static BOOL looked = FALSE; // native version of this function available on Vista and Server 2003 if (!looked && !GetCurrentProcessorNumber_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetCurrentProcessorNumber_p = (pGetCurrentProcessorNumber) GetProcAddress(mod, "GetCurrentProcessorNumber"); else looked = TRUE; } if (GetCurrentProcessorNumber_p) return GetCurrentProcessorNumber_p(); else return GetCurrentProcessorNumberXP(); } typedef void (WINAPI *pFlushProcessWriteBuffers)(void); extern "C" void WINAPI AfxFlushProcessWriteBuffers() { static pFlushProcessWriteBuffers FlushProcessWriteBuffers_p = NULL; if (IsVista) { // Vista or higher if (!FlushProcessWriteBuffers_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) FlushProcessWriteBuffers_p = (pFlushProcessWriteBuffers) GetProcAddress(mod, "FlushProcessWriteBuffers"); } if (FlushProcessWriteBuffers_p) FlushProcessWriteBuffers_p(); } // no implementation for XP } typedef HANDLE (WINAPI *pCreateSemaphoreExW)(__in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,__in LONG lInitialCount, __in LONG lMaximumCount, __in_opt LPCWSTR lpName, __reserved DWORD dwFlags, __in DWORD dwDesiredAccess); extern "C" HANDLE WINAPI AfxCreateSemaphoreExW(__in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,__in LONG lInitialCount, __in LONG lMaximumCount, __in_opt LPCWSTR lpName, __reserved DWORD dwFlags, __in DWORD dwDesiredAccess) { static pCreateSemaphoreExW CreateSemaphoreExW_p = NULL; if (IsVista) { // Vista or higher if (!CreateSemaphoreExW_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateSemaphoreExW_p = (pCreateSemaphoreExW) GetProcAddress(mod, "CreateSemaphoreExW"); } return CreateSemaphoreExW_p(lpSemaphoreAttributes,lInitialCount,lMaximumCount, lpName, dwFlags, dwDesiredAccess); } else { // XP can't support last two parameters of CreateSemaphoreExW return CreateSemaphoreW(lpSemaphoreAttributes,lInitialCount,lMaximumCount, lpName); } } typedef int (WINAPI *pGetTimeFormatEx)(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpTime, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpTimeStr, __in int cchTime); extern "C" int WINAPI AfxGetTimeFormatEx(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpTime, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpTimeStr, __in int cchTime) { static pGetTimeFormatEx GetTimeFormatEx_p = NULL; if (IsVista) { // Vista or higher if (!GetTimeFormatEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetTimeFormatEx_p = (pGetTimeFormatEx) GetProcAddress(mod, "GetTimeFormatEx"); } return GetTimeFormatEx_p(lpLocaleName, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return GetTimeFormatW(lcid, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime); } } typedef int (WINAPI *pGetDateFormatEx)(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpDate, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpDateStr, __in int cchDate, __in_opt LPCWSTR lpCalendar); extern "C" int WINAPI AfxGetDateFormatEx(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpDate, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpDateStr, __in int cchDate, __in_opt LPCWSTR lpCalendar) { static pGetDateFormatEx GetDateFormatEx_p = NULL; if (IsVista) { // Vista or higher if (!GetDateFormatEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetDateFormatEx_p = (pGetDateFormatEx) GetProcAddress(mod, "GetDateFormatEx"); } return GetDateFormatEx_p(lpLocaleName, dwFlags, lpDate, lpFormat, lpDateStr, cchDate, lpCalendar); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return GetDateFormatW(lcid, dwFlags, lpDate, lpFormat, lpDateStr, cchDate); } } typedef BOOL (WINAPI *pSetThreadStackGuarantee)(__inout PULONG StackSizeInBytes); // available on Vista, XPx64, Server 2003 with SP1 but not XP x86 extern "C" BOOL WINAPI AfxSetThreadStackGuarantee(__inout PULONG StackSizeInBytes) { static pSetThreadStackGuarantee SetThreadStackGuarantee_p = NULL; static BOOL looked = FALSE; if (!looked && !SetThreadStackGuarantee_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) SetThreadStackGuarantee_p = (pSetThreadStackGuarantee) GetProcAddress(mod, "SetThreadStackGuarantee"); else looked = TRUE; } if (SetThreadStackGuarantee_p) return SetThreadStackGuarantee_p(StackSizeInBytes); else { // for XP we only need to support stack size query (if you pass in 0 as the stack size) - see _resetstkoflw in CRT source // not completed - left as an exercise to reader if (StackSizeInBytes && *StackSizeInBytes == 0) { *StackSizeInBytes = 0; return 1; } } return 0; } // STL stuff typedef BOOL (WINAPI *pInitializeCriticalSectionEx)(__out LPCRITICAL_SECTION lpCriticalSection, __in DWORD dwSpinCount, __in DWORD Flags); extern "C" BOOL WINAPI AfxInitializeCriticalSectionEx(__out LPCRITICAL_SECTION lpCriticalSection, __in DWORD dwSpinCount, __in DWORD Flags) { static pInitializeCriticalSectionEx InitializeCriticalSectionEx_p = NULL; if (IsVista) { // Vista or higher if (!InitializeCriticalSectionEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) InitializeCriticalSectionEx_p = (pInitializeCriticalSectionEx) GetProcAddress(mod, "InitializeCriticalSectionEx"); } return InitializeCriticalSectionEx_p(lpCriticalSection, dwSpinCount, Flags); } // on XP we'll just use InitializeCriticalSection for now InitializeCriticalSection(lpCriticalSection); return TRUE; } typedef BOOLEAN (WINAPI *pCreateSymbolicLinkA)(__in LPSTR lpSymlinkFileName, __in LPSTR lpTargetFileName, __in DWORD dwFlags); extern "C" BOOLEAN WINAPI AfxCreateSymbolicLinkA(__in LPSTR lpSymlinkFileName, __in LPSTR lpTargetFileName, __in DWORD dwFlags) { static pCreateSymbolicLinkA CreateSymbolicLinkA_p = NULL; if (IsVista) { // Vista or higher if (!CreateSymbolicLinkA_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateSymbolicLinkA_p = (pCreateSymbolicLinkA) GetProcAddress(mod, "CreateSymbolicLinkA"); } return CreateSymbolicLinkA_p(lpSymlinkFileName, lpTargetFileName, dwFlags); } return 0; } typedef BOOLEAN (WINAPI *pCreateSymbolicLinkW)(__in LPWSTR lpSymlinkFileName, __in LPWSTR lpTargetFileName, __in DWORD dwFlags); extern "C" BOOLEAN WINAPI AfxCreateSymbolicLinkW(__in LPWSTR lpSymlinkFileName, __in LPWSTR lpTargetFileName, __in DWORD dwFlags) { static pCreateSymbolicLinkW CreateSymbolicLinkW_p = NULL; if (IsVista) { // Vista or higher if (!CreateSymbolicLinkW_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateSymbolicLinkW_p = (pCreateSymbolicLinkW) GetProcAddress(mod, "CreateSymbolicLinkW"); } return CreateSymbolicLinkW_p(lpSymlinkFileName, lpTargetFileName, dwFlags); } return 0; } // GetLogicalProcessorInformationXP implementation provided by Michael Chourdakis of TurboIRC.COM BOOL GetLogicalProcessorInformationXP(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer,__inout PDWORD dwLength) { if (!dwLength) return 0; if (*dwLength < sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)) { SetLastError(ERROR_INSUFFICIENT_BUFFER); *dwLength = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); return FALSE; } if (Buffer == 0) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } SYSTEM_LOGICAL_PROCESSOR_INFORMATION& g1 = Buffer[0]; g1.ProcessorMask = 0x1; g1.Relationship = RelationProcessorCore; g1.ProcessorCore.Flags = 0; *dwLength = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); SetLastError(0); return TRUE; } typedef BOOL (WINAPI *pGetLogicalProcessorInformation)(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, __inout PDWORD ReturnLength); // GetLogicalProcessorInformation available on XP SP3 and above but not XP SP2 extern "C" BOOL WINAPI AfxGetLogicalProcessorInformation(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, __inout PDWORD ReturnLength) { static pGetLogicalProcessorInformation GetLogicalProcessorInformation_p = NULL; static BOOL looked = FALSE; if (!looked && !GetLogicalProcessorInformation_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetLogicalProcessorInformation_p = (pGetLogicalProcessorInformation) GetProcAddress(mod, "GetLogicalProcessorInformation"); else looked = TRUE; } if (GetLogicalProcessorInformation_p) return GetLogicalProcessorInformation_p(Buffer, ReturnLength); else return GetLogicalProcessorInformationXP(Buffer, ReturnLength); } // not thread-safe - may not even be correct BOOL WINAPI InitOnceExecuteOnceXP(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context) { BOOL ret = TRUE; static BOOL calledOnce = FALSE; if (!calledOnce) { ret = InitFn(InitOnce, Parameter, Context); calledOnce = TRUE; } return ret; } typedef BOOL (WINAPI *pInitOnceExecuteOnce)(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context); extern "C" BOOL WINAPI AfxInitOnceExecuteOnce(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context) { static pInitOnceExecuteOnce InitOnceExecuteOnce_p = NULL; if (IsVista) { // Vista or higher if (!InitOnceExecuteOnce_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) InitOnceExecuteOnce_p = (pInitOnceExecuteOnce) GetProcAddress(mod, "InitOnceExecuteOnce"); } return InitOnceExecuteOnce_p(InitOnce, InitFn, Parameter, Context); } else return InitOnceExecuteOnceXP(InitOnce, InitFn, Parameter, Context); } // RTM added 8 new Vista+ APIs: // // CloseThreadpoolTimer // CloseThreadpoolWait // CreateThreadpoolTimer // CreateThreadpoolWait // FreeLibraryWhenCallbackReturns // SetThreadpoolTimer // SetThreadpoolWait // WaitForThreadpoolTimerCallbacks typedef VOID (WINAPI *pCloseThreadpoolTimer)(__inout PTP_TIMER pti); extern "C" VOID WINAPI AfxCloseThreadpoolTimer(__inout PTP_TIMER pti) { static pCloseThreadpoolTimer CloseThreadpoolTimer_p = NULL; if (IsVista) { // Vista or higher if (!CloseThreadpoolTimer_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CloseThreadpoolTimer_p = (pCloseThreadpoolTimer) GetProcAddress(mod, "CloseThreadpoolTimer"); } CloseThreadpoolTimer_p(pti); } return; } typedef VOID (WINAPI *pCloseThreadpoolWait)(__inout PTP_WAIT pwa); extern "C" VOID WINAPI AfxCloseThreadpoolWait(__inout PTP_WAIT pwa) { static pCloseThreadpoolWait CloseThreadpoolWait_p = NULL; if (IsVista) { // Vista or higher if (!CloseThreadpoolWait_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CloseThreadpoolWait_p = (pCloseThreadpoolWait) GetProcAddress(mod, "CloseThreadpoolWait"); } CloseThreadpoolWait_p(pwa); } return; } typedef PTP_TIMER (WINAPI *pCreateThreadpoolTimer)(__in PTP_TIMER_CALLBACK pfnti, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe); extern "C" PTP_TIMER WINAPI AfxCreateThreadpoolTimer(__in PTP_TIMER_CALLBACK pfnti, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe) { static pCreateThreadpoolTimer CreateThreadpoolTimer_p = NULL; if (IsVista) { // Vista or higher if (!CreateThreadpoolTimer_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateThreadpoolTimer_p = (pCreateThreadpoolTimer) GetProcAddress(mod, "CreateThreadpoolTimer"); } return CreateThreadpoolTimer_p(pfnti, pv, pcbe); } return 0; } typedef PTP_WAIT (WINAPI *pCreateThreadpoolWait)(__in PTP_WAIT_CALLBACK pfnwa, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe); extern "C" PTP_WAIT WINAPI AfxCreateThreadpoolWait(__in PTP_WAIT_CALLBACK pfnwa, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe) { static pCreateThreadpoolWait CreateThreadpoolWait_p = NULL; if (IsVista) { // Vista or higher if (!CreateThreadpoolWait_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateThreadpoolWait_p = (pCreateThreadpoolWait) GetProcAddress(mod, "CreateThreadpoolWait"); } return CreateThreadpoolWait_p(pfnwa, pv, pcbe); } return 0; } typedef VOID (WINAPI *pFreeLibraryWhenCallbackReturns)(__inout PTP_CALLBACK_INSTANCE pci, __in HMODULE mod); extern "C" VOID WINAPI AfxFreeLibraryWhenCallbackReturns(__inout PTP_CALLBACK_INSTANCE pci, __in HMODULE mod) { static pFreeLibraryWhenCallbackReturns FreeLibraryWhenCallbackReturns_p = NULL; if (IsVista) { // Vista or higher if (!FreeLibraryWhenCallbackReturns_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) FreeLibraryWhenCallbackReturns_p = (pFreeLibraryWhenCallbackReturns) GetProcAddress(mod, "FreeLibraryWhenCallbackReturns"); } FreeLibraryWhenCallbackReturns_p(pci, mod); } return; } typedef VOID (WINAPI *pSetThreadpoolTimer)(__inout PTP_TIMER pti, __in_opt PFILETIME pftDueTime, __in DWORD msPeriod, __in_opt DWORD msWindowLength); extern "C" VOID WINAPI AfxSetThreadpoolTimer(__inout PTP_TIMER pti, __in_opt PFILETIME pftDueTime, __in DWORD msPeriod, __in_opt DWORD msWindowLength) { static pSetThreadpoolTimer SetThreadpoolTimer_p = NULL; if (IsVista) { // Vista or higher if (!SetThreadpoolTimer_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) SetThreadpoolTimer_p = (pSetThreadpoolTimer) GetProcAddress(mod, "SetThreadpoolTimer"); } SetThreadpoolTimer_p(pti, pftDueTime, msPeriod, msWindowLength); } return; } typedef VOID (WINAPI *pSetThreadpoolWait)(__inout PTP_WAIT pwa, __in_opt HANDLE h, __in_opt PFILETIME pftTimeout); extern "C" VOID WINAPI AfxSetThreadpoolWait(__inout PTP_WAIT pwa, __in_opt HANDLE h, __in_opt PFILETIME pftTimeout) { static pSetThreadpoolWait SetThreadpoolWait_p = NULL; if (IsVista) { // Vista or higher if (!SetThreadpoolWait_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) SetThreadpoolWait_p = (pSetThreadpoolWait) GetProcAddress(mod, "SetThreadpoolWait"); } SetThreadpoolWait_p(pwa, h, pftTimeout); } return; } typedef VOID (WINAPI *pWaitForThreadpoolTimerCallbacks)(__inout PTP_TIMER pti, __in BOOL fCancelPendingCallbacks); extern "C" VOID WINAPI AfxWaitForThreadpoolTimerCallbacks(__inout PTP_TIMER pti, __in BOOL fCancelPendingCallbacks) { static pWaitForThreadpoolTimerCallbacks WaitForThreadpoolTimerCallbacks_p = NULL; if (IsVista) { // Vista or higher if (!WaitForThreadpoolTimerCallbacks_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) WaitForThreadpoolTimerCallbacks_p = (pWaitForThreadpoolTimerCallbacks) GetProcAddress(mod, "WaitForThreadpoolTimerCallbacks"); } WaitForThreadpoolTimerCallbacks_p(pti, fCancelPendingCallbacks); } return; } // need to hook GetVersionEx for concrt runtime to initialized correctly // uses some globals (probably not thread-safe) typedef BOOL (WINAPI *pGetVersionExW)(__inout LPOSVERSIONINFO lpVersionInfo); static BOOL fakeVersion = FALSE; extern "C" BOOL WINAPI AfxGetVersionExW(__inout LPOSVERSIONINFO lpVersionInfo) { static pGetVersionExW GetVersionExW_p = NULL; BOOL retVal = FALSE; if (!GetVersionExW_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetVersionExW_p = (pGetVersionExW) GetProcAddress(mod, "GetVersionExW"); } if (GetVersionExW_p) retVal = GetVersionExW_p(lpVersionInfo); if (!IsVista && fakeVersion) { // XP and lower - trick ConCRT into thinking that it's Vista lpVersionInfo->dwMajorVersion = 6; lpVersionInfo->dwMinorVersion = 0; } return retVal; } #if !defined(_DEBUG) || !defined(_MFC_VER) || _MSC_FULL_VER >= 170050503 // sorry this workaround only works in release builds of MFC until Microsoft fixes this bug in VC11 // http://connect.microsoft.com/VisualStudio/feedback/details/630105/ #include <concrt.h> #if _MSC_FULL_VER >= 170050623 // pre-RTM // The following code accesses some private ConCRT data and is necessary because of the new threadpool support written // for Vista only should not be called on XP so we need to switch the Resource Manager's version back to XP after sucessfully // initializing it. class VersionSetterHack; #include <concrtrm.h> namespace Concurrency { namespace details { class ResourceManager : public Concurrency::IResourceManager { friend class VersionSetterHack; private: static IResourceManager::OSVersion s_version; public: static ResourceManager* CreateSingleton(); }; } } class VersionSetterHack { public: VersionSetterHack() { // s_version has private linkage: accessing private member using friend hack Concurrency::details::ResourceManager::s_version = Concurrency::details::ResourceManager::OSVersion::XP; } }; #endif void InitializeConCRT() { fakeVersion = TRUE; // the following function loads the resource manager using a temporary fake version (Vista) by hacking GetVersionEx Concurrency::details::_GetConcurrency(); #if _MSC_FULL_VER >= 170050623 // pre-RTM if (!IsVista) { // this needs to be done before setting back to XP because of an assertion checking for Vista Concurrency::details::ResourceManager::CreateSingleton(); // On XP OS reset version back to XP so ConCRT fallbacks will be used instead of Vista threadpooling functions VersionSetterHack versionSet; } #endif fakeVersion = FALSE; } class ForceConCRTInit { public: ForceConCRTInit() { InitializeConCRT(); } }; // this gets called before main() so allows ConCRT Resource Manager to be initialized early ForceConCRTInit init; #endif
34.791165
157
0.75303
WhyWolfie
ddb931107eeba6b3642942bac5d454e2310eb50f
2,248
cpp
C++
src/Context.cpp
santa01/frank-luna-dx11
57172ca245f7933116ad8ab1974a1ff95c6a4f4c
[ "MIT" ]
null
null
null
src/Context.cpp
santa01/frank-luna-dx11
57172ca245f7933116ad8ab1974a1ff95c6a4f4c
[ "MIT" ]
null
null
null
src/Context.cpp
santa01/frank-luna-dx11
57172ca245f7933116ad8ab1974a1ff95c6a4f4c
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Pavlo Lavrenenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Context.h" #include "Application.h" #include <chrono> Context::Context(Application& application, const ContextParams& params) : m_Application(application) , m_Params(params) { m_Window.reset(new Window(*this)); m_Device.reset(new DX11Device(*this)); } const ContextParams& Context::GetParams() const { return m_Params; } Window& Context::GetWindow() const { return *m_Window; } DX11Device& Context::GetDevice() const { return *m_Device; } float Context::GetFrameTime() const { return m_FrameTime; } void Context::Run() { m_Application.Start(*this); while (!m_Terminate) { auto frameBegin = std::chrono::high_resolution_clock::now(); m_Device->Begin(*this); m_Window->Update(*this); m_Application.Update(*this); m_Device->End(*this); auto frameEnd = std::chrono::high_resolution_clock::now(); std::chrono::duration<float> frameDuration = frameEnd - frameBegin; m_FrameTime = frameDuration.count(); } m_Application.Shutdown(*this); } void Context::Terminate() { m_Terminate = true; }
27.084337
81
0.711744
santa01
ddba5cf6d9aad6ae6bad3b4345ffd496eb24dd05
1,259
cpp
C++
11497/11497.cpp
retroinspect/my-first-ps
89c583cd7207b32465c9616b032dd1c3f1f54438
[ "Apache-2.0" ]
null
null
null
11497/11497.cpp
retroinspect/my-first-ps
89c583cd7207b32465c9616b032dd1c3f1f54438
[ "Apache-2.0" ]
null
null
null
11497/11497.cpp
retroinspect/my-first-ps
89c583cd7207b32465c9616b032dd1c3f1f54438
[ "Apache-2.0" ]
null
null
null
// 통나무 건너뛰기 #include <iostream> #include <string> #include <vector> #include <cassert> #include <cmath> #include <algorithm> #include <list> using namespace std; vector<int> input; int N; int logJumping() { sort(input.begin(), input.end()); list<int> reorder; for (int i=0; i<N; i++) { int e = input[i]; if (i%2 == 0) reorder.push_back(e); else reorder.push_front(e); } int maxDiff = -1; for (list<int>::iterator iter = reorder.begin(); iter != reorder.end(); iter++) { list<int>::iterator tmpIt = iter; tmpIt++; int num1 = *iter; int num2 = (tmpIt == reorder.end()) ? reorder.front() : *tmpIt; int tmp = abs(num1-num2); if (tmp > maxDiff) maxDiff = tmp; } return maxDiff; } int main() { string tmpString; cin >> tmpString; int T = stoi(tmpString); vector<int> answers; for (int i=0; i<T; i++) { cin >> tmpString; N = stoi(tmpString); for (int j=0; j<N; j++) { cin >> tmpString; int num = stoi(tmpString); input.push_back(num); } int answer = logJumping(); answers.push_back(answer); input.clear(); } for (vector<int>::iterator iter=answers.begin(); iter != answers.end(); iter++) { cout << *iter << endl; } return 0; }
17.985714
81
0.58062
retroinspect
ddbebac1a83fa5be9674f895330b132b682461fb
6,612
cpp
C++
src/lpython/tests/test_parse.cpp
akshanshbhatt/lpython
70fef49dbbb6cbb0447f7013231171e5c8b8e5df
[ "BSD-3-Clause" ]
31
2022-01-07T23:56:33.000Z
2022-03-29T16:09:02.000Z
src/lpython/tests/test_parse.cpp
akshanshbhatt/lpython
70fef49dbbb6cbb0447f7013231171e5c8b8e5df
[ "BSD-3-Clause" ]
197
2021-12-29T19:01:41.000Z
2022-03-31T15:58:25.000Z
src/lpython/tests/test_parse.cpp
akshanshbhatt/lpython
70fef49dbbb6cbb0447f7013231171e5c8b8e5df
[ "BSD-3-Clause" ]
17
2022-01-06T15:34:36.000Z
2022-03-31T13:55:33.000Z
#include <tests/doctest.h> #include <iostream> #include <sstream> #include <chrono> #include <string> #include <lpython/bigint.h> using LFortran::TRY; using LFortran::Result; using LFortran::BigInt::is_int_ptr; using LFortran::BigInt::ptr_to_int; using LFortran::BigInt::int_to_ptr; using LFortran::BigInt::string_to_largeint; using LFortran::BigInt::largeint_to_string; using LFortran::BigInt::MAX_SMALL_INT; using LFortran::BigInt::MIN_SMALL_INT; // Print any vector like iterable to a string template <class T> inline std::ostream &print_vec(std::ostream &out, T &d) { out << "["; for (auto p = d.begin(); p != d.end(); p++) { if (p != d.begin()) out << ", "; out << *p; } out << "]"; return out; } namespace doctest { // Convert std::vector<T> to string for doctest template<typename T> struct StringMaker<std::vector<T>> { static String convert(const std::vector<T> &value) { std::ostringstream oss; print_vec(oss, value); return oss.str().c_str(); } }; } class TokenizerError0 { }; TEST_CASE("Test Big Int") { int64_t i; void *p, *p2; /* Integer tests */ i = 0; CHECK(!is_int_ptr(i)); i = 5; CHECK(!is_int_ptr(i)); i = -5; CHECK(!is_int_ptr(i)); // Largest integer that is allowed is 2^62-1 i = 4611686018427387903LL; CHECK(i == MAX_SMALL_INT); CHECK(!is_int_ptr(i)); // this is an integer i = 4611686018427387904LL; CHECK(is_int_ptr(i)); // this is a pointer // Smallest integer that is allowed is -2^63 i = -9223372036854775808ULL; CHECK(i == MIN_SMALL_INT); CHECK(!is_int_ptr(i)); // this is an integer i = -9223372036854775809ULL; // This does not fit into a signed 64bit int CHECK(is_int_ptr(i)); // this is a pointer /* Pointer tests */ // Smallest pointer value is 0 (nullptr) p = nullptr; i = ptr_to_int(p); CHECK(is_int_ptr(i)); p2 = int_to_ptr(i); CHECK(p == p2); // Second smallest pointer value aligned to 4 is 4 p = (void*)4; i = ptr_to_int(p); CHECK(is_int_ptr(i)); p2 = int_to_ptr(i); CHECK(p == p2); // Maximum pointer value aligned to 4 is (2^64-1)-3 p = (void*)18446744073709551612ULL; i = ptr_to_int(p); CHECK(is_int_ptr(i)); p2 = int_to_ptr(i); CHECK(p == p2); /* Big int tests */ Allocator al(1024); LFortran::Str s; char *cs; s.from_str(al, "123"); i = string_to_largeint(al, s); CHECK(is_int_ptr(i)); cs = largeint_to_string(i); CHECK(std::string(cs) == "123"); s.from_str(al, "123567890123456789012345678901234567890"); i = string_to_largeint(al, s); CHECK(is_int_ptr(i)); cs = largeint_to_string(i); CHECK(std::string(cs) == "123567890123456789012345678901234567890"); } TEST_CASE("Test LFortran::Vec") { Allocator al(1024); LFortran::Vec<int> v; v.reserve(al, 2); CHECK(v.size() == 0); CHECK(v.capacity() == 2); v.push_back(al, 1); CHECK(v.size() == 1); CHECK(v.capacity() == 2); CHECK(v.p[0] == 1); CHECK(v[0] == 1); v.push_back(al, 2); CHECK(v.size() == 2); CHECK(v.capacity() == 2); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v[0] == 1); CHECK(v[1] == 2); v.push_back(al, 3); CHECK(v.size() == 3); CHECK(v.capacity() == 4); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v.p[2] == 3); CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 3); v.push_back(al, 4); CHECK(v.size() == 4); CHECK(v.capacity() == 4); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v.p[2] == 3); CHECK(v.p[3] == 4); CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 3); CHECK(v[3] == 4); v.push_back(al, 5); CHECK(v.size() == 5); CHECK(v.capacity() == 8); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v.p[2] == 3); CHECK(v.p[3] == 4); CHECK(v.p[4] == 5); CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 3); CHECK(v[3] == 4); CHECK(v[4] == 5); std::vector<int> sv = v.as_vector(); CHECK(sv.size() == 5); CHECK(&(sv[0]) != &(v.p[0])); CHECK(sv[0] == 1); CHECK(sv[1] == 2); CHECK(sv[2] == 3); CHECK(sv[3] == 4); CHECK(sv[4] == 5); } TEST_CASE("LFortran::Vec iterators") { Allocator al(1024); LFortran::Vec<int> v; v.reserve(al, 2); v.push_back(al, 1); v.push_back(al, 2); v.push_back(al, 3); v.push_back(al, 4); // Check reference (auto) int i = 0; for (auto &a : v) { i += a; } CHECK(i == 10); // Check reference (must be const) i = 0; for (const int &a : v) { i += a; } CHECK(i == 10); // Check direct type (auto) i = 0; for (auto a : v) { i += a; } CHECK(i == 10); // Check direct type (const) i = 0; for (const int a : v) { i += a; } CHECK(i == 10); // Check direct type (non const) i = 0; for (int a : v) { i += a; } CHECK(i == 10); } TEST_CASE("Test LFortran::Str") { Allocator al(1024); LFortran::Str s; const char *data = "Some string."; s.p = const_cast<char*>(data); s.n = 2; CHECK(s.size() == 2); CHECK(s.p == data); CHECK(s.str() == "So"); std::string scopy = s.str(); CHECK(s.p != &scopy[0]); CHECK(scopy == "So"); CHECK(scopy[0] == 'S'); CHECK(scopy[1] == 'o'); CHECK(scopy[2] == '\x00'); char *copy = s.c_str(al); CHECK(s.p != copy); CHECK(copy[0] == 'S'); CHECK(copy[1] == 'o'); CHECK(copy[2] == '\x00'); } TEST_CASE("Test LFortran::Allocator") { Allocator al(32); // Size is what we asked (32) plus alignment (8) = 40 CHECK(al.size_total() == 40); // Fits in the pre-allocated chunk al.alloc(32); CHECK(al.size_total() == 40); // Chunk doubles al.alloc(32); CHECK(al.size_total() == 80); // Chunk doubles al.alloc(90); CHECK(al.size_total() == 160); // We asked more than can fit in the doubled chunk (2*160), // so the chunk will be equal to what we asked (1024) plus alignment (8) al.alloc(1024); CHECK(al.size_total() == 1032); } TEST_CASE("Test LFortran::Allocator 2") { Allocator al(32); int *p = al.allocate<int>(); p[0] = 5; p = al.allocate<int>(3); p[0] = 1; p[1] = 2; p[2] = 3; std::vector<int> *v = al.make_new<std::vector<int>>(5); CHECK(v->size() == 5); // Must manually call the destructor: v->~vector<int>(); }
22.187919
77
0.535088
akshanshbhatt
ddc43cf6da150fb602bef9745593a4c071d4c933
30,276
cpp
C++
Javelin/Assembler/arm64/Assembler.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
10
2016-04-06T01:24:00.000Z
2021-11-16T10:16:51.000Z
Javelin/Assembler/arm64/Assembler.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
1
2016-05-06T05:38:58.000Z
2016-05-09T16:42:43.000Z
Javelin/Assembler/arm64/Assembler.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
null
null
null
//============================================================================ #if defined(__arm64__) //============================================================================ #include "Javelin/Assembler/arm64/Assembler.h" #include "Javelin/Assembler/JitMemoryManager.h" #include <algorithm> #include <stdint.h> //============================================================================ #if DEBUG #define USE_GOTO_LABELS 0 #else #define USE_GOTO_LABELS 1 #endif #define USE_OPTIMIZED_APPEND_INSTRUCTION_DATA 1 //============================================================================ using namespace Javelin; using namespace Javelin::arm64Assembler; //============================================================================ static int64_t cls(int64_t v) { int64_t result; asm("cls %0, %1" : "=r"(result) : "r"(v)); return result; } //============================================================================ SegmentAssembler::SegmentAssembler(JitMemoryManager &aMemoryManager) : memoryManager(aMemoryManager) { buildData.Reserve(8192); } //============================================================================ #if USE_OPTIMIZED_APPEND_INSTRUCTION_DATA __attribute__((naked)) void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s, uint32_t referenceAndDataLength, uint32_t labelData) { // Define JIT_OFFSETOF to avoid compiler warnings on offsetof() #define JIT_OFFSETOF(t,f) (size_t(&((t*)64)->f) - 64) asm volatile(".global __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj"); // Update numberOfLabels, numberOfForwardLabelReferences asm volatile("ldp w6, w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.numberOfLabels))); asm volatile("add w6, w6, w4, uxtb"); asm volatile("add w7, w7, w4, lsr #8"); asm volatile("stp w6, w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.numberOfLabels))); asm volatile("b __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj"); // Definition of AppendInstructionData(blockByteCodeSize, s); asm volatile(".global __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKh"); asm volatile("__ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKh:"); asm volatile("mov w3, %0" : : "i"(sizeof(AppendAssemblyReference))); // Definition for AppendInstructionData(blockByteCodeSize, s, referenceAndDataLength); asm volatile("__ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj:"); // Update byteCodeSize asm volatile("ldr w5, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.byteCodeSize))); asm volatile("add w5, w5, w1"); asm volatile("str w5, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.byteCodeSize))); // buildData.Append, x5 = offset, x6 = capacity. asm volatile("ldp w5, w6, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData))); asm volatile("add w7, w5, w3"); asm volatile("cmp w7, w6"); asm volatile("b.hi 1f"); asm volatile("str w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData))); asm volatile("ldr x0, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data))); asm volatile("add x0, x0, x5"); // Write referenceSize and assemblerData asm volatile("stp x2, x3, [x0]"); asm volatile("ret"); asm volatile("1:"); // Update offset and capacity asm volatile("add w1, w7, w7"); asm volatile("stp w7, w1, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData))); // Update data (inline of JitVectorBase::ExpandAndAppend asm volatile("stp x2, lr, [sp, #-48]!"); asm volatile("stp x0, x3, [sp, #16]"); asm volatile("str x5, [sp, #32]"); asm volatile("ldr x0, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data))); asm volatile("bl _realloc"); asm volatile("ldr x5, [sp, #32]"); asm volatile("ldp x7, x3, [sp, #16]"); asm volatile("ldp x2, lr, [sp], #48"); asm volatile("str x0, [x7, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data))); asm volatile("add x0, x0, x5"); // Write referenceSize and assemblerData asm volatile("stp x2, x3, [x0]"); asm volatile("ret"); } void* (SegmentAssembler::*volatile reference0)(uint32_t, const uint8_t*, uint32_t, uint32_t); //void* (SegmentAssembler::*volatile reference1)(uint32_t, const uint8_t*, uint32_t); //void (SegmentAssembler::*volatile reference2)(uint32_t, const uint8_t*); __attribute__((constructor)) static void EnsureLinkage() { reference0 = &SegmentAssembler::AppendInstructionData; // reference1 = &SegmentAssembler::AppendInstructionData; // reference2 = &SegmentAssembler::AppendInstructionData; } #else void SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s) { AppendInstructionData(blockByteCodeSize, s, sizeof(AppendAssemblyReference), 0); } void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s, uint32_t referenceAndDataLength) { return AppendInstructionData(blockByteCodeSize, s, referenceAndDataLength, 0); } void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s, uint32_t referenceAndDataLength, uint32_t labelData) { aggregateData.byteCodeSize += blockByteCodeSize; ProcessLabelData(labelData); AppendAssemblyReference *reference = (AppendAssemblyReference*) buildData.Append(referenceAndDataLength); reference->referenceSize = referenceAndDataLength; reference->assemblerData = s; return reference; } void SegmentAssembler::ProcessLabelData(uint32_t labelData) { int numberOfLabels = labelData & 0xff; int numberOfForwardLabelReferences = labelData >> 8; aggregateData.numberOfLabels += numberOfLabels; aggregateData.numberOfForwardLabelReferences += numberOfForwardLabelReferences; } #endif void* SegmentAssembler::AppendData(uint32_t byteSize) { static constexpr ActionType appendDataActions[2] = { ActionType::DataBlock, ActionType::Return, }; static_assert(sizeof(AppendByteReference) == 16, "Expected AppendByteReference to be 16 bytes"); uint32_t allocationSize = (sizeof(AppendByteReference) + byteSize + 7) & -8; AppendByteReference *reference = (AppendByteReference*) AppendInstructionData(byteSize, (const uint8_t*) &appendDataActions, allocationSize); reference->dataSize = byteSize; return reference + 1; } void SegmentAssembler::AppendDataPointer(const void *data, uint32_t byteSize) { static constexpr ActionType appendDataActions[2] = { ActionType::DataPointer, ActionType::Return, }; AppendDataPointerReference *reference = (AppendDataPointerReference*) AppendInstructionData(byteSize, (const uint8_t*) &appendDataActions, sizeof(AppendDataPointerReference)); reference->dataSize = byteSize; reference->pData = (const uint8_t*) data; } //============================================================================ __attribute__((always_inline)) int32_t SegmentAssembler::ReadSigned16(const uint8_t* &s) { int16_t result; memcpy(&result, s, sizeof(result)); s += sizeof(result); return result; } __attribute__((always_inline)) uint32_t SegmentAssembler::ReadUnsigned16(const uint8_t* &s) { uint16_t result; memcpy(&result, s, sizeof(result)); s += sizeof(result); return result; } __attribute__((always_inline)) uint32_t SegmentAssembler::ReadUnsigned32(const uint8_t* &s) { uint32_t result; memcpy(&result, s, sizeof(result)); s += sizeof(result); return result; } uint32_t SegmentAssembler::LogicalOpcodeValue(uint64_t v) { BitMaskEncodeResult result = EncodeBitMask(v); assert(result.size != 0 && "Unable to encode logical immediate"); uint32_t opcodeValue = result.rotate << 16; if(result.size == 64) opcodeValue |= 1 << 22; uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f; opcodeValue |= imms << 10; return opcodeValue; } void SegmentAssembler::Patch(uint8_t *p, RelEncoding encoding, int64_t delta) { switch(encoding) { case RelEncoding::Rel26: { uint32_t opcode; memcpy(&opcode, p, 4); assert((delta & 3) == 0); delta = opcode + (delta >> 2); opcode = (opcode & ~0x3ffffff) | (delta & 0x3ffffff); memcpy(p, &opcode, 4); } break; case RelEncoding::Rel19Offset5: { uint32_t opcode; memcpy(&opcode, p, 4); assert((delta & 3) == 0); delta = opcode + (uint32_t(delta) << 3); opcode = (opcode & ~0xffffe0) | (delta & 0xffffe0); memcpy(p, &opcode, 4); } break; case RelEncoding::Adrp: { uint64_t current = uint64_t(p) >> 12; uint64_t target = uint64_t(p + delta) >> 12; delta = target - current; } [[fallthrough]]; case RelEncoding::Rel21HiLo: { // struct Opcode // { // uint32_t _dummy0 : 5; // uint32_t offsetHi : 19; // uint32_t _dummy24 : 5; // uint32_t offsetLo : 2; // uint32_t _dummy31 : 1; // }; // // Opcode opcode; // memcpy(&opcode, p, 4); // // uint32_t rel = (opcode.offsetHi << 2) | opcode.offsetLo; // rel += delta; // opcode.offsetLo = rel; // opcode.offsetHi = rel >> 2; // memcpy(p, &opcode, 4); // The compiler does a poor job with the above code. It generates a // constant that is hoisted all the way to the start of // GenerateByteCode, which becomes overhead for every single call. // Attempts to use uint32_t with appropriate shift and masking still do // not result in the desired generated code. // -> Manually code it. It is both shorter and has less register pressure. uint32_t opcode; memcpy(&opcode, p, 4); uint32_t rel; asm volatile("sbfx %w1, %w0, #3, #21 \n\t" "bfxil %w1, %w0, #29, #2 \n\t" "add %w1, %w1, %w2 \n\t" "bfi %w0, %w1, #29, #2 \n\t" "lsr %w1, %w1, #2 \n\t" "bfi %w0, %w1, #5, #19 \n\t" : "+r"(opcode), "=&r"(rel) : "r"(delta)); memcpy(p, &opcode, 4); } break; case RelEncoding::Rel14Offset5: { uint32_t opcode; memcpy(&opcode, p, 4); delta = opcode + (uint32_t(delta) << 3); opcode = (opcode & ~0x7ffe0) | (delta & 0x7ffe0); memcpy(p, &opcode, 4); } break; case RelEncoding::Imm12: { uint32_t opcode; memcpy(&opcode, p, 4); uint32_t rel = (opcode >> 10) & 0xfff; if(int64_t(p) + delta == 0) rel = int32_t(delta); else rel += (int64_t(p) + delta); opcode = (opcode & ~0x3ffc00) | ((rel << 10) & 0x3ffc00); memcpy(p, &opcode, 4); } break; case RelEncoding::Rel64: { int64_t rel; memcpy(&rel, p, 8); rel += delta; memcpy(p, &rel, 8); } break; default: __builtin_unreachable(); } } //============================================================================ void SegmentAssembler::ProcessByteCode() { programStart = (uint8_t*) memoryManager.Allocate(aggregateData.byteCodeSize+4); // +4 is because some actions assume extra buffer. uint8_t *programEnd = GenerateByteCode(programStart); // Shrink allocation memoryManager.EndWrite(programStart); codeSize = uint32_t(programEnd - programStart); assert(codeSize <= aggregateData.byteCodeSize); memoryManager.Shrink(programStart, codeSize); } /** * There is a lot of function call overhead in GenerateBytecode() because a call to memcpy * requires the compiler to preserve all registers. * InlineMemcpy means that no external calls are made, and the compiler can make more use * of scracth registers. */ __attribute__((always_inline)) static void InlineMemcpyAndAdvancePointers(uint8_t* &dest, const uint8_t* &source, uint64_t dataSize) { int64_t scratch; asm volatile(" tst %1, #3 \n\t" " b.eq 2f \n\t" "1: \n\t" " ldrb %w0, [%3], #1 \n\t" " strb %w0, [%2], #1 \n\t" " sub %1, %1, #1 \n\t" " tst %1, #3 \n\t" " b.ne 1b \n\t" "2: \n\t" " tbz %1, #2, 1f \n\t" " ldr %w0, [%3], #4 \n\t" " str %w0, [%2], #4 \n\t" " sub %1, %1, #4 \n\t" "1: \n\t" " tbz %1, #3, 1f \n\t" " ldr %0, [%3], #8 \n\t" " str %0, [%2], #8 \n\t" " sub %1, %1, #8 \n\t" "1: \n\t" " tbz %1, #4, 1f \n\t" " ldr q0, [%3], #16 \n\t" " str q0, [%2], #16 \n\t" " sub %1, %1, #16 \n\t" "1: \n\t" " cbz %1, 2f \n\t" "1: \n\t" " ldp q0, q1, [%3], #32 \n\t" " stp q0, q1, [%2], #32 \n\t" " subs %1, %1, #32 \n\t" " b.ne 1b \n\t" "2: \n\t" : "=&r"(scratch), "+r"(dataSize), "+r"(dest), "+r"(source) : : "v0", "v1", "memory"); } #if USE_GOTO_LABELS #define CASE(x) x #define CONTINUE1(x) do { const uint8_t* pAction = s+x; void *jumpTarget = jumpOffsets[*pAction]; #define CONTINUE2 assert(s == pAction); ++s; goto *jumpTarget; } while(0) #define CONTINUE goto *jumpOffsets[*s++] #else #define CASE(x) case ActionType::x #define CONTINUE1(x) { const uint8_t* pAction = s+x; #define CONTINUE2 assert(s == pAction); continue; } #define CONTINUE continue #endif uint8_t *SegmentAssembler::GenerateByteCode(__restrict uint8_t* p) { #if USE_GOTO_LABELS static constexpr void *jumpOffsets[] = { #define TAG(x) &&x, #include "ActionTypeTags.h" #undef TAG }; #endif const AppendAssemblyReference *blockData = (AppendAssemblyReference*) buildData.begin(); const AppendAssemblyReference *const blockDataEnd = (AppendAssemblyReference*) buildData.end(); const __restrict uint8_t* s = blockData->assemblerData; #if !USE_GOTO_LABELS uint32_t opcodeValue; for(;;) { #endif #if USE_GOTO_LABELS CONTINUE; #else switch((ActionType) *s++) #endif { CASE(Return): blockData = blockData->GetNext(); if(blockData == blockDataEnd) return p; s = blockData->assemblerData; CONTINUE; CASE(Literal4): CONTINUE1(4); memcpy(p, s, 4); p += 4; s += 4; CONTINUE2; CASE(Literal8): CONTINUE1(8); memcpy(p, s, 8); p += 8; s += 8; CONTINUE2; CASE(Literal12): CONTINUE1(12); memcpy(p, s, 16); p += 12; s += 12; CONTINUE2; CASE(Literal16): CONTINUE1(16); memcpy(p, s, 16); p += 16; s += 16; CONTINUE2; CASE(Literal20): CONTINUE1(20); memcpy(p, s, 20); p += 20; s += 20; CONTINUE2; CASE(Literal24): CONTINUE1(24); memcpy(p, s, 24); p += 24; s += 24; CONTINUE2; CASE(Literal28): CONTINUE1(28); memcpy(p, s, 32); p += 28; s += 28; CONTINUE2; CASE(Literal32): CONTINUE1(32); memcpy(p, s, 32); p += 32; s += 32; CONTINUE2; CASE(LiteralBlock): { uint32_t length = ReadUnsigned16(s); InlineMemcpyAndAdvancePointers(p, s, length); CONTINUE; } CASE(Align): { CONTINUE1(1); uint8_t alignmentM1 = *s++; while(size_t(p) & 3) *p++ = 0; while(size_t(p) & alignmentM1) { const uint32_t opcode = 0xd503201f; memcpy(p, &opcode, 4); p += 4; } CONTINUE2; } CASE(Unalign): { CONTINUE1(1); uint8_t alignmentM1 = *s++; assert(alignmentM1 > 3); if(((size_t) p & alignmentM1) == 0) { const uint32_t opcode = 0xd503201f; memcpy(p, &opcode, 4); p += 4; } CONTINUE2; } CASE(Jump): s += *s + 1; CONTINUE; #if USE_GOTO_LABELS { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint32_t opcodeValue; #pragma clang diagnostic pop #endif #ifndef NDEBUG // Masked, unsigned and signed all have the same implementation in release mode, // If asserts are enabled, build 3 separate versions, where unsigned and signed // check the bounds of the provided expression. CASE(MaskedPatchB1Opcode): { int bitMask = *s++; int bitOffset = *s++; int valueShift = *s++; uint8_t value = ReadB1ExpressionValue(s, blockData); opcodeValue = ((value >> valueShift) & bitMask) << bitOffset; goto ProcessPatchOpcode; } CASE(UnsignedPatchB1Opcode): { int bitMask = *s++; int bitOffset = *s++; int valueShift = *s++; uint8_t value = ReadB1ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); assert((value & ~bitMask) == 0); opcodeValue = value >> valueShift << bitOffset; goto ProcessPatchOpcode; } #else CASE(MaskedPatchB1Opcode): CASE(UnsignedPatchB1Opcode): #endif CASE(SignedPatchB1Opcode): { int bitMask = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB1ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert((value & ~bitMask) == 0 || (value | bitMask) == -1); opcodeValue = (value & bitMask) << bitOffset; goto ProcessPatchOpcode; } #ifndef NDEBUG CASE(MaskedPatchB2Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB2ExpressionValue(s, blockData); value >>= valueShift; uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } #else CASE(MaskedPatchB2Opcode): #endif CASE(SignedPatchB2Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB2ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert(value >> numberOfBits == 0 || value >> numberOfBits == -1); uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } #ifndef NDEBUG CASE(MaskedPatchB4Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB4ExpressionValue(s, blockData); value >>= valueShift; uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } #else CASE(MaskedPatchB4Opcode): #endif CASE(SignedPatchB4Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB4ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert(value >> numberOfBits == 0 || value >> numberOfBits == -1); uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } CASE(UnsignedPatchB2Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; uint16_t value = ReadB2ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); assert(value >> (numberOfBits + valueShift) == 0); (void) numberOfBits; opcodeValue = value >> valueShift << bitOffset; goto ProcessPatchOpcode; } CASE(UnsignedPatchB4Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; uint32_t value = ReadB4ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert(value >> numberOfBits == 0); (void) numberOfBits; opcodeValue = value << bitOffset; goto ProcessPatchOpcode; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" { uint64_t v; #pragma clang diagnostic pop CASE(LogicalImmediatePatchB4Opcode): { uint32_t value = ReadB4ExpressionValue(s, blockData); v = (uint64_t(value)<<32) | value; goto ProcessPatchLogical; } CASE(LogicalImmediatePatchB8Opcode): v = ReadB8ExpressionValue(s, blockData); ProcessPatchLogical: opcodeValue = LogicalOpcodeValue(v); goto ProcessPatchOpcode; } CASE(RepeatPatchOpcode): ProcessPatchOpcode: { int offset = ReadSigned16(s); uint32_t opcode; memcpy(&opcode, p+offset, 4); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wconditional-uninitialized" opcode |= opcodeValue; #pragma clang diagnostic pop memcpy(p+offset, &opcode, 4); CONTINUE; } #if USE_GOTO_LABELS } #endif CASE(B1Expression): *p++ = ReadB1ExpressionValue(s, blockData); CONTINUE; CASE(B2Expression): { int16_t v = ReadB2ExpressionValue(s, blockData); memcpy(p, &v, sizeof(v)); p += sizeof(v); CONTINUE; } CASE(B4Expression): { int32_t v = ReadB4ExpressionValue(s, blockData); memcpy(p, &v, sizeof(v)); p += sizeof(v); CONTINUE; } CASE(B8Expression): { int64_t v = ReadB8ExpressionValue(s, blockData); memcpy(p, &v, sizeof(v)); p += sizeof(v); CONTINUE; } CASE(DataBlock): { uint32_t dataSize = ((const AppendByteReference*) blockData)->dataSize; const uint8_t *expressionData = (const uint8_t*) blockData + sizeof(AppendByteReference); InlineMemcpyAndAdvancePointers(p, expressionData, dataSize); CONTINUE; } CASE(DataPointer): { uint32_t dataSize = ((const AppendDataPointerReference*) blockData)->dataSize; const uint8_t *pData = ((const AppendDataPointerReference*) blockData)->pData; InlineMemcpyAndAdvancePointers(p, pData, dataSize); CONTINUE; } { // Scope block for v #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint64_t v; #pragma clang diagnostic pop CASE(Imm0B1Condition): v = ReadB1ExpressionValue(s, blockData); goto ProcessImm0Condition; CASE(Imm0B2Condition): v = ReadB2ExpressionValue(s, blockData); goto ProcessImm0Condition; CASE(Imm0B4Condition): v = ReadB4ExpressionValue(s, blockData); goto ProcessImm0Condition; CASE(Imm0B8Condition): v = ReadB8ExpressionValue(s, blockData); ProcessImm0Condition: asm volatile("; This comment prevents the compiler from expanding code inappropriately."); uint32_t offset = *s++; if(v != 0) s += offset; CONTINUE; } CASE(Delta21Condition): { // ADR has 21 bits int64_t v = ReadB8ExpressionValue(s, blockData); uint32_t offset = *s++; int64_t currentP = int64_t(p); int64_t delta = v - currentP; if(cls(delta) < 64-21) s += offset; CONTINUE; } CASE(Delta26x4Condition): { // Direct branches have 26 bits, representing delta*4 int64_t v = ReadB8ExpressionValue(s, blockData); uint32_t offset = *s++; int64_t currentP = int64_t(p); int64_t delta = v - currentP; if((delta & 3) != 0 || cls(delta) < 64-26-2) s += offset; CONTINUE; } CASE(AdrpCondition): { // ADRP has 21 bits uint64_t v = ReadB8ExpressionValue(s, blockData); uint32_t offset = *s++; uint64_t currentP = uint64_t(p); int64_t delta = (v >> 12) - (currentP >> 12); if(cls(delta) < 64-21) s += offset; CONTINUE; } { // Scope block for labelId #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint32_t labelId; #pragma clang diagnostic pop CASE(Label): labelId = ReadUnsigned32(s); goto ProcessLabel; CASE(ExpressionLabel): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); ProcessLabel: asm volatile("; This comment prevents the compiler from expanding code inappropriately."); // Insert into map. labels.Set(labelId, p); JitForwardReferenceMapLookupResult result = unresolvedLabels.Find(labelId); if(result.reference) { JitForwardReferenceData *data = result.reference; JitForwardReferenceData *last; do { Patch(data->p, (RelEncoding) data->data, (intptr_t) p - (intptr_t) data->p); last = data; data = data->next; } while(data); unresolvedLabels.Remove(result, last); } CONTINUE; } { // Scope block for encoding, labelId #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint32_t labelId; const uint8_t *target; #pragma clang diagnostic pop CASE(PatchExpression): target = (const uint8_t*) ReadB8ExpressionValue(s, blockData); goto ProcessBackwardTarget; CASE(PatchExpressionLabel): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); goto ProcessPatchLabel; CASE(PatchLabel): labelId = ReadUnsigned32(s); ProcessPatchLabel: target = (const uint8_t*) labels.GetIfExists(labelId); if(target == nullptr) goto ProcessForwardLabel; else goto ProcessBackwardTarget; CASE(PatchLabelForward): labelId = ReadUnsigned32(s); goto ProcessForwardLabel; CASE(PatchExpressionLabelForward): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); ProcessForwardLabel: { JitForwardReferenceData *refData = unresolvedLabels.Add(labelId); RelEncoding encoding = (RelEncoding) *s++; uint8_t *patchAddress = p + ReadSigned16(s); refData->data = (uint32_t) encoding; refData->p = patchAddress; } CONTINUE; CASE(PatchLabelBackward): labelId = ReadUnsigned32(s); goto ProcessBackwardLabel; CASE(PatchExpressionLabelBackward): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); ProcessBackwardLabel: target = (uint8_t*) labels.Get(labelId); ProcessBackwardTarget: RelEncoding encoding = (RelEncoding) *s++; uint8_t *patchAddress = p + ReadSigned16(s); int64_t delta = target - patchAddress; Patch(patchAddress, encoding, delta); } CONTINUE; // Continue outside variable scope produces better register allocations CASE(PatchAbsoluteAddress): { int offset = ReadSigned16(s); uint64_t v; memcpy(&v, p + offset, 8); v += (uint64_t) p + offset; memcpy(p + offset, &v, 8); CONTINUE; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" { uint32_t opcode; uint64_t value; uint64_t notValue; uint64_t logicalValue; #pragma clang diagnostic pop CASE(MovReg32Expression): opcode = *s++; value = (uint32_t) ReadB4ExpressionValue(s, blockData); notValue = ~uint32_t(value); logicalValue = value | (value << 32); goto ProcessMovExpression; CASE(MovReg64Expression): opcode = *s++ | 0x80000000; value = ReadB8ExpressionValue(s, blockData); notValue = ~value; logicalValue = value; ProcessMovExpression: if((value & 0xffffffffffff0000) == 0) opcode |= 0x52800000 | (value << 5); else if((value & 0xffffffff0000ffff) == 0) opcode |= 0x52a00000 | (value >> 11); else if((notValue & 0xffffffffffff0000) == 0) opcode |= 0x12800000 | (notValue << 5); else if((notValue & 0xffffffff0000ffff) == 0) opcode |= 0x12a00000 | (notValue >> 11); else if((value & 0xffff0000ffffffff) == 0) opcode |= 0x52c00000 | (value >> 27); else if((value & 0x0000ffffffffffff) == 0) opcode |= 0x52e00000 | (value >> 43); else if((notValue & 0xffff0000ffffffff) == 0) opcode |= 0x12c00000 | (notValue >> 27); else if((notValue & 0x0000ffffffffffff) == 0) opcode |= 0x12e00000 | (notValue >> 43); else { BitMaskEncodeResult result = EncodeBitMask(logicalValue); assert(result.size != 0 && "Unable to encode logical immediate"); if(result.size == 64) opcode |= 1 << 22; uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f; opcode |= 0x320003e0 | (result.rotate << 16) | (imms << 10); } memcpy(p, &opcode, 4); p += 4; } CONTINUE; #if !USE_GOTO_LABELS default: assert(!"Unhandled opcode"); #endif } #if !USE_GOTO_LABELS } #endif } //============================================================================ int8_t SegmentAssembler::ReadB1ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); return expressionData[offset]; } int32_t SegmentAssembler::ReadB2ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); int16_t result; memcpy(&result, expressionData + offset, sizeof(result)); return result; } int32_t SegmentAssembler::ReadB4ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); int32_t result; memcpy(&result, expressionData + offset, sizeof(result)); return result; } int64_t SegmentAssembler::ReadB8ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); int64_t result; memcpy(&result, expressionData + offset, sizeof(result)); return result; } //============================================================================ bool SegmentAssembler::IsValidBitmask64(uint64_t value) { return EncodeBitMask(value).size != 0; } //============================================================================ #pragma mark - Assembler //============================================================================ Assembler::Assembler(JitMemoryManager *codeSegmentMemoryManager, JitMemoryManager *dataSegmentMemoryManager) : SegmentAssembler(*codeSegmentMemoryManager) { if(dataSegmentMemoryManager) { hasDataSegment = true; new(&dataSegment) SegmentAssembler(*dataSegmentMemoryManager); } } Assembler::~Assembler() { if(hasDataSegment) dataSegment.~SegmentAssembler(); } __attribute__((flatten)) void* Assembler::Build() { if(hasDataSegment) { uint32_t numberOfLabels = aggregateData.numberOfLabels + dataSegment.aggregateData.numberOfLabels; uint32_t numberOfForwardLabelReferences = aggregateData.numberOfForwardLabelReferences + dataSegment.aggregateData.numberOfForwardLabelReferences; labels.Reserve(numberOfLabels); unresolvedLabels.Reserve(numberOfForwardLabelReferences); dataSegment.labels.StartUseBacking(labels); dataSegment.unresolvedLabels.StartUseBacking(unresolvedLabels); dataSegment.ProcessByteCode(); dataSegment.labels.StopUseBacking(labels); dataSegment.unresolvedLabels.StopUseBacking(unresolvedLabels); } else { labels.Reserve(aggregateData.numberOfLabels); unresolvedLabels.Reserve(aggregateData.numberOfForwardLabelReferences); } ProcessByteCode(); assert(!unresolvedLabels.HasData() && "Not all references have been resolved"); return programStart; } //============================================================================ #endif // defined(__arm64__) //============================================================================
30.862385
148
0.647113
jthlim
ddc72e086394b9020cfa8da295a9b09421540bdb
1,203
cpp
C++
Lab1_String_Class_Concepts/program2/functions.cpp
sanatRR/Data-Structures-ICT
c87f52987b3449ad902ffb1b37c198a0a50d480a
[ "MIT" ]
1
2021-07-07T14:38:08.000Z
2021-07-07T14:38:08.000Z
Lab1_String_Class_Concepts/program2/functions.cpp
sanatRR/Data-Structures-ICT
c87f52987b3449ad902ffb1b37c198a0a50d480a
[ "MIT" ]
null
null
null
Lab1_String_Class_Concepts/program2/functions.cpp
sanatRR/Data-Structures-ICT
c87f52987b3449ad902ffb1b37c198a0a50d480a
[ "MIT" ]
null
null
null
//Copyright (c) 2021 Sanat Raorane #include<iostream> #include"student.h" using namespace std; void student::read(student arrayA[],int num){ for(int i=0;i<num;i++){ cout<<"\n\n"; //Lines for spacing cout<<"Enter details for student "<<(i+1)<<endl; cout<<"Enter Name:"<<endl; cin.sync(); cin.get(arrayA[i].name,50); cout<<"Enter roll-number:"<<endl; cin>>arrayA[i].rollNo; cout<<"Enter grade:"<<endl; cin.sync(); cin>>arrayA[i].grade; } } void student::display(student arrayA[],int num){ cout<<"\n\n\n"; //lines for spacing for(int i=0;i<num;i++){ cout<<"The details for roll no "<<arrayA[i].rollNo<<" are"<<endl; cout<<"Name: "<<arrayA[i].name<<endl; cout<<"Grade: "<<arrayA[i].grade<<endl; } } void student::sortArr(student arrayA[],int num){ student temp; /* *Using Bubble Sort */ for(int i=0;i<num-1;i++){ for(int j=0;j<num-i-1;j++){ if(arrayA[j].rollNo>arrayA[j+1].rollNo){ temp=arrayA[j]; arrayA[j]=arrayA[j+1]; arrayA[j+1]=temp; } } } }
26.152174
73
0.512884
sanatRR
ddc7df328a0a0fc63c0eb711853554763af5474b
26,301
cpp
C++
keymaster/authorization_set_test.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
9
2017-11-10T15:54:02.000Z
2021-04-15T20:57:29.000Z
keymaster/authorization_set_test.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
keymaster/authorization_set_test.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
7
2018-01-08T02:53:32.000Z
2020-10-15T13:01:46.000Z
/* * Copyright (C) 2014 The Android Open Source Project * * 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 <keymaster/authorization_set.h> #include <keymaster/android_keymaster_utils.h> #include "android_keymaster_test_utils.h" namespace keymaster { namespace test { TEST(Construction, ListProvided) { keymaster_key_param_t params[] = { Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY), Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA), Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD), Authorization(TAG_APPLICATION_ID, "my_app", 6), Authorization(TAG_KEY_SIZE, 256), Authorization(TAG_AUTH_TIMEOUT, 300), }; AuthorizationSet set(params, array_length(params)); EXPECT_EQ(8U, set.size()); } TEST(Construction, Copy) { keymaster_key_param_t params[] = { Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY), Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA), Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD), Authorization(TAG_APPLICATION_ID, "my_app", 6), Authorization(TAG_KEY_SIZE, 256), Authorization(TAG_AUTH_TIMEOUT, 300), }; AuthorizationSet set(params, array_length(params)); AuthorizationSet set2(set); EXPECT_EQ(set, set2); } TEST(Construction, NullProvided) { keymaster_key_param_t params[] = { Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY), }; AuthorizationSet set1(params, 0); EXPECT_EQ(0U, set1.size()); EXPECT_EQ(AuthorizationSet::OK, set1.is_valid()); AuthorizationSet set2(reinterpret_cast<keymaster_key_param_t*>(NULL), array_length(params)); EXPECT_EQ(0U, set2.size()); EXPECT_EQ(AuthorizationSet::OK, set2.is_valid()); } TEST(Lookup, NonRepeated) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); EXPECT_EQ(8U, set.size()); int pos = set.find(TAG_ALGORITHM); ASSERT_NE(-1, pos); EXPECT_EQ(KM_TAG_ALGORITHM, set[pos].tag); EXPECT_EQ(KM_ALGORITHM_RSA, set[pos].enumerated); pos = set.find(TAG_MAC_LENGTH); EXPECT_EQ(-1, pos); uint32_t int_val = 0; EXPECT_TRUE(set.GetTagValue(TAG_USER_ID, &int_val)); EXPECT_EQ(7U, int_val); keymaster_blob_t blob_val; EXPECT_TRUE(set.GetTagValue(TAG_APPLICATION_ID, &blob_val)); EXPECT_EQ(6U, blob_val.data_length); EXPECT_EQ(0, memcmp(blob_val.data, "my_app", 6)); } TEST(Lookup, Repeated) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_SECURE_ID, 47727) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); EXPECT_EQ(9U, set.size()); int pos = set.find(TAG_PURPOSE); ASSERT_FALSE(pos == -1); EXPECT_EQ(KM_TAG_PURPOSE, set[pos].tag); EXPECT_EQ(KM_PURPOSE_SIGN, set[pos].enumerated); pos = set.find(TAG_PURPOSE, pos); EXPECT_EQ(KM_TAG_PURPOSE, set[pos].tag); EXPECT_EQ(KM_PURPOSE_VERIFY, set[pos].enumerated); EXPECT_EQ(-1, set.find(TAG_PURPOSE, pos)); pos = set.find(TAG_USER_SECURE_ID, pos); EXPECT_EQ(KM_TAG_USER_SECURE_ID, set[pos].tag); EXPECT_EQ(47727U, set[pos].long_integer); } TEST(Lookup, Indexed) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); EXPECT_EQ(8U, set.size()); EXPECT_EQ(KM_TAG_PURPOSE, set[0].tag); EXPECT_EQ(KM_PURPOSE_SIGN, set[0].enumerated); // Lookup beyond end doesn't work, just returns zeros, but doens't blow up either (verify by // running under valgrind). EXPECT_EQ(KM_TAG_INVALID, set[10].tag); } TEST(Serialization, RoundTrip) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_USER_SECURE_ID, 47727) .Authorization(TAG_AUTH_TIMEOUT, 300) .Authorization(TAG_ALL_USERS) .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3) .Authorization(TAG_ACTIVE_DATETIME, 10)); size_t size = set.SerializedSize(); EXPECT_TRUE(size > 0); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); AuthorizationSet deserialized(buf.get(), size); EXPECT_EQ(AuthorizationSet::OK, deserialized.is_valid()); EXPECT_EQ(set, deserialized); int pos = deserialized.find(TAG_APPLICATION_ID); ASSERT_NE(-1, pos); EXPECT_EQ(KM_TAG_APPLICATION_ID, deserialized[pos].tag); EXPECT_EQ(6U, deserialized[pos].blob.data_length); EXPECT_EQ(0, memcmp(deserialized[pos].blob.data, "my_app", 6)); } TEST(Deserialization, Deserialize) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); size_t size = set.SerializedSize(); EXPECT_TRUE(size > 0); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); AuthorizationSet deserialized; const uint8_t* p = buf.get(); EXPECT_TRUE(deserialized.Deserialize(&p, p + size)); EXPECT_EQ(p, buf.get() + size); EXPECT_EQ(AuthorizationSet::OK, deserialized.is_valid()); EXPECT_EQ(set.size(), deserialized.size()); for (size_t i = 0; i < set.size(); ++i) { EXPECT_EQ(set[i].tag, deserialized[i].tag); } int pos = deserialized.find(TAG_APPLICATION_ID); ASSERT_NE(-1, pos); EXPECT_EQ(KM_TAG_APPLICATION_ID, deserialized[pos].tag); EXPECT_EQ(6U, deserialized[pos].blob.data_length); EXPECT_EQ(0, memcmp(deserialized[pos].blob.data, "my_app", 6)); } TEST(Deserialization, TooShortBuffer) { uint8_t buf[] = {0, 0, 0}; AuthorizationSet deserialized(buf, array_length(buf)); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); const uint8_t* p = buf; EXPECT_FALSE(deserialized.Deserialize(&p, p + array_length(buf))); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); } TEST(Deserialization, InvalidLengthField) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); size_t size = set.SerializedSize(); EXPECT_TRUE(size > 0); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); *reinterpret_cast<uint32_t*>(buf.get()) = 9; AuthorizationSet deserialized(buf.get(), size); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); const uint8_t* p = buf.get(); EXPECT_FALSE(deserialized.Deserialize(&p, p + size)); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); } static uint32_t read_uint32(const uint8_t* buf) { uint32_t val; memcpy(&val, buf, sizeof(val)); return val; } static void add_to_uint32(uint8_t* buf, int delta) { uint32_t val; memcpy(&val, buf, sizeof(val)); val += delta; memcpy(buf, &val, sizeof(val)); } TEST(Deserialization, MalformedIndirectData) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_APPLICATION_DATA, "foo", 3)); size_t size = set.SerializedSize(); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); // This sucks. This test, as written, requires intimate knowledge of the serialized layout of // this particular set, which means it's brittle. But it's important to test that we handle // broken serialized data and I can't think of a better way to write this. // // The contents of buf are: // // Bytes: Content: // 0-3 Length of string data, which is 9. // 4-9 "my_app" // 10-12 "foo" // 13-16 Number of elements, which is 2. // 17-20 Length of elements, which is 24. // 21-24 First tag, TAG_APPLICATION_ID // 25-28 Length of string "my_app", 6 // 29-32 Offset of string "my_app", 0 // 33-36 Second tag, TAG_APPLICATION_DATA // 37-40 Length of string "foo", 3 // 41-44 Offset of string "foo", 6 // Check that stuff is where we think. EXPECT_EQ('m', buf[4]); EXPECT_EQ('f', buf[10]); // Length of "my_app" EXPECT_EQ(6U, read_uint32(buf.get() + 25)); // Offset of "my_app" EXPECT_EQ(0U, read_uint32(buf.get() + 29)); // Length of "foo" EXPECT_EQ(3U, read_uint32(buf.get() + 37)); // Offset of "foo" EXPECT_EQ(6U, read_uint32(buf.get() + 41)); // Check that deserialization works. AuthorizationSet deserialized1(buf.get(), size); EXPECT_EQ(AuthorizationSet::OK, deserialized1.is_valid()); const uint8_t* p = buf.get(); EXPECT_TRUE(deserialized1.Deserialize(&p, p + size)); EXPECT_EQ(AuthorizationSet::OK, deserialized1.is_valid()); // // Now mess them up in various ways: // // Move "foo" offset so offset + length goes off the end add_to_uint32(buf.get() + 41, 1); AuthorizationSet deserialized2(buf.get(), size); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized2.is_valid()); add_to_uint32(buf.get() + 41, -1); // Shorten the "my_app" length to make a gap between the blobs. add_to_uint32(buf.get() + 25, -1); AuthorizationSet deserialized3(buf.get(), size); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized3.is_valid()); add_to_uint32(buf.get() + 25, 1); // Extend the "my_app" length to make them overlap, and decrease the "foo" length to keep the // total length the same. We don't detect this but should. // TODO(swillden): Detect overlaps and holes that leave total size correct. add_to_uint32(buf.get() + 25, 1); add_to_uint32(buf.get() + 37, -1); AuthorizationSet deserialized4(buf.get(), size); EXPECT_EQ(AuthorizationSet::OK, deserialized4.is_valid()); } TEST(Growable, SuccessfulRoundTrip) { AuthorizationSet growable; EXPECT_TRUE(growable.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA))); EXPECT_EQ(1U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY))); EXPECT_EQ(2U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN))); EXPECT_EQ(3U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_ID, "data", 4))); EXPECT_EQ(4U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_DATA, "some more data", 14))); EXPECT_EQ(5U, growable.size()); size_t serialize_size = growable.SerializedSize(); UniquePtr<uint8_t[]> serialized(new uint8_t[serialize_size]); EXPECT_EQ(serialized.get() + serialize_size, growable.Serialize(serialized.get(), serialized.get() + serialize_size)); AuthorizationSet deserialized(serialized.get(), serialize_size); EXPECT_EQ(growable, deserialized); } TEST(Growable, InsufficientElemBuf) { AuthorizationSet growable; EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); // First insertion fits. EXPECT_TRUE(growable.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA))); EXPECT_EQ(1U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); // Second does too. EXPECT_TRUE(growable.push_back(Authorization(TAG_RSA_PUBLIC_EXPONENT, 3))); EXPECT_EQ(2U, growable.size()); } TEST(Growable, InsufficientIndirectBuf) { AuthorizationSet growable; EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); EXPECT_TRUE(growable.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA))); EXPECT_EQ(1U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_ID, "1234567890", 10))); EXPECT_EQ(2U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_DATA, "1", 1))); EXPECT_EQ(3U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); // Can still add another entry without indirect data. Now it's full. EXPECT_TRUE(growable.push_back(Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN))); EXPECT_EQ(4U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); } TEST(Growable, PushBackSets) { AuthorizationSetBuilder builder; builder.Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300); AuthorizationSet set1(builder.build()); AuthorizationSet set2(builder.build()); AuthorizationSet combined; EXPECT_TRUE(combined.push_back(set1)); EXPECT_TRUE(combined.push_back(set2)); EXPECT_EQ(set1.size() + set2.size(), combined.size()); EXPECT_EQ(12U, combined.indirect_size()); } TEST(GetValue, GetInt) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); uint32_t val; EXPECT_TRUE(set.GetTagValue(TAG_USER_ID, &val)); EXPECT_EQ(7U, val); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_KEY_SIZE, &val)); } TEST(GetValue, GetLong) { AuthorizationSet set1(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)); AuthorizationSet set2(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)); uint64_t val; EXPECT_TRUE(set1.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &val)); EXPECT_EQ(3U, val); // Find one that isn't there EXPECT_FALSE(set2.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &val)); } TEST(GetValue, GetLongRep) { AuthorizationSet set1(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_SECURE_ID, 8338) .Authorization(TAG_USER_SECURE_ID, 4334) .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)); AuthorizationSet set2(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)); uint64_t val; EXPECT_TRUE(set1.GetTagValue(TAG_USER_SECURE_ID, 0, &val)); EXPECT_EQ(8338U, val); EXPECT_TRUE(set1.GetTagValue(TAG_USER_SECURE_ID, 1, &val)); EXPECT_EQ(4334U, val); // Find one that isn't there EXPECT_FALSE(set2.GetTagValue(TAG_USER_SECURE_ID, &val)); } TEST(GetValue, GetEnum) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); keymaster_algorithm_t val; EXPECT_TRUE(set.GetTagValue(TAG_ALGORITHM, &val)); EXPECT_EQ(KM_ALGORITHM_RSA, val); // Find one that isn't there keymaster_padding_t val2; EXPECT_FALSE(set.GetTagValue(TAG_PADDING, &val2)); } TEST(GetValue, GetEnumRep) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); keymaster_purpose_t val; EXPECT_TRUE(set.GetTagValue(TAG_PURPOSE, 0, &val)); EXPECT_EQ(KM_PURPOSE_SIGN, val); EXPECT_TRUE(set.GetTagValue(TAG_PURPOSE, 1, &val)); EXPECT_EQ(KM_PURPOSE_VERIFY, val); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_PURPOSE, 2, &val)); } TEST(GetValue, GetDate) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); uint64_t val; EXPECT_TRUE(set.GetTagValue(TAG_ACTIVE_DATETIME, &val)); EXPECT_EQ(10U, val); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_USAGE_EXPIRE_DATETIME, &val)); } TEST(GetValue, GetBlob) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); keymaster_blob_t val; EXPECT_TRUE(set.GetTagValue(TAG_APPLICATION_ID, &val)); EXPECT_EQ(6U, val.data_length); EXPECT_EQ(0, memcmp(val.data, "my_app", 6)); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_APPLICATION_DATA, &val)); } TEST(Deduplication, NoDuplicates) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); EXPECT_EQ(copy.size(), set.size()); // Sets no longer compare equal, because of ordering (ugh, maybe it should be // AuthorizationList, not AuthorizationSet). EXPECT_NE(copy, set); } TEST(Deduplication, NoDuplicatesHasInvalid) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_INVALID) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); // Deduplicate should have removed the invalid. EXPECT_EQ(copy.size() - 1, set.size()); EXPECT_NE(copy, set); } TEST(Deduplication, DuplicateEnum) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); EXPECT_EQ(copy.size() - 2, set.size()); EXPECT_NE(copy, set); } TEST(Deduplication, DuplicateBlob) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_APPLICATION_DATA, "data", 4) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_APPLICATION_DATA, "data", 4) .Authorization(TAG_APPLICATION_DATA, "foo", 3) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); EXPECT_EQ(copy.size() - 3, set.size()); EXPECT_NE(copy, set); // The real test here is that valgrind reports no leak. } } // namespace test } // namespace keymaster
41.681458
99
0.63393
Keneral
ddcb34f1d4f4a1b84dff19e87cc67b491ab0c5af
264
cc
C++
source/skyline/solution_unittest.cc
Yang-33/SpatialSkylineQueries-on-TIN
82b828ccc5fe1e772fbfa04627cf6a8d8d69aaa1
[ "MIT" ]
null
null
null
source/skyline/solution_unittest.cc
Yang-33/SpatialSkylineQueries-on-TIN
82b828ccc5fe1e772fbfa04627cf6a8d8d69aaa1
[ "MIT" ]
null
null
null
source/skyline/solution_unittest.cc
Yang-33/SpatialSkylineQueries-on-TIN
82b828ccc5fe1e772fbfa04627cf6a8d8d69aaa1
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <vector> // See main.cc TEST(SolutionTest, NaiveAndFast) { std::vector<int> a{1, 2, 3}; std::vector<int> b{1, 2, 3}; ASSERT_EQ(a.size(), b.size()); for (size_t i = 0; i < a.size(); ++i) { EXPECT_EQ(a[i], b[i]); } }
20.307692
41
0.568182
Yang-33
ddcca0f40ab90bb6e024256380939f74eaa3a966
2,393
cpp
C++
scisim/ConstrainedMaps/FrictionMaps/FrictionOperator.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
scisim/ConstrainedMaps/FrictionMaps/FrictionOperator.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
scisim/ConstrainedMaps/FrictionMaps/FrictionOperator.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
// FrictionOperator.cpp // // Breannan Smith // Last updated: 09/22/2015 #include "FrictionOperator.h" #include "scisim/Constraints/Constraint.h" FrictionOperator::~FrictionOperator() {} // TODO: Despecialize from smooth void FrictionOperator::formGeneralizedSmoothFrictionBasis( const unsigned ndofs, const unsigned ncons, const VectorXs& q, const std::vector<std::unique_ptr<Constraint>>& K, const MatrixXXsc& bases, SparseMatrixsc& D ) { assert( ncons == K.size() ); const unsigned nambientdims{ static_cast<unsigned>( bases.rows() ) }; const unsigned nsamples{ nambientdims - 1 }; D.resize( ndofs, nsamples * ncons ); auto itr = K.cbegin(); { VectorXi column_nonzeros( D.cols() ); for( unsigned collision_number = 0; collision_number < ncons; ++collision_number ) { for( unsigned sample_number = 0; sample_number < nsamples; ++sample_number ) { assert( nsamples * collision_number + sample_number < column_nonzeros.size() ); column_nonzeros( nsamples * collision_number + sample_number ) = (*itr)->frictionStencilSize(); } ++itr; } assert( ( column_nonzeros.array() > 0 ).all() ); assert( itr == K.cend() ); D.reserve( column_nonzeros ); } itr = K.cbegin(); for( unsigned collision_number = 0; collision_number < ncons; ++collision_number ) { for( unsigned sample_number = 0; sample_number < nsamples; ++sample_number ) { const unsigned current_column{ nsamples * collision_number + sample_number }; const VectorXs current_sample{ bases.col( nambientdims * collision_number + sample_number + 1 ) }; assert( fabs( current_sample.dot( bases.col( nambientdims * collision_number ) ) ) <= 1.0e-6 ); (*itr)->computeGeneralizedFrictionGivenTangentSample( q, current_sample, current_column, D ); } ++itr; } assert( itr == K.cend() ); D.prune( []( const Eigen::Index& row, const Eigen::Index& col, const scalar& value ) { return value != 0.0; } ); assert( D.innerNonZeroPtr() == nullptr ); } #include <iostream> void FrictionOperator::formGeneralizedFrictionBasis( const VectorXs& q, const VectorXs& v, const std::vector<std::unique_ptr<Constraint>>& K, SparseMatrixsc& D, VectorXs& drel ) { std::cerr << "Deprecated method FrictionOperator::formGeneralizedFrictionBasis not implemented for " << name() << std::endl; std::exit( EXIT_FAILURE ); }
36.815385
217
0.689929
Lyestria
ddce127677fce6623d4d0bced04fc24d66d7e2a1
242
hpp
C++
src/main/Input/Input.hpp
ramp-eu/AGILPLAS
b2ae7a234859d758dbc6c8a876329a4060c53bd1
[ "Apache-2.0" ]
null
null
null
src/main/Input/Input.hpp
ramp-eu/AGILPLAS
b2ae7a234859d758dbc6c8a876329a4060c53bd1
[ "Apache-2.0" ]
5
2021-05-28T15:17:38.000Z
2021-06-15T10:04:29.000Z
src/main/Input/Input.hpp
ramp-eu/AGILPLAS
b2ae7a234859d758dbc6c8a876329a4060c53bd1
[ "Apache-2.0" ]
1
2021-05-31T14:39:14.000Z
2021-05-31T14:39:14.000Z
#ifndef INPUT_H_INCLUDED #define INPUT_H_INCLUDED class Input { private: int reference; String alias; public: Input(int reference, String alias); int getReference(); String getAlias(); void serialPrint(); }; #endif
13.444444
39
0.690083
ramp-eu
ddd09e71ba385f83682379de1e163d780b5bbfbb
515
cpp
C++
solved/o-q/odd-sum/odd.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/o-q/odd-sum/odd.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/o-q/odd-sum/odd.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> int a, b; int sum(int lo, int hi) { if (lo < 1) lo = 1; if (lo > hi) return 0; if (lo == hi) return lo; return (hi*(hi+1) - (lo-1)*lo)/2; } int solve() { int x = a % 2 == 0 ? a / 2 : (a - 1) / 2; int y = b % 2 == 0 ? b / 2 - 1 : (b - 1) / 2; return sum(x, y)*2 + y - x + 1; } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { scanf("%d%d", &a, &b); printf("Case %d: %d\n", ++ncase, solve()); } return 0; }
15.147059
50
0.4
abuasifkhan
ddd1d520109b5d536a00417fab5cb54c369f7a74
4,524
cpp
C++
src/main/c++/TestAPI/testMemIO.cpp
yildiz-online/component-native-freeimage
cb329c74ebe0aa16d8349a213e1e4b95204fce58
[ "MIT" ]
null
null
null
src/main/c++/TestAPI/testMemIO.cpp
yildiz-online/component-native-freeimage
cb329c74ebe0aa16d8349a213e1e4b95204fce58
[ "MIT" ]
1
2018-11-19T19:12:58.000Z
2018-11-19T19:12:58.000Z
src/main/c++/TestAPI/testMemIO.cpp
yildiz-online/component-native-freeimage
cb329c74ebe0aa16d8349a213e1e4b95204fce58
[ "MIT" ]
null
null
null
// ========================================================== // FreeImage 3 Test Script // // Design and implementation by // - Herv� Drolon (drolon@infonie.fr) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "TestSuite.h" void testSaveMemIO(const char *lpszPathName) { FIMEMORY *hmem = NULL; // load a regular file FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName); FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, 0); // open a memory handle hmem = FreeImage_OpenMemory(); // save the file to memory FreeImage_SaveToMemory(fif, dib, hmem, 0); // at this point, hmem contains the entire FREE_IMAGE_FORMAT data in memory. // the amount of space used by the memory is equal to file_size FreeImage_SeekMemory(hmem, 0, SEEK_END); long file_size = FreeImage_TellMemory(hmem); printf("File size : %ld\n", file_size); // its easy load an image from memory as well // seek to the start of the memory stream FreeImage_SeekMemory(hmem, 0L, SEEK_SET); // get the file type FREE_IMAGE_FORMAT mem_fif = FreeImage_GetFileTypeFromMemory(hmem, 0); // load an image from the memory handle FIBITMAP *check = FreeImage_LoadFromMemory(mem_fif, hmem, 0); // save as a regular file FreeImage_Save(FIF_PNG, check, "dump.png", PNG_DEFAULT); // make sure to free the data since FreeImage_SaveToMemory // will cause it to be malloc'd FreeImage_CloseMemory(hmem); FreeImage_Unload(check); FreeImage_Unload(dib); } //you could also have image data in memory via some other method, and just set //fmh.data to point to it, and set both fmh.datalen and fmh.filelen to the //size of that data, then FreeImage_LoadFromMemory could load the image from that memory void testLoadMemIO(const char *lpszPathName) { struct stat buf; int result; // get data associated with lpszPathName result = stat(lpszPathName, &buf); if(result == 0) { // allocate a memory buffer and load temporary data BYTE *mem_buffer = (BYTE*)malloc(buf.st_size * sizeof(BYTE)); if(mem_buffer) { FILE *stream = fopen(lpszPathName, "rb"); if(stream) { fread(mem_buffer, sizeof(BYTE), buf.st_size, stream); fclose(stream); // attach the binary data to a memory stream FIMEMORY *hmem = FreeImage_OpenMemory(mem_buffer, buf.st_size); // get the file type FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0); // load an image from the memory stream FIBITMAP *check = FreeImage_LoadFromMemory(fif, hmem, PNG_DEFAULT); // save as a regular file FreeImage_Save(FIF_PNG, check, "blob.png", PNG_DEFAULT); FreeImage_Unload(check); // close the stream FreeImage_CloseMemory(hmem); } } // user is responsible for freeing the data free(mem_buffer); } } void testAcquireMemIO(const char *lpszPathName) { FIMEMORY *hmem = NULL; // load a regular file FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName); FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, 0); // open and allocate a memory stream hmem = FreeImage_OpenMemory(); // save the file to memory FreeImage_SaveToMemory(FIF_PNG, dib, hmem, PNG_DEFAULT); FreeImage_Unload(dib); // get the buffer from the memory stream BYTE *mem_buffer = NULL; DWORD size_in_bytes = 0; FreeImage_AcquireMemory(hmem, &mem_buffer, &size_in_bytes); // save the buffer in a file stream FILE *stream = fopen("buffer.png", "wb"); if(stream) { fwrite(mem_buffer, sizeof(BYTE), size_in_bytes, stream); fclose(stream); } // close and free the memory stream FreeImage_CloseMemory(hmem); } void testMemIO(const char *lpszPathName) { printf("testMemIO ...\n"); testSaveMemIO(lpszPathName); testLoadMemIO(lpszPathName); testAcquireMemIO(lpszPathName); }
30.362416
89
0.715075
yildiz-online
ddd40ffa25cb716b4e26db8746e71abad6f85a73
3,167
cpp
C++
sniper/pico/Response.cpp
rtbtech/libsniper
0828df9da74f8ed11a1273c61c15dfb5816c3c1e
[ "Apache-2.0" ]
9
2020-05-08T21:17:12.000Z
2021-06-04T18:38:35.000Z
sniper/pico/Response.cpp
rtbtech/libsniper
0828df9da74f8ed11a1273c61c15dfb5816c3c1e
[ "Apache-2.0" ]
null
null
null
sniper/pico/Response.cpp
rtbtech/libsniper
0828df9da74f8ed11a1273c61c15dfb5816c3c1e
[ "Apache-2.0" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com /* * Copyright (c) 2018 - 2019, MetaHash, Oleg Romanenko (oleg@romanenko.ro) * * 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 <sniper/pico/picohttpparser.h> #include <sniper/strings/ascii_case.h> #include <sniper/strings/atoi.h> #include "Response.h" namespace sniper::pico { void Response::clear() noexcept { status = -1; header_size = 0; content_length = 0; keep_alive = false; headers.clear(); } ParseResult Response::parse(char* data, size_t size) noexcept { if (!data || !size) return ParseResult::Err; if (size < 5) return ParseResult::Partial; struct phr_header pico_headers[MAX_HEADERS]; size_t num_headers = sizeof(pico_headers) / sizeof(headers[0]); int pico_minor_version = -1; const char* msg = nullptr; size_t msg_len = 0; int ssize = phr_parse_response(data, size, &pico_minor_version, &status, &msg, &msg_len, pico_headers, &num_headers, 0); if (ssize > 0) { header_size = ssize; if (pico_minor_version == 1) keep_alive = true; bool content_length_found = false; bool connection_found = false; for (unsigned i = 0; i < num_headers; i++) { strings::to_lower_ascii(const_cast<char*>(pico_headers[i].name), pico_headers[i].name_len); strings::to_lower_ascii(const_cast<char*>(pico_headers[i].value), pico_headers[i].value_len); string_view key(pico_headers[i].name, pico_headers[i].name_len); string_view val(pico_headers[i].value, pico_headers[i].value_len); // content-length if (!content_length_found && key == "content-length") { content_length_found = true; if (auto len = strings::fast_atoi64(val); len) content_length = *len; else return ParseResult::Err; } // connection if (!connection_found && key == "connection") { connection_found = true; if (pico_minor_version == 0 && val == "keep-alive") keep_alive = true; else if (val == "close") keep_alive = false; } headers.emplace_back(key, val); } return ParseResult::Complete; } else if (ssize == -2) { return ParseResult::Partial; } else { return ParseResult::Err; } } } // namespace sniper::pico
30.747573
116
0.616672
rtbtech
ddd4d5ab025307843be0b62229c0d85036cf370d
582
cpp
C++
Notes_Week2/multipleInput.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
1
2019-01-06T22:36:01.000Z
2019-01-06T22:36:01.000Z
Notes_Week2/multipleInput.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
Notes_Week2/multipleInput.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
/********************************************************************* ** Author: Wei-Chien Hsu ** Date: 04/09/18 ** Description: Asks the user enters width and height, and output the Area. *********************************************************************/ #include <iostream> using namespace std; int main() { float width, height; int area; cout << "Please enters the width and height (in float): " << endl; cin >> width >> height; area = static_cast<int>(width * height); cout << "The area is : " << area << endl; return 0; }
27.714286
70
0.450172
WeiChienHsu
dddafcbbe3971a518cafdb18249ca33a8ffe9536
1,668
cc
C++
src/sockio.cc
SanczoPL/QtServer
c8350e920cadc215ad306592460cc16031eefff9
[ "MIT" ]
null
null
null
src/sockio.cc
SanczoPL/QtServer
c8350e920cadc215ad306592460cc16031eefff9
[ "MIT" ]
null
null
null
src/sockio.cc
SanczoPL/QtServer
c8350e920cadc215ad306592460cc16031eefff9
[ "MIT" ]
null
null
null
#include "../include/sockio.h" SockIO::SockIO(QTcpSocket* a_socket, QObject* parent) : QObject(parent) , m_socket{ a_socket } { connect(m_socket, &QTcpSocket::readyRead, this, &SockIO::onReadyRead); } bool SockIO::hasMessages() { return !m_messageQueue.isEmpty(); } Message SockIO::nextMessage() { if (!hasMessages()) qFatal("No mesages in queue!"); Message const MESSAGE{ m_messageQueue[0] }; m_messageQueue.pop_front(); return MESSAGE; } bool SockIO::sendMessage(Message const& a_message) { Logger->trace("SockIO::sendMessage()"); if (m_socket->write(a_message.rawData()) < 0) { Logger->warn("Failed to send message to host", m_socket->peerAddress().toString().toStdString()); return false; } return true; } void SockIO::onReadyRead() { m_bufer += m_socket->readAll(); Logger->trace("Recived data from ip:{}, bufSize:{}", m_socket->peerAddress().toString().toStdString(), m_bufer.size()); Logger->trace("while({} >= {})", m_bufer.size() ,static_cast<int>(sizeof(Message::Header)) ); while (m_bufer.size() >= static_cast<int>(sizeof(Message::Header))) { Logger->trace("checkPrefix:{}", Message::checkPrefix(m_bufer)); if (Message::checkPrefix(m_bufer)) { auto messageSize = Message::validate(m_bufer); Logger->trace("validate:{}", messageSize); if (messageSize > 0) { m_messageQueue.push_back(Message{ m_bufer }); m_bufer.remove(0, messageSize); Logger->trace("emit new message:"); emit(newMessage()); } else { Logger->trace("messageSize = 0"); break; } } else { Logger->warn("Buffer out of order {}", m_socket->peerAddress().toString().toStdString()); m_bufer.remove(0, 1); } } }
26.903226
120
0.676259
SanczoPL
50af57283f0874a8f209829a0822eb507912716d
536
hpp
C++
YYSloth/include/drivers/pic/pic8259.hpp
notYuriy/yayaos
4df7b015cb6e572797dd40a5d2891cf24abcb4d1
[ "MIT" ]
12
2020-04-13T12:38:54.000Z
2021-08-31T07:03:14.000Z
YYSloth/include/drivers/pic/pic8259.hpp
YayOrg/YayOS
4df7b015cb6e572797dd40a5d2891cf24abcb4d1
[ "MIT" ]
null
null
null
YYSloth/include/drivers/pic/pic8259.hpp
YayOrg/YayOS
4df7b015cb6e572797dd40a5d2891cf24abcb4d1
[ "MIT" ]
1
2020-07-18T12:11:37.000Z
2020-07-18T12:11:37.000Z
#ifndef __PIC_8259_HPP_INCLUDED__ #define __PIC_8259_HPP_INCLUDED__ #include <drivers/pic/pic.hpp> #include <utils.hpp> namespace drivers { class PIC8259 : public IPIC { uint8_t m_picMasterMask; uint8_t m_picSlaveMask; public: void init(); bool registerLegacyIrq(uint8_t irq, x86_64::IDTVector vec); virtual bool enableLegacyIrq(uint8_t irq); virtual bool disableLegacyIrq(uint8_t irq); virtual bool endOfLegacyIrq(uint8_t irq); }; }; // namespace drivers #endif
23.304348
67
0.695896
notYuriy
50af8f89a9594ef35a72183c8ffc3c849c577598
6,043
hpp
C++
src/accelerator/Component.hpp
chrpilat/mnemosyne
bde60abf5e2be614dadf599e9e7b6a44afa83907
[ "BSD-2-Clause" ]
6
2017-03-02T16:02:00.000Z
2022-02-15T13:25:50.000Z
src/accelerator/Component.hpp
chrpilat/mnemosyne
bde60abf5e2be614dadf599e9e7b6a44afa83907
[ "BSD-2-Clause" ]
null
null
null
src/accelerator/Component.hpp
chrpilat/mnemosyne
bde60abf5e2be614dadf599e9e7b6a44afa83907
[ "BSD-2-Clause" ]
2
2019-04-25T15:53:20.000Z
2020-02-10T02:45:32.000Z
/** * @copyright * Copyright (c) 2017 - SLD Group @ Columbia University. All Rights Reserved. * * This file is part of Mnemosyne. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file Component.hpp * @author Christian Pilato <pilato.christian@gmail.com> * * @brief Class to describe a component with memory access * */ #ifndef _COMPONENT_HPP_ #define _COMPONENT_HPP_ #include "utils.hpp" FORWARD_DECL(Array); FORWARD_DECL(ArrayList); FORWARD_DECL(ComponentList); FORWARD_DECL(MemoryWrapper); #include "UGraph.hpp" /** * @brief Component Declaration */ struct Component { //! Identifier of the component. const std::string name; std::string clock_name; std::string reset_name; std::string conf_done_name; std::string acc_done_name; std::set<std::string> dmain_prefix; std::set<std::string> dmaout_prefix; std::set<std::string> rdreq_prefix; std::set<std::string> wrreq_prefix; std::set<std::string> read_interfaces; std::set<std::string> write_interfaces; std::map<std::string, std::string> darkmem_to_buffer; std::map<std::string, std::set<std::string> > buffer_to_darkmem; /** * @brief Constructor */ Component(const std::string& name); /** * @brief Print method * @param os is the output stream */ void print(std::ostream& os) const; /** * @brief Overloaded operator to support print * @param os is the output stream * @param b is the component to be printed * @return is the returned stream */ friend std::ostream& operator<<(std::ostream& os, const Component& b) { b.print(os); return os; } void parse_interface(const YAML::Node& interface, const std::map<std::string, MemoryWrapperPtr> &buffer_to_wrapper); std::string get_rdreq_prefix() const; std::string get_wrreq_prefix() const; std::string get_dmain_prefix() const; std::string get_dmaout_prefix() const; }; ///refcount definition typedef boost::shared_ptr<Component> ComponentPtr; struct ComponentList { ///verbosity level of the class unsigned int verbosity; ///name of the top component std::string top_name; ///archive of components std::map<std::string, ComponentPtr> list; ///list of buffers to be stored ArrayListPtr buffers; typedef std::tuple<UGraphPtr, UNode> node_t; std::map<std::string, ArrayPtr> id_to_buffer; std::map<std::string, node_t> id_to_node; std::map<UGraphPtr, std::map<UNode, ArrayPtr> > node_to_buffer; std::map<UGraphPtr, std::string> graph_to_acc_name; std::vector<node_t> node_list; std::map<node_t, std::set<node_t> > comp_list; /** * @brief Component * @param verbosity is the verbosity level of the class */ ComponentList(unsigned int verbosity); /** * @brief Create single array * @param name is the id of the array * @param width is the bitwidth * @param height is the number of words * @param interfaces is the list of interfaces * @param init_file is the name of the initialization file (if any) */ void create_array(const std::string& name, const unsigned int width, unsigned int height, const std::string& interfaces, const std::string& init_file); /** * @brief Parse the multi-component definitions * @param name is the name of the top component * @param multiacc_config is the path to the file to be parsed */ bool parse_config(const std::string& name, const std::string& multiacc_config); /** * @brief Parse a single component definition * @param name is the name of the component * @param acc_config is the path to the configuration file to be parsed * @param input_cgraph is the path to the compatibility graph file to be parsed */ bool parse_config(const std::string& name, const std::string& acc_config, const std::string& input_cgraph, const std::string& scenario_config); /** * @brief Prepare buffer data structures for the given accelerator * @param name is the name of the accelerator */ void bufferLoad(const std::string& name); /** * @brief Parse the file describing the compatibilities * @param name is the name of the current component to be analyzed * @param input_cgraph is the file describing the compatibilities */ void parse_accelerator_config(const std::string& name, const std::string& input_cgraph); /** * @brief Get a string-based representation of the given clique * @param clique is the set of nodes composing the clique * @return the string representing the clique */ std::string get_clique_string(const std::set<node_t>& clique); }; ///refcount definition typedef boost::shared_ptr<ComponentList> ComponentListPtr; #endif
33.949438
154
0.707761
chrpilat
50b20c1135034b5cd83271592d6a03f873ae1c5f
1,326
cc
C++
modules/planning/tasks/traffic_decider/front_vehicle.cc
delding/apollo
22d67d6c2e28550105e04defdf61ce82f2f7e50f
[ "Apache-2.0" ]
null
null
null
modules/planning/tasks/traffic_decider/front_vehicle.cc
delding/apollo
22d67d6c2e28550105e04defdf61ce82f2f7e50f
[ "Apache-2.0" ]
null
null
null
modules/planning/tasks/traffic_decider/front_vehicle.cc
delding/apollo
22d67d6c2e28550105e04defdf61ce82f2f7e50f
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/traffic_decider/front_vehicle.h" #include <string> #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::util::WithinBound; using apollo::hdmap::PathOverlap; CIPV::CIPV(const TrafficRuleConfig& config) : TrafficRule(config) {} bool CIPV::ApplyRule(Frame* frame, ReferenceLineInfo* reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); return true; } } // namespace planning } // namespace apollo
30.136364
79
0.662142
delding
50b3329138cbe81855eaf86cf22bec99ae8d8dcc
935
hpp
C++
libs/libSocketHandler/src/SocketHandler.hpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
libs/libSocketHandler/src/SocketHandler.hpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
libs/libSocketHandler/src/SocketHandler.hpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
#pragma once #include <fstream> #include <memory> #include <chrono> #include <random> #include <vector> #include <thread> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> class Server { public: Server(int port); ~Server(); bool send(std::string& data); bool receive(std::string& data); private: void initServer(); void creatServerTcp(int port); bool m_initDone; int m_port; std::thread* threadInit; boost::asio::io_service m_ioService; boost::asio::ip::tcp::socket* m_socketTcp; boost::system::error_code m_error; }; class Client { public: Client(std::string& ip, int port); ~Client(); bool send(std::string& data); bool receive(std::string& data); private: void creatClientTcp(int port, std::string& ip); std::string m_ipServer; int m_port; boost::asio::io_service m_ioService; boost::asio::ip::tcp::socket* m_socketTcp; boost::system::error_code m_error; };
15.327869
48
0.708021
maxDcb
50b528ab4d6ecd9b379fd23b296cae56f26bb391
2,047
cc
C++
src/image/b3TxSaveInfo.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/image/b3TxSaveInfo.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/image/b3TxSaveInfo.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: b3TxSaveInfo.cc $ ** $Release: Dortmund 2001, 2016 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - File format encoder ** ** (C) Copyright 2001 - 2021 Steffen A. Mork ** All Rights Reserved ** ** */ /************************************************************************* ** ** ** Blizzard III includes ** ** ** *************************************************************************/ #include "blz3/image/b3Tx.h" #include "b3TxSaveInfo.h" /************************************************************************* ** ** ** PNG ** ** ** *************************************************************************/ b3TxSaveInfo::b3TxSaveInfo(b3Tx * tx, const char * filename, const char * write_mode) { m_Tx = tx; m_Tx->b3Name(filename); bzero(m_SaveBuffer, sizeof(m_SaveBuffer)); m_ThisRow = b3TypedAlloc<b3_pkd_color>(tx->xSize); if (m_ThisRow == nullptr) { b3PrintF(B3LOG_NORMAL, "Save Image: not enough memory!\n"); B3_THROW(b3TxException, B3_TX_MEMORY); } if (write_mode == nullptr) { m_FileHandle = nullptr; if (!m_File.b3Open(filename, B_WRITE)) { b3Free(); b3PrintF(B3LOG_NORMAL, "Save Image: file \"%s\" not created!\n", filename); B3_THROW(b3TxException, B3_TX_NOT_SAVED); } } else { m_FileHandle = fopen(filename, write_mode); if (m_FileHandle == nullptr) { b3Free(); b3PrintF(B3LOG_NORMAL, "Save Image: file \"%s\" not created!\n", filename); B3_THROW(b3TxException, B3_TX_NOT_SAVED); } } } b3TxSaveInfo::~b3TxSaveInfo() { if (m_FileHandle != nullptr) { fclose(m_FileHandle); } else { m_File.b3Close(); } }
25.5875
85
0.429897
stmork
50b69ba7a31c994d4e138ca87f9a08b483c9e6de
2,811
hpp
C++
include/codegen/include/Oculus/Platform/RoomType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Oculus/Platform/RoomType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Oculus/Platform/RoomType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:08 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.Enum #include "System/Enum.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: Oculus.Platform namespace Oculus::Platform { // Autogenerated type: Oculus.Platform.RoomType struct RoomType : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public Oculus.Platform.RoomType Unknown static constexpr const int Unknown = 0; // Get static field: static public Oculus.Platform.RoomType Unknown static Oculus::Platform::RoomType _get_Unknown(); // Set static field: static public Oculus.Platform.RoomType Unknown static void _set_Unknown(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Matchmaking static constexpr const int Matchmaking = 1; // Get static field: static public Oculus.Platform.RoomType Matchmaking static Oculus::Platform::RoomType _get_Matchmaking(); // Set static field: static public Oculus.Platform.RoomType Matchmaking static void _set_Matchmaking(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Moderated static constexpr const int Moderated = 2; // Get static field: static public Oculus.Platform.RoomType Moderated static Oculus::Platform::RoomType _get_Moderated(); // Set static field: static public Oculus.Platform.RoomType Moderated static void _set_Moderated(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Private static constexpr const int Private = 3; // Get static field: static public Oculus.Platform.RoomType Private static Oculus::Platform::RoomType _get_Private(); // Set static field: static public Oculus.Platform.RoomType Private static void _set_Private(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Solo static constexpr const int Solo = 4; // Get static field: static public Oculus.Platform.RoomType Solo static Oculus::Platform::RoomType _get_Solo(); // Set static field: static public Oculus.Platform.RoomType Solo static void _set_Solo(Oculus::Platform::RoomType value); // Creating value type constructor for type: RoomType RoomType(int value_ = {}) : value{value_} {} }; // Oculus.Platform.RoomType } DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::RoomType, "Oculus.Platform", "RoomType"); #pragma pack(pop)
49.315789
83
0.728211
Futuremappermydud
50bb67be19b9e4f3024490551da250d377d80309
1,743
cpp
C++
UVa 11496 musical loop/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 11496 musical loop/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 11496 musical loop/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <iostream> #include <vector> using namespace std; int main(void) { int n, first, last, current, sz; bool increasing; while (cin >> n) { if (n == 0) break; increasing = true; vector<int> points; for (int i = 0; i < n; i++) { cin >> current; if (i == 0) first = current; if (i == n - 1) last = current; if (points.size() < 2) { points.push_back(current); continue; } sz = points.size(); increasing = (points[sz - 1] > points[sz - 2]); if (current > points[sz - 1] && increasing) points[sz - 1] = current; else if (current < points[sz - 1] && !increasing) points[sz - 1] = current; else if (current > points[sz - 1]) { increasing = true; points.push_back(current); } else if (current < points[sz - 1]) { increasing = false; points.push_back(current); } } sz = points.size(); int result = sz; bool last_growing = (points[sz - 2] < points[sz - 1]); bool first_growing = (points[1] > points[0]); if (last_growing && points[0] > points[sz - 1]) result--; else if (first_growing && points[0] > points[sz - 1]) result--; else if (!last_growing && points[0] < points[sz - 1]) result--; else if (!first_growing && points[0] < points[sz - 1]) result--; cout << result << endl; } return 0; }
30.051724
62
0.430866
tadvi
50be740fd5091b26478e43a76633c15e31d3e26c
1,586
cpp
C++
2017/February/Silver/Why Did the Cow Cross the Road III.cpp
Sumitkk10/USACO-submissions
543dafe041356e83a18e7a57e5d93d24bc266682
[ "MIT" ]
2
2020-12-09T05:43:19.000Z
2020-12-09T06:24:45.000Z
2017/February/Silver/Why Did the Cow Cross the Road III.cpp
Sumitkk10/USACO-submissions
543dafe041356e83a18e7a57e5d93d24bc266682
[ "MIT" ]
null
null
null
2017/February/Silver/Why Did the Cow Cross the Road III.cpp
Sumitkk10/USACO-submissions
543dafe041356e83a18e7a57e5d93d24bc266682
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) using namespace std; const int N = 100 + 5; const int MOD = 1e9 + 7; int n, k, m, sol; set<pair<int, pair<int, pair<int, int> > > > s; bool ok, vis[N][N]; map<pair<int, int>, int> mp; void check(int i, int j){ if(i <= 0 or j <= 0 or i > n or j > n or vis[i][j]) return; sol += mp[{i,j}]; vis[i][j] = true; if(s.find({i, {j, {i + 1, j}}}) == s.end()) check(i + 1, j); if(s.find({i, {j, {i - 1, j}}}) == s.end()) check(i - 1, j); if(s.find({i, {j, {i, j + 1}}}) == s.end()) check(i, j + 1); if(s.find({i, {j, {i, j - 1}}}) == s.end()) check(i, j - 1); } int main() { fast; freopen("countcross.in", "r", stdin); freopen("countcross.out", "w", stdout); cin >> n >> k >> m; for(int i = 0; i < m; ++i){ int a, b, x, y; cin >> a >> b >> x >> y; s.insert({a, {b, {x, y}}}); s.insert({x, {y, {a, b}}}); } vector<pair<int, int> > cows; for(int i = 0; i < k; ++i) { int u, v; cin >> u >> v; mp[{u, v}]++; } long long ans1 = 0; vector<int> ans; for(int i = 1; i <= n; ++i){ for(int j = 1; j <= n; ++j){ if(!vis[i][j]){ check(i, j); ans.push_back(sol); sol = 0; } } } for(int i = 0; i < ans.size(); ++i) for(int j = i + 1; j < ans.size(); ++j) ans1 += (ans[i] * ans[j]); cout << ans1 << '\n'; return 0; }
26.433333
70
0.406053
Sumitkk10
50c0dcfccd74614378c4bf6189216683d5a33079
551
cpp
C++
acmicpc/14789.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/14789.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/14789.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> using namespace std; int t, k; string s; int main() { cin >> t; for (int T=1; T<=t; ++T) { cin >> s >> k; int cnt = 0; int n = s.length(); for (int i=0; i<=n-k; ++i) { if (s[i] == '-') { cnt++; for (int j=i; j<i+k; ++j) s[j] = s[j] == '+' ? '-' : '+'; } } bool flag = true; for (int i=0; i<n; ++i) { if (s[i] == '-') { flag = false; break; } } if (flag) cout << "Case #" << T << ": " << cnt << '\n'; else cout << "Case #" << T << ": IMPOSSIBLE\n"; } return 0; }
14.128205
48
0.3902
juseongkr
50c316fdf459561e0def613aad0f9139b8a64c68
71,364
cpp
C++
PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp
rbnbr/S4
61534933e305e76d00cbefb75fc5c713c5b90c74
[ "MIT" ]
1
2021-09-27T11:29:48.000Z
2021-09-27T11:29:48.000Z
PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp
rbnbr/S4
61534933e305e76d00cbefb75fc5c713c5b90c74
[ "MIT" ]
null
null
null
PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp
rbnbr/S4
61534933e305e76d00cbefb75fc5c713c5b90c74
[ "MIT" ]
1
2022-02-10T16:07:27.000Z
2022-02-10T16:07:27.000Z
#pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <vector> #include <numeric> #include <cmath> #include <cstring> #include <algorithm> #include <functional> #include <random> #include <thread> #include <atomic> #include <chrono> #include <ctime> #include <iostream> #include "macros.h" #include "BufferedNdArray.hpp" #include "PythonExtrasCLib.h" template<typename T> void resize_array_point(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { T* pInput = static_cast<T*>(pInputRaw); T* pOutput = static_cast<T*>(pOutputRaw); for (int x = 0; x < targetWidth; x++) { double tX = targetWidth > 1 ? static_cast<double>(x) / (targetWidth - 1) : 0; int sourceX = lround(tX * (sourceWidth - 1)); for (int y = 0; y < targetHeight; y++) { double tY = targetHeight > 1 ? static_cast<double>(y) / (targetHeight - 1) : 0; int sourceY = lround(tY * (sourceHeight - 1)); for (int z = 0; z < targetDepth; z++) { double tZ = targetDepth > 1 ? static_cast<double>(z) / (targetDepth - 1) : 0; int sourceZ = lround(tZ * (sourceDepth - 1)); size_t sourceIndexFlat = sourceX * sourceHeight * sourceDepth + sourceY * sourceDepth + sourceZ; pOutput[x * targetHeight * targetDepth + y * targetDepth + z] = pInput[sourceIndexFlat]; } } } } /// /// Compute the number of patches along each *patched* dimension. /// Old function kept for compatibility. New ones don't use 'source axes' and patch all the dimensions. /// std::vector<size_t> compute_patch_number_generic(const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, const std::vector<size_t>& patchInnerStride, size_t predictionDelay) { std::vector<size_t> patchNumber(sourceAxes.size()); for (size_t i = 0; i < sourceAxes.size(); i++) { size_t dim = sourceAxes[i]; size_t stride = patchStride[i]; // How many voxels a patch covers. // Last point in time (Y-value) is 'predictionDelay' frames away from the previous frame. // E.g. if 'lastFrameGap' is 1, it immediately follows it. size_t patchSupport = i > 0 ? (patchSize[i] - 1) * patchInnerStride[i] + 1 : (patchSize[i] - 2) * patchInnerStride[i] + 1 + predictionDelay; size_t totalPatchNumber = dataSize[dim] - patchSupport + 1; patchNumber[i] = (totalPatchNumber + stride - 1) / stride; // Round up. } return patchNumber; } //todo this code (and functions called by it) has too many vector allocations. look at '4d_fast' methods for optimization. // The problem mostly is that the std vector doesn't have a small size optimization, // and always allocates stuff on the heap. template<typename T> void extract_patches_batched(void* pDataVoid, void* pOutputVoid, size_t* pOutputCenters, size_t ndim, const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, size_t firstPatchIndex, size_t patchesPerBatch, bool isBatchSizedBuffer = false) { T* pData = static_cast<T*>(pDataVoid); T* pOutput = static_cast<T*>(pOutputVoid); auto multiplies = std::multiplies<size_t>(); // Cache the functor, don't recreate it in a loop. // Number of patched dimensions. size_t nPatchDim = sourceAxes.size(); std::vector<size_t> patchInnerStride(nPatchDim, size_t{1}); // Number of patches along the patched dimensions. std::vector<size_t> patchNumber = compute_patch_number_generic(dataSize, sourceAxes, patchSize, patchStride, patchInnerStride, 1ULL); // Compute the (data)size of each patch. // (Depends on the spatial extent a.k.a. 'patch size' of each patch, and on the size of the orig. data. std::vector<size_t> patchDataSize(ndim, 0); for (size_t dim = 0; dim < ndim; dim++) { auto itSourceDim = std::find(sourceAxes.begin(), sourceAxes.end(), dim); if (itSourceDim != sourceAxes.end()) { // If the dimension is patched, use the patch size. size_t patchDim = itSourceDim - sourceAxes.begin(); patchDataSize[dim] = patchSize[patchDim]; } else { // Otherwise, take all data along that dimension. patchDataSize[dim] = dataSize[dim]; } } // Total number of elements in a patch. size_t patchDataSizeFlat = std::accumulate(patchDataSize.begin(), patchDataSize.end(), size_t{1}, multiplies); std::vector<size_t> patchCenterShift(nPatchDim); for (size_t patchDim = 0; patchDim < nPatchDim; patchDim++) patchCenterShift[patchDim] = patchSize[patchDim] / 2; // For efficiency, we don't copy data element-by-element, but copy // continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension of the orig. data. std::vector<size_t> patchDataColumnNumber = std::vector<size_t>(patchDataSize.begin(), patchDataSize.end() - 1); size_t patchDataColumnNumberFlat = std::accumulate(patchDataColumnNumber.begin(), patchDataColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchDataSize[ndim - 1]; // This function supports batching, i.e. we only extract 'patchesPerBatch' patches // starting with 'firstPatchIndex' patch. // Loop over all patches in a batch. // Since the number of dimensions is dynamic, we loop over a flat index // and then unflatten it. for (size_t indexFlat = firstPatchIndex; indexFlat < firstPatchIndex + patchesPerBatch; indexFlat++) { std::vector<size_t> patchIndexNd = unflattenIndex(indexFlat, patchNumber); // Figure out where in the orig. data the patch begins. // For patched dimensions, this is index * stride. // For the rest it's zero, since the whole dim. is copied. std::vector<size_t> dataSelectorStart(ndim, 0); std::vector<size_t> patchCenter(nPatchDim); for (size_t dim = 0; dim < ndim; dim++) { auto itSourceDim = std::find(sourceAxes.begin(), sourceAxes.end(), dim); if (itSourceDim != sourceAxes.end()) { size_t patchDim = itSourceDim - sourceAxes.begin(); dataSelectorStart[dim] = patchIndexNd[patchDim] * patchStride[patchDim]; // Keep the location of the patch's center, which needs to be returned to the caller. patchCenter[patchDim] = dataSelectorStart[dim] + patchCenterShift[patchDim]; } } // Where in the output array should we write. // All the patches are stacked one after another. size_t outputOffset = indexFlat * patchDataSizeFlat; size_t centerOutputOffset = indexFlat * nPatchDim; // If the output buffer is batch-sized. Adjust the offset to the batch. if (isBatchSizedBuffer) { outputOffset = (indexFlat - firstPatchIndex) * patchDataSizeFlat; centerOutputOffset = (indexFlat - firstPatchIndex) * nPatchDim; } for (size_t columnIndexFlat = 0; columnIndexFlat < patchDataColumnNumberFlat; columnIndexFlat++) { std::vector<size_t> columnIndexNd = unflattenIndex(columnIndexFlat, patchDataColumnNumber); // Where the column starts in the original data . std::vector<size_t> sourceIndexNd(ndim); for (size_t dim = 0; dim < ndim; dim++) sourceIndexNd[dim] = dataSelectorStart[dim] + columnIndexNd[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd[ndim - 1] = dataSelectorStart[ndim - 1]; size_t sourceIndexFlat = flattenIndex(sourceIndexNd, dataSize); // Copy a whole column. std::copy(&pData[sourceIndexFlat], &pData[sourceIndexFlat + columnSize], pOutput + outputOffset + columnIndexFlat * columnSize); } // Copy the patch center. std::copy(patchCenter.begin(), patchCenter.end(), pOutputCenters + centerOutputOffset); } } template<typename T> void extract_patches(void* pDataVoid, void* pOutputVoid, size_t* pOutputCenters, size_t ndim, const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride) { auto multiplies = std::multiplies<size_t>(); // Cache the functor, don't recreate it in a loop. // Number of patches along the patched dimensions. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, sourceAxes, patchSize, patchStride, 1ULL); // Total flat number of patches that will be returned. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); extract_patches_batched<T>(pDataVoid, pOutputVoid, pOutputCenters, ndim, dataSize, sourceAxes, patchSize, patchStride, 0, patchNumberFlat); } /** * \brief * * Extract patches/windows from a 4-dimensional array. * Each patch gets split into training data: X and Y. * X holds the whole hypercube, except for the last frame. Y holds a single scalar * from the center of the last frame. (Time is the first dimension, C-order is assumed.) * 'Empty' patches are those, where all values in X and the Y value are equal to the 'empty value'. * Empty patches do not get extracted. * Extraction is performed in batches, returning control after 'batchSize' patches were extracted. * */ template<typename T> void extract_patched_training_data_without_empty_4d( T* pData, size_t dataStartFlat, size_t dataEndFlat, const std::vector<size_t>& dataSize, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, const std::vector<size_t>& patchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, T emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, T* pOutX, T* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { // Cache the functor, don't recreate it in a loop. auto multiplies = std::multiplies<size_t>(); // Prepare the random distribution for undersampling. std::random_device r; std::default_random_engine randomEngine(r()); std::uniform_real_distribution<float_t> randomDist(0.0f, 1.0f); const size_t ndim = 4; if (dataSize.size() != ndim || patchSize.size() != ndim || patchStride.size() != ndim) throw std::runtime_error("Invalid number of dimensions. Expected four."); if (patchInnerStride[3] != 1) { printf("Inner stride is probably broken, since we copy patch by columns. \n"); throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n"); } // Number of patches along each dimension. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); // For efficiency, we don't copy data element-by-element, but copy // continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension. std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1); size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(), patchXColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchSize[ndim - 1]; // This function supports batching, i.e. we only extract 'batchSize' patches // starting with 'batchStartIndex' patch. // Loop over all patches in a batch. Skip 'empty' patches. // We loop over a flat index and then unflatten it. We could write 'ndim' nested loops, // but this way is a little less verbose and more flexible. // Optimization: prepare allocate all vectors that we'll need, instead doing it in the loop. Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber); IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber); Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize); Index4d dataIndexNd{}; Index4d patchIndexNd{}; IndexNd<3> columnIndexNd{}; Index4d sourceIndexNd{}; Index4d sourceIndexNdY{}; bool pInputEndReached = false; size_t patchesExtracted = 0; size_t indexFlat = batchStartIndex; while (patchesExtracted < batchSize && indexFlat < patchNumberFlat) { // Skip some of the patches according to the provided probability. float_t random = randomDist(randomEngine); bool dontUndersample = undersamplingProb > 0.999; // Floating-point comparison. if (dontUndersample || random < undersamplingProb) { unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd); // Figure out where in the orig. data the patch begins. for (size_t dim = 0; dim < ndim; dim++) dataIndexNd.X[dim] = patchIndexNd.X[dim] * patchStride[dim]; // Where in the output array should we write. // All the patches are stacked one after another. size_t outputOffsetX = patchesExtracted * patchSizeXFlat; size_t outputOffsetY = patchesExtracted; size_t outputOffsetIndices = patchesExtracted * ndim; bool xIsEmpty = skipEmptyPatches; // Init to false, if not skipping empty patches. for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++) { unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd); // Where the column starts in the original data . for (size_t dim = 0; dim < ndim - 1; dim++) sourceIndexNd.X[dim] = dataIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd.X[ndim - 1] = dataIndexNd.X[ndim - 1]; size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS); size_t sourceIndexRel = sourceIndexFlat - dataStartFlat; // The input data is buffered, i.e. we only have a chunk of it. // Check if the buffer has the data we need. if (sourceIndexFlat + columnSize >= dataEndFlat) { pInputEndReached = true; break; } // Check if the column is empty. auto first = &pData[sourceIndexRel]; auto last = &pData[sourceIndexRel + columnSize]; bool allValuesEqual = skipEmptyPatches && std::adjacent_find(first, last, std::not_equal_to<T>()) == last; xIsEmpty = xIsEmpty && *first == emptyValue && allValuesEqual; // Copy the whole column, even if it's empty. We don't know if the whole patch is empty or not. std::copy(first, last, pOutX + outputOffsetX + columnIndexFlat * columnSize); } // Extract Y. // Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead. sourceIndexNdY.X[0] = dataIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap; for (size_t dim = 1; dim < ndim; dim++) { // Take the value in the middle of the patch. sourceIndexNdY.X[dim] = dataIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim]; } size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS); size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat; // Check if the buffer has the data we need. if (pInputEndReached || sourceIndexYFlat >= dataEndFlat) { pInputEndReached = true; break; } T y = pData[sourceIndexYRel]; bool yIsEmpty = y == emptyValue; if (!xIsEmpty || !yIsEmpty) { // Copy the results. *(pOutY + outputOffsetY) = y; std::copy(&dataIndexNd.X[0], &dataIndexNd.X[4], pOutIndices + outputOffsetIndices); // Advance the output offset. patchesExtracted += 1; } } indexFlat += 1; } // Return the information about the extracted batch. *pOutPatchesExtracted = patchesExtracted; *pOutNextBatchIndex = indexFlat; *pOutInputEndReached = pInputEndReached; } /// /// A multithreaded version of the same method. Uses an atomic counter to synchronize output to the buffer. /// template<typename T> void extract_patched_training_data_without_empty_4d_multi( T* pData, size_t dataStartFlat, size_t dataEndFlat, const std::vector<size_t>& dataSize, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, const std::vector<size_t>& patchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, T emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, std::atomic<size_t>& globalBufferOffset, T* pOutX, T* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutPatchesEmpty, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { // Cache the functor, don't recreate it in a loop. auto multiplies = std::multiplies<size_t>(); // Prepare the random distribution for undersampling. std::random_device r; std::default_random_engine randomEngine(r()); std::uniform_real_distribution<float_t> randomDist(0.0f, 1.0f); const size_t ndim = 4; if (dataSize.size() != ndim || patchSize.size() != ndim || patchStride.size() != ndim) throw std::runtime_error("Invalid number of dimensions. Expected four."); if (patchInnerStride[3] != 1) { printf("Inner stride is probably broken, since we copy patch by columns. \n"); throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n"); } // Number of patches along each dimension. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); // For efficiency, we don't copy data element-by-element, but copy continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension. std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1); size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(), patchXColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchSize[ndim - 1]; // Consistency check: A thread should be allocated at least some work. if (batchStartIndex >= patchNumberFlat) { printf("Thread's start index is larger than the total number of patches.\n"); throw std::runtime_error("Thread's start index is larger than the total number of patches."); } // This function supports batching, i.e. we only extract 'batchSize' patches // starting with 'batchStartIndex' patch. // Loop over all patches in a batch. Skip 'empty' patches. // We loop over a flat index and then unflatten it. We could write 'ndim' nested loops, // but this way is a little less verbose and more flexible. // Optimization: allocate all the vectors that we'll need, instead of doing it in the loop. Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber); IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber); Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize); Index4d dataIndexNd{}; Index4d patchIndexNd{}; IndexNd<3> columnIndexNd{}; Index4d sourceIndexNd{}; Index4d sourceIndexNdY{}; // Allocate memory for storing a single patch that is being processed. // When it's assembled, it will be copied to the global buffer. // If we don't have an intermediate buffer, another thread can write over our results. std::vector<T> patchDataX(patchSizeXFlat); bool inputEndReached = false; size_t patchesExtracted = 0; size_t patchesEmpty = 0; size_t indexFlat = batchStartIndex; // Batch counts input patches, not the output (like in single-threaded code). // This makes the code more deterministic, i.e. we are sure that at the end // all input has been processed. // But this also means, that fewer (or even zero) patches could be returned. size_t batchEndIndex = batchStartIndex + batchSize; while (indexFlat < batchEndIndex && indexFlat < patchNumberFlat) // Note: break conditions below, due to convenience. { // Skip some of the patches according to the provided probability. float_t random = randomDist(randomEngine); bool dontUndersample = undersamplingProb > 0.999; // Floating-point comparison. if (dontUndersample || random < undersamplingProb) { unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd); // Figure out where in the orig. data the patch begins. for (size_t dim = 0; dim < ndim; dim++) dataIndexNd.X[dim] = patchIndexNd.X[dim] * patchStride[dim]; bool xIsEmpty = skipEmptyPatches; // Init to false, if not skipping empty patches. for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++) { unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd); // Where the column starts in the original data . for (size_t dim = 0; dim < ndim - 1; dim++) sourceIndexNd.X[dim] = dataIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd.X[ndim - 1] = dataIndexNd.X[ndim - 1]; size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS); size_t sourceIndexRel = sourceIndexFlat - dataStartFlat; // The input data is buffered, i.e. we only have a chunk of it. // Check if the buffer has the data we need. if (sourceIndexFlat + columnSize >= dataEndFlat) { inputEndReached = true; break; } // Check if the column is empty. auto first = &pData[sourceIndexRel]; auto last = &pData[sourceIndexRel + columnSize]; bool allValuesEqual = skipEmptyPatches && std::adjacent_find(first, last, std::not_equal_to<T>()) == last; xIsEmpty = xIsEmpty && *first == emptyValue && allValuesEqual; // Copy the whole column, even if it's empty. We don't know if the whole patch is empty or not. std::copy(first, last, patchDataX.data() + columnIndexFlat * columnSize); } // Extract Y. // Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead. sourceIndexNdY.X[0] = dataIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap; for (size_t dim = 1; dim < ndim; dim++) { // Take the value in the middle of the patch. sourceIndexNdY.X[dim] = dataIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim]; } size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS); size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat; // Check if the buffer has the data we need. if (inputEndReached || sourceIndexYFlat >= dataEndFlat) { inputEndReached = true; break; } T y = pData[sourceIndexYRel]; bool yIsEmpty = y == emptyValue; if (!xIsEmpty || !yIsEmpty) { // Claim output buffer space by advancing the atomic counter. // Atomic fetch_add performs read-modify-write as a single operation, so we are thread safe. size_t outputOffset = globalBufferOffset.fetch_add(1); // Where in the output array should we write. size_t outputOffsetX = outputOffset * patchSizeXFlat; size_t outputOffsetY = outputOffset; size_t outputOffsetIndices = outputOffset * ndim; // Write the results. std::copy(patchDataX.begin(), patchDataX.end(), pOutX + outputOffsetX); *(pOutY + outputOffsetY) = y; std::copy(&dataIndexNd.X[0], &dataIndexNd.X[4], pOutIndices + outputOffsetIndices); // Count how many patches this thread has extracted. patchesExtracted += 1; } else { patchesEmpty += 1; } } indexFlat += 1; } // Return the information about the extracted batch. *pOutPatchesExtracted = patchesExtracted; *pOutPatchesEmpty = patchesEmpty; *pOutNextBatchIndex = indexFlat; *pOutInputEndReached = inputEndReached; } /** * * This version doesn't use undersampling, empty patch skipping or striding. * It's meant for dense multi-threaded patch extraction. * */ template<typename T> void extract_patched_training_data_dense_4d(T* pData, size_t dataStartFlat, size_t dataEndFlat, const std::vector<size_t>& dataSize, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchInnerStride, size_t lastFrameGap, size_t batchStartIndex, size_t batchSize, T* pOutX, T* pOutY, size_t* pOutPatchesExtracted, bool* pOutInputEndReached) { const size_t ndim = 4; const std::vector<size_t> patchStride{ 1, 1, 1, 1 }; // Cache the functor, don't recreate it in a loop. auto multiplies = std::multiplies<size_t>(); if (dataSize.size() != ndim || patchSize.size() != ndim) throw std::runtime_error("Invalid number of dimensions. Expected four."); if (patchInnerStride[3] != 1) { printf("Inner stride is probably broken, since we copy patch by columns. \n"); throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n"); } // Number of patches along each dimension. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); // For efficiency, we don't copy data element-by-element, but copy // continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension. std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1); size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(), patchXColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchSize[ndim - 1]; // This function supports batching, i.e. we only extract 'batchSize' patches // starting with 'batchStartIndex' patch. // We loop over a flat index and then unflatten it. We could write 'ndim' nested loops, // but this way is a little less verbose and more flexible. // Optimization: allocate all vectors that we'll need, instead of doing it in the loop. Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber); Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize); IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber); // index4d_t dataIndexNd{}; <-- Is the same as patch index, since we have no striding. Index4d patchIndexNd{}; IndexNd<3> columnIndexNd{}; Index4d sourceIndexNd{}; Index4d sourceIndexNdY{}; bool inputEndReached = false; size_t patchesExtracted = 0; while (patchesExtracted < batchSize && batchStartIndex + patchesExtracted < patchNumberFlat) { // Since we don't skip patches, flat index follows 'patchesExtracted'. size_t indexFlat = batchStartIndex + patchesExtracted; unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd); // Where in the output array should we write. // All the patches are stacked one after another. size_t outputOffsetX = patchesExtracted * patchSizeXFlat; size_t outputOffsetY = patchesExtracted; for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++) { unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd); // Where the column starts in the original data . for (size_t dim = 0; dim < ndim - 1; dim++) sourceIndexNd.X[dim] = patchIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd.X[ndim - 1] = patchIndexNd.X[ndim - 1]; size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS); size_t sourceIndexRel = sourceIndexFlat - dataStartFlat; // The input data is buffered, i.e. we only have a chunk of it. // Check if the buffer has the data we need. if (sourceIndexFlat + columnSize >= dataEndFlat) { inputEndReached = true; break; } // Copy the whole column. auto first = &pData[sourceIndexRel]; auto last = &pData[sourceIndexRel + columnSize]; std::copy(first, last, pOutX + outputOffsetX + columnIndexFlat * columnSize); } // Extract Y. // Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead. sourceIndexNdY.X[0] = patchIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap; for (size_t dim = 1; dim < ndim; dim++) { // Take the value in the middle of the patch. sourceIndexNdY.X[dim] = patchIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim]; } size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS); size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat; // Check if the buffer has the data we need. if (inputEndReached || sourceIndexYFlat >= dataEndFlat) { inputEndReached = true; break; } // Copy the Y *(pOutY + outputOffsetY) = pData[sourceIndexYRel]; // Advance the output offset. patchesExtracted += 1; } // Return the information about the extracted batch. *pOutPatchesExtracted = patchesExtracted; *pOutInputEndReached = inputEndReached; } template <typename T> void sparse_insert_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues, size_t valueNumber) { size_t ndim = pArray->GetNdim(); typename BufferedNdArray<T>::Tuple indexNd(ndim); for (size_t i = 0; i < valueNumber; i++) { size_t const* pIndex = pIndices + i * ndim; std::copy(pIndex, pIndex + ndim, indexNd.data()); pArray->Write(indexNd, *(pValues + i)); } } template <typename T> void sparse_insert_slices_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues, size_t sliceNdim, size_t sliceNumber) { size_t ndim = pArray->GetNdim(); // Total array axis number. size_t sliceIndexNdim = ndim - sliceNdim; // Length of a slice index (non-sliced axis number). typename BufferedNdArray<T>::Tuple sliceIndexNd(sliceIndexNdim); size_t sliceSizeFlat = pArray->GetSliceSizeFromNdim(sliceNdim); for (size_t i = 0; i < sliceNumber; i++) { size_t const* pIndex = pIndices + i * sliceIndexNdim; std::copy(pIndex, pIndex + sliceIndexNdim, sliceIndexNd.data()); pArray->WriteSlice(sliceIndexNd, sliceNdim, pValues + i * sliceSizeFlat); } } /// /// Insert patches at location specified by the indices (lower patch corner). /// If 'isConstPatch' is false, expect a buffer with N patches, otherwise take a buffer with a single patch. /// template <typename T> void sparse_insert_patches_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues, size_t const* pPatchSize, size_t patchNumber, bool isConstPatch) { size_t ndim = pArray->GetNdim(); typename BufferedNdArray<T>::Tuple patchSize(pPatchSize, pPatchSize + ndim); size_t patchSizeFlat = std::accumulate(patchSize.begin(), patchSize.end(), 1, std::multiplies<>()); typename BufferedNdArray<T>::Tuple patchIndexNd(ndim, 0); for (size_t i = 0; i < patchNumber; i++) { size_t const* pIndex = pIndices + i * ndim; std::copy(pIndex, pIndex + ndim, patchIndexNd.data()); if (!isConstPatch) pArray->WritePatch(patchIndexNd, patchSize, pValues + i * patchSizeFlat); else pArray->WritePatch(patchIndexNd, patchSize, pValues); // Always write the same patch. } } template <typename T> void sparse_insert_const_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const& constValue, size_t valuesToInsert) { size_t ndim = pArray->GetNdim(); typename BufferedNdArray<T>::Tuple indexNd(ndim); for (size_t i = 0; i < valuesToInsert; i++) { size_t const* pIndex = pIndices + i * ndim; std::copy(pIndex, pIndex + ndim, indexNd.data()); pArray->Write(indexNd, constValue); } } void _multithreading_test_worker(uint8_t* pData, uint64_t offset, uint64_t size) { for (size_t i = 0; i < size; i++) { size_t computationNumber = 20; size_t dummyResult = 0; for (size_t j = 0; j < computationNumber; j++) { dummyResult += 13 + dummyResult * 5 % 3; } pData[offset + i] += static_cast<uint8_t>(dummyResult % 256); } } //todo Keeping state between calls experiment. uint64_t StaticState = 5; extern "C" { // todo Get rid of the void pointers. Ctypes can handle typed pointers. // todo remove the test code. __DLLEXPORT void test(void* pInput, int width, int height) { double* pData = static_cast<double *>(pInput); for (int i = 0; i < width * height; ++i) { pData[i] = pData[i] * 2; } } __DLLEXPORT void static_state_test(uint64_t increment, uint64_t* out) { StaticState += increment; *out = StaticState; } __DLLEXPORT void multithreading_test(uint8_t* pData, uint64_t size, uint64_t threadNumber) { std::vector<std::thread> threads{}; size_t chunkSize = size / threadNumber; for (size_t i = 0; i < threadNumber; i++) { size_t chunkOffset = i * chunkSize; size_t actualChunkSize = std::min(chunkSize, size - chunkOffset); threads.emplace_back([=]() { _multithreading_test_worker(pData, chunkOffset, actualChunkSize); }); } for (auto& thread : threads) thread.join(); } __DLLEXPORT void resize_array_point_float32(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { resize_array_point<float_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth, pOutputRaw, targetWidth, targetHeight, targetDepth); } __DLLEXPORT void resize_array_point_float64(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { resize_array_point<double_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth, pOutputRaw, targetWidth, targetHeight, targetDepth); } __DLLEXPORT void resize_array_point_uint8(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { resize_array_point<uint8_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth, pOutputRaw, targetWidth, targetHeight, targetDepth); } __DLLEXPORT void extract_patches_uint8(void* data, void* output, size_t* outputCenters, size_t ndim, size_t* dataSize, size_t dataSizeL, size_t* sourceAxes, size_t sourceAxesL, size_t* patchSize, size_t patchSizeL, size_t* patchStride, size_t patchStrideL) { extract_patches<uint8_t>(data, output, outputCenters, ndim, std::vector<size_t>(dataSize, dataSize + dataSizeL), std::vector<size_t>(sourceAxes, sourceAxes + sourceAxesL), std::vector<size_t>(patchSize, patchSize + patchSizeL), std::vector<size_t>(patchStride, patchStride + patchStrideL)); } __DLLEXPORT void extract_patches_batched_uint8(void* data, void* output, size_t* outputCenters, size_t ndim, size_t* dataSize, size_t dataSizeL, size_t* sourceAxes, size_t sourceAxesL, size_t* patchSize, size_t patchSizeL, size_t* patchStride, size_t patchStrideL, size_t firstPatchIndex, size_t patchesPerBatch, bool isBatchSizedBuffer) { extract_patches_batched<uint8_t>(data, output, outputCenters, ndim, std::vector<size_t>(dataSize, dataSize + dataSizeL), std::vector<size_t>(sourceAxes, sourceAxes + sourceAxesL), std::vector<size_t>(patchSize, patchSize + patchSizeL), std::vector<size_t>(patchStride, patchStride + patchStrideL), firstPatchIndex, patchesPerBatch, isBatchSizedBuffer); } __DLLEXPORT void extract_patched_training_data_without_empty_4d_uint8( uint8_t* pData, size_t dataStartFlat, size_t dataEndFlat, size_t* dataSize, size_t* patchSize, size_t* patchStride, size_t* patchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, uint8_t emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, uint8_t* pOutX, uint8_t* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { extract_patched_training_data_without_empty_4d<uint8_t>(pData, dataStartFlat, dataEndFlat, std::vector<size_t>(dataSize, dataSize + 4), std::vector<size_t>(patchSize, patchSize + 4), std::vector<size_t>(patchStride, patchStride + 4), std::vector<size_t>(patchInnerStride, patchInnerStride + 4), lastFrameGap, skipEmptyPatches, emptyValue, batchStartIndex, batchSize, undersamplingProb, pOutX, pOutY, pOutIndices, pOutPatchesExtracted, pOutNextBatchIndex, pOutInputEndReached); } __DLLEXPORT void extract_patched_training_data_without_empty_4d_multithreaded_uint8( uint8_t* pData, size_t dataStartFlat, size_t dataEndFlat, size_t* pDataSize, size_t* pPatchSize, size_t* pPatchStride, size_t* pPatchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, uint8_t emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, size_t threadNumber, uint8_t* pOutX, uint8_t* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { const size_t ndim = 4; std::vector<size_t> dataSize(pDataSize, pDataSize + ndim); std::vector<size_t> patchSize(pPatchSize, pPatchSize + ndim); std::vector<size_t> patchStride(pPatchStride, pPatchStride + ndim); std::vector<size_t> patchInnerStride(pPatchInnerStride, pPatchInnerStride + ndim); std::vector<std::thread> threads{}; std::atomic<size_t> globalBufferOffset{0}; std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, std::multiplies<>()); size_t patchesToProcess = std::min(batchSize, patchNumberFlat - batchStartIndex); size_t chunkSize = patchesToProcess / threadNumber; // Output buffers. std::vector<size_t> patchesExtracted(threadNumber, 0); std::vector<size_t> patchesEmpty(threadNumber, 0); std::vector<size_t> nextBatchIndex(threadNumber, 0); bool* inputEndReached = new bool[threadNumber]; for (size_t i = 0; i < threadNumber; i++) { // Each thread gets allocated a fixed chunk of the input. // But a thread can write out an arbitrary number of patches, due to undersampling, // running out of input buffer or empty patch skipping. size_t chunkOffset = i * chunkSize; size_t actualChunkSize = i < threadNumber - 1 ? chunkSize : patchesToProcess - chunkOffset; threads.emplace_back([&, i, chunkOffset, actualChunkSize]() // Capture local vars by value! { extract_patched_training_data_without_empty_4d_multi<uint8_t>( pData, dataStartFlat, dataEndFlat, dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap, skipEmptyPatches, emptyValue, batchStartIndex + chunkOffset, actualChunkSize, undersamplingProb, globalBufferOffset, pOutX, pOutY, pOutIndices, &patchesExtracted[i], &patchesEmpty[i], &nextBatchIndex[i], &inputEndReached[i]); }); } for (auto& thread : threads) thread.join(); // Stop collecting results after encountering the first thread that couldn't finish. bool endReached = false; size_t totalPatchesExtracted = 0; size_t lastNextBatchIndex = nextBatchIndex[threadNumber - 1]; // By default, the last thread is the last ;). for (size_t i = 0; i < threadNumber; i++) { // printf("Thread %zu extracted %zu patches and skipped %zu. Run out: %d\n", i, patchesExtracted[i], patchesEmpty[i], inputEndReached[i]); totalPatchesExtracted += patchesExtracted[i]; if (!endReached && inputEndReached[i]) { endReached = true; // If we didn't have enough data - start over (next batch) at the first thread that had to stop. lastNextBatchIndex = nextBatchIndex[i]; } else if (endReached) { // Validate the assumption that if a thread runs out of input data, // then all the following threads extracted zero patches. // We assume that patches are layed out linearly wrt. to input, // if one thread requires an input element with at least index X, all following // threads require that or even higher indices. if (patchesExtracted[i] > 0) { printf("ASSUMPTION FAILED: We have run out of input data, \n"); printf("but the next thread %zu still extracted %zu patches. ", i, patchesExtracted[i]); abort(); } } } delete[] inputEndReached; // Do a consistency check: number of global output buffer increments should be the same // as the sum of local patch counters. if (totalPatchesExtracted != globalBufferOffset) { printf("FAILED THE CONSISTENCY CHECK: PATCHES MISSING DUE TO A RACE CONDITION?\n"); printf("Expected %zu patches to be written, got %zu instead\n", totalPatchesExtracted, globalBufferOffset.load()); abort(); } *pOutPatchesExtracted = totalPatchesExtracted; *pOutNextBatchIndex = lastNextBatchIndex; *pOutInputEndReached = endReached; } __DLLEXPORT void extract_patched_training_data_multithreaded_uint8( uint8_t* pData, size_t dataStartFlat, size_t dataEndFlat, size_t* dataSize, size_t* patchSize, size_t* patchInnerStride, size_t lastFrameGap, size_t batchStartIndex, size_t batchSize, size_t threadNumber, uint8_t* pOutX, uint8_t* pOutY, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { const int ndim = 4; auto multiplies = std::multiplies<size_t>(); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize, patchSize + 4); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); std::vector<std::thread> threads{}; size_t chunkSize = batchSize / threadNumber; // Output buffers. std::vector<size_t> patchesExtracted(threadNumber, 0); std::vector<size_t> nextBatchIndex(threadNumber, 0); bool* inputEndReached = new bool[threadNumber]; for (size_t i = 0; i < threadNumber; i++) { size_t chunkOffset = i * chunkSize; size_t actualChunkSize = i < threadNumber - 1 ? chunkSize : batchSize - chunkOffset; threads.emplace_back([&, i, chunkOffset, actualChunkSize]() { extract_patched_training_data_dense_4d<uint8_t>( pData, dataStartFlat, dataEndFlat, std::vector<size_t>(dataSize, dataSize + ndim), std::vector<size_t>(patchSize, patchSize + ndim), std::vector<size_t>(patchInnerStride, patchInnerStride + ndim), lastFrameGap, batchStartIndex + chunkOffset, actualChunkSize, pOutX + chunkOffset * patchSizeXFlat, pOutY + chunkOffset, &patchesExtracted[i], &inputEndReached[i] ); }); } for (auto& thread : threads) thread.join(); // Stop collecting results after encountering the first thread that couldn't finish. bool endReached = false; size_t totalPatchesExtracted = 0; for (size_t i = 0; i < threadNumber; i++) { totalPatchesExtracted += patchesExtracted[i]; if (inputEndReached[i]) { endReached = true; break; } } *pOutPatchesExtracted = totalPatchesExtracted; *pOutNextBatchIndex = batchStartIndex + totalPatchesExtracted; // No empty skipping, so it's the same. *pOutInputEndReached = endReached; delete[] inputEndReached; } __DLLEXPORT void sparse_insert_into_bna_uint8(void* pArrayRaw, size_t const* pIndices, uint8_t const* pValues, size_t valuesToInsert) { BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw); sparse_insert_into_bna<uint8_t>(pArray, pIndices, pValues, valuesToInsert); } __DLLEXPORT void sparse_insert_slices_into_bna_float32(void* pArrayRaw, size_t const* pIndices, float_t const* pValues, size_t sliceNdim, size_t valueNumber) { auto pArray = reinterpret_cast<BufferedNdArray<float_t>*>(pArrayRaw); sparse_insert_slices_into_bna<float_t>(pArray, pIndices, pValues, sliceNdim, valueNumber); } __DLLEXPORT void sparse_insert_patches_into_bna_uint8(void* pArrayRaw, size_t const* pIndices, uint8_t const* pValues, size_t const* pPatchSize, size_t patchNumber, bool isConstPatch) { BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw); sparse_insert_patches_into_bna(pArray, pIndices, pValues, pPatchSize, patchNumber, isConstPatch); } __DLLEXPORT void sparse_insert_patches_into_bna_float32(void* pArrayRaw, size_t const* pIndices, float_t const* pValues, size_t const* pPatchSize, size_t patchNumber, bool isConstPatch) { BufferedNdArray<float_t>* pArray = reinterpret_cast<BufferedNdArray<float_t>*>(pArrayRaw); sparse_insert_patches_into_bna(pArray, pIndices, pValues, pPatchSize, patchNumber, isConstPatch); } __DLLEXPORT void sparse_insert_const_into_bna_uint8(void* pArrayRaw, size_t const* pIndices, uint8_t constValue, size_t valueNumber) { BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw); sparse_insert_const_into_bna<uint8_t>(pArray, pIndices, constValue, valueNumber); } __DLLEXPORT void smooth_3d_array_average_float(float_t const* pInputData, size_t const* pDataSize, size_t kernelRadius, float_t* pOutputData) { smooth_3d_array_average(pInputData, IndexNd<3>(pDataSize, pDataSize + 3), kernelRadius, pOutputData); } void upscale_attention_patch(float_t const* pAttPatchSource, std::vector<size_t> const& attPatchSize, std::vector<size_t> const& attPatchSliceSizes, std::vector<size_t> const& targetSize, Index4d const& targetSliceSizes, std::vector<float_t>& outputPatch) { for (size_t targetT = 0; targetT < targetSize[0]; targetT++) { size_t patchT = int(roundf(static_cast<float>(targetT) / (targetSize[0] - 1) * (attPatchSize[0] - 1))); for (size_t targetZ = 0; targetZ < targetSize[1]; targetZ++) { // An edge-case for 2D data. size_t patchZ = targetSize[1] > 1 ? int(roundf(static_cast<float>(targetZ) / (targetSize[1] - 1) * (attPatchSize[1] - 1))) : 0; for (size_t targetY = 0; targetY < targetSize[2]; targetY++) { size_t patchY = int(roundf(static_cast<float>(targetY) / (targetSize[2] - 1) * (attPatchSize[2] - 1))); for (size_t targetX = 0; targetX < targetSize[3]; targetX++) { size_t patchX = int(roundf(static_cast<float>(targetX) / (targetSize[3] - 1) * (attPatchSize[3] - 1))); size_t outputIndexFlat = targetT * targetSliceSizes.X[0] + targetZ * targetSliceSizes.X[1] + targetY * targetSliceSizes.X[2] + targetX * targetSliceSizes.X[3]; size_t attIndexFlat = patchT * attPatchSliceSizes[0] + patchZ * attPatchSliceSizes[1] + patchY * attPatchSliceSizes[2] + patchX * attPatchSliceSizes[3]; outputPatch[outputIndexFlat] = *(pAttPatchSource + attIndexFlat); } } } } } /// /// Aggregates a raw 8D attention volume into a 4D volume /// by adding attention from each patch to spatial positions. /// Essentially computes "overall voxel importance". /// // todo Move to a separate project? __DLLEXPORT void aggregate_attention_volume(void* pAttentionRawArray, size_t* pDataSize, size_t* pPatchXSize, size_t* pPredictionStride, void* pAttentionOutArray) { // todo prediction delay isn't needed anymore, because attention is written based on X-indices. constexpr size_t DataNdim = 4; constexpr size_t AttNdim = 8; auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray); auto pAttentionOut = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionOutArray); std::vector<size_t> dataSize{ pDataSize, pDataSize + DataNdim }; std::vector<size_t> patchXSize{ pPatchXSize, pPatchXSize + DataNdim }; Index4d patchXSizeNd{pPatchXSize, pPatchXSize + DataNdim}; std::vector<size_t> predictionStride{ pPredictionStride, pPredictionStride + DataNdim }; std::vector<size_t> attVolSize = pAttentionRaw->GetShape(); // Domain size includes only the spatiotemporal dimensions. std::vector<size_t> attVolDomainSize{ attVolSize.data(), attVolSize.data() + DataNdim }; std::vector<size_t> attPatchSize{ attVolSize.begin() + DataNdim, attVolSize.end() }; auto multiplesFunc = std::multiplies<>(); size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc); size_t patchXSizeFlat = std::accumulate(patchXSize.begin(), patchXSize.end(), size_t{1}, multiplesFunc); size_t attVolDomainSizeFlat = std::accumulate(attVolDomainSize.begin(), attVolDomainSize.end(), size_t{1}, multiplesFunc); std::vector<size_t> attPatchSliceSizes = compute_slice_sizes(attPatchSize); Index4d patchXSliceSizes = compute_slice_sizes_fast<DataNdim>(patchXSize); Index4d dataSliceSizes = compute_slice_sizes_fast<DataNdim>(dataSize); Index4d attVolDomainSliceSizes = compute_slice_sizes_fast<DataNdim>(attVolDomainSize); std::vector<float_t> attPatchRaw(attPatchSizeFlat); std::vector<float_t> attPatchScaled(patchXSizeFlat); std::vector<size_t> attIndexVec(DataNdim, 0); for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++) { Index4d attIndexNd{}; Index4d dataIndexNd{}; unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd); std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector. // Compute the data index of the lower patch corner. Att volume can be smaller in the case of strided prediction. for (size_t dim = 0; dim < DataNdim; dim++) dataIndexNd[dim] = attIndexNd[dim] * predictionStride[dim]; if (attIndexNd[1] == 0 && attIndexNd[2] == 0 && attIndexNd[3] == 0) { auto time = std::chrono::system_clock::now(); std::time_t timeC = std::chrono::system_clock::to_time_t(time); std::string timeStr{std::ctime(&timeC)}; timeStr.pop_back(); printf("[%s] Processing frame %zu / %zu. \n", timeStr.c_str(), attIndexNd[0], attVolSize[0]); std::cout.flush(); } // Read the raw attention patch. pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data()); // Upscale it to match the data patch size. upscale_attention_patch(attPatchRaw.data(), attPatchSize, attPatchSliceSizes, patchXSize, patchXSliceSizes, attPatchScaled); size_t firstIndexFlat = flattenIndex_fast(dataIndexNd, dataSliceSizes); size_t lastIndexFlat = flattenIndex_fast(dataIndexNd + patchXSizeNd, dataSliceSizes); pAttentionOut->_assureRangeInBuffer(firstIndexFlat, lastIndexFlat); for (size_t patchIndexFlat = 0; patchIndexFlat < patchXSizeFlat; patchIndexFlat++) { Index4d patchIndexNd{}; unflattenIndex_fast(patchIndexFlat, patchXSliceSizes, patchIndexNd); size_t outputIndexFlat = flattenIndex_fast(dataIndexNd + patchIndexNd, dataSliceSizes); size_t relIndexFlat = outputIndexFlat - pAttentionOut->_bufferOffset; pAttentionOut->_buffer[relIndexFlat] = pAttentionOut->_buffer[relIndexFlat] + attPatchScaled[patchIndexFlat]; pAttentionOut->_isBufferDirty = true; } } printf("Input buffer efficiency: %f\n", pAttentionRaw->ComputeBufferEfficiency()); printf("Output buffer efficiency: %f\n", pAttentionOut->ComputeBufferEfficiency()); std::cout.flush(); } /// /// A dumb version of attention aggregation that works much faster. /// Used for debugging purposes. /// __DLLEXPORT void aggregate_attention_volume_dumb(void* pAttentionRawArray, size_t* pDataSize, size_t* pPatchSize, size_t predictionDelay, void* pAttentionOutArray) { const size_t dataNdim = 4; const size_t attNdim = 8; auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray); auto pAttentionOut = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionOutArray); std::vector<size_t> dataSize{ pDataSize, pDataSize + dataNdim }; std::vector<size_t> patchSize{ pPatchSize, pPatchSize + dataNdim }; std::vector<size_t> attVolSize = pAttentionRaw->GetShape(); std::vector<size_t> attPatchSize{ attVolSize[4], attVolSize[5], attVolSize[6], attVolSize[7] }; auto multiplesFunc = std::multiplies<>(); size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc); size_t patchSizeFlat = std::accumulate(patchSize.begin(), patchSize.end(), size_t{1}, multiplesFunc); size_t dataSizeFlat = std::accumulate(dataSize.begin(), dataSize.end(), size_t{1}, multiplesFunc); Index4d dataSliceSizes = compute_slice_sizes_fast<4>(dataSize); std::vector<size_t> attPatchSliceSizes = compute_slice_sizes(attPatchSize); std::vector<size_t> attVolSliceSizesVec = compute_slice_sizes(attVolSize); std::vector<float_t> attPatchRaw(attPatchSizeFlat); std::vector<float_t> attPatchScaled(patchSizeFlat); std::vector<size_t> domainLow{ patchSize[0] - 2 + predictionDelay, patchSize[1] / 2, patchSize[2] / 2, patchSize[3] / 2 }; std::vector<size_t> domainHigh{ dataSize[0], dataSize[1] - (patchSize[1] - patchSize[1] / 2) + 1, dataSize[2] - (patchSize[2] - patchSize[2] / 2) + 1, dataSize[3] - (patchSize[3] - patchSize[3] / 2) + 1 }; std::vector<size_t> dataIndexVec(dataNdim, 0); for (size_t dataIndexFlat = 0; dataIndexFlat < dataSizeFlat; dataIndexFlat++) { Index4d dataIndexNd{}; unflattenIndex_fast(dataIndexFlat, dataSliceSizes, dataIndexNd); std::copy(dataIndexNd.X, dataIndexNd.X + dataNdim, dataIndexVec.data()); // Convert to vector. if (dataIndexNd.X[1] == 0 && dataIndexNd.X[2] == 0 && dataIndexNd.X[3] == 0) printf("Processing frame %zu. \n", dataIndexNd.X[0]); if (dataIndexNd.X[0] < domainLow[0] || dataIndexNd.X[0] >= domainHigh[0] || dataIndexNd.X[1] < domainLow[1] || dataIndexNd.X[1] >= domainHigh[1] || dataIndexNd.X[2] < domainLow[2] || dataIndexNd.X[2] >= domainHigh[2] || dataIndexNd.X[3] < domainLow[3] || dataIndexNd.X[3] >= domainHigh[3]) { continue; } // Read the raw attention patch. pAttentionRaw->ReadSlice(dataIndexVec, attNdim - dataNdim, attPatchRaw.data()); // size_t attentionPatchIndexFlat = attPatchRaw.size() / 2; size_t attentionPatchIndexFlat = 0; // printf("%f \n", attPatchRaw[0]); float_t oldValue = pAttentionOut->Read(dataIndexFlat); pAttentionOut->Write(dataIndexFlat, oldValue + attPatchRaw[attentionPatchIndexFlat]); } printf("Input buffer efficiency: %f\n", pAttentionRaw->ComputeBufferEfficiency()); printf("Output buffer efficiency: %f\n", pAttentionOut->ComputeBufferEfficiency()); } /// /// /// __DLLEXPORT void aggregate_attention_volume_local_attention(void* pAttentionRawArray, double_t* pOutAttentionAvg, double_t* pOutAttentionVar) { constexpr size_t DataNdim = 4; constexpr size_t AttNdim = 8; auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray); std::vector<size_t> attVolSize = pAttentionRaw->GetShape(); // Domain size includes only the spatiotemporal dimensions. std::vector<size_t> attVolDomainSize{ attVolSize.data(), attVolSize.data() + DataNdim }; std::vector<size_t> attPatchSize{ attVolSize.begin() + DataNdim, attVolSize.end() }; auto multiplesFunc = std::multiplies<>(); size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc); size_t attVolDomainSizeFlat = std::accumulate(attVolDomainSize.begin(), attVolDomainSize.end(), size_t{1}, multiplesFunc); Index4d attVolDomainSliceSizes = compute_slice_sizes_fast<DataNdim>(attVolDomainSize); // Zero-fill the output buffers to be safe. memset(pOutAttentionAvg, 0, attPatchSizeFlat); memset(pOutAttentionVar, 0, attPatchSizeFlat); std::vector<float_t> attPatchRaw(attPatchSizeFlat); std::vector<size_t> attIndexVec(DataNdim, 0); for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++) { Index4d attIndexNd{}; unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd); std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector. // Read the raw attention patch. pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data()); // For each voxel of the attention patch, add its value to the avg. patch buffer. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t oldValue = *(pOutAttentionAvg + patchIndexFlat); *(pOutAttentionAvg + patchIndexFlat) = oldValue + attPatchRaw[patchIndexFlat]; } } // Now that we have a sum of all attention patches, we can compute the average by dividing. // For each voxel of the attention patch, add its value to the avg. patch buffer. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t sum = *(pOutAttentionAvg + patchIndexFlat); *(pOutAttentionAvg + patchIndexFlat) = sum / static_cast<double_t>(attVolDomainSizeFlat); } // Repeat the same loop over the attention patches, now computing their variance. for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++) { Index4d attIndexNd{}; unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd); std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector. // Read the raw attention patch. pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data()); // For each voxel of the attention patch, add its value to the avg. patch buffer. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t oldValue = *(pOutAttentionVar + patchIndexFlat); double_t mean = *(pOutAttentionAvg + patchIndexFlat); // Sum average square deviation from the mean. *(pOutAttentionVar + patchIndexFlat) = oldValue + std::pow(attPatchRaw[patchIndexFlat] - mean, 2); } } // Divide by the number of patches to get variance. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t sum = *(pOutAttentionVar + patchIndexFlat); *(pOutAttentionVar + patchIndexFlat) = sum / static_cast<double_t>(attVolDomainSizeFlat); } } }
46.011605
149
0.606749
rbnbr
50c650e0f191878630bdfa2f07e11db89750fae1
4,011
cpp
C++
flakor/math/GLMatrix.cpp
sainthsu/Flakor
c414502f85d637b82a47754f20d1175e747b0a7d
[ "Libpng", "Apache-2.0", "MIT" ]
4
2015-01-26T08:42:51.000Z
2015-04-14T09:22:12.000Z
flakor/math/GLMatrix.cpp
sainthsu/Flakor
c414502f85d637b82a47754f20d1175e747b0a7d
[ "Libpng", "Apache-2.0", "MIT" ]
null
null
null
flakor/math/GLMatrix.cpp
sainthsu/Flakor
c414502f85d637b82a47754f20d1175e747b0a7d
[ "Libpng", "Apache-2.0", "MIT" ]
null
null
null
#include "macros.h" #include <assert.h> #include "math/GLMatrix.h" FLAKOR_NS_BEGIN MatrixStack* modelviewStack; MatrixStack* projectionStack; MatrixStack* textureStack; MatrixStack* currentStack = NULL; static unsigned char initialized = 0; #ifdef __cplusplus extern "C" { #endif void lazyInitialize() { if (!initialized) { Matrix4* identity = new Matrix4(); //Temporary identity matrix //Initialize all 3 stacks modelviewStack = new MatrixStack(); projectionStack = new MatrixStack(); textureStack = new MatrixStack(); currentStack = modelviewStack; initialized = 1; //Make sure that each stack has the identity matrix modelviewStack->push(identity); projectionStack->push(identity); textureStack->push(identity); } } void GLMode(StackMode mode) { lazyInitialize(); switch(mode) { case GL_MODELVIEW: currentStack = modelviewStack; break; case GL_PROJECTION: currentStack = projectionStack; break; case GL_TEXTURE: currentStack = textureStack; break; default: assert(0 && "Invalid matrix mode specified"); //TODO: Proper error handling break; } } void GLPush(void) { Matrix4* top = new Matrix4(); lazyInitialize(); //Initialize the stacks if they haven't been already //Duplicate the top of the stack (i.e the current matrix) top->set(currentStack->top->get(),COLUMN_MAJOR); currentStack->push(top); } void GLPop(void) { assert(initialized && "Cannot Pop empty matrix stack"); //No need to lazy initialize, you shouldn't be popping first anyway! currentStack->pop(NULL); } void GLLoadIdentity() { lazyInitialize(); currentStack->top->identity(); //Replace the top matrix with the identity matrix } void GLFreeAll() { //Clear the matrix stacks modelviewStack->release(); projectionStack->release(); textureStack->release(); //Delete the matrices initialized = 0; //Set to uninitialized currentStack = NULL; //Set the current stack to point nowhere } void GLMultiply(const Matrix4* in) { lazyInitialize(); *currentStack->top = (*currentStack->top)*(*in); } void GLLoad(Matrix4* in) { lazyInitialize(); in->set(currentStack->top->get(),COLUMN_MAJOR); } void GLGet(StackMode mode, Matrix4* out) { lazyInitialize(); switch(mode) { case GL_MODELVIEW: FKLOG("MV TOP:%s",modelviewStack->top->toString()); out->set(modelviewStack->top->get(),COLUMN_MAJOR); break; case GL_PROJECTION: FKLOG("P TOP:%s",projectionStack->top->toString()); out->set(projectionStack->top->get(),COLUMN_MAJOR); break; case GL_TEXTURE: FKLOG("Tex TOP:%s",textureStack->top->toString()); out->set(textureStack->top->get(),COLUMN_MAJOR); break; default: assert(1 && "Invalid matrix mode specified"); //TODO: Proper error handling break; } } void GLTranslatef(float x, float y, float z) { Matrix4 *translation = new Matrix4(); //Create a rotation matrix using the axis and the angle translation->translate(x,y,z); //Multiply the rotation matrix by the current matrix *currentStack->top = (*currentStack->top)*(*translation); } void GLRotatef(float angle, float x, float y, float z) { //Create an axis vector Vector3* axis = new Vector3(x, y, z); Matrix4* rotation = new Matrix4(); //Create a rotation matrix using the axis and the angle rotation->rotate(angle, *axis); //Multiply the rotation matrix by the current matrix *currentStack->top = (*currentStack->top)*(*rotation); } void GLScalef(float x, float y, float z) { Matrix4* scaling = new Matrix4(); scaling->scale(x, y, z); *currentStack->top = (*currentStack->top)*(*scaling); } #ifdef __cplusplus } #endif FLAKOR_NS_END
23.051724
87
0.640987
sainthsu
50c673c4e99d14630c64df5ad4f9829184d85221
9,577
cpp
C++
src/gfx/graphics/vulkan/swapchain_vulkan.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
src/gfx/graphics/vulkan/swapchain_vulkan.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
src/gfx/graphics/vulkan/swapchain_vulkan.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
#include "init_struct.hpp" #include "swapchain_vulkan.hpp" #include "image_view_vulkan.hpp" #include "result.hpp" namespace gfx { inline namespace v1 { namespace vulkan { uint32_t swapchain_implementation::current_image() const noexcept { return _current_image; } void swapchain_implementation::present() { if (_presented) { vkResetCommandBuffer(_primary_command_buffers[_current_image], 0); init<VkCommandBufferBeginInfo> begin_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; vkBeginCommandBuffer(_primary_command_buffers[_current_image], &begin_info); init<VkImageMemoryBarrier> imb{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; imb.srcAccessMask = 0; imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; imb.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imb.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imb.image = _temp_images[_current_image]; imb.oldLayout = VK_IMAGE_LAYOUT_GENERAL; imb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imb.subresourceRange.baseArrayLayer = 0; imb.subresourceRange.baseMipLevel = 0; imb.subresourceRange.layerCount = 1; imb.subresourceRange.levelCount = 1; vkCmdPipelineBarrier(_primary_command_buffers[_current_image], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &imb); vkEndCommandBuffer(_primary_command_buffers[_current_image]); std::array<VkSemaphore, 1> wait_semaphores{_present_semaphore}; std::array<VkPipelineStageFlags, 1> wait_masks{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; std::array<VkCommandBuffer, 1> command_buffers{_primary_command_buffers[_current_image]}; init<VkSubmitInfo> submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &_primary_command_buffers[_current_image]; submit.pWaitSemaphores = std::data(wait_semaphores); submit.waitSemaphoreCount = static_cast<u32>(std::size(wait_semaphores)); submit.pSignalSemaphores = &_render_semaphore; submit.signalSemaphoreCount = 1; submit.pWaitDstStageMask = std::data(wait_masks); // In graphics queue. Waits on all posted semaphores. check_result(vkQueueSubmit(_graphics_queue, 1, &submit, _render_fences[_current_image])); uint32_t idx = _current_image; init<VkPresentInfoKHR> present_info{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; present_info.pImageIndices = &idx; present_info.pSwapchains = &_swapchain; present_info.swapchainCount = 1; present_info.pWaitSemaphores = &_render_semaphore; present_info.waitSemaphoreCount = 1; VkResult swapchain_result; present_info.pResults = &swapchain_result; // Solely in present queue, but waits for _render_semaphore which is triggered only after all posted semaphores are signaled. VkResult present_result = check_result(vkQueuePresentKHR(_present_queue, &present_info)); check_result(swapchain_result); } check_result(vkAcquireNextImageKHR(_device, _swapchain, std::numeric_limits<uint64_t>::max(), _present_semaphore, nullptr, &_current_image)); // Wait until last frame using this image has finished rendering check_result(vkWaitForFences(_device, 1, &_render_fences[_current_image], true, std::numeric_limits<uint64_t>::max())); check_result(vkResetFences(_device, 1, &_render_fences[_current_image])); _presented = true; } void swapchain_implementation::resize(uint32_t width, uint32_t height) { auto& ctx = context::current(); _ctx_impl = static_cast<context_implementation*>(std::any_cast<detail::context_implementation*>(ctx->implementation())); if (!_render_fences.empty()) vkWaitForFences(_ctx_impl->device(), static_cast<u32>(_render_fences.size()), _render_fences.data(), true, default_fence_timeout); vkDeviceWaitIdle(_ctx_impl->device()); this->~swapchain_implementation(); _presented = false; _device = _ctx_impl->device(); init<VkSwapchainCreateInfoKHR> swapchain_info{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; swapchain_info.clipped = true; swapchain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchain_info.imageArrayLayers = 1; swapchain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT; swapchain_info.pQueueFamilyIndices = &(_ctx_impl->queue_families()[fam::present]); swapchain_info.queueFamilyIndexCount = 1; VkSurfaceCapabilitiesKHR capabilities; check_result(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &capabilities)); swapchain_info.surface = _ctx_impl->surface(); swapchain_info.imageExtent = VkExtent2D{width, height}; swapchain_info.minImageCount = ctx->options().framebuffer_images; swapchain_info.preTransform = capabilities.currentTransform; u32 fmt_count = 0; check_result(vkGetPhysicalDeviceSurfaceFormatsKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &fmt_count, nullptr)); std::vector<VkSurfaceFormatKHR> formats(fmt_count); check_result(vkGetPhysicalDeviceSurfaceFormatsKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &fmt_count, formats.data())); if (const auto it = std::find_if(formats.begin(), formats.end(), [](const VkSurfaceFormatKHR& fmt) { return fmt.format == VK_FORMAT_B8G8R8A8_UNORM && fmt.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; }); it == formats.end()) { elog << "Did not find bgra8 format with srgb-nonlinear color space."; } else { swapchain_info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; swapchain_info.imageFormat = VK_FORMAT_B8G8R8A8_UNORM; } u32 pm_count = 0; check_result(vkGetPhysicalDeviceSurfacePresentModesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &pm_count, nullptr)); std::vector<VkPresentModeKHR> present_modes(pm_count); check_result(vkGetPhysicalDeviceSurfacePresentModesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &pm_count, present_modes.data())); if (const auto it = std::find_if(present_modes.begin(), present_modes.end(), [](const VkPresentModeKHR& mode) { return mode == VK_PRESENT_MODE_MAILBOX_KHR; }); it == present_modes.end()) { elog << "Did not find mailbox present mode."; } else swapchain_info.presentMode = VK_PRESENT_MODE_MAILBOX_KHR; check_result(vkCreateSwapchainKHR(_device, &swapchain_info, nullptr, &_swapchain)); _present_queue = _ctx_impl->queues()[fam::present]; _graphics_queue = _ctx_impl->queues()[fam::graphics]; // TODO: u32 img_count = 0; check_result(vkGetSwapchainImagesKHR(_device, _swapchain, &img_count, nullptr)); _temp_images.resize(img_count); check_result(vkGetSwapchainImagesKHR(_device, _swapchain, &img_count, _temp_images.data())); init<VkCommandBufferAllocateInfo> cmd_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cmd_info.commandBufferCount = static_cast<uint32_t>(_temp_images.size()); cmd_info.commandPool = _ctx_impl->command_pools()[fam::graphics]; cmd_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; _primary_command_buffers.resize(_temp_images.size()); check_result(vkAllocateCommandBuffers(_device, &cmd_info, _primary_command_buffers.data())); _command_pool = _ctx_impl->command_pools()[fam::graphics]; init<VkSemaphoreCreateInfo> sem_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; check_result(vkCreateSemaphore(_device, &sem_info, nullptr, &_present_semaphore)); check_result(vkCreateSemaphore(_device, &sem_info, nullptr, &_render_semaphore)); init<VkFenceCreateInfo> fen_info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; fen_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (int i = 0; i < _temp_images.size(); ++i) { check_result(vkCreateFence(_device, &fen_info, nullptr, &_render_fences.emplace_back())); image_view& view = _image_views.emplace_back(); static_cast<image_view_implementation*>(&*view.implementation())->initialize_vk(gfx::imgv_type::image2d, gfx::format::bgra8unorm, _temp_images[i], 0, 1, 0, 1); } } const std::vector<image_view>& swapchain_implementation::image_views() const { return _image_views; } handle swapchain_implementation::api_handle() { return _swapchain; } swapchain_implementation::~swapchain_implementation() { if (_swapchain) vkDestroySwapchainKHR(_device, _swapchain, nullptr); for (auto& f : _render_fences) vkDestroyFence(_device, f, nullptr); if (_device && !_primary_command_buffers.empty()) vkFreeCommandBuffers(_device, _command_pool, static_cast<u32>(_primary_command_buffers.size()), _primary_command_buffers.data()); if (_present_semaphore) vkDestroySemaphore(_device, _present_semaphore, nullptr); if (_render_semaphore) vkDestroySemaphore(_device, _render_semaphore, nullptr); } } // namespace vulkan } // namespace v1 } // namespace gfx
49.365979
161
0.732066
johannes-braun
50c7ba74baa9d0d989196197f1e0fc6c28ef57e1
1,044
cc
C++
shuffle-an-array.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
shuffle-an-array.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
shuffle-an-array.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <vector> #include <random> class Solution { public: std::vector<int> arr_; std::random_device dev_; std::mt19937 rng_; std::vector<std::uniform_int_distribution<int>> dists_; std::vector<int> res_; Solution(std::vector<int>& nums) : arr_(nums), dev_(), rng_(dev_()), res_(nums) { dists_.reserve(nums.size()); for (int i = 0; i < res_.size() - 1; i++) dists_.emplace_back(i, res_.size() - 1); } /** Resets the array to its original configuration and return it. */ std::vector<int> reset() { return arr_; } /** Returns a random shuffling of the array. */ std::vector<int> shuffle() { for (int i = 0; i < res_.size() - 1; i++) { std::swap(res_[dists_[i](rng_)], res_[i]); } return res_; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(nums); * vector<int> param_1 = obj->reset(); * vector<int> param_2 = obj->shuffle(); */
26.1
83
0.564176
ArCan314
50ccf6e8002517cfa041552b8f5ac2102158a917
83
cpp
C++
ksn-2021-pertahanan/solution-1.cpp
ia-toki/ksn-2021
e925029fa9ce6198aae489c5f8505c47078da28e
[ "CC-BY-4.0" ]
null
null
null
ksn-2021-pertahanan/solution-1.cpp
ia-toki/ksn-2021
e925029fa9ce6198aae489c5f8505c47078da28e
[ "CC-BY-4.0" ]
null
null
null
ksn-2021-pertahanan/solution-1.cpp
ia-toki/ksn-2021
e925029fa9ce6198aae489c5f8505c47078da28e
[ "CC-BY-4.0" ]
1
2021-12-05T04:17:41.000Z
2021-12-05T04:17:41.000Z
#include <bits/stdc++.h> using namespace std; int main() { cout << 9 << '\n'; }
11.857143
24
0.554217
ia-toki
50cd5b9f93c313756548633084e08427f4b688bd
8,537
cpp
C++
src/SamplesLibElise/CPP_CilliaImg.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
src/SamplesLibElise/CPP_CilliaImg.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
src/SamplesLibElise/CPP_CilliaImg.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MiccMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSCoordones_global_essai.txte image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "StdAfx.h" int Homol2GCP_main(int argc,char ** argv) { std::string aFile1; std::string aFile2; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Sentinel Homol" ) << EAMC(aFile2, "tfw file") << EAMC(aFileOut, "out= global coordinate file"), LArgMain() ); ELISE_fp aFIn(aFile1.c_str(),ELISE_fp::READ); ELISE_fp aFIn2(aFile2.c_str(),ELISE_fp::READ); FILE * aFOut = FopenNN(aFileOut.c_str(),"w","Cillia") ; char * aLine; std::vector<Pt2dr> aV2Ok; // std::vector<Pt3dr> aV3Ok; std::vector<double> tfw; while ((aLine = aFIn2.std_fgets())) { double V ; int aNb=sscanf(aLine,"%lf ",&V ); ELISE_ASSERT(aNb==1,"Could not read 2 double values"); tfw.push_back(V); } double tfw1 = tfw.at(0); double tfw4 = tfw.at(3); double tfw5 = tfw.at(4); double tfw6 = tfw.at(5); while ((aLine = aFIn.std_fgets())) { Pt2dr aP; int aNb = sscanf(aLine,"%lf %lf",&aP.x , &aP.y); ELISE_ASSERT(aNb==2,"Could not read 2 double values"); aV2Ok.push_back(aP); fprintf(aFOut,"%lf %.14lf ", aP.x *tfw1 + tfw5 , aP.y * tfw4 + tfw6 ); } return (1); delete aLine; delete aFOut; fclose(aFOut); // return(1); } int GlobToLocal_main(int argc,char ** argv) { std::string aFile1; std::string aFile2; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Global coordinate " ) << EAMC(aFile2, " tfw file") << EAMC(aFileOut, "Out= Local coordinate file"), LArgMain() ); ELISE_fp aFIn2(aFile2.c_str(),ELISE_fp::READ); char * aLine; std::vector<double> tfw; while ((aLine = aFIn2.std_fgets())) { double V ; int aNb=sscanf(aLine,"%lf ",&V ); ELISE_ASSERT(aNb==1,"Could not read 2 double values") tfw.push_back(V); } double tfw1 = tfw.at(0); double tfw4 = tfw.at(3); double tfw5 = tfw.at(4); double tfw6 = tfw.at(5); ELISE_fp aFIn(aFile1.c_str(),ELISE_fp::READ); FILE * aFOut = FopenNN(aFileOut.c_str(),"w","Cilliap") ; char * aLine2; std::vector<Pt2dr> aV2Ok; int aCnt=0; while ((aLine2 = aFIn.std_fgets())) { aCnt++; Pt2dr aP; int aNb= sscanf(aLine2,"%lf %lf",&aP.x , &aP.y); ELISE_ASSERT(aNb==2,"Could not read 2 double values"); aV2Ok.push_back(aP); std::cout << aCnt << " " << aP << "\n"; } for(int aK=0; aK<int(aV2Ok.size()-1); aK++) { fprintf(aFOut,"%.14lf %.14lf\n ", (aV2Ok.at(aK).x - tfw5)/ tfw1 , (aV2Ok.at(aK).y- tfw6) / tfw4 ); } fprintf(aFOut,"%.14lf %.14lf ", (aV2Ok.at(aV2Ok.size()-1).x - tfw5)/ tfw1 , (aV2Ok.at(aV2Ok.size()-1).y- tfw6) / tfw4 ); fclose(aFOut); delete aLine; delete aLine2; return EXIT_SUCCESS; } int ExtractZ_main(int argc,char ** argv) { std::string aFile1; std::string aImg; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Local coordinate " ) << EAMC(aImg, "SRTM image") << EAMC(aFileOut, "Out= coordinate xyz file"), LArgMain() ); // Read of an image Tiff_Im ImgTiff = Tiff_Im::UnivConvStd(aImg.c_str()); Im2D_REAL4 I(ImgTiff.sz().x, ImgTiff.sz().y); ELISE_COPY ( I.all_pts(), ImgTiff.in(), I.out() ); //interpolation cInterpolBilineaire<REAL4> * bicu = new cInterpolBilineaire<REAL4>; //Lecture de point qui sont deja dans l'espace d'image SRTM" ELISE_fp aFIn(aFile1.c_str(),ELISE_fp::READ); std::vector<Pt2dr> aV2Ok; char * aLine; while ((aLine = aFIn.std_fgets())) { Pt2dr aP; int aNb=sscanf(aLine,"%lf %lf",&aP.x , &aP.y); ELISE_ASSERT(aNb==2,"Could not read 2 double values"); aV2Ok.push_back(aP); //std::cout << " " << aP << "\n"; } // Pt2dr aP; // Recuperation de valeurs Z sur SRTM FILE *aFOut = FopenNN(aFileOut.c_str(),"w","Cillia") ; double aZTmp=0; int aCntOut=0; for(int aK=0; aK< int(aV2Ok.size()); aK++) { if( (aV2Ok.at(aK).x >=0) && (aV2Ok.at(aK).x <ImgTiff.sz().x) && (aV2Ok.at(aK).y >=0) && (aV2Ok.at(aK).y <ImgTiff.sz().y) ) { aZTmp = I.Get(aV2Ok.at(aK), *bicu , 0.5); fprintf(aFOut, "%lf %lf %lf \n", aV2Ok.at(aK).x, aV2Ok.at(aK).y, aZTmp); } else { aCntOut++; std::cout << "Point out of image=" << aV2Ok.at(aK) << " " << aCntOut << "\n"; } } return EXIT_SUCCESS; fclose(aFOut); } int XYZ_Global_main(int argc,char ** argv) { std::string aFile1; std::string aFile2; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Global coordinate " ) << EAMC(aFile2, " xyz file") << EAMC(aFileOut, "Out= file XYZ global"), LArgMain() ); ELISE_fp aFIn1(aFile1.c_str(),ELISE_fp::READ); ELISE_fp aFIn2(aFile2.c_str(),ELISE_fp::READ); // std::string aNameOut="XYZ_global_Full_final.txt"; FILE * aFOut = FopenNN(aFileOut.c_str(),"w","Cillia") ; std::vector<Pt2dr> aV2Ok; char * aLine1; std::vector<Pt3dr> aV3Ok; char * aLine2; Pt3dr aP3d; Pt2dr aP2d; std::vector<Pt2dr> aVXY; std::vector<double> aVZ; //read the first file while ( (aLine1 = aFIn1.std_fgets()) ) { int aNb1 = sscanf(aLine1,"%lf %lf", &aP2d.x , &aP2d.y); ELISE_ASSERT(aNb1==2,"Could not read 2 double values"); aVXY.push_back(aP2d); std::cout << "AA=" << aP2d.x <<"\n" ; } //read the second file while ( (aLine2=aFIn2.std_fgets()) ) { int aNb2 = sscanf(aLine2,"%lf %lf %lf", &aP3d.x , &aP3d.y , &aP3d.z); ELISE_ASSERT(aNb2==3,"Could not read 3 double values"); aVZ.push_back(aP3d.z); } if( aVZ.size() == aVXY.size() ) for( int aK=0; aK<int(aVZ.size()); aK++) fprintf(aFOut, "%lf %lf %lf\n",aVXY.at(aK).x ,aVXY.at(aK).y , aVZ.at(aK) ); else ELISE_ASSERT(false,"The number of points in your files is not the same") return(1); }
26.512422
121
0.538597
kikislater
50cd7e3c47b62a36e926996848352808662522a0
831
hh
C++
src/websocket_server/Packets/Out/WeatherStatusPacket.hh
3n16m4/websocket-server
5b6575bbd459feeef459b20a093ada3fd9d035e5
[ "MIT" ]
2
2020-11-16T15:53:39.000Z
2021-03-20T09:08:36.000Z
src/websocket_server/Packets/Out/WeatherStatusPacket.hh
3n16m4/websocket-server
5b6575bbd459feeef459b20a093ada3fd9d035e5
[ "MIT" ]
2
2020-12-09T23:54:55.000Z
2020-12-11T20:14:52.000Z
src/websocket_server/Packets/Out/WeatherStatusPacket.hh
3n16m4/websocket-server
5b6575bbd459feeef459b20a093ada3fd9d035e5
[ "MIT" ]
1
2021-03-20T09:08:41.000Z
2021-03-20T09:08:41.000Z
#ifndef WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH #define WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH #include <array> namespace amadeus { enum class WebSocketSessionFlag : std::uint8_t; #pragma pack(push, 1) namespace out { /// \brief Defines the WeatherStatusPacket which is sent by the server if a /// WebSocketSession requested a weather update for a specific TCP connection /// (µC). struct WeatherStatusPacket { /// Packet header. std::uint8_t header{0x04}; /// A unique identifier for the corresponding TCP Client which is used for /// authentication. std::array<std::uint8_t, 16> uuid; /// Reserved server specific flag, not used anymore. WebSocketSessionFlag flag; }; #pragma pack(pop) } // namespace out } // namespace amadeus #endif // !WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH
29.678571
78
0.758123
3n16m4
50d35331a0380b1acbd4127c8f8c2c6966f4b433
831
hpp
C++
cpp2c/test_data/mmalloc.hpp
mendlin/SIMD-libgen
0f386bb639c829275a00f46c4b31d59c5ed84a28
[ "AFL-1.1" ]
1
2021-01-07T03:18:27.000Z
2021-01-07T03:18:27.000Z
cpp2c/test_data/mmalloc.hpp
Logicalmars/SIMD-libgen
0f386bb639c829275a00f46c4b31d59c5ed84a28
[ "AFL-1.1" ]
null
null
null
cpp2c/test_data/mmalloc.hpp
Logicalmars/SIMD-libgen
0f386bb639c829275a00f46c4b31d59c5ed84a28
[ "AFL-1.1" ]
1
2021-11-29T07:28:13.000Z
2021-11-29T07:28:13.000Z
#ifndef ALIGNED_MMALLOC_HPP #define ALIGNED_MMALLOC_HPP /*============================================================================= allocator.hpp - Platform independent aligned memory allocation. Created on: 06-December-2011 Author: Ken Herdy Description: TODO - Wrap routines inside a class scope and/or C++ custom namespace. =============================================================================*/ #include "bitblock.hpp" #if defined USE_NEON #error "Neon aligned memory allocation not implemented. Aborting compilation." #else // USE_SSE template <class T> T * simd_malloc(uint32_t n) { return (T*)_mm_malloc(n*sizeof(T), sizeof(BitBlock)); } template <class T> void simd_free(T* p) { if(p != NULL) { _mm_free(p); p = NULL; } } #endif #endif // ALIGNED_MMALLOC_HPP
22.459459
79
0.565584
mendlin
50dae8608e9b682934ff5632912f808772132924
4,010
cpp
C++
test/test_array_derivatives.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
131
2016-07-06T04:06:49.000Z
2022-03-19T22:34:47.000Z
test/test_array_derivatives.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
19
2016-06-20T20:20:23.000Z
2022-02-15T14:55:01.000Z
test/test_array_derivatives.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
31
2017-10-07T00:07:49.000Z
2022-03-05T17:51:17.000Z
/* test_array_derivatives.cpp - Test derivatives of array expressions Copyright (C) 2017 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. */ #include <adept_arrays.h> // Arbitrary algorithm converting array of general type A to scalar of // type S, which may be active or passive template <class A, class S> void algorithm(const A& x, S& y) { using namespace adept; A tmp; intVector index(2); index << 1, 0; tmp = atan2((exp(x) * x), spread<0>(x(index,1),2)) / x(0,0); y = sum(tmp); } int main(int argc, const char** argv) { using namespace adept; Stack stack; // Matrix dimension static const int N = 2; static const Real MAX_FRAC_ERR = 1.0e-5; // Perturbation size for numerical calculation Real dx = 1.0e-6; if (sizeof(Real) < 8) { // Single precision only works with larger perturbations dx = 1.0e-4; } // Maximum fractional error Real max_frac_err; bool error_too_large = false; // Input data Matrix X(N,N); X << 2, 3, 5, 7; // Numerical calculation std::cout << "NUMERICAL CALCULATION\n"; Matrix dJ_dx_num(N,N); { Real J; algorithm(X, J); std::cout << "J = " << J << "\n"; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { Matrix Xpert(N,N); Xpert = X; Xpert(i,j) += dx; Real Jpert; algorithm(Xpert, Jpert); dJ_dx_num(i,j) = (Jpert - J) / dx; } } } std::cout << "dJ_dx_num = " << dJ_dx_num << "\n"; std::cout << "\nNUMERICAL CALCULATION WITH \"FixedArray\"\n"; Matrix22 dJ_dx_num_FixedArray; { Real J; algorithm(X, J); std::cout << "J = " << J << "\n"; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { Matrix22 Xpert = X; Xpert(i,j) += dx; Real Jpert; algorithm(Xpert, Jpert); dJ_dx_num_FixedArray(i,j) = (Jpert - J) / dx; } } } std::cout << "dJ_dx_num_FixedArray = " << dJ_dx_num_FixedArray << "\n"; // Adept calculation with aArray std::cout << "\nADEPT CALCULATION WITH \"aArray\"\n"; Matrix dJ_dx_adept_Array(N,N); { aMatrix aX = X; stack.new_recording(); aReal aJ; algorithm(aX, aJ); std::cout << "J = " << aJ << "\n"; aJ.set_gradient(1.0); stack.reverse(); dJ_dx_adept_Array = aX.get_gradient(); } std::cout << "dJ_dx_adept_Array = " << dJ_dx_adept_Array << "\n"; max_frac_err = maxval(abs(dJ_dx_adept_Array-dJ_dx_num)/dJ_dx_num); if (max_frac_err <= MAX_FRAC_ERR) { std::cout << "max fractional error = " << max_frac_err << ": PASSED\n"; } else { std::cout << "max fractional error = " << max_frac_err << ": FAILED\n"; error_too_large = true; } // Adept calculation with aFixedArray std::cout << "\nADEPT CALCULATION WITH \"aFixedArray\"\n"; Matrix dJ_dx_adept_FixedArray; { aMatrix22 aX = X; stack.new_recording(); aReal aJ; algorithm(aX, aJ); std::cout << "J = " << aJ << "\n"; aJ.set_gradient(1.0); stack.reverse(); dJ_dx_adept_FixedArray = aX.get_gradient(); } std::cout << "dJ_dx_adept_FixedArray = " << dJ_dx_adept_FixedArray << "\n"; max_frac_err = maxval(abs(dJ_dx_adept_FixedArray-dJ_dx_num)/dJ_dx_num); if (max_frac_err <= MAX_FRAC_ERR) { std::cout << "max fractional error = " << max_frac_err << ": PASSED\n"; } else { std::cout << "max fractional error = " << max_frac_err << ": FAILED\n"; error_too_large = true; } std::cout << "\n"; if (error_too_large) { std::cerr << "*** Error: fractional error in the derivatives of some configurations too large\n"; if (sizeof(Real) < 8) { std::cerr << "*** (but you are using less than double precision so it is not surprising)\n"; } return 1; } else { return 0; } }
23.727811
101
0.610474
yairchu
50db783e21b99550fa09f93b00936396feab61e9
9,908
hpp
C++
ze_common/include/ze/common/ringbuffer.hpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
30
2016-09-27T07:41:28.000Z
2021-12-03T20:44:28.000Z
ze_common/include/ze/common/ringbuffer.hpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
1
2018-12-18T15:53:06.000Z
2018-12-21T03:10:06.000Z
ze_common/include/ze/common/ringbuffer.hpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
12
2016-11-05T07:51:29.000Z
2020-07-13T02:26:08.000Z
// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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. #pragma once #include <map> #include <tuple> #include <thread> #include <utility> #include <mutex> #include <Eigen/Dense> #include <ze/common/logging.hpp> #include <ze/common/ring_view.hpp> #include <ze/common/types.hpp> #include <ze/common/time_conversions.hpp> namespace ze { //! @todo: move the interpolators somewhere where they make more sense? //! //! Interpolators have to implement: //! _ interpolate(Ringbuffer<...>*, int64_t time, Ringbuffer<...>timering_t::iterator); //! Passing the (optional) interator to the timestamp right before the to be //! interpolated value speeds up the process. //! The passed it_before is expected to be valid. //! //! A nearest neighbour "interpolator". struct InterpolatorNearest { template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time, typename Ringbuffer_T::timering_t::iterator it_before) { // the end value auto it_after = it_before + 1; if (it_after == buffer->times_.end()) { LOG(WARNING) << "Interpolation hit end of buffer."; return buffer->dataAtTimeIterator(it_before); } // The times are ordered, we can guarantee those differences to be positive if ((time - *it_before) < (*it_after - time)) { return buffer->dataAtTimeIterator(it_before); } return buffer->dataAtTimeIterator(it_after); } template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time) { auto it_before = buffer->iterator_equal_or_before(time); // caller should check the bounds: CHECK(it_before != buffer->times_.end()); return interpolate(buffer, time, it_before); } }; //! A simple linear interpolator struct InterpolatorLinear { template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time, typename Ringbuffer_T::timering_t::iterator it_before) { // the end value auto it_after = it_before + 1; if (it_after == buffer->times_.end()) { LOG(WARNING) << "Interpolation hit end of buffer."; return buffer->dataAtTimeIterator(it_before); } const real_t w1 = static_cast<real_t>(time - *it_before) / static_cast<real_t>(*it_after - *it_before); return (real_t{1.0} - w1) * buffer->dataAtTimeIterator(it_before) + w1 * buffer->dataAtTimeIterator(it_after); } template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time) { auto it_before = buffer->iterator_equal_or_before(time); // caller should check the bounds: CHECK(it_before != buffer->times_.end()); return interpolate(buffer, time, it_before); } }; using DefaultInterpolator = InterpolatorLinear; //! A fixed size timed buffer templated on the number of entries. //! Opposed to the `Buffer`, values are expected to be received ORDERED in //! TIME! // Oldest entry: buffer.begin(), newest entry: buffer.rbegin() template <typename Scalar, size_t ValueDim, size_t Size> class Ringbuffer { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! Ringbuffer is friend with the interpolator types. friend struct InterpolatorNearest; friend struct InterpolatorLinear; typedef int64_t time_t; typedef Eigen::Matrix<time_t, Size, 1> times_t; typedef Eigen::Matrix<time_t, Eigen::Dynamic, 1> times_dynamic_t; typedef Eigen::Matrix<Scalar, ValueDim, Size> data_t; typedef Eigen::Matrix<Scalar, ValueDim, Eigen::Dynamic> data_dynamic_t; // time ring is used to keep track of the positions of the data // in the dataring // uses fixed size ring_view typedef ring_view<time_t> timering_t; using DataType = Eigen::Matrix<Scalar, ValueDim, 1>; using DataTypeMap = Eigen::Map<DataType>; // a series of return types using DataBoolPair = std::pair<DataType, bool>; using TimeDataBoolTuple = std::tuple<time_t, DataType, bool>; using TimeDataRangePair = std::pair<times_dynamic_t, data_dynamic_t>; Ringbuffer() : times_(timering_t(times_raw_.data(), times_raw_.data() + Size, times_raw_.data(), 0)) {} //! no copy, no move as there is no way to track the mutex Ringbuffer(const Ringbuffer& from) = delete; Ringbuffer(const Ringbuffer&& from) = delete; inline void insert(time_t stamp, const DataType& data) { std::lock_guard<std::mutex> lock(mutex_); times_.push_back(stamp); data_.col(times_.back_idx()) = data; } //! Get value with timestamp closest to stamp. Boolean returns if successful. std::tuple<time_t, DataType, bool> getNearestValue(time_t stamp); //! Get oldest value in buffer. std::pair<DataType, bool> getOldestValue() const; //! Get newest value in buffer. std::pair<DataType, bool> getNewestValue() const; //! Get timestamps of newest and oldest entry. std::tuple<time_t, time_t, bool> getOldestAndNewestStamp() const; /*! @brief Get Values between timestamps. * * If timestamps are not matched, the values * are interpolated. Returns a vector of timestamps and a block matrix with * values as columns. Returns empty matrices if not successful. */ template <typename Interpolator = DefaultInterpolator> TimeDataRangePair getBetweenValuesInterpolated(time_t stamp_from, time_t stamp_to); //! Get the values of the container at the given timestamps //! The requested timestamps are expected to be in order! template <typename Interpolator = DefaultInterpolator> data_dynamic_t getValuesInterpolated(times_dynamic_t stamps); //! Interpolate a single value template <typename Interpolator = DefaultInterpolator> bool getValueInterpolated(time_t t, Eigen::Ref<data_dynamic_t> out); inline void clear() { std::lock_guard<std::mutex> lock(mutex_); times_.reset(); } inline size_t size() const { std::lock_guard<std::mutex> lock(mutex_); return times_.size(); } inline bool empty() const { std::lock_guard<std::mutex> lock(mutex_); return times_.empty(); } //! technically does not remove but only moves the beginning of the ring inline void removeDataBeforeTimestamp(time_t stamp) { std::lock_guard<std::mutex> lock(mutex_); removeDataBeforeTimestamp_impl(stamp); } inline void removeDataOlderThan(real_t seconds) { std::lock_guard<std::mutex> lock(mutex_); if(times_.empty()) { return; } removeDataBeforeTimestamp_impl( times_.back() - secToNanosec(seconds)); } inline void lock() const { mutex_.lock(); } inline void unlock() const { mutex_.unlock(); } const data_t& data() const { CHECK(!mutex_.try_lock()) << "Call lock() before accessing data."; return data_; } const timering_t& times() const { CHECK(!mutex_.try_lock()) << "Call lock() before accessing data."; return times_; } typename timering_t::iterator iterator_equal_or_before(time_t stamp); typename timering_t::iterator iterator_equal_or_after(time_t stamp); //! returns an iterator to the first element in the times_ ring that //! is greater or equal to stamp inline typename timering_t::iterator lower_bound(time_t stamp); inline std::mutex& mutex() {return mutex_;} protected: mutable std::mutex mutex_; data_t data_; times_t times_raw_; timering_t times_; //! return the data at a given point in time inline DataType dataAtTimeIterator(typename timering_t::iterator iter) const { //! @todo: i believe this is wrong. return data_.col(iter.container_index()); } //! return the data at a given point in time (const) inline DataType dataAtTimeIterator(typename timering_t::const_iterator iter) const { //! @todo: i believe this is wrong. return data_.col(iter.container_index()); } //! shifts the starting point of the ringbuffer to the given timestamp //! no resizing or deletion happens. inline void removeDataBeforeTimestamp_impl(time_t stamp) { auto it = lower_bound(stamp); times_.reset_front(it.container_index()); } }; } // namespace ze #include <ze/common/ringbuffer-inl.hpp>
31.858521
87
0.709931
rockenbf
50db7ca281441c15525ea23e0f2a09d9258fc9dd
3,198
cpp
C++
src/libraries/core/primitives/strings/lists/hashedWordList.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/primitives/strings/lists/hashedWordList.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/primitives/strings/lists/hashedWordList.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "hashedWordList.hpp" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // void CML::hashedWordList::rehash() { indices_.clear(); forAll(*this, i) { indices_.insert(List<word>::operator[](i), i); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // CML::hashedWordList::hashedWordList() : List<word>() {} CML::hashedWordList::hashedWordList(const UList<word>& names) : List<word>(names) { rehash(); } CML::hashedWordList::hashedWordList(const hashedWordList& names) : List<word>(static_cast<const UList<word>&>(names)) { rehash(); } CML::hashedWordList::hashedWordList(const Xfer< List<word> >& names) : List<word>(names) { rehash(); } CML::hashedWordList::hashedWordList ( const label nNames, const char** names ) : List<word>(nNames) { forAll(*this, i) { List<word>::operator[](i) = names[i]; } rehash(); } CML::hashedWordList::hashedWordList ( const char** names ) { // count names label nNames = 0; for (unsigned i = 0; names[i] && *(names[i]); ++i) { ++nNames; } List<word>::setSize(nNames); forAll(*this, i) { List<word>::operator[](i) = names[i]; } rehash(); } CML::hashedWordList::hashedWordList(Istream& is) { is >> *this; } // * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * // void CML::hashedWordList::clear() { List<word>::clear(); indices_.clear(); } void CML::hashedWordList::append(const word& name) { const label idx = size(); List<word>::append(name); indices_.insert(name, idx); } void CML::hashedWordList::transfer(List<word>& lst) { List<word>::transfer(lst); rehash(); } // * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * // CML::Istream& CML::operator>>(Istream& is, hashedWordList& lst) { is >> static_cast<List<word>&>(lst); lst.rehash(); return is; } CML::Ostream& CML::operator<<(Ostream& os, const hashedWordList& lst) { os << static_cast<const List<word>&>(lst); return os; } // ************************************************************************* //
20.5
79
0.530019
MrAwesomeRocks
50e125deb4b320ce3f86b69e55896749b3dd1652
70
cpp
C++
gui/applicationdata.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
4
2016-02-18T00:48:10.000Z
2016-03-02T23:41:54.000Z
gui/applicationdata.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
null
null
null
gui/applicationdata.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
1
2016-02-29T18:13:34.000Z
2016-02-29T18:13:34.000Z
#include "applicationdata.h" ApplicationData::ApplicationData() { }
14
38
0.757143
UnnamedCompany
50e27a852f0b1d876c84eba4259fca8df2a4e44b
11,149
cc
C++
store/benchmark/retwisClient.cc
yc1111/tapir
2ce0f57725611076cd76ad7374b44f887d8618d8
[ "MIT" ]
437
2016-01-13T23:06:06.000Z
2022-03-07T07:41:55.000Z
store/benchmark/retwisClient.cc
yc1111/tapir
2ce0f57725611076cd76ad7374b44f887d8618d8
[ "MIT" ]
13
2016-01-14T06:12:21.000Z
2021-09-15T07:45:17.000Z
store/benchmark/retwisClient.cc
yc1111/tapir
2ce0f57725611076cd76ad7374b44f887d8618d8
[ "MIT" ]
58
2016-01-14T05:54:13.000Z
2022-03-08T02:56:33.000Z
// -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*- /*********************************************************************** * * store/benchmark/retwisClient.cc: * Retwis benchmarking client for a distributed transactional store. * **********************************************************************/ #include "store/common/truetime.h" #include "store/common/frontend/client.h" #include "store/strongstore/client.h" #include "store/weakstore/client.h" #include "store/tapirstore/client.h" #include <algorithm> using namespace std; // Function to pick a random key according to some distribution. int rand_key(); bool ready = false; double alpha = -1; double *zipf; vector<string> keys; int nKeys = 100; int main(int argc, char **argv) { const char *configPath = NULL; const char *keysPath = NULL; int duration = 10; int nShards = 1; int closestReplica = -1; // Closest replica id. int skew = 0; // difference between real clock and TrueTime int error = 0; // error bars Client *client; enum { MODE_UNKNOWN, MODE_TAPIR, MODE_WEAK, MODE_STRONG } mode = MODE_UNKNOWN; // Mode for strongstore. strongstore::Mode strongmode; int opt; while ((opt = getopt(argc, argv, "c:d:N:k:f:m:e:s:z:r:")) != -1) { switch (opt) { case 'c': // Configuration path { configPath = optarg; break; } case 'f': // Generated keys path { keysPath = optarg; break; } case 'N': // Number of shards. { char *strtolPtr; nShards = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (nShards <= 0)) { fprintf(stderr, "option -N requires a numeric arg\n"); } break; } case 'd': // Duration in seconds to run. { char *strtolPtr; duration = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (duration <= 0)) { fprintf(stderr, "option -d requires a numeric arg\n"); } break; } case 'k': // Number of keys to operate on. { char *strtolPtr; nKeys = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (nKeys <= 0)) { fprintf(stderr, "option -k requires a numeric arg\n"); } break; } case 's': // Simulated clock skew. { char *strtolPtr; skew = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (skew < 0)) { fprintf(stderr, "option -s requires a numeric arg\n"); } break; } case 'e': // Simulated clock error. { char *strtolPtr; error = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (error < 0)) { fprintf(stderr, "option -e requires a numeric arg\n"); } break; } case 'z': // Zipf coefficient for key selection. { char *strtolPtr; alpha = strtod(optarg, &strtolPtr); if ((*optarg == '\0') || (*strtolPtr != '\0')) { fprintf(stderr, "option -z requires a numeric arg\n"); } break; } case 'r': // Preferred closest replica. { char *strtolPtr; closestReplica = strtod(optarg, &strtolPtr); if ((*optarg == '\0') || (*strtolPtr != '\0')) { fprintf(stderr, "option -r requires a numeric arg\n"); } break; } case 'm': // Mode to run in [occ/lock/...] { if (strcasecmp(optarg, "txn-l") == 0) { mode = MODE_TAPIR; } else if (strcasecmp(optarg, "txn-s") == 0) { mode = MODE_TAPIR; } else if (strcasecmp(optarg, "qw") == 0) { mode = MODE_WEAK; } else if (strcasecmp(optarg, "occ") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_OCC; } else if (strcasecmp(optarg, "lock") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_LOCK; } else if (strcasecmp(optarg, "span-occ") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_SPAN_OCC; } else if (strcasecmp(optarg, "span-lock") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_SPAN_LOCK; } else { fprintf(stderr, "unknown mode '%s'\n", optarg); exit(0); } break; } default: fprintf(stderr, "Unknown argument %s\n", argv[optind]); break; } } if (mode == MODE_TAPIR) { client = new tapirstore::Client(configPath, nShards, closestReplica, TrueTime(skew, error)); } else if (mode == MODE_WEAK) { client = new weakstore::Client(configPath, nShards, closestReplica); } else if (mode == MODE_STRONG) { client = new strongstore::Client(strongmode, configPath, nShards, closestReplica, TrueTime(skew, error)); } else { fprintf(stderr, "option -m is required\n"); exit(0); } // Read in the keys from a file. string key, value; ifstream in; in.open(keysPath); if (!in) { fprintf(stderr, "Could not read keys from: %s\n", keysPath); exit(0); } for (int i = 0; i < nKeys; i++) { getline(in, key); keys.push_back(key); } in.close(); struct timeval t0, t1, t2; int nTransactions = 0; // Number of transactions attempted. int ttype; // Transaction type. int ret; bool status; vector<int> keyIdx; gettimeofday(&t0, NULL); srand(t0.tv_sec + t0.tv_usec); while (1) { keyIdx.clear(); // Begin a transaction. client->Begin(); gettimeofday(&t1, NULL); status = true; // Decide which type of retwis transaction it is going to be. ttype = rand() % 100; if (ttype < 5) { // 5% - Add user transaction. 1,3 keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); sort(keyIdx.begin(), keyIdx.end()); if ((ret = client->Get(keys[keyIdx[0]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[0]].c_str(), ret); status = false; } for (int i = 0; i < 3 && status; i++) { client->Put(keys[keyIdx[i]], keys[keyIdx[i]]); } ttype = 1; } else if (ttype < 20) { // 15% - Follow/Unfollow transaction. 2,2 keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); sort(keyIdx.begin(), keyIdx.end()); for (int i = 0; i < 2 && status; i++) { if ((ret = client->Get(keys[keyIdx[i]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[i]].c_str(), ret); status = false; } client->Put(keys[keyIdx[i]], keys[keyIdx[i]]); } ttype = 2; } else if (ttype < 50) { // 30% - Post tweet transaction. 3,5 keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); sort(keyIdx.begin(), keyIdx.end()); for (int i = 0; i < 3 && status; i++) { if ((ret = client->Get(keys[keyIdx[i]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[i]].c_str(), ret); status = false; } client->Put(keys[keyIdx[i]], keys[keyIdx[i]]); } for (int i = 0; i < 2; i++) { client->Put(keys[keyIdx[i+3]], keys[keyIdx[i+3]]); } ttype = 3; } else { // 50% - Get followers/timeline transaction. rand(1,10),0 int nGets = 1 + rand() % 10; for (int i = 0; i < nGets; i++) { keyIdx.push_back(rand_key()); } sort(keyIdx.begin(), keyIdx.end()); for (int i = 0; i < nGets && status; i++) { if ((ret = client->Get(keys[keyIdx[i]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[i]].c_str(), ret); status = false; } } ttype = 4; } if (status) { status = client->Commit(); } else { Debug("Aborting transaction due to failed Read"); } gettimeofday(&t2, NULL); long latency = (t2.tv_sec - t1.tv_sec) * 1000000 + (t2.tv_usec - t1.tv_usec); int retries = 0; if (!client->Stats().empty()) { retries = client->Stats()[0]; } fprintf(stderr, "%d %ld.%06ld %ld.%06ld %ld %d %d %d", ++nTransactions, t1.tv_sec, t1.tv_usec, t2.tv_sec, t2.tv_usec, latency, status?1:0, ttype, retries); fprintf(stderr, "\n"); if (((t2.tv_sec-t0.tv_sec)*1000000 + (t2.tv_usec-t0.tv_usec)) > duration*1000000) break; } fprintf(stderr, "# Client exiting..\n"); return 0; } int rand_key() { if (alpha < 0) { // Uniform selection of keys. return (rand() % nKeys); } else { // Zipf-like selection of keys. if (!ready) { zipf = new double[nKeys]; double c = 0.0; for (int i = 1; i <= nKeys; i++) { c = c + (1.0 / pow((double) i, alpha)); } c = 1.0 / c; double sum = 0.0; for (int i = 1; i <= nKeys; i++) { sum += (c / pow((double) i, alpha)); zipf[i-1] = sum; } ready = true; } double random = 0.0; while (random == 0.0 || random == 1.0) { random = (1.0 + rand())/RAND_MAX; } // binary search to find key; int l = 0, r = nKeys, mid; while (l < r) { mid = (l + r) / 2; if (random > zipf[mid]) { l = mid + 1; } else if (random < zipf[mid]) { r = mid - 1; } else { break; } } return mid; } }
30.545205
90
0.44865
yc1111
50e2b45736a4cb23039bc11d8b549132c96b556b
94
cpp
C++
src/cli/InvalidCommandSyntaxException.cpp
mbassale/ownpass
a84e0cd3933ec8c3febf0e09647990baf3c2d506
[ "MIT" ]
null
null
null
src/cli/InvalidCommandSyntaxException.cpp
mbassale/ownpass
a84e0cd3933ec8c3febf0e09647990baf3c2d506
[ "MIT" ]
null
null
null
src/cli/InvalidCommandSyntaxException.cpp
mbassale/ownpass
a84e0cd3933ec8c3febf0e09647990baf3c2d506
[ "MIT" ]
null
null
null
// // Created by Marco Bassaletti on 18-03-21. // #include "InvalidCommandSyntaxException.h"
15.666667
43
0.734043
mbassale
50e75f1d819c1c35e5f770807a9f53e427904d2f
1,144
hpp
C++
DOS_Boat_Source/RequireSpace.hpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
DOS_Boat_Source/RequireSpace.hpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
DOS_Boat_Source/RequireSpace.hpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
/**************************************************************************** * Author: Michael S. Lewis * * Date: 6/3/2016 * * Description: RequireSpace.hpp is the RequireSpace class declaration * * (interface) file (for Final Project "DOS Boat"). * * A Require Space tests whether a specific object is in * * inventory before allowing the user to proceed to a * * particular adjacent space. * *****************************************************************************/ #ifndef REQUIRESPACE_HPP #define REQUIRESPACE_HPP #include <string> #include "Ocean.hpp" class Babbage; // Declaration of Babbage class. class RequireSpace : public Ocean { private: virtual void playSpace(Babbage* babbage, bool displayHint); virtual void nextSpace(Babbage* babbage); std::string required; std::string restricted; public: RequireSpace(); RequireSpace(std::string nameSpacem, std::string spaceHeading, std::string spaceType, std::string requiredItem, std::string restrictedArea); }; #endif // REQUIRESPACE_HPP
35.75
79
0.566434
michaelslewis
50e780b7bab76861f125a4c3ff88c3d8acf4c755
360
cpp
C++
books/C++_advanced_course/Chapter6/template_parameter_4.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
books/C++_advanced_course/Chapter6/template_parameter_4.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
books/C++_advanced_course/Chapter6/template_parameter_4.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include <iostream> using std::cout; using std::endl; template<class T, int a> class X { public: T valX[a]; }; template<class T, int a> class Y { X<T, a> valY; public: void Set(T t) { valY.valX[0] = t; } void ShowFirst() { cout << valY.valX[0] << endl; } }; int main() { Y<double, 3> y; y.Set(0.8); y.ShowFirst(); system("pause"); return 0; }
10.588235
51
0.586111
liangjisheng
50e8fb9c008d57e9f0091fbfd6c1d3c827741bbc
1,836
cpp
C++
tests/rect_follow_mouse.cpp
AlexandruIca/SoftRender
9466251ad919d6896a1e3d1455a156186106cbaa
[ "Unlicense" ]
null
null
null
tests/rect_follow_mouse.cpp
AlexandruIca/SoftRender
9466251ad919d6896a1e3d1455a156186106cbaa
[ "Unlicense" ]
null
null
null
tests/rect_follow_mouse.cpp
AlexandruIca/SoftRender
9466251ad919d6896a1e3d1455a156186106cbaa
[ "Unlicense" ]
null
null
null
#include <chrono> #include <cmath> #include "softrender.hpp" struct rect_t { softrender::point_t pos{ 0, 0 }; int w{ 0 }; int h{ 0 }; }; using microsecond_t = decltype(std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::seconds(1)) .count()); auto follow_mouse(rect_t& t_rect, softrender::point_t const& t_mouse_pos, microsecond_t const t_elapsed_time) noexcept -> void { double const elapsed = t_elapsed_time / double{ 1e6 }; int constexpr velocity = 300; // pixels double const center_x = t_rect.pos.x + t_rect.w / 2.0; double const center_y = t_rect.pos.y + t_rect.h / 2.0; double const dest_x = t_mouse_pos.x; double const dest_y = t_mouse_pos.y; double const dx = dest_x - center_x; double const dy = dest_y - center_y; double const distance = std::sqrt(dx * dx + dy * dy); if(distance < 5) { return; } t_rect.pos.x += static_cast<int>(velocity * elapsed * dx / distance); t_rect.pos.y += static_cast<int>(velocity * elapsed * dy / distance); } auto main(int, char*[]) -> int { using namespace softrender; window_t window{ 1280, 720 }; microsecond_t elapsed{ 0 }; rect_t rect{ { window.width() / 2 - 200, window.height() / 2 - 200 }, 400, 400 }; auto start = std::chrono::high_resolution_clock::now(); while(!window.closed()) { auto end = std::chrono::high_resolution_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start) .count(); start = end; follow_mouse(rect, window.get_mouse_position(), elapsed); window.draw_rectangle(rect.pos, rect.w, rect.h, pink); window.draw(); } }
26.228571
78
0.594227
AlexandruIca
50e90c212b6c069bf716bd2de7e2fd50dc270404
4,508
cpp
C++
Code/GraphMol/catch_tests.cpp
Mike575/rdkit
373a89021e478f878c6011a201e3fb8f4a122093
[ "PostgreSQL" ]
1
2019-01-23T06:02:24.000Z
2019-01-23T06:02:24.000Z
Code/GraphMol/catch_tests.cpp
Mike575/rdkit
373a89021e478f878c6011a201e3fb8f4a122093
[ "PostgreSQL" ]
null
null
null
Code/GraphMol/catch_tests.cpp
Mike575/rdkit
373a89021e478f878c6011a201e3fb8f4a122093
[ "PostgreSQL" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do // this in one cpp file #include "catch.hpp" #include <GraphMol/RDKitBase.h> #include <GraphMol/RDKitQueries.h> #include <GraphMol/Chirality.h> #include <GraphMol/FileParsers/FileParsers.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/SmilesParse/SmartsWrite.h> using namespace RDKit; TEST_CASE("SMILES Parsing works", "[molops]") { std::unique_ptr<RWMol> mol(SmilesToMol("C1CC1")); REQUIRE(mol); REQUIRE(mol->getNumAtoms() == 3); } TEST_CASE("Sanitization tests", "[molops]") { std::unique_ptr<RWMol> mol(SmilesToMol("C1=CC=CC=C1Cc2ccccc2", false, false)); REQUIRE(mol); REQUIRE(mol->getNumAtoms() == 13); SECTION("properties") { mol->updatePropertyCache(); CHECK(mol->getAtomWithIdx(0)->getTotalNumHs() == 1); CHECK(!mol->getAtomWithIdx(0)->getIsAromatic()); CHECK(mol->getAtomWithIdx(7)->getIsAromatic()); SECTION("aromaticity") { unsigned int opThatFailed; MolOps::sanitizeMol(*mol, opThatFailed, MolOps::SANITIZE_SETAROMATICITY); // mol->debugMol(std::cerr); CHECK(mol->getAtomWithIdx(7)->getIsAromatic()); // blocked by #1730 // CHECK(mol->getAtomWithIdx(0)->getIsAromatic()); } SECTION("kekulize") { unsigned int opThatFailed; MolOps::sanitizeMol(*mol, opThatFailed, MolOps::SANITIZE_KEKULIZE); CHECK(!mol->getAtomWithIdx(0)->getIsAromatic()); CHECK(!mol->getAtomWithIdx(7)->getIsAromatic()); } } } TEST_CASE("Github #2062", "[bug, molops]") { SmilesParserParams ps; ps.removeHs = false; ps.sanitize = true; std::unique_ptr<RWMol> mol(SmilesToMol("[C:1][C:2]([H:3])([H])[O:4][H]", ps)); REQUIRE(mol); CHECK(mol->getNumAtoms() == 6); mol->getAtomWithIdx(1)->setProp("intProp", 42); MolOps::mergeQueryHs(*mol); CHECK(mol->getNumAtoms() == 3); SECTION("basics") { CHECK(mol->getAtomWithIdx(1)->getAtomMapNum() == 2); } SECTION("other props") { REQUIRE(mol->getAtomWithIdx(1)->hasProp("intProp")); CHECK(mol->getAtomWithIdx(1)->getProp<int>("intProp") == 42); } } TEST_CASE("Github #2086", "[bug, molops]") { SECTION("reported version") { auto mol = "C1CCCC1"_smiles; REQUIRE(mol); MolOps::addHs(*mol); REQUIRE(mol->getNumAtoms() == 15); mol->removeBond(4, 13); MolOps::removeHs(*mol); REQUIRE(mol->getNumAtoms() == 6); } } TEST_CASE("github #299", "[bug, molops, SSSR]"){ SECTION("simplified"){ auto mol = "C13%13%14.C124%18.C25%13%15.C368%17.C4679.C75%10%17.C8%11%14%16.C9%11%12%18.C%10%12%15%16"_smiles; REQUIRE(mol); REQUIRE(mol->getNumAtoms()==9); } SECTION("old example from molopstest"){ auto mol = "C123C45C11C44C55C22C33C14C523"_smiles; REQUIRE(mol); REQUIRE(mol->getNumAtoms()==9); } SECTION("carborane"){ std::unique_ptr<RWMol> mol(SmilesToMol("[B]1234[B]567[B]118[B]229[B]33%10[B]454[B]656[B]711[B]822[C]933[B]%1045[C]6123",0,false)); REQUIRE(mol); CHECK(mol->getNumAtoms()==12); mol->updatePropertyCache(false); MolOps::findSSSR(*mol); REQUIRE(mol->getRingInfo()->isInitialized()); } SECTION("original report from ChEbI"){ std::string pathName = getenv("RDBASE"); pathName += "/Code/GraphMol/test_data/"; std::unique_ptr<RWMol> mol(MolFileToMol(pathName + "ChEBI_50252.mol",false)); REQUIRE(mol); CHECK(mol->getNumAtoms()==80); mol->updatePropertyCache(false); MolOps::findSSSR(*mol); REQUIRE(mol->getRingInfo()->isInitialized()); } } TEST_CASE("github #2224", "[bug, molops, removeHs, query]"){ SECTION("the original report"){ std::string pathName = getenv("RDBASE"); pathName += "/Code/GraphMol/test_data/"; std::unique_ptr<RWMol> mol(MolFileToMol(pathName + "github2224_1.mol")); REQUIRE(mol); REQUIRE(mol->getNumAtoms()==7); } SECTION("basics") { SmilesParserParams ps; ps.removeHs = false; ps.sanitize = true; std::unique_ptr<ROMol> mol(SmilesToMol("C[H]", ps)); REQUIRE(mol); REQUIRE(mol->getNumAtoms()==2); { // The H without a query is removed std::unique_ptr<ROMol> m2(MolOps::removeHs(*mol)); CHECK(m2->getNumAtoms()==1); } { // but if we add a query feature it's not removed RWMol m2(*mol); m2.replaceAtom(1,new QueryAtom(1)); m2.getAtomWithIdx(1)->setAtomicNum(1); MolOps::removeHs(m2); CHECK(m2.getNumAtoms()==2); } } }
32.2
134
0.648625
Mike575
50eb9c8a790c3cdc7a4a284c23365dca8452f292
973
cpp
C++
Problems/IEEEXtreme/IEEEXtreme_11.0/Codes/Full.Pyramid.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/IEEEXtreme/IEEEXtreme_11.0/Codes/Full.Pyramid.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/IEEEXtreme/IEEEXtreme_11.0/Codes/Full.Pyramid.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fi first #define se second #define maxk 17 #define maxn 100003 #define mod 1000000007 using namespace std; typedef pair<int,int> pi; int s; int comb[maxk][maxk]; pi dp[maxn][maxk]; int f( int ind , int step , int rem ) { if( ind == step ) return 1; if( dp[rem][ind].se == step + 1 ) return dp[rem][ind].fi; dp[rem][ind] = pi( 0 , step + 1 ); dp[rem][ind].fi = ( dp[rem][ind].fi + f( ind + 1 , step , rem ) ) % mod; if( comb[step][ind] <= rem ) dp[rem][ind].fi = ( dp[rem][ind].fi + f( ind , step , rem - comb[step][ind] ) ) % mod; return dp[rem][ind].fi; } int main() { for( int i = 0 ; i < maxk ; i++ ) comb[i][0] = 1; for( int i = 1 ; i < maxk ; i++ ) for( int j = 1 ; j <= i ; j++ ) comb[i][j] = ( comb[i-1][j-1] + comb[i-1][j] ) % mod; scanf( "%d" , &s ); int ans = 0; for( int i = 0 ; (1<<i) <= s ; i++ ) ans = ( ans + f( 0 , i , s - (1 << i) ) ) % mod; printf( "%d\n" , ans ); return 0; }
20.702128
88
0.50668
metehkaya
50f527b18788b52c38ea6e11fa240c91a476f68d
2,346
cpp
C++
iOS/Game/GameWindows.cpp
Amazong/Nebula
8b5b0d3dea53b4a9558b6149c84d10564b86cf6d
[ "MIT" ]
null
null
null
iOS/Game/GameWindows.cpp
Amazong/Nebula
8b5b0d3dea53b4a9558b6149c84d10564b86cf6d
[ "MIT" ]
11
2016-07-14T11:55:17.000Z
2016-07-14T12:14:01.000Z
iOS/Game/GameWindows.cpp
Amazong/iOS---Instrument-Outlet-Simulator
8b5b0d3dea53b4a9558b6149c84d10564b86cf6d
[ "MIT" ]
null
null
null
#include "headers\GameWindows.h" #include "headers\Errors.h" int render_splash() { sf::RenderWindow *splash_screen = new sf::RenderWindow(sf::VideoMode(887, 407), "", sf::Style::None); sf::Clock splash_clk; sf::Texture splash_png; if (!(splash_png.loadFromFile("res/png/Splash.png"))) { splash_screen->setVisible(0); return 42; } sf::Sprite splash_sprite; splash_sprite.setTexture(splash_png); while (splash_clk.getElapsedTime().asSeconds() < 4.0f) { splash_screen->clear(sf::Color::Black); splash_screen->draw(splash_sprite); splash_screen->display(); } delete splash_screen; return 0; } int n_words(const std::string & str) { if (str.empty()) return(0); int counter = 0; int size = str.length(); int num = str.find_first_of(' '); if (num == std::string::npos) return(1); while (num != std::string::npos) { counter++; num = str.find_first_of(' ', num + 1); } return(counter + 1); } std::string * get_string_tab(std::string & str, int & size, unsigned int line_size) { if (str.empty()) { size = 1; return(new std::string("")); } if (str.length() <= line_size) { size = 1; return(new std::string(str)); } int words = n_words(str), pos = 0, counter = 0, i = 0; size = str.length(); if (words == 1) { size = 1; return(new std::string(str)); } // edge cases std::string * tab_ptr = new std::string[words]; for (int i = 0, j = 0; i < size; i++) { if (str[i] == ' ') { tab_ptr[j] = str.substr(pos, (i - pos)) + ' '; pos = ++i; counter++; j++; } if (words - counter == 1) tab_ptr[j] = str.substr(pos); } // now tab_ptr[j] has all words of phrase. std::vector<std::string *> fitted_strings; std::string temp = ""; for (int i = 0; i < words; i++) { if (temp.size() + tab_ptr[i].size() > line_size) { fitted_strings.push_back(new std::string(temp)); temp.clear(); temp += tab_ptr[i]; continue; } temp += tab_ptr[i]; } fitted_strings.push_back(new std::string(temp)); delete[] tab_ptr; size = fitted_strings.size(); std::string * str_ptr = new std::string[size]; for (int i = 0; i < size; i++) { str_ptr[i] = *(fitted_strings[i]); delete fitted_strings[i]; } return(str_ptr); } void show_textbox(std::string & str, unsigned int line_size, unsigned int char_size) //NO DOUBLE FUCKING SPACES { }
18.046154
113
0.617221
Amazong
50f5eac597a7a48fdf25f1af7c48233c64a486e6
260
cpp
C++
Version0.2/Kernel/Discretization/preprocessing.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
37
2020-12-09T20:24:36.000Z
2022-02-18T17:19:23.000Z
Version0.2/Kernel/Discretization/preprocessing.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
25
2020-11-25T20:37:33.000Z
2022-02-25T15:53:11.000Z
Version0.2/Kernel/Discretization/preprocessing.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
8
2020-11-30T15:34:06.000Z
2022-01-09T21:06:00.000Z
#ifndef __PREPROCESSING #define __PREPROCESSING #include "../preprocessing/errormsg.cpp" #include "../preprocessing/ioutilities.cpp" #include "../preprocessing/readbinaryfiles.cpp" #ifdef HAVE_CUDA #include "../preprocessing/gpuDeviceInfo.cpp" #endif #endif
21.666667
47
0.788462
glwagner
50f7589a35ef392e993cef7dfd97e16115d1e4be
508
cpp
C++
cpp/utility_make_from_tuple.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/utility_make_from_tuple.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/utility_make_from_tuple.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/utility_make_from_tuple.exe ./cpp/utility_make_from_tuple.cpp && (cd ../_build/cpp/;./utility_make_from_tuple.exe) https://en.cppreference.com/w/cpp/utility/make_from_tuple */ #include <iostream> #include <tuple> struct Foo { Foo(int first, float second, int third) { std::cout << first << ", " << second << ", " << third << "\n"; } }; int main() { auto tuple = std::make_tuple(42, 3.14f, 0); std::make_from_tuple<Foo>(std::move(tuple)); }
28.222222
156
0.635827
rpuntaie
50f96c187b9ce94499cc1b4e6b8e24405bfdfa12
4,365
cxx
C++
STEER/STEERBase/AliDetectorTagCuts.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEERBase/AliDetectorTagCuts.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEERBase/AliDetectorTagCuts.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Author: Panos Christakoglou. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------- // AliDetectorTagCuts class // This is the class to deal with the Detector tag level cuts // Origin: Panos Christakoglou, UOA-CERN, Panos.Christakoglou@cern.ch //----------------------------------------------------------------- class AliLog; #include "AliDetectorTag.h" #include "AliDetectorTagCuts.h" #include "TObjString.h" #include "TString.h" ClassImp(AliDetectorTagCuts) //___________________________________________________________________________ AliDetectorTagCuts::AliDetectorTagCuts() : TObject(), fDetectorsReco(0), fDetectorsDAQ(0), fDetectorsFlag(kFALSE), fDetectorValidityMatch(), fDetectorValidityFlag() { //Default constructor which calls the Reset method. for (int iter = 0; iter<AliDAQ::kHLTId; iter++) { fDetectorValidityMatch[iter] = 0; fDetectorValidityFlag[iter] = 0; } } //___________________________________________________________________________ AliDetectorTagCuts::~AliDetectorTagCuts() { //Defaut destructor. } //___________________________________________________________________________ Bool_t AliDetectorTagCuts::IsAccepted(AliDetectorTag *detTag) const { //Returns true if the event is accepted otherwise false. if (fDetectorsFlag) { Bool_t daqsel = (detTag->GetIntDetectorMaskDAQ() & fDetectorsDAQ) > 0; Bool_t recsel = (detTag->GetIntDetectorMaskReco() & fDetectorsReco) > 0; Bool_t valsel = kTRUE; for (int iter=0; iter<AliDAQ::kHLTId; iter++) { if (fDetectorValidityFlag[iter]) if (!(fDetectorValidityMatch[iter] == detTag->GetDetectorValidityRange(iter))) valsel = kFALSE; } return (daqsel && recsel && valsel); } return true; // if(fDetectorsFlag){ // TString detStr = fDetectors; // TObjArray *activeDetectors = detTag->GetDetectorMask(); // for (Int_t iDet = 0; iDet < activeDetectors->GetEntries(); iDet++) { // TObjString *detectorString = (TObjString *)activeDetectors->At(iDet); // if (!IsSelected(detectorString->GetString(), detStr))return kFALSE; // } // } // return kTRUE; } void AliDetectorTagCuts::SetDetectorValidityValue(TString det, UShort_t val) { // Set Validity requiement for detector Short_t detid = AliDAQ::DetectorID(det.Data()); if (detid >= 0) { fDetectorValidityMatch[detid] = val; fDetectorsFlag = kTRUE; } } //___________________________________________________________________________ // Bool_t AliDetectorTagCuts::IsSelected(TString detName, TString& detectors) const { // //Returns true if the detector is included // if ((detectors.CompareTo("ALL") == 0) || // detectors.BeginsWith("ALL ") || // detectors.EndsWith(" ALL") || // detectors.Contains(" ALL ")) { // detectors = "ALL"; // return kTRUE; // } // // search for the given detector // Bool_t result = kFALSE; // if ((detectors.CompareTo(detName) == 0) || // detectors.BeginsWith(detName+" ") || // detectors.EndsWith(" "+detName) || // detectors.Contains(" "+detName+" ")) { // detectors.ReplaceAll(detName, ""); // result = kTRUE; // } // // clean up the detectors string // while (detectors.Contains(" ")) detectors.ReplaceAll(" ", " "); // while (detectors.BeginsWith(" ")) detectors.Remove(0, 1); // while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1); // return result; // }
36.680672
85
0.6252
AllaMaevskaya
50ff1bc5ed5b30251e2a0c6b4e0289112d84e0e2
6,165
hpp
C++
src/morda/widgets/group/list.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/widgets/group/list.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/widgets/group/list.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
18
2016-11-22T14:41:37.000Z
2020-04-22T18:16:10.000Z
/* morda - GUI framework Copyright (C) 2012-2021 Ivan Gagis <igagis@gmail.com> 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 3 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/>. */ /* ================ LICENSE END ================ */ #pragma once #include "../widget.hpp" #include "../container.hpp" #include "../base/oriented_widget.hpp" namespace morda{ /** * @brief Scrollable list widget. * This is a base class for vertical and horizontal lists. */ class list_widget : // NOTE: order of virtual public and private declarations here matters for clang due to some bug, // see http://stackoverflow.com/questions/42427145/clang-cannot-cast-to-private-base-while-there-is-a-public-virtual-inheritance virtual public widget, public container, protected oriented_widget { // index of the first item added to container as child size_t added_index = size_t(-1); size_t pos_index = 0; // index of the first visible item // offset in pixels of the first visible item. // the value is positive, tough the item is biased towards negative coordinate values. real pos_offset = real(0); size_t num_tail_items = 0; // zero means that number of tail items has to be recomputed size_t first_tail_item_index = 0; real first_tail_item_offset = real(0); real first_tail_item_dim = real(0); protected: list_widget(std::shared_ptr<morda::context> c, const treeml::forest& desc, bool vertical); public: list_widget(const list_widget&) = delete; list_widget& operator=(const list_widget&) = delete; /** * @brief list items provider. * User should subclass this class to provide items to the list. */ class provider : virtual public utki::shared{ friend class list_widget; list_widget* parent_list = nullptr; protected: provider(){} public: /** * @brief Get parent list widget. * @return list widget which owns the provider, in case the provider is set to some list widget. * @return nullptr in case the provider is not set to any list widget. */ list_widget* get_list()noexcept{ return this->parent_list; } /** * @brief Get total number of items in the list. * @return Number of items in the list. */ virtual size_t count()const noexcept = 0; /** * @brief Get widget for item. * @param index - index of item to get widget for. * @return widget for the requested item. */ virtual std::shared_ptr<widget> get_widget(size_t index) = 0; /** * @brief Recycle widget of item. * @param index - index of item to recycle widget of. * @param w - widget to recycle. */ virtual void recycle(size_t index, std::shared_ptr<widget> w){} void notify_data_set_change(); }; void set_provider(std::shared_ptr<provider> item_provider = nullptr); void lay_out()override; morda::vector2 measure(const morda::vector2& quotum) const override; /** * @brief Set scroll position as factor from [0:1]. * @param factor - factor of the scroll position to set. */ void set_scroll_factor(real factor); /** * @brief Get scroll factor. * @return Current scroll position as factor from [0:1]. */ real get_scroll_factor()const noexcept; /** * @brief Get scroll band. * Returns scroll band as a fraction of 1. This is basically the number of visible elements divided by total number of elements in the list. * @return scroll band. */ real get_scroll_band()const noexcept; /** * @brief Get index of the first visible item. * @return index of the first visible item. */ size_t get_pos_index()const noexcept{ return this->pos_index; } /** * @brief Get offset of the first visible item. * The value is positive, though the item coordinate is <= 0. * @return offset in pixels of the first visible item. */ real get_pos_offset()const noexcept{ return this->pos_offset; } /** * @brief Scroll the list by given number of pixels. * @param delta - number of pixels to scroll, can be positive or negative. */ void scroll_by(real delta); /** * @brief Data set changed signal. * Emitted when list widget contents have actually been updated due to change in provider's model data set. */ std::function<void(list_widget&)> data_set_change_handler; /** * @brief Scroll position changed signal. * Emitted when list's scroll position has changed. */ std::function<void(list_widget&)> scroll_change_handler; private: std::shared_ptr<provider> item_provider; void update_children_list(); // returns true if it was the last visible widget bool arrange_widget( std::shared_ptr<widget>& w, real& pos, bool add, size_t index, widget_list::const_iterator& insertBefore ); void update_tail_items_info(); void handle_data_set_changed(); void notify_scroll_pos_changed(); void notify_scroll_pos_changed(size_t old_index, real old_offset); real calc_num_visible_items()const noexcept; }; /** * @brief Horizontal list widget. * Panorama list widget. * From GUI script it can be instantiated as "pan_list". */ class pan_list : public list_widget{ public: pan_list(std::shared_ptr<morda::context> c, const treeml::forest& desc) : widget(std::move(c), desc), list_widget(this->context, desc, false) {} pan_list(const pan_list&) = delete; pan_list& operator=(const pan_list&) = delete; }; /** * @brief Vertical list widget. * From GUI script it can be instantiated as "list". */ class list : public list_widget{ public: list(std::shared_ptr<morda::context> c, const treeml::forest& desc) : widget(std::move(c), desc), list_widget(this->context, desc, true) {} list(const list&) = delete; list& operator=(const list&) = delete; }; }
28.022727
144
0.710949
igagis
dd00c037105c4c257d0293e8d5c4d7cc9b5180d3
1,415
cpp
C++
libs/settings/src/help.cpp
robertdickson/ledger
fd9ba1a3fb2ccbb212561695ebb745747a5402b4
[ "Apache-2.0" ]
96
2018-08-23T16:49:05.000Z
2021-11-25T00:47:16.000Z
libs/settings/src/help.cpp
robertdickson/ledger
fd9ba1a3fb2ccbb212561695ebb745747a5402b4
[ "Apache-2.0" ]
1,011
2018-08-17T12:25:21.000Z
2021-11-18T09:30:19.000Z
libs/settings/src/help.cpp
robertdickson/ledger
fd9ba1a3fb2ccbb212561695ebb745747a5402b4
[ "Apache-2.0" ]
65
2018-08-20T20:05:40.000Z
2022-02-26T23:54:35.000Z
//------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // 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 "settings/help.hpp" #include "settings/setting_collection.hpp" namespace { constexpr char const *NAME = "help"; constexpr char const *DESCRIPTION = "Print this help and exit"; } // namespace namespace fetch { namespace settings { Help::Help(SettingCollection &reg) : SettingBase(reg, NAME, DESCRIPTION) , reg_(reg) {} void Help::FromStream(std::istream & /*stream*/) {} void Help::ToStream(std::ostream & /*stream*/) const {} bool Help::TerminateNow() const { reg_.DisplayHelp(); return true; } std::string Help::envname() const { return {}; } } // namespace settings } // namespace fetch
25.267857
80
0.619081
robertdickson
dd033758b6c3f0807ce81c62ef206680f2338422
1,930
hpp
C++
experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Gameplay2D/Transform.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog.Experimental/Gameplay/detail/ComponentTypeIndex.hpp" #include "Pomdog.Experimental/Gameplay/Component.hpp" #include "Pomdog/Basic/Export.hpp" #include "Pomdog/Math/Quaternion.hpp" #include "Pomdog/Math/Radian.hpp" #include "Pomdog/Math/Vector2.hpp" #include "Pomdog/Math/Vector3.hpp" namespace Pomdog { class POMDOG_EXPORT Transform final : public Component { public: Transform() noexcept; Vector2 GetPosition2D() const noexcept; void SetPosition2D(const Vector2& positionIn) noexcept; const Vector3& GetPosition() const noexcept; void SetPosition(const Vector3& positionIn) noexcept; void SetPositionX(float x) noexcept; void SetPositionY(float y) noexcept; void SetPositionZ(float z) noexcept; const Vector3& GetScale() const noexcept; void SetScale(const Vector3& scaleIn) noexcept; void SetScale(float scaleIn) noexcept; Vector2 GetScale2D() const noexcept; Radian<float> GetRotation2D() const noexcept; Quaternion GetRotation() const noexcept; void SetRotation(const Quaternion& rotationIn) noexcept; void SetRotationX(const Radian<float>& angle) noexcept; void SetRotationY(const Radian<float>& angle) noexcept; void SetRotationZ(const Radian<float>& angle) noexcept; void Rotate(const Vector3& eulerAngles); void Rotate2D(const Radian<float>& rotationZ); Matrix4x4 GetTransformMatrix() const noexcept; private: Vector3 position; Vector3 scale; Quaternion rotation; }; template <> struct ComponentTypeDeclaration<Transform> final { static std::uint8_t GetTypeIndex(); }; template <> class ComponentCreator<Transform> final : public ComponentCreatorBase { public: std::shared_ptr<Component> CreateComponent() override; std::uint8_t GetComponentType() override; }; } // namespace Pomdog
24.43038
71
0.74715
ValtoForks
dd03afbf58d3d03eb05365cd7623fa1cef1ac089
1,766
cpp
C++
bachelor/computer-graphics/Les1/CG1_EdgeTableRow.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
bachelor/computer-graphics/Les1/CG1_EdgeTableRow.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
bachelor/computer-graphics/Les1/CG1_EdgeTableRow.cpp
Brent-rb/University
caae9c7d8e44bf7589865517f786529b1f171059
[ "MIT" ]
null
null
null
// CG1_EdgeTableRow.cpp: implementation of the CG1_EdgeTableRow class. // ////////////////////////////////////////////////////////////////////// #include "CG1_EdgeTableRow.h" #include <stdio.h> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------- CG1_EdgeTableRow::CG1_EdgeTableRow() { } //-------------------------------------------------------------------- CG1_EdgeTableRow::~CG1_EdgeTableRow() { CG1_Edge *CurrentEdge = 0; for(EdgeIterator = Edges.begin(); EdgeIterator != Edges.end(); EdgeIterator++) { CurrentEdge = *EdgeIterator; delete CurrentEdge; } Edges.erase(Edges.begin(), Edges.end()); } //-------------------------------------------------------------------- void CG1_EdgeTableRow::AddEdge(CG1_Edge* Newedge) { bool inserted = false; CG1_Edge* CurrentEdge; for(EdgeIterator = Edges.begin(); EdgeIterator != Edges.end() && !inserted; EdgeIterator++) { CurrentEdge = *EdgeIterator; if(CurrentEdge->x_down > Newedge->x_down) { Edges.insert(EdgeIterator, Newedge); inserted = true; } } if(!inserted) { Edges.push_back(Newedge); } } //-------------------------------------------------------------------- void CG1_EdgeTableRow::WriteData(int index) { if(Edges.size() > 0) { printf("%d: ", index); CG1_Edge* CurrentEdge; for(EdgeIterator = Edges.begin(); EdgeIterator != Edges.end(); EdgeIterator++) { CurrentEdge = *EdgeIterator; printf(" x = %d ", CurrentEdge->x_down); } printf("\n"); } else { printf("%d: empty\n", index); } }
24.527778
93
0.460362
Brent-rb
dd04525b5224e62126bbb901f63b44d59724b3a2
12,579
cpp
C++
tests/Replication2/ReplicatedState/MaintenanceTest.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
tests/Replication2/ReplicatedState/MaintenanceTest.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
tests/Replication2/ReplicatedState/MaintenanceTest.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Lars Maier //////////////////////////////////////////////////////////////////////////////// #include <gtest/gtest.h> #include "Cluster/Maintenance.h" #include "Replication2/ReplicatedLog/LogStatus.h" #include "Replication2/ReplicatedState/StateStatus.h" #include "Basics/StringUtils.h" using namespace arangodb; using namespace arangodb::maintenance; using namespace arangodb::replication2; struct ReplicatedStateMaintenanceTest : ::testing::Test { MaintenanceFeature::errors_t errors; containers::FlatHashSet<DatabaseID> dirtyset; bool callNotify = false; std::vector<std::shared_ptr<ActionDescription>> actions; DatabaseID const database{"mydb"}; ParticipantId const serverId{"MyServerId"}; LogId const logId{12}; }; namespace { template<typename T> auto decodeFromString(std::string_view src) -> std::optional<T> { auto buffer = arangodb::basics::StringUtils::decodeBase64(src); auto slice = VPackSlice(reinterpret_cast<uint8_t const*>(buffer.c_str())); if (!slice.isNone()) { return T::fromVelocyPack(slice); } return std::nullopt; } } // namespace TEST_F(ReplicatedStateMaintenanceTest, create_state_test_without_local_log) { /* * Test that the maintenance waits for the replicated log to be present first * before creating a replicated state. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{}; auto const localStates = ReplicatedStateStatusMap{}; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {}}, {"otherServer", {}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 0); } TEST_F(ReplicatedStateMaintenanceTest, create_state_test_with_local_log) { /* * Test that the maintenance create an action to create the replicated state. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{}; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 1); auto const& action = actions.front(); EXPECT_EQ(action->get(NAME), UPDATE_REPLICATED_STATE); EXPECT_EQ(action->get(DATABASE), database); EXPECT_EQ(action->get(REPLICATED_LOG_ID), to_string(logId)); EXPECT_TRUE(dirtyset.find(database) != dirtyset.end()); EXPECT_TRUE(callNotify); auto current = decodeFromString<replicated_state::agency::Current>( action->get(REPLICATED_STATE_CURRENT)); EXPECT_EQ(current, std::nullopt); } TEST_F(ReplicatedStateMaintenanceTest, create_state_test_with_local_log_and_current_entry) { /* * Test that the maintenance creates a replicated state and forwards the * current entry into the action. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{}; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{{ logId, replicated_state::agency::Current{ .participants = { {serverId, {.generation = replicated_state::StateGeneration{0}, .snapshot = {}}}, }, .supervision = {}}, }}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 1); auto const& action = actions.front(); EXPECT_EQ(action->get(NAME), UPDATE_REPLICATED_STATE); EXPECT_EQ(action->get(DATABASE), database); EXPECT_EQ(action->get(REPLICATED_LOG_ID), to_string(logId)); EXPECT_TRUE(dirtyset.find(database) != dirtyset.end()); EXPECT_TRUE(callNotify); auto current = decodeFromString<replicated_state::agency::Current>( action->get(REPLICATED_STATE_CURRENT)); EXPECT_EQ(current, currentStates.at(logId)); } TEST_F(ReplicatedStateMaintenanceTest, do_nothing_if_stable) { /* * Check that if the configuration is stable, nothing happens. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{ {logId, {{replicated_state::UnconfiguredStatus{ .generation = replicated_state::StateGeneration{1}, .snapshot = {}}}}}, }; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{{ logId, replicated_state::agency::Current{ .participants = { {serverId, {.generation = replicated_state::StateGeneration{0}, .snapshot = {}}}, }, .supervision = {}}, }}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 0); } TEST_F(ReplicatedStateMaintenanceTest, check_resync_if_generation_changes) { /* * Check that the maintenance triggers a resync if the generation changes. */ auto const participantsConfig = ParticipantsConfig{.generation = 1, .participants = { {serverId, {}}, {"otherServer", {}}, }}; auto const localLogs = ReplicatedLogStatusMap{ {logId, replicated_log::QuickLogStatus{ replicated_log::ParticipantRole::kUnconfigured}}, }; auto const localStates = ReplicatedStateStatusMap{ {logId, {{replicated_state::UnconfiguredStatus{ .generation = replicated_state::StateGeneration{0}, .snapshot = {}}}}}, }; auto const planLogs = ReplicatedLogSpecMap{ {logId, agency::LogPlanSpecification{logId, std::nullopt, participantsConfig}}, }; auto const planStates = ReplicatedStateSpecMap{ {logId, replicated_state::agency::Plan{ .id = logId, .generation = replicated_state::StateGeneration{1}, .properties = {}, .participants = { {serverId, {.generation = replicated_state::StateGeneration{1}}}, {"otherServer", {.generation = replicated_state::StateGeneration{1}}}, }}}}; auto const currentStates = ReplicatedStateCurrentMap{{ logId, replicated_state::agency::Current{ .participants = { {serverId, {.generation = replicated_state::StateGeneration{0}, .snapshot = {}}}, }, .supervision = {}}, }}; maintenance::diffReplicatedStates(database, localLogs, localStates, planLogs, planStates, currentStates, serverId, errors, dirtyset, callNotify, actions); ASSERT_EQ(actions.size(), 1); auto const& action = actions.front(); EXPECT_EQ(action->get(NAME), UPDATE_REPLICATED_STATE); EXPECT_EQ(action->get(DATABASE), database); EXPECT_EQ(action->get(REPLICATED_LOG_ID), to_string(logId)); EXPECT_TRUE(dirtyset.find(database) != dirtyset.end()); EXPECT_TRUE(callNotify); auto current = decodeFromString<replicated_state::agency::Current>( action->get(REPLICATED_STATE_CURRENT)); EXPECT_EQ(current, std::nullopt); // Current not needed. }
40.317308
80
0.581922
LLcat1217
dd04eeadcb3d3eec69af42fe91c490728494de2b
3,977
cpp
C++
ch08/8.exercise.05.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
51
2017-03-24T06:08:11.000Z
2022-03-18T00:28:14.000Z
ch08/8.exercise.05.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
1
2019-06-23T07:33:42.000Z
2019-12-12T13:14:04.000Z
ch08/8.exercise.05.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
25
2017-04-07T13:22:45.000Z
2022-03-18T00:28:15.000Z
// 8.exercise.05.cpp // // Write two functions that reverse the order of element in a vector<int>. // For example, 1, 3, 5, 6, 9 becomes 9, 7, 5, 3, 1. The first reverse // function should produce a new vector with the reverse sequence, leaving the // original vector unchanged. The other reverse function should reverse the // elements of its vector without using any other vectors (hint: swap). // // COMMENTS // // The fibonacci() and print() functions comes in handy to test the proposed // functions on this exercise. // // The first function will be named reverse_cr() as parameter will be passed // by const-reference. The other one will be reverse_r() as parameter will be // passed by reference. For this one we use swap(), as the hint says, but we // will no implement it since its available on the standard library, as // pointed out in §8.5.5. // // We must check for odd and even size sequences. #include "std_lib_facilities.h" void print(const string& label, const vector<int>& data) // Only read arguments, so it safe to pass them by const-reference { cout << label << ": { "; for (int i : data) cout << i << ' '; cout << "}\n"; } int check_add(int a, int b) // Adds two integers performing overflow control to avoid undefined behavior. // (Search for INT32-C on https://www.securecoding.cert.org) { if (((b > 0) && (a > (numeric_limits<int>::max() - b))) || ((b < 0) && (a < (numeric_limits<int>::min() - b)))) error("check_add(): integer add overflows."); else return a+b; } void fibonacci(int x, int y, vector<int>& v, int n) // Generates a Fibonacci sequence of n values into v, starting with values x // and y (integers passed by value, and we are modifying v, so it is passed by // reference). // Preconditions: // Vector must be empty // To simplify, n must be equal or greater than two. { if (v.size() != 0) error("fibonacci(): Non empty vector passed as argument."); if (n < 2) error("fibonacci(): n must be al least 2."); v.push_back(x); v.push_back(y); // Add a try-catch block to catch overflow and let the program continue try { for (int i = 2; i < n; ++i) v.push_back(check_add(v[i-2],v[i-1])); } catch(exception& e){ cerr << e.what() << '\n'; } } vector<int> reverse_cr(const vector<int>& v) // Returns a new vector with vector v elements in reverse order { vector<int> r; for (size_t i = v.size(); i > 0; --i) r.push_back(v[i-1]); return r; } void reverse_r(vector<int>& v) // Reverses order of elements of vector v { size_t limit{v.size()/2}; // Only traverse half of the elements. // This way, if we have an odd number of elements // the division ignores the middle one. size_t last_idx{v.size()-1}; // Last element index. To avoid recalc. for (size_t i = 0; i < limit; ++i) swap(v[i], v[last_idx-i]); } int main() try { // Test a vector with even element number vector<int> e1; fibonacci(1, 2, e1, 8); // Generate a vector with even element number print("Original even ", e1); vector<int> e2{reverse_cr(e1)}; // New vector reversed print("Reverse even by const-ref", e2); reverse_r(e1); // Reverse original vector print("Reverse even by ref ", e1); // Test a vector with odd element number vector<int> o1; fibonacci(1, 2, o1, 7); // Generate a vector with odd element number print("Original odd ", o1); vector<int> o2{reverse_cr(o1)}; // New vector reversed print("Reverse odd by const-ref ", o2); reverse_r(o1); // Reverse original vector print("Reverse odd by ref ", o1); return 0; } catch(exception& e) { cerr << e.what() << '\n'; return 1; } catch(...) { cerr << "Unknwon exception!!\n"; return 2; }
31.816
81
0.608499
0p3r4t4
dd050b40b3689ecaa72f8691d1d6f53df4276d02
274
cpp
C++
source/shared_traits.cpp
phikaczu/logging
c926d9ac72208ae10364adb368e9b39f0c43cbdc
[ "MIT" ]
null
null
null
source/shared_traits.cpp
phikaczu/logging
c926d9ac72208ae10364adb368e9b39f0c43cbdc
[ "MIT" ]
null
null
null
source/shared_traits.cpp
phikaczu/logging
c926d9ac72208ae10364adb368e9b39f0c43cbdc
[ "MIT" ]
null
null
null
#include "shared_traits.h" #include<cassert> using namespace logs2::SharedTraits; AssertCheck::AssertCheck() : _threadId{ std::this_thread::get_id() } { } void AssertCheck::isSameThread() const { assert(std::this_thread::get_id() == _threadId); }
17.125
53
0.671533
phikaczu
dd08360f1d9633daaf49c3bce9979d7835eca5e8
6,324
cpp
C++
core/src/zxing/qrcode/decoder/BitMatrixParser.cpp
camposm/tinyzxing
ab156e0c7e0602f0b091a1e0a24afdf670c6373e
[ "Apache-2.0" ]
null
null
null
core/src/zxing/qrcode/decoder/BitMatrixParser.cpp
camposm/tinyzxing
ab156e0c7e0602f0b091a1e0a24afdf670c6373e
[ "Apache-2.0" ]
1
2021-09-27T13:16:08.000Z
2021-09-27T13:16:08.000Z
core/src/zxing/qrcode/decoder/BitMatrixParser.cpp
camposm/tinyzxing
ab156e0c7e0602f0b091a1e0a24afdf670c6373e
[ "Apache-2.0" ]
null
null
null
/* * BitMatrixParser.cpp * zxing * * Created by Christian Brunschen on 20/05/2008. * Copyright 2008 ZXing 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 <zxing/qrcode/decoder/BitMatrixParser.h> #include <zxing/qrcode/decoder/DataMask.h> namespace zxing { namespace qrcode { int BitMatrixParser::copyBit(size_t x, size_t y, int versionBits) { return bitMatrix_.get(x, y) ? (versionBits << 1) | 0x1 : versionBits << 1; } BitMatrixParser::BitMatrixParser (sampled_grid_t& bitMatrix) : bitMatrix_(bitMatrix), found_error(false), parsedVersion_(0), parsedFormatInfo_() { size_t dimension = bitMatrix.getHeight(); if ((dimension < 21) || (dimension & 0x03) != 1) { found_error = true; } } std::optional<FormatInformation> BitMatrixParser::readFormatInformation() { if (parsedFormatInfo_) { return parsedFormatInfo_; } // Read top-left format info bits int formatInfoBits1 = 0; for (int i = 0; i < 6; i++) { formatInfoBits1 = copyBit(i, 8, formatInfoBits1); } // .. and skip a bit in the timing pattern ... formatInfoBits1 = copyBit(7, 8, formatInfoBits1); formatInfoBits1 = copyBit(8, 8, formatInfoBits1); formatInfoBits1 = copyBit(8, 7, formatInfoBits1); // .. and skip a bit in the timing pattern ... for (int j = 5; j >= 0; j--) { formatInfoBits1 = copyBit(8, j, formatInfoBits1); } // Read the top-right/bottom-left pattern int dimension = bitMatrix_.getHeight(); int formatInfoBits2 = 0; int jMin = dimension - 7; for (int j = dimension - 1; j >= jMin; j--) { formatInfoBits2 = copyBit(8, j, formatInfoBits2); } for (int i = dimension - 8; i < dimension; i++) { formatInfoBits2 = copyBit(i, 8, formatInfoBits2); } return FormatInformation::decodeFormatInformation(formatInfoBits1,formatInfoBits2); } const Version* BitMatrixParser::readVersion() { if (parsedVersion_ != nullptr) { return parsedVersion_; } int dimension = bitMatrix_.getHeight(); int provisionalVersion = (dimension - 17) >> 2; if (provisionalVersion <= 6) { return Version::getVersionForNumber(provisionalVersion); } // Read top-right version info: 3 wide by 6 tall int versionBits = 0; for (int y = 5; y >= 0; y--) { int xMin = dimension - 11; for (int x = dimension - 9; x >= xMin; x--) { versionBits = copyBit(x, y, versionBits); } } parsedVersion_ = Version::decodeVersionInformation(versionBits); if (parsedVersion_ != nullptr && parsedVersion_->getDimensionForVersion() == dimension) { return parsedVersion_; } // Hmm, failed. Try bottom left: 6 wide by 3 tall versionBits = 0; for (int x = 5; x >= 0; x--) { int yMin = dimension - 11; for (int y = dimension - 9; y >= yMin; y--) { versionBits = copyBit(x, y, versionBits); } } parsedVersion_ = Version::decodeVersionInformation(versionBits); if (parsedVersion_ != nullptr && parsedVersion_->getDimensionForVersion() == dimension) { return parsedVersion_; } return nullptr; } codewords_t BitMatrixParser::readCodewords() { codewords_t result = {0}; auto formatInfo = readFormatInformation(); const Version* version = readVersion(); if (version == nullptr || !formatInfo) { return result; } // Get the data mask for the format used in this QR Code. This will exclude // some bits from reading as we wind through the bit matrix. auto dataMask = DataMask::select((int) formatInfo.value().getDataMask()); if (!dataMask) { return result; } int dimension = bitMatrix_.getHeight(); dataMask.value().unmaskBitMatrix(bitMatrix_, dimension); bitmatrix_t<config::MaxGridSize, config::MaxGridSize> functionPattern(dimension); version->buildFunctionPattern(functionPattern); bool readingUp = true; int resultOffset = 0; int currentByte = 0; int bitsRead = 0; // Read columns in pairs, from right to left for (int x = dimension - 1; x > 0; x -= 2) { if (x == 6) { // Skip whole column with vertical alignment pattern; // saves time and makes the other code proceed more cleanly x--; } // Read alternatingly from bottom to top then top to bottom for (int counter = 0; counter < dimension; counter++) { int y = readingUp ? dimension - 1 - counter : counter; for (int col = 0; col < 2; col++) { // Ignore bits covered by the function pattern if (!functionPattern.get(x - col, y)) { // Read a bit bitsRead++; currentByte <<= 1; if (bitMatrix_.get(x - col, y)) { currentByte |= 1; } // If we've made a whole byte, save it off if (bitsRead == 8) { result[resultOffset++] = (char)currentByte; bitsRead = 0; currentByte = 0; } } } } readingUp = !readingUp; // switch directions } if (resultOffset != version->getTotalCodewords()) { for (auto n = 0; n < result.size(); ++n) { result[n] = 0; } } return result; } } // ns qrcode } // ns zxing
28.232143
92
0.576534
camposm
dd085a10754d853dfa6fc05db45c3c43bdb39bf4
155
hpp
C++
src/utils/assert.hpp
JacobDomagala/Shady
cdb8b07a83d179f58bd70c42957e987ddd201eb4
[ "MIT" ]
2
2020-10-27T00:16:18.000Z
2021-03-29T12:59:48.000Z
src/utils/assert.hpp
JacobDomagala/DEngine
cdb8b07a83d179f58bd70c42957e987ddd201eb4
[ "MIT" ]
58
2020-08-23T21:38:21.000Z
2021-08-05T16:12:31.000Z
src/utils/assert.hpp
JacobDomagala/Shady
cdb8b07a83d179f58bd70c42957e987ddd201eb4
[ "MIT" ]
null
null
null
#pragma once #include <string_view> namespace shady::utils { void Assert(bool assertion, std::string_view logMsg); } // namespace shady::utils
15.5
49
0.703226
JacobDomagala
dd085d6124666640274f9c20f98790de6a10b19f
2,554
cpp
C++
examples/tumor/tumor_main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
7
2018-01-19T00:19:19.000Z
2021-06-22T00:53:00.000Z
examples/tumor/tumor_main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
66
2021-06-22T22:44:21.000Z
2022-03-16T15:18:00.000Z
examples/tumor/tumor_main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
6
2017-04-13T19:42:27.000Z
2022-03-26T18:46:24.000Z
// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com> // SPDX-License-Identifier: MIT #include "ads/simulation.hpp" #include "tumor.hpp" #include "vasculature.hpp" // clang-tidy 12 complains about deleted default constructor not // initializing some members // // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init) struct sim_params { int p; // 2 int elems; // 80 ads::timesteps_config steps; // 10000, 0.1 int plot_every; tumor::params tumor_params; tumor::vasc::config vasc_config; }; sim_params parse_params(char* args[], int idx) { using std::atof; using std::atoi; auto next = [&]() { return args[idx++]; }; auto next_int = [&]() { return atoi(next()); }; auto next_float = [&]() { return atof(next()); }; int p = next_int(); int elems = next_int(); int nsteps = next_int(); double dt = next_float(); int plot_every = next_int(); // tumor parameters tumor::params tumor; tumor.tau_b = next_float(); tumor.o_prol_TC = next_float(); tumor.o_death_TC = next_float(); tumor.t_prol_TC = next_float(); tumor.t_death_TC = next_float(); tumor.P_b = next_float(); tumor.r_b = next_float(); tumor.beta_m = next_float(); tumor.gamma_a = next_float(); tumor.chi_aA = next_float(); tumor.gamma_oA = next_float(); tumor.diff_c = next_float(); tumor.cons_c = next_float(); // 3D only tumor.alpha_0 = next_float(); tumor.gamma_T = next_float(); tumor.alpha_1 = next_float(); // Vasculature parameters tumor::vasc::config vasc; vasc.init_stability = next_float(); vasc.degeneration = next_float(); vasc.t_ec_sprout = next_float(); vasc.segment_length = next_float(); vasc.t_ec_collapse = next_float(); vasc.c_min = next_float(); // 2D only vasc.t_ec_migr = next_float(); // 3D only vasc.r_sprout = next_float(); vasc.r_max = next_float(); vasc.t_ec_switch = next_float(); vasc.c_switch = next_float(); vasc.dilatation = next_float(); return {p, elems, {nsteps, dt}, plot_every, tumor, vasc}; } int main(int /*argc*/, char* argv[]) { sim_params sp = parse_params(argv, 1); ads::dim_config dim{sp.p, sp.elems, 0, 3000.0}; int ders = 1; ads::config_2d c{dim, dim, sp.steps, ders}; tumor::vasc::random_vasculature rand_vasc{sp.vasc_config, 0}; tumor::tumor_2d sim{c, sp.tumor_params, sp.plot_every, rand_vasc()}; sim.run(); }
26.884211
76
0.632733
Pan-Maciek
dd0b9b7c456ca5ce3c9b526dde6e385123c9401a
1,012
cpp
C++
src/hdfs_common.cpp
ZEMUSHKA/pydoop
e3d3378ae9921561f6c600c79364c2ad42ec206d
[ "Apache-2.0" ]
1
2017-11-16T02:13:15.000Z
2017-11-16T02:13:15.000Z
src/hdfs_common.cpp
ZEMUSHKA/pydoop
e3d3378ae9921561f6c600c79364c2ad42ec206d
[ "Apache-2.0" ]
null
null
null
src/hdfs_common.cpp
ZEMUSHKA/pydoop
e3d3378ae9921561f6c600c79364c2ad42ec206d
[ "Apache-2.0" ]
null
null
null
// BEGIN_COPYRIGHT // // Copyright 2009-2014 CRS4. // // 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. // // END_COPYRIGHT #include "hdfs_common.hpp" void hdfs_exception_translator(hdfs_exception const& x) { PyErr_SetString(PyExc_IOError, x.what()); } //++++++++++++++++++++++++++++++// // Exporting class definitions. // //++++++++++++++++++++++++++++++// using namespace boost::python; void export_hdfs_common() { register_exception_translator<hdfs_exception>(hdfs_exception_translator); }
28.111111
78
0.699605
ZEMUSHKA
dd0eb99be4447e58a8bfd4d6efe3a0f03c41d8ff
26,469
cpp
C++
libraries/graphic/context.cpp
Max1412/vgraphics
852141a63b24c975f0ab59d1d4517ea4dc64e3a5
[ "CC-BY-4.0" ]
1
2021-12-09T14:24:04.000Z
2021-12-09T14:24:04.000Z
libraries/graphic/context.cpp
Max1412/vgraphics
852141a63b24c975f0ab59d1d4517ea4dc64e3a5
[ "CC-BY-4.0" ]
null
null
null
libraries/graphic/context.cpp
Max1412/vgraphics
852141a63b24c975f0ab59d1d4517ea4dc64e3a5
[ "CC-BY-4.0" ]
null
null
null
#include <set> #define GLFW_INCLUDE_VULKAN #include "Context.h" #include "imgui/imgui_impl_vulkan.h" #include "imgui/imgui_impl_glfw.h" #include "spdlog/sinks/stdout_color_sinks.h" namespace help { VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pCallback) { auto func = reinterpret_cast<PFN_vkCreateDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT")); if (func != nullptr) { return func(instance, pCreateInfo, pAllocator, pCallback); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT callback, const VkAllocationCallbacks* pAllocator) { auto func = reinterpret_cast<PFN_vkDestroyDebugUtilsMessengerEXT>(vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT")); if (func != nullptr) { func(instance, callback, pAllocator); } } } //todo remove this when the SDK update happened VkResult vkCreateAccelerationStructureNV(VkDevice device, const VkAccelerationStructureCreateInfoNV* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkAccelerationStructureNV* pAccelerationStructure) { auto func = reinterpret_cast<PFN_vkCreateAccelerationStructureNV>(vkGetDeviceProcAddr(device, "vkCreateAccelerationStructureNV")); if (func != nullptr) { return func(device, pCreateInfo, pAllocator, pAccelerationStructure); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } void vkDestroyAccelerationStructureNV(VkDevice device, VkAccelerationStructureNV accelerationStructure, const VkAllocationCallbacks* pAllocator) { auto func = reinterpret_cast<PFN_vkDestroyAccelerationStructureNV>(vkGetDeviceProcAddr(device, "vkDestroyAccelerationStructureNV")); if (func != nullptr) { return func(device, accelerationStructure, pAllocator); } } void vkGetAccelerationStructureMemoryRequirementsNV(VkDevice device, const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo, VkMemoryRequirements2KHR* pMemoryRequirements) { auto func = reinterpret_cast<PFN_vkGetAccelerationStructureMemoryRequirementsNV>(vkGetDeviceProcAddr(device, "vkGetAccelerationStructureMemoryRequirementsNV")); if (func != nullptr) { return func(device, pInfo, pMemoryRequirements); } } VkResult vkBindAccelerationStructureMemoryNV(VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV* pBindInfos) { auto func = reinterpret_cast<PFN_vkBindAccelerationStructureMemoryNV>(vkGetDeviceProcAddr(device, "vkBindAccelerationStructureMemoryNV")); if (func != nullptr) { return func(device, bindInfoCount, pBindInfos); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } VkResult vkGetAccelerationStructureHandleNV( VkDevice device, VkAccelerationStructureNV accelerationStructure, size_t dataSize, void* pData) { auto func = reinterpret_cast<PFN_vkGetAccelerationStructureHandleNV>(vkGetDeviceProcAddr(device, "vkGetAccelerationStructureHandleNV")); if (func != nullptr) { return func(device, accelerationStructure, dataSize, pData); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } VkResult vkCreateRayTracingPipelinesNV(VkDevice device, VkPipelineCache pipelineCache, uint32_t createInfoCount, const VkRayTracingPipelineCreateInfoNV* pCreateInfos, const VkAllocationCallbacks* pAllocator, VkPipeline* pPipelines) { auto func = reinterpret_cast<PFN_vkCreateRayTracingPipelinesNV>(vkGetDeviceProcAddr(device, "vkCreateRayTracingPipelinesNV")); if (func != nullptr) { return func(device, pipelineCache, createInfoCount, pCreateInfos, pAllocator, pPipelines); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } VkResult vkGetRayTracingShaderGroupHandlesNV(VkDevice device, VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void* pData) { auto func = reinterpret_cast<PFN_vkGetRayTracingShaderGroupHandlesNV>(vkGetDeviceProcAddr(device, "vkGetRayTracingShaderGroupHandlesNV")); if (func != nullptr) { return func(device, pipeline, firstGroup, groupCount, dataSize, pData); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } namespace vg { Context::Context(const std::vector<const char*>& requiredDeviceExtensions) : m_requiredDeviceExtensions(requiredDeviceExtensions) { // init logger m_logger = spdlog::stdout_color_mt("standard"); m_logger->info("Logger initialized."); // init rest initWindow(); initVulkan(); initImgui(); } Context::~Context() { cleanupImgui(); vmaDestroyAllocator(m_allocator); for (const auto& imageView : m_swapChainImageViews) { m_device.destroyImageView(imageView); } m_device.destroySwapchainKHR(m_swapchain); m_instance.destroySurfaceKHR(m_surface); m_device.destroy(); help::DestroyDebugUtilsMessengerEXT(m_instance, m_callback, nullptr); m_instance.destroy(); glfwDestroyWindow(m_window); glfwTerminate(); } void Context::initWindow() { glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); //glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); m_window = glfwCreateWindow(m_width, m_height, "Vulkan", nullptr, nullptr); glfwSetWindowUserPointer(m_window, this); glfwSetFramebufferSizeCallback(m_window, framebufferResizeCallback); } void Context::framebufferResizeCallback(GLFWwindow* window, int width, int height) { auto context = reinterpret_cast<Context*>(glfwGetWindowUserPointer(window)); context->m_frameBufferResized = true; } void Context::initVulkan() { createInstance(); setupDebugCallback(); createSurface(); pickPhysicalDevice(); createLogicalDevice(); createAllocator(); createSwapChain(); createImageViews(); } void Context::createAllocator() { VmaAllocatorCreateInfo createInfo = {}; createInfo.device = m_device; createInfo.physicalDevice = m_phsyicalDevice; //createInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; auto result = vmaCreateAllocator(&createInfo, &m_allocator); if (result != VK_SUCCESS) throw std::runtime_error("Failed to create Allocator"); } void Context::createInstance() { if (g_enableValidationLayers && !checkValidationLayerSupport()) { throw std::runtime_error("Validation layers requested, but not available!"); } vk::ApplicationInfo appInfo("Vulkan Test New", 1, "No Engine", 1, VK_API_VERSION_1_1); // glfw + (cond.) debug layer auto requiredExtensions = getRequiredExtensions(); std::vector<const char*> layerNames; if constexpr (g_enableValidationLayers) layerNames = g_validationLayers; vk::InstanceCreateInfo createInfo({}, &appInfo, static_cast<uint32_t>(layerNames.size()), layerNames.data(), static_cast<uint32_t>(requiredExtensions.size()), requiredExtensions.data()); if (vk::createInstance(&createInfo, nullptr, &m_instance) != vk::Result::eSuccess) throw std::runtime_error("Instance could not be created"); // print instance extensions // getAllSupportedExtensions(true); } std::vector<const char*> Context::getRequiredExtensions() { uint32_t glfwExtensionCount = 0; const auto exts = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char*> extensions(exts, exts + glfwExtensionCount); if constexpr (g_enableValidationLayers) extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); return extensions; } std::vector<vk::ExtensionProperties> Context::getAllSupportedExtensions() { return vk::enumerateInstanceExtensionProperties(); } bool Context::checkValidationLayerSupport() const { auto availableLayers = vk::enumerateInstanceLayerProperties(); for (const char* layerName : g_validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } VKAPI_ATTR VkBool32 VKAPI_CALL Context::debugCallback( VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { auto logger = spdlog::get("standard"); // todo log this properly depending on severity & type switch (messageSeverity) { case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT: logger->info("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: logger->info("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: logger->warn("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: logger->critical("Validation layer: {} -- {}", vk::to_string(static_cast<vk::DebugUtilsMessageTypeFlagsEXT>(messageType)), pCallbackData->pMessage); break; case VK_DEBUG_UTILS_MESSAGE_SEVERITY_FLAG_BITS_MAX_ENUM_EXT: break; default: break ; } return VK_FALSE; } void Context::setupDebugCallback() { if constexpr (!g_enableValidationLayers) return; using sevFlags = vk::DebugUtilsMessageSeverityFlagBitsEXT; using typeFlags = vk::DebugUtilsMessageTypeFlagBitsEXT; vk::DebugUtilsMessengerCreateInfoEXT createInfo( {}, sevFlags::eError | sevFlags::eWarning | sevFlags::eVerbose,// | sevFlags::eInfo, typeFlags::eGeneral | typeFlags::ePerformance | typeFlags::eValidation, reinterpret_cast<PFN_vkDebugUtilsMessengerCallbackEXT>(debugCallback) ); if (help::CreateDebugUtilsMessengerEXT(m_instance, reinterpret_cast<VkDebugUtilsMessengerCreateInfoEXT*>(&createInfo), nullptr, reinterpret_cast<VkDebugUtilsMessengerEXT *>(&m_callback)) != VK_SUCCESS) { throw std::runtime_error("failed to set up debug callback!"); } } void Context::pickPhysicalDevice() { // TODO scoring system preferring discrete GPUs auto physDevices = m_instance.enumeratePhysicalDevices(); if (physDevices.empty()) throw std::runtime_error("No physical devices found"); for (const auto& device : physDevices) { if (isDeviceSuitable(device)) { m_phsyicalDevice = device; break; } } if (!m_phsyicalDevice) throw std::runtime_error("No suitable physical device found"); } bool Context::isDeviceSuitable(vk::PhysicalDevice physDevice) { // TODO use actual stuff here auto properties = physDevice.getProperties(); auto features = physDevice.getFeatures(); vk::PhysicalDeviceSubgroupProperties subProps; vk::PhysicalDeviceProperties2 props; props.pNext = &subProps; if(std::find_if(m_requiredDeviceExtensions.begin(), m_requiredDeviceExtensions.end(), [](const char* input){ return (strcmp(input, "VK_NV_ray_tracing") == 0); }) != m_requiredDeviceExtensions.end()) { m_raytracingProperties.emplace(); props.pNext = &m_raytracingProperties.value(); m_raytracingProperties.value().pNext = &subProps; } physDevice.getProperties2(&props); //NVIDIA only? const bool testSubgroups = static_cast<uint32_t>(subProps.supportedStages) & static_cast<uint32_t>(vk::ShaderStageFlagBits::eRaygenNV); // look for a GPU with geometry shader const bool suitable = (properties.deviceType == vk::PhysicalDeviceType::eIntegratedGpu || properties.deviceType == vk::PhysicalDeviceType::eDiscreteGpu) && features.geometryShader; // look for a graphics queue QueueFamilyIndices indices = findQueueFamilies(physDevice); // look if the wanted extensions are supported const bool extensionSupport = checkDeviceExtensionSupport(physDevice); // look for swapchain support bool swapChainAdequate = false; if (extensionSupport) { SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physDevice); swapChainAdequate = !swapChainSupport.m_formats.empty() && !swapChainSupport.m_presentModes.empty(); } return suitable && indices.isComplete() && extensionSupport && swapChainAdequate && features.samplerAnisotropy; } bool Context::checkDeviceExtensionSupport(vk::PhysicalDevice physDevice) { auto availableExtensions = physDevice.enumerateDeviceExtensionProperties(); std::set<std::string> requiredExtensions(m_requiredDeviceExtensions.begin(), m_requiredDeviceExtensions.end()); for (const auto& extension : availableExtensions) requiredExtensions.erase(extension.extensionName); return requiredExtensions.empty(); } QueueFamilyIndices Context::findQueueFamilies(vk::PhysicalDevice physDevice) const { QueueFamilyIndices indices; auto qfprops = physDevice.getQueueFamilyProperties(); uint32_t i = 0; for (const auto& queueFamily : qfprops) { if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) indices.graphicsFamily = i; bool presentSupport = physDevice.getSurfaceSupportKHR(i, m_surface); if (queueFamily.queueCount > 0 && presentSupport && queueFamily.queueFlags & vk::QueueFlagBits::eGraphics) indices.presentFamily = i; if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eTransfer && !(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics)) indices.transferFamily = i; if (queueFamily.queueCount > 0 && queueFamily.queueFlags & vk::QueueFlagBits::eCompute && !(queueFamily.queueFlags & vk::QueueFlagBits::eGraphics)) indices.computeFamily = i; if (indices.isComplete()) break; i++; } //indices.computeFamily = 0; return indices; } void Context::createLogicalDevice() { QueueFamilyIndices indices = findQueueFamilies(m_phsyicalDevice); std::vector<vk::DeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value(), indices.transferFamily.value(), indices.computeFamily.value() }; const float queuePriority = 1.0f; for (uint32_t queueFamily : uniqueQueueFamilies) { vk::DeviceQueueCreateInfo queueCreateInfo({}, queueFamily, 1, &queuePriority); queueCreateInfos.push_back(queueCreateInfo); } vk::PhysicalDeviceFeatures deviceFeatures; deviceFeatures.samplerAnisotropy = VK_TRUE; deviceFeatures.vertexPipelineStoresAndAtomics = VK_TRUE; deviceFeatures.fragmentStoresAndAtomics = VK_TRUE; deviceFeatures.multiDrawIndirect = VK_TRUE; deviceFeatures.shaderStorageImageExtendedFormats = VK_TRUE; vk::DeviceCreateInfo createInfo({}, static_cast<uint32_t>(queueCreateInfos.size()), queueCreateInfos.data(), 0, nullptr, static_cast<uint32_t>(m_requiredDeviceExtensions.size()), m_requiredDeviceExtensions.data(), &deviceFeatures); if constexpr (g_enableValidationLayers) { createInfo.enabledLayerCount = static_cast<uint32_t>(g_validationLayers.size()); createInfo.ppEnabledLayerNames = g_validationLayers.data(); } m_device = m_phsyicalDevice.createDevice(createInfo); // get all the queues! m_presentQueue = m_device.getQueue(indices.presentFamily.value(), 0); m_graphicsQueue = m_device.getQueue(indices.graphicsFamily.value(), 0); m_transferQueue = m_device.getQueue(indices.transferFamily.value(), 0); m_computeQueue = m_device.getQueue(indices.computeFamily.value(), 0); } void Context::createSurface() { if (glfwCreateWindowSurface(m_instance, m_window, nullptr, reinterpret_cast<VkSurfaceKHR*>(&m_surface)) != VK_SUCCESS) throw std::runtime_error("Surface creation failed"); } SwapChainSupportDetails Context::querySwapChainSupport(vk::PhysicalDevice physDevice) const { SwapChainSupportDetails details; details.m_capabilities = physDevice.getSurfaceCapabilitiesKHR(m_surface); details.m_formats = physDevice.getSurfaceFormatsKHR(m_surface); details.m_presentModes = physDevice.getSurfacePresentModesKHR(m_surface); return details; } vk::SurfaceFormatKHR Context::chooseSwapChainSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats) { if (availableFormats.size() == 1 && availableFormats.at(0).format == vk::Format::eUndefined) return { vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear }; for (const auto& availableFormat : availableFormats) { if (availableFormat.format == vk::Format::eB8G8R8A8Unorm && availableFormat.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear) return availableFormat; } return availableFormats.at(0); } vk::PresentModeKHR Context::chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes) { auto bestMode = vk::PresentModeKHR::eFifo; for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == vk::PresentModeKHR::eMailbox) return availablePresentMode; if (availablePresentMode == vk::PresentModeKHR::eImmediate) bestMode = availablePresentMode; } return bestMode; } vk::Extent2D Context::chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities) { if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) { return capabilities.currentExtent; } else { glfwGetFramebufferSize(m_window, &m_width, &m_height); VkExtent2D actualExtent = { static_cast<uint32_t>(m_width), static_cast<uint32_t>(m_height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } void Context::createSwapChain() { auto swapChainSupport = querySwapChainSupport(m_phsyicalDevice); auto surfaceFormat = chooseSwapChainSurfaceFormat(swapChainSupport.m_formats); auto presentMode = chooseSwapPresentMode(swapChainSupport.m_presentModes); auto extent = chooseSwapExtent(swapChainSupport.m_capabilities); // determine the number of images in the swapchain (queue length) uint32_t imageCount = swapChainSupport.m_capabilities.minImageCount + 1; if (swapChainSupport.m_capabilities.maxImageCount > 0 && imageCount > swapChainSupport.m_capabilities.maxImageCount) imageCount = swapChainSupport.m_capabilities.maxImageCount; vk::SwapchainCreateInfoKHR createInfo({}, m_surface, imageCount, surfaceFormat.format, surfaceFormat.colorSpace, extent, 1, vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eStorage); QueueFamilyIndices indices = findQueueFamilies(m_phsyicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = vk::SharingMode::eConcurrent; // exclusive is standard value createInfo.queueFamilyIndexCount = 2; // 0 is standard value } else { createInfo.imageSharingMode = vk::SharingMode::eExclusive; createInfo.queueFamilyIndexCount = 1; } createInfo.pQueueFamilyIndices = queueFamilyIndices; createInfo.preTransform = swapChainSupport.m_capabilities.currentTransform; createInfo.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque; createInfo.presentMode = presentMode; createInfo.clipped = true; createInfo.oldSwapchain = nullptr; m_swapchain = m_device.createSwapchainKHR(createInfo); m_swapChainImages = m_device.getSwapchainImagesKHR(m_swapchain); m_swapChainImageFormat = surfaceFormat.format; m_swapChainExtent = extent; } void Context::createImageViews() { m_swapChainImageViews.resize(m_swapChainImages.size()); for (size_t i = 0; i < m_swapChainImages.size(); i++) { vk::ImageViewCreateInfo createInfo({}, m_swapChainImages.at(i), vk::ImageViewType::e2D, m_swapChainImageFormat, {}, { vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1 }); m_swapChainImageViews.at(i) = m_device.createImageView(createInfo); } } vk::ShaderModule Context::createShaderModule(const std::vector<char>& code) const { vk::ShaderModuleCreateInfo createInfo({}, code.size(), reinterpret_cast<const uint32_t*>(code.data())); return m_device.createShaderModule(createInfo); } void Context::initImgui() { ImGui::CreateContext(); ImGui_ImplGlfw_InitForVulkan(m_window, true); // create imgui descriptor pool vk::DescriptorPoolSize poolSizeCombinedImageSampler(vk::DescriptorType::eCombinedImageSampler, 1); std::array<vk::DescriptorPoolSize, 1> poolSizes = { poolSizeCombinedImageSampler }; vk::DescriptorPoolCreateInfo poolInfo({}, 1, static_cast<uint32_t>(poolSizes.size()), poolSizes.data()); m_imguiDescriptorPool = m_device.createDescriptorPool(poolInfo); // create imgui renderpass vk::AttachmentDescription colorAttachment({}, m_swapChainImageFormat, vk::SampleCountFlagBits::e1, vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eStore, // load store op vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, // stencil op vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::ePresentSrcKHR ); vk::AttachmentReference colorAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal); vk::AttachmentDescription depthAttachment({}, vk::Format::eD32SfloatS8Uint, vk::SampleCountFlagBits::e1, vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eDontCare, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eDepthStencilAttachmentOptimal, vk::ImageLayout::eDepthStencilAttachmentOptimal ); vk::AttachmentReference depthAttachmentRef(1, vk::ImageLayout::eDepthStencilAttachmentOptimal); vk::SubpassDependency dependency(VK_SUBPASS_EXTERNAL, 0, vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput, {}, vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite, vk::DependencyFlagBits::eByRegion); vk::SubpassDescription subpass({}, vk::PipelineBindPoint::eGraphics, 0, nullptr, // input attachments (standard values) 1, &colorAttachmentRef, // color attachments: layout (location = 0) out -> colorAttachmentRef is at index 0 nullptr, // no resolve attachment &depthAttachmentRef); // depth stencil attachment // other attachment at standard values: Preserved std::array<vk::AttachmentDescription, 2> attachments = { colorAttachment, depthAttachment }; vk::RenderPassCreateInfo renderpassInfo({}, static_cast<uint32_t>(attachments.size()), attachments.data(), 1, &subpass, 1, &dependency); m_imguiRenderpass = m_device.createRenderPass(renderpassInfo); // init imgui ImGui_ImplVulkan_InitInfo initInfo = {}; initInfo.Instance = static_cast<VkInstance>(m_instance); initInfo.PhysicalDevice = static_cast<VkPhysicalDevice>(m_phsyicalDevice); initInfo.Device = static_cast<VkDevice>(m_device); initInfo.QueueFamily = findQueueFamilies(m_phsyicalDevice).graphicsFamily.value(); initInfo.Queue = m_graphicsQueue; initInfo.PipelineCache = nullptr; initInfo.DescriptorPool = m_imguiDescriptorPool; ImGui_ImplVulkan_Init(&initInfo, static_cast<VkRenderPass>(m_imguiRenderpass)); } void Context::cleanupImgui() { ImGui_ImplVulkan_InvalidateFontUploadObjects(); ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); m_device.destroyDescriptorPool(m_imguiDescriptorPool); m_device.destroyRenderPass(m_imguiRenderpass); } }
41.55259
231
0.689297
Max1412
dd1068e1623204396bc4ae2d3b64b14cb7c2f6e8
1,381
cpp
C++
025_reverseNodesInKGroup/main.cpp
IdLeoO/LC
445d8f1521d02c8481d590e5af914b6599bf8d7d
[ "MIT" ]
null
null
null
025_reverseNodesInKGroup/main.cpp
IdLeoO/LC
445d8f1521d02c8481d590e5af914b6599bf8d7d
[ "MIT" ]
null
null
null
025_reverseNodesInKGroup/main.cpp
IdLeoO/LC
445d8f1521d02c8481d590e5af914b6599bf8d7d
[ "MIT" ]
null
null
null
#include "main.hpp" #include <iostream> #include <stack> using namespace std; ListNode* Solution::reverseKGroup(ListNode* head, int k){ stack<ListNode*> storage; ListNode* curPtr = head; if (k == 1){ return head; } for (int i = 0; i < k; i++){ if (curPtr == nullptr){ return head; } storage.push(curPtr); curPtr = curPtr->next; } ListNode* reverseHead = storage.top(); ListNode* nextRec = reverseHead->next; storage.pop(); reverseHead->next = storage.top(); for (int i = 0; i < k - 1; i++){ ListNode* reverseCur = storage.top(); storage.pop(); if (storage.empty()){ reverseCur->next = reverseKGroup(nextRec, k); } else{ reverseCur->next = storage.top(); } } return reverseHead; } int main(int argc, char* argv[]){ ListNode *empty = new ListNode(); ListNode *a1 = new ListNode(1); ListNode *a2 = new ListNode(2); ListNode *a3 = new ListNode(3); ListNode *a4 = new ListNode(4); ListNode *a5 = new ListNode(5); a1->next = a2; a2->next = a3; a3->next = a4; a4->next = a5; Solution sol; auto result = sol.reverseKGroup(a1, 1); while (result){ cout << result->val << " "; result = result->next; } cout << endl; return 0; }
23.40678
57
0.539464
IdLeoO
dd113b5535d1ff6a1a61ff598beeb5c329880ad4
871
cpp
C++
leddriver/src/ledimage.cpp
freesurfer-rge/picolife
db54c3398baf3fdfab5c72c75a5207b73847f443
[ "MIT" ]
null
null
null
leddriver/src/ledimage.cpp
freesurfer-rge/picolife
db54c3398baf3fdfab5c72c75a5207b73847f443
[ "MIT" ]
7
2021-12-25T11:54:10.000Z
2021-12-27T17:24:30.000Z
leddriver/src/ledimage.cpp
freesurfer-rge/picolife
db54c3398baf3fdfab5c72c75a5207b73847f443
[ "MIT" ]
null
null
null
#include "leddriver/ledimage.hpp" namespace LEDDriver { LEDImage::LEDImage() : red(std::make_unique<Channel>()), green(std::make_unique<Channel>()), blue(std::make_unique<Channel>()) { this->Clear(); } void LEDImage::Clear() { this->red->fill(0); this->green->fill(0); this->blue->fill(0); } void LEDImage::SetPixel(const unsigned int ix, const unsigned int iy, const uint8_t r, const uint8_t g, const uint8_t b) { const size_t idx = ix + (LEDArray::nCols * iy); this->red->at(idx) = r; this->green->at(idx) = g; this->blue->at(idx) = b; } void LEDImage::SendToLEDArray(LEDArray &target) const { target.UpdateBuffer(*(this->red), *(this->green), *(this->blue)); } }
27.21875
78
0.523536
freesurfer-rge
dd13f8ef1f5dc809a9358cb3a5be8178d5e380e8
726
cpp
C++
CD12/Maximum Number of Events That Can Be Attended.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
4
2019-12-12T19:59:50.000Z
2020-01-20T15:44:44.000Z
CD12/Maximum Number of Events That Can Be Attended.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
null
null
null
CD12/Maximum Number of Events That Can Be Attended.cpp
shtanriverdi/CS487-Introduction-to-Competitive-Programming-Progress
0d7a4fa4346ee08d9b2b2f628c3ffab7f3f81166
[ "MIT" ]
null
null
null
// Question Link ---> https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/ class Solution { public: static bool cmp(vector<int> &a, vector<int> &b) { if (a[1] == b[1]) { return a[0] < b[0]; } return a[1] < b[1]; } int maxEvents(vector<vector<int>>& events) { unordered_set<int> attended; sort(events.begin(), events.end(), cmp); for (auto event : events) { for (int i = event[0]; i <= event[1]; i++) { if (!attended.count(i)) { attended.insert(i); break; } } } return attended.size(); } };
30.25
100
0.453168
shtanriverdi
dd166f8404be9351b29d0b3ec652e9c95cd2dce7
6,584
cpp
C++
source/PEST++/src/libs/pestpp_common/TerminationController.cpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
1
2021-02-23T20:47:29.000Z
2021-02-23T20:47:29.000Z
source/PEST++/src/libs/pestpp_common/TerminationController.cpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
null
null
null
source/PEST++/src/libs/pestpp_common/TerminationController.cpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
2
2020-01-03T17:14:39.000Z
2020-03-04T14:21:27.000Z
/* This file is part of PEST++. PEST++ 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 3 of the License, or (at your option) any later version. PEST++ 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 PEST++. If not, see<http://www.gnu.org/licenses/>. */ #include "TerminationController.h" #include <vector> #include <algorithm> #include "utilities.h" #include "ObjectiveFunc.h" using namespace pest_utils; using namespace std; TerminationController::TerminationController(int _noptmax, double _phiredstp, int _nphistp, int _nphinored, double _relparstp, int _nrelpar, bool _use_dynaimc_regul, double _phim_accept) : phiredstp(_phiredstp), relparstp(_relparstp), phim_accept(_phim_accept), current_phi(99e99), nphistp(_nphistp), noptmax(_noptmax), nphinored(_nphinored), nopt_count(0), nphinored_count(0), nrelpar(_nrelpar), nrelpar_count(0), terminate_code(false), use_dynaimc_regul(_use_dynaimc_regul), phi_accept_achieved(false) { termimate_reason = "unknown"; } void TerminationController::reset() { nopt_count = 0; nphinored_count = 0; lowest_phi.clear(); terminate_code = false; } bool TerminationController::process_iteration(const PhiComponets &phi_comp, double relpar) { ++nopt_count; double phi_m = phi_comp.meas; double phi_r = phi_comp.regul; double phi = 9e99; bool regul_reject = false; if (use_dynaimc_regul == false) { phi = phi_m + phi_r; } else if (!phi_accept_achieved && phi_m > phim_accept) { phi = phi_m; regul_reject = false; } else if (use_dynaimc_regul && !phi_accept_achieved && phi_m <= phim_accept) { lowest_phi.clear(); phi_accept_achieved = true; phi = phi_r; regul_reject = false; } else if (use_dynaimc_regul && phi_m < phim_accept) { phi = phi_r; regul_reject = false; } else { regul_reject = true; } current_phi = phi; if (!regul_reject) { // keep track of number of iterations since lowest phi if (lowest_phi.size() == 0 || phi <= lowest_phi.front()) { nphinored_count = 0; } else { ++nphinored_count; } // keep track of NPHISTP lowest phi's if (lowest_phi.size() < nphistp) { lowest_phi.push_back(phi); } else if (phi < lowest_phi.back()) { lowest_phi.back() = phi; } sort(lowest_phi.begin(), lowest_phi.end()); } // Check maximum relative parameter change if (abs(relpar) < relparstp) { ++nrelpar_count; } else { nrelpar_count = 0; } return check_last_iteration(); } bool TerminationController::check_last_iteration() { if (nopt_count >= noptmax) { terminate_code = true; termimate_reason = "NOPTMAX criterion met"; return terminate_code; } double min_phi_diff = lowest_phi.back() - lowest_phi.front(); if (current_phi <= std::numeric_limits<double>::denorm_min()) { terminate_code = true; termimate_reason = "PHI is zero"; } // Impose Termination Criteria else if (nphinored_count > nphinored) { terminate_code = true; termimate_reason = "NPHINORED criterion met"; } else if (lowest_phi.size() >= nphistp && min_phi_diff <= phiredstp*current_phi) { terminate_code = true; termimate_reason = "PHIREDSTP / NPHISTP criterion met"; } else if (nrelpar_count > nrelpar) { terminate_code = true; termimate_reason = "RELPARSTP / NRELPAR criterion met"; } else { terminate_code = false; termimate_reason = "Unexpected Termination"; } return terminate_code; } void TerminationController::termination_summary(std::ostream &fout) { fout << "-----------------------------------------" << endl; fout << " --- OPTIMIZATION COMPLETE --- " << endl; fout << " Reason for terminating PEST++ simulation: " << termimate_reason << endl; fout << " Summary of termination criteria:" << endl; fout << " NOPTMAX = " << noptmax << " ; NOPT at termination = " << nopt_count << endl; fout << " NPHINORED = " << nphinored << " ; NPHINORED at termination = " << nphinored_count << endl; fout << " NRELPAR = " << nrelpar << "; RELPARSTP = " << relparstp << " ; NRELPAR at termination = " << nrelpar_count << endl; fout << " PHIREDSTP = " << phiredstp << "; NPHISTP = " << nphistp << endl; if (!use_dynaimc_regul || !phi_accept_achieved) { fout << " NPHISTP lowest PHI's:" << endl; } else { fout << " NPHISTP lowest regularization PHI componets:" << endl; } for (const auto &it : lowest_phi) { fout << " " << it << endl; } } const TerminationController& TerminationController::operator=(const TerminationController &rhs) { noptmax = rhs.noptmax; nphinored = rhs.nphinored; nphinored_count = rhs.nphinored_count; nrelpar = rhs.nrelpar; nrelpar_count = rhs.nrelpar_count; nphistp = rhs.nphistp; phiredstp = rhs.phiredstp; relparstp = rhs.relparstp; lowest_phi = rhs.lowest_phi; return *this; } void TerminationController::save_state(std::ostream &fout) { fout << "termination_info_1 " << noptmax << " " << nopt_count << " " << nphinored << " " << nphinored_count << " " << nrelpar << endl; fout << "termination_info_2 " << nrelpar_count << " " << nphistp << " " << phiredstp << " " << relparstp << endl; fout << "termination_info_3 "; for (double &a : lowest_phi) { fout << " " << a; } fout << endl; } void TerminationController::read_state(const std::string &line) { vector<string> tokens; tokenize(line, tokens); try { string line_type = upper_cp(tokens[0]); if (line_type == "TERMINATION_INFO_1") { convert_ip(tokens[1], noptmax); convert_ip(tokens[2], nopt_count); convert_ip(tokens[3], nphinored); convert_ip(tokens[4], nphinored_count); convert_ip(tokens[5], nrelpar); } else if (line_type == "TERMINATION_INFO_2") { convert_ip(tokens[1], nrelpar_count); convert_ip(tokens[2],nphistp); convert_ip(tokens[3],phiredstp); convert_ip(tokens[4],relparstp ); } else if (line_type == "TERMINATION_INFO_3") { lowest_phi.clear(); for (int i=1; i<tokens.size(); ++i) { double val = convert_cp<double>(tokens[1]); lowest_phi.push_back(val); } } } catch(std::runtime_error &e) { cerr << "Error processing restart file on line:" << endl; cerr << line << endl << endl; cerr << e.what() << endl << endl; throw(e); } } TerminationController::~TerminationController(void) { }
25.71875
128
0.68226
usgs
dd1d6b6636cd1bd56bda65e303c3c37afcb999cc
9,568
cpp
C++
Codes/SysMonDlg.cpp
liyuan-rey/SysMon
38052326d97fd732d36f9313f3415ae9f33fb3c3
[ "MIT" ]
null
null
null
Codes/SysMonDlg.cpp
liyuan-rey/SysMon
38052326d97fd732d36f9313f3415ae9f33fb3c3
[ "MIT" ]
null
null
null
Codes/SysMonDlg.cpp
liyuan-rey/SysMon
38052326d97fd732d36f9313f3415ae9f33fb3c3
[ "MIT" ]
null
null
null
// SysMonDlg.cpp : implementation file // #include "stdafx.h" #include "SysMon.h" #include "SysMonDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define VK_ESCAPE 0x1B ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange *pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange *pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSysMonDlg dialog CSysMonDlg::CSysMonDlg(CWnd *pParent /*=NULL*/) : CDialog(CSysMonDlg::IDD, pParent) { //{{AFX_DATA_INIT(CSysMonDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CSysMonDlg::DoDataExchange(CDataExchange *pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSysMonDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSysMonDlg, CDialog) //{{AFX_MSG_MAP(CSysMonDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_COMMAND(IDR_SYS_ABOUT, OnSysAbout) ON_COMMAND(IDM_SYS_HELP, OnSysHelp) ON_COMMAND(IDM_PROC_REFRESH, OnProcRefresh) ON_COMMAND(IDM_PROC_TERMINATE, OnProcTerminate) ON_COMMAND(IDM_PROC_SENDMSG, OnProcSendmsg) ON_WM_CHAR() ON_COMMAND(IDM_SYS_EXIT, OnSysExit) ON_WM_CLOSE() ON_WM_SIZE() ON_COMMAND(IDM_SHELLICON_SHOWWINDOW, OnShelliconShowwindow) ON_COMMAND(IDM_SHELLICON_EXIT, OnShelliconExit) ON_COMMAND(IDM_SVR_LOAD, OnSvrLoad) ON_COMMAND(IDM_SVR_PAUSE, OnSvrPause) ON_COMMAND(IDM_SVR_REFRESH, OnSvrRefresh) ON_COMMAND(IDM_SVR_RESUME, OnSvrResume) ON_COMMAND(IDM_SVR_STOP, OnSvrStop) ON_UPDATE_COMMAND_UI(IDM_SVR_LOAD, OnUpdateSvrLoad) //}}AFX_MSG_MAP ON_MESSAGE(WM_SYSMONNOTIFY, OnSysMonNotify) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSysMonDlg message handlers BOOL CSysMonDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu *pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here nIsHide = SW_SHOW; // 初始化属性单 m_sheet.AddPage(&m_propSysinfo); m_sheet.AddPage(&m_propProcess); m_sheet.AddPage(&m_propService); m_sheet.AddPage(&m_propRule); m_sheet.AddPage(&m_propTask); m_sheet.AddPage(&m_propSetting); m_sheet.Create(this, WS_CHILD | WS_VISIBLE, 0); m_sheet.ModifyStyleEx(0, WS_EX_CONTROLPARENT); m_sheet.ModifyStyle(0, WS_TABSTOP); return TRUE; // return TRUE unless you set the focus to a control } void CSysMonDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CSysMonDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM)dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CSysMonDlg::OnQueryDragIcon() { return (HCURSOR)m_hIcon; } void CSysMonDlg::OnSysAbout() { // TODO: Add your command handler code here CAboutDlg dlgAbout; dlgAbout.DoModal(); } void CSysMonDlg::OnSysHelp() { // TODO: Add your command handler code here AfxMessageBox("Sorry, Help is not available for now!"); } void CSysMonDlg::OnProcRefresh() { // TODO: Add your command handler code here m_propProcess.OnProcRefresh(); } void CSysMonDlg::OnProcTerminate() { // TODO: Add your command handler code here m_propProcess.OnProcTerminate(); } void CSysMonDlg::OnProcSendmsg() { // TODO: Add your command handler code here m_propProcess.OnProcSendmsg(); } void CSysMonDlg::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default AfxMessageBox(nChar); // 添加任务栏图标 if (nChar == VK_ESCAPE) { NOTIFYICONDATA nid; nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = this->m_hWnd; nid.uID = IDR_MAINFRAME; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; nid.uCallbackMessage = WM_SYSMONNOTIFY; nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); strcpy(nid.szTip, _T("系统监控器")); Shell_NotifyIcon(NIM_ADD, &nid); } // 隐藏窗体 ShowWindow(SW_HIDE); CDialog::OnChar(nChar, nRepCnt, nFlags); } void CSysMonDlg::OnSysMonNotify(WPARAM wParam, LPARAM lParam) { UINT uID; //发出该消息的图标的ID UINT uMouseMsg; //鼠标动作 POINT point; uID = (UINT)wParam; uMouseMsg = (UINT)lParam; if (uMouseMsg == WM_RBUTTONUP) // 如果是双击左键 { if (uID == IDR_MAINFRAME) // 如果是我们的图标 { GetCursorPos(&point); //取得鼠标位置 // 取菜单资源 CMenu mnuTop; mnuTop.LoadMenu(IDR_MENU_SHELLICON); // 取子菜单 CMenu *pPopup = mnuTop.GetSubMenu(0); ASSERT_VALID(pPopup); // 设置默认菜单 SetMenuDefaultItem(pPopup->m_hMenu, 0, TRUE); // 显示菜单 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON, point.x, point.y, AfxGetMainWnd(), NULL); // 弹出式菜单的命令会被 MFC 的消息路由机制自动处理 } } if (uMouseMsg == WM_LBUTTONDBLCLK) //如果是双击左键 { if (uID == IDR_MAINFRAME) //如果是我们的图标 OnShelliconShowwindow(); // 显示窗体 } return; } void CSysMonDlg::OnSysExit() { // TODO: Add your command handler code here // 退出程序 SendMessage(WM_CLOSE); } void CSysMonDlg::OnClose() { // TODO: Add your message handler code here and/or call default if (IDOK == AfxMessageBox(_T("确定要退出系统监控程序吗?"), MB_OKCANCEL)) { CDialog::OnClose(); // CDialog::OnOK(); } } void CSysMonDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here // 添加任务栏图标 if (nType == SIZE_MINIMIZED) { NOTIFYICONDATA nid; nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = this->m_hWnd; nid.uID = IDR_MAINFRAME; nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; nid.uCallbackMessage = WM_SYSMONNOTIFY; nid.hIcon = LoadIcon(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); strcpy(nid.szTip, _T("系统监控器")); Shell_NotifyIcon(NIM_ADD, &nid); } // 隐藏窗体 if (nIsHide == SW_SHOW) { ShowWindow(SW_SHOWMINIMIZED); ShowWindow(SW_HIDE); UpdateWindow(); nIsHide = SW_HIDE; } } void CSysMonDlg::OnShelliconShowwindow() { // TODO: Add your command handler code here // 显示窗体 if (nIsHide == SW_HIDE) { ShowWindow(SW_RESTORE); SetForegroundWindow(); nIsHide = SW_SHOW; } // 删除任务栏图标 NOTIFYICONDATA nid; nid.cbSize = sizeof(NOTIFYICONDATA); nid.hWnd = this->m_hWnd; nid.uID = IDR_MAINFRAME; // 保证删除的是我们的图标 Shell_NotifyIcon(NIM_DELETE, &nid); } void CSysMonDlg::OnShelliconExit() { // TODO: Add your command handler code here OnShelliconShowwindow(); SendMessage(WM_CLOSE); } void CSysMonDlg::OnSvrLoad() { // TODO: Add your command handler code here m_propService.OnSvrLoad(); } void CSysMonDlg::OnSvrPause() { // TODO: Add your command handler code here m_propService.OnSvrPause(); } void CSysMonDlg::OnSvrResume() { // TODO: Add your command handler code here m_propService.OnSvrResume(); } void CSysMonDlg::OnSvrStop() { // TODO: Add your command handler code here m_propService.OnSvrStop(); } void CSysMonDlg::OnSvrRefresh() { // TODO: Add your command handler code here m_propService.OnSvrRefresh(); } void CSysMonDlg::OnUpdateSvrLoad(CCmdUI *pCmdUI) { // TODO: Add your command update UI handler code here AfxMessageBox("!"); }
23.055422
80
0.676526
liyuan-rey
dd1d9c969864541580624569ad00c7b04983d2c8
2,471
cpp
C++
component-tester/src/component-tester.cpp
shawnmharris/tachyon-examples
0e634b969063ef87186b4863bf71c93b9c512df6
[ "MIT" ]
null
null
null
component-tester/src/component-tester.cpp
shawnmharris/tachyon-examples
0e634b969063ef87186b4863bf71c93b9c512df6
[ "MIT" ]
null
null
null
component-tester/src/component-tester.cpp
shawnmharris/tachyon-examples
0e634b969063ef87186b4863bf71c93b9c512df6
[ "MIT" ]
null
null
null
#include <iostream> #include <tachyon/component.hpp> #include <itestcontract.hpp> using namespace tachyon; int main() { MasterFactory &mf = MasterFactory::Instance(); mf.Manage("component1"); mf.Manage("component2"); // test 1 is implemented in a shared dll sp<ITestContract> sp1 = mf.Create<ITestContract>("ITestContract.TestComponent1"); // test 2 is implemented in a shared dll sp<ITestContract> sp2 = mf.Create<ITestContract>("ITestContract.TestComponent2"); sp<ITestContract> sp3 = sp1; sp<ITestContract> sp4 = sp2; sp<ITestContract> sp5 = mf.Create<ITestContract>("ITestContract.TestComponent1"); if (!sp1.isValid() || !sp3.isValid() || !sp5.isValid()) { std::cerr << "Invalid TestComponent1, program abort" << std::endl; exit(0); } if (!sp2.isValid() || !sp4.isValid()) { std::cerr << "Invalid TestComponent2, program abort" << std::endl; exit(0); } if (!sp1->PostInit() || !sp3->PostInit() || !sp5->PostInit()) { std::cerr << "TestComponent1, PostInit failure, program abort" << std::endl; exit(0); } if (!sp2->PostInit() || !sp4->PostInit()) { std::cerr << "TestComponent2, PostInit failure, program abort" << std::endl; exit(0); } std::cout << std::endl; std::cout << "BEGIN TESTS" << std::endl; std::cout << std::endl; std::cout << "TEST sp1->TestMethod() shows Implementation TestComponent1" << std::endl; sp1->TestMethod(); std::cout << std::endl; std::cout << "TEST sp2->TestMethod() shows Implementation TestComponent2" << std::endl; sp2->TestMethod(); std::cout << std::endl; std::cout << "TEST sp1 and sp3 have same name" << std::endl; std::cout << "sp1 name :" << sp1->GetName() << std::endl; std::cout << "sp3 name :" << sp3->GetName() << std::endl; std::cout << std::endl; std::cout << "TEST sp5 has unique name" << std::endl; std::cout << "sp5 name :" << sp5->GetName() << std::endl; std::cout << std::endl; std::cout << "TEST sp2 and sp4 have same name" << std::endl; std::cout << "sp2 name :" << sp2->GetName() << std::endl; std::cout << "sp4 name :" << sp4->GetName() << std::endl; std::cout << std::endl; std::string pattern = "ITestContract\\.(.*)"; std::cout << "TEST find contracts using Regex pattern: " << pattern << std::endl; auto spList = mf.CreateAll<ITestContract>(pattern); for (auto itr = spList.begin(); itr != spList.end(); itr++) { if (itr->isValid()) { std::cout << "PATTERN TEST FOUND : " << (*itr)->GetName() << std::endl; } } }
27.455556
88
0.630109
shawnmharris
dd1ebe2c18a8823b5181e05b83c5dbcf972340c5
14,728
cpp
C++
torob/src/moinag.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
7
2016-12-10T15:44:00.000Z
2020-08-27T17:40:11.000Z
torob/src/moinag.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
2
2020-04-14T15:19:53.000Z
2021-01-26T21:26:47.000Z
torob/src/moinag.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
2
2017-01-29T03:01:06.000Z
2021-12-15T14:59:10.000Z
/* * <one line to give the library's name and an idea of what it does.> * Copyright (C) 2015 Guillaume L. <guillaume.lozenguez@mines-douai.fr> * * 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 3 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/>. * */ #include "global.h" #include "moinag.h" #include "tools.h" #include <iostream> #include <array> using namespace :: mia; using namespace :: std; Moinag::Moinag(float eps, float robot_radius, float pcpt_radius):Agent(pcpt_number, act_number), a_stateMachine(this, state_number, &Moinag::stateDefault), a_body( 0.f, 0.f, robot_radius), //Global::config["robot"]["radius"].as<float>() ), a_epsilon( eps ), //Global::config["robot"]["epsilon"].as<float>() ),// 0.06f a_topo(eps, pcpt_radius), a_controlTarget( 100.f, 0.f ), a_traceDistance2( 0.8*0.8 ), a_wait(1), a_waitCount(0), a_perceptionRadius( pcpt_radius ) //Global::config["robot"]["perception"].as<float>() ) { a_stateMachine.setStateProcess( state_wait, &Moinag::stateWait ); a_stateMachine.setStateProcess( state_new_target, &Moinag::stateNewTarget ); a_stateMachine.setState(state_wait); // a_stateMachine.setStateProcess( state_2, &Moinag::state2 ); } Moinag::~Moinag() { } // Static Factory : //------------------ Moinag * Moinag :: factory( int agentType ) { switch( agentType ) { case agent_moinag : return new Moinag( Global::config["robot"]["epsilon"].as<float>(), Global::config["robot"]["radius"].as<float>(), Global::config["robot"]["perception"].as<float>() ); default : return new Moinag( Global::config["robot"]["epsilon"].as<float>(), Global::config["robot"]["radius"].as<float>(), Global::config["robot"]["perception"].as<float>() ); } } // state machine : //------------------ void Moinag :: act( const InteractStr &sensor, InteractStr &actuator ){ for( int iact(0); iact < actuator_size() ; ++iact ) actuator[iact].clear(); cout << "Moinag process...\n"; a_stateMachine.process(sensor, actuator); cout << "\t visibility map with " << a_topo.a_visibility.edge_size() << " edges\n"; cout << "Moinag process end" << endl; } // State Tools : //-------------- int Moinag :: processSensor(const InteractStr& sensor) { list<Particle> obstacle; Particle move; Particle lastBody= a_body; int count(0); // for( list<Data>::const_iterator it= a_sensor[pcpt_communication].begin(); it != a_sensor[pcpt_communication].end(); ++it ) // ; for( list<Data>::const_iterator it= sensor[pcpt_position].begin(); it != sensor[pcpt_position].end(); ++it ) { a_body= Particle(*it); } for( list<Data>::const_iterator it= sensor[pcpt_movement].begin(); it != sensor[pcpt_movement].end(); ++it ) { move= Particle( *it ); a_body.position+= move.position; a_body.theta= reduceRadian( a_body.theta + move.theta); a_body.radius= a_body.radius + move.radius; } for( list<Data>::const_iterator it= sensor[pcpt_map].begin(); it != sensor[pcpt_map].end(); ++it ) { //Get meta-data : int width( it->flag(0) ), height( it->flag(1) ); float resolution( it->value(0) ); cout << "\t" << it->mesage() << " " << width << "x" << height << endl; //Clear map : a_topo.clear(); a_topo.setEpsilon(resolution*0.999f); int ** node = new int*[width]; int obs_dist= 1; //Copy map: for( int i(0); i < width ; ++i ) { node[i]= new int[height]; for( int j(0); j < height ; ++j ) { node[i][j]= it->flag(2+i+j*width); } } //threshold: for( int i(0); i < width ; ++i ) { for( int j(0); j < height ; ++j ) { if( node[i][j] > 0 ) node[i][j]= 100; } } //filtering too little free area; for(bool map_ok(false) ; !map_ok ; map_ok= true ) { for( int i(0); i < width ; ++i ) for( int j(0); j < height ; ++j ) { int nbFreeNeiborg(0); int i1(max(0, i-1)), i2(min(i+1, width-1)); int j1(max(0, j-1)), j2(min(j+1, height-1)); nbFreeNeiborg+= ( node[i1][j] == 0 )?1:0; nbFreeNeiborg+= ( node[i2][j] == 0 )?1:0; nbFreeNeiborg+= ( node[i][j1] == 0 )?1:0; nbFreeNeiborg+= ( node[i][j2] == 0 )?1:0; if( node[i][j] == 0 && ( nbFreeNeiborg == 0 || nbFreeNeiborg == 1 && ( node[i1][j] == -1 || node[i2][j] == -1 || node[i][j1] == -1 || node[i][j2] == -1 ) ) ) { node[i][j]= -1; map_ok= false; } } } //filtering thick obstatcle definition: for( int i(0); i < width ; ++i ) { for( int j(0); j < height ; ++j ) { int i1(max(0, i-1)), i2(min(i+1, width-1)); int j1(max(0, j-1)), j2(min(j+1, height-1)); if( node[i][j] == 100 && node[i1][j] != 0 && node[i2][j] != 0 && node[i][j1] != 0 && node[i][j2] != 0 ) node[i][j]= -1; } } //From grid to vector: for( int i(0); i < width ; ++i ) { for( int j(0); j < height ; ++j ) { if( node[i][j] == 100 ) { Float2 p(i*resolution, j*resolution); node[i][j]= a_topo.add_corner(p); for( int iiend(i), ii= max(0, i-obs_dist); ii < iiend ; ++ii ) for( int jjend( min(height, j+1+obs_dist) ), jj= max(0, j-obs_dist); jj < jjend ; ++jj ) { if( node[ii][jj] != -1 ) { a_topo.add_edge( node[i][j], node[ii][jj], Visibility::edge_obstacle ); } } for( int jjend(j), jj= max(0, j-obs_dist); jj < jjend ; ++jj ) { if( node[i][jj] != -1 ) { a_topo.add_edge( node[i][j], node[i][jj], Visibility::edge_obstacle ); } } } else node[i][j]= -1; } } // topo clean : a_topo.clean(); } for( list<Data>::const_iterator it= sensor[pcpt_wall].begin(); it != sensor[pcpt_wall].end(); ++it ) { obstacle.push_back( Particle( *it ) ); } if( a_trace.empty() || distance2( *(a_trace.rbegin()), a_body.position ) > a_traceDistance2 ) a_trace.push_back( a_body.position ); a_obstacle.resize( obstacle.size() ); std::copy( obstacle.begin(), obstacle.end(), a_obstacle.begin() ); return count; } int Moinag :: processLocal() { //a_obstacle : float epsilon2( a_epsilon*a_epsilon ), doubleEpsilon2(epsilon2*4); float safeDist( ( a_epsilon+a_body.radius*1.1f ) ), _2safeDist2( safeDist*safeDist*4 ); Particle::sortAngle( a_obstacle ); if( a_obstacle.size() > 1 ){ a_filterObs= Particle::polarFiltering( a_obstacle, a_epsilon); vector<Particle> filterOdst( a_filterObs.size() ); int size(0); for( list<Float2>::iterator it= a_filterObs.begin(); it != a_filterObs.end() ; ++it ){ filterOdst[size].position= *it; filterOdst[size].radius= a_epsilon; ++size; } // Initialize local entrance/exit : list< int > section; for(int i= 1; i < filterOdst.size(); ++i){ if( distance2(filterOdst[i].position, filterOdst[i-1].position) > _2safeDist2 ) { section.push_back(i-1); section.push_back(i); } } if( distance2( filterOdst[0].position, filterOdst[size-1].position ) > _2safeDist2 ) { section.push_front(0); section.push_back( filterOdst.size()-1 ); } else{ section.push_back( *section.begin() ); section.pop_front(); } if( section.size() == 0 ){ // The farest obstacle from the agent : int iMax1(0), iMax2(0); float max2= 0.f; for(int i= 1; i < filterOdst.size(); ++i){ float dist2= filterOdst[i].position.length2(); if( dist2 > max2 ) { iMax1= i; max2= dist2; } } max2= 0.f; // The farest obstacle from the first farest obstacle : for(int i= 1; i < filterOdst.size(); ++i){ float dist2= distance2Between( filterOdst[iMax1].position, filterOdst[i].position ); if( dist2 > max2 ) { iMax2= i; max2= dist2; } } section.push_back( iMax1 ); section.push_back( iMax2 ); section.push_back( iMax2 ); section.push_back( iMax1 ); } // Rafine section (target multiple linear regression) : list<int>::iterator it2, it1= section.begin(); while( it1 != section.end() ){ it2= it1; ++it2; int select(-1); float maxDist= 0.0; float angle= ( filterOdst[*it2].position - filterOdst[*it1].position ).angle(); for(int i= *it1 ; i != *it2 ; i= (i+1)%filterOdst.size() ) { Float2 p= filterOdst[i].position.toBasis( angle, filterOdst[*it1].position ); p.y= fabsf( p.y ); if( p.y > maxDist ){ maxDist= p.y; select= i; } } if( maxDist > a_epsilon ){ section.insert( it2, select ); section.insert( it2, select ); } else{ ++it1; ++it1; } } // TODO linear Regression section per section ? : // Build local topology : a_localMap.initialize( a_body, filterOdst, section, a_epsilon, safeDist ); // TODO initializeObstacles with list<Float2> wall, float epsilon, foat safeDistance : using particle fusion. a_localMap.actualize(); } return boost::num_vertices( a_localMap.a_local ); } int Moinag :: processControl(InteractStr& actuator) { float angle( a_controlTarget.angle() ); float dist( a_controlTarget.length() ); float rotation= 1.f; float speed= 2.0f; if( angle < 0.f ){ rotation= -1; angle*= -1.f; } if( angle < 0.01f ) rotation= 0.f; else if( angle < 0.1f ) rotation*= 0.2f; else if( angle < 0.5f ) rotation*= 0.8f; else if( angle < 1.2f ) rotation*= 1.4f; if( dist < a_epsilon ){ speed= 0.f; rotation= 0.f; } else if( dist < a_body.radius ) speed*= 0.4f; Data control( "control", 0, 4 ); control.a_value[0]= speed; // speed; control.a_value[1]= rotation; // rotation; control.a_value[2]= 0.f; // scale; control.a_value[3]= 0.f; // brake; actuator[ act_move ].push_back( control ); return 1; } // State Machine : //---------------- int Moinag :: stateWait(const InteractStr & sensor, InteractStr &actuator){ cout << "\tMoinag State Wait" << "\n"; if( a_waitCount < 0 || a_waitCount > a_wait ) a_waitCount= 0; int nbMsg= processSensor(sensor); processLocal(); ++a_waitCount; if( a_waitCount == a_wait ){ a_waitCount= 0; return state_new_target; } return state_wait; } int Moinag :: stateNewTarget(const InteractStr & sensor, InteractStr &actuator) { cout << "\tMoinag State New Target" << "\n"; stateDefault(sensor, actuator); // a_targetVertex= a_topo.a_visibility.random_vertex_index(); // assert( a_topo.a_visibility.is_vertex_index( a_targetVertex ) ); // cout << "target vertex :" << a_targetVertex << "\n"; return state_default; } int Moinag :: stateDefault(const InteractStr & sensor, InteractStr &actuator) { cout << "\tMoinag State Default" << "\n"; int nbMsg= processSensor(sensor); processLocal(); // cout << ""\n"\t- Position: " << a_body.position << " angle: " << a_body.theta << "\n"; // cout << "\t- Actualize visibility graph:" << "\n"; a_topo.actualize( &a_localMap, a_body.position ); // cout << "\t- " << a_topo.a_visibility.vertex_size() << " vertices and " << a_topo.a_visibility.edge_size() << " edges" << "\n"; // a_topo.print(cout); // cout << "\t- Define control:" << "\n"; a_controlTarget= a_localMap.getDirection( Float2( 100.f, 0.f ), LocalModel::particle_exit ).first.position; processControl(actuator); // a_targetVertex= a_topo.a_visibility.random_vertex_index(); // assert( a_topo.a_visibility.is_vertex_index( a_targetVertex ) ); return state_default; } void Moinag :: log( const InteractStr& sensor, std::ostream & os ) const { /// log perceived data os << sensor.size() << "\n"; for(unsigned int i(0) ; i < sensor.size() ; ++i ) { os << sensor[i].size() << "\n"; for( list<Data>::const_iterator itEnd( sensor[i].end() ), it( sensor[i].begin() ); it != itEnd ; ++it ) { it->log(os); } } }
32.227571
174
0.502444
CARMinesDouai
dd1f67c1ddda587b369e6747e25dc400b32df9f1
2,336
hh
C++
src/ui/win32/bindings/MultiLineGridBinding.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
71
2018-04-15T13:02:43.000Z
2022-03-26T11:19:18.000Z
src/ui/win32/bindings/MultiLineGridBinding.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
309
2018-04-15T12:10:59.000Z
2022-01-22T20:13:04.000Z
src/ui/win32/bindings/MultiLineGridBinding.hh
Jamiras/RAIntegration
ccf3dea24d81aefdcf51535f073889d03272b259
[ "MIT" ]
17
2018-04-17T16:09:31.000Z
2022-03-04T08:49:03.000Z
#ifndef RA_UI_WIN32_MULTILINEGRIDBINDING_H #define RA_UI_WIN32_MULTILINEGRIDBINDING_H #pragma once #include "GridBinding.hh" namespace ra { namespace ui { namespace win32 { namespace bindings { class MultiLineGridBinding : public GridBinding { public: explicit MultiLineGridBinding(ViewModelBase& vmViewModel) noexcept : GridBinding(vmViewModel) {} GSL_SUPPRESS_F6 ~MultiLineGridBinding() noexcept = default; MultiLineGridBinding(const MultiLineGridBinding&) noexcept = delete; MultiLineGridBinding& operator=(const MultiLineGridBinding&) noexcept = delete; MultiLineGridBinding(MultiLineGridBinding&&) noexcept = delete; MultiLineGridBinding& operator=(MultiLineGridBinding&&) noexcept = delete; GSL_SUPPRESS_CON3 LRESULT OnLvnItemChanging(const LPNMLISTVIEW pnmListView) override; GSL_SUPPRESS_CON3 void OnLvnItemChanged(const LPNMLISTVIEW pnmListView) override; LRESULT OnCustomDraw(NMLVCUSTOMDRAW* pCustomDraw) override; void OnNmClick(const NMITEMACTIVATE* pnmItemActivate) override; void OnNmDblClick(const NMITEMACTIVATE* pnmItemActivate) override; void EnsureVisible(gsl::index nIndex) override; protected: void UpdateAllItems() override; void UpdateItems(gsl::index nColumn) override; void OnViewModelStringValueChanged(gsl::index nIndex, const StringModelProperty::ChangeArgs& args) override; void OnViewModelAdded(gsl::index nIndex) override; void OnViewModelRemoved(gsl::index nIndex) override; void OnEndViewModelCollectionUpdate() override; private: gsl::index GetIndexForLine(gsl::index nLine) const; void UpdateLineBreaks(gsl::index nIndex, gsl::index nColumn, const ra::ui::win32::bindings::GridColumnBinding* pColumn, size_t nChars); static void GetLineBreaks(const std::wstring& sText, size_t nChars, std::vector<unsigned int>& vLineBreaks); void UpdateLineOffsets(); int GetMaxCharsForColumn(gsl::index nColumn) const; struct ItemMetrics { unsigned int nFirstLine = 0; unsigned int nNumLines = 1; std::map<int, std::vector<unsigned int>> mColumnLineOffsets; }; std::vector<ItemMetrics> m_vItemMetrics; gsl::index m_nLastClickedItem = 0; }; } // namespace bindings } // namespace win32 } // namespace ui } // namespace ra #endif // !RA_UI_WIN32_MULTILINEGRIDBINDING_H
36.5
139
0.769692
Jamiras
dd200071bfce5c6e220d3a598d1c6775aad5419a
1,070
cpp
C++
Ch 3 Paradigms/Dynamic Programming/Top Down/uva-10616-01Knapsack.cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
Ch 3 Paradigms/Dynamic Programming/Top Down/uva-10616-01Knapsack.cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
Ch 3 Paradigms/Dynamic Programming/Top Down/uva-10616-01Knapsack.cpp
sladewinter/UVa-Online-Judge
3e8003e8ae5452eed1468be44ae5d7bbcc763dd1
[ "MIT" ]
null
null
null
//Uva- 10616 - Divisible Group Sums #include <iostream> #include <cstring> using namespace std; using ll = long long; int N, Q, D, M; int arr[200]; ll memo[200][20][10]; //Index,Sum % 20,#Items picked ll knapsack( int idx, int sum, int m ) { if( idx + M - m > N ) //Impossible to collect M items return 0; if( m == M ) //Collected all M items return sum == 0; ll &comb{ memo[idx][sum][m] }; //Memoization if( comb != -1 ) return comb; comb = 0; //To guarantee that modulo is always +ve int rem{ ( ( (sum + arr[idx]) % D ) + D ) % D }; //Taking item arr[idx] comb += knapsack( idx + 1, rem, m + 1 ); //Not taking item arr[idx] comb += knapsack( idx + 1, sum, m ); return comb; } int main() { int setNo{ 0 }; while( scanf("%d %d", &N, &Q ), N ) { printf( "SET %d:\n", ++setNo ); for( int i{0}; i < N; ++i ) scanf( "%d", &arr[i] ); int Qno{ 0 }; while( Q-- ) { memset(memo, -1, sizeof(memo)); scanf( "%d %d", &D, &M ); printf("QUERY %d: %lld\n",++Qno,knapsack(0, 0, 0)); } } return 0; }
18.448276
59
0.530841
sladewinter
dd237c93e24ce9fe0246c6a0e207899a455714f3
2,610
cpp
C++
CApp.cpp
abishek-sampath/SDL-GameFramework
0194540851eeaff6b4563feefb8edae7ca868700
[ "MIT" ]
null
null
null
CApp.cpp
abishek-sampath/SDL-GameFramework
0194540851eeaff6b4563feefb8edae7ca868700
[ "MIT" ]
null
null
null
CApp.cpp
abishek-sampath/SDL-GameFramework
0194540851eeaff6b4563feefb8edae7ca868700
[ "MIT" ]
null
null
null
#include "CApp.h" #undef main CApp::CApp() { // SDL resources window = NULL; renderer = NULL; // User Resources resourceManager = NULL; running = true; score = 0; beginTime = 0; numb_lives_to_gen = PLAYER_MAX_HEALTH - 2; generateLives = true; } CApp::CApp(SDL_Renderer* renderer, ResourceManager* resourceManager) { // SDL resources window = NULL; this->renderer = renderer; // User Resources this->resourceManager = resourceManager; running = true; score = 0; beginTime = 0; numb_lives_to_gen = PLAYER_MAX_HEALTH - 2; generateLives = true; } int CApp::OnExecute() { if(OnInit() == false) { printf("Initialization failed!\n"); OnCleanup(); return -1; } SDL_Event event; while (running) { while (SDL_PollEvent(&event)) { OnEvent(&event); } OnLoop(); OnRender(); } if(score != -1) { // load the music file gameover_music = Mix_LoadMUS(GAMEOVER_MUSIC_FILE); if (gameover_music != NULL) { Mix_PlayMusic(gameover_music, -1); } // START display GameLost SDL_RenderClear(renderer); SDL_Color whiteColor = { 0xff, 0xff, 0xff }; FontTexture endMsgTexture; FontTexture endTexture; std::stringstream endMsg; endMsg << GAME_END_1 << score << GAME_END_2 << timeText.str() << GAME_END_3; resourceManager->loadFontTexture(endMsgTexture, endMsg.str(), &whiteColor, FONT_SIZE_SMALL, (SCREEN_WIDTH * 0.9)); endMsgTexture.render(renderer, (SCREEN_WIDTH * 0.05), (SCREEN_HEIGHT * 0.3)); resourceManager->loadFontTexture(endTexture, GAME_END, &whiteColor, FONT_SIZE_SMALL, (SCREEN_WIDTH * 0.9)); endTexture.render(renderer, (SCREEN_WIDTH * 0.05), (SCREEN_HEIGHT * 0.9)); SDL_RenderPresent(renderer); SDL_Event e; // remove events during delay SDL_Delay(1000); SDL_PumpEvents(); SDL_FlushEvent(SDL_KEYDOWN | SDL_QUIT); while(SDL_WaitEvent(&e)) { if (e.type == SDL_KEYDOWN || e.type == SDL_QUIT) { break; } } // set elaped time in milliseconds beginTime = SDL_GetTicks() - beginTime; // END display GameLost } OnCleanup(); return 0; } int main2(int argc, char* argv[]) { CApp theApp; return theApp.OnExecute(); } int CApp::GetFinalScore() { return score; } Uint32 CApp::GetFinalTime() { return beginTime; }
21.570248
122
0.586207
abishek-sampath
dd248d32555237459b88abf3d9a3703abb16eac6
174
hpp
C++
src/nSkinz.hpp
Massimoni/skinchanger
f2638f9cea2fe72340a62cc05d2d3c42cacc59ab
[ "MIT" ]
null
null
null
src/nSkinz.hpp
Massimoni/skinchanger
f2638f9cea2fe72340a62cc05d2d3c42cacc59ab
[ "MIT" ]
null
null
null
src/nSkinz.hpp
Massimoni/skinchanger
f2638f9cea2fe72340a62cc05d2d3c42cacc59ab
[ "MIT" ]
1
2019-05-23T11:09:42.000Z
2019-05-23T11:09:42.000Z
#pragma once #include "SDK.hpp" #include "RecvProxyHook.hpp" extern VMTHook* g_client_hook; extern VMTHook* g_game_event_manager_hook; extern RecvPropHook* g_sequence_hook;
21.75
42
0.821839
Massimoni
dd25f6c5d6c0376cd11b5e8d0bba88ddfba6a7d8
421
cpp
C++
src/math/agg_final.cpp
tarkmeper/numpgsql
a5098af9b7c4d88564092c0a4809029aab9f614f
[ "MIT" ]
5
2019-04-08T15:25:32.000Z
2019-12-07T16:31:55.000Z
src/math/agg_final.cpp
tarkmeper/numpgsql
a5098af9b7c4d88564092c0a4809029aab9f614f
[ "MIT" ]
null
null
null
src/math/agg_final.cpp
tarkmeper/numpgsql
a5098af9b7c4d88564092c0a4809029aab9f614f
[ "MIT" ]
null
null
null
#include "agg.hpp" extern "C" { PG_FUNCTION_INFO_V1(internal_to_array); Datum internal_to_array(PG_FUNCTION_ARGS); } Datum internal_to_array(PG_FUNCTION_ARGS) { //TODO trigger destructor Assert(AggCheckCallContext(fcinfo, NULL)); if (PG_ARGISNULL(0)) { PG_RETURN_NULL(); } else { AggInternal* state = (AggInternal*)(PG_GETARG_POINTER(0)); PG_RETURN_ARRAYTYPE_P( state->fnc(state) ); } }
21.05
63
0.712589
tarkmeper
dd269092067c738ec28eaa4435a0ab0069323c62
77,457
cpp
C++
IGC/Compiler/CISACodeGen/LinkTessControlShaderMCFPass.cpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
IGC/Compiler/CISACodeGen/LinkTessControlShaderMCFPass.cpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
IGC/Compiler/CISACodeGen/LinkTessControlShaderMCFPass.cpp
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======================= end_copyright_notice ==================================*/ #include "Compiler/CISACodeGen/LinkTessControlShaderMCFPass.h" #include "Compiler/IGCPassSupport.h" #include "common/LLVMWarningsPush.hpp" #include <llvm/IR/Constants.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/Function.h> #include <llvm/IR/InstVisitor.h> #include <llvm/IR/IRBuilder.h> #include "llvm/IR/Dominators.h" #include "llvm/IR/InstIterator.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include <llvmWrapper/IR/Function.h> #include <llvmWrapper/IR/InstrTypes.h> #include "llvm/Analysis/PostDominators.h" #include "llvm/Analysis/LoopInfo.h" #include "common/LLVMWarningsPop.hpp" #include "common/IGCIRBuilder.h" #include "Compiler/MetaDataUtilsWrapper.h" #include "Compiler/CodeGenPublic.h" using namespace llvm; using namespace IGC; using namespace IGC::IGCMD; // Summary: The role of this pass is to link the TCS generated by OGL FE // by adding a loop to loop through the number of output control points and // replace all occurrences of HSControlPointID with the loopCounter // When barriers are present in TCS this pass elimates them by splitting // a shader into multiple continuation functions (code between barriers, // see http ://compilers.cs.uni-saarland.de/papers/karrenberg_opencl.pdf ) // running every continuation function in a control point loop before // moving to the next phase. // Values that need to be passed between phases are converted into // global allocas and sized (arrays) by the number of control points. // Continuation functions receive pointers to proper global alloca entries // (i.e. indexed by control point ID) for data passing. namespace IGC { class LinkTessControlShaderMCF : public llvm::ModulePass { public: // Pass identification, replacement for typeid static char ID; static const uint32_t LARGE_INSTRUCTIONS_COUNT = 1000; /// @brief Constructor LinkTessControlShaderMCF(); ~LinkTessControlShaderMCF() { delete mpBuilder; }; /// @brief Provides name of pass virtual llvm::StringRef getPassName() const override { return "LinkTessControlShaderMCF"; } virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override { AU.addRequired<MetaDataUtilsWrapper>(); AU.addRequired<CodeGenContextWrapper>(); AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<PostDominatorTreeWrapperPass>(); } /// @brief Main entry point. /// @param F The current function. virtual bool runOnModule(llvm::Module& M) override; private: llvm::IGCIRBuilder<>* mpBuilder{ nullptr }; Module* mpModule{ nullptr }; DominatorTree* mpDT{ nullptr }; Function* mpMainFunction{ nullptr }; uint32_t mNumBarriers; uint32_t mOutputControlPointCount; uint32_t mNumInstructions; bool m_useMultipleHardwareThread; // SIMD size for tessellation workloads is SIMD8 static const uint32_t SIMDSize = 8; // Special state that indicates that program has exited. static const uint32_t ExitState = 0xFFFFFFFF; ////////////////////////////////////////////////////////////////////////// /// BarrierInfo ////////////////////////////////////////////////////////////////////////// struct BarrierInfo { uint32_t id{ 0 }; // Unique identifier }; std::vector<CallInst*> mBarriers; std::map<CallInst*, BarrierInfo> mBarrierInfo; std::vector<CallInst*> mBarriersPHIInLoop; std::vector<CallInst*> mMemoryFence; ////////////////////////////////////////////////////////////////////////// /// GlobalAllocas /// @brief Used to keep track of all alloca values that are live across /// barrier. ////////////////////////////////////////////////////////////////////////// typedef llvm::Value* global_alloca_key_t; class GlobalAllocas { std::map<global_alloca_key_t, Value*> mGlobalAllocas; bool mGlobalAllocasUpdated = { false }; public: /// @brief Returns LLVM type for the alloca specified by key. Type* GetType(global_alloca_key_t key) { assert(!mGlobalAllocasUpdated && "map updated - type no longer available"); Value* pVal = mGlobalAllocas[key]; assert(pVal && "global alloca not found!"); return pVal->getType(); } /// @brief Inserts alloca into a global map. void AddAllocaRef(Value* pAlloca) { assert(!mGlobalAllocasUpdated && "map updated - cannot add new allocas"); mGlobalAllocas[pAlloca] = pAlloca; } /// @brief Returns pointer to local alloca specified by key. Value* GetAllocaRef(global_alloca_key_t allocaKey) { assert(!mGlobalAllocasUpdated && "map updated - cannot reference local allocas"); return mGlobalAllocas[allocaKey]; } /// @brief Returns pointer to global alloca specified by key. Value* GetGlobalAlloca(global_alloca_key_t allocaKey) { assert(mGlobalAllocasUpdated && "map not yet updated - alloca not available"); return mGlobalAllocas[allocaKey]; } void MoveAllocas(Instruction* pInsert); void CreateGlobalAllocas(llvm::IGCIRBuilder<>& builder, uint32_t count); }; GlobalAllocas mGlobalAllocas; ////////////////////////////////////////////////////////////////////////// /// ContinuationFunction /// @brief Represents a sequence of basic blocks for a single shader phase /// (up to a barrier) and pointers to allocas that are used for /// accross barrier value passing. /// @todo Can change lists to vector. ////////////////////////////////////////////////////////////////////////// struct ContinuationFunction { uint32_t id{ 0 }; ///< This id is used for switch case. Function* pFunc{ nullptr }; BasicBlock* pEntry{ nullptr }; std::vector<BasicBlock*> exits; ///< terminator blocks std::vector<BasicBlock*> blocks; ///< blocks in a continuation function std::set<global_alloca_key_t> inputs; ///< global allocas for ins/outs }; std::set<global_alloca_key_t> fullInputsList; ////////////////////////////////////////////////////////////////////////// /// EdgeLives - Tracks all lives between edges in CFG. ////////////////////////////////////////////////////////////////////////// struct EdgeLives { BasicBlock* pFrom{ nullptr }; BasicBlock* pTo{ nullptr }; std::set<Value*> lives; }; std::map<BasicBlock*, EdgeLives> mEdgeLives; // Maps an entry block to each continuation function. std::map<BasicBlock*, ContinuationFunction> mEntryMap; std::vector<ContinuationFunction*> mContinuationFunctions; std::map<BasicBlock*, bool> mVisited; ////////////////////////////////////////////////////////////////////////// /// BasicBlockMeta ////////////////////////////////////////////////////////////////////////// struct BasicBlockMeta { bool isPreBarrierBlock{ false }; BarrierInfo* pBarrierInfo{ nullptr }; BarrierInfo* pPreBarrierInfo{ nullptr }; BasicBlock* pPostBarrierBlock{ nullptr }; }; // Maps metadata to basic blocks. std::map<BasicBlock*, BasicBlockMeta> mBlockMeta; // Each post barrier basic block will become an entry block for a continuation function. // The FunctionEntryBlock list contains all post-barrier blocks and the main entry block. std::vector<BasicBlock*> mFunctionEntryBlocks; // For 'switch' instructions each CF needs to receive full function arguments list. bool mIsPhiWith3OrMoreIncomingValues; ////////////////////////////////////////////////////////////////////////// /// Internal methods. ////////////////////////////////////////////////////////////////////////// /// Helper getters. llvm::IGCIRBuilder<>& Builder(void) { assert(mpBuilder); return *mpBuilder; } Module* GetModule(void) { assert(mpModule); return mpModule; } Function* GetMainFunction(void) { assert(mpMainFunction); return mpMainFunction; } DominatorTree* GetDT(void) { assert(mpDT); return mpDT; } ////////////////////////////////////////////////////////////////////////// /// @brief Returns true if basic block is a pre-barrier block. bool IsPreBarrierBlock(BasicBlock* pBlock) { BasicBlockMeta& meta = mBlockMeta[pBlock]; return (meta.isPreBarrierBlock); } ////////////////////////////////////////////////////////////////////////// /// @brief Returns true if basic block is a post barrier block. bool IsPostBarrierBlock(BasicBlock* pBlock) { BasicBlockMeta& meta = mBlockMeta[pBlock]; return (meta.pBarrierInfo != nullptr); } ////////////////////////////////////////////////////////////////////////// /// @brief Returns the immediate dominator for the current basic block. /// This is used by live-ness analysis to help walk up the CFG. BasicBlock* GetImmediateDominator(BasicBlock* pBlock) { assert(GetDT()->getNode(pBlock) != nullptr); DomTreeNode* pNode = GetDT()->getNode(pBlock)->getIDom(); return pNode ? pNode->getBlock() : nullptr; } // Forward declarations. HullShaderDispatchModes DetermineDispatchMode(void); void FindBarriers(Function& f); void ReplaceReturn(Function& f, uint32_t retValue); void SplitBasicBlocksAtBarriers(Function& f); void UnlinkPreBarrierBlocks(Function& f); void GetContinuationBlocks(BasicBlock* pCurBlock, ContinuationFunction& cf); bool IsBlockOutside(ContinuationFunction& cf, BasicBlock* pBlock); void AddLive(BasicBlock* pCurBlock, BasicBlock* pEndBlock, Instruction* pLive); void FindBarrierLives(Function& f); void ReplaceValueWithinBB(BasicBlock* pBlock, Value* pOld, Value* pNew); AllocaInst* ReplaceWithIntermittentAlloca(Instruction* pDef); void ReplaceLive(Value* pOld, Value* pNew); void ConvertBarrierLivesToAllocas(Function& f); void CollectArguments(ContinuationFunction& cf); void FixUpControlPointID(ContinuationFunction& cf); void DetectBarrierPHIInLoop(Function& cf); void FixUpHSControlPointIDVsGlobalVar(Function& f); void RemovePhiInstructions(Function& cf); void PurgeFunction(Function& f); void BuildContinuationFunction(ContinuationFunction& cf); void BuildContinuationFunctions(Function& f); void RebuildMainFunction(void); void TCSwHWBarriersSupport(MetaDataUtils* pMdUtils); bool SelectTCSwHWBarrierSupport(void); llvm::Function* CreateNewTCSFunction(llvm::Function* pCurrentFunc); }; char LinkTessControlShaderMCF::ID = 0; // Register pass to igc-opt #define PASS_FLAG "igc-LinkTessControlShaderMCF" #define PASS_DESCRIPTION "Perform looping of tessellation function based on control point count" #define PASS_CFG_ONLY false #define PASS_ANALYSIS false IGC_INITIALIZE_PASS_BEGIN(LinkTessControlShaderMCF, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS) IGC_INITIALIZE_PASS_END(LinkTessControlShaderMCF, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS) LinkTessControlShaderMCF::LinkTessControlShaderMCF() : llvm::ModulePass(ID), mNumBarriers(0), mOutputControlPointCount(0), mNumInstructions(0), m_useMultipleHardwareThread(false), mIsPhiWith3OrMoreIncomingValues(false) { initializeLinkTessControlShaderMCFPass(*llvm::PassRegistry::getPassRegistry()); } HullShaderDispatchModes LinkTessControlShaderMCF::DetermineDispatchMode(void) { llvm::NamedMDNode* metaData = GetModule()->getOrInsertNamedMetadata("HullShaderDispatchMode"); IGC::CodeGenContext* pCodeGenContext = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); /* Instance Count ** This field determines the number of threads(minus one) spawned per input patch. ** If the HS kernel uses a barrier function, software must restrict the Instance Count ** to the number of threads that can be simultaneously active within a subslice. ** Factors which must be considered includes scratch memory availability. ** Value Description ** [0, 15] representing[1, 16] instances */ // Use HS single patch if WA exists and input control points >= 29 as there are not enough registers for push constants bool useSinglePatch = false; if (pCodeGenContext->platform.WaDispatchGRFHWIssueInGSAndHSUnit()) { llvm::GlobalVariable* pGlobal = GetModule()->getGlobalVariable("TessInputControlPointCount"); if (pGlobal && pGlobal->hasInitializer()) { unsigned int inputControlPointCount = int_cast<unsigned int>(llvm::cast<llvm::ConstantInt>(pGlobal->getInitializer())->getZExtValue()); if (inputControlPointCount >= 29) { useSinglePatch = true; } } } if (pCodeGenContext->platform.useOnlyEightPatchDispatchHS() || (pCodeGenContext->platform.supportHSEightPatchDispatch() && !(m_useMultipleHardwareThread && mOutputControlPointCount >= 16) && !useSinglePatch && IGC_IS_FLAG_DISABLED(EnableHSSinglePatchDispatch))) { Constant* cval = llvm::ConstantInt::get( Builder().getInt32Ty(), HullShaderDispatchModes::EIGHT_PATCH_DISPATCH_MODE); llvm::MDNode* mdNode = llvm::MDNode::get( Builder().getContext(), llvm::ConstantAsMetadata::get(cval)); metaData->addOperand(mdNode); return HullShaderDispatchModes::EIGHT_PATCH_DISPATCH_MODE; } else { Constant* cval = llvm::ConstantInt::get( Builder().getInt32Ty(), HullShaderDispatchModes::SINGLE_PATCH_DISPATCH_MODE); llvm::MDNode* mdNode = llvm::MDNode::get( Builder().getContext(), llvm::ConstantAsMetadata::get(cval)); metaData->addOperand(mdNode); return HullShaderDispatchModes::SINGLE_PATCH_DISPATCH_MODE; } } ////////////////////////////////////////////////////////////////////////// /// @brief Finds all barriers in program and populates barrier info. /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::FindBarriers(Function& f) { mNumBarriers = 0; for (auto i = inst_begin(f), e = inst_end(f); i != e; ++i) { Instruction& inst = cast<Instruction>(*i); mNumInstructions++; if (GenIntrinsicInst * pInst = dyn_cast<GenIntrinsicInst>(&inst)) { GenISAIntrinsic::ID IID = pInst->getIntrinsicID(); if (IID == GenISAIntrinsic::GenISA_threadgroupbarrier) { BarrierInfo& info = mBarrierInfo[pInst]; if (info.id > 0) continue; mNumBarriers++; info.id = mNumBarriers; // id starts at 1. mBarriers.push_back(pInst); } if (IID == GenISAIntrinsic::GenISA_memoryfence) { // MemoryFence inst is going to be removed for MCF solution. mMemoryFence.push_back(pInst); } } else if (PHINode * pPhi = dyn_cast<PHINode>(&inst)) { // Set this member only when 'barrier' instr is before PHI. mIsPhiWith3OrMoreIncomingValues = ((pPhi->getNumIncomingValues() >= 3) && (mNumBarriers > 0)); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Replace original returns (void) with our exit marker ret(0xFFFFFFFF). /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::ReplaceReturn(Function& f, uint32_t retValue) { SmallVector<Instruction*, 8> retInstructions; for (inst_iterator i = inst_begin(f), e = inst_end(f); i != e; ++i) { Instruction* pInst = &(*i); if (isa<ReturnInst>(pInst)) { retInstructions.push_back(pInst); } } for (Instruction* pRet : retInstructions) { Builder().SetInsertPoint(pRet); Builder().CreateRet(Builder().getInt32(retValue)); pRet->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Splits all basic blocks with barriers and setup meta info. /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::SplitBasicBlocksAtBarriers(Function& f) { mFunctionEntryBlocks.push_back(&f.getEntryBlock()); for (auto pBarrier : mBarriers) { BasicBlock* pBarrierBlock = pBarrier->getParent(); assert(pBarrierBlock != nullptr); Builder().SetInsertPoint(pBarrier); BarrierInfo& info = mBarrierInfo[pBarrier]; llvm::StringRef name = pBarrierBlock->getName(); std::string postfix = std::string(".postbarrier.") + std::to_string(info.id); BasicBlock* pPostBarrierBlock = pBarrierBlock->splitBasicBlock(pBarrier->getNextNode(), name + postfix.c_str()); // Check whether the current barrier instruction is on the mBarriersPHIInLoop list. // This solution handles only barriers within loop in one BB i.e. without any control flow. for (auto pLocBarrier : mBarriersPHIInLoop) { if (pLocBarrier->getParent() == pBarrierBlock) { for (BasicBlock::iterator i = pPostBarrierBlock->begin(), e = pPostBarrierBlock->end(); i != e; ++i) { Instruction* pInst = &(*i); if (llvm::BranchInst * pBrInst = dyn_cast<BranchInst>(pInst)) { // Replace : br COND, BB_IF_TRUE, BB_IF_FALSE // with : br COND, BB_IF_TRUE.postbarrier, BB_IF_FALSE Builder().SetInsertPoint(pInst); BranchInst::Create(pPostBarrierBlock, pBrInst->getSuccessor(1), pBrInst->getCondition(), pPostBarrierBlock); pInst->eraseFromParent(); break; } } break; } } // Each post barrier basic block is an entry block for a continuation function. mFunctionEntryBlocks.push_back(pPostBarrierBlock); // The pBarrierBlock is now the pre-barrier block after the split. BasicBlockMeta& preBarrierMeta = mBlockMeta[pBarrierBlock]; preBarrierMeta.isPreBarrierBlock = true; preBarrierMeta.pPreBarrierInfo = &info; preBarrierMeta.pPostBarrierBlock = pPostBarrierBlock; BasicBlockMeta& postBarrierMeta = mBlockMeta[pPostBarrierBlock]; postBarrierMeta.pBarrierInfo = &info; EdgeLives& edge = mEdgeLives[pPostBarrierBlock]; edge.pFrom = pBarrierBlock; edge.pTo = pPostBarrierBlock; } // Remove barrier instructions. for (auto pBarrier : mBarriers) { pBarrier->eraseFromParent(); } mBarriers.clear(); // Remove barrier instructions from 'in loop' sections of code. mBarriersPHIInLoop.clear(); // Remove 'memory fence' instructions. for (auto pMemoryFence : mMemoryFence) { pMemoryFence->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief For each pre-barrier block insert new return instruction /// and remove original terminator. These new returns will be used /// by continuation functions. /// @param f- The function we're working on with this pass. void LinkTessControlShaderMCF::UnlinkPreBarrierBlocks(Function& f) { for (BasicBlock& basicBlock : f.getBasicBlockList()) { BasicBlock* pBasicBlock = &basicBlock; if (IsPreBarrierBlock(pBasicBlock)) { BasicBlockMeta& meta = mBlockMeta[pBasicBlock]; // Insert return(n) that will be used by continuation function. Builder().SetInsertPoint(pBasicBlock->getTerminator()); Builder().CreateRet(Builder().getInt32(meta.pPreBarrierInfo->id)); // Unlink the pre-barrier block from the post-barrier block by removing // original terminator. pBasicBlock->getTerminator()->eraseFromParent(); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Finds all blocks that belong to a continuation function. /// @param pCurBlock - Current block in depth-first traversal. /// @param cf - Continuation function we're adding to. void LinkTessControlShaderMCF::GetContinuationBlocks(BasicBlock* pCurBlock, ContinuationFunction& cf) { // If we have already visited this node then can end traversal. if (mVisited[pCurBlock] == true) { return; } mVisited[pCurBlock] = true; BasicBlockMeta& meta = mBlockMeta[pCurBlock]; cf.blocks.push_back(pCurBlock); // If the current block is pre-barrier block then end traversal. if (meta.isPreBarrierBlock) { cf.exits.push_back(pCurBlock); return; } uint32_t numSuccessors = 0; for (auto i = succ_begin(pCurBlock), e = succ_end(pCurBlock); i != e; ++i) { BasicBlock* pSuccessor = *i; GetContinuationBlocks(pSuccessor, cf); numSuccessors++; } if (numSuccessors == 0) { cf.exits.push_back(pCurBlock); } } ////////////////////////////////////////////////////////////////////////// /// @brief Return true if basic block does not belong to CF. /// @param cf - current continuation function /// @param pBlock - Block we're testing bool LinkTessControlShaderMCF::IsBlockOutside(ContinuationFunction& cf, BasicBlock* pBlock) { for (auto pCfBlock : cf.blocks) { if (pCfBlock == pBlock) { return false; } } return true; } ////////////////////////////////////////////////////////////////////////// /// @brief This walks the CFG from the current block to the end block /// and if it finds a post-barrier block along the way then it /// adds the "live" to the edge between pre and post barrier blocks. /// These lives are later used to generate spill/fills. void LinkTessControlShaderMCF::AddLive(BasicBlock* pCurBlock, BasicBlock* pEndBlock, Instruction* pLive) { if (mVisited[pCurBlock] == true) { return; } mVisited[pCurBlock] = true; if (pCurBlock != pEndBlock) { for (auto i = pred_begin(pCurBlock), end = pred_end(pCurBlock); i != end; ++i) { BasicBlock* pPredBlock = *i; if (pPredBlock != pEndBlock) { AddLive(pPredBlock, pEndBlock, pLive); } } } if (IsPostBarrierBlock(pCurBlock)) { EdgeLives& edge = mEdgeLives[pCurBlock]; edge.lives.insert(pLive); } } ////////////////////////////////////////////////////////////////////////// /// @brief Analyzes all instructions in the function and for each use /// determines the live range. If any barrier falls within this live /// range then we need to generate a spill/fill. /// @note Post-barrier blocks should never contain a phi. Algorithm assumes that. void LinkTessControlShaderMCF::FindBarrierLives(Function& f) { // Update dominator tree. mpDT = &getAnalysis<DominatorTreeWrapperPass>(*GetMainFunction()).getDomTree(); for (auto i = inst_begin(f), e = inst_end(f); i != e; ++i) { Instruction* pDef = &*i; BasicBlock* pDefBlock = pDef->getParent(); for (User* pUser : pDef->users()) { Instruction* pUserInst = cast<Instruction>(pUser); BasicBlock* pUseBlock = pUserInst->getParent(); if (PHINode * pPhi = dyn_cast<PHINode>(pUser)) { for (uint32_t incoming = 0; incoming < pPhi->getNumIncomingValues(); ++incoming) { if (pPhi->getIncomingValue(incoming) == pDef) { pUseBlock = pPhi->getIncomingBlock(incoming); break; } } } while (pDefBlock != pUseBlock) { BasicBlock* pIDom = GetImmediateDominator(pUseBlock); if (pIDom) { mVisited.clear(); // Reset visited for next traversal. AddLive(pUseBlock, pIDom, pDef); } pUseBlock = pIDom; } } } mVisited.clear(); // Reset visited for future use. } ////////////////////////////////////////////////////////////////////////// /// @brief Replace all uses of old value with a new value within BB only. void LinkTessControlShaderMCF::ReplaceValueWithinBB(BasicBlock* pBlock, Value* pOld, Value* pNew) { std::set<llvm::Use*> useList; for (auto ui = pOld->use_begin(), ue = pOld->use_end(); ui != ue; ++ui) { Use& use = *ui; Instruction* pUser = dyn_cast<Instruction>(use.getUser()); if (pUser && pUser->getParent() == pBlock) { useList.insert(&use); } } for (auto pUse : useList) { pUse->set(pNew); } } ////////////////////////////////////////////////////////////////////////// /// @brief Create intermittent alloca for a value and add loads for uses. /// @param def - value to be processed through alloca. AllocaInst* LinkTessControlShaderMCF::ReplaceWithIntermittentAlloca(Instruction* pDef) { assert(pDef); Type* pType = pDef->getType(); BasicBlock* pDefBlock = pDef->getParent(); std::string defName = pDef->getName(); std::string newName = "l_" + defName; // Start with inserting new alloca after defining instruction. BasicBlock::iterator ii(pDef); Builder().SetInsertPoint(&(*(++ii))); AllocaInst* pAlloca = Builder().CreateAlloca(pType, nullptr, VALUE_NAME(defName)); // Add load new value. // We replace def value even within defining BB just to be sure // alghorithm is consistent. Compiler will optimize this later. Value* pNewValue = Builder().CreateLoad(pAlloca, VALUE_NAME(newName)); // Step 1. // Insert load instruction in all post-barrier basic blocks, // where this value is used. std::map<BasicBlock*, Value*> loadedValueMap; mVisited.clear(); loadedValueMap[pDefBlock] = pNewValue; mVisited[pDefBlock] = true; for (auto ui = pDef->user_begin(), ue = pDef->user_end(); ui != ue; ++ui) { Instruction* pUser = cast<Instruction>(*ui); BasicBlock* pUseBlock = pUser->getParent(); PHINode* pPhi = dyn_cast<PHINode>(pDef); // For phi instructions actual use block is incoming one. if (pPhi != nullptr) { uint32_t numIncoming = pPhi->getNumIncomingValues(); for (uint32_t incoming = 0; incoming < numIncoming; ++incoming) { if (pPhi->getIncomingValue(incoming) == pDef) { pUseBlock = pPhi->getIncomingBlock(incoming); break; } } } if (!mVisited[pUseBlock]) { mVisited[pUseBlock] = true; Builder().SetInsertPoint(pUseBlock->getFirstNonPHI()); Value* pNewValue = Builder().CreateLoad(pAlloca, VALUE_NAME(newName)); loadedValueMap[pUseBlock] = pNewValue; } } mVisited.clear(); // Step 2. // Replace all uses. // while (pDef->use_begin() != pDef->use_end()) { Instruction* pUser = cast<Instruction>(pDef->use_begin()->getUser()); BasicBlock* pUseBlock = pUser->getParent(); PHINode* pPhi = dyn_cast<PHINode>(pDef); // For phi instructions actual use block is incoming one. if (pPhi != nullptr) { uint32_t numIncoming = pPhi->getNumIncomingValues(); for (uint32_t incoming = 0; incoming < numIncoming; ++incoming) { if (pPhi->getIncomingValue(incoming) == pDef) { pUseBlock = pPhi->getIncomingBlock(incoming); break; } } } // If we have new value fetched for the block already, then use it as replacement, // if not, then walk up dominance tree to find the correct one. auto mi = loadedValueMap.find(pUseBlock); pNewValue = (*mi).second; assert(pNewValue && "loaded value not found for added alloca!!!"); if (pNewValue != pDef) { ReplaceValueWithinBB(pUseBlock, pDef, pNewValue); } } // Add 'store' inst for storing an old value. BasicBlock::iterator bbi(pAlloca); Builder().SetInsertPoint(&(*++bbi)); Builder().CreateStore(pDef, pAlloca); return pAlloca; } ////////////////////////////////////////////////////////////////////////// /// @brief Replace live value marked in our tables with a new one. void LinkTessControlShaderMCF::ReplaceLive(Value* pOld, Value* pNew) { for (auto& edgeMapEntry : mEdgeLives) { EdgeLives& edge = edgeMapEntry.second; auto pos = edge.lives.find(pOld); if (pos != edge.lives.end()) { edge.lives.erase(pos); edge.lives.insert(pNew); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Make any values crossing barriers to use intermittent allocas. /// Alghoritm depends on only allocas being live at barriers; // these are then moved to main function and converted into // continuation function arguments. void LinkTessControlShaderMCF::ConvertBarrierLivesToAllocas(Function& f) { for (auto edgeMapEntry : mEdgeLives) { EdgeLives& edge = edgeMapEntry.second; for (Value* pLive : edge.lives) { Instruction* pInst = cast<Instruction>(pLive); // If it's not alloca, create an intermittent alloca // and make all uses go through it. if (!isa<AllocaInst>(pInst)) { Instruction* pNewDef = ReplaceWithIntermittentAlloca(pInst); ReplaceLive(pLive, pNewDef); } } } } ////////////////////////////////////////////////////////////////////////// /// @brief Collects information about lives across barrier boundaries. void LinkTessControlShaderMCF::CollectArguments(ContinuationFunction& cf) { // First continuation function should not have live-ins. assert(cf.id != 0 || mEdgeLives[cf.pEntry].lives.size() == 0); // Generate inputs first. EdgeLives& edge = mEdgeLives[cf.pEntry]; for (auto& pLive : edge.lives) { Instruction* pInst = dyn_cast<Instruction>(pLive); assert(isa<AllocaInst>(pInst)); cf.inputs.insert(pLive); mGlobalAllocas.AddAllocaRef(pLive); } if (mIsPhiWith3OrMoreIncomingValues) { // For 'switch' inst scenarios, each CF needs to get a complete list of arguments. for (auto inputArg : fullInputsList) { cf.inputs.insert(inputArg); } } // Generate outputs. for (auto& pExit : cf.exits) { BasicBlockMeta& meta = mBlockMeta[pExit]; if (meta.isPreBarrierBlock) { BasicBlock* pPostBarrier = meta.pPostBarrierBlock; assert(pPostBarrier != nullptr); EdgeLives& edge = mEdgeLives[pPostBarrier]; assert((edge.pFrom != nullptr) && (pExit == edge.pFrom)); for (auto pLive : edge.lives) { Instruction* pInst = dyn_cast<Instruction>(pLive); assert(isa<AllocaInst>(pInst)); cf.inputs.insert(pLive); mGlobalAllocas.AddAllocaRef(pLive); if (mIsPhiWith3OrMoreIncomingValues) { // Collect input arguments from each CF. fullInputsList.insert(pLive); } } } } } ////////////////////////////////////////////////////////////////////////// /// @brief Replace all uses of @genISA.DCL.HSControlPointID() with /// first argument of continuation function. /// @param cf - current continuation function void LinkTessControlShaderMCF::FixUpControlPointID(ContinuationFunction& cf) { SmallVector<Instruction*, 10> instructionToRemove; llvm::Value* pHSControlPointID = llvm::GenISAIntrinsic::getDeclaration( cf.pFunc->getParent(), GenISAIntrinsic::GenISA_DCL_HSControlPointID); Argument* arg0 = &(*cf.pFunc->arg_begin()); for (Value::user_iterator i = pHSControlPointID->user_begin(), e = pHSControlPointID->user_end(); i != e; ++i) { Instruction* useInst = cast<Instruction>(*i); if (useInst->getParent()->getParent() == cf.pFunc) { instructionToRemove.push_back(useInst); useInst->replaceAllUsesWith(arg0); } } for (auto& inst : instructionToRemove) { inst->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Detect whether barrier inst is within 'inloop' section. /// For such scenarios each relevant PHI instruction must be /// replaced with set of alloca/store/load/store. /// See RemovePhiInstructions description. /// @param f - main function void LinkTessControlShaderMCF::DetectBarrierPHIInLoop(Function& f) { // Examine only BB which contains Barrier instruction. for (auto pBarrier : mBarriers) { BasicBlock* pBarrierBlock = pBarrier->getParent(); assert(pBarrierBlock != nullptr); bool isPHIInBB = false; bool isBarrierInLoop = false; for (BasicBlock::iterator i = pBarrierBlock->begin(), e = pBarrierBlock->end(); i != e; ++i) { Instruction* pInst = &(*i); if (dyn_cast<PHINode>(pInst)) { isPHIInBB = true; } else if (llvm::BranchInst * pBrInst = dyn_cast<BranchInst>(pInst)) { // Check whether any of successors(i.e. BB) matches pBarrierBlock. for (unsigned int successorId = 0; successorId < pBrInst->getNumSuccessors(); ++successorId) { isBarrierInLoop = (pBrInst->getSuccessor(successorId) == pBarrierBlock) ? true : isBarrierInLoop; } } } if (isPHIInBB && isBarrierInLoop) { // Barrier and PHI instructions are in the loop. // Store Barrier instruction , this data is needed in the RemovePhiInstructions. // This solution handles only barriers within loop in one BB i.e. without any control flow. mBarriersPHIInLoop.push_back(pBarrier); } } } ////////////////////////////////////////////////////////////////////////// /// @brief Replace each relevant PHI instruction with /// set of alloca/store/load/store. /// E.g. /// %Temp-91.i.i = phi float [ %Temp-87.i.i, %MainCode ], [ %Temp-92.i.i, %Label-88.i.i ] /// --> /// %Temp-91.i.i28 = alloca float /// store float %Temp-87.i.i, float* %Temp-91.i.i28 /// ( Label.postbarrier: ) <-- added by SplitBasicBlocksAtBarriers() /// %Temp-91.i.i29 = load float* %Temp-91.i.i28 /// store float %Temp-92.i.i, float* %Temp-91.i.i28 /// @param f - main function void LinkTessControlShaderMCF::RemovePhiInstructions(Function& f) { SmallVector<Instruction*, 4> phiToRemove; // Do removal of PHI instructions only in BB which contains Barrier and PHI in the loop. // This solution handles only barriers within loop in one BB i.e. without any control flow. for (auto pBarrier : mBarriersPHIInLoop) { BasicBlock* pBarrierBlock = pBarrier->getParent(); Instruction* pBarrierInst = cast<Instruction>(pBarrier); for (BasicBlock::iterator i = pBarrierBlock->begin(), e = pBarrierBlock->end(); i != e; ++i) { Instruction* pDef = &*i; if (PHINode * pPhi = dyn_cast<PHINode>(pDef)) { phiToRemove.push_back(pPhi); std::string defName = pPhi->getName(); std::string newName = pDef->getName(); Type* pType = pPhi->getType(); BasicBlock::iterator ii(pDef); Builder().SetInsertPoint(&(*ii)); // 1. Create 'alloca' inst to store incoming values to PHI instruction. AllocaInst* pAllocaPHI = Builder().CreateAlloca(pType, nullptr, VALUE_NAME(defName)); // 2. Create 'store' inst to store the 1st out of the PHI incoming values. Instruction* pIncoming1stDef = cast<Instruction>(pPhi->getIncomingValue(0)); Builder().CreateStore(pIncoming1stDef, pAllocaPHI); // 3. Create 'load' inst after barrier inst to load one of the PHI incoming values. // This instruction loads firstly the value from the 1st PHI incoming values // and secondly,later the 2nd PHI incoming value. BasicBlock::iterator iAfterThreadBarrier(pBarrierInst); Builder().SetInsertPoint(&(*++iAfterThreadBarrier)); Value* pNewValue = Builder().CreateLoad(pAllocaPHI, VALUE_NAME(newName)); // 4. Create 'store' inst to store the 2nd out of the PHI incoming values. Instruction* pIncoming2ndDef = cast<Instruction>(pPhi->getIncomingValue(1)); BasicBlock::iterator iAfterIncoming2ndDef(pIncoming2ndDef); Builder().SetInsertPoint(&(*++iAfterIncoming2ndDef)); Builder().CreateStore(pIncoming2ndDef, pAllocaPHI); pPhi->replaceAllUsesWith(pNewValue); } } } for (auto& phiInst : phiToRemove) { phiInst->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Makes a "shell" function removing all basic blocks. /// @param f - The function we're working on. void LinkTessControlShaderMCF::PurgeFunction(Function& f) { std::vector<BasicBlock*> blocksToRemove; // Find blocks to be removed. for (Function::iterator bb = f.begin(), be = f.end(); bb != be; ++bb) { BasicBlock* pBlock = &*bb; if (pBlock->getParent() == &f) { blocksToRemove.push_back(pBlock); pBlock->dropAllReferences(); } } for (BasicBlock* pBlock : blocksToRemove) { pBlock->eraseFromParent(); } } ////////////////////////////////////////////////////////////////////////// /// @brief Builds LLVM function for continuation. /// @param cf - The continuation function we're working on. void LinkTessControlShaderMCF::BuildContinuationFunction(ContinuationFunction& cf) { Function* pMainFunc = GetMainFunction(); // We don't expect main function to have any arguments. assert(pMainFunc->arg_begin() == pMainFunc->arg_end()); // Prepare argument list for a function. std::vector<Type*> argTypes; argTypes.push_back(Builder().getInt32Ty()); // CPId for (auto alloca_key : cf.inputs) { argTypes.push_back(mGlobalAllocas.GetType(alloca_key)); } std::string funcName = std::string("tcs.phase.") + std::to_string(cf.id); cf.pFunc = Function::Create( FunctionType::get(Builder().getInt32Ty(), argTypes, false), llvm::GlobalValue::PrivateLinkage, funcName, mpModule); cf.pFunc->addFnAttr(llvm::Attribute::AlwaysInline); // Map ValueToValueMapTy vmap; SmallVector<ReturnInst*, 8> returns; // Loop over the arguments, copying the names of the mapped arguments over... Function::arg_iterator ai = cf.pFunc->arg_begin(); ai->setName("CPId"); ++ai; for (auto ii : cf.inputs) { const Value* pVal = mGlobalAllocas.GetAllocaRef(ii); if (vmap.count(pVal) == 0) { // Copy the name over... ai->setName("arg" + pVal->getName()); // Add mapping to ValueMap vmap[pVal] = static_cast<Argument*>(&*ai); ++ai; } } // Fix up starting block, by moving it to the function beginning. cf.pEntry->moveBefore(&*(pMainFunc->begin())); CloneAndPruneFunctionInto(cf.pFunc, pMainFunc, vmap, false, returns); FixUpControlPointID(cf); } ////////////////////////////////////////////////////////////////////////// /// @brief Replace each usage of global loaded from HSControlPointID by /// a call directly to it. As a result, instead of having one load /// of CPID and multiple usages of the global variable initialized /// by that value, there are calls to HSControlPointID before each /// usage. /// E.g. /// See method replacing the 'load' instructions that reference to /// global variable which stores the CPId value with /// HSControlPointID() calls. /// /// FROM --> /// % 3 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() /// store i32 % 3, i32* @0 /// . . . /// % 4 = load i32, i32* @0 /// . . . /// % 10 = insertelement <4 x i32> <i32 0, i32 0, i32 undef, i32 1>, i32 % 4, i32 2 /// /// TO --> /// % 3 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() /// store i32 % 3, i32* @0 /// . . . /// % 4 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() /// . . . /// % 10 = insertelement <4 x i32> <i32 0, i32 0, i32 undef, i32 1>, i32 % 4, i32 2 /// /// /// @param f - The function we're working on. void LinkTessControlShaderMCF::FixUpHSControlPointIDVsGlobalVar(Function& f) { SmallVector<Instruction*, 10> instructionToUpdate; llvm::Value* pHSControlPointID = llvm::GenISAIntrinsic::getDeclaration( f.getParent(), GenISAIntrinsic::GenISA_DCL_HSControlPointID); // Pass through usages of the call to HSControlPointID. // e.g.: %3 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() // %16 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() for (Value::user_iterator i = pHSControlPointID->user_begin(), e = pHSControlPointID->user_end(); i != e; ++i) { Instruction* useInst = cast<Instruction>(*i); // Pass through the usages of the each HSControlPointID's call result. // e.g.: call void @llvm.genx.GenISA.OutputTessControlPoint(float %19, float %20, float %21, float %22, i32 %11, i32 %16, i32 %17) // store i32 %3, i32* @0 for (Value::user_iterator _i = useInst->user_begin(), _e = useInst->user_end(); _i != _e; ++_i) { // Find the 'store' instr and check if it is storing local val(i.e.the result of HSControlPointID's call) into a global variable. // e.g.: store i32 %3, i32* @0 if (llvm::StoreInst * storeInst = llvm::dyn_cast<llvm::StoreInst>(*_i)) { llvm::Value* op1 = storeInst->getOperand(1); if (isa<GlobalVariable>(op1)) { // Pass through usages of that global to find load instructions to replace. // e.g.: %5 = load i32, i32* @0 // % 4 = load i32, i32* @0 for (auto ui = op1->user_begin(), ue = op1->user_end(); ui != ue; ++ui) { if (llvm::LoadInst * ldInst = llvm::dyn_cast<llvm::LoadInst>(*ui)) { instructionToUpdate.push_back(ldInst); } } } } } } // Do the actual replacement of global variable to variable resulting // from call to HSControlPointID. for (auto& ldInst : instructionToUpdate) { Builder().SetInsertPoint(ldInst); llvm::Value* pCPId = Builder().CreateCall(pHSControlPointID); ldInst->replaceAllUsesWith(pCPId); ldInst->eraseFromParent(); // e.g.: %4 = load i32, i32* @0 <--replaced with --> %4 = call i32 @llvm.genx.GenISA.DCL.HSControlPointID() } } ////////////////////////////////////////////////////////////////////////// /// @brief Constructs a set of barrier-free functions from a main function /// that contains barriers. Each new function is called a continuation /// function that contains all of the basic blocks up to a barrier. /// @param f - Main function we're breaking up into multiple functions. void LinkTessControlShaderMCF::BuildContinuationFunctions(Function& f) { FixUpHSControlPointIDVsGlobalVar(f); DetectBarrierPHIInLoop(f); RemovePhiInstructions(f); SplitBasicBlocksAtBarriers(f); FindBarrierLives(f); ConvertBarrierLivesToAllocas(f); // Perform a depth-first traversal from each continuation entry // basic block to find all blocks that belong to each continuation // function. Traversal for each continuation function ends when a // pre-barrier block is hit or the final return block. for (auto pEntry : mFunctionEntryBlocks) { // Effectively we're allocating the Continuation Function with the entry map. ContinuationFunction& cf = mEntryMap[pEntry]; cf.pEntry = pEntry; BasicBlockMeta& meta = mBlockMeta[pEntry]; if (meta.pBarrierInfo != nullptr) { cf.id = meta.pBarrierInfo->id; } GetContinuationBlocks(pEntry, cf); // We'll traverse this list and build continuation functions from this. mContinuationFunctions.push_back(&cf); // Reset the visited list for generating next continuation function. mVisited.clear(); } // Collect arguments for continuation functions. for (auto pCF : mContinuationFunctions) { CollectArguments(*pCF); } // Here we are done with analysis. // Now we create actual continuation functions through transforming // and cloning the main function. // Replace existing returns with ret(-1) which marks end of program. ReplaceReturn(f, ExitState); // Remove BR instructions linking pre- and post-barrier blocks and replace // them with ret(N) instructions (where N is barrier id). UnlinkPreBarrierBlocks(f); // Create new basic block to temporary hold all global allocas, // and move allocas into it. This way alloca instructions won't be cloned // into continuation functions. BasicBlock* pEntry = &(f.getEntryBlock()); BasicBlock* pAllocaBlock = BasicBlock::Create( GetModule()->getContext(), VALUE_NAME("alloca_block"), &f, pEntry); Instruction* pTerminator = BranchInst::Create(pEntry, pAllocaBlock); mGlobalAllocas.MoveAllocas(pTerminator); for (auto pCF : mContinuationFunctions) { BuildContinuationFunction(*pCF); } } ////////////////////////////////////////////////////////////////////////// /// @brief Moves global allocas to the BB specified by insertion point. /// @param pIsert - Insertion point. void LinkTessControlShaderMCF::GlobalAllocas::MoveAllocas(Instruction* pInsert) { assert(pInsert); for (auto& ai : mGlobalAllocas) { Instruction* pAllocaInst = cast<Instruction>(ai.second); pAllocaInst->moveBefore(pInsert); } } ////////////////////////////////////////////////////////////////////////// /// @brief Creates global allocas for values shared between phases. /// @param arraySize - number of elements in allocas. /// @note Caller should set IRBuilder insert point. void LinkTessControlShaderMCF::GlobalAllocas::CreateGlobalAllocas( llvm::IGCIRBuilder<>& builder, uint32_t arraySize) { std::string suffix = "[" + std::to_string(arraySize) + "]"; for (auto& ai : mGlobalAllocas) { Value* pOldAlloca = ai.second; std::string name = pOldAlloca->getName().str() + suffix; Type* oldType = pOldAlloca->getType()->getPointerElementType(); Type* allocaType = ArrayType::get(oldType, arraySize); Value* pAlloca = builder.CreateAlloca(allocaType, nullptr, name); ai.second = pAlloca; } mGlobalAllocasUpdated = true; } ////////////////////////////////////////////////////////////////////////// /// @brief Builds the wrapper function that calls the continuation /// functions. Each continuation function returns a state. The /// wrapper implements a state machine using while loop and a switch. /// @param f- The original function. void LinkTessControlShaderMCF::RebuildMainFunction() { LLVMContext& ctx = GetModule()->getContext(); std::string oldEntryFuncName = GetMainFunction()->getName().str(); // Need to create unconnected entry block for the new function first, // Because we need info from old main function to create global allocas. BasicBlock* pEntry = BasicBlock::Create(ctx, oldEntryFuncName); Builder().SetInsertPoint(pEntry); mGlobalAllocas.CreateGlobalAllocas(Builder(), mOutputControlPointCount); // Now we can delete old function. PurgeFunction(*GetMainFunction()); Function* pNewFunc = GetMainFunction(); // Determine the dispatch mode HullShaderDispatchModes dispatchMode = DetermineDispatchMode(); // Create new basic blocks for main function. pEntry->insertInto(pNewFunc); BasicBlock* pStateLoopHeader = BasicBlock::Create(ctx, "state_loop_header", pNewFunc); BasicBlock* pStateDone = BasicBlock::Create(ctx, "state_done", pNewFunc); BasicBlock* pExit = BasicBlock::Create(ctx, "exit", pNewFunc); Value* pConstant0 = llvm::ConstantInt::get(Builder().getInt32Ty(), 0); Value* pLoopLimit = llvm::ConstantInt::get(Builder().getInt32Ty(), mOutputControlPointCount); Value* pBaseCPID = nullptr; Value* pCpidIncrement = nullptr; // Map to keep pointers to global alloca variables. std::map<size_t, Value*> allocas; // Create rest of the entry block, setting starting CPID value and adding block terminator branch. // Starting CPID is zero for EIGHT_PATCH dispatch and lane ID for SINGLE_PATCH. Builder().SetInsertPoint(pEntry); switch (dispatchMode) { case SINGLE_PATCH_DISPATCH_MODE: // In single patch mode we will need SIMD lane ID to calculate CPID. { Value* pSimdLane = Builder().CreateCall( GenISAIntrinsic::getDeclaration(pNewFunc->getParent(), GenISAIntrinsic::GenISA_simdLaneId), None, VALUE_NAME("simd_lane_id")); pBaseCPID = Builder().CreateZExt(pSimdLane, Builder().getInt32Ty()); pCpidIncrement = llvm::ConstantInt::get(Builder().getInt32Ty(), SIMDSize); } break; case EIGHT_PATCH_DISPATCH_MODE: pBaseCPID = pConstant0; pCpidIncrement = llvm::ConstantInt::get(Builder().getInt32Ty(), 1); break; default: assert(0 && "should not reach here"); break; } Builder().CreateBr(pStateLoopHeader); // The barrier state machine part. It consists of the loop enclosing switch // over the next state == barrier ID. Loop is finished when the next state is (-1). Builder().SetInsertPoint(pStateDone); PHINode* pNextStatePhi = Builder().CreatePHI(Builder().getInt32Ty(), mContinuationFunctions.size(), VALUE_NAME("next_state_phi")); Builder().SetInsertPoint(pStateLoopHeader); PHINode* pStatePhi = Builder().CreatePHI(Builder().getInt32Ty(), 2, VALUE_NAME("state_phi")); pStatePhi->addIncoming(pConstant0, pEntry); pStatePhi->addIncoming(pNextStatePhi, pNextStatePhi->getParent()); BasicBlock* pPrevStateCheckBlock = nullptr; std::vector<Instruction*> nextState; for (auto pCF : mContinuationFunctions) { //switch(state) std::string strId = std::to_string(pCF->id); BasicBlock* pStateCheckBlock = BasicBlock::Create(ctx, VALUE_NAME(std::string("state_check_cf") + strId), pNewFunc, pStateDone); BasicBlock* pStateExecBlock = BasicBlock::Create(ctx, VALUE_NAME(std::string("state_exec_cf") + strId), pNewFunc, pStateDone); BasicBlock* pCpidExecBlock = BasicBlock::Create(ctx, VALUE_NAME(std::string("cpid_exec_cf") + strId), pNewFunc, pStateDone); if (pPrevStateCheckBlock != nullptr) { IGCLLVM::TerminatorInst* pTerminator = pPrevStateCheckBlock->getTerminator(); BranchInst* pCondBranch = cast<BranchInst>(pTerminator); assert(pCondBranch->isConditional()); pCondBranch->setOperand(1, pStateCheckBlock); } else { Builder().SetInsertPoint(pStateLoopHeader); Builder().CreateBr(pStateCheckBlock); } Builder().SetInsertPoint(pStateCheckBlock); Value* pCond = Builder().CreateICmpEQ(pStatePhi, llvm::ConstantInt::get(Builder().getInt32Ty(), pCF->id)); Builder().CreateCondBr(pCond, pStateExecBlock, pExit); // Create a loop over CPID. Builder().SetInsertPoint(pStateExecBlock); PHINode* pCurrentCPID = Builder().CreatePHI(Builder().getInt32Ty(), 2, VALUE_NAME("CPID")); // Create counter incrementation. Builder().SetInsertPoint(pCpidExecBlock); Value* pIncrementedCPID = Builder().CreateAdd(pCurrentCPID, pCpidIncrement, VALUE_NAME("cpid_inc")); // Continue with loop creation. Builder().SetInsertPoint(pStateExecBlock); pCurrentCPID->addIncoming(pBaseCPID, pStateCheckBlock); pCurrentCPID->addIncoming(pIncrementedCPID, pCpidExecBlock); PHINode* pStateVal = Builder().CreatePHI(Builder().getInt32Ty(), 2, VALUE_NAME("next_state")); pStateVal->addIncoming(pStatePhi, pStateCheckBlock); nextState.push_back(pStateVal); // Create CPID loop header with checking of the loop condition: "CPID < NumOutputControlPoints" Value* pCounterConditionalRes = Builder().CreateICmpULT( pCurrentCPID, pLoopLimit, VALUE_NAME("tcs_if_ult_cond2")); Builder().CreateCondBr(pCounterConditionalRes, pCpidExecBlock, pStateDone); // Build cpid exec block by inserting GEPs and call to continuation function. Builder().SetInsertPoint(pCpidExecBlock); // Just forward arguments to continuation functions. std::vector<Value*> args; // First argument is control point ID. args.push_back(pCurrentCPID); for (auto input : pCF->inputs) { Value* pAlloca = mGlobalAllocas.GetGlobalAlloca(input); Value* indexList[2] = { pConstant0, pCurrentCPID }; // Create GEP for curent instance. Value* pGEP = Builder().CreateGEP(pAlloca, ArrayRef<Value*>(indexList, 2), VALUE_NAME(std::string("p_") + pAlloca->getName())); args.push_back(pGEP); } // CFn(uint arg0, type1* arg1, type2* arg2, ...); Instruction* pCfResult = Builder().CreateCall( pCF->pFunc, args, VALUE_NAME(std::string("cf_result") + strId)); pStateVal->addIncoming(pCfResult, pCpidExecBlock); // Add CPID loop termination. Builder().CreateBr(pStateExecBlock); pPrevStateCheckBlock = pStateCheckBlock; } // Now complete the phi instruction for the "state done" block. Builder().SetInsertPoint(pStateDone); for (auto pNextStateCall : nextState) { // pNextStateCall should always be in immediate predecessor. pNextStatePhi->addIncoming(pNextStateCall, pNextStateCall->getParent()); } // Add state loop condition check. Value* pCond = Builder().CreateICmpEQ(pNextStatePhi, llvm::ConstantInt::get(Builder().getInt32Ty(), ExitState)); Builder().CreateCondBr(pCond, pExit, pStateLoopHeader); // Add function terminator. Builder().SetInsertPoint(pExit); Builder().CreateRetVoid(); } llvm::Function* LinkTessControlShaderMCF::CreateNewTCSFunction(llvm::Function* pCurrentFunc) { llvm::IRBuilder<> irBuilder(pCurrentFunc->getContext()); CodeGenContext* ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); std::vector<llvm::Type*> callArgTypes; for (auto& argIter : range(pCurrentFunc->arg_begin(), pCurrentFunc->arg_end())) { callArgTypes.push_back(argIter.getType()); } callArgTypes.push_back(irBuilder.getInt32Ty()); std::string funcName = "tessControlShaderEntry"; llvm::Function* pNewFunction = llvm::Function::Create( llvm::FunctionType::get( irBuilder.getVoidTy(), callArgTypes, false), llvm::GlobalValue::PrivateLinkage, funcName, ctx->getModule()); pNewFunction->addFnAttr(llvm::Attribute::AlwaysInline); // Move over the contents of the original function pNewFunction->getBasicBlockList().splice(pNewFunction->begin(), pCurrentFunc->getBasicBlockList()); llvm::Function* pToBeDeletedFunc = pCurrentFunc; for (auto oldArg = pToBeDeletedFunc->arg_begin(), oldArgEnd = pToBeDeletedFunc->arg_end(), newArg = pNewFunction->arg_begin(); oldArg != oldArgEnd; ++oldArg, ++newArg) { oldArg->replaceAllUsesWith(&(*newArg)); newArg->takeName(&(*oldArg)); } // delete the old function signature pToBeDeletedFunc->eraseFromParent(); // now replace all occurrences of HSControlPointID with the current // loop iteration CPID - pCurrentCPID SmallVector<Instruction*, 10> instructionToRemove; llvm::Value* pHSControlPointID = llvm::GenISAIntrinsic::getDeclaration(pNewFunction->getParent(), GenISAIntrinsic::GenISA_DCL_HSControlPointID); unsigned int argIndexInFunc = IGCLLVM::GetFuncArgSize(pNewFunction) - 1; Function::arg_iterator arg = pNewFunction->arg_begin(); for (unsigned int i = 0; i < argIndexInFunc; ++i, ++arg); for (Value::user_iterator i = pHSControlPointID->user_begin(), e = pHSControlPointID->user_end(); i != e; ++i) { Instruction* useInst = cast<Instruction>(*i); if (useInst->getParent()->getParent() == pNewFunction) { instructionToRemove.push_back(useInst); useInst->replaceAllUsesWith(&(*arg)); } } for (auto& inst : instructionToRemove) { inst->eraseFromParent(); } return pNewFunction; } void LinkTessControlShaderMCF::TCSwHWBarriersSupport(MetaDataUtils* pMdUtils) { CodeGenContext* ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext(); std::string oldEntryFuncName = GetMainFunction()->getName().str(); llvm::Function* pNewTCSFunction = CreateNewTCSFunction(mpMainFunction); m_useMultipleHardwareThread = (mNumBarriers != 0) ? true : false; // Determine the dispatch mode HullShaderDispatchModes dispatchMode = DetermineDispatchMode(); // This function is the new entry function llvm::Function* pNewLoopFunc = llvm::Function::Create(llvm::FunctionType::get(Builder().getVoidTy(), false), llvm::GlobalValue::ExternalLinkage, oldEntryFuncName, ctx->getModule()); llvm::BasicBlock* pEntryBlock = llvm::BasicBlock::Create( pNewLoopFunc->getContext(), oldEntryFuncName, pNewLoopFunc); Builder().SetInsertPoint(pEntryBlock); // first create a call to simdLaneId() intrinsic llvm::Value* pCPId = nullptr; llvm::Function* pFuncPatchInstanceIdOrSIMDLaneId = nullptr; switch (dispatchMode) { case SINGLE_PATCH_DISPATCH_MODE: pFuncPatchInstanceIdOrSIMDLaneId = llvm::GenISAIntrinsic::getDeclaration( pNewLoopFunc->getParent(), llvm::GenISAIntrinsic::GenISA_simdLaneId); pCPId = Builder().CreateCall(pFuncPatchInstanceIdOrSIMDLaneId); if (m_useMultipleHardwareThread) { // CPID = patchInstanceID * 8 + SimdLaneId; pFuncPatchInstanceIdOrSIMDLaneId = llvm::GenISAIntrinsic::getDeclaration( pNewLoopFunc->getParent(), llvm::GenISAIntrinsic::GenISA_patchInstanceId); pCPId = Builder().CreateAdd( Builder().CreateZExt( pCPId, Builder().getInt32Ty()), Builder().CreateMul( Builder().CreateCall(pFuncPatchInstanceIdOrSIMDLaneId), llvm::ConstantInt::get(Builder().getInt32Ty(), SIMDSize))); } break; case EIGHT_PATCH_DISPATCH_MODE: pCPId = Builder().getInt32(0); if (m_useMultipleHardwareThread) { pFuncPatchInstanceIdOrSIMDLaneId = llvm::GenISAIntrinsic::getDeclaration( pNewLoopFunc->getParent(), llvm::GenISAIntrinsic::GenISA_patchInstanceId); pCPId = Builder().CreateCall(pFuncPatchInstanceIdOrSIMDLaneId); } break; default: assert(0 && "should not reach here"); break; } // We don't need to deal with any loops when we are using multiple hardware threads if (!m_useMultipleHardwareThread) { // initialize instanceCount to output control point count llvm::Value* pInstanceCount = Builder().getInt32(mOutputControlPointCount); // initialize loopCounter llvm::Value* pLoopCounter = Builder().CreateAlloca(Builder().getInt32Ty(), 0, "loopCounter"); llvm::Value* pConstInt = Builder().getInt32(0); Builder().CreateStore(pConstInt, pLoopCounter, false); // create loop-entry basic block and setInsertPoint to loop-entry llvm::BasicBlock* pLoopEntryBB = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_loop_entry"), pNewLoopFunc); llvm::BasicBlock* pLoopConditionTrue = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_loop_condition_true"), pNewLoopFunc); // Create loop-continue basic block llvm::BasicBlock* pLoopContinueBB = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_loop_continue"), pNewLoopFunc); // create loop exit basic block llvm::BasicBlock* pAfterLoopBB = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_after_loop"), pNewLoopFunc); // setInsertPoint to loopEntryBB Builder().CreateBr(pLoopEntryBB); Builder().SetInsertPoint(pLoopEntryBB); // Load the loop counter llvm::LoadInst* pLoadLoopCounter = Builder().CreateLoad(pLoopCounter); llvm::Value* pMulLoopCounterRes = nullptr; llvm::Value* pCurrentCPID = nullptr; llvm::Value* pConditionalRes1 = nullptr; uint32_t loopIterationCount = 0; switch (dispatchMode) { case SINGLE_PATCH_DISPATCH_MODE: // currentCPID = pCPId + loopCounter x simdsize ( in this case its always simd 8 ) pMulLoopCounterRes = Builder().CreateMul( pLoadLoopCounter, llvm::ConstantInt::get(Builder().getInt32Ty(), SIMDSize)); pCurrentCPID = Builder().CreateAdd( Builder().CreateZExt( pCPId, Builder().getInt32Ty()), pMulLoopCounterRes); // cmp currentCPID to instanceCount so we enable only the required lanes pConditionalRes1 = Builder().CreateICmpULT( pCurrentCPID, pInstanceCount, VALUE_NAME("tcs_if_ult_cond1")); // if true go to startBB else jump to pAfterLoopBB Builder().CreateCondBr(pConditionalRes1, pLoopConditionTrue, pAfterLoopBB); loopIterationCount = ((mOutputControlPointCount - 1) / 8) + 1; break; case EIGHT_PATCH_DISPATCH_MODE: pCurrentCPID = pLoadLoopCounter; loopIterationCount = mOutputControlPointCount; // jump to startBB Builder().CreateBr(pLoopConditionTrue); break; default: assert(false && "should not reach here"); break; } // branch to pLoopContinueBB from endBB Builder().SetInsertPoint(pLoopConditionTrue); // Create a call to the TCS function when condition is true to loop the function as many times as the number of control points Builder().CreateCall(pNewTCSFunction, pCurrentCPID); Builder().CreateBr(pLoopContinueBB); // setInsertPoint to pLoopContinueBB Builder().SetInsertPoint(pLoopContinueBB); // increment loop counter loopCounter = loopCounter + 1 llvm::Value* pIncrementedLoopCounter = Builder().CreateAdd( pLoadLoopCounter, llvm::ConstantInt::get(Builder().getInt32Ty(), 1)); Builder().CreateStore(pIncrementedLoopCounter, pLoopCounter, false); // now evaluate loop, if( ( incrementedLoopCounter ) < ( ( maxControlPointCount - 1 )/8) + 1 ) // then continue loop else go to after loop llvm::Value* pNumberOfLoopIterationsRequired = llvm::ConstantInt::get(Builder().getInt32Ty(), loopIterationCount); llvm::Value* pConditionalRes2 = Builder().CreateICmpULT( pIncrementedLoopCounter, pNumberOfLoopIterationsRequired, VALUE_NAME("tcs_if_ult_cond2")); // create branch to LoopEntryBB or AfterLoopBB based on result of conditional branch Builder().CreateCondBr(pConditionalRes2, pLoopEntryBB, pAfterLoopBB); // set insert point to afterloop basic block Builder().SetInsertPoint(pAfterLoopBB); } else if (dispatchMode == SINGLE_PATCH_DISPATCH_MODE) { // In single patch dispatch mode the execution mask is 0xFF. Make // that only valid CPIDs execute. // Create the main basic block for the shader llvm::BasicBlock* pTcsBody = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_body"), pNewLoopFunc); // and the end block. llvm::BasicBlock* pAfterTcsBody = llvm::BasicBlock::Create(pNewLoopFunc->getContext(), VALUE_NAME("tcs_end"), pNewLoopFunc); // Compare current CPID to the number of CPIDs to enable only the required lanes. llvm::Value* pIsLaneEnabled = Builder().CreateICmpULT( pCPId, Builder().getInt32(mOutputControlPointCount), VALUE_NAME("tcs_if_ult_cond1")); Builder().CreateCondBr(pIsLaneEnabled, pTcsBody, pAfterTcsBody); Builder().SetInsertPoint(pTcsBody); // Call TCS function. Builder().CreateCall(pNewTCSFunction, pCPId); Builder().CreateBr(pAfterTcsBody); Builder().SetInsertPoint(pAfterTcsBody); } else { // when using multiple hardware threads just call the Control Point function once with the appropriate CPID Builder().CreateCall(pNewTCSFunction, pCPId); } // add terminator to the afterloop basic block Builder().CreateRetVoid(); pMdUtils->clearFunctionsInfo(); IGCMetaDataHelper::addFunction(*pMdUtils, pNewLoopFunc); } ////////////////////////////////////////////////////////////////////////// /// @brief - Checks whether the TCS with HW barrier support is a better /// option in comparison to TCS with SW barriers. bool LinkTessControlShaderMCF::SelectTCSwHWBarrierSupport(void) { if ((mNumBarriers == 0) || (mNumInstructions > LARGE_INSTRUCTIONS_COUNT)) { // Comment for mNumInstructions > LARGE_INSTRUCTIONS_COUNT: // TCSs with SW barrier enabled and having large instructions count consume much more scratch space per // thread than TCSs with HW barriers enabled. For a very large instructions count TCSs with SW barriers enabled // can run in pull vertex mode what negatively impacts performance. return true; } else { return false; } } ////////////////////////////////////////////////////////////////////////// /// @brief Perform pass operations. /// @param M- The original module. bool LinkTessControlShaderMCF::runOnModule(llvm::Module& M) { mpModule = &M; MetaDataUtils* pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils(); if (pMdUtils->size_FunctionsInfo() != 1) { return false; } mpMainFunction = pMdUtils->begin_FunctionsInfo()->first; assert(mpMainFunction); mpBuilder = new llvm::IGCIRBuilder<>(M.getContext()); // Get the output control point count. llvm::GlobalVariable* pOCPCount = GetMainFunction()->getParent()->getGlobalVariable("HSOutputControlPointCount"); mOutputControlPointCount = int_cast<uint32_t>(llvm::cast<llvm::ConstantInt>(pOCPCount->getInitializer())->getZExtValue()); // Get the barriers count. FindBarriers(*mpMainFunction); if (SelectTCSwHWBarrierSupport()) { TCSwHWBarriersSupport(pMdUtils); } else { // SW barriers support. BuildContinuationFunctions(*mpMainFunction); RebuildMainFunction(); } return true; } ////////////////////////////////////////////////////////////////////////// /// @brief Create this pass. llvm::Pass* createLinkTessControlShaderMCF() { return new LinkTessControlShaderMCF(); } }
41.069459
151
0.56279
dkurt
dd27326be8d22edbd4a9ba089e777615d84611af
4,217
tpp
C++
uppdev/TopicTest/topic++/src/Ntlvsstl.en-us.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/TopicTest/topic++/src/Ntlvsstl.en-us.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/TopicTest/topic++/src/Ntlvsstl.en-us.tpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
TITLE("NTLvsSTL") TOPIC_TEXT( "[ $$0,0#00000000000000000000000000000000:Default][l288;i704;a17;O9;~~~.992; $$1," "0#10431211400427159095818037425705:param][a83;*R6 $$2,5#3131016247420302412518841" "7583966:caption][b83;* $$3,5#07864147445237544204411237157677:title][b167;a42;C $" "$4,6#40027414424643823182269349404212:item][b42;a42; $$5,5#4541300047534217475409" "1244180557:text][l288;a17; $$6,6#27521748481378242620020725143825:desc][l321;t246" ";C@5;1 $$7,7#20902679421464641399138805415013:code][b2503; $$8,0#6514237545610002" "3862071332075487:separator][*@(0.0.255) $$9,0#83433469410354161042741608181528:ba" "se][t4167;C+117 $$10,0#37138531426314131251341829483380:class][l288;a17;*1 $$11,1" "1#70004532496200323422659154056402:requirement][i416;b42;a42;O9;~~~.416; $$12,12#" "10566046415157235020018451313112:tparam][b167;C $$13,13#9243045944346046191110808" "0531343:item1][a42;C $$14,14#77422149456609303542238260500223:item2][*@2$(0.128.1" "28) $$15,15#34511555403152284025741354420178:NewsDate][l321;*C$7 $$16,16#03451589" "433145915344929335295360:result][l321;b83;a83;*C$7 $$17,17#0753155046352950537122" "8428965313:result`-line][l160;t4167;*C+117 $$18,5#8860394944220582595880005322242" "5:package`-title][{_}%EN-US [s2; NTL - STL Comparison&][s5; NTL was created to so" "lve following problems we used to encounter when using STL: &][s3; Copy-construct" "ible requirements&][s5; STL requires the elements stored in containers to meet th" "e requirements of copy-constructible and assignable types. This causes two proble" "ms:&][s5;i150;O2; Elements that do not satisfy these requirements cannot be direc" "tly stored in STL containers.&][s5;i150;O2; For many types of elements, including" " STL containers themselves, copy-constructor and assign operator is a very expens" "ive operation, that is why often they cannot be stored in STL containers effectiv" "ely.&][s5; NTL addresses this problem by introducing [^dpp`:`/`/SourceDoc`/Contai" "ners`/Overview^ Vector] and [^dpp`:`/`/SourceDoc`/Containers`/Overview^ Array] fl" "avors of containers.&][s3; Value transfer&][s5; Content o") TOPIC_TEXT( "f STL containers can be transfered only using expensive deep-copy constructor/as" "sigment operator. This causes performance problems especially when using STL cont" "ainers as function return values, but lack of better functionality is missing els" "ewhere too. NTL provides [^dpp`:`/`/SourceDoc`/Containers`/pick`_^ transfer seman" "tics] concepts to deal with this problem.&][s3; Random access and random access n" "otation&][s5; STL uses iterators as the preferred way how to access and identify " "elements in containers. While this is generally the most generic way, real-life p" "roblems often require or at least benefit from random access using indices. NTL p" "rovides fast random access to all kinds of containers and NTL interfaces prefer n" "otation using indices. As a side effect, NTL user can completely avoid using iter" "ators in favor of indices, which in current C`++ results in much simpler and less" " verbose syntax (using modern optimizing compilers there is no difference in perf" "ormance).&][s3; Index&][s5; A completely new type of associative container, [^dpp" "`:`/`/`:`:`/Index`<class T`, class HashFn `= StdHash`<T`> `>`/template `<class T`" ", class HashFn `= StdHash`<T`> `> class Index^ Index], is introduced, as an ideal" " building block for all kinds of associative operations.&][s3; Algorithm requirem" "ents&][s5; Requirements of STL algorithms are very loosely defined. NTL tries to " "provide more specific requirements and also minimal ones. This allows e.g. [^dpp`" ":`/`/www`/pages`/polyarray^ direct sorting of Array of polymorphic elements].&][s" "3; Minor improvements&][s5; There are also some minor improvements:&][s5;i150;O2;" " Besides [* reserve] present in STL, NTL provides also [* Shrink] method to minim" "ize a container's memory consumption.&][s5;i150;O2; Iterators can be assigned a N" "ULL value.&][s5;i150;O2; Associative containers are based on hashing to provide b" "etter performance. Utility classes and functions are provided to support building" " correct hashing functions.")
78.092593
84
0.751008
dreamsxin
dd2c81e44b3caf19cc2cbec4b4667358fca2c594
3,917
cpp
C++
Source/WebCore/html/RadioNodeList.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/html/RadioNodeList.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/html/RadioNodeList.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2012 Motorola Mobility, Inc. All rights reserved. * Copyright (C) 2014-2020 Apple 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: * 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. * * THIS SOFTWARE IS PROVIDED BY MOTOROLA MOBILITY, INC. AND ITS 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 MOTOROLA MOBILITY, INC. OR ITS * 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 "config.h" #include "RadioNodeList.h" #include "HTMLFormElement.h" #include "HTMLInputElement.h" #include "HTMLObjectElement.h" #include "NodeRareData.h" #include <wtf/IsoMallocInlines.h> namespace WebCore { using namespace HTMLNames; WTF_MAKE_ISO_ALLOCATED_IMPL(RadioNodeList); RadioNodeList::RadioNodeList(ContainerNode& rootNode, const AtomString& name) : CachedLiveNodeList(rootNode, InvalidateForFormControls) , m_name(name) , m_isRootedAtDocument(is<HTMLFormElement>(rootNode)) { } Ref<RadioNodeList> RadioNodeList::create(ContainerNode& rootNode, const AtomString& name) { return adoptRef(*new RadioNodeList(rootNode, name)); } RadioNodeList::~RadioNodeList() { ownerNode().nodeLists()->removeCacheWithAtomName(*this, m_name); } static RefPtr<HTMLInputElement> nonEmptyRadioButton(Element& element) { if (!is<HTMLInputElement>(element)) return nullptr; auto& inputElement = downcast<HTMLInputElement>(element); if (!inputElement.isRadioButton() || inputElement.value().isEmpty()) return nullptr; return &inputElement; } String RadioNodeList::value() const { auto length = this->length(); for (unsigned i = 0; i < length; ++i) { if (auto button = nonEmptyRadioButton(*item(i))) { if (button->checked()) return button->value(); } } return String(); } void RadioNodeList::setValue(const String& value) { auto length = this->length(); for (unsigned i = 0; i < length; ++i) { if (auto button = nonEmptyRadioButton(*item(i))) { if (button->value() == value) { button->setChecked(true); return; } } } } bool RadioNodeList::elementMatches(Element& element) const { if (!is<HTMLObjectElement>(element) && !is<HTMLFormControlElement>(element)) return false; if (is<HTMLInputElement>(element) && downcast<HTMLInputElement>(element).isImageButton()) return false; if (is<HTMLFormElement>(ownerNode())) { RefPtr<HTMLFormElement> form; if (is<HTMLObjectElement>(element)) form = downcast<HTMLObjectElement>(element).form(); else form = downcast<HTMLFormControlElement>(element).form(); if (!form || form != &ownerNode()) return false; } return element.getIdAttribute() == m_name || element.getNameAttribute() == m_name; } } // namespace WebCore
33.478632
93
0.697728
jacadcaps
dd2f39398626d6035f8b8ec8dcb0379927b7c5cc
1,555
cpp
C++
src/utils.cpp
atlochowski/harbour-powietrze
e47bf1f397d81a9f69363a44e785ca9248ecef17
[ "BSD-3-Clause" ]
2
2019-10-24T12:43:18.000Z
2019-12-22T20:59:18.000Z
src/utils.cpp
atlochowski/harbour-powietrze
e47bf1f397d81a9f69363a44e785ca9248ecef17
[ "BSD-3-Clause" ]
9
2019-07-18T19:39:14.000Z
2021-06-13T18:29:55.000Z
src/utils.cpp
atlochowski/harbour-powietrze
e47bf1f397d81a9f69363a44e785ca9248ecef17
[ "BSD-3-Clause" ]
5
2019-10-24T12:49:15.000Z
2021-05-17T10:47:42.000Z
#include "utils.h" #include <notification.h> #include <iostream> void Utils::simpleNotification(QString header, QString body, QString function, QVariantList parameters) { Notification notification; notification.setCategory("powietrze.update"); notification.setSummary(header); notification.setBody(body); notification.setPreviewSummary(header); notification.setPreviewBody(body); notification.setRemoteAction(Notification::remoteAction("default", "", "harbour.powietrze.service", "/harbour/powietrze/service", "harbour.powietrze.service", function, parameters)); notification.publish(); } float Utils::calculateWHONorms(const Pollution& sensorData) { if (!sensorData.isInitialized()) { return -1; } std::list<WHONorm> pollutions = { {"pm25", 25.f, 24}, {"pm10", 50.f, 24}, {"no2", 200.f, 1}, {"o3", 100.f, 8}, {"so2", 350.f, 1}, {"co", 30000.f, 1} }; for (auto pollution: pollutions) { if (pollution.name == sensorData.code) { float avg = sensorData.avg(pollution.hours); return avg / pollution.value * 100; } } return -1; }
31.1
103
0.48746
atlochowski
dd33a90e8cc809ea9c75c6242e9d70d25c283785
3,655
cxx
C++
private/inet/mshtml/src/other/scrtoid/misc.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/other/scrtoid/misc.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/other/scrtoid/misc.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------------- // // Microsoft Trident // Copyright (C) Microsoft Corporation, 1997 - 1998. // // File: misc.cxx // // Contents: misc helpers for scriptoid handlers // //---------------------------------------------------------------------------- #include <headers.hxx> #ifndef X_DISPEX_H_ #define X_DISPEX_H_ #include <dispex.h> #endif #ifndef X_MISC_HXX_ #define X_MISC_HXX_ #include "misc.hxx" #endif //+------------------------------------------------------------------------ // // Function: GetProperty_Dispatch // //------------------------------------------------------------------------- HRESULT GetProperty_Dispatch(IDispatch * pDisp, LPTSTR pchName, IDispatch ** ppDispRes) { HRESULT hr; DISPID dispid; DISPPARAMS dispparams = {NULL, NULL, 0, 0}; VARIANT varRes; EXCEPINFO excepinfo; UINT nArgErr; *ppDispRes = NULL; hr = pDisp->GetIDsOfNames(IID_NULL, &pchName, 1, LOCALE_SYSTEM_DEFAULT, &dispid); if (hr) goto Cleanup; hr = pDisp->Invoke( dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &dispparams, &varRes, &excepinfo, &nArgErr); if (hr) goto Cleanup; if (VT_DISPATCH != V_VT(&varRes)) { hr = E_UNEXPECTED; goto Cleanup; } (*ppDispRes) = V_DISPATCH(&varRes); Cleanup: return hr; } //+------------------------------------------------------------------------ // // Function: PutProperty_Dispatch // //------------------------------------------------------------------------- HRESULT PutProperty_Dispatch(IDispatch * pDisp, LPTSTR pchName, IDispatch * pDispArg) { HRESULT hr; DISPID dispid; VARIANT varArg; VARIANT varRes; EXCEPINFO excepinfo; UINT nArgErr; DISPPARAMS dispparams = {&varArg, NULL, 1, 0}; VariantInit(&varArg); V_VT(&varArg) = VT_DISPATCH; V_DISPATCH(&varArg) = pDispArg; hr = pDisp->GetIDsOfNames(IID_NULL, &pchName, 1, LOCALE_SYSTEM_DEFAULT, &dispid); if (hr) goto Cleanup; hr = pDisp->Invoke( dispid, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYPUT, &dispparams, &varRes, &excepinfo, &nArgErr); Cleanup: return hr; } //+------------------------------------------------------------------------ // // Function: GetDocument // //------------------------------------------------------------------------- HRESULT GetDocument(IDispatch * pElement, IDispatch ** ppDispDocument) { return GetProperty_Dispatch(pElement, _T("document"), ppDispDocument); } //+------------------------------------------------------------------------ // // Function: GetWindow // //------------------------------------------------------------------------- HRESULT GetWindow(IDispatch * pElement, IDispatchEx ** ppDispWindow) { HRESULT hr; IDispatch * pDispDocument = NULL; IDispatch * pDispWindow = NULL; *ppDispWindow = NULL; hr = GetDocument(pElement, &pDispDocument); if (hr) goto Cleanup; hr = GetProperty_Dispatch (pDispDocument, _T("parentWindow"), &pDispWindow); if (hr) goto Cleanup; hr = pDispWindow->QueryInterface (IID_IDispatchEx, (void**) ppDispWindow); Cleanup: ReleaseInterface(pDispDocument); ReleaseInterface(pDispWindow); return S_OK; }
24.046053
86
0.468947
King0987654
dd35531bf699f1b942f91eee1b38b6f15f2bdb4b
69
hpp
C++
include/components/battle/Fainted.hpp
Ghabriel/PokemonCpp
dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e
[ "Apache-2.0" ]
6
2018-08-05T21:45:23.000Z
2021-10-30T19:48:34.000Z
include/components/battle/Fainted.hpp
Ghabriel/PokemonCpp
dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e
[ "Apache-2.0" ]
null
null
null
include/components/battle/Fainted.hpp
Ghabriel/PokemonCpp
dcdbbde0ea99afc98edecd764b02ff92d8ca6a6e
[ "Apache-2.0" ]
1
2021-11-01T20:15:38.000Z
2021-11-01T20:15:38.000Z
#ifndef FAINTED_HPP #define FAINTED_HPP struct Fainted { }; #endif
9.857143
19
0.753623
Ghabriel
dd37a9ec1f567d6efebbf27b6a8daabc460e3d5a
4,472
cpp
C++
601-700/636-Exclusive_Time_of_Functions-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
601-700/636-Exclusive_Time_of_Functions-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
601-700/636-Exclusive_Time_of_Functions-m.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given the running logs of n functions that are executed in a nonpreemptive // single threaded CPU, find the exclusive time of these functions. // Each function has a unique id, start from 0 to n-1. A function may be called // recursively or by another function. // A log is a string has this format : function_id:start_or_end:timestamp. For // example, "0:start:0" means function 0 starts from the very beginning of time // 0. "0:end:0" means function 0 ends to the very end of time 0. // Exclusive time of a function is defined as the time spent within this // function, the time spent by calling other functions should not be considered // as this function's exclusive time. You should return the exclusive time of // each function sorted by their function id. // Example 1: // Input: // n = 2 // logs = // ["0:start:0", // "1:start:2", // "1:end:5", // "0:end:6"] // Output:[3, 4] // Explanation: // Function 0 starts at time 0, then it executes 2 units of time and reaches the // end of time 1. Now function 0 calls function 1, function 1 starts at time 2, // executes 4 units of time and end at time 5. Function 0 is running again at // time 6, and also end at the time 6, thus executes 1 unit of time. So function // 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 // units of time. // Note: // Input logs will be sorted by timestamp, NOT log id. // Your output should be sorted by function id, which means the 0th element // of your output corresponds to the exclusive time of function 0. Two // functions won't start or end at the same time. Functions could be called // recursively, and will always end. 1 <= n <= 100 // WTF the problem description is class Solution { public: vector<int> exclusiveTime(int n, vector<string> &logs) { vector<int> ret(n); vector<vector<int>> ilogs(logs.size(), vector<int>(3)); // ilogs[i] == {id, start or end, time}, with unified timestamp for (int i = 0; i < logs.size(); ++i) { auto c = logs[i].find(':'); ilogs[i][0] = stoi(logs[i].substr(0, c)); ilogs[i][1] = logs[i][c + 1]; ilogs[i][2] = stoi(logs[i].substr(logs[i].rfind(':') + 1)) + (ilogs[i][1] == 'e'); } stack<vector<int>> s; for (int i = 0; i < ilogs.size(); ++i) { if (s.empty()) { s.push(ilogs[i]); continue; } ret[s.top()[0]] += ilogs[i][2] - s.top()[2]; if (ilogs[i][0] == s.top()[0] && ilogs[i][1] == 'e') { int t = ilogs[i][2]; s.pop(); if (!s.empty()) s.top()[2] = t; } else s.push(ilogs[i]); // cout << ret[0] << ' ' << ret[1] << endl; } return ret; } }; // simplified class Solution { public: vector<int> exclusiveTime(int n, vector<string> &logs) { vector<int> ret(n); stack<array<int, 3>> s; int id, status, t; // {id, status, unified timestamp} for (auto &&lg : logs) { auto c = lg.find(':'); id = stoi(lg.substr(0, c)); status = lg[c + 1]; t = stoi(lg.substr(lg.rfind(':') + 1)) + (status == 'e'); if (s.empty()) { s.push({id, status, t}); continue; } ret[s.top()[0]] += t - s.top()[2]; if (id == s.top()[0] && status == 'e') { s.pop(); if (!s.empty()) s.top()[2] = t; } else s.push({id, status, t}); } return ret; } }; // further simplified class Solution { public: vector<int> exclusiveTime(int n, vector<string> &logs) { vector<int> ret(n); stack<int> s; int id, t, prevt; char status; for (auto &&lg : logs) { auto c = lg.find(':'); id = stoi(lg.substr(0, c)); status = lg[c + 1]; t = stoi(lg.substr(lg.rfind(':') + 1)) + (status == 'e'); if (s.empty()) s.push(id); else { ret[s.top()] += t - prevt; if (id == s.top() && status == 'e') s.pop(); else s.push(id); } prevt = t; } return ret; } };
30.421769
80
0.503801
ysmiles
dd38657946b816e7b1dfe0382561956675f3d3bd
376
cpp
C++
DP/DP_Basic_in_Class/Maximum_Subarray_Sum.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
DP/DP_Basic_in_Class/Maximum_Subarray_Sum.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
DP/DP_Basic_in_Class/Maximum_Subarray_Sum.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int dp(int arr[],int n) { int res=0,ans=0; for(int i=0;i<n;i++) { res = max(arr[i],res+arr[i]); ans = max(ans,res); } return ans; } int main() { int n,arr[1000]; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("%d\n",dp(arr,n)); return 0; } /* Input: 6 3 -4 9 -8 8 7 Output: 16 * */
10.444444
31
0.518617
Sowmik23
dd3b3c9771b3885e6a182e1137e291c6d2a4d353
541
hpp
C++
src/color/gray/akin/lab.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
120
2015-12-31T22:30:14.000Z
2022-03-29T15:08:01.000Z
src/color/gray/akin/lab.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
6
2016-08-22T02:14:56.000Z
2021-11-06T22:39:52.000Z
src/color/gray/akin/lab.hpp
ehtec/color
aa6d8c796303d1f3cfd7361978bfa58eac808b6e
[ "Apache-2.0" ]
23
2016-02-03T01:56:26.000Z
2021-09-28T16:36:27.000Z
#ifndef color_gray_akin_lab #define color_gray_akin_lab #include "../../generic/akin/gray.hpp" #include "../category.hpp" #include "../../lab/category.hpp" namespace color { namespace akin { template < typename tag_name ,::color::constant::lab::reference_enum lab_reference_number > struct gray< ::color::category::lab< tag_name, lab_reference_number > > { public: typedef ::color::category::gray< tag_name > akin_type; }; } } #endif
19.321429
77
0.593346
ehtec
dd3dfe96c626cba5ef08dd7a1d50a578b5654795
1,383
cpp
C++
source/requests/EdgarRequests.cpp
Jde-cpp/TwsWebSocket
099ef66e2481bd12019d634ba8125b17d9c2d67e
[ "MIT" ]
null
null
null
source/requests/EdgarRequests.cpp
Jde-cpp/TwsWebSocket
099ef66e2481bd12019d634ba8125b17d9c2d67e
[ "MIT" ]
null
null
null
source/requests/EdgarRequests.cpp
Jde-cpp/TwsWebSocket
099ef66e2481bd12019d634ba8125b17d9c2d67e
[ "MIT" ]
null
null
null
#include "EdgarRequests.h" #include "../../../Private/source/markets/edgar/Edgar.h" #include "../../../Private/source/markets/edgar/Form13F.h" namespace Jde::Markets::TwsWebSocket { void EdgarRequests::Filings( Cik cik, ProcessArg&& inputArg )noexcept { std::thread( [cik, arg=move(inputArg)]() { try { auto p = Edgar::LoadFilings(cik); p->set_request_id( arg.ClientId ); MessageType msg; msg.set_allocated_filings( p.release() ); arg.Push( move(msg) ); } catch( IException& e ) { arg.Push( "could not retreive filings", e ); } }).detach(); } void Investors2( function<up<Edgar::Proto::Investors>()> f, ProcessArg&& inputArg )noexcept { std::thread( [f, arg=move(inputArg)]() { try { auto p = f(); p->set_request_id( arg.ClientId ); MessageType msg; msg.set_allocated_investors( p.release() ); arg.Push( move(msg) ); } catch( IException& e ) { arg.Push( "Could not load investors", e ); } }).detach(); } void EdgarRequests::Investors( ContractPK contractId, ProcessArg&& arg )noexcept { return Investors2( [contractId]() { auto pDetails = SFuture<::ContractDetails>( Tws::ContractDetail(contractId) ).get(); //TwsClientSync::ReqContractDetails( contractId ).get(); CHECK( (pDetails->size()==1) ); return Edgar::Form13F::LoadInvestors( pDetails->longName ); }, move(arg) ); } }
27.66
92
0.647144
Jde-cpp
dd3f5a22d08de4ccd846d871c43757f0f2945b2c
8,007
cpp
C++
Game/Game/Game/Export/Export_Lua_Scene.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
Game/Game/Game/Export/Export_Lua_Scene.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
Game/Game/Game/Export/Export_Lua_Scene.cpp
CBE7F1F65/fb43b70cb3d36ad8b8ee3a9aed9c6493
da25260dc8128ed66b48d391c738eb15134d7d4f
[ "Zlib", "MIT-0", "MIT" ]
null
null
null
#include "Export_Lua_Scene.h" #include "Export_Lua_Const.h" #include "../Header/SceneConst.h" #include "../Classes/LoadingScene.h" #include "../Classes/TitleScene.h" #include "../Classes/HelpScene.h" #include "../Classes/StageSelectScene.h" #include "../Classes/MissionSelectScene.h" #include "../Classes/StoryScene.h" #include "../Classes/PlayScene.h" #define LUASCENE_SCENE_IO "Scene_IO" #define LUASCENE_SCENE_CB "Scene_CB" #define LUASCENE_INPUTLAYER_CB "InputLayer_CB" #define LUASCENE_TOUCHLAYER_CB "TouchLayer_CB" LuaFunction<bool> * Export_Lua_Scene::ioScene; LuaFunction<bool> * Export_Lua_Scene::cbScene; LuaFunction<bool> * Export_Lua_Scene::cbInputLayer; LuaFunction<bool> * Export_Lua_Scene::cbTouchLayer; bool Export_Lua_Scene::_LuaRegistConst(LuaObject * obj) { obj->SetInteger("SceneIOFlag_OnInit", LUASCENE_IOFLAG_ONINIT); obj->SetInteger("SceneIOFlag_OnEnter", LUASCENE_IOFLAG_ONENTER); obj->SetInteger("SceneIOFlag_OnEnterA", LUASCENE_IOFLAG_ONENTERA); obj->SetInteger("SceneIOFlag_OnEnterTDF", LUASCENE_IOFLAG_ONENTERTDF); obj->SetInteger("SceneIOFlag_OnEnterTDFA", LUASCENE_IOFLAG_ONENTERTDFA); obj->SetInteger("SceneIOFlag_OnUpdate", LUASCENE_IOFLAG_ONUPDATE); obj->SetInteger("SceneIOFlag_OnExit", LUASCENE_IOFLAG_ONEXIT); obj->SetInteger("SceneIOFlag_OnTouchBegin", LUASCENE_IOFLAG_ONTOUCHBEGIN); obj->SetInteger("SceneIOFlag_OnTouchEnd", LUASCENE_IOFLAG_ONTOUCHEND); obj->SetInteger("ktag_BaseSceneLayer", KTAG_BASESCENELAYER); obj->SetInteger("ktag_LoadingSceneLayer", KTAG_LOADINGSCENELAYER); obj->SetInteger("ktag_TitleSceneLayer", KTAG_TITLESCENELAYER); obj->SetInteger("ktag_HelpSceneLayer", KTAG_HELPSCENELAYER); obj->SetInteger("ktag_StageSelectSceneLayer", KTAG_STAGESELECTSCENELAYER); obj->SetInteger("ktag_MissionSelectSceneLayer", KTAG_MISSIONSELECTSCENELAYER); obj->SetInteger("ktag_StorySceneLayer", KTAG_STORYSCENELAYER); obj->SetInteger("ktag_PlaySceneLayer", KTAG_PLAYSCENELAYER); obj->SetInteger("ktag_OverlayLayer", KTAG_OVERLAYLAYER); return true; } bool Export_Lua_Scene::_LuaRegistFunction(LuaObject * obj) { return true; } bool Export_Lua_Scene::InitCallbacks() { LuaState * ls = state; LuaObject _obj = ls->GetGlobal(LUASCENE_SCENE_IO); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_SCENE_IO); return false; } static LuaFunction<bool> _fsceneio = _obj; _fsceneio = _obj; ioScene = &_fsceneio; _obj = ls->GetGlobal(LUASCENE_SCENE_CB); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_SCENE_CB); return false; } static LuaFunction<bool> _fscenecb = _obj; _fscenecb = _obj; cbScene = &_fscenecb; _obj = ls->GetGlobal(LUASCENE_INPUTLAYER_CB); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_INPUTLAYER_CB); return false; } static LuaFunction<bool> _finputlayercb = _obj; _finputlayercb = _obj; cbInputLayer = &_finputlayercb; _obj = ls->GetGlobal(LUASCENE_TOUCHLAYER_CB); if (!_obj.IsFunction()) { ShowError(LUAERROR_NOTFUNCTION, LUASCENE_TOUCHLAYER_CB); return false; } static LuaFunction<bool> _ftouchlayercb = _obj; _ftouchlayercb = _obj; cbTouchLayer = &_ftouchlayercb; return true; } /************************************************************************/ /* SceneGet */ /************************************************************************/ void Export_Lua_Scene::_GetSceneMenuCallback(int scenetag, SEL_MenuHandler * cbfunc, SEL_CallFuncND * cbndfunc) { scenetag = scenetag & KTAG_SCENELAYERMASK; switch (scenetag) { case KTAG_LOADINGSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(LoadingScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(LoadingScene::NodeCallbackFunc); } break; case KTAG_TITLESCENELAYER: if (cbfunc) { *cbfunc = menu_selector(TitleScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(TitleScene::NodeCallbackFunc); } break; case KTAG_HELPSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(HelpScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(HelpScene::NodeCallbackFunc); } break; case KTAG_STAGESELECTSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(StageSelectScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(StageSelectScene::NodeCallbackFunc); } break; case KTAG_MISSIONSELECTSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(MissionSelectScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(MissionSelectScene::NodeCallbackFunc); } break; case KTAG_STORYSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(StoryScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(StoryScene::NodeCallbackFunc); } break; case KTAG_PLAYSCENELAYER: if (cbfunc) { *cbfunc = menu_selector(PlayScene::MenuCallbackFunc); } if (cbndfunc) { *cbndfunc = callfuncND_selector(PlayScene::NodeCallbackFunc); } break; } } int Export_Lua_Scene::_GetTopTag(int itemtag) { return itemtag & KTAG_SCENELAYERMASK; } int Export_Lua_Scene::_GetSubLayerTag(int itemtag) { return itemtag & KTAG_SUBLAYERMASK; } int Export_Lua_Scene::_GetMenuGroupTag(int itemtag) { return itemtag & KTAG_MENUGROUPMASK; } int Export_Lua_Scene::_GetMenuItemTag(int itemtag) { return itemtag & KTAG_MENUITEMMASK; } CCScene * Export_Lua_Scene::_GetNewScene(int scenetag) { scenetag = scenetag & KTAG_SCENELAYERMASK; switch (scenetag) { case KTAG_LOADINGSCENELAYER: return LoadingScene::scene(); break; case KTAG_TITLESCENELAYER: return TitleScene::scene(); break; case KTAG_HELPSCENELAYER: return HelpScene::scene(); break; case KTAG_STAGESELECTSCENELAYER: return StageSelectScene::scene(); break; case KTAG_MISSIONSELECTSCENELAYER: return MissionSelectScene::scene(); break; case KTAG_STORYSCENELAYER: return StoryScene::scene(); break; case KTAG_PLAYSCENELAYER: return PlayScene::scene(); break; } return NULL; } /************************************************************************/ /* Callback */ /************************************************************************/ bool Export_Lua_Scene::ExecuteIOScene(BYTE flag, CCLayer *toplayer, int toptag) { LuaState * ls = state; bool bret = (*ioScene)(flag, CDOUBLEN(toplayer), toptag); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; } bool Export_Lua_Scene::ExecuteCBScene(int tag, CCLayer * toplayer, int dataindex /* = -1 */) { LuaState * ls = state; bool bret = (*cbScene)(tag, CDOUBLEN(toplayer), _GetTopTag(tag), _GetSubLayerTag(tag), _GetMenuGroupTag(tag), _GetMenuItemTag(tag), dataindex); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; } bool Export_Lua_Scene::ExecuteCBInputLayer(int tag, CCLayer * toplayer, int eventtag, const char * text) { LuaState * ls = state; bool bret = (*cbInputLayer)(tag, CDOUBLEN(toplayer), eventtag, _GetTopTag(tag), _GetSubLayerTag(tag), text); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; } bool Export_Lua_Scene::ExecuteCBTouchLayer(int tag, CCLayer * toplayer, int eventtag, CCLayer * thislayer, int index, BYTE gesture) { LuaState * ls = state; bool bret = (*cbTouchLayer)(CDOUBLEN(toplayer), eventtag, _GetTopTag(tag), tag&KTAG_SUBLAYERMASK, CDOUBLEN(thislayer), index, gesture); if (state->CheckError()) { Export_Lua::ShowError(LUAERROR_LUAERROR, state->GetError()); } return bret; }
28.393617
145
0.690396
CBE7F1F65
dd436f744aa5f2ac3f40b87939557997b4564269
605
cpp
C++
Tree/(LEETCODE)BST_from_preorderTraversal.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
Tree/(LEETCODE)BST_from_preorderTraversal.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
Tree/(LEETCODE)BST_from_preorderTraversal.cpp
kothariji/Competitive-Programming
c49f8b0135c8e9dd284ce8ab583e85ba3d809b8c
[ "MIT" ]
null
null
null
class Solution { public: TreeNode* constructBST(vector<int> preorder,int low,int high){ if(low>=preorder.size() || low>high) return NULL; TreeNode* root=new TreeNode(preorder[low]); if(high==low) return root; int i; for(i=low;i<=high;i++) if(preorder[i]>root->val) break; root->left=constructBST(preorder,low+1,i-1); root->right=constructBST(preorder,i,high); return root; } TreeNode* bstFromPreorder(vector<int>& preorder) { return constructBST(preorder,0,preorder.size()-1); } };
25.208333
66
0.585124
kothariji
dd50ebbb858c8453eb9a4bd8aabf945f87c3bd67
1,716
hpp
C++
HugeCTR/include/pybind/data_source_wrapper.hpp
mikemckiernan/HugeCTR
1a0a618f9848eb908e9d1265c555fba9924d2861
[ "Apache-2.0" ]
130
2021-10-11T11:55:28.000Z
2022-03-31T21:53:07.000Z
HugeCTR/include/pybind/data_source_wrapper.hpp
Teora/HugeCTR
c55a63401ad350669ccfcd374aefd7a5fc879ca2
[ "Apache-2.0" ]
72
2021-10-09T04:59:09.000Z
2022-03-31T11:27:54.000Z
HugeCTR/include/pybind/data_source_wrapper.hpp
Teora/HugeCTR
c55a63401ad350669ccfcd374aefd7a5fc879ca2
[ "Apache-2.0" ]
29
2021-11-03T22:35:01.000Z
2022-03-30T13:11:59.000Z
/* * Copyright (c) 2021, NVIDIA 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. */ #pragma once #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <hdfs_backend.hpp> namespace HugeCTR { namespace python_lib { void DataSourcePybind(pybind11::module &m) { pybind11::module data = m.def_submodule("data", "data submodule of hugectr"); pybind11::class_<HugeCTR::DataSourceParams, std::shared_ptr<HugeCTR::DataSourceParams>>( data, "DataSourceParams") .def(pybind11::init<const bool, const std::string &, const int>(), pybind11::arg("use_hdfs") = false, pybind11::arg("namenode") = "localhost", pybind11::arg("port") = 9000) .def_readwrite("use_hdfs", &HugeCTR::DataSourceParams::use_hdfs) .def_readwrite("namenode", &HugeCTR::DataSourceParams::namenode) .def_readwrite("port", &HugeCTR::DataSourceParams::port); pybind11::class_<HugeCTR::DataSource, std::shared_ptr<HugeCTR::DataSource>>(data, "DataSource") .def(pybind11::init<const DataSourceParams &>(), pybind11::arg("data_source_params")) .def("move_to_local", &HugeCTR::DataSource::move_to_local); } } // namespace python_lib } // namespace HugeCTR
41.853659
97
0.7162
mikemckiernan
dd53adb8829fe1a6c7df45a709fbe0d46c630245
2,221
cc
C++
base/base_paths_android.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
base/base_paths_android.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
base/base_paths_android.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Defines base::PathProviderAndroid which replaces base::PathProviderPosix for // Android in base/path_service.cc. #include <limits.h> #include <unistd.h> #include "base/android/jni_android.h" #include "base/android/path_utils.h" #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/notreached.h" #include "base/process/process_metrics.h" namespace base { bool PathProviderAndroid(int key, FilePath* result) { switch (key) { case base::FILE_EXE: { FilePath bin_dir; if (!ReadSymbolicLink(FilePath(kProcSelfExe), &bin_dir)) { NOTREACHED() << "Unable to resolve " << kProcSelfExe << "."; return false; } *result = bin_dir; return true; } case base::FILE_MODULE: // dladdr didn't work in Android as only the file name was returned. NOTIMPLEMENTED(); return false; case base::DIR_MODULE: return base::android::GetNativeLibraryDirectory(result); case base::DIR_SRC_TEST_DATA_ROOT: case base::DIR_GEN_TEST_DATA_ROOT: // These are only used by tests. In that context, they are overridden by // PathProviders in //base/test/test_support_android.cc. NOTREACHED(); return false; case base::DIR_USER_DESKTOP: // Android doesn't support GetUserDesktop. NOTIMPLEMENTED(); return false; case base::DIR_CACHE: return base::android::GetCacheDirectory(result); case base::DIR_ASSETS: // On Android assets are normally loaded from the APK using // base::android::OpenApkAsset(). In tests, since the assets are no // packaged, DIR_ASSETS is overridden to point to the build directory. return false; case base::DIR_ANDROID_APP_DATA: return base::android::GetDataDirectory(result); case base::DIR_ANDROID_EXTERNAL_STORAGE: return base::android::GetExternalStorageDirectory(result); } // For all other keys, let the PathService fall back to a default, if defined. return false; } } // namespace base
33.651515
80
0.697434
zealoussnow
dd542d215fe0fe0fb9d485c8e756b68b4c9ebd9e
2,151
cpp
C++
problems/week03-first_hit/src/algorithm.cpp
haeggee/algolab
176a7d4efbbfb2842f46e93250be00d3b59e0ec3
[ "MIT" ]
null
null
null
problems/week03-first_hit/src/algorithm.cpp
haeggee/algolab
176a7d4efbbfb2842f46e93250be00d3b59e0ec3
[ "MIT" ]
null
null
null
problems/week03-first_hit/src/algorithm.cpp
haeggee/algolab
176a7d4efbbfb2842f46e93250be00d3b59e0ec3
[ "MIT" ]
null
null
null
//1 #include <CGAL/Exact_predicates_exact_constructions_kernel.h> typedef CGAL::Exact_predicates_exact_constructions_kernel K; typedef K::Point_2 P; typedef K::Segment_2 S; typedef K::Ray_2 R; using namespace std; double floor_to_double(const K::FT& x) { double a = std::floor(CGAL::to_double(x)); while (a > x) a -= 1; while (a+1 <= x) a += 1; return a; } int main() { ios_base::sync_with_stdio(false); int n; std::cin >> n; while(n > 0) { long x, y, a, b; cin >> x; cin >> y; cin >> a; cin >> b; P source = P(x,y); P closest_hit; R ray(source, P(a,b)); S hit_seg; bool hits = false; vector<S> segments(n); for(int i = 0; i < n; i++) { long r, s, t, u; cin >> r; cin >> s; cin >> t; cin >> u; P seg_p1 = P(r,s); P seg_p2 = P(t,u); S seg(seg_p1, seg_p2); segments[i] = seg; } random_shuffle(segments.begin(), segments.end()); for(int i = 0; i < n; i++) { S seg = segments[i]; P seg_p1 = seg.source(); P seg_p2 = seg.target(); if(!hits && CGAL::do_intersect(ray,seg)) { // no hit yet, i.e. only have ray auto o = CGAL::intersection(ray,seg); if (const P* op = boost::get<P>(&*o)) { // point intersec closest_hit = *op; } else { // segment intersec closest_hit = CGAL::has_larger_distance_to_point(source, seg_p1, seg_p2) ? seg_p2 : seg_p1; } hit_seg = S(source, closest_hit); hits = true; } else if(CGAL::do_intersect(hit_seg,seg)) { // hit once, so we have a segment auto o = CGAL::intersection(hit_seg,seg); if (const P* op = boost::get<P>(&*o)) { // point intersec closest_hit = *op; hit_seg = S(source, closest_hit); } else { // segment intersec closest_hit = CGAL::has_larger_distance_to_point(source, seg_p1, seg_p2) ? seg_p2 : seg_p1; hit_seg = S(source, closest_hit); } } } if(!hits) cout << "no" << endl; else cout << long(floor_to_double(closest_hit.x())) << " " << long(floor_to_double(closest_hit.y())) << endl; cin >> n; } }
29.875
111
0.55881
haeggee