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
109
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
48.5k
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
f477acb834ef5d09a1b8d6bb5b20a4411eabd74f
2,992
cpp
C++
Algorithms/Validator/valGeneral3Deg.cpp
lucaskeiler/AlgoritmosTCC
eccf14c2c872acb9e0728eb8948eee121b274f2e
[ "MIT" ]
null
null
null
Algorithms/Validator/valGeneral3Deg.cpp
lucaskeiler/AlgoritmosTCC
eccf14c2c872acb9e0728eb8948eee121b274f2e
[ "MIT" ]
null
null
null
Algorithms/Validator/valGeneral3Deg.cpp
lucaskeiler/AlgoritmosTCC
eccf14c2c872acb9e0728eb8948eee121b274f2e
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cmath> #include "infection3deg.h" #include <ctime> using namespace std; int main (){ printf("["); for(int t = 20;t <= 10000;t+=20){ int n = t; Graph graph(n); graph.degree[0] = 1; graph.degree[n-1] = 1; //int y = 1,m = 1; int k = int(n/4 + 1); // while(y < n){ // for(int i=0;i<k-2 && y<n;i++){ // if(y == n-1){ // graph.degree[y++] = 3; // m+=3; // }else{ // if(y == n-2){ // graph.degree[y++] = 2; // m+=2; // }else{ // graph.degree[y++] = 3; // m+=3; // } // } // if(y<n){ // graph.degree[y++] = 1; // m++; // } // } // if(y < n){ // if(y == n-1){ // graph.degree[y++] = 1; // m+=1; // }else{ // graph.degree[y++] = 2; // m+=2; // } // } // } for(int i=1;i<n-1;i++){ if(i%2) graph.degree[i] = 3; else graph.degree[i] = 1; } //m/=2; graph.adjList[0].push_back(1); graph.adjList[1].push_back(0); for(int i=1;i<n-2;i+=2){ graph.adjList[i].push_back(i+1); graph.adjList[i+1].push_back(i); graph.adjList[i].push_back(i+2); graph.adjList[i+2].push_back(i); } // y = 1; // while(y < n){ // if(graph.degree[y] == 3){ // if(y+1 < n){ // graph.adjList[y].push_back(y+1); // graph.adjList[y+1].push_back(y); // } // if(y+2 < n){ // graph.adjList[y].push_back(y+2); // graph.adjList[y+2].push_back(y); // } // y += 2; // }else{ // if(y+1 < n){ // graph.adjList[y].push_back(y+1); // graph.adjList[y+1].push_back(y); // } // y++; // } // } //DEBUG // for(int i=0;i<n;i++){ // printf("(%d) -> %d: ",i,graph.degree[i]); // for(auto viz : graph.adjList[i]) // printf("%d, ",viz); // printf("\n"); // } clock_t begin = clock(); decide(graph,k); //getchar(); clock_t end = clock(); //printf("%d\n",resp); printf("[%d, %f], ",n,(double)(end - begin)/CLOCKS_PER_SEC); } printf("]\n"); return 0; }
23.559055
68
0.304144
lucaskeiler
f47c3987fa2311f982ef31193d7757bacaf250b7
8,285
cpp
C++
Examples_5_4/Sticktrace/SticktraceWindow.cpp
hukushirom/luastick
29e43ee9d7e26b6ab45a510e664825b8c64845ac
[ "MIT" ]
12
2020-04-26T11:38:00.000Z
2021-11-02T21:13:27.000Z
Examples_5_4/Sticktrace/SticktraceWindow.cpp
hukushirom/luastick
29e43ee9d7e26b6ab45a510e664825b8c64845ac
[ "MIT" ]
null
null
null
Examples_5_4/Sticktrace/SticktraceWindow.cpp
hukushirom/luastick
29e43ee9d7e26b6ab45a510e664825b8c64845ac
[ "MIT" ]
null
null
null
// SticktraceWindow.cpp : DLL の初期化ルーチンです。 // #include "stdafx.h" #include <thread> #include "Resource.h" // For IDD_STICK_TRACE. #include "RegBase.h" #include "DlgSticktrace.h" #include "Sticktrace.h" #ifdef _DEBUG #define new DEBUG_NEW #endif class __declspec(dllexport) SticktraceWindow { private: static SticktraceWindow* New( const wchar_t* companyName, const wchar_t* packageName, const wchar_t* applicationName, unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ); static void Delete(SticktraceWindow* mtw); SticktraceWindow( unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ); ~SticktraceWindow(); bool Show(bool show); bool IsVisible(bool & isVisible); bool IsScriptModified(bool & isModified); bool SetSource(const char * sandbox, const char * name, const char * source); bool IsDebugMode(); bool IsBreakpoint(const char* name, int lineIndex); bool OnSuspended(); bool OnResumed(); bool Jump(const char * name, int lineIndex); bool NewSession(); bool OnStart(SticktraceDef::ExecType execType); bool OnStop(SticktraceDef::ExecType execType); //----- 21.05.18 Fukushiro M. 削除始 ()----- //// 21.05.18 Fukushiro M. 1行追加 () // bool OnErrorStop(const char* message); //----- 21.05.18 Fukushiro M. 削除終 ()----- bool OutputError(const char* message); bool OutputDebug(const char* message); bool SetWatch(const char * data); bool SetVariableNotify(bool succeeded); SticktraceDef::SuspendCommand WaitCommandIsSet(StickString & paramA, uint32_t waitMilliseconds); // 20.06.10 1行削除 () // void Create(unsigned int dialogId); void Destroy(); static void StaticThreadFunc( SticktraceWindow* stickTrace, unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ); void ThreadFunc( unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ); private: CDlgSticktrace* m_stickTraceDlg; LONG m_threadId; LONG m_threadTerminateFlag; }; SticktraceWindow* SticktraceWindow::New( const wchar_t* companyName, const wchar_t* packageName, const wchar_t* applicationName, unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ) { FCRegBase::SetApplicationInfo(companyName, packageName, applicationName); return new SticktraceWindow(dialogId, DGT_debuggerCallbackFunc, debuggerCallbackData); } void SticktraceWindow::Delete(SticktraceWindow* mtw) { delete mtw; } SticktraceWindow::SticktraceWindow( unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ) : m_stickTraceDlg(nullptr) , m_threadId(0) , m_threadTerminateFlag(0) { if (::InterlockedCompareExchange(&m_threadId, 0, 0) != 0) return; std::thread{ SticktraceWindow::StaticThreadFunc, this, dialogId, DGT_debuggerCallbackFunc, debuggerCallbackData }.detach(); for (int i = 0; i != 100 && ::InterlockedCompareExchange(&m_threadId, 0, 0) == 0; i++) ::Sleep(10); } SticktraceWindow::~SticktraceWindow() { Destroy(); } void SticktraceWindow::StaticThreadFunc( SticktraceWindow* stickTrace, unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ) { stickTrace->ThreadFunc(dialogId, DGT_debuggerCallbackFunc, debuggerCallbackData); } void SticktraceWindow::ThreadFunc( unsigned int dialogId, SticktraceDef::DebuggerCallbackFunc DGT_debuggerCallbackFunc, void* debuggerCallbackData ) { m_stickTraceDlg = new CDlgSticktrace(); m_stickTraceDlg->SetDialogId(dialogId); m_stickTraceDlg->SetDebuggerCallback(DGT_debuggerCallbackFunc, debuggerCallbackData); m_stickTraceDlg->Create(IDD_STICK_TRACE); m_stickTraceDlg->EnableWindow(FALSE); // スレッドIDを設定。後で強制終了できるよう。CSロック前なのでInterlockedで設定。 ::InterlockedExchange(&m_threadId, (LONG)::GetCurrentThreadId()); while (::InterlockedCompareExchange(&m_threadTerminateFlag, 0, 0) == 0) AfxGetApp()->PumpMessage(); //----- 20.07.30 Fukushiro M. 削除始 ()----- // MSG msg; // for (;;) // { // if (::InterlockedCompareExchange(&m_threadTerminateFlag, 0, 0) != 0) // break; //// AfxGetApp()->PumpMessage(); // if (::GetMessage(&msg, NULL, 0, 0)) // { // if (!m_stickTraceDlg->PreTranslateMessage(&msg)) // { // // ::TranslateMessage(&msg); // ::DispatchMessage(&msg); // } // } // } // // // while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) // { // if (::InterlockedCompareExchange(&m_threadTerminateFlag, 0, 0) != 0) // break; // if (!AfxGetApp()->PumpMessage()) // { // break; // } // } //----- 20.07.30 Fukushiro M. 削除終 ()----- //----- 20.07.30 Fukushiro M. 変更終 ()----- m_stickTraceDlg->DestroyWindow(); delete m_stickTraceDlg; m_stickTraceDlg = nullptr; // スレッドIDを解除。 ::InterlockedExchange(&m_threadId, 0); ::InterlockedExchange(&m_threadTerminateFlag, 0); } void SticktraceWindow::Destroy() { auto threadId = (DWORD)::InterlockedCompareExchange(&m_threadId, 0, 0); if (threadId == 0) return; auto threadHandle = ::OpenThread(THREAD_ALL_ACCESS, false, threadId); ::InterlockedExchange(&m_threadTerminateFlag, 1); #if defined(_DEBUG) static constexpr int WAIT_COUNT = 5000; #else static constexpr int WAIT_COUNT = 50; #endif DWORD result = WAIT_TIMEOUT; for (int i = 0; i != WAIT_COUNT && result == WAIT_TIMEOUT; i++) { // Post the WM_USER as a dummy message to work the GetMessage function. if (::IsWindow(m_stickTraceDlg->GetSafeHwnd())) m_stickTraceDlg->PostMessage(WM_USER); result = ::WaitForSingleObject(threadHandle, 100); } if (result == WAIT_TIMEOUT) { ::TerminateThread(threadHandle, 0); ::CloseHandle(threadHandle); // delete m_stickTraceDlg はできない。スレッドを強制停止したため。 } m_stickTraceDlg = nullptr; ::InterlockedExchange(&m_threadId, 0); ::InterlockedExchange(&m_threadTerminateFlag, 0); } bool SticktraceWindow::Show(bool show) { return m_stickTraceDlg->APT_Show(show); } bool SticktraceWindow::IsVisible(bool & isVisible) { if (m_stickTraceDlg == nullptr) return false; return m_stickTraceDlg->APT_IsVisible(isVisible); } bool SticktraceWindow::IsScriptModified(bool & isModified) { if (m_stickTraceDlg == nullptr) return false; return m_stickTraceDlg->APT_IsScriptModified(isModified); } bool SticktraceWindow::SetSource(const char * sandbox, const char * name, const char * source) { return m_stickTraceDlg->APT_SetSource(sandbox, name, source); } bool SticktraceWindow::IsDebugMode() { return m_stickTraceDlg->APT_IsDebugMode(); } bool SticktraceWindow::IsBreakpoint(const char* name, int lineIndex) { return m_stickTraceDlg->APT_IsBreakpoint(name, lineIndex); } bool SticktraceWindow::OnSuspended() { return m_stickTraceDlg->APT_OnSuspended(); } bool SticktraceWindow::OnResumed() { return m_stickTraceDlg->APT_OnResumed(); } bool SticktraceWindow::Jump(const char * name, int lineIndex) { return m_stickTraceDlg->APT_Jump(name, lineIndex); } bool SticktraceWindow::NewSession() { return m_stickTraceDlg->APT_NewSession(); } bool SticktraceWindow::OnStart(SticktraceDef::ExecType execType) { return m_stickTraceDlg->APT_OnStart(execType); } bool SticktraceWindow::OnStop(SticktraceDef::ExecType execType) { return m_stickTraceDlg->APT_OnStop(execType); } //----- 21.05.18 Fukushiro M. 削除始 ()----- ////----- 21.05.18 Fukushiro M. 追加始 ()----- //bool SticktraceWindow::OnErrorStop(const char * message) //{ // return m_stickTraceDlg->APT_OnErrorStop(message); //} ////----- 21.05.18 Fukushiro M. 追加終 ()----- //----- 21.05.18 Fukushiro M. 削除終 ()----- bool SticktraceWindow::OutputError(const char * message) { return m_stickTraceDlg->APT_OutputError(message); } bool SticktraceWindow::OutputDebug(const char * message) { return m_stickTraceDlg->APT_OutputDebug(message); } bool SticktraceWindow::SetWatch(const char * data) { return m_stickTraceDlg->APT_SetWatch(data); } bool SticktraceWindow::SetVariableNotify(bool succeeded) { return m_stickTraceDlg->APT_SetVariableNotify(succeeded); } SticktraceDef::SuspendCommand SticktraceWindow::WaitCommandIsSet(StickString & paramA, uint32_t waitMilliseconds) { return m_stickTraceDlg->APT_WaitCommandIsSet(paramA, waitMilliseconds); }
26.812298
124
0.749427
hukushirom
f47e429b41b9e543425fde38c44e240f9a80fd1f
18,267
cpp
C++
src/caffe/test/test_roi_pooling_layer.cpp
imoisture/caffe
4d6892afeff234c57ce470056939101e0ae71369
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_roi_pooling_layer.cpp
imoisture/caffe
4d6892afeff234c57ce470056939101e0ae71369
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_roi_pooling_layer.cpp
imoisture/caffe
4d6892afeff234c57ce470056939101e0ae71369
[ "BSD-2-Clause" ]
null
null
null
/* All modification made by Cambricon Corporation: © 2018-2019 Cambricon Corporation All rights reserved. All other contributions: Copyright (c) 2014--2019, the respective contributors All rights reserved. For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <algorithm> #include <cfloat> #include <cmath> #include <memory> #include <random> #include <string> #include <vector> #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/layers/mlu_roi_pooling_layer.hpp" #include "caffe/layers/roi_pooling_layer.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/util/math_functions.hpp" #include "gtest/gtest.h" using std::max; using std::min; using std::floor; using std::ceil; namespace caffe { template <typename Dtype> void caffe_roipool(const Blob<Dtype>* in, const Blob<Dtype>* in2, ROIPoolingParameter* roi_pool_param, Blob<Dtype>* out, int mode_option) { int channels_ = in->channels(); int height_ = in->height(); int width_ = in->width(); CHECK_GT(roi_pool_param->pooled_h(), 0) << "pooled_h must be > 0"; CHECK_GT(roi_pool_param->pooled_w(), 0) << "pooled_w must be > 0"; int pooled_height_ = roi_pool_param->pooled_h(); int pooled_width_ = roi_pool_param->pooled_w(); float spatial_scale_ = roi_pool_param->spatial_scale(); const Dtype* bottom_data = in->cpu_data(); const Dtype* bottom_rois = in2->cpu_data(); // Number of ROIs int num_rois = in2->num(); int batch_size = in->num(); int top_count = out->count(); Dtype* top_data = out->mutable_cpu_data(); caffe_set(top_count, Dtype(0), top_data); // For each ROI R = [batch_index x1 y1 x2 y2]: max pool over R int roi_batch_ind; int roi_start_w; int roi_start_h; int roi_end_w; int roi_end_h; for (int n = 0; n < num_rois; ++n) { if (mode_option == 0) { roi_batch_ind = bottom_rois[0]; roi_start_w = round(bottom_rois[1] * spatial_scale_); roi_start_h = round(bottom_rois[2] * spatial_scale_); roi_end_w = round(bottom_rois[3] * spatial_scale_); roi_end_h = round(bottom_rois[4] * spatial_scale_); } else { roi_batch_ind = bottom_rois[4]; roi_start_w = round(bottom_rois[0] * spatial_scale_); roi_start_h = round(bottom_rois[1] * spatial_scale_); roi_end_w = round(bottom_rois[2] * spatial_scale_); roi_end_h = round(bottom_rois[3] * spatial_scale_); } CHECK_GE(roi_batch_ind, 0); CHECK_LT(roi_batch_ind, batch_size); int roi_height = max(roi_end_h - roi_start_h + 1, 1); int roi_width = max(roi_end_w - roi_start_w + 1, 1); const Dtype bin_size_h = static_cast<Dtype>(roi_height) / static_cast<Dtype>(pooled_height_); const Dtype bin_size_w = static_cast<Dtype>(roi_width) / static_cast<Dtype>(pooled_width_); const Dtype* batch_data = bottom_data + in->offset(roi_batch_ind); for (int c = 0; c < channels_; ++c) { for (int ph = 0; ph < pooled_height_; ++ph) { for (int pw = 0; pw < pooled_width_; ++pw) { // Compute pooling region for this output unit: // start (included) = floor(ph * roi_height / pooled_height_) // end (excluded) = ceil((ph + 1) * roi_height / pooled_height_) int hstart = static_cast<int>(floor(static_cast<Dtype>(ph) * bin_size_h)); int wstart = static_cast<int>(floor(static_cast<Dtype>(pw) * bin_size_w)); int hend = static_cast<int>(ceil(static_cast<Dtype>(ph + 1) * bin_size_h)); int wend = static_cast<int>(ceil(static_cast<Dtype>(pw + 1) * bin_size_w)); hstart = min(max(hstart + roi_start_h, 0), height_); hend = min(max(hend + roi_start_h, 0), height_); wstart = min(max(wstart + roi_start_w, 0), width_); wend = min(max(wend + roi_start_w, 0), width_); bool is_empty = (hend <= hstart) || (wend <= wstart); const int pool_index = ph * pooled_width_ + pw; if (is_empty) { top_data[pool_index] = 0; } for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { const int index = h * width_ + w; if (batch_data[index] > top_data[pool_index]) { top_data[pool_index] = batch_data[index]; } } } } } // Increment all data pointers by one channel batch_data += in->offset(0, 1); top_data += out->offset(0, 1); } // Increment ROI data pointer bottom_rois += 5; } } void pad_uniform_distribution_data_roi_pooling(float* data, int count, int seed, float min, float max) { assert(data); std::mt19937 gen(seed); std::uniform_real_distribution<float> uniform(min, max); for (int i = 0; i < count; i++) { data[i] = uniform(gen); } } template <typename Dtype> void setInputData(Blob<Dtype>* bottom0, Blob<Dtype>* bottom1, int mode_option) { int num_rois = bottom1->count() / 5; int raw_count = bottom0->count(); float* data_raw = static_cast<float*>(malloc(raw_count * sizeof(float))); for (int i = 0; i < raw_count; i++) { data_raw[i] = i * 0.01; } float* cx = static_cast<float*>(malloc(num_rois * sizeof(float))); float* cy = static_cast<float*>(malloc(num_rois * sizeof(float))); float* w = static_cast<float*>(malloc(num_rois * sizeof(float))); float* h = static_cast<float*>(malloc(num_rois * sizeof(float))); float* idx = static_cast<float*>(malloc(num_rois * sizeof(float))); memset(idx, 0, num_rois * sizeof(float)); // NOLINT pad_uniform_distribution_data_roi_pooling(cx, num_rois, 1000, 5, 32); pad_uniform_distribution_data_roi_pooling(cy, num_rois, 1000, 5, 32); pad_uniform_distribution_data_roi_pooling(w, num_rois, 1000, 0, 10); pad_uniform_distribution_data_roi_pooling(h, num_rois, 1000, 0, 10); float* x1 = static_cast<float*>(malloc(num_rois * sizeof(float))); float* y1 = static_cast<float*>(malloc(num_rois * sizeof(float))); float* x2 = static_cast<float*>(malloc(num_rois * sizeof(float))); float* y2 = static_cast<float*>(malloc(num_rois * sizeof(float))); for (int i = 0; i < num_rois; i++) { x1[i] = cx[i] - w[i] / 2; x1[i] = std::min(x1[i], static_cast<float>(32)); y1[i] = cy[i] - h[i] / 2; y1[i] = std::min(y1[i], static_cast<float>(32)); x2[i] = cx[i] + w[i] / 2; x2[i] = std::min(x2[i], static_cast<float>(32)); y2[i] = cy[i] + h[i] / 2; y2[i] = std::min(y2[i], static_cast<float>(32)); } free(cx); free(cy); free(w); free(h); int unit_num = 5; if (mode_option == 0) { float* concat_data = static_cast<float*>(malloc(num_rois * unit_num * sizeof(float))); for (int i = 0; i < num_rois; i++) { concat_data[i * unit_num] = idx[i]; concat_data[i * unit_num + 1] = x1[i]; concat_data[i * unit_num + 2] = y1[i]; concat_data[i * unit_num + 3] = x2[i]; concat_data[i * unit_num + 4] = y2[i]; } for (int i = 0; i < bottom0->count(); i++) { bottom0->mutable_cpu_data()[i] = data_raw[i]; } for (int i = 0; i < bottom1->count(); i++) { bottom1->mutable_cpu_data()[i] = concat_data[i]; } } else { float* rois_conc_data = static_cast<float*>(malloc(num_rois * unit_num * sizeof(float))); for (int i = 0; i < num_rois; i++) { rois_conc_data[i * unit_num] = x1[i]; rois_conc_data[i * unit_num + 1] = y1[i]; rois_conc_data[i * unit_num + 2] = x2[i]; rois_conc_data[i * unit_num + 3] = y2[i]; rois_conc_data[i * unit_num + 4] = idx[i]; } for (int i = 0; i < bottom0->count(); i++) { bottom0->mutable_cpu_data()[i] = data_raw[i]; } for (int i = 0; i < bottom1->count(); i++) { bottom1->mutable_cpu_data()[i] = rois_conc_data[i]; } } free(x1); free(y1); free(x2); free(y2); free(idx); } template <typename TypeParam> class RoiPoolingLayerTest : public CPUDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: RoiPoolingLayerTest() : blob_bottom_(new Blob<Dtype>(1, 38, 20, 12)), blob_bottom2_(new Blob<Dtype>(1, 1, 1, 5)), blob_top_(new Blob<Dtype>()) {} virtual ~RoiPoolingLayerTest() { delete blob_bottom_; delete blob_bottom2_; delete blob_top_; } virtual void SetUp() { FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom2_); blob_bottom_vec_.push_back(blob_bottom_); blob_bottom_vec_.push_back(blob_bottom2_); blob_top_vec_.push_back(blob_top_); } virtual Blob<Dtype>* MakeReferenceTop(Blob<Dtype>* top) { this->ref_blob_top_.reset(new Blob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_bottom2_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; shared_ptr<Blob<Dtype>> ref_blob_top_; }; TYPED_TEST_CASE(RoiPoolingLayerTest, TestDtypesAndDevices); TYPED_TEST(RoiPoolingLayerTest, TestSetUp) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ROIPoolingParameter* roi_pool_param = layer_param.mutable_roi_pooling_param(); roi_pool_param->set_pooled_h(3); roi_pool_param->set_pooled_w(3); roi_pool_param->set_spatial_scale(3); shared_ptr<ROIPoolingLayer<Dtype>> layer( new ROIPoolingLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(RoiPoolingLayerTest, Forward) { typedef typename TypeParam::Dtype Dtype; setInputData(this->blob_bottom_, this->blob_bottom2_, 0); LayerParameter layer_param; ROIPoolingParameter* roi_pool_param = layer_param.mutable_roi_pooling_param(); roi_pool_param->set_pooled_h(3); roi_pool_param->set_pooled_w(3); roi_pool_param->set_spatial_scale(3); ROIPoolingLayer<Dtype> layer(layer_param); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data = this->blob_top_->cpu_data(); caffe_roipool(this->blob_bottom_, this->blob_bottom2_, roi_pool_param, this->MakeReferenceTop(this->blob_top_), 0); const Dtype* ref_top_data = this->ref_blob_top_->cpu_data(); const int count = this->blob_top_->count(); for (int i = 0; i < count; i++) { EXPECT_NEAR(top_data[i], ref_top_data[i], 5e-3); } } #ifdef USE_MLU template <typename TypeParam> class MLUBangRoiPoolingLayerTest : public MLUDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: MLUBangRoiPoolingLayerTest() : blob_bottom_(new Blob<Dtype>(1, 32, 80, 90)), blob_bottom2_(new Blob<Dtype>(1, 1, 1, 5)), blob_top_(new Blob<Dtype>()) {} virtual ~MLUBangRoiPoolingLayerTest() { delete blob_bottom_; delete blob_bottom2_; delete blob_top_; } virtual void SetUp() { FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom2_); blob_bottom_vec_.push_back(blob_bottom_); blob_bottom_vec_.push_back(blob_bottom2_); blob_top_vec_.push_back(blob_top_); } virtual Blob<Dtype>* MakeReferenceTop(Blob<Dtype>* top) { this->ref_blob_top_.reset(new Blob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_bottom2_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; shared_ptr<Blob<Dtype>> ref_blob_top_; }; TYPED_TEST_CASE(MLUBangRoiPoolingLayerTest, TestMLUDevices); TYPED_TEST(MLUBangRoiPoolingLayerTest, TestSetUpBangOp) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ROIPoolingParameter* roi_pool_param = layer_param.mutable_roi_pooling_param(); roi_pool_param->set_pooled_h(3); roi_pool_param->set_pooled_w(3); roi_pool_param->set_spatial_scale(3); shared_ptr<MLUROIPoolingLayer<Dtype>> layer( new MLUROIPoolingLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); OUTPUT("bottom1", this->blob_bottom_->shape_string().c_str()); } TYPED_TEST(MLUBangRoiPoolingLayerTest, ForwardBangOp) { typedef typename TypeParam::Dtype Dtype; setInputData(this->blob_bottom_, this->blob_bottom2_, 1); LayerParameter layer_param; ROIPoolingParameter* roi_pool_param = layer_param.mutable_roi_pooling_param(); roi_pool_param->set_pooled_h(3); roi_pool_param->set_pooled_w(3); roi_pool_param->set_spatial_scale(3); MLUROIPoolingLayer<Dtype> layer(layer_param); Caffe::setDetectOpMode(1); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Reshape_dispatch(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data = this->blob_top_->cpu_data(); caffe_roipool(this->blob_bottom_, this->blob_bottom2_, roi_pool_param, this->MakeReferenceTop(this->blob_top_), 1); const Dtype* ref_top_data = this->ref_blob_top_->cpu_data(); const int count = this->blob_top_->count(); float err_sum = 0, sum = 0; for (int i = 0; i < count; i++) { err_sum += std::abs(top_data[i] - ref_top_data[i]); sum += std::abs(ref_top_data[i]); } EXPECT_LT(err_sum/sum, 0.1); } template <typename TypeParam> class MFUSBangRoiPoolingLayerTest : public MFUSDeviceTest<TypeParam> { typedef typename TypeParam :: Dtype Dtype; protected: MFUSBangRoiPoolingLayerTest() : blob_bottom_(new Blob<Dtype>(1, 32, 80, 90)), blob_bottom2_(new Blob<Dtype>(1, 1, 1, 5)), blob_top_(new Blob<Dtype>()) {} virtual ~MFUSBangRoiPoolingLayerTest() { delete blob_bottom_; delete blob_bottom2_; delete blob_top_; } virtual void SetUp() { FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_bottom2_); blob_bottom_vec_.push_back(blob_bottom_); blob_bottom_vec_.push_back(blob_bottom2_); blob_top_vec_.push_back(blob_top_); } virtual Blob<Dtype>* MakeReferenceTop(Blob<Dtype>* top) { this->ref_blob_top_.reset(new Blob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_bottom2_; Blob<Dtype>* const blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; shared_ptr<Blob<Dtype> > ref_blob_top_; }; TYPED_TEST_CASE(MFUSBangRoiPoolingLayerTest, TestMFUSDevices); TYPED_TEST(MFUSBangRoiPoolingLayerTest, TestSetUp) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; ROIPoolingParameter* roi_pool_param = layer_param.mutable_roi_pooling_param(); roi_pool_param->set_pooled_h(3); roi_pool_param->set_pooled_w(3); roi_pool_param->set_spatial_scale(3); shared_ptr<MLUROIPoolingLayer<Dtype>> layer( new MLUROIPoolingLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); } TYPED_TEST(MFUSBangRoiPoolingLayerTest, ForwardBang) { typedef typename TypeParam::Dtype Dtype; setInputData(this->blob_bottom_, this->blob_bottom2_, 1); LayerParameter layer_param; ROIPoolingParameter* roi_pool_param = layer_param.mutable_roi_pooling_param(); roi_pool_param->set_pooled_h(3); roi_pool_param->set_pooled_w(3); roi_pool_param->set_spatial_scale(3); MLUROIPoolingLayer<Dtype> layer(layer_param); Caffe::setDetectOpMode(1); layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); ASSERT_TRUE(layer.mfus_supported()); MFusion<Dtype> fuser; fuser.reset(); fuser.addInputs(this->blob_bottom_vec_); fuser.addOutputs(this->blob_top_vec_); layer.Reshape_dispatch(this->blob_bottom_vec_, this->blob_top_vec_); layer.fuse(&fuser); fuser.compile(); fuser.forward(); const Dtype* top_data = this->blob_top_->cpu_data(); caffe_roipool(this->blob_bottom_, this->blob_bottom2_, roi_pool_param, this->MakeReferenceTop(this->blob_top_), 1); const Dtype* ref_top_data = this->ref_blob_top_->cpu_data(); const int count = this->blob_top_->count(); float err_sum = 0, sum = 0; for (int i = 0; i < count; i++) { EXPECT_NEAR(top_data[i], ref_top_data[i], 5e-3); err_sum += std::abs(top_data[i] - ref_top_data[i]); sum += std::abs(ref_top_data[i]); } EXPECT_LT(err_sum/sum, 0.1); } #endif } // namespace caffe
37.203666
92
0.69059
imoisture
f47eaa9c3c7d9147e6cf84b23dbbcf03d35c3c84
3,576
cpp
C++
libs/assign/v2/test/chain.cpp
rogard/assign_v2
8735f57177dbee57514b4e80c498dd4b89f845e5
[ "BSL-1.0" ]
null
null
null
libs/assign/v2/test/chain.cpp
rogard/assign_v2
8735f57177dbee57514b4e80c498dd4b89f845e5
[ "BSL-1.0" ]
null
null
null
libs/assign/v2/test/chain.cpp
rogard/assign_v2
8735f57177dbee57514b4e80c498dd4b89f845e5
[ "BSL-1.0" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // Boost.Assign v2 // // // // Copyright (C) 2003-2004 Thorsten Ottosen // // Copyright (C) 2011 Erwann Rogard // // Use, modification and distribution are subject to the // // Boost Software License, Version 1.0. (See accompanying file // // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ////////////////////////////////////////////////////////////////////////////// #include <iterator> #include <vector> #include <list> #include <string> #include <boost/assign/v2/include/ref/csv_array.hpp> #include <boost/assign/v2/include/csv_deque_basic.hpp> #include <boost/assign/v2/include/chain.hpp> #include <boost/assign/v2/chain/check.hpp> #include <boost/assign/v2/chain/operator.hpp> #include <boost/next_prior.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm/equal.hpp> #include <boost/range/algorithm_ext/iota.hpp> #include <boost/range/begin.hpp> #include <boost/range/end.hpp> #include <libs/assign/v2/test/chain.h> namespace test_assign_v2{ namespace xxx_chain{ // MSVC REMINDER : fully qualify boost::begin boost::end - error C2668 void test() { namespace as2 = boost::assign::v2; { namespace ns = as2::check_chain_aux; { typedef int T; ns::static_<T>(); ns::static_<T>(); } { typedef double T; ns::static_<T>(); ns::static_<T>(); } } // Non-Boost.Assign.v2 containers { //[test_chain1 typedef std::string T; std::vector<T> word; boost::copy( as2::csv_deque( "O", "R" ) | as2::_chain( as2::csv_deque( "B", "I", "T" ) ), std::back_inserter( word ) ); BOOST_ASSIGN_V2_CHECK( boost::range::equal( word, as2::csv_deque<T>( "O", "R", "B", "I", "T" ) ) ); //] } { //[test_chain2 typedef int T; boost::array<T, 3> head; std::list<T> tail( 2 ); boost::copy( as2::csv_deque( 1, 2, 3, 4, 5 ), boost::begin( head | as2::_chain( tail ) ) ); BOOST_ASSIGN_V2_CHECK( boost::range::equal( head, as2::csv_deque( 1, 2, 3 ) ) ); BOOST_ASSIGN_V2_CHECK( boost::range::equal( tail, as2::csv_deque( 4, 5 ) ) ); //] } // Boost.Assign.v2 containers { //[test_chain3 std::vector<int> source( 8 ); boost::iota(source, 1); boost::array<int, 4> head; int t, a, i, l; /*<<Brings `&&` to scope>>*/using namespace boost::assign::v2; boost::copy( source, boost::begin( head && (/*<< rvalue! >>*/ as2::ref::csv_array( t, a, i, l ) | as2::ref::_get ) ) ); BOOST_ASSIGN_V2_CHECK( boost::range::equal( head, as2::csv_deque( 1, 2, 3, 4 ) ) ); BOOST_ASSIGN_V2_CHECK( t == 5 ); BOOST_ASSIGN_V2_CHECK( a == 6 ); BOOST_ASSIGN_V2_CHECK( i == 7 ); BOOST_ASSIGN_V2_CHECK( l == 8 ); //] } }// test }// xxx_chain }// test_assign_v2
35.058824
99
0.465324
rogard
f480b2588ac6aaea63bfb023173718530adc59ec
6,976
cpp
C++
PDFWriterTestPlayground/TestsRunner.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
620
2015-02-10T16:38:47.000Z
2022-03-30T11:06:17.000Z
PDFWriterTestPlayground/TestsRunner.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
124
2015-01-14T20:50:29.000Z
2021-12-08T09:51:01.000Z
PDFWriterTestPlayground/TestsRunner.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
185
2015-04-16T11:09:39.000Z
2022-03-07T03:25:15.000Z
/* Source File : TestsRunner.cpp Copyright 2011 Gal Kahana PDFWriter 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 "TestsRunner.h" #include <iostream> using namespace std; using namespace PDFHummus; TestsRunner::TestsRunner(void) { } TestsRunner::~TestsRunner(void) { DeleteTests(); } void TestsRunner::DeleteTests() { StringToStringAndTestUnitListMap::iterator it = mTests.begin(); for(;it!= mTests.end();++it) { StringAndTestUnitList::iterator itList = it->second.begin(); for(; itList != it->second.end();++itList) delete(itList->second); } mTests.clear(); } EStatusCode TestsRunner::RunAll(const TestConfiguration& inTestConfiguration) { StringAndTestUnitList testsList; StringToTestUnitMap::iterator it = mTestsByName.begin(); for(;it != mTestsByName.end();++it) testsList.push_back(StringAndTestUnit(it->first,it->second)); return RunTestsInList(inTestConfiguration,testsList); } EStatusCode TestsRunner::RunTestsInList(const TestConfiguration& inTestConfiguration,const StringAndTestUnitList& inTests) { EStatusCode testsStatus; if(inTests.size() == 0) { cout<<"No tests to run\n"; testsStatus = PDFHummus::eSuccess; } else if(inTests.size() == 1) { testsStatus = RunSingleTest(inTestConfiguration,inTests.front().first,inTests.front().second); } else { unsigned long failedCount = 0,succeededCount = 0; StringAndTestUnitList::const_iterator it = inTests.begin(); EStatusCode testStatus; testsStatus = PDFHummus::eSuccess; cout<<"Start tests run\n"; for(;it!= inTests.end();++it) { testStatus = RunSingleTest(inTestConfiguration,it->first,it->second); if(PDFHummus::eFailure == testStatus) { ++failedCount; testsStatus = PDFHummus::eFailure; } else { ++succeededCount; } } cout<<"--------------------------------------------------------------\n"; cout<<"Test run ended: "<<succeededCount<<" tests succeeded, "<<failedCount<<" tests failed.\n"; } return testsStatus; } EStatusCode TestsRunner::RunSingleTest(const TestConfiguration& inTestConfiguration,const string& inTestName,ITestUnit* inTest) { EStatusCode testStatus; cout<<"Running Test "<<inTestName<<"\n"; testStatus = inTest->Run(inTestConfiguration); if(PDFHummus::eFailure == testStatus) cout<<"Test "<<inTestName<<" Failed\n\n"; else cout<<"Test "<<inTestName<<" Succeeded\n\n"; return testStatus; } void TestsRunner::AddTest(const std::string& inTestLabel,const std::string& inCategory,ITestUnit* inTest) { StringToStringAndTestUnitListMap::iterator it = mTests.find(inCategory); if(it == mTests.end()) it = mTests.insert(StringToStringAndTestUnitListMap::value_type(inCategory,StringAndTestUnitList())).first; it->second.push_back(StringAndTestUnit(inTestLabel,inTest)); mTestsByName.insert(StringToTestUnitMap::value_type(inTestLabel,inTest)); } static const string scGeneral= "General"; void TestsRunner::AddTest(const string& inTestLabel,ITestUnit* inTest) { AddTest(inTestLabel,scGeneral,inTest); } EStatusCode TestsRunner::RunTest(const TestConfiguration& inTestConfiguration,const string& inTestLabel) { StringToTestUnitMap::iterator it = mTestsByName.find(inTestLabel); if(it == mTestsByName.end()) { cout<<"Test not found\n"; return PDFHummus::eSuccess; } else return RunSingleTest(inTestConfiguration,it->first,it->second); } EStatusCode TestsRunner::RunTests(const TestConfiguration& inTestConfiguration,const StringList& inTestsLabels) { StringAndTestUnitList testsList; StringList::const_iterator it = inTestsLabels.begin(); for(; it != inTestsLabels.end(); ++it) { StringToTestUnitMap::iterator itMap = mTestsByName.find(*it); if(itMap != mTestsByName.end()) testsList.push_back(StringAndTestUnit(itMap->first,itMap->second)); else cout<<"Test "<<*it<<" not found\n"; } return RunTestsInList(inTestConfiguration,testsList); } EStatusCode TestsRunner::RunCategory(const TestConfiguration& inTestConfiguration,const string& inCategory) { StringToStringAndTestUnitListMap::iterator it = mTests.find(inCategory); if(it == mTests.end()) { cout<<"Category "<<inCategory<<"not found\n"; return PDFHummus::eSuccess; } else return RunTestsInList(inTestConfiguration,it->second); } EStatusCode TestsRunner::RunCategories(const TestConfiguration& inTestConfiguration,const StringList& inCategories) { StringAndTestUnitList testsList; StringList::const_iterator it = inCategories.begin(); for(; it != inCategories.end(); ++it) { StringToStringAndTestUnitListMap::iterator itMap = mTests.find(*it); if(itMap != mTests.end()) testsList.insert(testsList.end(),itMap->second.begin(),itMap->second.end()); else cout<<"Category "<<*it<<" not found\n"; } return RunTestsInList(inTestConfiguration,testsList); } EStatusCode TestsRunner::RunCategories(const TestConfiguration& inTestConfiguration,const StringList& inCategories, const StringSet& inTestsToExclude) { StringAndTestUnitList testsList; StringList::const_iterator it = inCategories.begin(); for(; it != inCategories.end(); ++it) { StringToStringAndTestUnitListMap::iterator itMap = mTests.find(*it); if(itMap != mTests.end()) { StringAndTestUnitList::iterator itCategoryTests = itMap->second.begin(); for(;itCategoryTests != itMap->second.end();++itCategoryTests) if(inTestsToExclude.find(itCategoryTests->first) == inTestsToExclude.end()) testsList.push_back(StringAndTestUnit(itCategoryTests->first,itCategoryTests->second)); } else cout<<"Category "<<*it<<" not found\n"; } return RunTestsInList(inTestConfiguration,testsList); } EStatusCode TestsRunner::RunExcludeCategories(const TestConfiguration& inTestConfiguration,const StringSet& inCategories) { StringAndTestUnitList testsList; StringToStringAndTestUnitListMap::iterator it = mTests.begin(); for(; it != mTests.end(); ++it) if(inCategories.find(it->first) == inCategories.end()) testsList.insert(testsList.end(),it->second.begin(),it->second.end()); return RunTestsInList(inTestConfiguration,testsList); } EStatusCode TestsRunner::RunExcludeTests(const TestConfiguration& inTestConfiguration,const StringSet& inTests) { StringAndTestUnitList testsList; StringToTestUnitMap::iterator it = mTestsByName.begin(); for(; it != mTestsByName.end();++it) if(inTests.find(it->first) == inTests.end()) testsList.push_back(StringAndTestUnit(it->first,it->second)); return RunTestsInList(inTestConfiguration,testsList); }
30.462882
150
0.743836
thmclellan
f481619b9d3faf9bb1c0053840c7fa61c16127e8
1,093
hpp
C++
ch13/icstring.hpp
bashell/CppStandardLibrary
2aae03019288132c911036aeb9ba36edc56e510b
[ "MIT" ]
null
null
null
ch13/icstring.hpp
bashell/CppStandardLibrary
2aae03019288132c911036aeb9ba36edc56e510b
[ "MIT" ]
null
null
null
ch13/icstring.hpp
bashell/CppStandardLibrary
2aae03019288132c911036aeb9ba36edc56e510b
[ "MIT" ]
null
null
null
#ifndef ICSTRING_HPP #define ICSTRING_HPP #include <iostream> #include <string> #include <cctype> struct ignorecase_traits : public std::char_traits<char> { static bool eq(const char &c1, const char &c2) { return std::toupper(c1) == std::toupper(c2); } static bool lt(const char &c1, const char &c2) { return std::toupper(c1) < std::toupper(c2); } static int compare(const char *s1, const char *s2, std::size_t n) { for(std::size_t i = 0; i < n; ++i) { if(!eq(s1[i], s2[i])) { return lt(s1[i], s2[i]) ? -1 : 1; } } return 0; } static const char *find(const char *s, std::size_t n, const char &c) { for(std::size_t i = 0; i < n; ++i) { if(eq(s[i], c)) { return &(s[i]); } } return 0; } }; typedef std::basic_string<char, ignorecase_traits> icstring; inline std::ostream& operator<<(std::ostream &strm, const icstring &s) { return strm << std::string(s.data(), s.length()); } #endif /* ICSTRING_HPP */
25.418605
74
0.538884
bashell
f48696bca49c2e0233eabbac093b4b5c4482367b
204
cpp
C++
sources/ECS/Components/ModelMatrixComponent.cpp
Gilqamesh/GameEngineDemo
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
[ "MIT" ]
null
null
null
sources/ECS/Components/ModelMatrixComponent.cpp
Gilqamesh/GameEngineDemo
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
[ "MIT" ]
null
null
null
sources/ECS/Components/ModelMatrixComponent.cpp
Gilqamesh/GameEngineDemo
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
[ "MIT" ]
null
null
null
#include "ECS/Components/ModelMatrixComponent.hpp" namespace NAMESPACE { std::ostream &operator<<(std::ostream &os, const ModelMatrixComponent &a) { TRACE(); os << a.m; return (os); } }
14.571429
73
0.656863
Gilqamesh
f48deb148495a1f4ae92dcd20a7e3877b360ff57
2,937
cpp
C++
Framework/Source/Windows/LWVideo/LWVideoDrivers/LWVideoDriver_OpenGL3_3_Windows.cpp
slicer4ever/Lightwaver
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
3
2017-10-24T08:04:49.000Z
2018-08-28T10:08:08.000Z
Framework/Source/Windows/LWVideo/LWVideoDrivers/LWVideoDriver_OpenGL3_3_Windows.cpp
slicer4ever/Lightwave
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
null
null
null
Framework/Source/Windows/LWVideo/LWVideoDrivers/LWVideoDriver_OpenGL3_3_Windows.cpp
slicer4ever/Lightwave
1f444e42eab9988632f541ab3c8f491d557c7de7
[ "MIT" ]
null
null
null
#include "LWVideo/LWVideoDrivers/LWVideoDriver_OpenGL3_3.h" #include "LWPlatform/LWWindow.h" LWVideoDriver_OpenGL3_3 *LWVideoDriver_OpenGL3_3::MakeVideoDriver(LWWindow *Window, uint32_t Type) { LWWindowContext WinCon = Window->GetContext(); int32_t PixelFormat; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0 }; int32_t AttribList[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 2, 0, 0 }; LWOpenGL3_3Context Context = { nullptr, nullptr }; LWVideoDriver_OpenGL3_3 *Driver = nullptr; HGLRC GLContext = nullptr; if ((Context.m_DC = GetDC(WinCon.m_WND)) == nullptr) LWWindow::MakeDialog("Error: 'GetDC'", "ERROR", LWWindow::DialogOK); else if ((PixelFormat = ChoosePixelFormat(Context.m_DC, &pfd)) == 0) LWWindow::MakeDialog("Error: 'ChoosePixelFormat'", "ERROR", LWWindow::DialogOK); else if (!SetPixelFormat(Context.m_DC, PixelFormat, &pfd)) LWWindow::MakeDialog("Error: 'SetPixelFormat'", "ERROR", LWWindow::DialogOK); else if ((GLContext = wglCreateContext(Context.m_DC)) == nullptr) LWWindow::MakeDialog("Error: 'wglCreateContext'", "ERROR", LWWindow::DialogOK); else if (!wglMakeCurrent(Context.m_DC, GLContext)) LWWindow::MakeDialog("Error: 'wglMakeCurrent'", "ERROR", LWWindow::DialogOK); else if (glewInit() != GLEW_OK) LWWindow::MakeDialog("Error: 'glewInit'", "ERROR", LWWindow::DialogOK); else if (GLEW_VERSION_3_3) { if ((Context.m_GLRC = wglCreateContextAttribsARB(Context.m_DC, 0, AttribList)) == nullptr) LWWindow::MakeDialog("Error: 'wglCreateContextAttribsARB'", "ERROR", LWWindow::DialogOK); else { wglDeleteContext(GLContext); wglMakeCurrent(Context.m_DC, Context.m_GLRC); int32_t UniformBlockSize = 0; glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &UniformBlockSize); Driver = Window->GetAllocator()->Allocate<LWVideoDriver_OpenGL3_3>(Window, Context, (uint32_t)UniformBlockSize); } } if (!Driver) { if (GLContext) wglDeleteContext(GLContext); if (Context.m_GLRC) wglDeleteContext(Context.m_GLRC); if (Context.m_DC) ReleaseDC(WinCon.m_WND, Context.m_DC); } return Driver; } bool LWVideoDriver_OpenGL3_3::DestroyVideoContext(LWVideoDriver_OpenGL3_3 *Driver) { LWWindowContext &WinCon = Driver->GetWindow()->GetContext(); LWOpenGL3_3Context &Con = Driver->GetContext(); if (Con.m_GLRC) wglDeleteContext(Con.m_GLRC); if (Con.m_DC) ReleaseDC(WinCon.m_WND, Con.m_DC); LWAllocator::Destroy(Driver); return true; } bool LWVideoDriver_OpenGL3_3::Update(void) { return true; } LWVideoDriver &LWVideoDriver_OpenGL3_3::Present(uint32_t SwapInterval){ wglSwapIntervalEXT(SwapInterval); SwapBuffers(m_Context.m_DC); return *this; }
52.446429
210
0.716377
slicer4ever
f48eb9ce9f49c9e6ed3546c5b0f2289a44e0750d
466
hpp
C++
src/texture/systems/source.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
2
2021-03-18T16:25:04.000Z
2021-11-13T00:29:27.000Z
src/texture/systems/source.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
null
null
null
src/texture/systems/source.hpp
hexoctal/zenith
eeef065ed62f35723da87c8e73a6716e50d34060
[ "MIT" ]
1
2021-11-13T00:29:30.000Z
2021-11-13T00:29:30.000Z
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #ifndef ZEN_TEXTURES_SYSTEMS_SOURCE_HPP #define ZEN_TEXTURES_SYSTEMS_SOURCE_HPP #include <string> #include "../../ecs/entity.hpp" namespace Zen { Entity CreateTextureSource (Entity texture, std::string src, int index); void DestroyTextureSource (Entity source); } // namespace Zen #endif
20.26087
74
0.740343
hexoctal
f4932bd0df1fe71f9aa4c3962b8921a9258d28d0
3,275
cc
C++
base/core/test/dynamic_fws_multimap_test.cc
dgcl/motis
6b134f80aa3b6445f710418962f1fed9cffda3a0
[ "MIT" ]
null
null
null
base/core/test/dynamic_fws_multimap_test.cc
dgcl/motis
6b134f80aa3b6445f710418962f1fed9cffda3a0
[ "MIT" ]
null
null
null
base/core/test/dynamic_fws_multimap_test.cc
dgcl/motis
6b134f80aa3b6445f710418962f1fed9cffda3a0
[ "MIT" ]
1
2021-10-06T13:48:23.000Z
2021-10-06T13:48:23.000Z
#include "gtest/gtest.h" #include <algorithm> #include <iostream> #include <iterator> #include "motis/core/common/dynamic_fws_multimap.h" namespace motis { namespace { template <typename T, bool ConstBucket> void check_result( std::vector<T> const& ref, typename dynamic_fws_multimap<T>::template bucket<ConstBucket> const& result) { if (ref.size() != result.size() && result.size() < 10) { std::cout << "Invalid result:\n Expected: "; std::copy(begin(ref), end(ref), std::ostream_iterator<T>(std::cout, " ")); std::cout << "\n Result: "; std::copy(begin(result), end(result), std::ostream_iterator<T>(std::cout, " ")); std::cout << std::endl; } ASSERT_EQ(ref.size(), result.size()); for (auto i = 0UL; i < ref.size(); ++i) { EXPECT_EQ(ref[i], result[i]); } } template <typename T, typename SizeType> void print_multimap(dynamic_fws_multimap<T, SizeType>& mm) { for (auto const& bucket : mm) { std::cout << "key={" << bucket.index() << "} => [ "; for (auto const& entry : bucket) { std::cout << entry << " "; } std::cout << "]\n"; } } /* struct test_node { std::uint32_t id_{}; std::uint32_t tag_{}; }; */ struct test_edge { std::uint32_t from_{}; std::uint32_t to_{}; std::uint32_t weight_{}; }; inline std::ostream& operator<<(std::ostream& out, test_edge const& e) { return out << "{from=" << e.from_ << ", to=" << e.to_ << ", weight=" << e.weight_ << "}"; } } // namespace TEST(fws_dynamic_multimap_test, int_1) { dynamic_fws_multimap<int> mm; ASSERT_EQ(0, mm.element_count()); ASSERT_EQ(0, mm.index_size()); mm[0].push_back(42); ASSERT_EQ(1, mm.element_count()); ASSERT_EQ(1, mm.index_size()); check_result<int>({42}, mm[0]); ASSERT_EQ(1, mm[0].size()); mm[1].push_back(4); ASSERT_EQ(2, mm.element_count()); ASSERT_EQ(2, mm.index_size()); check_result<int>({42}, mm[0]); ASSERT_EQ(1, mm[0].size()); check_result<int>({4}, mm[1]); ASSERT_EQ(1, mm[1].size()); mm[1].push_back(8); ASSERT_EQ(3, mm.element_count()); ASSERT_EQ(2, mm.index_size()); check_result<int>({42}, mm[0]); ASSERT_EQ(1, mm[0].size()); check_result<int>({4, 8}, mm[1]); ASSERT_EQ(2, mm[1].size()); mm[1].emplace_back(15); ASSERT_EQ(4, mm.element_count()); ASSERT_EQ(2, mm.index_size()); check_result<int>({42}, mm[0]); ASSERT_EQ(1, mm[0].size()); check_result<int>({4, 8, 15}, mm[1]); ASSERT_EQ(3, mm[1].size()); mm[1].push_back(16); ASSERT_EQ(5, mm.element_count()); ASSERT_EQ(2, mm.index_size()); check_result<int>({42}, mm[0]); ASSERT_EQ(1, mm[0].size()); check_result<int>({4, 8, 15, 16}, mm[1]); ASSERT_EQ(4, mm[1].size()); mm[0].push_back(23); ASSERT_EQ(6, mm.element_count()); ASSERT_EQ(2, mm.index_size()); check_result<int>({42, 23}, mm[0]); ASSERT_EQ(2, mm[0].size()); check_result<int>({4, 8, 15, 16}, mm[1]); ASSERT_EQ(4, mm[1].size()); print_multimap(mm); } TEST(fws_dynamic_multimap_test, graph_1) { dynamic_fws_multimap<test_edge> mm; mm[0].emplace_back(0U, 1U, 10U); mm[1].emplace_back(1U, 2U, 20U); mm[1].emplace_back(1U, 3U, 30U); mm[3].emplace_back(3U, 0U, 50U); mm[2].emplace_back(2U, 3U, 5U); print_multimap(mm); } } // namespace motis
25
78
0.611603
dgcl
f49389d01da292cd85b77f6261c0a4d53d7d35a2
1,581
cpp
C++
UVa Online Judge (UVa)/Volume 5/516 - Prime Land.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 5/516 - Prime Land.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 5/516 - Prime Land.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
2
2018-11-06T19:37:56.000Z
2018-11-09T19:05:46.000Z
#include <cstdio> #include <iostream> #include <sstream> #include <cmath> #include <vector> using namespace std; #define N 32768 #define Check(N, pos) ((bool) ((N)&(1<<(pos)))) #define Set(N, pos) ((N)=((N)|(1<<(pos)))) unsigned status[(N>>5)+2], factor[N], power[N]; vector < unsigned > primes; void bitSieve() { unsigned sqrtN = unsigned (sqrt(N)); for(unsigned i=3 ; i<=sqrtN ; i+=2) if( !Check(status[i>>5], i&31) ) for(unsigned j=i*i ; j<=N ; j+=(i<<1)) Set(status[j>>5], j&31); primes.push_back(2); for(unsigned i=3 ; i<=N ; i+=2) if( !Check(status[i>>5], i&31) ) primes.push_back(i); } int main() { bitSieve(); string input; while( getline(cin, input) && input!="0" ) { stringstream converter(input); unsigned base, exponent, x = 1; while( converter >> base >> exponent ) for(unsigned i=1 ; i<=exponent ; i++) x *= base; x--; for(unsigned i=0 ; i<N ; i++) factor[i] = power[i] = 0; unsigned sz = primes.size(), len = 0; for(unsigned i=0 ; i<sz ; i++) { if( !(x%primes[i]) ) { factor[len] = primes[i]; while( !(x%primes[i]) ) { power[len]++; x /= primes[i]; } len++; } if( x==1 ) break; } for(unsigned i=len-1 ; i>0 ; i--) printf("%u %d ", factor[i], power[i]); printf("%u %d\n", factor[0], power[0]); } return 0; }
23.954545
75
0.460468
sreejonK19
f495aedea4e41eb706b3880fb79b008473595cf9
1,963
cpp
C++
Source/System/auth/xbox_live_server.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
2
2021-07-17T13:34:20.000Z
2022-01-09T00:55:51.000Z
Source/System/auth/xbox_live_server.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
null
null
null
Source/System/auth/xbox_live_server.cpp
blgrossMS/xbox-live-api
17c586336e11f0fa3a2a3f3acd665b18c5487b24
[ "MIT" ]
1
2018-11-18T08:32:40.000Z
2018-11-18T08:32:40.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "xsapi/system.h" #include "xbox_live_server_impl.h" using namespace XBOX_LIVE_NAMESPACE; NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_BEGIN xbox_live_server::xbox_live_server() { m_server_impl = std::make_shared<xbox_live_server_impl>(); } pplx::task<xbox_live_result<void>> xbox_live_server::signin(_In_ cert_context cert) { return m_server_impl->signin(std::move(cert), false); } pplx::task<xbox_live_result<token_and_signature_result>> xbox_live_server::get_token_and_signature( _In_ const string_t& httpMethod, _In_ const string_t& url, _In_ const string_t& headers ) { return m_server_impl->get_token_and_signature(httpMethod, url, headers); } pplx::task<xbox_live_result<token_and_signature_result>> xbox_live_server::get_token_and_signature( _In_ const string_t& httpMethod, _In_ const string_t& url, _In_ const string_t& headers, _In_ const string_t& requestBodyString ) { return m_server_impl->get_token_and_signature(httpMethod, url, headers, requestBodyString); } pplx::task<xbox_live_result<token_and_signature_result>> xbox_live_server::get_token_and_signature_array( _In_ const string_t& httpMethod, _In_ const string_t& url, _In_ const string_t& headers, _In_ const std::vector<unsigned char>& requestBodyArray ) { return m_server_impl->get_token_and_signature_array(httpMethod, url, headers, requestBodyArray); } bool xbox_live_server::is_signed_in() const { return m_server_impl->is_signed_in(); } NAMESPACE_MICROSOFT_XBOX_SERVICES_SYSTEM_CPP_END
28.449275
100
0.731024
blgrossMS
f495b0417ffb6b2773358e29281900d81e1a8a6d
2,938
cpp
C++
d19/a.cpp
Immortale-dev/adventofcode2022
019c0a08ff23e9fcb79c75a08b1cebd65333ca24
[ "MIT" ]
null
null
null
d19/a.cpp
Immortale-dev/adventofcode2022
019c0a08ff23e9fcb79c75a08b1cebd65333ca24
[ "MIT" ]
null
null
null
d19/a.cpp
Immortale-dev/adventofcode2022
019c0a08ff23e9fcb79c75a08b1cebd65333ca24
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #include "../helpers/string_helpers.cpp" #include "./scanner.cpp" typedef long long int ll; vector<Scanner> input; vector<bool> done; vector<Beacon> positions; void prepare() { string s; Scanner scan; while(getline(cin, s)){ if(s == ""){ input.push_back(scan); } else if(s[1] == '-') { scan = Scanner(); } else { auto arr = split_line(s, ","); scan.add_beacon({stoi(arr[0]), stoi(arr[1]), stoi(arr[2])}); } } input.push_back(scan); done = vector<bool>(input.size(), false); positions = vector<Beacon>(input.size(), {0,0,0}); } ll get_beacon_id(Beacon b){ return ((ll)(b.x * 100000000LL)) + ((ll)(b.y * 10000LL)) + ((ll)(b.z)); } bool try_resolve(int ia, int ib) { auto& scanA = input[ia]; auto& scanB = input[ib]; set<ll> ids; for(auto& it : scanA.get_beacons()){ ids.insert(get_beacon_id(it)); } for(int xi=0;xi<4;xi++) { for(int yi=0;yi<4;yi++){ for(int zi=0;zi<4;zi++){ // Try to match scans for(auto& itA : scanA.get_beacons()){ for(auto& itB : scanB.get_beacons()){ int mx = itB.x-itA.x; int my = itB.y-itA.y; int mz = itB.z-itA.z; int matchCount = 0; for(auto& itC : scanB.get_beacons()){ Beacon b{itC.x-mx, itC.y-my, itC.z-mz}; if(ids.count(get_beacon_id(b))){ matchCount++; } } if(matchCount >= 12){ // Found! done[ib] = true; positions[ib] = {positions[ia].x+mx, positions[ia].y+my, positions[ia].z+mz}; return true; } } } scanB.rotateZ(1); } scanB.rotateY(1); } scanB.rotateX(1); } return false; } void print_progress(double coof) { cout << "\033[s"; // save pos cout << "\033[K"; // erase line cout << "["; for(int i=0;i<=30;i++){ if((double)i/30 < coof) cout << "*"; else cout <<" "; } cout << "]"; cout << flush; cout << "\033[u"; // restore pos } ll first() { done[0] = true; queue<int> q; q.push(0); int cnt = 0; while(!q.empty()) { int ind = q.front(); q.pop(); print_progress((double)(++cnt)/input.size()); for(int j=0;j<input.size();j++){ if(!done[j]) { if(try_resolve(ind, j)) { q.push(j); } } } } cout << "\033[K"; // erase line for(auto it : done){ assert(it); } int sz = 0; for(auto& scan : input){ sz += scan.get_beacons().size(); } set<ll> ids; for(int i=0;i<input.size();i++){ auto& scan = input[i]; for(auto& it : scan.get_beacons()){ ids.insert(get_beacon_id( {it.x-positions[i].x, it.y-positions[i].y, it.z-positions[i].z} )); } } return ids.size(); } ll second() { int mx = 0; for(auto& ita : positions) { for(auto& itb : positions) { mx = max(mx, abs(ita.x-itb.x) + abs(ita.y-itb.y) + abs(ita.z-itb.z)); } } return mx; } int main() { prepare(); cout << "First: " << first() << endl; cout << "Second: " << second() << endl; return 0; }
18.594937
96
0.544929
Immortale-dev
f49b45244cf94f256ab7e87288ec6bb5749f3e3d
4,462
inl
C++
src/math/q3Mat3.inl
TraistaRafael/qu3e
abdb7a964ad6278dab21ed5bec5937f231c0f20b
[ "Zlib" ]
791
2015-01-04T02:26:39.000Z
2022-03-30T12:31:36.000Z
src/math/q3Mat3.inl
TraistaRafael/qu3e
abdb7a964ad6278dab21ed5bec5937f231c0f20b
[ "Zlib" ]
48
2015-02-17T19:29:51.000Z
2021-12-21T01:08:28.000Z
src/math/q3Mat3.inl
TraistaRafael/qu3e
abdb7a964ad6278dab21ed5bec5937f231c0f20b
[ "Zlib" ]
108
2015-02-16T08:20:04.000Z
2022-03-01T09:39:47.000Z
//-------------------------------------------------------------------------------------------------- // q3Mat3.inl // // Copyright (c) 2014 Randy Gaul http://www.randygaul.net // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. //-------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------- // q3Mat3 //-------------------------------------------------------------------------------------------------- inline void q3Identity( q3Mat3& m ) { m.Set( r32( 1.0 ), r32( 0.0 ), r32( 0.0 ), r32( 0.0 ), r32( 1.0 ), r32( 0.0 ), r32( 0.0 ), r32( 0.0 ), r32( 1.0 ) ); } //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3Rotate( const q3Vec3& x, const q3Vec3& y, const q3Vec3& z ) { return q3Mat3( x, y, z ); } //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3Transpose( const q3Mat3& m ) { return q3Mat3( m.ex.x, m.ey.x, m.ez.x, m.ex.y, m.ey.y, m.ez.y, m.ex.z, m.ey.z, m.ez.z ); } //-------------------------------------------------------------------------------------------------- inline void q3Zero( q3Mat3& m ) { memset( &m, 0, sizeof( r32 ) * 9 ); } //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3Diagonal( r32 a ) { return q3Mat3( r32( a ), r32( 0.0 ), r32( 0.0 ), r32( 0.0 ), r32( a ), r32( 0.0 ), r32( 0.0 ), r32( 0.0 ), r32( a ) ); } //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3Diagonal( r32 a, r32 b, r32 c ) { return q3Mat3( r32( a ), r32( 0.0 ), r32( 0.0 ), r32( 0.0 ), r32( b ), r32( 0.0 ), r32( 0.0 ), r32( 0.0 ), r32( c ) ); } //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3OuterProduct( const q3Vec3& u, const q3Vec3& v ) { q3Vec3 a = v * u.x; q3Vec3 b = v * u.y; q3Vec3 c = v * u.z; return q3Mat3( a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z ); } //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3Covariance( q3Vec3 *points, u32 numPoints ) { r32 invNumPoints = r32( 1.0 ) / r32( numPoints ); q3Vec3 c = q3Vec3( r32( 0.0 ), r32( 0.0 ), r32( 0.0 ) ); for ( u32 i = 0; i < numPoints; ++i ) c += points[ i ]; c /= r32( numPoints ); r32 m00, m11, m22, m01, m02, m12; m00 = m11 = m22 = m01 = m02 = m12 = r32( 0.0 ); for ( u32 i = 0; i < numPoints; ++i ) { q3Vec3 p = points[ i ] - c; m00 += p.x * p.x; m11 += p.y * p.y; m22 += p.z * p.z; m01 += p.x * p.y; m02 += p.x * p.z; m12 += p.y * p.z; } r32 m01inv = m01 * invNumPoints; r32 m02inv = m02 * invNumPoints; r32 m12inv = m12 * invNumPoints; return q3Mat3( m00 * invNumPoints, m01inv, m02inv, m01inv, m11 * invNumPoints, m12inv, m02inv, m12inv, m22 * invNumPoints ); }; //-------------------------------------------------------------------------------------------------- inline const q3Mat3 q3Inverse( const q3Mat3& m ) { q3Vec3 tmp0, tmp1, tmp2; r32 detinv; tmp0 = q3Cross( m.ey, m.ez ); tmp1 = q3Cross( m.ez, m.ex ); tmp2 = q3Cross( m.ex, m.ey ); detinv = r32( 1.0 ) / q3Dot( m.ez, tmp2 ); return q3Mat3( tmp0.x * detinv, tmp1.x * detinv, tmp2.x * detinv, tmp0.y * detinv, tmp1.y * detinv, tmp2.y * detinv, tmp0.z * detinv, tmp1.z * detinv, tmp2.z * detinv ); }
30.772414
100
0.44173
TraistaRafael
f49b50d843b661fb801dcd5fcbc1cc05e9c875b0
621
cpp
C++
Kaminec/kits/JsonKit/AssetIndex.cpp
kaniol-lck/Kaminec
bdbb6645035d6124a3772742362e683938b389fb
[ "BSD-2-Clause" ]
23
2017-06-23T11:58:27.000Z
2022-03-05T06:58:49.000Z
Kaminec/kits/JsonKit/AssetIndex.cpp
kaniol-lck/Kaminec
bdbb6645035d6124a3772742362e683938b389fb
[ "BSD-2-Clause" ]
4
2017-12-08T11:41:19.000Z
2021-04-03T17:50:39.000Z
Kaminec/kits/JsonKit/AssetIndex.cpp
kaniol-lck/Kaminec
bdbb6645035d6124a3772742362e683938b389fb
[ "BSD-2-Clause" ]
5
2019-02-19T13:03:42.000Z
2021-11-04T13:58:04.000Z
#include "AssetIndex.h" #include "assistance/utility.h" #include <QUrl> AssetIndex::AssetIndex(const QVariant &assetIndexVariant) : assetIndexVariant_(assetIndexVariant) {} QString AssetIndex::id() const { return value(assetIndexVariant_, "id").toString(); } int AssetIndex::size() const { return value(assetIndexVariant_, "size").toInt(); } QString AssetIndex::sha1() const { return value(assetIndexVariant_, "sha1").toString(); } QUrl AssetIndex::url() const { return value(assetIndexVariant_, "url").toUrl(); } int AssetIndex::totalSize() const { return value(assetIndexVariant_, "totalSize").toInt(); }
17.742857
59
0.73752
kaniol-lck
f49f96b04b4b364bcf289554f5f51b7b81a0b7c0
5,486
cpp
C++
Project/zoolib/GameEngine/Util.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
13
2015-01-28T21:05:09.000Z
2021-11-03T22:21:11.000Z
Project/zoolib/GameEngine/Util.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
null
null
null
Project/zoolib/GameEngine/Util.cpp
ElectricMagic/zoolib_cxx
cb3ccfde931b3989cd420fa093153204a7899805
[ "MIT" ]
4
2018-11-16T08:33:33.000Z
2021-12-11T19:40:46.000Z
// Copyright (c) 2019 Andrew Green. MIT License. http://www.zoolib.org #include "zoolib/GameEngine/Util.h" #include "zoolib/Callable_Function.h" #include "zoolib/Cartesian_Matrix.h" #include "zoolib/Chan_XX_Buffered.h" #include "zoolib/ChanRU_UTF_Std.h" #include "zoolib/Log.h" #include "zoolib/NameUniquifier.h" // For ThreadVal_NameUniquifier #include "zoolib/Util_Chan.h" #include "zoolib/Util_string.h" #include "zoolib/Util_ZZ_JSON.h" #include "zoolib/Util_ZZ_JSONB.h" //#include "zoolib/ZMACRO_auto.h" #include "zoolib/Apple/CGData_Channer.h" #include "zoolib/Apple/Pixmap_CGImage.h" #include "zoolib/GameEngine/Util_TextData.h" #include "zoolib/Pixels/Blit.h" #include "zoolib/Pixels/Formats.h" #include "zoolib/Pixels/PixmapCoder_PNG.h" namespace ZooLib { namespace GameEngine { using namespace Util_string; using Pixels::Ord; // ================================================================================================= #pragma mark - ZQ<GPoint> sQGPoint(const ZQ<Val>& iValQ) { if (iValQ) return sQGPoint(*iValQ); return null; } ZQ<GPoint> sQGPoint(const Val& iVal) { if (ZQ<CVec3> theCVecQ = sQCVec3(1, iVal)) return sCartesian(*theCVecQ); return null; } ZQ<GPoint> sQGPoint(const ZQ<Val_ZZ>& iValQ) { if (iValQ) return sQGPoint(*iValQ); return null; } ZQ<GPoint> sQGPoint(const Val_ZZ& iVal) { if (ZQ<CVec3> theCVecQ = sQCVec3(1, iVal)) return sCartesian(*theCVecQ); return null; } // ================================================================================================= #pragma mark - template <class Rect_p, class Seq_p> ZQ<Rect_p> spQGRect_T(const Seq_p& iSeq) { if (iSeq.Count() == 4) { if (false) {} else if (NotQ<Rat> l = sQRat(iSeq[0])) {} else if (NotQ<Rat> t = sQRat(iSeq[1])) {} else if (NotQ<Rat> r = sQRat(iSeq[2])) {} else if (NotQ<Rat> b = sQRat(iSeq[3])) {} else { return sRect<Rect_p>(*l, *t, *r, *b); } } if (ZMACRO_auto_(theFirstQ, sQCVec3(0, iSeq[0]))) { if (ZMACRO_auto_(theSecondQ, sQCVec3(0, iSeq[1]))) return sRect(*theFirstQ, *theFirstQ + *theSecondQ); else return sRect<Rect_p>(*theFirstQ); } return null; } ZQ<GRect> sQGRect(const ZQ<Val>& iValQ) { if (iValQ) return sQGRect(*iValQ); return null; } ZQ<GRect> sQGRect(const ZQ<Val_ZZ>& iValQ) { if (iValQ) return sQGRect(*iValQ); return null; } ZQ<GRect> sQGRect(const Val& iVal) { if (ZMACRO_auto_(theSeqQ, iVal.QGet<Seq>())) return spQGRect_T<GRect>(*theSeqQ); else if (ZMACRO_auto_(theSeqQ, iVal.QGet<Seq_ZZ>())) return spQGRect_T<GRect>(*theSeqQ); return null; } ZQ<GRect> sQGRect(const Val_ZZ& iVal) { if (ZMACRO_auto_(theSeqQ, iVal.QGet<Seq>())) return spQGRect_T<GRect>(*theSeqQ); else if (ZMACRO_auto_(theSeqQ, iVal.QGet<Seq_ZZ>())) return spQGRect_T<GRect>(*theSeqQ); return null; } // ================================================================================================= #pragma mark - static ZP<ChannerR_Bin> spChanner_Buffered(const ZP<ChannerR_Bin>& iChanner) { return sChannerR_Buffered(iChanner, 4096); } ZP<ChannerW_Bin> sCreateW_Clear(const FileSpec& iFS) { if (ZP<ChannerWPos_Bin> theChannerWPos = iFS.CreateWPos(true, true)) { sClear(*theChannerWPos); return theChannerWPos; } return null; } ZP<ChannerR_Bin> sOpenR_Buffered(const FileSpec& iFS) { if (ZP<ChannerR_Bin> theChannerR = iFS.OpenR()) return spChanner_Buffered(theChannerR); return null; } void sWriteBin(const ChanW_Bin& ww, const Val_ZZ& iVal) { Util_ZZ_JSONB::sWrite(ww, iVal); } Val_ZZ sReadBin(const ChanR_Bin& iChanR) { ThreadVal_NameUniquifier theNU; if (ZQ<Val_ZZ> theQ = Util_ZZ_JSONB::sQRead(iChanR)) return *theQ; return Val_ZZ(); } void sDump(const ChanW_UTF& ww, const Val& iVal) { sDump(ww, iVal.As<Val_ZZ>()); } void sDump(const Val& iVal) { sDump(iVal.As<Val_ZZ>()); } void sDump(const ChanW_UTF& ww, const Val_ZZ& iVal) { ww << "\n"; Util_ZZ_JSON::sWrite(ww, iVal, true); } void sDump(const Val_ZZ& iVal) { if (ZLOGF(w, eDebug-1)) sDump(w, iVal); } // ================================================================================================= #pragma mark - uint64 sNextID() { static uint64 spID; return ++spID; } // ================================================================================================= #if ZMACRO_IOS #else static bool spPremultiply(Ord iH, Ord iV, RGBA& ioColor, void* iRefcon) { sRed(ioColor) *= sAlpha(ioColor); sGreen(ioColor) *= sAlpha(ioColor); sBlue(ioColor) *= sAlpha(ioColor); return true; } #endif Pixmap sPixmap_PNG(const ZP<ChannerR_Bin>& iChannerR) { #if ZMACRO_IOS if (ZP<CGDataProviderRef> theProvider_File = CGData_Channer::sProvider(iChannerR)) { if (ZP<CGImageRef> theImageRef = sAdopt& ::CGImageCreateWithPNGDataProvider( theProvider_File, nullptr, true, kCGRenderingIntentDefault)) { //CGImageAlphaInfo theInfo = ::CGImageGetAlphaInfo(theImageRef); return sPixmap(theImageRef); } } #else if (Pixmap thePixmap = Pixels::sReadPixmap_PNG(*iChannerR)) { if (thePixmap.GetRasterDesc().fPixvalDesc.fDepth != 32) { const PointPOD theSize = thePixmap.Size(); Pixmap target = sPixmap(theSize, Pixels::EFormatStandard::RGBA_32, sRGBA(0,0,0,0)); sBlit(thePixmap, sRect<RectPOD>(theSize), target, sPointPOD(0,0)); thePixmap = target; } sMunge(thePixmap, spPremultiply, nullptr); return thePixmap; } #endif return null; } } // namespace GameEngine } // namespace ZooLib
23.545064
100
0.635436
ElectricMagic
f4a17da42ad498394629dca2918d914e5a087839
921
cpp
C++
test/types.cpp
jfalcou/tts
5b8326aa8706feb2a03d56d2b0a5ef0e1aa47b40
[ "MIT" ]
12
2020-11-12T17:15:44.000Z
2022-03-15T12:59:17.000Z
test/types.cpp
jfalcou/tts
5b8326aa8706feb2a03d56d2b0a5ef0e1aa47b40
[ "MIT" ]
14
2019-09-28T14:04:18.000Z
2021-12-11T20:08:31.000Z
test/types.cpp
jfalcou/tts
5b8326aa8706feb2a03d56d2b0a5ef0e1aa47b40
[ "MIT" ]
null
null
null
//================================================================================================== /** TTS - Tiny Test System Copyright : TTS Contributors & Maintainers SPDX-License-Identifier: MIT **/ //================================================================================================== #define TTS_MAIN #include <tts/tts.hpp> #include <array> TTS_CASE( "Check that types can be tested for equality" ) { TTS_TYPE_IS( std::add_pointer<float const>::type, float const* ); }; TTS_CASE( "Check that expression types can be tested for equality" ) { [[maybe_unused]] double d; TTS_EXPR_IS( &d + 5 , double* ); TTS_EXPR_IS( std::move(d) , double&& ); TTS_EXPR_IS( std::swap(d,d), void ); }; TTS_CASE_TPL( "Check interaction with templates" , int,float,char,void* ) <typename Type>(::tts::type<Type>) { TTS_TYPE_IS( std::add_const_t<Type>, Type const); };
27.909091
100
0.510315
jfalcou
f4a2bd62ae20afd210fd1a4f437a062a23cb1537
937
hpp
C++
src/Core/Game.hpp
iceonepiece/strong-man
c880b5ecadef87fe4bbcd1195526de8f020929cf
[ "MIT" ]
null
null
null
src/Core/Game.hpp
iceonepiece/strong-man
c880b5ecadef87fe4bbcd1195526de8f020929cf
[ "MIT" ]
null
null
null
src/Core/Game.hpp
iceonepiece/strong-man
c880b5ecadef87fe4bbcd1195526de8f020929cf
[ "MIT" ]
null
null
null
#pragma once #include <unordered_map> #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include "Input.hpp" class Game { public: Game(); virtual ~Game(); bool Initialize(); void Run(); void Shutdown(); void SetCurrentScene(std::string sceneName); unsigned int GetScreenWidth() { return m_ScreenWidth; } unsigned int GetScreenHeight() { return m_ScreenHeight; } class Font* GetFont(const std::string& name); class Audio* GetAudio() { return m_Audio; } protected: virtual void LoadData() = 0; virtual void UnloadData() = 0; bool m_Running; Uint32 m_TicksCount; unsigned int m_ScreenWidth; unsigned int m_ScreenHeight; class Renderer* m_Renderer; class Audio* m_Audio; Input m_Input; class Scene* m_CurrentScene; std::unordered_map<std::string, class Scene*> m_Scenes; std::unordered_map<std::string, class Font*> m_Fonts; private: void ProcessInput(); void Update(); void Render(); };
18.74
58
0.726788
iceonepiece
f4a47ce6fad08680e565e8ea9a255b563417cd40
535
hpp
C++
include/boost/url/url.hpp
syoliver/url
7a992f6aa758807bbcd2e92e413453da98ee0c3d
[ "BSL-1.0" ]
null
null
null
include/boost/url/url.hpp
syoliver/url
7a992f6aa758807bbcd2e92e413453da98ee0c3d
[ "BSL-1.0" ]
null
null
null
include/boost/url/url.hpp
syoliver/url
7a992f6aa758807bbcd2e92e413453da98ee0c3d
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/vinniefalco/url // #ifndef BOOST_URL_URL_HPP #define BOOST_URL_URL_HPP #include <boost/url/config.hpp> #include <boost/url/basic_url.hpp> #include <memory> namespace boost { namespace urls { using url = basic_url<std::allocator<char>>; } // urls } // boost #endif
20.576923
79
0.73271
syoliver
f4a52da293b8216b7235307e5da9abb35c5b810c
3,952
cpp
C++
Packet/PacketCondenser.cpp
RodrigoHolztrattner/Packet
ea514f326b7678414ef6521a6b4546e878f5c4ec
[ "MIT" ]
6
2018-03-15T09:11:07.000Z
2021-05-11T16:19:53.000Z
Packet/PacketCondenser.cpp
RodrigoHolztrattner/Packet
ea514f326b7678414ef6521a6b4546e878f5c4ec
[ "MIT" ]
16
2019-02-14T22:56:21.000Z
2019-07-08T20:21:01.000Z
Packet/PacketCondenser.cpp
RodrigoHolztrattner/Packet
ea514f326b7678414ef6521a6b4546e878f5c4ec
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Filename: FluxMyWrapper.cpp //////////////////////////////////////////////////////////////////////////////// #include "PacketCondenser.h" #include <filesystem> #include <fstream> /////////////// // NAMESPACE // /////////////// PacketUsingDevelopmentNamespace(Packet) PacketCondenser::PacketCondenser() { // Set the initial data // ... } PacketCondenser::~PacketCondenser() { } std::vector<CondensedFileInfo> PacketCondenser::CondenseFolder(std::string _rootPath, uint32_t _currentCondenseFileCount, std::vector<std::pair<Hash, std::string>>& _fileInfos) { // Out output vector std::vector<CondensedFileInfo> output; // Check if we have at last one file if (_fileInfos.size() == 0) { // There is nothing to be done return output; } // Get the root folder name auto rootFolderName = GetRootFolder(_rootPath); // Return a valid name for the condensed file auto GetCondensedFilename = [&]() { std::string temp = CondensedName; return rootFolderName.append(temp.append(std::to_string(_currentCondenseFileCount + output.size()).append(CondensedExtension))); }; // The current condensed file info CondensedFileInfo currentCondensedFileInfo = {}; currentCondensedFileInfo.filePath = GetCondensedFilename(); // The current condensed file size and the current output write file uint64_t currentCondensedFileSize = 0; std::ofstream writeFile(currentCondensedFileInfo.filePath, std::ios::out); if (!writeFile.is_open()) { // Error creating the file return std::vector<CondensedFileInfo>(); } // For each file inside the given folder for (auto&[hash, filePath] : _fileInfos) { // Get the path to the file auto path = std::filesystem::path(filePath); // Get the file size auto fileSize = std::filesystem::file_size(path); // The condensed internal file info that we will use for this file CondensedFileInfo::InternalFileInfo internalFileInfo = {}; internalFileInfo.hash = hash; internalFileInfo.size = uint64_t(fileSize); internalFileInfo.time = uint64_t(std::filesystem::last_write_time(filePath).time_since_epoch().count()); // Check if we need to generate another condensed file info if (currentCondensedFileSize + fileSize >= MaximumPackageSize) { // Insert it into the output vector output.push_back(currentCondensedFileInfo); // Create another condensed file info currentCondensedFileInfo = CondensedFileInfo(); currentCondensedFileInfo.filePath = GetCondensedFilename(); // Close the current file and write to a new one writeFile.close(); writeFile = std::ofstream(currentCondensedFileInfo.filePath, std::ios::out); if (!writeFile.is_open()) { // Error creating the file return std::vector<CondensedFileInfo>(); } // Zero the current condensed file size currentCondensedFileSize = 0; } // Set the file location internalFileInfo.location = currentCondensedFileSize; // Open the target file and write it into the current condensed file { // Open the file std::ifstream file(filePath, std::ios::binary); if (!file.is_open()) { // Error openning this file return std::vector<CondensedFileInfo>(); } // Get the file data and close the file std::vector<char> buffer((unsigned int)fileSize); file.read(buffer.data(), fileSize); file.close(); // Write the file data writeFile.write(buffer.data(), fileSize); // Increment the current condensed file size currentCondensedFileSize += fileSize; } // Set the file info currentCondensedFileInfo.fileInfos[currentCondensedFileInfo.totalNumberFiles] = internalFileInfo; // Increment the total number of files currentCondensedFileInfo.totalNumberFiles++; } // Close the current condensed file writeFile.close(); // Insert the current condensed file into the output vector output.push_back(currentCondensedFileInfo); return output; }
29.274074
176
0.698381
RodrigoHolztrattner
f4a5ccdefd09cbf1852aff88879c7a6ed81d461b
1,467
cpp
C++
done/124_max_path_sum.cpp
zjuMrzhang/leetcode
35ab78be5b9a2ef0fb35f99c146c2190b2bed148
[ "MIT" ]
null
null
null
done/124_max_path_sum.cpp
zjuMrzhang/leetcode
35ab78be5b9a2ef0fb35f99c146c2190b2bed148
[ "MIT" ]
null
null
null
done/124_max_path_sum.cpp
zjuMrzhang/leetcode
35ab78be5b9a2ef0fb35f99c146c2190b2bed148
[ "MIT" ]
1
2020-09-30T19:03:01.000Z
2020-09-30T19:03:01.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int tmpmax=0x80000000; int maxPathSumofRoot(TreeNode* root){ // if(root==NULL) return 0; int v=root->val; if(root->left==NULL && root->right==NULL) return v; int l=maxPathSumofRoot(root->left); int r=maxPathSumofRoot(root->right); // 最大值不包括自己,在最左右的下面 // 这里需要注意,必须要有才更新,否则空子树传 // 来的0会对结果产生影响 [-1,-2], if(root->left!=NULL){ tmpmax=max(tmpmax,l); } if(root->right!=NULL){ tmpmax=max(tmpmax,r); } // 最大值 包括自己,但是不向上传递 tmpmax=max(tmpmax,max(v,v+l+r)); // l+r+v 这里如果lr 都是0x80000000 会反向越界错误 // 只针对 空子树返回负最小值的情况,改为返回0消失 printf("%d ",tmpmax); // 最大值包括上面节点,上面处理 return max(v,max(v+l,v+r)); } int maxPathSum(TreeNode* root) { // 这题需要往上传递参数,后续遍历更合适 // 一个最长路径可能出现在的位置: // 已经记录的位置 // 左边子树里面l--记录在最大位置 // 右边子树里面r--记录在最大位置 // 包含自己:本次需要处理的 // max( v+l / v+r / v ) --todo -传递到上面 // v+l+r --记录在最大位置 // l / r --记录在最大位置 return max(tmpmax,maxPathSumofRoot(root)); } };
27.166667
77
0.479891
zjuMrzhang
f4b07deac6aa6af3f7ee54cbe5bdee6fcaa83860
247
hpp
C++
src/components/component_job_list.hpp
Nodmgatall/ytba
19de0ac40236e0c8cf5f1f7eb77efe764bc51b1f
[ "MIT" ]
null
null
null
src/components/component_job_list.hpp
Nodmgatall/ytba
19de0ac40236e0c8cf5f1f7eb77efe764bc51b1f
[ "MIT" ]
null
null
null
src/components/component_job_list.hpp
Nodmgatall/ytba
19de0ac40236e0c8cf5f1f7eb77efe764bc51b1f
[ "MIT" ]
null
null
null
#ifndef COMPONENT_JOB_LIST_HPP #define COMPONENT_JOB_LIST_HPP #include "../sub_types/terrain_types.hpp" #include "entityx/entityx.h" struct job_list : entityx::Component<job_list> { job_list() { std::vector<Job*> job_list; } #endif
19
48
0.732794
Nodmgatall
f4b38a8da4e8b2add36e4d77eda66b1c226df21b
1,764
hpp
C++
libfma/include/fma/types/Class.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
14
2018-01-25T10:31:05.000Z
2022-02-19T13:08:11.000Z
libfma/include/fma/types/Class.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
1
2020-12-24T10:10:28.000Z
2020-12-24T10:10:28.000Z
libfma/include/fma/types/Class.hpp
BenjaminSchulte/fma
df2aa5b0644c75dd34a92defeff9beaa4a32ffea
[ "MIT" ]
null
null
null
#ifndef __FMA_TYPES_CLASS_H__ #define __FMA_TYPES_CLASS_H__ #include <vector> #include "Base.hpp" namespace FMA { namespace interpret { class BaseContext; typedef std::shared_ptr<BaseContext> ContextPtr; struct Parameter; struct GroupedParameterList; } namespace types { class ClassPrototype; class Class : public Base { public: Class(const std::string &name, const std::string &fullName); virtual bool isClass() const { return true; } virtual ClassPtr asClass() { return std::dynamic_pointer_cast<Class>(getPointer()); } ObjectPtr createInstance(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameters); void extends(const ClassPtr &other); virtual std::string asString() const; virtual void dump(const std::string &); const std::string &getName() const { return name; } const std::string &getFullName() const { return fullName; } const ClassPrototypePtr &getPrototype(); virtual bool hasMember(const std::string &name) const; virtual TypePtr getMember(const std::string &name) const; bool hasOwnMember(const std::string &name) const; TypePtr getOwnMember(const std::string &name) const; virtual bool hasPrototypeMember(const std::string &name); virtual TypePtr getPrototypeMember(const std::string &name); bool isInstanceOf(const ClassPtr &other) const; bool isInstanceOf(const std::string &other) const; virtual interpret::ResultPtr callWithoutDecoratorTest(const interpret::ContextPtr &context, const interpret::GroupedParameterList &parameter); inline const std::vector<ClassPtr> &getParents() const { return parents; }; protected: std::string name; std::string fullName; mutable ClassPrototypePtr prototype; std::vector<ClassPtr> parents; }; } } #endif
28.918033
145
0.757937
BenjaminSchulte
f4b5488371e33a3bab3d7f520adc51b3dda49001
1,296
cpp
C++
src/sport/enum/MarketSort.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
5
2019-06-30T06:29:46.000Z
2021-12-17T12:41:23.000Z
src/sport/enum/MarketSort.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
2
2018-01-09T17:14:45.000Z
2020-03-23T00:16:50.000Z
src/sport/enum/MarketSort.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
7
2015-09-13T18:40:58.000Z
2020-01-24T10:57:56.000Z
/** * Copyright 2017 Colin Doig. Distributed under the MIT license. */ #include <stdexcept> #include "greentop/sport/enum/MarketSort.h" #include "greentop/Enum.h" namespace greentop { namespace sport { const std::string MarketSort::MINIMUM_TRADED = "MINIMUM_TRADED"; const std::string MarketSort::MAXIMUM_TRADED = "MAXIMUM_TRADED"; const std::string MarketSort::MINIMUM_AVAILABLE = "MINIMUM_AVAILABLE"; const std::string MarketSort::MAXIMUM_AVAILABLE = "MAXIMUM_AVAILABLE"; const std::string MarketSort::FIRST_TO_START = "FIRST_TO_START"; const std::string MarketSort::LAST_TO_START = "LAST_TO_START"; MarketSort::MarketSort() { valid = false; } MarketSort::MarketSort(const std::string& v) { if (v != MINIMUM_TRADED && v != MAXIMUM_TRADED && v != MINIMUM_AVAILABLE && v != MAXIMUM_AVAILABLE && v != FIRST_TO_START && v != LAST_TO_START) { throw std::invalid_argument("Invalid MarketSort: " + v); } value = v; valid = true; } bool MarketSort::operator<(const MarketSort& other) const { return value < other.value; } bool MarketSort::operator==(const MarketSort& other) const { return value == other.value; } bool MarketSort::operator!=(const MarketSort& other) const { return value != other.value; } } }
25.92
70
0.692901
Sherlock92
f4b57a65a8fd9bc91423240c1fec3adfcddf73a3
1,669
hpp
C++
include/CASM/codec/pcm.hpp
Liastre/CASM
4f978664ac4812e8cfcd76025ac2429a46543582
[ "MIT" ]
1
2021-08-06T07:55:21.000Z
2021-08-06T07:55:21.000Z
include/CASM/codec/pcm.hpp
Liastre/CASM
4f978664ac4812e8cfcd76025ac2429a46543582
[ "MIT" ]
1
2021-08-05T09:33:13.000Z
2021-08-05T09:33:13.000Z
include/CASM/codec/pcm.hpp
Liastre/CASM
4f978664ac4812e8cfcd76025ac2429a46543582
[ "MIT" ]
null
null
null
/** * PCM codec implementation * @author Liastre * @copyright MIT */ #pragma once #include <CASM/codec/codec.hpp> #include <array> namespace CASM { namespace Codec { using WavHeader = struct { std::array<char, 4> chunkID {'R','I','F','F'}; // RIFF chunk std::uint32_t chunkSize {0}; // chunk size in bytes std::array<char, 4> chunkFormat {'W','A','V','E'}; // file type std::array<char, 4> fmtID {'f','m','t',' '}; // FMT sub-chunk std::uint32_t fmtSize {0}; // size of fmt chunk 16 + extra format bytes std::uint16_t fmtAudioFormat {0}; // format (compression code) std::uint16_t fmtNumChannels {0}; std::uint32_t fmtSampleRate {0}; std::uint32_t fmtByteRate {0}; std::uint16_t fmtBlockAlign {0}; std::uint16_t fmtBitsPerSample {0}; std::uint16_t fmtExtraParamSize {0}; char *fmtExtraParams {nullptr}; std::array<char, 4> dataID {'d','a','t','a'}; // DATA sub-chunk std::uint32_t dataSize {0}; }; class Pcm : public CodecInterface { public: WaveProperties readHeader(DataStream& fileHandler) final; bool writeHeader(DataStream& fileHandler, WaveProperties const& waveProperties) final; BufferStatus readData(DataStream& fileHandler, Buffer& buffer) final; bool writeData(DataStream& dataStream, Buffer const& buffer) final; bool finalize(DataStream& fileHandler) final; private: WavHeader _wavHeader; std::size_t _posDataChunk = 0; std::size_t _posFileLength = 0; bool _isFinalized = false; }; } // namespace Codec } // namespace CASM
31.490566
100
0.624326
Liastre
f4b80a7d286e7523c85f8f2980657ae4ddb3cfcd
914
cpp
C++
Src/IO/CPipe_get.cpp
Gjoll/OpSys
ebba2d8856d21a1f6cefe59c781ce7b9ff1430cf
[ "Apache-2.0" ]
null
null
null
Src/IO/CPipe_get.cpp
Gjoll/OpSys
ebba2d8856d21a1f6cefe59c781ce7b9ff1430cf
[ "Apache-2.0" ]
null
null
null
Src/IO/CPipe_get.cpp
Gjoll/OpSys
ebba2d8856d21a1f6cefe59c781ce7b9ff1430cf
[ "Apache-2.0" ]
null
null
null
/* Copyright 1992 Kurt W. Allen. This is an unpublished work by Kurt W. Allen. All rights are reserved, and no part of this work may be distributed or released with out the express permission of Kurt W. Allen, 3540 43'rd Ave S., Mpls, Mn 55406. */ /* $Revision: 1.1 $ $Modtime: 01 May 1993 09:32:52 $ $Workfile: cpipe2.cpp $ */ #include <OsConfig.h> #include <OsAssert.h> #include <Base.h> #include <ptrBlock.h> #include <Task.h> #include <Block.h> #include <Semaphore.h> #include <Pipe.h> #include <IoBuf.h> #include <CPipe.h> /* CPipe::get Description: Class: CPipe. get one character from the CPipe. This routine will be called by the formatted I/O methods of IOBuf. Parameters: c is a pointer to a character to store the character from the pipe into. */ Bool CPipe::get(char* c) { return (Pipe::get(c) == OS_DONE) ? OSTrue : OSFalse; }
21.761905
65
0.657549
Gjoll
f4c6edcc6f260b9832e56a66eb2d1067e7445604
1,271
cpp
C++
libnuklei/io/PLYObservation.cpp
chungying/nuklei
23db2a55a1b3260cf913d0ac10b3b27c000ae1a6
[ "BSD-3-Clause" ]
null
null
null
libnuklei/io/PLYObservation.cpp
chungying/nuklei
23db2a55a1b3260cf913d0ac10b3b27c000ae1a6
[ "BSD-3-Clause" ]
null
null
null
libnuklei/io/PLYObservation.cpp
chungying/nuklei
23db2a55a1b3260cf913d0ac10b3b27c000ae1a6
[ "BSD-3-Clause" ]
null
null
null
// (C) Copyright Renaud Detry 2007-2015. // Distributed under the GNU General Public License and under the // BSD 3-Clause License (See accompanying file LICENSE.txt). /** @file */ #include <nuklei/PLYObservation.h> namespace nuklei { const double PLYObservation::TOL = 1e-5; PLYObservation::PLYObservation() { NUKLEI_TRACE_BEGIN(); ColorDescriptor d; k_.setDescriptor(d); NUKLEI_TRACE_END(); } PLYObservation::PLYObservation(const kernel::r3& k) : k_(k) {} void PLYObservation::setLoc(Vector3 loc) { NUKLEI_TRACE_BEGIN(); k_.loc_ = loc; NUKLEI_TRACE_END(); } Vector3 PLYObservation::getLoc() const { return k_.loc_; } void PLYObservation::setWeight(weight_t weight) { NUKLEI_TRACE_BEGIN(); k_.setWeight(weight); NUKLEI_TRACE_END(); } weight_t PLYObservation::getWeight() const { return k_.getWeight(); } const Color& PLYObservation::getColor() const { NUKLEI_TRACE_BEGIN(); return dynamic_cast<const ColorDescriptor&>(k_.getDescriptor()).getColor(); NUKLEI_TRACE_END(); } void PLYObservation::setColor(const Color& color) { NUKLEI_TRACE_BEGIN(); dynamic_cast<ColorDescriptor&>(k_.getDescriptor()).setColor(color); NUKLEI_TRACE_END(); } }
22.696429
79
0.686861
chungying
f4ca2bab53a38121df662d29c6d539d0399b8a3a
2,378
cpp
C++
test/example.cpp
peterbygrave/coulombgalore
ac7d13641212c53c126f9d48f8aa6e8f249f514e
[ "MIT" ]
7
2019-08-12T15:00:40.000Z
2022-03-23T06:46:40.000Z
test/example.cpp
peterbygrave/coulombgalore
ac7d13641212c53c126f9d48f8aa6e8f249f514e
[ "MIT" ]
7
2019-10-19T12:24:29.000Z
2021-05-12T05:58:03.000Z
test/example.cpp
peterbygrave/coulombgalore
ac7d13641212c53c126f9d48f8aa6e8f249f514e
[ "MIT" ]
3
2019-07-10T12:30:20.000Z
2020-11-27T11:10:07.000Z
#include <iostream> #include <nlohmann/json.hpp> #include "coulombgalore.h" using namespace CoulombGalore; typedef Eigen::Vector3d Point; //!< typedef for 3d vector int main() { double pi = 3.141592653589793, // Pi e0 = 8.85419e-12, // Permittivity of vacuum [C^2/(J*m)] e = 1.602177e-19, // Absolute electronic unit charge [C] T = 298.15, // Temperature [K] kB = 1.380658e-23; // Boltzmann's constant [J/K] double z1 = 1, z2 = 2; // two monopoles double cutoff = 18e-10; // cutoff distance, here in meters [m] vec3 r = {7.0e-10, 0, 0}; // a distance vector, use same using as cutoff, i.e. [m] // energies are returned in electrostatic units and we must multiply // with the Coulombic constant to get more familiar units: double bjerrum_length = e * e / (4 * pi * e0 * kB * T); // [m] // this is just the plain old Coulomb potential Plain pot_plain; double u12 = pot_plain.ion_ion_energy(z1, z2, r.norm()); std::cout << "plain ion-ion energy: " << bjerrum_length * u12 << " kT" << std::endl; // this is just the plain old Coulomb potential double debye_length = 23.01e-10; Plain pot_plainY(debye_length); u12 = pot_plainY.ion_ion_energy(z1, z2, r.norm()); std::cout << "plain ion-ion energy: " << bjerrum_length * u12 << " kT" << std::endl; // this is a truncated potential qPotential pot_qpot(cutoff, 3); u12 = pot_qpot.ion_ion_energy(z1, z2, r.norm()); std::cout << "qPotential ion-ion energy: " << bjerrum_length * u12 << " kT" << std::endl; qPotential pot_qpot3(cutoff, 3); qPotential pot_qpot4(cutoff, 4); Fanourgakis pot_kis(cutoff); Ewald pot_ewald(cutoff, 0.1e10, infinity); for (double q = 0; q <= 1; q += 0.01) std::cout << q << " " << pot_qpot3.short_range_function(q) << " " << pot_qpot4.short_range_function(q) << " " << " " << pot_kis.short_range_function(q) << " " << " " << pot_ewald.short_range_function(q) << "\n"; #ifdef NLOHMANN_JSON_HPP // this is a truncated potential initiated using JSON Wolf pot_wolf(nlohmann::json({{"cutoff", cutoff}, {"alpha", 0.5}})); // if available, json can be used to (de)serialize nlohmann::json j; pot_qpot.to_json(j); std::cout << j << std::endl; #endif }
38.983607
117
0.605551
peterbygrave
f4ca32bfc5cb9f28143a90f8d084eb1178cacdfb
826
cpp
C++
CodeChef/LTIME67B/AGECAL.cpp
codemute/cp-sol
e6ea2533adf9f590f5e9d6a6b50031db9d3dca4a
[ "MIT" ]
1
2019-10-06T14:39:34.000Z
2019-10-06T14:39:34.000Z
CodeChef/LTIME67B/AGECAL.cpp
codemute/cp-sol
e6ea2533adf9f590f5e9d6a6b50031db9d3dca4a
[ "MIT" ]
1
2019-07-12T08:08:50.000Z
2019-10-04T07:56:33.000Z
CodeChef/LTIME67B/AGECAL.cpp
codemute/cp-sol
e6ea2533adf9f590f5e9d6a6b50031db9d3dca4a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int cei(int a, int b) { if(a % b == 0) return a / b; return (a / b) + 1; } int main() { int t; cin >> t; while(t--) { int n; cin >> n; int a[n], tot = 0; for(int i = 0; i < n; i++) { cin >> a[i]; tot += a[i]; } int yb, mb, db; cin >> yb >> mb >> db; int yc, mc, dc; cin >> yc >> mc >> dc; int u = (yc - yb) * tot; int v = 0; for(int i = min(mc, mb) + 1; i < max(mc, mb); i++) { v += a[i - 1]; } if(mc < mb) { v = - (v + a[mc - 1]); } else if(mc > mb) { v = v + a[mb - 1]; } int w = dc - db; int l = (((yc / 4) * 4) - (cei(yb, 4) * 4)) / 4; if(yc % 4 != 0) l++; // cout << u << " " << v << " " << w << endl; cout << u + v + w + l + 1 << endl; } return 0; }
20.65
56
0.360775
codemute
f4cc26f3ef7a3453c78b7e35f6bc3b1d34432453
928
hpp
C++
addons/bw/configs/CfgAmmo.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
null
null
null
addons/bw/configs/CfgAmmo.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
4
2018-12-21T06:57:25.000Z
2020-07-09T09:06:38.000Z
addons/bw/configs/CfgAmmo.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
null
null
null
/* Part of the TBMod ( https://github.com/TacticalBaconDevs/TBMod ) Developed by http://tacticalbacon.de */ class CfgAmmo { class BWA3_B_127x99_Ball; class BWA3_B_127x99_Ball_Raufoss : BWA3_B_127x99_Ball // 50.cal Long-Range Sniper BW { caliber = 2.5; // 5.2 explosive = 0.1; // 0 hit = 24; // 31.5 indirectHit = 30; // 0 indirectHitRange = 0.6; // 0 tracerEndTime = 8; // 3 tracerStartTime = 0.5; // 0.05 }; class BWA3_B_127x99_Ball_Raufoss_Tracer_Dim : BWA3_B_127x99_Ball_Raufoss // 50.cal HEIAP-T BW { caliber = 2.8; // 2.6 hit = 35; // 30 indirectHit = 30; // 12 indirectHitRange = 0.6; // 0.3 }; class B_338_Ball; class BWA3_B_86x70_Ball : B_338_Ball // G29 { ACE_ballisticCoefficients[] = {0.675}; // {0.322} BWMod hat falschen BC verwendet hit = 20; // 16 }; };
26.514286
97
0.577586
Braincrushy
f4d003ba3188b920728e3fc78baa0266093881f5
376
cpp
C++
assembler/main.cpp
terana/pdp-11
720ab9b3a15c832de012b5846cb363a5f0b8ce2c
[ "MIT" ]
null
null
null
assembler/main.cpp
terana/pdp-11
720ab9b3a15c832de012b5846cb363a5f0b8ce2c
[ "MIT" ]
null
null
null
assembler/main.cpp
terana/pdp-11
720ab9b3a15c832de012b5846cb363a5f0b8ce2c
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include "assembler.hpp" int main(int argc, char *argv[]) { std::string asm_file = argc > 1 ? argv[1] : "../programs/white_screen.s"; const char *bin_file = argc > 2 ? argv[2] : "white_screen"; std::ifstream asmStream(asm_file); Assembler assembler; assembler.generateBinary(asmStream, bin_file); return 0; }
23.5
77
0.664894
terana
f4dadf33f2b54fa45221dbd32ff8e6ae34f47d5a
614
cpp
C++
src/Npfs/Messages/Rread.cpp
joluxer/NpfsCpp
f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f
[ "Zlib" ]
null
null
null
src/Npfs/Messages/Rread.cpp
joluxer/NpfsCpp
f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f
[ "Zlib" ]
null
null
null
src/Npfs/Messages/Rread.cpp
joluxer/NpfsCpp
f19d422b9ab4fa67e35c1e0c29dfa2abc8b0d78f
[ "Zlib" ]
null
null
null
/* * Rread.cpp * * Created on: 18.07.2012 * Author: jlode */ #include "Rread.h" namespace Npfs { Rread::Rread(const Npfs::Tread& tref, MemoryManager* mm_) : Rmessage(tref), mm(mm_), count(tref.count), data((unsigned char*) mm->allocate(tref.count)) {} Rread::~Rread() { mm->release(data); } uint32_t Rread::msgLength() const { return 4 + count; /* count[4] data[count] */ } void Rread::serialize() { #ifndef NDEBUG logHeader("Rread"); log("count", count); log("data", NpStr("(not dumped)")); logNewLine(); #endif serializeHeader(); io.putUI32(count); io.put(data, count); } }
14.619048
94
0.627036
joluxer
f4ddbea6636b8499172b446ec266c77a29afebc5
1,177
cpp
C++
InterviewBit/Arrays/Set Matrix Zeros.cpp
sankalpmittal1911-BitSian/Competitive-Coding
eac5b4f465083e27496a0711a527d67ab657a35c
[ "MIT" ]
null
null
null
InterviewBit/Arrays/Set Matrix Zeros.cpp
sankalpmittal1911-BitSian/Competitive-Coding
eac5b4f465083e27496a0711a527d67ab657a35c
[ "MIT" ]
null
null
null
InterviewBit/Arrays/Set Matrix Zeros.cpp
sankalpmittal1911-BitSian/Competitive-Coding
eac5b4f465083e27496a0711a527d67ab657a35c
[ "MIT" ]
null
null
null
/*Asked in: Oracle Amazon Given an m x n matrix of 0s and 1s, if an element is 0, set its entire row and column to 0. Do it in place. Example Given array A as 1 0 1 1 1 1 1 1 1 On returning, the array A should be : 0 0 0 1 0 1 1 0 1 Note that this will be evaluated on the extra memory used. Try to minimize the space and time complexity.*/ void Solution::setZeroes(vector<vector<int> > &A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details int rows[A.size()]; int cols[A[0].size()]; memset(rows,0,sizeof rows); memset(cols,0,sizeof cols); for(int i=0;i<A.size();++i) { for(int j=0;j<A[i].size();++j) { if(A[i][j]==0) { rows[i]=1; cols[j]=1; } } } for(int i=0;i<A.size();++i) { for(int j=0;j<A[i].size();++j) { if(rows[i]==1 || cols[j]==1) A[i][j]=0; } } }
19.949153
107
0.544605
sankalpmittal1911-BitSian
f4dff7852c529967fd685d6dc5520ad3edce7e10
667
cpp
C++
competitive/c++/codeforces/round 690 div 3/maina.cpp
HackintoshwithUbuntu/BigRepo
70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874
[ "MIT" ]
null
null
null
competitive/c++/codeforces/round 690 div 3/maina.cpp
HackintoshwithUbuntu/BigRepo
70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874
[ "MIT" ]
null
null
null
competitive/c++/codeforces/round 690 div 3/maina.cpp
HackintoshwithUbuntu/BigRepo
70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, b; void solve() { int a[300]; int ans[300]; cin >> n; for(int i = 0; i < n; i++){ int z; cin >> z; a[i] = z; } int lp = 0; int rp = n - 1; for (int i = 0; i < n; i++) { if ((i & 1) == 0) { ans[i] = a[lp++]; } else { ans[i] = a[rp--]; } } for(int i = 0; i < n; i++){ cout << ans[i] << " "; } cout << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--) { solve(); } return 0; }
13.895833
37
0.346327
HackintoshwithUbuntu
f4e329e0eb966a4659fafb31f403f80081093825
278
cpp
C++
platform/include/platform/types/main.cpp
Garph/Carbon
4e412c5ff4a81e15cae2e86ff7476ca2ee3df080
[ "MIT" ]
null
null
null
platform/include/platform/types/main.cpp
Garph/Carbon
4e412c5ff4a81e15cae2e86ff7476ca2ee3df080
[ "MIT" ]
null
null
null
platform/include/platform/types/main.cpp
Garph/Carbon
4e412c5ff4a81e15cae2e86ff7476ca2ee3df080
[ "MIT" ]
null
null
null
#include "view.h" #include <iostream> void foo(emb::view<int> xs) { for (auto const& x : xs) { std::cout << x << ", "; } std::cout << std::endl; } int main(void) { int arr[5] = {0, 1, 2, 3, 4}; emb::view<int> xs(arr); foo(xs); return 0; }
13.9
33
0.478417
Garph
f4efb974f5df44fd84f4518c5d96e68f92ad6fde
804
cpp
C++
apps/vJoyList/MyMFCListCtrl.cpp
lukester1975/vJoy
28bede0a486dd0a303157c1365d4f18464e7034d
[ "MIT" ]
432
2015-08-12T03:06:13.000Z
2022-03-29T17:42:12.000Z
apps/vJoyList/MyMFCListCtrl.cpp
jiangnane/vJoy
911a2a53a972f73ea8b4a021c390c953012b7fb9
[ "MIT" ]
64
2016-01-11T06:31:05.000Z
2022-03-26T21:17:17.000Z
apps/vJoyList/MyMFCListCtrl.cpp
jiangnane/vJoy
911a2a53a972f73ea8b4a021c390c953012b7fb9
[ "MIT" ]
109
2015-10-11T14:27:28.000Z
2022-03-29T17:42:21.000Z
// MyMFCListCtrl.cpp : implementation file // #include "stdafx.h" #include "vJoyList.h" #include "MyMFCListCtrl.h" // CMyMFCListCtrl IMPLEMENT_DYNAMIC(CMyMFCListCtrl, CMFCListCtrl) COLORREF CMyMFCListCtrl::OnGetCellTextColor(int nRow, int nColum) { if (!Exist[nRow]) return RGB(200, 200, 200); else { if (!Owned[nRow]) return RGB(0, 0, 0); else return RGB(250, 50, 0); } } CMyMFCListCtrl::CMyMFCListCtrl() { } CMyMFCListCtrl::~CMyMFCListCtrl() { } void CMyMFCListCtrl::SetExist(int id, bool exist) { if (id < 1 || id>16) return; Exist[id - 1] = exist; } void CMyMFCListCtrl::SetOwned(int id, bool exist) { if (id < 1 || id>16) return; Owned[id - 1] = exist; } BEGIN_MESSAGE_MAP(CMyMFCListCtrl, CMFCListCtrl) END_MESSAGE_MAP() // CMyMFCListCtrl message handlers
13.4
65
0.686567
lukester1975
f4f341c0d915a82506d114579a0967963bae0e65
4,416
cpp
C++
pc-client/Public/LejuTbableWidget.cpp
LejuRobotics/Aelos-Vision-Demo
0b4ad1338bd018e8107533a7164d00442ff1d394
[ "Apache-2.0" ]
6
2018-10-23T07:28:35.000Z
2020-02-06T02:19:40.000Z
pc-client/Public/LejuTbableWidget.cpp
LejuRobotics/Aelos-Vision-Demo
0b4ad1338bd018e8107533a7164d00442ff1d394
[ "Apache-2.0" ]
null
null
null
pc-client/Public/LejuTbableWidget.cpp
LejuRobotics/Aelos-Vision-Demo
0b4ad1338bd018e8107533a7164d00442ff1d394
[ "Apache-2.0" ]
3
2018-12-25T08:34:15.000Z
2020-04-16T07:03:00.000Z
/** * @file LejuTbableWidget.cpp * @version 1.0 * @date 2017年07月22日 * @author C_Are * @copyright Leju * * @brief 记录标记颜色的列表,LejuTbableWidget类的cpp文件 */ #include "LejuTbableWidget.h" LejuTbableWidget::LejuTbableWidget(QWidget *parent) : QTableWidget(parent) { //设置表头 setColumnCount(7); m_headLabelList << tr(" Name") << tr("Time") << tr("Color") << tr("Width") << tr("Type") << tr("Turn") << tr("State"); setHorizontalHeaderLabels(m_headLabelList); horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents); horizontalHeader()->setSectionResizeMode(5, QHeaderView::ResizeToContents); horizontalHeader()->setSectionResizeMode(6, QHeaderView::ResizeToContents); // horizontalHeader()->setStyleSheet("color: red;"); // horizontalHeader()->setStyleSheet("color: red; background-color: #424242; "); horizontalHeader()->setStyleSheet("QHeaderView::section {background-color: #797979; border-radius:0px; border-width: 1px;}"); //创建右键菜单 menu = new QMenu(this); QAction *action = new QAction(this); action->setText(tr("删除")); connect(action,SIGNAL(triggered()),this,SLOT(onDeleteItem())); menu->addAction(action); } LejuTbableWidget::~LejuTbableWidget() { } void LejuTbableWidget::addItem(const QString &pTime, const QString &pColor, int pWidth) { insertRow(rowCount()); QComboBox *combox = new QComboBox(this); combox->setProperty("row", rowCount()-1); combox->addItem(tr("障碍物")); combox->addItem(tr("目标")); combox->addItem(tr("足球")); connect(combox, SIGNAL(currentIndexChanged(int)), this, SLOT(onTypeChanged(int))); QComboBox *combox_2 = new QComboBox(this); combox_2->setProperty("row", rowCount()-1); combox_2->addItem(tr("Left")); combox_2->addItem(tr("Right")); connect(combox_2, SIGNAL(currentIndexChanged(int)), this, SLOT(onTurnChanged(int))); LejuColorLabel *colorLabel = new LejuColorLabel(this); colorLabel->setColor(pColor); setItem(rowCount()-1,0,new QTableWidgetItem(QString(tr("目标%1")).arg(rowCount()))); setItem(rowCount()-1,1,new QTableWidgetItem(pTime)); setCellWidget(rowCount()-1, 2, colorLabel); setItem(rowCount()-1,3,new QTableWidgetItem(QString::number(pWidth))); setCellWidget(rowCount()-1, 4, combox); setCellWidget(rowCount()-1, 5, combox_2); setItem(rowCount()-1,6,new QTableWidgetItem(tr("未完成"))); item(rowCount()-1,1)->setTextAlignment(Qt::AlignCenter); item(rowCount()-1,3)->setTextAlignment(Qt::AlignCenter); item(rowCount()-1,6)->setTextAlignment(Qt::AlignCenter); } QString LejuTbableWidget::lastName() const { return item(rowCount()-1, 0)->text(); } int LejuTbableWidget::lastType() const { QComboBox *box = (QComboBox*)cellWidget(rowCount()-1,4); return box->currentIndex(); } int LejuTbableWidget::lastTurn() const { QComboBox *box = (QComboBox*)cellWidget(rowCount()-1,5); return box->currentIndex(); } bool LejuTbableWidget::isAllFinished() const { for (int i=0; i<rowCount(); ++i) { if (item(i, 6)->text() == tr("未完成")) { return false; } } return true; } void LejuTbableWidget::resetState() { for (int i=0; i<rowCount(); ++i) { item(i, 6)->setText(tr("未完成")); } } void LejuTbableWidget::onDeleteItem() { QString msg; msg = QString("Remove Target=%1").arg(currentRow()); emit sendData(msg.toUtf8()); removeRow(currentRow()); } void LejuTbableWidget::onTypeChanged(int index) { int nRow = sender()->property("row").toInt(); QString msg; msg = QString("set Target.Type=%1,%2").arg(nRow).arg(index); emit sendData(msg.toUtf8()); } void LejuTbableWidget::onTurnChanged(int index) { int nRow = sender()->property("row").toInt(); QString msg; msg = QString("set Target.Turn=%1,%2").arg(nRow).arg(index); emit sendData(msg.toUtf8()); } void LejuTbableWidget::contextMenuEvent(QContextMenuEvent *e) { menu->exec(QCursor::pos()); QTableWidget::contextMenuEvent(e); }
30.246575
129
0.666893
LejuRobotics
f4f83be5e7f79391192be51edcd62a436de028cf
7,576
tcc
C++
include/onnc/ADT/Bits/Digraph.tcc
LiuLeif/onnc
3f69e46172a9c33cc04541ff7fd78d5d7b6bdbba
[ "BSD-3-Clause" ]
450
2018-08-03T08:17:03.000Z
2022-03-17T17:21:06.000Z
include/onnc/ADT/Bits/Digraph.tcc
ffk0716/onnc
91e4955ade64b479db17aaeccacf4b7339fe44d2
[ "BSD-3-Clause" ]
104
2018-08-13T07:31:50.000Z
2021-08-24T11:24:40.000Z
include/onnc/ADT/Bits/Digraph.tcc
ffk0716/onnc
91e4955ade64b479db17aaeccacf4b7339fe44d2
[ "BSD-3-Clause" ]
100
2018-08-12T04:27:39.000Z
2022-03-11T04:17:42.000Z
//===-- Digraph.tcc -------------------------------------------------------===// // // The ONNC Project // // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Digraph //===----------------------------------------------------------------------===// template<typename NodeType, typename ArcType> Digraph<NodeType, ArcType>::Digraph() : m_pNodeHead(nullptr), m_pNodeRear(nullptr), m_pFreeNodeHead(nullptr), m_pFreeArcHead(nullptr), m_NodeList(), m_ArcList() { } template<typename NodeType, typename ArcType> Digraph<NodeType, ArcType>::~Digraph() { clear(); } template<typename NodeType, typename ArcType> template<class ... NodeCtorParams> typename Digraph<NodeType, ArcType>::Node* Digraph<NodeType, ArcType>::addNode(NodeCtorParams&& ... pParams) { // 1. find an available free node Node* result = nullptr; if (nullptr == m_pFreeNodeHead) { result = new NodeType(pParams...); m_NodeList.push_back(result); } else { result = m_pFreeNodeHead; m_pFreeNodeHead = static_cast<NodeType*>(m_pFreeNodeHead->next); } // 2. set up linkages result->prev = m_pNodeRear; result->next = nullptr; result->first_in = nullptr; result->last_in = nullptr; result->first_out = nullptr; result->last_out = nullptr; // 3. reset rear node if (nullptr != m_pNodeRear) { m_pNodeRear->next = result; } m_pNodeRear = result; if (nullptr == m_pNodeHead) m_pNodeHead = result; return result; } template<typename NodeType, typename ArcType> template<typename ... ArcCtorParams> typename Digraph<NodeType, ArcType>::Arc* Digraph<NodeType, ArcType>::addArc(Node& pU, Node& pV, ArcCtorParams&& ... pParams) { // 1. find an available free arc Arc* result = nullptr; if (nullptr == m_pFreeArcHead) { result = new ArcType(pParams...); m_ArcList.push_back(result); } else { result = m_pFreeArcHead; m_pFreeArcHead = static_cast<ArcType*>(m_pFreeArcHead->next_in); } // 2. set up arc result->source = &pU; result->target = &pV; result->prev_in = nullptr; result->next_in = nullptr; result->prev_out = nullptr; result->next_out = nullptr; // 3. set up fan-out linked list result->prev_out = pU.last_out; if (nullptr != pU.last_out) { pU.last_out->next_out = result; } else { // last_out is nullptr => a node without fan-out arcs. pU.first_out = result; } pU.last_out = result; // 4. set up fan-in linked list result->prev_in = pV.last_in; if (nullptr != pV.last_in) { pV.last_in->next_in = result; } else { // last_in is nullptr => a node without fan-in arcs pV.first_in = result; } pV.last_in = result; return result; } template<typename NodeType, typename ArcType> void Digraph<NodeType, ArcType>::erase(Node& pNode) { // 1. connect previous node and next node. if (nullptr != pNode.next) { pNode.next->prev = pNode.prev; } else { // pNode.next is NULL => pNode is the rear m_pNodeRear = pNode.getPrevNode(); } if (nullptr != pNode.prev) { pNode.prev->next = pNode.next; } else { // pNode.prev is NULL => pNode is the head m_pNodeHead = pNode.getNextNode(); } // 2. remove all fan-in arcs Arc* fan_in = pNode.getFirstInArc(); while(nullptr != fan_in) { Arc* next_in = fan_in->getNextIn(); erase(*fan_in); fan_in = next_in; } // 3. remove all fan-out arcs Arc* fan_out = pNode.getFirstOutArc(); while(nullptr != fan_out) { Arc* next_out = fan_out->getNextOut(); erase(*fan_out); fan_out = next_out; } // 4. put pNode in the free node list pNode.next = m_pFreeNodeHead; pNode.prev = nullptr; if (nullptr != m_pFreeNodeHead) m_pFreeNodeHead->prev = &pNode; m_pFreeNodeHead = &pNode; } template<typename NodeType, typename ArcType> void Digraph<NodeType, ArcType>::erase(Arc& pArc) { // 1. remove from the fan-out list if (nullptr != pArc.prev_out) { pArc.prev_out->next_out = pArc.next_out; } else { // pArc.prev_out is NULL => pArc is the first_out of the source pArc.source->first_out = pArc.next_out; } if (nullptr != pArc.next_out) { // a middle arc pArc.next_out->prev_out = pArc.prev_out; } // 2. remove from the fan-in list if (nullptr != pArc.prev_in) { pArc.prev_in->next_in = pArc.next_in; } else { pArc.target->first_in = pArc.next_in; } if (nullptr != pArc.next_in) { pArc.next_in->prev_in = pArc.prev_in; } // 3. put pArc in the free arc list // Use fan-in links to chain the free list pArc.next_in = m_pFreeArcHead; m_pFreeArcHead = &pArc; } template<typename NodeType, typename ArcType> void Digraph<NodeType, ArcType>::clear() { m_pNodeHead = nullptr; m_pNodeRear = nullptr; m_pFreeNodeHead = nullptr; m_pFreeArcHead = nullptr; // delete all nodes typename NodeList::iterator node, nEnd = m_NodeList.end(); for (node = m_NodeList.begin(); node != nEnd; ++node) delete *node; // delete all arcs typename ArcList::iterator arc, aEnd = m_ArcList.end(); for (arc = m_ArcList.begin(); arc != aEnd; ++arc) delete *arc; m_NodeList.clear(); m_ArcList.clear(); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::iterator Digraph<NodeType, ArcType>::begin() { return iterator(m_pNodeHead); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::iterator Digraph<NodeType, ArcType>::end() { return iterator(nullptr); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::const_iterator Digraph<NodeType, ArcType>::begin() const { return const_iterator(m_pNodeHead); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::const_iterator Digraph<NodeType, ArcType>::end() const { return const_iterator(nullptr); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::dfs_iterator Digraph<NodeType, ArcType>::dfs_begin() { return dfs_iterator(m_pNodeHead); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::dfs_iterator Digraph<NodeType, ArcType>::dfs_end() { return dfs_iterator(); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::const_dfs_iterator Digraph<NodeType, ArcType>::dfs_begin() const { return const_dfs_iterator(m_pNodeHead); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::const_dfs_iterator Digraph<NodeType, ArcType>::dfs_end() const { return const_dfs_iterator(); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::bfs_iterator Digraph<NodeType, ArcType>::bfs_begin() { return bfs_iterator(m_pNodeHead); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::bfs_iterator Digraph<NodeType, ArcType>::bfs_end() { return bfs_iterator(); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::const_bfs_iterator Digraph<NodeType, ArcType>::bfs_begin() const { return const_bfs_iterator(m_pNodeHead); } template<typename NodeType, typename ArcType> typename Digraph<NodeType, ArcType>::const_bfs_iterator Digraph<NodeType, ArcType>::bfs_end() const { return const_bfs_iterator(); } template<typename NodeType, typename ArcType> bool Digraph<NodeType, ArcType>::exists(const Node& pNode) const { iterator node, nEnd = end(); for (node = begin(); node != nEnd; ++node) { if (&pNode == node.node()) return true; } return false; }
25.508418
83
0.679382
LiuLeif
f4ff050c8ab412d4b5c1841fbe015805f5200bf6
2,203
hpp
C++
multi_robot_explore_cpp/include/multi_robot_explore_cpp/get_map_value_node.hpp
wt160/multi_robot_explore_testbed
9d5fd50f5c7fd5f77a6dc70c74608c65cdf96396
[ "BSD-3-Clause" ]
null
null
null
multi_robot_explore_cpp/include/multi_robot_explore_cpp/get_map_value_node.hpp
wt160/multi_robot_explore_testbed
9d5fd50f5c7fd5f77a6dc70c74608c65cdf96396
[ "BSD-3-Clause" ]
null
null
null
multi_robot_explore_cpp/include/multi_robot_explore_cpp/get_map_value_node.hpp
wt160/multi_robot_explore_testbed
9d5fd50f5c7fd5f77a6dc70c74608c65cdf96396
[ "BSD-3-Clause" ]
null
null
null
#ifndef ROBOT_CONTROL_INTERFACE_HPP #define ROBOT_CONTROL_INTERFACE_HPP #include "rclcpp/rclcpp.hpp" #include "rclcpp_action/rclcpp_action.hpp" #include "multi_robot_explore_cpp/explore_util.hpp" #include <thread> #include <chrono> #include <future> #include "geometry_msgs/msg/pose.hpp" #include "geometry_msgs/msg/point.hpp" #include "geometry_msgs/msg/twist.hpp" #include "nav_msgs/msg/occupancy_grid.hpp" #include "nav2_msgs/action/compute_path_to_pose.hpp" #include "nav2_msgs/action/navigate_to_pose.hpp" #include "geometry_msgs/msg/pose_stamped.hpp" #include "std_msgs/msg/string.hpp" #include "multi_robot_interfaces/srv/get_peer_map_value_on_coords.hpp" class GetMapValueNode: public rclcpp::Node{ public: using NavigateToPose = nav2_msgs::action::NavigateToPose; using GoalHandleNavigate = rclcpp_action::ClientGoalHandle<NavigateToPose>; GetMapValueNode(std::string robot_name, vector<std::string> peer_list); map<int, vector<int>> getMapValue(vector<pair<double, double>> frontier_pt_world_frame_list); int navigate_to_pose_state_ = 0; private: map<string, rclcpp::Client<multi_robot_interfaces::srv::GetPeerMapValueOnCoords>::SharedPtr> get_map_value_client_dict_; map<string, rclcpp::callback_group::CallbackGroup::SharedPtr> callback_group_map_; vector<string> peer_list_; vector<int> map_value_list_; bool is_received_; rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub_; rclcpp_action::Client<NavigateToPose>::SharedPtr navigate_client_ptr_; rclcpp::Subscription<std_msgs::msg::String>::SharedPtr test_sub_; int total_robot_num_; std::string robot_name_; int current_state_; int previous_state_; std::vector<std::string> persistent_robot_peers_; nav_msgs::msg::OccupancyGrid local_map_; nav_msgs::msg::OccupancyGrid inflated_local_map_; geometry_msgs::msg::Pose current_target_pose_; geometry_msgs::msg::Pose next_target_pose_; nav_msgs::msg::OccupancyGrid merged_map_; std::string robot_map_frame_; std::string robot_base_frame_; }; #endif
37.982759
128
0.744893
wt160
7605661c6c7945dd63c11ca1145de7d9743bcc63
10,670
cpp
C++
src/cpp/BaseWindow.cpp
orbitrc/blusher
bf90272308c0ff06560f0feace5845d77a05d70f
[ "MIT" ]
3
2019-08-08T05:48:24.000Z
2021-08-23T01:24:29.000Z
src/cpp/BaseWindow.cpp
orbitrc/blusher
bf90272308c0ff06560f0feace5845d77a05d70f
[ "MIT" ]
2
2021-06-28T10:50:52.000Z
2021-07-11T10:37:29.000Z
src/cpp/BaseWindow.cpp
orbitrc/blusher
bf90272308c0ff06560f0feace5845d77a05d70f
[ "MIT" ]
1
2019-08-15T04:19:51.000Z
2019-08-15T04:19:51.000Z
#include "BaseWindow.h" #include <stdint.h> #include <blusher/base.h> #include "DesktopEnvironment.h" #include "Ewmh.h" #include "Blusher.h" #include <QScreen> namespace bl { BaseWindow::BaseWindow(QWindow *parent) : QQuickWindow(parent) { this->m_netWmStrutPartial = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; this->m_type = static_cast<int>(BaseWindow::WindowType::Normal); this->m_pos.setX(QQuickWindow::x()); this->m_pos.setY(QQuickWindow::y()); this->m_size.setWidth(QQuickWindow::width()); this->m_size.setHeight(QQuickWindow::height()); this->m_scale = 1; this->m_menu = nullptr; this->m_anchors.setTop(AnchorLine(this->contentItem())); this->m_anchors.setLeft(AnchorLine(this->contentItem())); this->m_anchors.setRight(AnchorLine(this->contentItem())); this->m_anchors.setBottom(AnchorLine(this->contentItem())); QObject::connect(this, &QQuickWindow::screenChanged, this, &BaseWindow::q_onScreenChanged); QObject::connect(DesktopEnvironment::singleton, &DesktopEnvironment::screenScaleChanged, this, &BaseWindow::changeScale); // Connect signals that window geometry changed by window manager. // Not connect to setX signals because prevent circular signal chain. QObject::connect(this, &QWindow::xChanged, this, &BaseWindow::q_onXChanged); QObject::connect(this, &QWindow::yChanged, this, &BaseWindow::q_onYChanged); QObject::connect(this, &QWindow::widthChanged, this, &BaseWindow::q_onWidthChanged); QObject::connect(this, &QWindow::heightChanged, this, &BaseWindow::q_onHeightChanged); } QList<int> BaseWindow::netWmStrutPartial() const { return this->m_netWmStrutPartial; } void BaseWindow::setNetWmStrutPartial(QList<int> value) { if (value.length() == 12) { this->m_netWmStrutPartial = value; #ifdef BL_PLATFORM_LINUX Ewmh::set_net_wm_strut_partial(winId(), value); #endif // BL_BLATFORM_LINUX emit this->netWmStrutPartialChanged(value); } } bool BaseWindow::onAllDesktops() const { #ifdef BL_PLATFORM_LINUX uint32_t desktop = Ewmh::get_net_wm_desktop(winId()); if (desktop == 0xFFFFFFFF) { return true; } return false; #endif // BL_PLATFORM_LINUX return false; } void BaseWindow::setOnAllDesktops(bool value) { #ifdef BL_PLATFORM_LINUX if (this->onAllDesktops() != value && value == true) { Ewmh::set_net_wm_desktop(winId(), 0xFFFFFFFF); emit this->onAllDesktopsChanged(value); } else if (this->onAllDesktops() != value && value == false) { Ewmh::set_net_wm_desktop(winId(), 1); emit this->onAllDesktopsChanged(value); } #endif // BL_PLATFORM_LINUX } int BaseWindow::transientFor() const { return this->m_transientFor; } void BaseWindow::setTransientFor(int win) { if (this->m_transientFor != win) { this->m_transientFor = win; if (win != 0) { Ewmh::set_wm_transient_for(winId(), win); } emit this->transientForChanged(win); } } int BaseWindow::type() const { return this->m_type; } void BaseWindow::setType(int type) { if (type != this->m_type) { this->m_type = type; // No window frame for menu window. if (type == static_cast<int>(WindowType::Menu)) { QWindow::setFlag(Qt::FramelessWindowHint, true); QWindow::setFlag(Qt::Popup, true); } emit this->typeChanged(); } } int BaseWindow::x() const { return this->m_pos.x(); } void BaseWindow::setX(int x) { if (this->m_pos.x() != x) { this->m_pos.setX(x); QQuickWindow::setX(x); emit this->xChanged(x); } } int BaseWindow::y() const { return this->m_pos.y(); } void BaseWindow::setY(int y) { if (this->m_pos.y() != y) { this->m_pos.setY(y); QQuickWindow::setY(y); emit this->yChanged(y); } } int BaseWindow::width() const { return this->m_size.width(); } void BaseWindow::setWidth(int width) { if (this->m_size.width() != width) { this->m_size.setWidth(width); QQuickWindow::setWidth(width * this->screenScale()); emit this->widthChanged(width); } } int BaseWindow::height() const { return this->m_size.height(); } void BaseWindow::setHeight(int height) { if (this->m_size.height() != height) { this->m_size.setHeight(height); QQuickWindow::setHeight(height * this->screenScale()); emit this->heightChanged(height); } } Menu* BaseWindow::menu() const { return this->m_menu; } void BaseWindow::setMenu(Menu *menu) { if (this->m_menu != menu) { this->m_menu = menu; emit this->menuChanged(); } } qreal BaseWindow::screenScale() const { return this->m_scale; } QString BaseWindow::screenName() const { return this->screen()->name(); } int BaseWindow::windowId() const { return this->winId(); } AnchorLine BaseWindow::top() { return this->m_anchors.top(); } AnchorLine BaseWindow::bottom() { return this->m_anchors.bottom(); } //====================== // Event handlers //====================== bool BaseWindow::event(QEvent *event) { if (event->type() == QEvent::UpdateRequest) { // Grab mouse if window type is menu. if (this->type() == static_cast<int>(WindowType::Menu)) { QWindow::setMouseGrabEnabled(true); } } return QQuickWindow::event(event); } void BaseWindow::keyPressEvent(QKeyEvent *event) { if (this->type() == static_cast<int>(WindowType::Menu) && event->key() == Qt::Key_Escape) { QWindow::setMouseGrabEnabled(false); QQuickWindow::close(); } // Convert Qt key modifiers to Blusher modifiers. using KeyModifier = Blusher::KeyModifier; int modifiers = static_cast<int>(KeyModifier::None); if (event->modifiers() & Qt::ControlModifier) { modifiers |= static_cast<int>(KeyModifier::Control); } if (event->modifiers() & Qt::AltModifier) { modifiers |= static_cast<int>(KeyModifier::Alt); } if (event->modifiers() & Qt::ShiftModifier) { modifiers |= static_cast<int>(KeyModifier::Shift); } if (event->modifiers() & Qt::MetaModifier) { modifiers |= static_cast<int>(KeyModifier::Super); } KeyEvent *ke = new KeyEvent(modifiers, event->key()); ke->deleteLater(); emit this->keyPressed(ke); /* QObject::connect(ke, &QObject::destroyed, this, []() { qDebug() << "destroyed!"; }); */ QQuickWindow::keyPressEvent(event); } void BaseWindow::showEvent(QShowEvent *evt) { #ifdef BL_PLATFORM_LINUX if (this->m_type == static_cast<int>(WindowType::Normal)) { return QQuickWindow::showEvent(evt); } // Set _NET_WM_WINDOW_TYPE. switch (this->type()) { case static_cast<int>(WindowType::Dock): Ewmh::set_net_wm_window_type(winId(), WindowType::Dock); break; case static_cast<int>(WindowType::Desktop): Ewmh::set_net_wm_window_type(winId(), WindowType::Desktop, true); break; case static_cast<int>(WindowType::Toolbar): Ewmh::set_net_wm_window_type(winId(), WindowType::Toolbar); break; case static_cast<int>(WindowType::Menu): Ewmh::set_net_wm_window_type(winId(), WindowType::Menu); break; case static_cast<int>(WindowType::Utility): Ewmh::set_net_wm_window_type(winId(), WindowType::Utility); break; case static_cast<int>(WindowType::Splash): Ewmh::set_net_wm_window_type(winId(), WindowType::Splash); break; case static_cast<int>(WindowType::Dialog): Ewmh::set_net_wm_window_type(winId(), WindowType::Dialog); break; case static_cast<int>(WindowType::DropDownMenu): Ewmh::set_net_wm_window_type(winId(), WindowType::DropDownMenu); break; case static_cast<int>(WindowType::PopUpMenu): Ewmh::set_net_wm_window_type(winId(), WindowType::PopUpMenu); break; case static_cast<int>(WindowType::ToolTip): Ewmh::set_net_wm_window_type(winId(), WindowType::ToolTip); break; case static_cast<int>(WindowType::Notification): Ewmh::set_net_wm_window_type(winId(), WindowType::Notification); break; case static_cast<int>(WindowType::Combo): Ewmh::set_net_wm_window_type(winId(), WindowType::Combo); break; case static_cast<int>(WindowType::Dnd): Ewmh::set_net_wm_window_type(winId(), WindowType::Dnd); break; default: break; } #endif // BL_PLATFORM_LINUX return QQuickWindow::showEvent(evt); } //================= // Public slots //================= void BaseWindow::changeScale() { ScreenInfo *screen_info = nullptr; auto screen_info_list = bl::DesktopEnvironment::singleton->screens(); // Find screen info. for (auto&& info: screen_info_list) { if (info->name() == this->screenName()) { screen_info = info; break; } } qreal scale = screen_info ? screen_info->scale() : 1; this->m_scale = scale; // Scale window size. QWindow::setWidth(this->width() * scale); QWindow::setHeight(this->height() * scale); emit this->screenScaleChanged(scale); } //================= // Private slots //================= void BaseWindow::q_onScreenChanged(QScreen *qscreen) { emit this->screenNameChanged(); QString screen_name = qscreen->name(); ScreenInfo *screen_info = nullptr; auto screen_info_list = bl::DesktopEnvironment::singleton->screens(); // Find screen info. for (auto&& info: screen_info_list) { if (info->name() == screen_name) { screen_info = info; break; } } if (screen_info == nullptr) { qDebug() << "[WARNING] Screen name \"" << screen_name << "\" does not exist."; return; } this->m_scale = screen_info->scale(); emit this->screenScaleChanged(this->m_scale); } void BaseWindow::q_onXChanged(int x) { this->m_pos.setX(x); emit this->xChanged(x); } void BaseWindow::q_onYChanged(int y) { this->m_pos.setY(y); emit this->yChanged(y); } void BaseWindow::q_onWidthChanged(int width) { this->m_size.setWidth(width / this->screenScale()); emit this->widthChanged(width); } void BaseWindow::q_onHeightChanged(int height) { this->m_size.setHeight(height / this->screenScale()); emit this->heightChanged(height); } void BaseWindow::onScreensChanged() { } } // namespace bl
24.813953
92
0.627273
orbitrc
7606b9fc27c686a035d5ba98f410fd51316408f2
51,830
cpp
C++
pizmidi/midiConverter3/midiConverter3.cpp
nonameentername/pizmidi
a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2
[ "BSD-Source-Code" ]
null
null
null
pizmidi/midiConverter3/midiConverter3.cpp
nonameentername/pizmidi
a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2
[ "BSD-Source-Code" ]
null
null
null
pizmidi/midiConverter3/midiConverter3.cpp
nonameentername/pizmidi
a985e3d2bf8f02e3c0a87300dfbb82c35608bbd2
[ "BSD-Source-Code" ]
1
2021-01-26T12:25:01.000Z
2021-01-26T12:25:01.000Z
#include "midiConverter3.hpp" //------------------------------------------------------------------------------------------------------- AudioEffect* createEffectInstance (audioMasterCallback audioMaster) { return new MidiConverter (audioMaster); } MidiConverterProgram::MidiConverterProgram () { // default Program Values param[kIn] = 0.f; //CC in param[kCCin] = MIDI_TO_FLOAT(2.1); //CC 1 param[kNRPNin] = 0.f; param[kChin] = CHANNEL_TO_FLOAT(-1); //Any Channel param[kLowLimit] = 0.f; // param[kHighLimit] = 1.f; // full param[kLow] = 0.f; // range param[kHigh] = 1.f; // param[kRangeMode] = 0.f; param[kOffset] = MIDI_TO_FLOAT(63.1); //no offset param[kOut] = 0.02f; //CC out param[kCCout] = MIDI_TO_FLOAT2(2.1); //really 1 param[kNRPNout] = 0.f; param[kChout] = CHANNEL_TO_FLOAT(-1); //same channel out param[kThru] = 0.f; //don't pass on original message // default program name strcpy (name, "Default"); } //----------------------------------------------------------------------------- MidiConverter::MidiConverter(audioMasterCallback audioMaster) : PizMidi(audioMaster, kNumPrograms, kNumParams), programs(0) { programs = new MidiConverterProgram[numPrograms]; outmode = drop; inmode = cc; if (programs) { CFxBank* defaultBank = new CFxBank(kNumPrograms,kNumParams); if (readDefaultBank(PLUG_NAME,defaultBank)) { if((VstInt32)defaultBank->GetFxID()==PLUG_IDENT) { int i; for(i=0;i<kNumPrograms;i++){ for (int p=0;p<kNumParams;p++) { programs[i].param[p] = defaultBank->GetProgParm(i,p); } strcpy(programs[i].name,defaultBank->GetProgramName(i)); } } } else { // built-in programs int i; for(i=0;i<kNumPrograms;i++){ switch(i){ case 0: sprintf(programs[i].name,"Nothing"); break; default: sprintf(programs[i].name,"Program %d",i+1); break; } } } setProgram (0); } for (int ch=0;ch<16;ch++) { nrpn[ch]=-1; nrpncoarse[ch]=-1; rpn[ch]=-1; rpncoarse[ch]=-1; datafine[ch]=0; datacoarse[ch]=0; data[ch]=0; done[ch]=true; smoothcc[ch]=-1; lastPC[ch]=0; lastSentPC[ch]=0; for (int i=0;i<32;i++) { cc14msb[i][ch]=0; cc14lsb[i][ch]=0; } } //smoothing stuff counter=roundToInt(sampleRate*0.001f); lastpb=0x2000; targetpb=0x2000; lastcc=0; targetcc=0; init(); } //----------------------------------------------------------------------------------------- MidiConverter::~MidiConverter(){ if (programs) delete [] programs; } //------------------------------------------------------------------------ void MidiConverter::setProgram (VstInt32 program) { MidiConverterProgram* ap = &programs[program]; curProgram = program; for (int i=0;i<kNumParams;i++) { setParameter (i, ap->param[i]); } } //------------------------------------------------------------------------ void MidiConverter::setProgramName (char *name) { vst_strncpy (programs[curProgram].name, name, kVstMaxProgNameLen); } //------------------------------------------------------------------------ void MidiConverter::getProgramName (char *name) { if (!strcmp (programs[curProgram].name, "Init")) sprintf (name, "%s %d", programs[curProgram].name, curProgram + 1); else strcpy (name, programs[curProgram].name); } //----------------------------------------------------------------------------------------- bool MidiConverter::getProgramNameIndexed (VstInt32 category, VstInt32 index, char* text) { if (index < kNumPrograms) { strcpy (text, programs[index].name); return true; } return false; } //----------------------------------------------------------------------------------------- void MidiConverter::resume (){ AudioEffectX::resume(); lastpb=0x2000; targetpb=0x2000; counter=roundToInt(sampleRate*0.001f); for (int i=0;i<16;i++) done[i]=true; } //----------------------------------------------------------------------------------------- void MidiConverter::setParameter(VstInt32 index, float value){ MidiConverterProgram* ap = &programs[curProgram]; int lastoutmode=outmode; int lastinmode=inmode; float inc = 1.f/18.f; switch(index){ case kIn : param[kIn] = ap->param[kIn] = value; if (param[kIn]<1*inc) inmode=cc; else if (param[kIn]<2*inc) inmode=cc14; else if (param[kIn]<3*inc) inmode=pc; else if (param[kIn]<4*inc) inmode=pcdec; else if (param[kIn]<5*inc) inmode=pcinc; else if (param[kIn]<6*inc) inmode=cp; else if (param[kIn]<7*inc) inmode=pa; else if (param[kIn]<8*inc) inmode=pb; else if (param[kIn]<9*inc) inmode=pblsb; else if (param[kIn]<10*inc) inmode=NRPN; else if (param[kIn]<11*inc) inmode=NRPNlsb; else if (param[kIn]<12*inc) inmode=RPN; else if (param[kIn]<13*inc) inmode=RPNlsb; else if (param[kIn]<14*inc) inmode=nonn; else if (param[kIn]<15*inc) inmode=nonv; else if (param[kIn]<16*inc) inmode=noffn; else if (param[kIn]<17*inc) inmode=noffv; else inmode=clock; //else if (param[kIn]<0.9f) inmode=undefined; //else if (param[kIn]<0.96f) inmode=undefined; //else if (param[kIn]<1.0f) inmode=undefined; //else inmode=undefined; if (lastinmode != inmode) updateDisplay(); break; case kCCin : param[kCCin] = ap->param[kCCin] = value; updateDisplay(); break; case kNRPNin : param[kNRPNin] = ap->param[kNRPNin] = value; break; case kChin : param[kChin] = ap->param[kChin] = value; break; case kLowLimit : if (value>param[kHighLimit]) setParameterAutomated(kHighLimit,value); param[kLowLimit] = ap->param[kLowLimit] = value; break; case kHighLimit : if (param[kLowLimit]>value) setParameterAutomated(kLowLimit,value); param[kHighLimit] = ap->param[kHighLimit] = value; break; case kLow : param[kLow] = ap->param[kLow] = value; break; case kHigh : param[kHigh] = ap->param[kHigh] = value; break; case kRangeMode : param[kRangeMode] = ap->param[kRangeMode] = value; break; case kOffset : param[kOffset] = ap->param[kOffset] = value; break; case kOut : param[kOut] = ap->param[kOut] = value; inc = 1.f/20.f; if (param[kOut]<1*inc) outmode=drop; else if (param[kOut]<2*inc) outmode=cc; else if (param[kOut]<3*inc) outmode=cc14; else if (param[kOut]<4*inc) outmode=pc; else if (param[kOut]<5*inc) outmode=pcdec; else if (param[kOut]<6*inc) outmode=pcinc; else if (param[kOut]<7*inc) outmode=cp; else if (param[kOut]<8*inc) outmode=pa; else if (param[kOut]<9*inc) outmode=pb; else if (param[kOut]<10*inc) outmode=pblsb; else if (param[kOut]<11*inc) outmode=NRPN; else if (param[kOut]<12*inc) outmode=NRPNlsb; else if (param[kOut]<13*inc) outmode=RPN; else if (param[kOut]<14*inc) outmode=RPNlsb; else if (param[kOut]<15*inc) outmode=nonn; else if (param[kOut]<16*inc) outmode=nonv; else if (param[kOut]<17*inc) outmode=noffn; else if (param[kOut]<18*inc) outmode=noffv; else if (param[kOut]<19*inc) outmode=clock; else outmode=songselect; //else if (param[kOut]<1.0f) outmode=undefined; //else outmode=undefined; if (lastoutmode != outmode) updateDisplay(); break; case kCCout : param[kCCout] = ap->param[kCCout] = value; updateDisplay(); break; case kNRPNout : param[kNRPNout] = ap->param[kNRPNout] = value; break; case kChout : param[kChout] = ap->param[kChout] = value; break; case kThru : param[kThru] = ap->param[kThru] = value; break; default : break; } } //----------------------------------------------------------------------------------------- float MidiConverter::getParameter(VstInt32 index) { if (index<kNumParams) return param[index]; return 0.f; } //----------------------------------------------------------------------------------------- void MidiConverter::getParameterName(VstInt32 index, char *label){ switch(index){ case kIn : strcpy(label, "Input Type"); break; case kCCin : strcpy(label, "In Param 1"); break; case kNRPNin : strcpy(label, "In Param 2"); break; case kChin : strcpy(label, "Channel in"); break; case kLowLimit : strcpy(label, "Low Input"); break; case kHighLimit : strcpy(label, "High Input"); break; case kRangeMode : strcpy(label, "Map Mode"); break; case kLow : strcpy(label, "Low Output"); break; case kHigh : strcpy(label, "High Output"); break; case kOffset : strcpy(label, "Offset"); break; case kOut : strcpy(label, "Output Type"); break; case kCCout : strcpy(label, "Out Param 1"); break; case kNRPNout : strcpy(label, "Out Param 2"); break; case kChout : strcpy(label, "Channel out"); break; case kThru : strcpy(label, "Thru"); break; default : break; } } //----------------------------------------------------------------------------------------- void MidiConverter::getParameterDisplay(VstInt32 index, char *text){ switch(index){ case kIn: switch (inmode) { case cc: strcpy(text, "CC"); break; case cc14: strcpy(text, "14-bit CC"); break; case pc: strcpy(text, "Program Change"); break; case pcinc: strcpy(text, "ProgChg Inc"); break; case pcdec: strcpy(text, "ProgChg Dec"); break; case cp: strcpy(text, "Channel Pressure"); break; case pa: strcpy(text, "Poly Aftertouch"); break; case pb: strcpy(text, "Pitch Bend"); break; case pblsb: strcpy(text, "Pitch Bend (LSB)"); break; case NRPN: strcpy(text, "NRPN"); break; case NRPNlsb: strcpy(text, "NRPN (LSB)"); break; case RPN: strcpy(text, "RPN"); break; case RPNlsb: strcpy(text, "RPN (LSB)"); break; case nonn: strcpy(text, "Note On #"); break; case nonv: strcpy(text, "Note On Velocity"); break; case noffn: strcpy(text, "Note Off #"); break; case noffv: strcpy(text, "Note Off Velocity"); break; case clock: strcpy(text, "MIDI Clock"); break; default: strcpy(text, "???"); break; } break; case kCCin: if (inmode==cc) { if (FLOAT_TO_MIDI_X(param[kCCin])==-1) strcpy(text, "Any CC"); else sprintf(text, "CC %d", FLOAT_TO_MIDI_X(param[kCCin])); } else if (inmode==cc14) { if (FLOAT_TO_MIDI_X(param[kCCin])==-1) strcpy(text, "Any CC"); else if (FLOAT_TO_MIDI_X(param[kCCin])<32) sprintf(text, "CC %d / %d", FLOAT_TO_MIDI_X(param[kCCin]), FLOAT_TO_MIDI_X(param[kCCin])+32); else sprintf(text, "CC %d", FLOAT_TO_MIDI_X(param[kCCin])); } else if (inmode==pa || inmode==nonv || inmode==noffv) { if (FLOAT_TO_MIDI_X(param[kCCin])==-1) strcpy(text, "Any Note"); else sprintf(text, "Note %d (%s)", FLOAT_TO_MIDI_X(param[kCCin]),getNoteName(FLOAT_TO_MIDI_X(param[kCCin]),bottomOctave)); } else if (inmode==NRPN || inmode==NRPNlsb || inmode==RPN || inmode==RPNlsb) { if (FLOAT_TO_MIDI_X(param[kCCin])==-1) strcpy(text, "?"); else if (FLOAT_TO_MIDI_X(param[kCCin])==0) strcpy(text, "0x0000"); else sprintf(text, "%#.4x", (FLOAT_TO_MIDI_X(param[kCCin]))<<7); } else strcpy(text, " "); break; case kNRPNin: if (FLOAT_TO_MIDI_X(param[kCCin])==-1) strcpy(text, " "); else if (inmode==NRPN || inmode==NRPNlsb) { if (((FLOAT_TO_MIDI(param[kNRPNin]))|((FLOAT_TO_MIDI_X(param[kCCin]))<<7))==0) strcpy(text, "NRPN 0x0000"); else sprintf(text, "NRPN %#.4x", (FLOAT_TO_MIDI(param[kNRPNin]))|((FLOAT_TO_MIDI_X(param[kCCin]))<<7)); } else if (inmode==RPN || inmode==RPNlsb) { if ((FLOAT_TO_MIDI(param[kNRPNin])|((FLOAT_TO_MIDI_X(param[kCCin]))<<7))==0) strcpy(text, "RPN 0x0000"); else sprintf(text, "RPN %#.4x", (FLOAT_TO_MIDI(param[kNRPNin]))|((FLOAT_TO_MIDI_X(param[kCCin]))<<7)); } else strcpy(text, " "); break; case kChin: if (inmode==clock || inmode==songposition || inmode==songselect) strcpy(text," "); else { if (FLOAT_TO_CHANNEL(param[kChin])==-1) strcpy(text, "Any"); else sprintf(text, "Channel %d", FLOAT_TO_CHANNEL(param[kChin])+1); break; } case kLowLimit: if (inmode==pb) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kLowLimit])<<7)-0x2000); } else if (inmode==nonn || inmode==noffn) { sprintf(text, "%d (%s)", FLOAT_TO_MIDI(param[kLowLimit]), getNoteName(FLOAT_TO_MIDI(param[kLowLimit]),bottomOctave)); } else if (inmode==NRPN || inmode==RPN || inmode==cc14) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kLowLimit])<<7)&0x3f80 | FLOAT_TO_MIDI(param[kLowLimit])&0x007f); } else if (inmode==clock || inmode==pcinc || inmode==pcdec) strcpy(text," "); else sprintf(text, "%d", FLOAT_TO_MIDI(param[kLowLimit])); break; case kHighLimit: if (inmode==pb) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kHighLimit])<<7) + FLOAT_TO_MIDI(param[kHighLimit])-0x2000); } else if (inmode==nonn || inmode==noffn) sprintf(text, "%d (%s)", FLOAT_TO_MIDI(param[kHighLimit]), getNoteName(FLOAT_TO_MIDI(param[kHighLimit]),bottomOctave)); else if (inmode==NRPN || inmode==RPN || inmode==cc14) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kHighLimit])<<7)&0x3f80 | FLOAT_TO_MIDI(param[kHighLimit])&0x007f); } else if (inmode==clock || inmode==pcinc || inmode==pcdec) strcpy(text," "); else sprintf(text, "%d", FLOAT_TO_MIDI(param[kHighLimit])); break; case kLow: if (outmode==pb) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kLow])<<7) - 8192); } else if (outmode==NRPN || outmode==RPN || outmode==cc14) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kLow])<<7)); } else if (outmode==clock) strcpy(text, " "); else if (outmode==nonn || outmode==noffn) sprintf(text, "%d (%s)",FLOAT_TO_MIDI(param[kLow]),getNoteName(FLOAT_TO_MIDI(param[kLow]),bottomOctave)); else sprintf(text, "%d", FLOAT_TO_MIDI(param[kLow])); break; case kHigh: if (outmode==pb) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kHigh])<<7) + FLOAT_TO_MIDI(param[kHigh]) - 8192); } else if (outmode==NRPN || outmode==RPN || outmode==cc14) { sprintf(text, "%d", (FLOAT_TO_MIDI(param[kHigh])<<7)&0x3f80 | FLOAT_TO_MIDI(param[kHigh])&0x007f); } else if (outmode==clock) strcpy(text, " "); else if (outmode==nonn || outmode==noffn) sprintf(text, "%d (%s)",FLOAT_TO_MIDI(param[kHigh]),getNoteName(FLOAT_TO_MIDI(param[kHigh]),bottomOctave)); else sprintf(text, "%d", FLOAT_TO_MIDI(param[kHigh])); break; case kRangeMode: if (param[kRangeMode]<0.3f) strcpy(text, "Clip/Stretch/Limit"); else if (param[kRangeMode]<0.5) strcpy(text, "Clip/Stretch"); else if (param[kRangeMode]<0.8) strcpy(text, "Stretch/Stretch"); else strcpy(text,"Clip/Limit"); break; case kOffset: if (outmode==clock) strcpy(text, " "); else sprintf(text, "%d", (signed int)FLOAT_TO_MIDI(param[kOffset])-63); break; case kOut: switch (outmode) { case drop: strcpy(text, "Discard"); break; case cc: strcpy(text, "CC"); break; case cc14: strcpy(text, "14-bit CC"); break; case pc: strcpy(text, "Program Change"); break; case pcinc: strcpy(text, "ProgChg Inc"); break; case pcdec: strcpy(text, "ProgChg Dec"); break; case cp: strcpy(text, "Channel Pressure"); break; case pa: strcpy(text, "Poly Aftertouch"); break; case pb: strcpy(text, "Pitch Bend"); break; case pblsb: strcpy(text, "Pitch Bend (LSB)"); break; case NRPN: strcpy(text, "NRPN"); break; case NRPNlsb: strcpy(text, "NRPN (LSB)"); break; case RPN: strcpy(text, "RPN"); break; case RPNlsb: strcpy(text, "RPN (LSB)"); break; case nonn: strcpy(text, "Note On #"); break; case nonv: strcpy(text, "Note On Velocity"); break; case noffn: strcpy(text, "Note Off #"); break; case noffv: strcpy(text, "Note Off Velocity"); break; case clock: strcpy(text, "MIDI Clock"); break; default: strcpy(text, "???"); break; } break; case kCCout: switch (outmode) { case cc: if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, "As Input"); else sprintf(text, "CC %d", FLOAT_TO_MIDI_X(param[kCCout])); break; case cc14: if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, "As Input"); else if (FLOAT_TO_MIDI_X(param[kCCout])<32) sprintf(text, "CC %d / %d", FLOAT_TO_MIDI_X(param[kCCout]), FLOAT_TO_MIDI_X(param[kCCout])+32); else sprintf(text, "CC %d", FLOAT_TO_MIDI_X(param[kCCout])); break; case pa: case nonv: case noffv: if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, "As Input"); else sprintf(text, "Note %d (%s)", FLOAT_TO_MIDI_X(param[kCCout]),getNoteName(FLOAT_TO_MIDI_X(param[kCCout]),bottomOctave)); break; case pb: if (param[kCCout]<0.5f) strcpy(text, "Rough"); else strcpy(text, "Smooth"); break; case pblsb: if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, "As Input"); else sprintf(text, "MSB: %d", (FLOAT_TO_MIDI_X(param[kCCout])<<7) - 0x2000); break; case NRPN: case NRPNlsb: case RPN: case RPNlsb: if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, "As Input"); else if (FLOAT_TO_MIDI_X(param[kCCout])==0) strcpy(text, "0x0000"); else sprintf(text, "%#.4x", (FLOAT_TO_MIDI_X(param[kCCout]))<<7); break; case nonn: case noffn: if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, "As Input"); else sprintf(text, "Vel %d", FLOAT_TO_MIDI_X(param[kCCout])); break; default: strcpy(text, " "); break; } break; case kNRPNout: if (outmode==pb && param[kCCout]>=0.5f) { sprintf(text, "Inertia: %d", roundToInt(param[kNRPNout]*100.f)); } else if ((outmode==cc || outmode==cc14) && FLOAT_TO_MIDI_X(param[kCCout])!=-1) { sprintf(text, "Inertia: %d", roundToInt(param[kNRPNout]*100.f)); } else if (FLOAT_TO_MIDI_X(param[kCCout])==-1) strcpy(text, " "); else if (outmode==NRPN || outmode==NRPNlsb) { if ((FLOAT_TO_MIDI(param[kNRPNout])|((FLOAT_TO_MIDI_X(param[kCCout]))<<7))==0) strcpy(text, "NRPN 0x0000"); else sprintf(text, "NRPN %#.4x", FLOAT_TO_MIDI(param[kNRPNout])|((FLOAT_TO_MIDI_X(param[kCCout]))<<7)); } else if (outmode==RPN || outmode==RPNlsb) { if ((FLOAT_TO_MIDI(param[kNRPNout])|((FLOAT_TO_MIDI_X(param[kCCout]))<<7))==0) strcpy(text, "RPN 0x0000"); else sprintf(text, "RPN %#.4x", FLOAT_TO_MIDI(param[kNRPNout])|((FLOAT_TO_MIDI_X(param[kCCout]))<<7)); } else if (outmode==nonn) { if (FLOAT_TO_MIDI(param[kNRPNout])==0) strcpy(text, "NoteOn only"); else strcpy(text, "Add NoteOff"); } else { strcpy(text, " "); } break; case kChout : if (outmode==drop || outmode==clock || outmode==songposition || outmode==songselect) strcpy(text," "); else { if (FLOAT_TO_CHANNEL(param[kChout])==-1) strcpy(text, "No Change"); else sprintf(text, "Channel %d", FLOAT_TO_CHANNEL(param[kChout])+1); } break; case kThru: if (param[kThru]==0.f) strcpy(text, "Block All"); else if (param[kThru]<0.5f) strcpy(text, "Block Converted"); else if (param[kThru]<1.0f) strcpy(text, "Thru All"); else strcpy(text, "Converted Only"); break; default : break; } } void MidiConverter::processMidiEvents(VstMidiEventVec *inputs, VstMidiEventVec *outputs, VstInt32 sampleFrames) { // process incoming events for (unsigned int i=0;i<inputs[0].size();i++) { //copying event "i" from input (with all its fields) VstMidiEvent tomod = inputs[0][i]; short status = tomod.midiData[0] & 0xf0; // scraping channel short channel = tomod.midiData[0] & 0x0f; // isolating channel short data1 = tomod.midiData[1] & 0x7f; short data2 = tomod.midiData[2] & 0x7f; if (status==MIDI_NOTEON && data2==0) status=MIDI_NOTEOFF; int incc1 = FLOAT_TO_MIDI_X(param[kCCin]); //-1 == any int outcc1 = FLOAT_TO_MIDI_X(param[kCCout]); //-1 == no change int lolimit1 = FLOAT_TO_MIDI(param[kLowLimit]); int hilimit1 = FLOAT_TO_MIDI(param[kHighLimit]); int low1 = FLOAT_TO_MIDI(param[kLow]); int high1 = FLOAT_TO_MIDI(param[kHigh]); int offset1 = FLOAT_TO_MIDI(param[kOffset])-63; int chin1 = FLOAT_TO_CHANNEL(param[kChin]); int chout1 = FLOAT_TO_CHANNEL(param[kChout]); int inputnrpn1 = FLOAT_TO_MIDI(param[kNRPNin]) | (incc1<<7); int outputnrpn1 = FLOAT_TO_MIDI(param[kNRPNout]) | (outcc1<<7); if (chout1==-1) chout1=channel; if (chin1==-1) chin1=channel; if (incc1==-1) incc1=data1; if (outcc1==-1) outcc1=data1; bool discard = false; int idata = data2; int odata = data2; bool sendout=false; int send=1; int idata14 = data1 | (data2<<7); int odata14 = idata14; int olsb = 0; bool inis14bit=false; bool inisRPN=false; bool inisNRPN=false; bool proginc=false; bool progdec=false; //pre-processing: //keep track of all (N)RPNs if (inisNRPN || inisRPN) { send=0; const int ncoarse = inisNRPN ? 99 : 101; const int nfine = inisNRPN ? 98 : 100; int* c = inisNRPN ? nrpncoarse : rpncoarse; int* n = inisNRPN ? nrpn : rpn; // only send nprn stuff through if "thru" is on if (param[kThru]<0.5 && (data1==nfine || data1==ncoarse || data1==6 || data1==38 || data1==96 || data1==97)) { discard=true; } if (data1==ncoarse) c[channel] = data2; else if (data1==nfine && c[channel]>=0) { n[channel] = data2|(c[channel]<<7); } if (n[channel]==inputnrpn1) { if (data1==6) { //data entry slider (coarse) datacoarse[channel] = data2; data[channel] = datafine[channel] | (datacoarse[channel]<<7); send = 1; } else if (data1==38) { //data entry slider (fine) datafine[channel] = data2; data[channel] = datafine[channel] | (datacoarse[channel]<<7); send = 2; } else if (data1==96) { //data increment button if (outmode==cc) { datacoarse[channel]+=1; if (datacoarse[channel]>127) datacoarse[channel]=127; data[channel] = datafine[channel] | (datacoarse[channel]<<7); send = 1; } else { data[channel]+=1; if (data[channel]>127) data[channel]=127; datacoarse[channel] = (data[channel] & 0x3f80) >> 7; datafine[channel] = data[channel] & 0x007f; send = 2; } } else if (data1==97) { //data decrement button if (outmode==cc) { datacoarse[channel]-=1; if (datacoarse[channel]<0) datacoarse[channel]=0; data[channel] = datafine[channel] | (datacoarse[channel]<<7); send = 1; } else { data[channel]-=1; if (data[channel]<0) data[channel]=0; datacoarse[channel] = (data[channel] & 0x3f80) >> 7; datafine[channel] = data[channel] & 0x007f; send = 2; } } idata14 = data[channel]; if ((idata14>=(lolimit1<<7) && idata14<=(hilimit1|(hilimit1<<7))) || param[kRangeMode]>=0.5f && param[kRangeMode]<0.8f) { if (lolimit1==hilimit1) odata14=(low1|(low1<<7)+high1|(high1<<7))/2 + offset1|(offset1<<7); else if (param[kRangeMode]<0.3f) odata14 = MAP_TO_MIDI(idata14,low1|(low1<<7),high1|(high1<<7),0,16383) + offset1|(offset1<<7); else if (param[kRangeMode]<0.5f) odata14 = MAP_TO_MIDI(idata14,low1|(low1<<7),high1|(high1<<7),lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); else if (param[kRangeMode]<0.8f){ odata14 = MAP_TO_MIDI(idata14,0,16383,low1|(low1<<7),high1|(high1<<7)); odata14 = MAP_TO_MIDI(odata14,low1|(low1<<7),high1|(high1<<7),lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); } if (odata14>16383) odata14=16383; else if (odata14<0) odata14=0; odata = (odata14 & 0x3f80) >> 7; //odata = roundToInt((double)odata14*0.0077519379844961240310077519379845); olsb = odata14 & 0x007f; inis14bit = true; } } if (inmode==NRPNlsb || inmode==RPNlsb) idata = roundToInt((double)(data[channel])*0.0077519379844961240310077519379845); } //keep track of program changes else if (status == MIDI_PROGRAMCHANGE) { if ((lastPC[channel]==127 && data1==0) || (data1==lastPC[channel]+1)) { if (channel==chin1) proginc=true; } else if ((lastPC[channel]==0 && data1==127) || (data1==lastPC[channel]-1)) { if (channel==chin1) progdec=true; } lastPC[channel]=data1; } //------------------------------------------------------------------------------ if ( ((inmode==cc || inmode==cc14 || inmode==NRPN || inmode==NRPNlsb || inmode==RPN || inmode==RPNlsb) && status==MIDI_CONTROLCHANGE) || ((inmode==pc || inmode==pcinc || inmode==pcdec) && status==MIDI_PROGRAMCHANGE) || (inmode==cp && status==MIDI_CHANNELPRESSURE) || (inmode==pa && status==MIDI_POLYKEYPRESSURE) || ((inmode==pblsb || inmode==pb) && status==MIDI_PITCHBEND) || (inmode==nonn && status==MIDI_NOTEON) || (inmode==nonv && (status==MIDI_NOTEON || status==MIDI_NOTEOFF)) || ((inmode==noffn || inmode==noffv) && status==MIDI_NOTEOFF) || (inmode==clock && status==MIDI_TIMINGCLOCK) ) { switch (inmode) { case pc: case pcinc: case pcdec: case cp: case pblsb: case noffn: incc1=data1; idata=data1; odata=data1; break; case nonn: idata=data1; break; case nonv: if (status==MIDI_NOTEOFF) data2=0; break; case NRPN: inisNRPN=true; break; case NRPNlsb: inisNRPN=true; incc1=data1; break; case RPN: inisRPN=true; break; case RPNlsb: inisRPN=true; incc1=data1; break; case clock: case songposition: case songselect: chin1=channel; break; default: break; } if (channel==chin1) { if (inmode==pb) { if ((idata14>=(lolimit1<<7) && idata14<=(hilimit1|(hilimit1<<7))) || param[kRangeMode]>=0.5f && param[kRangeMode]<0.8f) { odata14 = idata14; if (lolimit1==hilimit1) odata14 = (low1|(low1<<7)+high1|(high1<<7))/2 + offset1|(offset1<<7); else if (param[kRangeMode]<0.3f) { //stretch clipped input to full range odata14 = MAP_TO_MIDI(idata14,0,16383,lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); //then limit output if (odata14>(high1|(high1<<7))) odata14=(high1|(high1<<7)); else if (odata14<(low1|(low1<<7))) odata14=(low1|(low1<<7)); } else if (param[kRangeMode]<0.5f) odata14 = MAP_TO_MIDI(idata14,low1|(low1<<7),high1|(high1<<7),lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); else if (param[kRangeMode]<0.8f) { odata14 = MAP_TO_MIDI(idata14,0,16383,low1|(low1<<7),high1|(high1<<7)); odata14 = MAP_TO_MIDI(idata14,low1|(low1<<7),high1|(high1<<7),lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); } else { if (odata14>(high1|(high1<<7))) odata14=(high1|(high1<<7)); else if (odata14<(low1|(low1<<7))) odata14=(low1|(low1<<7)); } if (odata14>16383) odata14=16383; else if (odata14<0) odata14=0; odata = (odata14 & 0x3f80) >> 7; olsb = odata14 & 0x007f; inis14bit = true; // send old message if "thru" is on if (channel==chout1 && outmode==pb) discard=true; sendout=true; } else if (param[kThru]<0.5f) discard=true; //outside range } else if (inmode==pcinc && proginc) sendout=true; else if (inmode==pcdec && progdec) sendout=true; else if (inmode==cc14 && incc1<32 && (data1==incc1 || data1==(incc1+32))) { int finecc = incc1+32; if (param[kThru]<0.5) discard=true; if (data1==incc1) cc14msb[incc1][channel] = data2; else if (data1==finecc) cc14lsb[incc1][channel] = data2; idata14 = (cc14lsb[incc1][channel])|(cc14msb[incc1][channel]<<7); if ((idata14>=(lolimit1<<7) && idata14<=(hilimit1|(hilimit1<<7))) || param[kRangeMode]>=0.5f && param[kRangeMode]<0.8f) { if (lolimit1==hilimit1) odata14=(low1|(low1<<7)+high1|(high1<<7))/2 + offset1|(offset1<<7); else if (param[kRangeMode]<0.3f) { //stretch clipped input to full range odata14 = MAP_TO_MIDI(idata14,0,16383,lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); //then limit output if (odata14>(high1|(high1<<7))) odata14=(high1|(high1<<7)); else if (odata14<(low1|(low1<<7))) odata14=(low1|(low1<<7)); } else if (param[kRangeMode]<0.5f) odata14 = MAP_TO_MIDI(idata14,low1|(low1<<7),high1|(high1<<7),lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); else if (param[kRangeMode]<0.8f) { odata14 = MAP_TO_MIDI(idata14,0,16383,low1|(low1<<7),high1|(high1<<7)); odata14 = MAP_TO_MIDI(odata14,low1|(low1<<7),high1|(high1<<7),lolimit1|(lolimit1<<7),hilimit1|(hilimit1<<7)) + offset1|(offset1<<7); } if (odata14>16383) odata14=16383; else if (odata14<0) odata14=0; odata = (odata14 & 0x3f80) >> 7; //odata = roundToInt((double)odata14*0.0077519379844961240310077519379845); olsb = odata14 & 0x007f; inis14bit = true; sendout=true; } else if (param[kThru]<0.5f) discard=true; //outside range } else if (inmode==clock) sendout=true; else if (data1==incc1) { //clip input here, unless stretching input to fit in input range if ((idata>=lolimit1 && idata<=hilimit1) || param[kRangeMode]>=0.5f && param[kRangeMode]<0.8f) { if (inmode==NRPNlsb) idata=data1; if (lolimit1==hilimit1) odata=(low1+high1)/2 + offset1; else if (param[kRangeMode]<0.3f) //clip/limit { //stretch clipped input to full range odata = MAP_TO_MIDI(idata,0,127,lolimit1,hilimit1) + offset1; //then limit output if (odata>high1) odata=high1; else if (odata<low1) odata=low1; } else if (param[kRangeMode]<0.5f) //clip/stretch { //stretch clipped input to output range odata = MAP_TO_MIDI(idata,low1,high1,lolimit1,hilimit1) + offset1; } else if (param[kRangeMode]<0.8f){ //stretch/stretch //stretch 0-127 to input range odata = MAP_TO_MIDI(idata,lolimit1,hilimit1,0,127); //then stretch input range to output range odata = MAP_TO_MIDI(odata,low1,high1,lolimit1,hilimit1) + offset1; } else { if (odata>high1) odata=high1; else if (odata<low1) odata=low1; } if (odata>127) odata=127; else if (odata<0) odata=0; if (inmode==nonv && status==MIDI_NOTEOFF) odata=0; // send old message if "thru" is on switch (inmode) { case cc: case pa: if (channel==chout1 && data1==outcc1 && outmode==inmode) discard=true; break; case pc: case cp: if (channel==chout1 && outmode==inmode) discard=true; break; case pblsb: if (channel==chout1 && (outmode==pb || outmode==pblsb)) discard=true; break; case NRPNlsb: if (channel==chout1 && (outmode==NRPN || outmode==NRPNlsb)) discard=true; break; default: break; } //create new message sendout=true; } else if (param[kThru]<0.5f) discard=true; //outside range } } } if (sendout) { // create new message VstMidiEvent outmsg = tomod; if (outmode==drop) { sendout=false; } if (outmode==cc) { if (roundToInt(param[kNRPNout]*100.f)==0 || (FLOAT_TO_MIDI_X(param[kCCout])==-1)) { outmsg.midiData[0] = MIDI_CONTROLCHANGE | chout1; outmsg.midiData[1] = outcc1; outmsg.midiData[2] = odata; } else { targetcc=odata; sendout=false; smoothcc[chout1]=outcc1; } } if (outmode==cc14) { if (roundToInt(param[kNRPNout]*100.f)==0) { if (outcc1 < 32) { outmsg.midiData[0] = MIDI_CONTROLCHANGE | chout1; outmsg.midiData[1] = outcc1; outmsg.midiData[2] = odata; outputs[0].push_back(outmsg); outmsg.midiData[1] = outcc1 + 32; if (!inis14bit) { if (odata>64) olsb = odata; else olsb = 0; } outmsg.midiData[2] = olsb; outputs[0].push_back(outmsg); sendout=false; } else { outmsg.midiData[0] = MIDI_CONTROLCHANGE | chout1; outmsg.midiData[1] = outcc1; outmsg.midiData[2] = odata; } } else { targetcc=olsb|(odata<<7); sendout=false; smoothcc[chout1]=outcc1 + 1000; } } else if (outmode==pc) { //program change outmsg.midiData[0] = MIDI_PROGRAMCHANGE | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = 0; } else if (outmode==pc) { //program change outmsg.midiData[0] = MIDI_PROGRAMCHANGE | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = 0; } else if (outmode==pcinc) { //program change++ odata = lastSentPC[chout1]+1; if (odata>high1) odata=low1; outmsg.midiData[0] = MIDI_PROGRAMCHANGE | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = 0; } else if (outmode==pcdec) { //program change-- odata = lastSentPC[chout1]-1; if (odata<low1) odata=high1; outmsg.midiData[0] = MIDI_PROGRAMCHANGE | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = 0; } else if (outmode==cp) { //channel pressure outmsg.midiData[0] = MIDI_CHANNELPRESSURE | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = 0; } else if (outmode==pa) { //aftertouch outmsg.midiData[0] = MIDI_POLYKEYPRESSURE | chout1; outmsg.midiData[1] = outcc1; outmsg.midiData[2] = odata; } else if (outmode==pb) { //pitch bend if (!inis14bit) { if (odata>64) olsb = odata; else olsb = 0; } if (param[kCCout]<0.5f) { outmsg.midiData[0] = MIDI_PITCHBEND | chout1; outmsg.midiData[1] = olsb; outmsg.midiData[2] = odata; } else { targetpb=olsb|(odata<<7); sendout=false; done[chout1]=false; } } else if (outmode==pblsb) { //pitch bend (LSB) outmsg.midiData[0] = MIDI_PITCHBEND | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = outcc1; } else if (outmode==NRPN) { //NRPN if (outcc1>=0 && send>0) { VstMidiEvent ncoarse = inputs[0][i]; ncoarse.midiData[0] = MIDI_CONTROLCHANGE | chout1; ncoarse.midiData[1] = 99; ncoarse.midiData[2] = outcc1; outputs[0].push_back(ncoarse); VstMidiEvent nfine = inputs[0][i]; nfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; nfine.midiData[1] = 98; nfine.midiData[2] = outputnrpn1; outputs[0].push_back(nfine); VstMidiEvent dcoarse = inputs[0][i]; dcoarse.midiData[0] = MIDI_CONTROLCHANGE | chout1; dcoarse.midiData[1] = 6; dcoarse.midiData[2] = odata; outputs[0].push_back(dcoarse); VstMidiEvent dfine = inputs[0][i]; dfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; dfine.midiData[1] = 38; if (!inis14bit) { if (odata>64) olsb = odata; else olsb = 0; } dfine.midiData[2] = olsb; outputs[0].push_back(dfine); sendout=false; } } else if (outmode==NRPNlsb) { //NRPN LSB if (outcc1>=0 && send>0) { VstMidiEvent ncoarse = inputs[0][i]; ncoarse.midiData[0] = MIDI_CONTROLCHANGE | chout1; ncoarse.midiData[1] = 99; ncoarse.midiData[2] = outcc1; outputs[0].push_back(ncoarse); VstMidiEvent nfine = inputs[0][i]; nfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; nfine.midiData[1] = 98; nfine.midiData[2] = outputnrpn1; outputs[0].push_back(nfine); VstMidiEvent dfine = inputs[0][i]; dfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; dfine.midiData[1] = 38; dfine.midiData[2] = odata; outputs[0].push_back(dfine); sendout=false; } } else if (outmode==RPN) { //RPN if (outcc1>=0 && send>0) { VstMidiEvent ncoarse = inputs[0][i]; ncoarse.midiData[0] = MIDI_CONTROLCHANGE | chout1; ncoarse.midiData[1] = 101; ncoarse.midiData[2] = outcc1; outputs[0].push_back(ncoarse); VstMidiEvent nfine = inputs[0][i]; nfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; nfine.midiData[1] = 100; nfine.midiData[2] = outputnrpn1; outputs[0].push_back(nfine); VstMidiEvent dcoarse = inputs[0][i]; dcoarse.midiData[0] = MIDI_CONTROLCHANGE | chout1; dcoarse.midiData[1] = 6; dcoarse.midiData[2] = odata; outputs[0].push_back(dcoarse); VstMidiEvent dfine = inputs[0][i]; dfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; dfine.midiData[1] = 38; if (!inis14bit) { if (odata>64) olsb = odata; else olsb = 0; } dfine.midiData[2] = olsb; outputs[0].push_back(dfine); sendout=false; } } else if (outmode==RPNlsb) { //RPN LSB if (outcc1>=0 && send>0) { VstMidiEvent ncoarse = inputs[0][i]; ncoarse.midiData[0] = MIDI_CONTROLCHANGE | chout1; ncoarse.midiData[1] = 101; ncoarse.midiData[2] = outcc1; outputs[0].push_back(ncoarse); VstMidiEvent nfine = inputs[0][i]; nfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; nfine.midiData[1] = 100; nfine.midiData[2] = outputnrpn1; outputs[0].push_back(nfine); VstMidiEvent dfine = inputs[0][i]; dfine.midiData[0] = MIDI_CONTROLCHANGE | chout1; dfine.midiData[1] = 38; dfine.midiData[2] = odata; outputs[0].push_back(dfine); sendout=false; } } else if (outmode==nonn) { //Note On # outmsg.midiData[0] = MIDI_NOTEON | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = outcc1; if (FLOAT_TO_MIDI(param[kNRPNout])>0) { //fix this part... queue a noteoff for later VstMidiEvent noteoff = outmsg; noteoff.midiData[0] = MIDI_NOTEOFF | chout1; noteoff.midiData[2] = 0; //noteoff.deltaFrames += FLOAT_TO_MIDI(param[kNRPNout]); outputs[0].push_back(outmsg); outputs[0].push_back(noteoff); sendout=false; } } else if (outmode==nonv) { //Note On Vel if (status==MIDI_NOTEOFF && inmode==nonv) odata = 0; outmsg.midiData[0] = MIDI_NOTEON | chout1; outmsg.midiData[1] = outcc1; outmsg.midiData[2] = odata; } else if (outmode==noffn) { //Note Off # outmsg.midiData[0] = MIDI_NOTEOFF | chout1; outmsg.midiData[1] = odata; outmsg.midiData[2] = outcc1; } else if (outmode==noffv) { //Note Off Vel outmsg.midiData[0] = MIDI_NOTEOFF | chout1; outmsg.midiData[1] = outcc1; outmsg.midiData[2] = odata; } else if (outmode==clock) { outmsg.midiData[0] = (char)MIDI_TIMINGCLOCK; outmsg.midiData[1] = 0; outmsg.midiData[2] = 0; } else if (outmode==songselect) { outmsg.midiData[0] = (char)MIDI_SONGSELECT; outmsg.midiData[1] = odata; outmsg.midiData[2] = 0; } if (sendout) { outputs[0].push_back(outmsg); if (outmode==pc || outmode==pcinc || outmode==pcdec) { lastSentPC[chout1] = outmsg.midiData[1]; } } if (param[kThru]<0.5f) discard=true; //block converted } else if (param[kThru]==1.0f) discard=true; //thru converted only if (param[kThru]==0.f) discard=true; //block all //send the original message if (!discard) outputs[0].push_back(tomod); } if (outmode==pb) for (int ch=0;ch<16;ch++) { if (!done[ch]) { //pitch bend smoothing for (int j=0;j<sampleFrames;j++) { if (counter==0) { counter=roundToInt(sampleRate*0.002f); lastpb = smooth(targetpb,lastpb,param[kNRPNout]); int pb2=(lastpb & 0x3F80)>>7; int pb1=(lastpb & 0x007F); VstMidiEvent pb; pb.deltaFrames=j; pb.midiData[0] = MIDI_PITCHBEND | ch; pb.midiData[1] = pb1; pb.midiData[2] = pb2; if (!done[ch]) outputs[0].push_back(pb); if (lastpb==targetpb) done[ch]=true; } counter--; } } } else if (outmode==cc || outmode==cc14) for (int ch=0;ch<16;ch++) { if (smoothcc[ch]>-1) { //cc smoothing bool is14bit = outmode==cc14; for (int j=0;j<sampleFrames;j++) { if (counter==0) { counter=roundToInt(sampleRate*(0.005f+0.002*param[kNRPNout])); lastcc = smooth(targetcc,lastcc,param[kNRPNout],is14bit); if (is14bit) { VstMidiEvent msb; msb.deltaFrames=j; msb.midiData[0] = MIDI_CONTROLCHANGE | ch; msb.midiData[1] = smoothcc[ch]-1000; msb.midiData[2] = (lastcc&0x3f80)>>7; VstMidiEvent lsb; lsb.deltaFrames=j; lsb.midiData[0] = MIDI_CONTROLCHANGE | ch; lsb.midiData[1] = smoothcc[ch]-1000 + 32; lsb.midiData[2] = lastcc&0x007f; if (smoothcc[ch]>-1) { outputs[0].push_back(msb); outputs[0].push_back(lsb); } } else { VstMidiEvent cc; cc.deltaFrames=j; cc.midiData[0] = MIDI_CONTROLCHANGE | ch; cc.midiData[1] = smoothcc[ch]; cc.midiData[2] = lastcc&0x007f; if (smoothcc[ch]>-1) outputs[0].push_back(cc); } if (lastcc==targetcc) smoothcc[ch]=-1; } counter--; } } } } int MidiConverter::smooth(int newvalue, int oldvalue, float inertia, bool is14bit) { float change = (float)(newvalue-oldvalue)*(1.0f-inertia*0.95f); //make sure change isn't smaller than 1 if (change<1.0f && change>0.0f) change=1.0f; else if (change<0.0f && change>-1.0f) change=-1.0f; if (change<0.f) newvalue=oldvalue-roundToInt(-change); else newvalue=oldvalue+roundToInt(change); if (is14bit) { if (newvalue>0x7fff) newvalue = 0x7fff; } else { if (newvalue>0x7f) newvalue = 0x7f; } if (newvalue<0) newvalue = 0; return newvalue; }
43.738397
160
0.482732
nonameentername
76090310b2814e60bfb752addad00581e480c9c5
10,370
cpp
C++
vive_bridge/src/vive_interface.cpp
mortaas/vive_rrcc
cdec4645dd3bc1510e15af4be20c7f8dfef321e0
[ "MIT" ]
1
2020-05-14T02:19:56.000Z
2020-05-14T02:19:56.000Z
vive_bridge/src/vive_interface.cpp
mortaas/vive_rrcc
cdec4645dd3bc1510e15af4be20c7f8dfef321e0
[ "MIT" ]
null
null
null
vive_bridge/src/vive_interface.cpp
mortaas/vive_rrcc
cdec4645dd3bc1510e15af4be20c7f8dfef321e0
[ "MIT" ]
null
null
null
#include "vive_bridge/vive_interface.h" // Default functions for logging inline void DefaultDebugMsgCallback(const std::string &msg) { std::cerr << "VR Debug: " << msg << std::endl; } inline void DefaultInfoMsgCallback(const std::string &msg) { std::cerr << "VR Info: " << msg << std::endl; } inline void DefaultWarnMsgCallback(const std::string &msg) { std::cerr << "VR Warn: " << msg << std::endl; } inline void DefaultErrorMsgCallback(const std::string &msg) { std::cerr << "VR Error: " << msg << std::endl; } inline void DefaultFatalMsgCallback(const std::string &msg) { std::cerr << "VR Fatal: " << msg << std::endl; } std::map<vr::TrackedPropertyError, std::string> TrackedPropErrorStrings { { vr::TrackedProp_Success, "The property request was successful"}, { vr::TrackedProp_WrongDataType, "The property was requested with the wrong typed function." }, { vr::TrackedProp_WrongDeviceClass, "The property was requested on a tracked device with the wrong class." }, { vr::TrackedProp_BufferTooSmall, "The string property will not fit in the provided buffer. The buffer size needed is returned." }, { vr::TrackedProp_UnknownProperty, "The property enum value is unknown." }, { vr::TrackedProp_InvalidDevice, "The tracked device index was invalid." }, { vr::TrackedProp_CouldNotContactServer, "OpenVR could not contact vrserver to query the device for this property." }, { vr::TrackedProp_ValueNotProvidedByDevice, "The driver for this device returned that it does not provide this specific property for this device." }, { vr::TrackedProp_StringExceedsMaximumLength, "The string property value returned by a driver exceeded the maximum property length of 32k." } }; ViveInterface::ViveInterface() : VR_DEBUG(DefaultDebugMsgCallback), VR_INFO(DefaultInfoMsgCallback), VR_WARN(DefaultWarnMsgCallback), VR_ERROR(DefaultErrorMsgCallback), VR_FATAL(DefaultFatalMsgCallback) { } ViveInterface::~ViveInterface() { } bool ViveInterface::Init(int argc, char **argv) { /** * Initialize the OpenVR API and get access to the vr::IVRSystem interface. * The vr::IVRSystem interface provides access to display configuration information, * tracking data, distortion functions, controller state, events, and device properties. */ vr::EVRInitError peError = vr::VRInitError_None; pHMD_ = vr::VR_Init(&peError, vr::VRApplication_Background); if (peError != vr::VRInitError_None) { pHMD_ = nullptr; VR_FATAL("OpenVR API initialization failed: " + std::string(vr::VR_GetVRInitErrorAsEnglishDescription(peError) ) ); return false; } // // Camera interface // pCamera_ = INVALID_TRACKED_CAMERA_HANDLE; // pCamera_ = vr::VRTrackedCamera(); // if (!pCamera_) { // VR_WARN("Camera interface initialization failed"); // } else { // // Check if camera is available // bool bHasCamera = false; // vr::EVRTrackedCameraError nCameraError = pCamera_->HasCamera(vr::k_unTrackedDeviceIndex_Hmd, &bHasCamera); // if (nCameraError == vr::VRTrackedCameraError_None && bHasCamera) { // // Check firmware description of camera to ensure that the communication is valid // vr::TrackedPropertyError pError = vr::TrackedProp_UnknownProperty; // std::string string_prop = GetStringProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_CameraFirmwareDescription_String, &pError); // if (pError != vr::TrackedProp_Success) { // VR_ERROR("Error occurred when getting camera firmware description from HMD: " + TrackedPropErrorStrings[pError] ); // } else { // VR_INFO("Camera is available with firmware: \n" + string_prop); // } // } else { // VR_WARN("Camera is not available"); // } // } VR_INFO("OpenVR API initialization succeeded"); return true; } void ViveInterface::Shutdown() { /** * Shuts down the connection to the VR hardware and cleans up the OpenVR API. * The vr::IVRSystem pointer returned by vr::VR_Init will be invalid after this call is made. */ // Check if the OpenVR API is initialized if (pHMD_) { vr::VR_Shutdown(); pHMD_ = nullptr; } } std::string ViveInterface::GetStringProperty(vr::TrackedDeviceIndex_t unDeviceIndex, vr::TrackedDeviceProperty prop, vr::TrackedPropertyError *pError) { /** * Returns the static string property of a tracked device. * * vr::TrackedDeviceIndex unDeviceIndex - Index of the device to get the property for. * vr::TrackedDeviceProperty prop - Which property to get. */ uint32_t unBufferSize = pHMD_->GetStringTrackedDeviceProperty(unDeviceIndex, prop, nullptr, 0, pError); // Return empty string if the property is empty if (unBufferSize == 0) { return ""; } // Get string property char *pchValue = new char[unBufferSize]; unBufferSize = pHMD_->GetStringTrackedDeviceProperty(unDeviceIndex, prop, pchValue, unBufferSize, pError); std::string strValue = pchValue; delete [] pchValue; return strValue; } void ViveInterface::GetControllerState(const unsigned int &device_index, std::vector<float> &axes, std::vector<int> &buttons) { /** * Get controller state and map it to axes and buttons */ pHMD_->GetControllerState(device_index, &controller_state_, sizeof(vr::VRControllerState_t) ); // Axes axes[0] = controller_state_.rAxis[0].x; axes[1] = controller_state_.rAxis[0].y; axes[2] = controller_state_.rAxis[1].x; // Buttons buttons.assign(13, 0); if (vr::ButtonMaskFromId(vr::k_EButton_ApplicationMenu) & controller_state_.ulButtonPressed) { buttons[0] = 1; } if (vr::ButtonMaskFromId(vr::k_EButton_Dashboard_Back) & controller_state_.ulButtonPressed) { buttons[1] = 1; } if (vr::ButtonMaskFromId(vr::k_EButton_SteamVR_Touchpad) & controller_state_.ulButtonPressed) { buttons[2] = 1; } if (vr::ButtonMaskFromId(vr::k_EButton_SteamVR_Trigger) & controller_state_.ulButtonPressed) { buttons[3] = 1; } } bool ViveInterface::PollNextEvent(unsigned int &event_type, unsigned int &device_index) { /** * Returns true if there is any event waiting in the event queue, * and also returns the event type and device index of this event. * Returns event type VREvent_None (0) and device index k_unTrackedDeviceIndexInvalid (4294967295) * if there is no event waiting in the event queue. */ if (!pHMD_->PollNextEvent(&event_, sizeof(event_) ) ) { event_type = vr::VREvent_None; device_index = vr::k_unTrackedDeviceIndexInvalid; return false; } else { event_type = event_.eventType; device_index = event_.trackedDeviceIndex; return true; } } void ViveInterface::GetDeviceSN(const unsigned int &device_index, std::string &device_sn) { /** * Get the serial number of a tracked device */ vr::TrackedPropertyError pError = vr::TrackedProp_UnknownProperty; device_sn = GetStringProperty(device_index, vr::Prop_SerialNumber_String, &pError); if (pError != vr::TrackedProp_Success) { VR_ERROR("Error occurred when getting serial number from tracked device: " + TrackedPropErrorStrings[pError] ); } } void ViveInterface::GetDevicePose(const unsigned int &device_index, float m[3][4]) { /** * Get the pose of a tracked device * This pose is represented as the top 3 rows of a homogeneous transformation matrix */ for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) m[i][j] = device_poses_[device_index].mDeviceToAbsoluteTracking.m[i][j]; } void ViveInterface::GetDeviceVelocity(const unsigned int &device_index, float linear[3], float angular[3]) { /** * Get the linear and angular velocity (twist) of a tracked device */ for (int i = 0; i < 3; i++) { linear[i] = device_poses_[device_index].vVelocity.v[i]; angular[i] = device_poses_[device_index].vAngularVelocity.v[i]; } } unsigned char ViveInterface::GetDeviceClass(const unsigned int &device_index) { /** * Get the class of a tracked device */ return pHMD_->GetTrackedDeviceClass(device_index); } unsigned char ViveInterface::GetControllerRole(const unsigned int &device_index) { /** * Get the controller role of a tracked device, e.g. left or right hand */ return pHMD_->GetControllerRoleForTrackedDeviceIndex(device_index); } bool ViveInterface::PoseIsValid(const unsigned int &device_index) { /** * Check if the pose of a tracked device is valid */ return (device_poses_[device_index].eTrackingResult == vr::TrackingResult_Running_OK && device_poses_[device_index].bPoseIsValid && device_poses_[device_index].bDeviceIsConnected); } void ViveInterface::Update() { /* * Calculates updated poses and velocities for all tracked devices * TrackingUniverseRawAndUncalibrated - provides poses relative to the hardware-specific coordinate system in the driver */ pHMD_->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseSeated, 0, device_poses_, vr::k_unMaxTrackedDeviceCount); } void ViveInterface::TriggerHapticPulse(const unsigned int &device_index, const unsigned short &duration) { /* * Triggers a single haptic pulse on a controller given its device index, and the pulse duration 0-3999 µs ("strength") */ if (GetDeviceClass(device_index) == vr::TrackedDeviceClass_Controller) { unsigned short usDurationMicroSec = duration; usDurationMicroSec = std::min(usDurationMicroSec, (unsigned short) 3999); usDurationMicroSec = std::max(usDurationMicroSec, (unsigned short) 0); pHMD_->TriggerHapticPulse(device_index, 0, usDurationMicroSec); } } // Logging to ROS void ViveInterface::SetDebugMsgCallback(DebugMsgCallback fn) { VR_DEBUG = fn; } void ViveInterface::SetInfoMsgCallback(InfoMsgCallback fn) { VR_INFO = fn; } void ViveInterface::SetWarnMsgCallback(WarnMsgCallback fn) { VR_WARN = fn; } void ViveInterface::SetErrorMsgCallback(ErrorMsgCallback fn) { VR_ERROR = fn; } void ViveInterface::SetFatalMsgCallback(FatalMsgCallback fn) { VR_FATAL = fn; }
38.838951
152
0.694021
mortaas
760953b3829e16f1b8f24601633c3caff4c06347
1,443
cpp
C++
Day2/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
4
2021-12-06T17:14:00.000Z
2021-12-10T06:29:35.000Z
Day2/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
null
null
null
Day2/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
null
null
null
#include "aoc21/helpers.h" #include <set> namespace { using Movement = std::pair<char, int>; constexpr std::string_view DIRECTION_FORWARD("forward"); constexpr std::string_view DIRECTION_UP("up"); constexpr std::string_view DIRECTION_DOWN("down"); std::set<std::string_view> DIRECTIONS = { DIRECTION_FORWARD, DIRECTION_UP, DIRECTION_DOWN, }; }; int main(int argc, char** argv) { aoc::AutoTimer t; auto f = aoc::open_argv_1(argc, argv); // Part 1 int virt = 0; int horiz = 0; // Part 2 int depth = 0; const auto parse_movement = [](const std::string &s) { const auto pos = s.find(' '); assert(pos != std::string::npos); const std::string_view direction(&s[0], pos); const int value = ::atoi(&s[pos + 1]); assert(DIRECTIONS.find(direction) != DIRECTIONS.end()); Movement m = std::make_pair(direction[0], value); return m; }; const auto walk_path = [&](const std::string& line) { const Movement m = parse_movement(line); switch (m.first) { case 'd': virt += m.second; break; case 'u': virt -= m.second; break; case 'f': horiz += m.second; depth += (m.second * virt); break; default: break; } }; std::string l; while (aoc::getline(f, l)) { walk_path(l); } aoc::print_results((virt * horiz), (horiz * depth)); return 0; }
20.323944
60
0.575191
baldwinmatt
7609549b84d30b06941f2bc18f9bdcbb36f4d85e
2,930
cpp
C++
tree/binary_tree/103_binary-tree-zigzag-level-order-traversal.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
tree/binary_tree/103_binary-tree-zigzag-level-order-traversal.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
tree/binary_tree/103_binary-tree-zigzag-level-order-traversal.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
// Author: b1tank // Email: b1tank@outlook.com //================================= /* 103_binary-tree-zigzag-level-order-traversal LeetCode Solution: - BFS (deque rather than queue) - DFS (recursive) (potentially O(logN) space for auto-cast enabled language like Java, Python) */ #include <iostream> #include <vector> #include <deque> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { void dfs(TreeNode* cur, int level, vector<deque<int>>& v_dq) { // use reference !!!! int n = v_dq.size(); if (level >= n) { deque<int> v{cur->val}; v_dq.push_back(v); } else { if (level % 2 == 0) { v_dq[level].push_back(cur->val); } else { v_dq[level].push_front(cur->val); } } if (cur->left) { dfs(cur->left, level+1, v_dq); } if (cur->right) { dfs(cur->right, level+1, v_dq); } return; } public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; if (root == nullptr) return res; vector<deque<int>> res_dq; dfs(root, 0, res_dq); for (auto i = 0; i < res_dq.size(); ++i) { vector<int> tmp(res_dq[i].begin(), res_dq[i].end()); res.push_back(tmp); } return res; // vector<vector<int>> res; // if (root == nullptr) return res; // deque<TreeNode*> dq; // dq.push_back(root); // bool left2right = true; // int count = 0; // int level = dq.size(); // vector<int> tmp; // TreeNode* cur{nullptr}; // while (!dq.empty()) { // cur = left2right ? dq.front() : dq.back(); // if (left2right) { // dq.pop_front(); // if (cur->left) dq.push_back(cur->left); // if (cur->right) dq.push_back(cur->right); // } else { // dq.pop_back(); // if (cur->right) dq.push_front(cur->right); // if (cur->left) dq.push_front(cur->left); // } // tmp.push_back(cur->val); // ++count; // if (count == level) { // res.push_back(tmp); // tmp.clear(); // count = 0; // level = dq.size(); // left2right = !left2right; // } // } // return res; } };
30.206186
99
0.454949
b1tank
760ab8227a4933c0797445037a7ee0c712dca22c
1,103
cpp
C++
Other/Additional Practice 14.12.2019/rightWayToAllocateDynamicMatrix.cpp
terziev-viktor/FMI-UP-2019-2020
1974eec4677257229dcb5f9327aed5dfb38d1f8c
[ "MIT" ]
4
2019-11-06T12:03:06.000Z
2020-02-24T18:33:11.000Z
Other/Additional Practice 14.12.2019/rightWayToAllocateDynamicMatrix.cpp
terziev-viktor/FMI-UP-2019-2020
1974eec4677257229dcb5f9327aed5dfb38d1f8c
[ "MIT" ]
null
null
null
Other/Additional Practice 14.12.2019/rightWayToAllocateDynamicMatrix.cpp
terziev-viktor/FMI-UP-2019-2020
1974eec4677257229dcb5f9327aed5dfb38d1f8c
[ "MIT" ]
3
2019-11-27T17:13:59.000Z
2020-02-24T18:33:15.000Z
#include <iostream> void deleteMatrix(int** matrix, size_t rows) { for(int i = 0; i < rows; ++i) { delete[] matrix[i]; } delete[] matrix; } int** allocateMatrixByRowsAndCols(size_t n, size_t m) { int** matrix = new (std::nothrow) int* [n]; if(matrix == nullptr) { // if operator new can't allocate memory on the heap return nullptr; // return nullptr pointer. But for this, we should write } // option (std::nothrow) after operator new! for(size_t i = 0; i < n; ++i) { matrix[i] = new (std::nothrow) int[m]; // same stuff here if(matrix[i] == nullptr) { // if operator new return nullptr, we should deleteMatrix(matrix, i); // clean all dynamic memory which we allocate before return nullptr; // this moment, and return nullptr } } return matrix; // if all dynamic memory is allocate correctly, we return pointer // to this memory } int main() { size_t n, m; std::cin >> n >> m; int** matrix = allocateMatrixByRowsAndCols(n, m); if(matrix != nullptr) { // do stuff with matrix } if(matrix != nullptr) { deleteMatrix(matrix, n); } return 0; }
25.068182
81
0.646419
terziev-viktor
760fc027a88ce6e1c6af2ad87fc7e27045f77a01
3,959
hpp
C++
include/GlobalNamespace/NetworkPlayerEntitlementChecker_CachedTcs.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/NetworkPlayerEntitlementChecker_CachedTcs.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/NetworkPlayerEntitlementChecker_CachedTcs.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: NetworkPlayerEntitlementChecker #include "GlobalNamespace/NetworkPlayerEntitlementChecker.hpp" // Including type: EntitlementsStatus #include "GlobalNamespace/EntitlementsStatus.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Threading::Tasks namespace System::Threading::Tasks { // Forward declaring type: TaskCompletionSource`1<TResult> template<typename TResult> class TaskCompletionSource_1; // Forward declaring type: Task`1<TResult> template<typename TResult> class Task_1; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x24 #pragma pack(push, 1) // Autogenerated type: NetworkPlayerEntitlementChecker/CachedTcs class NetworkPlayerEntitlementChecker::CachedTcs : public ::Il2CppObject { public: // private System.Single kRefreshTime // Size: 0x4 // Offset: 0x10 float kRefreshTime; // Field size check static_assert(sizeof(float) == 0x4); // Padding between fields: kRefreshTime and: source char __padding0[0x4] = {}; // private readonly System.Threading.Tasks.TaskCompletionSource`1<EntitlementsStatus> _source // Size: 0x8 // Offset: 0x18 System::Threading::Tasks::TaskCompletionSource_1<GlobalNamespace::EntitlementsStatus>* source; // Field size check static_assert(sizeof(System::Threading::Tasks::TaskCompletionSource_1<GlobalNamespace::EntitlementsStatus>*) == 0x8); // private System.Single _creationTime // Size: 0x4 // Offset: 0x20 float creationTime; // Field size check static_assert(sizeof(float) == 0x4); // Creating value type constructor for type: CachedTcs CachedTcs(float kRefreshTime_ = {}, System::Threading::Tasks::TaskCompletionSource_1<GlobalNamespace::EntitlementsStatus>* source_ = {}, float creationTime_ = {}) noexcept : kRefreshTime{kRefreshTime_}, source{source_}, creationTime{creationTime_} {} // public System.Threading.Tasks.Task`1<EntitlementsStatus> get_task() // Offset: 0x11B3730 System::Threading::Tasks::Task_1<GlobalNamespace::EntitlementsStatus>* get_task(); // public System.Void SetResult(EntitlementsStatus status) // Offset: 0x11B3780 void SetResult(GlobalNamespace::EntitlementsStatus status); // public System.Boolean Refresh() // Offset: 0x11B3814 bool Refresh(); // public System.Void .ctor() // Offset: 0x11B36A8 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NetworkPlayerEntitlementChecker::CachedTcs* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::NetworkPlayerEntitlementChecker::CachedTcs::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NetworkPlayerEntitlementChecker::CachedTcs*, creationType>())); } }; // NetworkPlayerEntitlementChecker/CachedTcs #pragma pack(pop) static check_size<sizeof(NetworkPlayerEntitlementChecker::CachedTcs), 32 + sizeof(float)> __GlobalNamespace_NetworkPlayerEntitlementChecker_CachedTcsSizeCheck; static_assert(sizeof(NetworkPlayerEntitlementChecker::CachedTcs) == 0x24); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::NetworkPlayerEntitlementChecker::CachedTcs*, "", "NetworkPlayerEntitlementChecker/CachedTcs");
49.4875
255
0.731498
darknight1050
761bc7887fd6ad28909273d105e929189ccc8c0a
1,435
cpp
C++
shaders/src/sib_color_to_vector.cpp
caron/sitoa
52a0a4b35f51bccb6223a8206d04b40edc80071c
[ "Apache-2.0" ]
34
2018-02-01T16:13:48.000Z
2021-07-16T07:37:47.000Z
shaders/src/sib_color_to_vector.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
72
2018-02-16T17:30:41.000Z
2021-11-22T11:41:45.000Z
shaders/src/sib_color_to_vector.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
15
2018-02-15T15:36:58.000Z
2021-04-14T03:54:25.000Z
/************************************************************************************************************************************ Copyright 2017 Autodesk, Inc. 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 <ai.h> AI_SHADER_NODE_EXPORT_METHODS(SIBColorToVectorMethods); enum SIBColorToVectorParams { p_input, p_method, p_scale }; node_parameters { AiParameterRGB ( "input" , 1.0f , 1.0f , 1.0f ); AiParameterInt ( "method", 0 ); // Not implemented AiParameterFlt ( "scale" , 1.0f ); } node_initialize{} node_update{} node_finish{} shader_evaluate { AtRGB input = AiShaderEvalParamRGB(p_input); float scale = AiShaderEvalParamFlt(p_scale); sg->out.VEC().x = input.r * scale; sg->out.VEC().y = input.g * scale; sg->out.VEC().z = input.b * scale; }
33.372093
134
0.594425
caron
76211f9acf908b7c72af662ad7b24013fd460d73
2,619
cpp
C++
src/test/logging/log_record_test.cpp
abingham/ackward
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
[ "MIT" ]
null
null
null
src/test/logging/log_record_test.cpp
abingham/ackward
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
[ "MIT" ]
null
null
null
src/test/logging/log_record_test.cpp
abingham/ackward
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
[ "MIT" ]
null
null
null
#include <Python.h> #include <fstream> #include <boost/python/tuple.hpp> #include <boost/test/unit_test.hpp> #include <ackward/logging/LogRecord.hpp> using namespace ackward::logging; namespace { struct Fixture { Fixture() : rec (L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple()) {} LogRecord rec; }; } BOOST_AUTO_TEST_SUITE( logging ) BOOST_FIXTURE_TEST_SUITE( logRecord, Fixture ) BOOST_AUTO_TEST_CASE( constructor ) { LogRecord(L"foo", DEBUG(), L"/some/path/name", 101, L"Message", boost::python::tuple(), boost::python::make_tuple( boost::python::object(), boost::python::object(), boost::python::object())); } BOOST_AUTO_TEST_CASE( getMessage ) { BOOST_CHECK(rec.getMessage() == L"Message"); } BOOST_AUTO_TEST_CASE( args ) { boost::python::tuple args = rec.args; } // BOOST_AUTO_TEST_CASE( asctime ) // { // std::wstring at = rec.asctime; // } BOOST_AUTO_TEST_CASE( created ) { float c = rec.created; } // BOOST_AUTO_TEST_CASE( exc_info ) // { // boost::python::tuple ei = rec.exc_info; // } BOOST_AUTO_TEST_CASE( filename ) { std::wstring fn = rec.filename; } // BOOST_AUTO_TEST_CASE( funcName ) // { // std::wstring fn = rec.funcName; // } BOOST_AUTO_TEST_CASE( levelname ) { std::wstring ln = rec.levelname; } BOOST_AUTO_TEST_CASE( levelno ) { int ln = rec.levelno; } BOOST_AUTO_TEST_CASE( lineno ) { int ln = rec.lineno; } BOOST_AUTO_TEST_CASE( module ) { std::wstring m = rec.module; } BOOST_AUTO_TEST_CASE( msecs ) { float ms = rec.msecs; } // BOOST_AUTO_TEST_CASE( message ) // { // std::wstring m = rec.message; // } BOOST_AUTO_TEST_CASE( msg ) { std::wstring m = rec.msg; } BOOST_AUTO_TEST_CASE( name ) { std::wstring n = rec.name; } BOOST_AUTO_TEST_CASE( pathname ) { std::wstring pn = rec.pathname; } BOOST_AUTO_TEST_CASE( process ) { int p = rec.process; } BOOST_AUTO_TEST_CASE( processName ) { std::wstring pn = rec.processName; } BOOST_AUTO_TEST_CASE( relateveCreated ) { float rc = rec.relativeCreated; } #if PYTHON_MAJOR_VERSION == 3 BOOST_AUTO_TEST_CASE( stack_info ) { boost::python::object si = rec.stack_info; } #endif BOOST_AUTO_TEST_CASE( thread ) { unsigned long t = rec.thread; } BOOST_AUTO_TEST_CASE( threadName ) { std::wstring tn = rec.threadName; } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
16.166667
48
0.623139
abingham
76239975a019ff7a8095b7f41e9b9ffdbc5e73b6
6,277
cpp
C++
src/gammaGenerator.cpp
bhurwitz33/bayesembler
b1d8200d5ffa2ae3476391d9f35f26e5f14f517f
[ "MIT" ]
1
2019-01-10T15:43:12.000Z
2019-01-10T15:43:12.000Z
src/gammaGenerator.cpp
bhurwitz33/bayesembler
b1d8200d5ffa2ae3476391d9f35f26e5f14f517f
[ "MIT" ]
null
null
null
src/gammaGenerator.cpp
bhurwitz33/bayesembler
b1d8200d5ffa2ae3476391d9f35f26e5f14f517f
[ "MIT" ]
null
null
null
/* gammaGenerator.cpp - This file is part of the Bayesembler (v1.1.1) The MIT License (MIT) Copyright (c) 2014 Lasse Maretty and Jonas Andreas Sibbesen 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 <math.h> #include <gammaGenerator.h> #include <boost/math/constants/constants.hpp> #include <boost/lexical_cast.hpp> #include <boost/math/distributions/gamma.hpp> #include <boost/math/distributions/lognormal.hpp> #include <boost/random/variate_generator.hpp> #include <boost/random/gamma_distribution.hpp> #include <boost/random/lognormal_distribution.hpp> /* Gamma-sampler class */ SymmetricGammaGenerator::SymmetricGammaGenerator(HyperPrior * hyper_prior_in, int slice_iterations_in, double slice_window_size_in, int slice_max_windows_in, boost::random::mt19937* mt_rng_pt_in) { hyper_prior = hyper_prior_in; slice_iterations = slice_iterations_in; slice_window_size = slice_window_size_in; slice_max_windows = slice_max_windows_in; mt_rng_pt = mt_rng_pt_in; } // Init gamma with sample from the hyperprior double SymmetricGammaGenerator::initGamma() { return hyper_prior->init(); } double SymmetricGammaGenerator::generateGamma(ExpressionValueContainer expression) { vector<double> expression_s_plus; for (int i = 0; i < expression.getPlusSize(); i++) { int idx = expression.getPlus(i); double value = expression.getValue(idx); expression_s_plus.push_back(value); } // Init gamma and uniform sampler uniform_01_sampler_t sample_uniform_01(mt_rng_pt); double gamma_current = sample_uniform_01(); if (gamma_current < double_underflow) { gamma_current = double_underflow; } double gamma = gamma_current; for (int i=0; i < slice_iterations; i++) { double y = calculateLogDensity(expression_s_plus, gamma_current) + hyper_prior->calculateLogDensity(gamma_current) + log(1-sample_uniform_01()); // Find slice by "step-out" double left = gamma_current - sample_uniform_01() * slice_window_size; double right = left + slice_window_size; int j = floor(slice_max_windows*sample_uniform_01()); int k = slice_max_windows-1-j; // Truncate at zero if (left < double_underflow) { left = double_underflow; j = 0; } while (j > 0 && y < (calculateLogDensity(expression_s_plus, left) + hyper_prior->calculateLogDensity(left))) { left = left - slice_window_size; j--; if (left < double_underflow) { left = double_underflow; break; } } // Expand window to the right while (k > 0 && y < (calculateLogDensity(expression_s_plus, right) + hyper_prior->calculateLogDensity(right))) { right = right + slice_window_size; k--; } // Sample from the window until in slice gamma = sample_uniform_01()*(right-left) + left; while ( y >= (calculateLogDensity(expression_s_plus, gamma) + hyper_prior->calculateLogDensity(gamma))) { if (gamma < gamma_current) { left = gamma; gamma = sample_uniform_01()*(right-left) + left; } else { right = gamma; gamma = sample_uniform_01()*(right-left) + left; } } gamma_current = gamma; } return gamma; } double SymmetricGammaGenerator::calculateLogDensity(vector<double>& expression, double gamma) { int size = expression.size(); // Init prob with normalisation constant double prob = boost::math::lgamma(size*gamma) - size*boost::math::lgamma(gamma); for (int i=0; i < size; i++) { prob += (gamma-1)*log(expression[i]); } return prob; } FixedGammaGenerator::FixedGammaGenerator(double gamma_in) { gamma = gamma_in; } double FixedGammaGenerator::initGamma() { return gamma; } double FixedGammaGenerator::generateGamma(ExpressionValueContainer expression) { return gamma; } GammaHyperPrior::GammaHyperPrior(double shape_in, double scale_in, mt_rng_pt_t mt_rng_pt_in) { shape = shape_in; scale = scale_in; mt_rng_pt = mt_rng_pt_in; }; double GammaHyperPrior::init() { boost::random::gamma_distribution<> gamma_dist(shape, scale); boost::random::variate_generator<boost::random::mt19937*, boost::random::gamma_distribution<> > sample_gamma(mt_rng_pt, gamma_dist); double gamma = sample_gamma(); return gamma; } double GammaHyperPrior::calculateLogDensity(double gamma) { double prob = (shape-1)*log(gamma) - (gamma/scale); return prob; }; LogNormalHyperPrior::LogNormalHyperPrior(double location_in, double scale_in, mt_rng_pt_t mt_rng_pt_in) { location = location_in; scale = scale_in; mt_rng_pt = mt_rng_pt_in; } double LogNormalHyperPrior::init() { boost::random::lognormal_distribution<> lognormal_dist(location, scale); boost::random::variate_generator<boost::random::mt19937*, boost::random::lognormal_distribution<> > sample_gamma(mt_rng_pt, lognormal_dist); double gamma = sample_gamma(); return gamma; } double LogNormalHyperPrior::calculateLogDensity(double gamma) { double prob = - log(gamma) - pow(log(gamma)-location,2)/(2*pow(scale,2)); return prob; }
27.774336
197
0.703043
bhurwitz33
762404feb02085ab9c4d08f8b714f6676543d87a
430
hpp
C++
src/argument_interpreter.hpp
rikutons/mytreecode
c25f955f946afb5c9e2d6fd14357e01eb4ff19f9
[ "MIT" ]
null
null
null
src/argument_interpreter.hpp
rikutons/mytreecode
c25f955f946afb5c9e2d6fd14357e01eb4ff19f9
[ "MIT" ]
null
null
null
src/argument_interpreter.hpp
rikutons/mytreecode
c25f955f946afb5c9e2d6fd14357e01eb4ff19f9
[ "MIT" ]
null
null
null
#pragma once #include <string> using namespace std; class ArgumentInterpreter { public: int cnt = 1; double dt = 0.01; double t = 1; double eps_square = 0.1 * 0.1; double theta_square = 0.5; // [rad^2] int simulator_mode = -1; string input_filename = ""; string output_filename = "output.csv"; // 以下はinputfileが決まっている場合無効となる int n = 1000; double rsize = 1.0; ArgumentInterpreter(int argc, char *argv[]); };
21.5
46
0.672093
rikutons
762716444ca4d252701dbcb91ff2688701eda79d
467
hpp
C++
libs/modelmd3/include/sge/model/md3/load_flags.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/modelmd3/include/sge/model/md3/load_flags.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/modelmd3/include/sge/model/md3/load_flags.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_MODEL_MD3_LOAD_FLAGS_HPP_INCLUDED #define SGE_MODEL_MD3_LOAD_FLAGS_HPP_INCLUDED #include <sge/model/md3/load_flags_fwd.hpp> namespace sge::model::md3 { enum class load_flags { switch_yz, fcppt_maximum = switch_yz }; } #endif
20.304348
61
0.738758
cpreh
7627af6217dd98f6d344ed1aacc825ceb81214e7
3,461
cpp
C++
XRADDicomGUI/Sources/DisplayFunctions/DisplayTomogram_CTAcquisition.cpp
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
1
2021-04-02T16:47:00.000Z
2021-04-02T16:47:00.000Z
XRADDicomGUI/Sources/DisplayFunctions/DisplayTomogram_CTAcquisition.cpp
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
null
null
null
XRADDicomGUI/Sources/DisplayFunctions/DisplayTomogram_CTAcquisition.cpp
n-kulberg/xrad
3d089cc24d942db4649f1a50defbd69f01739ae2
[ "BSD-3-Clause" ]
3
2021-08-30T11:26:23.000Z
2021-09-23T09:39:56.000Z
/* Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine All rights reserved. This file is licensed under BSD-3-Clause license. See LICENSE file for details. */ /*! \file \date 4/23/2018 5:46:49 PM \author kovbas */ #include "pre.h" #include "DisplayTomogram_CTAcquisition.h" XRAD_BEGIN enum display_ct_options_t { display_ct_slices, display_ct_metadata, display_ct_DICOM_file_content, display_ct_current, display_ct_voltage, display_CTDI_vol, display_ct_thickness, display_ct_positions, exit_ct_display }; const vector<wstring> &options_ct_names() { static vector<wstring> options(exit_ct_display + 1); do_once { options[display_ct_slices] = L"Display CT Slices"; options[display_ct_metadata] = L"Display CT Metadata"; options[display_ct_DICOM_file_content] = L"Display DICOM-file content"; options[display_ct_current] = L"Display CT current"; options[display_ct_voltage] = L"Display CT voltage"; options[display_CTDI_vol] = L"Display CTDI vol"; options[display_ct_thickness] = L"Display CT slice thickness"; options[display_ct_positions] = L"Display CT slice position"; options[exit_ct_display] = L"Exit display"; } return options; } void DisplayTomogram_CTAcquisition(const CTAcquisition &ct, const wstring &title) { display_ct_options_t options{ display_ct_slices }; auto title_full{ title + L" [" + ct.series_description() + L"]" }; while (options != exit_ct_display) { try { options = static_cast<display_ct_options_t>(GetButtonDecision(title_full, options_ct_names())); switch (options) { case display_ct_slices: DisplayMathFunction3D(ct.load_ordered_slices(), title_full); break; case display_ct_metadata: ShowText(title_full, ct.summary_info()); break; case display_ct_DICOM_file_content: ShowText(title_full, ct.get_dicom_file_content(GetUnsigned("Enter number of frame.", 0, 0, ct.n_elements() - 1))); break; case display_ct_current: DisplayMathFunction(ct.currents(), 0, 1, title_full + L" Current", L"mA", L"Slice No"); break; case display_ct_voltage: DisplayMathFunction(ct.voltages(), 0, 1, title_full + L" Voltage", L"kV", L"Slice No"); break; case display_CTDI_vol: DisplayMathFunction(ct.CTDIvols(), 0, 1, title_full + L" CTDIVol", L"mGy?", L"Slice No"); break; case display_ct_thickness: DisplayMathFunction(ct.thickness(), 0, 1, title_full + L" Slice Thickness", L"mm", L"Slice No"); break; case display_ct_positions: { auto image_positions_patient{ct.image_positions_patient()}; RealFunctionF64 locations_z(image_positions_patient.size(), 0); static_assert(std::is_same<decltype(image_positions_patient)::value_type::value_type, decltype(locations_z)::value_type>::value, "Type mismatch."); locations_z.CopyData(image_positions_patient, [](double &x, const auto &p) {return x = p[0];}); DisplayMathFunction(locations_z, 0, 1, title_full + L" Slice Position", L"mm", L"Slice No"); } break; } } catch (canceled_operation &) { // нажатие кнопки cancel в любом диалоговом окне, включая прогресс. // (например, отмена ошибочного выбранной команды без необходимости // дожидаться ее завершения) } catch (quit_application &) { // команда принудительного выхода из программы throw; } catch (exception &ex) { // все остальное, включая нехватку памяти ShowString("An error occured", ex.what()); } } } XRAD_END
29.084034
118
0.726091
n-kulberg
7629aa911a2a82f7aee1da1daeb7117fa133138d
5,244
cpp
C++
src/classes/controller/controller.cpp
kevinxtung/MICE
6559c8d242893f0697f64853ab49688198e9692d
[ "MIT" ]
null
null
null
src/classes/controller/controller.cpp
kevinxtung/MICE
6559c8d242893f0697f64853ab49688198e9692d
[ "MIT" ]
6
2018-05-14T23:38:17.000Z
2018-05-18T23:38:06.000Z
src/classes/controller/controller.cpp
kevinxtung/MICE
6559c8d242893f0697f64853ab49688198e9692d
[ "MIT" ]
null
null
null
#include "controller.h" #include "classes/topping/topping.h" #include "classes/container/container.h" #include "classes/scoop/scoop.h" #include "classes/order/order.h" #include <string> #include <iostream> void Controller::cli() { int cmd = -1; while (cmd != 0) { cmd = m_view.select(); execute(cmd); } } void Controller::execute(int cmd) { if (!cmd) { return; } switch (cmd) { case 0: // Exit break; case 1: { // Create item std::string name, description; double rawCost, retailPrice; int type; Gtk::Dialog *dialog = new Gtk::Dialog(); dialog->set_title("Create New Item"); // Title Gtk::HBox b_name; Gtk::Label l_name{"Name: "}; l_name.set_width_chars(15); b_name.pack_start(l_name, Gtk::PACK_SHRINK); Gtk::Entry e_name; e_name.set_max_length(50); b_name.pack_start(e_name, Gtk::PACK_SHRINK); dialog->get_vbox()->pack_start(b_name, Gtk::PACK_SHRINK); // Description Gtk::HBox b_description; Gtk::Label l_description{"Description: "}; l_description.set_width_chars(15); b_description.pack_start(l_description, Gtk::PACK_SHRINK); Gtk::Entry e_description; e_description.set_max_length(50); b_description.pack_start(e_description, Gtk::PACK_SHRINK); dialog->get_vbox()->pack_start(b_description, Gtk::PACK_SHRINK); // Cost Gtk::HBox b_rawCost; Gtk::Label l_rawCost{"Cost per item: "}; l_rawCost.set_width_chars(15); b_rawCost.pack_start(l_rawCost, Gtk::PACK_SHRINK); Gtk::Entry e_rawCost; e_rawCost.set_max_length(50); b_rawCost.pack_start(e_rawCost, Gtk::PACK_SHRINK); dialog->get_vbox()->pack_start(b_rawCost, Gtk::PACK_SHRINK); // Price Gtk::HBox b_retailPrice; Gtk::Label l_retailPrice{"Price per item: "}; l_retailPrice.set_width_chars(15); b_retailPrice.pack_start(l_retailPrice, Gtk::PACK_SHRINK); Gtk::Entry e_retailPrice; e_retailPrice.set_max_length(50); b_retailPrice.pack_start(e_retailPrice, Gtk::PACK_SHRINK); dialog->get_vbox()->pack_start(b_retailPrice, Gtk::PACK_SHRINK); // Type Gtk::HBox b_type; Gtk::Label l_type{"Type of item: "}; l_type.set_width_chars(15); b_type.pack_start(l_type, Gtk::PACK_SHRINK); Gtk::ComboBoxText c_type; c_type.set_size_request(160); c_type.append("Container"); c_type.append("Scoop"); c_type.append("Topping"); b_type.pack_start(c_type, Gtk::PACK_SHRINK); dialog->get_vbox()->pack_start(b_type, Gtk::PACK_SHRINK); // Finishing up dialog dialog->add_button("Cancel", 0); dialog->add_button("Create", 1); dialog->show_all(); int result = dialog->run(); dialog->close(); while (Gtk::Main::events_pending()) { Gtk::Main::iteration(); } if (result == 1) { name = e_name.get_text(); description = e_description.get_text(); rawCost = std::stod(e_rawCost.get_text()); retailPrice = std::stod(e_retailPrice.get_text()); type = c_type.get_active_row_number(); switch (type) { case 0: { int maxScoops; Gtk::Dialog *dialog = new Gtk::Dialog(); dialog->set_title("Enter Max Scoops"); Gtk::HBox b_maxScoops; Gtk::Label l_maxScoops{"Max Scoops: "}; l_maxScoops.set_width_chars(15); b_maxScoops.pack_start(l_maxScoops, Gtk::PACK_SHRINK); Gtk::Entry e_maxScoops; e_maxScoops.set_max_length(2); b_maxScoops.pack_start(e_maxScoops, Gtk::PACK_SHRINK); dialog->get_vbox()->pack_start(b_maxScoops, Gtk::PACK_SHRINK); dialog->add_button("Set", 1); dialog->show_all(); int result = dialog->run(); dialog->close(); while (Gtk::Main::events_pending()) { Gtk::Main::iteration(); } if (result == 1) { maxScoops = std::stoi(e_maxScoops.get_text()); m_emporium.addContainer(Container(name, description, rawCost, retailPrice, maxScoops)); } break; } case 1: m_emporium.addScoop(Scoop(name, description, rawCost, retailPrice)); break; case 2: m_emporium.addTopping(Topping(name, description, rawCost, retailPrice)); break; default: break; } } break; } case 2: { //emporium.addOrder(Orde); } case 3: { // Save save(); break; } case 4: { // Load load(); break; } case 66: { m_emporium.addContainer(Container("Waffle Cone", "A waffle cone.", 0.75, 1.00, 0, 3)); m_emporium.addContainer(Container("Cup", "A wax coated cup.", 0.15, 0.20, 0, 4)); m_emporium.addScoop(Scoop("Vanilla", "Plain vanilla.", 0.49, 0.80, 0)); m_emporium.addScoop(Scoop("Mint Chocolate Chip", "Deliciously minty.", 0.55, 0.80, 0)); m_emporium.addTopping(Topping("Peanuts", "Chopped nuts!", 0.50, 0.75, 0, "Normal")); m_emporium.addTopping(Topping("Hot Fudge", "Creamy and fattening.", 0.30, 0.75, 0, "Normal")); break; } default: m_view.error("ERROR: INVALID COMMAND."); break; } } Emporium& Controller::getEmporium() { return m_emporium; } Container Controller::container(std::string name, std::string description, double rawCost, double retailPrice, int maxScoops, int quantity) { return Container(name, description, rawCost, retailPrice, quantity, maxScoops); }
28.972376
141
0.657132
kevinxtung
762b6e6124d6e9d27b6a700ae265856ca5c0b334
1,429
cpp
C++
src/Modules/Vision/VisionUtils/DrawSSLClient/DrawSSLClientField/DrawSSLClientField.cpp
MatheusPaixaoG/project-unification
efeec63244a370e4408b3e94fbdbff2be082554a
[ "MIT" ]
2
2022-01-02T15:28:08.000Z
2022-01-05T17:46:15.000Z
src/Modules/Vision/VisionUtils/DrawSSLClient/DrawSSLClientField/DrawSSLClientField.cpp
MatheusPaixaoG/project-unification
efeec63244a370e4408b3e94fbdbff2be082554a
[ "MIT" ]
null
null
null
src/Modules/Vision/VisionUtils/DrawSSLClient/DrawSSLClientField/DrawSSLClientField.cpp
MatheusPaixaoG/project-unification
efeec63244a370e4408b3e94fbdbff2be082554a
[ "MIT" ]
1
2022-01-15T15:28:15.000Z
2022-01-15T15:28:15.000Z
#include "DrawSSLClientField.h" #include <protobufs/protobufs.h> #include "Modules/Vision/VisionUtils/DrawCIninho/DrawCIninho.h" DrawSSLClientField::DrawSSLClientField(const RoboCupSSL::SSL_GeometryFieldSize& field, bool drawCIninho, const QColor& color) : drawCIninho(drawCIninho), color(color) { for (const auto& line : field.field_lines()) { lines += Line{QLineF(line.p1().x(), line.p1().y(), line.p2().x(), line.p2().y()), line.thickness()}; } for (const auto& arc : field.field_arcs()) { arcs += Arc{QPointF(arc.center().x(), arc.center().y()), arc.radius() - arc.thickness() / 2.0, arc.radius() + arc.thickness() / 2.0, arc.a1(), arc.a2()}; } } void DrawSSLClientField::run(GameVisualizerPainter2D* f) { for (const auto& line : lines) { f->drawLine(line.line.p1(), line.line.p2(), color, line.thickness); } for (const auto& arc : arcs) { f->drawArc(arc.origin, arc.innerRadius, arc.outterRadius, arc.theta1, arc.theta2, color); if (arc.origin.isNull() && drawCIninho) { qreal scale = 1.2 * arc.outterRadius * std::sin(PI / 4); DrawCIninho draw(arc.origin, scale); draw.run(f); } } } std::unique_ptr<Painting> DrawSSLClientField::clone() const { return std::make_unique<DrawSSLClientField>(*this); }
33.232558
99
0.595521
MatheusPaixaoG
762f9f6fb8bd4271525b7bfe604e60ae64c94642
7,977
cpp
C++
src/infra/Measurement.cpp
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
160
2016-05-11T09:45:56.000Z
2022-03-06T09:32:19.000Z
src/infra/Measurement.cpp
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
57
2016-12-26T07:02:12.000Z
2022-03-06T16:34:31.000Z
src/infra/Measurement.cpp
cryptobiu/libscapi
49eee7aee9eb3544a7facb199d0a6e98097b058a
[ "MIT" ]
67
2016-10-10T17:56:22.000Z
2022-03-15T22:56:39.000Z
// // Created by liork on 17/09/17. // /** * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI) * This file is part of the SCAPI project. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * 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. * * We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to * http://crypto.biu.ac.il/SCAPI. * * Libscapi uses several open source libraries. Please see these projects for any further licensing issues. * For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD * * %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * */ #include "../../include/infra/Measurement.hpp" #include "../../include/cryptoInfra/Protocol.hpp" using namespace std; Measurement::Measurement(Protocol &protocol) { init(protocol); } Measurement::Measurement(Protocol &protocol, vector<string> &names) { init(protocol); init(names); } Measurement::Measurement(const string &protocolName, int internalIterationsNumber, int partyId, int partiesNumber) { init(protocolName, internalIterationsNumber, partyId, partiesNumber); } Measurement::Measurement(const string &protocolName, int internalIterationsNumber, int partyId, int partiesNumber, vector<string> &names) { init(protocolName, internalIterationsNumber, partyId, partiesNumber); init(names); } void Measurement::setTaskNames(const vector<string> & names) { init(names); } void Measurement::addTaskNames(vector<string> & names) { names.insert(names.end(), m_names.begin(), m_names.end()); delete m_cpuStartTimes; delete m_cpuEndTimes; init(names); } void Measurement::init(Protocol &protocol) { m_arguments = protocol.getArguments(); CmdParser parser = protocol.getParser(); m_protocolName = parser.getValueByKey(m_arguments, "protocolName"); m_numberOfIterations = stoi(parser.getValueByKey(m_arguments,"internalIterationsNumber")); string partyId = parser.getValueByKey(m_arguments, "partyID"); if(partyId.compare("NotFound") != 0) m_partyId = stoi(partyId); m_numOfParties = atoi(parser.getValueByKey(m_arguments, "numParties").c_str()); } void Measurement::init(const string &protocolName, int internalIterationsNumber, int partyId, int partiesNumber) { m_protocolName = protocolName; m_numberOfIterations = internalIterationsNumber; m_partyId = partyId; m_numOfParties = partiesNumber; } void Measurement::init(const vector <string> &names) { m_cpuStartTimes = new vector<vector<double>>(names.size(), vector<double>(m_numberOfIterations,0)); m_cpuEndTimes = new vector<vector<double>>(names.size(), vector<double>(m_numberOfIterations, 0)); m_memoryUsage = new vector<vector<double>>(names.size(), vector<double>(m_numberOfIterations, 0)); m_names = move(names); } int Measurement::getTaskIdx(const string &name) { auto it = find(m_names.begin(), m_names.end(), name); auto idx = distance(m_names.begin(), it); return idx; } void Measurement::startSubTask(const string &taskName, int currentIterationNum) { auto now = system_clock::now(); auto ms = (double) time_point_cast<nanoseconds>(now).time_since_epoch().count() / 1000000; int taskIdx = getTaskIdx(taskName); (*m_cpuStartTimes)[taskIdx][currentIterationNum] = ms; } void Measurement::endSubTask(const string &taskName, int currentIterationNum) { int taskIdx = getTaskIdx(taskName); auto now = system_clock::now(); auto ms = (double) time_point_cast<nanoseconds>(now).time_since_epoch().count() / 1000000; (*m_cpuEndTimes)[taskIdx][currentIterationNum] = ms - (*m_cpuStartTimes)[taskIdx][currentIterationNum]; struct sysinfo systemInfo; (*m_memoryUsage)[taskIdx][currentIterationNum] = systemInfo.totalram / systemInfo.mem_unit; } void Measurement::writeData(const string &key, const string &value) { if (m_auxiliaryData.find(key) == m_auxiliaryData.end ()) m_auxiliaryData[key] = value; else m_auxiliaryData[key] += " " + value; } void Measurement::analyze() { string filePath = getcwdStr(); string fileName = filePath + "/" + m_protocolName + "*"; for (size_t idx = 1; idx< m_arguments.size(); idx++) fileName += "*" + m_arguments[idx].second; fileName += ".json"; json partyTimes = json::array(); for (size_t taskNameIdx = 0; taskNameIdx < m_names.size(); taskNameIdx++) { //Write for each task name all the iteration json task = json::object(); task["name"] = m_names[taskNameIdx]; for (int iterationIdx = 0; iterationIdx < m_numberOfIterations; iterationIdx++) { ostringstream streamObj; streamObj << fixed << setprecision(3) << (*m_cpuEndTimes)[taskNameIdx][iterationIdx]; task["iteration_" + to_string(iterationIdx)] = streamObj.str(); } partyTimes.insert(partyTimes.begin(), task); } //party is the root of the json objects json party; party["times"] = partyTimes; //read auxiliary data party["auxiliaryData"] = m_auxiliaryData; map <string, string> argumentsToFile; copy(m_arguments.begin(), m_arguments.end(), inserter(argumentsToFile, argumentsToFile.begin())); party["parameters"] = argumentsToFile; //send json object to create file createJsonFile(party, fileName); } void Measurement::analyzeComm(const json & j, const string &fileName) { createJsonFile(j, fileName); } void Measurement::analyzeMemory() { string filePath = getcwdStr(); string fileName = filePath + "/party" + to_string(m_partyId) + "Memory.json"; json partyTimes = json::array(); for (size_t taskNameIdx = 0; taskNameIdx < m_names.size(); taskNameIdx++) { //Write for each task name all the iteration json task = json::object(); task["name"] = m_names[taskNameIdx]; for (int iterationIdx = 0; iterationIdx < m_numberOfIterations; iterationIdx++) { ostringstream streamObj; streamObj << fixed << setprecision(3) << (*m_memoryUsage)[taskNameIdx][iterationIdx]; task["iteration_" + to_string(iterationIdx)] = streamObj.str(); } partyTimes.insert(partyTimes.begin(), task); } //party is the root of the json objects json party; party["times"] = partyTimes; createJsonFile(party, fileName); } void Measurement::createJsonFile(const json &j, const string &fileName) { try { ofstream myfile (fileName, ostream::out); myfile << j; } catch (exception& e) { cout << "Exception thrown : " << e.what() << endl; } } Measurement::~Measurement() { analyze(); analyzeMemory(); delete m_cpuStartTimes; delete m_cpuEndTimes; delete m_memoryUsage; }
34.834061
157
0.689357
cryptobiu
7632d1ab4a4c2eb45bb31e7f52c08e7fdf8ba5ec
3,226
hpp
C++
src/OpenGL/Framebuffer.hpp
Mischa-Alff/world
93772b438df7477104298cc253737713d510a595
[ "MIT" ]
null
null
null
src/OpenGL/Framebuffer.hpp
Mischa-Alff/world
93772b438df7477104298cc253737713d510a595
[ "MIT" ]
null
null
null
src/OpenGL/Framebuffer.hpp
Mischa-Alff/world
93772b438df7477104298cc253737713d510a595
[ "MIT" ]
3
2016-07-10T08:39:10.000Z
2019-08-28T01:35:06.000Z
#pragma once #include <vector> #include <GL/glew.h> #include <GL/gl.h> namespace Graphics { namespace OpenGL { class Texture; /*! \brief A wrapper around the OpenGL framebuffer API */ class Framebuffer { private: /*! \brief The internal OpenGL framebuffer object */ GLuint m_framebuffer; public: /*! \brief Creates the internal frambuffer object */ void create(); /*! \brief Binds a 1D texture to an attachment on the framebuffer * \param[in] attachment the point to attach to * \param[in] tex the texture to attach * \param[in] level the LOD level to use */ void bindTexture1D(GLenum attachment, Texture &tex, GLint level); /*! \brief Binds a 2D texture to an attachment on the framebuffer * \param[in] attachment the point to attach to * \param[in] tex the texture to attach * \param[in] level the LOD level to use */ void bindTexture2D(GLenum attachment, Texture &tex, GLint level); /*! \brief Binds a 3D texture to an attachment on the framebuffer * \param[in] attachment the point to attach to * \param[in] tex the texture to attach * \param[in] level the LOD level to use * \param[in] layer the layer of the 3D texture to use */ void bindTexture3D( GLenum attachment, Texture &tex, GLint level, GLint layer ); /*! \brief Binds fragment shader outputs to the framebuffer's bound color * buffers. * \param[in] buffers A vector of buffers to bind. Their position in the * vector corresponds to the 2nd argument in * [ShaderProgram::bindFragDataLocation]. * \sa ShaderProgram::bindFragDataLocation */ void drawBuffers(std::vector<GLenum> buffers); /*! \brief Destroys the internal frambuffer object */ void destroy(); /*! \brief Returns the internal framebuffer object. * \returns the internal framebuffer object */ operator GLuint(); /*! \brief Returns whether the internal frambuffer object is valid or not. * \returns whether the internal frambuffer object is valid or not. */ explicit operator bool() const; /*! \brief Returns whether the internal frambuffer object is valid or not. * \returns whether the internal frambuffer object is valid or not. */ bool isValid() const; /*! \brief binds the given framebuffer (or none if nullptr) to GL_FRAMEBUFFER \param[in] framebuffer the framebuffer to bind */ static void bind(Framebuffer *framebuffer); /*! \brief binds the given framebuffer (or none if nullptr) to the given bind point \param[in] bind_point the bind point to bind to \param[in] framebuffer the framebuffer to bind */ static void bind(GLenum bind_point, Framebuffer *framebuffer); /*! \brief Binds the framebuffer to the given bind point * (default is GL_FRAMEBUFFER) * \param[in] bind_point the bind point to bind to */ void bind(GLenum bind_point = GL_FRAMEBUFFER); /*! \brief Constructs the framebuffer object. */ Framebuffer(); /*! \brief Destroys the framebuffer object. */ ~Framebuffer(); }; } }
28.548673
77
0.656851
Mischa-Alff
7633680275b64df4765f0614af5165d18c6bd3a0
3,560
cc
C++
test/unit/picolibrary/spi/gpio_output_pin_device_selector/main.cc
jaylamb/picolibrary
528d04fac031c80c64df86574737be3bfca1b867
[ "Apache-2.0" ]
3
2021-02-12T04:05:42.000Z
2022-02-15T19:23:52.000Z
test/unit/picolibrary/spi/gpio_output_pin_device_selector/main.cc
jaylamb/picolibrary
528d04fac031c80c64df86574737be3bfca1b867
[ "Apache-2.0" ]
633
2019-08-31T20:58:26.000Z
2022-03-31T22:23:36.000Z
test/unit/picolibrary/spi/gpio_output_pin_device_selector/main.cc
jaylamb/picolibrary
528d04fac031c80c64df86574737be3bfca1b867
[ "Apache-2.0" ]
1
2021-02-17T20:40:49.000Z
2021-02-17T20:40:49.000Z
/** * picolibrary * * Copyright 2020-2021, Andrew Countryman <apcountryman@gmail.com> and the picolibrary * contributors * * 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 * \brief picolibrary::SPI::GPIO_Output_Pin_Device_Selector unit test program. */ #include "gmock/gmock.h" #include "gtest/gtest.h" #include "picolibrary/error.h" #include "picolibrary/result.h" #include "picolibrary/spi.h" #include "picolibrary/testing/unit/error.h" #include "picolibrary/testing/unit/gpio.h" #include "picolibrary/testing/unit/random.h" #include "picolibrary/void.h" namespace { using ::picolibrary::Error_Code; using ::picolibrary::Result; using ::picolibrary::Void; using ::picolibrary::Testing::Unit::Mock_Error; using ::picolibrary::Testing::Unit::random; using ::testing::Return; using Device_Selector = ::picolibrary::SPI::GPIO_Output_Pin_Device_Selector<::picolibrary::Testing::Unit::GPIO::Mock_Output_Pin>; } // namespace /** * \brief Verify picolibrary::SPI::GPIO_Output_Pin_Device_Selector::select() properly * handles a selection error. */ TEST( select, selectionError ) { auto device_selector = Device_Selector{}; auto const error = random<Mock_Error>(); EXPECT_CALL( device_selector, transition_to_high() ).WillOnce( Return( error ) ); auto const result = device_selector.select(); EXPECT_TRUE( result.is_error() ); EXPECT_EQ( result.error(), error ); } /** * \brief Verify picolibrary::SPI::GPIO_Output_Pin_Device_Selector::select() works * properly. */ TEST( select, worksProperly ) { auto device_selector = Device_Selector{}; EXPECT_CALL( device_selector, transition_to_high() ).WillOnce( Return( Result<Void, Error_Code>{} ) ); EXPECT_FALSE( device_selector.select().is_error() ); } /** * \brief Verify picolibrary::SPI::GPIO_Output_Pin_Device_Selector::dedeselect() properly * handles a deselection error. */ TEST( deselect, deselectionError ) { auto device_selector = Device_Selector{}; auto const error = random<Mock_Error>(); EXPECT_CALL( device_selector, transition_to_low() ).WillOnce( Return( error ) ); auto const result = device_selector.deselect(); EXPECT_TRUE( result.is_error() ); EXPECT_EQ( result.error(), error ); } /** * \brief Verify picolibrary::SPI::GPIO_Output_Pin_Device_Selector::deselect() works * properly. */ TEST( deselect, worksProperly ) { auto device_selector = Device_Selector{}; EXPECT_CALL( device_selector, transition_to_low() ).WillOnce( Return( Result<Void, Error_Code>{} ) ); EXPECT_FALSE( device_selector.deselect().is_error() ); } /** * \brief Execute the picolibrary::SPI::GPIO_Output_Pin_Device_Selector unit tests. * * \param[in] argc The number of arguments to pass to testing::InitGoogleMock(). * \param[in] argv The array of arguments to pass to testing::InitGoogleMock(). * * \return See Google Test's RUN_ALL_TESTS(). */ int main( int argc, char * argv[] ) { ::testing::InitGoogleMock( &argc, argv ); return RUN_ALL_TESTS(); }
28.943089
109
0.719101
jaylamb
763f1e13446725f865d345f189d95cf8f57f10fc
1,173
cpp
C++
libs/library/src/library.cpp
briancairl/snek
ebdd90ba2790bfcbf843c0eb52a13c7f212f8e8f
[ "MIT" ]
null
null
null
libs/library/src/library.cpp
briancairl/snek
ebdd90ba2790bfcbf843c0eb52a13c7f212f8e8f
[ "MIT" ]
null
null
null
libs/library/src/library.cpp
briancairl/snek
ebdd90ba2790bfcbf843c0eb52a13c7f212f8e8f
[ "MIT" ]
null
null
null
/** * @copyright 2022-present Brian Cairl * * @file library.cpp */ // LibDL #include <dlfcn.h> // Snek #include <snek/assert.hpp> #include <snek/library.hpp> namespace snek { Library::Library(Library&& other) : native_handle_{other.native_handle_} { other.native_handle_ = nullptr; } Library::Library(const char* path) : native_handle_{nullptr} { if (native_handle_ = dlopen(path, RTLD_LAZY | RTLD_LOCAL); native_handle_ != nullptr) { return; } else if (const char* errstr = dlerror(); errstr != nullptr) { native_handle_ = nullptr; throw std::runtime_error{errstr}; } SNEK_ASSERT_NON_NULL(dlopen(path, RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD)); } void* Library::get_opaque_symbol(const char* symbol_name) const { SNEK_ASSERT_TRUE(Library::is_loaded()); return dlsym(native_handle_, symbol_name); } void Library::unload() { if (!is_loaded()) { return; } else if (const int retval = dlclose(native_handle_); retval == 0) { native_handle_ = nullptr; } } Library& Library::operator=(Library&& other) { native_handle_ = other.native_handle_; other.native_handle_ = nullptr; return *this; } } // namespace snek
19.881356
108
0.693947
briancairl
7640e1b2223bf4821609e32166d7f02f73080d21
9,173
cc
C++
arcane/src/arcane/std/ProfPerformanceService.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/std/ProfPerformanceService.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/std/ProfPerformanceService.cc
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* ProfPerformanceService.cc (C) 2000-2021 */ /* */ /* Informations de performances utilisant les signaux de profiling. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/utils/ArcanePrecomp.h" #include "arcane/utils/ValueConvert.h" #include "arcane/utils/NotImplementedException.h" #include "arcane/utils/PlatformUtils.h" #include "arcane/utils/FatalErrorException.h" #include "arcane/utils/TraceInfo.h" #include "arcane/FactoryService.h" #include "arcane/AbstractService.h" #include "arcane/utils/IProfilingService.h" #include "arcane/std/ProfilingInfo.h" // NOTE: Ce fichier nécessitant la libunwind, il n'est compilé que sur // les OS de style UNIX. #define UNW_LOCAL_ONLY #include <libunwind.h> #include <stdio.h> #include <cxxabi.h> #include <sys/time.h> #include <signal.h> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arcane { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Service de profiling utilisant 'setitimer'. */ class ProfPerformanceService : public AbstractService , public IProfilingService { public: ProfPerformanceService(const ServiceBuildInfo& sbi); virtual ~ProfPerformanceService(); public: virtual void initialize(); virtual void startProfiling(); virtual void switchEvent(); virtual void stopProfiling(); virtual void printInfos(bool dump_file); virtual void getInfos(Int64Array&); virtual void dumpJSON(JSONWriter& writer); virtual void reset(); virtual ITimerMng* timerMng() { return 0; } public: private: int m_period; private: }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_REGISTER_APPLICATION_FACTORY(ProfPerformanceService, IProfilingService, ProfProfilingService); /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ProfPerformanceService:: ProfPerformanceService(const ServiceBuildInfo& sbi) : AbstractService(sbi) , m_period(100) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ProfPerformanceService:: ~ProfPerformanceService() { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ static void _setTimer(Integer usecond) { struct itimerval time_val; struct itimerval otime_val; time_val.it_value.tv_sec = 0; time_val.it_value.tv_usec = usecond; time_val.it_interval.tv_sec = 0; time_val.it_interval.tv_usec = 0; int r = setitimer(ITIMER_PROF,&time_val,&otime_val); if (r!=0) cout << "** ERROR in setitimer r=" << r << '\n'; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace { int nb_total = 0; ProfInfos* global_infos = nullptr; bool global_is_active = false; //! Temps du timer en micro-seconde int global_timer_period = 10000; } extern "C" void arcane_prof_handler() { static bool is_in_handler = false; // Sous Linux avec gcc, les exceptions utilisent la libunwind contenue // dans gcc et cela peut provoquer des deadlocks avec notre utilisation // si cet handler est appelé lors du dépilement d'une exception. // Pour éviter ce problème, on ne fait rien tant qu'une exception est // active. if (Exception::hasPendingException()){ cout << "** WARNING: ProfHandler in pending exception\n"; return; } if (is_in_handler){ cout << "** In handler\n"; return; } is_in_handler = true; ++nb_total; int overflow_event[MAX_COUNTER]; int nb_overflow_event = 1; overflow_event[0] = 0; unw_word_t func_ip = 0; unw_word_t offset = 0; { unw_cursor_t cursor; unw_context_t uc; unw_getcontext(&uc); unw_init_local(&cursor, &uc); int current_func = 0; String message; // Le 3 indique le nombre de fonctions avant la bonne // (il y a cette fonction, puis le _arcaneProfilingSigFunc // et le signal lui meme. while (unw_step(&cursor) > 0 && current_func<3) { //while (current_func<3) { //unw_step(&cursor); unw_get_reg(&cursor, UNW_REG_IP, &func_ip); #if 0 char func_name_buf[10000]; unw_get_proc_name(&cursor,func_name_buf,10000,&offset); cout << "** I=" << current_func << " FUNC NAME=" << func_name_buf << " ip=" << (void*)func_ip << '\n'; #endif ++current_func; } } global_infos->addEvent((void*)(func_ip+offset),overflow_event,nb_overflow_event); is_in_handler = false; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ extern "C" void _arcaneProfilingSigFunc(int signum) { //cout << "**SIGPROF=" << global_is_active << "\n"; if (signum!=SIGPROF) return; if (global_is_active){ arcane_prof_handler(); // Il est préférable de positionner le timer une fois // la fonction de profiling appelée car si le timer est petit, // il peut se déclencher dans la boucle _setTimer(global_timer_period); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: initialize() { if (!global_infos) global_infos = new ProfInfos(traceMng()); global_infos->setFunctionDepth(4); global_infos->setNbEventBeforeGettingStack(100); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: startProfiling() { global_is_active = true; global_infos->startProfiling(); ::sigset(SIGPROF,_arcaneProfilingSigFunc); _setTimer(global_timer_period); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: switchEvent() { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: stopProfiling() { if (!global_infos) return; global_is_active = false; _setTimer(global_timer_period); ::sigset(SIGPROF,SIG_IGN); //info() << "PROFILING: stop profiling nb_total=" << nb_total; global_infos->stopProfiling(); //global_infos->printInfos(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: printInfos(bool dump_file) { if (global_infos) global_infos->printInfos(dump_file); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: dumpJSON(JSONWriter& writer) { if (global_infos) global_infos->dumpJSON(writer); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: getInfos(Int64Array&) { throw NotImplementedException(A_FUNCINFO); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void ProfPerformanceService:: reset() { if (global_infos) global_infos->reset(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
30.07541
83
0.444784
JeromeDuboisPro
7645af02312abcebdd8f3c3d3a087226498ed96e
881
cpp
C++
palimdromicGame.cpp
sagar-sam/codechef-solutions
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
[ "MIT" ]
null
null
null
palimdromicGame.cpp
sagar-sam/codechef-solutions
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
[ "MIT" ]
null
null
null
palimdromicGame.cpp
sagar-sam/codechef-solutions
ea414d17435f0cfbc84b0c6b172ead0b22f32a23
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <iterator> using namespace std; int main(){ int t; scanf("%d",&t); while(t--) { string a,b; cin>>a; cin>>b; map<char,int> a1,b1; for(int i=0;i<a.length();i++) { a1[a[i]]++; b1[b[i]]++; } int flag=0; for(map<char,int> :: iterator it=a1.begin();it!=a1.end();it++) { if(b1[it->first]==0) { flag=1; break; } } if(flag==0) { printf("B\n"); continue; } flag=0; for(map<char,int> :: iterator it=a1.begin();it!=a1.end();it++) { if(it->second>1 && b1[it->first]==0) { flag=1; break; } } if(flag==1) { printf("A\n"); continue; } flag=0; for(map<char,int> :: iterator it=b1.begin();it!=b1.end();it++) { if(a1[it->first]==0) { flag=1; break; } } if(flag==0) { printf("A\n"); } else { printf("B\n"); } } }
12.955882
64
0.475596
sagar-sam
76464428f0d4aa053f6d9bf93c3edfec11c33bd2
1,916
cpp
C++
aws-cpp-sdk-backup/source/model/ListReportJobsRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-backup/source/model/ListReportJobsRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-backup/source/model/ListReportJobsRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/backup/model/ListReportJobsRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Backup::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; ListReportJobsRequest::ListReportJobsRequest() : m_byReportPlanNameHasBeenSet(false), m_byCreationBeforeHasBeenSet(false), m_byCreationAfterHasBeenSet(false), m_byStatusHasBeenSet(false), m_maxResults(0), m_maxResultsHasBeenSet(false), m_nextTokenHasBeenSet(false) { } Aws::String ListReportJobsRequest::SerializePayload() const { return {}; } void ListReportJobsRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_byReportPlanNameHasBeenSet) { ss << m_byReportPlanName; uri.AddQueryStringParameter("ReportPlanName", ss.str()); ss.str(""); } if(m_byCreationBeforeHasBeenSet) { ss << m_byCreationBefore.ToGmtString(DateFormat::ISO_8601); uri.AddQueryStringParameter("CreationBefore", ss.str()); ss.str(""); } if(m_byCreationAfterHasBeenSet) { ss << m_byCreationAfter.ToGmtString(DateFormat::ISO_8601); uri.AddQueryStringParameter("CreationAfter", ss.str()); ss.str(""); } if(m_byStatusHasBeenSet) { ss << m_byStatus; uri.AddQueryStringParameter("Status", ss.str()); ss.str(""); } if(m_maxResultsHasBeenSet) { ss << m_maxResults; uri.AddQueryStringParameter("MaxResults", ss.str()); ss.str(""); } if(m_nextTokenHasBeenSet) { ss << m_nextToken; uri.AddQueryStringParameter("NextToken", ss.str()); ss.str(""); } }
23.084337
69
0.679019
perfectrecall
76479256096b7fad549a443ecbeb55cfc4550f3d
6,442
cpp
C++
src/Mx3.cpp
infinitelyCannon/Mx3
9d2ae82344821c428272511f23a937c9025d92a3
[ "MIT" ]
null
null
null
src/Mx3.cpp
infinitelyCannon/Mx3
9d2ae82344821c428272511f23a937c9025d92a3
[ "MIT" ]
null
null
null
src/Mx3.cpp
infinitelyCannon/Mx3
9d2ae82344821c428272511f23a937c9025d92a3
[ "MIT" ]
null
null
null
#include "Mx3.hpp" #include "fmod_errors.h" #include "Song.hpp" #include <cstdlib> #define ERRCHECK(x) ErrorCheck(x, __FILE__, __LINE__) #define HEAD_CHANNEL "Mx3_Main" #define SOLO_CHANNEL "Mx3_Solo" ErrorCallback Mx3::mErrorCallback = nullptr; /* * TODO: Find a way to have the library be imported without the user having to use/include FMOD headers * (Might help with glue implementations) */ Mx3::Mx3() : mSystem(nullptr) { // TODO: Add call to CoInitialize for Windows ERRCHECK(FMOD::System_Create(&mSystem, FMOD_VERSION)); ERRCHECK(mSystem->init(32, FMOD_INIT_NORMAL, 0)); mTracks[HEAD_CHANNEL] = nullptr; mTracks[SOLO_CHANNEL] = nullptr; ERRCHECK(mSystem->createChannelGroup(HEAD_CHANNEL, &mTracks[HEAD_CHANNEL])); ERRCHECK(mSystem->createChannelGroup(SOLO_CHANNEL, &mTracks[SOLO_CHANNEL])); ERRCHECK(mTracks[HEAD_CHANNEL]->addGroup(mTracks[SOLO_CHANNEL])); } Mx3::Mx3(int maxchannels, FMOD_INITFLAGS flags, void* driverdata): mSystem(nullptr) { ERRCHECK(FMOD::System_Create(&mSystem, FMOD_VERSION)); ERRCHECK(mSystem->init(maxchannels, flags, driverdata)); mTracks[HEAD_CHANNEL] = nullptr; mTracks[SOLO_CHANNEL] = nullptr; ERRCHECK(mSystem->createChannelGroup(HEAD_CHANNEL, &mTracks[HEAD_CHANNEL])); ERRCHECK(mSystem->createChannelGroup(SOLO_CHANNEL, &mTracks[SOLO_CHANNEL])); ERRCHECK(mTracks[HEAD_CHANNEL]->addGroup(mTracks[SOLO_CHANNEL])); } void Mx3::AddToQueue(std::string file) { if (file.empty()) return; mQueue.push_back(file); } void Mx3::AddToQueue(std::vector<std::string> &files) { mQueue.insert(mQueue.end(), files.begin(), files.end()); } void Mx3::ClearQueue() { Stop(); mQueue.clear(); //for (auto sound : mSounds) // ERRCHECK(sound.second->release()); //mSounds.clear(); } void Mx3::Debug() { bDebug = true; } void Mx3::ErrorCheck(FMOD_RESULT result, const char *file, int line) { if(result != FMOD_OK) { if(mErrorCallback) mErrorCallback(FMOD_ErrorString(result), file, line); } } unsigned int Mx3::GetLength() { if(mChannels.empty()) return 0; return mChannels.begin()->second->GetLength(); } bool Mx3::GetPaused() { bool paused = false; ERRCHECK(mTracks[HEAD_CHANNEL]->getPaused(&paused)); return paused; } unsigned int Mx3::GetPosition() { if (bDebug) bDebug = false; if(mChannels.empty()) return 0; return mChannels.begin()->second->GetPosition(); } float Mx3::GetVolume() { float volume = 0; ERRCHECK(mTracks[HEAD_CHANNEL]->getVolume(&volume)); return volume; } bool Mx3::IsPlaying() { bool result = false; ERRCHECK(mTracks[HEAD_CHANNEL]->isPlaying(&result)); return result; } bool Mx3::IsSoundLoaded(const std::string file) { /*auto songRef = mSounds.find(file); if(songRef == mSounds.end()) return false; if(songRef->second) { FMOD_OPENSTATE state; ERRCHECK(songRef->second->getOpenState(&state, 0, 0, 0)); return state != FMOD_OPENSTATE_ERROR; }*/ return false; } //void Mx3::LoadSound(const std::string name) //{ // if (IsSoundLoaded(name)) // return; // // auto soundRef = mSounds.find(name); // if (soundRef != mSounds.end()) // return; // // mSounds[name] = nullptr; // FMOD_MODE mode = FMOD_NONBLOCKING | FMOD_CREATESTREAM | FMOD_2D | FMOD_LOOP_NORMAL; // ERRCHECK(mSystem->createSound(name.c_str(), mode, 0, &mSounds[name])); //} void Mx3::Next() { if (mQueue.empty()) return; else if (mQueue.size() == 1) Play(NowPlayingIdx); Play((NowPlayingIdx + 1) % mQueue.size()); } void Mx3::Play(int index) { if (index >= mQueue.size() || index < 0) return; if (!mChannels.empty()) Stop(); //LoadSound(mQueue[index]); NowPlayingIdx = index; mChannels.emplace(NextChannelID++, new Song(mSystem, mQueue[index], mTracks[SOLO_CHANNEL])); } //void Mx3::PlaySound(std::string file) //{ // auto songRef = mSounds.find(file); // // if(songRef == mSounds.end()) // { // LoadSound(file); // songRef = mSounds.find(file); // if(songRef == mSounds.end()) // return; // } // // mChannels.emplace( // std::make_pair(NextChannelID++, Song(mSystem, file, mTracks[SOLO_CHANNEL])) // ); //} void Mx3::Previous() { // TODO: Have it restart currrent song if at/before certain position if (mQueue.empty() || NowPlayingIdx == 0) return; else if (mQueue.size() == 1) Play(NowPlayingIdx); Play((NowPlayingIdx - 1) % mQueue.size()); } void Mx3::RemoveFromQueue(int index) { if (index < 0 || index >= mQueue.size()) return; else if (mQueue.size() == 1) { ClearQueue(); return; } //NOTE: Might need to switch to having Songs manage the Sound *'s mQueue.erase(mQueue.begin() + index); if (index < NowPlayingIdx) --NowPlayingIdx; else if (index == NowPlayingIdx) Play(NowPlayingIdx); } void Mx3::SetErrorCallback(ErrorCallback func) { mErrorCallback = func; Song::SetErrorCallback(func); } void Mx3::SetPaused(bool paused) { ERRCHECK(mTracks[HEAD_CHANNEL]->setPaused(paused)); } void Mx3::SetRepeatMode(int mode) { if (!IsPlaying()) return; mChannels.begin()->second->SetRepeatMode(mode); } void Mx3::SetVolume(float volume, bool clamp) { if(clamp) { if(volume < 0) volume = 0; else if(volume > 1.0f) volume = 1.0f; } ERRCHECK(mTracks[HEAD_CHANNEL]->setVolume(volume)); } void Mx3::Stop() { for (auto it = mTracks.begin(); it != mTracks.end();) { if (it->first == HEAD_CHANNEL || it->first == SOLO_CHANNEL) ++it; else { ERRCHECK(it->second->stop()); it = mTracks.erase(it); } } mChannels.clear(); NextChannelID = 0; } void Mx3::SwapSongs(int first, int second) { if (first < 0 || first >= mQueue.size() || second < 0 || second >= mQueue.size()) return; if (first == second) return; std::string temp = mQueue[first]; mQueue[first] = mQueue[second]; mQueue[second] = temp; if (NowPlayingIdx == first) NowPlayingIdx = second; else if (NowPlayingIdx == second) NowPlayingIdx = first; } //void Mx3::UnLoadSound(std::string file) //{ // auto soundRef = mSounds.find(file); // // if(soundRef != mSounds.end()) // return; // // ERRCHECK(mSounds[file]->release()); // mSounds.erase(soundRef); //} void Mx3::Update(float deltaTime) { ERRCHECK(mSystem->update()); for (auto it = mChannels.begin(); it != mChannels.end();) { it->second->Update(deltaTime); if (it->second->IsStopped()) it = mChannels.erase(it); else ++it; } } Mx3::~Mx3() { ERRCHECK(mTracks[HEAD_CHANNEL]->stop()); mChannels.clear(); //for(auto sound : mSounds) // ERRCHECK(sound.second->release()); ERRCHECK(mSystem->release()); }
20.068536
102
0.681931
infinitelyCannon
7648659fe4b6c7405b296766b3515d9de6ba108f
9,364
cpp
C++
src/DaggyCore/tests/local/DaggyCoreLocalTests.cpp
milovidov/dataagregator
1150f66fc2ef2bbcf62c0174ef147109185cad98
[ "MIT" ]
135
2019-06-23T20:32:33.000Z
2022-02-06T15:41:41.000Z
src/DaggyCore/tests/local/DaggyCoreLocalTests.cpp
milovidov/dataagregator
1150f66fc2ef2bbcf62c0174ef147109185cad98
[ "MIT" ]
2
2020-10-16T17:31:44.000Z
2022-01-02T22:02:04.000Z
src/DaggyCore/tests/local/DaggyCoreLocalTests.cpp
milovidov/dataagregator
1150f66fc2ef2bbcf62c0174ef147109185cad98
[ "MIT" ]
11
2019-12-26T14:36:44.000Z
2022-02-23T02:14:41.000Z
/* MIT License Copyright (c) 2021 Mikhail Milovidov 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 "Precompiled.h" #include "DaggyCoreLocalTests.h" #include <DaggyCore/Core.hpp> #include <DaggyCore/Errors.hpp> using namespace daggy; namespace { constexpr const char* json_data = R"JSON( { "sources": { "localhost" : { "type": "local", "commands": { "pingpong": { "exec": "pingpong", "extension": "log" }, "pingpong_restart": { "exec": "pingpong -c 1", "extension": "log", "restart": true }, "pingpong_once": { "exec": "pingpong -c 1", "extension": "log" } } } } } )JSON"; constexpr const char* yaml_data = R"YAML( aliases: - &my_commands pingpong: exec: pingpong extension: log pingpong_restart: exec: pingpong -c 1 extension: log restart: true pingpong_once: exec: pingpong -c 1 extension: log sources: localhost: type: local commands: *my_commands )YAML"; thread_local const Sources test_sources{ { "localhost", { "local", "", { { "pingpong", { "log", "pingpong", {}, false } }, { "pingpong_restart", { "log", "pingpong -c 1", {}, true } }, { "pingpong_once", { "log", "pingpong -c 1", {}, false } }, }, false, {} } } }; thread_local const Sources fake_data_sources = { { "localhost", { "local", "", { { "fake_ping", { "log", "ping_fake 127.0.0.1", {}, false } } }, false, {} } } }; thread_local const Sources once_process_data_sources = { { "localhost", { "local", "", { { "pingpong", { "log", "pingpong", {}, false } } }, false, {} } } }; } DaggyCoreLocalTests::DaggyCoreLocalTests(QObject *parent) : QObject(parent) { } void DaggyCoreLocalTests::init() { } void DaggyCoreLocalTests::cleanup() { } void DaggyCoreLocalTests::checkVersion() { daggy::Core core({}); auto version = core.version(); QCOMPARE(QString(version.full), QString(DAGGY_VERSION_FULL)); QCOMPARE(version.major, DAGGY_VERSION_MAJOR); QCOMPARE(version.minor, DAGGY_VERSION_MINOR); QCOMPARE(version.patch, DAGGY_VERSION_PATCH); QCOMPARE(version.build, DAGGY_VERSION_BUILD); QCOMPARE(QString(version.postfix), QString(DAGGY_VERSION_POSTFIX)); QCOMPARE(QString(version.vendor), QString(DAGGY_VENDOR)); QCOMPARE(QString(version.commit), QString(DAGGY_VERSION_COMMIT)); } void DaggyCoreLocalTests::startAndTerminateTest_data() { QTest::addColumn<QString>("type"); QTest::addColumn<QString>("data"); QTest::newRow("json") << "json" << json_data; #ifdef YAML_SUPPORT QTest::newRow("yaml") << "yaml" << yaml_data; #endif } void DaggyCoreLocalTests::startAndTerminateTest() { QFETCH(QString, type); QFETCH(QString, data); Sources sources; QString error; if (type == "json") sources = std::move(*sources::convertors::json(data, error)); else sources = std::move(*sources::convertors::yaml(data, error)); QVERIFY(error.isEmpty()); QCOMPARE(sources, test_sources); Core core(std::move(sources)); const auto& session = core.session(); QCOMPARE(core.prepare(error), errors::success); QVERIFY(core.state() == DaggyNotStarted); QCOMPARE(core.sources(), test_sources); QSignalSpy states_spy(&core, &Core::stateChanged); QSignalSpy streams_spy(&core, &Core::commandStream); QTimer::singleShot(0, &core, [&]() { auto result = core.start(); QCOMPARE(result, errors::success); }); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); auto arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyStarted); QTimer::singleShot(3000, &core, [&]() { core.stop(); }); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyFinishing); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyFinished); streams_spy.wait(); QVERIFY(!streams_spy.isEmpty()); QMap<QString, QList<sources::commands::Stream>> streams; for (auto command_stream : streams_spy) { auto command_id = command_stream[1].toString(); auto stream = command_stream[2].value<sources::commands::Stream>(); QVERIFY(!stream.part.isEmpty()); QCOMPARE(stream.meta.session, session); streams[command_id].push_back(stream); } auto stream_keys = streams.keys(); std::sort(stream_keys.begin(), stream_keys.end()); QList<QString> sources_keys; for (const auto& command : test_sources) { sources_keys += command.commands.keys(); } std::sort(sources_keys.begin(), sources_keys.end()); QCOMPARE(stream_keys, sources_keys); QVERIFY(!streams["pingpong_once"].isEmpty()); QVERIFY(!streams["pingpong_restart"].isEmpty()); QVERIFY(!streams["pingpong"].isEmpty()); } void DaggyCoreLocalTests::stopWithFakeProcess() { Core core(fake_data_sources); QString error; QCOMPARE(core.prepare(error), errors::success); QCOMPARE(core.state(), DaggyNotStarted); QSignalSpy states_spy(&core, &Core::stateChanged); QTimer::singleShot(0, &core, [&]() { auto result = core.start(); QCOMPARE(result, errors::success); }); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); auto arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyStarted); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyFinished); } void DaggyCoreLocalTests::stopOnceProcess() { Core core(once_process_data_sources); QCOMPARE(core.prepare(), errors::success); QCOMPARE(core.state(), DaggyNotStarted); QSignalSpy states_spy(&core, &Core::stateChanged); QSignalSpy streams_spy(&core, &Core::commandStream); QTimer::singleShot(0, &core, [&]() { auto result = core.start(); QCOMPARE(result, errors::success); }); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); auto arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyStarted); QTimer::singleShot(3000, &core, [&]() { core.stop(); }); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); QCOMPARE(states_spy.count(), 1); arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyFinishing); QVERIFY(states_spy.wait()); QVERIFY(!states_spy.isEmpty()); arguments = states_spy.takeFirst(); QCOMPARE(arguments.at(0).value<DaggyStates>(), DaggyFinished); QVERIFY(!streams_spy.isEmpty()); }
27.063584
78
0.562046
milovidov
7650955f6e972620c93af8e702e9f055198b3623
3,619
hpp
C++
pythran/pythonic/numpy/reduce.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/reduce.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/reduce.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_NUMPY_REDUCE_HPP #define PYTHONIC_NUMPY_REDUCE_HPP #include "pythonic/include/numpy/reduce.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/__builtin__/None.hpp" #include "pythonic/__builtin__/ValueError.hpp" #include "pythonic/utils/neutral.hpp" #ifdef USE_BOOST_SIMD #include <boost/simd/include/functions/broadcast.hpp> #include <boost/simd/memory/functions/aligned_store.hpp> #endif #include <algorithm> namespace pythonic { namespace numpy { template <class Op, bool vector_form> template <class E, class F> F _reduce<Op, 1, vector_form>::operator()(E e, F acc) { for (auto const &value : e) Op{}(acc, value); return acc; } #ifdef USE_BOOST_SIMD template <class Op> template <class E, class F> F _reduce<Op, 1, true>::operator()(E e, F acc) { using T = typename E::dtype; using vT = typename boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION>; static const size_t vN = boost::simd::meta::cardinal_of<vT>::value; const long n = e.shape()[0]; const long bound = n / vN * vN; long i = 0; if (bound > 0) { vT vacc = e.load(i); for (i = vN; i < bound; i += vN) Op{}(vacc, e.load(i)); alignas(sizeof(vT)) T stored[vN]; boost::simd::store(vacc, &stored[0]); for (size_t j = 0; j < vN; ++j) Op{}(acc, stored[j]); } for (; i < n; ++i) Op{}(acc, e.fast(i)); return acc; } #endif template <class Op, size_t N, bool vector_form> template <class E, class F> F _reduce<Op, N, vector_form>::operator()(E e, F acc) { for (auto const &value : e) acc = _reduce<Op, N - 1, vector_form>{}(value, acc); return acc; } template <class Op, class E> reduce_result_type<E> reduce(E const &expr, types::none_type) { bool constexpr is_vectorizable = E::is_vectorizable and not std::is_same<typename E::dtype, bool>::value; reduce_result_type<E> p = utils::neutral<Op, typename E::dtype>::value; return _reduce<Op, types::numpy_expr_to_ndarray<E>::N, is_vectorizable>{}( expr, p); } template <class Op, class E> auto reduce(E const &array, long axis) -> typename std::enable_if<E::value == 1, decltype(reduce<Op>(array))>::type { if (axis != 0) throw types::ValueError("axis out of bounds"); return reduce<Op>(array); } template <class Op, class E> typename std::enable_if<E::value != 1, reduced_type<E>>::type reduce(E const &array, long axis) { if (axis < 0 || size_t(axis) >= E::value) throw types::ValueError("axis out of bounds"); auto shape = array.shape(); if (axis == 0) { types::array<long, E::value - 1> shp; std::copy(shape.begin() + 1, shape.end(), shp.begin()); return _reduce<Op, 1, false /* not on scalars*/>{}( array, reduced_type<E>{shp, utils::neutral<Op, typename E::dtype>::value}); } else { types::array<long, E::value - 1> shp; auto next = std::copy(shape.begin(), shape.begin() + axis, shp.begin()); std::copy(shape.begin() + axis + 1, shape.end(), next); reduced_type<E> sumy{shp, __builtin__::None}; std::transform(array.begin(), array.end(), sumy.begin(), [axis](typename E::iterator::value_type other) { return reduce<Op>(other, axis - 1); }); return sumy; } } } } #endif
30.669492
80
0.576126
artas360
76685fdee2e27c3f2ca9a7a0f9635d827b1d8348
820
cpp
C++
src/ui/aim65proxy.cpp
LiamMayfair/EMU65
0d9540fd25ed84d501068becc71a11281fd6b01b
[ "MIT" ]
4
2021-01-31T05:23:48.000Z
2021-11-04T11:35:20.000Z
src/ui/aim65proxy.cpp
LiamMayfair/EMU65
0d9540fd25ed84d501068becc71a11281fd6b01b
[ "MIT" ]
null
null
null
src/ui/aim65proxy.cpp
LiamMayfair/EMU65
0d9540fd25ed84d501068becc71a11281fd6b01b
[ "MIT" ]
3
2018-10-11T01:15:36.000Z
2020-12-18T05:36:14.000Z
#include "../../include/ui/aim65proxy.h" Aim65Proxy::Aim65Proxy(Aim65 *aim65, QObject *parent) : QObject(parent), UiProxy() { this->m_aim65 = std::shared_ptr<Aim65>(Aim65::GetInstance()); this->m_aim65->Initialise(); this->RegisterProxy(); } Aim65Proxy::~Aim65Proxy() { } void Aim65Proxy::RegisterProxy() { UiProxyCollection::GetInstance()->InsertAim65Proxy(std::shared_ptr<Aim65Proxy>(this)); } void Aim65Proxy::Start() { //Cpu::GetInstance()->Reset(); Cpu::GetInstance()->Run(); } void Aim65Proxy::SetResetButton(bool newState) { if (newState == true) { Cpu::GetInstance()->Reset(); Start(); } else { Cpu::GetInstance()->Halt(); } this->m_aim65->SetPowerSwitch(newState); } bool Aim65Proxy::GetResetButton() const { return true; }
18.636364
90
0.636585
LiamMayfair
7668b543d43cc7764dd0490a8f34c67450528365
1,728
cpp
C++
algospot/amusementpark/main.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
13
2015-06-07T09:26:26.000Z
2019-05-01T13:23:38.000Z
algospot/amusementpark/main.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
null
null
null
algospot/amusementpark/main.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
4
2016-03-05T06:21:05.000Z
2017-02-17T15:34:18.000Z
// https://algospot.com/judge/problem/read/AMUSEMENTPARK #include <iostream> #include <map> #include <cmath> #include <vector> using namespace std; int row, col; int in[22][22] = {0, }; map<int, pair<int, int>> m; vector<int> out; bool cc(int r, int b, int d) { for (int i = b + 1; i < d; i++) { if (in[r][i] != 0) return false; } return true; } bool rr(int C, int a, int c) { for (int i = a + 1; i < c; i++) { if (in[i][C] != 0) return false; } return true; } int gcd(int a, int b) { return (a % b == 0) ? b : gcd(b, a % b); } bool ok(int me, int to) { auto a = m[me].first; auto b = m[me].second; auto c = m[to].first; auto d = m[to].second; if (a == c) { return cc(a, min(b, d), max(b, d)); } if (b == d) { return rr(b, min(a, c), max(a, c)); } int dr = (c-a); int dc = (d-b); if (abs(dr) == 1 || abs(dc) == 1) return true; else { int g = gcd((int)abs(dr), (int)abs(dc)); dr = dr / g; dc = dc / g; int rr = a + dr; int cc = b + dc; while (rr != c) { if (in[rr][cc] != 0) return false; rr += dr; cc += dc; } return true; } } int main() { int to; cin >> row >> col >> to; for (int r = 1; r <= row; r++) { for (int c = 1; c <= col; c++) { cin >> in[r][c]; if (in[r][c] != 0) { m[in[r][c]] = make_pair(r, c); } } } int me(1); int maxi = in[row][col]; while (to <= maxi) { if (ok(me, to)) out.push_back(me); me++; to++; } cout << out.size() << endl; for (int x : out) cout << x << endl; return 0; }
21.073171
56
0.426505
seirion
766af497af3c56d266e5d66c9ef41de8f7615f7e
10,973
hpp
C++
src/ros2_examples_headers/include/ros2_examples_headers/signal_handler/signal_handler.hpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
src/ros2_examples_headers/include/ros2_examples_headers/signal_handler/signal_handler.hpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
src/ros2_examples_headers/include/ros2_examples_headers/signal_handler/signal_handler.hpp
IntelligentSystemsLabUTV/ros2_examples
b34d9238d680dd6b06177586f81bfed0bae31eb2
[ "MIT" ]
null
null
null
/** * ROS 2-compliant signal handler. * * Roberto Masocco <robmasocco@gmail.com> * * January 17, 2022 */ #ifndef SIGNAL_HANDLER_HPP #define SIGNAL_HANDLER_HPP #include <thread> #include <mutex> #include <atomic> #include <semaphore.h> #include <stdexcept> #include <vector> #include <algorithm> #include <unistd.h> #include <rclcpp/rclcpp.hpp> namespace ROS2SignalHandler { /** * Global singleton signal handler object. */ class SignalHandler final { public: /** * @brief Returns the global singleton instance. * * @return Global signal handler object. */ static SignalHandler & get_global_signal_handler() { static SignalHandler instance; return instance; } /** * @brief Initializes the signal handler data. * * @param context rclcpp::Context to operate on. * @param logger_name Name to be visualized in rclcpp log prints. * @param deferred_handler Signal handler to be called alongside main thread. * @param system_handler System signal handler to be called while tracing. * * @throws InvalidArgument */ void init( std::shared_ptr<rclcpp::Context> context, std::string && logger_name = std::string("signal_handler"), std::function<void(int, std::string &)> && deferred_handler = nullptr, std::function<void(int, siginfo_t *, void *)> && system_handler = nullptr ) { // Check if provided context is valid if (!context) { throw std::invalid_argument("SignalHandler::init: context cannot be null"); } // Acquire installation lock std::scoped_lock<std::mutex> init_lock(install_lock_); // Check if signal handler is currently valid if (valid_) { throw std::runtime_error("SignalHandler::init: called on valid object"); } // Initialize semaphores if (sem_init(&sig_prod_, 0, 0) || sem_init(&sig_cons_, 0, 1)) { std::perror("sem_init"); throw std::runtime_error("SignalHandler::init: failed to initialize sempahores"); } // Initialize pointers context_ = context; deferred_handler_ = deferred_handler; system_handler_ = system_handler; // Initialize rclcpp logger name logger_name_ = logger_name; // Initialize local signal value sig_ = 0; // Initialize validity flag (this also acts as a barrier, validating data above) valid_.store(true, std::memory_order_release); // Initialize handler thread handler_thread_ = std::thread( [this]() -> void { this->handler_thread_routine(); }); } /** * @brief Installs the signal handler for a given signal. * * @param int Signal code. * * @throws RuntimeError */ void install(int sig) { // Prepare sigaction struct sigaction new_act; if (sigfillset(&(new_act.sa_mask))) { std::perror("sigfillset"); throw std::runtime_error("SignalHandler::install: failed to set blocked signals mask"); } new_act.sa_flags = SA_SIGINFO; new_act.sa_sigaction = &this->common_handler; // Acquire installation lock std::scoped_lock<std::mutex> install_lock(install_lock_); // Install handler if (sigaction(sig, &new_act, NULL)) { std::perror("sigaction"); throw std::runtime_error( "SignalHandler::install: failed to install handler for signal (" + std::to_string(sig) + ")" ); } // Add signal to installed list installed_.push_back(sig); RCLCPP_INFO( rclcpp::get_logger(logger_name_), "Installed handler for signal (%d)", sig ); } /** * @brief Uninstalls the signal handler for a given signal. * * @param int Signal code. * * @throws RuntimeError */ void uninstall(int sig) { uninstall_(sig); } /** * @brief Sets the "ignore" flag for a given signal. * * @param int Signal code. * * @throws RuntimeError */ void ignore(int sig) { // Prepare sigaction struct sigaction new_act; if (sigemptyset(&(new_act.sa_mask))) { std::perror("sigfillset"); throw std::runtime_error("SignalHandler::ignore: failed to set blocked signals mask"); } new_act.sa_flags = 0; new_act.sa_handler = SIG_IGN; // Acquire installation lock std::scoped_lock<std::mutex> ignore_lock(install_lock_); // Install ignore handler if (sigaction(sig, &new_act, NULL)) { std::perror("sigaction"); throw std::runtime_error( "SignalHandler::ignore: failed to install handler for signal (" + std::to_string(sig) + ")" ); } // Add signal to installed list installed_.push_back(sig); RCLCPP_INFO( rclcpp::get_logger(logger_name_), "Ignoring signal (%d)", sig ); } /** * @brief Reinitializes this signal handler. * * @throws RuntimeError */ void fini() { // Acquire installation lock std::scoped_lock<std::mutex> fini_lock(install_lock_); // Check if signal handler is currently valid if (!valid_) { throw std::runtime_error("SignalHandler::fini: called on invalid object"); } // Remove all installed handlers std::vector<int> installed_local = installed_; for (auto sig : installed_local) { uninstall_(sig, true); } // Reset validity flag valid_ = false; // Terminate and join handler thread sem_wait_(&sig_cons_); sig_ = -1; sem_post_(&sig_prod_); handler_thread_.join(); // Erase pointers context_.reset(); deferred_handler_ = nullptr; system_handler_ = nullptr; // Erase logger name logger_name_ = std::string(""); // Destroy semaphores if (sem_destroy(&sig_prod_) || sem_destroy(&sig_cons_)) { std::perror("sem_destroy"); throw std::runtime_error("SignalHandler::fini: failed to destroy semaphores"); } // Erase local signal value sig_ = 0; } /* Singleton: no copy constructor. */ SignalHandler(SignalHandler &&) = delete; /* Singleton: no move assignment operator. */ void operator=(SignalHandler &&) = delete; private: /* Singleton: private constructor. */ SignalHandler() {} /* Internal rclcpp logger name. */ std::string logger_name_; /* Pointer to context to operate on. */ std::shared_ptr<rclcpp::Context> context_ = nullptr; /* Deferred signal handler. */ std::function<void(int, std::string &)> deferred_handler_ = nullptr; /* System signal handler. */ inline static std::function<void(int, siginfo_t *, void *)> system_handler_ = nullptr; /* Internal handler status flag. */ inline static std::atomic_bool valid_ = false; /* Signal handler object installation mutex. */ inline static std::mutex install_lock_; /* Delivered signal, also used to notify termination. */ inline static int sig_ = 0; /* Delivered signal PRODUCED semaphore. */ inline static sem_t sig_prod_; /* Delivered signal CONSUMED semaphore. */ inline static sem_t sig_cons_; /* List of traced signals. */ std::vector<int> installed_{}; /* Signal handler thread. */ std::thread handler_thread_; /** * @brief Wraps the call to sem_post. * * @throws RuntimeError */ static void sem_post_(sem_t * sem) { if (sem_post(sem)) { std::perror("sem_post"); throw std::runtime_error("SignalHandler::sem_post_: failed to post semaphore"); } } /** * @brief Wraps the call to sem_wait. * * @throws RuntimeError */ static void sem_wait_(sem_t * sem) { if (sem_wait(sem)) { std::perror("sem_wait"); throw std::runtime_error("SignalHandler::sem_wait_: failed to wait sempahore"); } } /** * @brief Uninstalls the signal handler for a given signal. * * @param int Signal code. * @param has_lock Marks lock acquisition. * * @throws RuntimeError */ void uninstall_(int sig, bool has_lock = false) { // Prepare sigaction struct sigaction new_act; if (sigemptyset(&(new_act.sa_mask))) { std::perror("sigfillset"); throw std::runtime_error("SignalHandler::uninstall_: failed to set blocked signals mask"); } new_act.sa_flags = 0; new_act.sa_handler = SIG_DFL; // Acquire installation lock if (!has_lock) { install_lock_.lock(); } // Check if signal handler has been installed before if (std::find(installed_.begin(), installed_.end(), sig) == installed_.end()) { throw std::runtime_error("SignalHandler::uninstall_: signal handler wasn't installed"); } // Install default handler if (sigaction(sig, &new_act, NULL)) { std::perror("sigaction"); throw std::runtime_error( "SignalHandler::uninstall_: failed to install handler for signal (" + std::to_string(sig) + ")" ); } // Remove signal from installed list installed_.erase(std::remove(installed_.begin(), installed_.end(), sig), installed_.end()); RCLCPP_INFO( rclcpp::get_logger(logger_name_), "Uninstalled handler for signal (%d)", sig ); // Release installation lock if (!has_lock) { install_lock_.unlock(); } } /** * @brief Signal handler thread routine. */ void handler_thread_routine() { int local_sig; RCLCPP_INFO(rclcpp::get_logger(logger_name_), "Signal handler started"); while (true) { // Wait for external wakeup call sem_wait_(&sig_prod_); local_sig = sig_; sem_post_(&sig_cons_); // Check if termination is due if (local_sig == -1) { RCLCPP_INFO(rclcpp::get_logger(logger_name_), "Signal handler terminated"); return; } RCLCPP_INFO(rclcpp::get_logger(logger_name_), "Got signal (%d)", local_sig); // Call custom handler, if present if (deferred_handler_) { deferred_handler_(local_sig, logger_name_); } // Shut down context if requested if (context_->is_valid() && context_->get_init_options().shutdown_on_sigint) { RCLCPP_WARN(rclcpp::get_logger(logger_name_), "Shutting down context"); context_->shutdown("signal (" + std::to_string(sig_) + ")"); } } } /** * @brief Common signal handler installed for all signals. * * @param sig Traced signal. * @param info Additional trace information. * @param ucontext Additional context information provided by the kernel. */ static void common_handler(int sig, siginfo_t * info, void * ucontext) { // Acquire signal handler lock std::scoped_lock<std::mutex> common_handler_lock(install_lock_); // Call system handler, if present, bypassing the rest of the system if (system_handler_) { system_handler_(sig, info, ucontext); } // Check if signal handler is currently valid if (!valid_) { return; } // Notify handler thread sem_wait_(&sig_cons_); sig_ = sig; sem_post_(&sig_prod_); } }; // class SignalHandler } // namespace ROS2SignalHandler #endif
25.578089
96
0.646678
IntelligentSystemsLabUTV
7671264799bb22fb7423ad236f3efe3c750e049c
1,010
cc
C++
src/MyPrimaryGeneratorAction.cc
wangshishe/RutherfordScattering
ccc4353501ad7ca4fcc78bf5e4805a358bdaa3ce
[ "MIT" ]
null
null
null
src/MyPrimaryGeneratorAction.cc
wangshishe/RutherfordScattering
ccc4353501ad7ca4fcc78bf5e4805a358bdaa3ce
[ "MIT" ]
null
null
null
src/MyPrimaryGeneratorAction.cc
wangshishe/RutherfordScattering
ccc4353501ad7ca4fcc78bf5e4805a358bdaa3ce
[ "MIT" ]
1
2022-03-15T04:52:09.000Z
2022-03-15T04:52:09.000Z
#include "MyPrimaryGeneratorAction.hh" MyPrimaryGeneratorAction::MyPrimaryGeneratorAction() { G4int nParticle = 1; fParticleGun = new G4ParticleGun(nParticle); auto *particleTable = G4ParticleTable::GetParticleTable(); G4String particleName = "alpha"; G4ParticleDefinition *particle = particleTable->FindParticle(particleName); G4ThreeVector momentumDirection(-1., 0., 0.); G4double energy = 5. * MeV; fParticleGun->SetParticleDefinition(particle); fParticleGun->SetParticleMomentumDirection(momentumDirection); fParticleGun->SetParticleEnergy(energy); } MyPrimaryGeneratorAction::~MyPrimaryGeneratorAction() { delete fParticleGun; } void MyPrimaryGeneratorAction::GeneratePrimaries(G4Event *anEvent) { G4double gunPositionX = 1 * m - 1 * mm; G4double gunPositionYZ = 1 * mm * (G4UniformRand() - 0.5); fParticleGun->SetParticlePosition(G4ThreeVector(gunPositionX, gunPositionYZ, gunPositionYZ)); fParticleGun->GeneratePrimaryVertex(anEvent); }
31.5625
97
0.758416
wangshishe
7673ca365447584d996d5c88b643c3447a95671f
2,885
cpp
C++
controller/strformats.cpp
bartek56/quetzalcoatl
dc60dbed6e1e9de7b3318d26a6ef65a47a59120c
[ "MIT" ]
5
2015-06-10T07:47:19.000Z
2021-04-03T21:26:49.000Z
controller/strformats.cpp
bartek56/quetzalcoatl
dc60dbed6e1e9de7b3318d26a6ef65a47a59120c
[ "MIT" ]
1
2020-07-22T13:57:56.000Z
2020-08-07T00:03:44.000Z
controller/strformats.cpp
duganchen/quetzalcoatl2
6e7f1ef8f4b2eaf698cc86f4308039afc8df7b44
[ "MIT" ]
1
2022-01-11T16:02:41.000Z
2022-01-11T16:02:41.000Z
#include "strformats.h" #include <QStringBuilder> #include <QStringList> QString timeStr(unsigned duration) { // Can't remember where I got this time format from. It might have been Foobar2000. unsigned seconds = duration % 60; unsigned minutes = duration % 3600 / 60; unsigned hours = duration / 3600; // For the string formatting: // Re: https://stackoverflow.com/a/2618444/240515 if (!hours && !minutes) { return QStringLiteral("0:%1").arg(seconds, 2, 10, QLatin1Char('0')); } if (!hours) { return QStringLiteral("%1:%2").arg(QString::number(minutes), leftPad(seconds)); } return QStringLiteral("%1:%2:%3").arg(QString::number(hours), leftPad(minutes), leftPad(seconds)); } QString leftPad(unsigned i) { // Left-zero-pad to two digits. return QStringLiteral("%1").arg(i, 2, 10, QLatin1Char('0')); } QString songLabel(const mpd_song *song) { if (!song) { return QString(); } const char *title = mpd_song_get_tag(song, MPD_TAG_TITLE, 0); if (!title) { // You're supposed to have a title. This is just a fallback to let you know to fix the tags. title = mpd_song_get_uri(song); } return title; } QString songEntityLabel(mpd_entity *entity) { if (!entity) { return QString(); } if (mpd_entity_get_type(entity) != MPD_ENTITY_TYPE_SONG) { return QString(); } auto song = mpd_entity_get_song(entity); return songLabel(song); } QString dirEntryLabel(mpd_entity *entity) { if (!entity) { return QString(); } if (mpd_entity_get_type(entity) == MPD_ENTITY_TYPE_DIRECTORY) { return mpd_directory_get_path(mpd_entity_get_directory(entity)); } return songEntityLabel(entity); } QString songToolTip(const mpd_song *song) { if (!song) { return QString(); } QStringList metadata; QVector<mpd_tag_type> tagTypes{MPD_TAG_TITLE, MPD_TAG_TRACK, MPD_TAG_ALBUM, MPD_TAG_DISC, MPD_TAG_ARTIST, MPD_TAG_ALBUM_ARTIST, MPD_TAG_COMPOSER, MPD_TAG_GENRE}; QString tagValue; QString tagName; for (auto tagType : tagTypes) { tagValue = mpd_song_get_tag(song, tagType, 0); if (tagValue.isEmpty()) { continue; } QString tagName = mpd_tag_name(tagType); metadata.append(tagName % ": " % tagValue); } return metadata.join("\n"); } QString songDuration(const mpd_song *song) { unsigned duration = mpd_song_get_duration(song); if (!duration) { // I have not personally encountered this. return "0:00"; } return timeStr(duration); }
24.65812
102
0.591334
bartek56
767546e1c60ef9bcddd19d949b21fbcab8a6e620
920
cpp
C++
vnoj/thmst.cpp
tiozo/Training
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
[ "MIT" ]
1
2021-08-28T04:16:34.000Z
2021-08-28T04:16:34.000Z
vnoj/thmst.cpp
tiozo/Training
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
[ "MIT" ]
null
null
null
vnoj/thmst.cpp
tiozo/Training
02cc8c4fcf68e07c16520fd05fcbfa524c171b6b
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; long long giaithua(int n) { int giai_thua = 1; for (int i = 1; i <= n; i++) giai_thua *= i; return giai_thua; } int main() { int N; cin >> N; long long res = 0,largest = 0; for (int i=1;i<N;++i) { long long x,y,z; cin >> x >> y >> z; res += z; largest = max(largest,z); } if (N>2) { long long a,b; a = N-1,b=N-2; a = giaithua(a)/(giaithua(2)*giaithua(a-2)); b = giaithua(b)/(giaithua(2)*giaithua(b-2)); res+=(largest+1)*(a-b)+largest*b; --N; while (N-2>2 || N-1>2) { a = N-1,b=N-2; a = giaithua(a)/(giaithua(2)*giaithua(a-2)); b = giaithua(b)/(giaithua(2)*giaithua(b-2)); res+=(largest+1)*(a-b)+largest*b; --N; } cout << res; } else cout << res; return 0; }
23.589744
56
0.444565
tiozo
76858b68fc441244110a83d05e89f5ff39d24686
3,991
cpp
C++
RipleyK.cpp
lsaravia/SpatialAnalysis
899148a65407dc8807475a923b4a231984441301
[ "Unlicense", "MIT" ]
null
null
null
RipleyK.cpp
lsaravia/SpatialAnalysis
899148a65407dc8807475a923b4a231984441301
[ "Unlicense", "MIT" ]
null
null
null
RipleyK.cpp
lsaravia/SpatialAnalysis
899148a65407dc8807475a923b4a231984441301
[ "Unlicense", "MIT" ]
null
null
null
#include "RipleyK.h" void RipleyK(char * outfile, simplmat <float>& ftr, int numAnn, float widAnn, int treeDensity, int xDist, int yDist ) { simplmat <float> ripknl(100); simplmat <float> pairs(100); simplmat <float> kripley(100); simplmat <float> lripley(100); simplmat <float> ce95(100); simplmat <float> l_d(100); simplmat <float> pdf(100); simplmat <float> frank(100); simplmat <float> kfrank(100); simplmat <float> lfrank(100); // cout << "Ripley's K for run #" << run << "Tree density of " << treeDensity << endl; float searchDist = numAnn * widAnn; const int xCoor = 0; const int yCoor = 1; ripknl.fill(0.0); frank.fill(0.0); kfrank.fill(0.0); l_d.fill(0.0); ce95.fill(0.0); pdf.fill(0.0); float dist=0; int distpt=0; int foc,tar; for(foc=0; foc<treeDensity; foc++) { int fx = ftr(foc,xCoor); int fy = ftr(foc,yCoor); int focb1=0,focb2=0; // Determine distance from point FOC to nearest 2 boundaries // focBound(focb1,focb2,fx,fy,xDist,yDist); for(tar=0; tar<treeDensity; tar++) { if(tar!=foc) { int tx=ftr(tar,xCoor); int ty=ftr(tar,yCoor); int xDiff = abs(tx-fx); int yDiff = abs(ty-fy); if( xDiff <= searchDist && yDiff <= searchDist ) { dist = sqrt(xDiff*xDiff + yDiff*yDiff ); distpt = int(dist/widAnn) + 1; if(distpt <= numAnn) { double wij=0; if( dist<=focb1) // No adjustement wij=1; else { double arccos1=0,arccos2=0; double x1=0,x2=0; if( (dist*dist) <= (focb1*focb1+focb2*focb2) ) // 1-border adjustement { x1 = focb1/dist; arccos1 = Pi/2 - atan(x1/sqrt(1-x1*x1)); wij = 1 / (1 - arccos1/Pi); } else { x1 = focb1/dist; x2 = focb2/dist; arccos1 = Pi/2 - atan(x1/sqrt(1-x1*x1)); arccos2 = Pi/2 - atan(x2/sqrt(1-x2*x2)); wij = 1 / (1 - (arccos1+arccos2+Pi/2)/(2*Pi)); } } if( wij < 1 ) cerr << "Error"; if( wij > 4 ) wij = 4; ripknl(distpt) += wij; double c1 = (4/3/Pi)*(dist/xDist + dist/yDist); double c2 = ((11/3/Pi) - 1 )*(dist*dist/(yDist*xDist)); double fc1c2 = 1 - c1-c2; if( fc1c2 < 0 ) { cerr << "Bogus fc1c2 of " << fc1c2 << endl; exit(1); } frank(distpt) += fc1c2; } } } } // next tar } // next foc double area = xDist*yDist; double areaDens = area/(treeDensity*(treeDensity-1)); int ppp=0; for(distpt=0;distpt<numAnn; distpt++) { for(ppp=0; ppp<distpt; ppp++) { kripley(distpt) += ripknl(ppp); kfrank(distpt) += frank(ppp); } kripley(distpt) = areaDens * kripley(distpt); kfrank(distpt) = areaDens * kfrank(distpt); } int ddd; for(ddd=0; ddd<numAnn; ddd++) { lripley(ddd) = sqrt(kripley(ddd)/Pi); lfrank(ddd) = sqrt(kfrank(ddd)/Pi); double d = ddd*widAnn; double c1 = (4/(3*Pi))*(d/xDist + d/yDist); double c2 = (4- 35/(3*Pi))*(d*d/area); double corr = 1-c1-c2; ce95(ddd) = 1.95*sqrt(areaDens/(2*Pi*corr)); l_d(ddd) = lripley(ddd) - d; if( ddd>0 ) pdf(ddd) = lripley(ddd) - lripley(ddd-1) - widAnn; } cout << " Tree density was" << treeDensity << endl; for(ddd=0; ddd<numAnn; ddd++) { // cout << head << ddd*widAnn << l_d(ddd) << endl; cout << ddd*widAnn << "\t" << lripley(ddd) << "\t" << l_d(ddd) << "\t" << ce95(ddd); if( fabs(l_d(ddd)) >= ce95(ddd)) cout << "\t*"; else cout << "\t"; cout << "\t" << pdf(ddd) << endl; } } void focBound(int & focb1, int & focb2, int fx, int fy, int xDist, int yDist) { // Nearest boundary distance focb1 = min(min(fx,xDist-fx), min(fy, yDist-fy)); // Second closest boundary if( focb1 == fx || focb1 == xDist-fx) focb2 = min(fy, yDist-fy); else focb2 = min(fx, xDist-fx); }
24.94375
118
0.532448
lsaravia
768a3b303b0142b532a7689994c0a4a824c3464c
3,823
cpp
C++
test/Rational/main.cpp
Enseed/GenericMath
d54ae97ddaaeb25842371f16f9889a05dac6754d
[ "Apache-2.0" ]
null
null
null
test/Rational/main.cpp
Enseed/GenericMath
d54ae97ddaaeb25842371f16f9889a05dac6754d
[ "Apache-2.0" ]
null
null
null
test/Rational/main.cpp
Enseed/GenericMath
d54ae97ddaaeb25842371f16f9889a05dac6754d
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* Copyright 2008 Enseed inc. 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. Author: Gaspard Petit *******************************************************************************/ #include <Generic/Math/Rational.h> #include <iostream> using namespace std; ostream& operator << (ostream& os, const Rational &r) { os << r.numerator() << '/' << r.denominator(); return os; } int main(int argc, const char *argv[]) { /*************************************************************************** * Today, we test the Rational object. * * The Rational object represends a number as A/B. A is the numerator * while B is the denominator. This is convenient, because you can * keep exact representation of numbers that cannot be correctly * represented as floats or doubles (for example, 1/3). * **************************************************************************/ /*************************************************************************** * INITIALISATION * * A Rational object can be initialized in two ways: */ Rational rat1(1, 2); // 1/2 Rational rat2 = Rational::fromFloat(0.75); /* * Great, now we have two rationals, let's see what they are: */ cout << "rat1 = " << rat1 << endl; cout << "rat2 = " << rat2 << endl; /* * You can also express them as floats if you prefer... */ cout << "rat1 = " << rat1.toFloat() << endl; cout << "rat2 = " << rat2.toFloat() << endl; /* * ... or as doubles */ cout << "rat1 = " << rat1.toDouble() << endl; cout << "rat2 = " << rat2.toDouble() << endl; /* * You have to be careful with the Rational::fromFloat function - some * numbers, though very simple in base 10, cannot be expressed correctly * in base 2. For example: */ Rational rat3 = Rational::fromFloat(1.9); cout << "this is nasty: 1.9 = " << rat3 << " = " << rat3.toDouble() << endl; /* * You can also do all kinds of operations with rationals: */ cout << rat1 << " + " << rat2 << " = " << rat1 + rat2 << endl; cout << rat1 << " - " << rat2 << " = " << rat1 - rat2 << endl; cout << rat1 << " * " << rat2 << " = " << rat1 * rat2 << endl; cout << rat1 << " / " << rat2 << " = " << rat1 / rat2 << endl; cout << rat1 << " + " << "3" << " = " << rat1 + 3 << endl; cout << rat1 << " - " << "3" << " = " << rat1 - 3 << endl; cout << rat1 << " * " << "3" << " = " << rat1 * 3 << endl; cout << rat1 << " / " << "3" << " = " << rat1 / 3 << endl; cout << "3" << " + " << rat1 << " = " << 3 + rat1 << endl; cout << "3" << " - " << rat1 << " = " << 3 - rat1 << endl; cout << "3" << " * " << rat1 << " = " << 3 * rat1 << endl; cout << "3" << " / " << rat1 << " = " << 3 / rat1 << endl; cout << "~" << rat1 << " = " << ~rat1 << endl; return 0; }
35.073394
80
0.542506
Enseed
768b1e397ac35290164c077a55ca2a16397fb23a
4,551
cpp
C++
src/hybrid_window.cpp
edublancas/dplyr
3ace34bf8eaec8295d5a7f09ab19947ced3438cd
[ "MIT" ]
1
2020-10-19T20:04:09.000Z
2020-10-19T20:04:09.000Z
src/hybrid_window.cpp
edublancas/dplyr
3ace34bf8eaec8295d5a7f09ab19947ced3438cd
[ "MIT" ]
null
null
null
src/hybrid_window.cpp
edublancas/dplyr
3ace34bf8eaec8295d5a7f09ab19947ced3438cd
[ "MIT" ]
1
2020-10-20T17:53:42.000Z
2020-10-20T17:53:42.000Z
#include "pch.h" #include <dplyr/main.h> #include <dplyr/HybridHandlerMap.h> #include <dplyr/Result/ILazySubsets.h> #include <dplyr/Result/Rank.h> using namespace Rcpp; using namespace dplyr; namespace dplyr { template <bool ascending> Result* row_number_asc(const RObject& data) { switch (TYPEOF(data)) { case INTSXP: return new RowNumber<INTSXP, ascending>(data); case REALSXP: return new RowNumber<REALSXP, ascending>(data); case STRSXP: return new RowNumber<STRSXP, ascending>(data); default: return 0; } } Result* row_number(const RObject& data, const bool ascending) { if (ascending) { return row_number_asc<true>(data); } else { return row_number_asc<false>(data); } } Result* row_number_prototype(SEXP call, const ILazySubsets& subsets, int nargs) { if (nargs > 1 || subsets.size() == 0) return 0; if (nargs == 0) return new RowNumber_0(); RObject data(CADR(call)); bool ascending = true; if (TYPEOF(data) == LANGSXP && CAR(data) == Rf_install("desc")) { data = CADR(data); ascending = false; } if (TYPEOF(data) == SYMSXP) { SymbolString name = SymbolString(Symbol(data)); if (subsets.has_non_summary_variable(name)) data = subsets.get_variable(name); else return 0; } if (subsets.nrows() != Rf_length(data)) return 0; return row_number(data, ascending); } template <bool ascending> Result* ntile_asc(const RObject& data, const int number_tiles) { switch (TYPEOF(data)) { case INTSXP: return new Ntile<INTSXP, ascending>(data, number_tiles); case REALSXP: return new Ntile<REALSXP, ascending>(data, number_tiles); case STRSXP: return new Ntile<STRSXP, ascending>(data, number_tiles); default: return 0; } } Result* ntile(const RObject& data, const int number_tiles, const bool ascending) { if (ascending) { return ntile_asc<true>(data, number_tiles); } else { return ntile_asc<false>(data, number_tiles); } } Result* ntile_prototype(SEXP call, const ILazySubsets& subsets, int nargs) { if (nargs != 2) return 0; // handle 2nd arg SEXP ntiles = maybe_rhs(CADDR(call)); if (TYPEOF(ntiles) != INTSXP && TYPEOF(ntiles) != REALSXP) return 0; int number_tiles = as<int>(ntiles); if (number_tiles == NA_INTEGER) return 0; RObject data(maybe_rhs(CADR(call))); bool ascending = true; if (TYPEOF(data) == LANGSXP && CAR(data) == Rf_install("desc")) { data = CADR(data); ascending = false; } if (TYPEOF(data) == SYMSXP) { SymbolString name = SymbolString(Symbol(data)); if (subsets.has_non_summary_variable(name)) data = subsets.get_variable(name); else return 0; } if (subsets.nrows() != Rf_length(data)) return 0; return ntile(data, number_tiles, ascending); } template <typename Increment, bool ascending> Result* rank_asc(const RObject& data) { switch (TYPEOF(data)) { case INTSXP: return new Rank_Impl<INTSXP, Increment, ascending>(data); case REALSXP: return new Rank_Impl<REALSXP, Increment, ascending>(data); case STRSXP: return new Rank_Impl<STRSXP, Increment, ascending>(data); default: return 0; } } template <typename Increment> Result* rank(const RObject& data, bool ascending) { if (ascending) { return rank_asc<Increment, true>(data); } else { return rank_asc<Increment, false>(data); } } template <typename Increment> Result* rank_impl_prototype(SEXP call, const ILazySubsets& subsets, int nargs) { if (nargs != 1) return 0; RObject data(maybe_rhs(CADR(call))); bool ascending = true; if (TYPEOF(data) == LANGSXP && CAR(data) == Rf_install("desc")) { data = maybe_rhs(CADR(data)); ascending = false; } if (TYPEOF(data) == SYMSXP) { SymbolString name = SymbolString(Symbol(data)); if (subsets.has_non_summary_variable(name)) data = subsets.get_variable(name); else return 0; } if (subsets.nrows() != Rf_length(data)) return 0; return rank<Increment>(data, ascending); } } void install_window_handlers(HybridHandlerMap& handlers) { handlers[ Rf_install("row_number") ] = row_number_prototype; handlers[ Rf_install("ntile") ] = ntile_prototype; handlers[ Rf_install("min_rank") ] = rank_impl_prototype<dplyr::internal::min_rank_increment>; handlers[ Rf_install("percent_rank") ] = rank_impl_prototype<dplyr::internal::percent_rank_increment>; handlers[ Rf_install("dense_rank") ] = rank_impl_prototype<dplyr::internal::dense_rank_increment>; handlers[ Rf_install("cume_dist") ] = rank_impl_prototype<dplyr::internal::cume_dist_increment>; }
27.251497
104
0.69633
edublancas
7693859c18fea97bc702f87f58ebc274cff29972
10,711
cpp
C++
TRAP/src/Graphics/Renderer2D.cpp
GamesTrap/TRAP
007de9ce70273cb8ae11066cc8488d9db78b1038
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-23T18:18:19.000Z
2019-05-27T21:10:07.000Z
TRAP/src/Graphics/Renderer2D.cpp
GamesTrap/TRAP
007de9ce70273cb8ae11066cc8488d9db78b1038
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
88
2018-08-02T01:08:04.000Z
2019-07-24T19:13:26.000Z
TRAP/src/Graphics/Renderer2D.cpp
GamesTrap/TRAP
007de9ce70273cb8ae11066cc8488d9db78b1038
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
2
2018-08-02T01:10:40.000Z
2020-08-14T14:05:58.000Z
#include "TRAPPCH.h" #include "Renderer2D.h" #include "Buffers/VertexArray.h" #include "Shaders/Shader.h" #include "Buffers/UniformBuffer.h" #include "RenderCommand.h" #include "Application.h" #include "Embed.h" #include "Cameras/Camera.h" #include "Textures/TextureManager.h" namespace TRAP::Graphics { struct QuadVertex { Math::Vec3 Position; Math::Vec4 Color; Math::Vec2 TexCoord; float TexIndex; }; struct Renderer2DData { static constexpr uint32_t MaxQuads = 20000; static constexpr uint32_t MaxVertices = MaxQuads * 4; static constexpr uint32_t MaxIndices = MaxQuads * 6; static constexpr uint32_t MaxTextureSlots = 32; //TODO: RenderCaps (OpenGL already has GetMaxTextureUnits()) Scope<VertexArray> QuadVertexArray; Scope<VertexBuffer> QuadVertexBuffer; Scope<Shader> TextureShader; Scope<Texture2D> WhiteTexture; Scope<std::array<QuadVertex, MaxVertices>> QuadVertices = MakeScope<std::array<QuadVertex, MaxVertices>>(); uint32_t QuadIndexCount = 0; QuadVertex* QuadVertexBufferBase = nullptr; QuadVertex* QuadVertexBufferPtr = nullptr; std::array<Texture2D*, MaxTextureSlots> TextureSlots{}; uint32_t TextureSlotIndex = 1; //0 = White texture std::array<Math::Vec4, 4> QuadVertexPositions{}; Renderer2D::Statistics Stats; Scope<UniformBuffer> CameraUniformBuffer; struct UniformCamera { Math::Mat4 ProjectionMatrix{ 1.0f }; Math::Mat4 ViewMatrix{ 1.0f }; } UniformCamera; }; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Graphics::Renderer2DData TRAP::Graphics::Renderer2D::s_data{}; //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::Init() { TP_PROFILE_FUNCTION(); TP_DEBUG(Log::Renderer2DPrefix, "Initializing"); s_data.QuadVertexArray = VertexArray::Create(); s_data.QuadVertexBuffer = VertexBuffer::Create(Renderer2DData::MaxVertices * sizeof(QuadVertex)); s_data.QuadVertexBuffer->SetLayout ({ { ShaderDataType::Float3, "Position" }, { ShaderDataType::Float4, "Color" }, { ShaderDataType::Float2, "TexCoord" }, { ShaderDataType::Float, "TexIndex" } }); s_data.QuadVertexArray->SetVertexBuffer(s_data.QuadVertexBuffer); s_data.QuadVertexBufferBase = (*s_data.QuadVertices).data(); Scope<std::array<uint32_t, Renderer2DData::MaxIndices>> quadIndices = MakeScope<std::array<uint32_t, Renderer2DData::MaxIndices>>(); for(uint32_t offset = 0, i = 0; i < Renderer2DData::MaxIndices; i += 6) { (*quadIndices)[i + 0] = offset + 0; (*quadIndices)[i + 1] = offset + 1; (*quadIndices)[i + 2] = offset + 2; (*quadIndices)[i + 3] = offset + 2; (*quadIndices)[i + 4] = offset + 3; (*quadIndices)[i + 5] = offset + 0; offset += 4; } Scope<IndexBuffer> quadIndexBuffer = IndexBuffer::Create((*quadIndices).data(), Renderer2DData::MaxIndices); s_data.QuadVertexArray->SetIndexBuffer(quadIndexBuffer); quadIndices.reset(); s_data.CameraUniformBuffer = UniformBuffer::Create("CameraBuffer", &s_data.UniformCamera, sizeof(Renderer2DData::UniformCamera), BufferUsage::Stream); s_data.TextureShader = Shader::CreateFromSource("Renderer2D", Embed::Renderer2DVS, Embed::Renderer2DFS); const Scope<Image> whiteImage = Image::LoadFromMemory(1, 1, Image::ColorFormat::RGBA, std::vector<uint8_t>{255, 255, 255, 255}); s_data.WhiteTexture = Texture2D::CreateFromImage("Renderer2DWhite", whiteImage); std::array<int32_t, Renderer2DData::MaxTextureSlots> samplers{}; for (uint32_t i = 0; i < Renderer2DData::MaxTextureSlots; i++) samplers[i] = i; //Set first texture slot to 0 s_data.TextureSlots[0] = s_data.WhiteTexture.get(); s_data.QuadVertexPositions[0] = { -0.5f, -0.5f, 0.0f, 1.0f }; s_data.QuadVertexPositions[1] = { 0.5f, -0.5f, 0.0f, 1.0f }; s_data.QuadVertexPositions[2] = { 0.5f, 0.5f, 0.0f, 1.0f }; s_data.QuadVertexPositions[3] = { -0.5f, 0.5f, 0.0f, 1.0f }; TextureManager::Get2D("Fallback2D")->Bind(0); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::Shutdown() { TP_PROFILE_FUNCTION(); TP_DEBUG(Log::Renderer2DPrefix, "Shutting down"); s_data.CameraUniformBuffer.reset(); s_data.TextureShader.reset(); s_data.WhiteTexture.reset(); s_data.QuadVertexArray->Unbind(); s_data.QuadVertexArray.reset(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::BeginScene(const Camera& camera, const Math::Mat4& transform) { TP_PROFILE_FUNCTION(); s_data.UniformCamera.ProjectionMatrix = camera.GetProjectionMatrix(); s_data.UniformCamera.ViewMatrix = Math::Inverse(transform); //Bind Shader s_data.TextureShader->Bind(); StartBatch(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::BeginScene(const OrthographicCamera& camera) { TP_PROFILE_FUNCTION(); s_data.UniformCamera.ProjectionMatrix = camera.GetProjectionMatrix(); s_data.UniformCamera.ViewMatrix = camera.GetViewMatrix(); //Bind Shader s_data.TextureShader->Bind(); StartBatch(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::EndScene() { TP_PROFILE_FUNCTION(); Flush(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::Flush() { if (s_data.QuadIndexCount == 0) return; //Nothing to render //Update Camera s_data.CameraUniformBuffer->UpdateData(&s_data.UniformCamera); s_data.CameraUniformBuffer->Bind(0); //Bind Vertex Array s_data.QuadVertexArray->Bind(); const uint32_t dataSize = static_cast<uint32_t>(reinterpret_cast<uint8_t*>(s_data.QuadVertexBufferPtr) - reinterpret_cast<uint8_t*>(s_data.QuadVertexBufferBase)); s_data.QuadVertexArray->GetVertexBuffer()->SetData(s_data.QuadVertexBufferBase, dataSize); //Bind textures for (uint32_t i = 0; i < s_data.TextureSlotIndex; i++) s_data.TextureSlots[i]->Bind(i); RenderCommand::DrawIndexed(s_data.QuadVertexArray, s_data.QuadIndexCount); s_data.Stats.DrawCalls++; } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::StartBatch() { s_data.QuadIndexCount = 0; s_data.QuadVertexBufferPtr = s_data.QuadVertexBufferBase; s_data.TextureSlotIndex = 1; } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::NextBatch() { Flush(); StartBatch(); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::DrawQuad(const Transform& transform, const Math::Vec4& color) { DrawQuad(transform, color, s_data.WhiteTexture); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::DrawQuad(const Transform& transform, const Scope<Texture2D>& texture) { DrawQuad(transform, Math::Vec4(1.0f), texture); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::DrawQuad(const Transform& transform, const Math::Vec4& color, const Scope<Texture2D>& texture) { TP_PROFILE_FUNCTION(); Math::Mat4 transformation; if (transform.Rotation.x != 0.0f || transform.Rotation.y != 0.0f || transform.Rotation.z != 0.0f) transformation = Math::Translate(transform.Position) * Mat4Cast(Math::Quaternion(Radians(transform.Rotation))) * Math::Scale(transform.Scale); else transformation = Math::Translate(transform.Position) * Math::Scale(transform.Scale); DrawQuad(transformation, color, texture); } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::DrawQuad(const Math::Mat4& transform, const Math::Vec4& color, const Scope<Texture2D>& texture) { constexpr uint64_t quadVertexCount = 4; constexpr std::array<Math::Vec2, 4> textureCoords = { {{0.0f, 0.0f}, {1.0f, 0.0f}, {1.0f, 1.0f}, {0.0f, 1.0f}} }; if (s_data.QuadIndexCount >= Renderer2DData::MaxIndices) NextBatch(); const float textureIndex = GetTextureIndex(texture); for (uint64_t i = 0; i < quadVertexCount; i++) { s_data.QuadVertexBufferPtr->Position = Math::Vec3(transform * s_data.QuadVertexPositions[i]); s_data.QuadVertexBufferPtr->Color = color; s_data.QuadVertexBufferPtr->TexCoord = textureCoords[i]; s_data.QuadVertexBufferPtr->TexIndex = textureIndex; s_data.QuadVertexBufferPtr++; } s_data.QuadIndexCount += 6; s_data.Stats.QuadCount++; } //-------------------------------------------------------------------------------------------------------------------// float TRAP::Graphics::Renderer2D::GetTextureIndex(const Scope<Texture2D>& texture) { float textureIndex = 0.0f; if (!texture) return textureIndex; for (uint32_t i = 1; i < s_data.TextureSlotIndex; i++) { if (s_data.TextureSlots[i] == texture.get()) { textureIndex = static_cast<float>(i); break; } } if (textureIndex == 0.0f) { if (s_data.TextureSlotIndex >= Renderer2DData::MaxTextureSlots) NextBatch(); textureIndex = static_cast<float>(s_data.TextureSlotIndex); s_data.TextureSlots[s_data.TextureSlotIndex] = texture.get(); s_data.TextureSlotIndex++; } return textureIndex; } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Graphics::Renderer2D::Statistics::GetTotalVertexCount() const { return QuadCount * 4; } //-------------------------------------------------------------------------------------------------------------------// uint32_t TRAP::Graphics::Renderer2D::Statistics::GetTotalIndexCount() const { return QuadCount * 6; } //-------------------------------------------------------------------------------------------------------------------// TRAP::Graphics::Renderer2D::Statistics TRAP::Graphics::Renderer2D::GetStats() { return s_data.Stats; } //-------------------------------------------------------------------------------------------------------------------// void TRAP::Graphics::Renderer2D::ResetStats() { std::memset(&s_data.Stats, 0, sizeof(Statistics)); }
32.359517
151
0.586033
GamesTrap
769386d37046607a690418cdc0e2ccc6e39c0e61
737
cpp
C++
src/Pandacoin/Address.cpp
justthedoctor/wallet-core
c0d9e9144f89919fcde67c192b8c5e1c2e5e4c6b
[ "MIT" ]
null
null
null
src/Pandacoin/Address.cpp
justthedoctor/wallet-core
c0d9e9144f89919fcde67c192b8c5e1c2e5e4c6b
[ "MIT" ]
null
null
null
src/Pandacoin/Address.cpp
justthedoctor/wallet-core
c0d9e9144f89919fcde67c192b8c5e1c2e5e4c6b
[ "MIT" ]
null
null
null
// Copyright © 2017-2019 Trust. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #pragma once namespace TW::Pandacoin { class Address { /// Determines whether a string makes a valid address. static bool isValid(const std::string& string); /// Initializes an address from a string representation. Address(const std::string& string); /// Initializes an address from a public key. Address(const PublicKey& publicKey); /// Returns a string representation of the address. std::string string() const; }; } // namespace TW::Pandacoin
29.48
77
0.717775
justthedoctor
7698a3aec2f0962c3babeda904b51bfd9d595a83
2,104
cpp
C++
laborator-1/l1_252/main.cpp
mcmarius/poo
ba380d170d30feb1cb3d52026bf8761ae0d6324a
[ "Unlicense" ]
15
2020-10-30T21:50:50.000Z
2022-03-25T14:20:53.000Z
altele/2020-2021/l1_252/main.cpp
Moarcas/poo-1
bf520c749067a9280cf5e1077e54be9dd3d68dba
[ "Unlicense" ]
null
null
null
altele/2020-2021/l1_252/main.cpp
Moarcas/poo-1
bf520c749067a9280cf5e1077e54be9dd3d68dba
[ "Unlicense" ]
4
2020-10-31T21:42:44.000Z
2022-03-25T14:20:44.000Z
#include <iostream> class trotineta { std::string culoare; int nr_roti; public: trotineta(const std::string &culoare = "verde", int nrRoti = 2) : culoare(culoare), nr_roti(nrRoti) { std::cout << "constr trotineta\n"; } ~trotineta() { std::cout << "destr trotineta\n"; } }; class bicicleta { std::string culoare; int nr_roti_ajutatoare; public: bicicleta(const std::string &culoare = "galben", int nrRoti = 2) : culoare(culoare), nr_roti_ajutatoare(nrRoti) { std::cout << "constr bicla\n"; } ~bicicleta() { std::cout << "destr bicla\n"; } }; class motor { int cai_putere; public: void run() { std::cout << "motor goes brr\n"; } motor(int caiPutere) : cai_putere(caiPutere) { std::cout << "constr motor " << cai_putere << "\n"; } motor(const motor& copie) : cai_putere(copie.cai_putere - 10) { std::cout << "cc motor\n"; } ~motor() { std::cout << "destr motor " << cai_putere << "\n"; } }; class vehicul_electric { motor m; int capacitate_baterie; bool se_incarca; static int nr; public: vehicul_electric(motor m = motor(50)) : m(m) { ++nr; std::cout << "constr v electric\n"; } virtual ~vehicul_electric() = 0; static int getNr() { return nr; } }; int vehicul_electric::nr; vehicul_electric::~vehicul_electric() { --nr; std::cout << "destr v electric\n"; } class trotineta_electrica : trotineta, public vehicul_electric { public: trotineta_electrica() { std::cout << "constr trotineta electrica\n"; } virtual ~trotineta_electrica() { { std::cout << "destr trotineta electrica\n"; } } }; class bicicleta_electrica : bicicleta, public vehicul_electric { public: bicicleta_electrica() {} }; int main() { trotineta_electrica t; vehicul_electric& v = t; std::cout << t.getNr() << "\n"; bicicleta_electrica b; std::cout << v.getNr() << "\n"; // t.~trotineta_electrica(); { trotineta tr; } return 0; }
20.038095
117
0.58365
mcmarius
769d00b2042c81e983dc22226c5ef689a92d1809
2,432
hpp
C++
dep/win/include/boost/histogram/detail/common_type.hpp
Netis/packet-agent
70da3479051a07e3c235abe7516990f9fd21a18a
[ "BSD-3-Clause" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
dep/win/include/boost/histogram/detail/common_type.hpp
Netis/packet-agent
70da3479051a07e3c235abe7516990f9fd21a18a
[ "BSD-3-Clause" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
dep/win/include/boost/histogram/detail/common_type.hpp
Netis/packet-agent
70da3479051a07e3c235abe7516990f9fd21a18a
[ "BSD-3-Clause" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
// Copyright 2015-2018 Hans Dembinski // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_HISTOGRAM_DETAIL_COMMON_TYPE_HPP #define BOOST_HISTOGRAM_DETAIL_COMMON_TYPE_HPP #include <boost/histogram/detail/meta.hpp> #include <boost/histogram/fwd.hpp> #include <boost/mp11/list.hpp> #include <boost/mp11/utility.hpp> #include <tuple> #include <type_traits> namespace boost { namespace histogram { namespace detail { // clang-format off template <class T, class U> using common_axes = mp11::mp_cond< is_tuple<T>, T, is_tuple<U>, U, is_sequence_of_axis<T>, T, is_sequence_of_axis<U>, U, std::true_type, T >; template <class T, class U> using common_container = mp11::mp_cond< is_array_like<T>, T, is_array_like<U>, U, is_vector_like<T>, T, is_vector_like<U>, U, std::true_type, T >; // clang-format on template <class T> using type_score = mp11::mp_size_t<((!std::is_pod<T>::value) * 1000 + std::is_floating_point<T>::value * 50 + sizeof(T))>; template <class T, class U> struct common_storage_impl; template <class T, class U> struct common_storage_impl<storage_adaptor<T>, storage_adaptor<U>> { using type = mp11::mp_if_c<(type_score<typename storage_adaptor<T>::value_type>::value >= type_score<typename storage_adaptor<U>::value_type>::value), storage_adaptor<T>, storage_adaptor<U>>; }; template <class T, class A> struct common_storage_impl<storage_adaptor<T>, unlimited_storage<A>> { using type = mp11::mp_if_c<(type_score<typename storage_adaptor<T>::value_type>::value >= type_score<typename unlimited_storage<A>::value_type>::value), storage_adaptor<T>, unlimited_storage<A>>; }; template <class C, class A> struct common_storage_impl<unlimited_storage<A>, storage_adaptor<C>> : common_storage_impl<storage_adaptor<C>, unlimited_storage<A>> {}; template <class A1, class A2> struct common_storage_impl<unlimited_storage<A1>, unlimited_storage<A2>> { using type = unlimited_storage<A1>; }; template <class A, class B> using common_storage = typename common_storage_impl<A, B>::type; } // namespace detail } // namespace histogram } // namespace boost #endif
30.78481
89
0.686266
Netis
37200938914b2178b42413c7dd8b6844e8db3400
3,839
cpp
C++
src/kdev_discord.cpp
FiniteReality/kdev_discord
3cac16a7272c5396e20ea16a687266e10db2e16d
[ "MIT" ]
5
2018-05-28T10:30:38.000Z
2020-08-08T20:14:32.000Z
src/kdev_discord.cpp
FiniteReality/kdev_discord
3cac16a7272c5396e20ea16a687266e10db2e16d
[ "MIT" ]
1
2020-06-22T16:59:50.000Z
2021-08-30T19:03:02.000Z
src/kdev_discord.cpp
FiniteReality/kdev_discord
3cac16a7272c5396e20ea16a687266e10db2e16d
[ "MIT" ]
1
2020-06-17T20:33:41.000Z
2020-06-17T20:33:41.000Z
#include "kdev_discord.h" #include <debug.h> #include <QRegularExpression> #include <KPluginFactory> #include <interfaces/icore.h> #include <interfaces/idocumentcontroller.h> #include <interfaces/isession.h> #include <interfaces/iprojectcontroller.h> #include <interfaces/iproject.h> #include <KTextEditor/Document> #include <discord_rpc.h> #define APPID "429055143087177730" static bool discordReady; static bool running; static void SetDefaultState(); K_PLUGIN_FACTORY_WITH_JSON(kdev_discordFactory, "kdev_discord.json", registerPlugin<kdev_discord>(); ) kdev_discord::kdev_discord(QObject *parent, const QVariantList& args) : KDevelop::IPlugin(QStringLiteral("kdev_discord"), parent) { Q_UNUSED(args); discordReady = false; auto* documentController = core()->documentController(); QObject::connect( documentController, SIGNAL(documentActivated(KDevelop::IDocument*)), this, SLOT(onDocumentActivated(KDevelop::IDocument*))); load(); } void kdev_discord::load() { running = true; DiscordEventHandlers handlers; memset(&handlers, 0, sizeof(handlers)); handlers.ready = [](const DiscordUser*){ discordReady = true; SetDefaultState(); }; callbackThread = std::thread([]() { while (running) { const std::chrono::duration<int64_t, std::milli> sleepTime{500LL}; Discord_RunCallbacks(); std::this_thread::sleep_for(sleepTime); } }); Discord_Initialize(APPID, &handlers, 1, nullptr); } void kdev_discord::unload() { discordReady = false; Discord_Shutdown(); running = false; callbackThread.join(); } void kdev_discord::onDocumentActivated(KDevelop::IDocument* document) { if (document->isTextDocument()) setCurrentFile(document); } void kdev_discord::setCurrentFile(KDevelop::IDocument* document) { if (discordReady) { KTextEditor::Document* textDoc = document->textDocument(); auto fileName = textDoc->documentName(); auto fileType = textDoc->mimeType(); auto session = core()->activeSession(); auto projectCtrl = core()->projectController(); auto project = projectCtrl == nullptr ? nullptr : projectCtrl->findProjectForUrl(document->url()); if (session != nullptr && projectCtrl != nullptr && project != nullptr) { auto projects = session->containedProjects(); auto sessionProjs = QString::number(projects.size()); auto sessionName = session->name(); auto sessionDesc = session->description(); auto projectName = project->name(); QString state = "Editing some code"; QString details = fileName; if (!sessionName.isEmpty()) state = "In session " + sessionName + " (" + sessionProjs + " projects)"; if (!projectName.isEmpty()) details = fileName + " in " + projectName; DiscordRichPresence presence; memset(&presence, 0, sizeof(presence)); presence.state = state.toUtf8().constData(); presence.details = details.toUtf8().constData(); presence.largeImageKey = "kdev_logo"; presence.largeImageText = sessionDesc.toUtf8().constData(); presence.startTimestamp = time(nullptr); Discord_UpdatePresence(&presence); } } } static void SetDefaultState() { DiscordRichPresence presence; memset(&presence, 0, sizeof(presence)); presence.state = "Idle"; presence.largeImageKey = "kdev_logo"; presence.startTimestamp = time(nullptr); Discord_UpdatePresence(&presence); } // needed for QObject class created from K_PLUGIN_FACTORY_WITH_JSON #include "kdev_discord.moc"
26.659722
102
0.648085
FiniteReality
37238744afa24c58aac13b73c6bb38b498473476
105
hpp
C++
src/physics/polygon.hpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
1
2020-09-23T11:17:35.000Z
2020-09-23T11:17:35.000Z
src/physics/polygon.hpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
src/physics/polygon.hpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <SFML/Graphics.hpp> using Polygon = std::vector<sf::Vector2f>;
15
42
0.72381
astrellon
3727fe483c2a80e9e79facc6d87eaed8bfa83eb7
665
cpp
C++
Dialogs/brightnessdialog.cpp
kalpanki/ocvGUI
9fc1f2278b414c316f091e1de5a4b1c4e3695ee9
[ "BSD-2-Clause" ]
2
2019-08-21T13:37:51.000Z
2019-10-18T01:39:53.000Z
Dialogs/brightnessdialog.cpp
kalpanki/ocvGUI
9fc1f2278b414c316f091e1de5a4b1c4e3695ee9
[ "BSD-2-Clause" ]
null
null
null
Dialogs/brightnessdialog.cpp
kalpanki/ocvGUI
9fc1f2278b414c316f091e1de5a4b1c4e3695ee9
[ "BSD-2-Clause" ]
null
null
null
#include "brightnessdialog.h" #include "ui_brightnessdialog.h" BrightnessDialog::BrightnessDialog(QWidget *parent) : QDialog(parent), ui(new Ui::BrightnessDialog) { ui->setupUi(this); } BrightnessDialog::~BrightnessDialog() { delete ui; } void BrightnessDialog::on_alphaDoubleSpinBox_valueChanged(double arg1) { double alpha = ui->alphaDoubleSpinBox->value(); int beta = ui->betaSpinBox->value(); sendBrightnessSignal(alpha, beta); } void BrightnessDialog::on_betaSpinBox_valueChanged(int arg1) { double alpha = ui->alphaDoubleSpinBox->value(); int beta = ui->betaSpinBox->value(); sendBrightnessSignal(alpha, beta); }
21.451613
70
0.726316
kalpanki
3730a40a6b71018014acf7061f965369160c608d
709
hpp
C++
tests/test_spin_lock.hpp
djmott/xtl
cadb963a3d1ad292033f08f4754c545066be75f7
[ "BSL-1.0" ]
6
2016-06-30T11:23:33.000Z
2019-10-22T13:09:49.000Z
tests/test_spin_lock.hpp
djmott/xtl
cadb963a3d1ad292033f08f4754c545066be75f7
[ "BSL-1.0" ]
null
null
null
tests/test_spin_lock.hpp
djmott/xtl
cadb963a3d1ad292033f08f4754c545066be75f7
[ "BSL-1.0" ]
4
2016-07-24T10:38:43.000Z
2021-04-02T11:18:09.000Z
/** @file xtd::concurrent::spin_lock system and unit tests @copyright David Mott (c) 2016. Distributed under the Boost Software License Version 1.0. See LICENSE.md or http://boost.org/LICENSE_1_0.txt for details. */ #include <xtd/concurrent/spin_lock.hpp> TEST(test_spin_lock, initialization){ xtd::concurrent::spin_lock oLock; } TEST(test_spin_lock, lock){ xtd::concurrent::spin_lock oLock; oLock.lock(); } TEST(test_spin_lock, unlock){ xtd::concurrent::spin_lock oLock; oLock.lock(); oLock.unlock(); } TEST(test_spin_lock, try_lock){ xtd::concurrent::spin_lock oLock; EXPECT_TRUE(oLock.try_lock()); EXPECT_FALSE(oLock.try_lock()); oLock.unlock(); EXPECT_TRUE(oLock.try_lock()); }
23.633333
153
0.736248
djmott
3739a84e1f47b2c087950d0297aabe106eec4f17
114
hpp
C++
include/memory/hadesmem/detail/warning_disable_suffix.hpp
phlip9/hadesmem
59e13a92c05918b8c842141fd5cac1ed390cd79e
[ "MIT" ]
19
2017-10-19T23:13:11.000Z
2022-03-29T11:37:26.000Z
include/memory/hadesmem/detail/warning_disable_suffix.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
null
null
null
include/memory/hadesmem/detail/warning_disable_suffix.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
10
2018-04-04T07:55:16.000Z
2021-11-23T20:22:43.000Z
// Copyright (C) 2010-2015 Joshua Boyce // See the file COPYING for copying permission. #pragma warning(pop)
22.8
48
0.719298
phlip9
373e8cc2d89af8d558b30c174ea3962fc1265ab2
2,135
cpp
C++
core/src/GLFWInput.cpp
matthew-oconnell/glitter
d9eb6cea96063f080121e9c6e59098e2d690c427
[ "Apache-2.0" ]
null
null
null
core/src/GLFWInput.cpp
matthew-oconnell/glitter
d9eb6cea96063f080121e9c6e59098e2d690c427
[ "Apache-2.0" ]
null
null
null
core/src/GLFWInput.cpp
matthew-oconnell/glitter
d9eb6cea96063f080121e9c6e59098e2d690c427
[ "Apache-2.0" ]
null
null
null
#include "GLFWInput.h" #include "Game.h" using namespace Glitter; GLFWInput::GLFWInput(GLFWwindow *window) : window(window){ glfwSetKeyCallback(window, key_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_position_callback); for (bool &keyboard_key : keyboard_keys) keyboard_key = false; for (bool &mouse_button : mouse_buttons) mouse_button = false; } void GLFWInput::key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { auto input = static_cast<Engine*>(glfwGetWindowUserPointer(window))->getInput(); if(action == GLFW_PRESS) input->keyboard_keys[key] = true; else if(action == GLFW_RELEASE) input->keyboard_keys[key] = false; } void GLFWInput::mouse_button_callback(GLFWwindow *window, int button, int action, int mods) { auto input = static_cast<Engine*>(glfwGetWindowUserPointer(window))->getInput(); if(action == GLFW_PRESS) input->mouse_buttons[button] = true; else if(action == GLFW_RELEASE) input->mouse_buttons[button] = false; } void GLFWInput::cursor_position_callback(GLFWwindow *window, double x, double y) { auto input = static_cast<Engine*>(glfwGetWindowUserPointer(window))->getInput(); input->mouse_x = (float)x; input->mouse_y = (float)y; } unsigned int GLFWInput::mapToGLFWKeycode(Player::Input::KEYS k) const { if(k == Player::Input::KEYS::W) return GLFW_KEY_W; if(k == Player::Input::KEYS::A) return GLFW_KEY_A; if(k == Player::Input::KEYS::S) return GLFW_KEY_S; if(k == Player::Input::KEYS::D) return GLFW_KEY_D; if(k == Player::Input::KEYS::SPACE) return GLFW_KEY_SPACE; return MAX_KEYBOARD_KEYS+1; } bool GLFWInput::pressed(Player::Input::KEYS k) const { unsigned int keycode = mapToGLFWKeycode(k); if(keycode > MAX_KEYBOARD_KEYS) return false; return keyboard_keys[keycode]; } bool GLFWInput::isMouseButtonPressed(unsigned int button_code) const { if(button_code > MAX_MOUSE_BUTTONS) return false; return mouse_buttons[button_code]; } Math::Vec2d GLFWInput::getCursorLocation() const { return {mouse_x, mouse_y}; }
34.435484
95
0.733958
matthew-oconnell
3743275a0c913f6817ce8effacc9cd07d6bbb7a6
251
hpp
C++
parser/nodes/stmt.hpp
cursorweb/Asula-Lang
173a814f92b977064a889febc69798a93c906ebe
[ "MIT" ]
2
2022-03-09T20:13:26.000Z
2022-03-10T14:18:19.000Z
parser/nodes/stmt.hpp
cursorweb/Asula-Lang
173a814f92b977064a889febc69798a93c906ebe
[ "MIT" ]
null
null
null
parser/nodes/stmt.hpp
cursorweb/Asula-Lang
173a814f92b977064a889febc69798a93c906ebe
[ "MIT" ]
null
null
null
#ifndef STMT_HPP #define STMT_HPP // visitor list class StmtVisitor; // stmt list class Stmt { public: virtual void accept(StmtVisitor visitor); }; // nodes // visitor list class StmtVisitor { public: // virtual C visit(); }; #endif
9.296296
45
0.673307
cursorweb
3746811b08e49103a4b553bc31698e84a064bff1
183
cpp
C++
applications/builder/source/builder_modes.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
applications/builder/source/builder_modes.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
applications/builder/source/builder_modes.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
#include "builder_modes.h" #undef _BUILDER_MODES_H_ #include "kernel/meta/macros/meta_macros_enum_cpp.h" #include "builder_modes.h" #include "kernel/meta/macros/meta_macros_enum_h.h"
30.5
52
0.819672
skarab
37475954f61c70fbc81285c66c8f93fdc0de4f55
1,261
cpp
C++
src/Panel2D.cpp
cfrpg/SourcePanelMethod
0d16482b345c0457e48935a53a06c63a9205bd22
[ "MIT" ]
null
null
null
src/Panel2D.cpp
cfrpg/SourcePanelMethod
0d16482b345c0457e48935a53a06c63a9205bd22
[ "MIT" ]
null
null
null
src/Panel2D.cpp
cfrpg/SourcePanelMethod
0d16482b345c0457e48935a53a06c63a9205bd22
[ "MIT" ]
null
null
null
#include "Panel2D.h" #include "MathHelper.h" #include <cmath> #include <cstdio> Panel2D::Panel2D(void) { } Panel2D::Panel2D(Vector2 _v1,Vector2 _v2) { v1=_v1; v2=_v2; midpoint=v1+v2; midpoint/=2; normal=-Vector2((v2-v1).y,-(v2-v1).x); angle=atan2(v2.y-v1.y,v2.x-v1.x); if(angle<0) angle+=2*PI; direction=(v2-v1); direction.Normalize(); normal.Normalize(); lengthSqure=(v2-v1).GetLengthSqure(); } Vector2 Panel2D::GetNormal() { return normal; } Vector2 Panel2D::GetMidpoint() { return midpoint; } void Panel2D::Reset(Vector2 _v1,Vector2 _v2) { v1=_v1; v2=_v2; midpoint=v1+v2; midpoint/=2; normal.x=-(v2-v1).y; normal.y=(v2-v1).x; angle=atan2(v2.y-v1.y,v2.x-v1.x); if(angle<0) angle+=2*PI; direction=(v2-v1); direction.Normalize(); } void Panel2D::Reverse() { normal=-normal; v1+=v2; v2=v1-v2; v1-=v2; } double Panel2D::GetAngle() { return angle; } Vector2 Panel2D::GetDirection() { return direction; } double Panel2D::GetX1() { return v1.x; } double Panel2D::GetY1() { return v1.y; } double Panel2D::GetX2() { return v2.x; } double Panel2D::GetY2() { return v2.y; } double Panel2D::GetLengthSqure() { return lengthSqure; } double Panel2D::GetLength() { return sqrt(lengthSqure); } Panel2D::~Panel2D(void) { }
12.485149
44
0.666931
cfrpg
37489c6dca94e1c7cd65ebf002e34f3feb15663f
1,365
cpp
C++
src/ScreenshotView.cpp
humdingerb/HaikuThemeManager
b38a77fc147cf4a8dc083b52ce4941b0a44cf160
[ "MIT" ]
4
2016-02-26T08:13:04.000Z
2019-11-17T22:15:04.000Z
src/ScreenshotView.cpp
humdingerb/HaikuThemeManager
b38a77fc147cf4a8dc083b52ce4941b0a44cf160
[ "MIT" ]
26
2017-01-05T04:18:51.000Z
2021-10-08T04:22:14.000Z
src/ScreenshotView.cpp
humdingerb/HaikuThemeManager
b38a77fc147cf4a8dc083b52ce4941b0a44cf160
[ "MIT" ]
4
2017-12-06T19:29:54.000Z
2020-10-26T07:27:34.000Z
/* * Copyright 2000-2008, François Revol, <revol@free.fr>. All rights reserved. * Distributed under the terms of the MIT License. */ #include "ScreenshotView.h" #include <View.h> #include <Bitmap.h> #include <stdio.h> #include <Debug.h> // PRIVATE: in libzeta for now. extern status_t ScaleBitmap(const BBitmap& inBitmap, BBitmap& outBitmap); ScreenshotView::ScreenshotView(BRect bounds, const char *name, uint32 resizeMask, uint32 flags) : BView(bounds, name, resizeMask, flags) { fBitmap = NULL; } ScreenshotView::~ScreenshotView() { if (fBitmap) delete fBitmap; } void ScreenshotView::AttachedToWindow() { UpdateScreenshot(); } void ScreenshotView::UpdateScreenshot() { if (Window() == NULL) return; ClearViewBitmap(); if (fBitmap) { #ifdef __HAIKU__ SetViewBitmap(fBitmap, fBitmap->Bounds(), Bounds(), B_FOLLOW_ALL, B_FILTER_BITMAP_BILINEAR); #else SetViewBitmap(fBitmap, fBitmap->Bounds(), Bounds()); #endif } Invalidate(); } void ScreenshotView::SetScreenshot(BBitmap *bitmap) { if (fBitmap) delete fBitmap; fBitmap = bitmap; #ifdef B_ZETA_VERSION if (bitmap) { BBitmap *scaled = new BBitmap(Bounds(), B_RGB32); status_t err = ENOSYS; err = ScaleBitmap(*bitmap, *scaled); if( err == B_OK ) { fBitmap = scaled; delete bitmap; } else delete scaled; } #endif UpdateScreenshot(); }
16.058824
77
0.698168
humdingerb
37498a6e0c3032f7f83715fff555ff0f0d506299
3,763
hpp
C++
include/rectojump/global/config_settings.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/global/config_settings.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
include/rectojump/global/config_settings.hpp
Malekblubb/rectojump
66c04e9a081bd1b830205bb0c515a42eeb4befb6
[ "MIT" ]
null
null
null
// // Copyright (c) 2013-2021 Christoph Malek // See LICENSE for more information. // #ifndef RJ_GLOBAL_CONFIG_SETTINGS_HPP #define RJ_GLOBAL_CONFIG_SETTINGS_HPP #include "config.hpp" #include <rectojump/shared/utils.hpp> #include <mlk/signals_slots/slot.h> #include <mlk/tools/utils.h> namespace rj { namespace settings { inline void init() { config::get(); } inline mlk::slot<>& on_changed() { return config::get().on_setting_changed; } // setters inline void set_window_size(const vec2u& size) { config::get().set_entry("window_width", size.x); config::get().set_entry("window_height", size.y); config::get().on_setting_changed(); } inline void set_fullscreen(bool b) { config::get().set_entry("fullscreen", b); config::get().on_setting_changed(); } inline void set_sound_volume(int vol) { config::get().set_entry("sound_volume", vol); } inline void set_color_light(const std::string& hex) { config::get().set_entry("color_light", hex); } inline void set_color_dark(const std::string& hex) { config::get().set_entry("color_dark", hex); } inline void set_color_default_dark(const std::string& hex) { config::get().set_entry("color_default_dark", hex); } inline void set_color_default_light(const std::string& hex) { config::get().set_entry("color_default_light", hex); } inline void set_editor_scroll_step(float step) { config::get().set_entry("editor_scroll_step", step); } inline void set_editor_settings_expanded(bool b) { config::get().set_entry("editor_settings_expanded", b); } inline void set_main_menu_effects(bool b) { config::get().set_entry("main_menu_effects", b); } // getters template <typename Vec_Type = vec2u, typename Val_Type = decltype(Vec_Type::x)> inline Vec_Type get_window_size() { return {config::get().get_entry<Val_Type>("window_width"), config::get().get_entry<Val_Type>("window_height")}; } inline bool get_fullscreen() { return config::get().get_entry<bool>("fullscreen"); } inline int get_sound_volume() { return config::get().get_entry<int>("sound_volume"); } inline sf::Color get_color_light() { return to_rgb(config::get().get_entry<std::string>("color_light")); } inline sf::Color get_color_dark() { return to_rgb(config::get().get_entry<std::string>("color_dark")); } inline sf::Color get_color_default_dark() { return to_rgb( config::get().get_entry<std::string>("color_default_dark")); } inline sf::Color get_color_default_light() { return to_rgb( config::get().get_entry<std::string>("color_default_light")); } inline float get_editor_scroll_step() { return config::get().get_entry<float>("editor_scroll_step"); } inline bool get_editor_settings_expanded() { return mlk::parse_bool(config::get().get_entry<std::string>( "editor_settings_expanded")); } inline bool get_main_menu_effects() { return mlk::parse_bool( config::get().get_entry<std::string>("main_menu_effects")); } // fixed settings inline std::string data_path() { return "data/"; } inline std::string level_path() { return "levels/"; } inline std::string rj_font() { return "Fipps-Regular.otf"; } inline std::string text_font() { return "Ubuntu-R.ttf"; } inline constexpr mlk::uint text_size() { return 15; } inline sf::Color text_color() { return to_rgb("#373737"); } inline std::string version() { return "0.0.0"; } inline constexpr float game_warmup_time() { return 1500.f; } inline constexpr float player_start_x() { return 100.f; } inline constexpr float player_start_y() { return 500.f; } }// namespace settings }// namespace rj #endif// RJ_GLOBAL_CONFIG_SETTINGS_HPP
24.594771
70
0.689078
Malekblubb
375874543e19c087fa3046111ddf0f636b1debad
322
cpp
C++
05. Matrix/02 Sum/ColWiseSum.cpp
samdev-py/100DaysOfCode
b0d96e42aeb657902153434c6a7ec8aec265f461
[ "MIT" ]
6
2021-10-30T10:18:11.000Z
2021-12-27T17:25:30.000Z
05. Matrix/02 Sum/ColWiseSum.cpp
samdev-py/Data-Structures-and-algorithms
b0d96e42aeb657902153434c6a7ec8aec265f461
[ "MIT" ]
null
null
null
05. Matrix/02 Sum/ColWiseSum.cpp
samdev-py/Data-Structures-and-algorithms
b0d96e42aeb657902153434c6a7ec8aec265f461
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void printColSum(int arr[][3], int row, int col) { cout << "The Column Sum: " << endl; for (col = 0; col < 3; col++) { int sum = 0; for (row = 0; row < 3; row++) { sum += arr[row][col]; } cout << sum << endl; } }
20.125
48
0.447205
samdev-py
375bc1d302d0377dc2250e4b16d042c88e17ee26
1,991
cpp
C++
viandanti/src/ofApp.cpp
npisanti/np-sketches
256203d73c8bedecc106157841e048731a7ab50a
[ "MIT" ]
1
2019-05-08T17:01:46.000Z
2019-05-08T17:01:46.000Z
viandanti/src/ofApp.cpp
npisanti/np-sketches
256203d73c8bedecc106157841e048731a7ab50a
[ "MIT" ]
null
null
null
viandanti/src/ofApp.cpp
npisanti/np-sketches
256203d73c8bedecc106157841e048731a7ab50a
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ gui.setup("panel", "settings.xml", ofGetWidth()-220, 20 ); gui.add( travelers.parameters ); gui.add( color.set("color", ofColor(255, 80, 80), ofColor(0), ofColor(255)) ); ofBackground(0); ofSetWindowTitle( "mouse controlled traveler" ); } //-------------------------------------------------------------- void ofApp::update(){ travelers.update(); } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor( color ); travelers.draw(); gui.draw(); } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ travelers.move( x, y ); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ travelers.enter(); travelers.move( x, y ); } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ travelers.move( x, y ); travelers.exit(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
24.280488
82
0.347062
npisanti
376581b25525deacf94b5e57d952d4caff20b7ae
486
cpp
C++
ackermann_ekf/src/ackermann_ekf_node.cpp
OssianEriksson/autonomous-twizy
d78e352c37dd4b2dcdd588b89e2bedb665e7175e
[ "Apache-2.0" ]
8
2021-03-18T21:49:43.000Z
2022-03-14T20:23:16.000Z
ackermann_ekf/src/ackermann_ekf_node.cpp
OssianEriksson/autonomous-twizy
d78e352c37dd4b2dcdd588b89e2bedb665e7175e
[ "Apache-2.0" ]
1
2021-04-04T20:25:34.000Z
2021-04-04T20:31:07.000Z
ackermann_ekf/src/ackermann_ekf_node.cpp
OssianEriksson/autonomous-twizy
d78e352c37dd4b2dcdd588b89e2bedb665e7175e
[ "Apache-2.0" ]
null
null
null
/** * @file ackermann_ekf_node.cpp * * @brief ROS node for sensor fusion using EKF based on Ackermann steering model * * @author Ossian Eriksson \<ossiane@student.chalmers.se\> */ #include "ackermann_ekf/sensor_array.h" #include <ros/ros.h> int main(int argc, char **argv) { ros::init(argc, argv, "ackermann_ekf"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); ackermann_ekf::SensorArray sensor_array(nh, nh_private); ros::spin(); return 0; }
20.25
80
0.679012
OssianEriksson
3766f65844cad48fcc4334bef5b61517063f7886
78
cpp
C++
test_package/example.cpp
sintef-ocean/conan-netcdf-c
7807ca2b743cfcd2b087bc9da950b05cf35ee5a3
[ "MIT" ]
null
null
null
test_package/example.cpp
sintef-ocean/conan-netcdf-c
7807ca2b743cfcd2b087bc9da950b05cf35ee5a3
[ "MIT" ]
1
2020-06-24T15:02:32.000Z
2020-06-24T15:02:32.000Z
test_package/example.cpp
sintef-ocean/conan-netcdf-c
7807ca2b743cfcd2b087bc9da950b05cf35ee5a3
[ "MIT" ]
null
null
null
#include <iostream> #include "netcdf.h" int main() { nc_inq_libvers(); }
11.142857
21
0.641026
sintef-ocean
376708cc4f0b1b35f45dc74e960d152b5223a1b6
854
cpp
C++
10703.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
10703.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
10703.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <algorithm> #include <string> using namespace std; int total,bawah,samping,n,x,y,z,kasus; int x1,x2,y1,y2; int peta[550][550]; int main() { kasus=0; do { scanf("%d %d %d",&samping,&bawah,&n); if(samping == 0) break; scanf("\n"); kasus++; total=samping*bawah; for(z=0;z<n;z++) { scanf("%d %d %d %d",&x1,&y1,&x2,&y2); for(y=min(y1,y2);y<=max(y1,y2);y++) for(x=min(x1,x2);x<=max(x1,x2);x++) if(peta[x][y] != kasus) { peta[x][y] = kasus; total--; } } switch(total) { case 0: printf("There is no empty spots.\n"); break; case 1: printf("There is one empty spot.\n"); break; default:printf("There are %d empty spots.\n",total); break; } } while(samping != 0); return 0; }
17.791667
64
0.522248
felikjunvianto
3767e93c4b093e02df6d37a0caebb926404eb729
681
cpp
C++
solutions-PAT/A1005.cpp
Ki-Seki/solutions
e4329712d664180d850e0a48d7d0f637215f13d0
[ "MIT" ]
1
2022-02-26T10:33:24.000Z
2022-02-26T10:33:24.000Z
solutions-PAT/A1005.cpp
Ki-Seki/solutions
e4329712d664180d850e0a48d7d0f637215f13d0
[ "MIT" ]
null
null
null
solutions-PAT/A1005.cpp
Ki-Seki/solutions
e4329712d664180d850e0a48d7d0f637215f13d0
[ "MIT" ]
1
2021-12-01T14:54:33.000Z
2021-12-01T14:54:33.000Z
#include <iostream> #include <cstring> #define MAXN 105 using namespace std; int main() { char number[MAXN], trans[10][7] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; scanf("%s", number); int len = strlen(number), sum = 0; for (int i = 0; i < len; i++) sum += number[i] - '0'; // due to the sum < 1000, there is no need to calculate the digit of var. sum if (0 <= sum && sum <= 9) printf("%s", trans[sum]); if (10 <= sum && sum <= 99) printf("%s %s", trans[sum/10], trans[sum%10]); if (100 <= sum && sum <= 999) printf("%s %s %s", trans[sum/100], trans[sum/10%10], trans[sum%10]); return 0; }
35.842105
119
0.54185
Ki-Seki
3769ec2ab96b5d2e4a3719d381e405a675d07bc5
1,313
hpp
C++
boost/network/protocol/http/message/header/value.hpp
antoinelefloch/cpp-netlib
5eb9b5550a10d06f064ee9883c7d942d3426f31b
[ "BSL-1.0" ]
3
2015-02-10T22:08:08.000Z
2021-11-13T20:59:25.000Z
include/boost/network/protocol/http/message/header/value.hpp
waTeim/boost
eb3850fae8c037d632244cf15cf6905197d64d39
[ "BSL-1.0" ]
1
2018-08-10T04:47:12.000Z
2018-08-10T13:54:57.000Z
include/boost/network/protocol/http/message/header/value.hpp
waTeim/boost
eb3850fae8c037d632244cf15cf6905197d64d39
[ "BSL-1.0" ]
5
2017-12-28T12:42:25.000Z
2021-07-01T07:41:53.000Z
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HEADER_VALUE_HPP_20101028 #define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HEADER_VALUE_HPP_20101028 // Copyright 2010 Dean Michael Berris. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <utility> namespace boost { namespace network { namespace http { struct request_header_narrow; struct request_header_wide; struct response_header_narrow; struct response_header_wide; template <class T1, class T2> T1 & value(std::pair<T1,T2> const & p) { return p.second; } inline request_header_narrow::string_type const & value(request_header_narrow const & h) { return h.value; } inline request_header_wide::string_type const & value(request_header_wide const & h) { return h.value; } inline response_header_narrow::string_type const & value(response_header_narrow const & h) { return h.value; } inline response_header_wide::string_type const & value(response_header_wide const & h) { return h.value; } } /* http */ } /* network */ } /* boost */ #endif /* BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_HEADER_VALUE_HPP_20101028 */
25.745098
74
0.708302
antoinelefloch
376a6dad0a17b41abfe64db72cd74e5167b63e16
11,676
cc
C++
src/pong.cc
tomredant/winpong
f5ef70852be4e1161dc5e8eeb8bc309571c20763
[ "MIT", "Unlicense" ]
null
null
null
src/pong.cc
tomredant/winpong
f5ef70852be4e1161dc5e8eeb8bc309571c20763
[ "MIT", "Unlicense" ]
null
null
null
src/pong.cc
tomredant/winpong
f5ef70852be4e1161dc5e8eeb8bc309571c20763
[ "MIT", "Unlicense" ]
null
null
null
// Copyright [2015] <Chafic Najjar> #include "src/pong.h" #include <iostream> #include "src/ball.h" #include "src/paddle.h" #include "src/utilities.h" #include <QFile> #include <QDir> // Screen resolution. const int Pong::SCREEN_WIDTH = 640; const int Pong::SCREEN_HEIGHT = 480; Pong::Pong(int argc, char *argv[]) { // Intialize SDL. SDL_Init(SDL_INIT_EVERYTHING); // Don't show cursor. SDL_ShowCursor(0); // Create window and renderer. window = SDL_CreateWindow("Winpong", SDL_WINDOWPOS_UNDEFINED, // Centered window. SDL_WINDOWPOS_UNDEFINED, // Centered window. SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); // Instantiate game objects. ball = new Ball(SCREEN_WIDTH/2-ball->LENGTH/2, SCREEN_HEIGHT/2-ball->LENGTH/2); left_paddle = new Paddle(40, SCREEN_HEIGHT/2-Paddle::HEIGHT/2); right_paddle = new Paddle(SCREEN_WIDTH-(40+Paddle::WIDTH), SCREEN_HEIGHT/2-Paddle::HEIGHT/2); // Sounds. // Initialize SDL_mixer. Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024); // Load paddle sound. QFile paddleHitFile(":/resources/sounds/paddle_hit.wav"); QString paddleHitFilePath = QDir::temp().absolutePath() + "/" + paddleHitFile.fileName().split("/").last(); paddleHitFile.copy(paddleHitFilePath); paddle_sound = Mix_LoadWAV(paddleHitFilePath.toUtf8().constData()); // Load wall sound. QFile wallHitFile(":/resources/sounds/wall_hit.wav"); QString wallHitFilePath = QDir::temp().absolutePath() + "/" + wallHitFile.fileName().split("/").last(); wallHitFile.copy(wallHitFilePath); wall_sound = Mix_LoadWAV(wallHitFilePath.toUtf8().constData()); // Load score_update sound. QFile scoreUpdateFile(":/resources/sounds/score_update.wav"); QString scoreUpdateFilePath = QDir::temp().absolutePath() + "/" + scoreUpdateFile.fileName().split("/").last(); scoreUpdateFile.copy(scoreUpdateFilePath); score_sound = Mix_LoadWAV(scoreUpdateFilePath.toUtf8().constData()); // Controllers. if (argc == 2) { if ( strcmp(argv[1], "keyboard") == 0 ) { controller = keyboard; } else if ( strcmp(argv[1], "joystick") == 0 ) { controller = joystick; } else { controller = mouse; } } else { controller = mouse; // Default controller. } if (controller == joystick) { printf("%i joysticks were found.\n\n", SDL_NumJoysticks() ); printf("The names of the joysticks are:\n"); // Give control to the first joystick. gamepad = SDL_JoystickOpen(0); for (int i = 0; i < SDL_NumJoysticks(); i++) { std::cout << "\t" << SDL_JoystickName(gamepad) << std::endl; } // Initialize joystick controller. SDL_JoystickEventState(SDL_ENABLE); gamepad_direction = 0; } // Fonts. TTF_Init(); // Initialize font. font_color = {255, 255, 255, 255}; font_name = ":/resources/fonts/NES-Chimera/NES-Chimera.ttf"; font_image_launch = renderText("Press SPACE to start", font_name, font_color, 16, renderer); // Scores. left_score = 0; right_score = 0; // Indicates when rendering new score is necessary. left_score_changed = true; // Indicates when rendering new score is necessary. right_score_changed = true; // Game status. exit = false; // Initialize potentially non-used pointers to nullptr. font_image_winner = nullptr; font_image_restart = nullptr; } Pong::~Pong() { // Destroy textures. SDL_DestroyTexture(font_image_left_score); SDL_DestroyTexture(font_image_right_score); if(font_image_winner != nullptr) SDL_DestroyTexture(font_image_winner); if(font_image_restart != nullptr) SDL_DestroyTexture(font_image_restart); SDL_DestroyTexture(font_image_launch); // Free sound effects. Mix_FreeChunk(paddle_sound); Mix_FreeChunk(wall_sound); Mix_FreeChunk(score_sound); // Quit SDL_mixer. Mix_CloseAudio(); // Close joystick. if (controller == joystick) { SDL_JoystickClose(gamepad); } // Destroy renderer and window. SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); // Shuts down SDL. SDL_Quit(); } void Pong::execute() { while (!exit) { input(); update(); render(); SDL_Delay(10); } } void Pong::input() { // Handle events. SDL_Event event; while (SDL_PollEvent(&event)) { // Track mouse movement. if (event.type == SDL_MOUSEMOTION) { SDL_GetMouseState(&mouse_x, &mouse_y); } // Clicking 'x' or pressing F4. if (event.type == SDL_QUIT) { exit = true; } // Joystick direction controller moved. if (event.type == SDL_JOYAXISMOTION) { // 32767. // Up or down. if (event.jaxis.axis == 1) { gamepad_direction = event.jaxis.value/5461; } } // Joystick action button pressed. if (event.type == SDL_JOYBUTTONDOWN) { if (ball->status == ball->READY) { ball->status = ball->LAUNCH; } } // Pressing a key. if (event.type == SDL_KEYDOWN) { switch (event.key.keysym.sym) { // Pressing ESC exits from the game. case SDLK_ESCAPE: exit = true; break; // Pressing space will launch the ball if it isn't // already launched. case SDLK_SPACE: if (ball->status == ball->READY) { ball->status = ball->LAUNCH; } break; // Pressing F11 to toggle fullscreen. case SDLK_F11: int flags = SDL_GetWindowFlags(window); if (flags & SDL_WINDOW_FULLSCREEN) { SDL_SetWindowFullscreen(window, 0); } else { SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); } break; } } } } // Update game values. void Pong::update() { // Paddle movement. if (controller == mouse) { // Right paddle follows the player's mouse on the y-axis. right_paddle->set_y(mouse_y); } else if (controller == joystick) { // Right paddle follows the player's gamepad. right_paddle->add_to_y(gamepad_direction); } // AI paddle movement. left_paddle->AI(ball); // Launch ball. if (ball->status == ball->READY) { return; } else if (ball->status == ball->LAUNCH) { ball->launch_ball(left_paddle); ball->predicted_y = left_paddle->predict(ball); } // Update ball speed. ball->update_speed(); // Collision. if (ball->collides_with(left_paddle)) { ball->bounces_off(left_paddle); Mix_PlayChannel(-1, paddle_sound, 0); // Play collision sound. } else if (ball->collides_with(right_paddle)) { ball->bounces_off(right_paddle); // Predict ball position on the y-axis. ball->predicted_y = left_paddle->predict(ball); Mix_PlayChannel(-1, paddle_sound, 0); } // Upper and bottom walls collision. if (ball->wall_collision()) { ball->dy *= -1; // Reverse ball direction on y-axis. Mix_PlayChannel(-1, wall_sound, 0); // Play collision sound. } // Update ball coordinates. ball->x += ball->dx; ball->y += ball->dy; // Ball goes out. if (ball->x > SCREEN_WIDTH || ball->x < 0) { // Change score. if (ball->x > SCREEN_WIDTH) { left_score++; left_score_changed = true; } else { right_score++; right_score_changed = true; } Mix_PlayChannel(-1, score_sound, 0); ball->reset(); } } // Render objects on screen. void Pong::render() { // Clear screen (background color). SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Dark grey. SDL_RenderClear(renderer); // Paddle color. SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // Render filled paddle. SDL_Rect paddle1 = { left_paddle->get_x(), left_paddle->get_y(), Paddle::WIDTH, Paddle::HEIGHT }; SDL_RenderFillRect(renderer, &paddle1); // Render filled paddle. SDL_Rect paddle2 = { right_paddle->get_x(), right_paddle->get_y(), Paddle::WIDTH, Paddle::HEIGHT }; SDL_RenderFillRect(renderer, &paddle2); // Render ball. SDL_Rect pong_ball = { ball->x, ball->y, ball->LENGTH, ball->LENGTH }; SDL_RenderFillRect(renderer, &pong_ball); // Render scores. if (left_score_changed) { font_image_left_score = renderText(std::to_string(left_score), font_name, font_color, 24, renderer); left_score_changed = false; if (left_score == 5) { font_image_winner = renderText("Player 1 won!", font_name, font_color, 24, renderer); font_image_restart = renderText("Press SPACE to restart", font_name, font_color, 14, renderer); } } renderTexture(font_image_left_score, renderer, SCREEN_WIDTH * 4 / 10, SCREEN_HEIGHT / 12); int score_font_size = 24; if (right_score_changed) { font_image_right_score = renderText(std::to_string(right_score), font_name, font_color, score_font_size, renderer); right_score_changed = false; if (right_score == 5) { font_image_winner = renderText("Player 2 won!", font_name, font_color, 24, renderer); font_image_restart = renderText("Press SPACE to restart", font_name, font_color, 14, renderer); } } renderTexture(font_image_right_score, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT/ 12); // Render text indicating the winner. if (left_score == 5) { // Align with score. renderTexture(font_image_winner, renderer, SCREEN_WIDTH * 1 / 10 + 3, SCREEN_HEIGHT / 4); renderTexture(font_image_restart, renderer, SCREEN_WIDTH * 1 / 10 + 3, SCREEN_HEIGHT / 3); if (ball->status == ball->LAUNCHED) { left_score = 0; right_score = 0; left_score_changed = true; right_score_changed = true; } } else if (right_score == 5) { // Align with score. renderTexture(font_image_winner, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT / 4); renderTexture(font_image_restart, renderer, SCREEN_WIDTH * 6 / 10 - score_font_size/2, SCREEN_HEIGHT / 3); if (ball->status == ball->LAUNCHED) { left_score = 0; right_score = 0; left_score_changed = true; right_score_changed = true; } } else if (ball->status == ball->READY) { // Draw "Press SPACE to start". renderTexture(font_image_launch, renderer, SCREEN_WIDTH / 2 - 160, SCREEN_HEIGHT - 30); } // Swap buffers. SDL_RenderPresent(renderer); }
30.970822
115
0.583248
tomredant
376e05ab6f756be8b5f358b871a73f9280c63f69
241
cpp
C++
Game/Client/WXClient/Network/PacketHandler/CGBankAcquireListHandler.cpp
hackerlank/SourceCode
b702c9e0a9ca5d86933f3c827abb02a18ffc9a59
[ "MIT" ]
4
2021-07-31T13:56:01.000Z
2021-11-13T02:55:10.000Z
Game/Client/WXClient/Network/PacketHandler/CGBankAcquireListHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
null
null
null
Game/Client/WXClient/Network/PacketHandler/CGBankAcquireListHandler.cpp
shacojx/SourceCodeGameTLBB
e3cea615b06761c2098a05427a5f41c236b71bf7
[ "MIT" ]
7
2021-08-31T14:34:23.000Z
2022-01-19T08:25:58.000Z
#include"stdafx.h" #include "CGBankAcquireList.h" uint CGBankAcquireListHandler::Execute( CGBankAcquireList* pPacket, Player* pPlayer ) { __ENTER_FUNCTION return PACKET_EXE_CONTINUE ; __LEAVE_FUNCTION return PACKET_EXE_ERROR ; }
15.0625
85
0.788382
hackerlank
3778022c92ed20985cce66298dbb5d285c8c6842
19,247
cc
C++
tests/neuron_support_code_threshold/neuron_support_code_threshold_CODE/synapseUpdate.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-06-28T19:48:48.000Z
2020-06-28T19:48:48.000Z
tests/neuron_support_code_threshold/neuron_support_code_threshold_CODE/synapseUpdate.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-02-10T15:26:29.000Z
2020-02-10T15:26:29.000Z
tests/neuron_support_code_threshold/neuron_support_code_threshold_CODE/synapseUpdate.cc
9inpachi/genn-opencl
33231225a72611c7b629ef1d13f325f35d4ae2f7
[ "MIT" ]
1
2020-02-10T10:47:12.000Z
2020-02-10T10:47:12.000Z
#include "definitionsInternal.h" #include "supportCode.h" extern "C" const char* updateSynapsesProgramSrc = R"(typedef float scalar; void atomic_add_f_global(volatile __global float *source, const float operand) { union { unsigned int intVal; float floatVal; } newVal; union { unsigned int intVal; float floatVal; } prevVal; do { prevVal.floatVal = *source; newVal.floatVal = prevVal.floatVal + operand; } while (atomic_cmpxchg((volatile __global unsigned int *)source, prevVal.intVal, newVal.intVal) != prevVal.intVal); } __kernel void updatePresynapticKernel(__global unsigned int* d_glbSpkCntpre, __global unsigned int* d_glbSpkpre, __global float* d_inSynsyn0, __global float* d_inSynsyn1, __global float* d_inSynsyn2, __global float* d_inSynsyn3, __global float* d_inSynsyn4, __global float* d_inSynsyn5, __global float* d_inSynsyn6, __global float* d_inSynsyn7, __global float* d_inSynsyn8, __global float* d_inSynsyn9, __global scalar* d_wsyn0, __global scalar* d_wsyn1, __global scalar* d_wsyn2, __global scalar* d_wsyn3, __global scalar* d_wsyn4, __global scalar* d_wsyn5, __global scalar* d_wsyn6, __global scalar* d_wsyn7, __global scalar* d_wsyn8, __global scalar* d_wsyn9, __global scalar* d_xpre, volatile unsigned int spkQuePtrpre, float t) { const size_t localId = get_local_id(0); const unsigned int id = get_global_id(0); __local unsigned int shSpk[32]; // syn0 if(id < 32) { const unsigned int preReadDelaySlot = spkQuePtrpre; const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (id < 10) { unsigned int synAddress = (shSpk[j] * 10) + id; d_wsyn0[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (id < 10) { d_inSynsyn0[id] += linSyn; } } // syn1 if(id >= 32 && id < 64) { const unsigned int lid = id - 32; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 9) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn1[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn1[lid] += linSyn; } } // syn2 if(id >= 64 && id < 96) { const unsigned int lid = id - 64; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 8) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn2[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn2[lid] += linSyn; } } // syn3 if(id >= 96 && id < 128) { const unsigned int lid = id - 96; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 7) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn3[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn3[lid] += linSyn; } } // syn4 if(id >= 128 && id < 160) { const unsigned int lid = id - 128; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 6) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn4[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn4[lid] += linSyn; } } // syn5 if(id >= 160 && id < 192) { const unsigned int lid = id - 160; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 5) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn5[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn5[lid] += linSyn; } } // syn6 if(id >= 192 && id < 224) { const unsigned int lid = id - 192; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 4) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn6[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn6[lid] += linSyn; } } // syn7 if(id >= 224 && id < 256) { const unsigned int lid = id - 224; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 3) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn7[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn7[lid] += linSyn; } } // syn8 if(id >= 256 && id < 288) { const unsigned int lid = id - 256; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 2) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn8[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn8[lid] += linSyn; } } // syn9 if(id >= 288 && id < 320) { const unsigned int lid = id - 288; const unsigned int preReadDelaySlot = ((spkQuePtrpre + 1) % 10); const unsigned int preReadDelayOffset = preReadDelaySlot * 10; // only do this for existing neurons float linSyn = 0; { const size_t localIdi = get_local_id(0); const unsigned int numSpikes = d_glbSpkCntpre[preReadDelaySlot]; const unsigned int numSpikeBlocks = (numSpikes + 32 - 1) / 32; for (unsigned int r = 0; r < numSpikeBlocks; r++) { const unsigned int numSpikesInBlock = (r == numSpikeBlocks - 1) ? ((numSpikes - 1) % 32) + 1 : 32; barrier(CLK_LOCAL_MEM_FENCE); if (localIdi < numSpikesInBlock) { const unsigned int spk = d_glbSpkpre[preReadDelayOffset + (r * 32) + localIdi]; shSpk[localIdi] = spk; } barrier(CLK_LOCAL_MEM_FENCE); // loop through all incoming spikes for (unsigned int j = 0; j < numSpikesInBlock; j++) { // only work on existing neurons if (lid < 10) { unsigned int synAddress = (shSpk[j] * 10) + lid; d_wsyn9[synAddress]= d_xpre[preReadDelayOffset + shSpk[j]];} } } } // only do this for existing neurons if (lid < 10) { d_inSynsyn9[lid] += linSyn; } } } )"; // Initialize the synapse update kernel(s) void updateSynapsesProgramKernels() { updatePresynapticKernel = cl::Kernel(updateSynapsesProgram, "updatePresynapticKernel"); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(0, d_glbSpkCntpre)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(1, d_glbSpkpre)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(2, d_inSynsyn0)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(3, d_inSynsyn1)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(4, d_inSynsyn2)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(5, d_inSynsyn3)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(6, d_inSynsyn4)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(7, d_inSynsyn5)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(8, d_inSynsyn6)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(9, d_inSynsyn7)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(10, d_inSynsyn8)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(11, d_inSynsyn9)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(12, d_wsyn0)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(13, d_wsyn1)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(14, d_wsyn2)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(15, d_wsyn3)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(16, d_wsyn4)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(17, d_wsyn5)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(18, d_wsyn6)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(19, d_wsyn7)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(20, d_wsyn8)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(21, d_wsyn9)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(22, d_xpre)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(23, spkQuePtrpre)); } void updateSynapses(float t) { { CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(23, spkQuePtrpre)); CHECK_OPENCL_ERRORS(updatePresynapticKernel.setArg(24, t)); const cl::NDRange globalWorkSize(320, 1); const cl::NDRange localWorkSize(32, 1); CHECK_OPENCL_ERRORS(commandQueue.enqueueNDRangeKernel(updatePresynapticKernel, cl::NullRange, globalWorkSize, localWorkSize)); CHECK_OPENCL_ERRORS(commandQueue.finish()); } }
46.602906
734
0.561802
9inpachi
3786b8f456e1b5fc95c201b9653f7ca95bb3105b
153
cpp
C++
src/ble/blPermission.cpp
fidoriel/track38
d3773a7ae704e460da25c5ec68e444dab82bfdc1
[ "MIT" ]
null
null
null
src/ble/blPermission.cpp
fidoriel/track38
d3773a7ae704e460da25c5ec68e444dab82bfdc1
[ "MIT" ]
null
null
null
src/ble/blPermission.cpp
fidoriel/track38
d3773a7ae704e460da25c5ec68e444dab82bfdc1
[ "MIT" ]
null
null
null
#if defined( WIN32 ) || defined( __linux__ ) #include "blPermission.h" bool bleIsAutorized() { return true; } void askForPermission() { } #endif
10.2
44
0.673203
fidoriel
3787f23976b04e86007092b401d60d613db9ba2f
641
cc
C++
controllers/download_route.cc
Rynnya/hanaru
2bfa40d9040b9b4e3b952099886dc293921a5a25
[ "MIT" ]
1
2021-12-13T10:37:30.000Z
2021-12-13T10:37:30.000Z
controllers/download_route.cc
Rynnya/hanaru
2bfa40d9040b9b4e3b952099886dc293921a5a25
[ "MIT" ]
null
null
null
controllers/download_route.cc
Rynnya/hanaru
2bfa40d9040b9b4e3b952099886dc293921a5a25
[ "MIT" ]
null
null
null
#include "download_route.hh" #include "../impl/downloader.hh" #include "../impl/utils.hh" Task<HttpResponsePtr> download_route::get(HttpRequestPtr req, int64_t id) { const auto [code, filename, content] = co_await hanaru::downloader::get().download_map(id); if (code != k200OK) { SEND_ERROR(code, content); } HttpResponsePtr response = HttpResponse::newFileResponse( reinterpret_cast<const unsigned char*>(content.data()), content.size(), filename ); response->setContentTypeCodeAndCustomString(drogon::CT_CUSTOM, "application/x-osu-beatmap-archive"); co_return response; }
26.708333
104
0.691108
Rynnya