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
f0db72dce53a713876d31a7f4dbb58d6e20f8f3b
2,273
cpp
C++
Callflow.cpp
DineshDevaraj/hivecf
6462131c8aa75d8b41c7592f11cb7aef03ecbc47
[ "MIT" ]
null
null
null
Callflow.cpp
DineshDevaraj/hivecf
6462131c8aa75d8b41c7592f11cb7aef03ecbc47
[ "MIT" ]
null
null
null
Callflow.cpp
DineshDevaraj/hivecf
6462131c8aa75d8b41c7592f11cb7aef03ecbc47
[ "MIT" ]
null
null
null
/** * * Author : D.Dinesh * Licence : Refer the license file * **/ #include "Callflow.h" struct Node { int m_line; int m_level; Node *m_next; const char *m_szFunc; const char *m_szFile; }; static int g_level = 0; static Node *g_base = 0; static Node *g_last = 0; static int g_max_level = 0; static void ShutCallflow(int sig); static int SslExistAtLevel(int level, Node *node); static void InitCallflow() __attribute__((constructor)); static void InitCallflow() { static Node node; g_last = g_base = &node; signal(SIGSEGV, ShutCallflow); } static int SslExistAtLevel(int level, Node *node) { for(node = node->m_next; node; node = node->m_next) if(node->m_level < level) return 0; else if(node->m_level == level) return 1; return 0; } static void ShutCallflow(int sig) { Node *node = g_base->m_next; bool *pSsl = new bool[g_max_level - 1]; /* succeeding sibling */ printf("%s [%s:%d]\n", node->m_szFunc, node->m_szFile, node->m_line); for(node = node->m_next; node; node = node->m_next) { /* I -> Index */ /* L -> Level */ /* M -> Memory */ int I = 0; int M = node->m_level - 1; memset(pSsl, true, g_max_level - 1); for(int L = 1; L < M; L++) { I = L - 1; if(pSsl[I]) { pSsl[I] = SslExistAtLevel(L + 1, node); if(pSsl[I]) printf("| "); else printf(" "); } else { printf(" "); } } if(0 == node->m_next || node->m_level > node->m_next->m_level || (node->m_level < node->m_next->m_level && !SslExistAtLevel(node->m_next->m_level - 1, node->m_next))) putchar('`'); else putchar('|'); printf("-- %s [%s:%d]\n", node->m_szFunc, node->m_szFile, node->m_line); } exit(0); } Callflow::Callflow(int line, const char *szFunc, const char *szFile) { g_level++; if(g_level > g_max_level) g_max_level = g_level; Node *node = new Node; node->m_next = 0; node->m_line = line; node->m_level = g_level; node->m_szFunc = szFunc; node->m_szFile = szFile; g_last->m_next = node; g_last = node; } Callflow::~Callflow() { g_level--; }
20.853211
78
0.556093
DineshDevaraj
f0de20d8f5185bf47585f5d7a7b526d35f267688
558
cc
C++
draw/main.cc
FacelessManipulator/StructureAlgo
73ce3cbd469c4beb7df88c39e8cf2a7777eb27e8
[ "MIT" ]
null
null
null
draw/main.cc
FacelessManipulator/StructureAlgo
73ce3cbd469c4beb7df88c39e8cf2a7777eb27e8
[ "MIT" ]
null
null
null
draw/main.cc
FacelessManipulator/StructureAlgo
73ce3cbd469c4beb7df88c39e8cf2a7777eb27e8
[ "MIT" ]
null
null
null
#include "draw/table.hpp" using namespace Faceless; int main() { Table table; Terminal term; table[0][0].setContent("root ").setAlign(Cell::Right).setFiller('-'); table[0][1].setContent("--> child1 ").setAlign(Cell::Right).setFiller('-'); table[0][2].setContent("--> child2 ").setAlign(Cell::Right).setFiller('-'); table[1][2].setContent("|-> child3 ").setAlign(Cell::Left).setFiller('-'); table[1][1].setContent("| ").setAlign(Cell::Left); table[2][1].setContent("|-> child4 ").setAlign(Cell::Left).setFiller('-'); table.dump(term); }
37.2
79
0.639785
FacelessManipulator
f0e6e482ffe222966f3744c15bb1d40b14e77ae0
4,329
cpp
C++
105/105.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
105/105.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
105/105.cpp
bsamseth/project-euler
60d70b117960f37411935bc18eab5bb2fca220e2
[ "MIT" ]
null
null
null
/* Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true: 1. S(B) ≠ S(C); that is, sums of subsets cannot be equal. 2. If B contains more elements than C then S(B) > S(C). For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules for all possible subset pair combinations and S(A) = 1286. Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with one-hundred sets containing seven to twelve elements (the two examples given above are the first two sets in the file), identify all the special sum sets, A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak). NOTE: This problem is related to Problem 103 and Problem 106. Solution comment: ~15 ms. Purely reuse of code from 103. Only thing of note was to remember to sort the set before testing, as the code from 103 assumed to set to be in ascending order for some efficient checks. */ #include <iostream> #include <fstream> #include <string> #include <sstream> #include <cstdlib> #include <cmath> #include <chrono> #include <vector> #include <numeric> #include <algorithm> /* * Return a vector of sums, where sum[i] is the sum of the set * containing A[k] where k is the index of all the set bits in i. * * Example: * A = {1, 2, 3} * sum[3] = sum[0b011] = A[0] + A[1] * sum[4] = sum[0b100] = A[3] */ template<typename Container> auto all_subset_sums(const Container &A) { const auto n = std::distance(A.begin(), A.end()); std::vector<int> subset_sums((std::size_t) std::pow(2, n)); for (std::size_t i = 1; i < subset_sums.size(); i++) { auto selector = i; for (int element : A) { if (selector & 1) { subset_sums[i] += element; } selector >>= 1; } } return subset_sums; } template<typename Container> bool is_special(const Container &A) { // Computing size of A. Workaround for cppitertools classes // which don't have a .size() method. const auto n = std::distance(A.begin(), A.end()); // Rule 1: Smaller subsets have smaller sums. // Shortcut, since A is sorted: a1 + a2 > an, a1+a2+a3 > a(n-1) + an etc. // is a sufficient condition to check. // We check this first, as this is _much_ easier to do. int left_sum = A[0]; int right_sum = 0; for (int i = 0; i < n / 2; i++) { left_sum += A[i + 1]; right_sum += A[n - 1 - i]; if (left_sum <= right_sum) return false; } // Rule 2: No duplicate subset sums. // If two duplicate sums are found, we check if // the corresponding sets are disjoint (meaning // set i and set k have no common set bits). If // both conditions are met, no special sum for you. const auto sums = all_subset_sums(A); auto n_sums = std::distance(sums.begin(), sums.end()); for (int i = 0; i < n_sums; ++i) { auto k = std::distance(sums.begin(), std::find(sums.begin() + i + 1, sums.end(), sums[i]) ); if (k != n_sums and not (i & k)) return false; } return true; } int main() { auto start = std::chrono::high_resolution_clock::now(); long total = 0; std::ifstream input("../../105/p105_sets.txt"); std::string line; while (std::getline(input, line)) { std::stringstream linestream(line); std::vector<int> A; std::string number; while (std::getline(linestream, number, ',')) { A.push_back(std::stoi(number)); } // Important! Needs to be sorted! std::sort(A.begin(), A.end()); if (is_special(A)) { total = std::accumulate(A.begin(), A.end(), total); } } printf("Answer: %ld\n", total); auto end = std::chrono::high_resolution_clock::now(); auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() / (double) 1e6; printf("Found in time: %g ms\n", time); }
33.55814
105
0.584893
bsamseth
f0e802d21d2a747063a6c3c6ca1dd4419fb4ea63
1,428
cpp
C++
src/RCE/Gui/rce/gui/RGraphicsPolylineItem.cpp
Timie/PositionEstimationAccuracy
9e88597c271ccc2a1a8442db6fa62236b7178296
[ "MIT" ]
1
2019-05-15T09:46:40.000Z
2019-05-15T09:46:40.000Z
src/RCE/Gui/rce/gui/RGraphicsPolylineItem.cpp
Timie/PositionEstimationAccuracy
9e88597c271ccc2a1a8442db6fa62236b7178296
[ "MIT" ]
null
null
null
src/RCE/Gui/rce/gui/RGraphicsPolylineItem.cpp
Timie/PositionEstimationAccuracy
9e88597c271ccc2a1a8442db6fa62236b7178296
[ "MIT" ]
null
null
null
#include "RGraphicsPolylineItem.h" #include <QPainterPath> #include <QPainterPathStroker> rce::gui::RGraphicsPolylineItem:: RGraphicsPolylineItem(const QPolygonF &path, const QPen &pen, QGraphicsItem *parent): QGraphicsPathItem(parent), polyline_(path), penWidth_(pen.widthF()) { setBrush(QBrush(Qt::transparent)); setPen(pen); regenerate(); } QPainterPath rce::gui::RGraphicsPolylineItem:: lineShape() const { return lineShape_; } void rce::gui::RGraphicsPolylineItem:: regenerate() { QPainterPath path; if(polyline_.size() != 1) path.addPolygon(polyline_); else { path.addRect(polyline_.first().x() - 0.5f, polyline_.first().y() - 0.5f, 1,1); } setPath(path); QPainterPathStroker stroker; stroker.setCapStyle(pen().capStyle()); stroker.setDashOffset(pen().dashOffset()); stroker.setDashPattern(pen().dashPattern()); stroker.setJoinStyle(pen().joinStyle()); stroker.setMiterLimit(pen().miterLimit()); stroker.setWidth(pen().widthF()); lineShape_ = stroker.createStroke(path); } void rce::gui::RGraphicsPolylineItem:: setPenWidth(const double penWidth) { if (penWidth >= 0) { penWidth_ = penWidth; QPen newPen = pen(); newPen.setWidth(penWidth_); setPen(newPen); } regenerate(); }
20.112676
50
0.62395
Timie
f0ea5e2a0dd12c21431427276e3402e14e3dd423
1,567
hpp
C++
src/TestXE/XETCommon/TestControllerSystem.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
src/TestXE/XETCommon/TestControllerSystem.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
src/TestXE/XETCommon/TestControllerSystem.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
2
2019-08-29T10:23:51.000Z
2020-04-03T06:08:34.000Z
#pragma once #include <XEngine.hpp> #include "TestController.hpp" namespace XE { class GraphicsManager; class OgreConsole; class XEngine; } namespace XET { class TestControllerSystem : public entityx::System < TestControllerSystem > , public XE::SDLInputHandler { public: TestControllerSystem(XE::XEngine& engine); ~TestControllerSystem(); void setBasicInputEvents(TestControllerComponent& controller); virtual void onPointMoved(XE::ActionContext context); virtual void onPointSelectStart(XE::ActionContext context); virtual void onPointSelectEnd(XE::ActionContext context); virtual void onResized(XE::ActionContext context); virtual void onKeyDown(XE::ActionContext context); virtual void onKeyPressed(XE::ActionContext context); virtual void onTextEntered(XE::ActionContext context); virtual void onQuit(); virtual void menuNav(XE::ActionContext context, TestControllerComponent& controller); //realtime action virtual void move(entityx::Entity entity, float dt); void update(entityx::EntityManager &es, entityx::EventManager &events, entityx::TimeDelta dt) override; inline XE::XEngine& getEngine() { return mEngine; } private: float _turn_speed; float _zoom_speed; XE::XEngine& mEngine; bool mDecalDestroy; XE::Vector2 mMousePos; XE::Vector2 _lastMousePos; bool _mousePressed; XE::Vector3 moveDirection; // set to null per frame /// Mouse movement since last frame. XE::Vector2 m_mouseMove; /// Mouse wheel movement since last frame. int m_mouseMoveWheel; }; } // namespace XET
24.484375
106
0.758775
devxkh
f0ecd75c90b1397381cc270c29c3cc394e32feee
8,784
cpp
C++
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite hit testing sample (Windows 8)/C++/DWriteHitTesting.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite hit testing sample (Windows 8)/C++/DWriteHitTesting.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite hit testing sample (Windows 8)/C++/DWriteHitTesting.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "DWriteHitTesting.h" using namespace Microsoft::WRL; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Core; using namespace Windows::ApplicationModel::Activation; using namespace Windows::UI::Core; using namespace Windows::System; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::Storage; DWriteHitTesting::DWriteHitTesting() { } void DWriteHitTesting::CreateDeviceIndependentResources() { DirectXBase::CreateDeviceIndependentResources(); m_text = "Touch Me To Change My Underline!"; // Create a DirectWrite text format object. DX::ThrowIfFailed( m_dwriteFactory->CreateTextFormat( L"Segoe UI", nullptr, DWRITE_FONT_WEIGHT_LIGHT, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, 64.0f, L"en-US", // locale &m_textFormat ) ); // Center the text horizontally. DX::ThrowIfFailed( m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER) ); // Center the text vertically. DX::ThrowIfFailed( m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER) ); // Boolean array to keep track of which characters are underlined m_underlineArray = ref new Platform::Array<bool>(m_text->Length()); // Initialize the array to all false in order to represent the initial un-underlined text for (unsigned int i = 0; i < m_text->Length(); i++) { m_underlineArray[i] = false; } } void DWriteHitTesting::CreateDeviceResources() { DirectXBase::CreateDeviceResources(); m_sampleOverlay = ref new SampleOverlay(); m_sampleOverlay->Initialize( m_d2dDevice.Get(), m_d2dContext.Get(), m_wicFactory.Get(), m_dwriteFactory.Get(), "DirectWrite hit testing sample" ); DX::ThrowIfFailed( m_d2dContext->CreateSolidColorBrush( D2D1::ColorF(D2D1::ColorF::Black), &m_blackBrush ) ); } void DWriteHitTesting::CreateWindowSizeDependentResources() { DirectXBase::CreateWindowSizeDependentResources(); D2D1_SIZE_F size = m_d2dContext->GetSize(); // Create a DirectWrite Text Layout object DX::ThrowIfFailed( m_dwriteFactory->CreateTextLayout( m_text->Data(), // Text to be displayed m_text->Length(), // Length of the text m_textFormat.Get(), // DirectWrite Text Format object size.width, // Width of the Text Layout size.height, // Height of the Text Layout &m_textLayout ) ); SetUnderlineOnRedraw(); } void DWriteHitTesting::Render() { m_d2dContext->BeginDraw(); m_d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue)); m_d2dContext->SetTransform(D2D1::Matrix3x2F::Identity()); m_d2dContext->DrawTextLayout( D2D1::Point2F(0.0f, 0.0f), m_textLayout.Get(), m_blackBrush.Get() ); // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device // is lost. It will be handled during the next call to Present. HRESULT hr = m_d2dContext->EndDraw(); if (hr != D2DERR_RECREATE_TARGET) { DX::ThrowIfFailed(hr); } m_sampleOverlay->Render(); } void DWriteHitTesting::Initialize( _In_ CoreApplicationView^ applicationView ) { applicationView->Activated += ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &DWriteHitTesting::OnActivated); CoreApplication::Suspending += ref new EventHandler<SuspendingEventArgs^>(this, &DWriteHitTesting::OnSuspending); CoreApplication::Resuming += ref new EventHandler<Platform::Object^>(this, &DWriteHitTesting::OnResuming); } void DWriteHitTesting::SetWindow( _In_ CoreWindow^ window ) { window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0); window->SizeChanged += ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &DWriteHitTesting::OnWindowSizeChanged); window->PointerPressed += ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &DWriteHitTesting::OnPointerPressed); DisplayProperties::LogicalDpiChanged += ref new DisplayPropertiesEventHandler(this, &DWriteHitTesting::OnLogicalDpiChanged); DisplayProperties::DisplayContentsInvalidated += ref new DisplayPropertiesEventHandler(this, &DWriteHitTesting::OnDisplayContentsInvalidated); DirectXBase::Initialize(window, DisplayProperties::LogicalDpi); } void DWriteHitTesting::Load( _In_ Platform::String^ entryPoint ) { // Retrieve any stored variables from the LocalSettings collection. IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values; if (settingsValues->HasKey("m_underlineArray")) { safe_cast<IPropertyValue^>(settingsValues->Lookup("m_underlineArray"))->GetBooleanArray(&m_underlineArray); SetUnderlineOnRedraw(); } } void DWriteHitTesting::Run() { Render(); Present(); m_window->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessUntilQuit); } void DWriteHitTesting::Uninitialize() { } void DWriteHitTesting::OnWindowSizeChanged( _In_ CoreWindow^ sender, _In_ WindowSizeChangedEventArgs^ args ) { UpdateForWindowSizeChange(); m_sampleOverlay->UpdateForWindowSizeChange(); Render(); Present(); } void DWriteHitTesting::OnPointerPressed( _In_ CoreWindow^ sender, _In_ PointerEventArgs^ args ) { DWRITE_HIT_TEST_METRICS hitTestMetrics; BOOL isTrailingHit; BOOL isInside; Windows::UI::Input::PointerPoint^ point = args->CurrentPoint; DX::ThrowIfFailed( m_textLayout->HitTestPoint( point->Position.X, point->Position.Y, &isTrailingHit, &isInside, &hitTestMetrics ) ); if (isInside) { BOOL underline; DX::ThrowIfFailed( m_textLayout->GetUnderline(hitTestMetrics.textPosition, &underline) ); DWRITE_TEXT_RANGE textRange = {hitTestMetrics.textPosition, 1}; DX::ThrowIfFailed( m_textLayout->SetUnderline(!underline, textRange) ); m_underlineArray[hitTestMetrics.textPosition] = !underline; } Render(); Present(); } // This function is used to keep track of which elements are underlined - in order to redraw // the underline if the text layout needs to be recreated void DWriteHitTesting::SetUnderlineOnRedraw() { for (unsigned int i = 0; i < m_text->Length(); i++) { DWRITE_TEXT_RANGE textRange = {i, 1}; DX::ThrowIfFailed( m_textLayout->SetUnderline(m_underlineArray[i], textRange) ); } } void DWriteHitTesting::OnLogicalDpiChanged( _In_ Platform::Object^ sender ) { SetDpi(DisplayProperties::LogicalDpi); Render(); Present(); } void DWriteHitTesting::OnDisplayContentsInvalidated( _In_ Platform::Object^ sender ) { // Ensure the D3D Device is available for rendering. ValidateDevice(); Render(); Present(); } void DWriteHitTesting::OnActivated( _In_ CoreApplicationView^ applicationView, _In_ IActivatedEventArgs^ args ) { m_window->Activate(); } void DWriteHitTesting::OnSuspending( _In_ Platform::Object^ sender, _In_ SuspendingEventArgs^ args ) { IPropertySet^ settingsValues = ApplicationData::Current->LocalSettings->Values; if (settingsValues->HasKey("m_underlineArray")) { settingsValues->Remove("m_underlineArray"); } settingsValues->Insert("m_underlineArray", PropertyValue::CreateBooleanArray(m_underlineArray)); } void DWriteHitTesting::OnResuming( _In_ Platform::Object^ sender, _In_ Platform::Object^ args ) { } IFrameworkView^ DirectXAppSource::CreateView() { return ref new DWriteHitTesting(); } [Platform::MTAThread] int main(Platform::Array<Platform::String^>^) { auto directXAppSource = ref new DirectXAppSource(); CoreApplication::Run(directXAppSource); return 0; }
27.111111
122
0.675546
alonmm
f0ee749e1a3d95496f8274ffbe8edb9ea3eb2222
2,778
cpp
C++
Modules/ProxyModule/firewalldiscoverymanager.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
2
2016-09-28T02:23:07.000Z
2019-07-13T15:53:47.000Z
Modules/ProxyModule/firewalldiscoverymanager.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
Modules/ProxyModule/firewalldiscoverymanager.cpp
OwNet/qtownet
bcddc85401a279e850f269cdd14e2d08dff5e02e
[ "MIT" ]
null
null
null
#include "firewalldiscoverymanager.h" #include "irequest.h" #include "iproxyconnection.h" #include "idatabasesettings.h" #include "isession.h" #include "isettings.h" #include <QThread> #include <QTimer> bool FirewallDiscoveryManager::m_wasPingedBack = false; bool FirewallDiscoveryManager::m_statusChecked = false; FirewallDiscoveryManager::FirewallDiscoveryManager(IProxyConnection *proxyConnection, QObject *parent) : QObject(parent), m_proxyConnection(proxyConnection) { connect(this, SIGNAL(finishedPing()), this, SLOT(deleteLater())); } void FirewallDiscoveryManager::ping(const QString &clientId) { m_clientToPingId = clientId; QThread* thread = new QThread; this->moveToThread(thread); connect(thread, SIGNAL(started()), this, SLOT(startPing())); connect(this, SIGNAL(finishedPing()), thread, SLOT(quit())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); } void FirewallDiscoveryManager::checkFirewallStatus() { if (m_statusChecked) { emit finishedPing(); return; } QObject parent; QString myId = m_proxyConnection->databaseSettings(&parent)->clientId(); QVariantMap availableClients = m_proxyConnection->session(&parent)->availableClients(); m_statusChecked = true; foreach (QString id, availableClients.keys()) { if (id == myId) continue; IRequest *request = m_proxyConnection->createRequest(IRequest::GET, "clients", QString("%1/firewall/ping_me?my_id=%2") .arg(id) .arg(myId), &parent); if (m_proxyConnection->callModule(request)->status() == IResponse::OK) { QTimer::singleShot(5 * 1000, this, SLOT(checkPingResponse())); return; } } m_statusChecked = false; emit finishedPing(); } void FirewallDiscoveryManager::setPingedBack(bool pingedBack) { m_wasPingedBack = pingedBack; } void FirewallDiscoveryManager::startPing() { IRequest *request = m_proxyConnection->createRequest(IRequest::GET, "clients", QString("%1/firewall/ping") .arg(m_clientToPingId), this); m_proxyConnection->callModule(request); emit finishedPing(); } void FirewallDiscoveryManager::checkPingResponse() { if (!m_wasPingedBack) { QObject parent; int port = m_proxyConnection->settings(&parent)->listenPort(); m_proxyConnection->message(tr("Firewall was detected that prevents OwNet from functioning properly. Please deactivate the firewall on port %1.").arg(port), tr("Firewall Detected"), IProxyConnection::CriticalPopup); } emit finishedPing(); }
32.302326
222
0.662707
OwNet
f0f3edf65ada39edd4d875628f77efab8c768201
270
cpp
C++
old/practice/lesson2/special.cpp
Lyuminarskiy/oop
b8c6a4b1cf8905c8bbeea5aa80769b5519307654
[ "MIT" ]
3
2018-02-16T11:22:55.000Z
2018-03-23T14:10:33.000Z
old/practice/lesson2/special.cpp
OOP-course/OOP-course
b8c6a4b1cf8905c8bbeea5aa80769b5519307654
[ "MIT" ]
null
null
null
old/practice/lesson2/special.cpp
OOP-course/OOP-course
b8c6a4b1cf8905c8bbeea5aa80769b5519307654
[ "MIT" ]
1
2020-04-28T17:13:02.000Z
2020-04-28T17:13:02.000Z
#include <string> using namespace std; struct Backup final { static void makeBakup(string path) {} }; struct Printer final { static void print(string text) {} }; int main() { Backup::makeBakup("C:/myBackups/"); Printer::print("Hello, world!"); return 0; }
12.857143
39
0.666667
Lyuminarskiy
e7cc78d92806210ceb5c2003c6ddbce43886464a
16,811
cpp
C++
nsl/api/glsl/generator.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
nsl/api/glsl/generator.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
292
2020-03-19T22:38:52.000Z
2022-03-05T22:49:34.000Z
nsl/api/glsl/generator.cpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
#include "generator.h" #include <sstream> #include <regex> using namespace natus::nsl::glsl ; natus::ntd::string_t generator::replace_buildin_symbols( natus::ntd::string_t code ) noexcept { natus::nsl::repl_syms_t repls = { { natus::ntd::string_t( "mul" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "mul ( INVALID_ARGS ) " ; return args[ 0 ] + " * " + args[ 1 ] ; } }, { natus::ntd::string_t( "mmul" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "mmul ( INVALID_ARGS ) " ; return args[ 0 ] + " * " + args[ 1 ] ; } }, { natus::ntd::string_t( "add" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "add ( INVALID_ARGS ) " ; return args[ 0 ] + " + " + args[ 1 ] ; } }, { natus::ntd::string_t( "sub" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "sub ( INVALID_ARGS ) " ; return args[ 0 ] + " - " + args[ 1 ] ; } }, { natus::ntd::string_t( "div" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "div ( INVALID_ARGS ) " ; return args[ 0 ] + " / " + args[ 1 ] ; } }, { natus::ntd::string_t( "pulse" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 3 ) return "pulse ( INVALID_ARGS ) " ; return "( step ( " + args[ 0 ] + " , " + args[ 2 ] + " ) - " + "step ( " + args[ 1 ] + " , " + args[ 2 ] + " ) )" ; } }, { natus::ntd::string_t( "texture" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "texture ( INVALID_ARGS ) " ; return "texture( " + args[ 0 ] + " , " + args[ 1 ] + " ) " ; } }, { natus::ntd::string_t( "rt_texture" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "rt_texture ( INVALID_ARGS ) " ; return "texture( " + args[ 0 ] + " , " + args[ 1 ] + " ) " ; } }, { natus::ntd::string_t( "lt" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "lt ( INVALID_ARGS ) " ; return args[ 0 ] + " < " + args[ 1 ] ; } }, { natus::ntd::string_t( "gt" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 2 ) return "gt ( INVALID_ARGS ) " ; return args[ 0 ] + " > " + args[ 1 ] ; } }, { natus::ntd::string_t( "ret" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 1 ) return "ret ( INVALID_ARGS ) " ; return "return " + args[ 0 ] ; } }, { natus::ntd::string_t( "mix" ), [=] ( natus::ntd::vector< natus::ntd::string_t > const& args ) -> natus::ntd::string_t { if( args.size() != 3 ) return "mix ( INVALID_ARGS ) " ; return "mix (" + args[ 0 ] + " , " + args[ 1 ] + " , " + args[ 2 ] + " ) " ; } } } ; return natus::nsl::perform_repl( std::move( code ), repls ) ; } natus::ntd::string_t generator::map_variable_type( natus::nsl::type_cref_t type ) noexcept { typedef std::pair< natus::nsl::type_t, natus::ntd::string_t > mapping_t ; static mapping_t const __mappings[] = { mapping_t( natus::nsl::type_t(), "unknown" ), mapping_t( natus::nsl::type_t::as_float(), "float" ), mapping_t( natus::nsl::type_t::as_vec2(), "vec2" ), mapping_t( natus::nsl::type_t::as_vec3(), "vec3" ), mapping_t( natus::nsl::type_t::as_vec4(), "vec4" ), mapping_t( natus::nsl::type_t::as_mat2(), "mat2" ), mapping_t( natus::nsl::type_t::as_mat3(), "mat3" ), mapping_t( natus::nsl::type_t::as_mat4(), "mat4" ), mapping_t( natus::nsl::type_t::as_tex1d(), "sampler1D" ), mapping_t( natus::nsl::type_t::as_tex2d(), "sampler2D" ) } ; for( auto const& m : __mappings ) if( m.first == type ) return m.second ; return __mappings[ 0 ].second ; } natus::ntd::string_cref_t generator::to_texture_type( natus::nsl::type_cref_t t ) noexcept { typedef std::pair< natus::nsl::type_ext, natus::ntd::string_t > __mapping_t ; static __mapping_t const __mappings[] = { __mapping_t( natus::nsl::type_ext::unknown, "unknown" ), __mapping_t( natus::nsl::type_ext::texture_1d, "sampler1D" ), __mapping_t( natus::nsl::type_ext::texture_2d, "sampler2D" ) } ; for( auto const& m : __mappings ) if( m.first == t.ext ) return m.second ; return __mappings[ 0 ].second ; } natus::ntd::string_t generator::replace_types( natus::ntd::string_t code ) noexcept { size_t p0 = 0 ; size_t p1 = code.find_first_of( ' ' ) ; while( p1 != std::string::npos ) { auto const dist = p1 - p0 ; auto token = code.substr( p0, dist ) ; natus::nsl::type_t const t = natus::nsl::to_type( token ) ; if( t.base != natus::nsl::type_base::unknown ) { code.replace( p0, dist, this_t::map_variable_type( t ) ) ; } p0 = p1 + 1 ; p1 = code.find_first_of( ' ', p0 ) ; } return std::move( code ) ; } natus::nsl::generated_code_t::shaders_t generator::generate( natus::nsl::generatable_cref_t genable_, natus::nsl::variable_mappings_cref_t var_map_ ) noexcept { natus::nsl::variable_mappings_t var_map = var_map_ ; natus::nsl::generatable_t genable = genable_ ; // start renaming internal variables { for( auto& var : var_map ) { if( var.fq == natus::nsl::flow_qualifier::out && var.st == natus::nsl::shader_type::vertex_shader && var.binding == natus::nsl::binding::position ) { var.new_name = "gl_Position" ; } } } // replace buildins { for( auto& s : genable.config.shaders ) { for( auto& c : s.codes ) { for( auto& l : c.lines ) { l = this_t::replace_buildin_symbols( std::move( l ) ) ; } } } for( auto& frg : genable.frags ) { for( auto& f : frg.fragments ) { //for( auto& l : c.lines ) { f = this_t::replace_buildin_symbols( std::move( f ) ) ; } } } } natus::nsl::generated_code_t::shaders_t ret ; for( auto const& s : genable.config.shaders ) { natus::nsl::shader_type const s_type = s.type ; natus::nsl::generated_code_t::shader_t shd ; for( auto& var : var_map ) { if( var.st != s_type ) continue ; natus::nsl::generated_code_t::variable_t v ; v.binding = var.binding ; v.fq = var.fq ; v.name = var.new_name ; shd.variables.emplace_back( std::move( v ) ) ; } // generate the code { if( s_type == natus::nsl::shader_type::unknown ) { natus::log::global_t::warning( "[glsl generator] : unknown shader type" ) ; continue; } shd.type = s_type ; shd.codes.emplace_back( this_t::generate( genable, s, var_map, natus::nsl::api_type::es3 ) ) ; shd.codes.emplace_back( this_t::generate( genable, s, var_map, natus::nsl::api_type::gl3 ) ) ; } ret.emplace_back( std::move( shd ) ) ; } return std::move( ret ) ; } natus::nsl::generated_code_t::code_t generator::generate( natus::nsl::generatable_cref_t genable, natus::nsl::post_parse::config_t::shader_cref_t s, natus::nsl::variable_mappings_cref_t var_mappings, natus::nsl::api_type const type ) noexcept { natus::nsl::generated_code_t::code code ; std::stringstream text ; // 1. glsl stuff at the front { switch( type ) { case natus::nsl::api_type::gl3: text << "#version 130" << std::endl << std::endl ; break ; case natus::nsl::api_type::es3: text << "#version 300 es" << std::endl ; text << "precision mediump float ;" << std::endl << std::endl ; break ; default: text << "#version " << "glsl_type case missing" << std::endl << std::endl ; break ; } } // add extensions for pixel shader if( s.type == natus::nsl::shader_type::pixel_shader ) { size_t num_color = 0 ; for( auto const& var : s.variables ) { num_color += natus::nsl::is_color( var.binding ) ? 1 : 0 ; } // mrt requires extensions for glsl 130 if( num_color > 1 && type == natus::nsl::api_type::gl3 ) { text << "#extension GL_ARB_separate_shader_objects : enable" << std::endl << "#extension GL_ARB_explicit_attrib_location : enable" << std::endl << std::endl ; } } // 2. make prototypes declarations from function signatures // the prototype help with not having to sort funk definitions { text << "// Declarations // " << std::endl ; for( auto const& f : genable.frags ) { text << this_t::map_variable_type( f.sig.return_type ) << " " ; text << f.sym_long.expand( "_" ) << " ( " ; for( auto const& a : f.sig.args ) { text << this_t::map_variable_type( a.type ) + ", " ; } text.seekp( -2, std::ios_base::end ) ; text << " ) ; " << std::endl ; } text << std::endl ; } // 3. make all functions with replaced symbols { text << "// Definitions // " << std::endl ; for( auto const& f : genable.frags ) { // make signature { text << this_t::map_variable_type( f.sig.return_type ) << " " ; text << f.sym_long.expand( "_" ) << " ( " ; for( auto const& a : f.sig.args ) { text << this_t::map_variable_type( a.type ) + " " + a.name + ", " ; } text.seekp( -2, std::ios_base::end ) ; text << " )" << std::endl ; } // make body { text << "{" << std::endl ; for( auto const& l : f.fragments ) { text << this_t::replace_types( l ) << std::endl ; } text << "}" << std::endl ; } } text << std::endl ; } // 4. make all glsl uniforms from shader variables { size_t num_color = 0 ; for( auto const& var : s.variables ) { num_color += natus::nsl::is_color( var.binding ) ? 1 : 0 ; } size_t layloc_id = 0 ; text << "// Uniforms and in/out // " << std::endl ; for( auto const& v : s.variables ) { if( v.fq == natus::nsl::flow_qualifier::out && v.binding == natus::nsl::binding::position ) continue ; natus::ntd::string_t name = v.name ; natus::ntd::string_t const type_ = this_t::map_variable_type( v.type ) ; size_t const idx = natus::nsl::find_by( var_mappings, v.name, v.binding, v.fq, s.type ) ; if( idx != size_t( -1 ) ) { name = var_mappings[ idx ].new_name ; } // do some regex replacements { //type_ = std::regex_replace( type_, std::regex( "tex([1-3]+)d" ), "sampler$1D" ) ; } natus::ntd::string_t layloc ; if( v.fq == natus::nsl::flow_qualifier::out && s.type == natus::nsl::shader_type::pixel_shader && num_color > 1 ) { layloc = "layout( location = " + std::to_string( layloc_id++ ) + " ) " ; } natus::ntd::string_t const flow = v.fq == natus::nsl::flow_qualifier::global ? "uniform" : natus::nsl::to_string( v.fq ) ; text << layloc << flow << " " << type_ << " " << name << " ; " << std::endl ; } text << std::endl ; } // 5. insert main/shader from config { text << "// The shader // " << std::endl ; for( auto const& c : s.codes ) { for( auto const& l : c.lines ) { text << this_t::replace_types( l ) << std::endl ; } } } // 6. post over the code and replace all dependencies and in/out { auto shd = text.str() ; // variable dependencies { for( auto const& v : genable.vars ) { size_t const p0 = shd.find( v.sym_long.expand() ) ; if( p0 == std::string::npos ) continue ; size_t const p1 = shd.find_first_of( " ", p0 ) ; shd = shd.substr( 0, p0 ) + v.value + shd.substr( p1 ) ; } } // fragment dependencies { for( auto const& f : genable.frags ) { for( auto const& d : f.deps ) { size_t const p0 = shd.find( d.expand() ) ; if( p0 == std::string::npos ) continue ; size_t const p1 = shd.find_first_of( " ", p0 ) ; shd = shd.substr( 0, p0 ) + d.expand( "_" ) + shd.substr( p1 ) ; } } } // shader dependencies { for( auto const& d : s.deps ) { size_t const p0 = shd.find( d.expand() ) ; if( p0 == std::string::npos ) continue ; size_t const p1 = shd.find_first_of( " ", p0 ) ; shd = shd.substr( 0, p0 ) + d.expand( "_" ) + shd.substr( p1 ) ; } } // replace in code in/out/globals { size_t const off = shd.find( "// The shader" ) ; for( auto const& v : var_mappings ) { if( v.st != s.type ) continue ; natus::ntd::string_t flow ; if( v.fq == natus::nsl::flow_qualifier::in ) flow = "in." ; else if( v.fq == natus::nsl::flow_qualifier::out ) flow = "out." ; { natus::ntd::string_t const repl = flow + v.old_name ; size_t p0 = shd.find( repl, off ) ; while( p0 != std::string::npos ) { shd.replace( p0, repl.size(), v.new_name ) ; p0 = shd.find( repl, p0 + 3 ) ; } } } } // replace numbers { shd = std::regex_replace( shd, std::regex( " num_float \\( ([0-9]+) \\, ([0-9]+) \\) " ), " $1.$2 " ) ; shd = std::regex_replace( shd, std::regex( " num_uint \\( ([0-9]+) \\) " ), " $1u " ) ; shd = std::regex_replace( shd, std::regex( " num_int \\( ([0-9]+) \\) " ), " $1 " ) ; } { shd = this_t::replace_buildin_symbols( std::move( shd ) ) ; } code.shader = shd ; } code.api = type ; //ret.emplace_back( std::move( code ) ) ; return std::move( code ) ; }
33.893145
242
0.454762
aconstlink
e7cf06b3e60825044f85863d5f24f3f9fae10376
8,733
cpp
C++
Source/Core/Visualization/Mapper/Streamline.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Visualization/Mapper/Streamline.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Visualization/Mapper/Streamline.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /** * @file Streamline.cpp * @author Yukio Yasuhra, Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: Streamline.cpp 1778 2014-05-28 10:16:57Z [email protected] $ */ /*****************************************************************************/ #include "Streamline.h" #include <kvs/Type> #include <kvs/IgnoreUnusedVariable> #include <kvs/Message> #include <kvs/RGBColor> #include <kvs/Vector3> #include <kvs/VolumeObjectBase> #include <kvs/UniformGrid> #include <kvs/RectilinearGrid> #include <kvs/TetrahedralCell> #include <kvs/HexahedralCell> #include <kvs/QuadraticTetrahedralCell> #include <kvs/QuadraticHexahedralCell> #include <kvs/PyramidalCell> #include <kvs/PrismaticCell> #include <kvs/CellTreeLocator> namespace kvs { Streamline::StructuredVolumeInterpolator::StructuredVolumeInterpolator( const kvs::StructuredVolumeObject* volume ) { switch ( volume->gridType() ) { case kvs::StructuredVolumeObject::Uniform: m_grid = new kvs::UniformGrid( volume ); break; case kvs::StructuredVolumeObject::Rectilinear: m_grid = new kvs::RectilinearGrid( volume ); break; default: m_grid = NULL; break; } } Streamline::StructuredVolumeInterpolator::~StructuredVolumeInterpolator() { if ( m_grid ) { delete m_grid; } } kvs::Vec3 Streamline::StructuredVolumeInterpolator::interpolatedValue( const kvs::Vec3& point ) { m_grid->bind( point ); return m_grid->vector(); } bool Streamline::StructuredVolumeInterpolator::containsInVolume( const kvs::Vec3& point ) { const kvs::Vec3& min_coord = m_grid->referenceVolume()->minObjectCoord(); const kvs::Vec3& max_coord = m_grid->referenceVolume()->maxObjectCoord(); if ( point.x() < min_coord.x() || max_coord.x() <= point.x() ) return false; if ( point.y() < min_coord.y() || max_coord.y() <= point.y() ) return false; if ( point.z() < min_coord.z() || max_coord.z() <= point.z() ) return false; return true; } Streamline::UnstructuredVolumeInterpolator::UnstructuredVolumeInterpolator( const kvs::UnstructuredVolumeObject* volume ) { switch ( volume->cellType() ) { case kvs::UnstructuredVolumeObject::Tetrahedra: m_cell = new kvs::TetrahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::Hexahedra: m_cell = new kvs::HexahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::QuadraticTetrahedra: m_cell = new kvs::QuadraticTetrahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::QuadraticHexahedra: m_cell = new kvs::QuadraticHexahedralCell( volume ); break; case kvs::UnstructuredVolumeObject::Pyramid: m_cell = new kvs::PyramidalCell( volume ); break; case kvs::UnstructuredVolumeObject::Prism: m_cell = new kvs::PrismaticCell( volume ); break; default: m_cell = NULL; break; } m_locator = new kvs::CellTreeLocator( volume ); } Streamline::UnstructuredVolumeInterpolator::~UnstructuredVolumeInterpolator() { if ( m_cell ) { delete m_cell; } if ( m_locator ) { delete m_locator; } } kvs::Vec3 Streamline::UnstructuredVolumeInterpolator::interpolatedValue( const kvs::Vec3& point ) { int index = m_locator->findCell( point ); if ( index < 0 ) { return kvs::Vec3::Zero(); } m_cell->bindCell( kvs::UInt32( index ) ); return m_cell->vector(); } bool Streamline::UnstructuredVolumeInterpolator::containsInVolume( const kvs::Vec3& point ) { const kvs::Vec3& min_obj = m_cell->referenceVolume()->minObjectCoord(); const kvs::Vec3& max_obj = m_cell->referenceVolume()->maxObjectCoord(); if ( point.x() < min_obj.x() || max_obj.x() <= point.x() ) return false; if ( point.y() < min_obj.y() || max_obj.y() <= point.y() ) return false; if ( point.z() < min_obj.z() || max_obj.z() <= point.z() ) return false; return m_locator->findCell( point ) != -1; } kvs::Vec3 Streamline::EulerIntegrator::next( const kvs::Vec3& point ) { const kvs::Real32 k0 = step(); const kvs::Vec3 v1 = point; const kvs::Vec3 k1 = direction( v1 ) * k0; return point + k1; } kvs::Vec3 Streamline::RungeKutta2ndIntegrator::next( const kvs::Vec3& point ) { const kvs::Real32 k0 = step(); const kvs::Vec3 v1 = point; const kvs::Vec3 k1 = direction( v1 ) * k0; const kvs::Vec3 v2 = point + k1 / 2.0f; if ( !contains( v2 ) ) { return point; } const kvs::Vec3 k2 = direction( v2 ) * k0; return point + k2; } kvs::Vec3 Streamline::RungeKutta4thIntegrator::next( const kvs::Vec3& point ) { const kvs::Real32 k0 = step(); const kvs::Vec3 v1 = point; const kvs::Vec3 k1 = direction( v1 ) * k0; const kvs::Vec3 v2 = point + k1 / 2.0f; if ( !contains( v2 ) ) { return point; } const kvs::Vec3 k2 = direction( v2 ) * k0; const kvs::Vec3 v3 = point + k2 / 2.0f; if ( !contains( v3 ) ) { return point; } const kvs::Vec3 k3 = direction( v3 ) * k0; const kvs::Vec3 v4 = point + k3; if ( !contains( v4 ) ) { return point; } const kvs::Vec3 k4 = direction( v4 ) * k0; return point + ( k1 + 2.0f * ( k2 + k3 ) + k4 ) / 6.0f; } /*===========================================================================*/ /** * @brief Constructs a new streamline class and executes this class. * @param volume [in] pointer to the input volume object * @param seed_points [in] pointer to the seed points */ /*===========================================================================*/ Streamline::Streamline( const kvs::VolumeObjectBase* volume, const kvs::PointObject* seed_points, const kvs::TransferFunction& transfer_function ): kvs::StreamlineBase() { BaseClass::setTransferFunction( transfer_function ); BaseClass::setSeedPoints( seed_points ); this->exec( volume ); } /*===========================================================================*/ /** * @brief Executes the mapper process. * @param object [in] pointer to the volume object * @return line object */ /*===========================================================================*/ Streamline::BaseClass::SuperClass* Streamline::exec( const kvs::ObjectBase* object ) { if ( !object ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is NULL."); return NULL; } const kvs::VolumeObjectBase* volume = kvs::VolumeObjectBase::DownCast( object ); if ( !volume ) { BaseClass::setSuccess( false ); kvsMessageError("Input object is not volume dat."); return NULL; } // Check whether the volume can be processed or not. if ( volume->veclen() != 3 ) { BaseClass::setSuccess( false ); kvsMessageError("Input volume is not vector field data."); return NULL; } // Attach the pointer to the volume object. BaseClass::attachVolume( volume ); BaseClass::setRange( volume ); BaseClass::setMinMaxCoords( volume, this ); // set the min/max vector length. if ( !volume->hasMinMaxValues() ) { volume->updateMinMaxValues(); } Interpolator* interpolator = NULL; switch ( volume->volumeType() ) { case kvs::VolumeObjectBase::Structured: { const kvs::StructuredVolumeObject* svolume = kvs::StructuredVolumeObject::DownCast( volume ); interpolator = new StructuredVolumeInterpolator( svolume ); break; } case kvs::VolumeObjectBase::Unstructured: { const kvs::UnstructuredVolumeObject* uvolume = kvs::UnstructuredVolumeObject::DownCast( volume ); interpolator = new UnstructuredVolumeInterpolator( uvolume ); break; } default: break; } Integrator* integrator = NULL; switch ( m_integration_method ) { case BaseClass::Euler: integrator = new EulerIntegrator(); break; case BaseClass::RungeKutta2nd: integrator = new RungeKutta2ndIntegrator(); break; case BaseClass::RungeKutta4th: integrator = new RungeKutta4thIntegrator(); break; default: break; } integrator->setInterpolator( interpolator ); integrator->setStep( m_integration_interval * m_integration_direction ); BaseClass::mapping( integrator ); delete interpolator; delete integrator; return this; } } // end of namespace kvs
31.189286
105
0.612504
CCSEPBVR
e7d5b7e1336a699fc45f5c704060073b301168fb
2,385
cpp
C++
ext/nuvo_image/src/Gif.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
null
null
null
ext/nuvo_image/src/Gif.cpp
crema/nuvo_image
7868601deca054dc1bd45507c8d01e640611d322
[ "MIT" ]
5
2016-08-02T13:33:02.000Z
2020-11-03T15:22:52.000Z
ext/nuvo_image/src/Gif.cpp
crema/nuvo-image
365e4a54429fe4180e03adb1968ab9989e7ee5fb
[ "MIT" ]
null
null
null
#include "Gif.h" #include <cstring> bool Gif::TryReadFromBuffer(const std::shared_ptr<std::vector<unsigned char>>& buffer, Gif& gif, Flatten flatten) { GifBuffer readBuffer(buffer->data(), buffer->size()); int error = 0; auto gifFile = DGifOpen(&readBuffer, GifBuffer::ReadFromData, &error); if (gifFile == NULL) return false; if (DGifSlurp(gifFile) != GIF_OK) return false; cv::Mat mat(gifFile->SHeight, gifFile->SWidth, CV_8UC3); if (flatten == Flatten::Black) { mat.setTo(cv::Scalar(0, 0, 0)); } else if (flatten == Flatten::White) { mat.setTo(cv::Scalar(255, 255, 255)); } for (int i = 0; i < gifFile->ImageCount; ++i) { GraphicsControlBlock gcb; DGifSavedExtensionToGCB(gifFile, i, &gcb); mat = ReadFrame(mat.clone(), gifFile, i, gcb.TransparentColor); gif.frames->push_back(GifFrame(mat, gcb.DelayTime)); } DGifCloseFile(gifFile, &error); return true; } cv::Mat Gif::ReadFrame(cv::Mat mat, GifFileType* gifFile, int index, int transparentColor) { auto gifImage = &gifFile->SavedImages[index]; auto& imageDesc = gifImage->ImageDesc; const auto row = imageDesc.Top; /* Image Position relative to Screen. */ const auto col = imageDesc.Left; const auto width = imageDesc.Width; const auto bottom = row + imageDesc.Height; auto colorMap = imageDesc.ColorMap == nullptr ? gifFile->SColorMap : imageDesc.ColorMap; unsigned char* srcPtr = gifImage->RasterBits; for (int i = row; i < bottom; ++i) { auto destPtr = mat.data + mat.step * i + mat.channels() * col; for (int x = 0; x < width; ++x) { SetPixel(destPtr, srcPtr, colorMap, transparentColor); destPtr += mat.channels(); srcPtr++; } } return mat; } void Gif::SetPixel(unsigned char* dest, const unsigned char* src, ColorMapObject* colorMap, int transparentColor) { if (transparentColor >= 0 && transparentColor == *src) return; auto colorEntry = colorMap->Colors[*src]; dest[0] = colorEntry.Blue; dest[1] = colorEntry.Green; dest[2] = colorEntry.Red; } int GifBuffer::ReadFromData(GifFileType* gif, GifByteType* bytes, int size) { return ((GifBuffer*)gif->UserData)->Read(bytes, size); } int GifBuffer::Read(GifByteType* bytes, int size) { if (length - position < size) size = length - position; std::memcpy(bytes, buffer + position, size); position += size; return size; }
29.085366
115
0.67086
crema
e7db49fd1820aac516d688f41489b6279c002c05
857
cpp
C++
src/Core/Application.cpp
TheJoKeR15/RaiTracer
fb7c498d49c6f886228d54aed1939580bbfb4043
[ "Apache-2.0" ]
1
2020-12-26T03:55:08.000Z
2020-12-26T03:55:08.000Z
src/Core/Application.cpp
TheJoKeR15/RaiTracer
fb7c498d49c6f886228d54aed1939580bbfb4043
[ "Apache-2.0" ]
null
null
null
src/Core/Application.cpp
TheJoKeR15/RaiTracer
fb7c498d49c6f886228d54aed1939580bbfb4043
[ "Apache-2.0" ]
null
null
null
#include "Application.h" ApplicationLayer::ApplicationLayer(GLFWwindow* window, int weight, int height) { m_imGuiLayer = new ImGuiLayer(window, ImVec2((float)weight, (float)height)); } ApplicationLayer ::~ApplicationLayer() { delete m_imGuiLayer; } void ApplicationLayer::OnAttach() { RenderSettings rDesc; rDesc.height = 380; rDesc.width = 640; rDesc.spp = 1; sRenderer.SetupRenderer(rDesc); m_imGuiLayer->Init(); } void ApplicationLayer::OnStartFrame() { m_imGuiLayer->StartFrame(); bool show_app_dockspace = true; m_imGuiLayer->SetupDockspace(&show_app_dockspace); sRenderer.RenderUI(); } void ApplicationLayer::OnUpdate() { ImGui::ShowDemoWindow(); m_imGuiLayer->Render(); } void ApplicationLayer::OnEndFrame() { } void ApplicationLayer::OnDettach() { m_imGuiLayer->Shutdown(); }
18.234043
80
0.705951
TheJoKeR15
e7dc9cc36818cacc1b256cc8333ebf8286fbefed
215
cpp
C++
puzzlemoppet/source/NodeHandler.cpp
LibreGames/puzzlemoppet
d79b10e6968f9f1f27e930c4f13194700ff42126
[ "WTFPL" ]
null
null
null
puzzlemoppet/source/NodeHandler.cpp
LibreGames/puzzlemoppet
d79b10e6968f9f1f27e930c4f13194700ff42126
[ "WTFPL" ]
null
null
null
puzzlemoppet/source/NodeHandler.cpp
LibreGames/puzzlemoppet
d79b10e6968f9f1f27e930c4f13194700ff42126
[ "WTFPL" ]
null
null
null
#include "NodeHandler.h" void NodeHandler::ReceiveRenderPosition(core::vector3df pos) { irrNode->setPosition(pos); } void NodeHandler::ReceiveRenderRotation(core::vector3df rot) { irrNode->setRotation(rot); }
15.357143
60
0.767442
LibreGames
e7e21691c1e63353a0f8d4b3921fd608f4703eb1
940
cpp
C++
sources/2015/2015_10.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
2
2021-02-01T13:19:37.000Z
2021-02-25T10:39:46.000Z
sources/2015/2015_10.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
sources/2015/2015_10.cpp
tbielak/AoC_cpp
69f36748536e60a1b88f9d44a285feff20df8470
[ "MIT" ]
null
null
null
#include "2015_10.h" namespace Day10_2015 { pair<size_t, size_t> both_parts(string input) { size_t p1 = 0; size_t p2 = 0; for (int j = 1; j <= 50; j++) { string next; int cnt = 0; char ch = 0; for (size_t i = 0; i < input.size(); i++) { if (input[i] != ch) { if (ch) next += to_string(cnt) + ch; ch = input[i]; cnt = 1; } else cnt++; } if (ch) next += to_string(cnt) + ch; input = next; if (j == 40) p1 = input.size(); if (j == 50) p2 = input.size(); } return make_pair(p1, p2); } t_output main(const t_input& input) { auto t0 = chrono::steady_clock::now(); auto px = both_parts(input[0]); auto t1 = chrono::steady_clock::now(); vector<string> solutions; solutions.push_back(to_string(px.first)); solutions.push_back(to_string(px.second)); return make_pair(solutions, chrono::duration<double>((t1 - t0) * 1000).count()); } }
18.431373
82
0.565957
tbielak
e7e59a8104e8fabe05e8d54858ac8af31f80afc9
5,253
cpp
C++
examples/log_example.cpp
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
examples/log_example.cpp
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
examples/log_example.cpp
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <qi/log.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char **argv) { po::options_description desc("Allowed options"); int globalVerbosity; // Used to parse options, as well as to put help message desc.add_options() ("help,h", "Produces help message") ("version", "Output NAOqi version.") ("verbose,v", "Set verbose verbosity.") ("debug,d", "Set debug verbosity.") ("quiet,q", "Do not show logs on console.") ("context,c", po::value<int>(), "Show context logs: [0-7] (0: none, 1: categories, 2: date, 3: file+line, 4: date+categories, 5: date+line+file, 6: categories+line+file, 7: all (date+categories+line+file+function)).") ("synchronous-log", "Activate synchronous logs.") ("log-level,L", po::value<int>(&globalVerbosity), "Change the log minimum level: [0-6] (0: silent, 1: fatal, 2: error, 3: warning, 4: info, 5: verbose, 6: debug). Default: 4 (info)") ; // Map containing all the options with their values po::variables_map vm; // program option library throws all kind of errors, we just catch them // all, print usage and exit try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (po::error &e) { std::cerr << e.what() << std::endl; std::cout << desc << std::endl; exit(1); } if (vm.count("help")) { std::cout << desc << std::endl; return 0; } // set default log verbosity // set default log context if (vm.count("log-level")) { if (globalVerbosity > 0 && globalVerbosity <= 6) qi::log::setLogLevel((qi::LogLevel)globalVerbosity); if (globalVerbosity > 6) qi::log::setLogLevel(qi::LogLevel_Debug); if (globalVerbosity <= 0) qi::log::setLogLevel(qi::LogLevel_Silent); } // Remove consoleloghandler (default log handler) if (vm.count("quiet")) qi::log::removeHandler("consoleloghandler"); if (vm.count("debug")) qi::log::setLogLevel(qi::LogLevel_Debug); if (vm.count("verbose")) qi::log::setLogLevel(qi::LogLevel_Verbose); if (vm.count("context")) { int globalContext = vm["context"].as<int>(); if (globalContext < 0) { qi::log::setContext(0); } else { qi::log::setContext(globalContext); } } if (vm.count("synchronous-log")) qi::log::setSynchronousLog(true); qiLogFatal("core.log.example.1", "%d\n", 41); qiLogError("core.log.example.1", "%d\n", 42); qiLogWarning("core.log.example.1", "%d\n", 43); qiLogInfo("core.log.example.1", "%d\n", 44); qiLogVerbose("core.log.example.1", "%d\n", 45); qiLogDebug("core.log.example.1", "%d\n", 46); qiLogFatal("core.log.example.2") << "f" << 4 << std::endl; qiLogError("core.log.example.2") << "e" << 4 << std::endl; qiLogWarning("core.log.example.2") << "w" << 4 << std::endl; qiLogInfo("core.log.example.2") << "i" << 4 << std::endl; qiLogVerbose("core.log.example.2") << "v" << 4 << std::endl; qiLogDebug("core.log.example.2") << "d" << 4 << std::endl; qiLogFatal("core.log.example.1", "without '\\n': %d", 41); qiLogError("core.log.example.1", "without '\\n': %d", 42); qiLogWarning("core.log.example.1", "without '\\n': %d", 43); qiLogInfo("core.log.example.1", "without '\\n': %d", 44); qiLogVerbose("core.log.example.1", "without '\\n': %d", 45); qiLogDebug("core.log.example.1", "without '\\n': %d", 46); qiLogFatal("core.log.example.1", ""); qiLogFatal("core.log.example.1", "\n"); qiLogFatal("core.log.example.2") << "f " << "without '\\n'"; qiLogError("core.log.example.2") << "e " << "without '\\n'"; qiLogWarning("core.log.example.2") << "w " << "without '\\n'"; qiLogInfo("core.log.example.2") << "i " << "without '\\n'"; qiLogVerbose("core.log.example.2") << "v " << "without '\\n'"; qiLogDebug("core.log.example.2") << "d " << "without '\\n'"; qiLogFatal("core.log.example.2") << ""; qiLogFatal("core.log.example.2") << std::endl; qiLogFatal("core.log.example.3", "%d", 21) << "f" << 4 << std::endl; qiLogError("core.log.example.3", "%d", 21) << "e" << 4 << std::endl; qiLogWarning("core.log.example.3", "%d", 21) << "w" << 4 << std::endl; qiLogInfo("core.log.example.3", "%d", 21) << "i" << 4 << std::endl; qiLogVerbose("core.log.example.3", "%d", 21) << "v" << 4 << std::endl; qiLogDebug("core.log.example.3", "%d", 21) << "d" << 4 << std::endl; //c style qiLogWarning("core.log.example.4", "Oups my buffer is too bad: %x\n", 0x0BADCAFE); //c++ style qiLogError("core.log.example.4") << "Where is nao?" << " - Nao is in the kitchen." << " - How many are they? " << 42 << std::endl; //mixup style qiLogInfo("core.log.example.4", "%d %d ", 41, 42) << 43 << " " << 44 << std::endl; std::cout << "I've just finished to log!" << std::endl; }
35.734694
227
0.570912
yumilceh
e7e5d5107266ecb4fcb40f9eae3608ef75bab634
1,826
cpp
C++
test/unit/math/opencl/kernel_cl_test.cpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/kernel_cl_test.cpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/opencl/kernel_cl_test.cpp
peterwicksstringfield/math
5ce0718ea64f2cca8b2f1e4eeac27a2dc2bd246e
[ "BSD-3-Clause" ]
null
null
null
#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/opencl/opencl.hpp> #include <gtest/gtest.h> #include <algorithm> #define EXPECT_MATRIX_NEAR(A, B, DELTA) \ for (int i = 0; i < A.size(); i++) \ EXPECT_NEAR(A(i), B(i), DELTA); TEST(MathGpu, make_kernel) { stan::math::matrix_d m0(3, 3); stan::math::matrix_d m0_dst(3, 3); m0 << 1, 2, 3, 4, 5, 6, 7, 8, 9; stan::math::matrix_cl<double> m00(m0); stan::math::matrix_cl<double> m00_dst(m0.cols(), m0.rows()); stan::math::opencl_kernels::transpose(cl::NDRange(m00.rows(), m00.cols()), m00_dst, m00, m00.rows(), m00.cols()); m0_dst = stan::math::from_matrix_cl(m00_dst); } TEST(MathGpu, write_after_write) { using stan::math::matrix_cl; for (int j = 0; j < 1000; j++) { matrix_cl<double> m_cl(3, 3); for (int i = 0; i < 4; i++) { stan::math::opencl_kernels::fill(cl::NDRange(3, 3), m_cl, i, 3, 3, stan::math::matrix_cl_view::Entire); } stan::math::matrix_d res = stan::math::from_matrix_cl(m_cl); stan::math::matrix_d correct = stan::math::matrix_d::Constant(3, 3, 3); EXPECT_MATRIX_NEAR(res, correct, 1e-13); } } TEST(MathGpu, read_after_write_and_write_after_read) { using stan::math::matrix_cl; matrix_cl<double> m_cl(3, 3); matrix_cl<double> ms_cl[1000]; for (int j = 0; j < 1000; j++) { stan::math::opencl_kernels::fill(cl::NDRange(3, 3), m_cl, j, 3, 3, stan::math::matrix_cl_view::Entire); ms_cl[j] = m_cl; } for (int j = 0; j < 1000; j++) { stan::math::matrix_d res = stan::math::from_matrix_cl(ms_cl[j]); stan::math::matrix_d correct = stan::math::matrix_d::Constant(3, 3, j); EXPECT_MATRIX_NEAR(res, correct, 1e-13); } } #endif
29.451613
78
0.594195
peterwicksstringfield
e7e609a2ee5b0ac3c5d65d3452624fc99092084e
13,267
cpp
C++
src/atta/fileSystem/project/projectSerializer.cpp
brenocq/atta
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
5
2021-11-18T02:44:45.000Z
2021-12-21T17:46:10.000Z
src/atta/fileSystem/project/projectSerializer.cpp
Brenocq/RobotSimulator
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
1
2021-11-18T02:56:14.000Z
2021-12-04T15:09:16.000Z
src/atta/fileSystem/project/projectSerializer.cpp
Brenocq/RobotSimulator
dc0f3429c26be9b0a340e63076f00f996e9282cc
[ "MIT" ]
3
2020-09-10T07:17:00.000Z
2020-11-05T10:24:41.000Z
//-------------------------------------------------- // Atta File System // projectSerializer.cpp // Date: 2021-09-15 // By Breno Cunha Queiroz //-------------------------------------------------- #include <atta/fileSystem/project/projectSerializer.h> #include <atta/fileSystem/serializer/serializer.h> #include <atta/cmakeConfig.h> #include <atta/componentSystem/componentManager.h> #include <atta/componentSystem/components/components.h> #include <atta/resourceSystem/resourceManager.h> #include <atta/resourceSystem/resources/mesh.h> #include <atta/resourceSystem/resources/texture.h> #include <atta/graphicsSystem/graphicsManager.h> #include <atta/core/config.h> namespace atta { ProjectSerializer::ProjectSerializer(std::shared_ptr<Project> project): _project(project) { } ProjectSerializer::~ProjectSerializer() { } void ProjectSerializer::serialize() { fs::path attaTemp = _project->getFile(); attaTemp.replace_extension(".atta.temp"); std::ofstream os(attaTemp, std::ofstream::trunc | std::ofstream::binary); serializeHeader(os); serializeConfig(os); serializeComponentSystem(os); serializeGraphicsSystem(os); write(os, "end"); os.close(); // Override atta file with temp file fs::rename(attaTemp, _project->getFile()); } void ProjectSerializer::deserialize() { fs::path attaFile = _project->getFile(); std::ifstream is(attaFile, std::ifstream::in | std::ifstream::binary); Header header = deserializeHeader(is); //LOG_VERBOSE("ProjectSerializer", "[*y]Header:[]\n\tversion:$0.$1.$2.$3\n\tproj:$4\n\tcounter:$5", // header.version[0], header.version[1], header.version[2], header.version[3], // header.projectName, header.saveCounter); while(is) { std::string marker; read(is, marker); if(marker == "config") deserializeConfig(is); else if(marker == "comp") deserializeComponentSystem(is); else if(marker == "gfx") deserializeGraphicsSystem(is); else if(marker == "end") break; else { LOG_WARN("ProjectSerializer", "Unknown marker [w]$0[]. The file may be corrupted", marker); break; } } is.close(); } void ProjectSerializer::serializeHeader(std::ofstream& os) { // Atta info write(os, "atta"); uint16_t version[] = { ATTA_VERSION_MAJOR, ATTA_VERSION_MINOR, ATTA_VERSION_PATCH, ATTA_VERSION_TWEAK }; write(os, version);// Version // Project info write(os, "proj"); write(os, _project->getName());// Project name uint32_t saveCounter = 0; write(os, saveCounter);// Save counter (number of times that was saved) write(os, "hend"); } ProjectSerializer::Header ProjectSerializer::deserializeHeader(std::ifstream& is) { std::string marker; Header header; while(true) { read(is, marker); if(marker == "hend") { return header; } else if(marker == "atta") { read(is, header.version); } else if(marker == "proj") { read(is, header.projectName); read(is, header.saveCounter); } else { LOG_WARN("ProjectSerializer", "Unknown marker found at the header [w]$0[]", marker); return header; } } return header; } void ProjectSerializer::serializeConfig(std::ofstream& os) { write(os, "config"); // Dt write(os, "dt"); write(os, Config::getDt()); write(os, "cend"); } void ProjectSerializer::deserializeConfig(std::ifstream& is) { std::string marker; while(true) { read(is, marker); if(marker == "dt") { float dt; read(is, dt); Config::setDt(dt); } else if(marker == "cend") { return; } else { LOG_WARN("ProjectSerializer", "Unknown marker found at the config [w]$0[]", marker); } } } void ProjectSerializer::serializeComponentSystem(std::ofstream& os) { std::stringstream oss; std::basic_ostream<char>::pos_type posBefore = oss.tellp(); //---------- Write to temporary buffer ----------// // Serialize entity ids std::vector<EntityId> entities = ComponentManager::getNoCloneView(); write(oss, "id");// Entity id marker write<uint64_t>(oss, entities.size()); for(EntityId entity : entities) write(oss, entity); // Serialize number of components write<uint32_t>(oss, ComponentManager::getComponentRegistries().size()); // Serialize components for(auto compReg : ComponentManager::getComponentRegistries()) { // Write name write(oss, compReg->getDescription().name); // Get all entities that have this component std::vector<std::pair<EntityId,Component*>> pairs; for(auto entity : entities) { Component* comp = ComponentManager::getEntityComponentById(compReg->getId(), entity); if(comp != nullptr) pairs.push_back(std::make_pair(entity, comp)); } // Write size in bytes of this next section (can be useful if the component is unknown and can't be deserialized) unsigned totalSectionSize = 0; for(auto compPair : pairs) totalSectionSize += compReg->getSerializedSize(compPair.second) + sizeof(EntityId); write<uint32_t>(oss, totalSectionSize); std::basic_ostream<char>::pos_type posBef = oss.tellp(); for(auto compPair : pairs) { // TODO Open vector write(oss, compPair.first); compReg->serialize(oss, compPair.second); } ASSERT(oss.tellp()-posBef == totalSectionSize, "Serialized section size and calculated section size does not match"); } //---------- Flush buffer to file ----------// // Write section header size_t size = (int)oss.tellp() - posBefore; write(os, "comp");// Section title write(os, size);// Section size // Write section body char* buffer = new char[size]; oss.rdbuf()->pubseekpos(0);// Return to first position oss.rdbuf()->sgetn(buffer, size);// Copy to buffer os.write(reinterpret_cast<const char*>(buffer), size); delete[] buffer; } void ProjectSerializer::deserializeComponentSystem(std::ifstream& is) { // Read section size in bytes size_t sizeBytes; read(is, sizeBytes); int endSectionPos = int(is.tellg()) + sizeBytes;// Used to validate position at the end // Read section std::string marker; uint32_t numComponents = 0; // Read entity ids { read(is, marker); if(marker != "id") { LOG_WARN("ProjectSerializer", "First component marker must be [w]id[], but it is [w]$0[]. Could not load atta file", marker); return; } uint64_t numIds; read(is, numIds); for(uint64_t i = 0; i < numIds; i++) { EntityId id; read(is, id); EntityId res = ComponentManager::createEntity(id); if(res != id) LOG_WARN("ProjectSerializer","Could not create entity with id $0", id); } } // Read number of components read(is, numComponents); for(uint32_t i = 0; i < numComponents; i++) { uint32_t componentSectionSize;// Can be used to skip the component data if it is an unknown component // Read component name read(is, marker); read(is, componentSectionSize); ComponentRegistry* compReg = nullptr; int componentSectionEndPos = int(is.tellg()) + componentSectionSize; // Find correct component registry for(auto componentRegistry : ComponentManager::getComponentRegistries()) { if(componentRegistry->getDescription().name == marker) { compReg = componentRegistry; break; } } // If not found the component, skip this section if(compReg == nullptr) { is.ignore(componentSectionEndPos); continue; } // Deserialize while(int(is.tellg()) < componentSectionEndPos) { EntityId eid; read(is, eid); Component* component = ComponentManager::addEntityComponentById(compReg->getId(), eid); compReg->deserialize(is, component); } // Check finished at right position if(int(is.tellg()) != componentSectionEndPos) { LOG_WARN("ProjectSerializer", "Expected position ([w]$0[]) and actual position ([w]$1[])does not match for [*w]component $2 section[]. Some data may have been incorrectly initialized for this component", (int)is.tellg(), componentSectionEndPos, compReg->getDescription().name); is.seekg(componentSectionEndPos, std::ios_base::beg); } } if(int(is.tellg()) != endSectionPos) { LOG_WARN("ProjectSerializer", "Expected position ([w]$0[]) and actual position ([w]$1[])does not match for the [*w]component system section[]. Some data may have been incorrectly initialized", (int)is.tellg(), endSectionPos); is.seekg(endSectionPos, std::ios_base::beg); } } void ProjectSerializer::serializeGraphicsSystem(std::ofstream& os) { std::stringstream oss; std::basic_ostream<char>::pos_type posBefore = oss.tellp(); //---------- Write to temporary buffer ----------// // Number of subsections write<uint32_t>(oss, 1); //----- Viewport subsection -----// write(oss, "viewports"); std::vector<std::shared_ptr<Viewport>> viewports = GraphicsManager::getViewports(); unsigned sectionSize = 0; for(auto viewport : viewports) sectionSize += viewport->getSerializedSize(); // Serialize section size in bytes write<uint32_t>(oss, sectionSize); // Serialize number of viewports write<uint32_t>(oss, viewports.size()); // Serialize for(auto viewport : viewports) viewport->serialize(oss); //---------- Flush buffer to file ----------// // Write section header size_t size = (int)oss.tellp() - posBefore; write(os, "gfx");// Section title write(os, size);// Section size // Write section body char* buffer = new char[size]; oss.rdbuf()->pubseekpos(0);// Return to first position oss.rdbuf()->sgetn(buffer, size);// Copy to buffer os.write(reinterpret_cast<const char*>(buffer), size); delete[] buffer; } void ProjectSerializer::deserializeGraphicsSystem(std::ifstream& is) { size_t sizeBytes; read(is, sizeBytes); int sectionEndPos = int(is.tellg()) + sizeBytes;// Used to validate position at the end unsigned numSections; read(is, numSections); unsigned curr = numSections; while(curr--) { std::string marker; read(is, marker); if(marker == "viewports") { // Read section size in bytes unsigned sectionSize; read(is, sectionSize); // Read number of viewports unsigned numViewports; read(is, numViewports); // Deserialize GraphicsManager::clearViewports(); for(unsigned i = 0; i < numViewports; i++) { std::shared_ptr<Viewport> viewport; viewport = std::make_shared<Viewport>(Viewport::CreateInfo{}); viewport->deserialize(is); GraphicsManager::addViewport(viewport); } } } if(int(is.tellg()) != sectionEndPos) { LOG_WARN("ProjectSerializer", "Expected position ([w]$0[]) and actual position ([w]$1[])does not match for the [*w]graphics system section[]. Some data may have been incorrectly initialized", (int)is.tellg(), sectionEndPos); is.seekg(sectionEndPos, std::ios_base::beg); } } }
33.587342
293
0.544434
brenocq
e7efd444fb854946efc856df366d11f249d692db
233
cpp
C++
greeting.cpp
ADITYA-CS/ncurse
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
[ "MIT" ]
null
null
null
greeting.cpp
ADITYA-CS/ncurse
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
[ "MIT" ]
null
null
null
greeting.cpp
ADITYA-CS/ncurse
f6a9ce3b5e024b76338ab92ae966daf63eb53bc2
[ "MIT" ]
null
null
null
#include <ncurses.h> int main(void) { initscr(); char text[] = "Greetings from NCurses!"; char *t = text; while(*t) { addch(*t++); refresh(); napms(100); } endwin(); return 0; }
12.944444
44
0.472103
ADITYA-CS
e7f039a3480d5001ccc2814ae9898acf0a79cdaf
483
cpp
C++
src/node.cpp
pedroccrp/mata54-compressor
921fe88abd09217a7d6b865106ece4871ba2ec87
[ "MIT" ]
null
null
null
src/node.cpp
pedroccrp/mata54-compressor
921fe88abd09217a7d6b865106ece4871ba2ec87
[ "MIT" ]
null
null
null
src/node.cpp
pedroccrp/mata54-compressor
921fe88abd09217a7d6b865106ece4871ba2ec87
[ "MIT" ]
null
null
null
#include "node.h" Node::Node() { } Node::Node(char value_, int rate_, bool isLeaf_) { value = value_; rate = rate_; isLeaf = isLeaf_; } Node::~Node() { } void Node::addChild(Node node) { children.push_back(node); } bool operator<(const Node& n1, const Node& n2) { return n1.rate < n2.rate; } bool operator>(const Node& n1, const Node& n2) { return n1.rate > n2.rate; } bool operator==(const Node& n1, const Node& n2) { return n1.rate == n2.rate; }
13.054054
48
0.619048
pedroccrp
e7f4dc026ad488f4a4b3e4f1f385c222346d1ab6
1,901
cpp
C++
ZooidEngine/UI/UIInputComponent.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
4
2019-05-31T22:55:49.000Z
2020-11-26T11:55:34.000Z
ZooidEngine/UI/UIInputComponent.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
null
null
null
ZooidEngine/UI/UIInputComponent.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
1
2018-04-11T02:50:47.000Z
2018-04-11T02:50:47.000Z
#include "UIInputComponent.h" #include "ZooidUI.h" #include "ZEGameContext.h" #include "Input/InputManager.h" #include "Input/Keys.h" namespace ZE { IMPLEMENT_CLASS_1(UIInputComponent, Component); UIInputComponent::UIInputComponent(GameContext* gameContext) : Component(gameContext) { } void UIInputComponent::setupComponent() { Component::setupComponent(); addEventDelegate(Event_UPDATE, &UIInputComponent::handleUpdateEvent); addEventDelegate(Event_MOUSE_SCROLL, &UIInputComponent::handleMouseScroll); addEventDelegate(Event_KEY_UP, &UIInputComponent::handleKeyUp); addEventDelegate(Event_KEY_DOWN, &UIInputComponent::handleKeyDown); addEventDelegate(Event_TEXT_INPUT, &UIInputComponent::handleTextInput); } void UIInputComponent::handleUpdateEvent(Event* _event) { Int32 mouseX = 0; Int32 mouseY = 0; EButtonState buttonState = EButtonState::BUTTON_DOWN; InputManager* inputManager = m_gameContext->getInputManager(); inputManager->getMousePosition(mouseX, mouseY); buttonState = inputManager->IsKeyDown(Key::MouseLeftButton) ? EButtonState::BUTTON_DOWN : EButtonState::BUTTON_UP; ZE::UI::UpdateMouseState((Float32)mouseX, (Float32)mouseY, buttonState); } void UIInputComponent::handleMouseScroll(Event* _event) { Event_MOUSE_SCROLL* pRealEvent = (Event_MOUSE_SCROLL*)_event; ZE::UI::RecordMouseScroll(pRealEvent->m_deltaScrollY); } void UIInputComponent::handleKeyUp(Event* _event) { Event_INPUT* inputEvent = (Event_INPUT*)_event; ZE::UI::RecordKeyboardButton(inputEvent->m_keyId, 1); } void UIInputComponent::handleKeyDown(Event* _event) { Event_INPUT* inputEvent = (Event_INPUT*)_event; ZE::UI::RecordKeyboardButton(inputEvent->m_keyId, 0); } void UIInputComponent::handleTextInput(Event* _event) { Event_TEXT_INPUT* inputEvent = (Event_TEXT_INPUT*)_event; ZE::UI::RecordTextInput(inputEvent->m_charCode); } }
27.550725
116
0.776433
azon04
e7fa714d7f40dcea1a236b7ac245bc545bbac3b3
2,190
cpp
C++
game/modules/settings.cpp
tapio/weep
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
[ "MIT" ]
33
2017-01-13T20:47:21.000Z
2022-03-21T23:29:17.000Z
game/modules/settings.cpp
tapio/weep
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
[ "MIT" ]
null
null
null
game/modules/settings.cpp
tapio/weep
aca40e3ce20eae4ce183a98ab707ac65c4be4e63
[ "MIT" ]
4
2016-12-10T16:10:42.000Z
2020-06-28T04:44:11.000Z
// Implements a settings menu for end-user. This is in a separate module // so that it can be shared between multiple small example games. #include "common.hpp" #include "renderer.hpp" #include "glrenderer/renderdevice.hpp" #include "audio.hpp" #include "gui.hpp" #include "../game.hpp" #include <json11/json11.hpp> using json11::Json; MODULE_EXPORT void MODULE_FUNC_NAME(uint msg, void* param) { Game& game = *static_cast<Game*>(param); switch (msg) { case $id(INIT): case $id(RELOAD): { game.moduleInit(); break; } case $id(DRAW_SETTINGS_MENU): { RenderSystem& renderer = game.entities.get_system<RenderSystem>(); AudioSystem& audio = game.entities.get_system<AudioSystem>(); bool vsync = game.engine.vsync(); bool oldVsync = vsync; ImGui::Checkbox("V-sync", &vsync); if (vsync != oldVsync) game.engine.vsync(vsync); ImGui::SameLine(); bool fullscreen = game.engine.fullscreen(); bool oldFullscreen = fullscreen; ImGui::Checkbox("Fullscreen", &fullscreen); if (fullscreen != oldFullscreen) { game.engine.fullscreen(fullscreen); renderer.device().resizeRenderTargets(RenderDevice::RENDER_TARGET_SCREEN); } float volume = audio.soloud->getGlobalVolume(); float oldVolume = volume; ImGui::SliderFloat("Volume", &volume, 0.f, 1.25f); if (volume != oldVolume) audio.soloud->setGlobalVolume(volume); ImGui::SliderInt("Threads", (int*)&game.engine.threads, 0, 8); if (CVar<int>* cvar_msaa = CVar<int>::getCVar("r.msaaSamples")) { int oldMsaa = glm::max((*cvar_msaa)(), 1); float msaa = log2(oldMsaa); ImGui::SliderFloat("MSAA", &msaa, 0.f, 3.f, "%.0f"); int newMsaa = powf(2, msaa); ImGui::SameLine(); ImGui::Text("%dx", newMsaa); if (newMsaa != oldMsaa) { cvar_msaa->value = newMsaa; renderer.device().resizeRenderTargets(RenderDevice::RENDER_TARGET_SCREEN); } } bool fxaa = renderer.env().postAA == Environment::POST_AA_FXAA; ImGui::Checkbox("FXAA", &fxaa); renderer.env().postAA = fxaa ? Environment::POST_AA_FXAA : Environment::POST_AA_NONE; ImGui::SameLine(); ImGui::Checkbox("Shadows", &renderer.settings.shadows); break; } } }
30
88
0.677626
tapio
e7fc661eb3da78393138874d92b0124b6335f4fb
4,069
cpp
C++
StyleFramework/StyleGridCtrl.cpp
edwig/StyleFramework
c9b19af74f5298c3da348cdbdc988191e76ed807
[ "MIT" ]
2
2021-04-03T12:50:30.000Z
2022-02-08T23:23:56.000Z
StyleFramework/StyleGridCtrl.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
10
2022-01-14T13:28:32.000Z
2022-02-13T12:46:34.000Z
StyleFramework/StyleGridCtrl.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////// // // File: StyleGridCtrl.cpp // Function: Styling frame for the Chris Maunder CGridCtrl grid. // // _____ _ _ _ ______ _ // / ____| | | (_) | ____| | | // | (___ | |_ _ _| |_ _ __ __ _| |__ _ __ __ _ _ __ ___ _____ _____ _ __| | __ // \___ \| __| | | | | | '_ \ / _` | __| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ / // ____) | |_| |_| | | | | | | (_| | | | | | (_| | | | | | | __/\ V V / (_) | | | < // |_____/ \__|\__, |_|_|_| |_|\__, |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_\ // __/ | __/ | // |___/ |___/ // // // Author: ir. W.E. Huisman // For license: See the file "LICENSE.txt" in the root folder // #include "stdafx.h" #include "StyleGridCtrl.h" #include "StyleFonts.h" #include "Stylecolors.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // StyleGridCtrl StyleGridCtrl::StyleGridCtrl() { } StyleGridCtrl::~StyleGridCtrl() { } BEGIN_MESSAGE_MAP(StyleGridCtrl, CGridCtrl) ON_WM_PAINT() ON_WM_SHOWWINDOW() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // message handlers void StyleGridCtrl::InitSkin() { // Test if init already done if(GetWindowLongPtr(GetSafeHwnd(),GWLP_USERDATA) != NULL) { return; } // Skin our grid SetFont(&STYLEFONTS.DialogTextFont); SkinScrollWnd* skin = SkinWndScroll(this,1); skin->SetScrollbarBias(0); } void StyleGridCtrl::ResetSkin() { UnskinWndScroll(this); } LRESULT StyleGridCtrl::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { if(message == WM_VSCROLL || message == WM_HSCROLL) { WORD sbCode = LOWORD(wParam); if (sbCode == SB_THUMBTRACK || sbCode == SB_THUMBPOSITION) { SCROLLINFO siv = { 0 }; siv.cbSize = sizeof(SCROLLINFO); siv.fMask = SIF_ALL; SCROLLINFO sih = siv; int nPos = HIWORD(wParam); GetScrollInfo(SB_VERT, &siv); GetScrollInfo(SB_HORZ, &sih); // Rather clunky: but it gets the job done // But this is what CGridCtrl also does: translate to single scroll actions if (WM_VSCROLL == message) { return SendMessage(message,nPos > siv.nPos ? SB_LINEDOWN : SB_LINEUP,0); } else { return SendMessage(message,nPos > sih.nPos ? SB_RIGHT : SB_LEFT); } } } return CGridCtrl::WindowProc(message, wParam, lParam); } void StyleGridCtrl::DrawFrame() { COLORREF color = ThemeColor::_Color1; SkinScrollWnd* skin = (SkinScrollWnd*)GetWindowLongPtr(m_hWnd,GWLP_USERDATA); if(skin) { skin->DrawFrame(color); } } void StyleGridCtrl::OnPaint() { if(!m_inPaint) { m_inPaint = true; CGridCtrl::OnPaint(); DrawFrame(); m_inPaint = false; } } SkinScrollWnd* StyleGridCtrl::GetSkin() { return (SkinScrollWnd*)GetWindowLongPtr(GetSafeHwnd(), GWLP_USERDATA); } // Propagate the ShowWindow command void StyleGridCtrl::OnShowWindow(BOOL bShow, UINT nStatus) { SkinScrollWnd* skin = GetSkin(); if (skin && nStatus == 0) { // nStatus == 0 means: Message sent is caused by an explict "ShowWindow" call skin->ShowWindow(bShow ? SW_SHOW : SW_HIDE); } else { CGridCtrl::OnShowWindow(bShow, nStatus); } } ////////////////////////////////////////////////////////////////////////// // // SUPPORT FOR DynamicDataEXchange in Dialogs // ////////////////////////////////////////////////////////////////////////// void WINAPI DDX_Control(CDataExchange* pDX,int nIDC,StyleGridCtrl& p_gridControl) { CWnd& control = reinterpret_cast<CWnd&>(p_gridControl); DDX_Control(pDX,nIDC,control); p_gridControl.InitSkin(); }
25.753165
91
0.529123
edwig
e7fcefc0e0a7f5b05a9d3530c85fee061e89034e
15,397
cpp
C++
xyfd/GaussLegendreQuad.cpp
xxxiasu/XYFDPlus
6bc49723100c9c052a8613ae8ca3135794bc558f
[ "MIT" ]
2
2020-09-08T15:58:16.000Z
2020-09-09T12:44:18.000Z
xyfd/GaussLegendreQuad.cpp
xxxiasu/XYFDPlus
6bc49723100c9c052a8613ae8ca3135794bc558f
[ "MIT" ]
null
null
null
xyfd/GaussLegendreQuad.cpp
xxxiasu/XYFDPlus
6bc49723100c9c052a8613ae8ca3135794bc558f
[ "MIT" ]
null
null
null
/** * GaussLegendreQuad.cpp : xyfd class for representing Gauss-Legendre quadrature rules. * * @author * Xiasu Yang <[email protected]> */ /*------------------------------------------------------------------*\ Dependencies \*------------------------------------------------------------------*/ #include "GaussLegendreQuad.h" #include <iostream> #include <cmath> #include <vector> #include <array> /*------------------------------------------------------------------*\ Aliases \*------------------------------------------------------------------*/ using StdArray2d = std::array<double, 2>; using DoubleVec = std::vector<double>; //-More comments in GaussLegendreQuad.h // namespace xyfd { void GaussLegendreQuad::_setX() { int deg = floor((order_ - 1)/2) + 1; if (deg < 1) throw std::invalid_argument("Gauss-Legendre degree must >= 1!!!"); else if (deg > 12) throw std::invalid_argument("deg > 12 data not available for Gauss-Legendre rule!!!"); else if (deg == 1) x_ = {0.}; else if (deg == 2) x_ = {-1./sqrt(3.), 1./sqrt(3.)}; else if (deg == 3) x_ = {-sqrt(3.)/sqrt(5.), 0., sqrt(3.)/sqrt(5.)}; else if (deg == 4) x_= {-sqrt(15.+2.*sqrt(30.))/sqrt(35.), -sqrt(15.-2.*sqrt(30.))/sqrt(35.), sqrt(15.-2.*sqrt(30.))/sqrt(35.), sqrt(15.+2.*sqrt(30.))/sqrt(35.)}; else if (deg == 5) x_ = {-sqrt(35.+2.*sqrt(70.))/(3.*sqrt(7.)), -sqrt(35.-2.*sqrt(70.))/(3.*sqrt(7.)), 0., sqrt(35.-2.*sqrt(70.))/(3.*sqrt(7.)), sqrt(35.+2.*sqrt(70.))/(3.*sqrt(7.))}; else if (deg == 6) x_ = {-0.932469514203152027812301554493994609134765737712289824872549616526613, -0.661209386466264513661399595019905347006448564395170070814526705852183, -0.238619186083196908630501721680711935418610630140021350181395164574274, 0.238619186083196908630501721680711935418610630140021350181395164574274, 0.661209386466264513661399595019905347006448564395170070814526705852183, 0.932469514203152027812301554493994609134765737712289824872549616526613}; else if (deg == 7) x_ = {-0.949107912342758524526189684047851262400770937670617783548769103913063, -0.741531185599394439863864773280788407074147647141390260119955351967429, -0.405845151377397166906606412076961463347382014099370126387043251794663, 0., 0.405845151377397166906606412076961463347382014099370126387043251794663, 0.741531185599394439863864773280788407074147647141390260119955351967429, 0.949107912342758524526189684047851262400770937670617783548769103913063}; else if (deg == 8) x_ = {-0.960289856497536231683560868569472990428235234301452038271639777372424, -0.796666477413626739591553936475830436837171731615964832070170295039217, -0.525532409916328985817739049189246349041964243120392857750857099272454, -0.183434642495649804939476142360183980666757812912973782317188473699204, 0.183434642495649804939476142360183980666757812912973782317188473699204, 0.525532409916328985817739049189246349041964243120392857750857099272454, 0.796666477413626739591553936475830436837171731615964832070170295039217, 0.960289856497536231683560868569472990428235234301452038271639777372424}; else if (deg == 9) x_ = {-0.968160239507626089835576202903672870049404800491925329550023311849080, -0.836031107326635794299429788069734876544106718124675996104371979639455, -0.613371432700590397308702039341474184785720604940564692872812942281267, -0.324253423403808929038538014643336608571956260736973088827047476842186, 0., 0.324253423403808929038538014643336608571956260736973088827047476842186, 0.613371432700590397308702039341474184785720604940564692872812942281267, 0.836031107326635794299429788069734876544106718124675996104371979639455, 0.968160239507626089835576202903672870049404800491925329550023311849080}; else if (deg == 10) x_ = {-0.973906528517171720077964012084452053428269946692382119231212066696595, -0.865063366688984510732096688423493048527543014965330452521959731845374, -0.679409568299024406234327365114873575769294711834809467664817188952558, -0.433395394129247190799265943165784162200071837656246496502701513143766, -0.148874338981631210884826001129719984617564859420691695707989253515903, 0.148874338981631210884826001129719984617564859420691695707989253515903, 0.433395394129247190799265943165784162200071837656246496502701513143766, 0.679409568299024406234327365114873575769294711834809467664817188952558, 0.865063366688984510732096688423493048527543014965330452521959731845374, 0.973906528517171720077964012084452053428269946692382119231212066696595}; else if (deg == 11) x_ = {-0.978228658146056992803938001122857390771422408919784415425801065983663, -0.887062599768095299075157769303927266631675751225314384967411055537611, -0.730152005574049324093416252031153458049643062026130311978378339687013, -0.519096129206811815925725669458609554480227115119928489020922611486695, -0.269543155952344972331531985400861524679621862439052281623925631880057, 0., 0.269543155952344972331531985400861524679621862439052281623925631880057, 0.519096129206811815925725669458609554480227115119928489020922611486695, 0.730152005574049324093416252031153458049643062026130311978378339687013, 0.887062599768095299075157769303927266631675751225314384967411055537611, 0.978228658146056992803938001122857390771422408919784415425801065983663}; else if (deg == 12) x_ = {-0.981560634246719250690549090149280822960155199813731510462682121807793, -0.904117256370474856678465866119096192537596709213297546554075760681234, -0.769902674194304687036893833212818075984925750018931637664419064249116, -0.587317954286617447296702418940534280369098514048052481510270879667340, -0.367831498998180193752691536643717561256360141335409621311799879504089, -0.125233408511468915472441369463853129983396916305444273212921754748462, 0.125233408511468915472441369463853129983396916305444273212921754748462, 0.367831498998180193752691536643717561256360141335409621311799879504089, 0.587317954286617447296702418940534280369098514048052481510270879667340, 0.769902674194304687036893833212818075984925750018931637664419064249116, 0.904117256370474856678465866119096192537596709213297546554075760681234, 0.981560634246719250690549090149280822960155199813731510462682121807793}; } void GaussLegendreQuad::_setW() { int deg = floor((order_ - 1)/2) + 1; if (deg < 1) throw std::invalid_argument("Gauss-Legendre degree must >= 1!!!"); else if (deg > 12) throw std::invalid_argument("deg > 12 data not available for Gauss-Legendre rule!!!"); else if (deg == 1) w_ = {2.}; else if (deg == 2) w_ = {1., 1.}; else if (deg == 3) w_ = {5./9., 8./9., 5./9.}; else if (deg == 4) w_ = {49./(6.*(18.+sqrt(30.))), 49./(6.*(18.-sqrt(30.))), 49./(6.*(18.-sqrt(30.))), 49./(6.*(18.+sqrt(30.)))}; else if (deg == 5) w_ = {5103./(50.*(322.+13.*sqrt(70.))), 5103./(50.*(322.-13.*sqrt(70.))), 128./225., 5103./(50.*(322.-13.*sqrt(70.))), 5103./(50.*(322.+13.*sqrt(70.)))}; else if (deg == 6) w_ = {0.171324492379170345040296142172732893526822501484043982398635439798945, 0.360761573048138607569833513837716111661521892746745482289739240237140, 0.467913934572691047389870343989550994811655605769210535311625319963914, 0.467913934572691047389870343989550994811655605769210535311625319963914, 0.360761573048138607569833513837716111661521892746745482289739240237140, 0.171324492379170345040296142172732893526822501484043982398635439798945}; else if (deg == 7) w_ = {0.129484966168869693270611432679082018328587402259946663977208638724655, 0.279705391489276667901467771423779582486925065226598764537014032693618, 0.381830050505118944950369775488975133878365083533862734751083451030705, 0.417959183673469387755102040816326530612244897959183673469387755102040, 0.381830050505118944950369775488975133878365083533862734751083451030705, 0.279705391489276667901467771423779582486925065226598764537014032693618, 0.129484966168869693270611432679082018328587402259946663977208638724655}; else if (deg == 8) w_ = {0.101228536290376259152531354309962190115394091051684957059003698064740, 0.222381034453374470544355994426240884430130870051249564725909289293616, 0.313706645877887287337962201986601313260328999002734937690263945074656, 0.362683783378361982965150449277195612194146039894330540524823067566686, 0.362683783378361982965150449277195612194146039894330540524823067566686, 0.313706645877887287337962201986601313260328999002734937690263945074956, 0.222381034453374470544355994426240884430130870051249564725909289293616, 0.101228536290376259152531354309962190115394091051684957059003698064740}; else if (deg == 9) w_ = {0.0812743883615744119718921581105236506756617207824107507111076768806866, 0.180648160694857404058472031242912809514337821732040484498335906471357, 0.260610696402935462318742869418632849771840204437299951939997002119610, 0.312347077040002840068630406584443665598754861261904645554011165599143, 0.330239355001259763164525069286974048878810783572688334593096497858402, 0.312347077040002840068630406584443665598754861261904645554011165599143, 0.260610696402935462318742869418632849771840204437299951939997002119610, 0.180648160694857404058472031242912809514337821732040484498335906471357, 0.0812743883615744119718921581105236506756617207824107507111076768806866}; else if (deg == 10) w_ = {0.0666713443086881375935688098933317928578648343201581451286948816134120, 0.149451349150580593145776339657697332402556639669427367835477268753238, 0.219086362515982043995534934228163192458771870522677089880956543635199, 0.269266719309996355091226921569469352859759938460883795800563276242153, 0.295524224714752870173892994651338329421046717026853601354308029755995, 0.295524224714752870173892994651338329421046717026853601354308029755995, 0.269266719309996355091226921569469352859759938460883795800563276242153, 0.219086362515982043995534934228163192458771870522677089880956543635199, 0.149451349150580593145776339657697332402556639669427367835477268753238, 0.0666713443086881375935688098933317928578648343201581451286948816134120}; else if (deg == 11) w_ = {0.0556685671161736664827537204425485787285156256968981483483842856741554, 0.125580369464904624634694299223940100197615791395403500663934010817914, 0.186290210927734251426097641431655891691284748040203411781506404173872, 0.233193764591990479918523704843175139431798172316958509027319722121932, 0.262804544510246662180688869890509195372764677603144556380055371485512, 0.272925086777900630714483528336342189156041969894783747597600411453225, 0.262804544510246662180688869890509195372764677603144556380055371485512, 0.233193764591990479918523704843175139431798172316958509027319722121932, 0.186290210927734251426097641431655891691284748040203411781506404173872, 0.125580369464904624634694299223940100197615791395403500663934010817914, 0.0556685671161736664827537204425485787285156256968981483483842856741554}; else if (deg == 12) w_ = {0.0471753363865118271946159614850170603170290739948470895605053470038097, 0.106939325995318430960254718193996224214570173470324880005126042102818, 0.160078328543346226334652529543359071872011730490864177909899544157954, 0.203167426723065921749064455809798376506518147274590146398594565797645, 0.233492536538354808760849898924878056259409972199754874730523497821492, 0.249147045813402785000562436042951210830460902569618831395351003116279, 0.249147045813402785000562436042951210830460902569618831395351003116279, 0.233492536538354808760849898924878056259409972199754874730523497821492, 0.203167426723065921749064455809798376506518147274590146398594565797645, 0.160078328543346226334652529543359071872011730490864177909899544157954, 0.106939325995318430960254718193996224214570173470324880005126042102818, 0.0471753363865118271946159614850170603170290739948470895605053470038097}; } GaussLegendreQuad::GaussLegendreQuad(int order) //-Remark : use member initializer list when possible // to limit parameter copying : order_(order) { _setX(); _setW(); } GaussLegendreQuad::GaussLegendreQuad(const GaussLegendreQuad &obj) : order_(obj.order_), x_(obj.x_), w_(obj.w_) {} GaussLegendreQuad &GaussLegendreQuad::operator=(const GaussLegendreQuad &obj) { order_ = obj.order_; x_ = obj.x_; w_ = obj.w_; return *this; } int GaussLegendreQuad::getOrder() const { return order_; } DoubleVec GaussLegendreQuad::getX() const { return x_; } DoubleVec GaussLegendreQuad::getW() const { return w_; } } // namespace xyfd
58.543726
98
0.673053
xxxiasu
f0069085f03a6eff49cae6b18f4a5eed49d722e6
766
hpp
C++
src/ast/include/function_call_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
5
2017-03-28T00:36:54.000Z
2019-08-06T00:05:44.000Z
src/ast/include/function_call_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
4
2017-03-28T01:36:05.000Z
2017-04-17T20:34:46.000Z
src/ast/include/function_call_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
null
null
null
#ifndef FUNCTION_CALL_EXPR_HPP #define FUNCTION_CALL_EXPR_HPP class FunctionDecl; #include "expr.hpp" class FunctionCallExpr : virtual public Expr { private: FunctionDecl* func; std::vector<std::unique_ptr<Expr>> args; public: FunctionCallExpr() = delete; FunctionCallExpr(ScopeCreator* owner, Expr* pe, FunctionDecl* fd) : Stmt(owner), Expr(owner, pe), func(fd) {} virtual ~FunctionCallExpr() = default; FunctionDecl* getFunc() { return func; } const FunctionDecl* getFunc() const { return func; } void setFunc(FunctionDecl* fd) { func = fd; } std::vector<Expr*> getArgs(); std::vector<const Expr*> getArgs() const; void addArg(std::unique_ptr<Expr> arg) { args.emplace_back(std::move(arg)); } }; #include "function_decl.hpp" #endif
26.413793
79
0.715405
bfeip
f00ac9b055704cdea5f7e2c8677c5d0a2c99a793
369
cpp
C++
source/XCalcSigLib/Data/Functions.cpp
feudalnate/NinjaCrypt
e0a2a42735f3ffcb0e88c1d66998a126569e2d67
[ "Unlicense" ]
2
2022-03-11T20:13:05.000Z
2022-03-12T07:49:01.000Z
source/XCalcSigLib/Data/Functions.cpp
feudalnate/NinjaCrypt
e0a2a42735f3ffcb0e88c1d66998a126569e2d67
[ "Unlicense" ]
null
null
null
source/XCalcSigLib/Data/Functions.cpp
feudalnate/NinjaCrypt
e0a2a42735f3ffcb0e88c1d66998a126569e2d67
[ "Unlicense" ]
1
2022-03-11T20:13:07.000Z
2022-03-11T20:13:07.000Z
#include "Functions.h" void memcpy(byte* dst, byte* src, u32 len) { for (u32 i = 0; i < len; i++) dst[i] = src[i]; } void memset(byte* buffer, byte value, u32 len) { for (u32 i = 0; i < len; i++) buffer[i] = value; } bool32 memcmp(byte* a, byte* b, u32 len) { for (u32 i = 0; i < len; i++) if (a[i] != b[i]) return false; return true; }
20.5
49
0.531165
feudalnate
f01827da3aaf42c2b8e6c91563718b54dacc7769
73
cpp
C++
src/logging/log.cpp
stridera/FieryV4
747c80fee1dc71e2e06f57fc3f058f3540aaf880
[ "Unlicense" ]
1
2020-07-17T14:03:34.000Z
2020-07-17T14:03:34.000Z
src/logging/log.cpp
stridera/FieryV4
747c80fee1dc71e2e06f57fc3f058f3540aaf880
[ "Unlicense" ]
null
null
null
src/logging/log.cpp
stridera/FieryV4
747c80fee1dc71e2e06f57fc3f058f3540aaf880
[ "Unlicense" ]
null
null
null
#include "log.hpp" std::shared_ptr<spdlog::logger> Mud::Logger::logger_;
24.333333
53
0.739726
stridera
f01b3c73bf5c9a48a978288b48022b83aa893a29
34,690
hxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterial_EquivGlazingMaterial_Blind.hxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterial_EquivGlazingMaterial_Blind.hxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterial_EquivGlazingMaterial_Blind.hxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // #ifndef SIM_MATERIAL_EQUIV_GLAZING_MATERIAL_BLIND_HXX #define SIM_MATERIAL_EQUIV_GLAZING_MATERIAL_BLIND_HXX #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace schema { namespace simxml { namespace ResourcesGeneral { class SimMaterial_EquivGlazingMaterial_Blind; } } } #include <memory> // ::std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include "simmaterial_equivglazingmaterial.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { class SimMaterial_EquivGlazingMaterial_Blind: public ::schema::simxml::ResourcesGeneral::SimMaterial_EquivGlazingMaterial { public: // SimMaterial_SlatWidth // typedef ::xml_schema::double_ SimMaterial_SlatWidth_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatWidth_type > SimMaterial_SlatWidth_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatWidth_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatWidth_traits; const SimMaterial_SlatWidth_optional& SimMaterial_SlatWidth () const; SimMaterial_SlatWidth_optional& SimMaterial_SlatWidth (); void SimMaterial_SlatWidth (const SimMaterial_SlatWidth_type& x); void SimMaterial_SlatWidth (const SimMaterial_SlatWidth_optional& x); // SimMaterial_SlatAngle // typedef ::xml_schema::double_ SimMaterial_SlatAngle_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatAngle_type > SimMaterial_SlatAngle_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatAngle_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatAngle_traits; const SimMaterial_SlatAngle_optional& SimMaterial_SlatAngle () const; SimMaterial_SlatAngle_optional& SimMaterial_SlatAngle (); void SimMaterial_SlatAngle (const SimMaterial_SlatAngle_type& x); void SimMaterial_SlatAngle (const SimMaterial_SlatAngle_optional& x); // SimMaterial_SlatOrientation // typedef ::xml_schema::string SimMaterial_SlatOrientation_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatOrientation_type > SimMaterial_SlatOrientation_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatOrientation_type, char > SimMaterial_SlatOrientation_traits; const SimMaterial_SlatOrientation_optional& SimMaterial_SlatOrientation () const; SimMaterial_SlatOrientation_optional& SimMaterial_SlatOrientation (); void SimMaterial_SlatOrientation (const SimMaterial_SlatOrientation_type& x); void SimMaterial_SlatOrientation (const SimMaterial_SlatOrientation_optional& x); void SimMaterial_SlatOrientation (::std::auto_ptr< SimMaterial_SlatOrientation_type > p); // SimMaterial_SlatSeparation // typedef ::xml_schema::double_ SimMaterial_SlatSeparation_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatSeparation_type > SimMaterial_SlatSeparation_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatSeparation_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatSeparation_traits; const SimMaterial_SlatSeparation_optional& SimMaterial_SlatSeparation () const; SimMaterial_SlatSeparation_optional& SimMaterial_SlatSeparation (); void SimMaterial_SlatSeparation (const SimMaterial_SlatSeparation_type& x); void SimMaterial_SlatSeparation (const SimMaterial_SlatSeparation_optional& x); // SimMaterial_SlatCrown // typedef ::xml_schema::double_ SimMaterial_SlatCrown_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatCrown_type > SimMaterial_SlatCrown_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatCrown_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatCrown_traits; const SimMaterial_SlatCrown_optional& SimMaterial_SlatCrown () const; SimMaterial_SlatCrown_optional& SimMaterial_SlatCrown (); void SimMaterial_SlatCrown (const SimMaterial_SlatCrown_type& x); void SimMaterial_SlatCrown (const SimMaterial_SlatCrown_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type > SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_traits; const SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans () const; SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans (); void SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans (const SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans (const SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseSolarTrans // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type > SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_traits; const SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarTrans () const; SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarTrans (); void SimMaterial_BackSideSlatBeam_DiffuseSolarTrans (const SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_type& x); void SimMaterial_BackSideSlatBeam_DiffuseSolarTrans (const SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type > SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_traits; const SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect () const; SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect (); void SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect (const SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect (const SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type > SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_traits; const SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarReflect () const; SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseSolarReflect (); void SimMaterial_BackSideSlatBeam_DiffuseSolarReflect (const SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_type& x); void SimMaterial_BackSideSlatBeam_DiffuseSolarReflect (const SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type > SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_traits; const SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans () const; SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans (); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type > SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_traits; const SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans () const; SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans (); void SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_type& x); void SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans (const SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional& x); // SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type > SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_traits; const SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect () const; SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect (); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_type& x); void SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional& x); // SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type > SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_traits; const SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect () const; SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect (); void SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_type& x); void SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect (const SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional& x); // SimMaterial_SlatDiffuse_DiffuseSolarTrans // typedef ::xml_schema::double_ SimMaterial_SlatDiffuse_DiffuseSolarTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatDiffuse_DiffuseSolarTrans_type > SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatDiffuse_DiffuseSolarTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatDiffuse_DiffuseSolarTrans_traits; const SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional& SimMaterial_SlatDiffuse_DiffuseSolarTrans () const; SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional& SimMaterial_SlatDiffuse_DiffuseSolarTrans (); void SimMaterial_SlatDiffuse_DiffuseSolarTrans (const SimMaterial_SlatDiffuse_DiffuseSolarTrans_type& x); void SimMaterial_SlatDiffuse_DiffuseSolarTrans (const SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional& x); // SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type > SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_traits; const SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect () const; SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect (); void SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_type& x); void SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional& x); // SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type > SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_traits; const SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect () const; SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect (); void SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_type& x); void SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional& x); // SimMaterial_SlatDiffuse_DiffuseVisibleTrans // typedef ::xml_schema::double_ SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type > SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatDiffuse_DiffuseVisibleTrans_traits; const SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional& SimMaterial_SlatDiffuse_DiffuseVisibleTrans () const; SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional& SimMaterial_SlatDiffuse_DiffuseVisibleTrans (); void SimMaterial_SlatDiffuse_DiffuseVisibleTrans (const SimMaterial_SlatDiffuse_DiffuseVisibleTrans_type& x); void SimMaterial_SlatDiffuse_DiffuseVisibleTrans (const SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional& x); // SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type > SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_traits; const SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect () const; SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect (); void SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_type& x); void SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional& x); // SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect // typedef ::xml_schema::double_ SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type > SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_traits; const SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect () const; SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional& SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect (); void SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_type& x); void SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect (const SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional& x); // SimMaterial_SlatInfraredTrans // typedef ::xml_schema::double_ SimMaterial_SlatInfraredTrans_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatInfraredTrans_type > SimMaterial_SlatInfraredTrans_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatInfraredTrans_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_SlatInfraredTrans_traits; const SimMaterial_SlatInfraredTrans_optional& SimMaterial_SlatInfraredTrans () const; SimMaterial_SlatInfraredTrans_optional& SimMaterial_SlatInfraredTrans (); void SimMaterial_SlatInfraredTrans (const SimMaterial_SlatInfraredTrans_type& x); void SimMaterial_SlatInfraredTrans (const SimMaterial_SlatInfraredTrans_optional& x); // SimMaterial_FrontSideSlatInfraredEmissivity // typedef ::xml_schema::double_ SimMaterial_FrontSideSlatInfraredEmissivity_type; typedef ::xsd::cxx::tree::optional< SimMaterial_FrontSideSlatInfraredEmissivity_type > SimMaterial_FrontSideSlatInfraredEmissivity_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_FrontSideSlatInfraredEmissivity_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_FrontSideSlatInfraredEmissivity_traits; const SimMaterial_FrontSideSlatInfraredEmissivity_optional& SimMaterial_FrontSideSlatInfraredEmissivity () const; SimMaterial_FrontSideSlatInfraredEmissivity_optional& SimMaterial_FrontSideSlatInfraredEmissivity (); void SimMaterial_FrontSideSlatInfraredEmissivity (const SimMaterial_FrontSideSlatInfraredEmissivity_type& x); void SimMaterial_FrontSideSlatInfraredEmissivity (const SimMaterial_FrontSideSlatInfraredEmissivity_optional& x); // SimMaterial_BackSideSlatInfraredEmissivity // typedef ::xml_schema::double_ SimMaterial_BackSideSlatInfraredEmissivity_type; typedef ::xsd::cxx::tree::optional< SimMaterial_BackSideSlatInfraredEmissivity_type > SimMaterial_BackSideSlatInfraredEmissivity_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_BackSideSlatInfraredEmissivity_type, char, ::xsd::cxx::tree::schema_type::double_ > SimMaterial_BackSideSlatInfraredEmissivity_traits; const SimMaterial_BackSideSlatInfraredEmissivity_optional& SimMaterial_BackSideSlatInfraredEmissivity () const; SimMaterial_BackSideSlatInfraredEmissivity_optional& SimMaterial_BackSideSlatInfraredEmissivity (); void SimMaterial_BackSideSlatInfraredEmissivity (const SimMaterial_BackSideSlatInfraredEmissivity_type& x); void SimMaterial_BackSideSlatInfraredEmissivity (const SimMaterial_BackSideSlatInfraredEmissivity_optional& x); // SimMaterial_SlatAngleCntrl // typedef ::xml_schema::string SimMaterial_SlatAngleCntrl_type; typedef ::xsd::cxx::tree::optional< SimMaterial_SlatAngleCntrl_type > SimMaterial_SlatAngleCntrl_optional; typedef ::xsd::cxx::tree::traits< SimMaterial_SlatAngleCntrl_type, char > SimMaterial_SlatAngleCntrl_traits; const SimMaterial_SlatAngleCntrl_optional& SimMaterial_SlatAngleCntrl () const; SimMaterial_SlatAngleCntrl_optional& SimMaterial_SlatAngleCntrl (); void SimMaterial_SlatAngleCntrl (const SimMaterial_SlatAngleCntrl_type& x); void SimMaterial_SlatAngleCntrl (const SimMaterial_SlatAngleCntrl_optional& x); void SimMaterial_SlatAngleCntrl (::std::auto_ptr< SimMaterial_SlatAngleCntrl_type > p); // Constructors. // SimMaterial_EquivGlazingMaterial_Blind (); SimMaterial_EquivGlazingMaterial_Blind (const RefId_type&); SimMaterial_EquivGlazingMaterial_Blind (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); SimMaterial_EquivGlazingMaterial_Blind (const SimMaterial_EquivGlazingMaterial_Blind& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual SimMaterial_EquivGlazingMaterial_Blind* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; SimMaterial_EquivGlazingMaterial_Blind& operator= (const SimMaterial_EquivGlazingMaterial_Blind& x); virtual ~SimMaterial_EquivGlazingMaterial_Blind (); // Implementation. // protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: SimMaterial_SlatWidth_optional SimMaterial_SlatWidth_; SimMaterial_SlatAngle_optional SimMaterial_SlatAngle_; SimMaterial_SlatOrientation_optional SimMaterial_SlatOrientation_; SimMaterial_SlatSeparation_optional SimMaterial_SlatSeparation_; SimMaterial_SlatCrown_optional SimMaterial_SlatCrown_; SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_optional SimMaterial_FrontSideSlatBeam_DiffuseSolarTrans_; SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_optional SimMaterial_BackSideSlatBeam_DiffuseSolarTrans_; SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_optional SimMaterial_FrontSideSlatBeam_DiffuseSolarReflect_; SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_optional SimMaterial_BackSideSlatBeam_DiffuseSolarReflect_; SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_optional SimMaterial_FrontSideSlatBeam_DiffuseVisibleTrans_; SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_optional SimMaterial_BackSideSlatBeam_DiffuseVisibleTrans_; SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_optional SimMaterial_FrontSideSlatBeam_DiffuseVisibleReflect_; SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_optional SimMaterial_BackSideSlatBeam_DiffuseVisibleReflect_; SimMaterial_SlatDiffuse_DiffuseSolarTrans_optional SimMaterial_SlatDiffuse_DiffuseSolarTrans_; SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_optional SimMaterial_FrontSideSlatDiffuse_DiffuseSolarReflect_; SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_optional SimMaterial_BackSideSlatDiffuse_DiffuseSolarReflect_; SimMaterial_SlatDiffuse_DiffuseVisibleTrans_optional SimMaterial_SlatDiffuse_DiffuseVisibleTrans_; SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_optional SimMaterial_FrontSideSlatDiffuse_DiffuseVisibleReflect_; SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_optional SimMaterial_BackSideSlatDiffuse_DiffuseVisibleReflect_; SimMaterial_SlatInfraredTrans_optional SimMaterial_SlatInfraredTrans_; SimMaterial_FrontSideSlatInfraredEmissivity_optional SimMaterial_FrontSideSlatInfraredEmissivity_; SimMaterial_BackSideSlatInfraredEmissivity_optional SimMaterial_BackSideSlatInfraredEmissivity_; SimMaterial_SlatAngleCntrl_optional SimMaterial_SlatAngleCntrl_; }; } } } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // SIM_MATERIAL_EQUIV_GLAZING_MATERIAL_BLIND_HXX
45.228162
212
0.769155
EnEff-BIM
f01d7722a7494aa12536d92b9f4445bdc7bd5b43
1,875
inl
C++
samples/extensions/open_cl_interop/open_cl_functions.inl
samhsw/Vulkan-Samples
53b75db552330772c3c08734adf1ca983bedbf88
[ "Apache-2.0" ]
20
2020-03-25T17:57:32.000Z
2022-03-12T08:16:10.000Z
samples/extensions/open_cl_interop/open_cl_functions.inl
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-02-18T07:08:52.000Z
2020-02-18T07:08:52.000Z
samples/extensions/open_cl_interop/open_cl_functions.inl
JasonWinston/Vulkan-Samples
fe3fd6435e5f209b00d72a85004f189d01debee4
[ "Apache-2.0" ]
1
2020-04-12T16:23:18.000Z
2020-04-12T16:23:18.000Z
/* Copyright (c) 2021, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * * 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. */ // Core OpenCL functions, loaded from libOpenCL.so #if !defined(OPENCL_EXPORTED_FUNCTION) #define OPENCL_EXPORTED_FUNCTION(fun) #endif OPENCL_EXPORTED_FUNCTION(clCreateContext); OPENCL_EXPORTED_FUNCTION(clGetDeviceIDs); OPENCL_EXPORTED_FUNCTION(clGetPlatformIDs); OPENCL_EXPORTED_FUNCTION(clCreateBuffer); OPENCL_EXPORTED_FUNCTION(clReleaseMemObject); OPENCL_EXPORTED_FUNCTION(clCreateProgramWithSource); OPENCL_EXPORTED_FUNCTION(clBuildProgram); OPENCL_EXPORTED_FUNCTION(clCreateKernel); OPENCL_EXPORTED_FUNCTION(clSetKernelArg); OPENCL_EXPORTED_FUNCTION(clEnqueueNDRangeKernel); OPENCL_EXPORTED_FUNCTION(clFlush); OPENCL_EXPORTED_FUNCTION(clFinish); OPENCL_EXPORTED_FUNCTION(clCreateCommandQueue); OPENCL_EXPORTED_FUNCTION(clReleaseContext); OPENCL_EXPORTED_FUNCTION(clGetPlatformInfo); OPENCL_EXPORTED_FUNCTION(clGetExtensionFunctionAddressForPlatform); #undef OPENCL_EXPORTED_FUNCTION // Extension functions, loaded using clGetExtensionFunctionAddressForPlatform #if !defined(OPENCL_EXPORTED_EXTENSION_FUNCTION) #define OPENCL_EXPORTED_EXTENSION_FUNCTION(fun) #endif OPENCL_EXPORTED_EXTENSION_FUNCTION(clImportMemoryARM); #undef OPENCL_EXPORTED_EXTENSION_FUNCTION
38.265306
78
0.817067
samhsw
f026eb7a1d592f75bed531fdd748786e38ecc01e
2,990
cpp
C++
cbits/nqs.cpp
BagrovAndrey/nqs-playground
e2834e8d340c06468687944516a2858bb754cbfe
[ "BSD-3-Clause" ]
null
null
null
cbits/nqs.cpp
BagrovAndrey/nqs-playground
e2834e8d340c06468687944516a2858bb754cbfe
[ "BSD-3-Clause" ]
null
null
null
cbits/nqs.cpp
BagrovAndrey/nqs-playground
e2834e8d340c06468687944516a2858bb754cbfe
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Tom Westerhout // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "nqs.hpp" #include <pybind11/pybind11.h> #include <torch/extension.h> namespace py = pybind11; namespace { auto bind_polynomial_state(py::module m) -> void { using namespace tcm; py::class_<PolynomialStateV2>(m, "PolynomialState") .def(py::init([](std::shared_ptr<Polynomial> polynomial, std::string const& state, std::pair<size_t, size_t> input_shape) { return std::make_unique<PolynomialStateV2>( std::move(polynomial), load_forward_fn(state), input_shape); })) .def("__call__", [](PolynomialStateV2& self, py::array_t<SpinVector, py::array::c_style> spins) { return self({spins.data(0), static_cast<size_t>(spins.shape(0))}); }); } } // namespace #if defined(TCM_CLANG) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wmissing-prototypes" #endif PYBIND11_MODULE(_C_nqs, m) { #if defined(TCM_CLANG) # pragma clang diagnostic pop #endif m.doc() = R"EOF()EOF"; using namespace tcm; bind_spin(m.ptr()); bind_heisenberg(m); bind_explicit_state(m); bind_polynomial(m); // bind_options(m); // bind_chain_result(m); // bind_sampling(m); // bind_networks(m); // bind_dataloader(m); bind_monte_carlo(m.ptr()); bind_polynomial_state(m); }
37.375
81
0.692308
BagrovAndrey
f035ab93bef94a250ff2ca333fdd69a5f83a7943
6,444
cpp
C++
src/sim/entities/sim_Explosion.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
4
2021-01-28T17:39:38.000Z
2022-02-11T20:13:46.000Z
src/sim/entities/sim_Explosion.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
null
null
null
src/sim/entities/sim_Explosion.cpp
marek-cel/fightersfs
5511162726861fee17357f39274461250370c224
[ "MIT" ]
3
2021-02-22T21:22:30.000Z
2022-01-10T19:32:12.000Z
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * 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 <sim/entities/sim_Explosion.h> #include <osgParticle/ModularEmitter> #include <osgParticle/ParticleSystemUpdater> #include <osgParticle/RandomRateCounter> #include <osgParticle/RadialShooter> //////////////////////////////////////////////////////////////////////////////// using namespace sim; //////////////////////////////////////////////////////////////////////////////// Explosion::Explosion( float scale, Group *parent ) : Entity( parent, Active, 10.5f ) { createExplosionFire( scale ); createExplosionSmoke( scale ); } //////////////////////////////////////////////////////////////////////////////// Explosion::~Explosion() {} //////////////////////////////////////////////////////////////////////////////// void Explosion::createExplosionFire( float scale ) { osg::ref_ptr<osg::Group> group = new osg::Group(); _switch->addChild( group.get() ); osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform(); group->addChild( pat.get() ); pat->setAttitude( osg::Quat( 0.0, osg::Z_AXIS, -osg::PI_2, osg::Y_AXIS, -osg::PI_2, osg::X_AXIS ) ); osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem(); ps->getDefaultParticleTemplate().setLifeTime( 0.5f ); ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD ); ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(1.0f*scale, 2.0f*scale) ); ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) ); ps->getDefaultParticleTemplate().setColorRange( osgParticle::rangev4(osg::Vec4(1.0f,1.0f,0.5f,1.0f), osg::Vec4(1.0f,0.5f,0.0f,1.0f)) ); ps->setDefaultAttributes( getPath( "textures/explosion_fire.rgb" ), true, false ); osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter(); rrc->setRateRange( 10, 20 ); osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter(); shooter->setThetaRange( -osg::PI, osg::PI ); shooter->setPhiRange( -osg::PI, osg::PI ); shooter->setInitialSpeedRange( -10.0f, 10.0f ); osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter(); emitter->setParticleSystem( ps.get() ); emitter->setCounter( rrc.get() ); emitter->setShooter( shooter.get() ); emitter->setEndless( false ); emitter->setLifeTime( 0.25f ); pat->addChild( emitter.get() ); osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater(); updater->addParticleSystem( ps.get() ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode->addDrawable( ps.get() ); group->addChild( updater.get() ); group->addChild( geode.get() ); } //////////////////////////////////////////////////////////////////////////////// void Explosion::createExplosionSmoke( float scale ) { osg::ref_ptr<osg::Group> group = new osg::Group(); _switch->addChild( group.get() ); osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform(); group->addChild( pat.get() ); pat->setAttitude( osg::Quat( 0.0, osg::Z_AXIS, -osg::PI_2, osg::Y_AXIS, -osg::PI_2, osg::X_AXIS ) ); osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem(); ps->getDefaultParticleTemplate().setLifeTime( 10.0f ); ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD ); ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(1.0f*scale, 8.0f*scale) ); ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) ); ps->getDefaultParticleTemplate().setColorRange( osgParticle::rangev4(osg::Vec4(0.0f,0.0f,0.0f,1.0f), osg::Vec4(0.5f,0.5f,0.5f,1.0f)) ); ps->setDefaultAttributes( getPath( "textures/explosion_smoke.rgb" ), false, false ); osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter(); rrc->setRateRange( 10, 10 ); osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter(); shooter->setThetaRange( -osg::PI, osg::PI ); shooter->setPhiRange( -osg::PI, osg::PI ); shooter->setInitialSpeedRange( -2.0f, 2.0f ); osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter(); emitter->setStartTime( 0.1f ); emitter->setParticleSystem( ps.get() ); emitter->setCounter( rrc.get() ); emitter->setShooter( shooter.get() ); emitter->setEndless( false ); emitter->setLifeTime( 0.5f ); pat->addChild( emitter.get() ); osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater(); updater->addParticleSystem( ps.get() ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode->addDrawable( ps.get() ); group->addChild( updater.get() ); group->addChild( geode.get() ); }
43.836735
105
0.617008
marek-cel
f039bed9ffb5dc464e1986b13a2bfe6e726662a1
2,678
cc
C++
google/cloud/spanner/internal/time_format_benchmark.cc
devjgm/google-cloud-cpp-spanner
e9f73518069f69f79ab8e74e69ea68babcc20a58
[ "Apache-2.0" ]
29
2019-05-03T15:03:48.000Z
2021-06-04T06:15:55.000Z
google/cloud/spanner/internal/time_format_benchmark.cc
devjgm/google-cloud-cpp-spanner
e9f73518069f69f79ab8e74e69ea68babcc20a58
[ "Apache-2.0" ]
1,199
2019-05-03T13:05:54.000Z
2020-06-01T18:58:26.000Z
google/cloud/spanner/internal/time_format_benchmark.cc
devjgm/google-cloud-cpp-spanner
e9f73518069f69f79ab8e74e69ea68babcc20a58
[ "Apache-2.0" ]
18
2019-05-02T20:53:06.000Z
2021-10-07T21:29:36.000Z
// Copyright 2020 Google LLC // // 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 "google/cloud/spanner/internal/time_format.h" #include <benchmark/benchmark.h> #include <string> namespace google { namespace cloud { namespace spanner { inline namespace SPANNER_CLIENT_NS { namespace internal { namespace { // Run on (6 X 2300 MHz CPU s) // CPU Caches: // L1 Data 32K (x3) // L1 Instruction 32K (x3) // L2 Unified 256K (x3) // L3 Unified 46080K (x1) // Load Average: 0.22, 0.26, 0.77 // --------------------------------------------------------------- // Benchmark Time CPU Iterations // --------------------------------------------------------------- // BM_FormatTime 55.2 ns 54.7 ns 12779010 // BM_FormatTimeWithFmt 1047 ns 1042 ns 668990 // BM_ParseTime 129 ns 128 ns 5474604 // BM_ParseTimeWithFmt 1323 ns 1314 ns 489764 void BM_FormatTime(benchmark::State& state) { std::tm tm; tm.tm_year = 2020 - 1900; tm.tm_mon = 1 - 1; tm.tm_mday = 17; tm.tm_hour = 18; tm.tm_min = 54; tm.tm_sec = 12; for (auto _ : state) { benchmark::DoNotOptimize(FormatTime(tm)); } } BENCHMARK(BM_FormatTime); void BM_FormatTimeWithFmt(benchmark::State& state) { std::tm tm; tm.tm_year = 2020 - 1900; tm.tm_mon = 1 - 1; tm.tm_mday = 17; tm.tm_hour = 18; tm.tm_min = 54; tm.tm_sec = 12; for (auto _ : state) { benchmark::DoNotOptimize(FormatTime("%Y-%m-%dT%H:%M:%S", tm)); } } BENCHMARK(BM_FormatTimeWithFmt); void BM_ParseTime(benchmark::State& state) { std::tm tm; std::string s = "2020-01-17T18:54:12"; for (auto _ : state) { benchmark::DoNotOptimize(ParseTime(s, &tm)); } } BENCHMARK(BM_ParseTime); void BM_ParseTimeWithFmt(benchmark::State& state) { std::tm tm; std::string s = "2020-01-17T18:54:12"; for (auto _ : state) { benchmark::DoNotOptimize(ParseTime("%Y-%m-%dT%H:%M:%S", s, &tm)); } } BENCHMARK(BM_ParseTimeWithFmt); } // namespace } // namespace internal } // namespace SPANNER_CLIENT_NS } // namespace spanner } // namespace cloud } // namespace google
28.795699
75
0.621733
devjgm
f0477bf7e895edc949eceae7f9ced2770cf779fe
664
hpp
C++
library/ATF/std___String_baseInfo.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/std___String_baseInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/std___String_baseInfo.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <std___String_base.hpp> START_ATF_NAMESPACE namespace std { namespace Info { using std___String_basector__String_base1_ptr = int64_t (WINAPIV*)(struct std::_String_base*, struct std::_String_base*); using std___String_basector__String_base1_clbk = int64_t (WINAPIV*)(struct std::_String_base*, struct std::_String_base*, std___String_basector__String_base1_ptr); }; // end namespace Info }; // end namespace std END_ATF_NAMESPACE
34.947368
175
0.713855
lemkova
f053c47d0bc953e643b5c0aafc06430eca429c6e
3,922
cc
C++
src/ir/ir_printer_test.cc
Cypher1/raksha
0f52f108ceb8bc7b8be36a7bf8e9662188c57551
[ "Apache-2.0" ]
null
null
null
src/ir/ir_printer_test.cc
Cypher1/raksha
0f52f108ceb8bc7b8be36a7bf8e9662188c57551
[ "Apache-2.0" ]
null
null
null
src/ir/ir_printer_test.cc
Cypher1/raksha
0f52f108ceb8bc7b8be36a7bf8e9662188c57551
[ "Apache-2.0" ]
null
null
null
//----------------------------------------------------------------------------- // Copyright 2022 Google LLC // // 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 // // https://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 "src/ir/ir_printer.h" #include "absl/container/flat_hash_set.h" #include "src/common/testing/gtest.h" #include "src/ir/attribute.h" #include "src/ir/block_builder.h" #include "src/ir/module.h" #include "src/ir/value.h" namespace raksha::ir { namespace { enum class ToStringVariant { // Call IRPrinter::ToString(const Entity&) kToString, // Call IRPrinter::ToString(std::ostream&, const Entity&) kToStringOstream, // Call `out << entity` kOperator, }; class IRPrinterTest : public testing::TestWithParam<ToStringVariant> { public: IRPrinterTest() : plus_op_("core.plus"), minus_op_("core.minus") { BlockBuilder builder; operation_ = std::addressof(builder.AddOperation(plus_op_, {}, {})); block_ = std::addressof(global_module_.AddBlock(builder.build())); global_module_.AddBlock(std::make_unique<Block>()); } const Operator& plus_op() const { return plus_op_; } const Operator& minus_op() const { return minus_op_; } const Block& block() const { return *block_; } const Module& global_module() const { return global_module_; } template <typename T> std::string ToString(const T& entity) { switch (GetParam()) { case ToStringVariant::kToString: return IRPrinter::ToString(entity); case ToStringVariant::kToStringOstream: { std::ostringstream out; IRPrinter::ToString(out, entity); return out.str(); } case ToStringVariant::kOperator: { std::ostringstream out; out << entity; return out.str(); } } // Placate compiler by marking path as unreachable. CHECK(false) << "Unreachable!"; } private: Operator plus_op_; Operator minus_op_; Module global_module_; const Operation* operation_; const Block* block_; }; INSTANTIATE_TEST_SUITE_P(IRPrinterTest, IRPrinterTest, testing::Values(ToStringVariant::kToString, ToStringVariant::kToStringOstream, ToStringVariant::kOperator)); TEST_P(IRPrinterTest, PrettyPrintsModuleWithProperIndentation) { EXPECT_EQ(ToString(global_module()), R"(module m0 { block b0 { %0 = core.plus []() } // block b0 block b1 { } // block b1 } // module m0 )"); } TEST_P(IRPrinterTest, PrettyPrintsBlockWithProperIndentation) { EXPECT_EQ(ToString(block()), R"(block b0 { %0 = core.plus []() } // block b0 )"); } TEST_P(IRPrinterTest, PrettyPrintsOperationWithProperIndentation) { Operation operation(nullptr, plus_op(), {}, {}, std::make_unique<Module>()); EXPECT_EQ(ToString(operation), R"(%0 = core.plus []() { module m0 { } // module m0 } )"); } TEST_P(IRPrinterTest, PrettyPrintAttributesAndArgsInSortedOrder) { Operation operation( nullptr, minus_op(), {{"access", StringAttribute::Create("private")}, {"name", StringAttribute::Create("addition")}}, {{"const", Value(value::Any())}, {"arg", Value(value::Any())}}); EXPECT_EQ(ToString(operation), "%0 = core.minus [access: private, name: addition](arg: <<ANY>>, " "const: <<ANY>>)\n"); } } // namespace } // namespace raksha::ir
31.126984
79
0.63794
Cypher1
f053f6e90c761647c48770c12ec88db3da347152
2,526
cpp
C++
old_src/example_server/imageplot.cpp
InsightCenterNoodles/NoodlesPlusPlus
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
[ "MIT" ]
null
null
null
old_src/example_server/imageplot.cpp
InsightCenterNoodles/NoodlesPlusPlus
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
[ "MIT" ]
null
null
null
old_src/example_server/imageplot.cpp
InsightCenterNoodles/NoodlesPlusPlus
3396e530a5948416fd364cc9ffa3f5bcbb8abc3b
[ "MIT" ]
null
null
null
#include "imageplot.h" #include "plotty.h" void ImagePlot::rebuild(Domain const& d) { auto center = (m_top_left + m_bottom_right) / 2.0f; auto o = -(m_bottom_left - center); if (!m_image_texture) { m_image_texture = noo::create_texture_from_file(m_doc, m_image_data); } if (!m_image_mat) { noo::MaterialData mat; mat.color = { 1, 1, 1, 1 }; mat.metallic = 0; mat.roughness = 1; mat.texture = m_image_texture; m_image_mat = noo::create_material(m_doc, mat); } noo::MeshTPtr mesh; { // create a plane std::array<glm::vec3, 4> positions = { m_top_left, m_bottom_left, m_bottom_right, o }; for (auto& p : positions) { p = d.transform(p); } std::array<glm::vec3, 4> normals; for (auto& n : normals) { n = glm::cross(m_top_left - m_bottom_left, m_bottom_right - m_bottom_left); n = glm::normalize(n); } std::array<glm::u16vec3, 2> index = { glm::u16vec3 { 0, 1, 2 }, glm::u16vec3 { 3, 1, 2 }, }; noo::BufferMeshDataRef ref; ref.positions = positions; ref.normals = normals; ref.triangles = index; std::vector<std::byte> mesh_data; auto result = noo::pack_mesh_to_vector(ref, mesh_data); noo::BufferCopySource buffer_data; buffer_data.to_copy = mesh_data; auto buffer_ptr = noo::create_buffer(m_doc, buffer_data); noo::MeshData noo_mesh_data(result, buffer_ptr); mesh = create_mesh(m_doc, noo_mesh_data); } noo::ObjectData object_data; object_data.material = m_image_mat; object_data.transform = glm::mat4(1); object_data.mesh = mesh; m_obj = create_object(m_doc, object_data); } ImagePlot::ImagePlot(Plotty& host, int64_t id, std::vector<std::byte> image_data, glm::vec3 top_left, glm::vec3 bottom_left, glm::vec3 bottom_right) : Plot(host, id), m_image_data(std::move(image_data)), m_top_left(top_left), m_bottom_left(bottom_left), m_bottom_right(bottom_right) { rebuild(host.domain()->current_domain()); } ImagePlot::~ImagePlot() { } void ImagePlot::domain_updated(Domain const& d) { rebuild(d); }
25.515152
77
0.548694
InsightCenterNoodles
f05c7289ea1481eaad964d4db7cdafb1cd8c0b55
3,878
cpp
C++
NOV18B/PRITREE.cpp
Chhekur/codechef-solutions
14ca902ea693139de13ffe5b9f602447bf34b79f
[ "MIT" ]
1
2019-03-25T14:14:47.000Z
2019-03-25T14:14:47.000Z
NOV18B/PRITREE.cpp
Chhekur/codechef-solutions
14ca902ea693139de13ffe5b9f602447bf34b79f
[ "MIT" ]
null
null
null
NOV18B/PRITREE.cpp
Chhekur/codechef-solutions
14ca902ea693139de13ffe5b9f602447bf34b79f
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> #include<utility> #include<cstdlib> #include<set> #include<stack> using namespace std; vector<pair<int, int> > edges; vector<pair<int, int> > graph; vector<vector<int> > temp_graph; int a[1001]; bool isPrime(int num){ int f = 0; for(int i = 2; i * i <= num; i++){ if(num % i == 0) f = 1; } if(!f)return true; else return false; } // void genTree(int n){ // edges.clear(); // graph.clear(); // set< pair<int,int> >::iterator it; // while(edges.size() < n - 1){ // int x = ( rand() % ( n ) ); // int y = ( rand() % ( n ) ); // // cout<<x<<" "<<y<<"\n"; // // break; // int f = 0; // for(it=edges.begin(); it!=edges.end(); ++it){ // if(it->first == y && it->second == x)f = 1; // } // if(x == y) f = 1; // if(!f) edges.insert(make_pair(x , y)); // // i++; // } // for(it=edges.begin(); it!=edges.end(); ++it){ // graph.push_back(make_pair(it->first + 1, it->second + 1)); // // cout<<it->first<<" "<<it->second<<"\n"; // } // } void print_edges(){ for(int i = 0; i < edges.size(); i++){ cout<<edges[i].first + 1<<" "<<edges[i].second + 1<<"\n"; } } int main(void){ int n;cin>>n; vector<int> prime_index; vector<int> numbers; int index = -1; for(int i = 0; i < n; i++){ cin>>a[i]; // if(a[i] == 2) index = i + 1; // int f = 0; // for(int j = 2; j * j <= a[i]; j++){ // if(a[i] % j == 0) f = 1; // } // if(!f)prime_index.push_back(i + 1); // else numbers.push_back(i + 1); } // if(n == 2) cout<<"1 2\n"; // else{ for(int i = 0; i < n; i++){ if(a[i] != 0){ for(int j = i + 1; j < n; j++){ if(a[j] != 0){ if(isPrime(a[i] + a[j])){ edges.push_back(make_pair(i,j)); a[i] = 0; a[j] = 0; break; } } } } } // print_edges(); if(edges.size() == 0){ int f = 0, ind; for(int i = 0; i < n; i++){ if(isPrime(a[i])) { f = 1; ind = i; break; } } if(f){ for(int i = 0; i < n; i++){ if(ind + 1 == i + 1) continue; cout<<ind + 1<<" "<<i + 1<<"\n"; } }else{ for(int i = 0; i < n - 1; i++){ edges.push_back(make_pair(i,i + 1)); } print_edges(); } } else{ vector <int> temp; for(int i = 0; i < n; i++){ if(a[i] == 0) continue; // cout<<a[i]<<" "<<i<<"\n"; temp.push_back(i); } int size = edges.size(); if(temp.size() > 0){ for(int j = 0; j < size; j++){ if(j % 2 == 0) // cout<<temp[j]<<" "; edges.push_back(make_pair(temp[temp.size()/2],edges[j].first)); else edges.push_back(make_pair(temp[temp.size() / 2],edges[j].second)); } for(int j = 0; j < temp.size() - 1; j++){ edges.push_back(make_pair(temp[j],temp[j + 1])); } } else{ int size = edges.size(); for(int i = 0; i < size - 1; i++){ edges.push_back(make_pair(edges[i].first, edges[i + 1].second)); } } print_edges(); } // } // int z = 10; // int tree_count = 0; // vector<pair<int, int> > ans; // while(z--){ // genTree(n); // int count = 0; // for(int i = 0; i < graph.size(); i++){ // // cout<<graph[i].first<<" "<<graph[i].second<<"\n"; // set<int> temp; // temp.insert(graph[i].second); // for(int j = 0; j < graph.size(); j++){ // if(i == j)continue; // temp.insert(graph[j].first); // temp.insert(graph[j].second); // } // set<int>::iterator it; // long val = 0; // for(it = temp.begin(); it != temp.end(); it++){ // // cout<<*it<<" "; // val += *it; // } // // cout<<"\n"; // if(isPrime(graph[i].first))count++; // if(isPrime(val))count++; // } // if(count > tree_count){ // // cout<<count<<" "<<tree_count<<"\n"; // tree_count = count; // ans = graph; // } // } // for(int i = 0; i < ans.size(); i++){ // cout<<ans[i].first<<" "<<ans[i].second<<"\n"; // } }
22.287356
72
0.465446
Chhekur
f05d7aafd52938ad7b393f36679dfc15e8292de4
22,731
cpp
C++
unittests/utils/FileCheckTest.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
unittests/utils/FileCheckTest.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
unittests/utils/FileCheckTest.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
//===- llvm/unittest/Support/FileCheckTest.cpp - FileCheck tests --===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "FileChecker.h" #include "gtest/gtest.h" #include <unordered_set> using namespace polar::basic; using namespace polar::filechecker; using namespace polar::utils; namespace { class FileCheckTest : public ::testing::Test {}; TEST_F(FileCheckTest, testLiteral) { // Eval returns the literal's value. FileCheckExpressionLiteral ten(10); Expected<uint64_t> value = ten.eval(); EXPECT_TRUE(bool(value)); EXPECT_EQ(10U, *value); // max value can be correctly represented. FileCheckExpressionLiteral max(std::numeric_limits<uint64_t>::max()); value = max.eval(); EXPECT_TRUE(bool(value)); EXPECT_EQ(std::numeric_limits<uint64_t>::max(), *value); } static std::string toString(const std::unordered_set<std::string> &Set) { bool First = true; std::string Str; for (StringRef S : Set) { Str += Twine(First ? "{" + S : ", " + S).getStr(); First = false; } Str += '}'; return Str; } static void expectUndefErrors(std::unordered_set<std::string> ExpectedUndefVarNames, Error Err) { handle_all_errors(std::move(Err), [&](const FileCheckUndefVarError &E) { ExpectedUndefVarNames.erase(E.getVarName()); }); EXPECT_TRUE(ExpectedUndefVarNames.empty()) << toString(ExpectedUndefVarNames); } static void expectUndefError(const Twine &ExpectedUndefVarName, Error Err) { expectUndefErrors({ExpectedUndefVarName.getStr()}, std::move(Err)); } TEST_F(FileCheckTest, testNumericVariable) { // Undefined variable: getValue and eval fail, error returned by eval holds // the name of the undefined variable and setValue does not trigger assert. FileCheckNumericVariable fooVar = FileCheckNumericVariable("FOO", 1); EXPECT_EQ("FOO", fooVar.getName()); FileCheckNumericVariableUse fooVarUse = FileCheckNumericVariableUse("FOO", &fooVar); EXPECT_FALSE(fooVar.getValue()); Expected<uint64_t> evalResult = fooVarUse.eval(); EXPECT_FALSE(evalResult); expectUndefError("FOO", evalResult.takeError()); fooVar.setValue(42); // Defined variable: getValue and eval return value set. std::optional<uint64_t> value = fooVar.getValue(); EXPECT_TRUE(bool(value)); EXPECT_EQ(42U, *value); evalResult = fooVarUse.eval(); EXPECT_TRUE(bool(evalResult)); EXPECT_EQ(42U, *evalResult); // Clearing variable: getValue and eval fail. Error returned by eval holds // the name of the cleared variable. fooVar.clearValue(); value = fooVar.getValue(); EXPECT_FALSE(value); evalResult = fooVarUse.eval(); EXPECT_FALSE(evalResult); expectUndefError("FOO", evalResult.takeError()); } uint64_t doAdd(uint64_t OpL, uint64_t OpR) { return OpL + OpR; } TEST_F(FileCheckTest, testBinop) { FileCheckNumericVariable fooVar = FileCheckNumericVariable("FOO"); fooVar.setValue(42); std::unique_ptr<FileCheckNumericVariableUse> fooVarUse = std::make_unique<FileCheckNumericVariableUse>("FOO", &fooVar); FileCheckNumericVariable barVar = FileCheckNumericVariable("BAR"); barVar.setValue(18); std::unique_ptr<FileCheckNumericVariableUse> BarVarUse = std::make_unique<FileCheckNumericVariableUse>("BAR", &barVar); FileCheckASTBinop Binop = FileCheckASTBinop(doAdd, std::move(fooVarUse), std::move(BarVarUse)); // Defined variable: eval returns right value. Expected<uint64_t> value = Binop.eval(); EXPECT_TRUE(bool(value)); EXPECT_EQ(60U, *value); // 1 undefined variable: eval fails, error contains name of undefined // variable. fooVar.clearValue(); value = Binop.eval(); EXPECT_FALSE(value); expectUndefError("FOO", value.takeError()); // 2 undefined variables: eval fails, error contains names of all undefined // variables. barVar.clearValue(); value = Binop.eval(); EXPECT_FALSE(value); expectUndefErrors({"FOO", "BAR"}, value.takeError()); } TEST_F(FileCheckTest, testValidVarNameStart) { EXPECT_TRUE(FileCheckPattern::isValidVarNameStart('a')); EXPECT_TRUE(FileCheckPattern::isValidVarNameStart('G')); EXPECT_TRUE(FileCheckPattern::isValidVarNameStart('_')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('2')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('$')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('@')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('+')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart('-')); EXPECT_FALSE(FileCheckPattern::isValidVarNameStart(':')); } static StringRef bufferize(SourceMgr &SM, StringRef Str) { std::unique_ptr<MemoryBuffer> Buffer = MemoryBuffer::getMemBufferCopy(Str, "TestBuffer"); StringRef StrBufferRef = Buffer->getBuffer(); SM.addNewSourceBuffer(std::move(Buffer), SMLocation()); return StrBufferRef; } TEST_F(FileCheckTest, testParseVar) { SourceMgr SM; StringRef OrigVarName = bufferize(SM, "GoodVar42"); StringRef varName = OrigVarName; Expected<FileCheckPattern::VariableProperties> parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(parsedVarResult->name, OrigVarName); EXPECT_TRUE(varName.empty()); EXPECT_FALSE(parsedVarResult->isPseudo); varName = OrigVarName = bufferize(SM, "$GoodGlobalVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(parsedVarResult->name, OrigVarName); EXPECT_TRUE(varName.empty()); EXPECT_FALSE(parsedVarResult->isPseudo); varName = OrigVarName = bufferize(SM, "@GoodPseudoVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(parsedVarResult->name, OrigVarName); EXPECT_TRUE(varName.empty()); EXPECT_TRUE(parsedVarResult->isPseudo); varName = bufferize(SM, "42BadVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(error_to_bool(parsedVarResult.takeError())); varName = bufferize(SM, "$@"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(error_to_bool(parsedVarResult.takeError())); varName = OrigVarName = bufferize(SM, "B@dVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, OrigVarName.substr(1)); EXPECT_EQ(parsedVarResult->name, "B"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = OrigVarName = bufferize(SM, "B$dVar"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, OrigVarName.substr(1)); EXPECT_EQ(parsedVarResult->name, "B"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = bufferize(SM, "BadVar+"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, "+"); EXPECT_EQ(parsedVarResult->name, "BadVar"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = bufferize(SM, "BadVar-"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, "-"); EXPECT_EQ(parsedVarResult->name, "BadVar"); EXPECT_FALSE(parsedVarResult->isPseudo); varName = bufferize(SM, "BadVar:"); parsedVarResult = FileCheckPattern::parseVariable(varName, SM); EXPECT_TRUE(bool(parsedVarResult)); EXPECT_EQ(varName, ":"); EXPECT_EQ(parsedVarResult->name, "BadVar"); EXPECT_FALSE(parsedVarResult->isPseudo); } class PatternTester { private: size_t LineNumber = 1; SourceMgr SM; FileCheckRequest Req; FileCheckPatternContext Context; FileCheckPattern P = FileCheckPattern(check::CheckPlain, &Context, LineNumber++); public: PatternTester() { std::vector<std::string> globalDefines; globalDefines.emplace_back(std::string("#FOO=42")); globalDefines.emplace_back(std::string("BAR=BAZ")); EXPECT_FALSE( error_to_bool(Context.defineCmdlineVariables(globalDefines, SM))); Context.createLineVariable(); // Call parsePattern to have @LINE defined. P.parsePattern("N/A", "CHECK", SM, Req); // parsePattern does not expect to be called twice for the same line and // will set FixedStr and RegExStr incorrectly if it is. Therefore prepare // a pattern for a different line. initNextPattern(); } void initNextPattern() { P = FileCheckPattern(check::CheckPlain, &Context, LineNumber++); } bool parseNumVarDefExpect(StringRef Expr) { StringRef ExprBufferRef = bufferize(SM, Expr); return error_to_bool(FileCheckPattern::parseNumericVariableDefinition( ExprBufferRef, &Context, LineNumber, SM) .takeError()); } bool parseSubstExpect(StringRef Expr) { StringRef ExprBufferRef = bufferize(SM, Expr); std::optional<FileCheckNumericVariable *> DefinedNumericVariable; return error_to_bool(P.parseNumericSubstitutionBlock( ExprBufferRef, DefinedNumericVariable, false, SM) .takeError()); } bool parsePatternExpect(StringRef Pattern) { StringRef PatBufferRef = bufferize(SM, Pattern); return P.parsePattern(PatBufferRef, "CHECK", SM, Req); } bool matchExpect(StringRef Buffer) { StringRef BufferRef = bufferize(SM, Buffer); size_t MatchLen; return error_to_bool(P.match(BufferRef, MatchLen, SM).takeError()); } }; TEST_F(FileCheckTest, testParseNumericVariableDefinition) { PatternTester tester; // Invalid definition of pseudo. EXPECT_TRUE(tester.parseNumVarDefExpect("@LINE")); // Conflict with pattern variable. EXPECT_TRUE(tester.parseNumVarDefExpect("BAR")); // Defined variable. EXPECT_FALSE(tester.parseNumVarDefExpect("FOO")); } TEST_F(FileCheckTest, testParseExpr) { PatternTester tester; // Variable definition. // Definition of invalid variable. EXPECT_TRUE(tester.parseSubstExpect("10VAR:")); EXPECT_TRUE(tester.parseSubstExpect("@FOO:")); EXPECT_TRUE(tester.parseSubstExpect("@LINE:")); // Garbage after name of variable being defined. EXPECT_TRUE(tester.parseSubstExpect("VAR GARBAGE:")); // Variable defined to numeric expression. EXPECT_TRUE(tester.parseSubstExpect("VAR1: FOO")); // Acceptable variable definition. EXPECT_FALSE(tester.parseSubstExpect("VAR1:")); EXPECT_FALSE(tester.parseSubstExpect(" VAR2:")); EXPECT_FALSE(tester.parseSubstExpect("VAR3 :")); EXPECT_FALSE(tester.parseSubstExpect("VAR3: ")); // Numeric expression. // Unacceptable variable. EXPECT_TRUE(tester.parseSubstExpect("10VAR")); EXPECT_TRUE(tester.parseSubstExpect("@FOO")); // Only valid variable. EXPECT_FALSE(tester.parseSubstExpect("@LINE")); EXPECT_FALSE(tester.parseSubstExpect("FOO")); EXPECT_FALSE(tester.parseSubstExpect("UNDEF")); // Use variable defined on same line. EXPECT_FALSE(tester.parsePatternExpect("[[#LINE1VAR:]]")); EXPECT_TRUE(tester.parseSubstExpect("LINE1VAR")); // Unsupported operator. EXPECT_TRUE(tester.parseSubstExpect("@LINE/2")); // Missing offset operand. EXPECT_TRUE(tester.parseSubstExpect("@LINE+")); // Valid expression. EXPECT_FALSE(tester.parseSubstExpect("@LINE+5")); EXPECT_FALSE(tester.parseSubstExpect("FOO+4")); tester.initNextPattern(); EXPECT_FALSE(tester.parsePatternExpect("[[#FOO+FOO]]")); EXPECT_FALSE(tester.parsePatternExpect("[[#FOO+3-FOO]]")); } TEST_F(FileCheckTest, testParsePattern) { PatternTester tester; // Space in pattern variable expression. EXPECT_TRUE(tester.parsePatternExpect("[[ BAR]]")); // Invalid variable name. EXPECT_TRUE(tester.parsePatternExpect("[[42INVALID]]")); // Invalid pattern variable definition. EXPECT_TRUE(tester.parsePatternExpect("[[@PAT:]]")); EXPECT_TRUE(tester.parsePatternExpect("[[PAT+2:]]")); // Collision with numeric variable. EXPECT_TRUE(tester.parsePatternExpect("[[FOO:]]")); // Valid use of pattern variable. EXPECT_FALSE(tester.parsePatternExpect("[[BAR]]")); // Valid pattern variable definition. EXPECT_FALSE(tester.parsePatternExpect("[[PAT:[0-9]+]]")); // Invalid numeric expressions. EXPECT_TRUE(tester.parsePatternExpect("[[#42INVALID]]")); EXPECT_TRUE(tester.parsePatternExpect("[[#@FOO]]")); EXPECT_TRUE(tester.parsePatternExpect("[[#@LINE/2]]")); EXPECT_TRUE(tester.parsePatternExpect("[[#YUP:@LINE]]")); // Valid numeric expressions and numeric variable definition. EXPECT_FALSE(tester.parsePatternExpect("[[#FOO]]")); EXPECT_FALSE(tester.parsePatternExpect("[[#@LINE+2]]")); EXPECT_FALSE(tester.parsePatternExpect("[[#NUMVAR:]]")); } TEST_F(FileCheckTest, testMatch) { PatternTester tester; // Check matching a definition only matches a number. tester.parsePatternExpect("[[#NUMVAR:]]"); EXPECT_TRUE(tester.matchExpect("FAIL")); EXPECT_FALSE(tester.matchExpect("18")); // Check matching the variable defined matches the correct number only tester.initNextPattern(); tester.parsePatternExpect("[[#NUMVAR]] [[#NUMVAR+2]]"); EXPECT_TRUE(tester.matchExpect("19 21")); EXPECT_TRUE(tester.matchExpect("18 21")); EXPECT_FALSE(tester.matchExpect("18 20")); // Check matching a numeric expression using @LINE after match failure uses // the correct value for @LINE. tester.initNextPattern(); EXPECT_FALSE(tester.parsePatternExpect("[[#@LINE]]")); // Ok, @LINE is 4 now. EXPECT_FALSE(tester.matchExpect("4")); tester.initNextPattern(); // @LINE is now 5, match with substitution failure. EXPECT_FALSE(tester.parsePatternExpect("[[#UNKNOWN]]")); EXPECT_TRUE(tester.matchExpect("FOO")); tester.initNextPattern(); // Check that @LINE is 6 as expected. EXPECT_FALSE(tester.parsePatternExpect("[[#@LINE]]")); EXPECT_FALSE(tester.matchExpect("6")); } TEST_F(FileCheckTest, testSubstitution) { SourceMgr SM; FileCheckPatternContext Context; std::vector<std::string> globalDefines; globalDefines.emplace_back(std::string("FOO=BAR")); EXPECT_FALSE(error_to_bool(Context.defineCmdlineVariables(globalDefines, SM))); // Substitution of an undefined string variable fails and error holds that // variable's name. FileCheckStringSubstitution StringSubstitution = FileCheckStringSubstitution(&Context, "VAR404", 42); Expected<std::string> SubstValue = StringSubstitution.getResult(); EXPECT_FALSE(bool(SubstValue)); expectUndefError("VAR404", SubstValue.takeError()); // Substitutions of defined pseudo and non-pseudo numeric variables return // the right value. FileCheckNumericVariable LineVar = FileCheckNumericVariable("@LINE"); LineVar.setValue(42); FileCheckNumericVariable nvar = FileCheckNumericVariable("N"); nvar.setValue(10); auto LineVarUse = std::make_unique<FileCheckNumericVariableUse>("@LINE", &LineVar); auto NVarUse = std::make_unique<FileCheckNumericVariableUse>("N", &nvar); FileCheckNumericSubstitution SubstitutionLine = FileCheckNumericSubstitution( &Context, "@LINE", std::move(LineVarUse), 12); FileCheckNumericSubstitution SubstitutionN = FileCheckNumericSubstitution(&Context, "N", std::move(NVarUse), 30); SubstValue = SubstitutionLine.getResult(); EXPECT_TRUE(bool(SubstValue)); EXPECT_EQ("42", *SubstValue); SubstValue = SubstitutionN.getResult(); EXPECT_TRUE(bool(SubstValue)); EXPECT_EQ("10", *SubstValue); // Substitution of an undefined numeric variable fails, error holds name of // undefined variable. LineVar.clearValue(); SubstValue = SubstitutionLine.getResult(); EXPECT_FALSE(bool(SubstValue)); expectUndefError("@LINE", SubstValue.takeError()); nvar.clearValue(); SubstValue = SubstitutionN.getResult(); EXPECT_FALSE(bool(SubstValue)); expectUndefError("N", SubstValue.takeError()); // Substitution of a defined string variable returns the right value. FileCheckPattern P = FileCheckPattern(check::CheckPlain, &Context, 1); StringSubstitution = FileCheckStringSubstitution(&Context, "FOO", 42); SubstValue = StringSubstitution.getResult(); EXPECT_TRUE(bool(SubstValue)); EXPECT_EQ("BAR", *SubstValue); } TEST_F(FileCheckTest, testFileCheckContext) { FileCheckPatternContext cxt = FileCheckPatternContext(); std::vector<std::string> globalDefines; SourceMgr SM; // Missing equal sign. globalDefines.emplace_back(std::string("LocalVar")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); globalDefines.clear(); globalDefines.emplace_back(std::string("#LocalNumVar")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Empty variable name. globalDefines.clear(); globalDefines.emplace_back(std::string("=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); globalDefines.clear(); globalDefines.emplace_back(std::string("#=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Invalid variable name. globalDefines.clear(); globalDefines.emplace_back(std::string("18LocalVar=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); globalDefines.clear(); globalDefines.emplace_back(std::string("#18LocalNumVar=18")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // name conflict between pattern and numeric variable. globalDefines.clear(); globalDefines.emplace_back(std::string("LocalVar=18")); globalDefines.emplace_back(std::string("#LocalVar=36")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); cxt = FileCheckPatternContext(); globalDefines.clear(); globalDefines.emplace_back(std::string("#LocalNumVar=18")); globalDefines.emplace_back(std::string("LocalNumVar=36")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); cxt = FileCheckPatternContext(); // Invalid numeric value for numeric variable. globalDefines.clear(); globalDefines.emplace_back(std::string("#LocalNumVar=x")); EXPECT_TRUE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Define local variables from command-line. globalDefines.clear(); globalDefines.emplace_back(std::string("LocalVar=FOO")); globalDefines.emplace_back(std::string("emptyVar=")); globalDefines.emplace_back(std::string("#LocalNumVar=18")); EXPECT_FALSE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); // Check defined variables are present and undefined is absent. StringRef LocalVarStr = "LocalVar"; StringRef LocalNumVarRef = bufferize(SM, "LocalNumVar"); StringRef EmptyVarStr = "emptyVar"; StringRef UnknownVarStr = "UnknownVar"; Expected<StringRef> LocalVar = cxt.getPatternVarValue(LocalVarStr); FileCheckPattern P = FileCheckPattern(check::CheckPlain, &cxt, 1); std::optional<FileCheckNumericVariable *> DefinedNumericVariable; Expected<std::unique_ptr<FileCheckExpressionAST>> expressionAST = P.parseNumericSubstitutionBlock(LocalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(LocalVar)); EXPECT_EQ(*LocalVar, "FOO"); Expected<StringRef> emptyVar = cxt.getPatternVarValue(EmptyVarStr); Expected<StringRef> UnknownVar = cxt.getPatternVarValue(UnknownVarStr); EXPECT_TRUE(bool(expressionAST)); Expected<uint64_t> expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(bool(expressionVal)); EXPECT_EQ(*expressionVal, 18U); EXPECT_TRUE(bool(emptyVar)); EXPECT_EQ(*emptyVar, ""); EXPECT_TRUE(error_to_bool(UnknownVar.takeError())); // Clear local variables and check they become absent. cxt.clearLocalVars(); LocalVar = cxt.getPatternVarValue(LocalVarStr); EXPECT_TRUE(error_to_bool(LocalVar.takeError())); // Check a numeric expression's evaluation fails if called after clearing of // local variables, if it was created before. This is important because local // variable clearing due to --enable-var-scope happens after numeric // expressions are linked to the numeric variables they use. EXPECT_TRUE(error_to_bool((*expressionAST)->eval().takeError())); P = FileCheckPattern(check::CheckPlain, &cxt, 2); expressionAST = P.parseNumericSubstitutionBlock( LocalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(expressionAST)); expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(error_to_bool(expressionVal.takeError())); emptyVar = cxt.getPatternVarValue(EmptyVarStr); EXPECT_TRUE(error_to_bool(emptyVar.takeError())); // Clear again because parseNumericSubstitutionBlock would have created a // dummy variable and stored it in GlobalNumericVariableTable. cxt.clearLocalVars(); // Redefine global variables and check variables are defined again. globalDefines.emplace_back(std::string("$GlobalVar=BAR")); globalDefines.emplace_back(std::string("#$GlobalNumVar=36")); EXPECT_FALSE(error_to_bool(cxt.defineCmdlineVariables(globalDefines, SM))); StringRef GlobalVarStr = "$GlobalVar"; StringRef GlobalNumVarRef = bufferize(SM, "$GlobalNumVar"); Expected<StringRef> GlobalVar = cxt.getPatternVarValue(GlobalVarStr); EXPECT_TRUE(bool(GlobalVar)); EXPECT_EQ(*GlobalVar, "BAR"); P = FileCheckPattern(check::CheckPlain, &cxt, 3); expressionAST = P.parseNumericSubstitutionBlock( GlobalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(expressionAST)); expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(bool(expressionVal)); EXPECT_EQ(*expressionVal, 36U); // Clear local variables and check global variables remain defined. cxt.clearLocalVars(); EXPECT_FALSE(error_to_bool(cxt.getPatternVarValue(GlobalVarStr).takeError())); P = FileCheckPattern(check::CheckPlain, &cxt, 4); expressionAST = P.parseNumericSubstitutionBlock( GlobalNumVarRef, DefinedNumericVariable, /*IsLegacyLineExpr=*/false, SM); EXPECT_TRUE(bool(expressionAST)); expressionVal = (*expressionAST)->eval(); EXPECT_TRUE(bool(expressionVal)); EXPECT_EQ(*expressionVal, 36U); } } // namespace
39.259067
85
0.723505
PHP-OPEN-HUB
f05e11c9aa8b06d2cce2ca4aa7b0eb9e2b992d49
5,180
hpp
C++
include/System/Data/DataRowAction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/DataRowAction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Data/DataRowAction.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: System.Data namespace System::Data { // Forward declaring type: DataRowAction struct DataRowAction; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::System::Data::DataRowAction, "System.Data", "DataRowAction"); // Type namespace: System.Data namespace System::Data { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: System.Data.DataRowAction // [TokenAttribute] Offset: FFFFFFFF // [FlagsAttribute] Offset: FFFFFFFF struct DataRowAction/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: DataRowAction constexpr DataRowAction(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public System.Data.DataRowAction Nothing static constexpr const int Nothing = 0; // Get static field: static public System.Data.DataRowAction Nothing static ::System::Data::DataRowAction _get_Nothing(); // Set static field: static public System.Data.DataRowAction Nothing static void _set_Nothing(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Delete static constexpr const int Delete = 1; // Get static field: static public System.Data.DataRowAction Delete static ::System::Data::DataRowAction _get_Delete(); // Set static field: static public System.Data.DataRowAction Delete static void _set_Delete(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Change static constexpr const int Change = 2; // Get static field: static public System.Data.DataRowAction Change static ::System::Data::DataRowAction _get_Change(); // Set static field: static public System.Data.DataRowAction Change static void _set_Change(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Rollback static constexpr const int Rollback = 4; // Get static field: static public System.Data.DataRowAction Rollback static ::System::Data::DataRowAction _get_Rollback(); // Set static field: static public System.Data.DataRowAction Rollback static void _set_Rollback(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Commit static constexpr const int Commit = 8; // Get static field: static public System.Data.DataRowAction Commit static ::System::Data::DataRowAction _get_Commit(); // Set static field: static public System.Data.DataRowAction Commit static void _set_Commit(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction Add static constexpr const int Add = 16; // Get static field: static public System.Data.DataRowAction Add static ::System::Data::DataRowAction _get_Add(); // Set static field: static public System.Data.DataRowAction Add static void _set_Add(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction ChangeOriginal static constexpr const int ChangeOriginal = 32; // Get static field: static public System.Data.DataRowAction ChangeOriginal static ::System::Data::DataRowAction _get_ChangeOriginal(); // Set static field: static public System.Data.DataRowAction ChangeOriginal static void _set_ChangeOriginal(::System::Data::DataRowAction value); // static field const value: static public System.Data.DataRowAction ChangeCurrentAndOriginal static constexpr const int ChangeCurrentAndOriginal = 64; // Get static field: static public System.Data.DataRowAction ChangeCurrentAndOriginal static ::System::Data::DataRowAction _get_ChangeCurrentAndOriginal(); // Set static field: static public System.Data.DataRowAction ChangeCurrentAndOriginal static void _set_ChangeCurrentAndOriginal(::System::Data::DataRowAction value); // Get instance field reference: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& dyn_value__(); }; // System.Data.DataRowAction #pragma pack(pop) static check_size<sizeof(DataRowAction), 0 + sizeof(int)> __System_Data_DataRowActionSizeCheck; static_assert(sizeof(DataRowAction) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
51.287129
97
0.733398
v0idp
f06de431cb9933773c4c4fbea87a43ffd31cbb7c
2,404
cpp
C++
lua100/sources/utils/plugin_loader.cpp
SoulWorkerResearch/swp-loader
00d8ca0d59e0e5a0d279e5d4b5d08850042aa190
[ "WTFPL" ]
1
2022-01-05T13:36:26.000Z
2022-01-05T13:36:26.000Z
lua100/sources/utils/plugin_loader.cpp
SoulWorkerResearch/swp-loader
00d8ca0d59e0e5a0d279e5d4b5d08850042aa190
[ "WTFPL" ]
1
2022-01-06T04:41:02.000Z
2022-01-06T04:41:02.000Z
lua100/sources/utils/plugin_loader.cpp
SoulWorkerResearch/swp-loader
00d8ca0d59e0e5a0d279e5d4b5d08850042aa190
[ "WTFPL" ]
null
null
null
// local #include "../../headers/utils/plugin_loader.hpp" #include "../../headers/utils/game_version.hpp" #include "../../headers/plugins.hpp" // windows #include <Windows.h> // local deps #include <swpsdk/utils/spdlog_formatter.hpp> #include <swpsdk/plugin/attach.hpp> #include <swpsdk/plugin/loader.hpp> // deps #include <spdlog/spdlog.h> #include <spdlog/async.h> #include <spdlog/sinks/stdout_color_sinks.h> // cpp #include <system_error> #include <filesystem> #include <ranges> #include <future> namespace fs = std::filesystem; auto create_logger(const std::string& _name) { return spdlog::stdout_color_mt<spdlog::async_factory>(_name, spdlog::color_mode::always); } auto lua100::utils::plugin_loader::operator()(const fs::directory_entry& _entry) const->std::unique_ptr<plugin_info> { win::dll dll{ _entry }; auto logger{ m_logger_factory->create(_entry.path()) }; if (not dll) { logger->error(std::system_category().message(GetLastError())); return nullptr; } using attach_ptr_t = decltype(swpsdk::plugin::attach)*; const auto address{ GetProcAddress(static_cast<HMODULE>(dll), "attach") }; const auto attach{ reinterpret_cast<attach_ptr_t>(address) }; if (not attach) { logger->error("haven't attach function.", _entry); return nullptr; } const std::unique_ptr<swpsdk::plugin::info> info{ attach() }; if (not info) { logger->error("can't get info.", _entry); return nullptr; } if (info->game_version != m_game_version) { logger->warn("mismatch game version [plugin: {}] != [game: {}]", info->game_version, m_game_version); } if (info->sdk_version != swpsdk::current_version) { logger->warn("mismatch sdk version [plugin: {}] != [loader: {}]", info->sdk_version, swpsdk::current_version); } using loader_t = swpsdk::plugin::loader; auto p{ reinterpret_cast<const loader_t*>(info->instance) }; std::invoke(&loader_t::attach, p, logger); logger->info("attached v{}", info->plugin_version); return std::make_unique<plugin_info>(std::forward<decltype(dll)>(dll), std::forward<decltype(logger)>(logger)); } lua100::utils::plugin_loader::plugin_loader(const logger_factory_t& _logger_factory) : m_game_version{ utils::game_version::read() } , m_logger_factory{ _logger_factory } { spdlog::info("game v{}", m_game_version); }
30.05
117
0.680532
SoulWorkerResearch
f07244b9aa7b9739d855c629eed6db0a68eb950c
12,578
hpp
C++
src/include/InterpolationTemplate.hpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
5
2022-03-21T08:50:42.000Z
2022-03-31T05:31:41.000Z
src/include/InterpolationTemplate.hpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
null
null
null
src/include/InterpolationTemplate.hpp
12ff54e/BSplineInterpolation
b0f04414807bea999c5102f1274ea2ad9c2a6b6f
[ "MIT" ]
1
2022-03-31T11:12:24.000Z
2022-03-31T11:12:24.000Z
#pragma once #include "BSpline.hpp" #include "Mesh.hpp" namespace intp { template <typename T, size_t D> class InterpolationFunction; // Forward declaration, since template has // a member of it. /** * @brief Template for interpolation with only coordinates, and generate * interpolation function when fed by function values. * */ template <typename T, size_t D> class InterpolationFunctionTemplate { public: using function_type = InterpolationFunction<T, D>; using size_type = typename function_type::size_type; using coord_type = typename function_type::coord_type; using val_type = typename function_type::val_type; static constexpr size_type dim = D; template <typename U> using DimArray = std::array<U, dim>; using MeshDim = MeshDimension<dim>; /** * @brief Construct a new Interpolation Function Template object * * @param order Order of BSpline * @param periodicity Periodicity of each dimension * @param interp_mesh_dimension The structure of coordinate mesh * @param x_ranges Begin and end iterator/value pairs of each dimension */ template <typename... Ts> InterpolationFunctionTemplate(size_type order, DimArray<bool> periodicity, MeshDim interp_mesh_dimension, std::pair<Ts, Ts>... x_ranges) : input_coords{}, mesh_dimension(interp_mesh_dimension), base(order, periodicity, input_coords, mesh_dimension, x_ranges...) { // adjust dimension according to periodicity { DimArray<size_type> dim_size_tmp; bool p_flag = false; for (size_type d = 0; d < dim; ++d) { dim_size_tmp[d] = mesh_dimension.dim_size(d) - (base.periodicity(d) ? ((p_flag = true), 1) : 0); } if (p_flag) { mesh_dimension.resize(dim_size_tmp); } } DimArray<typename function_type::spline_type::BaseSpline> base_spline_vals_per_dim; const auto& spline = base.spline(); // pre-calculate base spline of periodic dimension, since it never // changes due to its even-spaced knots for (size_type d = 0; d < dim; ++d) { if (base.periodicity(d) && base.uniform(d)) { base_spline_vals_per_dim[d] = spline.base_spline_value( d, spline.knots_begin(d) + order, spline.knots_begin(d)[order] + (1 - order % 2) * base.__dx[d] * .5); } } // loop through each dimension to construct coefficient matrix for (size_type d = 0; d < dim; ++d) { std::vector<Eigen::Triplet<val_type>> coef_list; // rough estimate of upper limit of coefficient number, reserve // space to make sure no re-allocation occurs during the filling // process coef_list.reserve(mesh_dimension.dim_size(d) * (order + 1)); for (size_type i = 0; i < mesh_dimension.dim_size(d); ++i) { const auto knot_num = spline.knots_num(d); // This is the index of knot point to the left of i-th // interpolated value's coordinate, notice that knot points has // a larger gap in both ends in non-periodic case. size_type knot_ind{}; if (base.uniform(d)) { knot_ind = base.periodicity(d) ? i + order : std::min( knot_num - order - 2, i > order / 2 ? i + (order + 1) / 2 : order); if (!base.periodicity(d)) { if (knot_ind <= 2 * order + 1 || knot_ind >= knot_num - 2 * order - 2) { // update base spline const auto iter = spline.knots_begin(d) + knot_ind; const coord_type x = spline.range(d).first + i * base.__dx[d]; base_spline_vals_per_dim[d] = spline.base_spline_value(d, iter, x); } } } else { coord_type x = input_coords[d][i]; // using BSpline::get_knot_iter to find current // knot_ind const auto iter = base.periodicity(d) ? spline.knots_begin(d) + i + order : i == 0 ? spline.knots_begin(d) + order : i == input_coords[d].size() - 1 ? spline.knots_end(d) - order - 2 : spline.get_knot_iter( d, x, i + 1, std::min(knot_num - order - 1, i + order)); knot_ind = iter - spline.knots_begin(d); base_spline_vals_per_dim[d] = spline.base_spline_value(d, iter, x); } for (size_type j = 0; j < order + 1; ++j) { coef_list.emplace_back( i, (knot_ind - order + j) % mesh_dimension.dim_size(d), base_spline_vals_per_dim[d][j]); } } // fill coefficient matrix { Eigen::SparseMatrix<double> coef(mesh_dimension.dim_size(d), mesh_dimension.dim_size(d)); coef.setFromTriplets(coef_list.begin(), coef_list.end()); solver[d].compute(coef); } #ifdef _DEBUG if (solver[d].info() != Eigen::Success) { throw std::runtime_error( std::string{ "Coefficient matrix decomposition failed at dim "} + std::to_string(d) + std::string{".\n"}); } #endif } } /** * @brief Construct a new 1D Interpolation Function Template object. * * @param order order of interpolation, the interpolated function is of * $C^{order-1}$ * @param periodic whether to construct a periodic spline * @param f_length point number of to-be-interpolated data * @param x_range a pair of x_min and x_max */ template <typename C1, typename C2> InterpolationFunctionTemplate(size_type order, bool periodicity, size_type f_length, std::pair<C1, C2> x_range) : InterpolationFunctionTemplate(order, {periodicity}, MeshDim{f_length}, x_range) { static_assert( dim == size_type{1}, "You can only use this overload of constructor in 1D case."); } template <typename C1, typename C2> InterpolationFunctionTemplate(size_type order, size_type f_length, std::pair<C1, C2> x_range) : InterpolationFunctionTemplate(order, false, f_length, x_range) {} /** * @brief Construct a new (nonperiodic) Interpolation Function Template * object * * @param order Order of BSpline * @param interp_mesh_dimension The structure of coordinate mesh * @param x_ranges Begin and end iterator/value pairs of each dimension */ template <typename... Ts> InterpolationFunctionTemplate(size_type order, MeshDim interp_mesh_dimension, std::pair<Ts, Ts>... x_ranges) : InterpolationFunctionTemplate(order, {}, interp_mesh_dimension, x_ranges...) {} template <typename MeshOrIterPair> function_type interpolate(MeshOrIterPair&& mesh_or_iter_pair) const& { function_type interp{base}; interp.__spline.load_ctrlPts( __solve_for_control_points(Mesh<val_type, dim>{ std::forward<MeshOrIterPair>(mesh_or_iter_pair)})); return interp; } template <typename MeshOrIterPair> function_type interpolate(MeshOrIterPair&& mesh_or_iter_pair) && { base.__spline.load_ctrlPts( __solve_for_control_points(Mesh<val_type, dim>{ std::forward<MeshOrIterPair>(mesh_or_iter_pair)})); return std::move(base); } private: // input coordinates, needed only in nonuniform case DimArray<typename function_type::spline_type::KnotContainer> input_coords; MeshDim mesh_dimension; // the base interpolation function with unspecified weights function_type base; // solver for weights DimArray<Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>>> solver; Mesh<val_type, dim> __solve_for_control_points( const Mesh<val_type, dim>& f_mesh) const { Mesh<val_type, dim> weights{mesh_dimension}; // Copy interpolating values into weights mesh as the initial state of // the iterative control points solving algorithm for (auto it = f_mesh.begin(); it != f_mesh.end(); ++it) { auto f_indices = f_mesh.iter_indices(it); bool skip_flag = false; for (size_type d = 0; d < dim; ++d) { // Skip last point of periodic dimension if (f_indices[d] == weights.dim_size(d)) { skip_flag = true; break; } } if (!skip_flag) { weights(f_indices) = *it; } } // loop through each dimension to solve for control points for (size_type d = 0; d < dim; ++d) { // size of hyperplane when given dimension is fixed size_type hyperplane_size = weights.size() / weights.dim_size(d); // loop over each point (representing a 1D spline) of hyperplane for (size_type i = 0; i < hyperplane_size; ++i) { DimArray<size_type> ind_arr; for (size_type d_ = 0, total_ind = i; d_ < dim; ++d_) { if (d_ == d) { continue; } ind_arr[d_] = total_ind % weights.dim_size(d_); total_ind /= weights.dim_size(d_); } // loop through one dimension, update interpolating value to // control points Eigen::VectorXd mesh_val_1d(weights.dim_size(d)); size_type ind_1d{}; for (auto it = weights.begin(d, ind_arr); it != weights.end(d, ind_arr); ++it, ++ind_1d) { mesh_val_1d(ind_1d) = *it; } Eigen::VectorXd weights_1d = solver[d].solve(mesh_val_1d); ind_1d = 0; for (auto it = weights.begin(d, ind_arr); it != weights.end(d, ind_arr); ++it, ++ind_1d) { *it = weights_1d(ind_1d); } } } return weights; } }; template <typename T> class InterpolationFunctionTemplate1D : public InterpolationFunctionTemplate<T, size_t{1}> { private: using base = InterpolationFunctionTemplate<T, size_t{1}>; public: InterpolationFunctionTemplate1D(typename base::size_type f_length, typename base::size_type order = 3, bool periodicity = false) : InterpolationFunctionTemplate1D( std::make_pair( (typename base::coord_type){}, static_cast<typename base::coord_type>(f_length - 1)), f_length, order, periodicity) {} template <typename C1, typename C2> InterpolationFunctionTemplate1D(std::pair<C1, C2> x_range, typename base::size_type f_length, typename base::size_type order = 3, bool periodicity = false) : base(order, periodicity, f_length, x_range) {} }; } // namespace intp
40.574194
79
0.5225
12ff54e
f073a8f2172f9a84bb1539aa1a7d706d36e8e251
25,075
cpp
C++
src/Networking.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
1
2015-08-27T17:01:48.000Z
2015-08-27T17:01:48.000Z
src/Networking.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
11
2015-09-24T03:15:13.000Z
2016-02-23T03:03:04.000Z
src/Networking.cpp
crumblingstatue/Galaxy
a33d1df85e57a88206265c2780b288f3fda52bbb
[ "CC-BY-3.0" ]
1
2016-02-16T22:25:06.000Z
2016-02-16T22:25:06.000Z
#include "Networking.h" #include "globalvars.h" #include <iostream> #include <iomanip> #include <stdio.h> #include <string> namespace network { int mainPort = 23636; bool packetDeletion = false; bool servWait = false; bool cliWait = false; bool server = false; bool client = false; bool chatting = false; bool needTime = false; bool givingTime = false; std::string name = ""; std::string connectedServer = ""; } int displayPort() { return network::mainPort; } Identity::Identity() { wrongVersion = "Wrong Version"; connection = "Connection"; connectionSuccessful = "Connection Successful"; textMessage = "Text Message"; drawStuffs = "Draw Stuffs"; grid = "Grid"; peers = "Peers"; clientMouse = "Client Mouse Position"; gridUpdate = "Grid Update"; tilesUpdate = "Tiles Update"; ping = "Ping"; pong = "Pong"; updateRoster = "Update Roster"; updateItems = "Update Items"; } Identity ident; sf::IpAddress server("127.0.0.1"); bool TcpFirstRun = true; sf::TcpListener servListener; sf::TcpSocket servSocket; sf::TcpSocket cliSocket; std::list<sf::TcpSocket*> clients; sf::SocketSelector selector; BoolPacket::BoolPacket() { toDelete = false; } std::vector<BoolPacket> packetContainer; /////////////////////////////////////////////////// ///////// /// Launch a server, wait for an incoming connection, /// send a message and wait for the answer. /// //////////////////////////////////////////////////////////// ServerController::ServerController() { waiting = false; conID = 100; } ServerController servCon; ClientController::ClientController() { mode = "Local"; waiting = false; connected = false; chatting = false; name = ""; ID = -1; } ClientController cliCon; Peer::Peer() { name = ""; ID = servCon.conID++; } Peers peers; void DealPackets() { if(gvars::debug) std::cout << "DealPacket Begins" << packetContainer.size() << std::endl; int PackLimit = packetContainer.size(); for(int i = 0; i != PackLimit; i++) { //packetContainer[i].Packet std::string GotIdent; packetContainer[i].packet >> GotIdent; if(gvars::debug) std::cout << "GotIdent: \n" << GotIdent << std::endl; if(GotIdent != "") { cliCon.waiting = false; if(gvars::debug) std::cout << "Message received from server " << ", Type:" << GotIdent << std::endl; if(GotIdent == ident.wrongVersion) { std::string ver; packetContainer[i].packet >> ver; std::cout << "You have the wrong version. \n"; std::cout << "Servers Version: " << ver << ", Your Version: " << gvars::version << std::endl; std::cout << "You should acquire the same version as the server. \n"; cliCon.connected = false; } if(GotIdent == ident.connectionSuccessful) { std::cout << "Your now connected to " << cliCon.server << std::endl; cliCon.connected = true; } if(GotIdent == ident.textMessage) { if(gvars::debug) std::cout << "Dealing with Text Message, Pack: " << i << std::endl; std::string Text; packetContainer[i].packet >> Text; cliCon.chatHistory.push_back(Text); std::cout << "* " << Text; sf::Packet SendPacket; SendPacket << ident.textMessage << Text; for (std::list<sf::TcpSocket*>::iterator zit = clients.begin(); zit != clients.end(); ++zit) { if(gvars::debug) std::cout << "Running through clients \n"; sf::TcpSocket& clientz = **zit; clientz.send(SendPacket); } if(gvars::debug) std::cout << "Done with Text Message Packet:" << i << std::endl; } if(GotIdent == ident.drawStuffs) { //NeedsToDraw = true; } if(GotIdent == ident.connection) { Peer peer; packetContainer[i].packet >> peer.name; peers.connected.push_back(peer); } if(GotIdent == ident.clientMouse) { std::string Name; packetContainer[i].packet >> Name; if(gvars::debug) std::cout << "Dealing with ClientMouse from," << Name << ", Pack: " << i << std::endl; for(int i = 0; i != peers.connected.size(); i++) { if(Name == peers.connected[i].name) { //packetContainer[i].Packet >> peers.Connected[i].MousePos.x >> peers.Connected[i].MousePos.y; sf::Uint32 x; sf::Uint32 y; packetContainer[i].packet >> x >> y; peers.connected[i].mousePos.x = x; peers.connected[i].mousePos.y = y; } } } if(GotIdent == ident.pong) { std::string peerName; packetContainer[i].packet >> peerName; for(auto &peer : peers.connected) { if(peer.name == peerName) { sf::Clock myClock; sf::Time recvTime; sf::Time myTime = myClock.getElapsedTime(); sf::Uint32 recvValue; packetContainer[i].packet >> recvValue; recvTime = sf::microseconds(recvValue); int thePing = myTime.asMicroseconds() - recvTime.asMicroseconds(); peer.ping = thePing; } } } if(GotIdent == ident.tilesUpdate) { int regionX, regionY, tileX, tileY, tileZ, tileID; sf::Packet pack; pack = packetContainer[i].packet; while(!pack.endOfPacket()) { pack >> regionX >> regionY; pack >> tileX >> tileY >> tileZ; pack >> tileID; int regionXDiff = regionX - gvars::currentregionx; int regionYDiff = regionY - gvars::currentregiony; tiles[(tileX)][(tileY)][tileZ].setTilebyID(tileID); if(abs_to_index(regionXDiff) <= 1 && abs_to_index(regionYDiff) <= 1) { //tiles[(tileX+(regionXDiff*CHUNK_SIZE))][(tileY+(regionYDiff*CHUNK_SIZE))][tileZ].setTilebyID(tileID); } std::cout << "tilesUpdate: " << regionXDiff << "/" << regionYDiff << "/" << tileX << "/" << tileY << "/" << tileZ << "/" << tileID << std::endl; } } } packetContainer[i].toDelete = true; } bool DoneDeleting = false; std::vector<BoolPacket>::iterator EndLimit = packetContainer.end(); std::vector<NestClass> Nested; int DeleteAmount = 0; for(std::vector<BoolPacket>::iterator i = packetContainer.begin(); i != EndLimit; i++) { bool CatchAll = false; if(i->toDelete == true) { DeleteAmount++; NestClass NC; NC.nestIter = i; Nested.push_back(NC); //CatchAll = true; //EndLimit--; } } //packetContainer.erase(packetContainer.begin(),packetContainer.begin()+DeleteAmount); if(gvars::debug) std::cout << "Nested: " << Nested.size() << std::endl; network::packetDeletion = true; for(int i = Nested.size()-1; i != -1; i--) { if(gvars::debug) std::cout << "Removed: " << i << std::endl; packetContainer.erase( Nested[i].nestIter ); } Nested.clear(); network::packetDeletion = false; //Global.PackWait = false; /* for(std::vector<std::vector<BoolPacket>::iterator>::iterator i = Nested.end(); i != Nested.begin(); i--) { packetContainer.erase(i); } */ /* while(DoneDeleting == false) { std::vector<BoolPacket>::iterator i; DoneDeleting = true; // try{ for(i = packetContainer.begin(); i != EndLimit; i++) { bool CatchAll = false; if(i->ToDelete == true) { DoneDeleting = false; packetContainer.erase(i); Nested.push_back(i); CatchAll = true; EndLimit--; break; } if(CatchAll) { std::cout << "Caught somefin' Paul! \n"; break; } } // }catch (std::exception& e){ std::cout << "Packet Container try-fail! \n"; } } */ } void runTcpServer(unsigned short port) { // Create a server socket to accept new connections //Code ripped to Main.cpp, Code 555000999 // Wait for a connection if(TcpFirstRun) { TcpFirstRun = false; /* sf::TcpSocket* client = new sf::TcpSocket; if (servListener.accept(*client) != sf::Socket::Done) { std::cout << "Infinite? \n"; return; } //std::cout << "Client connected: " << client.getRemoteAddress() << std::endl; selector.add(*client); clients.push_back(client); */ } while(selector.wait()) { if(gvars::debug) std::cout << "Wait Successful! \n"; if(selector.isReady(servListener)) { std::cout << "Listener is ready! \n"; sf::TcpSocket* client = new sf::TcpSocket; if (servListener.accept(*client) == sf::Socket::Done) { selector.add(*client); clients.push_back(client); } else { std::cout << "Deleting a Client! Is this normal? \n"; delete client; } std::cout << "Listener is done, Moving on. \n"; } else { for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) { //std::cout << "Running through clients \n"; sf::TcpSocket& client = **it; if(selector.isReady(client)) { if(gvars::debug) std::cout << "Client is ready! \n"; sf::Packet GotPacket; if(client.receive(GotPacket) != sf::Socket::Done) { std::cout << "Not Ready"; return; } BoolPacket BP; BP.packet = GotPacket; int Delay = 0; while(network::packetDeletion == true) { std::cout << " " << Delay++; } packetContainer.push_back(BP); if(gvars::debug) std::cout << "Client is done. \n"; } else { if(gvars::debug) std::cout << "IsReady(Client) is false \n"; } } } } if(gvars::debug) std::cout << "Do we make it here? \n"; //DealPackets(); if(gvars::debug) std::cout << "And if so, How about here? \n"; //Global.ServWait = false; } void runTcpClient(unsigned short port) { // Create a socket for communicating with the server // Connect to the server if(gvars::debug) std::cout << "Waiting on Message! \n"; sf::Packet GotPacket; if (cliSocket.receive(GotPacket) != sf::Socket::Done) { network::cliWait = false; return; } std::string GotIdent; GotPacket >> GotIdent; if(gvars::debug) std::cout << "GotIdent: " << GotIdent << std::endl; if(GotIdent != "") { network::cliWait = false; cliCon.waiting = false; if(gvars::debug) std::cout << "Message received from server " << ", Type:" << GotIdent << std::endl; if(GotIdent == ident.wrongVersion) { std::string ver; GotPacket >> ver; std::cout << "You have the wrong version. \n"; std::cout << "Servers Version: " << ver << ", Your Version: " << gvars::version << std::endl; std::cout << "You should acquire the same version as the server. \n"; cliCon.connected = false; } if(GotIdent == ident.connectionSuccessful) { std::cout << "Your now connected to " << cliCon.server << std::endl; cliCon.connected = true; } if(GotIdent == ident.textMessage) { std::string Text; GotPacket >> Text; cliCon.chatHistory.push_back(Text); chatBox.addChat(Text,sf::Color::White); std::cout << Text; } if(GotIdent == ident.drawStuffs) { //NeedsToDraw = true; } if(GotIdent == ident.clientMouse) { std::string Name; GotPacket >> Name; bool Exists = false; for(int i = 0; i != peers.connected.size(); i++) { if(Name == peers.connected[i].name) Exists = true; } if(!Exists) { Peer peer; peer.name = Name; peer.mousePos = sf::Vector2f(5,5); peers.connected.push_back(peer); } for(int i = 0; i != peers.connected.size(); i++) { if(Name == peers.connected[i].name) { sf::Uint32 x; sf::Uint32 y; GotPacket >> x >> y; peers.connected[i].mousePos.x = x; peers.connected[i].mousePos.y = y; } } } if(GotIdent == ident.gridUpdate) { networkGridUpdate(GotPacket); } if(GotIdent == ident.ping) { sf::Packet toSend; toSend << ident.pong << network::name; sf::Uint32 peerTime; GotPacket >> peerTime; toSend << peerTime; cliSocket.send(toSend); } if(GotIdent == ident.peers) { peers.connected.clear(); while(!GotPacket.endOfPacket()) { Peer peer; sf::Uint32 peerPing; GotPacket >> peer.name >> peerPing; peer.ping = peerPing; peers.connected.push_back(peer); } } if(GotIdent == ident.updateRoster) { network::needTime = true; sf::Lock lock(mutex::npcList); while(!GotPacket.endOfPacket()) { std::string npcName, npcBloodContent; sf::Uint32 npcID, npcXpos, npcYpos, npcZpos; GotPacket >> npcName >> npcID >> npcXpos >> npcYpos >> npcZpos >> npcBloodContent; bool npcFound = false; for(auto &npc : npclist) { if(npc.name == npcName && npc.id == npcID) { npcFound = true; npc.xpos = npcXpos; npc.ypos = npcYpos; npc.zpos = npcZpos; npc.bloodcontent = npcBloodContent; } } if(npcFound == false) { Npc npc; npc = *getGlobalCritter("Human"); //npc.img.setTexture(texturemanager.getTexture("Human.png")); npc.xpos = npcXpos; npc.ypos = npcYpos; npc.zpos = npcZpos; npc.id = npcID; npc.name = npcName; npc.reCreateSkills(); npc.hasSpawned = true; npc.bloodcontent = npcBloodContent; npclist.push_back(npc); } } } if(GotIdent == ident.updateItems) { sf::Lock lock(mutex::itemList); while(!GotPacket.endOfPacket()) { std::string itemName; sf::Uint32 itemID, itemXpos, itemYpos, itemZpos, itemProdrate; GotPacket >> itemName >> itemID >> itemXpos >> itemYpos >> itemZpos >> itemProdrate; bool itemFound = false; for(auto &item : worlditems) { if(item.name == itemName && item.id == itemID) { itemFound = true; item.xpos = itemXpos; item.ypos = itemYpos; item.zpos = itemZpos; item.prodratetimer = itemProdrate; } } if(itemFound == false) { Item item; item = *getGlobalItem(itemName); item.xpos = itemXpos; item.ypos = itemYpos; item.zpos = itemZpos; item.id = itemID; item.name = itemName; item.prodratetimer = itemProdrate; worlditems.push_back(item); } } } } } void tcpSendtoAll(sf::Packet pack) { for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) { sf::TcpSocket& client = **it; client.send(pack); } } bool chatCommand(std::string input) { std::vector<std::string> elements; bool finished = false; sf::Color errorColor(100,100,100); sf::Color warmColor(255,150,150); sf::Color goodColor = sf::Color::White; size_t tStart = 0; size_t tEnd = 0; while(finished == false) { tEnd = input.find(" ",tStart); std::string injection; injection.append(input,tStart,tEnd-tStart); elements.push_back(injection); tStart = tEnd+1; if(tEnd == input.npos) finished = true; } std::cout << "input: " << input << std::endl; for(auto &i : elements) { std::cout << "elements: " << i << std::endl; } if(elements[0] == "/connect") { std::cout << "Connect chat command detected. \n"; if(network::connectedServer != "") { chatBox.addChat("Server: Error, You're already connected to " + network::connectedServer, errorColor); return false; } if(network::name == "") { chatBox.addChat("Server: Error, please give yourself a name with /setname before attempting to connect.", errorColor); return false; } try { int test = std::stoi(elements[2]); } catch (std::exception &e) { chatBox.addChat("Command: /connect [IP Address] [Port]", errorColor); return false; } if (cliSocket.connect(elements[1], std::stoi(elements[2])) == sf::Socket::Done) { std::cout << "Connected to server " << elements[1] << std::endl; network::connectedServer = elements[1]; sf::Packet packet; packet << ident.connection << network::name; cliSocket.send(packet); packet.clear(); packet << ident.clientMouse << network::name << gvars::mousePos.x << gvars::mousePos.y; cliSocket.send(packet); packet.clear(); packet << ident.textMessage << network::name + randomWindowName(); cliSocket.send(packet); chatBox.addChat("Server: Connected to " + elements[1] + "(" + elements[2] + ")", goodColor); return true; } chatBox.addChat("Server: Something went wrong...", goodColor); return false; } else if(elements[0] == "/setname") { chatBox.addChat("Server: " + network::name + " has changed their name to " + elements[1], goodColor); network::name = elements[1]; if(elements[1] == "Lithi" || elements[1] == "Biocava" || elements[1] == "Sneaky" || elements[1] == "SneakySnake") chatBox.addChat("Server: Ooo, Ooo, I like you!", warmColor); if(elements[1] == "Argwm" || elements[1] == "Dehaku") chatBox.addChat("Server: Hey, that's my masters name!", warmColor); return true; } else if(elements[0] == "/repeat") { try { int test = std::stoi(elements[1]); } catch (std::exception &e) { chatBox.addChat("Invalid argument: " + elements[1] + " in command " + input, errorColor); chatBox.addChat("Command: /repeat [numberoftimes] [series of words or numbers]", errorColor); return false; } std::string repeatingLine; for(int i = 0; i != elements.size(); i++) { if(i != 0 && i != 1) { repeatingLine.append(elements[i] + " "); } } for(int i = 0; i != std::stoi(elements[1]); i++) { chatBox.addChat("Server: Repeating; " + repeatingLine, goodColor); } return true; } chatBox.addChat("Unrecognized command: " + input, errorColor); return false; } void ServerController::updateClients() { if((gvars::framesPassed % 30) == 0 && gvars::sendGrid) { /* Tile Updates */ sf::Packet pack; pack << ident.gridUpdate; for(int x = 0; x != GRIDS; x++) for(int y = 0; y != GRIDS; y++) for(int z = 0; z != CHUNK_SIZE; z++) { sf::Uint32 tileID = tiles[x][y][z].id; pack << tileID; } tcpSendtoAll(pack); } if((gvars::framesPassed % 30) == 0) { sf::Packet pack; sf::Clock myClock; sf::Time theTime = myClock.getElapsedTime(); sf::Uint32 sendTime = theTime.asMicroseconds(); pack << ident.ping << sendTime; tcpSendtoAll(pack); pack.clear(); pack << ident.peers; for(auto &i : peers.connected) { sf::Uint32 peerPing = i.ping; pack << i.name << peerPing; } tcpSendtoAll(pack); } if((gvars::framesPassed % 30) == 0) { sf::Packet pack; pack << ident.updateRoster; sf::Lock lock(mutex::npcList); for(auto &npc : npclist) { sf::Uint32 npcID = npc.id, npcXpos = npc.xpos, npcYpos = npc.ypos, npcZpos = npc.zpos; pack << npc.name << npcID << npcXpos << npcYpos << npcZpos << npc.bloodcontent; } tcpSendtoAll(pack); } if((gvars::framesPassed % 30) == 0) { sf::Packet pack; pack << ident.updateItems; sf::Lock lock(mutex::itemList); for(auto &item : worlditems) { sf::Uint32 itemID = item.id, itemXpos = item.xpos, itemYpos = item.ypos, itemZpos = item.zpos, itemProdrate = item.prodratetimer; pack << item.name << itemID << itemXpos << itemYpos << itemZpos << itemProdrate; } tcpSendtoAll(pack); } }
31.501256
180
0.45324
crumblingstatue
f07413236a6a881943dacab4e29821e19995c331
323
hpp
C++
src/RadialGrid/RadialGrid.hpp
rdietric/lsms
8d0d5f01186abf9a1cc54db3f97f9934b422cf92
[ "BSD-3-Clause" ]
28
2020-01-05T20:05:31.000Z
2022-03-07T09:08:01.000Z
src/RadialGrid/RadialGrid.hpp
rdietric/lsms
8d0d5f01186abf9a1cc54db3f97f9934b422cf92
[ "BSD-3-Clause" ]
8
2019-07-30T13:59:18.000Z
2022-03-31T17:43:35.000Z
lsms/src/RadialGrid/RadialGrid.hpp
hkershaw-brown/MuST
9db4bc5061c2f2c4d7dfd92f53b4ef952602c070
[ "BSD-3-Clause" ]
13
2020-02-11T17:04:45.000Z
2022-03-28T09:23:46.000Z
#ifndef LSMS_RGRID_H #define LSMS_RGRID_H #include <vector> #include "Real.hpp" class RadialGrid { public: inline RadialGrid() : N(0), jmt(0), jws(0), h(0.0) {} int N,jmt,jws; Real h; std::vector<Real> r_mesh,x_mesh; }; void generateRadialGrid(RadialGrid * g, Real x0, Real h, int N, int jmt, int jws); #endif
17.944444
82
0.674923
rdietric
7eb581ab465752104d52238a6737e197c1a6fefd
683
cc
C++
solutions/cpp/448-find-all-numbers-disappeared-in-an-array.cc
PW486/leetcode
c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9
[ "Unlicense" ]
null
null
null
solutions/cpp/448-find-all-numbers-disappeared-in-an-array.cc
PW486/leetcode
c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9
[ "Unlicense" ]
null
null
null
solutions/cpp/448-find-all-numbers-disappeared-in-an-array.cc
PW486/leetcode
c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9
[ "Unlicense" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> findDisappearedNumbers(vector<int> &nums) { vector<int> result; int len = nums.size(); for (int i = 0; i < len; i++) { int pos = abs(nums[i]) - 1; if (nums[pos] > 0) { nums[pos] = -nums[pos]; } } for (int i = 0; i < len; i++) { if (nums[i] > 0) result.push_back(i + 1); } return result; } }; int main() { vector<int> nums = {4, 3, 2, 7, 8, 2, 3, 1}; vector<int> result = Solution().findDisappearedNumbers(nums); for (int i = 0; i < result.size(); i++) { cout << result[i] << endl; } return 0; }
18.972222
63
0.524158
PW486
7eb8391219baa3aad813314e31142d86f4cf2224
1,176
cpp
C++
src/devices/video/WXGLDevice.cpp
SolarAquarion/ffmpegyag
bb77508afd7dd30b853ff8e56a9a062c01ca8237
[ "MIT" ]
12
2017-09-24T06:27:25.000Z
2022-02-02T09:40:38.000Z
src/devices/video/WXGLDevice.cpp
SolarAquarion/ffmpegyag
bb77508afd7dd30b853ff8e56a9a062c01ca8237
[ "MIT" ]
3
2017-09-24T06:34:06.000Z
2018-06-11T05:31:21.000Z
src/devices/video/WXGLDevice.cpp
SolarAquarion/ffmpegyag
bb77508afd7dd30b853ff8e56a9a062c01ca8237
[ "MIT" ]
4
2018-03-02T15:23:12.000Z
2019-06-05T12:07:13.000Z
#include "WXGLDevice.h" WXGLDevice::WXGLDevice() { widget = NULL; } WXGLDevice::~WXGLDevice() { // } void* WXGLDevice::CreateWidget(const char* title, int width, int height, bool fullscreen) { // TODO: create wxWidgets window return NULL; } void WXGLDevice::DestroyWidget(void* Widget) { Release(); wxWindow* tmp = (wxWindow*)Widget; if(tmp) { if(tmp == widget) { // internal widget is same as widget requested for destruction widget = NULL; } wxDELETE(tmp); tmp = NULL; //Widget = NULL; // statement has no effect, pointer only valid in local scope } } bool WXGLDevice::Init(void* Widget) { widget = (wxGLCanvas*)Widget; if(widget && widget->GetContext()) { return true; } widget = NULL; return false; } void WXGLDevice::Release() { // } void WXGLDevice::MakeCurrent() { if(widget && widget->GetContext()) { widget->SetCurrent(); } } void WXGLDevice::SwapBuffers() { widget->SwapBuffers(); // SwapBuffer has no negative effect on single buffering (can always be used) GLDevice::SwapBuffers(); }
18.092308
104
0.602891
SolarAquarion
7eb87aaedd0bb95200e6b68d928558a911803211
466
hpp
C++
srcs/game/components/LimitSide.hpp
BenjaminRepingon/Nibbler-MultiLib
71ae0b374346fef63ea5280f05722b185afa793a
[ "Apache-2.0" ]
null
null
null
srcs/game/components/LimitSide.hpp
BenjaminRepingon/Nibbler-MultiLib
71ae0b374346fef63ea5280f05722b185afa793a
[ "Apache-2.0" ]
null
null
null
srcs/game/components/LimitSide.hpp
BenjaminRepingon/Nibbler-MultiLib
71ae0b374346fef63ea5280f05722b185afa793a
[ "Apache-2.0" ]
null
null
null
#ifndef LIMITSIDE_HPP # define LIMITSIDE_HPP # include "../../core/AComponent.hpp" # include "../../utils/vec.hpp" class LimitSide : public AComponent { public: // LimitSide( void ); LimitSide( Vec2i const & a, Vec2i const & b); ~LimitSide( void ); LimitSide( LimitSide const & src ); LimitSide & operator=( LimitSide const & rhs ); virtual int update( ILib const * lib, double delta ); virtual int render( ILib const * lib ) const; }; #endif
22.190476
58
0.665236
BenjaminRepingon
7eb89fa94b69a80478d0a7c23f0facb0389627e5
363
cpp
C++
recursion/jumps.cpp
heysujal/Problem-Solving-in-cpp
b5e21bc467d57d3c2050776b948e7f59daabe945
[ "Unlicense" ]
1
2021-10-04T16:24:57.000Z
2021-10-04T16:24:57.000Z
recursion/jumps.cpp
heysujal/Problem-Solving-in-cpp
b5e21bc467d57d3c2050776b948e7f59daabe945
[ "Unlicense" ]
null
null
null
recursion/jumps.cpp
heysujal/Problem-Solving-in-cpp
b5e21bc467d57d3c2050776b948e7f59daabe945
[ "Unlicense" ]
1
2021-10-04T16:25:00.000Z
2021-10-04T16:25:00.000Z
// no of ways to reach n by only jumping 1, 2 or 3 steps at a time. #include <bits/stdc++.h> using namespace std; int jump_count(int n) { if (n < 0) return 0; if (n == 0) return 1; return jump_count(n - 1) + jump_count(n - 2) + jump_count(n - 3); } int main() { int n; cin >> n; cout << jump_count(n); return 0; }
15.125
69
0.5427
heysujal
7ebbf675263b8a48bc6ce5c9c43edda6c5720677
1,472
cpp
C++
CleaningService/main.cpp
KamranMackey/cplusplusprojects
1b42afa9b530098dcb9ada8b133c1351ab4c8155
[ "MIT" ]
null
null
null
CleaningService/main.cpp
KamranMackey/cplusplusprojects
1b42afa9b530098dcb9ada8b133c1351ab4c8155
[ "MIT" ]
null
null
null
CleaningService/main.cpp
KamranMackey/cplusplusprojects
1b42afa9b530098dcb9ada8b133c1351ab4c8155
[ "MIT" ]
null
null
null
#include <iostream> int main() { std::cout << "Hello there, welcome to the Cleaning Service!\n\n"; auto small_room_count{0}; std::cout << "Please enter the amount of small rooms you would like cleaned: "; std::cin >> small_room_count; auto large_room_count{0}; std::cout << "Please enter the amount of large rooms you would like cleaned: "; std::cin >> large_room_count; const auto small_room_price{25.0}; const auto large_room_price{35.0}; const auto sales_tax{0.06}; const auto estimate_expiry{30}; std::cout << "\nEstimate for Cleaning Service:\n"; std::cout << "Number of small rooms: " << small_room_count << "\n"; std::cout << "Number of large rooms: " << large_room_count << "\n"; std::cout << "Price per small room: $" << small_room_price << "\n"; std::cout << "Price per large room: $" << large_room_price << "\n"; const auto small_room_total{small_room_price * small_room_count}; const auto large_room_total{large_room_price * large_room_count}; const auto total_cost{small_room_total + large_room_total}; std::cout << "Total Cost: $" << total_cost << "\n"; const auto total_tax{total_cost * sales_tax}; std::cout << "Total Tax: $" << total_tax << "\n"; std::cout << "\n==============================================\n"; const auto total_estimate{total_cost + total_tax}; std::cout << "Total estimate: $" << total_estimate << "\n"; std::cout << "This estimate is valid for " << estimate_expiry << " days." << "\n"; return 0; }
38.736842
83
0.658967
KamranMackey
7ebd99138b259d93d69fc7793560b665a749cdb6
374
cpp
C++
source/code/RigorPhysics/AABBox.cpp
AdamWallberg/RigorPhysics
85da20dbf1f1990f703e2be687b65987fc48386f
[ "MIT" ]
null
null
null
source/code/RigorPhysics/AABBox.cpp
AdamWallberg/RigorPhysics
85da20dbf1f1990f703e2be687b65987fc48386f
[ "MIT" ]
null
null
null
source/code/RigorPhysics/AABBox.cpp
AdamWallberg/RigorPhysics
85da20dbf1f1990f703e2be687b65987fc48386f
[ "MIT" ]
null
null
null
#include "AABBox.h" namespace rg { AABBox::AABBox() : min(ZeroVector) , max(ZeroVector) { } AABBox::AABBox(Vector3 min, Vector3 max) : min(min) , max(max) { } bool AABBox::inside(const Vector3& position) const { return position.x >= min.x && position.x <= max.x && position.y >= min.y && position.y <= max.y && position.z >= min.z && position.z <= max.z; } }
14.384615
50
0.620321
AdamWallberg
7ebdb1bf448696ebfb075de4a3ece125b9b5eb6a
394
cpp
C++
codeforces/round-294/div-2/a_and_b_and_team_training.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
codeforces/round-294/div-2/a_and_b_and_team_training.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
codeforces/round-294/div-2/a_and_b_and_team_training.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <algorithm> #include <iostream> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int experienced; unsigned int newbies; cin >> experienced >> newbies; cout << min({(experienced + newbies) / 3, experienced, newbies}) << '\n'; return 0; }
15.153846
77
0.65736
Rkhoiwal
7ec4d9509feb5da68609c9181629b63d62a508f6
1,361
hpp
C++
modules/memory/include/shard/memory/allocators/proxy_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/memory/include/shard/memory/allocators/proxy_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
modules/memory/include/shard/memory/allocators/proxy_allocator.hpp
ikimol/shard
72a72dbebfd247d2b7b300136c489672960b37d8
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Miklos Molnar. All rights reserved. #ifndef SHARD_MEMORY_PROXY_ALLOCATOR_HPP #define SHARD_MEMORY_PROXY_ALLOCATOR_HPP #include "shard/memory/allocator.hpp" namespace shard { namespace memory { class proxy_allocator : public allocator { public: explicit proxy_allocator(allocator& a, const char* name = "") : allocator(a.size()), m_allocator(a), m_name(name) {} void* allocate(std::size_t size, std::size_t align) override { assert(size != 0); ++m_allocation_count; auto used = m_allocator.used_memory(); auto ptr = m_allocator.allocate(size, align); // calculate the actual size of the allocation, because an allocation // might allocate more memory than requested m_used_memory += m_allocator.used_memory() - used; return ptr; } void deallocate(void* ptr) override { assert(ptr); --m_allocation_count; auto used = m_allocator.used_memory(); m_allocator.deallocate(ptr); m_used_memory -= used - m_allocator.used_memory(); } const char* name() const { return m_name; } private: allocator& m_allocator; const char* m_name = nullptr; }; } // namespace memory // bring symbols into parent namespace using memory::proxy_allocator; } // namespace shard #endif // SHARD_MEMORY_PROXY_ALLOCATOR_HPP
27.22
120
0.685525
ikimol
7eca9af2de615d15fc20145673768b53402310d4
1,182
cpp
C++
SYCL/ESIMD/api/simd_view_select_2d_fp.cpp
abuyukku/llvm-test-suite
b10bd8e733519ae0e365fc097d36a32bc1d53d62
[ "Apache-2.0" ]
null
null
null
SYCL/ESIMD/api/simd_view_select_2d_fp.cpp
abuyukku/llvm-test-suite
b10bd8e733519ae0e365fc097d36a32bc1d53d62
[ "Apache-2.0" ]
null
null
null
SYCL/ESIMD/api/simd_view_select_2d_fp.cpp
abuyukku/llvm-test-suite
b10bd8e733519ae0e365fc097d36a32bc1d53d62
[ "Apache-2.0" ]
null
null
null
//==------- simd_view_select_2d_fp.cpp - DPC++ ESIMD on-device test -------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // REQUIRES: gpu // UNSUPPORTED: cuda || hip // TODO: esimd_emulator fails due to unimplemented 'single_task()' method // XFAIL: esimd_emulator // RUN: %clangxx -fsycl %s -fsycl-device-code-split=per_kernel -o %t.out // RUN: %GPU_RUN_PLACEHOLDER %t.out // // Smoke test for 2D region select API which can be used to represent 2D tiles. // Tests FP types. #include "simd_view_select_2d.hpp" int main(int argc, char **argv) { queue q(esimd_test::ESIMDSelector{}, esimd_test::createExceptionHandler()); auto dev = q.get_device(); std::cout << "Running on " << dev.get_info<info::device::name>() << "\n"; bool passed = true; passed &= test<half>(q); passed &= test<float>(q); passed &= test<double>(q); std::cout << (passed ? "=== Test passed\n" : "=== Test FAILED\n"); return passed ? 0 : 1; }
35.818182
80
0.624365
abuyukku
7ed312ce24f292fc67bf7e568395df052560d8ae
4,291
cpp
C++
src/selectappdialog.cpp
FinchX/loli_profiler
9391bb82fd0a26c5855770974ae886f42daf4266
[ "BSD-2-Clause" ]
388
2021-03-11T04:20:19.000Z
2022-03-29T05:55:07.000Z
src/selectappdialog.cpp
habbyge/loli_profiler
fc5700acd5ee034698da2fff1189e58873721711
[ "BSD-2-Clause" ]
23
2021-03-24T06:38:29.000Z
2022-03-30T06:17:17.000Z
src/selectappdialog.cpp
habbyge/loli_profiler
fc5700acd5ee034698da2fff1189e58873721711
[ "BSD-2-Clause" ]
44
2021-03-11T06:27:02.000Z
2022-03-28T03:58:09.000Z
#include "selectappdialog.h" #include <QVBoxLayout> #include <QListWidget> #include <QKeyEvent> ArrowLineEdit::ArrowLineEdit(QListWidget* listView, QWidget *parent) : QLineEdit(parent), listView_(listView) { connect(this, &QLineEdit::textChanged, this, &ArrowLineEdit::onTextChanged); } void ArrowLineEdit::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Up || event->key() == Qt::Key_Down) { auto selectedItems = listView_->selectedItems(); QListWidgetItem* item = nullptr; if (selectedItems.count() > 0) { auto currentRow = listView_->row(selectedItems[0]); if (event->key() == Qt::Key_Down) { while (currentRow + 1 < listView_->count()) { currentRow++; auto curItem = listView_->item(currentRow); if (!curItem->isHidden()) { item = curItem; break; } } } else { while (currentRow - 1 >= 0) { currentRow--; auto curItem = listView_->item(currentRow); if (!curItem->isHidden()) { item = curItem; break; } } } } if (item) listView_->setCurrentItem(item); } else if (event->key() == Qt::Key_Right) { auto selectedItems = listView_->selectedItems(); if (selectedItems.count() > 0) { setText(selectedItems[0]->text()); } } else { QLineEdit::keyPressEvent(event); } } void ArrowLineEdit::onTextChanged(const QString& text) { // Use regular expression to search fuzzily // "Hello\n" -> ".*H.*e.*l.*l.*o.*\\.*n" QString pattern; for (auto i = 0; i < text.size(); i++) { pattern += QRegularExpression::escape(text[i]); if (i != text.size() - 1) pattern += ".*"; } QRegularExpression re(pattern, QRegularExpression::CaseInsensitiveOption); auto first = true; for (int i = 0; i < listView_->count(); ++i) { auto item = listView_->item(i); if (item->text().contains(re)) { item->setHidden(false); item->setSelected(first); first = false; } else { item->setHidden(true); item->setSelected(false); } } } SelectAppDialog::SelectAppDialog(QWidget *parent , Qt::WindowFlags f) : QDialog(parent, f) { auto layout = new QVBoxLayout(); layout->setMargin(2); layout->setSpacing(2); listWidget_ = new QListWidget(); listWidget_->setSelectionMode(QListWidget::SelectionMode::SingleSelection); auto hbLayout = new QHBoxLayout(); searchLineEdit_ = new ArrowLineEdit(listWidget_); connect(searchLineEdit_, &QLineEdit::returnPressed, [this]() { auto selected = listWidget_->selectedItems(); if (selected.count() > 0 && callback_) callback_(selected[0]->text(), subProcessNameLineEdit_->text()); close(); }); connect(listWidget_, &QListWidget::itemClicked, [this](QListWidgetItem *item) { callback_(item->text(), subProcessNameLineEdit_->text()); close(); }); subProcessNameLineEdit_ = new QLineEdit(); subProcessNameLineEdit_->setPlaceholderText("subProcessName"); hbLayout->addWidget(searchLineEdit_); hbLayout->addWidget(subProcessNameLineEdit_); hbLayout->setStretchFactor(searchLineEdit_, 2); hbLayout->setStretchFactor(subProcessNameLineEdit_, 1); layout->addLayout(hbLayout); layout->addWidget(listWidget_); searchLineEdit_->setFocus(); setLayout(layout); setWindowModality(Qt::WindowModal); setWindowTitle("Selection Application"); setMinimumSize(400, 300); resize(400, 300); } void SelectAppDialog::SelectApp(QStringList apps, std::function<void(const QString&, const QString&)> outCallback) { listWidget_->clear(); for (auto& app : apps) { auto lineParts = app.split(':'); if (lineParts.count() > 1) { listWidget_->addItem(lineParts[1].trimmed()); } } listWidget_->setCurrentItem(listWidget_->item(0)); callback_ = outCallback; }
35.172131
116
0.582149
FinchX
7ed9f7f322642e5063a174aea77f62f59d93c87f
9,515
cpp
C++
test/inventory_test.cpp
YADRO-KNS/obmc-yadro-lsinventory
2b52c92669d35500d3ad2f0c656dab5c9bec1625
[ "Apache-2.0" ]
null
null
null
test/inventory_test.cpp
YADRO-KNS/obmc-yadro-lsinventory
2b52c92669d35500d3ad2f0c656dab5c9bec1625
[ "Apache-2.0" ]
2
2020-04-22T07:32:25.000Z
2022-03-10T09:40:32.000Z
test/inventory_test.cpp
YADRO-KNS/obmc-yadro-lsinventory
2b52c92669d35500d3ad2f0c656dab5c9bec1625
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 // Copyright (C) 2020 YADRO #include "inventory.hpp" #include <sdbusplus/test/sdbus_mock.hpp> using ::testing::_; using ::testing::Invoke; using ::testing::Return; using ::testing::StrEq; /** * class InventoryTest * @brief Inventory tests. */ class InventoryTest : public ::testing::Test { protected: InventoryTest() : bus(sdbusplus::get_mocked_new(&mock)) {} testing::NiceMock<sdbusplus::SdBusMock> mock; sdbusplus::bus::bus bus; }; TEST_F(InventoryTest, EmptyList) { EXPECT_CALL(mock, sd_bus_message_at_end).WillRepeatedly(Return(1)); std::vector<InventoryItem> inventory = getInventory(bus); EXPECT_TRUE(inventory.empty()); } TEST_F(InventoryTest, FullList) { // clang-format off // ordered list of inventory items const char* orderedNames[] = { "cpu0", "cpu0/core0", "cpu0/core1", "cpu0/core5", "cpu0/core10", "cpu5", "cpu10", }; // unordered list of D-Bus objects const char* dbusPaths[] = { "/xyz/openbmc_project/inventory/system/chassis/cpu0/core1", "/xyz/openbmc_project/inventory/system/chassis/cpu10", "/xyz/openbmc_project/inventory/system/chassis/cpu0", "/xyz/openbmc_project/inventory/system/chassis/cpu0/core5", "/xyz/openbmc_project/inventory/system/chassis/cpu5", "/xyz/openbmc_project/inventory/system/chassis/cpu0/core10", "/xyz/openbmc_project/inventory/system/chassis/cpu0/core0", }; // clang-format on const size_t itemsCount = sizeof(orderedNames) / sizeof(orderedNames[0]); static_assert(itemsCount == sizeof(dbusPaths) / sizeof(dbusPaths[0])); // returns "end-of-array" flag, callback for "GetSubTree", // we need only object's path, so set "end-of-array" for every second call, // because GetSubTree wants map<string, map<string, vector<string>>> size_t counter = 0; EXPECT_CALL(mock, sd_bus_message_at_end) .WillRepeatedly(Invoke([&](sd_bus_message*, int) { const size_t index = counter / 2; const bool hasData = counter % 2 == 0 && index < itemsCount; ++counter; return hasData ? 0 : 1; })); // returns D-Bus object path, callback for "GetSubTree" size_t index = 0; EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillRepeatedly(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = index < itemsCount ? dbusPaths[index] : "<ERR>"; ++index; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), itemsCount); for (size_t i = 0; i < itemsCount; ++i) { const InventoryItem& item = inventory[i]; EXPECT_EQ(item.name, orderedNames[i]); EXPECT_TRUE(item.properties.empty()); EXPECT_TRUE(item.prettyName().empty()); EXPECT_TRUE(item.isPresent()); } } TEST_F(InventoryTest, BooleanProperty) { const char* key = "BooleanProperty"; const bool val = true; EXPECT_CALL(mock, sd_bus_message_at_end) .WillOnce(Return(0)) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetSubTree const char** s = static_cast<const char**>(p); *s = "/xyz/openbmc_project/inventory/dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = "xyz.openbmc_project.dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property name) const char** s = static_cast<const char**>(p); *s = key; return 0; })); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("s"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("x"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("t"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("u"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("q"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("y"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("b"))) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 'b', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { *static_cast<char*>(p) = val; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), 1); const InventoryItem& item = inventory[0]; EXPECT_EQ(item.properties.size(), 1); ASSERT_NE(item.properties.find(key), item.properties.end()); const auto& chkVal = item.properties.find(key)->second; ASSERT_TRUE(std::holds_alternative<bool>(chkVal)); EXPECT_EQ(std::get<bool>(chkVal), val); } TEST_F(InventoryTest, NumericProperty) { const char* key = "NumericProperty"; const int64_t val = 42; EXPECT_CALL(mock, sd_bus_message_at_end) .WillOnce(Return(0)) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetSubTree const char** s = static_cast<const char**>(p); *s = "/xyz/openbmc_project/inventory/dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = "xyz.openbmc_project.dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property name) const char** s = static_cast<const char**>(p); *s = key; return 0; })); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("x"))) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 'x', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { *static_cast<int64_t*>(p) = val; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), 1); const InventoryItem& item = inventory[0]; EXPECT_EQ(item.properties.size(), 1); ASSERT_NE(item.properties.find(key), item.properties.end()); const auto& chkVal = item.properties.find(key)->second; ASSERT_TRUE(std::holds_alternative<int64_t>(chkVal)); EXPECT_EQ(std::get<int64_t>(chkVal), val); } TEST_F(InventoryTest, StringProperty) { const char* key = "PrettyName"; const char* val = "Object pretty name \t \r\n "; const char* valResult = "Object pretty name"; EXPECT_CALL(mock, sd_bus_message_at_end) .WillOnce(Return(0)) .WillOnce(Return(0)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(1)) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("x"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("t"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("u"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("q"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("y"))) .WillOnce(Return(0)); EXPECT_CALL(mock, sd_bus_message_verify_type(_, 'v', StrEq("s"))) .WillOnce(Return(1)); EXPECT_CALL(mock, sd_bus_message_read_basic(_, 's', _)) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetSubTree const char** s = static_cast<const char**>(p); *s = "/xyz/openbmc_project/inventory/dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { const char** s = static_cast<const char**>(p); *s = "xyz.openbmc_project.dummy"; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property name) const char** s = static_cast<const char**>(p); *s = key; return 0; })) .WillOnce(Invoke([&](sd_bus_message*, char, void* p) { // callback for GetAll (property value) const char** s = static_cast<const char**>(p); *s = val; return 0; })); std::vector<InventoryItem> inventory = getInventory(bus); ASSERT_EQ(inventory.size(), 1); const InventoryItem& item = inventory[0]; EXPECT_EQ(item.properties.size(), 1); EXPECT_EQ(item.prettyName(), valResult); }
35.240741
79
0.601051
YADRO-KNS
7ee266dec2493da56f8108fd80c43a5700ff351d
397
cpp
C++
BeginnerLevel/Puppy_and_Sum.cpp
AkashKumarSingh11032001/CodeChef-Beginner-To-Medium
5c4a55b909ba90976099cb81374a8cecb4c3ead3
[ "MIT" ]
1
2021-05-05T04:50:26.000Z
2021-05-05T04:50:26.000Z
BeginnerLevel/Puppy_and_Sum.cpp
AkashKumarSingh11032001/CodeChef-Beginner-To-Medium
5c4a55b909ba90976099cb81374a8cecb4c3ead3
[ "MIT" ]
null
null
null
BeginnerLevel/Puppy_and_Sum.cpp
AkashKumarSingh11032001/CodeChef-Beginner-To-Medium
5c4a55b909ba90976099cb81374a8cecb4c3ead3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int sum_l(int d, int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } if (d == 1) return sum; else return sum_l(d - 1, sum); } int main() { int T; cin >> T; int d, n; while (T--) { /* code */ cin >> d >> n; cout << sum_l(d, n) << endl; } }
13.233333
36
0.387909
AkashKumarSingh11032001
7ee2bf9dc25225b64833301e070299f46c913d02
8,700
cpp
C++
test-src/suite.cpp
cslauritsen/cslhomie
e30bca41406099233e877b44186124f337a78f0b
[ "MIT" ]
null
null
null
test-src/suite.cpp
cslauritsen/cslhomie
e30bca41406099233e877b44186124f337a78f0b
[ "MIT" ]
null
null
null
test-src/suite.cpp
cslauritsen/cslhomie
e30bca41406099233e877b44186124f337a78f0b
[ "MIT" ]
null
null
null
#include "homie.hpp" #include <algorithm> #include <gtest/gtest.h> #include <list> #include <string> using Msg = homie::Message; class TestDevice : public homie::Device { public: TestDevice() : homie::Device("testdevice", "1.0", "TestDevice") { extensions.push_back("com.planetlauritsen.test:0.0.1:[4.x]"); } std::list<homie::Message> publications; int rssi = -58; int getRssi() override { return rssi; } std::vector<std::string> getExtensions() { return extensions; } protected: void publish(homie::Message m) override { std::cerr << "publishing to " << m.topic << std::endl; publications.push_back(m); } }; class PropertyTest : public ::testing::Test { protected: void SetUp() override { d = new TestDevice(); n = new homie::Node(d, "node1", "Node1", "generic"); p = new homie::Property(n, "prop1", "Prop1", homie::INTEGER, isWritable(), []() { return "s1"; }); p->setWriterFunc([this](std::string s) { this->capture.push_back(s); }); } void TearDown() override { delete d; } virtual bool isWritable() { return false; } TestDevice *d; homie::Node *n; homie::Property *p; std::list<std::string> capture; }; class WritablePropertyTest : public PropertyTest { protected: bool isWritable() override { return true; } }; TEST(HomieSuite, ToFahrenheit) { EXPECT_FLOAT_EQ(homie::to_fahrenheit(28.0), 82.4); } TEST(HomieSuite, formatMac) { EXPECT_EQ("aa:bb:cc:dd:ee:ff", homie::formatMac("aabb:ccdd:eeff")); } TEST(HomieSuite, bool_to_string) { EXPECT_EQ("false", homie::to_string(false)); EXPECT_EQ("true", homie::to_string(true)); } TEST(HomieSuite, splitString) { std::vector<std::string> res; homie::split_string("a/b/c", "/", res); EXPECT_EQ(3, res.size()); EXPECT_EQ("a", res[0]); EXPECT_EQ("b", res[1]); EXPECT_EQ("c", res[2]); } TEST(HomieSuite, f2s) { float f = 1.22222; auto x = homie::f2s(f); ASSERT_EQ("1.2", x) << f << " % %.1f => 100"; } TEST_F(WritablePropertyTest, NodeIsPresent) { EXPECT_TRUE(d->getNode("node1") == n); } TEST_F(PropertyTest, PropertyIsPresent) { EXPECT_TRUE(n->getProperty("prop1") == p); } TEST_F(PropertyTest, PropertyIsRead) { EXPECT_FALSE(p->isSettable()); EXPECT_EQ("s1", p->read()); } TEST_F(WritablePropertyTest, WritablePropertyWritesValue) { EXPECT_TRUE(p->isSettable()); EXPECT_EQ("s1", p->read()); EXPECT_EQ(1, capture.size()) << "Captured writes should have 1 member from read()"; p->setValue("wooga"); EXPECT_EQ(2, capture.size()) << "Captured writes should have 2 members after setValue()"; auto iter = capture.begin(); EXPECT_EQ("s1", *iter++) << "Captured writes first member should be from read()"; EXPECT_EQ("wooga", *iter++) << "Capture writes second member should be from setValue()"; } TEST_F(PropertyTest, NonWritablePropertyIgnoresWriterFunc) { EXPECT_FALSE(p->isSettable()); EXPECT_EQ("s1", p->read()); EXPECT_EQ(0, this->capture.size()) << "Captured writes list should be empty"; p->setValue("wooga"); EXPECT_EQ(0, this->capture.size()) << "Captured writes list should be empty, even after setValue()"; auto iter = this->capture.begin(); EXPECT_EQ(iter, this->capture.end()) << "Captured writes list should not iterate"; } TEST_F(PropertyTest, PropertyPublish) { p->publish(); EXPECT_EQ(1, d->publications.size()) << "Publication count should be " << 1; } TEST_F(PropertyTest, PropertyIntroduce) { p->introduce(); EXPECT_GT(d->publications.size(), 3) << "After introduction, publication count should be > 3"; } TEST_F(PropertyTest, PropertyIntroduceUnit) { p->setUnit("jigawatts"); p->introduce(); auto count = std::count_if( d->publications.begin(), d->publications.end(), [](homie::Message m) { return m.topic.find("$unit") != std::string::npos; }); EXPECT_EQ(1, count) << "There should be one and only one $unit topic emitted."; } TEST_F(PropertyTest, PropertyIntroduceFormat) { p->setFormat("1:9"); p->introduce(); auto l = d->publications; auto count = std::count_if(l.begin(), l.end(), [](Msg m) { return m.topic.find("$format") != std::string::npos; }); EXPECT_EQ(1, count) << "There should be one and only one $format topic emitted."; auto count2 = std::count_if(l.begin(), l.end(), [](Msg m) { return m.payload == "1:9"; }); EXPECT_EQ(1, count2) << "There should be one and only one $format payload emitted."; } TEST_F(PropertyTest, NodePropertyNotFound) { EXPECT_EQ(nullptr, n->getProperty("wooga")) << "Nonexistent property should return nullptr"; } TEST_F(PropertyTest, NodeSinglePropertyIntroduction) { n->introduce(); auto count = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.topic.find("$properties") != std::string::npos; }); auto count2 = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.payload.find(",") != std::string::npos; }); EXPECT_EQ(1, count) << "only one $properties message should be published"; EXPECT_EQ(0, count2) << "no commas in single properties"; } TEST_F(PropertyTest, NodeMultiplePropertyIntroduction) { new homie::Property(n, "prop2", "Prop2", homie::INTEGER, isWritable(), []() { return "s2"; }); n->introduce(); auto count = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.topic.find("$properties") != std::string::npos; }); auto count2 = std::count_if(d->publications.begin(), d->publications.end(), [](Msg m) { return m.payload.find(",") != std::string::npos; }); EXPECT_EQ(1, count) << "only one $properties message should be published"; EXPECT_EQ(1, count2) << "single comma in properties"; } TEST_F(PropertyTest, WifiSignalStrength) { d->rssi = -100; EXPECT_EQ(0, d->getWifiSignalStrength()); d->rssi = -49; EXPECT_EQ(100, d->getWifiSignalStrength()); d->rssi = -58; EXPECT_EQ(84, d->getWifiSignalStrength()); d->introduce(); } TEST_F(PropertyTest, PublishWifi) { d->rssi = -49; // -> signal strength "100" d->publishWifi(); EXPECT_EQ(1, std::count_if(d->publications.begin(), d->publications.end(), [this](Msg m) { return m.topic.find(homie::PROP_NM_RSSI) != std::string::npos && m.payload == std::to_string(this->d->rssi); })); EXPECT_EQ(1, std::count_if( d->publications.begin(), d->publications.end(), [](Msg m) { return m.topic.find("/signal") != std::string::npos && m.payload == "100"; })); } TEST_F(PropertyTest, PublishLocalIp) { d->setLocalIp("1.2.3.4"); d->introduce(); EXPECT_EQ(1, std::count_if(d->publications.begin(), d->publications.end(), [this](Msg m) { return m.topic.find("/localip") != std::string::npos && m.payload == this->d->getLocalIp(); })); } TEST_F(PropertyTest, PublishMac) { d->setMac("fe:ed:fa:ce:de:ad"); d->introduce(); EXPECT_EQ(1, std::count_if(d->publications.begin(), d->publications.end(), [this](Msg m) { return m.topic.find("/mac") != std::string::npos && m.payload == this->d->getMac(); })); } TEST_F(WritablePropertyTest, CheckSubTopic) { EXPECT_EQ(p->getPubTopic() + "/set", p->getSubTopic()); } TEST_F(PropertyTest, CheckMissingNodeReturnsNullPtr) { EXPECT_EQ(nullptr, d->getNode("fjdfkdlkff0dfj00-0l")); } TEST_F(PropertyTest, CheckLwtIsLost) { EXPECT_EQ("lost", d->getLwt().payload); } TEST_F(WritablePropertyTest, CheckInputMessage) { auto inputMsg = Msg("homie/" + d->getId() + "/" + n->getId() + "/" + p->getId() + "/set", "awesome new value"); d->onMessage(inputMsg); EXPECT_EQ(inputMsg.payload, p->getValue()); } TEST_F(PropertyTest, InputMessageIgnoredForNonWritableProperty) { auto inputMsg = Msg("homie/" + d->getId() + "/" + n->getId() + "/" + p->getId() + "/set", "woo-hoo"); p->setValue("previous"); d->onMessage(inputMsg); EXPECT_EQ("previous", p->getValue()); } TEST_F(PropertyTest, CheckExtensions) { EXPECT_EQ(2, d->getExtensions().size()); }
32.103321
80
0.595287
cslauritsen
7ee43efa331193d3f74507e4f2181196fe53e5b3
2,877
cpp
C++
Chapter07/Exercise7.01/EnemyCharacter.cpp
rutuja027/Game-Development-Projects-with-Unreal-Engine
e165ebd9404c76b9bdffa38d040dc640ba9b79ed
[ "MIT" ]
41
2020-11-14T07:18:27.000Z
2022-03-28T13:42:02.000Z
Chapter07/Exercise7.01/EnemyCharacter.cpp
fghaddar/Game-Development-Projects-with-Unreal-Engine
79a987c01dd672b6e8b95bdd15f1d17380044bf8
[ "MIT" ]
null
null
null
Chapter07/Exercise7.01/EnemyCharacter.cpp
fghaddar/Game-Development-Projects-with-Unreal-Engine
79a987c01dd672b6e8b95bdd15f1d17380044bf8
[ "MIT" ]
23
2021-01-20T07:05:38.000Z
2022-03-15T05:25:54.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "EnemyCharacter.h" #include "Engine/World.h" #include "Kismet/KismetMathLibrary.h" #include "Kismet/GameplayStatics.h" #include "TimerManager.h" #include "DodgeballProjectile.h" #include "DodgeballFunctionLibrary.h" #include "GameFramework/ProjectileMovementComponent.h" // Sets default values AEnemyCharacter::AEnemyCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SightSource = CreateDefaultSubobject<USceneComponent>(TEXT("Sight Source")); SightSource->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void AEnemyCharacter::BeginPlay() { Super::BeginPlay(); } // Called every frame void AEnemyCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Fetch the character currently being controlled by the player ACharacter* PlayerCharacter = UGameplayStatics::GetPlayerCharacter(this, 0); // Look at the player character every frame bCanSeePlayer = LookAtActor(PlayerCharacter); if (bCanSeePlayer != bPreviousCanSeePlayer) { if (bCanSeePlayer) { //Start throwing dodgeballs GetWorldTimerManager().SetTimer(ThrowTimerHandle, this, &AEnemyCharacter::ThrowDodgeball, ThrowingInterval, true, ThrowingDelay); } else { //Stop throwing dodgeballs GetWorldTimerManager().ClearTimer(ThrowTimerHandle); } } bPreviousCanSeePlayer = bCanSeePlayer; } bool AEnemyCharacter::LookAtActor(const AActor * TargetActor) { if (TargetActor == nullptr) return false; const TArray<const AActor*> IgnoreActors = { this, TargetActor }; if (UDodgeballFunctionLibrary::CanSeeActor(GetWorld(), SightSource->GetComponentLocation(), TargetActor, IgnoreActors)) { FVector Start = GetActorLocation(); FVector End = TargetActor->GetActorLocation(); // Calculate the necessary rotation for the Start point to face the End point FRotator LookAtRotation = UKismetMathLibrary::FindLookAtRotation(Start, End); //Set the enemy's rotation to that rotation SetActorRotation(LookAtRotation); return true; } return false; } void AEnemyCharacter::ThrowDodgeball() { if (DodgeballClass == nullptr) { return; } FVector ForwardVector = GetActorForwardVector(); float SpawnDistance = 40.f; FVector SpawnLocation = GetActorLocation() + (ForwardVector * SpawnDistance); FTransform SpawnTransform(GetActorRotation(), SpawnLocation); //Spawn new dodgeball ADodgeballProjectile* Projectile = GetWorld()->SpawnActorDeferred<ADodgeballProjectile>(DodgeballClass, SpawnTransform); Projectile->GetProjectileMovementComponent()->InitialSpeed = 2200.f; Projectile->FinishSpawning(SpawnTransform); }
27.4
121
0.748349
rutuja027
7ee7df3da333a5477cdb0454d3dcc4f4274c090f
1,493
cc
C++
fundamental/array/binary_search/binary_search.cc
geek-yang/Algorism
fc1fa544b0a21459808797cdc9287b9c6b8f5358
[ "Apache-2.0" ]
null
null
null
fundamental/array/binary_search/binary_search.cc
geek-yang/Algorism
fc1fa544b0a21459808797cdc9287b9c6b8f5358
[ "Apache-2.0" ]
null
null
null
fundamental/array/binary_search/binary_search.cc
geek-yang/Algorism
fc1fa544b0a21459808797cdc9287b9c6b8f5358
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { /* Solution for leetcode question 704. For binary search, it is a must that the given input array is sorted in ascending order and there is no repeated element. */ public: int binary_search(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; while (left <= right) { int middle = left + (right - left) / 2; if (nums[middle] > target) { right = middle - 1; } else if (nums[middle] < target) { left = middle + 1; } else { return middle; } } return -1; } void vector_print(vector<int>& nums, int size){ for (int i = 0; i < size; i++){ std::cout << nums[i] << ' '; } std::cout << "\n" << std::endl; } }; int main() { // first checker vector<int> nums {-1,0,3,5,9,12}; int target = 9; Solution solution; std::cout << "First test.\n"; std::cout << "Test data.\n"; solution.vector_print(nums, nums.size()); int result; result = solution.binary_search(nums, target); std::cout << "Output:" << result << "\n"; std::cout << "------------------------------\n"; // second checker target = 2; std::cout << "Second test.\n"; std::cout << "Output.\n"; result = solution.binary_search(nums, target); std::cout << "Output:" << result << "\n"; }
24.080645
54
0.513731
geek-yang
7ee82e3d0bdce9fd102a134ea79eba859025b141
2,297
cpp
C++
DXMPP/SASL/SASLMechanism.cpp
synergysky/dxmpp
8bd741993ee8cded5bfbc8cc739e7c7a81b3f203
[ "BSL-1.0" ]
17
2015-02-09T05:18:11.000Z
2021-10-10T04:13:11.000Z
DXMPP/SASL/SASLMechanism.cpp
synergysky/dxmpp
8bd741993ee8cded5bfbc8cc739e7c7a81b3f203
[ "BSL-1.0" ]
4
2017-04-07T13:55:10.000Z
2019-06-10T09:56:47.000Z
DXMPP/SASL/SASLMechanism.cpp
synergysky/dxmpp
8bd741993ee8cded5bfbc8cc739e7c7a81b3f203
[ "BSL-1.0" ]
24
2015-03-20T06:57:27.000Z
2020-06-18T15:29:22.000Z
// // SASLMechanism.cpp // DXMPP // // Created by Stefan Karlsson 2014 // Copyright (c) 2014 Deus ex Machinae. All rights reserved. // #include <DXMPP/SASL/SASLMechanism.hpp> #include <pugixml/pugixml.hpp> #include <DXMPP/JID.hpp> #include <boost/function.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/thread.hpp> #include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include <boost/array.hpp> #include <boost/algorithm/string.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/binary_from_base64.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/remove_whitespace.hpp> #include <cryptopp/cryptlib.h> #include <cryptopp/hex.h> #include <cryptopp/hmac.h> #include <cryptopp/sha.h> #include <cryptopp/base64.h> #include <cryptopp/queue.h> #include <sstream> #include <ostream> #include <iostream> #include "SaslChallengeParser.hpp" namespace DXMPP { namespace SASL { using namespace std; using namespace boost::asio::ip; using namespace boost::asio; using namespace pugi; using namespace boost::archive::iterators; typedef transform_width< binary_from_base64<remove_whitespace<string::const_iterator> >, 8, 6 > Base64Decode; typedef base64_from_binary<transform_width<string::const_iterator,6,8> > Base64Encode; string SASLMechanism::DecodeBase64(string Input) { unsigned int paddChars = count(Input.begin(), Input.end(), '='); std::replace(Input.begin(),Input.end(),'=','A'); string result(Base64Decode(Input.begin()), Base64Decode(Input.end())); result.erase(result.end()-paddChars,result.end()); return result; } string SASLMechanism::EncodeBase64(string Input) { unsigned int writePaddChars = (3-Input.length()%3)%3; string base64(Base64Encode(Input.begin()),Base64Encode(Input.end())); base64.append(writePaddChars,'='); return base64; } } }
30.223684
117
0.685677
synergysky
7eeb4e4e379d0b1a0d7ea46f9dd55e0a5bd079f2
2,070
hh
C++
construct/CSGNode.i.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
construct/CSGNode.i.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
construct/CSGNode.i.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
//---------------------------------*-C++-*-----------------------------------// /*! * \file construct/CSGNode.i.hh * \brief CSGNode inline method definitions * \note Copyright (c) 2021 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #pragma once namespace celeritas { //---------------------------------------------------------------------------// /*! * Construct a leaf (single surface) */ CSGNode::CSGNode(SurfaceId id) : type_(NodeType::leaf_surface), id_(id.get()) { CELER_ENSURE(this->is_surface()); } //---------------------------------------------------------------------------// /*! * Construct a node (single surface) */ CSGNode::CSGNode(Daughter daughter) : CSGNode({daughter}, CSGCell::LOGIC_AND) { CELER_ENSURE(!this->is_leaf()); } //---------------------------------------------------------------------------// /*! * \brief Surface ID */ auto CSGNode::surface_id() const -> SurfaceId { CELER_EXPECT(this->is_leaf()); return SurfaceId{id_}; } //---------------------------------------------------------------------------// /*! * \brief The daughter elements if this is a node */ auto CSGNode::daughters() const -> const VecDaughter& { CELER_EXPECT(!this->is_leaf()); return daughters_; } //---------------------------------------------------------------------------// /*! * \brief The conjunction type if this is a node */ auto CSGNode::conjunction() const -> CSGLogicToken { CELER_EXPECT(!this->is_leaf()); return (type_ == NodeType::node_and ? CSGCell::LOGIC_AND : CSGCell::LOGIC_OR); } //---------------------------------------------------------------------------// /*! * \brief Equality with another CSG node. */ bool CSGNode::operator==(const CSGNode& other) const { return type_ == other.type_ && id_ == other.id_ && daughters_ == other.daughters_; } //---------------------------------------------------------------------------// } // namespace celeritas
28.356164
79
0.423671
celeritas-project
7ef367188a456625b49bda5a02720ea64be9e6c3
154
hpp
C++
src/LevelScheduler.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
null
null
null
src/LevelScheduler.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
null
null
null
src/LevelScheduler.hpp
hpcg-benchmark/KHPCG3.0
9591b148ea6552342a0471a932d2abf332e490e0
[ "BSD-3-Clause" ]
3
2019-03-05T16:46:25.000Z
2021-12-22T03:49:00.000Z
#ifndef LEVELSCHEDULER_HPP #define LEVELSCHEDULER_HPP #include "KokkosSetup.hpp" #include "SparseMatrix.hpp" int levelSchedule(SparseMatrix & A); #endif
19.25
36
0.811688
hpcg-benchmark
7ef95f706923464ac5e1417ba4876f4e19fb3860
9,520
cpp
C++
Turso3D/Resource/ResourceCache.cpp
cadaver/turso3d
5659df48b7915b95a351dfcad382b3ed653573f2
[ "Zlib" ]
29
2015-03-21T22:35:50.000Z
2022-01-25T04:13:46.000Z
Turso3D/Resource/ResourceCache.cpp
cadaver/turso3d
5659df48b7915b95a351dfcad382b3ed653573f2
[ "Zlib" ]
1
2016-10-23T16:20:14.000Z
2018-04-13T13:32:13.000Z
Turso3D/Resource/ResourceCache.cpp
cadaver/turso3d
5659df48b7915b95a351dfcad382b3ed653573f2
[ "Zlib" ]
8
2015-09-28T06:26:41.000Z
2020-12-28T14:29:51.000Z
// For conditions of distribution and use, see copyright notice in License.txt #include "../Debug/Log.h" #include "../Debug/Profiler.h" #include "../IO/File.h" #include "../IO/FileSystem.h" #include "Image.h" #include "JSONFile.h" #include "ResourceCache.h" #include "../Debug/DebugNew.h" namespace Turso3D { ResourceCache::ResourceCache() { RegisterSubsystem(this); } ResourceCache::~ResourceCache() { UnloadAllResources(true); RemoveSubsystem(this); } bool ResourceCache::AddResourceDir(const String& pathName, bool addFirst) { PROFILE(AddResourceDir); if (!DirExists(pathName)) { LOGERROR("Could not open directory " + pathName); return false; } String fixedPath = SanitateResourceDirName(pathName); // Check that the same path does not already exist for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (!resourceDirs[i].Compare(fixedPath, false)) return true; } if (addFirst) resourceDirs.Insert(0, fixedPath); else resourceDirs.Push(fixedPath); LOGINFO("Added resource path " + fixedPath); return true; } bool ResourceCache::AddManualResource(Resource* resource) { if (!resource) { LOGERROR("Null manual resource"); return false; } if (resource->Name().IsEmpty()) { LOGERROR("Manual resource with empty name, can not add"); return false; } resources[MakePair(resource->Type(), StringHash(resource->Name()))] = resource; return true; } void ResourceCache::RemoveResourceDir(const String& pathName) { // Convert path to absolute String fixedPath = SanitateResourceDirName(pathName); for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (!resourceDirs[i].Compare(fixedPath, false)) { resourceDirs.Erase(i); LOGINFO("Removed resource path " + fixedPath); return; } } } void ResourceCache::UnloadResource(StringHash type, const String& name, bool force) { auto key = MakePair(type, StringHash(name)); auto it = resources.Find(key); if (it == resources.End()) return; Resource* resource = it->second; if (resource->Refs() == 1 || force) resources.Erase(key); } void ResourceCache::UnloadResources(StringHash type, bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; if (current->first.first == type) { Resource* resource = current->second; if (resource->Refs() == 1 || force) { resources.Erase(current); ++unloaded; } } } if (!unloaded) break; } } void ResourceCache::UnloadResources(StringHash type, const String& partialName, bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; if (current->first.first == type) { Resource* resource = current->second; if (resource->Name().StartsWith(partialName) && (resource->Refs() == 1 || force)) { resources.Erase(current); ++unloaded; } } } if (!unloaded) break; } } void ResourceCache::UnloadResources(const String& partialName, bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; Resource* resource = current->second; if (resource->Name().StartsWith(partialName) && (!resource->Refs() == 1 || force)) { resources.Erase(current); ++unloaded; } } if (!unloaded) break; } } void ResourceCache::UnloadAllResources(bool force) { // In case resources refer to other resources, repeat until there are no further unloads for (;;) { size_t unloaded = 0; for (auto it = resources.Begin(); it != resources.End();) { auto current = it++; Resource* resource = current->second; if (resource->Refs() == 1 || force) { resources.Erase(current); ++unloaded; } } if (!unloaded) break; } } bool ResourceCache::ReloadResource(Resource* resource) { if (!resource) return false; AutoPtr<Stream> stream = OpenResource(resource->Name()); return stream ? resource->Load(*stream) : false; } AutoPtr<Stream> ResourceCache::OpenResource(const String& nameIn) { String name = SanitateResourceName(nameIn); AutoPtr<Stream> ret; for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (FileExists(resourceDirs[i] + name)) { // Construct the file first with full path, then rename it to not contain the resource path, // so that the file's name can be used in further OpenResource() calls (for example over the network) ret = new File(resourceDirs[i] + name); break; } } // Fallback using absolute path if (!ret) ret = new File(name); if (!ret->IsReadable()) { LOGERROR("Could not open resource file " + name); ret.Reset(); } return ret; } Resource* ResourceCache::LoadResource(StringHash type, const String& nameIn) { String name = SanitateResourceName(nameIn); // If empty name, return null pointer immediately without logging an error if (name.IsEmpty()) return nullptr; // Check for existing resource auto key = MakePair(type, StringHash(name)); auto it = resources.Find(key); if (it != resources.End()) return it->second; SharedPtr<Object> newObject = Create(type); if (!newObject) { LOGERROR("Could not load unknown resource type " + String(type)); return nullptr; } Resource* newResource = dynamic_cast<Resource*>(newObject.Get()); if (!newResource) { LOGERROR("Type " + String(type) + " is not a resource"); return nullptr; } // Attempt to load the resource AutoPtr<Stream> stream = OpenResource(name); if (!stream) return nullptr; LOGDEBUG("Loading resource " + name); newResource->SetName(name); if (!newResource->Load(*stream)) return nullptr; // Store to cache resources[key] = newResource; return newResource; } void ResourceCache::ResourcesByType(Vector<Resource*>& result, StringHash type) const { result.Clear(); for (auto it = resources.Begin(); it != resources.End(); ++it) { if (it->second->Type() == type) result.Push(it->second); } } bool ResourceCache::Exists(const String& nameIn) const { String name = SanitateResourceName(nameIn); for (size_t i = 0; i < resourceDirs.Size(); ++i) { if (FileExists(resourceDirs[i] + name)) return true; } // Fallback using absolute path return FileExists(name); } String ResourceCache::ResourceFileName(const String& name) const { for (unsigned i = 0; i < resourceDirs.Size(); ++i) { if (FileExists(resourceDirs[i] + name)) return resourceDirs[i] + name; } return String(); } String ResourceCache::SanitateResourceName(const String& nameIn) const { // Sanitate unsupported constructs from the resource name String name = NormalizePath(nameIn); name.Replace("../", ""); name.Replace("./", ""); // If the path refers to one of the resource directories, normalize the resource name if (resourceDirs.Size()) { String namePath = Path(name); String exePath = ExecutableDir(); for (unsigned i = 0; i < resourceDirs.Size(); ++i) { String relativeResourcePath = resourceDirs[i]; if (relativeResourcePath.StartsWith(exePath)) relativeResourcePath = relativeResourcePath.Substring(exePath.Length()); if (namePath.StartsWith(resourceDirs[i], false)) namePath = namePath.Substring(resourceDirs[i].Length()); else if (namePath.StartsWith(relativeResourcePath, false)) namePath = namePath.Substring(relativeResourcePath.Length()); } name = namePath + FileNameAndExtension(name); } return name.Trimmed(); } String ResourceCache::SanitateResourceDirName(const String& nameIn) const { // Convert path to absolute String fixedPath = AddTrailingSlash(nameIn); if (!IsAbsolutePath(fixedPath)) fixedPath = CurrentDir() + fixedPath; // Sanitate away /./ construct fixedPath.Replace("/./", "/"); return fixedPath.Trimmed(); } void RegisterResourceLibrary() { static bool registered = false; if (registered) return; registered = true; Image::RegisterObject(); JSONFile::RegisterObject(); } }
25.72973
113
0.590651
cadaver
7d08b77c8a8b9574512877ad3a2afc49d0029fda
8,399
cpp
C++
src/tracker/TrackerSystem_simulate.cpp
bitbloop/KalmanFilter
f1616134d6eeeab05afc56bb6b0a921fad106d7f
[ "MIT" ]
1
2022-03-29T15:55:01.000Z
2022-03-29T15:55:01.000Z
src/tracker/TrackerSystem_simulate.cpp
bitbloop/KalmanFilter
f1616134d6eeeab05afc56bb6b0a921fad106d7f
[ "MIT" ]
null
null
null
src/tracker/TrackerSystem_simulate.cpp
bitbloop/KalmanFilter
f1616134d6eeeab05afc56bb6b0a921fad106d7f
[ "MIT" ]
1
2022-03-18T07:29:55.000Z
2022-03-18T07:29:55.000Z
#include "TrackerSystem.h" #include "TrackerSystemInputHandler.h" /** Do the simulation loop. */ void TrackerSystem::Loop() { { // Fast forward the simulation at the start. math::time::Timer fast_forward_timer; FastForward(TIME_TO_FAST_FORWARD, FAST_FORWARD_STEP); double fast_forward_end_time{ fast_forward_timer.elapsed() }; std::cout << "Fast forward for " << TIME_TO_FAST_FORWARD << "s took " << fast_forward_end_time << "s." << std::endl; } // Rest the global simulation time. global_timer.reset(); double last_frame_time{ global_timer.elapsed() }; // Until we signal for the window to close while (!::renderer::window::should_window_close()) { const auto global_t{ global_timer.elapsed() }; const auto delta_t{ global_t - last_frame_time }; last_frame_time = global_t; Update(global_t, delta_t); Render(); glFinish(); ::renderer::window::pool_events_and_swap_buffers(); } } /** Perform the simulation update step. */ void TrackerSystem::Update(const double& global_t, const double& delta_t) { // Upate the world objects object_X->Update(global_t, delta_t); object_C->Update(global_t, delta_t); // ----------------------------------------------------------------------------------- // Give the sensors the new ground truth variable. object_X_acceleration_sensor.SetGroundTruth(object_X->GetAcceleration()); object_X_acceleration_sensor.QueryForSensorValueChangedEvent(global_t); object_C_acceleration_sensor.SetGroundTruth(object_C->GetAcceleration()); object_C_acceleration_sensor.QueryForSensorValueChangedEvent(global_t); // Only set the sensor ground truth if the object is within the 3m range const auto dXC{ glm::pow(object_X->GetPosition() - object_C->GetPosition(),{ 2, 2, 2 }) }; if (dXC.x + dXC.y + dXC.z <= 9) { object_X_position_sensor.SetGroundTruth(object_X->GetPosition()); object_X_position_sensor.QueryForSensorValueChangedEvent(global_t); } // ----------------------------------------------------------------------------------- // If the interval to update the filter is here, update the filter with the new sensor values. if (next_filter_update_t <= global_t && next_filter_update_t != -1) { next_filter_update_t = global_t + filter_update_interval_t; { const auto estimate_X_position{ object_X_position_sensor.GetEstimate(global_t) }; const auto estimate_X_acceleration{ object_X_acceleration_sensor.GetEstimate(global_t) }; const auto estimate_C_acceleration{ object_C_acceleration_sensor.GetEstimate(global_t) }; // convert the measurements to camera space const auto estimate_position{ estimate_X_position - object_C->GetPosition() }; const auto estimate_acceleration{ estimate_X_acceleration - estimate_C_acceleration }; // The code below will get and set proper filter values depending on the chosen model. #ifdef DATA_3D { Eigen::VectorXd measurementv3d(3); measurementv3d << estimate_position.x, estimate_position.y, estimate_position.z; object_X_filter_pos_xyz.Update(measurementv3d); } { Eigen::VectorXd measurementv3d(6); measurementv3d << estimate_position.x, estimate_position.y, estimate_position.z, estimate_acceleration.x, estimate_acceleration.y, estimate_acceleration.z; object_X_filter_pos_acc_xyz.Update(measurementv3d); } #else { Eigen::VectorXd measurementv2d(4); measurementv2d << estimate_position.x, estimate_position.y, estimate_acceleration.x, estimate_acceleration.y; object_X_filter_xy.Update(measurementv2d); } #endif } #ifdef DATA_3D { // Update the dead reckoning algorithm #ifdef TRACK_KALMAN_FILTER_POSITION_ONLY const auto filter_estimate{ object_X_filter_pos_xyz.GetEstimate() }; const auto glm_filter_estimate_pos{ glm::dvec3({ filter_estimate[0], filter_estimate[1], filter_estimate[2] }) }; object_X_filter_dead_reckoning.SetSensorReading(glm_filter_estimate_pos, glm::dvec3(0), global_t); #else const auto filter_estimate{ object_X_filter_pos_acc_xyz.GetEstimate() }; const auto glm_filter_estimate_pos{ glm::dvec3({ filter_estimate[0], filter_estimate[1], filter_estimate[2] }) }; const auto glm_filter_estimate_acc{ glm::dvec3({ filter_estimate[3], filter_estimate[4], filter_estimate[5] }) }; object_X_filter_dead_reckoning.SetSensorReading(glm_filter_estimate_pos, glm_filter_estimate_acc, global_t); #endif } #else // Update the dead reckoning algorithm const auto filter_estimate{ object_X_filter_xy.GetEstimate() }; const auto glm_filter_estimate_pos{ glm::dvec3({ filter_estimate[0], filter_estimate[1], 0 }) }; const auto glm_filter_estimate_acc{ glm::dvec3({ filter_estimate[4], filter_estimate[5], 0 }) }; object_X_filter_dead_reckoning.SetSensorReading(glm_filter_estimate_pos, glm_filter_estimate_acc, global_t); #endif } // ----------------------------------------------------------------------------------- // Update and bake the graphs // Mark the next filter update interval if it is the first iteration of the loop if (next_graph_bake_update_t == 0) next_graph_bake_update_t = global_t + GRAPH_DATA_COLLECTION_DURATION; // Add more measurements to the graphs if the graphs were not baked and it is the allowed time to record a new measurement. if (!analysis.IsBaked() && (global_t < next_graph_bake_update_t || continuous_graph_data_capture) && !stop_graph_data_capture) { const auto ground_truth_position_X{ object_X->GetPosition() }; const auto ground_truth_position_C{ object_C->GetPosition() }; const auto sensor_read_position{ object_X_position_sensor.GetEstimate(global_t) - object_C->GetPosition() }; const auto dead_reckoning_position{ object_X_filter_dead_reckoning.GetPositionEstimate(global_t) }; const auto sensor_read_acceleration{ object_X_acceleration_sensor.GetEstimate(global_t) - object_C_acceleration_sensor.GetEstimate(global_t) }; const auto dead_reckoning_acceleration{ object_X_filter_dead_reckoning.GetAccelerationEstimate(global_t) }; // Future position estimation if (global_t >= future_resolution_time) { const glm::dvec3 d{ (ground_truth_position_X - ground_truth_position_C) - future_position }; last_future_prediction_error = { (d.x*d.x + d.y*d.y + d.z*d.z) }; future_resolution_time = global_t + FUTURE_PREDICTION_TIME; future_position = object_X_filter_dead_reckoning.GetPositionEstimate(global_t + FUTURE_PREDICTION_TIME); } analysis.AddPoint(ground_truth_position_X, ground_truth_position_C, sensor_read_position, sensor_read_acceleration, dead_reckoning_position, dead_reckoning_acceleration, last_future_prediction_error); } // If we are not capturing, and also the graphs are not baked, bake them. else if (!analysis.IsBaked()) { analysis.BakeGraphs(pointcloud_shader_id); } } /** Fast forward the soimulation */ void TrackerSystem::FastForward(const double & total_time, const double& time_step) { double ff_global_t{ 0 }; // The global time relative to the fast forward state // Pause the sensor threads object_X_position_sensor.SetPauseThread(true); object_X_acceleration_sensor.SetPauseThread(true); object_C_acceleration_sensor.SetPauseThread(true); // Set the states to start collecting data StartContinousCapture(); // Update the world Update(0, time_step); while (ff_global_t < total_time) { // Advance the total time elapsed ff_global_t += time_step; // Simulate sensors firing object_X_position_sensor.SimulateSensorReading(ff_global_t); object_X_position_sensor.QueryForSensorValueChangedEvent(ff_global_t); object_X_acceleration_sensor.SimulateSensorReading(ff_global_t); object_X_acceleration_sensor.QueryForSensorValueChangedEvent(ff_global_t); object_C_acceleration_sensor.SimulateSensorReading(ff_global_t); object_C_acceleration_sensor.QueryForSensorValueChangedEvent(ff_global_t); // Update the world Update(ff_global_t, time_step); } // Set the states to finish collecting data StopContinuousCapture(); // Reset to factory settings object_X_position_sensor.Reset(); object_X_acceleration_sensor.Reset(); object_C_acceleration_sensor.Reset(); object_X->Reset(); object_C->Reset(); // Disable further filter updating, since we are not collecting data next_filter_update_t = -1; // Resume the sensor threads object_X_position_sensor.SetPauseThread(false); object_X_acceleration_sensor.SetPauseThread(false); object_C_acceleration_sensor.SetPauseThread(false); }
40.970732
202
0.761162
bitbloop
7d0a1d436efbf4f8ef8ccd9bf1a9c61fab3bce51
3,136
hpp
C++
src/backends/reference/workloads/Lstm.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
856
2018-03-09T17:26:23.000Z
2022-03-24T21:31:33.000Z
src/backends/reference/workloads/Lstm.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
623
2018-03-13T04:40:42.000Z
2022-03-31T09:45:17.000Z
src/backends/reference/workloads/Lstm.hpp
sahilbandar/armnn
249950645b7bc0593582182097c7e2f1d6d97442
[ "MIT" ]
284
2018-03-09T23:05:28.000Z
2022-03-29T14:42:28.000Z
// // Copyright © 2021 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <armnn/TypesUtils.hpp> #include <backendsCommon/WorkloadData.hpp> #include "Encoders.hpp" #include "Decoders.hpp" namespace armnn { void LstmImpl(const LstmDescriptor& descriptor, const TensorInfo& inputInfo, const TensorInfo& outputInfo, const TensorShape& inputToOutputWeightsShape, const TensorShape& recurrentToOutputWeightsShape, std::unique_ptr<Decoder<float>>& inputData, std::unique_ptr<Decoder<float>>& outputStateIn, std::unique_ptr<Decoder<float>>& cellStateIn, std::unique_ptr<Encoder<float>>& outputStateOut, std::unique_ptr<Encoder<float>>& cellStateOut, std::unique_ptr<Encoder<float>>& output, std::unique_ptr<Decoder<float>>& cellStateOutDecoder, std::unique_ptr<Decoder<float>>& outputDecoder, std::unique_ptr<Decoder<float>>& inputToInputWeightsTensor, std::unique_ptr<Decoder<float>>& inputToForgetWeightsTensor, std::unique_ptr<Decoder<float>>& inputToCellWeightsTensor, std::unique_ptr<Decoder<float>>& inputToOutputWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToInputWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToForgetWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToCellWeightsTensor, std::unique_ptr<Decoder<float>>& recurrentToOutputWeightsTensor, std::unique_ptr<Decoder<float>>& cellToInputWeightsTensor, std::unique_ptr<Decoder<float>>& cellToForgetWeightsTensor, std::unique_ptr<Decoder<float>>& cellToOutputWeightsTensor, std::unique_ptr<Decoder<float>>& inputGateBiasTensor, std::unique_ptr<Decoder<float>>& forgetGateBiasTensor, std::unique_ptr<Decoder<float>>& cellBiasTensor, std::unique_ptr<Decoder<float>>& outputGateBiasTensor, std::unique_ptr<Decoder<float>>& projectionWeightsTensor, std::unique_ptr<Decoder<float>>& projectionBiasTensor, std::unique_ptr<Decoder<float>>& inputLayerNormWeights, std::unique_ptr<Decoder<float>>& forgetLayerNormWeights, std::unique_ptr<Decoder<float>>& cellLayerNormWeights, std::unique_ptr<Decoder<float>>& outputLayerNormWeights, std::unique_ptr<Encoder<float>>& inputGateScratch, std::unique_ptr<Encoder<float>>& cellScratch, std::unique_ptr<Encoder<float>>& forgetGateScratch, std::unique_ptr<Encoder<float>>& outputGateScratch, std::unique_ptr<Decoder<float>>& inputGateScratchDecoder, std::unique_ptr<Decoder<float>>& cellScratchDecoder, std::unique_ptr<Decoder<float>>& forgetGateScratchDecoder, std::unique_ptr<Decoder<float>>& outputGateScratchDecoder, float layerNormEpsilon); } //namespace armnn
50.580645
78
0.660714
sahilbandar
7d0a62159844187c30c4387853782473f2295c65
2,889
cpp
C++
modules/itmx/src/imagesources/DepthCorruptingImageSourceEngine.cpp
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
197
2015-10-01T07:23:01.000Z
2022-03-23T03:02:31.000Z
modules/itmx/src/imagesources/DepthCorruptingImageSourceEngine.cpp
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
16
2016-03-26T13:01:08.000Z
2020-09-02T09:13:49.000Z
modules/itmx/src/imagesources/DepthCorruptingImageSourceEngine.cpp
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
62
2015-10-03T07:14:59.000Z
2021-08-31T08:58:18.000Z
/** * itmx: DepthCorruptingImageSourceEngine.cpp * Copyright (c) Torr Vision Group, University of Oxford, 2019. All rights reserved. */ #include "imagesources/DepthCorruptingImageSourceEngine.h" #include <ITMLib/Engines/ViewBuilding/Shared/ITMViewBuilder_Shared.h> using namespace ITMLib; namespace itmx { //#################### CONSTRUCTORS #################### DepthCorruptingImageSourceEngine::DepthCorruptingImageSourceEngine(ImageSourceEngine *innerSource, double missingDepthFraction, float depthNoiseSigma) : m_depthNoiseSigma(depthNoiseSigma), m_innerSource(innerSource), m_rng(12345) { if(missingDepthFraction > 0.0) { m_missingDepthMask.reset(new ORBoolImage(innerSource->getDepthImageSize(), true, false)); bool *missingDepthMask = m_missingDepthMask->GetData(MEMORYDEVICE_CPU); for(size_t i = 0, size = m_missingDepthMask->dataSize; i < size; ++i) { missingDepthMask[i] = m_rng.generate_real_from_uniform<double>(0.0, 1.0) <= missingDepthFraction; } } } //#################### PUBLIC MEMBER FUNCTIONS #################### ITMRGBDCalib DepthCorruptingImageSourceEngine::getCalib() const { return m_innerSource->getCalib(); } Vector2i DepthCorruptingImageSourceEngine::getDepthImageSize() const { return m_innerSource->getDepthImageSize(); } void DepthCorruptingImageSourceEngine::getImages(ORUChar4Image *rgb, ORShortImage *rawDepth) { const Vector2f depthCalibParams = getCalib().disparityCalib.GetParams(); // Get the uncorrupted images. m_innerSource->getImages(rgb, rawDepth); #ifdef WITH_OPENMP #pragma omp parallel for #endif for(int y = 0; y < rawDepth->noDims.y; ++y) { for(int x = 0; x < rawDepth->noDims.x; ++x) { const int offset = y * rawDepth->noDims.x + x; short& rawDepthValue = rawDepth->GetData(MEMORYDEVICE_CPU)[offset]; // If desired, zero out any depth values that should be missing. if(m_missingDepthMask && m_missingDepthMask->GetData(MEMORYDEVICE_CPU)[offset]) { rawDepthValue = 0; } // If desired, corrupt any depth values that still exist with zero-mean, depth-dependent Gaussian noise. if(m_depthNoiseSigma > 0.0f && rawDepthValue != 0) { float depth = 0.0f; convertDepthAffineToFloat(&depth, 0, 0, &rawDepthValue, rawDepth->noDims, depthCalibParams); #ifdef WITH_OPENMP #pragma omp critical #endif depth += m_rng.generate_from_gaussian(0.0f, m_depthNoiseSigma) * depth; rawDepthValue = CLAMP(static_cast<short>(ROUND((depth - depthCalibParams.y) / depthCalibParams.x)), 1, 32000); } } } rawDepth->UpdateDeviceFromHost(); } Vector2i DepthCorruptingImageSourceEngine::getRGBImageSize() const { return m_innerSource->getRGBImageSize(); } bool DepthCorruptingImageSourceEngine::hasMoreImages() const { return m_innerSource->hasMoreImages(); } }
30.734043
150
0.709242
torrvision
7d0a8f4b0c580058655d52745c5c9355d8295677
1,077
hpp
C++
Nacro/SDK/FN_AssetRegistry_structs.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_AssetRegistry_structs.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_AssetRegistry_structs.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Script Structs //--------------------------------------------------------------------------- // ScriptStruct AssetRegistry.AssetBundleEntry // 0x0028 struct FAssetBundleEntry { struct FPrimaryAssetId BundleScope; // 0x0000(0x0010) struct FName BundleName; // 0x0010(0x0008) (ZeroConstructor, IsPlainOldData) TArray<struct FStringAssetReference> BundleAssets; // 0x0018(0x0010) (ZeroConstructor) }; // ScriptStruct AssetRegistry.AssetBundleData // 0x0010 struct FAssetBundleData { TArray<struct FAssetBundleEntry> Bundles; // 0x0000(0x0010) (ZeroConstructor) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
29.916667
161
0.457753
Milxnor
7d0d89f6393eaa16a5a92f1444eb5c9a73ae4abf
5,433
cpp
C++
src/HADemoService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
src/HADemoService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
src/HADemoService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
/** * @copyright (c) 2017 Mark R. Jenkins. All rights reserved. * @file HADemoService.cpp * * @author MJenkins, ENPM 808X Spring 2017 * @date May 10, 2017 - Creation * * @brief Provides a Home Automation "demo" service (sends HBBehavior goals to bot_actor action server) * * This service provides a way to manually activate Home Automation system requests * for BotBehaviors by accepting a service request containing a behavior name and * a number of repetitions, then using an action client to send the same behavior * name and repetitions to the bot_actor action server, which executes the behavior * (if present in its repertoire). When the BotBehavior action ends, the service * call will return to the requestor with an outcome (reached the goal, or not). * * * * * BSD 3-Clause License * * Copyright (c) 2017, Mark Jenkins * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "homebot/HADemoService.hpp" /** * @brief Constructor for HADemoService that creates a demonstration service object populated with a service client and callback to use when service requests are received * @param pHAClients */ HADemoService::HADemoService(HAClients& pHAClients) : haClients(pHAClients), nh() { // Set the service server object using the node handle's advertiseService method, // the service name, and the callback method from this object ss = nh.advertiseService("ha_demo", &HADemoService::callback, this); ROS_INFO_STREAM( "HomeBot-HADemoService(constructor): Initialized ha_demo service"); } HADemoService::~HADemoService() { } /** * @brief Service callback for the Home Automation Demo service - handles service calls * @param [in] req data specifying the request details (behavior, repetitions) * @param [out] rsp data going back to the service requestor (result) * @return boolean success or failure of the service call */ bool HADemoService::callback(homebot::HADemo::Request& req, homebot::HADemo::Response& rsp) { // Validate that the repetition count is between 1 and 10 (to prevent mistaken invocations) if (req.repetitions < 1 || req.repetitions > 10) { ROS_WARN_STREAM( "HomeBot-HADemoService(callback): Invalid number of repetitions '" << static_cast<int>(req.repetitions) << "' requested, no action initiated"); rsp.result = "Rejected: Invalid number of repetitions requested"; return false; } // Validate that the behavior requested is not null if (req.behavior == "") { ROS_WARN_STREAM( "Null behavior requested, no action taken"); rsp.result = "Rejected: Null behavior requested"; return false; } // Check whether the action is still available if (!haClients.acHBBehavior.isServerConnected()) { ROS_WARN_STREAM( "HomeBot-HADemoService(callback): bot_actor action server not ready when trying to activate behavior '" << req.behavior << "' with " << static_cast<int>(req.repetitions) << " repetitions"); rsp.result = "Failed: action server not ready"; return false; } ROS_INFO_STREAM( "HomeBot-HADemoService(callback): sending goal to bot_actor action server (behavior '" << req.behavior << "' with " << static_cast<int>(req.repetitions) << " repetitions)"); // Send goal to move_base action server, then wait for result homebot::HBBehaviorGoal goal; goal.behavior = req.behavior; goal.repetitions = req.repetitions; haClients.acHBBehavior.sendGoal(goal); haClients.acHBBehavior.waitForResult(); if (haClients.acHBBehavior.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO_STREAM("HomeBot-HADemoService(callback): Behavior goal reached"); rsp.result = "Joy: Behavior completed successfully"; return true; } else { ROS_WARN_STREAM( "HomeBot-HADemoService(callback): Failed to reach behavior goal"); rsp.result = "Sadness: Behavior did not complete successfully"; return false; } }
45.655462
197
0.735689
mark1-umd
7d0dafd27bd571aad05a2041e55204df0ba0530f
1,033
cpp
C++
lintcode/maxproductsubarray.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode/maxproductsubarray.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode/maxproductsubarray.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * @param nums: a vector of integers * @return: an integer */ int maxProduct(vector<int>& nums) { // write your code here int n=nums.size(); if(n==0){ return 0; } //maintain a mintemp incase negative * negative got a large positive int mintemp=nums[0]; int maxtemp=nums[0]; int res=nums[0]; //traversal every element to update minc and maxc for(int i=1; i<n; i++){ // not sure mintemp*nums[i] is small, it can be large baecause negative // not sure maxtemp*nums[i] is large, it can be small since negative int tempmin=min(mintemp*nums[i],maxtemp*nums[i]); int tempmax=max(mintemp*nums[i],maxtemp*nums[i]); mintemp=min(tempmin,nums[i]); maxtemp=max(tempmax,nums[i]); res=max(maxtemp,res); } return res; } };
27.918919
83
0.504356
WIZARD-CXY
7d14fd45738791225df985e91d6006f6f9a6b859
506
cpp
C++
LibSFML/SFText.cpp
Gotatang/FrameWorkIA
347b3b400a706427ecf7d5401e19ba4bd2bf18c3
[ "MIT" ]
null
null
null
LibSFML/SFText.cpp
Gotatang/FrameWorkIA
347b3b400a706427ecf7d5401e19ba4bd2bf18c3
[ "MIT" ]
null
null
null
LibSFML/SFText.cpp
Gotatang/FrameWorkIA
347b3b400a706427ecf7d5401e19ba4bd2bf18c3
[ "MIT" ]
null
null
null
/*Documentation */ /*@author : Quentin Ladevie */ /*@file : SFText.cpp */ /*@date : 29/12/2015 */ /*@brief : Fichier source des textes SFML */ #include "stdafx.h" #include "SFText.hpp" namespace DadEngine { SFText::SFText() { } SFText::~SFText() { } // Get/Set sf::Text& SFText::GetText() { return m_text; } void SFText::SetText(const sf::Text& _newText) { m_text = _newText; } // Get a copy Text* SFText::GetClone() { return new SFText (*this); } }
12.65
47
0.579051
Gotatang
7d18a518d116a68731c9290c5e73dbc3da4a6e63
4,271
cpp
C++
sqsgenerator/core/python/iteration.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
14
2019-11-16T10:34:04.000Z
2022-03-28T09:32:42.000Z
sqsgenerator/core/python/iteration.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
5
2019-11-21T05:54:07.000Z
2022-03-29T07:56:34.000Z
sqsgenerator/core/python/iteration.cpp
dgehringer/sqsgenerator
562697166a53f806629e8e1086b381871d9a675e
[ "MIT" ]
4
2020-09-28T14:28:23.000Z
2021-03-05T14:11:44.000Z
// // Created by dominik on 14.07.21. // #include "iteration.hpp" #include "helpers.hpp" namespace sqsgenerator::python { shuffling_bounds_t convert_bound_list(py::list &list) { shuffling_bounds_t bounds; if (list.is_none()) return bounds; for (int i = 0; i < len(list); i++) { auto bound = list[i]; bounds.push_back(std::forward_as_tuple(py::extract<size_t>(bound[0]), py::extract<size_t>(bound[1]))); } return bounds; } IterationSettingsPythonWrapper::IterationSettingsPythonWrapper( StructurePythonWrapper structure, py::dict composition, np::ndarray target_objective, np::ndarray parameter_weights, py::dict shell_weights, int iterations, int output_configurations, py::list threads_per_rank, double atol, double rtol, iteration_mode iteration_mode) : m_structure(structure), m_handle(new IterationSettings( *structure.handle(), helpers::convert_composition(composition), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(target_objective), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(parameter_weights), helpers::dict_to_map<shell_t, double>(shell_weights), iterations, output_configurations, helpers::list_to_vector<int>(threads_per_rank), atol, rtol, iteration_mode )) {} IterationSettingsPythonWrapper::IterationSettingsPythonWrapper( StructurePythonWrapper structure, py::dict composition, np::ndarray target_objective, np::ndarray parameter_weights, py::dict shell_weights, int iterations, int output_configurations, py::list distances, py::list threads_per_rank, double atol, double rtol, iteration_mode iteration_mode) : m_structure(structure), m_handle(new IterationSettings( *structure.handle(), helpers::convert_composition(composition), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(target_objective), helpers::ndarray_to_multi_array<const_array_3d_ref_t>(parameter_weights), helpers::dict_to_map<shell_t, double>(shell_weights), iterations, output_configurations, helpers::list_to_vector<double>(distances), helpers::list_to_vector<int>(threads_per_rank), atol, rtol, iteration_mode )) {} double IterationSettingsPythonWrapper::atol() const { return m_handle->atol(); } double IterationSettingsPythonWrapper::rtol() const { return m_handle->rtol(); } size_t IterationSettingsPythonWrapper::num_atoms() const { return m_handle->num_atoms(); } size_t IterationSettingsPythonWrapper::num_shells() const { return m_handle->num_shells(); } int IterationSettingsPythonWrapper::num_iterations() const { return m_handle->num_iterations(); } size_t IterationSettingsPythonWrapper::num_species() const { return m_handle->num_species(); } iteration_mode IterationSettingsPythonWrapper::mode() const { return m_handle->mode(); } np::ndarray IterationSettingsPythonWrapper::target_objective() const { return helpers::multi_array_to_ndarray(m_handle->target_objective()); } StructurePythonWrapper IterationSettingsPythonWrapper::structure() const { return m_structure; } int IterationSettingsPythonWrapper::num_output_configurations() const { return m_handle->num_output_configurations(); } py::dict IterationSettingsPythonWrapper::shell_weights() const { return helpers::map_to_dict(m_handle->shell_weights()); } np::ndarray IterationSettingsPythonWrapper::parameter_weights() const { return helpers::multi_array_to_ndarray(m_handle->parameter_weights()); } std::shared_ptr<IterationSettings> IterationSettingsPythonWrapper::handle() const { return m_handle; } }
33.367188
114
0.648326
dgehringer
7d1df48aacc2edd0b2dace2583a02e4ad527144d
10,603
cpp
C++
Cpp/SDK/BP_WeatherSystem_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
1
2020-08-15T08:31:55.000Z
2020-08-15T08:31:55.000Z
Cpp/SDK/BP_WeatherSystem_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-15T08:43:56.000Z
2021-01-15T05:04:48.000Z
Cpp/SDK/BP_WeatherSystem_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-10T12:05:42.000Z
2021-02-12T19:56:10.000Z
// Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_WeatherSystem.BP_WeatherSystem_C.SetupGlobalWind // (Public, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetupGlobalWind() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetupGlobalWind"); ABP_WeatherSystem_C_SetupGlobalWind_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SetupWindMaterial // (Public, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetupWindMaterial() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetupWindMaterial"); ABP_WeatherSystem_C_SetupWindMaterial_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.drawRoom // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // float CeilingHeight (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // float RoomWidth (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // float RoomLenght (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // TEnumAsByte<EPhysicalSurface> FloorType (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_WeatherSystem_C::drawRoom(float* CeilingHeight, float* RoomWidth, float* RoomLenght, TEnumAsByte<EPhysicalSurface>* FloorType) { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.drawRoom"); ABP_WeatherSystem_C_drawRoom_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (CeilingHeight != nullptr) *CeilingHeight = params.CeilingHeight; if (RoomWidth != nullptr) *RoomWidth = params.RoomWidth; if (RoomLenght != nullptr) *RoomLenght = params.RoomLenght; if (FloorType != nullptr) *FloorType = params.FloorType; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnParticleSystem // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SpawnParticleSystem() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnParticleSystem"); ABP_WeatherSystem_C_SpawnParticleSystem_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.WeatherSystemDirection // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::WeatherSystemDirection() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.WeatherSystemDirection"); ABP_WeatherSystem_C_WeatherSystemDirection_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnDistantParticleSystem // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SpawnDistantParticleSystem() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SpawnDistantParticleSystem"); ABP_WeatherSystem_C_SpawnDistantParticleSystem_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SetRadius // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetRadius() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetRadius"); ABP_WeatherSystem_C_SetRadius_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.UserConstructionScript"); ABP_WeatherSystem_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoomType // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::CheckRoomType() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoomType"); ABP_WeatherSystem_C_CheckRoomType_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoofMaterial // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::CheckRoofMaterial() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.CheckRoofMaterial"); ABP_WeatherSystem_C_CheckRoofMaterial_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ResetSpawningParticles // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::ResetSpawningParticles() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ResetSpawningParticles"); ABP_WeatherSystem_C_ResetSpawningParticles_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.LeaveNegativeArea // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::LeaveNegativeArea() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.LeaveNegativeArea"); ABP_WeatherSystem_C_LeaveNegativeArea_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.EnterNegativeArea // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::EnterNegativeArea() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.EnterNegativeArea"); ABP_WeatherSystem_C_EnterNegativeArea_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ApplyWeatherToMap // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::ApplyWeatherToMap() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ApplyWeatherToMap"); ABP_WeatherSystem_C_ApplyWeatherToMap_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.SetEffectLocation // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::SetEffectLocation() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.SetEffectLocation"); ABP_WeatherSystem_C_SetEffectLocation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.CheckPlayerProximity // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::CheckPlayerProximity() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.CheckPlayerProximity"); ABP_WeatherSystem_C_CheckPlayerProximity_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.UpdateWeatherDirection // (BlueprintCallable, BlueprintEvent) void ABP_WeatherSystem_C::UpdateWeatherDirection() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.UpdateWeatherDirection"); ABP_WeatherSystem_C_UpdateWeatherDirection_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveBeginPlay // (Event, Protected, BlueprintEvent) void ABP_WeatherSystem_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveBeginPlay"); ABP_WeatherSystem_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveTick // (Event, Public, BlueprintEvent) // Parameters: // float DeltaSeconds (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_WeatherSystem_C::ReceiveTick(float DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ReceiveTick"); ABP_WeatherSystem_C_ReceiveTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_WeatherSystem.BP_WeatherSystem_C.ExecuteUbergraph_BP_WeatherSystem // (Final, HasDefaults) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_WeatherSystem_C::ExecuteUbergraph_BP_WeatherSystem(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_WeatherSystem.BP_WeatherSystem_C.ExecuteUbergraph_BP_WeatherSystem"); ABP_WeatherSystem_C_ExecuteUbergraph_BP_WeatherSystem_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.129121
176
0.776761
MrManiak
7d24153e72beb069099d37518c6f00579d1007e1
5,736
cpp
C++
Source/Pineapple/Engine/Platform/FileSystem.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
11
2017-04-15T14:44:19.000Z
2022-02-04T13:16:04.000Z
Source/Pineapple/Engine/Platform/FileSystem.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
25
2017-04-19T12:48:42.000Z
2020-05-09T05:28:29.000Z
Source/Pineapple/Engine/Platform/FileSystem.cpp
JoshYaxley/Pineapple
490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec
[ "Zlib" ]
1
2019-04-21T21:14:04.000Z
2019-04-21T21:14:04.000Z
#include <Pineapple/Engine/Platform/FileSystem.h> #include <Pineapple/Engine/Platform/Memory.h> #include <Pineapple/Engine/Util/Macro.h> #include <cstdio> #include <sys/stat.h> namespace { pa::FileResult openFile(FILE** file, const char* path, const char* mode) { #ifdef _MSC_VER fopen_s(file, path, mode); #else *file = fopen(path, mode); #endif if (!*file) { switch (errno) { case ENOENT: // No such file or directory return pa::FileResult::NotFound; break; case EIO: // I/O Error return pa::FileResult::ReadError; break; case EACCES: // Permissions return pa::FileResult::AccessDenied; break; case ENAMETOOLONG: // File name is too long return pa::FileResult::NameTooLong; break; default: // Cannot find error return pa::FileResult::NotFound; break; } } return pa::FileResult::Success; } } void pa::FileBuffer::allocate(std::size_t size) { PA_ASSERTF(m_size == 0, "Buffer has already been allocated"); m_buffer = std::make_unique<unsigned char[]>(size); m_size = size; } std::unique_ptr<unsigned char[]>& pa::FileBuffer::getBuffer() { return m_buffer; } const std::unique_ptr<unsigned char[]>& pa::FileBuffer::getBuffer() const { return m_buffer; } std::size_t pa::FileBuffer::getSize() const { return m_size; } std::string pa::FileBuffer::createString() const { std::string string((char*)m_buffer.get(), m_size); return string; } void pa::FileBuffer::copyFromString(std::string string) { clear(); allocate(string.size()); memcpy(getBuffer().get(), string.c_str(), getSize()); } void pa::FileBuffer::clear() { m_buffer = nullptr; m_size = 0; } namespace { std::string combinePaths(const std::string& path1, const std::string& path2) { // <todo> make work with all path types std::string result = path1; if (!result.empty() && result[result.size() - 1] != '/') { result += '/'; } result += path2; return result; } std::string makeFilePath(const pa::FileSystem& fileSystem, pa::FileStorage storage, const std::string& path) { // <todo> add directory separators when building paths switch (storage) { case pa::FileStorage::EngineAsset: return combinePaths(fileSystem.getSettings().engineAssetPath, path); case pa::FileStorage::UserAsset: return combinePaths(fileSystem.getSettings().userAssetPath, path); case pa::FileStorage::Internal: return combinePaths(fileSystem.getSettings().internalPath, path); default: PA_ASSERTF(false, "Unknown FileStorage value"); return ""; } } } pa::FilePath::FilePath(const pa::FileSystem& fileSystem, pa::FileStorage storage, const std::string& path) : m_fileSystem(fileSystem) , m_path(makeFilePath(fileSystem, storage, path)) , m_storage(storage) { } const std::string& pa::FilePath::asString() const { return m_path; } pa::FileResult pa::FilePath::read(FileBuffer& buffer) const { return m_fileSystem.read(*this, buffer); } pa::FileResult pa::FilePath::write(const FileBuffer& buffer) const { return m_fileSystem.write(*this, buffer); } pa::FileResult pa::FilePath::getModificationTime(std::chrono::system_clock::time_point& modificationTime) const { return m_fileSystem.getModificationTime(*this, modificationTime); } pa::FileStorage pa::FilePath::getStorage() const { return m_storage; } pa::FileSystem::FileSystem(pa::PlatformSettings::FileSystem settings) : m_settings(settings) { } /*static*/ const char* pa::FileSystem::getResultString(pa::FileResult result) { switch (result) { case pa::FileResult::Success: return "Success"; case pa::FileResult::NotFound: return "File not found"; case pa::FileResult::ReadError: return "File read error"; case pa::FileResult::IOError: return "File I/O error"; case pa::FileResult::AccessDenied: return "Access denied"; case pa::FileResult::NameTooLong: return "File name too long"; case pa::FileResult::WriteError: return "File write error"; default: PA_ASSERTF(false, "Result string not implemented"); return ""; } } const pa::PlatformSettings::FileSystem& pa::FileSystem::getSettings() const { return m_settings; } pa::FileResult pa::FileSystem::read(const pa::FilePath& path, pa::FileBuffer& buffer) const { FILE* file; { auto result = openFile(&file, path.asString().c_str(), "rb"); if (result != pa::FileResult::Success) { // Cannot open the file so return error code return result; } } // Obtain the file size fseek(file, 0, SEEK_END); auto length = ftell(file); rewind(file); buffer.allocate(length); // Copy the file into the buffer pa::FileResult result = pa::FileResult::Success; auto readLength = fread(buffer.getBuffer().get(), sizeof(unsigned char), length, file); if (readLength != length) { result = pa::FileResult::ReadError; } fclose(file); return result; } pa::FileResult pa::FileSystem::write(const pa::FilePath& path, const pa::FileBuffer& buffer) const { FILE* file; { pa::FileResult result = openFile(&file, path.asString().c_str(), "wb"); if (result != pa::FileResult::Success) { // Cannot open the file so return error code return result; } } auto result = pa::FileResult::Success; auto count = fwrite(buffer.getBuffer().get(), sizeof(unsigned char), buffer.getSize(), file); if (count != buffer.getSize()) { result = pa::FileResult::WriteError; } fclose(file); return result; } pa::FileResult pa::FileSystem::getModificationTime(const pa::FilePath& path, std::chrono::system_clock::time_point& modificationTime) const { struct stat st; int ret = stat(path.asString().c_str(), &st); if (ret == -1) { return pa::FileResult::ReadError; } else { modificationTime = std::chrono::system_clock::from_time_t(st.st_mtime); return pa::FileResult::Success; } }
23.508197
139
0.699965
JoshYaxley
7d26bf1357b6c0628786f1e9d3f6754960393458
959
cpp
C++
c++/Functor/Argument.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Functor/Argument.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Functor/Argument.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #define TRUE 1 #define FALSE 0 template<typename Container, typename Functor> void for_each(Container container_, Functor functor_) { for (typename Container::iterator ite = container_.begin(); ite != container_.end(); ++ite) { functor_(*ite); } } class Out { public: static const int isNULL = FALSE; template<typename Type> void operator()(const Type& data_) { std::cout << "Out::" << data_ << std::endl; } }; class NULLType { public: static const int isNULL = TRUE; }; template<typename Type1, typename Type2 = NULLType, typename Type3 = NULLType> class Printer { public: void print(std::vector<int> container_) { for_each(container_, Type1()); } }; int main() { std::vector<int> container; for (int i = 0; i < 5; ++i) { container.push_back(i); } Printer<Out, Out, Out> printer; printer.print(container); return 0; }
15.983333
95
0.632951
taku-xhift
7d2a71dd1670cd90b80409cf45bfba5f895e52d9
1,640
hpp
C++
src/neural_network/optimizer/Dropout.hpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
14
2019-08-29T07:20:19.000Z
2022-03-22T12:51:02.000Z
src/neural_network/optimizer/Dropout.hpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
7
2020-08-07T11:08:45.000Z
2021-05-08T17:11:12.000Z
src/neural_network/optimizer/Dropout.hpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
3
2020-08-07T10:53:52.000Z
2021-02-16T22:13:22.000Z
#pragma once #include <vector> #include <boost/serialization/unique_ptr.hpp> #include <boost/serialization/access.hpp> #include "LayerOptimizer.hpp" namespace snn::internal { class Dropout final : public LayerOptimizer { private: friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, unsigned version); float value; float reverseValue; std::vector<bool> presenceProbabilities; bool randomProbability() const; public: Dropout() = default; // use restricted to Boost library only Dropout(float value, BaseLayer* layer); Dropout(const Dropout& dropout, const BaseLayer* layer); ~Dropout() override = default; std::unique_ptr<LayerOptimizer> clone(const BaseLayer* newLayer) const override; void applyAfterOutputForTraining(std::vector<float>& outputs, bool temporalReset) override; void applyAfterOutputForTesting(std::vector<float>& outputs) override; void applyBeforeBackpropagation(std::vector<float>& inputErrors) override; bool operator==(const LayerOptimizer& optimizer) const override; bool operator!=(const LayerOptimizer& optimizer) const override; }; template <class Archive> void Dropout::serialize(Archive& ar, [[maybe_unused]] const unsigned version) { boost::serialization::void_cast_register<Dropout, LayerOptimizer>(); ar & boost::serialization::base_object<LayerOptimizer>(*this); ar & this->value; ar & this->reverseValue; ar & this->presenceProbabilities; } }
33.469388
99
0.686585
MatthieuHernandez
7d2d7a43208e54bd51d3146d3f07b2a737c8db7c
1,745
cc
C++
test_hash.cc
pallas/libace
62477c78bd8848c80d91ffb311ad1c7708b655d7
[ "Zlib" ]
null
null
null
test_hash.cc
pallas/libace
62477c78bd8848c80d91ffb311ad1c7708b655d7
[ "Zlib" ]
null
null
null
test_hash.cc
pallas/libace
62477c78bd8848c80d91ffb311ad1c7708b655d7
[ "Zlib" ]
3
2018-06-04T12:52:51.000Z
2021-07-14T09:20:45.000Z
#include "hash.h" #include <cassert> #include <cstdlib> #include <string> #include <algorithm> int main(int, char*[]) { assert(lace::hash(0) == lace::hash(0)); assert(lace::hash<uint8_t>(1) == lace::hash<uint8_t>(1)); assert(lace::hash<uint16_t>(1) == lace::hash<uint16_t>(1)); assert(lace::hash<uint32_t>(1) == lace::hash<uint32_t>(1)); assert(lace::hash<uint64_t>(1) == lace::hash<uint64_t>(1)); assert(lace::hash<uint8_t>(1) != lace::hash<uint16_t>(1)); assert(lace::hash<uint16_t>(1) != lace::hash<uint32_t>(1)); assert(lace::hash<uint32_t>(1) != lace::hash<uint64_t>(1)); assert(lace::hash<uint8_t>(1) != lace::hash<uint8_t>(2)); assert(lace::hash<uint16_t>(1) != lace::hash<uint16_t>(2)); assert(lace::hash<uint32_t>(1) != lace::hash<uint32_t>(2)); assert(lace::hash<uint64_t>(1) != lace::hash<uint64_t>(2)); assert(lace::hash<const char *>("a") == lace::hash<const char *>("a")); assert(lace::hash<const char *>("a") != lace::hash<const char *>("b")); char c[] = "a"; assert(lace::hash<const char *>("a") == lace::hash<char *>(c)); assert(lace::hash("a") == lace::hash("a")); assert(lace::hash(L"a") == lace::hash(L"a")); assert(lace::hash(L"a") != lace::hash("a")); assert(lace::hash<const char *>("a") == lace::hash(std::string("a"))); assert(lace::hash<const char *>("a") != lace::hash(std::string("b"))); assert(lace::hash<std::string>(std::string("a")) == lace::hash<const std::string>(std::string("a"))); assert(lace::hash<std::string>(std::string("a")) != lace::hash<std::string>(("b"))); std::string A("A"); std::string aa("aa"); std::transform(A.begin(), A.end(), A.begin(), ::tolower); assert(lace::hash(A) == lace::hash(aa.substr(1))); return EXIT_SUCCESS; }
37.12766
103
0.603438
pallas
7d2ff077104f78ba5534f12a271add9d483f72e7
4,377
cpp
C++
NGS_testing/uParser/uTagTests.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
3
2015-11-23T14:24:06.000Z
2017-11-21T21:04:06.000Z
NGS_testing/uParser/uTagTests.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
null
null
null
NGS_testing/uParser/uTagTests.cpp
NGS-lib/NGSplusplus
7fa9fff2453917f24e9e35dab1f04a9be67f7f13
[ "BSL-1.0" ]
null
null
null
#include "uFormats.h" #include "uTags.h" #include "uRegion.h" #include <iostream> #include <string> #include <fstream> #include <vector> #include <time.h> #include <thread> #include <random> #include <string.h> #include "utility/utility.h" #include <time.h> #include <gtest/gtest.h> using namespace NGS; /**< Testing our unitary Tag */ TEST(uTagsTest, DefaultCTR){ uTags uTest; EXPECT_EQ(StrandDir::FORWARD,uTest.getStrand()); EXPECT_FALSE(uTest.isPE()); EXPECT_EQ(0,uTest.getStart()); EXPECT_EQ(0,uTest.getEnd()); } TEST(uTagsTest, 3ParCTR){ uTags Utest("chr1", 100, 200); EXPECT_EQ("chr1",Utest.getChr()); EXPECT_EQ(StrandDir::FORWARD,Utest.getStrand()); EXPECT_FALSE(Utest.isPE()); EXPECT_EQ(100,Utest.getStart()); EXPECT_EQ(200,Utest.getEnd()); } TEST(uTagsTest, 3ParCTRMinus){ EXPECT_ANY_THROW(uTags Utest("chr1", 200, 100)); // EXPECT_EQ("chr1",Utest.getChr()); // EXPECT_EQ(StrandDir::REVERSE,Utest.getStrand()); // EXPECT_FALSE(Utest.isPE()); // EXPECT_EQ(100,Utest.getStart()); // EXPECT_EQ(200,Utest.getEnd()); } TEST(uTagsTest, SetGet){ uTags Utest("chr1", 100, 200); uTags copyTag; Utest.setName("My Name is"); EXPECT_EQ("My Name is", Utest.getName()); EXPECT_EQ("", copyTag.getName()); Utest.setPhred("My Phred is"); EXPECT_EQ("My Phred is", Utest.getPhred()); Utest.setPhred("Now it is yar ar ar"); EXPECT_EQ("Now it is yar ar ar", Utest.getPhred()); copyTag=Utest; EXPECT_EQ("Now it is yar ar ar", Utest.getPhred()); Utest.setCigar("Hohoho"); EXPECT_EQ("Hohoho", Utest.getCigar()); } TEST(uTagsTest, CopyCTR){ uTags copyFrom("chr1", 100, 200); uTags copyTo; uTags copyFilled("chr4", 100000, 2000000); copyFrom.setName("My Name is"); copyFrom.setPhred("My Phred is"); copyFrom.setCigar("Hohoho"); copyFrom.setPELength(10); copyFrom.setMapQual(33); copyFrom.setSequence("LalaBonjourPatate"); copyTo.setChr("chr22"); copyTo.setMapped(true); copyTo=copyFrom; EXPECT_EQ(copyFrom.getPeLength(), copyTo.getPeLength()); EXPECT_EQ(copyFrom.getSequence(), copyTo.getSequence()); EXPECT_EQ(copyFrom.getMapQual(), copyTo.getMapQual()); EXPECT_EQ(copyFrom.getStrand(), copyTo.getStrand()); EXPECT_EQ(copyFrom.getName(), copyTo.getName()); EXPECT_EQ(copyFrom.getPhred(), copyTo.getPhred()); EXPECT_EQ(copyFrom.getSequence(), copyTo.getSequence()); EXPECT_EQ(copyFrom.getStart(), copyTo.getStart()); EXPECT_EQ(copyFrom.getChr(), copyTo.getChr()); EXPECT_EQ(copyFrom.getEnd(), copyTo.getEnd()); EXPECT_EQ(copyFrom.getCigar(), copyTo.getCigar()); copyTo.setChr("chr21"); EXPECT_NE(copyTo.getChr(),copyFrom.getChr()); copyFilled = copyFrom; EXPECT_EQ(copyFrom.getName(), copyFilled.getName()); EXPECT_EQ(copyFrom.getPhred(), copyFilled.getPhred()); EXPECT_EQ(copyFrom.getSequence(), copyFilled.getSequence()); EXPECT_EQ(copyFrom.getStart(), copyFilled.getStart()); EXPECT_EQ(copyFrom.getChr(), copyFilled.getChr()); EXPECT_EQ(copyFrom.getEnd(), copyFilled.getEnd()); } TEST(factoryTest, uTagsTest){ EXPECT_NO_THROW(uTags ourTest=factory::makeTagfromSamString("HWI-ST333_0111_FC:6:2202:20769:154221#TAGTCG/3 163 chr21 9719905 15 40M = 9719985 120 AGCAATTATCTTCACATAAAAACTACACAGAAACTTTCTG aaacceeegggggiiiiiiiiiihiihihiiiiiiiiiih X0:i:2 X1:i:57 MD:Z:2G2A27T6 XG:i:0 AM:i:0 NM:i:3 SM:i:0 XM:i:3 XO:i:0 XT:A:R")); uTags ourTest=factory::makeTagfromSamString("HWI-ST333_0111_FC:6:2202:20769:154221#TAGTCG/3 163 chr21 9719905 15 40M = 9719985 120 AGCAATTATCTTCACATAAAAACTACACAGAAACTTTCTG aaacceeegggggiiiiiiiiiihiihihiiiiiiiiiih X0:i:2 X1:i:57 MD:Z:2G2A27T6 XG:i:0 AM:i:0 NM:i:3 SM:i:0 XM:i:3 XO:i:0 XT:A:R"); EXPECT_EQ(ourTest.getChr(),"chr21"); EXPECT_EQ(ourTest.getLength(),40); EXPECT_EQ(ourTest.getStart(),9719905); EXPECT_EQ(ourTest.getEnd(),9719944); EXPECT_EQ(ourTest.getStrand(),StrandDir::FORWARD); uTags minusStrand; minusStrand=factory::makeTagfromSamString("HWI-ST333_0111_FC:6:2202:20769:154221#TAGTCG/3 83 chr21 9719905 15 40M = 9719985 120 AGCAATTATCTTCACATAAAAACTACACAGAAACTTTCTG aaacceeegggggiiiiiiiiiihiihihiiiiiiiiiih X0:i:2 X1:i:57 MD:Z:2G2A27T6 XG:i:0 AM:i:0 NM:i:3 SM:i:0 XM:i:3 XO:i:0 XT:A:R"); EXPECT_EQ(minusStrand.getStrand(),StrandDir::REVERSE); }
33.930233
314
0.705278
NGS-lib
7d3013745deb7db393378c97e18ae3e8e2f42bc3
2,808
cpp
C++
tests/RaZ/Render/Shader.cpp
Sausty/RaZ
211cc1c0c4a7374520a3141fc069b7717e2e5e0f
[ "MIT" ]
339
2017-09-24T17:26:15.000Z
2022-03-20T13:25:39.000Z
tests/RaZ/Render/Shader.cpp
Sausty/RaZ
211cc1c0c4a7374520a3141fc069b7717e2e5e0f
[ "MIT" ]
24
2017-09-22T10:30:12.000Z
2022-01-05T21:32:20.000Z
tests/RaZ/Render/Shader.cpp
Sausty/RaZ
211cc1c0c4a7374520a3141fc069b7717e2e5e0f
[ "MIT" ]
24
2018-01-21T17:38:18.000Z
2022-02-02T11:16:22.000Z
#include "Catch.hpp" #include "RaZ/Render/Renderer.hpp" #include "RaZ/Render/Shader.hpp" TEST_CASE("Shader validity") { Raz::Renderer::recoverErrors(); // Flushing errors { Raz::VertexShader vertShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); vertShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(vertShader.isValid()); } { Raz::GeometryShader geomShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(geomShader.isValid()); geomShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(geomShader.isValid()); } { Raz::FragmentShader fragShader; CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); fragShader.destroy(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK_FALSE(fragShader.isValid()); } } TEST_CASE("Vertex shader from source") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string vertSource = R"( #version 330 core void main() { gl_Position = vec4(1.0); } )"; const Raz::VertexShader vertShader = Raz::VertexShader::loadFromSource(vertSource); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); vertShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isCompiled()); } TEST_CASE("Fragment shader from source") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string fragSource = R"( #version 330 core layout(location = 0) out vec4 fragColor; void main() { fragColor = vec4(1.0); } )"; const Raz::FragmentShader fragShader = Raz::FragmentShader::loadFromSource(fragSource); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); fragShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isCompiled()); } TEST_CASE("Vertex shader imported") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string vertShaderPath = RAZ_TESTS_ROOT + "../shaders/common.vert"s; const Raz::VertexShader vertShader(vertShaderPath); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isValid()); CHECK(vertShader.getPath() == vertShaderPath); vertShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(vertShader.isCompiled()); } TEST_CASE("Fragment shader imported") { Raz::Renderer::recoverErrors(); // Flushing errors const std::string fragShaderPath = RAZ_TESTS_ROOT + "../shaders/lambert.frag"s; const Raz::FragmentShader fragShader(fragShaderPath); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isValid()); CHECK(fragShader.getPath() == fragShaderPath); fragShader.compile(); CHECK_FALSE(Raz::Renderer::hasErrors()); CHECK(fragShader.isCompiled()); }
25.297297
89
0.696581
Sausty
7d3273f11efd2af5e0ee426d3c1790d19dd893b3
6,546
cpp
C++
brain/sw/components/brain-httpd/firmware_handler.cpp
tomseago/sparklemotion
572369ff67977be3626a1162d208a33dddd33e63
[ "MIT" ]
24
2019-03-21T23:17:24.000Z
2022-03-10T07:59:27.000Z
brain/sw/components/brain-httpd/firmware_handler.cpp
tomseago/sparklemotion
572369ff67977be3626a1162d208a33dddd33e63
[ "MIT" ]
138
2019-03-21T23:29:48.000Z
2022-03-22T05:01:47.000Z
brain/sw/components/brain-httpd/firmware_handler.cpp
tomseago/sparklemotion
572369ff67977be3626a1162d208a33dddd33e63
[ "MIT" ]
5
2019-06-09T00:50:38.000Z
2022-02-02T04:22:44.000Z
// // Created by Tom Seago on 2019-08-07. // #include "firmware_handler.h" #include "http_server.h" #include <string.h> #include <sys/param.h> #include <esp_ota_ops.h> /* Max length a file path can have on storage */ //#define FILE_PATH_MAX (ESP_VFS_PATH_MAX + CONFIG_SPIFFS_OBJ_NAME_LEN) #define SCRATCH_BUFSIZE 8192 #define TAG TAG_HTTPD static esp_err_t glue_putHandler(httpd_req_t *req) { if (!req) return ESP_ERR_INVALID_ARG; return ((FirmwareHandler*)(req->user_ctx))->_putHandler(req); } esp_err_t FirmwareHandler::registerHandlers(HttpServer &server) { // Also do the equivalent initialization stuff - maybe want to come up with // a scheme for doing this better elsewhere //strcpy(this->basePath, "/spiffs/www"); httpd_uri_t firmwareHandler = { .uri = "/firmware", .method = HTTP_POST, .handler = glue_putHandler, .user_ctx = this, }; esp_err_t err; err = httpd_register_uri_handler(server.m_hServer, &firmwareHandler); if (ESP_OK != err) { ESP_LOGE(TAG, "Failed to register PUT uri handler %d", err); return err; } return ESP_OK; } // #define IS_FILE_EXT(filename, ext) \ // // (strcasecmp(&filename[strlen(filename) - sizeof(ext) + 1], ext) == 0) /* Set HTTP response content type according to file extension */ //static esp_err_t set_content_type_from_file(httpd_req_t *req, const char *filename) //{ // if (IS_FILE_EXT(filename, ".pdf")) { // return httpd_resp_set_type(req, "application/pdf"); // } else if (IS_FILE_EXT(filename, ".html")) { // return httpd_resp_set_type(req, "text/html"); // } else if (IS_FILE_EXT(filename, ".jpeg")) { // return httpd_resp_set_type(req, "image/jpeg"); // } else if (IS_FILE_EXT(filename, ".ico")) { // return httpd_resp_set_type(req, "image/x-icon"); // } // /* This is a limited set only */ // /* For any other type always set as plain text */ // return httpd_resp_set_type(req, "text/plain"); //} // ///* Copies the full path into destination buffer and returns // * pointer to path (skipping the preceding base path) */ //static const char* get_path_from_uri(char *dest, const char *base_path, const char *uri, size_t destsize) //{ // const size_t base_pathlen = strlen(base_path); // size_t pathlen = strlen(uri); // // const char *quest = strchr(uri, '?'); // if (quest) { // pathlen = MIN(pathlen, quest - uri); // } // const char *hash = strchr(uri, '#'); // if (hash) { // pathlen = MIN(pathlen, hash - uri); // } // // if (base_pathlen + pathlen + 1 > destsize) { // /* Full path string won't fit into destination buffer */ // return NULL; // } // // /* Construct full path (base + path) */ // strcpy(dest, base_path); // strlcpy(dest + base_pathlen, uri, pathlen + 1); // // /* Return pointer to path, skipping the base */ // return dest + base_pathlen; //} static void logFree(void *ctx) { ESP_LOGI(TAG, "Freeing a ctx"); free(ctx); } esp_err_t FirmwareHandler::_putHandler(httpd_req_t *req) { ESP_LOGE(TAG, "==== OTA via HTTP PUT Started ===="); // Could check filesize, but don't really care // req->content_len const esp_partition_t* updatePartition = esp_ota_get_next_update_partition(nullptr); if (!updatePartition) { ESP_LOGE(TAG, "Unable to get a next ota update partition"); return ESP_FAIL; } esp_ota_handle_t otaHandle; if (ESP_ERROR_CHECK_WITHOUT_ABORT(esp_ota_begin(updatePartition, OTA_SIZE_UNKNOWN, &otaHandle)) != ESP_OK) { return ESP_FAIL; } ESP_LOGE(TAG, "ota_begin() call succeeded."); ESP_LOGI(TAG, " type = %d", updatePartition->type); ESP_LOGI(TAG, " subtype = %d", updatePartition->subtype); ESP_LOGI(TAG, " address = 0x%x", updatePartition->address); ESP_LOGI(TAG, " size = %d", updatePartition->size); ESP_LOGI(TAG, " label = %s", updatePartition->label); if (!req->sess_ctx) { ESP_LOGI(TAG, "Creating a new session context"); req->sess_ctx = malloc(SCRATCH_BUFSIZE); if (!req->sess_ctx) { ESP_LOGE(TAG, "Failed to create session chunk buffer"); return ESP_FAIL; } req->free_ctx = logFree; } int received; int remaining = req->content_len; char* buf = (char*)req->sess_ctx; while (remaining > 0) { ESP_LOGI(TAG, "Remaining OTA size : %d", remaining); /* Receive the file part by part into a buffer */ if ((received = httpd_req_recv(req, buf, MIN(remaining, SCRATCH_BUFSIZE))) <= 0) { if (received == HTTPD_SOCK_ERR_TIMEOUT) { /* Retry if timeout occurred */ continue; } /* In case of unrecoverable error, * close and delete the unfinished file*/ esp_ota_end(otaHandle); ESP_LOGE(TAG, "Firmware reception failed!"); /* Respond with 500 Internal Server Error */ httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to receive firmware"); return ESP_FAIL; } /* Write buffer content to file on storage */ if (esp_ota_write(otaHandle, buf, received) != ESP_OK) { esp_ota_end(otaHandle); ESP_LOGE(TAG, "Firmware write failed!"); /* Respond with 500 Internal Server Error */ httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to write file to storage"); return ESP_FAIL; } /* Keep track of remaining size of * the file left to be uploaded */ remaining -= received; } auto endResult = esp_ota_end(otaHandle); if (endResult != ESP_OK) { ESP_LOGE(TAG, "OTA Failed with %d", endResult); /* Respond with an empty chunk to signal HTTP response completion */ httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; } ESP_LOGE(TAG, "==== Valid OTA received ===="); auto setResult = esp_ota_set_boot_partition(updatePartition); if (setResult != ESP_OK) { ESP_LOGE(TAG, "Setting the OTA boot partition failed: %d", endResult); /* Respond with an empty chunk to signal HTTP response completion */ httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; } ESP_LOGE(TAG, "Boot partition set, Triggering restart"); brain_restart(500); httpd_resp_send_chunk(req, NULL, 0); return ESP_OK; }
33.228426
112
0.624809
tomseago
7d392cb87a83460a79a6304169facef98f988304
2,451
cpp
C++
test/test.cpp
AZMDDY/astar
49ea623e042181e29a3de17bf79ec872d104fe61
[ "MIT" ]
2
2020-10-20T00:03:49.000Z
2020-10-24T09:27:13.000Z
test/test.cpp
AZMDDY/astar
49ea623e042181e29a3de17bf79ec872d104fe61
[ "MIT" ]
null
null
null
test/test.cpp
AZMDDY/astar
49ea623e042181e29a3de17bf79ec872d104fe61
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include "point.hpp" #include "map.hpp" #include "astar.hpp" #include "play.hpp" using namespace astar; Point MapRandPoint(uint32_t h, uint32_t w) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, h * w); auto res = dis(gen); int pH = res / w; int pW = res - pH * w; return {pW, pH}; } void GenBarrier(Map& map) { uint32_t count = (map.Height() * map.Width()) / 8; for (uint32_t i = 0; i < count;) { auto point = MapRandPoint(map.Height(), map.Width()); if (map.At(point) == 0) { map.Assign(point, 1); i++; } else { continue; } } } void GenStartAndEnd(Map& map, Point& start, Point& end) { if (map.Empty()) { return; } for (uint32_t i = 0; i < 2;) { auto point = MapRandPoint(map.Height(), map.Width()); if (map.At(point) == 0) { if (i == 0) { map.Assign(point, 2); start = point; } else { map.Assign(point, 3); end = point; } i++; } else { continue; } } } int main(int argc, char** argv) { uint32_t mapHeight = 0; uint32_t mapWidth = 0; std::cout << "map width: "; std::cin >> mapWidth; std::cout << "map height: "; std::cin >> mapHeight; Map maze(mapWidth, mapHeight); GenBarrier(maze); Point start; Point end; GenStartAndEnd(maze, start, end); AStar aStar(D8); aStar.LoadMap(maze); auto path = aStar.FindPath(start, end); // display the maze uint32_t count = 0; PrintMaze(maze); if (path.empty()) { std::cout << "path not found" << std::endl; return 0; } while (count < path.size()) { std::this_thread::sleep_for(1s); ClearScreen(maze.Height() + 1); maze.Assign(path[count], 4); PrintMaze(maze); ClearScreen(1); std::cout << "(" << path[count].x << ", " << path[count].y << ")" << std::endl; count++; } ClearScreen(maze.Height() + 1); PrintMaze(maze); uint32_t i = 0; for (; i < (path.size() - 1); i++) { std::cout << "(" << path[i].x << ", " << path[i].y << ") -> "; } std::cout << "(" << path[i].x << ", " << path[i].y << ")" << std::endl; return 0; }
23.122642
87
0.485924
AZMDDY
7d3c01ed6da3271047049ba6a690530cb4932984
8,237
cpp
C++
src/zoneserver/service/cheat/CheatService.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
src/zoneserver/service/cheat/CheatService.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
src/zoneserver/service/cheat/CheatService.cpp
mark-online/server
ca24898e2e5a9ccbaa11ef1ade57bb25260b717f
[ "MIT" ]
null
null
null
#include "ZoneServerPCH.h" #include "CheatService.h" #include "../arena/ArenaService.h" #include "../../model/gameobject/EntityEvent.h" #include "../../model/gameobject/Entity.h" #include "../../model/gameobject/AbstractAnchor.h" #include "../../model/gameobject/ability/Cheatable.h" #include "../../model/gameobject/ability/Networkable.h" #include "../../controller/EntityController.h" #include "../../controller/callback/BotCommandCallback.h" #include "../../controller/callback/BuildingStateCallback.h" #include "../../helper/InventoryHelper.h" #include "../../service/anchor/AnchorService.h" #include "../../service/arena/ArenaService.h" #include "../../world/World.h" #include "../../ZoneService.h" #include "../../s2s/ZoneArenaServerProxy.h" #include <sne/core/utility/Unicode.h> #include <boost/lexical_cast.hpp> namespace gideon { namespace zoneserver { /** * @class BotMoveEvent */ class BotMoveEvent : public go::EntityEvent, public sne::core::ThreadSafeMemoryPoolMixin<BotMoveEvent> { public: BotMoveEvent(const Position& position) : position_(position) {} private: virtual void call(go::Entity& entity) { gc::BotCommandCallback* callback = entity.getController().queryBotCommandCallback(); if (callback != nullptr) { callback->commandMoved(position_); } } private: const Position position_; }; /** * @class BotSkillCastEvent */ class BotSkillCastEvent : public go::EntityEvent, public sne::core::ThreadSafeMemoryPoolMixin<BotSkillCastEvent> { public: BotSkillCastEvent() {} private: virtual void call(go::Entity& entity) { gc::BotCommandCallback* callback = entity.getController().queryBotCommandCallback(); if (callback != nullptr) { callback->commandSkillCasted(); } } }; void CheatService::execute(go::Cheatable& cheatable, ObjectId ownerId, const wstring_t& command, const wstring_t& params) { if (! cheatable.canCheatable()) { return; } try { if (command == L"/additem") { const size_t find_pos = params.find_first_of(L" "); const string_t param1 = sne::core::toUtf8(params.substr(0, find_pos)); const string_t param2 = sne::core::toUtf8(params.substr(find_pos + 1)); const DataCode itemCode = boost::lexical_cast<DataCode>(param1); const uint8_t itemCount = uint8_t(boost::lexical_cast<uint32_t>(param2)); const uint8_t revisionItemCount = itemCount > getStackItemCount(itemCode) ? getStackItemCount(itemCode) : itemCount; const CodeType ct = getCodeType(itemCode); if (isItemType(ct)) { cheatable.cheatAddItem(itemCode, revisionItemCount); } } else if (command == L"/move") { const size_t find_pos = params.find_first_of(L" "); const wstring_t param1 = params.substr(0, find_pos); const wstring_t param2 = params.substr(find_pos + 1); const Position position(boost::lexical_cast<float32_t>(param1), boost::lexical_cast<float32_t>(param2), 0.0f); BotMoveEvent::Ref event(new BotMoveEvent(position)); WORLD->broadcast(event); // 브로드 캐스팅 } else if (command == L"/castskill") { BotSkillCastEvent::Ref event(new BotSkillCastEvent()); WORLD->broadcast(event); } else if (command == L"/fullpoints") { cheatable.cheatFullCharacterPoints(); } else if (command == L"/rewardexp") { const ExpPoint rewardExp = toExpPoint(boost::lexical_cast<int>(params)); cheatable.cheatRewardExp(rewardExp < ceMin ? ceMin: rewardExp); } else if (command == L"/showmethemoney") { const GameMoney money = boost::lexical_cast<GameMoney>(params); cheatable.cheatUpGameMoney(money < 0 ? 0 : money); } else if (command == L"/addskill") { const SkillCode skillCode = boost::lexical_cast<SkillCode>(params); cheatable.cheatAddSkill(skillCode); } else if (command == L"/recall") { const size_t find_pos = params.find_first_of(L" "); const Nickname nickname = params.substr(0, find_pos); cheatable.cheatRecall(nickname); } else if (command == L"/toplayer") { const size_t find_pos = params.find_first_of(L" "); const Nickname nickname = params.substr(0, find_pos); cheatable.cheatTeleportToPlayer(nickname); } else if (command == L"/toposition") { wstring_t tempParams = params; size_t find_pos = params.find_first_of(L" "); const wstring_t param1 = tempParams.substr(0, find_pos); tempParams = tempParams.substr(find_pos + 1); find_pos = tempParams.find_first_of(L" "); const wstring_t param2 = tempParams.substr(0, find_pos); tempParams = tempParams.substr(find_pos + 1); const wstring_t param3 = tempParams.substr(0, find_pos); const float32_t positionX = boost::lexical_cast<float32_t>(param1); const float32_t positionY = boost::lexical_cast<float32_t>(param2); const float32_t positionZ = boost::lexical_cast<float32_t>(param3); cheatable.cheatTeleportToPosition(Position(positionX, positionY, positionZ)); } else if (command == L"/mercenarypoint") { const MercenaryPoint mercenaryPoint = boost::lexical_cast<MercenaryPoint>(params); cheatable.cheatMercenaryPoint(mercenaryPoint < 0 ? 0 : mercenaryPoint); } else if (command == L"/logout") { const size_t find_pos = params.find_first_of(L" "); const Nickname nickname = params.substr(0, find_pos); go::Entity* player = WORLD->getPlayer(nickname); if (player) { player->queryNetworkable()->logout(); } } else if (command == L"/arenapoint") { const ArenaPoint arenaPoint = boost::lexical_cast<ArenaPoint>(params); cheatable.cheatArenaPoint(arenaPoint < 0 ? 0 : arenaPoint); } else if (command == L"/releasedeserter") { if (ZONE_SERVICE->isArenaServer()) { ARENA_SERVICE->releaseDeserter(ownerId); } else { ZONE_SERVICE->getArenaServerProxy().z2a_releaseDeserter(ownerId); } } else if (command == L"/who") { cheatable.cheatWhoIsInZone(); } else if (command == L"/destorybuilding") { const ObjectId buildingId = boost::lexical_cast<ObjectId>(params); go::AbstractAnchor* abstractAnchor = ANCHOR_SERVICE->getAnchor(GameObjectInfo(otBuilding, buildingId)); if (abstractAnchor) { gc::BuildingStateCallback* callback = abstractAnchor->getController().queryBuildingStateCallback(); if (callback) { callback->buildDestroyed(); static_cast<go::Entity*>(abstractAnchor)->despawn(); } } } else if (command == L"/destoryanchor") { const ObjectId buildingId = boost::lexical_cast<ObjectId>(params); go::AbstractAnchor* abstractAnchor = ANCHOR_SERVICE->getAnchor(GameObjectInfo(otAnchor, buildingId)); if (abstractAnchor) { static_cast<go::Entity*>(abstractAnchor)->despawn(); } } else if (command == L"/resetcooltime") { cheatable.cheatResetCooldown(); } else if (command == L"/acceptquest") { const QuestCode questCode = boost::lexical_cast<QuestCode>(params); cheatable.cheatAcceptQuest(questCode); } else if (command == L"/forgeCoin") { const ForgeCoin forgeCoin = boost::lexical_cast<ForgeCoin>(params); cheatable.cheatForgeCoin(forgeCoin < 0 ? 0 : forgeCoin); } } catch (boost::bad_lexical_cast&) { SNE_LOG_ERROR("bad cheat key") } } }} // namespace gideon { namespace zoneserver {
40.576355
115
0.613573
mark-online
7d42aec8e09eca5b92cc375c7235b51ff9e93e21
4,171
hpp
C++
include/foxy/impl/session/async_read.impl.hpp
djarek/foxy
c5a008760505f670e599216e003f08963c32d201
[ "BSL-1.0" ]
null
null
null
include/foxy/impl/session/async_read.impl.hpp
djarek/foxy
c5a008760505f670e599216e003f08963c32d201
[ "BSL-1.0" ]
null
null
null
include/foxy/impl/session/async_read.impl.hpp
djarek/foxy
c5a008760505f670e599216e003f08963c32d201
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot // 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/LeonineKing1199/foxy // #ifndef FOXY_IMPL_SESSION_ASYNC_READ_IMPL_HPP_ #define FOXY_IMPL_SESSION_ASYNC_READ_IMPL_HPP_ #include <foxy/session.hpp> namespace foxy { namespace detail { template <class Stream, class Parser, class ReadHandler> struct read_op : boost::asio::coroutine { private: struct state { ::foxy::basic_session<Stream>& session; Parser& parser; boost::asio::executor_work_guard<decltype(session.get_executor())> work; explicit state(ReadHandler const& handler, ::foxy::basic_session<Stream>& session_, Parser& parser_) : session(session_) , parser(parser_) , work(session.get_executor()) { } }; boost::beast::handler_ptr<state, ReadHandler> p_; public: read_op() = delete; read_op(read_op const&) = default; read_op(read_op&&) = default; template <class DeducedHandler> read_op(::foxy::basic_session<Stream>& session, Parser& parser, DeducedHandler&& handler) : p_(std::forward<DeducedHandler>(handler), session, parser) { } using executor_type = boost::asio::associated_executor_t< ReadHandler, decltype((std::declval<::foxy::basic_session<Stream>&>().get_executor()))>; using allocator_type = boost::asio::associated_allocator_t<ReadHandler>; auto get_executor() const noexcept -> executor_type { return boost::asio::get_associated_executor(p_.handler(), p_->session.get_executor()); } auto get_allocator() const noexcept -> allocator_type { return boost::asio::get_associated_allocator(p_.handler()); } auto operator()(boost::system::error_code ec, std::size_t const bytes_transferred, bool const is_continuation = true) -> void; }; template <class Stream, class Parser, class ReadHandler> auto read_op<Stream, Parser, ReadHandler>:: operator()(boost::system::error_code ec, std::size_t const bytes_transferred, bool const is_continuation) -> void { using namespace std::placeholders; using boost::beast::bind_handler; namespace http = boost::beast::http; auto& s = *p_; BOOST_ASIO_CORO_REENTER(*this) { BOOST_ASIO_CORO_YIELD http::async_read(s.session.stream, s.session.buffer, s.parser, std::move(*this)); if (ec) { goto upcall; } { auto work = std::move(s.work); return p_.invoke(boost::system::error_code(), bytes_transferred); } upcall: if (!is_continuation) { BOOST_ASIO_CORO_YIELD boost::asio::post(bind_handler(std::move(*this), ec, 0)); } auto work = std::move(s.work); p_.invoke(ec, 0); } } } // namespace detail template <class Stream, class X> template <class Parser, class ReadHandler> auto basic_session<Stream, X>::async_read( Parser& parser, ReadHandler&& handler) & -> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void(boost::system::error_code, std::size_t)) { boost::asio::async_completion<ReadHandler, void(boost::system::error_code, std::size_t)> init(handler); detail::timed_op_wrapper<Stream, detail::read_op, BOOST_ASIO_HANDLER_TYPE( ReadHandler, void(boost::system::error_code, std::size_t)), void(boost::system::error_code, std::size_t)>( *this, std::move(init.completion_handler)) .template init<Stream, Parser>(parser); return init.result.get(); } } // namespace foxy #endif // FOXY_IMPL_SESSION_ASYNC_READ_IMPL_HPP_
28.37415
80
0.614481
djarek
7d43465d3369eb5606cc416932eb52bd194549d1
2,428
cpp
C++
src/container/Handle.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
45
2018-08-24T12:57:38.000Z
2021-11-12T11:21:49.000Z
src/container/Handle.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
null
null
null
src/container/Handle.cpp
Lyatus/L
0b594d722200d5ee0198b5d7b9ee72a5d1e12611
[ "Unlicense" ]
4
2019-09-16T02:48:42.000Z
2020-07-10T03:50:31.000Z
#include "Handle.h" #include <atomic> #include "../system/Memory.h" using namespace L; static constexpr uint32_t address_bits = 48; static constexpr uint64_t address_mask = (1ull << address_bits) - 1; static constexpr uint64_t version_bits = 16; static constexpr uint64_t version_mask = (1ull << version_bits) - 1; static uint64_t* handle_objects = nullptr; static std::atomic<uint64_t> next_index = {0}; static std::atomic<uint64_t> freelist = {address_mask}; GenericHandle::GenericHandle(void* ptr) { L_ASSERT((uint64_t(ptr) & address_mask) == uint64_t(ptr)); for(uint64_t freeslot_index; freeslot_index = freelist, freelist != address_mask;) { const uint64_t freeslot = handle_objects[freeslot_index]; const uint64_t version = freeslot >> address_bits; const uint64_t new_freeslot_index = freeslot & address_mask; _ver_index = (version << address_bits) | freeslot_index; if(!freelist.compare_exchange_strong(freeslot_index, new_freeslot_index)) { continue; } handle_objects[freeslot_index] = (version << address_bits) | (uint64_t)ptr; return; } // Allocate memory for handle slots if(handle_objects == nullptr) { handle_objects = (uint64_t*)Memory::virtual_alloc(1ull << 20); } // Allocate new handle slot _ver_index = next_index++; handle_objects[_ver_index] = uint64_t(ptr); } void* GenericHandle::pointer() const { if(_ver_index != UINT64_MAX) { const uint64_t version = _ver_index >> address_bits; const uint64_t index = _ver_index & address_mask; const uint64_t object = handle_objects[index]; // Check object version matches if((object >> address_bits) == version) { return (void*)(object & address_mask); } } return nullptr; } uint64_t GenericHandle::index() const { return _ver_index & address_mask; } void GenericHandle::release() { if(_ver_index != UINT64_MAX) { const uint64_t version = _ver_index >> address_bits; const uint64_t new_freeslot_index = _ver_index & address_mask; const uint64_t new_freeslot = handle_objects[new_freeslot_index]; if((new_freeslot >> address_bits) == version) { uint64_t old_freeslot; do { old_freeslot = freelist; handle_objects[new_freeslot_index] = ((version + 1) << address_bits) | old_freeslot; } while(!freelist.compare_exchange_strong(old_freeslot, new_freeslot_index)); } _ver_index = UINT64_MAX; } }
31.128205
92
0.714168
Lyatus
7d53e8ed09ee0737c09b0d0b08b4f8b18c49fcf2
3,441
cpp
C++
test/src/test_enumeration.cpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
192
2016-09-29T17:10:07.000Z
2022-03-22T15:22:48.000Z
test/src/test_enumeration.cpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
35
2016-10-03T16:57:12.000Z
2021-09-28T13:11:15.000Z
test/src/test_enumeration.cpp
ivangalkin/spotify-json
68cfafc488ffae851cca3f556b90129cffb26be1
[ "Apache-2.0" ]
47
2016-09-29T08:21:32.000Z
2022-03-19T10:05:43.000Z
/* * Copyright (c) 2015-2016 Spotify AB * * 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 <string> #include <boost/test/unit_test.hpp> #include <spotify/json/codec/string.hpp> #include <spotify/json/codec/enumeration.hpp> #include <spotify/json/decode.hpp> #include <spotify/json/encode.hpp> #include <spotify/json/encode_exception.hpp> BOOST_AUTO_TEST_SUITE(spotify) BOOST_AUTO_TEST_SUITE(json) BOOST_AUTO_TEST_SUITE(codec) namespace { template <typename Codec> typename Codec::object_type test_decode(const Codec &codec, const std::string &json) { decode_context c(json.c_str(), json.c_str() + json.size()); auto obj = codec.decode(c); BOOST_CHECK_EQUAL(c.position, c.end); return obj; } template <typename Codec> void test_decode_fail(const Codec &codec, const std::string &json) { decode_context c(json.c_str(), json.c_str() + json.size()); BOOST_CHECK_THROW(codec.decode(c), decode_exception); } enum class Test { A, B }; } // namespace /* * Constructing */ BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct) { enumeration_t<Test, string_t> codec( string(), std::vector<std::pair<Test, std::string>>()); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_helper_with_codec) { enumeration<Test>(string(), { { Test::A, "A" } }); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_multiple_parameters_helper_with_codec) { enumeration<Test>(string(), { { Test::A, "A" }, { Test::B, "B" } }); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_helper) { enumeration<Test, std::string>({ { Test::A, "A" } }); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_construct_with_multiple_parameters_helper) { enumeration<Test, std::string>({ { Test::A, "A" }, { Test::B, "B" } }); } /* * Decoding */ BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_decode) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" }, { Test::B, "B" } }); BOOST_CHECK(test_decode(codec, "\"A\"") == Test::A); BOOST_CHECK(test_decode(codec, "\"B\"") == Test::B); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_not_decode_invalid_value) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" } }); test_decode_fail(codec, "\"B\""); } /* * Encoding */ BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_encode) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" }, { Test::B, "B" } }); BOOST_CHECK_EQUAL(encode(codec, Test::A), "\"A\""); BOOST_CHECK_EQUAL(encode(codec, Test::B), "\"B\""); } BOOST_AUTO_TEST_CASE(json_codec_enumeration_should_not_encode_missing_value) { const auto codec = enumeration<Test, std::string>({ { Test::A, "A" } }); BOOST_CHECK_THROW(encode(codec, Test::B), encode_exception); } BOOST_AUTO_TEST_SUITE_END() // codec BOOST_AUTO_TEST_SUITE_END() // json BOOST_AUTO_TEST_SUITE_END() // spotify
29.410256
106
0.718396
ivangalkin
7d5b6bc46dca279363db254f7ec569c81fbdf343
801
cpp
C++
Competitive Programming/counting_valleys.cpp
darnoceloc/Algorithms
bc455cc00d9405493c951b8ea3132e615a49c9ee
[ "MIT" ]
null
null
null
Competitive Programming/counting_valleys.cpp
darnoceloc/Algorithms
bc455cc00d9405493c951b8ea3132e615a49c9ee
[ "MIT" ]
null
null
null
Competitive Programming/counting_valleys.cpp
darnoceloc/Algorithms
bc455cc00d9405493c951b8ea3132e615a49c9ee
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <limits> #include <fstream> // Complete the countingValleys function below. int countingValleys(int n, std::string s) { int elevation = 0; int valleys = 0; for(int i = 0; i < n; i++){ if(elevation == 0 && s[i] == 'D'){ valleys += 1; } if (s[i] == 'U'){ elevation += 1; } if (s[i] == 'D'){ elevation += -1; } } return valleys; } int main(){ std::ofstream fout(getenv("OUTPUT_PATH")); int n; std::cin >> n; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::string s; std::getline(std::cin, s); int result = countingValleys(n, s); fout << result << "\n"; fout.close(); return 0; }
19.536585
71
0.503121
darnoceloc
7d603fbc768f522484dd1870294162a515fa6ce7
1,990
cpp
C++
PraktiskieDarbi/praktiskaisDarbs1.cpp
ElizaGulbe/MIprogramma_darbi
4b1e027afe939317046d82e99d65a4d22d84651e
[ "MIT" ]
null
null
null
PraktiskieDarbi/praktiskaisDarbs1.cpp
ElizaGulbe/MIprogramma_darbi
4b1e027afe939317046d82e99d65a4d22d84651e
[ "MIT" ]
null
null
null
PraktiskieDarbi/praktiskaisDarbs1.cpp
ElizaGulbe/MIprogramma_darbi
4b1e027afe939317046d82e99d65a4d22d84651e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> using namespace std; float computeAvgValue(int arr[10]){ float sum = 0; for (int i = 0; i <= 9; i++) { sum += arr[i]; } float average = sum/10; return average; } float findBiggest(float arr[10]) { float curBiggest = arr[0]; for (int i = 1; i<=9; i++) { if (curBiggest < arr[i]) { curBiggest = arr[i]; } } return curBiggest; } void displayArray(int arr[5][5]){ for(int i = 0; i<5;i++) { for(int x = 0; x<5;x++) { if (x == 4) { cout << x << endl; } else { cout << x << " "; } } } } void twoDimensionalArr() { int twoDimArr[5][5]; for(int i = 0; i<5;i++){ for(int x = 0; x<5;x++){ twoDimArr[i][x] = x; } } displayArray(twoDimArr); } int countOccurance(string userInput) { int occuranceOfA = 0; for(char i: userInput) { if (i == 'a') { occuranceOfA++; } } return occuranceOfA; } string cutNumbers(string userInput){ string retVal; for(int i = 0; i < userInput.size(); i++){ if (isdigit(userInput[i]) == 0) { retVal.push_back(userInput[i]); } else{ continue; } } return retVal; } int main(){ string userInput; getline(cin,userInput); cout << "varda " << userInput << "simbols a atkartojas " << countOccurance(userInput) << " reizes" << endl; string cutDigits; getline(cin,cutDigits); cout << "iznemot no simbolu virkes " << cutDigits << " visus ciparus sanak " << cutNumbers(cutDigits) << endl; int arr[10] = {1,2,3,4,5,6,8,8,9,10}; cout << "masiva videja vertiba ir " << computeAvgValue(arr) << endl; float arrfloat[10] = {1.1,2.2,3.3,4.4,10.1,5.4,6.7,7.8,8.9,9.8}; cout << "find biggest retVal" << findBiggest(arrfloat) << endl; twoDimensionalArr(); return 0; }
22.359551
115
0.51608
ElizaGulbe
7d60c646d8121c85bd5c9787487373c9855e66da
1,848
cpp
C++
frameworks/runtime-src/Classes/lua-binding/manual/lua_cocos2dx_plugin_manual.cpp
edwardzhou/ddz-client
ed5db2b625cc55192027ffd69e0ec5f342a40222
[ "MIT" ]
5
2018-01-22T13:00:11.000Z
2021-02-20T04:24:30.000Z
frameworks/runtime-src/Classes/lua-binding/manual/lua_cocos2dx_plugin_manual.cpp
edwardzhou/ddz-client
ed5db2b625cc55192027ffd69e0ec5f342a40222
[ "MIT" ]
null
null
null
frameworks/runtime-src/Classes/lua-binding/manual/lua_cocos2dx_plugin_manual.cpp
edwardzhou/ddz-client
ed5db2b625cc55192027ffd69e0ec5f342a40222
[ "MIT" ]
5
2018-01-10T00:40:29.000Z
2021-08-22T14:12:44.000Z
#include "lua_cocos2dx_plugin_manual.hpp" #include "PluginManager.h" #include "PluginProtocol.h" #include "ProtocolAnalytics.h" #include "PluginParam.h" #include "tolua_fix.h" #include "LuaBasicConversions.h" int tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00(lua_State* tolua_S) { int argc = 0; cocos2d::plugin::PluginProtocol* cobj = nullptr; bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 if (!tolua_isusertype(tolua_S,1,"plugin.PluginProtocol",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::plugin::PluginProtocol*)tolua_tousertype(tolua_S,1,0); #if COCOS2D_DEBUG >= 1 if (!cobj) { tolua_error(tolua_S,"invalid 'cobj' in function 'tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00'", nullptr); return 0; } #endif argc = lua_gettop(tolua_S)-1; if (argc == 0) { CCLOG("%s has wrong number of arguments: %d, was expecting at least %d \n", "callFuncWithParam",argc, 1); return 0; } std::std::vector<cocos2d::plugin::PluginParam*> params; for (int i=0; i<argc; i++) { if (lua_istable(tolua_S, i+2) > 0) { // table } } #if COCOS2D_DEBUG >= 1 tolua_lerror: tolua_error(tolua_S,"#ferror in function 'tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00'.",&tolua_err); #endif return 0; } static void extendPluginProtocol(lua_State* L) { lua_pushstring(L, "plugin.PluginProtocol"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { tolua_function(L, "callFuncWithParam", tolua_Cocos2d_plugin_PluginProtocol_callFuncWithParam00); } lua_pop(L, 1); } int register_all_cocos2dx_plugin_manual(lua_State* L) { if (nullptr == L) return 0; extendPluginProtocol(L); return 0; }
24.315789
125
0.6829
edwardzhou
7d629a2a0ec8fc39bc991f5e0e713bd7433d5e1a
2,122
cpp
C++
src/person.cpp
arctech-training-worldline-cpp/HospitalManagementDemo
a553c9fa523ac1308564e424ce996a676557d91f
[ "MIT" ]
7
2021-07-04T18:18:02.000Z
2022-02-20T14:29:23.000Z
src/person.cpp
arctech-training-worldline-cpp/HospitalManagementDemo
a553c9fa523ac1308564e424ce996a676557d91f
[ "MIT" ]
null
null
null
src/person.cpp
arctech-training-worldline-cpp/HospitalManagementDemo
a553c9fa523ac1308564e424ce996a676557d91f
[ "MIT" ]
2
2021-11-08T13:30:34.000Z
2021-11-16T02:57:26.000Z
using namespace std; #include <vector> #include <string> #include <iostream> #include <sstream> #include <fstream> #include "./../include/global.hh" #include "./../include/person.hh" person::person() { id = -1; } void person::addPerson(int16_t minAge, int16_t maxAge) { //getting basic details of the person from the user side; cout << "\nEnter name: \nFirst name:\n"; getline(cin >> ws, firstName); cout << "\nLast name:\n"; getline(cin, lastName); cout << "\nEnter age: \n"; cin >> age; while (age <= 0) cout << "Was that supposed to make any kind of sense?\nEnter again!\n", cin >> age; if (category != 2) { if (age < minAge) return void(cout << "Sorry, person should be at least " << minAge << " years old to be registered as a " << cat << ".\n"); else if (age > maxAge) return void(cout << "Sorry, we can't register a person older than " << maxAge << " years as a " << cat << ".\n"); } cout << "\nGender (M = Male || F = Female): \n"; cin >> gender; while (gender != 'M' && gender != 'F') cout << "M or F?\n", cin >> gender; cout << "\nEnter mobile number (with country code): \n"; getline(cin >> ws, mobNumber); add.takeInput(); return; } void person::printDetails() { if (id == -1) return; cout << "\nDetails:\n"; cout << "ID : " << id << "\n"; cout << "Full Name : " << firstName << " " << lastName << "\n"; cout << "Gender : " << gender << "\n"; cout << "Age : " << age << "\n"; cout << "Mobile : " << mobNumber << "\n"; cout << "Address : "; add.print(); return; } void person::printDetailsFromHistory() { if (id == -1) return; cout << "\nHistory Details :\n"; cout << "Full Name : " << firstName << " " << lastName << "\n"; cout << "Gender : " << gender << "\n"; cout << "Age : " << age << "\n"; cout << "Mobile : " << mobNumber << "\n"; cout << "Address : "; add.print(); return; }
30.314286
134
0.494816
arctech-training-worldline-cpp
7d667e5944be9ad5c6921f9e298ff28bd8beec5d
3,161
cpp
C++
project3D/GameObject.cpp
nandos13/Shadercpp
404f2ab8d3b32073a54945081d74fac46bdd0178
[ "MIT" ]
null
null
null
project3D/GameObject.cpp
nandos13/Shadercpp
404f2ab8d3b32073a54945081d74fac46bdd0178
[ "MIT" ]
null
null
null
project3D/GameObject.cpp
nandos13/Shadercpp
404f2ab8d3b32073a54945081d74fac46bdd0178
[ "MIT" ]
null
null
null
#include "GameObject.h" #include "Application3D.h" #include <limits> glm::mat4 GameObject::getMatrixTransform() { // Define radian float rad = 3.14f / 180.0f; glm::mat4 transform = glm::translate(m_translation) * glm::rotate(m_rotationEuler.z * rad, glm::vec3(0, 0, 1)) * glm::rotate(m_rotationEuler.y * rad, glm::vec3(0, 1, 0)) * glm::rotate(m_rotationEuler.x * rad, glm::vec3(1, 0, 0)) * glm::scale(m_scale); return transform; } GameObject::GameObject() { m_translation = glm::vec3(0); m_rotationEuler = glm::vec3(0); m_scale = glm::vec3(1); } GameObject::~GameObject() { } void GameObject::Draw(glm::mat4 cameraMatrix, unsigned int programID) { // Verify the model exists if (m_model != nullptr) { // Get Lighting information and pass into shader GetLights(programID); // Pass info in to draw model m_model->Draw(getMatrixTransform(), cameraMatrix, programID); } } void GameObject::GetLights(unsigned int programID) { // Get the vector of scene lights std::vector<Light*> sceneLights = Application3D::GetLightSources(); Light* closeLights[8]; int size = sceneLights.size(); if (size > 8) { // Loop through all lights and find the closest 8 light sources int i = sceneLights.size() - 1; while (i > 0) { // Sort the list by distance to the gameobject if (glm::distance(sceneLights[i]->GetPosition(), this->m_translation) < glm::distance(sceneLights[i - 1]->GetPosition(), this->m_translation)) { // Swap the two elements std::iter_swap(sceneLights.begin()+i, sceneLights.begin()+i-1); // Move index up in case distance is larger than those already tested if (i != sceneLights.size() - 1) i++; } else { i--; } } } // Find how many objects need to be copied unsigned int quantity = (sceneLights.size() > 8) ? 8 : sceneLights.size(); // Copy first 8 elements to the new array for (unsigned int j = 0; j < quantity; j++) { closeLights[j] = sceneLights[j]; } // Pass in the amount of lights to be used unsigned int quantityUniform = glGetUniformLocation(programID, "lightQuantity"); glUniform1i(quantityUniform, quantity); // Pass in the light positions & information (intensity, etc) glm::vec3 closeLightPositions[8]; glm::vec2 closeLightInfo[8]; for (int i = 0; i < quantity; i++) { if (closeLights[i] != nullptr) { closeLightPositions[i] = closeLights[i]->GetPosition(); closeLightInfo[i] = glm::vec2(closeLights[i]->GetIntensity(), closeLights[i]->GetReach()); } } // Positions unsigned int lightsUniform = glGetUniformLocation(programID, "lights"); glUniform3fv(lightsUniform, 8, &closeLightPositions[0].x); // Other info unsigned int lightsInfoUniform = glGetUniformLocation(programID, "lightsInfo"); glUniform2fv(lightsInfoUniform, 8, &closeLightInfo[0].x); } void GameObject::SetModel(Model * model) { m_model = model; } Model * GameObject::GetModel() { return m_model; } void GameObject::SetTranslation(glm::vec3 translation) { m_translation = translation; } void GameObject::SetRotation(glm::vec3 euler) { m_rotationEuler = euler; } void GameObject::SetScale(glm::vec3 localScale) { m_scale = localScale; }
25.288
93
0.693135
nandos13
7d670b5a68f4d4dcb4a193ed68aa5994f9d91229
4,690
hpp
C++
order.hpp
chaosmw/youdex
78e1c20548183b7c9b30ec924ff0711c029123ef
[ "MIT" ]
1
2020-08-29T09:53:29.000Z
2020-08-29T09:53:29.000Z
order.hpp
chaosmw/youdex
78e1c20548183b7c9b30ec924ff0711c029123ef
[ "MIT" ]
null
null
null
order.hpp
chaosmw/youdex
78e1c20548183b7c9b30ec924ff0711c029123ef
[ "MIT" ]
null
null
null
#pragma once #include <eosiolib/eosio.hpp> #include <eosiolib/asset.hpp> #include "exchange_types.hpp" using namespace eosio; using namespace std; namespace dex { // caution: the order is deliberately designd for matching routine, do not change it!!! // see get_range enum order_type: uint8_t { RESERVED = 0, ASK_MARKET = 1, ASK_LIMITED = 2, BID_MARKET = 3, // so we can use them for tick matching, do NOT change the order! BID_LIMITED = 4, // biding orders are always at the top price list, when calling get_price }; uint128_t make_match_128(uint16_t pid, uint8_t type, asset price) { uint128_t temp = 0; uint128_t pid128 = (uint128_t)pid; uint128_t type128 = (uint128_t)type; // Notic that for bidding orders, we use reverse order!!! uint64_t price64 = (type != BID_LIMITED) ? price.amount : static_cast<uint64_t>(-price.amount); temp = (pid128 << 72) | (type128 << 64) | price64; return temp; } enum close_reason: uint8_t { NORMAL = 0, CANCELLED = 1, EXPIRED = 2, NOT_ENOUGH_FEE = 3, }; const uint8_t ORDER_TYPE_MASK = 0x0F; auto temp = make_tuple(0, 0, 0); typedef asset order_price; typedef asset quote_amount; // Orders are stored within different scopes? // (_self, _self) struct order { uint64_t id; uint64_t gid; // primary key account_name owner; exch::exchange_pair_id pair_id; order_type type; // Timing related fileds time placed_time; time updated_time; time closed_time; uint8_t close_reason; time expiration_time; asset initial; asset remain; order_price price; quote_amount deal; void reset() { // CAN NOT CHANGE GID id = 0; pair_id = 0; type = RESERVED; placed_time = 0; updated_time = 0; closed_time = 0; close_reason = 0; expiration_time = 0; initial = asset(0); remain = asset(0); price = asset(0); deal = asset(0); } auto primary_key() const { return gid; } uint64_t get_id() const { return id; } uint64_t get_expiration() const { return expiration_time; } uint64_t get_owner() const { return owner; } uint128_t get_slot() const { return make_key_128(owner, type); } uint128_t get_price() const { return make_match_128(pair_id, type, price); } EOSLIB_SERIALIZE( order, (id)(gid)(owner)(pair_id)(type)(placed_time)(updated_time)\ (closed_time)(close_reason)(expiration_time)(initial)(remain)(price)(deal) ) }; typedef eosio::multi_index< N(orders), order, indexed_by< N( byid ), const_mem_fun< order, uint64_t, &order::get_id> >, indexed_by< N( byexp ), const_mem_fun< order, uint64_t, &order::get_expiration> >, indexed_by< N( byprice ), const_mem_fun< order, uint128_t, &order::get_price> >, indexed_by< N( byowner ), const_mem_fun< order, uint64_t, &order::get_owner> >, indexed_by< N( byslot ), const_mem_fun< order, uint128_t, &order::get_slot> > > order_table; bool match(); bool is_ask_order(order_type type) { if (type == ASK_LIMITED || type == ASK_MARKET) { return true; } return false; } bool is_limited_order(uint8_t type) { if (type == ASK_LIMITED || type == BID_LIMITED) { return true; } return false; } // pay attention to the order void get_range(order_type type, bool match_market, order_type& low, order_type& high) { switch (type) { case ASK_LIMITED: high = BID_LIMITED; low = match_market ? BID_MARKET : high; return; case ASK_MARKET: low = high = BID_LIMITED; return; case BID_LIMITED: high = ASK_LIMITED; low = match_market? ASK_MARKET : high; return; case BID_MARKET: low = high = ASK_LIMITED; return; default: eosio_assert(false, "not supported yet"); } } bool parse_order_from_string(string &memo, order& o, bool& match_now); } /// namespace dex
34.740741
114
0.550746
chaosmw
de10e86dc85a333467721695dbb3f08c264feceb
6,008
cpp
C++
cpp/oneapi/dal/algo/pca/backend/gpu/train_kernel_cov_dpc.cpp
dmitrii-kriukov/oneDAL
e962159893ffabdcc601f999f998ce2373c3ce71
[ "Apache-2.0" ]
null
null
null
cpp/oneapi/dal/algo/pca/backend/gpu/train_kernel_cov_dpc.cpp
dmitrii-kriukov/oneDAL
e962159893ffabdcc601f999f998ce2373c3ce71
[ "Apache-2.0" ]
1
2021-05-04T13:03:30.000Z
2021-05-04T13:03:30.000Z
cpp/oneapi/dal/algo/pca/backend/gpu/train_kernel_cov_dpc.cpp
dmitrii-kriukov/oneDAL
e962159893ffabdcc601f999f998ce2373c3ce71
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "oneapi/dal/algo/pca/backend/gpu/train_kernel.hpp" #include "oneapi/dal/algo/pca/backend/common.hpp" #include "oneapi/dal/algo/pca/backend/sign_flip.hpp" #include "oneapi/dal/table/row_accessor.hpp" #include "oneapi/dal/backend/primitives/lapack.hpp" #include "oneapi/dal/backend/primitives/blas.hpp" #include "oneapi/dal/backend/primitives/reduction.hpp" #include "oneapi/dal/backend/primitives/stat.hpp" #include "oneapi/dal/backend/primitives/utils.hpp" #include "oneapi/dal/detail/profiler.hpp" namespace oneapi::dal::pca::backend { namespace pr = oneapi::dal::backend::primitives; using dal::backend::context_gpu; using model_t = model<task::dim_reduction>; using input_t = train_input<task::dim_reduction>; using result_t = train_result<task::dim_reduction>; using descriptor_t = detail::descriptor_base<task::dim_reduction>; template <typename Float> auto compute_sums(sycl::queue& q, const pr::ndview<Float, 2>& data, const dal::backend::event_vector& deps = {}) { ONEDAL_PROFILER_TASK(compute_sums, q); const std::int64_t column_count = data.get_dimension(1); auto sums = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto reduce_event = pr::reduce_by_columns(q, data, sums, pr::sum<Float>{}, pr::identity<Float>{}, deps); return std::make_tuple(sums, reduce_event); } template <typename Float> auto compute_correlation(sycl::queue& q, const pr::ndview<Float, 2>& data, const pr::ndview<Float, 1>& sums, const dal::backend::event_vector& deps = {}) { ONEDAL_PROFILER_TASK(compute_correlation, q); ONEDAL_ASSERT(data.get_dimension(1) == sums.get_dimension(0)); const std::int64_t column_count = data.get_dimension(1); auto corr = pr::ndarray<Float, 2>::empty(q, { column_count, column_count }, sycl::usm::alloc::device); auto means = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto vars = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto tmp = pr::ndarray<Float, 1>::empty(q, { column_count }, sycl::usm::alloc::device); auto gemm_event = gemm(q, data.t(), data, corr, Float(1), Float(0), deps); auto corr_event = pr::correlation(q, data, sums, means, corr, vars, tmp, { gemm_event }); auto smart_event = dal::backend::smart_event{ corr_event }.attach(tmp); return std::make_tuple(corr, means, vars, smart_event); } template <typename Float> auto compute_eigenvectors_on_host(sycl::queue& q, pr::ndarray<Float, 2>&& corr, std::int64_t component_count, const dal::backend::event_vector& deps = {}) { ONEDAL_PROFILER_TASK(compute_eigenvectors_on_host); ONEDAL_ASSERT(corr.get_dimension(0) == corr.get_dimension(1)); const std::int64_t column_count = corr.get_dimension(0); auto eigvecs = pr::ndarray<Float, 2>::empty({ component_count, column_count }); auto eigvals = pr::ndarray<Float, 1>::empty(component_count); auto host_corr = corr.to_host(q, deps); pr::sym_eigvals_descending(host_corr, component_count, eigvecs, eigvals); return std::make_tuple(eigvecs, eigvals); } template <typename Float> static result_t train(const context_gpu& ctx, const descriptor_t& desc, const input_t& input) { auto& q = ctx.get_queue(); const auto data = input.get_data(); const std::int64_t row_count = data.get_row_count(); const std::int64_t column_count = data.get_column_count(); const std::int64_t component_count = get_component_count(desc, data); dal::detail::check_mul_overflow(row_count, column_count); dal::detail::check_mul_overflow(column_count, column_count); dal::detail::check_mul_overflow(component_count, column_count); const auto data_nd = pr::table2ndarray<Float>(q, data, sycl::usm::alloc::device); auto [sums, sums_event] = compute_sums(q, data_nd); auto [corr, means, vars, corr_event] = compute_correlation(q, data_nd, sums, { sums_event }); auto [eigvecs, eigvals] = compute_eigenvectors_on_host(q, std::move(corr), component_count, { corr_event }); if (desc.get_deterministic()) { sign_flip(eigvecs); } const auto model = model_t{}.set_eigenvectors( homogen_table::wrap(eigvecs.flatten(), component_count, column_count)); return result_t{} .set_model(model) .set_eigenvalues(homogen_table::wrap(eigvals.flatten(), 1, component_count)) .set_means(homogen_table::wrap(means.flatten(q), 1, column_count)) .set_variances(homogen_table::wrap(vars.flatten(q), 1, column_count)); } template <typename Float> struct train_kernel_gpu<Float, method::cov, task::dim_reduction> { result_t operator()(const context_gpu& ctx, const descriptor_t& desc, const input_t& input) const { return train<Float>(ctx, desc, input); } }; template struct train_kernel_gpu<float, method::cov, task::dim_reduction>; template struct train_kernel_gpu<double, method::cov, task::dim_reduction>; } // namespace oneapi::dal::pca::backend
44.176471
98
0.672437
dmitrii-kriukov
de110e5302019a7f0ee9f279285372df74156109
6,765
cpp
C++
src/extern/inventor/lib/database/src/so/nodes/SoCallback.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
2
2020-05-21T07:06:07.000Z
2021-06-28T02:14:34.000Z
src/extern/inventor/lib/database/src/so/nodes/SoCallback.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
null
null
null
src/extern/inventor/lib/database/src/so/nodes/SoCallback.cpp
OpenXIP/xip-libraries
9f0fef66038b20ff0c81c089d7dd0038e3126e40
[ "Apache-2.0" ]
6
2016-03-21T19:53:18.000Z
2021-06-08T18:06:03.000Z
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1.1.1 $ | | Classes: | SoCallback | | Author(s) : Paul S. Strauss | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/actions/SoGetMatrixAction.h> #include <Inventor/actions/SoHandleEventAction.h> #include <Inventor/actions/SoRayPickAction.h> #include <Inventor/actions/SoSearchAction.h> #include <Inventor/actions/SoWriteAction.h> #include <Inventor/elements/SoGLCacheContextElement.h> #include <Inventor/nodes/SoCallback.h> SO_NODE_SOURCE(SoCallback); //////////////////////////////////////////////////////////////////////// // // Description: // Constructor // // Use: public SoCallback::SoCallback() // //////////////////////////////////////////////////////////////////////// { SO_NODE_CONSTRUCTOR(SoCallback); isBuiltIn = TRUE; callbackFunc = NULL; callbackData = NULL; } //////////////////////////////////////////////////////////////////////// // // Description: // Copies the contents of the given node into this instance. // // Use: protected, virtual void SoCallback::copyContents(const SoFieldContainer *fromFC, SbBool copyConnections) // //////////////////////////////////////////////////////////////////////// { // Copy the usual stuff SoNode::copyContents(fromFC, copyConnections); // Copy the callback function and data const SoCallback *fromCB = (const SoCallback *) fromFC; setCallback(fromCB->callbackFunc, fromCB->callbackData); } //////////////////////////////////////////////////////////////////////// // // Description: // Destructor // // Use: private SoCallback::~SoCallback() // //////////////////////////////////////////////////////////////////////// { } //////////////////////////////////////////////////////////////////////// // // Description: // Typical action method. // // Use: extender void SoCallback::doAction(SoAction *action) // //////////////////////////////////////////////////////////////////////// { SoType actionType = action->getTypeId(); SoState *state = action->getState(); if (this->callbackFunc != NULL) (*this->callbackFunc)(this->callbackData, action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the callback action // // Use: extender void SoCallback::callback(SoCallbackAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the GL render action // // Use: extender void SoCallback::GLRender(SoGLRenderAction *action) // //////////////////////////////////////////////////////////////////////// { // Ask to be cached, to match Inventor 2.0 default: SoGLCacheContextElement::shouldAutoCache(action->getState(), TRUE); SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the get bounding box action // // Use: extender void SoCallback::getBoundingBox(SoGetBoundingBoxAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the get matrix action // // Use: extender void SoCallback::getMatrix(SoGetMatrixAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the handle event thing // // Use: extender void SoCallback::handleEvent(SoHandleEventAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Pick. // // Use: extender void SoCallback::pick(SoPickAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does search... // // Use: extender void SoCallback::search(SoSearchAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); SoNode::search(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Does the write action // // Use: extender void SoCallback::write(SoWriteAction *action) // //////////////////////////////////////////////////////////////////////// { SoCallback::doAction(action); SoNode::write(action); }
25.820611
77
0.520177
OpenXIP
de1856ea478f66b6f47989f7c6f155c6fd50efce
156
cpp
C++
codeforces/656A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/656A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
codeforces/656A.cpp
Shisir/Online-Judge
e58c32eeb7ca18a19cc2a83ef016f9c3b124370a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { long long a,res=1; cin>>a; for(int i=1; i<=a; i++)res*=2; cout<< res<<endl;; return 0; }
13
31
0.576923
Shisir
de1c1a9cd315d35bd625c7f15bde751057a7371d
2,918
cpp
C++
kinesis-video-pic/src/mkvgen/tst/AudioCpdParserTest.cpp
nsharma098/amazon-kinesis-video-streams-producer-sdk-cpp
e3b63724494b16e00079027ccc232e8914731d66
[ "Apache-2.0" ]
1
2021-04-29T08:08:10.000Z
2021-04-29T08:08:10.000Z
kinesis-video-pic/src/mkvgen/tst/AudioCpdParserTest.cpp
jonmnick/aws-kinesis-cpp-sdk
f7d4a0fa67081780808f5b1e4cc8b97697953a72
[ "Apache-2.0" ]
null
null
null
kinesis-video-pic/src/mkvgen/tst/AudioCpdParserTest.cpp
jonmnick/aws-kinesis-cpp-sdk
f7d4a0fa67081780808f5b1e4cc8b97697953a72
[ "Apache-2.0" ]
null
null
null
#include "MkvgenTestFixture.h" class AudioCpdParserTest : public MkvgenTestBase { }; TEST_F(AudioCpdParserTest, audioCpdParser_InvalidInput) { BYTE cpd[] = {0x00, 0x00}; UINT32 cpdSize = 2; DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(NULL, cpdSize, &samplingFrequency, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, 0, &samplingFrequency, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, MIN_AAC_CPD_SIZE - 1, &samplingFrequency, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, &channelConfig)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, NULL)); EXPECT_NE(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, NULL)); } TEST_F(AudioCpdParserTest, audioCpdParser_AacCpd) { BYTE cpd[] = {0x12, 0x10}; UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_SUCCESS, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, &channelConfig)); EXPECT_EQ((DOUBLE) 44100, samplingFrequency); EXPECT_EQ(2, channelConfig); } TEST_F(AudioCpdParserTest, audioCpdParser_InvalidCpd) { BYTE cpd[] = {0x12, 0x10}; UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD, getSamplingFreqAndChannelFromAacCpd(NULL, 2, &samplingFrequency, &channelConfig)); EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD, getSamplingFreqAndChannelFromAacCpd(NULL, 0, &samplingFrequency, &channelConfig)); EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD, getSamplingFreqAndChannelFromAacCpd(cpd, 0, &samplingFrequency, &channelConfig)); EXPECT_EQ(STATUS_NULL_ARG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, NULL)); EXPECT_EQ(STATUS_NULL_ARG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, &channelConfig)); EXPECT_EQ(STATUS_NULL_ARG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, NULL, NULL)); } TEST_F(AudioCpdParserTest, audioCpdParser_invalidSamplingFrequencyIndex) { BYTE cpd[] = {0x07, 0x90}; // sampling frequency index is 15 UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD_SAMPLING_FREQUENCY_INDEX, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, &channelConfig)); } TEST_F(AudioCpdParserTest, audioCpdParser_invalidChannelConfig) { BYTE cpd[] = {0x07, 0xc8}; // channel config is 9 UINT32 cpdSize = SIZEOF(cpd); DOUBLE samplingFrequency; UINT16 channelConfig; EXPECT_EQ(STATUS_MKV_INVALID_AAC_CPD_CHANNEL_CONFIG, getSamplingFreqAndChannelFromAacCpd(cpd, cpdSize, &samplingFrequency, &channelConfig)); }
42.911765
154
0.789239
nsharma098
de1e527e8357da26a93b7b50f7bfc04c6d250be5
18,329
cpp
C++
game/server/tfo/npc_monster.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
13
2016-04-05T23:23:16.000Z
2022-03-20T11:06:04.000Z
game/server/tfo/npc_monster.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
null
null
null
game/server/tfo/npc_monster.cpp
BerntA/tfo-code
afa3ea06a64cbbf7a9370b214ea5e80e69d9d7a1
[ "MIT" ]
4
2016-04-05T23:23:19.000Z
2021-05-16T05:09:46.000Z
//========= Copyright Bernt Andreas Eide, All rights reserved. ============// // // Purpose: Custom Monster NPC Entity - Allows parsing of unique stuff. Parses npc scripts in resource/data/npc // //=============================================================================// #include "cbase.h" #include "ai_basenpc.h" #include "ai_default.h" #include "ai_schedule.h" #include "ai_hull.h" #include "ai_motor.h" #include "game.h" #include "npc_headcrab.h" #include "npcevent.h" #include "entitylist.h" #include "ai_task.h" #include "activitylist.h" #include "engine/IEngineSound.h" #include "npc_BaseZombie.h" #include "npc_monster.h" #include "filesystem.h" #include <KeyValues.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define BREATH_VOL_MAX 0.6 #define ZOMBIE_ENEMY_BREATHE_DIST 300 // How close we must be to our enemy before we start breathing hard. static const char *pMoanSounds[] = { "Moan1", }; LINK_ENTITY_TO_CLASS( npc_monster, CNPC_Monster ); BEGIN_DATADESC( CNPC_Monster ) DEFINE_FIELD( m_flNextPainSoundTime, FIELD_TIME ), DEFINE_FIELD(m_bCanOpenDoors, FIELD_BOOLEAN), DEFINE_FIELD(m_iMaxHealth, FIELD_INTEGER), DEFINE_FIELD(m_iSkin, FIELD_INTEGER), DEFINE_FIELD(m_iDamage[0], FIELD_INTEGER), DEFINE_FIELD(m_iDamage[1], FIELD_INTEGER), DEFINE_FIELD(m_flAttackRange, FIELD_FLOAT), DEFINE_FIELD(cModel, FIELD_STRING), DEFINE_FIELD(cEntName, FIELD_STRING), DEFINE_FIELD(cSoundScript, FIELD_STRING), DEFINE_FIELD( m_bNearEnemy, FIELD_BOOLEAN ), DEFINE_KEYFIELD( cScript, FIELD_STRING, "Script" ), END_DATADESC() // Force Script: void CNPC_Monster::SetScript( const char *szScript ) { cScript = MAKE_STRING(szScript); } //----------------------------------------------------------------------------- // Purpose: Return a random model in the Models key. //----------------------------------------------------------------------------- const char *CNPC_Monster::GetRandomModel(KeyValues *pkvValues) { const char *szModel = NULL; int iCount = 0, iFind = 0; for (KeyValues *sub = pkvValues->GetFirstSubKey(); sub; sub = sub->GetNextKey()) iCount++; iFind = random->RandomInt(1, iCount); iCount = 0; for (KeyValues *sub = pkvValues->GetFirstSubKey(); sub; sub = sub->GetNextKey()) { iCount++; if (iCount == iFind) { szModel = ReadAndAllocStringValue(pkvValues, sub->GetName()); break; } } return szModel; } //----------------------------------------------------------------------------- // Purpose: Return data about the npc, if found. //----------------------------------------------------------------------------- KeyValues *CNPC_Monster::pkvNPCData( const char *szScript ) { KeyValues *pkvData = new KeyValues( "NPCDATA" ); if ( pkvData->LoadFromFile( filesystem, UTIL_VarArgs( "resource/data/npcs/%s.txt", szScript ), "MOD" ) ) { return pkvData; } pkvData->deleteThis(); return NULL; } //----------------------------------------------------------------------------- // Purpose: Parse data found from npcData keyValue... //----------------------------------------------------------------------------- void CNPC_Monster::ParseNPCScript( const char *szScript ) { // Get our data and make sure it is not NULL... KeyValues *pkvMyNPCData = pkvNPCData(szScript); if (!pkvMyNPCData) { Warning("NPC_MONSTER linked to %s.txt was removed, no such script exist!\n", szScript); UTIL_Remove(this); return; } // Parse our data: KeyValues *pkvInfoField = pkvMyNPCData->FindKey("Info"); KeyValues *pkvModelField = pkvMyNPCData->FindKey("Model"); KeyValues *pkvRandomModelsField = pkvMyNPCData->FindKey("Models"); bool bRandomModel = false; if (pkvInfoField) { cEntName = MAKE_STRING(ReadAndAllocStringValue(pkvInfoField, "Name")); cSoundScript = MAKE_STRING(ReadAndAllocStringValue(pkvInfoField, "SoundScript")); m_iHealth = pkvInfoField->GetInt("Health", 100); m_iDamage[0] = pkvInfoField->GetInt("DamageOneHand", 10); m_iDamage[1] = pkvInfoField->GetInt("DamageBothHands", 10); m_flAttackRange = pkvInfoField->GetFloat("AttackRange", 70.0f); m_iMaxHealth = m_iHealth; m_bCanOpenDoors = ((pkvInfoField->GetInt("CanOpenDoors") >= 1) ? true : false); } if (pkvModelField) { bRandomModel = (!pkvModelField->FindKey("Path")); if (!bRandomModel) cModel = MAKE_STRING(ReadAndAllocStringValue(pkvModelField, "Path")); m_fIsTorso = ((pkvModelField->GetInt("IsTorso") >= 1) ? true : false); if (!strcmp(pkvModelField->GetString("Skin"), "random")) m_iSkin = random->RandomInt(0, pkvModelField->GetInt("MaxSkins")); else m_iSkin = pkvModelField->GetInt("Skin"); SetBloodColor(pkvModelField->GetInt("BloodType")); } if (pkvRandomModelsField && bRandomModel) cModel = MAKE_STRING(GetRandomModel(pkvRandomModelsField)); Precache(); pkvMyNPCData->deleteThis(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::Precache( void ) { PrecacheModel( cModel.ToCStr() ); PrecacheScriptSound( UTIL_VarArgs( "NPC_%s.Die", cSoundScript.ToCStr() ) ); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Idle", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Pain", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Alert", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.FootstepRight", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.FootstepLeft", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Attack", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.FastBreath", cSoundScript.ToCStr())); PrecacheScriptSound(UTIL_VarArgs("NPC_%s.Moan1", cSoundScript.ToCStr())); // Default Zombie Precaching PrecacheScriptSound("Zombie.FootstepRight"); PrecacheScriptSound("Zombie.FootstepLeft"); PrecacheScriptSound("Zombie.ScuffRight"); PrecacheScriptSound("Zombie.ScuffLeft"); PrecacheScriptSound("Zombie.Pain"); PrecacheScriptSound("Zombie.Die"); PrecacheScriptSound("Zombie.Alert"); PrecacheScriptSound("Zombie.Idle"); PrecacheScriptSound("Zombie.Attack"); PrecacheScriptSound("NPC_BaseZombie.Moan1"); PrecacheScriptSound("NPC_BaseZombie.Moan2"); PrecacheScriptSound("NPC_BaseZombie.Moan3"); PrecacheScriptSound("NPC_BaseZombie.Moan4"); PrecacheScriptSound( "Zombie.AttackHit" ); PrecacheScriptSound( "Zombie.AttackMiss" ); BaseClass::Precache(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::Spawn( void ) { ParseNPCScript( cScript.ToCStr() ); m_flLastBloodTrail = gpGlobals->curtime; m_flNextPainSoundTime = 0; m_fIsHeadless = true; AddSpawnFlags( SF_NPC_LONG_RANGE ); m_flFieldOfView = 0.2; CapabilitiesClear(); CapabilitiesAdd( bits_CAP_MOVE_GROUND | bits_CAP_INNATE_MELEE_ATTACK1 ); BaseClass::Spawn(); } //----------------------------------------------------------------------------- // Purpose: Returns a moan sound for this class of zombie. //----------------------------------------------------------------------------- const char *CNPC_Monster::GetMoanSound( int nSound ) { return UTIL_VarArgs("NPC_%s.%s", cSoundScript.ToCStr(), pMoanSounds[nSound % ARRAYSIZE(pMoanSounds)]); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::StopLoopingSounds( void ) { BaseClass::StopLoopingSounds(); } //----------------------------------------------------------------------------- // Purpose: // Input : info - //----------------------------------------------------------------------------- void CNPC_Monster::Event_Killed( const CTakeDamageInfo &info ) { BaseClass::Event_Killed( info ); } void CNPC_Monster::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator ) { BaseClass::TraceAttack( info, vecDir, ptr, pAccumulator ); } //----------------------------------------------------------------------------- // Purpose: // Input : &inputInfo - // Output : int //----------------------------------------------------------------------------- int CNPC_Monster::OnTakeDamage_Alive( const CTakeDamageInfo &inputInfo ) { return BaseClass::OnTakeDamage_Alive( inputInfo ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- float CNPC_Monster::MaxYawSpeed( void ) { return BaseClass::MaxYawSpeed(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- Class_T CNPC_Monster::Classify( void ) { return CLASS_ZOMBIE; } //----------------------------------------------------------------------------- // Purpose: // // NOTE: This function is still heavy with common code (found at the bottom). // we should consider moving some into the base class! (sjb) //----------------------------------------------------------------------------- void CNPC_Monster::SetZombieModel( void ) { Hull_t lastHull = GetHullType(); SetModel( cModel.ToCStr() ); if (m_fIsTorso) SetHullType(HULL_TINY); else SetHullType(HULL_HUMAN); SetHullSizeNormal( true ); SetDefaultEyeOffset(); SetActivity( ACT_IDLE ); m_nSkin = m_iSkin; if ( lastHull != GetHullType() ) { if ( VPhysicsGetObject() ) { SetupVPhysicsHull(); } } CollisionProp()->SetSurroundingBoundsType( USE_OBB_COLLISION_BOUNDS ); } //----------------------------------------------------------------------------- // Purpose: Turns off our breath so we can play another vocal sound. // TODO: pass in duration //----------------------------------------------------------------------------- void CNPC_Monster::BreatheOffShort( void ) { } //----------------------------------------------------------------------------- // Purpose: Catches the monster-specific events that occur when tagged animation // frames are played. // Input : pEvent - //----------------------------------------------------------------------------- void CNPC_Monster::HandleAnimEvent( animevent_t *pEvent ) { QAngle pAng; Vector vecDir; if ( pEvent->event == AE_ZOMBIE_ATTACK_RIGHT ) { Vector right, forward; AngleVectors( GetLocalAngles(), &forward, &right, NULL ); right = right * 100; forward = forward * 200; pAng = QAngle(-15, -20, -10); vecDir = (right + forward); ClawAttack(GetClawAttackRange(), m_iDamage[0], pAng, vecDir, ZOMBIE_BLOOD_RIGHT_HAND); return; } if ( pEvent->event == AE_ZOMBIE_ATTACK_LEFT ) { Vector right, forward; AngleVectors( GetLocalAngles(), &forward, &right, NULL ); right = right * -100; forward = forward * 200; vecDir = (right + forward); pAng = QAngle(-15, 20, -10); ClawAttack(GetClawAttackRange(), m_iDamage[0], pAng, vecDir, ZOMBIE_BLOOD_LEFT_HAND); return; } if ( pEvent->event == AE_ZOMBIE_ATTACK_BOTH ) { Vector forward; QAngle qaPunch( 45, random->RandomInt(-5,5), random->RandomInt(-5,5) ); AngleVectors( GetLocalAngles(), &forward ); forward = forward * 200; ClawAttack( GetClawAttackRange(), m_iDamage[1], qaPunch, forward, ZOMBIE_BLOOD_BOTH_HANDS ); return; } BaseClass::HandleAnimEvent( pEvent ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CNPC_Monster::PrescheduleThink( void ) { bool bNearEnemy = false; if ( GetEnemy() != NULL ) { float flDist = (GetEnemy()->GetAbsOrigin() - GetAbsOrigin()).Length(); if ( flDist < ZOMBIE_ENEMY_BREATHE_DIST ) { bNearEnemy = true; } } if ( bNearEnemy ) { if ( !m_bNearEnemy ) { m_bNearEnemy = true; } } else if ( m_bNearEnemy ) { m_bNearEnemy = false; } BaseClass::PrescheduleThink(); // We're chopped off! And we're moving! Add some blood trail... if (m_fIsTorso && IsMoving() && (m_flLastBloodTrail < gpGlobals->curtime)) { m_flLastBloodTrail = gpGlobals->curtime + 1.0f; // We don't want to spam blood all over the place. trace_t tr; UTIL_TraceLine((GetAbsOrigin() + Vector(0, 0, 50)), (GetAbsOrigin() + Vector(0, 0, -300)), MASK_ALL, this, COLLISION_GROUP_NONE, &tr); UTIL_DecalTrace(&tr, "Blood"); } } //----------------------------------------------------------------------------- // Purpose: Allows for modification of the interrupt mask for the current schedule. // In the most cases the base implementation should be called first. //----------------------------------------------------------------------------- void CNPC_Monster::BuildScheduleTestBits( void ) { BaseClass::BuildScheduleTestBits(); if ( IsCurSchedule( SCHED_CHASE_ENEMY ) ) { SetCustomInterruptCondition( COND_LIGHT_DAMAGE ); SetCustomInterruptCondition( COND_HEAVY_DAMAGE ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CNPC_Monster::SelectFailSchedule( int nFailedSchedule, int nFailedTask, AI_TaskFailureCode_t eTaskFailCode ) { int nSchedule = BaseClass::SelectFailSchedule( nFailedSchedule, nFailedTask, eTaskFailCode ); return nSchedule; } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int CNPC_Monster::SelectSchedule( void ) { int nSchedule = BaseClass::SelectSchedule(); if ( nSchedule == SCHED_SMALL_FLINCH ) { m_flNextFlinchTime = gpGlobals->curtime + random->RandomFloat( 1, 3 ); } return nSchedule; } //----------------------------------------------------------------------------- // Purpose: // Input : scheduleType - // Output : int //----------------------------------------------------------------------------- int CNPC_Monster::TranslateSchedule( int scheduleType ) { if ( scheduleType == SCHED_COMBAT_FACE && IsUnreachable( GetEnemy() ) ) return SCHED_TAKE_COVER_FROM_ENEMY; return BaseClass::TranslateSchedule( scheduleType ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CNPC_Monster::ShouldPlayIdleSound( void ) { return CAI_BaseNPC::ShouldPlayIdleSound(); } //----------------------------------------------------------------------------- // Purpose: Play a random attack hit sound //----------------------------------------------------------------------------- void CNPC_Monster::AttackHitSound( void ) { EmitSound( "Zombie.AttackHit" ); } //----------------------------------------------------------------------------- // Purpose: Play a random attack miss sound //----------------------------------------------------------------------------- void CNPC_Monster::AttackMissSound( void ) { EmitSound( "Zombie.AttackMiss" ); } //----------------------------------------------------------------------------- // Purpose: Play a random attack sound. //----------------------------------------------------------------------------- void CNPC_Monster::AttackSound( void ) { EmitSound(UTIL_VarArgs("NPC_%s.Attack", cSoundScript.ToCStr())); } //----------------------------------------------------------------------------- // Purpose: Play a random idle sound. //----------------------------------------------------------------------------- void CNPC_Monster::IdleSound( void ) { // HACK: base zombie code calls IdleSound even when not idle! if ( m_NPCState != NPC_STATE_COMBAT ) { BreatheOffShort(); EmitSound(UTIL_VarArgs("NPC_%s.Idle", cSoundScript.ToCStr())); } } //----------------------------------------------------------------------------- // Purpose: Play a random pain sound. //----------------------------------------------------------------------------- void CNPC_Monster::PainSound( const CTakeDamageInfo &info ) { // Don't make pain sounds too often. if ( m_flNextPainSoundTime <= gpGlobals->curtime ) { //BreatheOffShort(); EmitSound(UTIL_VarArgs("NPC_%s.Pain", cSoundScript.ToCStr())); m_flNextPainSoundTime = gpGlobals->curtime + random->RandomFloat( 4.0, 7.0 ); } } void CNPC_Monster::DeathSound(const CTakeDamageInfo &info ) { if ( !( info.GetDamageType() & ( DMG_BLAST | DMG_ALWAYSGIB) ) ) { EmitSound(UTIL_VarArgs("NPC_%s.Die", cSoundScript.ToCStr())); } } //----------------------------------------------------------------------------- // Purpose: Play a random alert sound. //----------------------------------------------------------------------------- void CNPC_Monster::AlertSound( void ) { BreatheOffShort(); EmitSound(UTIL_VarArgs("NPC_%s.Alert", cSoundScript.ToCStr())); } //----------------------------------------------------------------------------- // Purpose: Sound of a footstep //----------------------------------------------------------------------------- void CNPC_Monster::FootstepSound( bool fRightFoot ) { if( fRightFoot ) { EmitSound(UTIL_VarArgs("NPC_%s.FootstepRight", cSoundScript.ToCStr())); } else { EmitSound(UTIL_VarArgs("NPC_%s.FootstepLeft", cSoundScript.ToCStr())); } if( ShouldPlayFootstepMoan() ) { m_flNextMoanSound = gpGlobals->curtime; } } //----------------------------------------------------------------------------- // Purpose: If we don't have any headcrabs to throw, we must close to attack our enemy. //----------------------------------------------------------------------------- bool CNPC_Monster::MustCloseToAttack(void) { return true; } //----------------------------------------------------------------------------- // Purpose: Overloaded so that explosions don't split the poison zombie in twain. //----------------------------------------------------------------------------- bool CNPC_Monster::ShouldBecomeTorso( const CTakeDamageInfo &info, float flDamageThreshold ) { return false; } int ACT_ZOMBIE_MONSTER_THREAT; AI_BEGIN_CUSTOM_NPC( npc_monster, CNPC_Monster ) DECLARE_ACTIVITY( ACT_ZOMBIE_MONSTER_THREAT ) AI_END_CUSTOM_NPC()
31.171769
136
0.540564
BerntA
de23c456db92799c7cdedb8b84d59f75e6bbe413
843
cpp
C++
matrix/matrix_power.cpp
ShinyaKato/competitive-programming-utils
53ae76cdc427dd816a7a11147d80a172fb16bcc3
[ "Apache-2.0" ]
1
2017-12-16T14:08:49.000Z
2017-12-16T14:08:49.000Z
matrix/matrix_power.cpp
ShinyaKato/competitive-programming-utils
53ae76cdc427dd816a7a11147d80a172fb16bcc3
[ "Apache-2.0" ]
2
2018-07-03T17:19:18.000Z
2018-07-03T17:23:10.000Z
matrix/matrix_power.cpp
ShinyaKato/competitive-programming-utils
53ae76cdc427dd816a7a11147d80a172fb16bcc3
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) #define MOD 1000000007LL using namespace std; typedef long long ll; typedef vector<ll> vec; typedef vector<vec> mat; mat mul(mat &A, mat &B) { mat C(A.size(), vector<ll>(B[0].size())); REP(i, 0, A.size()) REP(j, 0, B[0].size()) REP(k, 0, B.size()) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD; return C; } mat pow(mat A, ll n) { mat B(A.size(), vec(A.size())); REP(i, 0, A.size()) B[i][i] = 1; while(n > 0) { if(n & 1) B = mul(B, A); A = mul(A, A); n >>= 1; } return B; } int main(void) { // example of calculating n-the element of fibonacci mod 10^9 + 7 mat A(2, vec(2)); A[0][0] = 1; A[0][1] = 1; A[1][0] = 1; A[1][1] = 0; REP(i, 0, 20) cout << "fib(" << i << ") = " << pow(A, i)[1][0] << endl; }
24.085714
82
0.487544
ShinyaKato
de2bb30cb5a58184d70f4d07c3c6ca056aeddab0
82
hpp
C++
src/elona/main.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
84
2018-03-03T02:44:32.000Z
2019-07-14T16:16:24.000Z
src/elona/main.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
685
2018-02-27T04:31:17.000Z
2019-07-12T13:43:00.000Z
src/elona/main.hpp
XrosFade/ElonaFoobar
c33880080e0b475103ae3ea7d546335f9d4abd02
[ "MIT" ]
23
2019-07-26T08:52:38.000Z
2021-11-09T09:21:58.000Z
#pragma once namespace elona { int run(int argc, const char* const* argv); }
7.454545
43
0.670732
XrosFade
de331995ccb829155f588de8da5537d04ddaa885
3,694
hpp
C++
src/Core/TransactionExtra.hpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
1
2019-05-20T01:00:40.000Z
2019-05-20T01:00:40.000Z
src/Core/TransactionExtra.hpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
4
2018-05-07T07:15:53.000Z
2018-06-01T19:35:46.000Z
src/Core/TransactionExtra.hpp
mygirl8893/evo
c90f69ad6132c426042749ff3fe4174d22aa63b2
[ "MIT" ]
10
2018-05-09T10:45:07.000Z
2020-01-11T17:21:28.000Z
#pragma once #include <boost/variant.hpp> #include <vector> #include "CryptoNote.hpp" #include "seria/ISeria.hpp" namespace cryptonote { enum { TX_EXTRA_PADDING_MAX_COUNT = 255, TX_EXTRA_NONCE_MAX_COUNT = 255, TX_EXTRA_NONCE_PAYMENT_ID = 0x00 }; struct TransactionExtraPadding { size_t size = 0; enum { tag = 0x00 }; }; struct TransactionExtraPublicKey { crypto::PublicKey public_key; enum { tag = 0x01 }; }; struct TransactionExtraNonce { BinaryArray nonce; enum { tag = 0x02 }; }; struct TransactionExtraMergeMiningTag { size_t depth = 0; crypto::Hash merkle_root; enum { tag = 0x03 }; }; // tx_extra_field format, except tx_extra_padding and tx_extra_pub_key: // varint tag; // varint size; // varint data[]; typedef boost::variant<TransactionExtraPadding, TransactionExtraPublicKey, TransactionExtraNonce, TransactionExtraMergeMiningTag> TransactionExtraField; bool parse_transaction_extra(const BinaryArray &tx_extra, std::vector<TransactionExtraField> &tx_extra_fields); bool write_transaction_extra(BinaryArray &tx_extra, const std::vector<TransactionExtraField> &tx_extra_fields); crypto::PublicKey get_transaction_public_key_from_extra(const BinaryArray &tx_extra); bool add_transaction_public_key_to_extra(BinaryArray &tx_extra, const crypto::PublicKey &tx_pub_key); bool add_extra_nonce_to_transaction_extra(BinaryArray &tx_extra, const BinaryArray &extra_nonce); void set_payment_id_to_transaction_extra_nonce(BinaryArray &extra_nonce, const crypto::Hash &payment_id); bool get_payment_id_from_transaction_extra_nonce(const BinaryArray &extra_nonce, crypto::Hash &payment_id); bool append_merge_mining_tag_to_extra(BinaryArray &tx_extra, const TransactionExtraMergeMiningTag &mm_tag); bool get_merge_mining_tag_from_extra(const BinaryArray &tx_extra, TransactionExtraMergeMiningTag &mm_tag); bool get_payment_id_from_tx_extra(const BinaryArray &extra, crypto::Hash &payment_id); class TransactionExtra { public: TransactionExtra() {} TransactionExtra(const BinaryArray &extra) { parse(extra); } bool parse(const BinaryArray &extra) { m_fields.clear(); return cryptonote::parse_transaction_extra(extra, m_fields); } template<typename T> bool get(T &value) const { auto it = find(typeid(T)); if (it == m_fields.end()) { return false; } value = boost::get<T>(*it); return true; } template<typename T> void set(const T &value) { auto it = find(typeid(T)); if (it != m_fields.end()) { *it = value; } else { m_fields.push_back(value); } } template<typename T> void append(const T &value) { m_fields.push_back(value); } bool get_public_key(crypto::PublicKey &pk) const { cryptonote::TransactionExtraPublicKey extra_pk; if (!get(extra_pk)) { return false; } pk = extra_pk.public_key; return true; } BinaryArray serialize() const { BinaryArray extra; write_transaction_extra(extra, m_fields); return extra; } private: std::vector<cryptonote::TransactionExtraField>::const_iterator find(const std::type_info &t) const { return std::find_if( m_fields.begin(), m_fields.end(), [&t](const cryptonote::TransactionExtraField &f) { return t == f.type(); }); } std::vector<cryptonote::TransactionExtraField>::iterator find(const std::type_info &t) { return std::find_if( m_fields.begin(), m_fields.end(), [&t](const cryptonote::TransactionExtraField &f) { return t == f.type(); }); } std::vector<cryptonote::TransactionExtraField> m_fields; }; } namespace seria { class ISeria; void ser(cryptonote::TransactionExtraMergeMiningTag &v, ISeria &s); }
30.783333
117
0.73281
mygirl8893
de337a4c7dc31a4813842329f7ad3796967d3438
2,123
cpp
C++
Visual Mercutio/zBaseLib/PSS_Splitter.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zBaseLib/PSS_Splitter.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zBaseLib/PSS_Splitter.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_Splitter --------------------------------------------------------* **************************************************************************** * Description : Provides a splitter * * Developer : Processsoft * ****************************************************************************/ #include <StdAfx.h> #include "PSS_Splitter.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif //--------------------------------------------------------------------------- // Message map //--------------------------------------------------------------------------- #ifdef _WIN32 BEGIN_MESSAGE_MAP(PSS_Splitter, PSS_OutlookSplitterWnd) #else // in 16bit there is a bug, therefore do not accept moving splitter BEGIN_MESSAGE_MAP(PSS_Splitter, CSplitterWnd) //{{AFX_MSG_MAP(ZISplitter) ON_WM_LBUTTONDOWN() ON_WM_MOUSEMOVE() //}}AFX_MSG_MAP #endif END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_Splitter //--------------------------------------------------------------------------- PSS_Splitter::PSS_Splitter() : PSS_OutlookSplitterWnd() {} //--------------------------------------------------------------------------- PSS_Splitter::~PSS_Splitter() {} //--------------------------------------------------------------------------- #ifndef _WIN32 void PSS_Splitter::OnLButtonDown(UINT nFlags, CPoint point) { // in 16bit there is a bug, therefore do not accept moving splitter //CWnd::OnLButtonDown(nFlags, point); } #endif //--------------------------------------------------------------------------- #ifndef _WIN32 void PSS_Splitter::OnMouseMove(UINT nFlags, CPoint point) { // in 16bit there is a bug, therefore do not accept moving splitter //CWnd::OnMouseMove(nFlags, point); } #endif //---------------------------------------------------------------------------
37.910714
78
0.370231
Jeanmilost
de340e9fd170a18b5163c178219e094171ac96ed
7,769
cpp
C++
main/source/cl_dll/util.cpp
fmoraw/NS
6c3ae93ca7f929f24da4b8f2d14ea0602184cf08
[ "Unlicense" ]
27
2015-01-05T19:25:14.000Z
2022-03-20T00:34:34.000Z
main/source/cl_dll/util.cpp
fmoraw/NS
6c3ae93ca7f929f24da4b8f2d14ea0602184cf08
[ "Unlicense" ]
9
2015-01-14T06:51:46.000Z
2021-03-19T12:07:18.000Z
main/source/cl_dll/util.cpp
fmoraw/NS
6c3ae93ca7f929f24da4b8f2d14ea0602184cf08
[ "Unlicense" ]
5
2015-01-11T10:31:24.000Z
2021-01-06T01:32:58.000Z
/*** * * Copyright (c) 1999, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // util.cpp // // implementation of class-less helper functions // #include "stdio.h" #include "stdlib.h" #include "math.h" #include "hud.h" #include "cl_util.h" #include "common/cl_entity.h" #include <string.h> #ifndef M_PI #define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h #endif #include "pm_shared/pm_defs.h" #include "pm_shared/pm_shared.h" #include "pm_shared/pm_movevars.h" extern playermove_t *pmove; extern float HUD_GetFOV( void ); vec3_t vec3_origin( 0, 0, 0 ); extern vec3_t v_angles; //double sqrt(double x); // //float Length(const float *v) //{ // int i; // float length; // // length = 0; // for (i=0 ; i< 3 ; i++) // length += v[i]*v[i]; // length = sqrt (length); // FIXME // // return length; //} // //void VectorAngles( const float *forward, float *angles ) //{ // float tmp, yaw, pitch; // // if (forward[1] == 0 && forward[0] == 0) // { // yaw = 0; // if (forward[2] > 0) // pitch = 90; // else // pitch = 270; // } // else // { // yaw = (atan2(forward[1], forward[0]) * 180 / M_PI); // if (yaw < 0) // yaw += 360; // // tmp = sqrt (forward[0]*forward[0] + forward[1]*forward[1]); // pitch = (atan2(forward[2], tmp) * 180 / M_PI); // if (pitch < 0) // pitch += 360; // } // // angles[0] = pitch; // angles[1] = yaw; // angles[2] = 0; //} // //float VectorNormalize (float *v) //{ // float length, ilength; // // length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; // length = sqrt (length); // FIXME // // if (length) // { // ilength = 1/length; // v[0] *= ilength; // v[1] *= ilength; // v[2] *= ilength; // } // // return length; // //} // //void VectorInverse ( float *v ) //{ // v[0] = -v[0]; // v[1] = -v[1]; // v[2] = -v[2]; //} // //void VectorScale (const float *in, float scale, float *out) //{ // out[0] = in[0]*scale; // out[1] = in[1]*scale; // out[2] = in[2]*scale; //} // //void VectorMA (const float *veca, float scale, const float *vecb, float *vecc) //{ // vecc[0] = veca[0] + scale*vecb[0]; // vecc[1] = veca[1] + scale*vecb[1]; // vecc[2] = veca[2] + scale*vecb[2]; //} int ScreenHeight() { // CGC: Replace code when ready to fix overview map //int theViewport[4]; //gHUD.GetViewport(theViewport); //return theViewport[3]; return gHUD.m_scrinfo.iHeight; } // ScreenWidth returns the width of the screen, in pixels //#define ScreenWidth ( int theViewport[4]; gHUD.GetViewport(theViewport); return theViewport[2]; ) int ScreenWidth() { //int theViewport[4]; //gHUD.GetViewport(theViewport); //return theViewport[2]; return gHUD.m_scrinfo.iWidth; } /* HSPRITE SPR_Load(const char* inSpriteName) { HSPRITE theSpriteHandle = gEngfuncs.pfnSPR_Load(inSpriteName); // Check for "Can't allocate 128 HUD sprites" crash ASSERT(theSpriteHandle < 128); return theSpriteHandle; }*/ //----------------------------------------------------------------------------- // Purpose: // Given a field of view and mouse/screen positions as well as the current // render origin and angles, returns a unit vector through the mouse position // that can be used to trace into the world under the mouse click pixel. // Input : fov - // mousex - // mousey - // screenwidth - // screenheight - // vecRenderAngles - // c_x - // vpn - // vup - // 360.0 - //----------------------------------------------------------------------------- void CreatePickingRay( int mousex, int mousey, Vector& outVecPickingRay ) { float dx, dy; float c_x, c_y; float dist; Vector vpn, vup, vright; // char gDebugMessage[256]; float fovDegrees = gHUD.m_iFOV; //cl_entity_s* theLocalEntity = gEngfuncs.GetLocalPlayer(); //Vector vecRenderOrigin = theLocalEntity->origin; //Vector vecRenderAngles = theLocalEntity->angles; //Vector vecRenderAngles; vec3_t vecRenderAngles; //gEngfuncs.GetViewAngles((float*)vecRenderAngles); VectorCopy(v_angles, vecRenderAngles); //vec3_t theForward, theRight, theUp; //AngleVectors(v_angles, theForward, theRight, theUp); //ASSERT(v_angles.x == vecRenderAngles.x); //ASSERT(v_angles.y == vecRenderAngles.y); //ASSERT(v_angles.z == vecRenderAngles.z); c_x = ScreenWidth() / 2; c_y = ScreenHeight() / 2; dx = (float)mousex - c_x; // Invert Y dy = c_y - (float)mousey; // sprintf(gDebugMessage, "inMouseX/Y: %d/%d, dx/dy = %d/%d", (int)mousex, (int)mousey, (int)dx, (int)dy); // CenterPrint(gDebugMessage); // Convert view plane distance dist = c_x / tan( M_PI * fovDegrees / 360.0 ); // Decompose view angles AngleVectors( vecRenderAngles, vpn, vright, vup ); // Offset forward by view plane distance, and then by pixel offsets outVecPickingRay = vpn * dist + vright * ( dx ) + vup * ( dy ); //sprintf(gDebugMessage, "outVecPickingRay: %.0f, %.0f, %.0f", outVecPickingRay.x, outVecPickingRay.y, outVecPickingRay.z); //CenterPrint(gDebugMessage); // Convert to unit vector VectorNormalize( outVecPickingRay ); } void FillRGBAClipped(vgui::Panel* inPanel, int inStartX, int inStartY, int inWidth, int inHeight, int r, int g, int b, int a) { int thePanelXPos, thePanelYPos; inPanel->getPos(thePanelXPos, thePanelYPos); int thePanelWidth, thePanelHeight; inPanel->getSize(thePanelWidth, thePanelHeight); // Clip starting point inStartX = min(max(0, inStartX), thePanelWidth-1); inStartY = min(max(0, inStartY), thePanelHeight-1); // Clip width if it goes too far ASSERT(inWidth >= 0); ASSERT(inHeight >= 0); if(inStartX + inWidth >= thePanelWidth) { inWidth = max(0, thePanelWidth - inStartX); } if(inStartY + inHeight >= thePanelHeight) { inHeight = max(0, thePanelHeight - inStartY); } // Now we can draw FillRGBA(inStartX, inStartY, inWidth, inHeight, r, g, b, a); } HSPRITE LoadSprite(const char *pszName) { int i; char sz[256]; if (ScreenWidth() < 640) i = 320; else i = 640; sprintf(sz, pszName, i); return SPR_Load(sz); } bool LocalizeString(const char* inMessage, string& outputString) { #define kMaxLocalizedStringLength 1024 bool theSuccess = false; char theInputString[kMaxLocalizedStringLength]; char theOutputString[kMaxLocalizedStringLength]; // Don't localize empty strings if(strcmp(inMessage, "")) { if(*inMessage != '#') { sprintf(theInputString, "#%s", inMessage); } else { sprintf(theInputString, "%s", inMessage); } if((CHudTextMessage::LocaliseTextString(theInputString, theOutputString, kMaxLocalizedStringLength) != NULL)) { outputString = theOutputString; if(theOutputString[0] != '#') { theSuccess = true; } else { string theTempString = theOutputString; theTempString = theTempString.substr(1, theTempString.length()); outputString = theTempString; } } else { outputString = string("err: ") + theInputString; } } return theSuccess; }
24.663492
126
0.604582
fmoraw
de3593ab1508ac91eba7bd889caff87e1e6a0703
2,088
cpp
C++
json_rest_test/Client.cpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
1
2020-05-22T08:47:00.000Z
2020-05-22T08:47:00.000Z
json_rest_test/Client.cpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
json_rest_test/Client.cpp
cd606/tm_examples
5ea8e9774f5070fbcc073c71c39bcb7febef88a7
[ "Apache-2.0" ]
null
null
null
#include <tm_kit/infra/RealTimeApp.hpp> #include <tm_kit/infra/Environments.hpp> #include <tm_kit/infra/TerminationController.hpp> #include <tm_kit/infra/DeclarativeGraph.hpp> #include <tm_kit/basic/real_time_clock/ClockComponent.hpp> #include <tm_kit/basic/SpdLoggingComponent.hpp> #include <tm_kit/transport/CrossGuidComponent.hpp> #include <tm_kit/transport/TLSConfigurationComponent.hpp> #include <tm_kit/transport/MultiTransportRemoteFacilityManagingUtils.hpp> #include <tm_kit/transport/SimpleIdentityCheckerComponent.hpp> #include "Data.hpp" using namespace dev::cd606::tm; using Env = infra::Environment< infra::CheckTimeComponent<false> , infra::TrivialExitControlComponent , basic::TimeComponentEnhancedWithSpdLogging< basic::real_time_clock::ClockComponent , false > , transport::CrossGuidComponent , transport::TLSClientConfigurationComponent , transport::AllNetworkTransportComponents , transport::ClientSideSimpleIdentityAttacherComponent< std::string, Req > >; int main(int argc, char **argv) { Env env; bool useSsl = (argc>=2 && std::string_view(argv[1]) == "ssl"); if (useSsl) { env.transport::TLSClientConfigurationComponent::setConfigurationItem( transport::TLSClientInfoKey { "localhost", 34567 } , transport::TLSClientInfo { "../grpc_interop_test/DotNetServer/server.crt" , "" , "" } ); } for (int ii=0; ii<10; ++ii) { Req req { {"abc", "def"} , 2.0 , decltype(req.tChoice) {std::in_place_index<0>, 1} }; auto resp = transport::OneShotMultiTransportRemoteFacilityCall<Env> ::callWithProtocol<std::void_t, Req, Resp> ( &env , "json_rest://localhost:34567:user2:abcde:/test_facility" , std::move(req) , std::nullopt , false ).get(); std::cout << resp << '\n'; } }
31.164179
77
0.621169
cd606
de37255f5b9a56dec1a112ec3c95d5d573ec19e0
10,212
cpp
C++
videodecodethread.cpp
Whatchado/storyrecorder
a442ebf2f5f5920f965ec5c07fddeec38a2a7aab
[ "Zlib" ]
null
null
null
videodecodethread.cpp
Whatchado/storyrecorder
a442ebf2f5f5920f965ec5c07fddeec38a2a7aab
[ "Zlib" ]
null
null
null
videodecodethread.cpp
Whatchado/storyrecorder
a442ebf2f5f5920f965ec5c07fddeec38a2a7aab
[ "Zlib" ]
null
null
null
#include "videodecodethread.h" #include <QTime> #include <QElapsedTimer> #include "video_image.h" #include "log.h" VideoDecodeThread::VideoDecodeThread(QObject *parent) : QThread(parent) { is_Running=false; doStop=false; isPaused=false; doPause=false; vbuffer=NULL; doSeek=-1; got_audioframe=false; got_videoframe=false; } void VideoDecodeThread::setFile(QString const &_filename) { filename=_filename; play_start=0.0; } void VideoDecodeThread::setVideoBuffer(VideoBuffer *_videobuffer) { vbuffer=_videobuffer; } void VideoDecodeThread::seek(double _pos) { //log("VIDEODECODE","**************** seek %f\n",_pos); if(_pos==-1) return; if(!is_Running) { start(); } doPause=true; while(is_Running&&(!isPaused)) usleep(100); while(is_Running&&(doSeek!=-1)) // wait if other seek in progress usleep(100); doSeek=_pos; vbuffer->clear(); doPause=false; while((doSeek!=-1)&&(is_Running)) usleep(100); //log("VIDEODECODE","*END************ seek %f\n",_pos); return; } void VideoDecodeThread::stop() { doStop=true; } void VideoDecodeThread::pause() { doPause=true; while((!isPaused)&&(is_Running)) { usleep(1000); } } void VideoDecodeThread::waitTillStopped() { while(is_Running) { usleep(1000); } return; } void VideoDecodeThread::run() { log("VIDEODECODE","play_start=%f",play_start); if(play_start) { doSeek=play_start; } else doSeek=-1; doStop=false; doPause=false; is_Running=true; double current_time_offset=-1; double seek_pos=0; int errcode=0; QTime t_start=QTime::currentTime(); char *filenameSrc=strdup(filename.toLocal8Bit().data()); AVCodecContext *pCodecCtx=NULL,*pCodecCtx_audio=NULL; AVFormatContext *pFormatCtx = avformat_alloc_context(); AVCodec *pCodec=NULL,*pCodec_audio=NULL; /*#ifdef __unix__ AVInputFormat *iformat = av_find_input_format("video4linux2"); #else AVInputFormat *iformat = av_find_input_format("dshow"); #endif*/ AVInputFormat *iformat =NULL; AVFrame *frame_audio = av_frame_alloc(); //AVDictionary *options=NULL; //av_dict_set(&options, "framerate", "25", 0); log("VIDEODECODE","--------------------------------OPEN------------------------------------------"); if(avformat_open_input(&pFormatCtx,filenameSrc,iformat,NULL) != 0) {errcode=-12;is_Running=false;return;}; //av_dict_free(&options); if(avformat_find_stream_info(pFormatCtx,NULL) < 0) {errcode=-13;is_Running=false;return;}; av_dump_format(pFormatCtx, 0, filenameSrc, 0); int videoStream = -1; int audioStream = -1; log("VIDEODECODE","numstreams:%i----------------------------",pFormatCtx->nb_streams); for(int i=0; i < pFormatCtx->nb_streams; i++) { log("VIDEODECODE","coder_type=%i",(int)pFormatCtx->streams[i]->codec->codec_type); if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) { videoStream = i; } else if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_AUDIO) { audioStream = i; } } log("VIDEODECODE","-------------------------------videostream found %i audio=%i ------------------------------",videoStream,audioStream); if(videoStream == -1) {errcode=-14;is_Running=false;return;}; // video codec pCodecCtx = pFormatCtx->streams[videoStream]->codec; log("VIDEODECODE","codecid=%i",pCodecCtx); pCodec =avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL) {printf("codec not found\n");errcode=-15;is_Running=false;return;}; //codec not found if(avcodec_open2(pCodecCtx,pCodec,NULL) < 0) {errcode=-16;is_Running=false;return;}; // audio codec if(audioStream>=0) { pCodecCtx_audio = pFormatCtx->streams[audioStream]->codec; log("VIDEODECODE","audio codecid=%i",pCodecCtx_audio); pCodec_audio =avcodec_find_decoder(pCodecCtx_audio->codec_id); } if(pCodec_audio==NULL) {printf("audio codec not found");} else { log("VIDEODECODE","open audio codec"); if(avcodec_open2(pCodecCtx_audio,pCodec_audio,NULL) < 0) {errcode=-16;is_Running=false;return;}; } uint8_t *buffer; int numBytes; VIDEOIMAGE frame(pCodecCtx->width,pCodecCtx->height,pCodecCtx->pix_fmt); VIDEOIMAGE frameResize(640,360,AV_PIX_FMT_BGR24); int res; AVPacket packet; //av_seek_frame(pFormatCtx,-1,pos_start*AV_TIME_BASE,AVSEEK_FLAG_BACKWARD); t_start=QTime::currentTime(); QElapsedTimer timer; timer.start(); double video_duration=double(pFormatCtx->duration)/AV_TIME_BASE; if(video_duration) { emit durationChanged(video_duration); log("VIDEODECODE","duration=%f",video_duration); } if(doSeek!=-1) { av_seek_frame(pFormatCtx,-1,doSeek*AV_TIME_BASE,AVSEEK_FLAG_BACKWARD); seek_pos=doSeek; doSeek=-1; } log("VIDEODECODE","************************* DECODING seek_pos=%f duration=%f*************************",seek_pos,video_duration); while((res = av_read_frame(pFormatCtx,&packet))>=0) { double pts=0.0; if(packet.dts != AV_NOPTS_VALUE) pts = packet.dts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base); if(current_time_offset==-1) current_time_offset=pts; double current_time=pts-current_time_offset; // log("VIDEODECODE","frame[%i] %f (pts=%f dts=%f) (offset=%f)",packet.stream_index,current_time, // packet.pts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base), // packet.dts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base),current_time_offset); //while(pts>double(timer.elapsed())/1000.0) //{usleep(1000);}; if(packet.stream_index == videoStream) { int frameFinished=1; avcodec_decode_video2(pCodecCtx,frame.data,&frameFinished,&packet); //log("VIDEODECODE","%i",frameFinished); if(frameFinished) { double pts2 = av_frame_get_best_effort_timestamp ( frame.data )*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base); // TODO test for AV_NOPTS_VALUE log("VIDEODECODE","- decoded video frame %f (pts=%f dts=%f) pts2=%f",current_time, packet.pts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base), packet.dts*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base),pts2 ); if(pts2>=seek_pos) { int h=frame.width*9/16; if(h>frame.height) h=frame.height; frame.scale(frameResize,h); char *ibuffer=NULL; //QImage *img=frameResize.getQImage(&ibuffer); Frame bframe(pts2,frameResize.getRawImage(),frameResize.width,frameResize.height); vbuffer->addVideo(bframe); if(doSeek!=-1) got_videoframe=true; } else log("VIDEODECODE","frame video skipped for seek"); av_free_packet(&packet); } } else if(packet.stream_index == audioStream) { /* decode audio frame */ int decoded = packet.size; int got_audio_frame = 0; int ret = avcodec_decode_audio4(pCodecCtx_audio, frame_audio, &got_audio_frame, &packet); if (ret < 0) printf("Error decoding audio frame\n"); decoded = FFMIN(ret, packet.size); if (got_audio_frame) { double packet_t = av_frame_get_best_effort_timestamp ( frame_audio )*av_q2d(pFormatCtx->streams[packet.stream_index]->time_base); log("VIDEODECODE","decoded audio frame t=%f",packet_t); int samplesize=av_get_bytes_per_sample((AVSampleFormat )frame_audio->format); size_t unpadded_linesize = frame_audio->nb_samples * samplesize; int16_t *d16=(int16_t *)malloc(frame_audio->nb_samples*sizeof(int16_t)); if(samplesize==4) { for(int a=0;a<frame_audio->nb_samples;a++) { float* decoded_audio_data = reinterpret_cast<float*>(frame_audio->data[0]); d16[a]=(32768)*decoded_audio_data[a]; } }else if(samplesize==2) { for(int a=0;a<frame_audio->nb_samples;a++) { int16_t* decoded_audio_data = reinterpret_cast<int16_t*>(frame_audio->data[0]); d16[a]=decoded_audio_data[a]; } } vbuffer->addAudio(packet_t,d16,frame_audio->nb_samples); free(d16); if(doSeek!=-1) got_audioframe=true; } } while(vbuffer->isFull()&&(!doStop)&&(!doPause)&&(doSeek==-1)) { usleep(1000); } while(doPause&&(!doStop)&&(doSeek==-1)) { isPaused=true; usleep(100); } isPaused=false; if(doSeek!=-1) { got_audioframe=false; got_videoframe=false; log("VIDEODECODE","seek to %f",doSeek); av_seek_frame(pFormatCtx,-1,doSeek*AV_TIME_BASE,AVSEEK_FLAG_BACKWARD); avcodec_flush_buffers(pCodecCtx); avcodec_flush_buffers(pCodecCtx_audio); seek_pos=doSeek; vbuffer->clear(); doSeek=-1; } if (doStop) break; } log("VIDEODECODE","videoplayer thread end rc=%i",res); // set stop frame Frame stopFrame;stopFrame.t=0.0; vbuffer->addVideo(stopFrame); av_free_packet(&packet); avcodec_close(pCodecCtx); avformat_close_input(&pFormatCtx); log("VIDEODECODE","videoplayer thread end doStop=%i",doStop); doStop=false; is_Running=false; return; }
33.592105
145
0.588915
Whatchado
de3c4c6c328d2f6f66cddaf09aadd757796f46b3
4,486
hh
C++
src/kinetics/SyntheticMomentSource.i.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/kinetics/SyntheticMomentSource.i.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/kinetics/SyntheticMomentSource.i.hh
RLReed/libdetran
77637c788823e0a14aae7e40e476a291f6f3184b
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*----------------------------------// /** * @file SyntheticMomentSource.i.hh * @brief SyntheticMomentSource inline member definitions * @author Jeremy Roberts * @date Nov 15, 2012 */ //---------------------------------------------------------------------------// #ifndef detran_SYNTHETICMOMENTSOURCE_I_HH_ #define detran_SYNTHETICMOMENTSOURCE_I_HH_ namespace detran { //---------------------------------------------------------------------------// inline double SyntheticMomentSource::source(const size_t cell, const size_t group) { // Preconditions Require(group < d_source.size()); Require(cell < d_source[0].size()); return d_source[group][cell]; } //---------------------------------------------------------------------------// inline double SyntheticMomentSource::source(const size_t cell, const size_t group, const size_t angle) { // Preconditions Require(group < d_source.size()); Require(cell < d_source[0].size()); // Norm is 1/4pi or 1/2 return d_source[group][cell] * d_norm; } //---------------------------------------------------------------------------// inline void SyntheticMomentSource::build(const double dt, const vec_states &states, const vec_precursors &precursors, const size_t order) { // Preconditions Require(order > 0); Require(order <= 6); // Ensure the state size is consistent with the order requested size_t size_state = states.size(); Require(states.size() > 0); Require(states.size() >= order); // If the precursors are present, they must be the same size as the state size_t size_precursor = precursors.size(); Require((size_precursor == size_state) || (size_precursor == 0)); // Number of precursors size_t np = 0; if (size_precursor) np = precursors[0]->number_precursor_groups(); // Material map const detran_utilities::vec_int &mt = d_mesh->mesh_map("MATERIAL"); // Leading coefficient double a_0 = bdf_coefs[order-1][0]; // Clear the source for (size_t g = 0; g < d_material->number_groups(); ++g) for (size_t cell = 0; cell < d_mesh->number_cells(); ++cell) d_source[g][cell] = 0.0; // Add all backward terms for (size_t j = 0; j < order; ++j) { Assert(states[j]); if (size_precursor) { Assert(precursors[j]); } // Skip the first entry, which is for the (n+1) term double a_j = bdf_coefs[order-1][j + 1]; for (size_t g = 0; g < d_material->number_groups(); ++g) { // Add the flux term double phi_factor = a_j / dt / d_material->velocity(g); for (size_t cell = 0; cell < d_mesh->number_cells(); ++cell) { // std::cout << " phi factor=" << phi_factor // << " phi = " << states[j]->phi(g)[cell] // << " source = " << d_source[g][cell] << std::endl; d_source[g][cell] += phi_factor * states[j]->phi(g)[cell]; } // Add the precursor concentration, if applicable if (size_precursor) { for (size_t i = 0; i < np; ++i) { double C_factor = a_j * d_material->lambda(i) / (a_0 + dt * d_material->lambda(i)); for (size_t cell = 0; cell < d_mesh->number_cells(); ++cell) { d_source[g][cell] += C_factor * d_material->chi_d(mt[cell], i, g) * precursors[j]->C(i)[cell]; // std::cout << " C=" << precursors[j]->C(i)[cell] // << " chid = " << d_material->chi_d(mt[cell], i, g) // << " q= " << d_source[g][cell] // << std::endl; } } } } // end groups } // end backward terms // std::cout << " source = " << this->source(0, 0) << " " << this->source(1, 0) << std::endl; // std::cout << " source = " << this->source(0, 0, 0) << " " << this->source(1, 0, 0) << " " << dt << std::endl; } } // end namespace detran #endif // detran_SYNTHETICMOMENTSOURCE_I_HH_ //---------------------------------------------------------------------------// // end of file SyntheticMomentSource.i.hh //---------------------------------------------------------------------------//
34.244275
114
0.476371
RLReed