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
d896163823ae01eb3832beaccbb5f68748304b9c
1,752
hpp
C++
Siv3D/include/Siv3D/Types.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
1
2018-05-23T10:57:32.000Z
2018-05-23T10:57:32.000Z
Siv3D/include/Siv3D/Types.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/include/Siv3D/Types.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
1
2019-10-06T17:09:26.000Z
2019-10-06T17:09:26.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <cstdint> # include <iosfwd> namespace s3d { ////////////////////////////////////////////////// // // Integer Types // ////////////////////////////////////////////////// /// <summary> /// Signed integer type with width of 8 bits /// </summary> using int8 = std::int8_t; /// <summary> /// Signed integer type with width of 16 bits /// </summary> using int16 = std::int16_t; /// <summary> /// Signed integer type with width of 32 bits /// </summary> using int32 = std::int32_t; /// <summary> /// Signed integer type with width of 64 bits /// </summary> using int64 = std::int64_t; /// <summary> /// Unsigned integer type with width of 8 bits /// </summary> using uint8 = std::uint8_t; /// <summary> /// Unsigned integer type with width of 16 bits /// </summary> using uint16 = std::uint16_t; /// <summary> /// Unsigned integer type with width of 32 bits /// </summary> using uint32 = std::uint32_t; /// <summary> /// Unsigned integer type with width of 64 bits /// </summary> using uint64 = std::uint64_t; ////////////////////////////////////////////////// // // Character Types // ////////////////////////////////////////////////// /// <summary> /// UTF-8 character representation /// </summary> using char8 = char; /// <summary> /// UTF-16 character representation /// </summary> using char16 = char16_t; /// <summary> /// UTF-32 character representation /// </summary> using char32 = char32_t; }
20.372093
50
0.526826
Fuyutsubaki
d896b849aca3377adb70454abf8381637548e109
538
hpp
C++
include/sktest/ansi_color.hpp
kagurakanon/skjvm
bca3354777eebaf531087f19bb0c6914f639a15a
[ "Unlicense" ]
null
null
null
include/sktest/ansi_color.hpp
kagurakanon/skjvm
bca3354777eebaf531087f19bb0c6914f639a15a
[ "Unlicense" ]
null
null
null
include/sktest/ansi_color.hpp
kagurakanon/skjvm
bca3354777eebaf531087f19bb0c6914f639a15a
[ "Unlicense" ]
null
null
null
#ifndef sktest_ansi_color_hpp #define sktest_ansi_color_hpp #define BOLD_RED "\033[31;1m" #define RED "\033[31m" #define BOLD_GREEN "\033[32;1m" #define GREEN "\033[32m" #define BLUE "\033[34m" #define BOLD "\033[1m" #define RESET "\033[0m" #define bold_red(string) BOLD_RED string RESET #define red(string) RED string RESET #define bold_green(string) BOLD_GREEN string RESET #define green(string) GREEN string RESET #define blue(string) BLUE string RESET #define bold(string) BOLD string RESET #endif /* sktest_ansi_color_hpp */
21.52
50
0.760223
kagurakanon
d8b7ab0f0d2fc85cccd5b4d753b21f947470e5fe
2,154
cpp
C++
main.cpp
hamada147/Turning-Machine
572619594084e8321789e543188f5958854f23f7
[ "MIT" ]
null
null
null
main.cpp
hamada147/Turning-Machine
572619594084e8321789e543188f5958854f23f7
[ "MIT" ]
null
null
null
main.cpp
hamada147/Turning-Machine
572619594084e8321789e543188f5958854f23f7
[ "MIT" ]
null
null
null
#include <iostream> #include <list> #include "TurningMachine.h" #include "TurningMachineTransition.h" using namespace std; void main() { string Q0 = "q0"; // start state string q[] = { "q0", "q1", "q2", "q3" }; // the exisiting state char s[] = { '0', '1' }; // the existing letters TurningMachineTransition t[] = { // startState, token, write, mdirection, endState TurningMachineTransition("q0", '1', '1', 'R', "q0"), TurningMachineTransition("q0", '0', '1', 'R', "q1"), TurningMachineTransition("q1", '1', '1', 'R', "q1"), TurningMachineTransition("q1", 'U', 'U', 'L', "q2"), TurningMachineTransition("q2", '1', 'U', 'L', "q3"), TurningMachineTransition("q3", '1', '1', 'L', "q3"), TurningMachineTransition("q3", 'U', 'U', 'R', "q4"), }; // all exisint transitions string f[] = { "q4" }; // the final states list<string> Q; // list of the states list<char> Sigma; // list of the letters list<TurningMachineTransition> Delta; // list of all avilable transitions list<string> FinalState; // list of all final states list<string>::iterator it1 = Q.begin(); // an iterator to save the states from the array to the list for (int i = 0, arraySize = sizeof(q) / sizeof(q[0]); i < arraySize; i++) { Q.insert(it1, q[i]); // inserting it into the list } list<char>::iterator it2 = Sigma.begin(); // an iterator to save the letters from the array to the list for (int i = 0, arraySize = sizeof(s) / sizeof(s[0]); i < arraySize; i++) { Sigma.insert(it2, s[i]); // inserting it into the list } list<TurningMachineTransition>::iterator it3 = Delta.begin(); // an iterator to save the letters from the array to the list for (int i = 0, arraySize = sizeof(t) / sizeof(t[0]); i < arraySize; i++) { Delta.insert(it3, t[i]); // inserting it into the list } list<string>::iterator it4 = FinalState.begin(); for (int i = 0, arraySize = sizeof(f) / sizeof(f[0]); i < arraySize; i++) { FinalState.insert(it4, f[i]); // inserting it into the list } TurningMachine x = TurningMachine(Q, Sigma, Delta, Q0, FinalState); x.Accepts("11011"); system("PAUSE"); }
36.508475
125
0.623955
hamada147
d8b997e1ee4d6e1f2f4d31a8d3b97d270036a67e
797
cpp
C++
Kattis/oddmanout.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/oddmanout.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/oddmanout.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// // https://open.kattis.com/problems/oddmanout #include <iostream> #include <cmath> #include <algorithm> #include <string> #include <iomanip> #include <sstream> #include <vector> #include <iomanip> #include <map> #define Forcase int T; cin>>T; for(int t = 1; t <= T; t++) #define Forever while(true) using namespace std; int n; int a[1010]; int ans() { for (int i = 0; i < n + 1; i += 2) { if (a[i] != a[i + 1]) { return a[i]; } } if (a[n - 1] != a[n - 2]) { return a[n - 1]; } return 0; } int main() { Forcase { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n); cout << "Case #" << t << ": " << ans() << '\n'; } return 0; }
16.604167
58
0.449184
YourName0729
d8bcc4329605103d6e07398a907ca7a2e51d5f4b
1,496
cpp
C++
tests/all_tests.cpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
11
2021-03-15T07:06:21.000Z
2021-09-27T13:54:25.000Z
tests/all_tests.cpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
null
null
null
tests/all_tests.cpp
olegpublicprofile/stdfwd
19671bcc8e53bd4c008f07656eaf25a22495e093
[ "MIT" ]
1
2021-06-24T10:46:46.000Z
2021-06-24T10:46:46.000Z
#include "all_tests.hpp" #include "tests/headers_tests/container_headers_tests.hpp" #include "tests/headers_tests/utility_headers_tests.hpp" #include "tests/headers_tests/string_headers_tests.hpp" #include "tests/headers_tests/filesystem_headers_tests.hpp" #include "tests/headers_tests/thread_headers_tests.hpp" #include "tests/headers_tests/atomic_headers_tests.hpp" #include "tests/headers_tests/dynamic_memory_management_headers_tests.hpp" #include "tests/headers_tests/regex_headers_tests.hpp" #include "headers_tests/error_handling_headers_tests.hpp" #include "headers_tests/iterator_headers_tests.hpp" #include "headers_tests/localization_headers_tests.hpp" #include "headers_tests/numeric_headers_tests.hpp" #include "headers_tests/algorithms_headers_tests.hpp" //------------------------------------------------------------------------------ namespace all_tests { //------------------------------------------------------------------------------ void run() { container_headers_tests::run(); utility_headers_tests::run(); string_headers_tests::run(); filesystem_headers_tests::run(); thread_headers_tests::run(); atomic_headers_tests::run(); dynamic_memory_management_headers_tests::run(); regex_headers_tests::run(); error_handling_headers_tests::run(); iterator_headers_tests::run(); localization_headers_tests::run(); numeric_headers_tests::run(); algorithms_headers_tests::run(); } //------------------------------------------------------------------------------ }
34.790698
80
0.692513
olegpublicprofile
d8c740d37896fbecdfa2ab1292e0c02eeb78c423
2,596
cpp
C++
Lumi/src/Lumi/Renderer/Buffer.cpp
ChillyHub/Lumi
54977f228207471ba917e7fd93d0b44f49bec04e
[ "MIT" ]
null
null
null
Lumi/src/Lumi/Renderer/Buffer.cpp
ChillyHub/Lumi
54977f228207471ba917e7fd93d0b44f49bec04e
[ "MIT" ]
null
null
null
Lumi/src/Lumi/Renderer/Buffer.cpp
ChillyHub/Lumi
54977f228207471ba917e7fd93d0b44f49bec04e
[ "MIT" ]
null
null
null
#include "pch.h" #include "Buffer.h" #include "Renderer.h" #include "Platform/OpenGL/OpenGLBuffer.h" namespace Lumi { ///////////////////////////////////////////////////////////////////// // class VertexBuffer // ------------------ std::shared_ptr<VertexBuffer> VertexBuffer::Create(unsigned int count) { LM_PROFILE_FUNCTION(); switch (Renderer::GetAPI()) { case RendererAPI::API::None: LUMI_CORE_ASSERT(false, "RendererAPI: Unknown renderer API!"); return nullptr; case RendererAPI::API::OpenGL: return std::shared_ptr<VertexBuffer>(new OpenGLVertexBuffer(count)); case RendererAPI::API::Vulkan: LUMI_CORE_ASSERT(false, "RendererAPI: Vulkan currently not supported!"); return nullptr; case RendererAPI::API::DirectX: LUMI_CORE_ASSERT(false, "RendererAPI: DirectX currently not supported!"); return nullptr; default: break; } LUMI_CORE_ASSERT(false, "RendererAPI: Unknown renderer API!"); return nullptr; } std::shared_ptr<VertexBuffer> VertexBuffer::Create(float* vertices, unsigned int count) { LM_PROFILE_FUNCTION(); switch (Renderer::GetAPI()) { case RendererAPI::API::None: LUMI_CORE_ASSERT(false, "RendererAPI: Unknown renderer API!"); return nullptr; case RendererAPI::API::OpenGL: return std::shared_ptr<VertexBuffer>(new OpenGLVertexBuffer(vertices, count)); case RendererAPI::API::Vulkan: LUMI_CORE_ASSERT(false, "RendererAPI: Vulkan currently not supported!"); return nullptr; case RendererAPI::API::DirectX: LUMI_CORE_ASSERT(false, "RendererAPI: DirectX currently not supported!"); return nullptr; default: break; } LUMI_CORE_ASSERT(false, "RendererAPI: Unknown renderer API!"); return nullptr; } ///////////////////////////////////////////////////////////////////// // class IndexBuffer // ----------------- std::shared_ptr<IndexBuffer> IndexBuffer::Create(unsigned int* indices, unsigned int count) { LM_PROFILE_FUNCTION(); switch (Renderer::GetAPI()) { case RendererAPI::API::None: LUMI_CORE_ASSERT(false, "RendererAPI: Unknown renderer API!"); return nullptr; case RendererAPI::API::OpenGL: return std::shared_ptr<IndexBuffer>(new OpenGLIndexBuffer(indices, count)); case RendererAPI::API::Vulkan: LUMI_CORE_ASSERT(false, "RendererAPI: Vulkan currently not supported!"); return nullptr; case RendererAPI::API::DirectX: LUMI_CORE_ASSERT(false, "RendererAPI: DirectX currently not supported!"); return nullptr; default: break; } LUMI_CORE_ASSERT(false, "RendererAPI: Unknown renderer API!"); return nullptr; } }
28.527473
92
0.678737
ChillyHub
d8cd74fed69e6b3a7dc40297ab8056c00d592561
4,357
cpp
C++
Project/12-QPainter_Coord/mainwindow.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
Project/12-QPainter_Coord/mainwindow.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
Project/12-QPainter_Coord/mainwindow.cpp
liukai-tech/Qt-Learning
5f7d29f5868b6fa8b9340095af6cd025f94f698f
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QPainter> #include <QPaintEvent> #include <QEvent> //在label控件内动态绘制轨迹 //参考 https://blog.csdn.net/qq_41399894/article/details/88051337 int count = 0; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); ui->labelDraw->installEventFilter(this); m_updatePainterTimer = new QTimer; m_updatePainterTimer->setInterval(2000); connect(m_updatePainterTimer, SIGNAL(timeout()), this, SLOT(handleTimeout())); m_updatePainterTimer->start(); } MainWindow::~MainWindow() { delete ui; } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if(obj ==ui->labelDraw && event->type() == QEvent::Paint) { drawFunction(); } if(obj ==ui->labelDraw && event->type() == QEvent::Timer) { handleTimeout(); } return QWidget::eventFilter(obj, event); } //void MainWindow::paintEvent(QPaintEvent *event) //{ // Q_UNUSED(event); // ui->labelBtnInfo->setText("Draw Rect."); // QPainter painter(ui->labelDraw); // painter.setBrush(Qt::red); // painter.drawRect(0,0,100,100); // painter.setBrush(Qt::yellow); // painter.drawRect(-50,-50,100,100); //} void MainWindow::drawFunction() { QPainter painter(ui->labelDraw); painter.setRenderHint(QPainter::Antialiasing, true); // 设置画笔颜色、宽度 painter.setPen(QColor(0,0,0)); // 设置画笔颜色、宽度 // painter.setPen(QPen(QColor(0, 0, 0), 2)); // 设置画刷颜色 QFont font; font.setPointSize(15); font.setFamily("楷体"); font.setItalic(true); painter.setFont(font); //点坐标 QPoint points[4] = { QPoint(150,100), QPoint(300,150), QPoint(350,250), QPoint(100,300) }; QPainterPath path; path.addRect(150,150,100,100); path.moveTo(100,100); path.cubicTo(100,100,150,100,400,400); int startAngle = 90*16; // 跨越度数 int spanAngle = 180*16; switch (count) { case 0: ui->labelBtnInfo->setText("1.画矩形"); painter.drawRect(QRect(0,0,100,100)); break; case 1: ui->labelBtnInfo->setText("2.移动X:100px,画两倍圆"); //将(100,0)作为坐标原点 painter.translate(100,0); //放大两倍 painter.scale(2,2); painter.drawEllipse(QPointF(50, 50), 50, 50); break; case 2: ui->labelBtnInfo->setText("3.旋转画线"); painter.resetTransform(); painter.drawLine(200,150,400,150); //旋转45° painter.rotate(45); painter.drawLine(200,150,400,150); break; case 3: ui->labelBtnInfo->setText("4.画圆角矩形"); painter.drawRoundRect(QRect(150,0,100,100)); break; case 4: ui->labelBtnInfo->setText("5.画多边形"); painter.drawPolygon(points,4); break; case 5: ui->labelBtnInfo->setText("6.画多边线"); painter.drawPolyline(points,4); break; case 6: ui->labelBtnInfo->setText("7.画弧线"); painter.drawArc(QRect(150,0,100,100),startAngle,spanAngle); break; case 7: ui->labelBtnInfo->setText("8.画路径"); painter.drawPath(path); break; case 8: ui->labelBtnInfo->setText("9.画字"); painter.drawText(QRect(150,150,100,100),Qt::AlignCenter,tr("Hello Qt")); break; case 9: ui->labelBtnInfo->setText("10.画图"); painter.drawPixmap(150,50,QPixmap(":/Image/tracker")); break; default: break; } count == 9 ? count = 0:count++; } void MainWindow::handleTimeout() { ui->labelDraw->update(); } void MainWindow::on_btn1_clicked() { ui->labelBtnInfo->setText("Button 1 Clicked."); } void MainWindow::on_btn2_clicked() { ui->labelBtnInfo->setText("Button 2 Clicked."); } void MainWindow::on_btn3_clicked() { ui->labelBtnInfo->setText("Button 3 Clicked."); } void MainWindow::on_btn4_clicked() { ui->labelBtnInfo->setText("Button 4 Clicked."); } void MainWindow::on_btn5_clicked() { ui->labelBtnInfo->setText("Button 5 Clicked."); } void MainWindow::on_btn6_clicked() { ui->labelBtnInfo->setText("Button 6 Clicked."); } void MainWindow::on_btn7_clicked() { ui->labelBtnInfo->setText("Button 7 Clicked."); } void MainWindow::on_btn8_clicked() { ui->labelBtnInfo->setText("Button 8 Clicked."); }
23.175532
82
0.611889
liukai-tech
d8d2c822be16eb71314a5cba0bf6a003b66a276a
541
cpp
C++
ecs256/BoxPack/src/RcppExports.cpp
nick-ulle/teaching-notes
3ffc527153570c1f4d31d4d19fe0d993442ea225
[ "BSD-3-Clause-Clear" ]
28
2017-03-31T03:15:13.000Z
2020-09-21T19:58:35.000Z
ecs256/BoxPack/src/RcppExports.cpp
nick-ulle/teaching-notes
3ffc527153570c1f4d31d4d19fe0d993442ea225
[ "BSD-3-Clause-Clear" ]
null
null
null
ecs256/BoxPack/src/RcppExports.cpp
nick-ulle/teaching-notes
3ffc527153570c1f4d31d4d19fe0d993442ea225
[ "BSD-3-Clause-Clear" ]
33
2018-01-12T04:17:08.000Z
2021-11-24T04:31:05.000Z
// This file was generated by Rcpp::compileAttributes // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // pack_boxes List pack_boxes(int n, NumericVector p); RcppExport SEXP BoxPack_pack_boxes(SEXP nSEXP, SEXP pSEXP) { BEGIN_RCPP Rcpp::RObject __result; Rcpp::RNGScope __rngScope; Rcpp::traits::input_parameter< int >::type n(nSEXP); Rcpp::traits::input_parameter< NumericVector >::type p(pSEXP); __result = Rcpp::wrap(pack_boxes(n, p)); return __result; END_RCPP }
27.05
66
0.735675
nick-ulle
d8d994ab48010e4940d3829f9bc226ae044f3e9e
3,339
cpp
C++
tests/FIRTestSuite.cpp
ianran/DSP-lite
6c4cf040abf18a4c8e7bc0ba970df7ad77b1f0fe
[ "MIT" ]
null
null
null
tests/FIRTestSuite.cpp
ianran/DSP-lite
6c4cf040abf18a4c8e7bc0ba970df7ad77b1f0fe
[ "MIT" ]
null
null
null
tests/FIRTestSuite.cpp
ianran/DSP-lite
6c4cf040abf18a4c8e7bc0ba970df7ad77b1f0fe
[ "MIT" ]
null
null
null
/* Copyright 2018 Ian Rankin * * 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. */ // FIRTestSuite.cpp // Written Ian Rankin - June 2018 // // This is a test suite for the FIR filter to make sure // it is working correctly. #include <iostream> #include <FIRFilter.h> #include <Filter.h> float gains[] = {1.0, 1.0, 1.0, 1.0, 1.0}; int main(int argc, char **argv) { ////////////////// Test 1 /////////////////// float y[] = {1,2,3,4,5,5,5,5,5,5}; // Test that outputs are correct for basic block filter. Filter<float> *filter1 = new FIRFilter<float>(gains, 5); for (int i = 0; i < 10; i++) { float result = filter1->filter(1.0); if (result != y[i]) { std::cerr << "FAILED: test 1 for simple block filtering." << std::endl; return -1; } // end if } // end for ///////////////// Test 2 /////////////////////// int gains2[] = {3,-1,1}; int y2[] = {3,2,3,3,3}; FIRFilter<int> filter2; filter2.setGains(gains2, 3); for (int i = 0; i < 5; i++) { int result = filter2.filter(1); //std::cout << result << " y2 = " << y2[i] << " " << (int)(result != y2[i]) << std::endl; if (result != y2[i]) { std::cerr << "FAILED: test 2 for simple filtering." << std::endl; return -1; } // end if } // end for ///////////////////// Test 3 ///////////////////////// double gains3[] = {0.1, 0.2, 0.3, 0.4, 0.5}; double y3[] = {0.1, 0.4, 1.0, 2.0}; FIRFilter<double> filter3(gains3, 5); for (int i = 1; i < 5; i++) { filter3.filter(i); double result = filter3.getOutput(); if (result != y3[i-1]) { std::cerr << "FAILED: test 3 for simple filtering." << std::endl; std::cerr << "Result = " << result << " y3[i] = " << y3[i] << std::endl; return -1; } // end if } if (filter3.getLength() != 5) { std::cerr << "FAILED: test for get length function... (What did you break!?)" << std::endl; return -1; } if (filter3.getGains() == NULL) { std::cerr << "FAILED: get gains test (What did you break!?)" << std::endl; return -1; } // test passed if reached here. std::cout << "PASSED all tests!" << std::endl; return 0; } // end main
35.147368
99
0.573824
ianran
d8e0dea5dd13274eb7a46f819792391f73b292ab
3,387
hpp
C++
include/Type.hpp
LudwigBoltzmann/NeuralNetwork
490b345b3b6dd7bb0b97302c55bb5b7cc13f9598
[ "MIT" ]
1
2017-02-25T23:11:09.000Z
2017-02-25T23:11:09.000Z
include/Type.hpp
LudwigBoltzmann/NeuralNetwork
490b345b3b6dd7bb0b97302c55bb5b7cc13f9598
[ "MIT" ]
null
null
null
include/Type.hpp
LudwigBoltzmann/NeuralNetwork
490b345b3b6dd7bb0b97302c55bb5b7cc13f9598
[ "MIT" ]
null
null
null
#ifndef TYPE_H #define TYPE_H #include "vector" #include <iostream> #include "math.h" #include "time.h" #include "omp.h" #include "cilk/reducer.h" #include "cilk/cilk.h" #include "cilk/reducer_opadd.h" namespace DeepLearning { // columnwise template matrix class template <typename type> class tensor { public: typedef std::vector<type> typeVec; private: typeVec m_data; int m_nheight; int m_nwidth; int m_ndepth; int m_nchannel; public: tensor() : m_data(), m_nwidth(0), m_nheight(0), m_ndepth(0), m_nchannel(0) {} tensor(int nheight, int nwidth, int ndepth, int nchannel) : m_data(nwidth * nheight * ndepth * nchannel), m_nwidth(nwidth), m_nheight(nheight), m_ndepth(ndepth), m_nchannel(nchannel) {} typeVec& data(void) { return m_data; } int nrow(void) { return m_nrow; } int ncol(void) { return m_ncol; } int ndepth(void) { return m_ndepth; } int nchannel(void) { return m_nchannel; } void resize(int nwidth, int nheight, int ndepth, int nchannel) { m_data.resize(nrow * ncol * ndepth * nchannel); m_nwidth = nwidth; m_nheight = nheight; m_ndepth = ndepth; m_nchannel = nchannel; } type& operator()(int width, int height, int depth, int channel) { return *(m_data.data() + channel * m_nwidth * m_nheight * m_ndepth + depth * m_nwidth * m_nheight + height * m_nwidth + width); } }; // columnwise template matrix class template <typename type> class mat { public: typedef std::vector<type> typeVec; private: typeVec m_data; int m_nrow, m_ncol; public: mat() : m_data(), m_ncol(0), m_nrow(0) {} mat(int nrow, int ncol) : m_data(nrow * ncol), m_ncol(ncol), m_nrow(nrow) {} type* operator[](int row) { return m_data.data() + row * m_ncol; } typeVec& data(void) { return m_data; } int nrow(void) { return m_nrow; } int ncol(void) { return m_ncol; } void resize(int nrow, int ncol) { m_data.resize(nrow* ncol); m_ncol = ncol; m_nrow = nrow; } }; class randomGenerator { private: unsigned long m_seed; public: randomGenerator() { m_seed = 850702123123 + omp_get_wtime(); } unsigned long getSeed() { return m_seed; } unsigned long getRand() { return ((m_seed = 214013 * m_seed + 2531011) & 4294967295); } double getUniform() { return getRand() / 4294967296.0; } double boxMuller() { return sqrt(-2.0 * log(getUniform())) * cos(2.0 * 3.141592 * getUniform()); } }; typedef std::vector<double> rVec; typedef mat<double> rMat; typedef tensor<double> rTen; typedef std::vector<int> iVec; typedef mat<int> iMat; typedef tensor<int> iTen; } #endif // TYPE_H
27.762295
95
0.517272
LudwigBoltzmann
d8e1e430ac443761d808f53ae9dc141b10ac0150
385
cpp
C++
FileUtilities.cpp
refik-karic/ZSharp
643d4d7603e91d5b9150bf8ddfed8b1eab930b92
[ "MIT" ]
null
null
null
FileUtilities.cpp
refik-karic/ZSharp
643d4d7603e91d5b9150bf8ddfed8b1eab930b92
[ "MIT" ]
null
null
null
FileUtilities.cpp
refik-karic/ZSharp
643d4d7603e91d5b9150bf8ddfed8b1eab930b92
[ "MIT" ]
null
null
null
#include "FileUtilities.h" #include <fstream> namespace ZSharp { void ReadFileToBuffer(const char* fileName, std::vector<char>& fileBuffer) { std::ifstream inputStream(fileName, std::ios::binary); if (!inputStream.is_open()) { return; } fileBuffer = std::vector<char>(std::istreambuf_iterator<char>(inputStream), std::istreambuf_iterator<char>()); } }
20.263158
114
0.685714
refik-karic
d8e926ac4563a9be38abdfd8db7e4d3db8060434
549
cpp
C++
A/A1375.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
A/A1375.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
A/A1375.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> // Not understood using namespace std; int main(){ int t,n; cin>>t; while(t--){ cin>>n; vector<long> v(n); for(int i=0;i<n;i++){ cin>>v[i]; } for(int i=0;i<n;i++){ if(v[i] >= 0 && i % 2 == 1){ v[i] = -v[i]; }else if(v[i] <= 0 && i % 2 == 0){ v[i] = -v[i]; } } for(int i=0; i<n;i++){ cout<<v[i]<<" "; } cout<<endl; } return 0; }
20.333333
46
0.333333
Darknez07
d8e949088456e3247276d296f1708ac31c5076aa
14,635
cpp
C++
gcsdk/sqlaccess/schemafull.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
tf2_src/gcsdk/sqlaccess/schemafull.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
tf2_src/gcsdk/sqlaccess/schemafull.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //============================================================================= #include "stdafx.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" namespace GCSDK { CSchemaFull g_SchemaFull; CSchemaFull & GSchemaFull() { return g_SchemaFull; } //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CSchemaFull::CSchemaFull() { m_pubScratchBuffer = NULL; m_cubScratchBuffer = 0; m_unCheckSum = 0; m_mapFTSEnabled.SetLessFunc( DefLessFunc( enum ESchemaCatalog ) ); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CSchemaFull::~CSchemaFull() { Uninit(); } //----------------------------------------------------------------------------- // Purpose: Call this after you've finished setting up the SchemaFull (either // by loading it or by in GenerateIntrinsic). It calculates our checksum // and allocates our scratch buffer. //----------------------------------------------------------------------------- void CSchemaFull::FinishInit() { // Calculate our checksum m_unCheckSum = 0; for ( int iSchema = 0; iSchema < m_VecSchema.Count(); iSchema++ ) m_unCheckSum += m_VecSchema[iSchema].CalcChecksum(); // Allocate our scratch buffer Assert( NULL == m_pubScratchBuffer ); // Include some slop for field IDs and sizes in a sparse record // 2k is way overkill but still no big deal m_cubScratchBuffer = k_cubRecordMax + 2048; m_pubScratchBuffer = ( uint8 * ) malloc( m_cubScratchBuffer ); } //----------------------------------------------------------------------------- // Purpose: Call this after you've finished setting up the SchemaFull (either // by loading it or by in GenerateIntrinsic). It calculates our checksum // and allocates our scratch buffer. //----------------------------------------------------------------------------- void CSchemaFull::SetITable( CSchema* pSchema, int iTable ) { // make sure we don't have this schema anywhere already for ( int iSchema = 0; iSchema < m_VecSchema.Count(); iSchema++ ) { if ( pSchema != &m_VecSchema[iSchema] ) AssertFatalMsg( m_VecSchema[iSchema].GetITable() != iTable, "Duplicate iTable in schema definition.\n" ); } // set the pSchema object pSchema->SetITable( iTable ); } //----------------------------------------------------------------------------- // Purpose: Uninits the schema. Need to call this explicitly before app shutdown // on static instances of this object, as the CSchema objects // point to memory in static memory pools which may destruct // before static instances of this object. //----------------------------------------------------------------------------- void CSchemaFull::Uninit() { m_VecSchema.RemoveAll(); if ( NULL != m_pubScratchBuffer ) { free( m_pubScratchBuffer ); m_pubScratchBuffer = NULL; } } //----------------------------------------------------------------------------- // Purpose: Get the scratch buffer. It is large enough to handle any // record, sparse or otherwise // //----------------------------------------------------------------------------- uint8* CSchemaFull::GetPubScratchBuffer( ) { return m_pubScratchBuffer; } //----------------------------------------------------------------------------- // Purpose: This is used during the generation of our intrinsic schema. We've // added a new schema to ourselves, and we need to make sure that it // matches the corresponding C class. // Input: pSchema - Schema to check // cField - Number of fields the schema should contain. // cubRecord - Size of a record in the schema //----------------------------------------------------------------------------- void CSchemaFull::CheckSchema( CSchema *pSchema, int cField, uint32 cubRecord ) { // We generate our structures and our schema using macros that operate on the // same source. We check a couple of things to make sure that they're properly in sync. // This will fail if the schema's definition specifies the wrong iTable if ( pSchema != &m_VecSchema[pSchema->GetITable()] ) { EmitError( SPEW_SQL, "Table %s has a bad iTable\n", pSchema->GetPchName() ); } // This will fail if there are missing lines in the schema definition if ( pSchema->GetCField() != cField ) { EmitError( SPEW_SQL, "Badly formed table %s (blank line in schema def?)\n", pSchema->GetPchName() ); AssertFatal( false ); } // This is unlikely to fail. It indicates some kind of size mismatch (maybe a packing problem?) if ( pSchema->CubRecordFixed() != cubRecord ) { // You may hit this if END_FIELDDATA_HAS_VAR_FIELDS is not used properly EmitError( SPEW_SQL, "Table %s has an inconsistent size (class = %d, schema = %d)\n", pSchema->GetPchName(), cubRecord, pSchema->CubRecordFixed() ); AssertFatal( false ); } } //----------------------------------------------------------------------------- // Purpose: Finds the table with a given name. // Input: pchName - Name of the table to search for // Output: Index of the matching table ( k_iTableNil if there isn't one) //----------------------------------------------------------------------------- int CSchemaFull::FindITable( const char *pchName ) { for ( int iSchema = 0; iSchema < m_VecSchema.Count(); iSchema++ ) { if ( 0 == Q_strcmp( pchName, m_VecSchema[iSchema].GetPchName() ) ) return iSchema; } return k_iTableNil; } //----------------------------------------------------------------------------- // Purpose: Finds the table with a given iTable (iSchema) // Input: iTable - // Output: NULL or a const char * to the name (for temporary use only) //----------------------------------------------------------------------------- const char * CSchemaFull::PchTableFromITable( int iTable ) { if ( iTable < 0 || iTable >= m_VecSchema.Count() ) return NULL; else return m_VecSchema[ iTable ].GetPchName(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CSchemaFull::AddFullTextCatalog( enum ESchemaCatalog eCatalog, const char *pstrCatalogName, int nFileGroup ) { CFTSCatalogInfo info; info.m_eCatalog = eCatalog; info.m_nFileGroup = nFileGroup; info.m_pstrName = strdup(pstrCatalogName); m_vecFTSCatalogs.AddToTail( info ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- int CSchemaFull::GetFTSCatalogByName( enum ESchemaCatalog eCatalog, const char *pstrCatalogName ) { int nIndex = -1; FOR_EACH_VEC( m_vecFTSCatalogs, i ) { CFTSCatalogInfo &refInfo = m_vecFTSCatalogs[ i ]; if ( 0 == Q_stricmp( pstrCatalogName, refInfo.m_pstrName ) ) { nIndex = i; break; } } return nIndex; } //----------------------------------------------------------------------------- // Purpose: turn on FTS for the named schema catalog. Called by the // InitIntrinsic() function. //----------------------------------------------------------------------------- void CSchemaFull::EnableFTS( enum ESchemaCatalog eCatalog ) { // mark it enabled in the map m_mapFTSEnabled.Insert( eCatalog, true ); } //----------------------------------------------------------------------------- // Purpose: is FTS enabled for the supplied schema catalog? //----------------------------------------------------------------------------- bool CSchemaFull::GetFTSEnabled( enum ESchemaCatalog eCatalog ) { int iEntry = m_mapFTSEnabled.Find( eCatalog ); if ( iEntry == m_mapFTSEnabled.InvalidIndex() ) return false; return true; } //----------------------------------------------------------------------------- // Purpose: Adds a schema conversion instruction (for use in converting from // a different SchemaFull to this one). //----------------------------------------------------------------------------- void CSchemaFull::AddDeleteTable( const char *pchTableName ) { DeleteTable_t &deleteTable = m_VecDeleteTable[m_VecDeleteTable.AddToTail()]; Q_strncpy( deleteTable.m_rgchTableName, pchTableName, sizeof( deleteTable.m_rgchTableName ) ); } //----------------------------------------------------------------------------- // Purpose: Adds a schema conversion instruction (for use in converting from // a different SchemaFull to this one). //----------------------------------------------------------------------------- void CSchemaFull::AddRenameTable( const char *pchTableNameOld, const char *pchTableNameNew ) { RenameTable_t &renameTable = m_VecRenameTable[m_VecRenameTable.AddToTail()]; Q_strncpy( renameTable.m_rgchTableNameOld, pchTableNameOld, sizeof( renameTable.m_rgchTableNameOld ) ); renameTable.m_iTableDst = FindITable( pchTableNameNew ); Assert( k_iTableNil != renameTable.m_iTableDst ); } //----------------------------------------------------------------------------- // Purpose: Adds a schema conversion instruction (for use in converting from // a different SchemaFull to this one). //----------------------------------------------------------------------------- void CSchemaFull::AddDeleteField( const char *pchTableName, const char *pchFieldName ) { int iSchema = FindITable( pchTableName ); AssertFatal( k_iTableNil != iSchema ); m_VecSchema[iSchema].AddDeleteField( pchFieldName ); } //----------------------------------------------------------------------------- // Purpose: Adds a schema conversion instruction (for use in converting from // a different SchemaFull to this one). //----------------------------------------------------------------------------- void CSchemaFull::AddRenameField( const char *pchTableName, const char *pchFieldNameOld, const char *pchFieldNameNew ) { int iSchema = FindITable( pchTableName ); AssertFatal( k_iTableNil != iSchema ); m_VecSchema[iSchema].AddRenameField( pchFieldNameOld, pchFieldNameNew ); } //----------------------------------------------------------------------------- // Purpose: Adds a schema conversion instruction (for use in converting from // a different SchemaFull to this one). //----------------------------------------------------------------------------- void CSchemaFull::AddAlterField( const char *pchTableName, const char *pchFieldNameOld, const char *pchFieldnameNew, PfnAlterField_t pfnAlterField ) { int iSchema = FindITable( pchTableName ); AssertFatal( k_iTableNil != iSchema ); m_VecSchema[iSchema].AddAlterField( pchFieldNameOld, pchFieldnameNew, pfnAlterField ); } //----------------------------------------------------------------------------- // Purpose: Add a trigger to the desired schema //----------------------------------------------------------------------------- void CSchemaFull::AddTrigger( ESchemaCatalog eCatalog, const char *pchTableName, const char *pchTriggerName, ETriggerType eTriggerType, const char *pchTriggerText ) { CTriggerInfo trigger; trigger.m_eTriggerType = eTriggerType; trigger.m_eSchemaCatalog = eCatalog; Q_strncpy( trigger.m_szTriggerName, pchTriggerName, Q_ARRAYSIZE( trigger.m_szTriggerName ) ); Q_strncpy( trigger.m_szTriggerTableName, pchTableName, Q_ARRAYSIZE( trigger.m_szTriggerTableName ) ); trigger.m_strText = pchTriggerText; // add it to our list m_VecTriggers.AddToTail( trigger ); } //----------------------------------------------------------------------------- // Purpose: Figures out how to map a table from another SchemaFull into us. // First we check our conversion instructions to see if any apply, // and then we look for a straightforward match. // Input: pchTableName - Name of the table we're trying to map // piTableDst - [Return] Index of the table to map it to // Output: true if we know what to do with this table (if false, the conversion // is undefined and dangerous). //----------------------------------------------------------------------------- bool CSchemaFull::BCanConvertTable( const char *pchTableName, int *piTableDst ) { // Should this table be deleted? for ( int iDeleteTable = 0; iDeleteTable < m_VecDeleteTable.Count(); iDeleteTable++ ) { if ( 0 == Q_strcmp( pchTableName, m_VecDeleteTable[iDeleteTable].m_rgchTableName ) ) { *piTableDst = k_iTableNil; return true; } } // Should this table be renamed? for ( int iRenameTable = 0; iRenameTable < m_VecRenameTable.Count(); iRenameTable++ ) { if ( 0 == Q_strcmp( pchTableName, m_VecRenameTable[iRenameTable].m_rgchTableNameOld ) ) { *piTableDst = m_VecRenameTable[iRenameTable].m_iTableDst; return true; } } // Find out which of our tables this table maps to (if it doesn't map // to any of them, we don't know what to do with it). *piTableDst = FindITable( pchTableName ); return ( k_iTableNil != *piTableDst ); } //----------------------------------------------------------------------------- // Purpose: Gets the default SQL schema name for a catalog //----------------------------------------------------------------------------- const char *CSchemaFull::GetDefaultSchemaNameForCatalog( ESchemaCatalog eCatalog ) { // For all catalogs it's actually the same if ( m_strDefaultSchemaName.IsEmpty() ) { m_strDefaultSchemaName.Set( CFmtStr( "App%u", GGCBase()->GetAppID() ) ); } return m_strDefaultSchemaName.Get(); } #ifdef DBGFLAG_VALIDATE //----------------------------------------------------------------------------- // Purpose: Run a global validation pass on all of our data structures and memory // allocations. // Input: validator - Our global validator object // pchName - Our name (typically a member var in our container) //----------------------------------------------------------------------------- void CSchemaFull::Validate( CValidator &validator, const char *pchName ) { VALIDATE_SCOPE(); ValidateObj( m_VecSchema ); for ( int iSchema = 0; iSchema < m_VecSchema.Count(); iSchema++ ) { ValidateObj( m_VecSchema[iSchema] ); } ValidateObj( m_VecDeleteTable ); ValidateObj( m_VecRenameTable ); ValidateObj( m_mapFTSEnabled ); ValidateObj( m_vecFTSCatalogs ); FOR_EACH_VEC( m_vecFTSCatalogs, i ) { ValidateObj( m_vecFTSCatalogs[i] ); } ValidateObj( m_VecTriggers ); FOR_EACH_VEC( m_VecTriggers, i ) { ValidateObj( m_VecTriggers[i] ); } validator.ClaimMemory( m_pubScratchBuffer ); } #endif // DBGFLAG_VALIDATE } // namespace GCSDK
35.695122
164
0.553946
DannyParker0001
d8eb7288ba741f466815cc973fa5a71c6f977d4c
11,165
cc
C++
xentrace.cc
chonghw/xenpwn
de3f3c2f839cd18099042585fa9900097082a314
[ "MIT" ]
150
2016-08-04T02:00:20.000Z
2021-11-23T08:04:35.000Z
xentrace.cc
chonghw/xenpwn
de3f3c2f839cd18099042585fa9900097082a314
[ "MIT" ]
2
2016-11-02T08:53:20.000Z
2020-07-16T14:11:42.000Z
xentrace.cc
felixwilhelm/xenpwn
de3f3c2f839cd18099042585fa9900097082a314
[ "MIT" ]
29
2016-08-04T04:23:33.000Z
2021-11-23T08:04:36.000Z
#include <iostream> #include <set> #include "spdlog/spdlog.h" #include "cmdline/cmdline.h" #include "utils.h" #include "error.h" #include "state.h" #include "events.h" #include "vmi_helper.h" void main_loop(std::string log, int debug, std::string vmid); std::vector<std::pair<addr_t, uint16_t>> get_domains(State* s); std::vector<addr_t> get_granttable_frames(State* s, addr_t domain_ptr); std::unordered_map<addr_t, event_ptr> grant_events; event_ptr reparse_event; addr_t target_domain; SimuTrace::StreamHandle stream; int main(int argc, char** argv) { cmdline::parser parser; parser.add<int>("debug", 'd', "debug level (0-5)", false, 2, cmdline::range(0, 5)); parser.add<std::string>("log", 'l', "log file (default stdout)", false, ""); parser.add("help", 'h', "print this message"); parser.footer("VMID"); bool ok = parser.parse(argc, argv); if (!ok || parser.exist("help") || parser.rest().size() != 1) { std::cerr << parser.usage(); std::cerr << "Examples:\n./xentrace -d 4 -l /tmp/memtrace.log " "hvm_xen\n"; std::cerr << "./memtrace hvm_xen\n"; return -1; } std::cout << " _ \n" " _ __ ___ ___ _ __ ___ | |_ _ __ __ _ ___ ___\n" " | '_ ` _ \\ / _ \\ '_ ` _ \\| __| '__/ _` |/ __/ _ \\\n" " | | | | | | __/ | | | | | |_| | | (_| | (_| __/\n" " |_| |_| |_|\\___|_| |_| |_|\\__|_| \\__,_|\\___\\___|\n\n\n"; std::cout << "XEN Edition\n"; main_loop(parser.get<std::string>("log"), parser.get<int>("debug"), parser.rest()[0]); // main_loop should not return; return 1; } void close_handler(int) { state->interrupted = true; } uint16_t get_domid() { reg_t rsp, cr3; vmi_get_vcpureg(state->vmi, &rsp, SYSENTER_ESP, 0); vmi_get_vcpureg(state->vmi, &cr3, CR3, 0); const int stack_size = 4096 << 3; addr_t current = (rsp & (~(stack_size - 1))) + stack_size - 232 + 208; addr_t vcpu = vmi::read_ptr(state->vmi, cr3, current); addr_t domain = vmi::read_ptr(state->vmi, cr3, vcpu + 16); return vmi::read_word(state->vmi, cr3, domain); } void xen_trace_event(vmi_instance_t vmi, event_ptr event); void reparse_grant_table(vmi_instance_t vmi, event_ptr event) { vmi_clear_event(vmi, event); vmi_step_event(vmi, event, event->vcpu_id, 1, NULL); state->logger->debug("Grant Table Change!"); auto old_grant_events = grant_events; auto frames = get_granttable_frames(state, target_domain); std::unordered_map<addr_t, event_ptr> new_events; // Add newly added frames. for (auto f : frames) { if (old_grant_events.count(f) > 0) { new_events[f] = old_grant_events[f]; } else { try { auto ev = new_page_memevent(state, f, VMI_MEMACCESS_RWX, xen_trace_event); new_events[f] = ev; state->logger->debug("Registered page event {:x}", f); } catch (const VMIException& e) { state->logger->error("Can't register page event {:x}", f); } } } // Remove old frames. for (auto p : old_grant_events) { if (std::find(frames.begin(), frames.end(), p.first) == frames.end()) { vmi_clear_event(state->vmi, p.second); } } grant_events = new_events; } void xen_trace_event(vmi_instance_t vmi, event_ptr event) { reg_t rip, cr3; vmi_get_vcpureg(vmi, &rip, RIP, event->vcpu_id); vmi_get_vcpureg(vmi, &cr3, CR3, event->vcpu_id); uint16_t domid = get_domid(); if (domid != 0 && !(rip > 0xffff82d080000000 && rip < 0xffff82d0bfffffff)) { vmi_clear_event(vmi, event); vmi_step_event(vmi, event, event->vcpu_id, 1, NULL); auto entry = traceclient::next_entry(stream); entry->ip = 0; entry->address = 0; entry->metadata.cycleCount = state->count++; entry->metadata.fullSize = 1; entry->data.data64 = 0; traceclient::submit(stream); return; } cs_insn* instruction; try { instruction = state->get_instruction(rip, cr3); } catch (CapstoneException e) { // Disassembling of the executed instruction failed. // We don't have much choice other than returning. // TODO: Log and investigate! vmi_clear_event(vmi, event); vmi_step_event(vmi, event, event->vcpu_id, 1, NULL); return; } // The size of the memory access int size; if (instruction->detail == nullptr) { size = 4; state->logger->error("Missing instruction details!"); } else { size = instruction->detail->x86.operands[0].size; } auto entry = traceclient::next_entry(stream); entry->ip = rip; entry->address = event->mem_event.gla; entry->metadata.cycleCount = state->count++; if (size == 8) { entry->metadata.fullSize = 1; entry->data.data64 = 0; } else if (size == 4) { entry->data.size = 4 * 8; entry->data.data32 = 0; } else if (size == 2) { entry->data.size = 2 * 8; entry->data.data16 = 0; } else if (size == 1) { entry->data.size = 8; entry->data.data8 = 0; } else { state->logger->error( "Invalid address_size {} in disassembled instruction!", size); } entry->metadata.tag = (event->mem_event.out_access & VMI_MEMACCESS_W) ? 1 : 0; traceclient::submit(stream); vmi_clear_event(vmi, event); vmi_step_event(vmi, event, event->vcpu_id, 1, NULL); } void main_loop(std::string logfile, int debug, std::string vmid) { /* Set loglevel to the command line argument. If no logfile was * specified we * log to STDOUT, otherwise use a rotating_log_file*/ utils::set_loglevel(debug); auto log = utils::get_logger(debug, logfile); log->debug("Registering signal handler.."); /* Make sure signals are catched and handled safely. If we do not * deregister our vmi events correctly, the virtual machine would hang * completely when our program quits. */ utils::register_signal_handler(close_handler); log->debug("Initializing libVMI"); State s(vmid, log, true); state = &s; auto domains = get_domains(state); if (domains.size() == 1) { log->error("Only one domain running in this Xen target!"); state->interrupted = true; traceclient::close_stream(stream); return; } target_domain = domains.back().first; // Reparse the grant tables after every do_grant_op hypercall // Address of ret instruction inside do_grant_table_op; long do_grant_table_op = 0xffff82d08010f4f8; // 0xffff82d08010f487; reg_t cr3; vmi_get_vcpureg(state->vmi, &cr3, CR3, 0); auto p_grant = vmi_pagetable_lookup(state->vmi, cr3, do_grant_table_op); reparse_event = new_byte_memevent(state, p_grant, VMI_MEMACCESS_X, reparse_grant_table); stream = traceclient::create_stream(state->trace_session, "process 0"); auto frames = get_granttable_frames(state, target_domain); for (auto f : frames) { try { auto ev = new_page_memevent(state, f, VMI_MEMACCESS_RWX, xen_trace_event); grant_events[f] = ev; state->logger->debug("Registered page event {:x}", f); } catch (const VMIException& e) { state->logger->debug("Can't register page event {}", f); } } // Wait for events. status_t status = VMI_SUCCESS; while (!state->interrupted) { log->debug("Waiting for events..."); status = vmi_events_listen(state->vmi, 500); if (status != VMI_SUCCESS) { log->error("Error waiting for events! Quitting..."); state->interrupted = true; } } log->info("Leaving main_loop"); vmi_clear_event(state->vmi, reparse_event); for (auto e : grant_events) { vmi_clear_event(state->vmi, e.second); } traceclient::close_stream(stream); } std::vector<std::pair<addr_t, uint16_t>> get_domains(State* s) { std::vector<std::pair<addr_t, uint16_t>> domains; addr_t domain_list = 0xffff82d0802ce100; // Xen 4.5 Ubuntu // 0xffff82d0802d6198; // SLES XEN reg_t cr3; vmi_get_vcpureg(s->vmi, &cr3, CR3, 0); addr_t dom_ptr = vmi::read_ptr(s->vmi, cr3, domain_list); const int offset_next = 104; while (dom_ptr != 0) { uint16_t domid = vmi::read_word(s->vmi, cr3, dom_ptr); state->logger->info("Domain found: {:x} {}", dom_ptr, domid); domains.push_back(std::make_pair(dom_ptr, domid)); dom_ptr = vmi::read_ptr(s->vmi, cr3, dom_ptr + offset_next); } return domains; } struct active_grant_entry { uint32_t pin; /* Reference count information. */ uint16_t domid; /* Domain being granted access. */ struct domain* trans_domain; uint32_t trans_gref; unsigned long frame; /* Frame being granted. */ unsigned long gfn; /* Guest's idea of the frame being granted. */ unsigned is_sub_page : 1; /* True if this is a sub-page grant. */ unsigned start : 15; /* For sub-page grants, the start offset in the page. */ unsigned length : 16; /* For sub-page grants, the length of the grant. */ }; addr_t get_entry_addr(State* s, addr_t cr3, addr_t active_table, int offset) { auto active = active_table; const int per_page = 4096 / sizeof(active_grant_entry); auto column_addr = active + (offset / per_page) * 8; auto column = vmi::read_ptr(s->vmi, cr3, column_addr); return column + ((offset % per_page) * sizeof(active_grant_entry)); } std::vector<addr_t> get_granttable_frames(State* s, addr_t domain_ptr) { std::vector<addr_t> frames; const int grant_table_offset = 200; reg_t cr3; vmi_get_vcpureg(state->vmi, &cr3, CR3, 0); auto grant_table = vmi::read_ptr(s->vmi, cr3, domain_ptr + grant_table_offset); auto nr_grant_frames = vmi::read_dword(s->vmi, cr3, grant_table); auto active_grant_ptr = vmi::read_ptr(s->vmi, cr3, grant_table + 32); auto version = vmi::read_dword(s->vmi, cr3, grant_table + 60); auto grant_entries = (nr_grant_frames << 12) / 16; if (version == 1) { grant_entries *= 2; } state->logger->debug("Number of Grant Entries: {:d} {:x} {}", grant_entries, active_grant_ptr, version); for (uint i = 0; i < grant_entries; i++) { addr_t active_grant = get_entry_addr(s, cr3, active_grant_ptr, i); auto frame = vmi::read_ptr(s->vmi, cr3, active_grant + 24); auto pin = vmi::read_dword(s->vmi, cr3, active_grant); if (!pin) { continue; } if (frame != 0) { frames.push_back(frame * 4096); } } return frames; }
32.456395
80
0.593372
chonghw
d8f21da4c84a6dd612f22d65ae1c51b36ddcde88
345
hpp
C++
libs/dkutil/include/dkutil_cli_misc.hpp
Goreli/DKCPPDEV
9436183d8b92fe62f32c3d227fa044c429724129
[ "MIT" ]
1
2019-10-27T13:26:55.000Z
2019-10-27T13:26:55.000Z
libs/dkutil/include/dkutil_cli_misc.hpp
Goreli/DKCPPDEV
9436183d8b92fe62f32c3d227fa044c429724129
[ "MIT" ]
null
null
null
libs/dkutil/include/dkutil_cli_misc.hpp
Goreli/DKCPPDEV
9436183d8b92fe62f32c3d227fa044c429724129
[ "MIT" ]
null
null
null
/* dkutil_cli_misc.hpp Declares miscellaneous CLI routines. Copyright(c) 2019 David Krikheli Modification history: 10/May/2020 - David Krikheli created the module. */ #ifndef dkutil_cli_misc_hpp #define dkutil_cli_misc_hpp namespace dk { void forceThousandsSeparators(std::ostream& os); }; // namespace dk #endif // dkutil_cli_misc_hpp
20.294118
52
0.782609
Goreli
2b05a4e19bc257b76b62efd11e94c950102aa0b7
752
cpp
C++
csgocheat/menu/framework/c_text.cpp
garryhvh420/e_xyz
668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9
[ "Apache-2.0" ]
4
2020-08-13T11:11:31.000Z
2021-09-24T16:55:42.000Z
csgocheat/menu/framework/c_text.cpp
garryhvh420/e_xyz
668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9
[ "Apache-2.0" ]
null
null
null
csgocheat/menu/framework/c_text.cpp
garryhvh420/e_xyz
668d8c8c2b7ccfc3bae9e321b1a50379a5e33ec9
[ "Apache-2.0" ]
6
2020-07-15T17:00:14.000Z
2022-03-25T07:45:13.000Z
#include "c_text.h" #include "../../hooks/idirect3ddevice9.h" c_text::c_text(const std::pair<std::string, char> text, const c_color color, const uint32_t font, const uint8_t flags, const bool centered) : c_drawable(c_vector2d()), text(text), color(color), font(font), flags(flags), centered(centered) { _rt(txt, text); size = renderer->get_text_size(txt, font); } void c_text::draw(const c_vector2d position) { _rt(txt, text); if (centered) renderer->text(position + c_vector2d(size.x / 2.f, 0), txt, color, font, flags); else renderer->text(position, txt, color, font, flags); } void c_text::set_text(const std::pair<std::string, char> text) { this->text = text; } void c_text::set_color(const c_color color) { this->color = color; }
25.066667
141
0.702128
garryhvh420
2b06f4bbfb0a0e3b6618de85ead334359ba0504a
134
cpp
C++
GameIntegration/Random.cpp
AdiBaby/NetworkingGame
31b3ec1acd3711bdb43c609a74076e0650dea642
[ "FSFAP" ]
null
null
null
GameIntegration/Random.cpp
AdiBaby/NetworkingGame
31b3ec1acd3711bdb43c609a74076e0650dea642
[ "FSFAP" ]
null
null
null
GameIntegration/Random.cpp
AdiBaby/NetworkingGame
31b3ec1acd3711bdb43c609a74076e0650dea642
[ "FSFAP" ]
null
null
null
#include "Random.h" #include <chrono> std::mt19937 Random::generator(std::chrono::system_clock::now().time_since_epoch().count());
33.5
92
0.723881
AdiBaby
2b09d138df8e2662826497db9ec577feb8a0ad54
13,131
cpp
C++
GCS_UTM.cpp
ClaudioLelis/UTM_TestBed
fee8d42cf481125f944ea5f70b31a13ec29fa378
[ "MIT" ]
null
null
null
GCS_UTM.cpp
ClaudioLelis/UTM_TestBed
fee8d42cf481125f944ea5f70b31a13ec29fa378
[ "MIT" ]
null
null
null
GCS_UTM.cpp
ClaudioLelis/UTM_TestBed
fee8d42cf481125f944ea5f70b31a13ec29fa378
[ "MIT" ]
1
2021-09-03T21:33:52.000Z
2021-09-03T21:33:52.000Z
#include "GCS_UTM.h" void GCS_UTM::updateSlots() { for (auto company : CompanyList) { for (auto const& [key, uav] : company->UAV_MAP) { //Update UAV Data Coord uavGridPos = geoToGrid(Geo( uav->lat, uav->lon), gconf); int r = round(uavGridPos.r); int c = round(uavGridPos.c); if (c >= 0 && r >= 0 && c < gconf.gridSize && r < gconf.gridSize) { if (uav->cell != AirspaceSlots[r][c]) { //uav->cell->remofromOnCell(uav); if (uav->cell != nullptr) { for (int i = 0; i < uav->cell->onCellList.size(); i++) { if (uav->cell->onCellList[i]->cod == uav->cod) { uav->cell->onCellList.erase(uav->cell->onCellList.begin() + i); break; } } } uav->cell = AirspaceSlots[r][c]; if (AirspaceSlots[r][c]->onCellList.size() != 0) { AirspaceSlots[r][c]->conflictsCount++; } AirspaceSlots[r][c]->onCellList.push_back(uav); } } } } } void GCS_UTM::checkSystems() { for (auto company : CompanyList) { for (auto system : company->mavsdk->systems()) { int sysId = system->get_system_id(); if (company->UAV_MAP.find(sysId) == company->UAV_MAP.end()) { UAV_MAV* uav = new UAV_MAV(); company->UAV_MAP[sysId] = uav; uav->system = system; uav->SysId = sysId; uav->company = company->cod; uav->cod = "c" + std::to_string(company->cod) + "-n" + std::to_string(sysId); uav->telemetry = new Telemetry{ uav->system }; uav->action = new Action{ uav->system }; uav->missionManager = new Mission{ uav->system }; uav->telemetry->set_rate_position_async(5.0, [](Telemetry::Result result) {}); uav->telemetry->set_rate_velocity_ned_async(5.0, [](Telemetry::Result result) {}); // uav->telemetry->set_rate_ar(1.0, [](Telemetry::Result result) {}); //uav->telemetry->set_rate_(5.0); //UAVMap[sysId]->telemetry->set_rate_scaled_imu(50.0); uav->telemetry->subscribe_position([uav](Telemetry::Position position) { uav->lat = position.latitude_deg; uav->lon = position.longitude_deg; }); uav->telemetry->subscribe_armed([uav](bool isArmed) { uav->isArmed = isArmed; }); uav->telemetry->subscribe_in_air([uav](bool inAir) { uav->inAir = inAir; }); uav->telemetry->subscribe_velocity_ned([uav](Telemetry::VelocityNed velNed) { uav->hdg = atan2(velNed.east_m_s, velNed.north_m_s) * 180.0 / 3.1416; }); uav->missionManager->subscribe_mission_progress([uav](Mission::MissionProgress progress) { uav->missionProgress = (double)progress.current / (double)progress.total; /*if (progress.current == progress.total) { uav->onMission = false; uav->finishedMission = false; uav->onHold = false; }*/ }); /* uav->telemetry->subscribe_status_text([uav](Telemetry::StatusText text) { //uav->statusText = text; std::cout << "\n" << text; });*/ } } } } void GCS_UTM::prepareSim(std::string type) { if (type == "delivery") { for (auto company : CompanyList) { for (auto const [key, uav] : company->UAV_MAP) { ActionData actArm{ "arm" }; uav->addTask(actArm); ActionData actTakeOff{ "takeOff" }; actTakeOff.alt = 2.5f ; uav->addTask(actTakeOff); //ActionData actFlyTo{ "flyTo", company->geoPos.lat, company->geoPos.lon, 30.0f, hdgFromPath(Geo(uav->lat, uav->lon), company->geoPos) }; //uav->addTask(actFlyTo); //uav->createMission("flyto", company->geoPos.lat, company->geoPos.lon); // ActionData actMissionUpload{ "missionUpload" }; //uav->addTask(actMissionUpload); //ActionData actMissionStart{ "missionStart" }; //uav->addTask(actMissionStart); } } } } void GCS_UTM::runTests(std::string test) { if (test == "Test1") { double testRunTime = getSimTime() - testStart; if (runningTest) { if (testRunTime >= 10) { if ((testFase + 2) * 5 < testRunTime && testFase <= testTotal) { testFase++; std::cout << "\nTestRunning::Fase::" << testFase; for (auto company : CompanyList) { for (auto const [key, uav] : company->UAV_MAP) { if (testFase % 2 == 0) { //Geo geo = gridToGeo(Coord(rand() % 20, rand() % 20), gconf); //uav->createMission("flyTo", geo.lat, geo.lon, 0.01); // ActionData actMissionUpload{ "flyTo", geo.lat, geo.lon,488+30,rand()% 360}; //uav->addTask(actMissionUpload); // ActionData actMissionStart{ "missionStart" }; // uav->addTask(actMissionStart); // uav->onMission = true; uav->createMission("random", 0, 0, 0.01); ActionData actMissionUpload{ "missionUpload" }; uav->addTask(actMissionUpload); } else { uav->createMission("random", 0, 0, 0.01); ActionData actMissionUpload{ "missionUpload" }; uav->addTask(actMissionUpload); // ActionData actMissionStart{ "missionStart" }; // uav->addTask(actMissionStart); // uav->onMission = true; } } } } } } else { testRunning == test; testStart = getSimTime(); testFase = 0; testTotal = 20; std::cout << "\nTESTE01::Started"; prepareSim("delivery"); runningTest = true; } if (testFase >= testTotal) { testRunning = "Finalizing..."; if (testRunTime > (testTotal + 2 ) * 5 + 15) { testRunning = "None"; runningTest = false; std::cout << "\nTESTE01::Finished(" << getSimTime() - testStart << ")"; testStart = 0; } } } } void GCS_UTM::generateStats(std::string file) { std::ofstream myfile; myfile.open(file, std::ios_base::app); myfile << "\n\ncod; company; actionRequests; actionSuccess; missionRequests; missionsSuccess; busy; cancel; timeouts\n"; for (auto company : CompanyList) { for (auto const [key, uav] : company->UAV_MAP) { int actionReq = 0; int actionOk = 0; int missionReq = 0; int missionOk = 0; int missionBusy = 0; int missionCancel = 0; int timeOuts = 0; for (auto const [key, res] : uav->actionsCounter) actionReq = actionReq + res; actionOk = uav->resultsCounter[Action::Result::Success]; if (uav->resultsCounter.find(Action::Result::Timeout) != uav->resultsCounter.end()) { timeOuts += uav->resultsCounter[Action::Result::Timeout]; } for (auto const [key, res] : uav->missionEventsCounter) missionReq = missionReq + res; missionOk = uav->resultsCounterMission[Mission::Result::Success]; if (uav->resultsCounterMission.find(Mission::Result::TransferCancelled) != uav->resultsCounterMission.end()) { missionCancel = uav->resultsCounterMission[Mission::Result::TransferCancelled]; } if (uav->resultsCounterMission.find(Mission::Result::Busy) != uav->resultsCounterMission.end()) { missionBusy = uav->resultsCounterMission[Mission::Result::Busy]; } if (uav->resultsCounterMission.find(Mission::Result::Timeout) != uav->resultsCounterMission.end()) { timeOuts = uav->resultsCounterMission[Mission::Result::Timeout]; } //myfile << "cod; company; actionRequests; actionSuccess; missionRequests; missionsSuccess, timeouts\n"; myfile << uav->cod << ";" << company->cod << ";"; myfile << actionReq << ";" << actionOk << ";"; myfile << missionReq << ";" << missionOk << ";"; myfile << missionBusy << ";" << missionCancel << ";"; myfile << timeOuts << "\n"; } } myfile.close(); } GCS_UTM::GCS_UTM(GridConfig gconf) : gconf(gconf) { //Load Config from config.json FILE* pFile = fopen("config.json", "r"); char buffer[65536]; FileReadStream is(pFile, buffer, sizeof(buffer)); Document config; config.ParseStream(is);// <0, UTF8<>, FileReadStream>(is); gridView = config["gridview"].GetInt(); const Value& companies = config["companies"]; //Define the companies positions //std::vector<Coord> companiesCoord = { {2,2}, {19,3}, {15,18} }; //Create de MAVSDk for the companies for (SizeType i = 0; i < companies.Size(); i++) // Uses SizeType instead of size_t { Mavsdk* mavsdk = new Mavsdk(); mavsdk->set_timeout_s(companies[i]["timeout"].GetInt()); ConnectionResult connection_result = mavsdk->add_any_connection("udp://0.0.0.0:" + std::to_string(companies[i]["port"].GetInt())); mavsdk->subscribe_on_new_system([&mavsdk]() {}); Company* aux_company = new Company(); aux_company->mavsdk = mavsdk; aux_company->cod = companies[i]["cod"].GetInt(); aux_company->cellPos = Coord(companies[i]["location"][0].GetFloat(), companies[i]["location"][1].GetFloat() ); aux_company->geoPos = gridToGeo(aux_company->cellPos, gconf); CompanyList.push_back(aux_company); std::cout << "Connection result: " << connection_result << '\n'; } for (int r = 0; r < gconf.gridSize; r++) { std::vector<Cell*> row; for (int c = 0; c < gconf.gridSize; c++) { Cell* cell = new Cell(); cell->r = r; cell->c = c; row.push_back(cell); for (int i = 0; i < numCompanies; i++) { if (CompanyList[i]->cellPos.c == c && CompanyList[i]->cellPos.r == r) { cell->company = i + 1 ; } } } AirspaceSlots.push_back(row); } startTime = std::clock(); } double GCS_UTM::getSimTime() { return (std::clock() - startTime) / (double)CLOCKS_PER_SEC; } double GCS_UTM::diffTime(double timeIni, double timeCur) { return (timeCur - timeIni); } void GCS_UTM::resetTime() { startTime = std::clock(); return; }
35.975342
153
0.444749
ClaudioLelis
2b0dde5ff26e2c98a3c8f43e4c6b32770d9fb5d4
7,233
cpp
C++
test/planner/plan_node_test.cpp
AndiLynn/terrier
6002f8a902d3d0d19bc67998514098f8b41ca264
[ "MIT" ]
null
null
null
test/planner/plan_node_test.cpp
AndiLynn/terrier
6002f8a902d3d0d19bc67998514098f8b41ca264
[ "MIT" ]
5
2019-04-08T20:47:46.000Z
2019-04-24T22:11:28.000Z
test/planner/plan_node_test.cpp
AndiLynn/terrier
6002f8a902d3d0d19bc67998514098f8b41ca264
[ "MIT" ]
1
2021-10-08T01:22:25.000Z
2021-10-08T01:22:25.000Z
#include <memory> #include <random> #include <string> #include <utility> #include <vector> #include "parser/expression/comparison_expression.h" #include "parser/expression/star_expression.h" #include "parser/expression/tuple_value_expression.h" #include "parser/postgresparser.h" #include "planner/plannodes/create_database_plan_node.h" #include "planner/plannodes/drop_database_plan_node.h" #include "planner/plannodes/hash_join_plan_node.h" #include "planner/plannodes/hash_plan_node.h" #include "planner/plannodes/seq_scan_plan_node.h" #include "util/test_harness.h" namespace terrier::planner { class PlanNodeTest : public TerrierTest { public: static std::shared_ptr<OutputSchema> BuildOneColumnSchema(std::string name, const type::TypeId type, const bool nullable, const catalog::col_oid_t oid) { OutputSchema::Column col(std::move(name), type, nullable, oid); std::vector<OutputSchema::Column> cols; cols.push_back(col); auto schema = std::make_shared<OutputSchema>(cols); return schema; } }; // NOLINTNEXTLINE TEST(PlanNodeTest, CreateDatabasePlanTest) { parser::PostgresParser pgparser; auto stms = pgparser.BuildParseTree("CREATE DATABASE test"); EXPECT_EQ(1, stms.size()); auto *create_stmt = static_cast<parser::CreateStatement *>(stms[0].get()); CreateDatabasePlanNode::Builder builder; auto plan = builder.SetFromCreateStatement(create_stmt).Build(); EXPECT_TRUE(plan != nullptr); EXPECT_STREQ("test", plan->GetDatabaseName().c_str()); EXPECT_EQ(PlanNodeType::CREATE_DATABASE, plan->GetPlanNodeType()); } // NOLINTNEXTLINE TEST(PlanNodeTest, DropDatabasePlanTest) { parser::PostgresParser pgparser; auto stms = pgparser.BuildParseTree("DROP DATABASE test"); EXPECT_EQ(1, stms.size()); auto *drop_stmt = static_cast<parser::DropStatement *>(stms[0].get()); DropDatabasePlanNode::Builder builder; auto plan = builder.SetDatabaseOid(catalog::db_oid_t(0)).SetFromDropStatement(drop_stmt).Build(); EXPECT_TRUE(plan != nullptr); EXPECT_EQ(catalog::db_oid_t(0), plan->GetDatabaseOid()); EXPECT_FALSE(plan->IsIfExists()); EXPECT_EQ(PlanNodeType::DROP_DATABASE, plan->GetPlanNodeType()); } // NOLINTNEXTLINE TEST(PlanNodeTest, DropDatabasePlanIfExistsTest) { parser::PostgresParser pgparser; auto stms = pgparser.BuildParseTree("DROP DATABASE IF EXISTS test"); EXPECT_EQ(1, stms.size()); auto *drop_stmt = static_cast<parser::DropStatement *>(stms[0].get()); DropDatabasePlanNode::Builder builder; auto plan = builder.SetDatabaseOid(catalog::db_oid_t(0)).SetFromDropStatement(drop_stmt).Build(); EXPECT_TRUE(plan != nullptr); EXPECT_EQ(catalog::db_oid_t(0), plan->GetDatabaseOid()); EXPECT_TRUE(plan->IsIfExists()); EXPECT_EQ(PlanNodeType::DROP_DATABASE, plan->GetPlanNodeType()); } // Test creation of simple two table join. // We construct the plan for the following query: SELECT table1.col1 FROM table1, table2 WHERE table1.col1 = // table2.col2; NOLINTNEXTLINE TEST(PlanNodeTest, HashJoinPlanTest) { SeqScanPlanNode::Builder seq_scan_builder; HashPlanNode::Builder hash_builder; HashJoinPlanNode::Builder hash_join_builder; // Build left scan auto seq_scan_1 = seq_scan_builder .SetOutputSchema(PlanNodeTest::BuildOneColumnSchema("col1", type::TypeId::INTEGER, false, catalog::col_oid_t(1))) .SetTableOid(catalog::table_oid_t(1)) .SetDatabaseOid(catalog::db_oid_t(0)) .SetScanPredicate(std::make_shared<parser::StarExpression>()) .SetIsForUpdateFlag(false) .SetIsParallelFlag(true) .Build(); EXPECT_EQ(PlanNodeType::SEQSCAN, seq_scan_1->GetPlanNodeType()); EXPECT_EQ(0, seq_scan_1->GetChildrenSize()); EXPECT_EQ(catalog::table_oid_t(1), seq_scan_1->GetTableOid()); EXPECT_EQ(catalog::db_oid_t(0), seq_scan_1->GetDatabaseOid()); EXPECT_EQ(parser::ExpressionType::STAR, seq_scan_1->GetScanPredicate()->GetExpressionType()); EXPECT_FALSE(seq_scan_1->IsForUpdate()); EXPECT_TRUE(seq_scan_1->IsParallel()); auto seq_scan_2 = seq_scan_builder .SetOutputSchema(PlanNodeTest::BuildOneColumnSchema("col2", type::TypeId::INTEGER, false, catalog::col_oid_t(2))) .SetTableOid(catalog::table_oid_t(2)) .SetDatabaseOid(catalog::db_oid_t(0)) .SetScanPredicate(std::make_shared<parser::StarExpression>()) .SetIsForUpdateFlag(false) .SetIsParallelFlag(true) .Build(); EXPECT_EQ(PlanNodeType::SEQSCAN, seq_scan_2->GetPlanNodeType()); EXPECT_EQ(0, seq_scan_2->GetChildrenSize()); EXPECT_EQ(catalog::table_oid_t(2), seq_scan_2->GetTableOid()); EXPECT_EQ(catalog::db_oid_t(0), seq_scan_2->GetDatabaseOid()); EXPECT_EQ(parser::ExpressionType::STAR, seq_scan_2->GetScanPredicate()->GetExpressionType()); EXPECT_FALSE(seq_scan_2->IsForUpdate()); EXPECT_TRUE(seq_scan_2->IsParallel()); auto hash_plan = hash_builder .SetOutputSchema(PlanNodeTest::BuildOneColumnSchema("col2", type::TypeId::INTEGER, false, catalog::col_oid_t(2))) .AddHashKey(std::make_shared<parser::TupleValueExpression>("col2", "table2")) .AddChild(std::move(seq_scan_2)) .Build(); EXPECT_EQ(PlanNodeType::HASH, hash_plan->GetPlanNodeType()); EXPECT_EQ(1, hash_plan->GetChildrenSize()); EXPECT_EQ(1, hash_plan->GetHashKeys().size()); EXPECT_EQ(parser::ExpressionType::VALUE_TUPLE, hash_plan->GetHashKeys()[0]->GetExpressionType()); std::vector<std::shared_ptr<parser::AbstractExpression>> expr_children; expr_children.push_back(std::make_shared<parser::TupleValueExpression>("col1", "table1")); expr_children.push_back(std::make_shared<parser::TupleValueExpression>("col2", "table2")); auto cmp_expression = std::make_shared<parser::ComparisonExpression>(parser::ExpressionType::COMPARE_EQUAL, std::move(expr_children)); auto hash_join_plan = hash_join_builder.SetJoinType(LogicalJoinType::INNER) .SetOutputSchema(PlanNodeTest::BuildOneColumnSchema("col1", type::TypeId::INTEGER, false, catalog::col_oid_t(1))) .SetJoinPredicate(std::move(cmp_expression)) .AddChild(std::move(seq_scan_1)) .AddChild(std::move(hash_plan)) .Build(); EXPECT_EQ(PlanNodeType::HASHJOIN, hash_join_plan->GetPlanNodeType()); EXPECT_EQ(2, hash_join_plan->GetChildrenSize()); EXPECT_EQ(LogicalJoinType::INNER, hash_join_plan->GetLogicalJoinType()); EXPECT_EQ(parser::ExpressionType::COMPARE_EQUAL, hash_join_plan->GetJoinPredicate()->GetExpressionType()); } } // namespace terrier::planner
46.365385
118
0.671644
AndiLynn
2b0e4b24d3a6ca701c0c5a056bd29ad0f28a6991
981
hpp
C++
VMIGameEngine/include/VMIGame/Keyboard.hpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
VMIGameEngine/include/VMIGame/Keyboard.hpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
VMIGameEngine/include/VMIGame/Keyboard.hpp
bakerjm24450/EE142
71ac007fe6850ced5b57336edfd9ddbae37f28c3
[ "MIT" ]
null
null
null
#pragma once #ifndef VMI_GAME_KEYBOARD_H #define VMI_GAME_KEYBOARD_H namespace vmi { // Define the keycodes. Note that we're just // copying the definition from SFML so that we can // simply pass the keycode on to the SFML function. enum class Key { Unknown = -1, A = 0, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Escape, LControl, LShift, LAlt, LSystem, RControl, RShift, RAlt, RSystem, Menu, LBracket, RBracket, SemiColon, Comma, Period, Quote, Slash, BackSlash, Tilde, Equal, Dash, Space, Return, BackSpace, Tab, PageUp, PageDown, End, Home, Insert, Delete, Add, Subtract, Multiply, Divide, Left, Right, Up, Down, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15, Pause, KeyCount }; } // namespace vmi #endif
23.357143
52
0.643221
bakerjm24450
2b13351b82d798a74f23709e50aea49f8087165f
1,756
cpp
C++
src/game/GameState.cpp
ciscprocess/pe-econ-sim
0d33507a451aace0d8157b45c29bfc582e6b3c18
[ "Apache-2.0" ]
null
null
null
src/game/GameState.cpp
ciscprocess/pe-econ-sim
0d33507a451aace0d8157b45c29bfc582e6b3c18
[ "Apache-2.0" ]
5
2015-07-14T02:30:37.000Z
2015-07-26T22:11:28.000Z
src/game/GameState.cpp
ciscprocess/pe-econ-sim
0d33507a451aace0d8157b45c29bfc582e6b3c18
[ "Apache-2.0" ]
null
null
null
// // Created by Nathan on 7/10/2015. // #include <numeric/Random.h> #include "game/GameState.h" namespace undocked { namespace game { using world::CellularBoard; extern numeric::Random random; void GameState::tick() { for (std::map<void*, GameActionQueue>::iterator i = actions.begin(); i != actions.end(); i++) { GameActionQueue& action = i->second; if (!action.tick(this)) { actions.erase(i--); if (actions.size() < 1) break; } } for (auto i = units.begin(); i != units.end(); i++) { auto unit = *i; unit->tick(); auto chance = unit->deathChance(); auto roll = random.get(); if (chance > roll) { units.erase(i--); if (units.size() < 1) break; } } } GameState::GameState(int width, int height, GameStateSeeder &seeder) { board = new CellularBoard(width, height); seeder.seedTerrain(this); seeder.seedUnits(this); selectedUnit = nullptr; } void GameState::queueAction(GameAction &action, void* key) { if (actions.count(key) == 0) { actions[key] = GameActionQueue(key); } GameActionQueue& queue = actions[key]; queue.add(action); } void GameState::putAction(GameAction &action, void* key) { actions[key] = GameActionQueue(key); GameActionQueue& queue = actions[key]; queue.add(action); } } }
29.762712
107
0.470387
ciscprocess
2b1385fbfc701e9357ed02fed578927d086e89de
2,431
cc
C++
src/cpu/vpred/lvp.cc
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/vpred/lvp.cc
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/vpred/lvp.cc
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
1
2020-12-15T20:53:56.000Z
2020-12-15T20:53:56.000Z
#include "cpu/vpred/lvp.hh" #include "base/intmath.hh" // #include "base/logging.hh" // #include "base/trace.hh" // #include "debug/Fetch.hh" #include "iostream" LVP::LVP(const LVPParams *params) : VPredUnit(params), lastPredictorSize(params->lastPredictorSize), lastCtrBits(params->lastCtrBits), classificationTable(lastPredictorSize, SatCounter(lastCtrBits)), valuePredictionTable(lastPredictorSize), tagTable(lastPredictorSize) { // valuePredictionTable.resize(lastPredictorSize); } bool LVP::lookup(Addr inst_addr, RegVal &value) { unsigned index = inst_addr%lastPredictorSize; uint8_t counter_val = classificationTable[index]; Addr tag=tagTable[index]; /*Gets the MSB of the count.*/ //bool prediction = counter_val >> (lastCtrBits-1); bool prediction = ((unsigned(counter_val) == (pow(2,lastCtrBits)-1)) && (tag==inst_addr>>(lastCtrBits))); if (prediction) { value = valuePredictionTable[index]; } return prediction; } float LVP::getconf(Addr inst_addr, RegVal &value) { unsigned index = inst_addr%lastPredictorSize; uint8_t counter_val = classificationTable[index]; return float(counter_val/2^lastCtrBits); // Returning prediction confidence } void LVP::updateTable(Addr inst_addr, bool isValuePredicted, bool isValueTaken, RegVal &trueValue) { unsigned index = inst_addr%lastPredictorSize; if (isValuePredicted) { if (isValueTaken) { // The Value predicted and True values are the same. classificationTable[index]++; } else { // Decrease the counter and update the value to prediction table. //classificationTable[index]--; classificationTable[index].reset(); valuePredictionTable[index] = trueValue; } } else { /*Increasing the Counter when the Predictor doesn't predict, so that it predicts in next instance.*/ if (tagTable[index]==inst_addr>>(lastCtrBits)){ classificationTable[index]++; valuePredictionTable[index] = trueValue; } else{ tagTable[index]=inst_addr>>(lastCtrBits); classificationTable[index].reset(); valuePredictionTable[index] = trueValue; } } } LVP* LVPParams::create() { return new LVP(this); }
23.152381
111
0.642123
surya00060
2b13fd65e3b42d8bdc2baed02661e2f9a49ef0a8
16,715
cpp
C++
src/utils/ofxInfiniteCanvas.cpp
radamchin/ofxNCKinect
ddfae48497e6303cd167f2972601db5cfd90eab7
[ "MIT" ]
58
2019-03-18T14:38:09.000Z
2021-08-03T19:24:07.000Z
src/utils/ofxInfiniteCanvas.cpp
radamchin/ofxNCKinect
ddfae48497e6303cd167f2972601db5cfd90eab7
[ "MIT" ]
1
2016-08-22T18:38:44.000Z
2016-08-23T09:08:40.000Z
src/utils/ofxInfiniteCanvas.cpp
radamchin/ofxNCKinect
ddfae48497e6303cd167f2972601db5cfd90eab7
[ "MIT" ]
7
2016-08-22T15:35:58.000Z
2020-02-11T17:40:31.000Z
// // ofxInfiniteCanvas.cpp // ofxInfiniteCanvas // // Created by Roy Macdonald on 27-06-15. // // #include "ofxInfiniteCanvas.h" ofMatrix4x4 ofxInfiniteCanvas::FM = ofMatrix4x4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); ofMatrix4x4 ofxInfiniteCanvas::BM = ofMatrix4x4(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); ofMatrix4x4 ofxInfiniteCanvas::LM = ofMatrix4x4( 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ); ofMatrix4x4 ofxInfiniteCanvas::RM = ofMatrix4x4( 0, 0,-1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1 ); ofMatrix4x4 ofxInfiniteCanvas::TM = ofMatrix4x4( 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1 ); ofMatrix4x4 ofxInfiniteCanvas::BoM = ofMatrix4x4( 1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 ); static const float minDifference = 0.1e-5f; static const unsigned long doubleclickTime = 300; //---------------------------------------- ofxInfiniteCanvas::ofxInfiniteCanvas(){ setLookAt(OFX2DCAM_FRONT); lastTap = 0; bMouseOverride = false; bApplyInertia =false; bDoTranslate = false; // bNotifyMouseDragged = false; // bNotifyMousePressed = false; // bNotifyMouseReleased = false; // bNotifyMouseScrolled = false; bMouseListenersEnabled = false; bDistanceSet = false; bDoScale = false; reset(); parameters.setName("ofxInfiniteCanvas"); parameters.add(bEnableMouse.set("Enable Mouse Input", false)); parameters.add(dragSensitivity.set("Drag Sensitivity", 1, 0, 3)); parameters.add(scrollSensitivity.set("Scroll Sensitivity", 10, 0, 30)); parameters.add(drag.set("Drag", 0.9, 0, 1)); parameters.add(farClip.set("Far Clip", 2000, 5000, 10000)); parameters.add(nearClip.set("Near Clip", -1000, -5000, 10000)); parameters.add(bFlipY.set("Flip Y axis", false)); bEnableMouse.addListener(this, &ofxInfiniteCanvas::enableMouseInputCB); enableMouseInput(); protectedParameters.setName("ofxInfiniteCanvasParams"); scale.setName("Scale"); protectedParameters.add(scale); translation.setName("translation"); protectedParameters.add(translation); lookAt.setName("Look At"); protectedParameters.add(lookAt); protectedParameters.add(parameters); cam.enableOrtho(); bUseOfCam = true; } //---------------------------------------- void ofxInfiniteCanvas::toggleOfCam(){ bUseOfCam ^= true; } //---------------------------------------- void ofxInfiniteCanvas::save(string path){ ofXml xml; xml.save(path); } //---------------------------------------- bool ofxInfiniteCanvas::load(string path){ ofFile f(path); if (f.exists()) { reset(); ofXml xml; xml.load(path); setLookAt(getLookAt()); return true; } return false; } //---------------------------------------- ofxInfiniteCanvas::~ofxInfiniteCanvas(){ disableMouseInput(); } //---------------------------------------- void ofxInfiniteCanvas::setOverrideMouse(bool b){ if(bMouseOverride != b){ enableMouseListeners(b); bMouseOverride = b; } } //---------------------------------------- void ofxInfiniteCanvas::reset(){ if (!viewport.isEmpty()) { translation = viewport.getCenter(); // translation = {viewport.width/2, viewport.height/2, 0.}; }else{ translation = {(ofGetWidth()/2.), (ofGetHeight()/2.), 0}; } offset = {0,0,0}; scale =1; move = {0,0,0}; bDoScale = false; bApplyInertia = false; bDoTranslate = false; } //---------------------------------------- void ofxInfiniteCanvas::begin(ofRectangle _viewport){ glm::vec3 t = glm::vec3(glm::vec4(translation.get() + offset,1.0) * orientationMatrix); viewport = _viewport; if(!bUseOfCam){ ofPushView(); ofViewport(viewport); ofSetupScreenOrtho(viewport.width, viewport.height, nearClip, farClip); ofPushMatrix(); ofRotateXDeg(orientation.x); ofRotateYDeg(orientation.y); ofTranslate(t); ofScale(scale,scale * (bFlipY?-1:1),scale); }else{ // cam.setOrientation(orientation); cam.setPosition(t.x * -1.0f, t.y * (bFlipY?-1:1), t.z * -1); cam.setScale(scale,scale * (bFlipY?-1:1),scale); cam.begin(); } } //---------------------------------------- ofxInfiniteCanvas::LookAt ofxInfiniteCanvas::getLookAt(){ return (LookAt)lookAt.get(); } //---------------------------------------- void ofxInfiniteCanvas::end(){ if(bUseOfCam){ cam.end(); }else{ ofPopMatrix(); ofPopView(); } } //---------------------------------------- void ofxInfiniteCanvas::setFarClip(float fc){ farClip = fc; } //---------------------------------------- void ofxInfiniteCanvas::setNearClip(float nc){ nearClip = nc; } //---------------------------------------- void ofxInfiniteCanvas::setDragSensitivity(float s){ dragSensitivity = s;} //---------------------------------------- void ofxInfiniteCanvas::setScrollSensitivity(float s){ scrollSensitivity = s; } //---------------------------------------- void ofxInfiniteCanvas::setLookAt(LookAt l){ bool bUpdateMatrix = false; lookAt = l; switch (l) { case OFX2DCAM_FRONT: orientationMatrix = FM; orientation={0,0,0};//.set(0); break; case OFX2DCAM_BACK: orientationMatrix = BM; orientation = {0,180,0};//.set(0,180,0); break; case OFX2DCAM_LEFT: orientationMatrix = LM; orientation = {0, 90,0};//.set(0, 90,0); break; case OFX2DCAM_RIGHT: orientationMatrix = RM; orientation = {0, -90, 0};//.set(0, -90, 0); break; case OFX2DCAM_TOP: orientationMatrix = TM; orientation = {-90, 0,0};//.set(-90, 0,0); break; case OFX2DCAM_BOTTOM: orientationMatrix = BoM; orientation = {90, 0, 0};//.set(90, 0, 0); break; default: break; } } //---------------------------------------- void ofxInfiniteCanvas::setFlipY(bool bFlipped){ bFlipY.set(bFlipped); } //---------------------------------------- void ofxInfiniteCanvas::setDrag(float drag){this->drag = drag;} //---------------------------------------- float ofxInfiniteCanvas::getDrag() const{return drag;} //---------------------------------------- void ofxInfiniteCanvas::setTranslation(glm::vec3 t){ translation = t; } //---------------------------------------- void ofxInfiniteCanvas::setScale(float s){ scale = s; } //---------------------------------------- void ofxInfiniteCanvas::setOffset(const glm::vec3& o){ offset = o; } //---------------------------------------- glm::vec3 ofxInfiniteCanvas::getOffset(){ return offset; } //---------------------------------------- void ofxInfiniteCanvas::enableMouseInputCB(bool &e){ enableMouseInput(e); } //---------------------------------------- void ofxInfiniteCanvas::enableMouseInput(bool e){ if(bMouseInputEnabled != e ){ if(e){ ofAddListener(ofEvents().update, this, &ofxInfiniteCanvas::update, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); }else{ ofRemoveListener(ofEvents().update, this, &ofxInfiniteCanvas::update, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); } if (!bMouseOverride) { enableMouseListeners(e); } bMouseInputEnabled = e; if (bEnableMouse != e) { bEnableMouse = e; } } } //---------------------------------------- void ofxInfiniteCanvas::enableMouseListeners(bool e){ if (bMouseListenersEnabled != e) { if (e) { ofAddListener(ofEvents().mouseDragged , this, &ofxInfiniteCanvas::mouseDragged, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); ofAddListener(ofEvents().mousePressed, this, &ofxInfiniteCanvas::mousePressed, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); ofAddListener(ofEvents().mouseReleased, this, &ofxInfiniteCanvas::mouseReleased, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); ofAddListener(ofEvents().mouseScrolled, this, &ofxInfiniteCanvas::mouseScrolled, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); }else{ ofRemoveListener(ofEvents().mouseDragged, this, &ofxInfiniteCanvas::mouseDragged, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); ofRemoveListener(ofEvents().mousePressed, this, &ofxInfiniteCanvas::mousePressed, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); ofRemoveListener(ofEvents().mouseReleased, this, &ofxInfiniteCanvas::mouseReleased, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); ofRemoveListener(ofEvents().mouseScrolled, this, &ofxInfiniteCanvas::mouseScrolled, bMouseOverride?OF_EVENT_ORDER_BEFORE_APP:OF_EVENT_ORDER_AFTER_APP); } bMouseListenersEnabled = e; } } //---------------------------------------- void ofxInfiniteCanvas::disableMouseInput(){ enableMouseInput(false); } //---------------------------------------- bool ofxInfiniteCanvas::getMouseInputEnabled(){ return bMouseInputEnabled; } //---------------------------------------- void ofxInfiniteCanvas::mousePressed(ofMouseEventArgs & mouse){ if(viewport.inside(mouse.x, mouse.y)){ if (bMouseInputEnabled) { prevMouse = mouse; bDoTranslate =(mouse.button == OF_MOUSE_BUTTON_LEFT); bDoScale =(mouse.button == OF_MOUSE_BUTTON_RIGHT); bApplyInertia = false; clicPoint = mouse - translation.get() - viewport.getPosition(); clicPoint /= scale; //clicPoint = screenToWorld(mouse); clicTranslation = translation.get(); clicScale = scale; } if (bMouseOverride) { // mouse.set(screenToWorld((glm::vec3)mouse));//convertir a glm // lastMousePressed = mouse; // bNotifyMousePressed = true; } // return bMouseOverride; } // return false; } //---------------------------------------- //bool void ofxInfiniteCanvas::mouseReleased(ofMouseEventArgs & mouse){ if(viewport.inside(mouse.x, mouse.y)){ if (bMouseInputEnabled) { unsigned long curTap = ofGetElapsedTimeMillis(); if(lastTap != 0 && curTap - lastTap < doubleclickTime){ reset(); return; } lastTap = curTap; bApplyInertia = true; mouseVel = mouse - prevMouse; updateMouse(); prevMouse = mouse; } if (bMouseOverride) { //mouse.set(screenToWorld((glm::vec3)mouse));//convertir a glm // lastMouseReleased = mouse; // bNotifyMouseReleased = true; } } // // return bMouseOverride; } //---------------------------------------- //bool void ofxInfiniteCanvas::mouseDragged(ofMouseEventArgs & mouse){ if(viewport.inside(mouse.x, mouse.y)){ if (bMouseInputEnabled) { mouseVel = mouse - prevMouse; bApplyInertia = false; updateMouse(); prevMouse = mouse; } if (bMouseOverride) { // mouse.set(screenToWorld((glm::vec3)mouse));//convertir a glm // lastMouseDragged = mouse; // bNotifyMouseDragged = true; } } // // return bMouseOverride; } //---------------------------------------- //bool void ofxInfiniteCanvas::mouseScrolled(ofMouseEventArgs & mouse){ if(viewport.inside(mouse.x, mouse.y)){ if (bMouseInputEnabled) { move.z = scrollSensitivity * mouse.scrollY / ofGetHeight(); bDoTranslate = false; bDoScale = true; clicPoint = glm::vec2(ofGetMouseX(), ofGetMouseY()) - translation.get()- viewport.getPosition(); clicPoint /= scale; clicScale = scale; clicTranslation = translation.get(); } if (bMouseOverride) { // mouse.set(screenToWorld((glm::vec3)mouse));//convertir a glm // lastMouseScrolled = mouse; // bNotifyMouseScrolled = true; } } // // return bMouseOverride; } //---------------------------------------- void ofxInfiniteCanvas::updateMouse(){ move = {0,0,0}; if(bDoScale){ move.z = dragSensitivity * mouseVel.y /ofGetHeight(); }else if(bDoTranslate){ move.x = mouseVel.x ; move.y = mouseVel.y; } } //---------------------------------------- void ofxInfiniteCanvas::update(ofEventArgs & args){ update(); } //---------------------------------------- void ofxInfiniteCanvas::update(){ if(bMouseInputEnabled){ if(bApplyInertia){ move *= drag; if(ABS(move.x) <= minDifference && ABS(move.y) <= minDifference && ABS(move.z) <= minDifference){ bApplyInertia = false; bDoTranslate = false; bDoScale = false; } } if(bDoTranslate){ translation += glm::vec3(move.x , move.y, 0); }else if(bDoScale){ scale += move.z + move.z*scale; translation = clicTranslation - clicPoint*(scale - clicScale); } if(!bApplyInertia){ move = {0,0,0}; } // if (bMouseOverride) { // if (bNotifyMousePressed) { // lastMousePressed.set(screenToWorld((glm::vec3)lastMousePressed)); // ofNotifyEvent(ofEvents().mousePressed, lastMousePressed); // bNotifyMousePressed = false; // } // if (bNotifyMouseReleased) { // lastMouseReleased.set(screenToWorld((glm::vec3)lastMouseReleased)); // ofNotifyEvent(ofEvents().mouseReleased, lastMouseReleased); // bNotifyMouseReleased = false; // } // if (bNotifyMouseDragged) { // lastMouseDragged.set(screenToWorld((glm::vec3)lastMouseDragged)); // ofNotifyEvent(ofEvents().mouseDragged, lastMouseDragged); // bNotifyMouseDragged = false; // } // if (bNotifyMouseScrolled) { // lastMouseScrolled.set(screenToWorld((glm::vec3)lastMouseScrolled)); // ofNotifyEvent(ofEvents().mouseScrolled, lastMouseScrolled); // bNotifyMouseScrolled = false; // } // } } } //---------------------------------------- void ofxInfiniteCanvas::drawDebug(){ string m = "translation: " + ofToString(translation) + "\n"; m += "scale: " + ofToString(scale) + "\n"; m += "clic point: " + ofToString(clicPoint) + "\n"; ofDrawBitmapString(m, 0, 20); } //---------------------------------------- glm::vec3 ofxInfiniteCanvas::screenToWorld(glm::vec3 screen){ glm::vec3 s = screen - translation.get() - offset - viewport.getPosition(); s = glm::vec3(glm::vec4(s,1.) * orientationMatrix); s /= scale; if(bFlipY)s.y*=-1; return s; } glm::vec3 ofxInfiniteCanvas::worldToScreen(glm::vec3 world){ glm::vec3 s = world * scale.get(); s = glm::vec3(glm::vec4(s,1.) * glm::inverse(orientationMatrix)); // s = s * orientationMatrix.getInverse(); s = s + translation.get() + offset + viewport.getPosition(); return s; }
36.898455
163
0.516183
radamchin
2b141b20cca6e54a940f73c3f58294c65c341742
6,533
cpp
C++
Core/commonCore.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
37
2020-12-09T20:24:36.000Z
2022-02-18T17:19:23.000Z
Core/commonCore.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
25
2020-11-25T20:37:33.000Z
2022-02-25T15:53:11.000Z
Core/commonCore.cpp
glwagner/Exasim
ee4540443435f958fa2ca78d59cbf9cff0fe69de
[ "MIT" ]
8
2020-11-30T15:34:06.000Z
2022-01-09T21:06:00.000Z
#ifndef __COMMONCORE #define __COMMONCORE #include <math.h> #include <algorithm> void faceindex2(int *in1, int *in2, int *facecon, int npf, int ncu, int npe, int nc, int f1, int f2) { int nf = f2-f1; int ndf = npf*ncu; int N = ndf*nf; for (int idx = 0; idx<N; idx++) { int i = idx%ndf; // [1, npf*ncu] int e = (idx-i)/ndf; // [1, nf] int g = i%npf; // [1, npf] int j = (i-g)/npf; // [1, ncu] int m = g + npf*(f1+e); int k1 = facecon[2*m]; int k2 = facecon[2*m+1]; int m1 = k1%npe; int m2 = k2%npe; int n1 = (k1-m1)/npe; int n2 = (k2-m2)/npe; in1[idx] = m1+j*npe+n1*npe*nc; in2[idx] = m2+j*npe+n2*npe*nc; } } void faceperm2(int *ind1, int *ind2, int *indpts, int *facecon, int *fblks, int npf, int ncu, int npe, int nc, int nbf) { int N = 0; for (int j=0; j<nbf; j++) { int f1 = fblks[3*j]-1; int f2 = fblks[3*j+1]; int nf = f2-f1; faceindex2(&ind1[N], &ind2[N], facecon, npf, ncu, npe, nc, f1, f2); indpts[j] = N; N = N + npf*ncu*nf; } indpts[nbf] = N; } void faceindex(int *in1, int *in2, int *facecon, int npf, int ncu, int npe, int nc, int f1, int f2) { int nf = f2-f1; int ndf = npf*nf; int N = ndf*ncu; for (int idx = 0; idx<N; idx++) { int i = idx%ndf; int j = (idx-i)/ndf; int m = npf*f1+i; int k1 = facecon[2*m]; int k2 = facecon[2*m+1]; int m1 = k1%npe; int m2 = k2%npe; int n1 = (k1-m1)/npe; int n2 = (k2-m2)/npe; in1[idx] = m1+j*npe+n1*npe*nc; in2[idx] = m2+j*npe+n2*npe*nc; } } void faceperm(int *ind1, int *ind2, int *indpts, int *facecon, int *fblks, int npf, int ncu, int npe, int nc, int nbf) { int N = 0; for (int j=0; j<nbf; j++) { int f1 = fblks[3*j]-1; int f2 = fblks[3*j+1]; int nf = f2-f1; int ndf = npf*nf; faceindex(&ind1[N], &ind2[N], facecon, npf, ncu, npe, nc, f1, f2); indpts[j] = N; N = N + ndf*ncu; } indpts[nbf] = N; } // void mysort(int *a, int n) // { // int b[n]; // for (int i=0; i<n; i++) // b[i] = a[i]; // std::sort(b,b+n); // for (int i=0; i<n; i++) // a[i] = b[i]; // } // // void faceperm(int *ind1, int *ind2, int *indpts, int *facecon, int *fblks, int npf, int ncu, int npe, int nc, int nbf) // { // int N = 0; // for (int j=0; j<nbf; j++) { // int f1 = fblks[3*j]-1; // int f2 = fblks[3*j+1]; // int nf = f2-f1; // int ndf = npf*nf; // int P = N+ndf*ncu; // faceindex(&ind1[N], &ind2[N], facecon, npf, ncu, npe, nc, f1, f2); // mysort(&ind1[N],ndf*ncu); // mysort(&ind2[N],ndf*ncu); // indpts[j] = N; // N = N + ndf*ncu; // } // indpts[nbf] = N; // } void faceindex1(int *in1, int *facecon, int npf, int ncu, int npe, int nc, int f1, int f2) { int nf = f2-f1; int ndf = npf*nf; int N = ndf*ncu; for (int idx = 0; idx<N; idx++) { int i = idx%ndf; int j = (idx-i)/ndf; int m = npf*f1+i; int k1 = facecon[2*m]; int m1 = k1%npe; int n1 = (k1-m1)/npe; in1[idx] = m1+j*npe+n1*npe*nc; } } void faceperm1(int *ind1, int *indpts, int *facecon, int *fblks, int npf, int ncu, int npe, int nc, int nbf) { int N = 0; for (int j=0; j<nbf; j++) { int f1 = fblks[3*j]-1; int f2 = fblks[3*j+1]; int nf = f2-f1; int ndf = npf*nf; faceindex1(&ind1[N], facecon, npf, ncu, npe, nc, f1, f2); indpts[j] = N; N = N + ndf*ncu; } indpts[nbf] = N; } void elemindex(int *ind, int npe, int nc, int ncu, int e1, int e2) { int nn = npe*(e2-e1); int N = nn*ncu; for (int idx = 0; idx<N; idx++) { int i = idx%nn; // [0, npe*ne] int j = (idx-i)/nn; // [0, ncu] int k = i%npe; // [0, npe] int e = (i-k)/npe+e1; ind[idx] = k+j*npe+e*npe*nc; } } void elemperm(int *ind, int *indpts, int *eblks, int npe, int nc, int ncu, int nbe) { int N=0; for (int j=0; j<nbe; j++) { int e1 = eblks[3*j]-1; int e2 = eblks[3*j+1]; int nn = npe*(e2-e1); elemindex(&ind[N], npe, nc, ncu, e1, e2); indpts[j] = N; N = N + nn*ncu; } indpts[nbe] = N; } template <typename T> T cpuArrayGetElementAtIndex(T *y, int n) { return y[n]; } template double cpuArrayGetElementAtIndex(double*, int); template float cpuArrayGetElementAtIndex(float*, int); template <typename T> void cpuArraySetValueAtIndex(T *y, T a, int n) { y[n] = a; } template void cpuArraySetValueAtIndex(double*, double, int); template void cpuArraySetValueAtIndex(float*, float, int); template <typename T> void cpuApplyGivensRotation(T *H, T *s, T *cs, T *sn, int i) { T temp; for (int k=0; k<i; k++) { temp = cs[k]*H[k] + sn[k]*H[k+1]; H[k+1] = -sn[k]*H[k] + cs[k]*H[k+1]; H[k] = temp; } if (H[i+1] == 0.0) { cs[i] = 1.0; sn[i] = 0.0; } else if (fabs(H[i+1]) > fabs(H[i])) { temp = H[i] / H[i+1]; sn[i] = 1.0 / sqrt( 1.0 + temp*temp ); cs[i] = temp * sn[i]; } else { temp = H[i+1] / H[i]; cs[i] = 1.0 / sqrt( 1.0 + temp*temp ); sn[i] = temp * cs[i]; } temp = cs[i]*s[i]; s[i+1] = -sn[i]*s[i]; s[i] = temp; H[i] = cs[i]*H[i] + sn[i]*H[i+1]; H[i+1] = 0.0; } template void cpuApplyGivensRotation(double*, double*, double*, double*, int); template void cpuApplyGivensRotation(float*, float*, float*, float*, int); template <typename T> void cpuBackSolve(T *y, T *H, T *s, int i, int n) { for (int j=i; j>=0; j--) y[j] = s[j]; for (int j=i; j>=0; j--) { y[j] = y[j]/H[j+n*j]; for (int k=j-1; k>=0; k--) y[k] = y[k] - H[k+n*j]*y[j]; } } template void cpuBackSolve(double*, double*, double*, int, int); template void cpuBackSolve(float*, float*, float*, int, int); #endif
27.682203
121
0.452931
glwagner
2b1434a159cfdc742584ef0c9277adf6aaebf973
316
cpp
C++
Level 1/Conditions avancees, operateurs booleens/Nombre de personnes a la fete/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
31
2018-10-30T09:54:23.000Z
2022-03-02T21:45:51.000Z
Level 1/Conditions avancees, operateurs booleens/Nombre de personnes a la fete/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
2
2016-12-24T23:39:20.000Z
2017-07-02T22:51:28.000Z
Level 1/Conditions avancees, operateurs booleens/Nombre de personnes a la fete/main.cpp
Wurlosh/France-ioi
f5fb36003cbfc56a2e7cf64ad43c4452f086f198
[ "MIT" ]
30
2018-10-25T12:28:36.000Z
2022-01-31T14:31:02.000Z
#include <iostream> using namespace std; int main() { int n,a; cin>>n; int cnt=0; int maximum=0; for(int i=0;i<2*n;++i) { cin>>a; if(a>0) cnt++; else cnt--; maximum=(maximum>cnt)?maximum:cnt; } cout<<maximum<<endl; return 0; }
15.047619
42
0.458861
Wurlosh
2b19122acf80e931a12bcd2425e74039efb3079e
2,782
cpp
C++
Core/Renderer/OpenGL/src/OGLFramebuffer.cpp
SDurand7/AVLIT-Engine
c7a8e361d91e57fb96acfc1c96a88c3b480bb256
[ "MIT" ]
null
null
null
Core/Renderer/OpenGL/src/OGLFramebuffer.cpp
SDurand7/AVLIT-Engine
c7a8e361d91e57fb96acfc1c96a88c3b480bb256
[ "MIT" ]
null
null
null
Core/Renderer/OpenGL/src/OGLFramebuffer.cpp
SDurand7/AVLIT-Engine
c7a8e361d91e57fb96acfc1c96a88c3b480bb256
[ "MIT" ]
null
null
null
#include "OGLFramebuffer.hpp" #include <random> #include <cmath> #include <Core/Base/include/Math.hpp> #include <Core/Renderer/OpenGL/include/OGLTexture.hpp> #include "bluenoise.h" namespace AVLIT { GLint OGLFramebuffer::m_defaultID = -1; OGLFramebuffer::OGLFramebuffer(GLuint textureCount) : m_textures(textureCount) { glGenFramebuffers(1, &m_fboID); } OGLFramebuffer::~OGLFramebuffer() { glDeleteRenderbuffers(1, &m_rboID); glDeleteFramebuffers(1, &m_fboID); } void OGLFramebuffer::attachTexture(const std::string &name, std::unique_ptr<OGLTexture> &&texture, GLenum attachment) { AVLIT_ASSERT(texture->textureType() == GL_TEXTURE_2D, "invalid texture type"); glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, texture->textureID(), 0); m_textures[name] = std::move(texture); GL_CHECK_ERROR(); } void OGLFramebuffer::attachRenderBuffer(GLenum format, GLenum attachment, GLsizei width, GLsizei height) { if(m_rboID == 0) { glGenRenderbuffers(1, &m_rboID); glBindRenderbuffer(GL_RENDERBUFFER, m_rboID); glRenderbufferStorage(GL_RENDERBUFFER, format, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_rboID); } else AVLIT_ERROR("the framebuffer " + std::to_string(m_fboID) + " already have a render buffer"); GL_CHECK_ERROR(); } void OGLFramebuffer::setDrawBuffers(const std::vector<GLenum> &attachments) { glDrawBuffers(attachments.size(), attachments.data()); GL_CHECK_ERROR(); } void OGLFramebuffer::setDrawBuffer(GLenum buffer) { glDrawBuffer(buffer); GL_CHECK_ERROR(); } void OGLFramebuffer::setReadBuffer(GLenum buffer) { glReadBuffer(buffer); GL_CHECK_ERROR(); } bool OGLFramebuffer::isComplete() const { return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; } void OGLFramebuffer::resizeRBO(GLenum format, GLuint width, GLuint height) { if(m_rboID != 0) { glBindRenderbuffer(GL_RENDERBUFFER, m_rboID); glRenderbufferStorage(GL_RENDERBUFFER, format, width, height); GL_CHECK_ERROR(); } } void OGLFramebuffer::setupShadowMap(uint width, uint height) { bind(); auto texture = std::make_unique<Texture>(TextureInternalFormat::DEPTH, TextureFormat::DEPTH, TextureType::TEXTURE2D, TextureDataType::FLOAT, false); texture->bind(1); texture->allocate<nullptr_t>(width, height, nullptr); texture->setParameter(GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); attachTexture("shadowMap", std::move(texture), GL_DEPTH_ATTACHMENT); setDrawBuffer(GL_NONE); setReadBuffer(GL_NONE); if(!isComplete()) AVLIT_ERROR("incomplete shadow map FBO"); } } // namespace AVLIT
33.119048
120
0.723221
SDurand7
2b22643ace63cb46c2d6a23877f2a46d29b493b6
6,285
hpp
C++
Algorithm/arcsim/adaptiveCloth/mesh.hpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
32
2016-12-13T05:49:12.000Z
2022-02-04T06:15:47.000Z
Algorithm/arcsim/adaptiveCloth/mesh.hpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
2
2019-07-30T02:01:16.000Z
2020-03-12T15:06:51.000Z
Algorithm/arcsim/adaptiveCloth/mesh.hpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
18
2017-11-16T13:37:06.000Z
2022-03-11T08:13:46.000Z
/* Copyright ©2013 The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #pragma once #include "transformation.hpp" #include "vectors.hpp" #include <utility> #include <vector> namespace arcsim { // material space (not fused at seams) struct Vert; struct Face; // world space (fused) struct Node; struct Edge; struct Sizing; // for dynamic remeshing struct Vert { int label; Vec2 u; // material space Node *node; // world space // topological data std::vector<Face*> adjf; // adjacent faces int index; // position in mesh.verts // derived material-space data that only changes with remeshing double a, m; // area, mass // remeshing data Sizing *sizing; // constructors Vert() {} explicit Vert(const Vec2 &u, int label = 0) : label(label), u(u) {} explicit Vert(const Vec3 &x, int label = 0) : label(label), u(project<2>(x)) {} }; struct Node { int label; std::vector<Vert*> verts; Vec3 y; // plastic embedding Vec3 x, x0, v; // position, old (collision-free) position, velocity bool preserve; // don't remove this node // topological data int index; // position in mesh.nodes std::vector<Edge*> adje; // adjacent edges // derived world-space data that changes every frame Vec3 n; // local normal, approximate // derived material-space data that only changes with remeshing double a, m; // area, mass // pop filter data Vec3 acceleration; Node() {} explicit Node(const Vec3 &y, const Vec3 &x, const Vec3 &v, int label = 0) : label(label), y(y), x(x), x0(x), v(v) {} explicit Node(const Vec3 &x, const Vec3 &v, int label = 0) : label(label), y(x), x(x), x0(x), v(v) {} explicit Node(const Vec3 &x, int label = 0) : label(label), y(x), x(x), x0(x), v(Vec3(0)) {} }; struct Edge { Node *n[2]; // nodes int label; // topological data Face *adjf[2]; // adjacent faces int index; // position in mesh.edges // derived world-space data that changes every frame double theta; // actual dihedral angle // derived material-space data double l; // length // plasticity data double theta_ideal, damage; // rest dihedral angle, damage parameter double reference_angle; // just to get sign of dihedral_angle() right // constructors Edge() {} explicit Edge(Node *node0, Node *node1, double theta_ideal, int label = 0) : label(label), theta_ideal(theta_ideal), damage(0), reference_angle(theta_ideal), l(0) { n[0] = node0; n[1] = node1; } explicit Edge(Node *node0, Node *node1, int label = 0) : label(label), theta_ideal(0), damage(0), reference_angle(0), l(0) { n[0] = node0; n[1] = node1; } }; struct Face { Vert* v[3]; // verts int label; // topological data Edge *adje[3]; // adjacent edges int index; // position in mesh.faces // derived world-space data that changes every frame Vec3 n; // local normal, exact // derived material-space data that only changes with remeshing double a, m; // area, mass Mat2x2 Dm, invDm; // finite element matrix // plasticity data Mat2x2 S_plastic; // plastic strain double damage; // accumulated norm of S_plastic/S_yield // constructors Face() {} explicit Face(Vert *vert0, Vert *vert1, Vert *vert2, int label = 0) : label(label), S_plastic(0), damage(0), a(0), m(0) { v[0] = vert0; v[1] = vert1; v[2] = vert2; } }; struct Mesh { std::vector<Vert*> verts; std::vector<Node*> nodes; std::vector<Edge*> edges; std::vector<Face*> faces; // These do *not* assume ownership, so no deletion on removal void add(Vert *vert); void add(Node *node); void add(Edge *edge); void add(Face *face); void remove(Vert *vert); void remove(Node *node); void remove(Edge *edge); void remove(Face *face); }; template <typename Prim> const std::vector<Prim*> &get(const Mesh &mesh); void connect(Vert *vert, Node *node); // assign vertex to node bool check_that_pointers_are_sane(const Mesh &mesh); bool check_that_contents_are_sane(const Mesh &mesh); void compute_ms_data(Mesh &mesh); // call after mesh topology changes void compute_ws_data(Mesh &mesh); // call after vert positions change Edge *get_edge(const Node *node0, const Node *node1); Vert *edge_vert(const Edge *edge, int side, int i); Vert *edge_opp_vert(const Edge *edge, int side); void update_indices(Mesh &mesh); void mark_nodes_to_preserve(Mesh &mesh); inline Vec2 derivative(double a0, double a1, double a2, const Face *face) { return face->invDm.t() * Vec2(a1 - a0, a2 - a0); } template <int n> Mat<n, 2> derivative(Vec<n> w0, Vec<n> w1, Vec<n> w2, const Face *face) { return Mat<n, 2>(w1 - w0, w2 - w0) * face->invDm; } inline Mat2x3 derivative(const Face *face) { return face->invDm.t()*Mat2x3::rows(Vec3(-1, 1, 0), Vec3(-1, 0, 1)); } void apply_transformation_onto(const Mesh& start_state, Mesh& onto, const Transformation& tr); void apply_transformation(Mesh& mesh, const Transformation& tr); void update_x0(Mesh &mesh); Mesh deep_copy(const Mesh &mesh); void delete_mesh(Mesh &mesh); }
29.78673
78
0.689578
dolphin-li
2b230c57699fdf09df76b5eb1898060440304bb2
3,413
cpp
C++
Core/MAGESLAM/Source/MageUtil.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
70
2020-05-07T03:09:09.000Z
2022-02-11T01:04:54.000Z
Core/MAGESLAM/Source/MageUtil.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
3
2020-06-01T00:34:01.000Z
2020-10-08T07:43:32.000Z
Core/MAGESLAM/Source/MageUtil.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
16
2020-05-07T03:09:13.000Z
2022-03-31T15:36:49.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "MageUtil.h" #include "Utils/cv.h" #include "Utils/Logging.h" #include "Tracking/Reprojection.h" #include "Device/CameraCalibration.h" namespace mage { mage::Rect CalculateOverlapCropSourceInTarget(const mage::Matrix& targetToSourceMat, const std::shared_ptr<const mage::calibration::CameraModel>& targetModel, const std::shared_ptr<const mage::calibration::CameraModel>& sourceModel, float depthMeters) { SCOPE_TIMER(MAGESlam::CalculateOverlapCropSourceInTarget); const CameraCalibration sourceCalibration(sourceModel); const CameraCalibration targetCalibration(targetModel); const cv::Matx44f targetToSource = mage::ToCVMat4x4(targetToSourceMat); assert(targetCalibration.GetDistortionType() == calibration::DistortionType::None && "expecting a null distortion, as this function wants images that are pre-undistorted"); assert(sourceCalibration.GetDistortionType() == calibration::DistortionType::None && "expecting a null distortion, as this function wants images that are pre-undistorted"); // create points in the corners of source frame const float maxSourceCol = (float)sourceCalibration.GetCalibrationWidth() - 1; const float maxSourceRow = (float)(sourceCalibration.GetCalibrationHeight() - 1); std::array<cv::Point2f, 4> ptsSource{ { { 0, 0 },{ maxSourceCol, 0 },{ 0,maxSourceRow },{ maxSourceCol, maxSourceRow } } }; // project the 4 corners of the source into the target frame cv::Point2f minSourceInTargetPt{ std::numeric_limits<float>::max(), std::numeric_limits<float>::max() }; cv::Point2f maxSourceInTargetPt{ std::numeric_limits<float>::min(), std::numeric_limits<float>::min() }; for (const auto& sourcePt : ptsSource) { cv::Point3f posWorld = mage::UnProject(sourceCalibration.GetInverseCameraMatrix(), targetToSource, { (int)sourcePt.x, (int)sourcePt.y }, depthMeters); mage::Projection projTargetFrame = mage::ProjectUndistorted(cv::Matx34f::eye(), targetCalibration.GetCameraMatrix(), posWorld); assert(projTargetFrame.Distance > 0 && "selected depth is behind the other camera"); minSourceInTargetPt.x = std::min(minSourceInTargetPt.x, projTargetFrame.Point.x); minSourceInTargetPt.y = std::min(minSourceInTargetPt.y, projTargetFrame.Point.y); maxSourceInTargetPt.x = std::max(maxSourceInTargetPt.x, projTargetFrame.Point.x); maxSourceInTargetPt.y = std::max(maxSourceInTargetPt.y, projTargetFrame.Point.y); } assert(minSourceInTargetPt.x != std::numeric_limits<float>::max() && minSourceInTargetPt.y != std::numeric_limits<float>::max() && "no points in front of camera"); assert(maxSourceInTargetPt.x != std::numeric_limits<float>::min() && maxSourceInTargetPt.y != std::numeric_limits<float>::min() && "no points in front of camera"); float width = maxSourceInTargetPt.x - minSourceInTargetPt.x + 1; float height = maxSourceInTargetPt.y - minSourceInTargetPt.y + 1; assert(width >= 0 && "expecting a positive width for crop rect"); assert(height >= 0 && "expecting a positive height for crop rect"); return { (int)minSourceInTargetPt.x, (int)minSourceInTargetPt.y, (size_t)width, (size_t)height }; } }
59.877193
180
0.709054
syntheticmagus
1a7477a5d631d204099e7db6edafb9c8ac0f7161
5,255
cpp
C++
src/setops/ii/ii-setops.cpp
daboyuka/PIQUE
d0e2ba4cc47aaeaf364b3c76339306e1795adb5e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/setops/ii/ii-setops.cpp
daboyuka/PIQUE
d0e2ba4cc47aaeaf364b3c76339306e1795adb5e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/setops/ii/ii-setops.cpp
daboyuka/PIQUE
d0e2ba4cc47aaeaf364b3c76339306e1795adb5e
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2015 David A. Boyuka II * * 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. */ /* * ii-setops.cpp * * Created on: Mar 20, 2014 * Author: David A. Boyuka II */ #include <vector> #include <boost/smart_ptr.hpp> #include <boost/make_shared.hpp> #include "pique/region/ii/ii.hpp" #include "pique/setops/setops.hpp" #include "pique/setops/ii/ii-setops.hpp" #include "pique/util/list-setops.hpp" boost::shared_ptr< IIRegionEncoding > IISetOperations::unary_set_op_impl( boost::shared_ptr< const IIRegionEncoding > region, UnarySetOperation op) const { boost::shared_ptr< IIRegionEncoding > output = boost::make_shared< IIRegionEncoding >(); output->domain_size = region->domain_size; const std::vector<rid_t> &input_rids = region->rids; std::vector<rid_t> &output_rids = output->rids; switch (op) { case UnarySetOperation::COMPLEMENT: { rid_t next_absent_rid = 0; for (auto rid_it = input_rids.cbegin(); rid_it != input_rids.cend(); ++rid_it) { const rid_t next_present_rid = *rid_it; for (rid_t i = next_absent_rid; i < next_present_rid; i++) output_rids.push_back(i); next_absent_rid = next_present_rid + 1; } for (rid_t i = next_absent_rid; i < region->domain_size; i++) output_rids.push_back(i); break; } default: abort(); } return output; } boost::shared_ptr< IIRegionEncoding > IISetOperations::binary_set_op_impl( boost::shared_ptr< const IIRegionEncoding > left, boost::shared_ptr< const IIRegionEncoding > right, NArySetOperation op) const { assert(left->domain_size == right->domain_size); const rid_t domain_size = left->domain_size; auto left_it = left->rids.cbegin(); auto right_it = right->rids.cbegin(); auto left_it_end = left->rids.cend(); auto right_it_end = right->rids.cend(); boost::shared_ptr< IIRegionEncoding > output = boost::make_shared< IIRegionEncoding >(domain_size); std::vector<rid_t> &output_rids = output->rids; list_set_operation<decltype(left_it), decltype(right_it), decltype(output_rids), rid_t> (op, left_it, left_it_end, right_it, right_it_end, output_rids); return output; } boost::shared_ptr< IIRegionEncoding > IISetOperationsNAry::nary_set_op_impl( RegionEncodingCPtrCIter region_it, RegionEncodingCPtrCIter region_end_it, NArySetOperation op) const { // Only N-ary union implemented for now if (op != NArySetOperation::UNION) abort(); // Struct used for managing the front queue struct top_element { top_element(rid_t elem, size_t operand) : elem(elem), operand(operand) {} rid_t elem; size_t operand; }; struct top_element_compare { // This is a max heap, so the comparison must be reversed bool operator() (const top_element& lhs, const top_element&rhs) const { return lhs.elem > rhs.elem; } }; const rid_t domain_size = (*region_it)->domain_size; // Capture the operand IIs size_t num_operands = 0; std::vector< typename std::vector<rid_t>::const_iterator > rid_its; std::vector< typename std::vector<rid_t>::const_iterator > rid_end_its; for (; region_it != region_end_it; region_it++) { const IIRegionEncoding &ii = **region_it; // first * = deref iterator, second * = deref pointer to II that the iterator was holding assert(ii.domain_size == domain_size); num_operands++; rid_its.push_back(ii.rids.cbegin()); rid_end_its.push_back(ii.rids.cend()); } // Create the output II boost::shared_ptr< IIRegionEncoding > output = boost::make_shared< IIRegionEncoding >(domain_size); std::vector<rid_t> &output_rids = output->rids; // Set up the front priority queue std::priority_queue< top_element, std::vector<top_element>, top_element_compare > front_queue; for (size_t i = 0; i < num_operands; i++) if (rid_its[i] != rid_end_its[i]) front_queue.emplace(*rid_its[i]++, i); // Alternately add the lowest RID (popped from the front of front_queue) to the output II and replace // it with the next-lowest RID from the operand from which it was originally taken rid_t last_rid = front_queue.top().elem + 1; // Any value that doesn't match the first element while (front_queue.size()) { // Pop the lowest RID element const top_element &next_elem = front_queue.top(); const rid_t next_rid = next_elem.elem; const size_t fill_operand = next_elem.operand; front_queue.pop(); // Push it to the output if it is not a repeat RID if (next_rid != last_rid) output_rids.push_back(next_rid); // Record this RID so it is not repeated in the future last_rid = next_rid; // Replace it with the smallest remaining RID from the operand II // from which it was taken, if any remain if (rid_its[fill_operand] != rid_end_its[fill_operand]) front_queue.emplace(*rid_its[fill_operand]++, fill_operand); } return output; }
31.848485
133
0.72902
daboyuka
1a7560bb6d50c829230220d5225446360b3b2fdc
593
cpp
C++
ParallelForLoopBenchmark/StopWatch.cpp
shaovoon/vcpp_parallel_loops
93a45f640073cfec76b1fd8ca568470230b2e735
[ "MIT" ]
2
2018-11-19T12:54:17.000Z
2020-01-11T02:43:35.000Z
ParallelForLoopBenchmark/StopWatch.cpp
shaovoon/vcpp_parallel_loops
93a45f640073cfec76b1fd8ca568470230b2e735
[ "MIT" ]
null
null
null
ParallelForLoopBenchmark/StopWatch.cpp
shaovoon/vcpp_parallel_loops
93a45f640073cfec76b1fd8ca568470230b2e735
[ "MIT" ]
1
2020-01-11T02:43:37.000Z
2020-01-11T02:43:37.000Z
#include "StdAfx.h" #include "StopWatch.h" #define TARGET_RESOLUTION 1 // 1-millisecond target resolution StopWatch::StopWatch(void) { TIMECAPS tc; if (timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) { // Error; application can't continue. } m_wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax); timeBeginPeriod(m_wTimerRes); } StopWatch::~StopWatch(void) { timeEndPeriod(m_wTimerRes); } void StopWatch::Start() { m_nStartTime = timeGetTime(); } UINT StopWatch::Stop() { UINT endTime = timeGetTime(); return endTime - m_nStartTime; }
16.472222
73
0.715008
shaovoon
1a7569e528464edeee8ea37a226f6a88a5f8741a
16,376
hpp
C++
include/json.hpp
smbss1/FoxJson
c4aa06d8ff062ff99c1c6776f1e50b46a5266973
[ "MIT" ]
2
2021-05-25T12:26:50.000Z
2021-05-25T12:27:36.000Z
include/json.hpp
smbss1/FoxJson
c4aa06d8ff062ff99c1c6776f1e50b46a5266973
[ "MIT" ]
null
null
null
include/json.hpp
smbss1/FoxJson
c4aa06d8ff062ff99c1c6776f1e50b46a5266973
[ "MIT" ]
null
null
null
#ifndef FOX_JSON_HPP_ #define FOX_JSON_HPP_ #include <assert.h> #include <string> #include <vector> #include <unordered_map> #include <iostream> namespace fox { namespace json { enum json_type { null, object, array, string, number_integer, number_float, number_unsigned, boolean }; class Value; template <typename T> struct Serializer; template <typename T> void serialize(Value& j, const T& value); template <typename T> void deserialize(const Value& j, T& value); using Array = std::vector<Value>; using Object = std::unordered_map<std::string, Value>; class Value { private: union json_value { /// object (stored with pointer to save storage) Object* object; /// array (stored with pointer to save storage) Array* array; /// string (stored with pointer to save storage) std::string* string; /// boolean bool boolean; /// number (integer) int number_integer; // /// number (unsigned integer) unsigned number_unsigned; // /// number (floating-point) double number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans explicit json_value(bool v) noexcept : boolean(v) {} /// constructor for numbers (integer) explicit json_value(int8_t v) noexcept : number_integer(v) {} explicit json_value(int16_t v) noexcept : number_integer(v) {} explicit json_value(int32_t v) noexcept : number_integer(v) {} explicit json_value(int64_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) explicit json_value(uint8_t v) noexcept : number_unsigned(v) {} explicit json_value(uint16_t v) noexcept : number_unsigned(v) {} explicit json_value(uint32_t v) noexcept : number_unsigned(v) {} explicit json_value(uint64_t v) noexcept : number_unsigned(v) {} // /// constructor for numbers (floating-point) explicit json_value(float v) noexcept : number_float(v) {} explicit json_value(double v) noexcept : number_float(v) {} /// constructor for empty values of a given type explicit json_value(json_type t) { object = nullptr; string = nullptr; array = nullptr; switch (t) { case json_type::object: { object = new Object(); break; } case json_type::array: { array = new Array(); break; } case json_type::string: { string = new std::string(""); break; } case json_type::boolean: { boolean = false; break; } case json_type::number_integer: { number_integer = 0; break; } case json_type::number_unsigned: { number_unsigned = 0; break; } case json_type::number_float: { number_float = 0.0f; break; } case json_type::null: { break; } default: { break; } } } /// constructor for strings json_value(const std::string& value) { string = new std::string(value); } /// constructor for strings json_value(const char* value) { string = new std::string(value); } /// constructor for rvalue strings json_value(std::string&& value) { string = new std::string(std::move(value)); } /// constructor for objects json_value(const Object& value) { object = new Object(value); } /// constructor for rvalue objects json_value(Object&& value) { object = new Object(std::move(value)); } /// constructor for arrays json_value(const Array& value) { array = new Array(value); } /// constructor for rvalue arrays json_value(Array&& value) { array = new Array(std::move(value)); } }; json_type type = json_type::null; json_value value; public: ~Value(); Value() = default; Value(bool v) : value(v), type(json_type::boolean) {} Value(int8_t v) : value(v), type(json_type::number_integer) {} Value(int16_t v) : value(v), type(json_type::number_integer) {} Value(int32_t v) : value(v), type(json_type::number_integer) {} Value(int64_t v) : value(v), type(json_type::number_integer) {} Value(uint8_t v) : value(v), type(json_type::number_unsigned) {} Value(uint16_t v) : value(v), type(json_type::number_unsigned) {} Value(uint32_t v) : value(v), type(json_type::number_unsigned) {} Value(uint64_t v) : value(v), type(json_type::number_unsigned) {} Value(float v) : value(v), type(json_type::number_float) {} Value(double v) : value(v), type(json_type::number_float) {} Value(json_type t) : value(t), type(t) {} Value(const char* v) : value(v), type(json_type::string) {} Value(const std::string& v) : value(v), type(json_type::string) {} Value(std::string&& v) : value(v), type(json_type::string) {} Value(const Object& v) : value(v), type(json_type::object) {} Value(Object&& v) : value(v), type(json_type::object) {} Value(const Array& v) : value(v), type(json_type::array) {} Value(Array&& v) : value(v), type(json_type::array) {} Value(const Value& other) { switch( other.type ) { case json_type::object: value.object = new Object( other.value.object->begin(), other.value.object->end() ); break; case json_type::array: value.array = new Array( other.value.array->begin(), other.value.array->end() ); break; case json_type::string: value.string = new std::string( *other.value.string ); break; default: value = other.value; } type = other.type; } template<typename T> Value(const T& obj) { serialize(*this, obj); } void clear_internal() { switch(type) { case json_type::object: delete value.object; break; case json_type::array: delete value.array; break; case json_type::string: delete value.string; break; default: break; } // type = json_type::null; } json_type get_type() const { return type; } Value& operator=(Value&& other) { clear_internal(); value = other.value; type = other.type; other.value.object = nullptr; other.type = json_type::null; return *this; } Value& operator=(const Value& other) { clear_internal(); switch( other.type ) { case json_type::object: value.object = new Object( other.value.object->begin(), other.value.object->end() ); break; case json_type::array: value.array = new Array( other.value.array->begin(), other.value.array->end() ); break; case json_type::string: value.string = new std::string( *other.value.string ); break; default: value = other.value; } type = other.type; return *this; } // Operator Object Value& operator[](const std::string& name) { if (!is_object()) { clear_internal(); value.object = new Object(); type = json_type::object; } return (*value.object)[name]; } Value& operator[](const std::string& name) const { // const operator[] only works for objects if (is_object()) { assert(value.object->find(name) != value.object->end()); return value.object->at(name); } throw std::runtime_error("cannot use operator[] with a string argument with " + std::string(type_name())); } // Operator Array Value& operator[](std::size_t i) { if (!is_array()) { clear_internal(); value.array = new Array(); type = json_type::array; } // operator[] only works for arrays if (is_array()) { // fill up array with null values if given idx is outside range if (i >= value.array->size()) { value.array->resize(i + 1); } } return (*value.array)[i]; } Value& operator[](std::size_t i) const { if (is_array()) { return value.array->at(i); } throw std::runtime_error("cannot use operator[] with a string argument with " + std::string(type_name())); } Value& operator[](int i) { if (!is_array()) { clear_internal(); value.array = new Array(); type = json_type::array; } // operator[] only works for arrays if (is_array()) { // fill up array with null values if given idx is outside range if (i >= value.array->size()) { value.array->resize(i + 1); } } return (*value.array)[i]; } Value& operator[](int i) const { if (is_array()) { return value.array->at(i); } throw std::runtime_error("cannot use operator[] with a string argument with " + std::string(type_name())); } template<typename T> T get() const { T new_type; deserialize<T>(*this, new_type); return new_type; } bool is_null() const; bool is_boolean() const; bool is_number() const; bool is_object() const; bool is_array() const; bool is_string() const; std::string dump(std::size_t depth = 1) const; private: std::string indent(std::size_t depth) const; std::string type_name() const; }; Value parse(const std::string&); template<> std::string Value::get() const; template<> const char* Value::get() const; template<> int8_t Value::get() const; template<> int16_t Value::get() const; template<> int32_t Value::get() const; template<> int64_t Value::get() const; template<> uint8_t Value::get() const; template<> uint16_t Value::get() const; template<> uint32_t Value::get() const; template<> uint64_t Value::get() const; template<> float Value::get() const; template<> double Value::get() const; template<> bool Value::get() const; template<> Object Value::get() const; template<> Array Value::get() const; // Serialization template <typename T> void serialize(Value& j, const T& value) { Serializer<T>::serialize(j, value); } template <typename T> void deserialize(const Value& j, T& value) { Serializer<T>::deserialize(j, value); } // Serializer template <typename T> struct Serializer<std::vector<T>> { static void serialize(Value& j, const std::vector<T>& value) { std::size_t i = 0; for (auto& elem : value) { j[i] = elem; ++i; } } static void deserialize(const Value& j, std::vector<T>& value) { if (j.is_array()) { value.reserve(j.get<Array>().size()); // vector.resize() works only for default constructible types for (auto& elem : j.get<Array>()) value.push_back(elem.get<T>()); // push rvalue } } }; template <typename K, typename V> struct Serializer<std::unordered_map<K, V>> { static void serialize(Value& j, const std::unordered_map<K, V>& value) { for (auto& pair : value) { Value key = pair.first; Value value = pair.second; j[key.get<std::string>()] = value; } } static void deserialize(const Value& j, std::unordered_map<K, V>& value) { if (j.is_object()) { Object obj = j.get<Object>(); for (auto it = obj.begin(); it != obj.end(); ++it) value[it->first] = it->second.get<V>(); } } }; std::ostream& operator<<(std::ostream& os, const Value& v); } } #endif
33.082828
122
0.418234
smbss1
1a7e91735629263f7f87154abcad0e7ae29da8ff
44
hpp
C++
contracts/beoslib/beos_privileged.hpp
terradacs/beos-core
31e19170bcad573b1d498811284e62babd478f92
[ "MIT" ]
9
2019-04-04T18:46:14.000Z
2022-03-03T16:22:56.000Z
contracts/beoslib/beos_privileged.hpp
terradacs/beos-core
31e19170bcad573b1d498811284e62babd478f92
[ "MIT" ]
null
null
null
contracts/beoslib/beos_privileged.hpp
terradacs/beos-core
31e19170bcad573b1d498811284e62babd478f92
[ "MIT" ]
3
2019-03-19T17:45:08.000Z
2021-03-22T21:45:35.000Z
#pragma once #include "beos_privileged.h"
8.8
28
0.75
terradacs
1a861fcc3d51dd79c5e7554eeb735f4290c85e41
390
hpp
C++
src/version.hpp
pmenzel/kiq
61c62917abc4392d6c79540762a7941b69f69945
[ "MIT" ]
5
2018-12-11T12:12:48.000Z
2019-02-26T10:47:23.000Z
src/version.hpp
pmenzel/kiq
61c62917abc4392d6c79540762a7941b69f69945
[ "MIT" ]
1
2019-01-10T16:31:58.000Z
2019-01-11T09:43:10.000Z
src/version.hpp
pmenzel/kiq
61c62917abc4392d6c79540762a7941b69f69945
[ "MIT" ]
null
null
null
#pragma once #define KIQ_VERSION_MAJOR 0 #define KIQ_VERSION_MINOR 2 #define KIQ_VERSION_PATCH 0 #define KIQ_VERSION_SUFFIX "" #define KIQ_STR_HELPER(x) #x #define KIQ_STR(x) KIQ_STR_HELPER(x) #define KIQ_VERSION_STRING \ (KIQ_STR(KIQ_VERSION_MAJOR) "." KIQ_STR(KIQ_VERSION_MINOR) "." KIQ_STR( \ KIQ_VERSION_PATCH) KIQ_VERSION_SUFFIX)
24.375
75
0.694872
pmenzel
1a8a5c0f12a459fb6c74177405da68e35bfd3be5
4,501
cpp
C++
log/src/LogColorizer.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
17
2019-02-12T14:40:06.000Z
2021-12-21T12:54:17.000Z
log/src/LogColorizer.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
null
null
null
log/src/LogColorizer.cpp
Arthapz/StormKit
7c8dead874734d04b97776287b25bf2ebe9be617
[ "MIT" ]
2
2019-02-21T10:07:42.000Z
2020-05-08T19:49:10.000Z
// Copyright (C) 2021 Arthur LAURENT <arthur.laurent4@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level of this distribution #include <storm/log/LogColorizer.hpp> #include <storm/core/Platform.hpp> using namespace storm; using namespace storm::log; #if defined(STORMKIT_OS_WINDOWS) #include <Windows.h> [[maybe_unused]] static constexpr core::UInt8 KBLA = 0; [[maybe_unused]] static constexpr core::UInt8 KRED = 12; [[maybe_unused]] static constexpr core::UInt8 KGRN = 2; [[maybe_unused]] static constexpr core::UInt8 KYEL = 14; [[maybe_unused]] static constexpr core::UInt8 KBLU = 9; [[maybe_unused]] static constexpr core::UInt8 KMAG = 13; [[maybe_unused]] static constexpr core::UInt8 KCYN = 11; [[maybe_unused]] static constexpr core::UInt8 KWHT = 15; [[maybe_unused]] static constexpr core::UInt8 KGRS = 8; namespace storm::log { ///////////////////////////////////// ///////////////////////////////////// void colorifyBegin(Severity severity, bool to_stderr) noexcept { HANDLE handle = GetStdHandle((to_stderr) ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); core::UInt8 background = KBLA; core::UInt8 text = KWHT; switch (severity) { case Severity::Info: background = KGRN; text = KBLA; break; case Severity::Warning: background = KMAG; text = KBLA; break; case Severity::Error: background = KYEL; text = KBLA; break; case Severity::Fatal: background = KRED; text = KBLA; break; case Severity::Debug: background = KCYN; text = KBLA; break; } SetConsoleTextAttribute(handle, (background << 4) + text); } ///////////////////////////////////// ///////////////////////////////////// void colorifyEnd(bool to_stderr) noexcept { HANDLE handle = GetStdHandle((to_stderr) ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); SetConsoleTextAttribute(handle, (KBLA << 4) + KWHT); } } // namespace storm::log #elif defined(STORMKIT_OS_IOS) namespace storm::log { ///////////////////////////////////// ///////////////////////////////////// void colorifyBegin([[maybe_unused]] Severity severity, [[maybe_unused]] bool to_stderr) {} ///////////////////////////////////// ///////////////////////////////////// void colorifyBEnd([[maybe_unused]] bool to_stderr) {} } // namespace storm::log #elif defined(STORMKIT_POSIX) using std::literals::string_view_literals::operator""sv; namespace storm::log { [[maybe_unused]] static constexpr auto KNRM = "\x1B[0m"sv; [[maybe_unused]] static constexpr auto KRED = "\x1B[31m"sv; [[maybe_unused]] static constexpr auto KGRN = "\x1B[32m"sv; [[maybe_unused]] static constexpr auto KYEL = "\x1B[33m"sv; [[maybe_unused]] static constexpr auto KBLU = "\x1B[34m"sv; [[maybe_unused]] static constexpr auto KMAG = "\x1B[35m"sv; [[maybe_unused]] static constexpr auto KCYN = "\x1B[36m"sv; [[maybe_unused]] static constexpr auto KWHT = "\x1B[37m"sv; [[maybe_unused]] static constexpr auto KGRS = "\033[1m"sv; [[maybe_unused]] static constexpr auto KINV = "\e[7m"sv; [[maybe_unused]] static constexpr auto KBLCK = "\e[30m"sv; ///////////////////////////////////// ///////////////////////////////////// void colorifyBegin(Severity severity, bool to_stderr) noexcept { auto &output = (to_stderr) ? std::cerr : std::cout; switch (severity) { case Severity::Info: output << KBLCK << KINV << KGRN; break; case Severity::Warning: output << KBLCK << KINV << KMAG; break; case Severity::Error: output << KBLCK << KINV << KYEL; break; case Severity::Fatal: output << KBLCK << KINV << KRED; break; case Severity::Debug: output << KBLCK << KINV << KCYN; break; } } ///////////////////////////////////// ///////////////////////////////////// void colorifyEnd(bool to_stderr) noexcept { auto &output = (to_stderr) ? std::cerr : std::cout; output << KNRM; } } // namespace storm::log #endif
39.831858
95
0.532548
Arthapz
1a8db25027951d689fafc646dea2503f5645a35e
1,116
hpp
C++
sprig/policy/detail/is_policy_any_of_check_impl.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
2
2017-10-24T13:56:24.000Z
2018-09-28T13:21:22.000Z
sprig/policy/detail/is_policy_any_of_check_impl.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
null
null
null
sprig/policy/detail/is_policy_any_of_check_impl.hpp
bolero-MURAKAMI/Sprig
51ce4db4f4d093dee659a136f47249e4fe91fc7a
[ "BSL-1.0" ]
2
2016-04-12T03:26:06.000Z
2018-09-28T13:21:22.000Z
/*============================================================================= Copyright (c) 2010-2016 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprig Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPRIG_POLICY_DETAIL_IS_POLICY_ANY_OF_CHECK_IMPL_HPP #define SPRIG_POLICY_DETAIL_IS_POLICY_ANY_OF_CHECK_IMPL_HPP #include <sprig/config/config.hpp> #ifdef SPRIG_USING_PRAGMA_ONCE # pragma once #endif // #ifdef SPRIG_USING_PRAGMA_ONCE #include <boost/mpl/identity.hpp> #include <boost/preprocessor/punctuation/comma.hpp> #include <sprig/policy/policy_traits/is_policy_any_of.hpp> // // SPRIG_IS_POLICY_ANY_OF_CHECK_IMPL // #define SPRIG_IS_POLICY_ANY_OF_CHECK_IMPL(TAGS, TYPE, DELECTIVE) \ DELECTIVE(( \ sprig::is_policy_any_of< \ boost::mpl::identity<TAGS>::type BOOST_PP_COMMA() \ boost::mpl::identity<TYPE>::type \ > \ )) #endif // #ifndef SPRIG_POLICY_DETAIL_IS_POLICY_ANY_OF_CHECK_IMPL_HPP
33.818182
79
0.678315
bolero-MURAKAMI
1a91061e9e20d97192d6a681f4fc61e79a0c97f4
6,683
cpp
C++
src/readCSV.cpp
Fs2a/fs2a
d860ca2e6e4abd938a1ddba809b5332ccfbdfb34
[ "BSD-3-Clause" ]
null
null
null
src/readCSV.cpp
Fs2a/fs2a
d860ca2e6e4abd938a1ddba809b5332ccfbdfb34
[ "BSD-3-Clause" ]
null
null
null
src/readCSV.cpp
Fs2a/fs2a
d860ca2e6e4abd938a1ddba809b5332ccfbdfb34
[ "BSD-3-Clause" ]
null
null
null
/* BSD 3-Clause License * * Copyright (c) 2020, Fs2a, Simon de Hartog <simon@fs2a.pro> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. 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. * * vim:set ts=4 sw=4 noet tw=120: */ #include <cstdint> #include <string> #include "readCSV.h" #define ERR "Error at line "s + std::to_string(line) + ", character "s + std::to_string(pos) + ": "s namespace Fs2a { Table<std::string> readCSV(std::istream & stream_i, const char separator_i) { using namespace std::string_literals; Table<std::string> t; std::vector<std::string> h; // Header bool readingHeader = true; bool quoted = false; char c; std::string f; // Field with data uint16_t col = 0; uint32_t row = 0; size_t line = 1; size_t pos = 1; enum last_e : uint8_t { beginQuote, endQuote, fieldData, separator, startOfRecord }; last_e last = startOfRecord; auto fieldReady = [&]() { if (readingHeader) { h.push_back(f); } else { t.cell(col, row) = f; } f.clear(); }; // Disable exceptions for EOF on the stream, because we need to be able to handle EOF properly. // If something bad happens other than EOF, throw exception. stream_i.exceptions(std::istream::badbit); while (stream_i.good()) { stream_i.read(&c, 1); if (stream_i.eof()) c = EOF; else pos++; // Skip valid but unused 8-bit characters at start of CSV if (readingHeader && last == startOfRecord && col == 0 && row == 0 && c != EOF && c & 0x80) continue; // If a field is quoted, only check for EOF, escaped quotes or end quote. // Store everything else (including separators and newlines) in the field data. // Do check newlines to keep track of character position. if (quoted) { switch (c) { case EOF: throw std::runtime_error(ERR + "Encountered EOF while reading quoted field"); case '\r': if (stream_i.peek() == '\n') { f.push_back(c); // Swallow \r\n stream_i.read(&c, 1); } // Fallthrough case '\n': f.push_back(c); line++; pos = 0; last = fieldData; continue; case '"': if (stream_i.peek() == '"') { // Escaped quote stream_i.read(&c, 1); pos++; f.push_back(c); last = fieldData; } else { // End quote. The field is stored on the next separator or end of record quoted = false; last = endQuote; } continue; default: f.push_back(c); last = fieldData; continue; } } // From here on, we are not reading a quoted field, so parse normally if (c == '\r' || c == '\n' || c == EOF) { // End of record if (c == '\r' && stream_i.peek() == '\n') { // Swallow \r\n stream_i.read(&c, 1); pos++; } switch (last) { case beginQuote: throw std::runtime_error(ERR + "Found End Of Record just after begin quote"); case endQuote: case fieldData: case separator: fieldReady(); break; case startOfRecord: if (stream_i.peek() != EOF) throw std::runtime_error(ERR + "Found empty line"); else return t; } if (readingHeader) { if (h.empty()) { throw std::runtime_error(ERR + "Empty line at beginning, unable to determine number of columns"s); } // Both column adressing and count are // uint16_t, so max is UINT16_MAX - 1 if (h.size() >= UINT16_MAX) { throw std::out_of_range(ERR + "Encountered too many columns "s + std::to_string(h.size()) + ", maximum is " + std::to_string(UINT16_MAX-1)); } t.columns(static_cast<uint16_t>(h.size())); for (col = 0; col < h.size(); col++) { t.cell(col, 0) = h.at(col); } h.clear(); row = 1; col = 0; pos = 0; readingHeader = false; } else { if (col > 0 && !f.empty() && col != t.columns() - 1) { throw std::runtime_error(ERR + "Found EndOfRecord after "s + std::to_string(col+1) + " column(s), but column count should be "s + std::to_string(t.columns())); } col = 0; if (row == UINT32_MAX) { throw std::runtime_error(ERR + "Input data has more than "s + std::to_string(UINT32_MAX) + " rows"); } row++; } line++; pos = 0; last = startOfRecord; continue; } // Remember, quoted = false here if (c == '"') { switch (last) { case beginQuote: case endQuote: throw std::runtime_error(ERR + "Found quote character after quote, but not quoted field?"); case fieldData: // Include sole " in unquoted field f.push_back(c); continue; case separator: case startOfRecord: quoted = true; f.clear(); continue; } continue; } // Remember, quoted = false here if (c == separator_i) { fieldReady(); last = separator; if (!readingHeader) { if (col >= t.columns() - 1) { throw std::runtime_error(ERR + "Field count "s + std::to_string(col+1) + " would exceed column count "s + std::to_string(t.columns())); } col++; } continue; } // The default case for c: f.push_back(c); last = fieldData; } return t; } } // Fs2a namespace
28.682403
106
0.617088
Fs2a
1a92d09bc8c493a9f7a0e50fab7dfc9ab951a78e
2,229
cpp
C++
GpuMiner/XDagCore/XFee.cpp
swordlet/DaggerAOCLminer
f4fa5b5aec4942863c234463d3aeb244c472eae4
[ "MIT" ]
5
2019-03-08T11:26:35.000Z
2022-01-15T12:53:57.000Z
GpuMiner/XDagCore/XFee.cpp
swordlet/DaggerAOCLminer
f4fa5b5aec4942863c234463d3aeb244c472eae4
[ "MIT" ]
null
null
null
GpuMiner/XDagCore/XFee.cpp
swordlet/DaggerAOCLminer
f4fa5b5aec4942863c234463d3aeb244c472eae4
[ "MIT" ]
6
2019-03-07T08:46:33.000Z
2022-02-15T17:38:18.000Z
// Implementation of fee // Author: Evgeniy Sukhomlinov // 2018 // Licensed under GNU General Public License, Version 3. See the LICENSE file. #include "XFee.h" #include "Core/Log.h" #ifdef _DEBUG #define FEE_PERIOD 4 const std::string GpuDevAddress = "YMB0XWN1vxY5jLiZwSDeTDQTRO2NVEW9"; #else #define FEE_PERIOD 100 const std::string GpuDevAddress = "kllHUGcgV3lWjAcgM1o9JZreqeSshnfk"; //developer's address const std::string CommunityAddress = "FQglVQtb60vQv2DOWEUL7yh3smtj7g1s"; //community fund #endif XFee::XFee(std::string& poolAddress) { _nextAddressIndex = 0; _taskCounter = 0; _connectionIsSwitched = false; strcpy(_poolAddress, poolAddress.c_str()); #ifdef _DEBUG _addressList.push_back(GpuDevAddress); #else _addressList.push_back(GpuDevAddress); _addressList.push_back(CommunityAddress); #endif } XFee::~XFee() { Disconnect(); } bool XFee::Connect() { if(!_connection.Initialize()) { clog(XDag::LogChannel) << "Failed to initialize network connection"; return false; } return _connection.Connect(_poolAddress); } void XFee::Disconnect() { _connection.Close(); } //increases internal tasks counter and once a 100 tasks switches connection and address for mining (duration - one task) bool XFee::SwitchConnection(XPoolConnection** currentPoolConnection, XPoolConnection* basePoolConnection) { if(_connectionIsSwitched) { if(_taskCounter++ == 0) { return 0; } _taskCounter = 0; *currentPoolConnection = basePoolConnection; // do nothing _connectionIsSwitched = false; Disconnect(); return true; } if(++_taskCounter < FEE_PERIOD) { return false; } _taskCounter = 0; if(!Connect()) { return false; } _connection.SetAddress(_addressList[_nextAddressIndex]); *currentPoolConnection = &_connection; // switch connection to fee( donate to developer or community) _connectionIsSwitched = true; if(++_nextAddressIndex >= _addressList.size()) { _nextAddressIndex = 0; } return true; }
25.044944
121
0.656797
swordlet
1a93da20f884d28297c65880ee825abe5305f220
560
hpp
C++
lib/src/cpu/cpu_median.hpp
akowalew/cuda-imgproc
5d8f8b13ff94e9d914e9106cd6cdefee2ee549ff
[ "MIT" ]
null
null
null
lib/src/cpu/cpu_median.hpp
akowalew/cuda-imgproc
5d8f8b13ff94e9d914e9106cd6cdefee2ee549ff
[ "MIT" ]
null
null
null
lib/src/cpu/cpu_median.hpp
akowalew/cuda-imgproc
5d8f8b13ff94e9d914e9106cd6cdefee2ee549ff
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // cpu_median.hpp // // Contains declarations for CPU median filterer /////////////////////////////////////////////////////////////////////////////// #pragma once #include "image.hpp" // // Public declarations // void cpu_median(Image& dst, const Image& src, int ksize); /** * @brief Applies median filter to an image * @details * * @param src source image * @param ksize size of the kernel * @return filtered image */ Image cpu_median(const Image& src, int ksize);
21.538462
79
0.496429
akowalew
1a9d421505c12c352499a2a69177f61a421ccf3f
965
hpp
C++
src/Commands/RemoveDirCommand.hpp
lucastarche/HacknetPlusPlus
9221be47157da5402ea7a0cc1f769ddeb4eca5c0
[ "MIT" ]
1
2021-12-15T17:24:17.000Z
2021-12-15T17:24:17.000Z
src/Commands/RemoveDirCommand.hpp
lucastarche/HacknetPlusPlus
9221be47157da5402ea7a0cc1f769ddeb4eca5c0
[ "MIT" ]
2
2020-11-26T14:05:36.000Z
2021-02-17T23:16:28.000Z
src/Commands/RemoveDirCommand.hpp
lucastarche/HacknetPlusPlus
9221be47157da5402ea7a0cc1f769ddeb4eca5c0
[ "MIT" ]
4
2020-11-26T03:19:07.000Z
2021-02-16T21:15:01.000Z
#pragma once #include "Command.hpp" class RemoveDirCommand : public Command { public: void run(const std::vector<std::string> &args) override { if (!hasExactArguments(2, args)) return; GameManager *game = GameManager::getInstance(); FileSystemElement* elem = game->getDirectory()->getElement(args[1]); if (elem == nullptr) { std::cout << "Error: directory does not exist.\n"; } else if (elem->getType() == FileSystemType::Folder) { Folder* folder = (Folder*) elem; if (folder->listChildren().empty()) { game->getDirectory()->deleteElement(args[1]); } else { std::cout << "Error: directory is not empty.\n"; } } else { std::cout << "Error: is not a directory.\n"; } } };
33.275862
80
0.47772
lucastarche
1aa011bbb55992c21f0f6dfae0f06c10fce80157
71
hpp
C++
src/zerocopy/args.hpp
ZaidQureshi/comm_scope
a3dc1a117c30e7f453c9be5dcc68cd979bd852d8
[ "Apache-2.0" ]
12
2020-05-07T20:48:01.000Z
2021-11-24T17:57:28.000Z
src/zerocopy/args.hpp
ZaidQureshi/comm_scope
a3dc1a117c30e7f453c9be5dcc68cd979bd852d8
[ "Apache-2.0" ]
41
2018-09-03T21:18:49.000Z
2021-03-05T21:55:27.000Z
src/zerocopy/args.hpp
ZaidQureshi/comm_scope
a3dc1a117c30e7f453c9be5dcc68cd979bd852d8
[ "Apache-2.0" ]
5
2019-12-14T19:38:47.000Z
2022-02-20T12:50:24.000Z
#pragma once #define ARGS() DenseRange(10, 33, 1)->ArgName("log2(N)")
17.75
56
0.661972
ZaidQureshi
1aa644e52a3c05f7a6478536636e0d9ee02c2e2b
833
hpp
C++
include/public/coherence/lang/Runnable.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
include/public/coherence/lang/Runnable.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
include/public/coherence/lang/Runnable.hpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #ifndef COH_RUNNABLE_HPP #define COH_RUNNABLE_HPP #include "coherence/lang/compatibility.hpp" #include "coherence/lang/interface_spec.hpp" #include "coherence/lang/TypedHandle.hpp" COH_OPEN_NAMESPACE2(coherence,lang) /** * Interface implemented by any class whose instances are intended to be * executed by a thread. * * @author mf 2007.12.10 */ class COH_EXPORT Runnable : public interface_spec<Runnable> { // ----- Runnable interface --------------------------------------------- public: /** * Invoke the Runnable. */ virtual void run() = 0; }; COH_CLOSE_NAMESPACE2 #endif // COH_RUNNABLE_HPP
21.358974
77
0.654262
chpatel3
1aa81052438d8c556bd7dab6e8bb63bef581c130
2,223
cpp
C++
ql/experimental/compoundoption/compoundoption.cpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/compoundoption/compoundoption.cpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/compoundoption/compoundoption.cpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
1
2022-03-29T05:44:27.000Z
2022-03-29T05:44:27.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2009 Dimitri Reiswich This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/experimental/compoundoption/compoundoption.hpp> namespace QuantLib { CompoundOption::CompoundOption( const boost::shared_ptr<StrikedTypePayoff>& motherPayoff, const boost::shared_ptr<Exercise>& motherExercise, const boost::shared_ptr<StrikedTypePayoff>& daughterPayoff, const boost::shared_ptr<Exercise>& daughterExercise) : OneAssetOption(daughterPayoff, daughterExercise), motherOption_(new OneAssetOption(motherPayoff,motherExercise)) {} void CompoundOption::setupArguments(PricingEngine::arguments* args) const { OneAssetOption::setupArguments(args); CompoundOption::arguments* moreArgs = dynamic_cast<CompoundOption::arguments*>(args); QL_REQUIRE(moreArgs != 0, "wrong argument type"); moreArgs->motherOption= motherOption_; } void CompoundOption::arguments::validate() const { OneAssetOption::arguments::validate(); QL_REQUIRE(motherOption->payoff(), "No payoff given for mother compound option."); QL_REQUIRE(motherOption->exercise(), "No exercise given for mother compound option."); QL_REQUIRE(motherOption->exercise()->lastDate()<=exercise->lastDate(), "Maturity of mother option exceeds " "maturity of daughter option."); } }
37.677966
79
0.689159
quantosaurosProject
1aaadfec6f8daab0b0ff59a6614b1bbb1aa4186c
1,152
hpp
C++
mpskit/point_functions.hpp
f-koehler/dmrg
335250d066170e7da6f1ee80b9ec1d30e80570c5
[ "MIT" ]
null
null
null
mpskit/point_functions.hpp
f-koehler/dmrg
335250d066170e7da6f1ee80b9ec1d30e80570c5
[ "MIT" ]
null
null
null
mpskit/point_functions.hpp
f-koehler/dmrg
335250d066170e7da6f1ee80b9ec1d30e80570c5
[ "MIT" ]
null
null
null
#ifndef MPSKIT_POINT_FUNCTIONS #define MPSKIT_POINT_FUNCTIONS #include <itensor/itensor.h> #include <itensor/mps/mps.h> #include <itensor/mps/siteset.h> #include <string> #include "types.hpp" namespace itensor { class MPS; } // namespace itensor struct OnePointFunction { protected: int m_index; Real m_prefactor; Complex m_value; itensor::ITensor m_op; public: OnePointFunction(const itensor::SiteSet &sites, int index, const std::string &op, Real prefactor = 1.0); const Complex &getValue() const; int getIndex() const; const Complex &operator()(itensor::MPS &mps); }; struct TwoPointFunction { protected: int m_i; int m_j; Real m_prefactor; Complex m_value; bool m_ordered, m_same_index; itensor::ITensor m_op_i, m_op_j; public: TwoPointFunction(const itensor::SiteSet &sites, int index1, int index2, const std::string &op1, const std::string &op2, Real prefactor = 1.0); const Complex &getValue() const; int getIndex1() const; int getIndex2() const; const Complex &operator()(itensor::MPS &mps); }; #endif /* MPSKIT_POINT_FUNCTIONS */
22.588235
108
0.689236
f-koehler
1aafe7be8b7c7e50491925c56c7bf405e4865fb0
1,739
cpp
C++
Instances/Matrix_Chain.cpp
namespace-Pt/Algorithm
59f70e4b82107ae37b3a06338e8ac73be6937d3f
[ "MIT" ]
null
null
null
Instances/Matrix_Chain.cpp
namespace-Pt/Algorithm
59f70e4b82107ae37b3a06338e8ac73be6937d3f
[ "MIT" ]
null
null
null
Instances/Matrix_Chain.cpp
namespace-Pt/Algorithm
59f70e4b82107ae37b3a06338e8ac73be6937d3f
[ "MIT" ]
null
null
null
#include<iostream> #include<limits.h> using namespace std; // 备忘录法自顶向下实现动态规划 int Lookup_Chain(int **M,int ** S,int *p,int i,int j){ // 如果值不是初始化的最大值,则返回 // O(1) if(M[i][j] < INT_MAX){ return M[i][j]; } // 如果只有一个矩阵,直接返回0 // O(1) if(i == j){ return 0; } else { // 从i~j中选出一个最优的k // 最多只有n-1种情况,即子状态图中每个节点最多只有n-1条边 for(int k = i;k < j;k++){ // 计算不同k下Ai...Aj的总计算次数 int q = Lookup_Chain(M,S,p,i,k) + Lookup_Chain(M,S,p,k+1,j) + p[i-1]*p[k]*p[j]; // 如果有更优的,则直接替换备忘录中的值 // 同时更新记录划分位置的矩阵 if(q < M[i][j]){ M[i][j] = q; S[i][j] = k; } } } // 返回Ai...Aj的最优计算次数 return M[i][j]; } // 初始化矩阵,调用算法计算最优计算次数 int Memoized(int ** S,int *p,int length){ // 申请空间 int ** M = new int*[7]; for(int i = 1;i < length;i++){ // 初始化两个数组,一个保存最优值,一个保存最优划分位置 M[i] = new int[7](); S[i] = new int[7](); // 初始化为最大int for(int j = i;j < length;j++){ M[i][j] = INT_MAX; } } return Lookup_Chain(M,S,p,1,length-1); } // 用于打印最终划分 void print_optimal(int ** s,int i,int j){ if(i==j){ cout<<"A"<<i; } else { cout<<'('; // 打印前半部分最优划分 print_optimal(s,i,s[i][j]); // 打印后半部分最优划分 print_optimal(s,s[i][j]+1,j); cout<<')'; } } int main(){ // 按照ppt输入矩阵规模序列 int p[7] = {30,35,15,5,10,20,25}; int ** S = new int*[7]; cout<<"input the matrix scale sequence of LENGTH 6:"<<endl; for(int i = 0;i < 7;i++){ cin>>p[i]; } cout<<Memoized(S,p,7)<<endl; print_optimal(S,1,6); return 0; }
20.702381
91
0.454284
namespace-Pt
1abb1f5affa4d04b9cdebaa179cddf9c4fc5fba7
1,642
cpp
C++
test/unit-test/src/test-csv-001.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
test/unit-test/src/test-csv-001.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
test/unit-test/src/test-csv-001.cpp
solosTec/cyng
3862a6b7a2b536d1f00fef20700e64170772dcff
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2019 Sylko Olzscher * */ #include "test-csv-001.h" #include <iostream> #include <boost/test/unit_test.hpp> #include <cyng/csv.h> #include <cyng/object.h> #include <cyng/factory.h> #include <cyng/io/serializer.h> #include <boost/uuid/random_generator.hpp> #include <boost/filesystem.hpp> namespace cyng { bool test_csv_001() { boost::uuids::random_generator rgen; // // create a vector of tuples // const auto vec = cyng::vector_factory({ cyng::tuple_factory(rgen(), "name-1", 1), cyng::tuple_factory(rgen(), "name-2", 2), cyng::tuple_factory(rgen(), "name-3", 3), cyng::tuple_factory(rgen(), "name-4", 4), cyng::tuple_factory(rgen(), "name-5", 5) }); //std::cout << io::to_str(vec) << std::endl; auto const s1 = io::to_str(vec); // // serialize to CSV // auto const tmp = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("unit-test-%%%%-%%%%-%%%%-%%%%.csv"); const std::string file_name(tmp.string()); { //std::cout << file_name << std::endl; std::ofstream f(file_name, std::ios::binary | std::ios::trunc | std::ios::out); BOOST_CHECK(f.is_open()); csv::write(f, make_object(vec)); } // // deserialize from CSV // { auto const vec = csv::read_file(tmp.string()); //std::cout << io::to_str(r) << std::endl; auto const s2 = io::to_str(vec); // // serialized and parsed data should be equal // BOOST_CHECK_EQUAL(s1, s2); } boost::system::error_code ec; boost::filesystem::remove(tmp, ec); BOOST_CHECK_MESSAGE(!ec, "cannot delete file"); return true; } }
22.493151
130
0.626066
solosTec
1abc792b90764a91ee35efa988a490c7cbc236f6
2,269
cxx
C++
MITK/Modules/OpenCV/Features/mitkSurfTester.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Modules/OpenCV/Features/mitkSurfTester.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Modules/OpenCV/Features/mitkSurfTester.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "mitkSurfTester.h" #include <cv.h> #include <highgui.h> #include <opencv2/nonfree/features2d.hpp> namespace mitk { //----------------------------------------------------------------------------- SurfTester::SurfTester() { } //----------------------------------------------------------------------------- SurfTester::~SurfTester() { } //----------------------------------------------------------------------------- void SurfTester::RunSurf(const std::string& inputFileName, const std::string& outputFileName) { cv::Mat inputImage = cv::imread(inputFileName); cv::Mat outputImage; cv::Mat inputResize; /* cv::Mat greyImage; cv::cvtColor( inputImage, greyImage, CV_BGRA2GRAY ); cv::resize(greyImage, inputResize, cv::Size(1920, 1080), 0,0, cv::INTER_LANCZOS4); cv::cvtColor( inputResize, outputImage, CV_GRAY2BGR ); std::vector<cv::Point2f> corners; double qualityLevel = 0.01; double minDistance = 10; int blockSize = 5; bool useHarrisDetector = false; double k = 0.04; int maxCorners = 5000; /// Apply corner detection goodFeaturesToTrack(inputResize, corners, maxCorners, qualityLevel, minDistance, cv::Mat(), blockSize, useHarrisDetector, k); /// Draw corners detected std::cout<<"** Number of corners detected: " << corners.size() << std::endl; int r = 10; for( int i = 0; i < corners.size(); i++ ) { cv::circle( outputImage, corners[i], r, cv::Scalar(0, 0, 255), 1, 8, 0 ); } */ cv::SURF detector; std::vector<cv::KeyPoint> keypoints; cv::resize(inputImage, inputResize, cv::Size(1920, 1080), 0,0, cv::INTER_LANCZOS4); detector.detect(inputResize, keypoints); cv::drawKeypoints(inputResize, keypoints, outputImage); cv::imwrite(outputFileName, outputImage); } } // end namespace
28.721519
127
0.581313
NifTK
1abdc6707530839ae47867e71ec1459b8c89c32a
13,453
cpp
C++
GameServer/Source/ItemUpgradeJewels.cpp
sp3cialk/MU-S8EP2-Repack
202856a74c905c203b9b2795fd161f564ca8b257
[ "MIT" ]
10
2019-04-09T23:36:43.000Z
2022-02-10T19:20:52.000Z
GameServer/Source/ItemUpgradeJewels.cpp
microvn/mu-s8ep2-repack
202856a74c905c203b9b2795fd161f564ca8b257
[ "MIT" ]
1
2019-09-25T17:12:36.000Z
2019-09-25T17:12:36.000Z
GameServer/Source/ItemUpgradeJewels.cpp
microvn/mu-s8ep2-repack
202856a74c905c203b9b2795fd161f564ca8b257
[ "MIT" ]
9
2019-09-25T17:12:57.000Z
2021-08-18T01:21:25.000Z
#include "stdafx.h" #include "ItemUpgradeJewels.h" #include "..\pugixml\pugixml.hpp" #include "logproc.h" #include "GameMain.h" #include "..\common\SetItemOption.h" using namespace pugi; ItemUpgradeJewels g_ItemUpgradeJewels; ItemUpgradeJewels::ItemUpgradeJewels() { } ItemUpgradeJewels::~ItemUpgradeJewels() { } void ItemUpgradeJewels::Init() { this->m_UpradeInfo.clear(); if( this->m_UpradeInfo.capacity() > 0 ) { std::vector<ItemUpgradeJewelsInfo>().swap(this->m_UpradeInfo); } } void ItemUpgradeJewels::Load() { this->Init(); this->Read(gDirPath.GetNewPath(FILE_ITEM_UPGRADE_JEWELS)); } void ItemUpgradeJewels::Read(LPSTR File) { xml_document Document; xml_parse_result Result = Document.load_file(File); // ---- if( Result.status != status_ok ) { MsgBox("[ItemUpgradeJewels] File %s not found!", File); return; } // ---- xml_node ChildCommon = Document.child("itemupgradejewels"); xml_node Node; // ---- for( Node = ChildCommon.child("jewel"); Node; Node = Node.next_sibling() ) { ItemUpgradeJewelsInfo lpItem; lpItem.ItemType = Node.attribute("type").as_int((int)-1); lpItem.ItemIndex = Node.attribute("index").as_int((int)-1); lpItem.DefaultRate = Node.attribute("rate").as_uint(); lpItem.TargetLevelMin = Node.child("rules").child("level").attribute("min").as_int((BYTE)-1); lpItem.TargetLevelMax = Node.child("rules").child("level").attribute("max").as_int((BYTE)-1); lpItem.TargetRankNormal = Node.child("rules").child("rank").attribute("normal").as_int((BYTE)-1); lpItem.TargetRankExcellent = Node.child("rules").child("rank").attribute("excellent").as_int((BYTE)-1); lpItem.TargetRankAncient = Node.child("rules").child("rank").attribute("ancient").as_int((BYTE)-1); lpItem.TargetRankSocket = Node.child("rules").child("rank").attribute("socket").as_int((BYTE)-1); lpItem.m_RateChangeRules.clear(); if( lpItem.m_RateChangeRules.capacity() > 0 ) { std::vector<ItemUpgradeJewelsRateChangeInfo>().swap(lpItem.m_RateChangeRules); } xml_node RateNode; for( RateNode = Node.child("ratechange"); RateNode; RateNode = RateNode.next_sibling() ) { ItemUpgradeJewelsRateChangeInfo lpRate; lpRate.Type = RateNode.attribute("type").as_int((BYTE)-1); lpRate.Level = RateNode.attribute("level").as_int((BYTE)-1); lpRate.Option = RateNode.attribute("option").as_int((BYTE)-1); lpRate.RateIncrease = RateNode.attribute("increase").as_uint(0); lpRate.RateDecrease = RateNode.attribute("decrease").as_uint(0); lpItem.m_RateChangeRules.push_back(lpRate); } this->m_UpradeInfo.push_back(lpItem); } } void ItemUpgradeJewels::ProcInsert(LPOBJ lpUser, int JewelPos, int TargetPos) { ItemUpgradeJewelsInfo* lpJewel = NULL; for( int i = 0; i < this->m_UpradeInfo.size(); i++ ) { if( ITEMGET(this->m_UpradeInfo[i].ItemType, this->m_UpradeInfo[i].ItemIndex) == lpUser->pInventory[JewelPos].m_Type) { lpJewel = &this->m_UpradeInfo[i]; break; } } if( lpJewel == NULL ) { GCReFillSend(lpUser->m_Index, (WORD)lpUser->Life, 0xFD, 1, lpUser->iShield); return; } if( this->ProcUpgrade(lpUser, JewelPos, TargetPos, lpJewel) ) { gObjInventoryItemSet(lpUser->m_Index, JewelPos, -1); lpUser->pInventory[JewelPos].Clear(); GCInventoryItemOneSend(lpUser->m_Index, TargetPos); GCInventoryItemDeleteSend(lpUser->m_Index, JewelPos, 1); } else { GCReFillSend(lpUser->m_Index, (WORD)lpUser->Life, 0xFD, 1, lpUser->iShield); } } bool ItemUpgradeJewels::ProcUpgrade(LPOBJ lpUser, int JewelPos, int TargetPos, ItemUpgradeJewelsInfo* lpJewel) { if( JewelPos < 0 || JewelPos > MAIN_INVENTORY_SIZE-1 ) { return false; } if( TargetPos < 0 || TargetPos > MAIN_INVENTORY_SIZE-1 ) { return false; } if( !lpUser->pInventory[JewelPos].IsItem() || !lpUser->pInventory[TargetPos].IsItem() ) { return false; } int JewelCode = lpUser->pInventory[JewelPos].m_Type; int TargetCode = lpUser->pInventory[TargetPos].m_Type; if( JewelCode == ITEMGET(14, 13) && TargetCode == ITEMGET(0, 41) ) { if( gObjItemLevelUpPickAxe(lpUser, JewelPos, TargetPos) == TRUE ) { return true; } else { return false; } } if( JewelCode == ITEMGET(14, 13) && TargetCode == ITEMGET(13, 37) ) { CItem* ItemFenrir = &lpUser->pInventory[TargetPos]; if( ItemFenrir->m_Durability >= 255 ) { return false; } if( rand()% 10000 < g_iFenrirRepairRate ) { int iAddDur = rand()%150 + 50; if( (ItemFenrir->m_Durability + iAddDur) > 255 ) { ItemFenrir->m_Durability = 255.0f; } else { ItemFenrir->m_Durability += iAddDur; } MsgOutput(lpUser->m_Index,lMsg.Get(3342),int(ItemFenrir->m_Durability)); LogAddTD("[FENRIR REPAIR][SUCCESS] [%s][%s] - %d/255 (+%d)",lpUser->AccountID, lpUser->Name,ItemFenrir->m_Durability,iAddDur); } else { MsgOutput(lpUser->m_Index,lMsg.Get(3343)); LogAddTD("[FENRIR REPAIR][FAILED] [%s][%s] - %d/255 (+%d)",lpUser->AccountID,lpUser->Name, ItemFenrir->m_Durability); } return true; } CItem* ItemTarget = &lpUser->pInventory[TargetPos]; if( ItemTarget->m_bLuckySet == TRUE ) { return false; } if( lpJewel->TargetLevelMax != (BYTE)-1 && ItemTarget->m_Level >= lpJewel->TargetLevelMax ) { return false; } if( lpJewel->TargetLevelMin != (BYTE)-1 && ItemTarget->m_Level < lpJewel->TargetLevelMin ) { return false; } if( ItemTarget->m_Type >= ITEMGET(12,36) && ItemTarget->m_Type <= ITEMGET(12,40) ) { } #if (CUSTOM_WINGS == 1) else if( ItemTarget->m_Type >= ITEMGET(12,440) && ItemTarget->m_Type <= ITEMGET(12,445) ) { } #endif else if( ItemTarget->m_Type >= ITEMGET(12,41) && ItemTarget->m_Type <= ITEMGET(12,43) ) { } else if( ItemTarget->m_Type == ITEMGET(12,49) || ItemTarget->m_Type == ITEMGET(12,50) ) { } else if( ItemTarget->m_Type >= ITEMGET(12,200) && ItemTarget->m_Type <= ITEMGET(12,214) ) { } else if( ItemTarget->m_Type >= ITEMGET(12,262) && ItemTarget->m_Type <= ITEMGET(12,265) ) { } else if(!(ItemTarget->m_Type < ITEMGET(12,7) || ItemTarget->m_Type == ITEMGET(13,30) ) || ItemTarget->m_Type == ITEMGET(4,7) || ItemTarget->m_Type == ITEMGET(4,15)) { return false; } if( ItemTarget->m_NewOption && lpJewel->TargetRankExcellent != 1 ) { return false; } if( gSetItemOption.IsSetItem(ItemTarget->m_Type) && ItemTarget->m_SetOption > 0 && lpJewel->TargetRankAncient != 1 ) { return false; } if( g_SocketItem.IsSocketItem(ItemTarget->m_Type) && lpJewel->TargetRankSocket != 1 ) { return false; } DWORD Rate = lpJewel->DefaultRate; for( int i = 0; i < lpJewel->m_RateChangeRules.size(); i++ ) { bool Bonus = false; if( lpJewel->m_RateChangeRules[i].Type == ItemUpgradeJewelsRateType::Luck && ItemTarget->m_Option2 ) { Bonus = true; } else if( lpJewel->m_RateChangeRules[i].Type == ItemUpgradeJewelsRateType::Excellent && ItemTarget->m_NewOption ) { Bonus = true; } else if( lpJewel->m_RateChangeRules[i].Type == ItemUpgradeJewelsRateType::Ancient && gSetItemOption.IsSetItem(ItemTarget->m_Type) && ItemTarget->m_SetOption > 0 ) { Bonus = true; } else if( lpJewel->m_RateChangeRules[i].Type == ItemUpgradeJewelsRateType::Socket && g_SocketItem.IsSocketItem(ItemTarget->m_Type) ) { Bonus = true; } else if( lpJewel->m_RateChangeRules[i].Type == ItemUpgradeJewelsRateType::Level && lpJewel->m_RateChangeRules[i].Level != (BYTE)-1 && lpJewel->m_RateChangeRules[i].Level == ItemTarget->m_Level ) { Bonus = true; } else if( lpJewel->m_RateChangeRules[i].Type == ItemUpgradeJewelsRateType::Option && lpJewel->m_RateChangeRules[i].Option != (BYTE)-1 && lpJewel->m_RateChangeRules[i].Option == ItemTarget->m_Option3 ) { Bonus = true; } if( Bonus ) { Rate -= lpJewel->m_RateChangeRules[i].RateDecrease; Rate += lpJewel->m_RateChangeRules[i].RateIncrease; } } if( JewelCode == ITEMGET(14, 13) ) { if( rand() % 10000 < Rate ) { ItemTarget->m_Level++; if( ItemTarget->m_Level > lpJewel->TargetLevelMax ) { ItemTarget->m_Level = lpJewel->TargetLevelMax; } } } else if( JewelCode == ITEMGET(14, 14) ) { if( rand() % 10000 < Rate ) { ItemTarget->m_Level++; if( ItemTarget->m_Level > lpJewel->TargetLevelMax ) { ItemTarget->m_Level = lpJewel->TargetLevelMax; } } else { if( ItemTarget->m_Level >= 7 ) { ItemTarget->m_Level = 0; } else { ItemTarget->m_Level--; if( ItemTarget->m_Level < 0 ) { ItemTarget->m_Level = 0; } } } } else if( JewelCode == ITEMGET(14, 16) ) { if( ItemTarget->m_Option3 == 0 ) { if(ItemTarget->m_Type >= ITEMGET(12,3) && ItemTarget->m_Type <= ITEMGET(12,6) || ItemTarget->m_Type == ITEMGET(12,49) || ItemTarget->m_Type == ITEMGET(12,42) ) { ItemTarget->m_NewOption &= 0xDF; if(rand()%2) { ItemTarget->m_NewOption |= 0x20; } } if( ItemTarget->m_Type >= ITEMGET(12,36) && ItemTarget->m_Type <= ITEMGET(12,40) || ItemTarget->m_Type == ITEMGET(12,43) || ItemTarget->m_Type == ITEMGET(12,50) #if (CUSTOM_WINGS == 1) || ItemTarget->m_Type >= ITEMGET(12,440) && ItemTarget->m_Type <= ITEMGET(12,445) #endif ) { ItemTarget->m_NewOption &= 0xDF; if(rand()%3) { ItemTarget->m_NewOption |= 0x20; } else if(rand()%3) { ItemTarget->m_NewOption |= 0x10; } } if( ItemTarget->m_Type >= ITEMGET(12,262) && ItemTarget->m_Type <= ITEMGET(12,265) ) { ItemTarget->m_NewOption &= 0xDF; if( rand()%2 ) { ItemTarget->m_NewOption |= 0x10; } } } if( ItemTarget->m_Option3 >= 7 ) { return false; } if( rand() % 10000 < Rate ) { ItemTarget->m_Option3++; } else { ItemTarget->m_Option3 = 0; } } else if( JewelCode == ITEMGET(14, 42) ) { if( g_kJewelOfHarmonySystem.m_bSystemSmeltingItem == false ) { return false; } if( g_kJewelOfHarmonySystem.IsStrengthenByJewelOfHarmony(ItemTarget) ) { LogAddTD("[JewelOfHarmony][Strengten Item] Already Strengtened [%s][%s]", lpUser->AccountID, lpUser->Name); return false; } int iItemType = g_kJewelOfHarmonySystem._GetItemType(ItemTarget); if( iItemType == JEWELOFHARMONY_ITEM_TYPE_NULL ) { LogAddTD("[JewelOfHarmony][Strengten Item] Strenghten Fail [%s][%s] Name[%s] Type[%d] Serial[%d] Invalid ItemType[%d]", lpUser->AccountID, lpUser->Name, ItemTarget->GetName(), ItemTarget->m_Type, ItemTarget->m_Number, iItemType); return false; } int iItemOption = g_kJewelOfHarmonySystem._GetSelectRandomOption(ItemTarget, iItemType); if( iItemOption == AT_JEWELOFHARMONY_NOT_STRENGTHEN_ITEM ) { LogAddTD("[JewelOfHarmony][Strengten Item] Strenghten Fail - NOT OPTION [%s][%s] Name[%s] Type[%d] Serial[%d] ItemType[%d]", lpUser->AccountID, lpUser->Name, ItemTarget->GetName(), ItemTarget->m_Type, ItemTarget->m_Number, iItemType); return false; } int iItemOptionLevel = g_kJewelOfHarmonySystem.m_itemOption[iItemType][iItemOption].iRequireLevel; if( rand() % 10000 < Rate ) { g_kJewelOfHarmonySystem._MakeOption(ItemTarget, iItemOption, iItemOptionLevel); LogAddTD("[JewelOfHarmony][Strengten Item] Strenghten Success [%s][%s] Name[%s] Type[%d] Serial[%d] Rate (%d/%d) Option %d OptionLevel %d", lpUser->AccountID, lpUser->Name, ItemTarget->GetName(), ItemTarget->m_Type, ItemTarget->m_Number, Rate, Rate, iItemOption, iItemOptionLevel); GCServerMsgStringSend(lMsg.Get(MSGGET(13, 46)), lpUser->m_Index, 1); } else { LogAddTD("[JewelOfHarmony][Strengten Item] Strenghten Fail [%s][%s] Name[%s] Type[%d] Serial[%d] Rate (%d/%d)", lpUser->AccountID, lpUser->Name, ItemTarget->GetName(), ItemTarget->m_Type, ItemTarget->m_Number, Rate, Rate); GCServerMsgStringSend(lMsg.Get(MSGGET(13, 45)), lpUser->m_Index, 1); } } gObjMakePreviewCharSet(lpUser->m_Index); float levelitemdur = (float)ItemGetDurability(lpUser->pInventory[TargetPos].m_Type, lpUser->pInventory[TargetPos].m_Level, lpUser->pInventory[TargetPos].IsExtItem(), lpUser->pInventory[TargetPos].IsSetItem()); lpUser->pInventory[TargetPos].m_Durability = levelitemdur * lpUser->pInventory[TargetPos].m_Durability / lpUser->pInventory[TargetPos].m_BaseDurability; lpUser->pInventory[TargetPos].Convert( lpUser->pInventory[TargetPos].m_Type, lpUser->pInventory[TargetPos].m_Option1, lpUser->pInventory[TargetPos].m_Option2, lpUser->pInventory[TargetPos].m_Option3, lpUser->pInventory[TargetPos].m_NewOption, lpUser->pInventory[TargetPos].m_SetOption, lpUser->pInventory[TargetPos].m_ItemOptionEx,0,-1, CURRENT_DB_VERSION); LogAddTD(lMsg.Get(557),lpUser->AccountID,lpUser->Name,lpUser->pInventory[JewelPos].m_Number, lpUser->pInventory[TargetPos].GetName(),lpUser->pInventory[TargetPos].m_Number, lpUser->pInventory[TargetPos].m_Level); return true; } bool ItemUpgradeJewels::IsJewel(int ItemCode) { for( int i = 0; i < m_UpradeInfo.size(); i++ ) { if( ITEMGET(m_UpradeInfo[i].ItemType, m_UpradeInfo[i].ItemIndex) == ItemCode) { return true; } } return false; } ItemUpgradeJewelsRateChangeInfo* ItemUpgradeJewels::GetRateChangeRule(ItemUpgradeJewelsInfo* lpJewel, BYTE Type) { for( int i = 0; i < lpJewel->m_RateChangeRules.size(); i++ ) { if( lpJewel->m_RateChangeRules[i].Type == Type ) { return &lpJewel->m_RateChangeRules[i]; } } return NULL; }
26.021277
153
0.674125
sp3cialk
1ad143769b25d61f79dc4f586e188da3149be318
342
cpp
C++
Easy/169_Majority_Element.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
1
2021-03-15T10:02:10.000Z
2021-03-15T10:02:10.000Z
Easy/169_Majority_Element.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
Easy/169_Majority_Element.cpp
ShehabMMohamed/LeetCodeCPP
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
[ "MIT" ]
null
null
null
class Solution { public: int majorityElement(vector<int>& nums) { unordered_map<int, int> freq; for(int& n : nums) freq[n]++; int major = nums[0]; for(auto it : freq) { if(it.second > floor(nums.size() / 2)) major = it.first; } return major; } };
24.428571
50
0.473684
ShehabMMohamed
1ad418a38a314be3ba44b9ed3a9cd93639f4325e
8,578
cpp
C++
ch09/9.exercise.12.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
51
2017-03-24T06:08:11.000Z
2022-03-18T00:28:14.000Z
ch09/9.exercise.12.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
1
2019-06-23T07:33:42.000Z
2019-12-12T13:14:04.000Z
ch09/9.exercise.12.cpp
0p3r4t4/PPPUCPP2nd
cf1bd23bb22ee00a77172e43678b7eaa91f592e0
[ "MIT" ]
25
2017-04-07T13:22:45.000Z
2022-03-18T00:28:15.000Z
// 9.exercise.12.cpp // // Change the representation of a Date to be the number of days since January // 1, 1970 (known as day 0), represented as a long int, and re-implement the // functions from §9.8. Be sure to reject dates outside the range we can // represent that way (feel free to reject days before day 0, i.e., no // negative days). // // COMMMENTS // // Like the previous exercise, I'll reference January 1, 1970 as epoch. // This is an almost complete rewrite of Chrono namespace and I will take the // chance to clean all I can. // // Despite the internal representation, is desiderable to preserve the (y,m,d) // format to construct the Date and to input/output it. We can add a new // constructor with "days since epoch" as the only argument. // // With Date::add_month() we have to decide. A month is a variable amount of // days. If day of the month is between 1 and 28, there is little to argue. // But, what if be add a month to March 31st? We have many options, mainly: // // - the "last day" option, so the result will be April 30th. // - the "offset" option, remaining days are added so it will be May 1st. // - the "administrative" option, which takes a month as 30 days, no less, // no more. // // The "administrative" will be te simplest one, and it as valid as imprecise. // Between the other two, the "last day" option is what Java and OracleDB do. // It says "If date is the last day of the month or if the resulting month has // fewer days than the day component of date, then the result is the last day // of the resulting month. Otherwise, the result has the same day component as // date". I feel more inclined to this one although the arithmetic is weird. // For example, add one month and another one result could be different than // adding two months: // // 2016/1/31 + 1 month -> 2016/2/29 + 1 month -> 2016/3/29 // 2016/1/31 + 2 months -> 2016/3/31 // // But for me, it makes sense to respect "last day" of the month concept. // // As for Date::add_year(), it has some difficulties to implement it by adding // days. Mainly the leap day, and when in a year is the date, before of after // it in our start date. After some tries, and seen that Date::add_month() // performs almost fine, the lazy solution was to use it. After all, a year is // not a fixed amount of days but a fixed amount of months. // // Using a "days since epoch" representation simplifies a lot the // implementation (except previous trivial accessors year(), month() and // day()). Also it makes useless member and helper functions and operator // overloads that are needed with the y,m,d representation. // I know my current implementation is far from efficient, but I really get // tired of date manipulation, so let it be. #include "std_lib_facilities.h" #include "9.exercise.12.Chrono.h" // print info functions (ugly) void test_days_since_epoch(Chrono::Date d) { cout << "Chrono::Date::days_since_epoch(): " << d.days_since_epoch() << " days have passed since epoch until " << d << '\n'; } void test_add_day(Chrono::Date d, int nd, string msg) { d.add_day(nd); cout << "Chrono::Date::add_day(" << nd << "): " << msg << d << '\n'; } void test_add_month(Chrono::Date d, int nm, string msg) { d.add_month(nm); cout << "Chrono::Date::add_month(" << nm << "): " << msg << d << '\n'; } void test_add_year(Chrono::Date d, int ny, string msg) { d.add_year(ny); cout << "Chrono::Date::add_year(" << ny << "): " << msg << d << '\n'; } void test_day_of_week(Chrono::Date d) { cout << "Chrono::day_of_week(): " << d << " is " << Chrono::day_of_week(d) << '\n'; } void test_next_sunday(Chrono::Date d) { cout << "Chrono::next_Sunday(): Next sunday to " << d << " (" << Chrono::day_of_week(d) << ") is " << Chrono::next_Sunday(d) << " (" << Chrono::day_of_week(Chrono::next_Sunday(d)) << ")\n"; } void test_next_workday(Chrono::Date d) { cout << "Chrono::next_workday(): Next workday to " << d << " (" << Chrono::day_of_week(d) << ") is " << Chrono::next_workday(d) << " (" << Chrono::day_of_week(Chrono::next_workday(d)) << ")\n"; } void test_week_of_year(Chrono::Date d) { cout << "Chrono::week_of_year(): For date " << d << " week of the year is " << Chrono::week_of_year(d) << '\n'; } int main() try { Chrono::Date date; cout << '\n'; test_days_since_epoch(date); test_days_since_epoch(Chrono::Date{2017, Chrono::Month::dec, 1}); test_days_since_epoch(Chrono::Date{2017, Chrono::Month::dec, 31}); test_days_since_epoch(Chrono::Date{17531}); test_days_since_epoch(Chrono::Date{2018, Chrono::Month::jan, 1}); test_days_since_epoch(Chrono::Date{17533}); cout << '\n'; date = Chrono::Date{2016, Chrono::Month::jan, 1}; test_add_day(date, 7, "January the 8th 2016? "); test_add_day(date, 31, "February the 1st 2016? "); test_add_day(date, 60, "March the 1st 2016? "); test_add_day(date, 365, "December the 31th 2016? "); test_add_day(date, 366, "January the 1st 2017? "); test_add_day(date, 397, "February the 1st 2017? "); date = Chrono::Date{2016, Chrono::Month::jan, 15}; test_add_day(date, 80, "April the 4th 2016? "); cout << '\n'; date = Chrono::Date{2016, Chrono::Month::jan, 1}; test_add_month(date, 1, "February the 1st 2016? "); test_add_month(date, 3, "April the 1st 2016? "); test_add_month(date, 6, "July the 1st 2016? "); test_add_month(date, 10, "November the 1st 2016? "); test_add_month(date, 15, "April the 1st 2017? "); date = Chrono::Date{2016, Chrono::Month::jan, 15}; test_add_month(date, 1, "February the 15th 2016? "); test_add_month(date, 3, "April the 15th 2016? "); test_add_month(date, 6, "July the 15th 2016? "); test_add_month(date, 10, "November the 15th 2016? "); test_add_month(date, 15, "April the 15th 2017? "); date = Chrono::Date{2016, Chrono::Month::jan, 31}; test_add_month(date, 1, "February the 29th 2016? "); test_add_month(date, 3, "April the 30th 2016? "); test_add_month(date, 6, "July the 31th 2016? "); test_add_month(date, 10, "November the 30th 2016? "); test_add_month(date, 15, "April the 30th 2017? "); date = Chrono::Date{2016, Chrono::Month::feb, 29}; test_add_month(date, 1, "March the 29th 2016? "); test_add_month(date, 12, "February the 28th 2017? "); cout << '\n'; date = Chrono::Date{2016, Chrono::Month::jan, 1}; test_add_year(date, 1, "January the 1st 2017? "); test_add_year(date, 4, "January the 1st 2020? "); test_add_year(date, 8, "January the 1st 2024? "); date = Chrono::Date{2016, Chrono::Month::feb, 29}; test_add_year(date, 1, "February the 28th 2017? "); test_add_year(date, 4, "February the 29th 2020? "); date = Chrono::Date{2016, Chrono::Month::mar, 15}; test_add_year(date, 1, "March the 15th 2017? "); test_add_year(date, 4, "March the 15th 2020? "); date = Chrono::Date{2015, Chrono::Month::mar, 15}; test_add_year(date, 1, "March the 15th 2016? "); test_add_year(date, 4, "March the 15th 2019? "); cout << '\n'; test_day_of_week(Chrono::Date{1970, Chrono::Month::jan, 1}); test_day_of_week(Chrono::Date{1978, Chrono::Month::feb, 23}); test_day_of_week(Chrono::Date{2010, Chrono::Month::mar, 31}); test_day_of_week(Chrono::Date{2017, Chrono::Month::may, 28}); cout << '\n'; test_next_sunday(Chrono::Date{2017, Chrono::Month::may, 28}); test_next_sunday(Chrono::Date{2017, Chrono::Month::may, 24}); test_next_sunday(Chrono::Date{2017, Chrono::Month::may, 29}); cout << '\n'; test_next_workday(Chrono::Date{2017, Chrono::Month::may, 24}); test_next_workday(Chrono::Date{2017, Chrono::Month::may, 26}); test_next_workday(Chrono::Date{2017, Chrono::Month::may, 27}); test_next_workday(Chrono::Date{2017, Chrono::Month::may, 28}); cout << '\n'; test_week_of_year(Chrono::Date{2017, Chrono::Month::jan, 1}); test_week_of_year(Chrono::Date{2017, Chrono::Month::jan, 9}); test_week_of_year(Chrono::Date{2017, Chrono::Month::feb, 7}); test_week_of_year(Chrono::Date{2017, Chrono::Month::mar, 15}); test_week_of_year(Chrono::Date{2017, Chrono::Month::may, 28}); cout << '\n'; return 0; } catch (Chrono::Date::Invalid& e) { cerr << "Invalid Date!!\n"; return 1; } catch (exception& e) { cerr << e.what() << '\n'; return 2; } catch (...) { cerr << "Unknown exception!\n"; return 3; }
40.084112
80
0.646887
0p3r4t4
1ada697321cc4bc20111abc71c345f2f1004c128
427
cpp
C++
src/sensors/clocks/DS3231.cpp
el-fuego/Arduino-devices
2bc0fa1a9cbc3343f118eda73387e71d59ae4657
[ "MIT" ]
null
null
null
src/sensors/clocks/DS3231.cpp
el-fuego/Arduino-devices
2bc0fa1a9cbc3343f118eda73387e71d59ae4657
[ "MIT" ]
null
null
null
src/sensors/clocks/DS3231.cpp
el-fuego/Arduino-devices
2bc0fa1a9cbc3343f118eda73387e71d59ae4657
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "Sodaq_DS3231.h" #include "./DS3231.h" void DS3231_Sensor::init() { rtc.begin(); }; void DS3231_Sensor::update() { dateTime = rtc.now(); } // hours and minutes in int unsigned int DS3231_Sensor::getIntTime() { return dateTime.hour() * 60 + dateTime.minute(); } // number of minutes since 01.01.2000 00:00 uint32_t DS3231_Sensor::toEpochMinutes() { return dateTime.getEpoch() % 60; }
17.791667
50
0.688525
el-fuego
1ae352af7b11e11c919a0a4d658a3b9f14a1e01c
181
hpp
C++
src/2d/Layout.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
81
2018-12-11T20:48:41.000Z
2022-03-18T22:24:11.000Z
src/2d/Layout.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
7
2020-04-19T11:50:39.000Z
2021-11-12T16:08:53.000Z
src/2d/Layout.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
4
2019-04-24T11:51:29.000Z
2021-03-10T05:26:33.000Z
#pragma once #include "Node2D.hpp" namespace ari::en { struct Layout : public Node2D { ARI_COMPONENT_CHILD(Layout, Node2D) }; } // namespace ari::en
12.928571
43
0.60221
kochol
1aeada443644154ed8f45a2520a105c3c26dd70e
1,087
cpp
C++
week5/MergeIntervals2.cpp
AngelaJubeJudy/Algorithms
3a6eef59fd2fcb54d80013c067273d73bc6e79b9
[ "MIT" ]
null
null
null
week5/MergeIntervals2.cpp
AngelaJubeJudy/Algorithms
3a6eef59fd2fcb54d80013c067273d73bc6e79b9
[ "MIT" ]
null
null
null
week5/MergeIntervals2.cpp
AngelaJubeJudy/Algorithms
3a6eef59fd2fcb54d80013c067273d73bc6e79b9
[ "MIT" ]
null
null
null
class MergeIntervals2 { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { // 双关键字排序:2个长为2的数组的比较 sort(intervals.begin(), intervals.end(), [](vector<int>& a, vector<int>& b){ return a[0] < b[0] || (a[0] == b[0] && a[1] < b[1]); }); // “差分” // +1事件=正在覆盖,-1事件=判断已有事件能否延续(count=0时停止) // 非零->零:结束;零->非零,开始覆盖 vector<vector<int>> ans; vector<pair<int, int>> events; // step 1: 2n个事件 for(vector<int>& interval: intervals){ events.push_back(make_pair(interval[0], 1)); events.push_back(make_pair(interval[1]+1, -1)); } // step 2: 判断覆盖过程 sort(events.begin(), events.end()); int count = 0; int left = 0; for(pair<int, int>& event: events){ // 开始覆盖 if(count == 0) left = event.first; count += event.second; // 结束覆盖 if(count == 0) ans.push_back({left, event.first - 1}); } return ans; } };
31.057143
85
0.471021
AngelaJubeJudy
1aeed8bde00b3dfdbdb3d99ce7a0c572d2956660
5,944
cpp
C++
ql/models/marketmodels/products/multistep/multistepvolswap.cpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
4
2016-03-28T15:05:23.000Z
2020-02-17T23:05:57.000Z
ql/models/marketmodels/products/multistep/multistepvolswap.cpp
universe1987/QuantLib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
1
2015-02-02T20:32:43.000Z
2015-02-02T20:32:43.000Z
ql/models/marketmodels/products/multistep/multistepvolswap.cpp
pcaspers/quantlib
bbb0145aff285853755b9f6ed013f53a41163acb
[ "BSD-3-Clause" ]
10
2015-01-26T14:50:24.000Z
2015-10-23T07:41:30.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2012 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/models/marketmodels/products/multistep/multistepvolswap.hpp> #include <ql/models/marketmodels/curvestate.hpp> #include <ql/models/marketmodels/utilities.hpp> namespace QuantLib { MultiStepVolSwap::MultiStepVolSwap(const std::vector<Time>& rateTimes, const std::vector<Time>& obsTimes, const std::vector<Time>& paymentTimes, const std::vector<Real>& structuredAccruals, const std::vector<Real>& floatingAccruals, const std::vector<Size>& structuredFixingIndices, const std::vector<Size>& floatingFixingIndices, const std::vector<Size>& structuredPaymentIndices, const std::vector<Size>& floatingPaymentIndices, const Rate fixedRate, const Real multiplier, const Rate floor, const std::pair<Size,Size>& referenceRateIndices, const Size referenceRateStep, const std::vector<Rate>& referenceRateFixings, bool payer) : MultiProductMultiStep(rateTimes), structuredAccruals_(structuredAccruals), floatingAccruals_(floatingAccruals), rateTimes_(rateTimes), fixedRate_(fixedRate), multiplier_(multiplier), floor_(floor), structuredFixingIndices_(structuredFixingIndices), floatingFixingIndices_(floatingFixingIndices), structuredPaymentIndices_(structuredPaymentIndices), floatingPaymentIndices_(floatingPaymentIndices), referenceRateIndices_(referenceRateIndices), referenceRateStep_(referenceRateStep), referenceRateFixings0_(referenceRateFixings), /*lastIndex_(obsTimes.size()-1),*/ payer_(payer), filterStructuredIndex_(-1) { QL_REQUIRE(obsTimes_.size()>1, "Rate times must contain at least two values"); checkIncreasingTimes(obsTimes_); checkIncreasingTimes(paymentTimes_); Size n = obsTimes_.size(); std::vector<Time> evolutionTimes(n); std::vector<std::pair<Size,Size> > relevanceRates(n); for (Size i=0; i<n; ++i) { evolutionTimes[i] = obsTimes_[i]; relevanceRates[i] = std::make_pair(i, rateTimes_.size()-1); } evolution_ = EvolutionDescription(rateTimes_, evolutionTimes, relevanceRates); QL_REQUIRE(referenceRateFixings0_.size()==8,"Reference rate fixings for 8 previous dates needed (" << referenceRateFixings_.size() << ")"); floatingFixingIndices_.push_back(QL_MAX_INTEGER); // an index that will never be reached structuredFixingIndices_.push_back(QL_MAX_INTEGER); // an index that will never be reached } bool MultiStepVolSwap::nextTimeStep( const CurveState& currentState, std::vector<Size>& numberCashFlowsThisStep, std::vector<std::vector<MarketModelMultiProduct::CashFlow> >& genCashFlows) { //std::cout << "currentIndex=" << currentIndex_ << std::endl; Rate referenceRate = currentState.swapRate(referenceRateIndices_.first, referenceRateIndices_.second, referenceRateStep_ ); for(Size i=8; i>=1; i--) referenceRateFixings_[i] = referenceRateFixings_[i-1]; referenceRateFixings_[0] = referenceRate; Size noCf=0; if(currentIndex_ == floatingFixingIndices_[currentFloatingIndex_]) { Rate liborRate = currentState.forwardRate(currentFloatingIndex_); //std::cout << "generate float payment @" << floatingPaymentIndices_[currentFloatingIndex_] << std::endl; genCashFlows[0][noCf].timeIndex = floatingPaymentIndices_[currentFloatingIndex_]; genCashFlows[0][noCf].amount = (payer_ ? 1.0 : -1.0)*liborRate*floatingAccruals_[currentFloatingIndex_]; noCf++; currentFloatingIndex_++; } if(currentIndex_ == structuredFixingIndices_[currentStructuredIndex_]) { //std::cout << "generate structured payment @" << paymentTimes_[structuredPaymentIndices_[currentStructuredIndex_]] << std::endl; Real volIdx = (fabs(referenceRateFixings_[1]-referenceRateFixings_[5])+ fabs(referenceRateFixings_[2]-referenceRateFixings_[6])+ fabs(referenceRateFixings_[3]-referenceRateFixings_[7])+ fabs(referenceRateFixings_[4]-referenceRateFixings_[8])) / 4.0; genCashFlows[0][noCf].timeIndex = structuredPaymentIndices_[currentStructuredIndex_]; genCashFlows[0][noCf].amount = ( (currentStructuredIndex_== (Size)filterStructuredIndex_ || filterStructuredIndex_== -1) ? 1.0 : 0.0)*(payer_ ? -1.0 : 1.0)*structuredAccruals_[currentStructuredIndex_]*std::max(floor_,fixedRate_+multiplier_*volIdx); //genCashFlows[0][noCf].amount = (currentIndex_==structuredFixingIndices_[0] ? 1.0 : 0.0)*std::max(referenceRate-fixedRate_,0.0)*currentState.swapAnnuity(12,12,52,2); // TEST (plain vanilla swaption payoff) noCf++; currentStructuredIndex_++; } numberCashFlowsThisStep[0] = noCf; ++currentIndex_; bool done = (floatingFixingIndices_[currentFloatingIndex_] == QL_MAX_INTEGER && structuredFixingIndices_[currentStructuredIndex_] == QL_MAX_INTEGER ); //std::cout << "ok, finished = " << done << std::endl; return done; } std::unique_ptr<MarketModelMultiProduct> MultiStepVolSwap::clone() const { return std::unique_ptr<MarketModelMultiProduct>(new MultiStepVolSwap(*this)); } }
47.935484
251
0.728129
universe1987
8c19629bba9b92700937ef7313aefa4480840d3b
807
cpp
C++
Catch2/include/internal/catch_decomposer.cpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
1,461
2022-02-25T17:44:34.000Z
2022-03-30T06:18:29.000Z
Catch2/include/internal/catch_decomposer.cpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
116
2021-05-29T16:32:51.000Z
2021-08-13T16:05:29.000Z
Catch2/include/internal/catch_decomposer.cpp
TheBlindMick/MPU6050
66880369fa7a73755846e60568137dfc07da1b5c
[ "BSL-1.0" ]
135
2019-04-16T09:10:13.000Z
2022-03-18T10:22:40.000Z
/* * Created by Phil Nash on 8/8/2017. * Copyright 2017 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #include "catch_decomposer.h" #include "catch_config.hpp" namespace Catch { ITransientExpression::~ITransientExpression() = default; void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) { if( lhs.size() + rhs.size() < 40 && lhs.find('\n') == std::string::npos && rhs.find('\n') == std::string::npos ) os << lhs << " " << op << " " << rhs; else os << lhs << "\n" << op << "\n" << rhs; } }
32.28
122
0.583643
TheBlindMick
8c1bf2b4549b3ff3e548af905dcf22df75e7c4ea
581
cpp
C++
MET/main.cpp
elem-azar-unis/Redis-RPQ
96cb520a1985a01ab67069ab2a2bc22e656c7583
[ "BSD-3-Clause" ]
2
2018-07-11T03:06:10.000Z
2018-07-19T06:12:47.000Z
MET/main.cpp
elem-azar-unis/Redis-RPQ
96cb520a1985a01ab67069ab2a2bc22e656c7583
[ "BSD-3-Clause" ]
null
null
null
MET/main.cpp
elem-azar-unis/Redis-RPQ
96cb520a1985a01ab67069ab2a2bc22e656c7583
[ "BSD-3-Clause" ]
null
null
null
#include "exp_runner.h" int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); // run<rpq_op_script, rpq_oracle>("TLA/rwf_rpq/rwf_rpq_2_4.script"); // run<rpq_op_script, rpq_oracle>("TLA/rwf_rpq/rwf_rpq_3_3.script"); std::ofstream out_2_4("out_2_4.script"); run<list_op_script, list_oracle>("TLA/rwf_list/rwf_list_2_4.script", out_2_4); std::ofstream out_3_3("out_3_3.script"); run<list_op_script, list_oracle>("TLA/rwf_list/rwf_list_3_3.script", out_3_3); // run<list_op_script, list_oracle>("test.script"); return 0; }
29.05
82
0.702238
elem-azar-unis
8c1c1bd6337aac99a4e87cb820358c91841b9427
1,485
cpp
C++
src/stage/dungeon.cpp
djoyahoy/eng
848f7f5e5ed9cfca4703b69fb6af8c2e24721619
[ "MIT" ]
null
null
null
src/stage/dungeon.cpp
djoyahoy/eng
848f7f5e5ed9cfca4703b69fb6af8c2e24721619
[ "MIT" ]
null
null
null
src/stage/dungeon.cpp
djoyahoy/eng
848f7f5e5ed9cfca4703b69fb6af8c2e24721619
[ "MIT" ]
null
null
null
#include <stdexcept> #include "stage/dungeon.h" #include "enemy_maker.h" #include "json/json.h" #include "prop_maker.h" namespace stage { Dungeon::Dungeon(std::unique_ptr<Zone> zone, enemy::EnemyVec enemies, prop::PropVec props) : zone(std::move(zone)), enemies(std::move(enemies)), props(std::move(props)) { } std::unique_ptr<Dungeon> make_dungeon(const Json::Value& doc) { if (!doc.isMember("zone")) { throw std::runtime_error("No member zone."); } std::unique_ptr<Zone> zone = make_zone(doc["zone"]); // make enemies if (!doc.isMember("enemies")) { throw std::runtime_error("No member enemies."); } enemy::EnemyVec enemies; for (auto i = doc["enemies"].begin(); i != doc["enemies"].end(); i++) { if (!i->isMember("type")) { throw std::runtime_error("Enemy has no member type."); } auto func = enemy::get_enemy_maker((*i)["type"].asString()); enemies.emplace_back(func(*i)); } // make props if (!doc.isMember("props")) { throw std::runtime_error("No member props."); } prop::PropVec props; for (auto i = doc["props"].begin(); i != doc["props"].end(); i++) { if (!i->isMember("type")) { throw std::runtime_error("Prop has no member type."); } auto func = prop::get_prop_maker((*i)["type"].asString()); props.emplace_back(func(*i)); } return std::make_unique<Dungeon>(std::move(zone), std::move(enemies), std::move(props)); } }
28.557692
94
0.606061
djoyahoy
8c22679a999ae85e2f2c14d641656edc6e84e8fe
1,180
cpp
C++
YorozuyaGSLib/source/_darkhole_job_pass_inform_zoclDetail.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_darkhole_job_pass_inform_zoclDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_darkhole_job_pass_inform_zoclDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_darkhole_job_pass_inform_zoclDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Detail { Info::_darkhole_job_pass_inform_zoclsize2_ptr _darkhole_job_pass_inform_zoclsize2_next(nullptr); Info::_darkhole_job_pass_inform_zoclsize2_clbk _darkhole_job_pass_inform_zoclsize2_user(nullptr); int _darkhole_job_pass_inform_zoclsize2_wrapper(struct _darkhole_job_pass_inform_zocl* _this) { return _darkhole_job_pass_inform_zoclsize2_user(_this, _darkhole_job_pass_inform_zoclsize2_next); }; ::std::array<hook_record, 1> _darkhole_job_pass_inform_zocl_functions = { _hook_record { (LPVOID)0x14026f840L, (LPVOID *)&_darkhole_job_pass_inform_zoclsize2_user, (LPVOID *)&_darkhole_job_pass_inform_zoclsize2_next, (LPVOID)cast_pointer_function(_darkhole_job_pass_inform_zoclsize2_wrapper), (LPVOID)cast_pointer_function((int(_darkhole_job_pass_inform_zocl::*)())&_darkhole_job_pass_inform_zocl::size) }, }; }; // end namespace Detail END_ATF_NAMESPACE
42.142857
126
0.714407
lemkova
8c2699b8e11dce7408442feff0d0d8aef640e163
1,018
cpp
C++
src/termui/signals.cpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
1
2020-07-31T01:34:47.000Z
2020-07-31T01:34:47.000Z
src/termui/signals.cpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
null
null
null
src/termui/signals.cpp
numerodix/bmon-cpp
fae0613776b879a33e327f9ccf1d3819383634dd
[ "MIT" ]
null
null
null
#include <csignal> #include <stdexcept> #include "except.hpp" #include "signals.hpp" namespace bandwit { namespace termui { void SignalSuspender::suspend() { sigset_t mask; sigemptyset(&mask); for (auto signo : signums_) { sigaddset(&mask, signo); } if (sigprocmask(SIG_BLOCK, &mask, nullptr) < 0) { THROW_CERROR(std::runtime_error, "SignalSuspender.suspend failed in sigprocmask()"); } } void SignalSuspender::restore() { sigset_t mask; sigemptyset(&mask); for (auto signo : signums_) { sigaddset(&mask, signo); } if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) < 0) { THROW_CERROR(std::runtime_error, "SignalSuspender.restore failed in sigprocmask()"); } } void sigint_handler([[maybe_unused]] int sig) { // Throw here to force the stack to unwind. If we did just exit() here that // would not happen. THROW(InterruptException); } } // namespace termui } // namespace bandwit
22.622222
79
0.631631
numerodix
8c2b424387a1f74c1059ca6adba94eb9e7f0ecfd
3,292
hpp
C++
source/hougfx/include/hou/gfx/vertex2.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/hougfx/include/hou/gfx/vertex2.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/hougfx/include/hou/gfx/vertex2.hpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #ifndef HOU_GFX_VERTEX_2_HPP #define HOU_GFX_VERTEX_2_HPP #include "hou/gfx/gfx_config.hpp" #include "hou/cor/pragmas.hpp" #include "hou/gl/open_gl.hpp" #include "hou/mth/matrix.hpp" #include "hou/sys/color.hpp" namespace hou { class vertex_format; HOU_PRAGMA_PACK_PUSH(1) /** Represents a vertex in 2d space. * * The vertex contains information about its position, texture coordinates, * and color. */ class HOU_GFX_API vertex2 { public: /** Retrieves the vertex_format. */ static const vertex_format& get_vertex_format(); public: /** Builds a vertex2 object with all elements set to 0. */ vertex2() noexcept; /** Builds a vertex2 object with the given position, texture coordinates, * and color. * * \param position the vertex position. * * \param tex_coords the vertex texture coordinates. * * \param color the vertex color. */ vertex2(const vec2f& position, const vec2f& tex_coords, const color& color) noexcept; /** Gets the vertex position. * * \return the vertex position. */ vec2f get_position() const noexcept; /** Sets the vertex position. * * \param pos the vertex position. */ void set_position(const vec2f& pos) noexcept; /** Gets the vertex texture coordinates. * * \return the vertex texture coordinates. */ vec2f get_texture_coordinates() const noexcept; /** Sets the vertex texture coordinates. * * \param tex_coords the vertex texture coordinates. */ void set_texture_coordinates(const vec2f& tex_coords) noexcept; /** Gets the vertex color. * * \return the vertex color. */ color get_color() const noexcept; /** Sets the vertex color. * * \param color the vertex color. */ void set_color(const color& color) noexcept; private: static constexpr size_t s_position_size = 2u; static constexpr size_t s_texture_coordinates_size = 2u; static constexpr size_t s_color_size = 4u; private: GLfloat m_position[s_position_size]; GLfloat m_tex_coords[s_texture_coordinates_size]; GLfloat m_color[s_color_size]; }; HOU_PRAGMA_PACK_POP() /** Checks if two vertex2 objects are equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are equal. */ HOU_GFX_API bool operator==(const vertex2& lhs, const vertex2& rhs) noexcept; /** Checks if two vertex2 objects are not equal. * * \param lhs the left operand. * * \param rhs the right operand. * * \return true if the two objects are not equal. */ HOU_GFX_API bool operator!=(const vertex2& lhs, const vertex2& rhs) noexcept; /** Checks if two vertex2 objects are equal with the specified accuracy. * * \param lhs the left operand. * * \param rhs the right operand. * * \param acc the accuracy. * * \return true if the two objects are equal. */ HOU_GFX_API bool close(const vertex2& lhs, const vertex2& rhs, float acc = std::numeric_limits<float>::epsilon()) noexcept; /** Writes the object into a stream. * * \param os the stream. * * \param v the vertex2. * * \return a reference to os. */ HOU_GFX_API std::ostream& operator<<(std::ostream& os, const vertex2& v); } // namespace hou #endif
21.946667
77
0.70079
DavideCorradiDev
8c2bdc13fa7d0c0196bba8d7d51f7c0978e1f90d
42
cpp
C++
test/autogen/smp@list@swap_index.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
9
2020-07-04T16:46:13.000Z
2022-01-09T21:59:31.000Z
test/autogen/smp@list@swap_index.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
null
null
null
test/autogen/smp@list@swap_index.cpp
jonathanpoelen/jln.mp
e5f05fc4467f14ac0047e3bdc75a04076e689985
[ "MIT" ]
1
2021-05-23T13:37:40.000Z
2021-05-23T13:37:40.000Z
#include "jln/mp/smp/list/swap_index.hpp"
21
41
0.761905
jonathanpoelen
8c2e32682e810154c5e8a4a9d5593809a86fd2b6
621
cpp
C++
Codeforces/899C/math.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Codeforces/899C/math.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Codeforces/899C/math.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> using namespace std; int ans[4] = {0, 1, 1, 0}, dArr[4] = {0, 1, 1, 2}, iArr[4] = {2, 1, 2, 1}; int main() { ios::sync_with_stdio(false); int n; cin >> n; int tmp = n % 4; cout << ans[tmp] << endl; cout << (n / 4) * 2 + dArr[tmp]; int i = iArr[tmp]; bool flag = true; while (i <= n) { cout << " " << i; if (flag) i += 1; else i += 3; flag = !flag; } return 0; }
17.25
74
0.47504
codgician
8c323418ba1817ed1d0831df8f896cfffdf45a18
3,805
cpp
C++
src/DlgQueryMsgID.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/DlgQueryMsgID.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/DlgQueryMsgID.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: DlgQueryMsgID.cpp,v $ /* Revision 1.1 2010/07/21 17:14:56 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.1 2009/06/09 13:21:28 richard_wood /* *** empty log message *** /* /* Revision 1.2 2008/09/19 14:51:06 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ // DlgQueryMsgID.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "DlgQueryMsgID.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDlgQueryMsgID dialog CDlgQueryMsgID::CDlgQueryMsgID(CWnd* pParent /*=NULL*/) : CDialog(CDlgQueryMsgID::IDD, pParent) { m_fGoogle = false; } void CDlgQueryMsgID::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDlgQueryMsgID, CDialog) ON_BN_CLICKED(IDOK, OnGoogle) ON_BN_CLICKED(IDC_BUT_TREATEMAIL, OnEmail) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgQueryMsgID message handlers void CDlgQueryMsgID::OnGoogle() { m_fGoogle = true; CDialog::EndDialog(IDOK); } void CDlgQueryMsgID::OnEmail() { m_fGoogle = false; CDialog::EndDialog(IDOK); } void CDlgQueryMsgID::OnCancel() { CDialog::OnCancel(); }
36.586538
85
0.561104
taviso
8c36c165d0deb2ec37a64655ac16a8ccf282f4ff
5,333
cpp
C++
src/qif191cli/QifResourcesDocument.cpp
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
src/qif191cli/QifResourcesDocument.cpp
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
src/qif191cli/QifResourcesDocument.cpp
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Copyright 2018-2020, Capvidia, Metrosage, and project contributors /// https://www.capvidia.com/ /// /// This software is provided for free use to the QIF Community under the /// following license: /// /// Boost Software License - Version 1.0 - August 17th, 2003 /// https://www.boost.org/LICENSE_1_0.txt /// /// Permission is hereby granted, free of charge, to any person or organization /// obtaining a copy of the software and accompanying documentation covered by /// this license (the "Software") to use, reproduce, display, distribute, /// execute, and transmit the Software, and to prepare derivative works of the /// Software, and to permit third-parties to whom the Software is furnished to /// do so, all subject to the following: /// /// The copyright notices in the Software and this entire statement, including /// the above license grant, this restriction and the following disclaimer, /// must be included in all copies of the Software, in whole or in part, and /// all derivative works of the Software, unless such copies or derivative /// works are solely in the form of machine-executable object code generated by /// a source language processor. /// /// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT /// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE /// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, /// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #include "stdafx.h" #include "QifResourcesDocument.h" #include <msclr\marshal.h> #include <msclr\marshal_cppstd.h> #define ss2ws(x) msclr::interop::marshal_as<std::wstring>(x) namespace Qif_1_9_1 { /// <summary> Constructor. </summary> /// <param name="filepath"> QIF file path </param> QifResourcesDocument::QifResourcesDocument(String^ filepath) { _document = new qif191::QifResourcesDocument(ss2ws(filepath)); } /// <summary> Finalizer. </summary> /// <returns></returns> QifResourcesDocument::!QifResourcesDocument() { delete _document; } /// <summary> Saves the given CMM list to the QIF document. </summary> /// <param name="cmmParameters"> CMM to save </param> /// <returns> True in case of success, otherwise false </returns> bool QifResourcesDocument::Save(IEnumerable<Qif::CmmParameters^>^ cmmParameters) { using namespace std; // Create our native list of CmmParameters vector<unique_ptr<qifbase::CmmParameters> > nativeCmmParameters; if(cmmParameters != nullptr) { for each(auto cmm in cmmParameters) { unique_ptr<qifbase::CmmParameters> nativeCmm(new qifbase::CmmParameters(*(cmm->InternalData))); nativeCmmParameters.push_back(std::move(nativeCmm)); } } // Call the underlying method return _document->Save(nativeCmmParameters); } /// <summary> Loads a list of CMMs from the QIF document. </summary> /// <returns> List of loaded CMMs in case of success, otherwise null </returns> IReadOnlyList<Qif::CmmParameters^>^ QifResourcesDocument::Load() { using namespace std; // Call the underlying method vector<unique_ptr<qifbase::CmmParameters> > nativeCmmList; bool result = _document->Load(nativeCmmList); if(result == false) return nullptr; // Build up our list of CmmParameter^ auto cmmList = gcnew List<Qif::CmmParameters^>(); for(size_t i = 0; i < nativeCmmList.size(); i++) { qifbase::CmmParameters* ptr = nativeCmmList[i].release(); cmmList->Add(gcnew Qif::CmmParameters(ptr)); } return cmmList; } /// <summary> Gets error list. </summary> IReadOnlyList<String^>^ QifResourcesDocument::ErrorList::get() { List<String^>^ list = gcnew List<String^>(); for(std::vector<std::wstring>::const_iterator it = _document->ErrorList().begin(); it != _document->ErrorList().end(); it++) list->Add(gcnew String((*it).c_str())); return list; } /// <summary> Gets error detail list. </summary> IReadOnlyList<String^>^ QifResourcesDocument::ErrorDetailsList::get() { List<String^>^ list = gcnew List<String^>(); for(std::vector<std::wstring>::const_iterator it = _document->ErrorDetailsList().begin(); it != _document->ErrorDetailsList().end(); it++) list->Add(gcnew String((*it).c_str())); return list; } /// <summary> Gets warning list. </summary> IReadOnlyList<String^>^ QifResourcesDocument::WarningList::get() { List<String^>^ list = gcnew List<String^>(); for(std::vector<std::wstring>::const_iterator it = _document->WarningList().begin(); it != _document->WarningList().end(); it++) list->Add(gcnew String((*it).c_str())); return list; } /// <summary> Gets warning detail list. </summary> IReadOnlyList<String^>^ QifResourcesDocument::WarningDetailsList::get() { List<String^>^ list = gcnew List<String^>(); for(std::vector<std::wstring>::const_iterator it = _document->WarningDetailsList().begin(); it != _document->WarningDetailsList().end(); it++) list->Add(gcnew String((*it).c_str())); return list; } }
38.644928
146
0.690606
QualityInformationFramework
8c432690893a0fe12d02abddaea7cc348c177fb9
676
hpp
C++
Loyalty/ApiServer/Managers/ClientsManagerDB.hpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
null
null
null
Loyalty/ApiServer/Managers/ClientsManagerDB.hpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
1
2021-03-06T11:38:01.000Z
2021-03-15T21:33:16.000Z
Loyalty/ApiServer/Managers/ClientsManagerDB.hpp
uno-labs-solana-hackathon/core-server
fdbdefd32e12fcaa19227f56154e0163c18a35cb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../ApiServer_global.hpp" namespace Sol::Loyalty::API::RPC { class ClientsManagerDB { CLASS_REMOVE_CTRS(ClientsManagerDB); using ClientDescT = Sol::Loyalty::DataModel::ClientDesc; using SelectResT = std::tuple<ClientDescT::SP, SInt64/*version*/>; public: static SelectResT SSelectById (std::string_view aClientId, GpDbConnection& aDbConn); static void SInsert (const ClientDescT& aClientDesc, GpDbConnection& aDbConn); static void SUpdate (const ClientDescT& aClientDesc, const SInt64 aVersion, GpDbConnection& aDbConn); }; }//namespace Sol::Loyalty::API::RPC
27.04
67
0.680473
uno-labs-solana-hackathon
8c43fe4e52fc2be1ed2dd56b6a4ddbb46ac9acdf
2,228
cpp
C++
test/types/ds/test_priority_queue.cpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2020-07-31T14:13:56.000Z
2021-02-03T09:51:43.000Z
test/types/ds/test_priority_queue.cpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
28
2015-09-22T07:38:21.000Z
2018-10-02T11:00:58.000Z
test/types/ds/test_priority_queue.cpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2018-10-11T14:10:50.000Z
2021-02-27T08:53:50.000Z
#include <boost/test/unit_test.hpp> #include "types/ds/priority_queue.hpp" BOOST_AUTO_TEST_SUITE(DSPriorityQueue) BOOST_AUTO_TEST_CASE(create_empty_pq) { { Types::DS::PriorityQueue<int> pq(Types::DS::PriorityQueue<int>::Type::MAX); BOOST_CHECK(pq.size() == 0); BOOST_CHECK(pq.isEmpty()); } { Types::DS::PriorityQueue<int> pq(Types::DS::PriorityQueue<int>::Type::MIN); BOOST_CHECK(pq.size() == 0); BOOST_CHECK(pq.isEmpty()); } } BOOST_AUTO_TEST_CASE(insert_elements_in_pq) { Types::DS::PriorityQueue<int> pq(Types::DS::PriorityQueue<int>::Type::MAX); pq.insert(10, 200); BOOST_CHECK(pq.top() == 10); pq.insert(9, 210); BOOST_CHECK(pq.top() == 9); pq.insert(1, 210); BOOST_CHECK(pq.top() == 9); pq.insert(20, 150); BOOST_CHECK(pq.top() == 9); pq.insert(10, 180); BOOST_CHECK(pq.top() == 9); pq.insert(15, 205); BOOST_CHECK(pq.top() == 9); } BOOST_AUTO_TEST_CASE(pop_elements_from_pq) { Types::DS::PriorityQueue<int> pq(Types::DS::PriorityQueue<int>::Type::MAX); pq.insert(10, 200); pq.insert(9, 210); pq.insert(1, 210); pq.insert(20, 150); pq.insert(10, 180); pq.insert(15, 205); BOOST_CHECK(pq.top() == 9); pq.pop(); BOOST_CHECK(pq.top() == 1); pq.pop(); BOOST_CHECK(pq.top() == 15); pq.pop(); BOOST_CHECK(pq.top() == 10); pq.pop(); BOOST_CHECK(pq.top() == 10); pq.pop(); BOOST_CHECK(pq.top() == 20); pq.pop(); BOOST_CHECK(pq.isEmpty()); } BOOST_AUTO_TEST_CASE(change_priority_in_pq) { Types::DS::PriorityQueue<int> pq(Types::DS::PriorityQueue<int>::Type::MAX); pq.insert(10, 200); pq.insert(9, 210); pq.insert(1, 210); pq.insert(20, 150); pq.insert(10, 180); pq.insert(15, 205); pq.setPriority(10, 300); pq.setPriority(1, 140); BOOST_CHECK(pq.top() == 10); pq.pop(); BOOST_CHECK(pq.top() == 10); pq.pop(); BOOST_CHECK(pq.top() == 9); pq.pop(); BOOST_CHECK(pq.top() == 15); pq.pop(); BOOST_CHECK(pq.top() == 20); pq.pop(); BOOST_CHECK(pq.top() == 1); pq.pop(); BOOST_CHECK(pq.isEmpty()); } BOOST_AUTO_TEST_SUITE_END()
21.219048
83
0.586176
iamantony
8c49d6557e119ddce3db1420594d1eaf02d1c0ea
3,113
cpp
C++
RWracesDBII/RWracesDBII.prj/LocationPrefTbl.cpp
rrvt/RWracesDB
4f01fed973df7dfb7ec516b2969b20fc6744d7fe
[ "MIT" ]
null
null
null
RWracesDBII/RWracesDBII.prj/LocationPrefTbl.cpp
rrvt/RWracesDB
4f01fed973df7dfb7ec516b2969b20fc6744d7fe
[ "MIT" ]
null
null
null
RWracesDBII/RWracesDBII.prj/LocationPrefTbl.cpp
rrvt/RWracesDB
4f01fed973df7dfb7ec516b2969b20fc6744d7fe
[ "MIT" ]
null
null
null
// LocationPref Table #include "stdafx.h" #include "LocationPrefTbl.h" #include "DAOfields.h" #include "DAOrecords.h" #include "NotePad.h" #include "Utilities.h" bool LocationPrefTbl::load(DAOtable* daoTable) { DAOrcdsIter iter(daoTable); FieldsP fields; int count; for (count = 0, fields = iter(DAOdenyWrite); fields; count++, fields = iter++) { LocationPrefRcd rcd; rcd.load(fields); data = rcd; } notePad << count << nCrlf; return true; } void LocationPrefRcd::load(FieldsP fields) { DAOfldsIter iter(fields); DAOfield* dsc; variant_t v; for (dsc = iter(); dsc; dsc = iter++) { v = dsc->value(); switch (iter.index()) { case 0: id = v; break; case 1: key = v; break; case 2: txt = v; break; default: throw _T("LocationPref Record Error"); } } } void LocationPrefTbl::store() { DAOtable* daoTbl = daoTables.bSearch(name); if (!daoTbl) throw _T("Unable to locate LocationPref Table"); DAOrcds daoRcds(daoTbl); FieldsP fieldsP; LocIter iter(*this); LocationPrefRcd* rcd; for (rcd = iter(); rcd; rcd = iter++) { if (rcd->isDeleted() && daoRcds.findRecord(rcd->id)) {daoRcds.delCurRcd(); iter.remove(); continue;} if (!rcd->isDirty()) continue; fieldsP = daoRcds.findRecord(rcd->id); if (!fieldsP) continue; // Add new records with addNewRcd daoRcds.edit(); rcd->store(fieldsP); daoRcds.update(); rcd->clearMark(); } } LocationPrefRcd* LocationPrefTbl::add(LocationPrefRcd& rcd) { DAOtable* daoTbl = daoTables.bSearch(name); if (!daoTbl) throw _T("Unable to locate LocationPref Table"); DAOrcds daoRcds(daoTbl); FieldsP fieldsP; fieldsP = daoRcds.findRecord(rcd.id); if (fieldsP) return 0; fieldsP = daoRcds.addNew(); rcd.store(fieldsP); daoRcds.update(); rcd.clearMark(); return data = rcd; } LocationPrefRcd* LocationPrefTbl::add(String key, String txt) { // Add a new record to table and database LocationPrefRcd rcd; rcd.key = key; rcd.txt = txt; return add(rcd); } void LocationPrefRcd::store(FieldsP fields) { DAOfldsIter iter(fields); DAOfield* field; variant_t v; for (field = iter(); field; field = iter++) { switch (iter.index()) { case 0: id = field->value(); continue; case 1: v = key; break; case 2: v = txt; break; default: throw _T("LocationPref Record Error"); } *field = v; } } void LocationPrefTbl::display() { LocIter iter(*this); LocationPrefRcd* rcd; setTabs(); notePad << _T("LocationPref Table") << nCrlf; for (rcd = iter(); rcd; rcd = iter++) rcd->display(); } void LocationPrefRcd::display() { notePad << nTab << id; notePad << nTab << key; notePad << nCrlf; } void LocationPrefTbl::setTabs() { LocIter iter(*this); LocationPrefRcd* rcd; int tab0 = 0; for (rcd = iter(); rcd; rcd = iter++) { maxLng(rcd->id, tab0); } notePad << nClrTabs; notePad << nSetRTab(tab0) << nSetTab(tab0 + 2); }
23.583333
114
0.609059
rrvt
8c4af24c1d86a6b4129e4ee3a0348640660b0869
2,577
cpp
C++
samples/simple/simple/simple.cpp
techsoft3d/exchange-polygonica-bridge
e626fdbe61738c28a76e04f22c0ae409da1b1d32
[ "MIT" ]
1
2021-07-13T21:07:08.000Z
2021-07-13T21:07:08.000Z
samples/simple/simple/simple.cpp
techsoft3d/exchange-polygonica-bridge
e626fdbe61738c28a76e04f22c0ae409da1b1d32
[ "MIT" ]
null
null
null
samples/simple/simple/simple.cpp
techsoft3d/exchange-polygonica-bridge
e626fdbe61738c28a76e04f22c0ae409da1b1d32
[ "MIT" ]
1
2020-06-05T19:22:52.000Z
2020-06-05T19:22:52.000Z
// simple.cpp : This file contains the 'main' function. Program execution begins and ends there. // // Loads a file using HOOPS Exchange, converts part into a Polygonica Solid and saves to an STL. // #include <iostream> #include "pgapi.h" #include "pgkey.h" #include "../../src/ExchangePolygonicaBridge.h" PTEnvironment pg_environment; static void handle_pg_error(PTStatus status, char* err_string) { PTStatus status_code; PTStatus err_code; PTStatus func_code; PTStatus fatal_error = PV_STATUS_OK; /* The status is made up of 3 parts */ status_code = PM_STATUS_FROM_API_ERROR_CODE(status); func_code = PM_FN_FROM_API_ERROR_CODE(status); err_code = PM_ERR_FROM_API_ERROR_CODE(status); if (status_code & PV_STATUS_BAD_CALL) { printf("PG:BAD_CALL: Function %d Error %d: %s\n", func_code, err_code, err_string); } if (status_code & PV_STATUS_MEMORY) { printf("PG:MEMORY: Function %d Error %d: %s\n", func_code, err_code, err_string); fatal_error |= status; } if (status_code & PV_STATUS_EXCEPTION) { printf("PG:EXCEPTION: Function %d Error %d: %s\n", func_code, err_code, err_string); fatal_error |= status; } if (status_code & PV_STATUS_FILE_IO) { printf("PG:FILE I/0: Function %d Error %d: %s\n", func_code, err_code, err_string); } if (status_code & PV_STATUS_INTERRUPT) { printf("PG:INTERRUPT: Function %d Error %d: %s\n", func_code, err_code, err_string); } if (status_code & PV_STATUS_INTERNAL_ERROR) { printf("PG:INTERNAL_ERROR: Function %d Error %d: %s\n", func_code, err_code, err_string); fatal_error |= status; } } int InitializePolygonica() { PTStatus status = PFInitialise(PV_LICENSE, NULL); if (status) { printf("Polygonica failed to initialize.\n"); return status; } status = PFEnvironmentCreate(NULL, &pg_environment); if (status) { printf("Failed to create Polygonica environment."); return status; } PFEntitySetPointerProperty(pg_environment, PV_ENV_PROP_ERROR_REPORT_CB, handle_pg_error); printf("Polygonica Loaded.\n"); return status; } int main() { InitializePolygonica(); ExchangePolygonicaBridge bridge(pg_environment); PTSolid solid = NULL; int ret = bridge.Process((char*)"Ring.CATPart", &solid); /* ADD ADDITIONAL POLYGONICA CODE HERE */ PTStream stream; PTStreamFileOpts stream_options; stream_options.filename_is_wchar = 0; ret = PFStreamFileOpen((char*)"Ring.stl", PV_FILE_WRITE, &stream_options, &stream); ret = PFSolidWrite(solid, PV_SOLID_DATA_BINARY_STL, stream, NULL); ret = PFStreamClose(stream); PFEnvironmentDestroy(pg_environment); PFTerminate(); }
27.126316
96
0.737679
techsoft3d
8c51e4b9441d8e80bd8b6bde671c8f40a716f820
10,059
cpp
C++
MSVC/14.24.28314/atlmfc/src/mfc/afxheaderctrl.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
MSVC/14.24.28314/atlmfc/src/mfc/afxheaderctrl.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
MSVC/14.24.28314/atlmfc/src/mfc/afxheaderctrl.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "afxheaderctrl.h" #include "afxglobals.h" #include "afxvisualmanager.h" #ifdef _DEBUG #define new DEBUG_NEW #endif IMPLEMENT_DYNAMIC(CMFCHeaderCtrl, CHeaderCtrl) ///////////////////////////////////////////////////////////////////////////// // CMFCHeaderCtrl CMFCHeaderCtrl::CMFCHeaderCtrl() { m_bIsMousePressed = FALSE; m_bMultipleSort = FALSE; m_bAscending = TRUE; m_nHighlightedItem = -1; m_bTracked = FALSE; m_bIsDlgControl = FALSE; m_hFont = NULL; } CMFCHeaderCtrl::~CMFCHeaderCtrl() { } BEGIN_MESSAGE_MAP(CMFCHeaderCtrl, CHeaderCtrl) ON_WM_ERASEBKGND() ON_WM_PAINT() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_CANCELMODE() ON_WM_CREATE() ON_WM_MOUSELEAVE() ON_WM_SETFONT() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMFCHeaderCtrl message handlers void CMFCHeaderCtrl::OnDrawItem(CDC* pDC, int iItem, CRect rect, BOOL bIsPressed, BOOL bIsHighlighted) { ASSERT_VALID(this); ASSERT_VALID(pDC); const int nTextMargin = 5; // Draw border: CMFCVisualManager::GetInstance()->OnDrawHeaderCtrlBorder(this, pDC, rect, bIsPressed, bIsHighlighted); if (iItem < 0) { return; } int nSortVal = 0; if (m_mapColumnsStatus.Lookup(iItem, nSortVal) && nSortVal != 0) { // Draw sort arrow: CRect rectArrow = rect; rectArrow.DeflateRect(5, 5); rectArrow.left = rectArrow.right - rectArrow.Height(); if (bIsPressed) { rectArrow.right++; rectArrow.bottom++; } rect.right = rectArrow.left - 1; int dy2 = (int)(.134 * rectArrow.Width()); rectArrow.DeflateRect(0, dy2); m_bAscending = nSortVal > 0; OnDrawSortArrow(pDC, rectArrow); } HD_ITEM hdItem; memset(&hdItem, 0, sizeof(hdItem)); hdItem.mask = HDI_FORMAT | HDI_BITMAP | HDI_TEXT | HDI_IMAGE; TCHAR szText [256]; hdItem.pszText = szText; hdItem.cchTextMax = 255; if (!GetItem(iItem, &hdItem)) { return; } // Draw bitmap and image: if ((hdItem.fmt & HDF_IMAGE) && hdItem.iImage >= 0) { // By Max Khiszinsky: // The column has a image from imagelist: CImageList* pImageList = GetImageList(); if (pImageList != NULL) { int cx = 0; int cy = 0; VERIFY(::ImageList_GetIconSize(*pImageList, &cx, &cy)); CPoint pt = rect.TopLeft(); pt.x ++; pt.y = (rect.top + rect.bottom - cy) / 2; VERIFY(pImageList->Draw(pDC, hdItem.iImage, pt, ILD_NORMAL)); rect.left += cx; } } if ((hdItem.fmt &(HDF_BITMAP | HDF_BITMAP_ON_RIGHT)) && hdItem.hbm != NULL) { CBitmap* pBmp = CBitmap::FromHandle(hdItem.hbm); ASSERT_VALID(pBmp); BITMAP bmp; pBmp->GetBitmap(&bmp); CRect rectBitmap = rect; if (hdItem.fmt & HDF_BITMAP_ON_RIGHT) { rectBitmap.right--; rect.right = rectBitmap.left = rectBitmap.right - bmp.bmWidth; } else { rectBitmap.left++; rect.left = rectBitmap.right = rectBitmap.left + bmp.bmWidth; } rectBitmap.top += max(0, (rectBitmap.Height() - bmp.bmHeight) / 2); rectBitmap.bottom = rectBitmap.top + bmp.bmHeight; pDC->DrawState(rectBitmap.TopLeft(), rectBitmap.Size(), pBmp, DSS_NORMAL); } // Draw text: if ((hdItem.fmt & HDF_STRING) && hdItem.pszText != NULL) { CRect rectLabel = rect; rectLabel.DeflateRect(nTextMargin, 0); CString strLabel = hdItem.pszText; UINT uiTextFlags = DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX; if (hdItem.fmt & HDF_CENTER) { uiTextFlags |= DT_CENTER; } else if (hdItem.fmt & HDF_RIGHT) { uiTextFlags |= DT_RIGHT; } pDC->DrawText(strLabel, rectLabel, uiTextFlags); } } void CMFCHeaderCtrl::SetSortColumn(int iColumn, BOOL bAscending, BOOL bAdd) { ASSERT_VALID(this); if (iColumn < 0) { m_mapColumnsStatus.RemoveAll(); return; } if (bAdd) { if (!m_bMultipleSort) { ASSERT(FALSE); bAdd = FALSE; } } if (!bAdd) { m_mapColumnsStatus.RemoveAll(); } m_mapColumnsStatus.SetAt(iColumn, bAscending ? 1 : -1); RedrawWindow(); } void CMFCHeaderCtrl::RemoveSortColumn(int iColumn) { ASSERT_VALID(this); m_mapColumnsStatus.RemoveKey(iColumn); RedrawWindow(); } BOOL CMFCHeaderCtrl::OnEraseBkgnd(CDC* /*pDC*/) { return TRUE; } void CMFCHeaderCtrl::OnPaint() { if (GetStyle() & HDS_FILTERBAR) { Default(); return; } CPaintDC dc(this); // device context for painting CMemDC memDC(dc, this); CDC* pDC = &memDC.GetDC(); CRect rectClip; dc.GetClipBox(rectClip); CRect rectClient; GetClientRect(rectClient); OnFillBackground(pDC); CFont* pOldFont = SelectFont(pDC); ASSERT_VALID(pOldFont); pDC->SetTextColor(GetGlobalData()->clrBtnText); pDC->SetBkMode(TRANSPARENT); CRect rect; GetClientRect(rect); CRect rectItem; int nCount = GetItemCount(); int xMax = 0; for (int i = 0; i < nCount; i++) { // Is item pressed? CPoint ptCursor; ::GetCursorPos(&ptCursor); ScreenToClient(&ptCursor); HDHITTESTINFO hdHitTestInfo; hdHitTestInfo.pt = ptCursor; int iHit = (int) SendMessage(HDM_HITTEST, 0, (LPARAM) &hdHitTestInfo); BOOL bIsHighlighted = iHit == i &&(hdHitTestInfo.flags & HHT_ONHEADER); BOOL bIsPressed = m_bIsMousePressed && bIsHighlighted; GetItemRect(i, rectItem); CRgn rgnClip; rgnClip.CreateRectRgnIndirect(&rectItem); pDC->SelectClipRgn(&rgnClip); // Draw item: OnDrawItem(pDC, i, rectItem, bIsPressed, m_nHighlightedItem == i); pDC->SelectClipRgn(NULL); xMax = max(xMax, rectItem.right); } // Draw "tail border": if (nCount == 0) { rectItem = rect; rectItem.right++; } else { rectItem.left = xMax; rectItem.right = rect.right + 1; } OnDrawItem(pDC, -1, rectItem, FALSE, FALSE); pDC->SelectObject(pOldFont); } void CMFCHeaderCtrl::OnFillBackground(CDC* pDC) { ASSERT_VALID(this); ASSERT_VALID(pDC); CRect rectClient; GetClientRect(rectClient); CMFCVisualManager::GetInstance()->OnFillHeaderCtrlBackground(this, pDC, rectClient); } CFont* CMFCHeaderCtrl::SelectFont(CDC *pDC) { ASSERT_VALID(this); ASSERT_VALID(pDC); CFont* pOldFont = NULL; if (m_hFont != NULL) { pOldFont = pDC->SelectObject(CFont::FromHandle(m_hFont)); } else { pOldFont = m_bIsDlgControl ? (CFont*) pDC->SelectStockObject(DEFAULT_GUI_FONT) : pDC->SelectObject(&(GetGlobalData()->fontRegular)); } return pOldFont; } void CMFCHeaderCtrl::OnLButtonDown(UINT nFlags, CPoint point) { m_bIsMousePressed = TRUE; CHeaderCtrl::OnLButtonDown(nFlags, point); } void CMFCHeaderCtrl::OnLButtonUp(UINT nFlags, CPoint point) { m_bIsMousePressed = FALSE; CHeaderCtrl::OnLButtonUp(nFlags, point); } void CMFCHeaderCtrl::OnDrawSortArrow(CDC* pDC, CRect rectArrow) { ASSERT_VALID(pDC); ASSERT_VALID(this); CMFCVisualManager::GetInstance()->OnDrawHeaderCtrlSortArrow(this, pDC, rectArrow, m_bAscending); } void CMFCHeaderCtrl::EnableMultipleSort(BOOL bEnable) { ASSERT_VALID(this); if (m_bMultipleSort == bEnable) { return; } m_bMultipleSort = bEnable; if (!m_bMultipleSort) { m_mapColumnsStatus.RemoveAll(); if (GetSafeHwnd() != NULL) { RedrawWindow(); } } } int CMFCHeaderCtrl::GetSortColumn() const { ASSERT_VALID(this); if (m_bMultipleSort) { TRACE0("Call CMFCHeaderCtrl::GetColumnState for muliple sort\n"); ASSERT(FALSE); return -1; } int nCount = GetItemCount(); for (int i = 0; i < nCount; i++) { int nSortVal = 0; if (m_mapColumnsStatus.Lookup(i, nSortVal) && nSortVal != 0) { return i; } } return -1; } BOOL CMFCHeaderCtrl::IsAscending() const { ASSERT_VALID(this); if (m_bMultipleSort) { TRACE0("Call CMFCHeaderCtrl::GetColumnState for muliple sort\n"); ASSERT(FALSE); return FALSE; } int nCount = GetItemCount(); for (int i = 0; i < nCount; i++) { int nSortVal = 0; if (m_mapColumnsStatus.Lookup(i, nSortVal) && nSortVal != 0) { return nSortVal > 0; } } return FALSE; } int CMFCHeaderCtrl::GetColumnState(int iColumn) const { int nSortVal = 0; m_mapColumnsStatus.Lookup(iColumn, nSortVal); return nSortVal; } void CMFCHeaderCtrl::OnMouseMove(UINT nFlags, CPoint point) { if ((nFlags & MK_LBUTTON) == 0) { HDHITTESTINFO hdHitTestInfo; hdHitTestInfo.pt = point; int nPrevHighlightedItem = m_nHighlightedItem; m_nHighlightedItem = (int) SendMessage(HDM_HITTEST, 0, (LPARAM) &hdHitTestInfo); if ((hdHitTestInfo.flags & HHT_ONHEADER) == 0) { m_nHighlightedItem = -1; } if (!m_bTracked) { m_bTracked = TRUE; TRACKMOUSEEVENT trackmouseevent; trackmouseevent.cbSize = sizeof(trackmouseevent); trackmouseevent.dwFlags = TME_LEAVE; trackmouseevent.hwndTrack = GetSafeHwnd(); TrackMouseEvent(&trackmouseevent); } if (nPrevHighlightedItem != m_nHighlightedItem) { RedrawWindow(); } } CHeaderCtrl::OnMouseMove(nFlags, point); } void CMFCHeaderCtrl::OnMouseLeave() { m_bTracked = FALSE; if (m_nHighlightedItem >= 0) { m_nHighlightedItem = -1; RedrawWindow(); } } void CMFCHeaderCtrl::OnCancelMode() { CHeaderCtrl::OnCancelMode(); if (m_nHighlightedItem >= 0) { m_nHighlightedItem = -1; RedrawWindow(); } } int CMFCHeaderCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CHeaderCtrl::OnCreate(lpCreateStruct) == -1) return -1; CommonInit(); return 0; } void CMFCHeaderCtrl::PreSubclassWindow() { CommonInit(); CHeaderCtrl::PreSubclassWindow(); } void CMFCHeaderCtrl::CommonInit() { ASSERT_VALID(this); for (CWnd* pParentWnd = GetParent(); pParentWnd != NULL; pParentWnd = pParentWnd->GetParent()) { if (pParentWnd->IsKindOf(RUNTIME_CLASS(CDialog))) { m_bIsDlgControl = TRUE; break; } } } void CMFCHeaderCtrl::OnSetFont(CFont* pFont, BOOL bRedraw) { m_hFont = (HFONT)pFont->GetSafeHandle(); if (bRedraw) { Invalidate(); UpdateWindow(); } }
19.087287
134
0.689532
825126369
8c5491ac41eb6cbb41d2cb6f5ec1207bebae42bd
1,074
cpp
C++
Math/SieveOfEratosthenes/SieveOfEratosthenes.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Math/SieveOfEratosthenes/SieveOfEratosthenes.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
Math/SieveOfEratosthenes/SieveOfEratosthenes.cpp
PrachieNaik/DSA
083522bb3c8a0694adec1f2856d4d4cd0fb51722
[ "MIT" ]
null
null
null
/* Problem statement: Sieve of Eratosthenes Given a number N, calculate the prime numbers up to N using Sieve of Eratosthenes. Example 1: Input: N = 10 Output: 2 3 5 7 Explanation: Prime numbers less than equal to N are 2 3 5 and 7. Time Complexity: O(NloglogN) Auxiliary Space: O(N) */ void SieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize all entries it as true. A value in prime[i] will finally be false if i is Not a prime, else true. bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed,then it is a prime if (prime[p] == true) { // Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p^2 are already been marked. for (int i = p * p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for (int p = 2; p <= n; p++) if (prime[p]) cout << p << " "; }
23.866667
161
0.588454
PrachieNaik
8c66312d8fd432d3b74dd1d092ce79aeab2b76f1
782
cpp
C++
tic-tac-toe/services/PlayerService.cpp
abdul699/Machine_Coding
7e71397aa25a77d7d96c4117eda8b473af341d4a
[ "MIT" ]
null
null
null
tic-tac-toe/services/PlayerService.cpp
abdul699/Machine_Coding
7e71397aa25a77d7d96c4117eda8b473af341d4a
[ "MIT" ]
null
null
null
tic-tac-toe/services/PlayerService.cpp
abdul699/Machine_Coding
7e71397aa25a77d7d96c4117eda8b473af341d4a
[ "MIT" ]
null
null
null
#include "PlayerService.h" #include "../models/Board.h" bool PlayerService :: winCurrentPlayer(Board br) { for(int i=0; i<3; i++) { if(br.getValueAt(i, 0) == br.getValueAt(i, 1) && br.getValueAt(i, 1)== br.getValueAt(i, 2) && br.getValueAt(i, 1) != '-') return true; } // check column for(int i=0; i<3; i++) { if(br.getValueAt(0, i) == br.getValueAt(1, i) && br.getValueAt(1, i)== br.getValueAt(2, i) && br.getValueAt(1, i) != '-') return true; } // check diagonals if(br.getValueAt(0, 0) == br.getValueAt(1, 1) && br.getValueAt(1, 1) == br.getValueAt(2, 2) && br.getValueAt(0, 0) != '-') return true; if(br.getValueAt(0, 2) == br.getValueAt(1, 1) && br.getValueAt(1, 1) == br.getValueAt(2, 0) && br.getValueAt(1, 1) != '-') return true; return false; }
46
141
0.595908
abdul699
8c70c2a8ca9bb611b6577a084fdd2ddc57acb178
923
cpp
C++
test/dag_to_dot.cpp
mdsudara/percy
b593922b98c9c20fe0a3e4726e50401e54b9cb09
[ "MIT" ]
14
2018-03-10T21:50:20.000Z
2021-11-22T04:09:09.000Z
test/dag_to_dot.cpp
mdsudara/percy
b593922b98c9c20fe0a3e4726e50401e54b9cb09
[ "MIT" ]
3
2018-06-12T15:17:22.000Z
2019-06-20T12:00:45.000Z
test/dag_to_dot.cpp
mdsudara/percy
b593922b98c9c20fe0a3e4726e50401e54b9cb09
[ "MIT" ]
12
2018-03-10T17:02:07.000Z
2022-01-09T16:04:56.000Z
#include <percy/percy.hpp> #include <percy/io.hpp> #include <cstdio> #include <fstream> using namespace percy; /******************************************************************************* Verifies that the DAG to .dot conversion works properly. *******************************************************************************/ int main(void) { int ctr = 0; binary_dag g; unbounded_dag_generator ugen; ugen.reset(3); ctr = 0; while (ugen.next_dag(g)) { if (++ctr > 10) { break; } to_dot(g, std::cout); } ugen.reset(4); ctr = 0; while (ugen.next_dag(g)) { if (++ctr > 10) { break; } to_dot(g, std::cout); } ternary_dag h(5); h.add_vertex({ 0, 1, 2 }); h.add_vertex({ 4, 3, 1 }); h.add_vertex({ 5, 6, 0 }); h.add_vertex({ 7, 6, 1 }); to_dot(h, std::cout); return 0; }
20.511111
80
0.423619
mdsudara
8c7122d5ebd3acbefd3caeadd18c26e6092602a9
1,967
cc
C++
benchmark/rtti_benchmark.cc
royvandam/r
6450874cf442684f2129021e1b23cc16b5f7fed0
[ "MIT" ]
11
2020-12-03T21:57:34.000Z
2020-12-18T15:16:35.000Z
benchmark/rtti_benchmark.cc
royvandam/r
6450874cf442684f2129021e1b23cc16b5f7fed0
[ "MIT" ]
null
null
null
benchmark/rtti_benchmark.cc
royvandam/r
6450874cf442684f2129021e1b23cc16b5f7fed0
[ "MIT" ]
2
2020-12-04T12:41:43.000Z
2021-08-15T12:24:51.000Z
#include <benchmark/benchmark.h> #include <rtti.hh> struct GrandParent : virtual RTTI::Enable { RTTI_DECLARE_TYPEINFO(GrandParent); }; struct ParentA : virtual GrandParent { RTTI_DECLARE_TYPEINFO(ParentA, GrandParent); }; struct ParentB : virtual GrandParent { RTTI_DECLARE_TYPEINFO(ParentB, GrandParent); }; struct Child : ParentA , ParentB { RTTI_DECLARE_TYPEINFO(Child, ParentA, ParentB); }; struct InvalidCast {}; static void NativeDynamicCast(benchmark::State& state) { for (auto _ : state) { Child c; // Upcasting GrandParent* pg; benchmark::DoNotOptimize(pg = dynamic_cast<GrandParent*>(&c)); ParentA* pa; benchmark::DoNotOptimize(pa = dynamic_cast<ParentA*>(&c)); ParentB* pb; benchmark::DoNotOptimize(pb = dynamic_cast<ParentB*>(&c)); InvalidCast* invalid; benchmark::DoNotOptimize(invalid = dynamic_cast<InvalidCast*>(&c)); // Downcasting Child* pc; benchmark::DoNotOptimize(pc = dynamic_cast<Child*>(pg)); benchmark::DoNotOptimize(pc = dynamic_cast<Child*>(pa)); benchmark::DoNotOptimize(pc = dynamic_cast<Child*>(pb)); } } BENCHMARK(NativeDynamicCast); static void RttiDynamicCast(benchmark::State& state) { for (auto _ : state) { Child c; // Upcasting GrandParent* pg; benchmark::DoNotOptimize(pg = c.cast<GrandParent>()); ParentA* pa; benchmark::DoNotOptimize(pa = c.cast<ParentA>()); ParentB* pb; benchmark::DoNotOptimize(pb = c.cast<ParentB>()); InvalidCast* invalid; benchmark::DoNotOptimize(invalid = c.cast<InvalidCast>()); // Downcasting Child* pc; benchmark::DoNotOptimize(pc = pg->cast<Child>()); benchmark::DoNotOptimize(pc = pa->cast<Child>()); benchmark::DoNotOptimize(pc = pb->cast<Child>()); } } BENCHMARK(RttiDynamicCast); BENCHMARK_MAIN();
24.898734
75
0.635994
royvandam
8c71a3bbebe556870f5434f7c41c4258870c7e28
311
cpp
C++
sum_digit_using_recursion/main.cpp
narendrajethi220/Getting-Started
fd1b910228b6cfb30b82f50f52f6c32e79437ea3
[ "MIT" ]
null
null
null
sum_digit_using_recursion/main.cpp
narendrajethi220/Getting-Started
fd1b910228b6cfb30b82f50f52f6c32e79437ea3
[ "MIT" ]
null
null
null
sum_digit_using_recursion/main.cpp
narendrajethi220/Getting-Started
fd1b910228b6cfb30b82f50f52f6c32e79437ea3
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int s(int num,int sum) { if(num==0) return sum; sum+=num%10; return s(num/10,sum); } int main() { int digit; cout<<"Enter digit "; cin>>digit; int sum=0; cout<<"Sum of digit is "<<s(digit,sum); return 0; }
15.55
44
0.5209
narendrajethi220
8c726e57467af13f972449e486392ade7c675836
1,896
cpp
C++
tests/network/http/websocket_test.cpp
jmjatlanta/bitshares-fc
8b571580c8646c487def1b4b517401e58fa82c9e
[ "Zlib", "Apache-2.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
2
2020-08-20T01:13:55.000Z
2020-08-20T01:24:06.000Z
tests/network/http/websocket_test.cpp
jmjatlanta/bitshares-fc
8b571580c8646c487def1b4b517401e58fa82c9e
[ "Zlib", "Apache-2.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
tests/network/http/websocket_test.cpp
jmjatlanta/bitshares-fc
8b571580c8646c487def1b4b517401e58fa82c9e
[ "Zlib", "Apache-2.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#include <boost/test/unit_test.hpp> #include <fc/network/http/websocket.hpp> #include <iostream> BOOST_AUTO_TEST_SUITE(fc_network) BOOST_AUTO_TEST_CASE(websocket_test) { fc::http::websocket_client client; fc::http::websocket_connection_ptr s_conn, c_conn; int port; { fc::http::websocket_server server; server.on_connection([&]( const fc::http::websocket_connection_ptr& c ){ s_conn = c; c->on_message_handler([&](const std::string& s){ c->send_message("echo: " + s); }); }); server.listen( 0 ); port = server.get_listening_port(); server.start_accept(); std::string echo; c_conn = client.connect( "ws://localhost:" + fc::to_string(port) ); c_conn->on_message_handler([&](const std::string& s){ echo = s; }); c_conn->send_message( "hello world" ); fc::usleep( fc::milliseconds(100) ); BOOST_CHECK_EQUAL("echo: hello world", echo); c_conn->send_message( "again" ); fc::usleep( fc::milliseconds(100) ); BOOST_CHECK_EQUAL("echo: again", echo); s_conn->close(0, "test"); fc::usleep( fc::milliseconds(100) ); BOOST_CHECK_THROW(c_conn->send_message( "again" ), fc::exception); c_conn = client.connect( "ws://localhost:" + fc::to_string(port) ); c_conn->on_message_handler([&](const std::string& s){ echo = s; }); c_conn->send_message( "hello world" ); fc::usleep( fc::milliseconds(100) ); BOOST_CHECK_EQUAL("echo: hello world", echo); } BOOST_CHECK_THROW(c_conn->send_message( "again" ), fc::assert_exception); BOOST_CHECK_THROW(client.connect( "ws://localhost:" + fc::to_string(port) ), fc::exception); } BOOST_AUTO_TEST_SUITE_END()
32.689655
96
0.582806
jmjatlanta
8c7754958d70ba7980e976379ed4c3d0d4bc5712
1,505
hh
C++
primer/examples/factory.hh
CaffeineViking/concepts-primer
041cec40fa4a25cd954ce91da6d9d10ee31499a3
[ "MIT" ]
17
2019-05-01T21:49:43.000Z
2022-02-25T06:50:47.000Z
primer/examples/factory.hh
CaffeineViking/concepts-primer
041cec40fa4a25cd954ce91da6d9d10ee31499a3
[ "MIT" ]
null
null
null
primer/examples/factory.hh
CaffeineViking/concepts-primer
041cec40fa4a25cd954ce91da6d9d10ee31499a3
[ "MIT" ]
null
null
null
#ifndef FACTORY_HH #define FACTORY_HH #include <type_traits> #if false struct NumberFactory { enum { INTEGRAL, FLOATING } number_type; template<typename T, typename = std::enable_if< std::is_integral_v<T>>> NumberFactory(T) : number_type { INTEGRAL } {} int create_number() const; template<typename T, typename = std::enable_if< std::is_floating_point_v<T>>> NumberFactory(T) : number_type { FLOATING } {} }; #endif #if false struct NumberFactory { enum { INTEGRAL, FLOATING } number_type; template<int> struct dummy { dummy(int) {} }; template<typename T, typename = std::enable_if< std::is_integral_v<T>>> NumberFactory(T, dummy<0>=0) : number_type { INTEGRAL } {} int create_number() const; template<typename T, typename = std::enable_if< std::is_floating_point_v<T>>> NumberFactory(T, dummy<1>=0) : number_type { FLOATING } {} }; #endif #if true struct NumberFactory { enum { INTEGRAL, FLOATING } number_type; template<typename T> requires std::is_integral_v<T> NumberFactory(T) : number_type { INTEGRAL } {} int create_number() const; template<typename T> requires std::is_floating_point_v<T> NumberFactory(T) : number_type { FLOATING } {} }; #endif int NumberFactory::create_number() const { if (number_type == INTEGRAL) return 42; else return 0xDEADBEEF; } #endif
20.616438
62
0.628571
CaffeineViking
8c779250ea01a82b13be6db32fe4149db75a62a3
1,737
cpp
C++
Sandbox/src/Sandbox3D.cpp
Kingalidj/Atlas
a4a6a1315b18bd72637702e76d148de912377482
[ "Apache-2.0" ]
3
2021-07-29T19:15:46.000Z
2021-09-28T15:29:57.000Z
Sandbox/src/Sandbox3D.cpp
Kingalidj/Atlas
a4a6a1315b18bd72637702e76d148de912377482
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Sandbox3D.cpp
Kingalidj/Atlas
a4a6a1315b18bd72637702e76d148de912377482
[ "Apache-2.0" ]
null
null
null
#include "Sandbox3D.h" #include "ImGui/imgui.h" #include <memory> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Atlas/Renderer/Mesh.h" using namespace Atlas; Sandbox3D::Sandbox3D() : Layer("Sandbox3D") {} void Sandbox3D::OnAttach() { Ref<Scene> scene = Application::GetActiveScene(); scene->SetActiveCamera(PerspectiveCameraController(1.0f)); scene->LoadMesh("assets/Models/Dragon.obj"); scene->LoadMesh("assets/Models/Box.obj"); Mesh& mesh = scene->LoadMesh("assets/Models/Box.obj"); mesh.AddTexture(Texture2D::Create("assets/Textures/Box_Diffuse.png"), Utils::TextureType::DIFFUSE); mesh.AddTexture(Texture2D::Create("assets/Textures/Box_Specular.png"), Utils::TextureType::SPECULAR); //Mesh& backpack = scene->LoadMesh("assets/Models/Backpack.obj"); //backpack.AddTexture(Texture2D::Create("assets/Textures/Backpack_Diffuse.jpg", false), Utils::TextureType::DIFFUSE); //backpack.AddTexture(Texture2D::Create("assets/Textures/Backpack_Specular.jpg", false), Utils::TextureType::SPECULAR); ECS::Entity lightEntity = scene->CreateEntity("Point light"); scene->CreateComponent<PointLightComponent>(lightEntity); scene->CreateComponent<TransformComponent>(lightEntity); ECS::Entity dirLight = scene->CreateEntity("Dir Light"); scene->CreateComponent<DirLightComponent>(dirLight); scene->CreateComponent<TransformComponent>(dirLight, glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(-2.0f, 1.0f, -4.0f), glm::vec3(1, 1, 1)); } void Sandbox3D::OnDetach() { } void Sandbox3D::OnUpdate(Timestep ts) { ATL_PROFILE_FUNCTION(); } void Sandbox3D::OnImGuiRender() { ATL_PROFILE_FUNCTION(); } void Sandbox3D::OnEvent(Event& e) { }
29.948276
135
0.724237
Kingalidj
8c827a3acfa11b8d4421ffcd52b263ad714ba17e
504
cpp
C++
a17/dispatch/topic.cpp
SRI-IPS/general-tools
b3113cbcf83c3a430c630d050d1b96e722dfb043
[ "BSD-3-Clause" ]
null
null
null
a17/dispatch/topic.cpp
SRI-IPS/general-tools
b3113cbcf83c3a430c630d050d1b96e722dfb043
[ "BSD-3-Clause" ]
null
null
null
a17/dispatch/topic.cpp
SRI-IPS/general-tools
b3113cbcf83c3a430c630d050d1b96e722dfb043
[ "BSD-3-Clause" ]
null
null
null
#include "topic.h" namespace a17 { namespace dispatch { std::string Topic::str() const { auto str = std::string{""}; if (!device_name.empty()) { str.append(device_name); } if (!node_name.empty()) { if (!str.empty() && str.back() != '/') { str.append("/"); } str.append(node_name); } if (!topic.empty()) { if (!str.empty() && str.back() != '/') { str.append("/"); } str.append(topic); } return str; } } // namespace dispatch } // namespace a17
18
44
0.531746
SRI-IPS
8c83556c0aa9a4d923a0b62fae6c8681b0504e1b
429
hpp
C++
src/wire/wire2lua/generate_options.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/wire2lua/generate_options.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/wire2lua/generate_options.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * generate_options.hpp * * Created on: May 13, 2016 * Author: zmij */ #ifndef WIRE_WIRE2LUA_GENERATE_OPTIONS_HPP_ #define WIRE_WIRE2LUA_GENERATE_OPTIONS_HPP_ #include <string> namespace wire { namespace idl { namespace lua { struct generate_options { ::std::string target_file; }; } /* namespace lua */ } /* namespace idl */ } /* namespace wire */ #endif /* WIRE_WIRE2LUA_GENERATE_OPTIONS_HPP_ */
14.793103
48
0.694639
zmij
8c84768841166dad2649cf110ad5c9cd34c08bf9
1,507
cpp
C++
ceres_test/curve_fitting.cpp
HeadReaper-hc/mystudy-and-test
4220093304592237a0d9ab56d610206ded89ffe7
[ "MIT" ]
null
null
null
ceres_test/curve_fitting.cpp
HeadReaper-hc/mystudy-and-test
4220093304592237a0d9ab56d610206ded89ffe7
[ "MIT" ]
null
null
null
ceres_test/curve_fitting.cpp
HeadReaper-hc/mystudy-and-test
4220093304592237a0d9ab56d610206ded89ffe7
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <math.h> #include <ceres/ceres.h> #include <vector> using namespace std; using namespace ceres; struct CostFunctor { CostFunctor(double observed_x , double observed_y):_observed_x(observed_x),_observed_y(observed_y){} template <typename T> bool operator()(const T* const a, T* residual) const { residual[0] = T(_observed_y) - ceres::exp(a[0]*_observed_x); return true; } double _observed_x; double _observed_y; }; int main(int argc , char** argv){ double a_truth=1.0; vector<double> observed_x; vector<double> observed_y; for(int i=0;i<100;i++) { observed_x.push_back(0.01*i); } for(int i=0;i<observed_x.size();i++) { observed_y.push_back(ceres::exp(observed_x[i]*a_truth)+double(rand())/RAND_MAX/5); cout<<observed_y[i]<<endl; } double a=0; Problem problem; for (int i = 0; i < observed_x.size(); i++) { CostFunction* cost_function = new AutoDiffCostFunction<CostFunctor, 1, 1>( new CostFunctor(observed_x[i],observed_y[i])); problem.AddResidualBlock(cost_function, NULL, &a); } Solver::Options options; options.minimizer_progress_to_stdout = true; Solver::Summary summary; Solve(options, &problem, &summary); std::cout << summary.BriefReport() << "\n"; std::cout << "a : " << a_truth << " -> " << a << "\n"; return 0; }
25.116667
103
0.606503
HeadReaper-hc
8c886a2a571dbcd71d63c516583be8dfd082b872
2,612
hpp
C++
include/utility/EventType.hpp
benhj/KnoxCrypt
41d2c2518fb42728a5a07f6de43682bf881ec77e
[ "BSD-3-Clause" ]
21
2016-08-24T04:48:43.000Z
2021-12-21T18:41:00.000Z
include/utility/EventType.hpp
benhj/KnoxCrypt
41d2c2518fb42728a5a07f6de43682bf881ec77e
[ "BSD-3-Clause" ]
2
2016-02-16T16:20:12.000Z
2016-02-27T16:51:14.000Z
include/utility/EventType.hpp
benhj/KnoxCrypt
41d2c2518fb42728a5a07f6de43682bf881ec77e
[ "BSD-3-Clause" ]
3
2016-09-15T17:29:58.000Z
2021-04-26T21:59:07.000Z
/* Copyright (c) <2014-2015>, <BenHJ> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once /// used to notifying when certain things happen namespace knoxcrypt { enum class EventType { KeyGenBegin, // before key gen is started KeyGenEnd, // when key gen is finished BigCipherBuildBegin, // before building big cipher BigCipherBuildEnd, // when building finished CipherBuildUpdate, // building progress notification ImageBuildStart, // start of image building process ImageBuildEnd, // end of image building process ImageBuildUpdate, // image building process IVWriteEvent, // IV is about to be written RoundsWriteEvent, // enc. rounds about to be written PhysicalExtractBegin, // physical extract utility start PhysicalExtractEnd // physical extract utility end }; }
52.24
85
0.672665
benhj
8c8ca008978b8807ba1c0c050f2526089ea5cf36
7,096
hpp
C++
include/IteratorRecognition/Analysis/GraphUpdater.hpp
robcasloz/IteratorRecognition
fa1a1e67c36cde3639ac40528228ae85e54e3b13
[ "MIT" ]
null
null
null
include/IteratorRecognition/Analysis/GraphUpdater.hpp
robcasloz/IteratorRecognition
fa1a1e67c36cde3639ac40528228ae85e54e3b13
[ "MIT" ]
6
2019-05-29T21:11:03.000Z
2021-07-01T10:47:02.000Z
include/IteratorRecognition/Analysis/GraphUpdater.hpp
robcasloz/IteratorRecognition
fa1a1e67c36cde3639ac40528228ae85e54e3b13
[ "MIT" ]
1
2019-05-13T11:55:39.000Z
2019-05-13T11:55:39.000Z
// // // #pragma once #include "IteratorRecognition/Config.hpp" #include "IteratorRecognition/Analysis/IteratorValueTracking.hpp" #include "IteratorRecognition/Support/Utils/StringConversion.hpp" #include "Pedigree/Analysis/Hazards.hpp" #include "llvm/Support/JSON.h" // using json::Value // using json::Object #include "llvm/ADT/GraphTraits.h" // using llvm::GraphTraits #include "llvm/Support/Debug.h" // using LLVM_DEBUG macro // using llvm::dbgs #include <vector> // using std::vector #include <tuple> // using std::tie #include <utility> // using std::pair // using std::make_pair #include <memory> // using std::unique_ptr // using std::make_unique namespace iteratorrecognition { struct UpdateAction { virtual void update() = 0; virtual llvm::json::Value toJSON() const = 0; }; inline void ExecuteAction(UpdateAction &UA) { UA.update(); } using ActionQueueT = std::vector<std::unique_ptr<UpdateAction>>; // template <typename T> class GraphUpdate : public UpdateAction { T &underlying() { return static_cast<T &>(*this); } T const &underlying() const { return static_cast<T const &>(*this); } public: void update() override { this->underlying().performUpdate(); } llvm::json::Value toJSON() const override { return this->underlying().convertToJSON(); } }; template <typename T> class GraphNoop : public GraphUpdate<GraphNoop<T>> { T Src, Dst; public: GraphNoop(T Src, T Dst) : Src(Src), Dst(Dst) {} GraphNoop(const GraphNoop &) = default; void performUpdate() {} llvm::json::Value convertToJSON() const { llvm::json::Object mapping; // TODO this maybe needs to be restricted with has_unit_t mapping["src"] = strconv::to_string(*Src->unit()); mapping["dst"] = strconv::to_string(*Dst->unit()); mapping["remark"] = "unknown relation"; return std::move(mapping); } }; template <typename T, typename InfoT> class GraphEdgeConnect : public GraphUpdate<GraphEdgeConnect<T, InfoT>> { T Src, Dst; InfoT Info; public: GraphEdgeConnect(T Src, T Dst, InfoT Info) : Src(Src), Dst(Dst), Info(Info) {} GraphEdgeConnect(const GraphEdgeConnect &) = default; void performUpdate() { Src->addDependentNode(Dst, Info); } llvm::json::Value convertToJSON() const { llvm::json::Object mapping; // TODO this maybe needs to be restricted with has_unit_t mapping["src"] = strconv::to_string(*Src->unit()); mapping["dst"] = strconv::to_string(*Dst->unit()); mapping["remark"] = "connect"; return std::move(mapping); } }; template <typename T> class GraphEdgeDisconnect : public GraphUpdate<GraphEdgeDisconnect<T>> { T Src, Dst; public: GraphEdgeDisconnect(T Src, T Dst) : Src(Src), Dst(Dst) {} GraphEdgeDisconnect(const GraphEdgeDisconnect &) = default; void performUpdate() { Src->removeDependentNode(Dst); } llvm::json::Value convertToJSON() const { llvm::json::Object mapping; // TODO this maybe needs to be restricted with has_unit_t mapping["src"] = strconv::to_string(*Src->unit()); mapping["dst"] = strconv::to_string(*Dst->unit()); mapping["remark"] = "disconnect"; return std::move(mapping); } }; template <typename T, typename InfoT> class GraphEdgeInfoUpdate : public GraphUpdate<GraphEdgeInfoUpdate<T, InfoT>> { T Src, Dst; InfoT Info; public: GraphEdgeInfoUpdate(T Src, T Dst, InfoT Info) : Src(Src), Dst(Dst), Info(Info) {} GraphEdgeInfoUpdate(const GraphEdgeInfoUpdate &) = default; void performUpdate() { Src->setEdgeInfo(Dst, Info); } llvm::json::Value convertToJSON() const { llvm::json::Object mapping; // TODO this maybe needs to be restricted with has_unit_t mapping["src"] = strconv::to_string(*Src->unit()); mapping["dst"] = strconv::to_string(*Dst->unit()); mapping["remark"] = "update info"; return std::move(mapping); } }; // template <typename GraphT> class IteratorVarianceGraphUpdateGenerator { GraphT &G; IteratorVarianceAnalyzer &IVA; using GraphNodeT = typename GraphT::NodeType; using GraphNodeRefT = typename llvm::GraphTraits<GraphT *>::NodeRef; using UnitT = typename GraphNodeT::UnitType; using EdgeInfoT = typename GraphNodeT::EdgeInfoType::value_type; using UpdateActionPairT = std::pair<std::unique_ptr<UpdateAction>, std::unique_ptr<UpdateAction>>; decltype(auto) createConnect(GraphNodeRefT Src, GraphNodeRefT Dst, EdgeInfoT Info) { return std::make_pair( std::make_unique<GraphEdgeConnect<GraphNodeRefT, EdgeInfoT>>(Src, Dst, Info), std::make_unique<GraphEdgeDisconnect<GraphNodeRefT>>(Src, Dst)); } decltype(auto) createDisconnect(GraphNodeRefT Src, GraphNodeRefT Dst, EdgeInfoT Info) { return std::make_pair( std::make_unique<GraphEdgeDisconnect<GraphNodeRefT>>(Src, Dst), std::make_unique<GraphEdgeConnect<GraphNodeRefT, EdgeInfoT>>(Src, Dst, Info)); } decltype(auto) createUpdate(GraphNodeRefT Src, GraphNodeRefT Dst, EdgeInfoT NewInfo, EdgeInfoT OldInfo) { return std::make_pair( std::make_unique<GraphEdgeInfoUpdate<GraphNodeRefT, EdgeInfoT>>( Src, Dst, NewInfo), std::make_unique<GraphEdgeInfoUpdate<GraphNodeRefT, EdgeInfoT>>( Src, Dst, OldInfo)); } public: IteratorVarianceGraphUpdateGenerator(GraphT &G, IteratorVarianceAnalyzer &IVA) : G(G), IVA(IVA) {} decltype(auto) create(UnitT Src, UnitT Dst) { auto srcIV = IVA.getOrInsertVariance(Src); auto dstIV = IVA.getOrInsertVariance(Dst); auto *srcNode = G.getNode(Src); auto *dstNode = G.getNode(Dst); UpdateActionPairT actions; if (srcIV == IteratorVarianceValue::Unknown || dstIV == IteratorVarianceValue::Unknown) { actions.first = std::make_unique<GraphNoop<GraphNodeRefT>>(srcNode, dstNode); actions.second = std::make_unique<GraphNoop<GraphNodeRefT>>(srcNode, dstNode); } else if (srcIV == IteratorVarianceValue::Variant || dstIV == IteratorVarianceValue::Variant) { if (auto infoOrEmpty = srcNode->getEdgeInfo(dstNode)) { if (auto info = *infoOrEmpty) { auto memInfo = info & pedigree::DO_Memory; auto newInfo = info; newInfo.reset(pedigree::DO_Memory); if (memInfo) { if (newInfo) { actions = createUpdate(srcNode, dstNode, newInfo, info); } else { actions = createDisconnect(srcNode, dstNode, memInfo); } } } } } else if (srcIV == IteratorVarianceValue::Invariant || dstIV == IteratorVarianceValue::Invariant) { if (!srcNode->hasEdgeWith(dstNode)) { if (auto newInfo = pedigree::DetermineHazard(Src, Dst)) { actions = createConnect(srcNode, dstNode, newInfo); } } } return actions; } }; } // namespace iteratorrecognition
28.963265
80
0.654594
robcasloz
8c8fe7c6ec689f8dfdf0c4748e1c408ac3949bad
3,153
cpp
C++
src/model/WxToolbarPanel.cpp
xzrunner/easyone
c6cc33585a3a5affd44e51938a1bae5b146ab7af
[ "MIT" ]
1
2020-07-07T07:14:01.000Z
2020-07-07T07:14:01.000Z
src/model/WxToolbarPanel.cpp
xzrunner/easyone
c6cc33585a3a5affd44e51938a1bae5b146ab7af
[ "MIT" ]
null
null
null
src/model/WxToolbarPanel.cpp
xzrunner/easyone
c6cc33585a3a5affd44e51938a1bae5b146ab7af
[ "MIT" ]
null
null
null
#include "model/WxToolbarPanel.h" #ifdef MODULE_MODEL #include "model/WxStagePage.h" #include <ee0/SubjectMgr.h> #include <ee0/WxImageVList.h> #include <ee0/WxLibraryItem.h> #include <ee3/WxSkeletalTreeCtrl.h> #include <node0/SceneNode.h> #include <node3/CompModelInst.h> #include <model/Model.h> #include <model/ModelInstance.h> #include <wx/radiobox.h> #include <wx/notebook.h> namespace eone { namespace model { WxToolbarPanel::WxToolbarPanel(wxWindow* parent, WxStagePage* stage) : wxPanel(parent) , m_stage(stage) { InitLayout(); } void WxToolbarPanel::LoadModel(const ::model::Model& model) { if (!model.ext) { return; } if (model.ext->Type() == ::model::EXT_SKELETAL) { auto& skeletal = *static_cast<::model::SkeletalAnim*>(model.ext.get()); m_tree_page->m_tree->LoadFromSkeletal(skeletal); } m_texture_page->Clear(); for (auto& tex : model.textures) { if (!tex.second) { continue; } auto item = std::make_shared<ee0::WxLibraryItem>(tex.first); m_texture_page->Insert(item); } } void WxToolbarPanel::InitLayout() { wxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); m_notebook = new wxNotebook(this, wxID_ANY); // edit { m_edit_page = new wxPanel(m_notebook); wxArrayString choices; choices.Add("Rotate Joint"); choices.Add("Translate Joint"); choices.Add("Skeletal IK"); choices.Add("Mesh IK"); auto radio = new wxRadioBox(m_edit_page, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, choices, 1, wxRA_SPECIFY_COLS); Connect(radio->GetId(), wxEVT_COMMAND_RADIOBOX_SELECTED, wxCommandEventHandler(WxToolbarPanel::OnChangeEditType)); auto sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(radio); m_edit_page->SetSizer(sizer); m_notebook->AddPage(m_edit_page, "Edit"); } // tree { m_tree_page = new WxTreeScrolled(m_notebook, m_stage->GetSubjectMgr()); m_notebook->AddPage(m_tree_page, "Tree"); } // texture { m_texture_page = new ee0::WxImageVList(m_notebook, ""); m_notebook->AddPage(m_texture_page, "Textures"); } top_sizer->Add(m_notebook, 1, wxEXPAND); SetSizer(top_sizer); } void WxToolbarPanel::OnChangeEditType(wxCommandEvent& event) { int sel = event.GetSelection(); switch (sel) { case 0: m_stage->SetEditOp(WxStagePage::OP_ROTATE_JOINT); break; case 1: m_stage->SetEditOp(WxStagePage::OP_TRANSLATE_JOINT); break; case 2: m_stage->SetEditOp(WxStagePage::OP_SKELETAL_IK); break; case 3: m_stage->SetEditOp(WxStagePage::OP_MESH_IK); break; } m_stage->GetSubjectMgr()->NotifyObservers(ee0::MSG_SET_CANVAS_DIRTY); } ////////////////////////////////////////////////////////////////////////// // class WxToolbarPanel::WxTreeScrolled ////////////////////////////////////////////////////////////////////////// WxToolbarPanel::WxTreeScrolled::WxTreeScrolled(wxWindow* parent, const ee0::SubjectMgrPtr& sub_mgr) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(300, 800)) { SetScrollbars(0, 1, 0, 10, 0, 0); auto sizer = new wxBoxSizer(wxVERTICAL); m_tree = new ee3::WxSkeletalTreeCtrl(this, sub_mgr); sizer->Add(m_tree, 1, wxEXPAND); SetSizer(sizer); } } } #endif // MODULE_MODEL
23.183824
99
0.68633
xzrunner
8c93b6455389186169e1ba624b7979eefda443b9
1,221
cpp
C++
Contest/Qualification Round Oct 2010/dinner.cpp
felikjunvianto/kfile-usaco-submissions
d4afdc0cbde7e19f09afc70c4b02d4bc5992696d
[ "MIT" ]
null
null
null
Contest/Qualification Round Oct 2010/dinner.cpp
felikjunvianto/kfile-usaco-submissions
d4afdc0cbde7e19f09afc70c4b02d4bc5992696d
[ "MIT" ]
null
null
null
Contest/Qualification Round Oct 2010/dinner.cpp
felikjunvianto/kfile-usaco-submissions
d4afdc0cbde7e19f09afc70c4b02d4bc5992696d
[ "MIT" ]
null
null
null
/* PROG: dinner LANG: C++ ID: felikju1 */ #include <cstdio> #include <iostream> #include <string> #include <cstring> #include <utility> #include <algorithm> #define fi first #define se second using namespace std; pair < long long, long long > sapi[1100]; pair < long long, long long > meja[1100]; bool duduk[1100]; int n,m,x,y,z; int hungry[1100],panjang; int main() { freopen("dinner.in","r",stdin); freopen("dinner.out","w",stdout); scanf("%lld %lld",&n,&m); for(x=1;x<=n;x++) scanf("%lld %lld",&sapi[x].fi,&sapi[x].se); for(x=1;x<=m;x++) scanf("%lld %lld",&meja[x].fi,&meja[x].se); memset(duduk,false,sizeof(duduk)); for(y=1;y<=m;y++) { long long min = 8000000000000LL; int siapa=1001; for(x=1;x<=n;x++) if(!duduk[x]) { long long temp = (long long)((meja[y].fi-sapi[x].fi)*(meja[y].fi-sapi[x].fi) +(meja[y].se-sapi[x].se)*(meja[y].se-sapi[x].se)); if(temp<min) { min=temp; siapa=x; } } duduk[siapa]=true; } panjang=0; for(x=1;x<=n;x++) if(!duduk[x]) { panjang++; hungry[panjang]=x; } if(panjang==0) printf("0\n"); else for(x=1;x<=panjang;x++) printf("%d\n",hungry[x]); fclose(stdin); fclose(stdout); return 0; }
17.442857
79
0.579853
felikjunvianto
8c96b6b8d78cc49c8dc3ca8b1b93021797ce1c74
1,817
cpp
C++
lib/protobuf/qml/server_method.cpp
pauldotknopf/protobuf-qml
e10f46567344738563140e8f06d5a2569b961d06
[ "MIT" ]
56
2015-05-14T16:00:43.000Z
2022-02-11T20:25:36.000Z
lib/protobuf/qml/server_method.cpp
pauldotknopf/protobuf-qml
e10f46567344738563140e8f06d5a2569b961d06
[ "MIT" ]
19
2015-05-11T14:50:33.000Z
2018-09-06T05:45:34.000Z
lib/protobuf/qml/server_method.cpp
pauldotknopf/protobuf-qml
e10f46567344738563140e8f06d5a2569b961d06
[ "MIT" ]
16
2015-10-29T13:25:48.000Z
2021-06-30T18:34:32.000Z
#include "protobuf/qml/server_method.h" #include <private/qv4arrayobject_p.h> #include <private/qv4scopedvalue_p.h> using namespace QV4; namespace protobuf { namespace qml { void ServerMethodHolder::respond(QQmlV4Function* args) { if (!impl()) { qWarning() << "Server method is not initialized."; args->setReturnValue(Encode(false)); return; } auto v4 = args->v4engine(); Scope scope(v4); ScopedValue tag(scope, (*args)[0]); if (!tag || !tag->isNumber()) { qWarning() << "Invalid tag argument"; args->setReturnValue(Encode(false)); return; } ScopedArrayObject data(scope, (*args)[1]); if (!data) { qWarning() << "Invalid data argument"; args->setReturnValue(Encode(false)); return; } auto msg = write_descriptor()->v4()->jsValueToMessage(v4, *data); auto res = impl()->respond(tag->toInt32(), std::move(msg)); args->setReturnValue(Encode(res)); } void RpcService::set_server(RpcServer* v) { if (server_ != v) { if (started()) { qWarning() << "Cannot change server once started."; return; } if (v && v->has_started()) { qWarning() << "Cannot set running server to a service."; return; } if (server_) { for (auto& c : connections_) { disconnect(c); } connections_.clear(); } if (v) { Q_ASSERT(connections_.empty()); connections_.push_back(connect(v, &RpcServer::starting, this, [this, v] { v->registerService(this); })); connections_.push_back(connect(v, &RpcServer::started, this, [this, v] { for (auto m : methods_) { m->startProcessing(); } })); } server_ = v; serverChanged(); } } bool RpcService::started() const { return server_ && server_->has_started(); } } }
25.236111
79
0.598239
pauldotknopf
8c9bd8c59c2be336d4bf321d13f63e4b09e0ab4b
1,824
hh
C++
srcs/algorithm/Simulation.hh
JeremyPouyet/equation_finder
bac228b7aeb720c083c4d673545573b65e42e784
[ "BSD-3-Clause" ]
null
null
null
srcs/algorithm/Simulation.hh
JeremyPouyet/equation_finder
bac228b7aeb720c083c4d673545573b65e42e784
[ "BSD-3-Clause" ]
null
null
null
srcs/algorithm/Simulation.hh
JeremyPouyet/equation_finder
bac228b7aeb720c083c4d673545573b65e42e784
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <string> #include <iostream> #include "AProblem.hh" #include "Config.hh" #include "Population.hh" #include "Display.hpp" #include "Chrono.hpp" #include "DynamicLoader.hpp" class Simulation { public: Simulation(); /** * Initialise the simulation * @param ac, command line parameters number * @param av, command line parameters * @return an error or success code that says if the initialisation succeeded */ int initialise(int ac, char **av); /** * run the simulation */ void run(); /** * properly destroy the simulation */ ~Simulation(); private: /** * Try to Solve the current Problem * @param population, chromosome population * @return whether the problem is solve or not */ bool solve(Population &population); /** * print informations about the population * @param population, population to get data from */ inline void printResume(const Population &population) const; /** * Initialise user data * @return whether the initialisation succeed */ bool userInitialisation(); /** * Initialise configuration file * @param ac, command line parameters number * @param av, command line parameters * @return an error or success code that says if the initialisation succeeded */ int configInitialisation(int ac, char **av); // problem to solve Problem *_problem = NULL; // display object Display &_display = Display::getInstance(); // Timer to time the simulation time Chrono _timer; // object that loads a shared library into the framework DynamicLoader<Problem> _problemLoader; // index of the current generation unsigned int _currentGeneration = 1; };
25.333333
82
0.648026
JeremyPouyet
8c9c094c9a7247ac578d2f9050891faa0a715e85
1,364
cpp
C++
brian2/codegen/runtime/weave_rt/templates/lumped_variable.cpp
divyashivaram/brian2
ac086e478efa50be772c6cee55b52b43018bc77a
[ "BSD-2-Clause" ]
1
2019-12-25T16:33:37.000Z
2019-12-25T16:33:37.000Z
brian2/codegen/runtime/weave_rt/templates/lumped_variable.cpp
divyashivaram/brian2
ac086e478efa50be772c6cee55b52b43018bc77a
[ "BSD-2-Clause" ]
null
null
null
brian2/codegen/runtime/weave_rt/templates/lumped_variable.cpp
divyashivaram/brian2
ac086e478efa50be772c6cee55b52b43018bc77a
[ "BSD-2-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// //// MAIN CODE ///////////////////////////////////////////////////////////// {% macro main() %} // USES_VARIABLES { _synaptic_post, _synaptic_pre, _num_target_neurons } ////// HANDLE DENORMALS /// {% for line in denormals_code_lines %} {{line}} {% endfor %} ////// HASH DEFINES /////// {% for line in hashdefine_lines %} {{line}} {% endfor %} ///// POINTERS //////////// {% for line in pointers_lines %} {{line}} {% endfor %} //// MAIN CODE //////////// // Set all the target variable values to zero for (int _target_idx=0; _target_idx<_num_target_neurons; _target_idx++) _ptr{{_target_var_array}}[_target_idx] = 0.0; // A bit confusing: The "neuron" index here refers to the synapses! for(int _idx=0; _idx<_num_synaptic_post; _idx++) { const int _postsynaptic_idx = _synaptic_post[_idx]; const int _presynaptic_idx = _synaptic_pre[_idx]; {% for line in code_lines %} {{line}} {% endfor %} _ptr{{_target_var_array}}[_postsynaptic_idx] += _synaptic_var; } {% endmacro %} //////////////////////////////////////////////////////////////////////////// //// SUPPORT CODE ////////////////////////////////////////////////////////// {% macro support_code() %} {% for line in support_code_lines %} {{line}} {% endfor %} {% endmacro %}
27.836735
76
0.502933
divyashivaram
8ca3aba8c8312b563ce5db9432626ec50cbf5601
21,269
cpp
C++
exploitimpl.cpp
smalltong02/Bruce-Ma
2ee9455635af9f0300f53781382de88d3ef99003
[ "MIT" ]
1
2021-06-22T04:41:41.000Z
2021-06-22T04:41:41.000Z
exploitimpl.cpp
smalltong02/Bruce-Ma
2ee9455635af9f0300f53781382de88d3ef99003
[ "MIT" ]
1
2021-02-23T17:45:30.000Z
2021-02-23T17:45:30.000Z
exploitimpl.cpp
smalltong02/Bruce-Ma
2ee9455635af9f0300f53781382de88d3ef99003
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "hookimpl.h" #include "HookImplementObject.h" #include "utils.h" #include "exploitmpl.h" #include "UniversalObject.h" using namespace cchips; processing_status WINAPI CHookImplementObject::detour_virtualAlloc(detour_node* node, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_virtualAllocEx(CHookImplementObject::detour_node* node, HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { EXPLOIT_POST_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() if (flAllocationType != MEM_COMMIT) break; // we only check it when target process is current process // this might fix mantis: 0492346 if (hProcess != GetCurrentProcess()) break; if (flProtect != PAGE_EXECUTE_READ && flProtect != PAGE_EXECUTE_READWRITE) break; std::vector<PVOID> frame_chains; WalkFrameCurrentChain(frame_chains); if (!frame_chains.size()) return processing_continue; for (const auto& chain : frame_chains) { if (CheckExploitFuncs::AddressInModule(reinterpret_cast<ULONG_PTR>(chain), node->hook_implement_object->GetSpecialModuleInfo().m_self_info)) { continue; } if (CheckExploitFuncs::AddressInModule(reinterpret_cast<ULONG_PTR>(chain), node->hook_implement_object->GetSpecialModuleInfo().m_vbe_info)) { if (CheckExploitFuncs::CheckStackInstruction(reinterpret_cast<ULONG_PTR>(chain))) { exploit_log("\"API\": \"{}\", \"reason\": {}", node->function->GetName(), CheckExploitFuncs::e_reason_vbe_suspicious); } } else { std::shared_ptr<CObObject> return_ptr = node->function->GetIdentifier(SI_RETURN); if (!return_ptr) return processing_continue; std::any anyvalue = return_ptr->GetValue(static_cast<char*>(node->return_va)); if (!anyvalue.has_value() || anyvalue.type() != typeid(PVOID)) return processing_continue; if (PVOID virtual_addr = std::any_cast<PVOID>(anyvalue); virtual_addr != nullptr) { if (CheckExploitFuncs::ValidStackPointer(reinterpret_cast<ULONG_PTR>(virtual_addr))) { exploit_log("\"API\": \"{}\", \"reason\": {}", node->function->GetName(), CheckExploitFuncs::e_reason_allocate_exec_stack); } } } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_virtualProtectEx(detour_node* node, HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, LPDWORD lpflOldProtect) { EXPLOIT_POST_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() // we only check it when target process is current process // this might fix mantis: 0492346 if (hProcess != GetCurrentProcess()) break; if (flNewProtect != PAGE_EXECUTE_READ && flNewProtect != PAGE_EXECUTE_READWRITE) break; std::vector<PVOID> frame_chains; WalkFrameCurrentChain(frame_chains); if (!frame_chains.size()) return processing_continue; for (const auto& chain : frame_chains) { if (CheckExploitFuncs::AddressInModule(reinterpret_cast<ULONG_PTR>(chain), node->hook_implement_object->GetSpecialModuleInfo().m_self_info)) { continue; } if (CheckExploitFuncs::AddressInModule(reinterpret_cast<ULONG_PTR>(chain), node->hook_implement_object->GetSpecialModuleInfo().m_vbe_info)) { if (CheckExploitFuncs::CheckStackInstruction(reinterpret_cast<ULONG_PTR>(chain))) { exploit_log("\"API\": \"{}\", \"reason\": {}", node->function->GetName(), CheckExploitFuncs::e_reason_vbe_suspicious); } continue; } if (CheckExploitFuncs::ValidStackPointer(reinterpret_cast<ULONG_PTR>(lpAddress))) { exploit_log("\"API\": \"{}\", \"reason\": {}", node->function->GetName(), CheckExploitFuncs::e_reason_allocate_exec_stack); } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_createProcessA(detour_node* node, LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() std::shared_ptr<CHookImplementObject> impl_ptr = node->hook_implement_object; if (lpApplicationName) { std::string str_name = lpApplicationName; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(str_name)) { exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, str_name); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } else if (lpCommandLine) { std::string str_name = lpCommandLine; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(str_name)) { exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, str_name); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_createProcessW(detour_node* node, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() std::shared_ptr<CHookImplementObject> impl_ptr = node->hook_implement_object; if (lpApplicationName) { std::wstring wstr_name = lpApplicationName; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(W2AString(wstr_name))) { exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, W2AString(wstr_name)); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } else if (lpCommandLine) { std::wstring wstr_name = lpCommandLine; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(W2AString(wstr_name))) { exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, W2AString(wstr_name)); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_createProcessInternalW(detour_node* node, HANDLE hToken, LPCWSTR lpApplicationName, LPWSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory, LPSTARTUPINFOW lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation, PHANDLE hNewToken) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() std::shared_ptr<CHookImplementObject> impl_ptr = node->hook_implement_object; if (lpApplicationName) { std::wstring wstr_name = lpApplicationName; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(W2AString(wstr_name))) { exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, W2AString(wstr_name)); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } else if (lpCommandLine) { std::wstring wstr_name = lpCommandLine; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(W2AString(wstr_name))) { exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, W2AString(wstr_name)); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_dialogBoxParamA(detour_node* node, HINSTANCE hInstance, LPCSTR lpTemplateName, HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { if ((DWORD)lpTemplateName == 4070) { // try unlock password of VBA behaviors found, report e_reason_unlock_vba exploit_log("\"API\": \"{}\", \"reason\": {}", node->function->GetName(), CheckExploitFuncs::e_reason_unlock_vba); std::shared_ptr<CObObject> return_ptr = node->function->GetIdentifier(SI_RETURN); if (!return_ptr) return processing_continue; std::any anyvalue = return_ptr->GetValue(static_cast<char*>(node->return_va)); if (!anyvalue.has_value() || anyvalue.type() != typeid(LPVOID)) return processing_continue; anyvalue = reinterpret_cast<LPVOID>(1); return_ptr->SetValue(static_cast<char*>(node->return_va), anyvalue); return processing_exit; } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_dialogBoxParamW(detour_node* node, HINSTANCE hInstance, LPCWSTR lpTemplateName, HWND hWndParent, DLGPROC lpDialogFunc, LPARAM dwInitParam) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { if ((DWORD)lpTemplateName == 4070) { // try unlock password of VBA behaviors found, report e_reason_unlock_vba exploit_log("\"API\": \"{}\", \"reason\": {}", node->function->GetName(), CheckExploitFuncs::e_reason_unlock_vba); std::shared_ptr<CObObject> return_ptr = node->function->GetIdentifier(SI_RETURN); if (!return_ptr) return processing_continue; std::any anyvalue = return_ptr->GetValue(static_cast<char*>(node->return_va)); if (!anyvalue.has_value() || anyvalue.type() != typeid(LPVOID)) return processing_continue; anyvalue = reinterpret_cast<LPVOID>(1); return_ptr->SetValue(static_cast<char*>(node->return_va), anyvalue); return processing_exit; } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_createFileA(detour_node* node, LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_createFileW(detour_node* node, LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_copyFileA(detour_node* node, LPCSTR lpExistingFileName, LPCSTR lpNewFileName, BOOL bFailIfExists) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_copyFileW(detour_node* node, LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName, BOOL bFailIfExists) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_shellExecuteA(detour_node* node, HWND hwnd, LPCSTR lpOperation, LPCSTR lpFile, LPCSTR lpParameters, LPCSTR lpDirectory, INT nShowCmd) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() std::shared_ptr<CHookImplementObject> impl_ptr = node->hook_implement_object; if (lpFile) { std::string str_name = lpFile; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(str_name)) { // start danger process behaviors found, report e_reason_danger_process exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, str_name); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_shellExecuteW(detour_node* node, HWND hwnd, LPCWSTR lpOperation, LPCWSTR lpFile, LPCWSTR lpParameters, LPCWSTR lpDirectory, INT nShowCmd) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() std::shared_ptr<CHookImplementObject> impl_ptr = node->hook_implement_object; if (lpFile) { std::wstring wstr_name = lpFile; if (impl_ptr->GetCategoryPtr()->IsDangerousCommand(W2AString(wstr_name))) { // start danger process behaviors found, report e_reason_danger_process exploit_log("\"API\": \"{}\", \"reason\": {}, \"command\": \"{}\"", node->function->GetName(), CheckExploitFuncs::e_reason_danger_process, W2AString(wstr_name)); } else { //if (CheckTaintList((LPWSTR)lpApplicationName)) { // FOUND_EXPLOIT(EXPLOIT_REASON_SUSPICIOUS_PROCESS, NULL); //} } } } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_URLDownloadToFileA(detour_node* node, LPUNKNOWN pCaller, LPCSTR szURL, LPCSTR szFileName, DWORD dwReserved, LPBINDSTATUSCALLBACK lpfnCB) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_URLDownloadToFileW(detour_node* node, LPUNKNOWN pCaller, LPCWSTR szURL, LPCWSTR szFileName, DWORD dwReserved, LPBINDSTATUSCALLBACK lpfnCB) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_URLDownloadToCacheFileA(detour_node* node, LPUNKNOWN lpUnkcaller, LPCSTR szURL, LPCSTR szFileName, DWORD cchFileName, DWORD dwReserved, IBindStatusCallback *pBSC) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_URLDownloadToCacheFileW(detour_node* node, LPUNKNOWN lpUnkcaller, LPCSTR szURL, LPCWSTR szFileName, DWORD cchFileName, DWORD dwReserved, IBindStatusCallback *pBSC) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_winExec(detour_node* node, LPCSTR lpCmdLine, UINT uCmdShow) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_loadLibraryA(detour_node* node, LPCSTR lpLibFileName) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_loadLibraryW(detour_node* node, LPCWSTR lpLibFileName) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_loadLibraryExA(detour_node* node, LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_loadLibraryExW(detour_node* node, LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_ntMapViewOfSection(detour_node* node, HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, ULONG ZeroBits, ULONG CommitSize, PLARGE_INTEGER SectionOffset, PULONG ViewSize, UINT InheritDisposition, ULONG AllocationType, ULONG Protect) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } PVOID WINAPI CHookImplementObject::detour_rtlAllocateHeap(PVOID HeapHandle, ULONG Flags, SIZE_T Size) { if (m_heap_allocation_define.rtlallocateheap_func) { PVOID ret_base = m_heap_allocation_define.rtlallocateheap_func(HeapHandle, Flags, Size); static LONG add_lock = 0; LONG lock_int = InterlockedCompareExchange(&add_lock, 1, 0); if (lock_int == 0) { #ifdef _X86_ do { if (CheckExploitFuncs::CheckHeapSpray(HeapHandle, ret_base, Size)) { // heap spray behaviors found, report e_reason_heap_spray exploit_log("\"API\": \"{}\", \"reason\": {}", "RtlAllocateHeap", CheckExploitFuncs::e_reason_heap_spray); } else { InterlockedExchange(&add_lock, 0); } } while (0); #endif } return ret_base; } return nullptr; } BOOLEAN WINAPI CHookImplementObject::detour_rtlFreeHeap(PVOID HeapHandle, ULONG Flags, PVOID BaseAddress) { if (m_heap_allocation_define.rtlfreeheap_func) { #ifdef _X86_ do { CheckExploitFuncs::FreeHeapSpray(HeapHandle, BaseAddress); } while (0); #endif return m_heap_allocation_define.rtlfreeheap_func(HeapHandle, Flags, BaseAddress); } return FALSE; } PVOID WINAPI CHookImplementObject::detour_rtlDestroyHeap(PVOID HeapHandle) { if (m_heap_allocation_define.rtldestroyheap_func) { #ifdef _X86_ do { CheckExploitFuncs::DestroyHeapSpray(HeapHandle); } while (0); #endif return m_heap_allocation_define.rtldestroyheap_func(HeapHandle); } return nullptr; } processing_status WINAPI CHookImplementObject::detour_WSAStartup(detour_node* node, WORD wVersionRequired, LPWSADATA lpWSAData) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_socket(detour_node* node, int af, int type, int protocol) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; } processing_status WINAPI CHookImplementObject::detour_connect(detour_node* node, SOCKET s, const sockaddr *name, int namelen) { EXPLOIT_PRE_BEGIN(node) #ifdef _X86_ do { CHECK_COMMON_EXPLOIT() } while (0); #endif return processing_continue; }
39.68097
432
0.669613
smalltong02
8caa26682c79e0eab7a19e45a9da271cc67aefdc
710
cpp
C++
Graphs/Traverse/BFS.cpp
xdanielsb/Marathon-book
620f1eb9ce54fc05a923e087ef1b130c98251b60
[ "MIT" ]
4
2017-01-15T04:59:55.000Z
2018-04-06T19:51:49.000Z
Graphs/Traverse/BFS.cpp
xdanielsb/MarathonBook
620f1eb9ce54fc05a923e087ef1b130c98251b60
[ "MIT" ]
1
2017-02-21T01:00:51.000Z
2017-03-06T03:24:27.000Z
Graphs/Traverse/BFS.cpp
xdanielsb/MarathonBook
620f1eb9ce54fc05a923e087ef1b130c98251b60
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define pb push_back using namespace std; typedef vector < int > vi; vi dis; vector < vi > graph; void show_distances(){ for( int i = 0; i< dis.size(); i++){ cout << i << " : " << dis[i] << "\n"; } } void bfs(int origin){ queue < int > q; dis[origin] = 0; q.push(origin); while( q.size() > 0){ int front = q.front(); q.pop(); for(int son: graph[front]){ if(dis[son] == -1){ dis[son] = dis[front] +1; q.push(son); } } } } int main(){ int num_nodes = 5; dis.assign(num_nodes, -1); graph.resize(num_nodes); graph[0].pb(1); graph[0].pb(2); graph[0].pb(3); graph[1].pb(4); bfs(0); show_distances(); return 0; }
18.205128
41
0.530986
xdanielsb
8cac01860bd3a906cd8d1492b09240f19944d139
3,630
hpp
C++
include/STELA/binding.hpp
Kerndog73/STELA
11449b4bb440494f3ec4b1172b2688b5ec1bcd0a
[ "MIT" ]
10
2018-06-20T05:12:59.000Z
2021-11-23T02:56:04.000Z
include/STELA/binding.hpp
Kerndog73/STELA
11449b4bb440494f3ec4b1172b2688b5ec1bcd0a
[ "MIT" ]
null
null
null
include/STELA/binding.hpp
Kerndog73/STELA
11449b4bb440494f3ec4b1172b2688b5ec1bcd0a
[ "MIT" ]
null
null
null
// // binding.hpp // STELA // // Created by Indi Kernick on 13/12/18. // Copyright © 2018 Indi Kernick. All rights reserved. // #ifndef stela_binding_hpp #define stela_binding_hpp #include <tuple> #include <memory> #include <algorithm> #include <type_traits> #include "retain ptr.hpp" #include "pass traits.hpp" namespace llvm { class ExecutionEngine; } namespace stela { /// A wrapper around a compiled stela function. Acts as an ABI adapter to call /// Stela functions using the Stela ABI template <typename Fun, bool Method = false> class Function; template <bool Method, typename Ret, typename... Params> class Function<Ret(Params...), Method> { template <typename Param, size_t Index, typename Tuple> static inline auto unwrap(const Tuple &params) noexcept { return pass_traits<Param>::unwrap(std::get<Index>(params)); } template <typename Param> using pass_type = typename pass_traits<Param>::type; template <typename Tuple, size_t... Indicies> inline Ret call(const Tuple &params, std::index_sequence<Indicies...>) noexcept { if constexpr (param_ret) { std::aligned_storage_t<sizeof(Ret), alignof(Ret)> retStorage; Ret *retPtr = reinterpret_cast<Ret *>(&retStorage); if constexpr (Method) { ptr(unwrap<Params, Indicies>(params)..., retPtr); } else { ptr(nullptr, unwrap<Params, Indicies>(params)..., retPtr); } Ret retObj{std::move(*retPtr)}; retPtr->~Ret(); return retObj; } else if constexpr (std::is_void_v<Ret>) { if constexpr (Method) { ptr(unwrap<Params, Indicies>(params)...); } else { ptr(nullptr, unwrap<Params, Indicies>(params)...); } } else { if constexpr (Method) { return pass_traits<Ret>::wrap(ptr(unwrap<Params, Indicies>(params)...)); } else { return pass_traits<Ret>::wrap(ptr(nullptr, unwrap<Params, Indicies>(params)...)); } } } public: static constexpr bool param_ret = pass_traits<Ret>::nontrivial; using type = std::conditional_t< Method, std::conditional_t< param_ret, void(pass_type<Params>..., Ret *) noexcept, pass_type<Ret>(pass_type<Params>...) noexcept >, std::conditional_t< param_ret, void(void *, pass_type<Params>..., Ret *) noexcept, pass_type<Ret>(void *, pass_type<Params>...) noexcept > >; explicit Function(const uint64_t addr) noexcept : ptr{reinterpret_cast<type *>(addr)} {} explicit Function(type *const ptr) noexcept : ptr{ptr} {} template <typename... Args> inline Ret operator()(Args &&... args) noexcept { std::tuple<Params...> params{std::forward<Args>(args)...}; using Indicies = std::index_sequence_for<Params...>; return call(params, Indicies{}); } private: type *ptr; }; template <typename Type> class Global { public: using type = Type; explicit Global(const uint64_t addr) noexcept : ptr{reinterpret_cast<type *>(addr)} {} type &operator*() const noexcept { return *ptr; } type *operator->() const noexcept { return ptr; } private: type *ptr; }; uint64_t getFunctionAddress(llvm::ExecutionEngine *, const std::string &); template <typename Sig, bool Method = false> auto getFunc(llvm::ExecutionEngine *engine, const std::string &name) { return Function<Sig, Method>{getFunctionAddress(engine, name)}; } uint64_t getGlobalAddress(llvm::ExecutionEngine *, const std::string &); template <typename Type> auto getGlobal(llvm::ExecutionEngine *engine, const std::string &name) { return Global<Type>{getGlobalAddress(engine, name)}; } } #endif
26.115108
89
0.664738
Kerndog73
8caf5b87ce063dcc81b8972ce58f417e9fec1e4e
6,159
hpp
C++
src/R.hpp
dantehemerson/Arkanoid-Returns
478ae8df92f978dce95fd227a9047e83dea9a855
[ "MIT" ]
3
2018-09-25T07:59:06.000Z
2019-08-24T09:35:43.000Z
src/R.hpp
dantehemerson/Arkanoid-Returns
478ae8df92f978dce95fd227a9047e83dea9a855
[ "MIT" ]
1
2018-05-08T11:34:05.000Z
2018-05-08T11:34:05.000Z
src/R.hpp
dantehemerson/Arkanoid-Returns
478ae8df92f978dce95fd227a9047e83dea9a855
[ "MIT" ]
1
2020-06-07T21:23:24.000Z
2020-06-07T21:23:24.000Z
#pragma once #ifndef R_HPP #define R_HPP #include <allegro5/allegro.h> #include <allegro5/allegro_color.h> #include <string> #include <array> namespace R { namespace Constant { // Frames por segundo. static const int FPS = 60; static const int SIZE_FONT_VENUS_18 = 18; static const int SIZE_FONT_VENUS_20 = 20; static const int SIZE_FONT_VENUS_TITLES = 60; static const int SIZE_FONT_VENUS_BIG = 50; static const int SIZE_FONT_VENUS_SMALL = 14; } namespace Dimen { // Ancho y alto de la pantalla static const int WIDTH = 800; static const int HEIGHT = 600; } namespace String { static const std::string WINDOW_TITLE = "Arkanoid"; static const std::string ERROR_INSTALL_KEYBOARD = "Error al instalar el teclado."; static const std::string ERROR_ALLEGRO_INIT = "Error al iniciar la librearía Allegro"; static const std::string ERROR_INSTALL_MOUSE = "Error al instalar el ratón"; static const std::string ERROR_INSTALL_AUDIO = "Error al instalar el periférico de audio."; static const std::string ERROR_INSTALL_PHYSICS = "Error al iniciar physics."; static const std::string ERROR_ABRIR_FICHERO_RECURSOS = "Error al abrir el fichero de recursos."; static const std::string PLAY_GAME = "START GAME"; static const std::string HIGHSCORES = "HIGHSCORES"; static const std::string OPTIONS = "OPTIONS"; static const std::string HELP = "HELP"; static const std::string ABOUT = "ABOUT"; static const std::string QUIT = "QUIT"; static const std::string BACK = "BACK"; static const std::string VERSION_GAME = "VERSION 1.0.0.1"; static const std::string POWERED = "POWERED"; static const std::string COPYRIGHT = "Copyright (C) 2017 Dante Calderon"; static const std::string GITHUB = "GITHUB"; static const std::string NAME_AUTHOR = "DANTE CALDERON"; static const std::string AND = "AND"; static const std::string BRICK_WHITE_DESCRIPTION = "WHITE - 50 PTS"; static const std::string BRICK_ORANGE_DESCRIPTION = "ORANGE - 60 PTS"; static const std::string BRICK_LIGHT_BLUE_DESCRIPTION = "LIGHT BLUE - 70 PTS"; static const std::string BRICK_GREEN_DESCRIPTION = "GREEN - 80 PTS"; static const std::string BRICK_RED_DESCRIPTION = "RED - 90 PTS"; static const std::string BRICK_BLUE_DESCRIPTION = "BLUE - 100 PTS"; static const std::string BRICK_PINK_DESCRIPTION = "PINK - 110 PTS"; static const std::string BRICK_YELLOW_DESCRIPTION = "YELLOW - 120 PTS"; static const std::string BRICK_SILVER_DESCRIPTION = "SILVER - 50 PTS X ROUND #"; static const std::string BRICK_GOLD_DESCRIPTION = "GOLD - INDESTRUCTIBLE"; /// Archivo de configuraciones titulos static const std::string CONFIG_SCREEN = "SCREEN"; static const std::string CONFIG_SOUND = "SOUND"; static const std::string CONFIG_CONTROL = "CONTROL"; /// Menu Pausa static const std::string PAUSE = "PAUSE"; static const std::string CONTINUE = "CONTINUE"; static const std::string RESTART = "RESTART"; static const std::string GAMEOVER = "GAME OVER"; } /// Colores namespace Color { static const ALLEGRO_COLOR WHITE = { 1.0, 1.0, 1.0 }; static const ALLEGRO_COLOR BLACK = { 0.0, 0.0, 0.0 }; static const ALLEGRO_COLOR GREEN = { 0.0, 1.0, 0.0 }; //static const ALLEGRO_COLOR GRAY = al_color_html("#2BDA50"); static const ALLEGRO_COLOR GRAY = al_color_html("#8F8F8F"); //static const ALLEGRO_COLOR YELLOW_BTN = al_color_html("#C3C3C3"); static const ALLEGRO_COLOR BUTTON_FOCUSED = al_color_html("#c22d2d"); static const ALLEGRO_COLOR SHADOWN_TITLE = al_color_html("#FF1F28"); static const ALLEGRO_COLOR GITHUB = al_color_html("#8B368C"); /* ? - Esto no funcióna la transparencia*/ //static const ALLEGRO_COLOR BACKGROUND_ABOUT_TRANSPARENT = al_map_rgba(125, 215, 215, 255); static const ALLEGRO_COLOR BACKGROUND_ABOUT_TRANSPARENT = al_map_rgba_f(0.4, 0.4, 0.4, 0.5); static const ALLEGRO_COLOR BACKGROUND_HIGHSCORE_TRANSPARENT = al_map_rgba_f(0.3, 0.3, 0.3, 0.5); static const ALLEGRO_COLOR TRANSPARENTS = al_map_rgba_f(0.0, 0.0, 0.0, 0.0); /* Declaro y no funcióna talvéz es por static */ static const ALLEGRO_COLOR BACKGROUND_STARTING = al_map_rgba(50, 50, 50, 150); static const ALLEGRO_COLOR BACKGROUND_LOSING = al_map_rgba(80, 0, 0, 150); static const ALLEGRO_COLOR SHADOW_GRAY = al_color_html("#8d8b8f"); } static const std::array<std::string, 5> fontsUrl = { "resources/fonts/venus.ttf", }; enum class Font { VENUS_18, VENUS_20, VENUS_TITLES, VENUS_SMALL, VENUS_BIG, VENUS_INTRO }; static const std::array<std::string, 19> imagesUrl = { "resources/images/arkanoid_logo.png", "resources/images/items.png", "resources/images/paddle.png", "resources/images/background1.png", "resources/images/button.png", "resources/images/button_focused.png", "resources/images/cplusplus.png", "resources/images/allegro.jpg", "resources/images/buttton_medium_focused.png", "resources/images/buttton_medium.png", "resources/images/buttton_medium_facebook.png", "resources/images/buttton_medium_github.png", "resources/images/buttton_medium_google_plus.png", "resources/images/button_small_focused.png", "resources/images/button_small.png", "resources/images/shadow_top.png", "resources/images/shadow_bottom.png", "resources/images/shadow_left.png", "resources/images/shadow_right.png" }; enum class Image { ARKANOID_LOGO, ITEMS, PADDLE, BACKGROUND1, BUTTON, BUTTON_FOCUSED, C_PLUS_PLUS_LOGO, ALLEGRO_LOGO, BUTTON_MEDIUM_FOCUSED, BUTTON_MEDIUM, BUTTON_FACEBOOK, BUTTON_GITHUB, BUTTON_GOOGLE_PLUS, BUTTON_SMALL_FOCUSED, BUTTON_SMALL, SHADOW_TOP, SHADOW_BOTTOM, SHADOW_LEFT, SHADOW_RIGHT }; static const std::array<std::string, 4> soundsUrl = { "resources/sounds/release.wav", "resources/sounds/bounce.wav", "resources/sounds/click.wav", "resources/sounds/shot.wav" }; enum class Sample { RELEASE, BOUNCE, CLICK, SHOT }; enum class Stream { }; } /// Constantes para registrar eventos. enum ActionMenu { DOWN, UP, ENTER, LEFT, RIGHT, MOUSE_MICKEY_LEFT, BACKSPACE, MOUSE_MICKEY_LEFT_DOWN, MOUSE_MICKEY_LEFT_UP, ESCAPE }; #endif // !R_HPP
31.106061
99
0.732911
dantehemerson
8cb7bdd20573b785824dcaf639fcd55279fd8b1a
853
cpp
C++
luogu/P1182.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
1
2020-07-24T03:07:08.000Z
2020-07-24T03:07:08.000Z
luogu/P1182.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
luogu/P1182.cpp
delphi122/knowledge_planet
e86cb8f9aa47ef8918cde0e814984a6535023c21
[ "Apache-2.0" ]
null
null
null
// // Created by yangtao on 20-4-21. // #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 1e5 + 5; int a[N]; int l, r; int n, m; int mmax, ssum; int calc(int step) { int team = 0; int s = a[0]; for(int i = 1; i < n; i++) { if(s + a[i] <= step) { s += a[i]; } else { s = a[i]; team++; } } return team; } int main() { cin >> n >>m; for(int i = 0 ; i < n; i++) { scanf("%d", &a[i]); mmax = max(mmax, a[i]); ssum += a[i]; } l= mmax, r = ssum; while(l <= r) { int mid = l + r >> 1; int team = calc(mid); if(team < m) { r = mid - 1; } else { l = mid + 1; } } cout << l << endl; return 0; }
16.09434
33
0.393904
delphi122
8cc1f4903612346513193a1c4c8303abb19724af
47
hpp
C++
src/boost_bimap_views_multiset_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_bimap_views_multiset_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_bimap_views_multiset_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/bimap/views/multiset_view.hpp>
23.5
46
0.808511
miathedev
bc4b8e0170b513dc78154fe2976e4e5333999e02
54,459
cpp
C++
FDPS-5.0g/src/particle_mesh/decomposition.cpp
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
77
2015-02-12T02:35:40.000Z
2022-03-11T01:10:31.000Z
FDPS-5.0g/src/particle_mesh/decomposition.cpp
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
9
2015-03-24T09:44:29.000Z
2021-11-30T19:42:58.000Z
FDPS-5.0g/src/particle_mesh/decomposition.cpp
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
28
2015-03-17T06:58:09.000Z
2022-02-14T07:16:25.000Z
#include "pp.h" namespace ParticleSimulator{ namespace ParticleMesh{ extern double (*p_cache)[4]; static char cbuf[CHARMAX]; void createDivision( const int n, int *ndiv){ int nx, ny, nz; int n0, n1; n0 = (int)pow(n+0.1,0.33333333333333333333); while(n%n0)n0--; nx = n0; n1 = n/nx; n0 = (int)sqrt(n1+0.1); while(n1%n0)n0++; ny = n0; nz = n1/n0; int ntmp; if (nz > ny){ ntmp = nz; nz = ny; ny = ntmp; } if (ny > nx){ ntmp = nx; nx = ny; ny = ntmp; } if (nz > ny){ ntmp = nz; nz = ny; ny = ntmp; } ndiv[0] = nx; ndiv[1] = ny; ndiv[2] = nz; } void getRange( const Particle *particle, const int n, double *bmin, double *bmax){ bmin[0] = 1.0e30; bmin[1] = 1.0e30; bmin[2] = 1.0e30; bmax[0] = -1.0e30; bmax[1] = -1.0e30; bmax[2] = -1.0e30; int i; for( i=0; i<n; i++){ if( particle[i].xpos < bmin[0]) bmin[0] = particle[i].xpos; if( particle[i].xpos > bmax[0]) bmax[0] = particle[i].xpos; if( particle[i].ypos < bmin[1]) bmin[1] = particle[i].ypos; if( particle[i].ypos > bmax[1]) bmax[1] = particle[i].ypos; if( particle[i].zpos < bmin[2]) bmin[2] = particle[i].zpos; if( particle[i].zpos > bmax[2]) bmax[2] = particle[i].zpos; } } /* rank to x-y-z*/ void getXYZIndex( const int inode, const int *ndiv, int *x, int *y, int *z){ if( ndiv[1] == 1){ *x = inode; *y = 0; *z = 0; } else{ if( ndiv[2] == 1){ *z = 0; *x = inode / ndiv[1]; *y = inode % ndiv[1]; } else{ int xy = ndiv[1] * ndiv[2]; *x = inode / xy; int inode2 = inode % xy; *y = inode2 / ndiv[2]; *z = inode2 % ndiv[2]; } } } void setUniformBoundary( pRunParam this_run, double (*bmin_all_new)[3], double (*bmax_all_new)[3]){ double hx = (this_run->global_bmax[0] - this_run->global_bmin[0]) / (double)this_run->ndiv[0]; double hy = (this_run->global_bmax[1] - this_run->global_bmin[1]) / (double)this_run->ndiv[1]; double hz = (this_run->global_bmax[2] - this_run->global_bmin[2]) / (double)this_run->ndiv[2]; double bmin[3], bmax[3]; int x, y, z; getXYZIndex( this_run->inode, this_run->ndiv, &x, &y, &z); bmin[0] = (double)x*hx + this_run->global_bmin[0]; bmin[1] = (double)y*hy + this_run->global_bmin[1]; bmin[2] = (double)z*hz + this_run->global_bmin[2]; #ifdef SHIFT_INITIAL_BOUNDARY double ds = 0.001 / pow( (double)NUMBER_OF_PART_ALL, 0.33333); fprintf_verbose( stderr, "shift_initial_boundary %e\n", ds); cerr << this_run->npart << "\t" << ds << endl; bmin[0] += ds; bmin[1] += ds; bmin[2] += ds; #endif bmax[0] = bmin[0] + hx; bmax[1] = bmin[1] + hy; bmax[2] = bmin[2] + hz; if( x == 0) bmin[0] = this_run->global_bmin[0]; if( y == 0) bmin[1] = this_run->global_bmin[1]; if( z == 0) bmin[2] = this_run->global_bmin[2]; if( x == this_run->ndiv[0]-1) bmax[0] = this_run->global_bmax[0]; if( y == this_run->ndiv[1]-1) bmax[1] = this_run->global_bmax[1]; if( z == this_run->ndiv[2]-1) bmax[2] = this_run->global_bmax[2]; MPI_Allgather( bmin, 3, MPI_DOUBLE, bmin_all_new, 3, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); MPI_Allgather( bmax, 3, MPI_DOUBLE, bmax_all_new, 3, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); this_run->bmin[0] = bmin[0]; this_run->bmin[1] = bmin[1]; this_run->bmin[2] = bmin[2]; this_run->bmax[0] = bmax[0]; this_run->bmax[1] = bmax[1]; this_run->bmax[2] = bmax[2]; } /* sort particle for exchange */ int sortInBoxParticle( Particle *particle, const int n, const double *bmin, const double *bmax){ /* * particle ___________________________________ * sort using area * ----------------------------------- * \no change node /\change node/ */ #ifdef STATIC_ARRAY static int inbox_flag[NUMBER_OF_PART]; #else int *inbox_flag = (int *) my_malloc( sizeof(int) * n); #endif int oldn = 0; #pragma omp parallel for reduction(+:oldn) for( int i=0; i<n; i++){ double pos[3]; getPos( &particle[i], pos); inbox_flag[i] = 1; if( (bmin[0] <= pos[0] && pos[0] < bmax[0]) && (bmin[1] <= pos[1] && pos[1] < bmax[1]) && (bmin[2] <= pos[2] && pos[2] < bmax[2])){ inbox_flag[i] = 0; oldn ++; } } int i = 0; int j = n - 1; while(i < j){ if( inbox_flag[i] == 0){ i++; } else if( inbox_flag[j] == 1){ j--; } else{ Particle particle_tmp = particle[i]; particle[i] = particle[j]; particle[j] = particle_tmp; i++; j--; } } #ifndef STATIC_ARRAY free( inbox_flag); #endif return oldn; } void particleSortUsingXpos( pParticle particle, const int n){ int i = 0; int j = n-1; double pivot = particle[n/2].xpos; while(1){ while( particle[i].xpos < pivot){ i++; } while( particle[j].xpos > pivot){ j--; } if( i >= j){ break; } Particle tmp_p = particle[j]; particle[j] = particle[i]; particle[i] = tmp_p; i++; j--; } if( 0 < i-1){ particleSortUsingXpos( particle, i); } if( j+1 < n-1){ particleSortUsingXpos( particle+j+1, n-j-1); } } void particleSortUsingYpos( pParticle particle, const int n){ int i = 0; int j = n-1; double pivot = particle[n/2].ypos; while(1){ while( particle[i].ypos < pivot){ i++; } while( particle[j].ypos > pivot){ j--; } if( i >= j){ break; } Particle tmp_p = particle[j]; particle[j] = particle[i]; particle[i] = tmp_p; i++; j--; } if( 0 < i-1){ particleSortUsingYpos( particle, i); } if( j+1 < n-1){ particleSortUsingYpos( particle+j+1, n-j-1); } } void particleSortUsingZpos( pParticle particle, const int n){ int i = 0; int j = n-1; double pivot = particle[n/2].zpos; while(1){ while( particle[i].zpos < pivot){ i++; } while( particle[j].zpos > pivot){ j--; } if( i >= j){ break; } Particle tmp_p = particle[j]; particle[j] = particle[i]; particle[i] = tmp_p; i++; j--; } if( 0 < i-1){ particleSortUsingZpos( particle, i); } if( j+1 < n-1){ particleSortUsingZpos( particle+j+1, n-j-1); } } void particleSortForExchange( pParticle particle, pRunParam this_run, const int dn, double bmax[][3], int *nsend){ int n = this_run->npart; int oldn = n - dn; int nx = this_run->ndiv[0]; int ny = this_run->ndiv[1]; int nz = this_run->ndiv[2]; for( int i=0; i<this_run->nnode; i++){ nsend[i] = 0; } if( dn == 0) return; qsortParticleUsingXpos( particle+oldn, dn, NLEVEL_KEY_SORT, NCHUNK_QSORT); #if 0 int i, j, k; int nxstart = oldn; for( i=0; i<nx; i++){ int bxnode = getVoxelIndex( i, 0, 0, this_run->ndiv); double xmax = bmax[bxnode][0]; int j; for( j=nxstart; j<n; j++){ if( particle[j].xpos >= xmax) break; } int nxend = j; if( i == nx-1) nxend = n; int dny = nxend - nxstart; if( dny == 0) continue; particleSortUsingYpos( &particle[nxstart], dny); //fprintf( stderr, "%d %d\n", i, dny); int nystart = nxstart; for( j=0; j<ny; j++){ int bynode = getVoxelIndex( i, j, 0, this_run->ndiv); double ymax = bmax[bynode][1]; for( k=nystart; k<nxend; k++){ if( particle[k].ypos >= ymax) break; } int nyend = k; if( j == ny-1) nyend = nxend; int dnz = nyend - nystart; if( dnz == 0) continue; particleSortUsingZpos( &particle[nystart], dnz); int bznode = bynode; int lstart = nystart; for( k=bznode; k<(bznode+nz); k++){ //fprintf( stderr, "lstart %d %d %d %d\n", this_run->inode, lstart, nyend, oldn); double zmax = bmax[k][2]; int l; for( l=lstart; l<nyend; l++){ if( particle[l].zpos < zmax){ nsend[k] ++; } else{ lstart = l; break; } } if( l == nyend) lstart = nyend; } nystart = nyend; } nxstart = nxend; } #else #ifdef STATIC_ARRAY static int nxstart[NXMAX]; static int nxend[NXMAX]; #else int *nxstart = new int[nx]; int *nxend = new int[nx]; #endif nxstart[0] = oldn; for( int i=0; i<(nx-1); i++){ int bxnode = getVoxelIndex( i, 0, 0, this_run->ndiv); double xmax = bmax[bxnode][0]; int j; for( j=nxstart[i]; j<n; j++){ if( particle[j].xpos >= xmax){ break; } } nxend[i] = j; nxstart[i+1] = nxend[i]; } nxend[nx-1] = n; #pragma omp parallel for CHUNK_DECOMPOSITION for( int i=0; i<nx; i++){ int dny = nxend[i] - nxstart[i]; if( dny == 0) continue; particleSortUsingYpos( &particle[nxstart[i]], dny); int j, k; int nystart = nxstart[i]; for( j=0; j<ny; j++){ int bynode = getVoxelIndex( i, j, 0, this_run->ndiv); double ymax = bmax[bynode][1]; for( k=nystart; k<nxend[i]; k++){ if( particle[k].ypos >= ymax) break; } int nyend = k; if( j == ny-1) nyend = nxend[i]; int dnz = nyend - nystart; if( dnz == 0) continue; particleSortUsingZpos( &particle[nystart], dnz); int bznode = bynode; int lstart = nystart; for( k=bznode; k<(bznode+nz); k++){ //fprintf( stderr, "lstart %d %d %d %d\n", this_run->inode, lstart, nyend, oldn); double zmax = bmax[k][2]; int l; for( l=lstart; l<nyend; l++){ if( particle[l].zpos < zmax){ nsend[k] ++; } else{ lstart = l; break; } } if( l == nyend) lstart = nyend; } nystart = nyend; } } #ifndef STATIC_ARRAY delete [] nxstart; delete [] nxend; #endif #endif } int samplingParticleX( const pParticle particle, const int n, const int nrate, float *xsamp_all, const pRunParam this_run){ int nnode = this_run->nnode; int nsamp_local = n / nrate + 1; float *xsamp = new float[nsamp_local]; nsamp_local = 0; #pragma omp parallel for reduction(+:nsamp_local) for( int i=0; i<n; i++){ if( i%nrate != 0) continue; int ip = i/nrate; xsamp[ip] = particle[i].xpos; nsamp_local ++; } static int nsamp_all_buf[MAXNNODE]; static int displs[MAXNNODE]; #ifdef KCOMPUTER MPI_Allgather( &nsamp_local, 1, MPI_INT, nsamp_all_buf, 1, MPI_INT, this_run->MPI_COMM_INTERNAL); #else MPI_Gather( &nsamp_local, 1, MPI_INT, nsamp_all_buf, 1, MPI_INT, 0, this_run->MPI_COMM_INTERNAL); #endif displs[0] = 0; for( int i=1; i<nnode; i++){ displs[i] = displs[i-1] + nsamp_all_buf[i-1]; } int nsamp = displs[nnode-1] + nsamp_all_buf[nnode-1]; #ifdef KCOMPUTER MPI_Allgatherv( xsamp, nsamp_local, MPI_FLOAT, xsamp_all, nsamp_all_buf, displs, MPI_FLOAT, this_run->MPI_COMM_INTERNAL); #else MPI_Gatherv( xsamp, nsamp_local, MPI_FLOAT, xsamp_all, nsamp_all_buf, displs, MPI_FLOAT, 0, this_run->MPI_COMM_INTERNAL); #endif delete [] xsamp; return nsamp; } int samplingParticleYZ( const pParticle particle, const int n, const int nrate, float *ysamp_all, float *zsamp_all, const pRunParam this_run){ int nnode = this_run->ndiv[1] * this_run->ndiv[2]; int nsamp_local = n / nrate + 1; float *ysamp = new float[nsamp_local]; float *zsamp = new float[nsamp_local]; nsamp_local = 0; #pragma omp parallel for reduction(+:nsamp_local) for( int i=0; i<n; i++){ if( i%nrate != 0) continue; int ip = i/nrate; ysamp[ip] = particle[i].ypos; zsamp[ip] = particle[i].zpos; nsamp_local ++; } static int nsamp_all_buf[MAXNNODE]; static int displs[MAXNNODE]; MPI_Allgather( &nsamp_local, 1, MPI_INT, nsamp_all_buf, 1, MPI_INT, this_run->MPI_COMM_YZ); displs[0] = 0; for( int i=1; i<nnode; i++){ displs[i] = displs[i-1] + nsamp_all_buf[i-1]; } int nsamp = displs[nnode-1] + nsamp_all_buf[nnode-1]; MPI_Allgatherv( ysamp, nsamp_local, MPI_FLOAT, ysamp_all, nsamp_all_buf, displs, MPI_FLOAT, this_run->MPI_COMM_YZ); MPI_Allgatherv( zsamp, nsamp_local, MPI_FLOAT, zsamp_all, nsamp_all_buf, displs, MPI_FLOAT, this_run->MPI_COMM_YZ); delete [] ysamp; delete [] zsamp; return nsamp; } int samplingParticle( const pParticle particle, const int n, const int nrate, float *xsamp_all, float *ysamp_all, float *zsamp_all, const pRunParam this_run){ int nnode = this_run->nnode; int nsamp_local = n / nrate + 1; float *xsamp = new float[nsamp_local]; float *ysamp = new float[nsamp_local]; float *zsamp = new float[nsamp_local]; nsamp_local = 0; #pragma omp parallel for reduction(+:nsamp_local) for( int i=0; i<n; i++){ if( i%nrate != 0) continue; int ip = i/nrate; float pos[3]; getPos2( &particle[i], pos); xsamp[ip] = pos[0]; ysamp[ip] = pos[1]; zsamp[ip] = pos[2]; nsamp_local ++; } static int nsamp_all_buf[MAXNNODE]; static int displs[MAXNNODE]; MPI_Allgather( &nsamp_local, 1, MPI_INT, nsamp_all_buf, 1, MPI_INT, this_run->MPI_COMM_INTERNAL); displs[0] = 0; for( int i=1; i<nnode; i++){ displs[i] = displs[i-1] + nsamp_all_buf[i-1]; } int nsamp = displs[nnode-1] + nsamp_all_buf[nnode-1]; MPI_Allgatherv( xsamp, nsamp_local, MPI_FLOAT, xsamp_all, nsamp_all_buf, displs, MPI_FLOAT, this_run->MPI_COMM_INTERNAL); MPI_Allgatherv( ysamp, nsamp_local, MPI_FLOAT, ysamp_all, nsamp_all_buf, displs, MPI_FLOAT, this_run->MPI_COMM_INTERNAL); MPI_Allgatherv( zsamp, nsamp_local, MPI_FLOAT, zsamp_all, nsamp_all_buf, displs, MPI_FLOAT, this_run->MPI_COMM_INTERNAL); delete [] xsamp; delete [] ysamp; delete [] zsamp; return nsamp; } void determineBoundary( float *xsamp_all, float *ysamp_all, float *zsamp_all, const int nsamp, const pRunParam this_run, double *bmin, double *bmax){ int inode = this_run->inode; int *ndiv = this_run->ndiv; int nnode2 = ndiv[1] * ndiv[2]; qsortPivotWrapper( ysamp_all, zsamp_all, xsamp_all, nsamp, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); int xindex = inode / nnode2; if( ndiv[1] == 1) xindex = inode; int xleft = xindex * nsamp/ndiv[0]; float xmin = xsamp_all[xleft]; if( xindex == 0) xmin = this_run->global_bmin[0]; int xright = (xindex+1) * nsamp/ndiv[0]; float xmax = xsamp_all[xright]; if( xindex == (ndiv[0]-1)) xmax = this_run->global_bmax[0]; int nsamp2 = xright - xleft; qsortPivotWrapper( zsamp_all+xleft, ysamp_all+xleft, nsamp2, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); int inode2 = inode - xindex*nnode2; int yindex = inode2 / ndiv[2]; if( ndiv[2] == 1) yindex = inode2; int yleft = yindex * nsamp2/ndiv[1] + xleft; float ymin = ysamp_all[yleft]; if( yindex == 0) ymin = this_run->global_bmin[1]; int yright = (yindex+1) * nsamp2/ndiv[1] + xleft; float ymax = ysamp_all[yright]; if( yindex == (ndiv[1]-1)) ymax = this_run->global_bmax[1]; int nsamp3 = yright - yleft; qsortBasicWrapper( zsamp_all+yleft, nsamp3, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); int inode3 = inode2 - yindex*ndiv[2]; int zindex = inode3; int zleft = zindex * nsamp3/ndiv[2] + yleft; float zmin = zsamp_all[zleft]; if( zindex == 0) zmin = this_run->global_bmin[2]; int zright = (zindex+1) * nsamp3/ndiv[2] + yleft; float zmax = zsamp_all[zright]; if( zindex == (ndiv[2]-1)) zmax = this_run->global_bmax[2]; bmin[0] = xmin; bmin[1] = ymin; bmin[2] = zmin; bmax[0] = xmax; bmax[1] = ymax; bmax[2] = zmax; } void determineBoundary2( float *xsamp_all, float *ysamp_all, float *zsamp_all, const int nsamp_x, const int nsamp_yz, const pRunParam this_run, double *bmin, double *bmax, const int sampx_on){ int inode = this_run->inode; int inode_yz = this_run->inode_yz; int nnode = this_run->nnode; int *ndiv = this_run->ndiv; int nnode2 = ndiv[1] * ndiv[2]; static float bminall[MAXNNODE]; static float bmaxall[MAXNNODE]; int nsamp_per_x = nsamp_x / ndiv[0]; float xmin = this_run->bmin[0]; float xmax = this_run->bmax[0]; if( sampx_on == 1){ if( inode == 0){ qsortBasicWrapper( xsamp_all, nsamp_x, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); #pragma omp parallel for for( int i=0; i<nnode; i++){ int xindex = i / nnode2; int xleft = xindex * nsamp_per_x; bminall[i] = xsamp_all[xleft]; if( xindex == 0) bminall[i] = this_run->global_bmin[0]; int xright = (xindex+1) * nsamp_per_x; bmaxall[i] = xsamp_all[xright]; if( xindex == (ndiv[0]-1)) bmaxall[i] = this_run->global_bmax[0]; } } MPI_Scatter( bminall, 1, MPI_FLOAT, &xmin, 1, MPI_FLOAT, 0, this_run->MPI_COMM_INTERNAL); MPI_Scatter( bmaxall, 1, MPI_FLOAT, &xmax, 1, MPI_FLOAT, 0, this_run->MPI_COMM_INTERNAL); } qsortPivotWrapper( zsamp_all, ysamp_all, nsamp_yz, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); int nsamp_per_y = nsamp_yz / ndiv[1]; int yindex = inode_yz / ndiv[2]; int yleft = yindex * nsamp_per_y; float ymin = ysamp_all[yleft]; if( yindex == 0) ymin = this_run->global_bmin[1]; int yright = (yindex+1) * nsamp_per_y; float ymax = ysamp_all[yright]; if( yindex == (ndiv[1]-1)) ymax = this_run->global_bmax[1]; int nsamp_z = yright - yleft; qsortBasicWrapper( zsamp_all+yleft, nsamp_z, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); int nsamp_per_z = nsamp_z / ndiv[2]; int inode_z = inode_yz - yindex*ndiv[2]; int zleft = inode_z * nsamp_per_z + yleft; float zmin = zsamp_all[zleft]; if( inode_z == 0) zmin = this_run->global_bmin[2]; int zright = (inode_z+1) * nsamp_per_z + yleft; float zmax = zsamp_all[zright]; if( inode_z == (ndiv[2]-1)) zmax = this_run->global_bmax[2]; bmin[0] = xmin; bmin[1] = ymin; bmin[2] = zmin; bmax[0] = xmax; bmax[1] = ymax; bmax[2] = zmax; } void dumpSamplingParticle( const pParticle particle, const pRunParam this_run, const char *filename){ int nrate = NRATE_EXCHANGE; int nsamp = this_run->npart_total / nrate + 1; int nmem = nsamp + this_run->nnode; int n = this_run->npart; float *xsamp_all = (float *) my_malloc( sizeof(float) * nmem); float *ysamp_all = (float *) my_malloc( sizeof(float) * nmem); float *zsamp_all = (float *) my_malloc( sizeof(float) * nmem); int nsamp_local = (int)(nsamp * this_run->nrate); nrate = n / nsamp_local + 1; nsamp = samplingParticle( particle, n, nrate, xsamp_all, ysamp_all, zsamp_all, this_run); assert( nsamp <= nmem); if( this_run->inode == 0){ fprintf( stderr, "writing %s nsamp:%d\n", filename, nsamp); FILE *fout = fopen( filename, "wb"); fwrite( &nsamp, sizeof(int), 1, fout); fwrite( xsamp_all, sizeof(float), nsamp, fout); fwrite( ysamp_all, sizeof(float), nsamp, fout); fwrite( zsamp_all, sizeof(float), nsamp, fout); fclose(fout); } free(xsamp_all); free(ysamp_all); free(zsamp_all); } /* determine own area using sampling particle */ void determineBoundary( pParticle particle, const int n, const long long int npart_all, const int *ndiv, double bmin[][3], double bmax[][3], RunParam *this_run){ double nowtime; double time1 = 0.0; getTime( &nowtime); int nrate = NRATE_EXCHANGE; int nsamp = npart_all / nrate + 1; int nmem = nsamp + this_run->nnode; #ifdef STATIC_ARRAY static float xsamp_all[NSAMPMAX]; static float ysamp_all[NSAMPMAX]; static float zsamp_all[NSAMPMAX]; nmem = NSAMPMAX; #else float *xsamp_all = new float[nmem]; float *ysamp_all = new float[nmem]; float *zsamp_all = new float[nmem]; #endif int nsamp_local = (int)(nsamp * this_run->nrate); nrate = n / nsamp_local + 1; double bminbuf[3], bmaxbuf[3]; #ifdef NEW_DECOMPOSITION static int nstep0 = 0; if( nstep0 < nstep_decompose_x){ nsamp = samplingParticle( particle, n, nrate, xsamp_all, ysamp_all, zsamp_all, this_run); My_MPI_Barrier( this_run->MPI_COMM_INTERNAL); time1 += getTime( &nowtime); assert( nsamp <= nmem); determineBoundary( xsamp_all, ysamp_all, zsamp_all, nsamp, this_run, bminbuf, bmaxbuf); } else{ int nsamp_x = 0; int sampx_on = 0; if( nstep0 % nstep_decompose_x == 0){ nsamp_x = samplingParticleX( particle,n, nrate, xsamp_all, this_run); sampx_on = 1; } int nsamp_yz = samplingParticleYZ( particle,n, nrate, ysamp_all, zsamp_all, this_run); determineBoundary2( xsamp_all, ysamp_all, zsamp_all, nsamp_x, nsamp_yz, this_run, bminbuf, bmaxbuf, sampx_on); } nstep0 ++; #else nsamp = samplingParticle( particle, n, nrate, xsamp_all, ysamp_all, zsamp_all, this_run); My_MPI_Barrier( this_run->MPI_COMM_INTERNAL); time1 += getTime( &nowtime); assert( nsamp <= nmem); determineBoundary( xsamp_all, ysamp_all, zsamp_all, nsamp, this_run, bminbuf, bmaxbuf); #endif #ifdef BOUNDARY_SMOOTHING static int nstep = 0; if( this_run->restart_flag == 1){ if( nstep < (nstep_smoothing_boundary-1)){ bminbuf[0] = this_run->bmin[0]; bminbuf[1] = this_run->bmin[1]; bminbuf[2] = this_run->bmin[2]; bmaxbuf[0] = this_run->bmax[0]; bmaxbuf[1] = this_run->bmax[1]; bmaxbuf[2] = this_run->bmax[2]; } } #endif My_MPI_Barrier( this_run->MPI_COMM_INTERNAL); getTime( &nowtime); MPI_Allgather( bminbuf, 3, MPI_DOUBLE, bmin, 3, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); MPI_Allgather( bmaxbuf, 3, MPI_DOUBLE, bmax, 3, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); My_MPI_Barrier( this_run->MPI_COMM_INTERNAL); time1 += getTime( &nowtime); this_run->t.exchange_determine_boundary_comm = time1; #ifndef STATIC_ARRAY delete [] xsamp_all; delete [] ysamp_all; delete [] zsamp_all; #endif #ifdef BOUNDARY_SMOOTHING static double t_bmin[nstep_smoothing_boundary][3]; static int sstep = 0; t_bmin[sstep][0] = bminbuf[0]; t_bmin[sstep][1] = bminbuf[1]; t_bmin[sstep][2] = bminbuf[2]; if( nstep >= (nstep_smoothing_boundary-1)){ double numerator[3] = {0.0, 0.0, 0.0}; for( int i=0; i<nstep_smoothing_boundary; i++){ int h = sstep - i; if( h < 0) h += nstep_smoothing_boundary; double w = (double)( nstep_smoothing_boundary - i); for( int j=0; j<3; j++){ numerator[j] += t_bmin[h][j] * w; } } double fac = 2.0 / (double)nstep_smoothing_boundary / (double)(nstep_smoothing_boundary+1); bminbuf[0] = numerator[0] * fac; bminbuf[1] = numerator[1] * fac; bminbuf[2] = numerator[2] * fac; int inode = this_run->inode; int px, py, pz; getXYZIndex( inode, ndiv, &px, &py, &pz); if( px == 0) bmin[inode][0] = 0.0; if( py == 0) bmin[inode][1] = 0.0; if( pz == 0) bmin[inode][2] = 0.0; MPI_Allgather( bminbuf, 3, MPI_DOUBLE, bmin, 3, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); int px2 = px + 1; if( px2 >= ndiv[0]) bmaxbuf[0] = 1.0; else bmaxbuf[0] = bmin[getVoxelIndex(px2, py, pz, ndiv)][0]; int py2 = py + 1; if( py2 >= ndiv[1]) bmaxbuf[1] = 1.0; else bmaxbuf[1] = bmin[getVoxelIndex(px, py2, pz, ndiv)][1]; int pz2 = pz + 1; if( pz2 >= ndiv[2]) bmaxbuf[2] = 1.0; else bmaxbuf[2] = bmin[getVoxelIndex(px, py, pz2, ndiv)][2]; MPI_Allgather( bmaxbuf, 3, MPI_DOUBLE, bmax, 3, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); //printBoundary( this_run, stderr, bminbuf, bmaxbuf); } nstep ++; sstep ++; if( sstep == nstep_smoothing_boundary) sstep = 0; #endif #ifdef BINARY_BOUNDARY double scale = (double)(1LL<<16); for( int i=0; i<this_run->nnode; i++){ for( int j=0; j<3; j++){ bmin[i][j] = (double)((long long int)( bmin[i][j] * scale)) / scale; bmax[i][j] = (double)((long long int)( bmax[i][j] * scale)) / scale; } } #endif } void exchangeParticle( pParticle particle, pRunParam this_run, double bmin_all[][3], double bmax_all[][3]){ double nowtime = 0.0; double time1 = 0.0; double time2 = 0.0; double time4 = 0.0; getTime(&nowtime); int n = this_run->npart; long long int npart_all = this_run->npart_total; int inode = this_run->inode; int nnode = this_run->nnode; MPI_Datatype MPI_PARTICLE; createMPIParticle( &MPI_PARTICLE); fprintf_verbose( stderr, "#exchangeParticle sortInBoxParticle start\n"); int oldn = sortInBoxParticle( particle, n, bmin_all[inode], bmax_all[inode]); int dn = n - oldn; // number of particle to send time4 += getTime( &nowtime); if( BOUNDARYLOG_ON == 1){ sprintf( cbuf, "%e\t%e\t%e\t%e\t%e\t%e\t%d\t%d\n", this_run->bmin[0], this_run->bmax[0], this_run->bmin[1], this_run->bmax[1], this_run->bmin[2], this_run->bmax[2], oldn, n); mp_print( cbuf, this_run->MPI_COMM_INTERNAL, this_run->boundary_file); } #ifdef USING_MPI_PARTICLE #ifdef STATIC_ARRAY if( dn >= bufsize_largemem0){ cerr << inode << "\t" << dn << "\t" << bufsize_largemem0 << endl; } assert( dn < bufsize_largemem0); static Particle sendbuf[bufsize_largemem0]; #else // STATIC_ARRAY pParticle sendbuf = (pParticle) my_malloc( sizeof(Particle)*dn + 1); #endif // STATIC_ARRAY #else // USING_MPI_PARTICLE double *sendbuf1 = new double[3*dn+1]; float *sendbuf2 = new float[3*dn+1]; IDTYPE *sendbuf3 = new IDTYPE[dn+1]; #endif // USING_MPI_PARTICLE static int nsend[MAXNNODE]; static int sdispls[MAXNNODE]; static int nrecv[MAXNNODE]; static int rdispls[MAXNNODE]; for( int i=0; i<nnode; i++){ nsend[i] = sdispls[i] = nrecv[i] = rdispls[i] = 0; } fprintf_verbose( stderr, "#exchangeParticle particleSortForExchange start\n"); particleSortForExchange( particle, this_run, dn, bmax_all, nsend); for( int i=oldn; i<n; i++){ #ifdef USING_MPI_PARTICLE sendbuf[i-oldn] = particle[i]; #else sendbuf1[3*(i-oldn)+0] = particle[i].xpos; sendbuf1[3*(i-oldn)+1] = particle[i].ypos; sendbuf1[3*(i-oldn)+2] = particle[i].zpos; sendbuf2[3*(i-oldn)+0] = particle[i].xvel; sendbuf2[3*(i-oldn)+1] = particle[i].yvel; sendbuf2[3*(i-oldn)+2] = particle[i].zvel; sendbuf3[i-oldn] = particle[i].id; #endif } /* int offset = 0; for( i=0; i<nnode; i++){ //fprintf( stderr, "%d %d %d\n", inode, nsend[i], dn); int j; for( j=0; j<nsend[i]; j++){ if( sendbuf[offset+j].xpos >= bmax_all[i][0] || sendbuf[offset+j].ypos >= bmax_all[i][1] || sendbuf[offset+j].zpos >= bmax_all[i][2] || sendbuf[offset+j].xpos < bmin_all[i][0] || sendbuf[offset+j].ypos < bmin_all[i][1] || sendbuf[offset+j].zpos < bmin_all[i][2]){ fprintf( stderr, "%d\t%d\t%d\t%d\t%e\t%e\t%e\t%lld\t%e\t%e\n", inode, i, j, nsend[i], sendbuf[offset+j].xpos, sendbuf[offset+j].ypos, sendbuf[offset+j].zpos, sendbuf[offset+j].id, bmin_all[i][2], bmax_all[i][2]); } } offset += nsend[i]; } */ for( int i=1; i<nnode; i++){ sdispls[i] = sdispls[i-1] + nsend[i-1]; } My_MPI_Barrier(this_run->MPI_COMM_INTERNAL); time1 += getTime( &nowtime); MPI_Alltoall( nsend, 1, MPI_INT, nrecv, 1, MPI_INT, this_run->MPI_COMM_INTERNAL); int nrecv_total = nrecv[0]; for( int i=1; i<nnode; i++){ rdispls[i] = rdispls[i-1] + nrecv[i-1]; nrecv_total += nrecv[i]; } #ifndef USING_MPI_PARTICLE double *recvbuf1 = new double[nrecv_total*3]; float *recvbuf2 = new float[nrecv_total*3]; IDTYPE *recvbuf3 = new IDTYPE[nrecv_total]; static int nsend2[MAXNNODE]; static int sdispls2[MAXNNODE]; static int nrecv2[MAXNNODE]; static int rdispls2[MAXNNODE]; for( int i=0; i<nnode; i++){ nsend2[i] = nsend[i] * 3; sdispls2[i] = sdispls[i] * 3; nrecv2[i] = nrecv[i] * 3; rdispls2[i] = rdispls[i] * 3; } #endif int n_scomm = 0; int n_rcomm = 0; static int scomm_inode[MAXNNODE]; static int rcomm_inode[MAXNNODE]; for( int i=0; i<nnode; i++){ if( nsend[i] != 0){ scomm_inode[n_scomm] = i; n_scomm ++; } if( nrecv[i] != 0){ rcomm_inode[n_rcomm] = i; n_rcomm ++; } } this_run->nscomm_exchange = n_scomm; this_run->nrcomm_exchange = n_rcomm; this_run->nsend_ex = dn; this_run->nrecv_ex = nrecv_total; fprintf_verbose( stderr, "#exchangeParticle comm start\n"); #ifdef EXCHANGE_COMM_NONBLOCKING static MPI_Request req_send[MAXNNODE3]; static MPI_Request req_recv[MAXNNODE3]; static MPI_Status st_send[MAXNNODE3]; static MPI_Status st_recv[MAXNNODE3]; //static int flag_send[MAXNNODE3]; //static int flag_recv[MAXNNODE3]; #ifdef USING_MPI_PARTICLE for( int i=0; i<n_rcomm; i++){ int src = rcomm_inode[i]; int e = MPI_Irecv( &particle[oldn+rdispls[src]], nrecv[src], MPI_PARTICLE, src, 0, this_run->MPI_COMM_INTERNAL, req_recv+i); assert( e == MPI_SUCCESS); } for( int i=0; i<n_scomm; i++){ int dest = scomm_inode[i]; MPI_Isend( &sendbuf[sdispls[dest]], nsend[dest], MPI_PARTICLE, dest, 0, this_run->MPI_COMM_INTERNAL, req_send+i); // MPI_Testall( n_rcomm, req_recv, flag_recv, st_recv); // MPI_Testall( i+1, req_send, flag_send, st_send); } MPI_Waitall( n_scomm, req_send, st_send); MPI_Waitall( n_rcomm, req_recv, st_recv); #else // USING_MPI_PARTICLE for( int i=0; i<n_rcomm; i++){ int src = rcomm_inode[i]; MPI_Irecv( &recvbuf1[rdispls2[src]], nrecv2[src], MPI_DOUBLE, src, 0, this_run->MPI_COMM_INTERNAL, req_recv+3*i); MPI_Irecv( &recvbuf2[rdispls2[src]], nrecv2[src], MPI_FLOAT, src, 1, this_run->MPI_COMM_INTERNAL, req_recv+3*i+1); MPI_Irecv( &recvbuf3[rdispls[src]], nrecv[src], MPI_IDTYPE, src, 2, this_run->MPI_COMM_INTERNAL, req_recv+3*i+2); } for( int i=0; i<n_scomm; i++){ int dest = scomm_inode[i]; MPI_Isend( &sendbuf1[sdispls2[dest]], nsend2[dest], MPI_DOUBLE, dest, 0, this_run->MPI_COMM_INTERNAL, req_send+3*i); MPI_Isend( &sendbuf2[sdispls2[dest]], nsend2[dest], MPI_FLOAT, dest, 1, this_run->MPI_COMM_INTERNAL, req_send+3*i+1); MPI_Isend( &sendbuf3[sdispls[dest]], nsend[dest], MPI_IDTYPE, dest, 2, this_run->MPI_COMM_INTERNAL, req_send+3*i+2); // MPI_Testall( n_rcomm*3, req_recv, flag_recv, st_recv); // MPI_Testall( 3*(i+1), req_send, flag_send, st_send); } MPI_Waitall( 3*n_scomm, req_send, st_send); MPI_Waitall( 3*n_rcomm, req_recv, st_recv); #endif // USING_MPI_PARTICLE #else //EXCHANGE_COMM_NONBLOCKING #ifndef EXCHANGE_COMM_SENDRECV #ifdef USING_MPI_PARTICLE MPI_Alltoallv( sendbuf, nsend, sdispls, MPI_PARTICLE, &particle[oldn], nrecv, rdispls, MPI_PARTICLE, this_run->MPI_COMM_INTERNAL); #else MPI_Alltoallv( sendbuf3, nsend, sdispls, MPI_IDTYPE, recvbuf3, nrecv, rdispls, MPI_IDTYPE, this_run->MPI_COMM_INTERNAL); MPI_Alltoallv( sendbuf2, nsend2, sdispls2, MPI_FLOAT, recvbuf2, nrecv2, rdispls2, MPI_FLOAT, this_run->MPI_COMM_INTERNAL); MPI_Alltoallv( sendbuf1, nsend2, sdispls2, MPI_DOUBLE, recvbuf1, nrecv2, rdispls2, MPI_DOUBLE, this_run->MPI_COMM_INTERNAL); #endif #else //EXCHANGE_COMM_SENDRECV MPI_Status stat; int inode_src = (inode + 1) % nnode; for( int k=(nnode-1); k>0; k--){ int inode_dest = (k+inode) % nnode; if( k != (nnode -1)){ inode_src = (inode_src+1) % nnode; if( inode_src == inode) inode_src = (inode_src+1) % nnode; } #ifdef USING_MPI_PARTICLE MPI_Sendrecv( &sendbuf[sdispls[inode_dest]], nsend[inode_dest], MPI_PARTICLE, inode_dest, inode, &particle[oldn+rdispls[inode_src]], nrecv[inode_src], MPI_PARTICLE, inode_src, inode_src, this_run->MPI_COMM_INTERNAL, &stat); #else MPI_Sendrecv( &sendbuf1[sdispls2[inode_dest]], nsend2[inode_dest], MPI_DOUBLE, inode_dest, inode, &recvbuf1[rdispls2[inode_src]], nrecv2[inode_src], MPI_DOUBLE, inode_src, inode_src, this_run->MPI_COMM_INTERNAL, &stat); MPI_Sendrecv( &sendbuf2[sdispls2[inode_dest]], nsend2[inode_dest], MPI_FLOAT, inode_dest, inode, &recvbuf2[rdispls2[inode_src]], nrecv2[inode_src], MPI_FLOAT, inode_src, inode_src, this_run->MPI_COMM_INTERNAL, &stat); MPI_Sendrecv( &sendbuf3[sdispls[inode_dest]], nsend[inode_dest], MPI_IDTYPE, inode_dest, inode, &recvbuf3[rdispls[inode_src]], nrecv[inode_src], MPI_IDTYPE, inode_src, inode_src, this_run->MPI_COMM_INTERNAL, &stat); #endif } #endif //EXCHANGE_COMM_SENDRECV #endif //EXCHANGE_COMM_NONBLOCKING fprintf_verbose( stderr, "#exchangeParticle push start\n"); #ifndef USING_MPI_PARTICLE for( int i=0; i<nrecv_total; i++){ particle[i+oldn].xpos = recvbuf1[i*3+0]; particle[i+oldn].ypos = recvbuf1[i*3+1]; particle[i+oldn].zpos = recvbuf1[i*3+2]; particle[i+oldn].xvel = recvbuf2[i*3+0]; particle[i+oldn].yvel = recvbuf2[i*3+1]; particle[i+oldn].zvel = recvbuf2[i*3+2]; particle[i+oldn].id = recvbuf3[i]; } #endif this_run->npart = oldn + nrecv_total; #ifdef USING_MPI_PARTICLE #ifndef STATIC_ARRAY free( sendbuf); #endif #else delete [] sendbuf1; delete [] sendbuf2; delete [] sendbuf3; delete [] recvbuf1; delete [] recvbuf2; delete [] recvbuf3; #endif // fprintf( stderr, "node:%d\toldn:%d\tn:%d\n", inode, oldn, this_run->npart); /* for protection */ long long int lli_npart_all = (long long int)npart_all; long long int npart_now = 0; long long int this_npart = (long long int)this_run->npart; MPI_Allreduce( &this_npart, &npart_now, 1, MPI_LONG_LONG_INT, MPI_SUM, this_run->MPI_COMM_INTERNAL); if( npart_now != npart_all){ #ifdef NPART_DIFFERENT_DUMP sprintf( cbuf, "npartdiff-%d", inode); ofstream fout( cbuf, ios::out); cerr << oldn << "\t" << this_run->npart << endl; for( int i=oldn; i<this_run->npart; i++){ fout << particle[i].xpos << "\t" << particle[i].ypos << "\t" << particle[i].zpos << "\t" << particle[i].xvel << "\t" << particle[i].yvel << "\t" << particle[i].zvel << "\t" << particle[i].id << endl; } fout.close(); MPI_Barrier( MPI_COMM_WORLD); #endif fprintf( stderr, "npart is different\n"); fprintf( stderr, "%lld\t%lld\n", lli_npart_all, npart_now); exit(0); } time2 += getTime( &nowtime); this_run->t.exchange_make_send_list = time1; this_run->t.exchange_make_send_list_pre = time4; this_run->t.exchange_comm = time2; } /* exchange particle with neighboring node */ void exchangeParticle( pParticle particle, pRunParam this_run, const int *ndiv){ /* * particle array / old_n \/ bn \ * ------------------------------------------------ * \no change node /\send buffer/\recv buffer/ * finished communication * ______________________abcde________edcba * move recv buffer particle to send buffer * particle array ___________________________ * \ new particle array / */ double nowtime = 0.0; getTime(&nowtime); int n = this_run->npart; long long int npart_all = this_run->npart_total; this_run->npart_old = n; int inode = this_run->inode; fprintf_verbose( stderr, "#exchangeParticle determineBoundary start\n"); #ifndef FIXED_BOUNDARY determineBoundary( particle, n, npart_all, ndiv, this_run->bmin_all, this_run->bmax_all, this_run); #endif this_run->bmin[0] = this_run->bmin_all[inode][0]; this_run->bmin[1] = this_run->bmin_all[inode][1]; this_run->bmin[2] = this_run->bmin_all[inode][2]; this_run->bmax[0] = this_run->bmax_all[inode][0]; this_run->bmax[1] = this_run->bmax_all[inode][1]; this_run->bmax[2] = this_run->bmax_all[inode][2]; this_run->t.exchange_determine_boundary = getTime( &nowtime); exchangeParticle( particle, this_run, this_run->bmin_all, this_run->bmax_all); } /* make super particle list */ #ifndef TREE2 void makeSendList( const pTreeTmp tree_tmp, const double cell_length2, const double *cicell, const double *i_half_length, float send_buf[][4], int *nsend, const long long int current_key, pParticle particle, pTreeParam treeparam){ int i, j; int adr = keyToAdr( current_key, tree_tmp->tree_cell, tree_tmp->tree_clistmask); double rcut2 = RADIUS_FOR_PP2; double dr = 0.0; #pragma loop simd for( j=0; j<3; j++){ double drj = cicell[j] - tree_tmp->tree_cell[adr].cm[j]; drj = fabs(drj); if( drj > 0.5) drj = 1.0 - drj; drj -= i_half_length[j]; if( drj > 0) dr += drj * drj; } double theta2_dr2 = treeparam->tree_theta2 * dr; /*fprintf( stdout, "%e\t%e\t%d\t%lld\t%e\t%e\n", dr, sqrt(rcut2), tree_tmp->tree_cell[adr].n, current_key, sqrt(cell_length2), sqrt(theta2_dr2));*/ if( theta2_dr2 > cell_length2){ // theta > d/l if( dr <= rcut2){ send_buf[*nsend][0] = tree_tmp->tree_cell[adr].cm[0]; send_buf[*nsend][1] = tree_tmp->tree_cell[adr].cm[1]; send_buf[*nsend][2] = tree_tmp->tree_cell[adr].cm[2]; send_buf[*nsend][3] = tree_tmp->tree_cell[adr].m; (*nsend) ++; } } else{ if( tree_tmp->tree_cell[adr].n > treeparam->tree_nleaf){ // have child for( i=0; i<8; i++){ int zeroflag = ( tree_tmp->tree_cell[adr].zeroflag>>i) & 1; if( zeroflag == 1) continue; long long int tmpkey = ((current_key<<3) | i); makeSendList( tree_tmp, cell_length2*0.25, cicell, i_half_length, send_buf, nsend, tmpkey, particle, treeparam); } } else{ // lowest cell int start = tree_tmp->tree_cell[adr].first_index; int end = start + tree_tmp->tree_cell[adr].n; for( j=start; j<end; j++){ int ii = tree_tmp->index[j]; #ifdef CLEAN_BOUNDARY_PARTICLE double dx = cicell[0] - particle[ii].xpos; double dy = cicell[1] - particle[ii].ypos; double dz = cicell[2] - particle[ii].zpos; dx = fabs( dx); dy = fabs( dy); dz = fabs( dz); if( dx > 0.5) dx = 1.0 - dx; if( dy > 0.5) dy = 1.0 - dy; if( dz > 0.5) dz = 1.0 - dz; dx -= i_half_length[0]; dy -= i_half_length[1]; dz -= i_half_length[2]; dx += fabs( dx); dy += fabs( dy); dz += fabs( dz); double dr2 = 0.25 * (dx*dx + dy*dy + dz*dz); if( dr2 <= rcut2){ send_buf[*nsend][3] = getMass( &particle[ii], treeparam->uniform_mass); getPos2( &particle[ii], send_buf[*nsend]); (*nsend) ++; } #else send_buf[*nsend][3] = getMass( &particle[ii], treeparam->uniform_mass); getPos2( &particle[ii], send_buf[*nsend]); (*nsend) ++; #endif } } } } #else /* make super particle list */ void makeSendList( const pTreeTmp tree_tmp, const double cell_length2, const double *cicell, const double *i_half_length, float send_buf[][4], int *nsend, const int now_cell, const pTreeParam treeparam, const double (*p_cache)[4]){ double rcut2 = RADIUS_FOR_PP2; pTreeCell tree_cell = tree_tmp->tree_cell; if( tree_cell[now_cell].n > treeparam->tree_nleaf){ double child_cell_length2 = cell_length2 * 0.25; double dr2[8]; double theta2_dr2[8]; for( int i=0; i<8; i++){ int adr = tree_cell[now_cell].next + i; double dx = cicell[0] - tree_cell[adr].cm[0]; double dy = cicell[1] - tree_cell[adr].cm[1]; double dz = cicell[2] - tree_cell[adr].cm[2]; dx = fabs( dx); dy = fabs( dy); dz = fabs( dz); if( dx > 0.5) dx = 1.0 - dx; if( dy > 0.5) dy = 1.0 - dy; if( dz > 0.5) dz = 1.0 - dz; dx -= i_half_length[0]; dy -= i_half_length[1]; dz -= i_half_length[2]; dx += fabs( dx); dy += fabs( dy); dz += fabs( dz); dr2[i] = 0.25 * (dx*dx + dy*dy + dz*dz); theta2_dr2[i] = treeparam->tree_theta2 * dr2[i]; } for( int i=0; i<8; i++){ int adr = tree_cell[now_cell].next + i; if( tree_cell[adr].n == 0) continue; if( theta2_dr2[i] > child_cell_length2){ // theta > d/l if( dr2[i] > rcut2) continue; int ji = *nsend; send_buf[ji][0] = tree_tmp->tree_cell[adr].cm[0]; send_buf[ji][1] = tree_tmp->tree_cell[adr].cm[1]; send_buf[ji][2] = tree_tmp->tree_cell[adr].cm[2]; send_buf[ji][3] = tree_tmp->tree_cell[adr].m; (*nsend) ++; } else{ makeSendList( tree_tmp, child_cell_length2, cicell, i_half_length, send_buf, nsend, adr, treeparam, p_cache); } } } else{ const int start = tree_cell[now_cell].first_index; const int n = tree_cell[now_cell].n; const int nj = *nsend; for( int j=0; j<n; j++){ int ji = nj + j; int pi = start + j; send_buf[ji][0] = p_cache[pi][0]; send_buf[ji][1] = p_cache[pi][1]; send_buf[ji][2] = p_cache[pi][2]; send_buf[ji][3] = p_cache[pi][3]; } (*nsend) += n; } } #endif void makeSendListWrapper( const pTreeTmp tree_tmp, const double cell_length2, const double *dest_bmin, const double *dest_bmax, float (*send_buf)[4], int *nsend, pParticle particle, pTreeParam treeparam, const double (*p_cache)[4]){ double dest_center[3], dest_bsize[3]; for( int j=0; j<3; j++){ dest_center[j] = 0.5 * (dest_bmax[j] + dest_bmin[j]); dest_bsize[j] = 0.5 * (dest_bmax[j] - dest_bmin[j]); } #ifdef TREE2 makeSendList( tree_tmp, cell_length2, dest_center, dest_bsize, send_buf, nsend, 0, treeparam, p_cache); #else makeSendList( tree_tmp, cell_length2, dest_center, dest_bsize, send_buf, nsend, 1, particle, treeparam); #endif } #ifndef TREE2 /*get the number of send list */ int getSendNumber( const pTreeTmp tree_tmp, const double cell_length2, const double *cicell, const double *i_half_length, const long long int current_key, pParticle particle, pTreeParam treeparam){ int nsend = 0; int i, j; int adr = keyToAdr( current_key, tree_tmp->tree_cell, tree_tmp->tree_clistmask); double rcut2 = RADIUS_FOR_PP2; double dr = 0.0; #pragma loop simd for( j=0; j<3; j++){ double drj = cicell[j] - tree_tmp->tree_cell[adr].cm[j]; drj = fabs(drj); if( drj > 0.5) drj = 1.0 - drj; drj -= i_half_length[j]; if( drj > 0) dr += drj * drj; } double theta2_dr2 = treeparam->tree_theta2 * dr; if( theta2_dr2 > cell_length2){ // theta > d/l if( dr <= rcut2){ nsend ++; } } else{ if( tree_tmp->tree_cell[adr].n > treeparam->tree_nleaf){ // have child for( i=0; i<8; i++){ int zeroflag = ( tree_tmp->tree_cell[adr].zeroflag>>i) & 1; if( zeroflag == 1) continue; long long int tmpkey = ((current_key<<3) | i); int nsend2 = getSendNumber( tree_tmp, cell_length2*0.25, cicell, i_half_length, tmpkey, particle, treeparam); nsend += nsend2; } } else{ // lowest cell #ifdef CLEAN_BOUNDARY_PARTICLE for( int i=0; i<tree_tmp->tree_cell[adr].n; i++){ int ii = tree_tmp->tree_cell[adr].first_index + i; int ip = tree_tmp->index[ii]; double dx = cicell[0] - particle[ip].xpos; double dy = cicell[1] - particle[ip].ypos; double dz = cicell[2] - particle[ip].zpos; dx = fabs( dx); dy = fabs( dy); dz = fabs( dz); if( dx > 0.5) dx = 1.0 - dx; if( dy > 0.5) dy = 1.0 - dy; if( dz > 0.5) dz = 1.0 - dz; dx -= i_half_length[0]; dy -= i_half_length[1]; dz -= i_half_length[2]; dx += fabs( dx); dy += fabs( dy); dz += fabs( dz); double dr2 = 0.25 * (dx*dx + dy*dy + dz*dz); if( dr2 <= rcut2) nsend ++; } #else nsend += tree_tmp->tree_cell[adr].n; #endif } } return nsend; } #else int getSendNumber( const pTreeTmp tree_tmp, const double cell_length2, const double *cicell, const double *i_half_length, const int now_cell, const pTreeParam treeparam){ int nsend = 0; double rcut2 = RADIUS_FOR_PP2; pTreeCell tree_cell = tree_tmp->tree_cell; if( tree_cell[now_cell].n > treeparam->tree_nleaf){ double child_cell_length2 = cell_length2 * 0.25; double dr2[8]; double theta2_dr2[8]; for( int i=0; i<8; i++){ int adr = tree_cell[now_cell].next + i; double dx = cicell[0] - tree_cell[adr].cm[0]; double dy = cicell[1] - tree_cell[adr].cm[1]; double dz = cicell[2] - tree_cell[adr].cm[2]; dx = fabs( dx); dy = fabs( dy); dz = fabs( dz); if( dx > 0.5) dx = 1.0 - dx; if( dy > 0.5) dy = 1.0 - dy; if( dz > 0.5) dz = 1.0 - dz; dx -= i_half_length[0]; dy -= i_half_length[1]; dz -= i_half_length[2]; dx += fabs( dx); dy += fabs( dy); dz += fabs( dz); dr2[i] = 0.25 * (dx*dx + dy*dy + dz*dz); theta2_dr2[i] = treeparam->tree_theta2 * dr2[i]; } for( int i=0; i<8; i++){ int adr = tree_cell[now_cell].next + i; if( tree_cell[adr].n == 0) continue; if( theta2_dr2[i] > child_cell_length2){ // theta > d/l if( dr2[i] <= rcut2) nsend ++; } else{ nsend += getSendNumber( tree_tmp, child_cell_length2, cicell, i_half_length, adr, treeparam); } } } else{ nsend += tree_cell[now_cell].n; } return nsend; } #endif int getSendNumberWrapper( const pTreeTmp tree_tmp, const double cell_length2, const double *dest_bmin, const double *dest_bmax, pParticle particle, pTreeParam treeparam){ double dest_center[3], dest_bsize[3]; for( int j=0; j<3; j++){ dest_center[j] = 0.5 * (dest_bmax[j] + dest_bmin[j]); dest_bsize[j] = 0.5 * (dest_bmax[j] - dest_bmin[j]); } #ifdef TREE2 int nsend = getSendNumber( tree_tmp, cell_length2, dest_center, dest_bsize, 0, treeparam); #else int nsend = getSendNumber( tree_tmp, cell_length2, dest_center, dest_bsize, 1, particle, treeparam); #endif return nsend; } /* communicate boundary particle using super-particle */ static float send_buf[bufsize_largemem][4]; static float recv_buf[bufsize_largemem][4]; int sendRecvBoundaryUsingTree( pParticle particle, pTreeParam treeparam, const int n, double bmin_all[][3], double bmax_all[][3], const int *comm_flag, pRunParam this_run, pTreeTmp tree_tmp){ double nowtime = 0.0; double time1 = 0.0; double time2 = 0.0; double time4 = 0.0; getTime(&nowtime); int nnode = this_run->nnode; double maxx = tree_tmp->maxx; // send and receive static int nsend[MAXNNODE]; static int sdispls[MAXNNODE]; static int nrecv[MAXNNODE]; static int rdispls[MAXNNODE]; long long int nsend_total = 0; long long int nrecv_total = 0; for( int i=0; i<nnode; i++){ nsend[i] = sdispls[i] = rdispls[i] = 0; } fprintf_verbose( stderr, "#getSendNumber\n"); getTime( &nowtime); #pragma omp parallel for CHUNK_DECOMPOSITION for( int i=0; i<nnode; i++){ if( comm_flag[i] == 0) continue; nsend[i] = getSendNumberWrapper( tree_tmp, maxx*maxx, this_run->bmin_all[i], this_run->bmax_all[i], particle, treeparam); } for( int i=0; i<nnode; i++) nsend_total += nsend[i]; assert( nsend_total < bufsize_largemem); for( int i=1; i<nnode; i++) sdispls[i] = sdispls[i-1] + nsend[i-1]; fprintf_verbose( stderr, "#comm SendNumber\n"); MPI_Alltoall( nsend, 1, MPI_INT, nrecv, 1, MPI_INT, this_run->MPI_COMM_INTERNAL); nrecv_total = nrecv[0]; for( int i=1; i<nnode; i++){ rdispls[i] = rdispls[i-1] + nrecv[i-1]; nrecv_total += nrecv[i]; } assert( nrecv_total < bufsize_largemem); #ifdef BOUNDARY_COMM_NONBLOCKING fprintf_verbose( stderr, "#start comm\n"); static int comm_inode[MAXNNODE]; int ncomm = 0; for( int i=0; i<nnode; i++){ if( comm_flag[i] == 0) continue; comm_inode[ncomm] = i; ncomm ++; } static MPI_Request req_send[MAXNNODE]; static MPI_Request req_recv[MAXNNODE]; static MPI_Status st[MAXNNODE]; for( int i=0; i<ncomm; i++){ int src = comm_inode[i]; MPI_Irecv( recv_buf[rdispls[src]], 4*nrecv[src], MPI_FLOAT, src, 0, this_run->MPI_COMM_INTERNAL, req_recv+i); } #ifndef BOUNDARY_COMM_NONBLOCKING_OVERLAP #pragma omp parallel for CHUNK_DECOMPOSITION for( int i=0; i<ncomm; i++){ int nsend0 = 0; int dest = comm_inode[i]; makeSendListWrapper( tree_tmp, maxx*maxx, this_run->bmin_all[dest], this_run->bmax_all[dest], &send_buf[sdispls[dest]], &nsend0, particle, treeparam, p_cache); assert( nsend0 == nsend[dest]); } fprintf_verbose( stderr, "#end makeSendList\n"); time1 += getTime(&nowtime); for( int i=0; i<ncomm; i++){ int dest = comm_inode[i]; MPI_Isend( send_buf[sdispls[dest]], 4*nsend[dest], MPI_FLOAT, dest, 0, this_run->MPI_COMM_INTERNAL, req_send+i); //MPI_Testall( ncomm, req_recv, flag_recv, st); //MPI_Testall( i+1, req_send, flag_send, st); } #else //BOUNDARY_COMM_NONBLOCKING_OVERLAP for( int i=0; i<ncomm; i++){ int nsend0 = 0; int dest = comm_inode[i]; makeSendListWrapper( tree_tmp, maxx*maxx, this_run->bmin_all[dest], this_run->bmax_all[dest], &send_buf[sdispls[dest]], &nsend0, particle, treeparam, p_cache); assert( nsend0 == nsend[dest]); MPI_Isend( send_buf[sdispls[dest]], 4*nsend0, MPI_FLOAT, dest, 0, this_run->MPI_COMM_INTERNAL, req_send+i); //MPI_Testall( ncomm, req_recv, flag_recv, st); //MPI_Testall( i+1, req_send, flag_send, st); } #endif MPI_Waitall( ncomm, req_send, st); MPI_Waitall( ncomm, req_recv, st); My_MPI_Barrier(this_run->MPI_COMM_INTERNAL); fprintf_verbose( stderr, "#end comm\n"); time2 += getTime(&nowtime); #else //BOUNDARY_COMM_NONBLOCKING MPI_Status stat; #pragma omp parallel for CHUNK_DECOMPOSITION for( int i=0; i<nnode; i++){ nsend[i] = 0; if( comm_flag[i] != 0){ makeSendListWrapper( tree_tmp, maxx*maxx, this_run->bmin_all[dest], this_run->bmax_all[dest], &send_buf[sdispls[dest]], &nsend0, particle, treeparam, p_cache); } } My_MPI_Barrier(this_run->MPI_COMM_INTERNAL); time1 += getTime(&nowtime); int inode = this_run->inode; int inode_src = (inode + 1) % nnode; for( int k=(nnode-1); k>0; k--){ int inode_dest = (k+inode) % nnode; if( k != (nnode -1)){ inode_src = (inode_src+1) % nnode; if( inode_src == inode) inode_src = (inode_src+1) % nnode; } MPI_Sendrecv( send_buf[sdispls[inode_dest]], 4*nsend[inode_dest], MPI_FLOAT, inode_dest, inode, recv_buf[rdispls[inode_src]], 4*nrecv[inode_src] , MPI_FLOAT, inode_src , inode_src, this_run->MPI_COMM_INTERNAL, &stat); } My_MPI_Barrier(this_run->MPI_COMM_INTERNAL); time2 += getTime(&nowtime); #endif //BOUNDARY_COMM_NONBLOCKING #pragma omp parallel for for( int i=0; i<nrecv_total; i++){ int ip = n+i; particle[ip].xpos = recv_buf[i][0]; particle[ip].ypos = recv_buf[i][1]; particle[ip].zpos = recv_buf[i][2]; particle[ip].xvel = recv_buf[i][3]; particle[ip].id = -1; } time4 += getTime(&nowtime); this_run->t.pp_get_boundary_make_send_list = time1; this_run->t.pp_get_boundary_comm = time2; this_run->t.pp_get_boundary_push = time4; this_run->nsend_tree = nsend_total; return nrecv_total; } void determineCommNode( double bmin_all[][3], double bmax_all[][3], int *comm_flag, pRunParam this_run){ int nnode = this_run->nnode; int inode = this_run->inode; double icenter[3], ibsize[3], ibsize2[3];; for( int j=0; j<3; j++){ icenter[j] = 0.5 * (bmax_all[inode][j] + bmin_all[inode][j]); ibsize[j] = 0.5 * (bmax_all[inode][j] - bmin_all[inode][j]); ibsize2[j] = ibsize[j] + SFT_FOR_PM; } for( int i=0; i<nnode; i++){ comm_flag[i] = 1; for( int j=0; j<3; j++){ double center = 0.5 * ( bmax_all[i][j] + bmin_all[i][j] ); double bsize = 0.5 * ( bmax_all[i][j] - bmin_all[i][j] ); double drj = icenter[j] - center; drj = fabs(drj); if( drj > 0.5) drj = 1.0 - drj; double max_length_j = ibsize2[j] + bsize; if( drj > max_length_j) comm_flag[i] = 0; } } comm_flag[inode] = 0; int nnode_comm = 0; for( int i=0; i<nnode; i++){ if( comm_flag[i] == 1) nnode_comm ++; } this_run->ncomm_tree = nnode_comm; } int getBoundaryParticle( pParticle particle, pRunParam this_run, TreeParam *treeparam #ifdef BUFFER_FOR_TREE ,TreeTmp &tree_tmp #endif ){ double nowtime = 0.0; getTime(&nowtime); int n = this_run->npart; double (*bmin_all)[3] = this_run->bmin_all; double (*bmax_all)[3] = this_run->bmax_all; static int comm_flag[MAXNNODE]; determineCommNode( bmin_all, bmax_all, comm_flag, this_run); this_run->t.pp_get_boundary_determine_comm_node = getTime(&nowtime); #ifndef BUFFER_FOR_TREE TreeTmp tree_tmp; TreeTmpTreeTmp( &tree_tmp, treeparam, n); #else TreeTmpTreeTmp( &tree_tmp, n, 0); #endif fprintf_verbose( stderr, "#PP getBoundaryParticle makeKey\n"); tree_tmp.maxx = makeKey( particle, tree_tmp.key, n); static int nstep = 0; if( nstep % SORT_STEP == 0){ #ifndef CALCPOT fprintf_verbose( stderr, "#PP getBoundaryParticle Sort start\n"); qsortPivotWrapper( particle, tree_tmp.key, n, NLEVEL_PARTICLE_SORT, NCHUNK_QSORT); this_run->t.pp_particle_sort = getTime(&nowtime); #endif } else{ fprintf_verbose( stderr, "#PP getBoundaryParticle qsort\n"); qsortPivotWrapper( tree_tmp.index, tree_tmp.key, n, NLEVEL_KEY_SORT, NCHUNK_QSORT); this_run->t.pp_get_boundary_make_key_sort = getTime(&nowtime); } nstep ++; #ifdef TREE_PARTICLE_CACHE fprintf_verbose( stderr, "#PP getBoundaryParticle copyPCache\n"); copyPCache( particle, tree_tmp.index, n, treeparam->uniform_mass); #endif fprintf_verbose( stderr, "#PP getBoundaryParticle treeConstruction\n"); int nwalk = 0; // for i-particle int key_level = 63; int ipflag = 0; //1:i-particle 0:upper 2:lower #ifdef TREE2 tree_tmp.tree_cell[0].first_index = 0; tree_tmp.tree_cell[0].n = n; tree_tmp.tree_cell[0].next = 1; #ifdef TREECONSTRUCTION_PARALLEL nwalk = treeConstructionParallel( &tree_tmp, n, tree_tmp.walklist, treeparam, p_cache); #else int ncell_all = 1; treeConstruction( &tree_tmp, 0, n, 1, key_level, tree_tmp.walklist, &nwalk, ipflag, 0, treeparam, &ncell_all, p_cache); #endif #else //TREE2 int col_cell_index = tree_tmp.tree_clistmask + 1; //for hash collision tree_tmp.tree_cell[1].key = 1; tree_tmp.tree_cell[1].n = n; treeConstruction( tree_tmp.tree_cell, tree_tmp.key, tree_tmp.index, particle, 0, n, tree_tmp.tree_clistmask, &col_cell_index, 1, key_level, tree_tmp.walklist, &nwalk, ipflag, 1, treeparam); #endif//TREE2 this_run->t.pp_get_boundary_construct_tree = getTime(&nowtime); fprintf_verbose( stderr, "#PP getBoundaryParticle sendRecvBoundaryUsingTree\n"); int bn = sendRecvBoundaryUsingTree( particle, treeparam, n, bmin_all, bmax_all, comm_flag, this_run, &tree_tmp); #ifndef BUFFER_FOR_TREE TreeTmpDTreeTmp( &tree_tmp); #endif return bn; } void createMPIParticle( MPI_Datatype *MPI_PARTICLE){ MPI_Type_contiguous( sizeof(Particle), MPI_CHAR, MPI_PARTICLE); MPI_Type_commit( MPI_PARTICLE); } } // namespace ParticleMesh } // namespace ParticleSimulator
28.334547
128
0.631246
subarutaro
bc507b82a15ddcf6137dbb7d418e83b632962315
655
hpp
C++
src/mxd.hpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
[ "MIT" ]
2
2018-11-06T18:57:29.000Z
2018-11-06T19:06:36.000Z
src/mxd.hpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
[ "MIT" ]
27
2018-11-12T23:45:43.000Z
2019-01-21T15:39:18.000Z
src/mxd.hpp
DavidR86/mxd
bf0a72305701dd5c76c2b3daa4bdba14d638b29d
[ "MIT" ]
3
2018-11-08T00:38:49.000Z
2020-06-18T04:40:11.000Z
// -*- coding:utf-8; mode:c++; mode:auto-fill; fill-column:80; -*- /// @file mxd.hpp /// @brief /// @author J. Arrieta <Juan.Arrieta@nablazerolabs.com> /// @date November 13, 2018 /// @copyright (C) 2018 Nabla Zero Labs #pragma once // C++ Standard Library namespace nzl { /// @brief Initialize mxd. /// @throw std::runtime_error if initialization is not successful. void initialize(); /// @brief Terminate mxd. void terminate() noexcept; /// @brief Throws an exception unless there is a current OpenGL context. /// @throws std::runtime_error if there is no active OpenGL context. void requires_current_context(); } // namespace nzl
24.259259
72
0.683969
DavidR86
bc512300cf211cac876998370987f2d78c9adb65
1,888
hpp
C++
src/Parser.hpp
yatsuha4/lilyan
6005667fb0bc887a74be8957b462f9963a75a6b6
[ "MIT" ]
null
null
null
src/Parser.hpp
yatsuha4/lilyan
6005667fb0bc887a74be8957b462f9963a75a6b6
[ "MIT" ]
null
null
null
src/Parser.hpp
yatsuha4/lilyan
6005667fb0bc887a74be8957b462f9963a75a6b6
[ "MIT" ]
null
null
null
/***********************************************************************//** @file ***************************************************************************/ #pragma once #include "Grammer.hpp" #include "Output.hpp" #include "Action.hpp" /***********************************************************************//** @brief ***************************************************************************/ class Parser : public Grammer { using super = Grammer; private: std::string className_; std::string rulePrefix_; Output output_; std::vector<std::shared_ptr<Action::Func>> actionFuncs_; public: Parser(); ~Parser() override = default; Parser& setClassName(const decltype(className_)& className) { className_ = className; return *this; } const auto& getClassName() const { return className_; } auto& getOutput() { return output_; } void parse(const std::filesystem::path& path); void puts(const std::string& text); bool skip() override; protected: std::any onGetToken(const std::string& pattern) override; std::any onRules(const std::any&) override; std::any onRule(const std::smatch&, const std::any&) override; std::any onSemantics(const std::any&) override; std::any onSemantic(const std::any&, const std::any&) override; std::any onTokens(const std::any&) override; std::any tokenEof() override; std::any tokenRule(const std::smatch&, const std::any&) override; std::any tokenString(const std::string&) override; std::any tokenRegexp(const std::string&) override; std::any onActionRule(const std::smatch&, const std::any&) override; std::any onActionConst(const std::smatch&) override; std::any onActionArg(const std::any&) override; std::any onArgs(const std::any&, const std::any&) override; std::any onArg(const std::smatch&) override; private: void putCpp(const Rules& rules); };
28.606061
77
0.581568
yatsuha4
bc5cd5834144b4965f8e7fbfa8e2b9e1db2d595c
470
cpp
C++
option.cpp
sovaz1997/Zevra
cef3318279f9092e8e1a046ad74492c39cdbd67e
[ "Apache-2.0" ]
3
2017-03-03T18:49:47.000Z
2018-03-11T12:51:34.000Z
option.cpp
sovaz1997/Zevra
cef3318279f9092e8e1a046ad74492c39cdbd67e
[ "Apache-2.0" ]
6
2016-10-11T18:17:56.000Z
2016-11-27T11:46:20.000Z
option.cpp
sovaz1997/Zevra
cef3318279f9092e8e1a046ad74492c39cdbd67e
[ "Apache-2.0" ]
12
2018-01-17T22:23:15.000Z
2020-02-22T19:29:42.000Z
#include "option.hpp" Option::Option() : UCI_AnalyseMode(false) {} void Option::print() { std::cout << "option name Clear Hash type button\n"; std::cout << "option name Hash type spin default 256 min " << min_hash_size << " max "<< max_hash_size << "\n"; std::cout << "option name UCI_AnalyseMode type check default false\n"; std::cout << "option name Move Overhead type spin default 30 min " << minMoveOverhead << " max " << maxMoveOverhead << "\n"; }
42.727273
126
0.657447
sovaz1997
bc64bb3d8b67cbb7348a0c554dcf9406fa90178c
1,059
cpp
C++
RegisterFile.cpp
AaqilZ/RISK-Non-pipelined-Processor-Simulation
148b5e8cc6b71296f524e5cef62225cb7052be9e
[ "MIT" ]
null
null
null
RegisterFile.cpp
AaqilZ/RISK-Non-pipelined-Processor-Simulation
148b5e8cc6b71296f524e5cef62225cb7052be9e
[ "MIT" ]
null
null
null
RegisterFile.cpp
AaqilZ/RISK-Non-pipelined-Processor-Simulation
148b5e8cc6b71296f524e5cef62225cb7052be9e
[ "MIT" ]
null
null
null
#include "RegisterFile.h" #include "Utilities.h" void RegisterFile:: print(){ if(writeToFile){ o << "*********** Register File ***********" << std::endl; o << "---Inputs---" << std::endl; o << "Read Register 1:" << readReg1 << std::endl; o << "Read Register 2:" << readReg2 << std::endl; o << "Write Register :" << writeReg << std::endl; o << "Write Data 1:" << writeData << std::endl; o << "---Outputs---" << std::endl; o << "Read Data 1:" << readData1 << std::endl; o << "Read Data 2:" << readData2 << std::endl; } std::cout << "*********** Register File ***********" << std::endl; std::cout << "---Inputs---" << std::endl; std::cout << "Read Register 1:" << readReg1 << std::endl; std::cout << "Read Register 2:" << readReg2 << std::endl; std::cout << "Write Register :" << writeReg << std::endl; std::cout << "Write Data 1:" << writeData << std::endl; std::cout << "---Outputs---" << std::endl; std::cout << "Read Data 1:" << readData1 << std::endl; std::cout << "Read Data 2:" << readData2 << std::endl; }
40.730769
68
0.524079
AaqilZ
bc65200dd0dc4a52b859c40c98bf8417f5bd67f5
1,150
cpp
C++
src/handlers/file/FileOpenHandler.cpp
Aerijo/latex-language-server
fbd520e40e7878ca9b114e408b21b6b1e181a875
[ "MIT" ]
4
2019-04-08T17:03:24.000Z
2019-09-13T17:20:20.000Z
src/handlers/file/FileOpenHandler.cpp
Aerijo/latex-language-server
fbd520e40e7878ca9b114e408b21b6b1e181a875
[ "MIT" ]
null
null
null
src/handlers/file/FileOpenHandler.cpp
Aerijo/latex-language-server
fbd520e40e7878ca9b114e408b21b6b1e181a875
[ "MIT" ]
null
null
null
#include <iostream> #include <filesystem/File.h> #include <filesystem/FileManager.h> #include <biber/BibIndexer.h> #include <lconfig.h> #include "FileOpenHandler.h" void FileOpenHandler::run (optional<Value> &params) { if (!params) { handleMissingFileOpenParams(); return; } Value &value = *params; Value &textDocument = value["textDocument"]; string uri = textDocument["uri"].GetString(); string languageId = textDocument["languageId"].GetString(); versionNum version = textDocument["version"].GetUint64(); std::cerr << "Opened " << uri << " with ID:" << languageId << ", v" << version << "\n"; string text = textDocument["text"].GetString(); File *file = new File { uri, languageId, version, text }; file->setupParser(); FileManager::add(uri, file); if (file->type == File::Type::Bib && file->hasParser) { BibIndexer indexer { file, g_config->bibtex.style }; indexer.completeIndex(); } } void FileOpenHandler::handleMissingFileOpenParams () { std::cerr << "Missing file open params!! Possibly out of sync!!\n"; // TODO: Request resync when this happens }
25.555556
91
0.654783
Aerijo
bc658dd458b5532dcdd1d02c79a284b34b91d4a1
1,398
hpp
C++
include/user_view.hpp
aaronamk/WM-GDC-Project-Parry
77c829e2ea241a3d0a47ea1263b10afb20d76ca2
[ "MIT" ]
7
2020-11-11T17:36:07.000Z
2021-09-23T00:19:39.000Z
include/user_view.hpp
aaronamk/WM-GDC-Project-Parry
77c829e2ea241a3d0a47ea1263b10afb20d76ca2
[ "MIT" ]
79
2020-12-06T21:42:56.000Z
2021-08-24T03:09:44.000Z
include/user_view.hpp
aaronamk/WM-GDC-Project-Parry
77c829e2ea241a3d0a47ea1263b10afb20d76ca2
[ "MIT" ]
5
2021-01-29T12:27:13.000Z
2021-04-24T01:52:53.000Z
#ifndef USER_VIEW_HPP #define USER_VIEW_HPP #include <chrono> #include <list> #include <memory> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <box2d/box2d.h> #include "view.hpp" #include "game_state_factory.hpp" class GameController; class Actor; class Pari; /** * Draw the screen for the player */ class UserView : public View { public: UserView(std::shared_ptr<GameController> game); const bool &isRunning(void) { return this->running; }; void terminate(void) { this->running = false; }; /** * Draw the screen. */ void drawScreen(void); void update(void) override; private: bool running = true; std::chrono::steady_clock::time_point lastUpdate; std::shared_ptr<GameController> game; std::shared_ptr<sf::RenderWindow> window; GameStateFactory gameStateFactory; std::shared_ptr<Pari> character; sf::Music musicTrack; /** * Respond to key press */ void pressEvent(sf::Event::KeyEvent key); /** * Respond to mouse press */ void pressEvent(sf::Event::MouseButtonEvent button); /** * Respond to key release */ void releaseEvent(sf::Event::KeyEvent key); /** * Respond to mouse release */ void releaseEvent(sf::Event::MouseButtonEvent button); /** * Respond to events */ void listen(void); /** * Center the view on an actor. * * @param actor to center on */ void viewFollow(const Actor &actor); }; #endif
16.642857
55
0.693133
aaronamk
bc66c348c440aa1bc034ee555b6df4b673b4455c
31,809
cc
C++
src/KnowledgeBase.cc
mnowotnik/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
4
2017-01-04T17:22:55.000Z
2018-12-08T02:10:18.000Z
src/KnowledgeBase.cc
Mike-Now/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
null
null
null
src/KnowledgeBase.cc
Mike-Now/fovris
82f692743fa6c96fef05041e686d716b03c22f07
[ "BSD-3-Clause" ]
1
2022-03-24T05:26:13.000Z
2022-03-24T05:26:13.000Z
#include "KnowledgeBase.h" #include "Utils.h" #include "DataPool.h" #include "KB/KBRuleDisjunct.h" #include "Pred/BinPredicateFunction.h" #include <cassert> #include <functional> #include <set> #include <utility> namespace fovris { namespace { struct VarInfo { TermType type; bool satisfied; }; /** * @param safe can the variable stand on its own; i.e., is not unsafe or in * the head */ void calcVarDiff(const std::vector<Term> &terms, const std::vector<TermType> &types, std::map<Term, VarInfo> &varDiff, bool safe) { assert(terms.size() == types.size()); auto termsIt = terms.begin(); auto typesIt = types.begin(); for (; termsIt != terms.end(); termsIt++, typesIt++) { auto &term = *termsIt; auto type = *typesIt; if (IsVar(term)) { if (!Contains(varDiff, term)) { varDiff.insert({term, {type, safe}}); } else { if (safe) { varDiff[term].satisfied = true; } if (varDiff[term].type != type) { throw InvalidInputException("Type of variable is not the " "same in every literal. " "Variable", term); } } } } } void checkDomainsTerms(const std::vector<TermType> &colDomains, const std::vector<Term> &terms) { if (colDomains.size() != terms.size()) { throw InvalidInputException("Wrong arity(", terms.size(), "). Should be ", colDomains.size(), "."); } for (size_t i = 0; i < terms.size(); ++i) { if (!IsVar(terms[i]) && colDomains[i] != terms[i].getType()) { throw InvalidInputException("Wrong constant type (should be ", colDomains[i], " or variable) at ", i, " index."); } } } void checkDomainsGroundTerms(const std::vector<TermType> &colDomains, const std::vector<Term> &terms) { if (colDomains.size() != terms.size()) { throw InvalidInputException("Wrong arity(", terms.size(), "). Should be ", colDomains.size(), "."); } for (size_t i = 0; i < terms.size(); ++i) { if (colDomains[i] != terms[i].getType() && !CanBe(terms[i], colDomains[i])) { throw InvalidInputException("Wrong constant type (should be ", colDomains[i], ") at ", i, " index."); } } } TermType getTermTypeFromMap(const Term &term, const std::map<Term, VarInfo> &varDiff) { auto it = varDiff.find(term); if (it == varDiff.end()) { throw InvalidInputException("Unknown variable: '", term, "'."); } return it->second.type; } void checkTermsForBuiltinPredicate(const std::vector<Term> &terms, const std::map<Term, VarInfo> &varDiff) { TermType a, b; if (terms[0].getType() == TermType::Var) { a = getTermTypeFromMap(terms[0], varDiff); } else { a = terms[0].getType(); } if (terms[1].getType() == TermType::Var) { b = getTermTypeFromMap(terms[1], varDiff); } else { b = terms[1].getType(); } if (a == b) { return; } if (a == TermType::Integer && b == TermType::Real) { return; } if (a == TermType::Real && b == TermType::Integer) { return; } throw InvalidInputException("Incompatible types in predicate(", a, " and ", b, ")."); } void checkFunction(const RuleLiteral &literal, const std::map<Term, VarInfo> &varDiff) { if (!literal.isBuiltinFunction()) { return; } if (literal.getTerms().size() != 2) { throw InvalidInputException("Wrong arity(", literal.getTerms().size(), "). Should be ", 2, "."); } try { checkTermsForBuiltinPredicate(literal.getTerms(), varDiff); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In literal: '", literal, "'."); } } const RelationDef &checkLiteral( const std::map<std::string, std::reference_wrapper<const RelationDef>> & relDefMap, const Literal &literal) { auto &pred = literal.getPredicateSymbol(); auto lIt = relDefMap.find(pred); if (lIt == relDefMap.end()) { throw InvalidInputException("Relation '", pred, "' not defined.'"); } checkDomainsTerms(lIt->second.get().getTypes(), literal.getTerms()); return lIt->second; } void checkLiteral( const std::map<std::string, std::reference_wrapper<const RelationDef>> & relDefMap, const RuleLiteral &literal) { if (!Contains(relDefMap, literal.getPredicateSymbol())) { if (!literal.isFunction()) { throw InvalidInputException("Unknown relation: '", literal.getPredicateSymbol(), "'."); } return; } checkLiteral(relDefMap, dynamic_cast<const Literal &>(literal)); } void checkFact( const std::map<std::string, std::reference_wrapper<const RelationDef>> relDefMap, const GroundLiteral &grndLiteral) { auto lIt = relDefMap.find(grndLiteral.getPredicateSymbol()); if (lIt == relDefMap.end()) { throw InvalidInputException( "Relation '", grndLiteral.getPredicateSymbol(), "' not defined. In literal: '", grndLiteral, "'."); } try { checkDomainsGroundTerms(lIt->second.get().getTypes(), grndLiteral.getTerms()); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In literal: '", grndLiteral, "'."); } } } class KnowledgeBaseImpl { public: // KnowledgeBase API Module retrieveModule(const std::string &moduleName) const; std::vector<GroundLiteral> retrieveRelation(const std::string &moduleName, const std::string &relationName) const; void addModule(const Module &module); RelationDef getRelationDef(const std::string &module, const std::string &rel) const; const std::deque<KBModule> getKBModules() const; ResultFact makeResultFact(const Array<KBGroundTerm> &tuple, TruthValue value, const std::vector<TermType> &types) const; Rule convertKBRule(const KBRule &rule, const KBModule &module) const; Literal convertKBHeadLiteral(const KBHeadLiteral &literal) const; RuleLiteral convertKBRuleLiteral(const KBRuleLiteral &literal, const KBModule &module) const; GroundLiteral retrieveGroundLiteral(const KBTuple &tuple, const std::string &relName, const std::vector<TermType> &types) const; GroundLiteral retrieveGroundLiteral(unsigned relId, const KBTuple &tuple) const; KBQuery convertQuery(const Query &query) const; // private unsigned queryModuleId(const std::string &module) const; unsigned queryRelationId(unsigned modId, const std::string &rel) const; TermType queryTermType(unsigned relationId, unsigned idx) const; std::vector<GroundLiteral> retrieveRelation(unsigned relId) const; unsigned addRelation(unsigned modId, const RelationDef &def); void addFact(unsigned modId, const GroundLiteral &fact); // convert api to kb KBRule convertRule(unsigned modId, const Rule &rule); KBHeadLiteral convertLiteral(unsigned modId, const Literal &literal); KBGroundLiteral convertGroundLiteral(unsigned modId, const GroundLiteral &literal); KBRuleLiteral convertRuleLiteral(unsigned modId, const RuleLiteral &literal); KBRuleFunction convertRuleFunction(const RuleLiteral &literal, const std::map<std::string, TermType> &typeMap); KBTerm convertTerm(const Term &term); KBGroundTerm convertGroundTerm(const Term &term); void validateModule(const Module &module) const; void checkRuleLiteral( const std::map<std::string, std::reference_wrapper<const RelationDef>> & relDefMap, const RuleLiteral &rl, std::map<Term, VarInfo> &varsDiff) const; void checkRule( const std::map<std::string, std::reference_wrapper<const RelationDef>> & relDefMap, const Rule &rule) const; std::deque<KBRelation> relations_; std::deque<KBModule> modules_; DataPool<std::string> moduleNamePool_; DataPool<std::pair<unsigned, std::string>> relSymPool_; TermMapper termMapper_; std::map<std::string, TermType> makeTypeMap(const RuleDisjunct &disjunct, unsigned modId) const; }; const TermMapper &KnowledgeBase::getTermMapper() const { return impl_->termMapper_; } KBRelation &KnowledgeBase::getKBRelation(unsigned relId) { return impl_->relations_[relId]; } const KBRelation &KnowledgeBase::getKBRelation(unsigned relId) const { return impl_->relations_[relId]; } const std::deque<KBModule> &KnowledgeBase::getKBModules() const { return impl_->modules_; } KnowledgeBase::~KnowledgeBase() {} KnowledgeBase::KnowledgeBase() : impl_(std::make_unique<KnowledgeBaseImpl>()) {} KnowledgeBase &KnowledgeBase::operator=(KnowledgeBase &&move) { impl_ = std::move(move.impl_); return *this; } void KnowledgeBase::addModule(const Module &module) { impl_->addModule(module); } const std::deque<KBModule> KnowledgeBaseImpl::getKBModules() const { return modules_; } void KnowledgeBaseImpl::checkRuleLiteral( const std::map<std::string, std::reference_wrapper<const RelationDef>> & relDefMap, const RuleLiteral &rl, std::map<Term, VarInfo> &varsDiff) const { if (!rl.isExternal()) { if (rl.hasConstraint()) { throw InvalidInputException( "'in' operator can only be defined for external literal: '", rl, "'."); } try { checkLiteral(relDefMap, rl); if (!rl.isFunction()) { calcVarDiff(rl.getTerms(), relDefMap.find(rl.getPredicateSymbol()) ->second.get() .getTypes(), varsDiff, true); return; } } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In literal: '", rl, "'."); } return; } unsigned modId, relId; try { modId = moduleNamePool_.queryId(*rl.getExternalModule()); } catch (std::out_of_range &e) { throw InvalidInputException("Module '", *rl.getExternalModule(), "' not found: '", rl, "'."); } try { relId = relSymPool_.queryId({modId, rl.getPredicateSymbol()}); } catch (std::out_of_range &e) { throw InvalidInputException("Relation('", rl.getPredicateSymbol(), "')in external literal not found: '", rl, "'."); } try { checkDomainsTerms(relations_[relId].colDomains, rl.getTerms()); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In literal: '", rl, "'."); } bool satisfy = true; if (rl.isUnsafe()) { satisfy = false; } calcVarDiff(rl.getTerms(), relations_[relId].colDomains, varsDiff, satisfy); } std::string unsatisfiedVars(const std::map<Term, VarInfo> &varsDiff) { using Pair = std::remove_reference<decltype(varsDiff)>::type::value_type; return printIterable( Filter(varsDiff, [](const Pair &p) { return !p.second.satisfied; }), ",", [](const Pair &p) { return p.first; }); } void KnowledgeBaseImpl::checkRule( const std::map<std::string, std::reference_wrapper<const RelationDef>> & relDefMap, const Rule &rule) const { std::map<Term, VarInfo> varsDiff; auto typesIt = relDefMap.find(rule.getHead().getPredicateSymbol()); if (typesIt == relDefMap.end()) { throw InvalidInputException("No such relation '", rule.getHead().getPredicateSymbol(), "' defined in the module."); } calcVarDiff(rule.getHead().getTerms(), typesIt->second.get().getTypes(), varsDiff, false); try { checkLiteral(relDefMap, rule.getHead()); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In literal: '", rule.getHead(), "'. In the head of rule: ", rule, "."); } for (auto &disjunct : rule.getDisjuncts()) { for (auto &rl : disjunct.getBody()) { try { checkRuleLiteral(relDefMap, rl, varsDiff); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In rule: ", rule, "."); } } for (auto &rl : disjunct.getBody()) { try { checkFunction(rl, varsDiff); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In rule: ", rule, "."); } } bool allVarsSatisfied = AllOf(varsDiff, [](const std::pair<Term, VarInfo> &p) { return p.second.satisfied; }); if (!allVarsSatisfied) { throw InvalidInputException("Not all variables (", unsatisfiedVars(varsDiff), ") are covered in rule: ", rule, "."); } } } void KnowledgeBaseImpl::addModule(const Module &module) { validateModule(module); auto modId = moduleNamePool_.insert(module.getName()).first; std::vector<unsigned> relationIds; std::vector<std::reference_wrapper<KBRelation>> relationRefs; std::vector<KBRule> rules; // add empty relations and relation ids to current KBModule for (auto &relDef : module.getRelations()) { unsigned relId = addRelation(modId, relDef); relationIds.push_back(relId); relationRefs.push_back({relations_[relId]}); } // add rules to current KBModule for (auto &rule : module.getRules()) { rules.push_back(convertRule(modId, rule)); } // add facts to relations for (auto &fact : module.getFacts()) { addFact(modId, fact); } for(auto& relationRef : relationRefs){ relationRef.get().finalize(); } modules_.emplace_back(module.getName(), modId, std::move(rules), std::move(relationIds), std::move(relationRefs)); } void KnowledgeBaseImpl::validateModule(const Module &module) const { if (moduleNamePool_.exists(module.getName())) { throw InvalidInputException("Module '", module.getName(), "' is already defined."); } std::map<std::string, std::reference_wrapper<const RelationDef>> relationDefMap; for (auto &relDef : module.getRelations()) { auto ret = relationDefMap.insert({relDef.getPredicateSymbol(), relDef}); if (!ret.second) { throw InvalidInputException( "Relation '", relDef.getPredicateSymbol(), "' defined more than once in the module '", module.getName(), "'."); } } try { for (auto &rule : module.getRules()) { checkRule(relationDefMap, rule); } for (auto &fact : module.getFacts()) { checkFact(relationDefMap, fact); } } catch (InvalidInputException &e) { throw InvalidInputException("Error in module '", module.getName(), "': ", e.what()); } } Module KnowledgeBase::retrieveModule(const std::string &moduleName) const { return impl_->retrieveModule(moduleName); } Module KnowledgeBaseImpl::retrieveModule(const std::string &moduleName) const { unsigned modId = queryModuleId(moduleName); const KBModule &kbm = modules_[modId]; std::vector<GroundLiteral> facts; std::vector<Rule> rules; std::vector<RelationDef> relations; for (auto relId : kbm.relationIds) { auto &kbr = relations_[relId]; const std::string relName = relSymPool_.get(relId).second; relations.push_back({relName, kbr.colDomains}); for (auto &kbFact : relations_.at(relId).getFacts()) { // TODO remove toKBGroundLiteral facts.push_back( retrieveGroundLiteral(kbFact, relName, kbr.colDomains)); } } const KBModule &kbModule = modules_[modId]; for (auto &kbRule : kbModule.rules) { rules.push_back(convertKBRule(kbRule, kbModule)); } return {moduleName, std::move(relations), std::move(rules), std::move(facts)}; } std::vector<GroundLiteral> KnowledgeBase::retrieveRelation(const std::string &moduleName, const std::string &relationName) const { return impl_->retrieveRelation(moduleName, relationName); } std::vector<GroundLiteral> KnowledgeBaseImpl::retrieveRelation(const std::string &moduleName, const std::string &relationName) const { unsigned modId = queryModuleId(moduleName); return retrieveRelation(queryRelationId(modId, relationName)); } std::vector<std::string> KnowledgeBase::listModules() const { std::vector<std::string> modules; for (auto &mod : impl_->modules_) { modules.push_back(mod.name); } return modules; } std::vector<RelationDef> KnowledgeBase::listRelations(const std::string &module) const { std::vector<RelationDef> relations; unsigned modId = impl_->queryModuleId(module); const KBModule &kbm = impl_->modules_[modId]; for (auto relId : kbm.relationIds) { auto &kbr = impl_->relations_[relId]; const std::string relName = impl_->relSymPool_.get(relId).second; relations.push_back({relName, kbr.colDomains}); } return relations; } RelationDef KnowledgeBase::getRelationDef(const std::string &module, const std::string &rel) const { return impl_->getRelationDef(module, rel); } RelationDef KnowledgeBaseImpl::getRelationDef(const std::string &module, const std::string &rel) const { unsigned modId = queryModuleId(module); unsigned relId = queryRelationId(modId, rel); return {rel, relations_[relId].colDomains}; } std::vector<GroundLiteral> KnowledgeBaseImpl::retrieveRelation(unsigned relId) const { const std::vector<TermType> colDomains = relations_.at(relId).colDomains; std::vector<GroundLiteral> result; auto &facts = relations_.at(relId).getFacts(); result.reserve(facts.size()); const std::string relName = relSymPool_.get(relId).second; for (auto &kbFact : facts) { // TODO remove toKBGroundLiteral result.push_back(retrieveGroundLiteral(kbFact, relName, colDomains)); } return result; } void KnowledgeBase::addResultToKB(std::vector<KBTuple> newFacts, unsigned relId) { auto &relation = impl_->relations_[relId]; for (auto &&tuple : newFacts) { relation.addTuple(std::move(tuple)); } } void KnowledgeBaseImpl::addFact(unsigned modId, const GroundLiteral &fact) { KBGroundLiteral literal = convertGroundLiteral(modId, fact); relations_[literal.getRelId()].addEdbFact(literal); } unsigned KnowledgeBaseImpl::addRelation(unsigned modId, const RelationDef &def) { auto relId = relSymPool_.insert({modId, def.getPredicateSymbol()}); if (!relId.second) { throw InvalidInputException("Relation is already defined (", def.getPredicateSymbol(), ")."); } relations_.emplace_back(relId.first, def.getTypes()); return relId.first; } KBTerm KnowledgeBaseImpl::convertTerm(const Term &term) { if (term.getType() == TermType::Var) { return KBTerm(termMapper_.internTerm(term), true); } return KBTerm(termMapper_.internTerm(term), false); } KBGroundTerm KnowledgeBaseImpl::convertGroundTerm(const Term &term) { assert(term.getType() != TermType::Var); return KBGroundTerm(termMapper_.internTerm(term)); } KBHeadLiteral KnowledgeBaseImpl::convertLiteral(unsigned modId, const Literal &literal) { unsigned relId = queryRelationId(modId, literal.getPredicateSymbol()); std::vector<KBTerm> kbTerms(literal.getTerms().size()); Transform(literal.getTerms(), kbTerms.begin(), [this](const Term &t) { return this->convertTerm(t); }); return KBHeadLiteral{literal.isTrue(), relId, std::move(kbTerms)}; } TermType KnowledgeBaseImpl::queryTermType(unsigned relationId, unsigned idx) const { return relations_[relationId].colDomains[idx]; } std::map<std::string, TermType> KnowledgeBaseImpl::makeTypeMap(const RuleDisjunct &disjunct, unsigned modId) const { std::map<std::string, TermType> typeMap; for (auto &literal : disjunct.getBody()) { if (literal.isFunction()) { continue; } unsigned idx = 0; unsigned literalModId = modId; if (literal.isExternal()) { literalModId = queryModuleId(*literal.getExternalModule()); } for (auto &term : literal.getTerms()) { if (!IsVar(term)) { idx++; continue; } typeMap.insert( {term.get<std::string>(), queryTermType(queryRelationId(literalModId, literal.getPredicateSymbol()), idx)}); idx++; } } return typeMap; } KBRule KnowledgeBaseImpl::convertRule(unsigned modId, const Rule &rule) { std::vector<KBRuleDisjunct> disjuncts; for (auto &disjunct : rule.getDisjuncts()) { std::map<std::string, TermType> typeMap = makeTypeMap(disjunct, modId); std::vector<KBRuleLiteral> disjunctLiterals; std::vector<KBRuleFunction> disjunctFunctions; for (auto &literal : disjunct.getBody()) { if (!literal.isFunction()) { disjunctLiterals.emplace_back( convertRuleLiteral(modId, literal)); } else { disjunctFunctions.emplace_back( convertRuleFunction(literal, typeMap)); } } disjuncts.emplace_back(std::move(disjunctLiterals), std::move(disjunctFunctions)); } return {convertLiteral(modId, rule.getHead()), std::move(disjuncts)}; } KBQuery KnowledgeBase::convertQuery(const Query &query) const { return impl_->convertQuery(query); } KBQuery KnowledgeBaseImpl::convertQuery(const Query &query) const { unsigned modId = queryModuleId(query.moduleSymbol); unsigned relId = queryRelationId(modId, query.predicateSymbol); try { checkDomainsTerms(relations_[relId].colDomains, query.terms); } catch (InvalidInputException &e) { throw InvalidInputException(e.what(), " In query: ", query); } std::vector<KBTerm> kbTerms(query.terms.size()); std::map<Term, unsigned> varMap; unsigned curVarId = 0; Transform(query.terms, kbTerms.begin(), [&](const Term &t) { if (t.getType() == TermType::Var) { auto it = varMap.find(t); if (it == varMap.end()) { varMap[t] = curVarId++; } return KBTerm(varMap[t], true); } else { try { unsigned id = termMapper_.queryTermId(t); return KBTerm(id, false); } catch (std::out_of_range) { throw InvalidInputException("Term '", t, "' not found"); } } }); return KBQuery(query.predicateSymbol, relId, std::move(kbTerms)); } KBGroundLiteral KnowledgeBaseImpl::convertGroundLiteral(unsigned modId, const GroundLiteral &literal) { unsigned relId = queryRelationId(modId, literal.getPredicateSymbol()); Array<KBGroundTerm> kbTerms(literal.getTerms().size()); Transform(literal.getTerms(), kbTerms.begin(), [this](const Term &t) { return this->convertGroundTerm(t); }); TruthValue logicVal = TruthValue::True; if (IsFalse(literal)) { logicVal = TruthValue::False; } return KBGroundLiteral(relId, std::move(kbTerms), logicVal); } KBRuleFunction KnowledgeBaseImpl::convertRuleFunction( const RuleLiteral &literal, const std::map<std::string, TermType> &typeMap) { assert(literal.isFunction() == true); std::vector<KBTerm> kbTerms; kbTerms.reserve(literal.getTerms().size()); std::vector<TermType> termTypes(literal.getTerms().size()); for (auto const &term : literal.getTerms()) { kbTerms.push_back(convertTerm(term)); if (IsVar(term)) { assert(Contains(typeMap, term.get<std::string>())); termTypes.push_back(typeMap.find(term.get<std::string>())->second); } else { termTypes.push_back(term.getType()); } } return {literal.isTrue(), literal.getPredicateFunction(), std::move(kbTerms), std::move(termTypes)}; } KBRuleLiteral KnowledgeBaseImpl::convertRuleLiteral(unsigned modId, const RuleLiteral &literal) { unsigned relId; if (literal.isExternal()) { modId = queryModuleId(*literal.getExternalModule()); } assert(literal.isFunction() == false); relId = queryRelationId(modId, literal.getPredicateSymbol()); std::vector<KBTerm> kbTerms(literal.getTerms().size()); Transform(literal.getTerms(), kbTerms.begin(), [this](const Term &t) { return this->convertTerm(t); }); const TruthValueSet logicSet = literal.getLogicConstraint(); TruthValueSet rlSet; if (IsFalse(literal) && logicSet.isEmpty()) { rlSet = TruthValueSet({TruthValue::False, TruthValue::Incons}); } else if (IsFalse(literal)) { rlSet = logicSet.getNegation(); } else if (logicSet.isEmpty()) { rlSet = TruthValueSet({TruthValue::True, TruthValue::Incons}); } else { rlSet = logicSet; } return {relId, std::move(kbTerms), rlSet}; } GroundLiteral KnowledgeBaseImpl::retrieveGroundLiteral(unsigned relId, const KBTuple &tuple) const { const std::vector<TermType> colDomains = relations_.at(relId).colDomains; const std::string relName = relSymPool_.get(relId).second; return retrieveGroundLiteral(tuple, relName, colDomains); } GroundLiteral KnowledgeBaseImpl::retrieveGroundLiteral( const KBTuple &tuple, const std::string &relName, const std::vector<TermType> &types) const { std::vector<Term> terms; auto &kbTerms = tuple.getTerms(); terms.reserve(kbTerms.size()); for (size_t i = 0; i < kbTerms.size(); i++) { terms.push_back(termMapper_.queryTerm(kbTerms[i].get(), types[i])); } bool t = true; if (tuple.getValue() == TruthValue::False) { t = false; } return GroundLiteral(t, relName, std::move(terms)); } ResultFact KnowledgeBase::makeResultFact(Array<KBGroundTerm> tuple, TruthValue value, const std::vector<TermType> &types) const { return impl_->makeResultFact(tuple, value, types); } ResultFact KnowledgeBaseImpl::makeResultFact( const Array<KBGroundTerm> &tuple, TruthValue value, const std::vector<TermType> &types) const { Array<Term> terms(tuple.size()); for (size_t i = 0; i < tuple.size(); i++) { terms[i] = termMapper_.queryTerm(tuple[i].get(), types[i]); } return {std::move(terms), value}; } Rule KnowledgeBaseImpl::convertKBRule(const KBRule &rule, const KBModule &module) const { std::vector<RuleDisjunct> ruleDisjuncts; for (auto &disjunct : rule.getDisjuncts()) { std::vector<RuleLiteral> disjunctBody; disjunctBody.reserve(disjunct.getBody().size()); Transform(disjunct.getBody(), std::back_inserter(disjunctBody), [&](const KBRuleLiteral &kbRuleLiteral) { return convertKBRuleLiteral(kbRuleLiteral, module); }); ruleDisjuncts.emplace_back(std::move(disjunctBody)); } return {convertKBHeadLiteral(rule.getHead()), std::move(ruleDisjuncts)}; } Literal KnowledgeBaseImpl::convertKBHeadLiteral( const KBHeadLiteral &literal) const { const std::string relName = relSymPool_.get(literal.getRelId()).second; const std::vector<TermType> &types = relations_[literal.getRelId()].colDomains; std::vector<Term> terms; terms.reserve(literal.getTerms().size()); for (size_t i = 0; i < literal.getTerms().size(); i++) { terms.push_back( termMapper_.queryTerm(literal.getTerms()[i].get(), types[i])); } return Literal(!literal.isNegated(), relName, std::move(terms)); } RuleLiteral KnowledgeBaseImpl::convertKBRuleLiteral(const KBRuleLiteral &literal, const KBModule &module) const { const std::string relName = relSymPool_.get(literal.getRelId()).second; const std::vector<TermType> &types = relations_[literal.getRelId()].colDomains; std::vector<Term> terms; for (size_t i = 0; i < literal.getTerms().size(); i++) { terms.push_back( termMapper_.queryTerm(literal.getTerms()[i].get(), types[i])); } if (Find(module.relationIds, literal.getRelId()) != module.relationIds.end()) { return RuleLiteral(!literal.getLogicSet().isFalse(), relName, std::move(terms)); } std::vector<TruthValue> lValueSet = literal.getLogicSet().getSet(); if (lValueSet.size() == 1 || lValueSet[0] == TruthValue::False || lValueSet[0] == TruthValue::True) { return RuleLiteral(!literal.getLogicSet().isFalse(), module.name, relName, std::move(terms)); } return RuleLiteral(module.name, relName, std::move(terms), lValueSet); } unsigned KnowledgeBaseImpl::queryModuleId(const std::string &module) const { unsigned modId; try { modId = moduleNamePool_.queryId(module); } catch (std::out_of_range &e) { throw InvalidInputException("No such module: ", module); } return modId; } unsigned KnowledgeBaseImpl::queryRelationId(unsigned modId, const std::string &rel) const { unsigned relId; try { relId = relSymPool_.queryId({modId, rel}); } catch (std::out_of_range &e) { throw InvalidInputException("No such relation '", rel, "' in module '", moduleNamePool_.get(modId), "'"); } return relId; } } // fovris
33.412815
80
0.594014
mnowotnik