hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
3068245fb2012c6185a50f5ed6d9c464cbf886c1
1,717
cpp
C++
control_app/joystick.cpp
houcy/wall-e-1
b159d05b0afa343cb161f60ec98974bc2f063afd
[ "MIT" ]
1
2021-05-05T14:11:03.000Z
2021-05-05T14:11:03.000Z
control_app/joystick.cpp
houcy/wall-e-1
b159d05b0afa343cb161f60ec98974bc2f063afd
[ "MIT" ]
null
null
null
control_app/joystick.cpp
houcy/wall-e-1
b159d05b0afa343cb161f60ec98974bc2f063afd
[ "MIT" ]
null
null
null
#include "joystick.h" #include "log.h" #include <QTimer> // Linux headers #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> /* Standard C++ API does not allow to read char device file in unblocking mode, * so used Linux API */ #define JOYSTICK_FILE "/dev/input/js0" #define READ_DATA_INTERVAL 50 Joystick::Joystick(QObject *parent) : QObject(parent) { if ((jsFile = open(JOYSTICK_FILE, O_RDONLY | O_NONBLOCK, S_IRUSR | S_IRGRP | S_IROTH)) == -1) { critical("Failed to open joystick file %d: %s", errno, strerror(errno)); return; } readDataTimer = new QTimer(this); connect(readDataTimer, SIGNAL(timeout()), this, SLOT(slotReadData())); readDataTimer->setInterval(READ_DATA_INTERVAL); readDataTimer->start(); } Joystick::~Joystick() { if (jsFile != -1) { if (close(jsFile)) critical("Failed to close joystick file"); } } void Joystick::slotReadData() { int n; while((n = read(jsFile, &jsEvent, sizeof(jsEvent))) == sizeof(jsEvent)) { switch (jsEvent.type) { case JS_EVENT_TYPE_AXIS: switch (jsEvent.number) { case JS_EVENT_AXIS_X_NS: case JS_EVENT_AXIS_X_WE: emit joystickEvent(jsEvent.type, jsEvent.number, jsEvent.value); default: break; } break; case JS_EVENT_TYPE_BUTTON: case JS_EVENT_TYPE_INIT: default: break; } } if (!n || (n > 0 && n != sizeof(jsEvent)) || (n == -1 && errno != EAGAIN)) { critical("Failed to read joystick file"); return; } }
22.893333
80
0.576005
3069a83b76d7aa1d62e769e3c75bcc32085ad3e2
2,168
cpp
C++
src/sorts/CombSort/comb_sort.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
src/sorts/CombSort/comb_sort.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
src/sorts/CombSort/comb_sort.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
#include "../../comms/comm_headers.h" #include <sorts/comb_sort.h> #define THIS_FILE "comb_sort.cpp" #define LOG_TAG "SORTS-COMB" TGSTK_EXPORT SortCombObject::SortCombObject(SortVTable & vTable, float factor) : SortObject(vTable) { this->factor = factor; if (factor <= 1) { mlog_e(LOG_TAG, THIS_FILE, "Param[factor](%d) should be larger than 1. Now set to 1.3F.", factor); this->factor = 1.3F; } } int SortCombObject::onSort(void * objs, int elemSize, int size, SortType type) { COMM_ASSERT_RETURN(objs && size > 0, -1); int ret = 0; int rc = 0; int i = 0; int hasExchange = 0; int gap = size; while (gap > 1 || hasExchange) { hasExchange = 0; gap = gap > 1 ? (int)((float)gap / this->factor) : gap; for (i = gap; i < size; i++) { rc = this->onCompare(COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i)); switch (type) { case emSortDesc: { if (rc < 0) { this->onExchange( COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i)); hasExchange = 1; } } break; case emSortAsc: { if (rc > 0) { this->onExchange( COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i)); hasExchange = 1; } } break; default: { ret = -1; mlog_e(LOG_TAG, THIS_FILE, "Invalid Param[type]: %d\n", type); } break; } } } return ret; }
31.42029
112
0.398985
306f23f5921876eb6705efe778fd911d6c548e85
294
cpp
C++
FruitManageSystem/Fruit.cpp
grahamitdev/FruitManageSystem
c3c9effaa84ad1d900767a8bc4aad9b35a2473fe
[ "Apache-2.0" ]
1
2021-02-17T12:33:12.000Z
2021-02-17T12:33:12.000Z
FruitManageSystem/Fruit.cpp
grahamitdev/FruitManageSystem
c3c9effaa84ad1d900767a8bc4aad9b35a2473fe
[ "Apache-2.0" ]
null
null
null
FruitManageSystem/Fruit.cpp
grahamitdev/FruitManageSystem
c3c9effaa84ad1d900767a8bc4aad9b35a2473fe
[ "Apache-2.0" ]
3
2018-02-07T01:58:30.000Z
2021-12-16T03:17:24.000Z
#include "Fruit.h" Fruit::Fruit(const QString &name, const double &price, const double &num) :name(name),price(price),num(num) { } QString Fruit::getName() const { return name; } double Fruit::getPrice() const { return price; } double Fruit::getNum() const { return num; }
12.782609
73
0.656463
307373a68a63c0a7466f75495fb6cfd8d2e2b32e
4,271
cpp
C++
test/lab/test_client.cpp
brigid-jp/brigid-core
edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589
[ "MIT" ]
6
2019-12-24T01:55:57.000Z
2021-01-18T02:51:28.000Z
test/lab/test_client.cpp
brigid-jp/brigid-core
edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589
[ "MIT" ]
11
2021-09-16T12:58:45.000Z
2021-12-08T08:14:58.000Z
test/lab/test_client.cpp
brigid-jp/brigid-core
edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589
[ "MIT" ]
null
null
null
// Copyright (c) 2021 <dev@brigid.jp> // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php #include <brigid/error.hpp> #include "test_common.hpp" #include <exception> #include <iomanip> #include <iostream> #include <vector> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <errno.h> #include <time.h> #include <unistd.h> namespace brigid { namespace { void run(const char* node, const char* serv) { int fd = -1; try { std::cout << std::setfill('0'); timer t; t.start(); addrinfo_t ai = getaddrinfo(node, serv, AI_ADDRCONFIG, AF_INET, SOCK_STREAM); t.stop(); t.print("getaddrinfo"); t.start(); fd = socket(ai->ai_family, ai->ai_socktype, 0); if (fd == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } t.stop(); t.print("socket"); { int v = 1; if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v)) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.start(); if (connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } t.stop(); t.print("connect"); t.start(); { int v = 0; socklen_t size = sizeof(v); if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &v, &size) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } std::cout << "SOL_SOCKET SO_SNDBUF " << v << "\n"; std::string buffer = "GET / HTTP/1.0\r\n\r\n"; if (send(fd, buffer.data(), buffer.size(), 0) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.stop(); t.print("send"); t.start(); { std::vector<char> buffer(4096); if (send(fd, buffer.data(), buffer.size(), 0) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.stop(); t.print("send"); t.start(); { if (shutdown(fd, SHUT_WR) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.stop(); t.print("shutdown"); t.start(); { std::vector<char> buffer(1); while (true) { { int v = 0; socklen_t size = sizeof(v); if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &v, &size) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } std::cout << "SOL_SOCKET SO_RCVBUF " << v << "\n"; } ssize_t size = read(fd, buffer.data(), buffer.size()); if (size > 0) { std::cout << "read " << size << "\n"; } else if (size == 0) { std::cout << "closed\n"; break; } else { int code = errno; throw BRIGID_RUNTIME_ERROR(std::generic_category().message(code), make_error_code("error number", code)); } struct timespec timeout = {}; timeout.tv_nsec = 100 * 1000 * 1000; nanosleep(&timeout, nullptr); } } t.stop(); t.print("read"); close(fd); } catch (...) { if (fd != -1) { close(fd); } throw; } } } } int main(int ac, char* av[]) { try { if (ac < 3) { std::cout << "usage: " << av[0] << " node serv\n"; return 1; } brigid::run(av[1], av[2]); return 0; } catch (const std::exception& e) { std::cerr << e.what() << "\n"; } return 1; }
29.054422
123
0.510887
30777d7ac5ce4310015b27a34498b181e760e9f1
1,068
cpp
C++
cpp/UniqueBinarySearchTreesII.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
12
2015-03-12T03:27:26.000Z
2021-03-11T09:26:16.000Z
cpp/UniqueBinarySearchTreesII.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
null
null
null
cpp/UniqueBinarySearchTreesII.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
11
2015-01-28T16:45:40.000Z
2017-03-28T20:01:38.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode *> generateTrees(int n) { vector<TreeNode *> v; generateTrees(1,n,v); return v; } void generateTrees(int start, int end, vector<TreeNode *>& trees) { if(start>end) { trees.push_back(NULL); return; } for(int i=start;i<=end;i++) { vector<TreeNode *> leftTrees; generateTrees(start, i-1, leftTrees); vector<TreeNode *> rightTrees; generateTrees(i+1, end, rightTrees); for(int j=0;j<leftTrees.size();j++) { for(int k=0;k<rightTrees.size();k++) { TreeNode* t = new TreeNode(i); t->left = leftTrees[j]; t->right = rightTrees[k]; trees.push_back(t); } } } } };
27.384615
71
0.476592
307aff939a124a82f61ec044b639cc285b500a99
2,296
hxx
C++
opencascade/StdSelect_FaceFilter.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/StdSelect_FaceFilter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/StdSelect_FaceFilter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1996-03-08 // Created by: Robert COUBLANC // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StdSelect_FaceFilter_HeaderFile #define _StdSelect_FaceFilter_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StdSelect_TypeOfFace.hxx> #include <SelectMgr_Filter.hxx> #include <Standard_Boolean.hxx> #include <TopAbs_ShapeEnum.hxx> class SelectMgr_EntityOwner; class StdSelect_FaceFilter; DEFINE_STANDARD_HANDLE(StdSelect_FaceFilter, SelectMgr_Filter) //! A framework to define a filter to select a specific type of face. //! The types available include: //! - any face //! - a planar face //! - a cylindrical face //! - a spherical face //! - a toroidal face //! - a revol face. class StdSelect_FaceFilter : public SelectMgr_Filter { public: //! Constructs a face filter object defined by the type of face aTypeOfFace. Standard_EXPORT StdSelect_FaceFilter(const StdSelect_TypeOfFace aTypeOfFace); //! Sets the type of face aNewType. aNewType is to be highlighted in selection. Standard_EXPORT void SetType (const StdSelect_TypeOfFace aNewType); //! Returns the type of face to be highlighted in selection. Standard_EXPORT StdSelect_TypeOfFace Type() const; Standard_EXPORT virtual Standard_Boolean IsOk (const Handle(SelectMgr_EntityOwner)& anobj) const Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean ActsOn (const TopAbs_ShapeEnum aStandardMode) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(StdSelect_FaceFilter,SelectMgr_Filter) protected: private: StdSelect_TypeOfFace mytype; }; #endif // _StdSelect_FaceFilter_HeaderFile
27.011765
117
0.77831
307e4dcc379f086608ed6971559fccc25010eecc
2,928
cpp
C++
Graphs/MazeRunner.cpp
TheArquitect/Classic-Algorithms
29ef20af79346142df8c76dd266e728b5e12cd10
[ "BSD-2-Clause" ]
1
2019-09-30T17:47:41.000Z
2019-09-30T17:47:41.000Z
Graphs/MazeRunner.cpp
TheArquitect/Classic-Algorithms
29ef20af79346142df8c76dd266e728b5e12cd10
[ "BSD-2-Clause" ]
null
null
null
Graphs/MazeRunner.cpp
TheArquitect/Classic-Algorithms
29ef20af79346142df8c76dd266e728b5e12cd10
[ "BSD-2-Clause" ]
null
null
null
/** File : MazeRunner.cpp Author : Menashe Rosemberg Created : 2019.04.02 Version: 20190402.12 Check all spaces reachable in a maze from a random start place BSD License Copyright (c) 2019 TheArquitect (Menashe Rosemberg) rosemberg@ymail.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ #include "MazeRunner.h" #include "MazeRunner_Running.h" void Run_MazeRunner_DFS() { MazeMap Maze = { "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW", "W WWW W W W W", "W WW W W WWW WWWW WWWWW W WWWW W", "W W W W W W W W W", "WWWWWWWWWW W WWWW W W W", "W W W W WWWWWW W", "WWWWWW W WW W W WWWW WWW W", "W W W W W WWWW W W W W WWWW W", "W WWWW W W W W W W W W", "W W W W WWWW W W WWW WWWW W", "WWWWWWWWWWWWWWWWWWW W W W W W W", "W WW W W", "W WWWWWWWWWWWWWWWWW WWWWWWWWWWW W W", "W W WWWWWW W W W", "W W WWWWWWWWWWWWW W W WWWWWWWWW W W", "W W W WW W W", "W WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW W", "W W", "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" }; RunRunner(Maze); }
49.627119
83
0.563525
3082d2b7b359e5c3f2df5d7dd1534c7b330b0f79
1,299
cpp
C++
microcontroller/lib/Timer/Timer.cpp
robfors/nut_sorter-microcontroller
bc909fdaa1cc856341fe16773aefe9f1af773c83
[ "Apache-2.0" ]
null
null
null
microcontroller/lib/Timer/Timer.cpp
robfors/nut_sorter-microcontroller
bc909fdaa1cc856341fe16773aefe9f1af773c83
[ "Apache-2.0" ]
null
null
null
microcontroller/lib/Timer/Timer.cpp
robfors/nut_sorter-microcontroller
bc909fdaa1cc856341fe16773aefe9f1af773c83
[ "Apache-2.0" ]
null
null
null
#include "Timer.h" // // public // Timer::Timer(Units units) { _default_length = 0; _length = 0; _units = units; _is_active = false; _start_time = 0; } Timer::Timer(unsigned long default_length, Units units) { _default_length = default_length; _length = 0; _units = units; _is_active = false; _start_time = 0; } boolean Timer::is_complete() { return !is_running(); } boolean Timer::is_running() { _update(); return _is_active; } void Timer::start() { _start_time = _current_time(); // save time first if (_default_length == 0) { _start_time = 0; return; } _length = _default_length; _is_active = true; } void Timer::start(unsigned long length) { _start_time = _current_time(); // save time first _length = length; _is_active = true; } void Timer::stop() { _start_time = 0; _length = 0; _is_active = false; } // // private // unsigned long Timer::_current_time() { switch (_units) { case Timer::Units::Microseconds: return micros(); break; case Timer::Units::Milliseconds: return millis(); break; case Timer::Units::Seconds: return millis()/1000; break; } return 0; } void Timer::_update() { if (_is_active && _current_time() >= _start_time + _length) _is_active = false; }
13.121212
61
0.639723
30863a06f9bb3bb0f2714fb003ace0def7f08e26
155
cpp
C++
benignware/1000.cpp
CodmingOut/SecretProjectAI
addc43117eab30a25453c18fa042739c33cc6cfb
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/1000/1000.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/1000/1000.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int count_0 = 0, count_1 = 0; int main(void) { int a, b; cin >> a >> b; cout << a + b << endl; return 0; }
11.071429
29
0.574194
308846f94715c810eea8e4c19b8358fdaa42b62a
309
cpp
C++
Sorting-and-Order-Statistics/Selection sort.cpp
Fresher001/Competitive-Programming-2
e1e953bb1d4ade46cc670b2d0432f68504538ed2
[ "MIT" ]
86
2016-10-18T23:30:36.000Z
2022-01-09T21:57:34.000Z
Sorting-and-Order-Statistics/Selection sort.cpp
Fresher001/Competitive-Programming-2
e1e953bb1d4ade46cc670b2d0432f68504538ed2
[ "MIT" ]
1
2018-04-13T09:38:36.000Z
2018-04-13T09:38:36.000Z
Sorting-and-Order-Statistics/Selection sort.cpp
Fresher001/Competitive-Programming-2
e1e953bb1d4ade46cc670b2d0432f68504538ed2
[ "MIT" ]
39
2017-03-02T07:25:40.000Z
2020-12-14T12:13:50.000Z
#include <bits/stdc++.h> using namespace std; void selection_sort(int A[], int l, int r) { for (int i = l; i < r; ++i) { int p = i; for (int j = i + 1; j <= r; ++j) if (A[j] < A[p]) p = j; swap(A[i], A[p]); } } int main() { return 0; }
13.434783
42
0.391586
3088a13f78577e5dd7fc484a9a15ea8b0dd1cc3e
829
cpp
C++
clang/test/SemaCXX/align-x86-abi7.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/SemaCXX/align-x86-abi7.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/SemaCXX/align-x86-abi7.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 -std=c++11 -triple i386-apple-darwin9 -fsyntax-only -verify -fclang-abi-compat=7 %s // expected-no-diagnostics using size_t = decltype(sizeof(0)); template <typename T, size_t Preferred> struct check_alignment { using type = T; static type value; static_assert(__alignof__(value) == Preferred, "__alignof__(value) != Preferred"); static_assert(__alignof__(type) == Preferred, "__alignof__(type) != Preferred"); static_assert(alignof(type) == Preferred, "alignof(type) != Preferred"); }; // PR3433 template struct check_alignment<double, 8>; template struct check_alignment<long long, 8>; template struct check_alignment<unsigned long long, 8>; // PR6362 template struct check_alignment<double[3], 8>; enum big_enum { x = 18446744073709551615ULL }; template struct check_alignment<big_enum, 8>;
31.884615
102
0.746683
308acdf55b1fd94729126e79d44df30fb1e46fdf
419
hpp
C++
src/PheromonWeight.hpp
mwieczor/ACO
aa30ecd728d6b205188da4993857e2291a464255
[ "MIT" ]
null
null
null
src/PheromonWeight.hpp
mwieczor/ACO
aa30ecd728d6b205188da4993857e2291a464255
[ "MIT" ]
null
null
null
src/PheromonWeight.hpp
mwieczor/ACO
aa30ecd728d6b205188da4993857e2291a464255
[ "MIT" ]
null
null
null
#pragma once #include "Ant.hpp" class WeightGraph; class Node; class PheromonWeight{ public: PheromonWeight(){} virtual ~PheromonWeight()=default; protected: virtual void leavePheromon(IWeightGraph &mGraph, Node lastNode, Node position, double weight); // virtual void leavePheromon(WeightGraph &mGraph, Node lastNode, Node position); virtual void evaporatePheromon(IWeightGraph &mGraph); };
19.952381
98
0.747017
308ee7bdaf4678260b1812aa891a01dd171bce97
46,577
cpp
C++
plugins/chain_plugin/test/test_trx_finality_status_processing.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
60
2022-01-03T18:41:12.000Z
2022-03-25T07:08:19.000Z
plugins/chain_plugin/test/test_trx_finality_status_processing.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
37
2022-01-13T22:23:58.000Z
2022-03-31T13:32:38.000Z
plugins/chain_plugin/test/test_trx_finality_status_processing.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
11
2022-01-14T21:14:11.000Z
2022-03-25T07:08:29.000Z
#define BOOST_TEST_MODULE transaction_finality_status #include <boost/test/included/unit_test.hpp> #include <eosio/chain_plugin/trx_finality_status_processing.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/block_header.hpp> #include <eosio/chain/genesis_state.hpp> #include <eosio/chain/name.hpp> #include <eosio/chain/trace.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <fc/mock_time.hpp> #include <fc/bitutil.hpp> #include <deque> #include <memory> namespace eosio::test::detail { using namespace eosio::chain; using namespace eosio::chain::literals; struct testit { uint64_t id; testit( uint64_t id = 0 ) : id(id){} static account_name get_account() { return chain::config::system_account_name; } static action_name get_name() { return "testit"_n; } }; } // eosio::test::detail FC_REFLECT( eosio::test::detail::testit, (id) ) namespace { using namespace eosio; using namespace eosio::chain; using namespace eosio::chain_apis; using namespace eosio::test::detail; auto get_private_key( chain::name keyname, std::string role = "owner" ) { auto secret = fc::sha256::hash( keyname.to_string() + role ); return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret ); } auto get_public_key( chain::name keyname, std::string role = "owner" ) { return get_private_key( keyname, role ).get_public_key(); } auto make_unique_trx( const fc::microseconds& expiration ) { static uint64_t unique_id = 0; ++unique_id; genesis_state gs{}; const auto& chain_id = gs.compute_chain_id(); account_name creator = config::system_account_name; signed_transaction trx; const auto now_exp = fc::time_point::now() + expiration; trx.expiration = now_exp; trx.actions.emplace_back( vector<permission_level>{{creator, config::active_name}}, testit{ unique_id } ); trx.sign( get_private_key("test"_n), chain_id ); return std::make_shared<packed_transaction>( std::move(trx), packed_transaction::compression_type::none); } chain::block_id_type make_block_id( uint32_t block_num ) { chain::block_id_type block_id; block_id._hash[0] &= 0xffffffff00000000; block_id._hash[0] += fc::endian_reverse_u32(block_num); return block_id; } chain::transaction_trace_ptr make_transaction_trace( const packed_transaction_ptr trx, uint32_t block_number, const eosio::chain::block_state_ptr& bs_ptr, chain::transaction_receipt_header::status_enum status = eosio::chain::transaction_receipt_header::executed ) { return std::make_shared<chain::transaction_trace>(chain::transaction_trace{ trx->id(), block_number, chain::block_timestamp_type(fc::time_point::now()), bs_ptr ? bs_ptr->id : std::optional<block_id_type> {}, chain::transaction_receipt_header{status}, fc::microseconds(0), 0, false, {}, // actions {}, {}, {}, {}, {} }); } auto make_block_state( uint32_t block_num ) { static uint64_t unique_num = 0; ++unique_num; chain::block_id_type block_id = make_block_id(block_num); block_id._hash[3] = unique_num; name producer = "brianj"_n; chain::signed_block_ptr block = std::make_shared<chain::signed_block>(); block->producer = producer; block->timestamp = fc::time_point::now(); block->previous = make_block_id(block_num - 1); auto priv_key = get_private_key( block->producer, "active" ); auto pub_key = get_public_key( block->producer, "active" ); auto prev = std::make_shared<chain::block_state>(); auto header_bmroot = chain::digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root())); auto sig_digest = chain::digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash )); block->producer_signature = priv_key.sign( sig_digest ); std::vector<chain::private_key_type> signing_keys; signing_keys.emplace_back( priv_key ); auto signer = [&]( chain::digest_type d ) { std::vector<chain::signature_type> result; result.reserve( signing_keys.size()); for( const auto& k: signing_keys ) result.emplace_back( k.sign( d )); return result; }; chain::pending_block_header_state pbhs; pbhs.producer = block->producer; pbhs.timestamp = block->timestamp; pbhs.previous = block->previous; chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer, chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}}; pbhs.active_schedule = schedule; pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}}; auto bsp = std::make_shared<chain::block_state>( std::move( pbhs ), std::move( block ), std::vector<chain::transaction_metadata_ptr>(), chain::protocol_feature_set(), []( chain::block_timestamp_type timestamp, const fc::flat_set<chain::digest_type>& cur_features, const std::vector<chain::digest_type>& new_features ) {}, signer ); bsp->id = block_id; bsp->block_num = block_num; return bsp; } std::string set_now(const char* date, const char* time) { std::string date_time = std::string(date) + " " + time; auto pnow = boost::posix_time::time_from_string(date_time); fc::mock_time_traits::set_now(pnow); return std::string(date) + "T" + time; }; } // anonymous namespace BOOST_AUTO_TEST_SUITE(trx_finality_status_processing_test) BOOST_AUTO_TEST_CASE(trx_finality_status_logic) { try { const auto pre_block_20_time = set_now("2022-04-04", "04:44:44.450"); fc::microseconds max_success_duration = fc::seconds(25); fc::microseconds max_failure_duration = fc::seconds(45); trx_finality_status_processing status(10'000, max_success_duration, max_failure_duration); using trx_deque = eosio::chain::deque< std::tuple< chain::transaction_trace_ptr, packed_transaction_ptr > >; uint32_t bn = 20; auto add = [&bn, &status](trx_deque& trx_pairs, const eosio::chain::block_state_ptr& bs_ptr) { auto trx = make_unique_trx(fc::seconds(2)); auto trace = make_transaction_trace( trx, bn, bs_ptr); trx_pairs.push_back(std::tuple(trace, trx)); status.signal_applied_transaction(trace, trx); }; trx_deque trx_pairs_20; // Create speculative block to begin applying transactions locally status.signal_block_start(bn); const eosio::chain::block_state_ptr no_bs; add(trx_pairs_20, no_bs); add(trx_pairs_20, no_bs); add(trx_pairs_20, no_bs); add(trx_pairs_20, no_bs); auto cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == eosio::chain::block_id_type{}); BOOST_TEST(!std::get<0>(trx_pairs_20[0])->producer_block_id.has_value()); BOOST_CHECK(cs.head_block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == eosio::chain::block_id_type{}); using op_ts = std::optional<eosio::chain_apis::trx_finality_status_processing::trx_state>; op_ts ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); // Simulate situation where the last 2 trxs do not make it into the block. trx_deque hold_pairs; std::vector<chain::packed_transaction_ptr> holds; hold_pairs.push_back(trx_pairs_20[2]); hold_pairs.push_back(trx_pairs_20[3]); trx_pairs_20.pop_back(); trx_pairs_20.pop_back(); //Make a real block start. Pull these before any updates to the trx/trace objects. // send block 20 const auto bs_20 = make_block_state(bn); status.signal_block_start(bn); for (const auto& trx_tuple : trx_pairs_20) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); trace->producer_block_id = bs_20->id; trace->block_time = bs_20->block->timestamp; status.signal_applied_transaction(trace, txn); } // and 2 new transactions const auto block_20_time = set_now("2022-04-04", "04:44:44.500"); add(trx_pairs_20, bs_20); add(trx_pairs_20, bs_20); status.signal_accepted_block(bs_20); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_20->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[0])->producer_block_id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[1])->producer_block_id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[2])->producer_block_id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[3])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_20->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK(fc::time_point_sec(ts->expiration) == (std::get<1>(trx_pairs_20[1])->expiration())); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); // send block 21 const auto block_21_time = set_now("2022-04-04", "04:44:45.000"); trx_deque trx_pairs_21; bn = 21; const auto bs_21 = make_block_state(bn); status.signal_block_start(bn); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); add(trx_pairs_21, bs_21); status.signal_accepted_block(bs_21); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_21->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_21[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_21->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 22 const auto block_22_time = set_now("2022-04-04", "04:44:45.500"); trx_deque trx_pairs_22; bn = 22; const auto bs_22 = make_block_state(bn); status.signal_block_start(bn); add(trx_pairs_22, bs_22); status.signal_accepted_block(bs_22); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_22->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_22[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_22->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 22 const auto block_22_alt_time = set_now("2022-04-04", "04:44:46.000"); trx_deque trx_pairs_22_alt; bn = 22; const auto bs_22_alt = make_block_state(bn); status.signal_block_start(bn); add(trx_pairs_22_alt, bs_22_alt); status.signal_accepted_block(bs_22_alt); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_22_alt->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_22_alt[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 19 (forking out previous blocks.) // Testing that code handles getting blocks before when it started const auto block_19_time = set_now("2022-04-04", "04:44:47.000"); trx_deque trx_pairs_19; bn = 19; const auto bs_19 = make_block_state(bn); status.signal_block_start(bn); add(trx_pairs_19, bs_19); status.signal_accepted_block(bs_19); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_19->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_19[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_19->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_19->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_19[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19->id); BOOST_CHECK(ts->block_timestamp == bs_19->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_19_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 19 alternate const auto block_19_alt_time = set_now("2022-04-04", "04:44:44.000"); trx_deque trx_pairs_19_alt; bn = 19; trx_pairs_19_alt.push_back(trx_pairs_19[0]); trx_pairs_19_alt.push_back(trx_pairs_20[0]); trx_pairs_19_alt.push_back(trx_pairs_20[1]); trx_pairs_19_alt.push_back(trx_pairs_20[2]); trx_pairs_19_alt.push_back(trx_pairs_20[3]); trx_pairs_19_alt.push_back(hold_pairs[0]); const auto bs_19_alt = make_block_state(bn); // const auto bs_19_alt = make_block_state(make_block_id(bn), std::vector<chain::packed_transaction_ptr>{}); status.signal_block_start(bn); for (const auto& trx_tuple : trx_pairs_19_alt) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); trace->producer_block_id = bs_19_alt->id; trace->block_time = bs_19_alt->block->timestamp; status.signal_applied_transaction(trace, txn); } status.signal_accepted_block(bs_19_alt); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_19_alt->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_19[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_19_alt->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_19[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_19_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // look for unknown transaction auto trx = make_unique_trx(fc::seconds(2)); ts = status.get_trx_state(trx->id()); BOOST_REQUIRE(!ts); // irreversible status.signal_irreversible_block(bs_19_alt); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_19_alt->id); BOOST_CHECK(cs.irr_id == bs_19_alt->id); BOOST_CHECK(cs.irr_block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK(cs.earliest_tracked_block_id == bs_19_alt->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_19[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_19_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); } FC_LOG_AND_RETHROW() } namespace { using trx_deque = eosio::chain::deque< std::tuple< chain::transaction_trace_ptr, packed_transaction_ptr > >; const eosio::chain::block_state_ptr no_bs; struct block_frame { static uint32_t last_used_block_num; static const uint32_t num = 5; trx_finality_status_processing& status; const uint32_t bn; const std::string time; trx_deque pre_block; trx_deque block; chain::block_state_ptr bs; std::string context; block_frame(trx_finality_status_processing& finality_status, const char* block_time, uint32_t block_num = 0) : status(finality_status), bn(block_num == 0 ? block_frame::last_used_block_num + 1 : block_num), time(set_now("2022-04-04", block_time)) { block_frame::last_used_block_num = bn; for (uint32_t i = 0; i < block_frame::num; ++i) { auto trx = make_unique_trx(fc::seconds(30)); auto trace = make_transaction_trace( trx, bn, no_bs); pre_block.push_back(std::tuple(trace, trx)); status.signal_applied_transaction(trace, trx); } bs = make_block_state(bn); for (uint32_t i = 0; i < block_frame::num; ++i) { auto trx = make_unique_trx(fc::seconds(30)); auto trace = make_transaction_trace( trx, bn, bs); block.push_back(std::tuple(trace, trx)); status.signal_applied_transaction(trace, trx); } } void verify_block(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_block"; verify(block, bs, begin, end); } void verify_block_not_there(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_block_not_there"; verify_not_there(block, begin, end); } void verify_spec_block(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_spec_block"; verify(pre_block, no_bs, begin, end); } void verify_spec_block_not_there(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_spec_block_not_there"; verify_not_there(pre_block, begin, end); } void send_block() { status.signal_block_start(bn); for (const auto& trx_tuple : block) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); status.signal_applied_transaction(trace, txn); } status.signal_accepted_block(bs); } void send_spec_block() { status.signal_block_start(bn); for (const auto& trx_tuple : pre_block) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); status.signal_applied_transaction(trace, txn); } } private: void verify(const trx_deque& trx_pairs, const chain::block_state_ptr& bs, uint32_t begin, uint32_t end) { if (end == std::numeric_limits<uint32_t>::max()) { end = block.size(); } const auto id = bs ? bs->id : eosio::chain::transaction_id_type{}; for (auto i = begin; i < end; ++i) { const auto& trx_pair = trx_pairs[i]; std::string msg = context + ": block_num==" + std::to_string(bn) + ", i==" + std::to_string(i) + ", id: " + std::string(std::get<1>(trx_pair)->id()); auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); BOOST_REQUIRE_MESSAGE(ts, msg); BOOST_CHECK_MESSAGE(ts->block_id == id, msg); } } void verify_not_there(const trx_deque& trx_pairs, uint32_t begin, uint32_t end) { if (end == std::numeric_limits<uint32_t>::max()) { end = block.size(); } for (auto i = begin; i < end; ++i) { std::string msg = context + "block_num==" + std::to_string(bn) + " i==" + std::to_string(i); const auto& trx_pair = trx_pairs[i]; auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); BOOST_REQUIRE_MESSAGE(!ts, msg); } } }; uint32_t block_frame::last_used_block_num = 0; } BOOST_AUTO_TEST_CASE(trx_finality_status_storage_reduction) { try { set_now("2022-04-04", "04:44:44.450"); fc::microseconds max_success_duration = fc::seconds(25); fc::microseconds max_failure_duration = fc::seconds(45); const uint64_t max_storage = 10'000; trx_finality_status_processing status(max_storage, max_success_duration, max_failure_duration); // auto verify_trx = [&status](trx_deque& trx_pairs, const eosio::chain::block_state_ptr& bs) { // const auto id = bs ? bs->id : eosio::chain::transaction_id_type{}; // for (const auto& trx_pair : trx_pairs) { // auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); // BOOST_REQUIRE(ts); // BOOST_CHECK(ts->block_id == id); // } // }; block_frame b_01(status, "04:44:00.500", 1); b_01.send_spec_block(); b_01.verify_spec_block(); b_01.send_block(); b_01.verify_block(); const auto block_and_speculative_size = status.get_storage_memory_size(); // test expects to not hit the storage limitation till the 12th block BOOST_REQUIRE(max_storage / 11 > block_and_speculative_size); BOOST_REQUIRE(max_storage / 12 < block_and_speculative_size); block_frame b_02(status, "04:44:01.500"); b_02.send_spec_block(); b_02.verify_spec_block(); b_02.send_block(); b_02.verify_block(); block_frame b_03(status, "04:44:02.500"); b_03.send_spec_block(); b_03.verify_spec_block(); b_03.send_block(); b_03.verify_block(); block_frame b_04(status, "04:44:03.500"); b_04.send_spec_block(); b_04.verify_spec_block(); b_04.send_block(); b_04.verify_block(); block_frame b_05(status, "04:44:04.500"); b_05.send_spec_block(); b_05.verify_spec_block(); b_05.send_block(); b_05.verify_block(); block_frame b_06(status, "04:44:05.500"); b_06.send_spec_block(); b_06.verify_spec_block(); b_06.send_block(); b_06.verify_block(); block_frame b_07(status, "04:44:06.500"); b_07.send_spec_block(); b_07.verify_spec_block(); b_07.send_block(); b_07.verify_block(); block_frame b_08(status, "04:44:07.500"); b_08.send_spec_block(); b_08.verify_spec_block(); b_08.send_block(); b_08.verify_block(); block_frame b_09(status, "04:44:08.500"); b_09.send_spec_block(); b_09.verify_spec_block(); b_09.send_block(); b_09.verify_block(); block_frame b_10(status, "04:44:09.500"); b_10.send_spec_block(); b_10.verify_spec_block(); b_10.send_block(); b_10.verify_block(); block_frame b_11(status, "04:44:10.500"); b_11.send_spec_block(); b_11.verify_spec_block(); b_11.send_block(); b_11.verify_block(); auto cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_11.bs->id); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_01.bs->id); // Test expects the next block range to exceed max_storage. Need to adjust // this test if this fails. BOOST_REQUIRE(status.get_storage_memory_size() + block_and_speculative_size > max_storage); block_frame b_12(status, "04:44:11.500"); b_12.send_spec_block(); b_12.verify_spec_block(); b_12.send_block(); b_12.verify_block(); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_12.bs->id); BOOST_CHECK(cs.head_block_timestamp == b_12.bs->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.irr_block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_03.bs->id); b_01.verify_spec_block_not_there(); b_01.verify_block_not_there(); b_02.verify_spec_block_not_there(); b_02.verify_block_not_there(); b_03.verify_spec_block(); b_03.verify_block(); b_04.verify_spec_block(); b_04.verify_block(); b_05.verify_spec_block(); b_05.verify_block(); b_06.verify_spec_block(); b_06.verify_block(); b_07.verify_spec_block(); b_07.verify_block(); b_08.verify_spec_block(); b_08.verify_block(); b_09.verify_spec_block(); b_09.verify_block(); b_10.verify_spec_block(); b_10.verify_block(); b_11.verify_spec_block(); b_11.verify_block(); b_12.verify_spec_block(); b_12.verify_block(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(trx_finality_status_lifespan) { try { set_now("2022-04-04", "04:44:44.450"); fc::microseconds max_success_duration = fc::seconds(25); fc::microseconds max_failure_duration = fc::seconds(35); const uint64_t max_storage = 10'000; trx_finality_status_processing status(max_storage, max_success_duration, max_failure_duration); // auto verify_trx = [&status](trx_deque& trx_pairs, const eosio::chain::block_state_ptr& bs) { // const auto id = bs ? bs->id : eosio::chain::transaction_id_type{}; // for (const auto& trx_pair : trx_pairs) { // auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); // BOOST_REQUIRE(ts); // BOOST_CHECK(ts->block_id == id); // } // }; block_frame b_01(status, "04:44:00.500", 1); b_01.send_spec_block(); b_01.verify_spec_block(); b_01.send_block(); b_01.verify_block(); block_frame b_02(status, "04:44:05.500"); b_02.send_spec_block(); b_02.verify_spec_block(); b_02.send_block(); b_02.verify_block(); block_frame b_03(status, "04:44:10.500"); b_03.send_spec_block(); b_03.verify_spec_block(); b_03.send_block(); b_03.verify_block(); block_frame b_04(status, "04:44:15.500"); b_04.send_spec_block(); b_04.verify_spec_block(); b_04.send_block(); b_04.verify_block(); block_frame b_05(status, "04:44:20.500"); b_05.send_spec_block(); b_05.verify_spec_block(); b_05.send_block(); b_05.verify_block(); // should be still available b_01.verify_block(); b_01.verify_spec_block(); // still available and will continue till failure time block_frame b_06(status, "04:44:25.500"); b_06.send_spec_block(); b_06.verify_spec_block(); b_06.send_block(); b_06.verify_block(); // block 1 now removed b_01.verify_block_not_there(); b_02.verify_block(); b_01.verify_spec_block(); auto cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_06.bs->id); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_02.bs->id); block_frame b_07(status, "04:44:30.500"); b_07.send_spec_block(); b_07.verify_spec_block(); b_07.send_block(); b_07.verify_block(); // block 2 now removed b_02.verify_block_not_there(); b_03.verify_block(); b_01.verify_spec_block(); b_02.verify_spec_block(); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_07.bs->id); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_03.bs->id); block_frame b_08(status, "04:44:35.500"); b_08.send_spec_block(); b_08.verify_spec_block(); b_08.send_block(); b_08.verify_block(); // block 3 now removed and speculative's from block 1 time frame b_03.verify_block_not_there(); b_04.verify_block(); b_01.verify_spec_block_not_there(); b_02.verify_spec_block(); b_03.verify_spec_block(); block_frame b_09(status, "04:44:40.500"); b_09.send_spec_block(); b_09.verify_spec_block(); b_09.send_block(); b_09.verify_block(); // block 4 now removed and speculative's from block 2 time frame b_04.verify_block_not_there(); b_05.verify_block(); b_02.verify_spec_block_not_there(); b_03.verify_spec_block(); b_04.verify_spec_block(); block_frame b_10(status, "04:44:45.500"); b_10.send_spec_block(); b_10.verify_spec_block(); b_10.send_block(); b_10.verify_block(); // block 5 now removed and speculative's from block 3 time frame b_05.verify_block_not_there(); b_06.verify_block(); b_03.verify_spec_block_not_there(); b_04.verify_spec_block(); b_05.verify_spec_block(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
36.790679
163
0.694313
3091aa4676803d92ae456bcbb9262bf7557229fb
5,095
cpp
C++
modules/core/src/Slot/gmSlotBase.cpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/core/src/Slot/gmSlotBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/core/src/Slot/gmSlotBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#include "gmSlotBase.hpp" #include "gmSlotInput.hpp" #include "gmSlotOutput.hpp" #include "gmNodeEditor.hpp" #include "gmNodeConnector.hpp" #include "gmSlotInputBase.hpp" #include "gmSlotOutputBase.hpp" #include "gmSlotConstraints.hpp" #include "gmAsync.hpp" namespace gm { namespace Slot { Base::Base(Component::Type componentType, Data::Type dataType, const QString& name, Constraints* constraints) : Component::Base(componentType, name), /*m_constraints(constraints),*/ m_dataType(dataType) { if (componentType == Component::Type::Input) { this->m_slotType = Type::Input; } else { this->m_slotType = Type::Output; } switch (dataType) { case Data::Type::Image: this->m_dataTypeString = "image"; break; case Data::Type::Number: this->m_dataTypeString = "number"; break; case Data::Type::Vector: this->m_dataTypeString = "vector"; break; case Data::Type::Pointset: this->m_dataTypeString = "pointset"; break; } this->setConstraints(constraints); } auto Base::setConstraints(Constraints* constraints) -> void { this->m_constraints = constraints; emit this->constraintsChanged(); } auto Base::getConstraints() -> Constraints* { return this->m_constraints; } auto Base::getDataTypeString() -> QString { return this->m_dataTypeString; } auto Base::moveConnectX(int x) -> void { if (this->m_slotType == Type::Output) { Node::Connector::instance->setX2(this->m_x + x); } else { Node::Connector::instance->setX1(this->m_x + x); } } auto Base::moveConnectY(int y) -> void { if (this->m_slotType == Type::Output) { Node::Connector::instance->setY2(this->m_y + y); } else { Node::Connector::instance->setY1(this->m_y + y); } } auto Base::setConnecting(bool connecting) -> void { if (this->m_connecting != connecting) { this->m_connecting = connecting; if (connecting) { Node::Connector::instance->setX1(this->m_x); Node::Connector::instance->setY1(this->m_y); Node::Connector::instance->setX2(this->m_x); Node::Connector::instance->setY2(this->m_y); Node::Connector::instance->setActive(true); } else { Node::Connector::instance->setActive(false); } } } auto Base::getConnecting() -> bool { return this->m_connecting; } auto Base::setX(int x) -> void { this->m_x = x; emit this->xChanged(); this->onPositionChanged(); } auto Base::getX() -> int { return this->m_x; } auto Base::setY(int y) -> void { this->m_y = y; emit this->yChanged(); this->onPositionChanged(); } auto Base::getY() -> int { return this->m_y; } auto Base::getDataType() -> Data::Type { return this->m_dataType; } auto Base::getSlotType() -> Slot::Type { return this->m_slotType; } auto Base::getSlotTypeID() -> int { return this->m_slotType == Type::Output; } auto Base::connect(Base* other) -> void { if (!other) { return; } Slot::InputBase* input = reinterpret_cast<Slot::InputBase*>(this->m_slotType == Type::Input ? this : other->m_slotType == Type::Input ? other : nullptr); Slot::OutputBase* output = reinterpret_cast<Slot::OutputBase*>(this->m_slotType == Type::Output ? this : other->m_slotType == Type::Output ? other : nullptr); if (input && output) { if (input->isConnected(output)) { return; } output->connect(input); } } auto Base::moveToMain() -> void { if (this->m_constraints) { Async::MoveToMain(this->m_constraints); } } Base::~Base() { delete this->m_constraints; } } }
28.305556
210
0.452208
309438d436575dc3a725135e24f23899ef17ab21
344
cpp
C++
leetcode/cpp/qt_reverse_string.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_reverse_string.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_reverse_string.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/* Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". */ class Solution { public: string reverseString(string s) { int start = 0; int end = s.size()-1; while(start < end) { swap(s[start++], s[end--]); } return s; } };
19.111111
78
0.561047
30975b6c7b89dfb8c38cf30bebfe7afef6d081db
5,087
cpp
C++
src/linearSolverFactorizedSLU_batched.cpp
GabrielCortesi/GPU-Linear-Solver-Small-Batched
7530707b043b4b96b7fb4081ee1e8cbeca92d833
[ "BSD-3-Clause" ]
1
2019-12-05T18:36:04.000Z
2019-12-05T18:36:04.000Z
src/linearSolverFactorizedSLU_batched.cpp
GabrielCortesi/GPU-Linear-Solver-Small-Batched
7530707b043b4b96b7fb4081ee1e8cbeca92d833
[ "BSD-3-Clause" ]
null
null
null
src/linearSolverFactorizedSLU_batched.cpp
GabrielCortesi/GPU-Linear-Solver-Small-Batched
7530707b043b4b96b7fb4081ee1e8cbeca92d833
[ "BSD-3-Clause" ]
1
2019-12-05T18:13:39.000Z
2019-12-05T18:13:39.000Z
 #ifdef __CDT_PARSER__ #undef __CUDA_RUNTIME_H__ #include <cuda_runtime.h> #endif #include <cuda_runtime.h> #include <math.h> #include <string.h> #include "utils.h" #include "operation_batched.h" #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif /***************************************************************************//** Purpose ------- SGETRS solves a system of linear equations A * X = B, A**T * X = B, or A**H * X = B with a general N-by-N matrix A using the LU factorization computed by SGETRF. This is a batched version that solves batchCount N-by-N matrices in parallel. dA, dB, and ipiv become arrays with one entry per matrix. Arguments --------- @param[in] trans magma_trans_t Specifies the form of the system of equations: - = MagmaNoTrans: A * X = B (No transpose) - = MagmaTrans: A**T * X = B (Transpose) - = MagmaConjTrans: A**H * X = B (Conjugate transpose) --------- @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in] nrhs INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. @param[in,out] dA_array Array of pointers, dimension (batchCount). Each is a REAL array on the GPU, dimension (LDDA,N). On entry, each pointer is an M-by-N matrix to be factored. On exit, the factors L and U from the factorization A = P*L*U; the unit diagonal elements of L are not stored. @param[in] ldda INTEGER The leading dimension of each array A. LDDA >= max(1,M). @param[out] dipiv_array Array of pointers, dimension (batchCount), for corresponding matrices. Each is an INTEGER array, dimension (min(M,N)) The pivot indices; for 1 <= i <= min(M,N), row i of the matrix was interchanged with row IPIV(i). @param[in,out] dB_array Array of pointers, dimension (batchCount). Each is a REAL array on the GPU, dimension (LDDB,N). On entry, each pointer is an right hand side matrix B. On exit, each pointer is the solution matrix X. @param[in] lddb INTEGER The leading dimension of the array B. LDB >= max(1,N). @param[in] batchCount INTEGER The number of matrices to operate on. @param[in] queue magma_queue_t Queue to execute in. *******************************************************************************/ extern "C" int linearSolverFactorizedSLU_batched( int n, int nrhs, float** dA_array, int ldda, int** dipiv_array, float** dB_array, int lddb, int batchCount, cudaStream_t queue) { int info = 0; if (n < 0) { info = -2; } else if (nrhs < 0) { info = -3; } else if (ldda < max(1, n)) { info = -5; } else if (lddb < max(1, n)) { info = -8; } if (info != 0) { utils_reportError(__func__, -(info)); return info; } /* Quick return if possible */ if (n == 0 || nrhs == 0) { return info; } float* dwork = NULL; // dwork is workspace for strsv float** dwork_array = NULL; // batch trsv requires workspace if (nrhs == 1) { int dwork_msize = n * nrhs; // TODO: resize workspace for trsv purpose only magma_malloc((void**)&dwork_array, batchCount * sizeof(*dwork_array)); magma_smalloc(&dwork, dwork_msize * batchCount); /* check allocation */ if (dwork == NULL || dwork_array == NULL) { magma_free(dwork_array); magma_free(dwork); info = MAGMA_ERR_DEVICE_ALLOC; magma_xerbla(__func__, -(info)); return info; } magmablas_slaset(MagmaFull, dwork_msize, batchCount, MAGMA_S_ZERO, MAGMA_S_ZERO, dwork, dwork_msize, queue); magma_sset_pointer(dwork_array, dwork, n, 0, 0, dwork_msize, batchCount, queue); } magma_slaswp_rowserial_batched(nrhs, dB_array, lddb, 1, n, dipiv_array, batchCount, queue); if (nrhs > 1) { printf("unhandled code path: nrhs != 1\n"); } else { // solve dwork = L^-1 * 1 magmablas_strsv_outofplace_batched(MagmaLower, MagmaNoTrans, MagmaUnit, n, dA_array, ldda, // dA dB_array, 1, // dB dwork_array, // dX //output batchCount, queue, 0); // solve X = U^-1 * dwork magmablas_strsv_outofplace_batched(MagmaUpper, MagmaNoTrans, MagmaNonUnit, n, dA_array, ldda, // dA dwork_array, 1, // dB dB_array, // dX //output batchCount, queue, 0); } magma_queue_sync(queue); if (nrhs == 1) { magma_free(dwork_array); magma_free(dwork); } return info; } #undef min #undef max
28.578652
116
0.549243
3098c961a04a961a07a9b587f9e56fac7d56ba21
287
hpp
C++
src/modules/osg/generated_code/TransformFeedbackBufferBinding.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osg/generated_code/TransformFeedbackBufferBinding.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osg/generated_code/TransformFeedbackBufferBinding.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef TransformFeedbackBufferBinding_hpp__pyplusplus_wrapper #define TransformFeedbackBufferBinding_hpp__pyplusplus_wrapper void register_TransformFeedbackBufferBinding_class(); #endif//TransformFeedbackBufferBinding_hpp__pyplusplus_wrapper
31.888889
62
0.891986
309cd4cf8ee842ba93c661842641de1cb0b0f4e5
42,488
cc
C++
src/cats/sql_create.cc
Acidburn0zzz/bareos
34a60296af2e2e948c8cd983876eebf5d4d31fc9
[ "MIT" ]
1
2018-04-28T14:03:39.000Z
2018-04-28T14:03:39.000Z
src/cats/sql_create.cc
Acidburn0zzz/bareos
34a60296af2e2e948c8cd983876eebf5d4d31fc9
[ "MIT" ]
null
null
null
src/cats/sql_create.cc
Acidburn0zzz/bareos
34a60296af2e2e948c8cd983876eebf5d4d31fc9
[ "MIT" ]
null
null
null
/* BAREOS® - Backup Archiving REcovery Open Sourced Copyright (C) 2000-2012 Free Software Foundation Europe e.V. Copyright (C) 2011-2016 Planets Communications B.V. Copyright (C) 2013-2017 Bareos GmbH & Co. KG This program is Free Software; you can redistribute it and/or modify it under the terms of version three of the GNU Affero General Public License as published by the Free Software Foundation and included in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Kern Sibbald, March 2000 */ /** * @file * BAREOS Catalog Database Create record interface routines */ #include "bareos.h" static const int dbglevel = 100; #if HAVE_SQLITE3 || HAVE_MYSQL || HAVE_POSTGRESQL || HAVE_INGRES || HAVE_DBI #include "cats.h" /* ----------------------------------------------------------------------- * * Generic Routines (or almost generic) * * ----------------------------------------------------------------------- */ /** * Forward referenced subroutines */ /** * Create a new record for the Job * Returns: false on failure * true on success */ bool B_DB::create_job_record(JCR *jcr, JOB_DBR *jr) { bool retval = false;; POOL_MEM buf; char dt[MAX_TIME_LENGTH]; time_t stime; int len; utime_t JobTDate; char ed1[30], ed2[30]; char esc_ujobname[MAX_ESCAPE_NAME_LENGTH]; char esc_jobname[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); stime = jr->SchedTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); JobTDate = (utime_t)stime; len = strlen(jcr->comment); /* TODO: use jr instead of jcr to get comment */ buf.check_size(len * 2 + 1); escape_string(jcr, buf.c_str(), jcr->comment, len); escape_string(jcr, esc_ujobname, jr->Job, strlen(jr->Job)); escape_string(jcr, esc_jobname, jr->Name, strlen(jr->Name)); /* * Must create it */ Mmsg(cmd, "INSERT INTO Job (Job,Name,Type,Level,JobStatus,SchedTime,JobTDate," "ClientId,Comment) " "VALUES ('%s','%s','%c','%c','%c','%s',%s,%s,'%s')", esc_ujobname, esc_jobname, (char)(jr->JobType), (char)(jr->JobLevel), (char)(jr->JobStatus), dt, edit_uint64(JobTDate, ed1), edit_int64(jr->ClientId, ed2), buf.c_str()); jr->JobId = sql_insert_autokey_record(cmd, NT_("Job")); if (jr->JobId == 0) { Mmsg2(errmsg, _("Create DB Job record %s failed. ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } db_unlock(this); return retval; } /** * Create a JobMedia record for medium used this job * Returns: false on failure * true on success */ bool B_DB::create_jobmedia_record(JCR *jcr, JOBMEDIA_DBR *jm) { bool retval = false; int count; char ed1[50], ed2[50], ed3[50]; db_lock(this); /* * Now get count for VolIndex */ Mmsg(cmd, "SELECT count(*) from JobMedia WHERE JobId=%s", edit_int64(jm->JobId, ed1)); count = get_sql_record_max(jcr); if (count < 0) { count = 0; } count++; Mmsg(cmd, "INSERT INTO JobMedia (JobId,MediaId,FirstIndex,LastIndex," "StartFile,EndFile,StartBlock,EndBlock,VolIndex,JobBytes) " "VALUES (%s,%s,%u,%u,%u,%u,%u,%u,%u,%s)", edit_int64(jm->JobId, ed1), edit_int64(jm->MediaId, ed2), jm->FirstIndex, jm->LastIndex, jm->StartFile, jm->EndFile, jm->StartBlock, jm->EndBlock, count, edit_uint64(jm->JobBytes, ed3)); Dmsg0(300, cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create JobMedia record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { /* * Worked, now update the Media record with the EndFile and EndBlock */ Mmsg(cmd, "UPDATE Media SET EndFile=%u, EndBlock=%u WHERE MediaId=%u", jm->EndFile, jm->EndBlock, jm->MediaId); if (!UPDATE_DB(jcr, cmd)) { Mmsg2(errmsg, _("Update Media record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } } db_unlock(this); Dmsg0(300, "Return from JobMedia\n"); return retval; } /** * Create Unique Pool record * Returns: false on failure * true on success */ bool B_DB::create_pool_record(JCR *jcr, POOL_DBR *pr) { bool retval = false; char ed1[30], ed2[30], ed3[50], ed4[50], ed5[50]; char esc_poolname[MAX_ESCAPE_NAME_LENGTH]; char esc_lf[MAX_ESCAPE_NAME_LENGTH]; int num_rows; Dmsg0(200, "In create pool\n"); db_lock(this); escape_string(jcr, esc_poolname, pr->Name, strlen(pr->Name)); escape_string(jcr, esc_lf, pr->LabelFormat, strlen(pr->LabelFormat)); Mmsg(cmd, "SELECT PoolId,Name FROM Pool WHERE Name='%s'", esc_poolname); Dmsg1(200, "selectpool: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 0) { Mmsg1(errmsg, _("pool record %s already exists\n"), pr->Name); sql_free_result(); goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Pool (Name,NumVols,MaxVols,UseOnce,UseCatalog," "AcceptAnyVolume,AutoPrune,Recycle,VolRetention,VolUseDuration," "MaxVolJobs,MaxVolFiles,MaxVolBytes,PoolType,LabelType,LabelFormat," "RecyclePoolId,ScratchPoolId,ActionOnPurge,MinBlocksize,MaxBlocksize) " "VALUES ('%s',%u,%u,%d,%d,%d,%d,%d,%s,%s,%u,%u,%s,'%s',%d,'%s',%s,%s,%d,%d,%d)", esc_poolname, pr->NumVols, pr->MaxVols, pr->UseOnce, pr->UseCatalog, pr->AcceptAnyVolume, pr->AutoPrune, pr->Recycle, edit_uint64(pr->VolRetention, ed1), edit_uint64(pr->VolUseDuration, ed2), pr->MaxVolJobs, pr->MaxVolFiles, edit_uint64(pr->MaxVolBytes, ed3), pr->PoolType, pr->LabelType, esc_lf, edit_int64(pr->RecyclePoolId,ed4), edit_int64(pr->ScratchPoolId,ed5), pr->ActionOnPurge, pr->MinBlocksize, pr->MaxBlocksize); Dmsg1(200, "Create Pool: %s\n", cmd); pr->PoolId = sql_insert_autokey_record(cmd, NT_("Pool")); if (pr->PoolId == 0) { Mmsg2(errmsg, _("Create db Pool record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } bail_out: db_unlock(this); Dmsg0(500, "Create Pool: done\n"); return retval; } /** * Create Unique Device record * Returns: false on failure * true on success */ bool B_DB::create_device_record(JCR *jcr, DEVICE_DBR *dr) { bool retval = false; SQL_ROW row; char ed1[30], ed2[30]; char esc[MAX_ESCAPE_NAME_LENGTH]; int num_rows; Dmsg0(200, "In create Device\n"); db_lock(this); escape_string(jcr, esc, dr->Name, strlen(dr->Name)); Mmsg(cmd, "SELECT DeviceId,Name FROM Device WHERE Name='%s' AND StorageId = %s", esc, edit_int64(dr->StorageId, ed1)); Dmsg1(200, "selectdevice: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); /* * If more than one, report error, but return first row */ if (num_rows > 1) { Mmsg1(errmsg, _("More than one Device!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching Device row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } dr->DeviceId = str_to_int64(row[0]); if (row[1]) { bstrncpy(dr->Name, row[1], sizeof(dr->Name)); } else { dr->Name[0] = 0; /* no name */ } sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Device (Name,MediaTypeId,StorageId) VALUES ('%s',%s,%s)", esc, edit_uint64(dr->MediaTypeId, ed1), edit_int64(dr->StorageId, ed2)); Dmsg1(200, "Create Device: %s\n", cmd); dr->DeviceId = sql_insert_autokey_record(cmd, NT_("Device")); if (dr->DeviceId == 0) { Mmsg2(errmsg, _("Create db Device record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a Unique record for Storage -- no duplicates * Returns: false on failure * true on success with id in sr->StorageId */ bool B_DB::create_storage_record(JCR *jcr, STORAGE_DBR *sr) { SQL_ROW row; bool retval = false; int num_rows; char esc[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc, sr->Name, strlen(sr->Name)); Mmsg(cmd, "SELECT StorageId,AutoChanger FROM Storage WHERE Name='%s'", esc); sr->StorageId = 0; sr->created = false; /* * Check if it already exists */ if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); /* * If more than one, report error, but return first row */ if (num_rows > 1) { Mmsg1(errmsg, _("More than one Storage record!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching Storage row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } sr->StorageId = str_to_int64(row[0]); sr->AutoChanger = atoi(row[1]); /* bool */ sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Storage (Name,AutoChanger)" " VALUES ('%s',%d)", esc, sr->AutoChanger); sr->StorageId = sql_insert_autokey_record(cmd, NT_("Storage")); if (sr->StorageId == 0) { Mmsg2(errmsg, _("Create DB Storage record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { sr->created = true; retval = true; } bail_out: db_unlock(this); return retval; } /** * Create Unique MediaType record * Returns: false on failure * true on success */ bool B_DB::create_mediatype_record(JCR *jcr, MEDIATYPE_DBR *mr) { bool retval = false; int num_rows; char esc[MAX_ESCAPE_NAME_LENGTH]; Dmsg0(200, "In create mediatype\n"); db_lock(this); escape_string(jcr, esc, mr->MediaType, strlen(mr->MediaType)); Mmsg(cmd, "SELECT MediaTypeId,MediaType FROM MediaType WHERE MediaType='%s'", esc); Dmsg1(200, "selectmediatype: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 0) { Mmsg1(errmsg, _("mediatype record %s already exists\n"), mr->MediaType); sql_free_result(); goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO MediaType (MediaType,ReadOnly) " "VALUES ('%s',%d)", mr->MediaType, mr->ReadOnly); Dmsg1(200, "Create mediatype: %s\n", cmd); mr->MediaTypeId = sql_insert_autokey_record(cmd, NT_("MediaType")); if (mr->MediaTypeId == 0) { Mmsg2(errmsg, _("Create db mediatype record %s failed: ERR=%s\n"), cmd, sql_strerror()); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create Media record. VolumeName and non-zero Slot must be unique * Returns: false on failure * true on success with id in mr->MediaId */ bool B_DB::create_media_record(JCR *jcr, MEDIA_DBR *mr) { bool retval = false; char ed1[50], ed2[50], ed3[50], ed4[50], ed5[50], ed6[50], ed7[50], ed8[50]; char ed9[50], ed10[50], ed11[50], ed12[50]; int num_rows; char esc_medianame[MAX_ESCAPE_NAME_LENGTH]; char esc_mtype[MAX_ESCAPE_NAME_LENGTH]; char esc_status[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc_medianame, mr->VolumeName, strlen(mr->VolumeName)); escape_string(jcr, esc_mtype, mr->MediaType, strlen(mr->MediaType)); escape_string(jcr, esc_status, mr->VolStatus, strlen(mr->VolStatus)); Mmsg(cmd, "SELECT MediaId FROM Media WHERE VolumeName='%s'", esc_medianame); Dmsg1(500, "selectpool: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 0) { Mmsg1(errmsg, _("Volume \"%s\" already exists.\n"), mr->VolumeName); sql_free_result(); goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Media (VolumeName,MediaType,MediaTypeId,PoolId,MaxVolBytes," "VolCapacityBytes,Recycle,VolRetention,VolUseDuration,MaxVolJobs,MaxVolFiles," "VolStatus,Slot,VolBytes,InChanger,VolReadTime,VolWriteTime," "EndFile,EndBlock,LabelType,StorageId,DeviceId,LocationId," "ScratchPoolId,RecyclePoolId,Enabled,ActionOnPurge,EncryptionKey," "MinBlocksize,MaxBlocksize) " "VALUES ('%s','%s',0,%u,%s,%s,%d,%s,%s,%u,%u,'%s',%d,%s,%d,%s,%s,0,0,%d,%s," "%s,%s,%s,%s,%d,%d,'%s',%d,%d)", esc_medianame, esc_mtype, mr->PoolId, edit_uint64(mr->MaxVolBytes,ed1), edit_uint64(mr->VolCapacityBytes, ed2), mr->Recycle, edit_uint64(mr->VolRetention, ed3), edit_uint64(mr->VolUseDuration, ed4), mr->MaxVolJobs, mr->MaxVolFiles, esc_status, mr->Slot, edit_uint64(mr->VolBytes, ed5), mr->InChanger, edit_int64(mr->VolReadTime, ed6), edit_int64(mr->VolWriteTime, ed7), mr->LabelType, edit_int64(mr->StorageId, ed8), edit_int64(mr->DeviceId, ed9), edit_int64(mr->LocationId, ed10), edit_int64(mr->ScratchPoolId, ed11), edit_int64(mr->RecyclePoolId, ed12), mr->Enabled, mr->ActionOnPurge, mr->EncrKey, mr->MinBlocksize, mr->MaxBlocksize); Dmsg1(500, "Create Volume: %s\n", cmd); mr->MediaId = sql_insert_autokey_record(cmd, NT_("Media")); if (mr->MediaId == 0) { Mmsg2(errmsg, _("Create DB Media record %s failed. ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; if (mr->set_label_date) { char dt[MAX_TIME_LENGTH]; if (mr->LabelDate == 0) { mr->LabelDate = time(NULL); } bstrutime(dt, sizeof(dt), mr->LabelDate); Mmsg(cmd, "UPDATE Media SET LabelDate='%s' " "WHERE MediaId=%d", dt, mr->MediaId); retval = UPDATE_DB(jcr, cmd); } /* * Make sure that if InChanger is non-zero any other identical slot * has InChanger zero. */ make_inchanger_unique(jcr, mr); } bail_out: db_unlock(this); return retval; } /** * Create a Unique record for the client -- no duplicates * Returns: false on failure * true on success with id in cr->ClientId */ bool B_DB::create_client_record(JCR *jcr, CLIENT_DBR *cr) { bool retval = false; SQL_ROW row; char ed1[50], ed2[50]; int num_rows; char esc_clientname[MAX_ESCAPE_NAME_LENGTH]; char esc_uname[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc_clientname, cr->Name, strlen(cr->Name)); escape_string(jcr, esc_uname, cr->Uname, strlen(cr->Uname)); Mmsg(cmd, "SELECT ClientId,Uname FROM Client WHERE Name='%s'", esc_clientname); cr->ClientId = 0; if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); /* * If more than one, report error, but return first row */ if (num_rows > 1) { Mmsg1(errmsg, _("More than one Client!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching Client row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } cr->ClientId = str_to_int64(row[0]); if (row[1]) { bstrncpy(cr->Uname, row[1], sizeof(cr->Uname)); } else { cr->Uname[0] = 0; /* no name */ } sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Client (Name,Uname,AutoPrune," "FileRetention,JobRetention) VALUES " "('%s','%s',%d,%s,%s)", esc_clientname, esc_uname, cr->AutoPrune, edit_uint64(cr->FileRetention, ed1), edit_uint64(cr->JobRetention, ed2)); cr->ClientId = sql_insert_autokey_record(cmd, NT_("Client")); if (cr->ClientId == 0) { Mmsg2(errmsg, _("Create DB Client record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a Unique record for the Path -- no duplicates * Returns: false on failure * true on success with id in cr->ClientId */ bool B_DB::create_path_record(JCR *jcr, ATTR_DBR *ar) { bool retval = false; SQL_ROW row; int num_rows; errmsg[0] = 0; esc_name = check_pool_memory_size(esc_name, 2 * pnl + 2); escape_string(jcr, esc_name, path, pnl); if (cached_path_id != 0 && cached_path_len == pnl && bstrcmp(cached_path, path)) { ar->PathId = cached_path_id; return true; } Mmsg(cmd, "SELECT PathId FROM Path WHERE Path='%s'", esc_name); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 1) { char ed1[30]; Mmsg2(errmsg, _("More than one Path!: %s for path: %s\n"), edit_uint64(num_rows, ed1), path); Jmsg(jcr, M_WARNING, 0, "%s", errmsg); } /* * Even if there are multiple paths, take the first one */ if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); ar->PathId = 0; ASSERT(ar->PathId); goto bail_out; } ar->PathId = str_to_int64(row[0]); sql_free_result(); /* * Cache path */ if (ar->PathId != cached_path_id) { cached_path_id = ar->PathId; cached_path_len = pnl; pm_strcpy(cached_path, path); } ASSERT(ar->PathId); retval = true; goto bail_out; } sql_free_result(); } Mmsg(cmd, "INSERT INTO Path (Path) VALUES ('%s')", esc_name); ar->PathId = sql_insert_autokey_record(cmd, NT_("Path")); if (ar->PathId == 0) { Mmsg2(errmsg, _("Create db Path record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); ar->PathId = 0; goto bail_out; } /* * Cache path */ if (ar->PathId != cached_path_id) { cached_path_id = ar->PathId; cached_path_len = pnl; pm_strcpy(cached_path, path); } retval = true; bail_out: return retval; } /** * Create a Unique record for the counter -- no duplicates * Returns: false on failure * true on success with counter filled in */ bool B_DB::create_counter_record(JCR *jcr, COUNTER_DBR *cr) { bool retval = false; char esc[MAX_ESCAPE_NAME_LENGTH]; COUNTER_DBR mcr; db_lock(this); memset(&mcr, 0, sizeof(mcr)); bstrncpy(mcr.Counter, cr->Counter, sizeof(mcr.Counter)); if (get_counter_record(jcr, &mcr)) { memcpy(cr, &mcr, sizeof(COUNTER_DBR)); retval = true; goto bail_out; } escape_string(jcr, esc, cr->Counter, strlen(cr->Counter)); /* * Must create it */ fill_query(SQL_QUERY_insert_counter_values, esc, cr->MinValue, cr->MaxValue, cr->CurrentValue, cr->WrapCounter); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB Counters record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a FileSet record. This record is unique in the * name and the MD5 signature of the include/exclude sets. * Returns: false on failure * true on success with FileSetId in record */ bool B_DB::create_fileset_record(JCR *jcr, FILESET_DBR *fsr) { bool retval = false; SQL_ROW row; int num_rows, len; char esc_fs[MAX_ESCAPE_NAME_LENGTH]; char esc_md5[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); fsr->created = false; escape_string(jcr, esc_fs, fsr->FileSet, strlen(fsr->FileSet)); escape_string(jcr, esc_md5, fsr->MD5, strlen(fsr->MD5)); Mmsg(cmd, "SELECT FileSetId,CreateTime FROM FileSet WHERE " "FileSet='%s' AND MD5='%s'", esc_fs, esc_md5); fsr->FileSetId = 0; if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 1) { Mmsg1(errmsg, _("More than one FileSet!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching FileSet row: ERR=%s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } fsr->FileSetId = str_to_int64(row[0]); if (row[1] == NULL) { fsr->cCreateTime[0] = 0; } else { bstrncpy(fsr->cCreateTime, row[1], sizeof(fsr->cCreateTime)); } sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ if (fsr->CreateTime == 0 && fsr->cCreateTime[0] == 0) { fsr->CreateTime = time(NULL); } bstrutime(fsr->cCreateTime, sizeof(fsr->cCreateTime), fsr->CreateTime); if (fsr->FileSetText) { POOL_MEM esc_filesettext(PM_MESSAGE); len = strlen(fsr->FileSetText); esc_filesettext.check_size(len * 2 + 1); escape_string(jcr, esc_filesettext.c_str(), fsr->FileSetText, len); Mmsg(cmd, "INSERT INTO FileSet (FileSet,MD5,CreateTime,FileSetText) " "VALUES ('%s','%s','%s','%s')", esc_fs, esc_md5, fsr->cCreateTime, esc_filesettext.c_str()); } else { Mmsg(cmd, "INSERT INTO FileSet (FileSet,MD5,CreateTime,FileSetText) " "VALUES ('%s','%s','%s','')", esc_fs, esc_md5, fsr->cCreateTime); } fsr->FileSetId = sql_insert_autokey_record(cmd, NT_("FileSet")); if (fsr->FileSetId == 0) { Mmsg2(errmsg, _("Create DB FileSet record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { fsr->created = true; retval = true; } bail_out: db_unlock(this); return retval; } /** * All sql_batch_* functions are used to do bulk batch insert in File/Filename/Path * tables. * * To sum up : * - bulk load a temp table * - insert missing paths into path with another single query (lock Path table to avoid duplicates). * - then insert the join between the temp, filename and path tables into file. * * Returns: false on failure * true on success */ bool B_DB::write_batch_file_records(JCR *jcr) { bool retval = false; int JobStatus = jcr->JobStatus; if (!jcr->batch_started) { /* no files to backup ? */ Dmsg0(50,"db_create_file_record : no files\n"); return true; } if (job_canceled(jcr)) { goto bail_out; } Dmsg1(50,"db_create_file_record changes=%u\n", changes); jcr->JobStatus = JS_AttrInserting; Jmsg(jcr, M_INFO, 0, "Insert of attributes batch table with %u entries start\n", jcr->db_batch->changes); if (!jcr->db_batch->sql_batch_end(jcr, NULL)) { Jmsg1(jcr, M_FATAL, 0, "Batch end %s\n", errmsg); goto bail_out; } if (job_canceled(jcr)) { goto bail_out; } /* * We have to lock tables */ if (!jcr->db_batch->sql_query(SQL_QUERY_batch_lock_path_query)) { Jmsg1(jcr, M_FATAL, 0, "Lock Path table %s\n", errmsg); goto bail_out; } if (!jcr->db_batch->sql_query(SQL_QUERY_batch_fill_path_query)) { Jmsg1(jcr, M_FATAL, 0, "Fill Path table %s\n",errmsg); jcr->db_batch->sql_query(SQL_QUERY_batch_unlock_tables_query); goto bail_out; } if (!jcr->db_batch->sql_query(SQL_QUERY_batch_unlock_tables_query)) { Jmsg1(jcr, M_FATAL, 0, "Unlock Path table %s\n", errmsg); goto bail_out; } if (!jcr->db_batch->sql_query( "INSERT INTO File (FileIndex, JobId, PathId, Name, LStat, MD5, DeltaSeq, Fhinfo, Fhnode) " "SELECT batch.FileIndex, batch.JobId, Path.PathId, " "batch.Name, batch.LStat, batch.MD5, batch.DeltaSeq, batch.Fhinfo, batch.Fhnode " "FROM batch " "JOIN Path ON (batch.Path = Path.Path) ")) { Jmsg1(jcr, M_FATAL, 0, "Fill File table %s\n", errmsg); goto bail_out; } jcr->JobStatus = JobStatus; /* reset entry status */ Jmsg(jcr, M_INFO, 0, "Insert of attributes batch table done\n"); retval = true; bail_out: sql_query("DROP TABLE batch"); jcr->batch_started = false; changes = 0; return retval; } /** * Create File record in B_DB * * In order to reduce database size, we store the File attributes, * the FileName, and the Path separately. In principle, there * is a single FileName record and a single Path record, no matter * how many times it occurs. This is this subroutine, we separate * the file and the path and fill temporary tables with this three records. * * Note: all routines that call this expect to be able to call * db_strerror(mdb) to get the error message, so the error message * MUST be edited into mdb->errmsg before returning an error status. * * Returns: false on failure * true on success */ bool B_DB::create_batch_file_attributes_record(JCR *jcr, ATTR_DBR *ar) { ASSERT(ar->FileType != FT_BASE); Dmsg1(dbglevel, "Fname=%s\n", ar->fname); Dmsg0(dbglevel, "put_file_into_catalog\n"); if (jcr->batch_started && jcr->db_batch->changes > BATCH_FLUSH) { jcr->db_batch->write_batch_file_records(jcr); } /* * Open the dedicated connection */ if (!jcr->batch_started) { if (!open_batch_connection(jcr)) { return false; /* error already printed */ } if (!jcr->db_batch->sql_batch_start(jcr)) { Mmsg1(errmsg, "Can't start batch mode: ERR=%s", jcr->db_batch->strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); return false; } jcr->batch_started = true; } jcr->db_batch->split_path_and_file(jcr, ar->fname); return jcr->db_batch->sql_batch_insert(jcr, ar); } /** * Create File record in B_DB * * In order to reduce database size, we store the File attributes, * the FileName, and the Path separately. In principle, there * is a single Path record, no matter how many times it occurs. * This is this subroutine, we separate * the file name and the path and create two database records. * * Returns: false on failure * true on success */ bool B_DB::create_file_attributes_record(JCR *jcr, ATTR_DBR *ar) { bool retval = false; db_lock(this); Dmsg1(dbglevel, "Fname=%s\n", ar->fname); Dmsg0(dbglevel, "put_file_into_catalog\n"); split_path_and_file(jcr, ar->fname); if (!create_path_record(jcr, ar)) { goto bail_out; } Dmsg1(dbglevel, "create_path_record: %s\n", esc_name); /* Now create master File record */ if (!create_file_record(jcr, ar)) { goto bail_out; } Dmsg0(dbglevel, "create_file_record OK\n"); Dmsg2(dbglevel, "CreateAttributes Path=%s File=%s\n", path, fname); retval = true; bail_out: db_unlock(this); return retval; } /** * This is the master File entry containing the attributes. * The filename and path records have already been created. * Returns: false on failure * true on success with fileid filled in */ bool B_DB::create_file_record(JCR *jcr, ATTR_DBR *ar) { bool retval = false; static const char *no_digest = "0"; const char *digest; ASSERT(ar->JobId); ASSERT(ar->PathId); esc_name = check_pool_memory_size(esc_name, 2*fnl+2); escape_string(jcr, esc_name, fname, fnl); if (ar->Digest == NULL || ar->Digest[0] == 0) { digest = no_digest; } else { digest = ar->Digest; } /* Must create it */ Mmsg(cmd, "INSERT INTO File (FileIndex,JobId,PathId,Name," "LStat,MD5,DeltaSeq,Fhinfo,Fhnode) VALUES (%u,%u,%u,'%s','%s','%s',%u,%llu,%llu)", ar->FileIndex, ar->JobId, ar->PathId, esc_name, ar->attr, digest, ar->DeltaSeq, ar->Fhinfo, ar->Fhnode); ar->FileId = sql_insert_autokey_record(cmd, NT_("File")); if (ar->FileId == 0) { Mmsg2(errmsg, _("Create db File record %s failed. ERR=%s"), cmd, sql_strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); } else { retval = true; } return retval; } /** * Create file attributes record, or base file attributes record * Returns: false on failure * true on success */ bool B_DB::create_attributes_record(JCR *jcr, ATTR_DBR *ar) { bool retval; errmsg[0] = 0; /* * Make sure we have an acceptable attributes record. */ if (!(ar->Stream == STREAM_UNIX_ATTRIBUTES || ar->Stream == STREAM_UNIX_ATTRIBUTES_EX)) { Mmsg1(errmsg, _("Attempt to put non-attributes into catalog. Stream=%d\n"), ar->Stream); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); return false; } if (ar->FileType != FT_BASE) { if (batch_insert_available()) { retval = create_batch_file_attributes_record(jcr, ar); /* * Error message already printed */ } else { retval = create_file_attributes_record(jcr, ar); } } else if (jcr->HasBase) { retval = create_base_file_attributes_record(jcr, ar); } else { Mmsg0(errmsg, _("Cannot Copy/Migrate job using BaseJob.\n")); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); retval = true; /* in copy/migration what do we do ? */ } return retval; } /** * Create Base File record in B_DB * Returns: false on failure * true on success */ bool B_DB::create_base_file_attributes_record(JCR *jcr, ATTR_DBR *ar) { bool retval; Dmsg1(dbglevel, "create_base_file Fname=%s\n", ar->fname); Dmsg0(dbglevel, "put_base_file_into_catalog\n"); db_lock(this); split_path_and_file(jcr, ar->fname); esc_name = check_pool_memory_size(esc_name, fnl * 2 + 1); escape_string(jcr, esc_name, fname, fnl); esc_path = check_pool_memory_size(esc_path, pnl * 2 + 1); escape_string(jcr, esc_path, path, pnl); Mmsg(cmd, "INSERT INTO basefile%lld (Path, Name) VALUES ('%s','%s')", (uint64_t)jcr->JobId, esc_path, esc_name); retval = INSERT_DB(jcr, cmd); db_unlock(this); return retval; } /** * Cleanup the base file temporary tables */ void B_DB::cleanup_base_file(JCR *jcr) { POOL_MEM buf(PM_MESSAGE); Mmsg(buf, "DROP TABLE new_basefile%lld", (uint64_t) jcr->JobId); sql_query(buf.c_str()); Mmsg(buf, "DROP TABLE basefile%lld", (uint64_t) jcr->JobId); sql_query(buf.c_str()); } /** * Put all base file seen in the backup to the BaseFile table * and cleanup temporary tables * Returns: false on failure * true on success */ bool B_DB::commit_base_file_attributes_record(JCR *jcr) { bool retval; char ed1[50]; db_lock(this); Mmsg(cmd, "INSERT INTO BaseFiles (BaseJobId, JobId, FileId, FileIndex) " "SELECT B.JobId AS BaseJobId, %s AS JobId, " "B.FileId, B.FileIndex " "FROM basefile%s AS A, new_basefile%s AS B " "WHERE A.Path = B.Path " "AND A.Name = B.Name " "ORDER BY B.FileId", edit_uint64(jcr->JobId, ed1), ed1, ed1); retval = sql_query(cmd); jcr->nb_base_files_used = sql_affected_rows(); cleanup_base_file(jcr); db_unlock(this); return retval; } /** * Find the last "accurate" backup state with Base jobs * 1) Get all files with jobid in list (F subquery) * 2) Take only the last version of each file (Temp subquery) => accurate list is ok * 3) Put the result in a temporary table for the end of job * * Returns: false on failure * true on success */ bool B_DB::create_base_file_list(JCR *jcr, char *jobids) { bool retval = false; POOL_MEM buf(PM_MESSAGE); db_lock(this); if (!*jobids) { Mmsg(errmsg, _("ERR=JobIds are empty\n")); goto bail_out; } fill_query(SQL_QUERY_create_temp_basefile, (uint64_t)jcr->JobId); if (!sql_query(cmd)) { goto bail_out; } fill_query(buf, SQL_QUERY_select_recent_version, jobids, jobids); fill_query(SQL_QUERY_create_temp_new_basefile, (uint64_t)jcr->JobId, buf.c_str()); retval = sql_query(cmd); bail_out: db_unlock(this); return retval; } /** * Create Restore Object record in B_DB * Returns: false on failure * true on success */ bool B_DB::create_restore_object_record(JCR *jcr, ROBJECT_DBR *ro) { bool retval = false; int plug_name_len; POOLMEM *esc_plug_name = get_pool_memory(PM_MESSAGE); db_lock(this); Dmsg1(dbglevel, "Oname=%s\n", ro->object_name); Dmsg0(dbglevel, "put_object_into_catalog\n"); fnl = strlen(ro->object_name); esc_name = check_pool_memory_size(esc_name, fnl * 2 + 1); escape_string(jcr, esc_name, ro->object_name, fnl); escape_object(jcr, ro->object, ro->object_len); plug_name_len = strlen(ro->plugin_name); esc_plug_name = check_pool_memory_size(esc_plug_name, plug_name_len*2+1); escape_string(jcr, esc_plug_name, ro->plugin_name, plug_name_len); Mmsg(cmd, "INSERT INTO RestoreObject (ObjectName,PluginName,RestoreObject," "ObjectLength,ObjectFullLength,ObjectIndex,ObjectType," "ObjectCompression,FileIndex,JobId) " "VALUES ('%s','%s','%s',%d,%d,%d,%d,%d,%d,%u)", esc_name, esc_plug_name, esc_obj, ro->object_len, ro->object_full_len, ro->object_index, ro->FileType, ro->object_compression, ro->FileIndex, ro->JobId); ro->RestoreObjectId = sql_insert_autokey_record(cmd, NT_("RestoreObject")); if (ro->RestoreObjectId == 0) { Mmsg2(errmsg, _("Create db Object record %s failed. ERR=%s"), cmd, sql_strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); } else { retval = true; } db_unlock(this); free_pool_memory(esc_plug_name); return retval; } /** * Create a quota record if it does not exist. * Returns: false on failure * true on success */ bool B_DB::create_quota_record(JCR *jcr, CLIENT_DBR *cr) { bool retval = false; char ed1[50]; int num_rows; db_lock(this); Mmsg(cmd, "SELECT ClientId FROM Quota WHERE ClientId='%s'", edit_uint64(cr->ClientId,ed1)); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows == 1) { sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Quota (ClientId, GraceTime, QuotaLimit)" " VALUES ('%s', '%s', %s)", edit_uint64(cr->ClientId, ed1), "0", "0"); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB Quota record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a NDMP level mapping if it does not exist. * Returns: false on failure * true on success */ bool B_DB::create_ndmp_level_mapping(JCR *jcr, JOB_DBR *jr, char *filesystem) { bool retval = false; char ed1[50], ed2[50]; int num_rows; db_lock(this); esc_name = check_pool_memory_size(esc_name, strlen(filesystem) * 2 + 1); escape_string(jcr, esc_name, filesystem, strlen(filesystem)); Mmsg(cmd, "SELECT ClientId FROM NDMPLevelMap WHERE " "ClientId='%s' AND FileSetId='%s' AND FileSystem='%s'", edit_uint64(jr->ClientId, ed1), edit_uint64(jr->FileSetId, ed2), esc_name); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows == 1) { sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO NDMPLevelMap (ClientId, FilesetId, FileSystem, DumpLevel)" " VALUES ('%s', '%s', '%s', %s)", edit_uint64(jr->ClientId, ed1), edit_uint64(jr->FileSetId, ed2), esc_name, "0"); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB NDMP Level Map record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a NDMP Job Environment String * Returns: false on failure * true on success */ bool B_DB::create_ndmp_environment_string(JCR *jcr, JOB_DBR *jr, char *name, char *value) { bool retval = false; char ed1[50], ed2[50]; char esc_envname[MAX_ESCAPE_NAME_LENGTH]; char esc_envvalue[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc_envname, name, strlen(name)); escape_string(jcr, esc_envvalue, value, strlen(value)); Mmsg(cmd, "INSERT INTO NDMPJobEnvironment (JobId, FileIndex, EnvName, EnvValue)" " VALUES ('%s', '%s', '%s', '%s')", edit_int64(jr->JobId, ed1), edit_uint64(jr->FileIndex, ed2), esc_envname, esc_envvalue); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB NDMP Job Environment record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } db_unlock(this); return retval; } /** * Create a Job Statistics record. * Returns: false on failure * true on success */ bool B_DB::create_job_statistics(JCR *jcr, JOB_STATS_DBR *jsr) { time_t stime; bool retval = false; char dt[MAX_TIME_LENGTH]; char ed1[50], ed2[50], ed3[50], ed4[50]; db_lock(this); stime = jsr->SampleTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); /* * Create job statistics record */ Mmsg(cmd, "INSERT INTO JobStats (SampleTime, JobId, JobFiles, JobBytes, DeviceId)" " VALUES ('%s', %s, %s, %s, %s)", dt, edit_int64(jsr->JobId, ed1), edit_uint64(jsr->JobFiles, ed2), edit_uint64(jsr->JobBytes, ed3), edit_int64(jsr->DeviceId, ed4)); Dmsg1(200, "Create job stats: %s\n", cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB JobStats record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a Device Statistics record. * Returns: false on failure * true on success */ bool B_DB::create_device_statistics(JCR *jcr, DEVICE_STATS_DBR *dsr) { time_t stime; bool retval = false; char dt[MAX_TIME_LENGTH]; char ed1[50], ed2[50], ed3[50], ed4[50], ed5[50], ed6[50]; char ed7[50], ed8[50], ed9[50], ed10[50], ed11[50], ed12[50]; db_lock(this); stime = dsr->SampleTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); /* * Create device statistics record */ Mmsg(cmd, "INSERT INTO DeviceStats (DeviceId, SampleTime, ReadTime, WriteTime," " ReadBytes, WriteBytes, SpoolSize, NumWaiting, NumWriters, MediaId," " VolCatBytes, VolCatFiles, VolCatBlocks)" " VALUES (%s, '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", edit_int64(dsr->DeviceId, ed1), dt, edit_uint64(dsr->ReadTime, ed2), edit_uint64(dsr->WriteTime, ed3), edit_uint64(dsr->ReadBytes, ed4), edit_uint64(dsr->WriteBytes, ed5), edit_uint64(dsr->SpoolSize, ed6), edit_uint64(dsr->NumWaiting, ed7), edit_uint64(dsr->NumWriters, ed8), edit_int64(dsr->MediaId, ed9), edit_uint64(dsr->VolCatBytes, ed10), edit_uint64(dsr->VolCatFiles, ed11), edit_uint64(dsr->VolCatBlocks, ed12)); Dmsg1(200, "Create device stats: %s\n", cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB DeviceStats record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a tapealert record. * Returns: false on failure * true on success */ bool B_DB::create_tapealert_statistics(JCR *jcr, TAPEALERT_STATS_DBR *tsr) { time_t stime; bool retval = false; char dt[MAX_TIME_LENGTH]; char ed1[50], ed2[50]; db_lock(this); stime = tsr->SampleTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); /* * Create device statistics record */ Mmsg(cmd, "INSERT INTO TapeAlerts (DeviceId, SampleTime, AlertFlags)" " VALUES (%s, '%s', %s)", edit_int64(tsr->DeviceId, ed1), dt, edit_uint64(tsr->AlertFlags, ed2)); Dmsg1(200, "Create tapealert: %s\n", cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB TapeAlerts record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } #endif /* HAVE_SQLITE3 || HAVE_MYSQL || HAVE_POSTGRESQL || HAVE_INGRES || HAVE_DBI */
28.708108
115
0.605583
30a19e7445d08c0baac9ae0bbc2d884232c675a1
1,446
hpp
C++
apps/las2oci.hpp
libLAS/libLAS-1.6
92b4c1370785481f212cc7fec9623637233c1418
[ "BSD-3-Clause" ]
1
2019-02-13T14:41:23.000Z
2019-02-13T14:41:23.000Z
apps/las2oci.hpp
libLAS/libLAS-1.6
92b4c1370785481f212cc7fec9623637233c1418
[ "BSD-3-Clause" ]
1
2018-03-13T07:12:06.000Z
2018-03-13T07:12:06.000Z
apps/las2oci.hpp
libLAS/libLAS-1.6
92b4c1370785481f212cc7fec9623637233c1418
[ "BSD-3-Clause" ]
2
2021-05-17T02:09:16.000Z
2021-06-21T12:15:52.000Z
#ifndef LAS2OCI_HPP_INCLUDED #define LAS2OCI_HPP_INCLUDED #include "oci_wrapper.h" #include <stdlib.h> // god-awful hack because of GDAL/GeoTIFF's shitty include structure #define CPL_SERV_H_INCLUDED #include <liblas/liblas.hpp> #include <boost/cstdint.hpp> #include <boost/concept_check.hpp> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <exception> #include <algorithm> #include <vector> #include <cctype> #include <cmath> #include <sys/stat.h> using namespace std; using namespace liblas; #ifdef _WIN32 #define compare_no_case(a,b,n) _strnicmp( (a), (b), (n) ) #else #define compare_no_case(a,b,n) strncasecmp( (a), (b), (n) ) #endif #include <boost/array.hpp> #include <boost/shared_ptr.hpp> typedef std::vector<boost::uint32_t> IDVector; typedef boost::shared_ptr< IDVector > IDVectorPtr; typedef struct { long* pc_ids; long* block_ids; long* num_points; OCILobLocator** locators; // =(OCILobLocator**) VSIMalloc( sizeof(OCILobLocator*) * 1 ); std::vector<boost::uint8_t>** blobs; long* srids; long* gtypes; OCIArray** element_arrays; OCIArray** coordinate_arrays; long size; } blocks; // typedef struct // { // double x0; // double x1; // double y0; // double y1; // double z0; // double z1; // bool bUse3d; // // } extent; #include "kdx_util.hpp" #include "oci_util.hpp" #endif // LAS2OCI
17.421687
92
0.674965
30a2394057ff68551582ba148aa198343ee00668
407
cpp
C++
src/system/kernel/arch/sparc/arch_platform.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
2
2020-02-02T06:48:30.000Z
2020-04-05T13:58:32.000Z
src/system/kernel/arch/sparc/arch_platform.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
null
null
null
src/system/kernel/arch/sparc/arch_platform.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1
2022-02-05T11:40:54.000Z
2022-02-05T11:40:54.000Z
/* Copyright 2019, Adrien Destugues, pulkomandy@pulkomandy.tk. * Distributed under the terms of the MIT License. */ #include <arch/platform.h> status_t arch_platform_init(struct kernel_args *kernelArgs) { return B_OK; } status_t arch_platform_init_post_vm(struct kernel_args *kernelArgs) { return B_OK; } status_t arch_platform_init_post_thread(struct kernel_args *kernelArgs) { return B_OK; }
14.535714
62
0.781327
30a7ede92394a9d33e79057d72973a78de7eb231
1,903
cpp
C++
detect_all_cycles.cpp
poojacos/graph_algos
a6e5d5f29b2c18fda73cfdace8781cbddc294650
[ "MIT" ]
null
null
null
detect_all_cycles.cpp
poojacos/graph_algos
a6e5d5f29b2c18fda73cfdace8781cbddc294650
[ "MIT" ]
null
null
null
detect_all_cycles.cpp
poojacos/graph_algos
a6e5d5f29b2c18fda73cfdace8781cbddc294650
[ "MIT" ]
null
null
null
// C++ program to print all the cycles // in an undirected graph //CONCEPT-use colors #include <bits/stdc++.h> using namespace std; const int N = 100000; // variables to be used // in both functions vector<int> graph[N]; vector<int> cycles[N]; // Function to mark the vertex with // different colors for different cycles void dfs_cycle(int node,int parent,int color[],int mark[],int par[],int cyclenumber){ if(color[node]==2)return; if(color[node]==1){ int curr=parent; cyclenumber++; mark[parent]=cyclenumber; //backtrack while(curr!=node){ curr=par[curr]; mark[curr]=cyclenumber; } return; } par[node]=parent; color[node]=1; for(int ii=0;ii<graph[node].size();ii++){ //if not visited previously if(graph[node][ii]==par[node])continue; dfs_cycle(graph[node][ii],node,color,mark,par,cyclenumber); } //all descendants seen so change the color color[node]=2; } // add the edges to the graph void addEdge(int u, int v) { graph[u].push_back(v); graph[v].push_back(u); } // Function to print the cycles void printCycles(int edges, int mark[], int& cyclenumber) { for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push_back(i); } // print all the vertex with same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle cout << "Cycle Number " << i << ": "; for (int x : cycles[i]) cout << x << " "; cout << endl; } } // Driver Code int main() { addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); int color[N]; int par[N]; int mark[N]; int cyclenumber = 0; int edges = 13; dfs_cycle(1, 0, color, mark, par, cyclenumber); printCycles(edges, mark, cyclenumber); }
21.144444
85
0.620074
30a90f9ce996f0be688e897fbc53ec7af868bc92
2,752
cpp
C++
csvreader.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
1
2022-02-23T03:15:54.000Z
2022-02-23T03:15:54.000Z
csvreader.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
null
null
null
csvreader.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
null
null
null
#include "infra/csvreader.h" namespace inf { CsvReader::CsvReader(const fs::path& filename) : _charset(detect_character_set(filename)) , _dataset(gdal::VectorDataSet::open(filename, gdal::VectorType::Csv)) , _layer(_dataset.layer(0)) { } int32_t CsvReader::column_count() const { return _layer.layer_definition().field_count(); } std::string_view CsvReader::column_name(int32_t index) const { return _layer.layer_definition().field_definition(index).name(); } std::optional<int32_t> CsvReader::column_index(const std::string& name) const { if (auto index = _layer.layer_definition().field_index(name); index >= 0) { return index; } return {}; } CsvRowIterator CsvReader::begin() const { return CsvRowIterator(_layer, _charset); } CsvRowIterator CsvReader::end() const { return CsvRowIterator(); } CsvRow::CsvRow(const gdal::Feature& feat, inf::CharacterSet charSet) : _feature(&feat) , _charSet(charSet) { } bool CsvRow::column_is_empty(int32_t index) const noexcept { return _feature->field_as<std::string_view>(index).empty(); } std::string CsvRow::get_string(int32_t index) const noexcept { if (_charSet == CharacterSet::Utf8) { return std::string(_feature->field_as<std::string_view>(index)); } else { return convert_to_utf8(_feature->field_as<std::string_view>(index)); } } std::optional<int32_t> CsvRow::get_int32(int32_t index) const noexcept { return _feature->opt_field_as<int32_t>(index); } std::optional<int64_t> CsvRow::get_int64(int32_t index) const noexcept { return _feature->opt_field_as<int64_t>(index); } std::optional<double> CsvRow::get_double(int32_t index) const noexcept { auto val = _feature->field_as<std::string>(index); if (val.empty()) { return {}; } return CPLAtofM(val.c_str()); } bool CsvRow::operator==(const CsvRow& other) const { return _feature == other._feature; } CsvRowIterator::CsvRowIterator(gdal::Layer layer, inf::CharacterSet charSet) : _iterator(std::move(layer)) , _charset(charSet) , _currentRow(*_iterator, _charset) { } const CsvRow& CsvRowIterator::operator*() { return _currentRow; } const CsvRow* CsvRowIterator::operator->() { return &_currentRow; } CsvRowIterator& CsvRowIterator::operator++() { ++_iterator; _currentRow = CsvRow(*_iterator, _charset); return *this; } CsvRowIterator& CsvRowIterator::operator=(CsvRowIterator&& other) { if (this != &other) { _iterator = std::move(other._iterator); } return *this; } bool CsvRowIterator::operator==(const CsvRowIterator& other) const { return _iterator == other._iterator; } bool CsvRowIterator::operator!=(const CsvRowIterator& other) const { return !(*this == other); } }
21.5
79
0.704578
dd5fdd066ff02cf62e2468cfca7b80c957514164
9,526
hpp
C++
Classes/GestureRecognizers.hpp
bennyk/SmoothDrawing-x
c6095ee078948b82804c30398a65c4f06e522d1b
[ "MIT" ]
4
2016-07-21T10:37:24.000Z
2019-08-22T13:13:53.000Z
Classes/GestureRecognizers.hpp
bennyk/SmoothDrawing-x
c6095ee078948b82804c30398a65c4f06e522d1b
[ "MIT" ]
1
2017-07-14T10:02:12.000Z
2017-07-14T12:54:33.000Z
Classes/GestureRecognizers.hpp
bennyk/SmoothDrawing-x
c6095ee078948b82804c30398a65c4f06e522d1b
[ "MIT" ]
7
2016-02-26T04:07:03.000Z
2021-05-31T01:59:30.000Z
// // GestureRecognizers.hpp // SmoothDrawing // // Created by Benny Khoo on 21/10/2015. // // #ifndef GestureRecognizers_hpp #define GestureRecognizers_hpp #include <stdio.h> #include <array> using namespace cocos2d; class VelocityCalculator { public: using time_point = std::chrono::high_resolution_clock::time_point; static constexpr int MaxVelocitySamples = 10; static constexpr bool Debug = false; public: VelocityCalculator () : _sampleCount(0), _runningVelocitySum(0, 0), _velocitySamples {}, _first(true) { } void reset() { _sampleCount = 0; _runningVelocitySum = Vec2 {0, 0}; _first = true; _velocitySamples = {}; } void addLocation(Vec2 location) { using namespace std::chrono; addLocation(location, high_resolution_clock::now()); } void addLocation(Vec2 location, time_point timestamp) { using namespace std::chrono; if (Debug) CCLOG("adding location %.2f %.2f timestamp %.2lld", location.x, location.y, time_point_cast<milliseconds>(timestamp).time_since_epoch().count()); if (!_first) { high_resolution_clock::duration timeSinceLastUpdate = (timestamp - _prevTimestamp); if (Debug) CCLOG("time since last update %.2lld", duration_cast<milliseconds>(timeSinceLastUpdate).count()); Vec2 instVelocity = Vec2 { (location.x - _prevLocation.x) / duration_cast<milliseconds>(timeSinceLastUpdate).count() * 1000, (location.y - _prevLocation.y) / duration_cast<milliseconds>(timeSinceLastUpdate).count() * 1000 }; int lastSampleIndex = _sampleCount % MaxVelocitySamples; Vec2 lastSample = _velocitySamples[lastSampleIndex]; _runningVelocitySum -= lastSample; _runningVelocitySum += instVelocity; _velocitySamples[lastSampleIndex] = instVelocity; _sampleCount++; } else { _first = false; } _prevLocation = location; _prevTimestamp = timestamp; } Vec2 getLastVelocitySample() { int lastSampleIndex = _sampleCount % MaxVelocitySamples; return _velocitySamples[lastSampleIndex]; } int getSampleCount() { return _sampleCount; } Vec2 getRunningAvgVelocity() { return _sampleCount >= MaxVelocitySamples ? Vec2 { _runningVelocitySum.x / MaxVelocitySamples, _runningVelocitySum.y / MaxVelocitySamples } : Vec2 { _runningVelocitySum.x / _sampleCount, _runningVelocitySum.y / _sampleCount }; } private: bool _first; time_point _prevTimestamp; Vec2 _prevLocation; std::array<Vec2, MaxVelocitySamples> _velocitySamples; int _sampleCount; Vec2 _runningVelocitySum; }; class BasicGestureRecognizer : public Ref { public: enum State { Possible, Began, Changed, Completed, Failed }; using targetCallBack = std::function<void(BasicGestureRecognizer*)>; public: virtual bool init() { _state = Possible; return true; } void setTarget(targetCallBack t) { _target = t; } Vec2 getLocation() { return _location; } State getState() { return _state; } virtual void addWithSceneGraphPriority(EventDispatcher *eventDispatcher, Node *node) = 0; protected: targetCallBack _target; State _state; Vec2 _location; }; class PanGestureRecognizer : public BasicGestureRecognizer { public: static constexpr float MinPanDistance = 5.0f; public: static PanGestureRecognizer *create() { PanGestureRecognizer *node = new (std::nothrow) PanGestureRecognizer(); if (node) { node->init(); node->autorelease(); } else { CC_SAFE_DELETE(node); } return node; } void addWithSceneGraphPriority(EventDispatcher *eventDispatcher, Node *node) { auto eventListener = EventListenerTouchOneByOne::create(); eventListener->onTouchBegan = [this] (Touch *touch, Event *event) -> bool { _location = touch->getLocation(); _velocityCalc.reset(); _velocityCalc.addLocation(_location); _beganLocation = touch->getLocation(); _state = Possible; return true; }; eventListener->onTouchMoved = [this] (Touch *touch, Event *event) { Vec2 location = touch->getLocation(); _velocityCalc.addLocation(touch->getLocation()); _location = location; if (_state == Possible) { if ((location - _beganLocation).getLength() > MinPanDistance) { _state = Began; _target(this); return; } } else if (_state == Began) { _state = Changed; } if (_state == Changed) { _target(this); } }; eventListener->onTouchEnded = [this] (Touch *touch, Event *event) { _location = touch->getLocation(); if (_state == Changed) { _state = Completed; _target(this); } }; eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener, node); } Vec2 getVelocity() { return _velocityCalc.getRunningAvgVelocity(); } private: Vec2 _beganLocation; VelocityCalculator _velocityCalc; }; class LongPressGestureRecognizer : public BasicGestureRecognizer { public: static constexpr long long MinimumPressDurationMilliSecs = 500; static constexpr float AllowableMovement = 10.0; using time_point = std::chrono::high_resolution_clock::time_point; private: static constexpr const char *UpdateKey = "LongPressGestureUpdate"; public: static LongPressGestureRecognizer *create() { LongPressGestureRecognizer *node = new (std::nothrow) LongPressGestureRecognizer(); if (node) { node->init(); node->autorelease(); } else { CC_SAFE_DELETE(node); } return node; } void addWithSceneGraphPriority(EventDispatcher *eventDispatcher, Node *node) { reset(); auto eventListener = EventListenerTouchOneByOne::create(); eventListener->onTouchBegan = [this] (Touch *touch, Event *event) -> bool { _state = Began; _startLocation = touch->getLocation(); _startTime = std::chrono::high_resolution_clock::now(); this->scheduleUpdate(); return true; }; eventListener->onTouchMoved = [this] (Touch *touch, Event *event) { if (_state == Began || _state == Changed) { if ( checkLongPress(touch) ) { _state = Changed; _target(this); } else { reset(); } } }; eventListener->onTouchEnded = [this] (Touch *touch, Event *event) { if (_state == Began || _state == Changed) { if ( checkLongPress(touch) ) { _state = Completed; _target(this); } else { reset(); } } }; eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener, node); _node = node; } void reset() { _state = Possible; this->removeUpdate(); } bool checkLongPress(Touch *touch) { using namespace std::chrono; bool result = false; Vec2 location = touch->getLocation(); float distMoved = (location - _startLocation).getLength(); auto duration = duration_cast<milliseconds>(high_resolution_clock::now() - _startTime).count(); // CCLOG("long press %.2f %lld", distMoved, duration); if ( distMoved < AllowableMovement && duration > MinimumPressDurationMilliSecs) { result = true; } return result; } void scheduleUpdate() { CC_ASSERT(_node != nullptr); // test if gesture is holding on one spot longer than MinimumPressDurationMilliSecs. _node->schedule([this](float dt) { using namespace std::chrono; // CCLOG("received long gesture update"); if (_state == Began || _state == Changed) { auto duration = duration_cast<milliseconds>(high_resolution_clock::now() - _startTime).count(); if (duration > MinimumPressDurationMilliSecs) { _state = Changed; _target(this); reset(); } } }, UpdateKey); } void removeUpdate() { // CCLOG("remove long gesture update"); if (_node != nullptr) { _node->unschedule(UpdateKey); } } private: Vec2 _startLocation; time_point _startTime; Node *_node; }; #endif /* GestureRecognizers_hpp */
28.435821
157
0.5633
dd63164241ee268e1eb32e5e92a5a6d709794b61
766
cpp
C++
interview_preparation_kit/string_manipulation/common_child.cpp
Surya-06/hackerrank
dc001aebe4d2a01adbb711d18089117ba6629b2b
[ "MIT" ]
null
null
null
interview_preparation_kit/string_manipulation/common_child.cpp
Surya-06/hackerrank
dc001aebe4d2a01adbb711d18089117ba6629b2b
[ "MIT" ]
null
null
null
interview_preparation_kit/string_manipulation/common_child.cpp
Surya-06/hackerrank
dc001aebe4d2a01adbb711d18089117ba6629b2b
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int** data; string a ,b; int max ( int a , int b ){ if ( a > b ) return a; return b; } int ss ( int ina , int inb ) { if ( ina == a.size() or inb==b.size() ) return 0; if ( data[ina][inb]!=-1 ) return data[ina][inb]; if ( a[ina]==b[inb] ){ data[ina][inb] = ss(ina+1,inb+1) + 1; return data[ina][inb]; } else{ data[ina][inb] = max ( ss(ina+1,inb) , ss(ina,inb+1) ); return data[ina][inb]; } return 0; } int main(int argc, char const *argv[]) { cin>>a>>b; data = new int*[a.size()+1]; for(int i=0;i<a.size()+1;i++){ data[i] = new int[b.size()+1]; for ( int j=0;j<b.size()+1;j++) data[i][j]=-1; } cout << ss (0,0) <<endl; return 0; }
18.682927
59
0.513055
dd645f424261ce5b53ea1744ecac4d11c2ca18b4
14,422
hpp
C++
include/types/mat.hpp
Oxsomi/core2
96d64fc5f47b6aee2e205205196e4bb1ddee59f6
[ "MIT" ]
null
null
null
include/types/mat.hpp
Oxsomi/core2
96d64fc5f47b6aee2e205205196e4bb1ddee59f6
[ "MIT" ]
12
2020-01-17T21:40:53.000Z
2020-11-18T18:13:35.000Z
include/types/mat.hpp
Oxsomi/core2
96d64fc5f47b6aee2e205205196e4bb1ddee59f6
[ "MIT" ]
null
null
null
#pragma once #include "vec.hpp" //Helper for generating matrices //All rotations and fovs are in radians //Matrix storage template<typename T, usz W, usz H> struct TMatStorage { union { T f[W * H]; T m[W][H]; Vec<T, W> axes[H]; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec<T, W> &axis, const args &...arg): axes{ axis, arg... } {} }; template<typename T> struct TMatStorage<T, 2, 2> { union { T f[4]; T m[2][2]; Vec2<T> axes[2]; struct { Vec2<T> x, y; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec2<T> &axis, const args &...arg): axes{ axis, arg... } {} }; template<typename T> struct TMatStorage<T, 3, 3> { union { T f[9]; T m[3][3]; Vec3<T> axes[3]; struct { Vec3<T> xAxis, yAxis, zAxis; }; struct { Vec2<T> x; T wx; Vec2<T> y; T wy; Vec2<T> pos; T one; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec3<T> &axis, const args &...arg): axes{ axis, arg... } {} }; template<typename T> struct TMatStorage<T, 4, 4> { union { T f[16]; T m[4][4]; Vec4<T> axes[4]; struct { Vec4<T> xAxis, yAxis, zAxis, pos4; }; struct { Vec3<T> x; T wx; Vec3<T> y; T wy; Vec3<T> z; T wz; Vec3<T> pos; T one; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec4<T> &axis0, const Vec4<T> &axis1, const args &...arg): axes{ axis0, axis1, arg... } {} }; template<typename T> struct TMatStorage<T, 4, 3> { union { T f[12]; T m[4][3]; Vec3<T> axes[4]; struct { Vec3<T> x, y, z, pos; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec3<T> &axis, const args &...arg): axes{ axis, arg... } {} }; //Col major matrix base template<typename T, usz W, usz H> struct Mat : public TMatStorage<T, W, H> { //Constants and types static constexpr usz N = W * H, diagonalN = W < H ? W : H; using Type = T; using Diagonal = Vec<T, diagonalN>; using Horizontal = Vec<T, W>; using Vertical = Vec<T, H>; using TMatStorage<T, W, H>::TMatStorage; using TMatStorage<T, W, H>::m; using TMatStorage<T, W, H>::f; using TMatStorage<T, W, H>::axes; static constexpr usz Height = H, Width = W; //Constructors Mat(const Mat&) = default; Mat(Mat&&) = default; Mat &operator=(const Mat&) = default; Mat &operator=(Mat&&) = default; //Scale matrix explicit constexpr inline Mat(const Diagonal &scale) { for (usz i = 0; i < diagonalN; ++i) m[i][i] = scale[i]; } //Identity constexpr inline Mat(): Mat(Diagonal(1)) { } // template<typename ...args> constexpr inline Mat(const Vec<T, W> &axis0, const Vec<T, W> &axis1, const args &...arg): TMatStorage<T, W, H>{ axis0, axis1, arg... } {} //Value matrix constexpr inline Mat(const T &t) { for (usz i = 0; i < N; ++i) f[i] = t; } //TODO: Constructor with T[N] and T[W][H] and T, T, T, ... //Empty matrix static constexpr inline Mat nil() { return Mat(0); } //Access to rows, cols and values static constexpr usz horizontal() { return W; } static constexpr usz vertical() { return H; } Vertical &operator[](const usz i) { return axes[i]; } constexpr const Vertical &operator[](const usz i) const { return axes[i]; } T &operator[](const Vec2usz &xy) { return m[xy.x][xy.y]; } constexpr const T &operator[](const Vec2usz &xy) const { return axes[xy.x][xy.y]; } constexpr Horizontal getHorizontal(const usz j) const { Vertical res; for (usz i = 0; i < W; ++i) res[i] = m[i][j]; return res; } constexpr const Vertical &getVertical(const usz i) const { return axes[i]; } //Arithmetic overloads constexpr Mat &operator+=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] += other.axes[i]; return *this; } constexpr Mat &operator-=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] -= other.axes[i]; return *this; } constexpr Mat &operator/=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] /= other.axes[i]; return *this; } constexpr Mat &operator%=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] %= other.axes[i]; return *this; } constexpr Mat operator+(const Mat &other) const { return Mat(*this) += other; } constexpr Mat operator-(const Mat &other) const { return Mat(*this) -= other; } constexpr Mat operator/(const Mat &other) const { return Mat(*this) /= other; } constexpr Mat operator%(const Mat &other) const { return Mat(*this) %= other; } //Since Matrix multiply is different, mulVal can be used to perform regular multiplications on the values constexpr Mat &mulVal(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] *= other.axes[i]; return *this; } static constexpr inline Mat mulVal(const Mat &a, const Mat &b) { return Mat(a).mulVal(b); } static constexpr inline Mat scale(const Diagonal &diag) { return Mat(diag); } //Comparison constexpr bool operator==(const Mat &other) const { return std::memcmp(f, other.f, sizeof(other)) == 0; } constexpr bool operator!=(const Mat &other) const { return std::memcmp(f, other.f, sizeof(other)); } //Matrix math //TODO: Inverse, determinant constexpr inline Vec<T, H> operator*(const Vec<T, W> &other) const { Vec<T, H> res{}; for (usz i = 0; i < W; ++i) for (usz j = 0; j < H; ++j) res[j] += m[i][j] * other[i]; return res; } constexpr inline Mat operator*(const Mat &other) const { Mat res; for (usz i = 0; i < W; ++i) for (usz j = 0; j < H; ++j) res.m[i][j] = getHorizontal(j).dot(other.getVertical(i)); return res; } constexpr inline Mat &operator*=(const Mat &other) { return *this = *this * other; } constexpr inline Mat<T, H, W> transpose() const { Mat<T, H, W> res{}; for (usz i = 0; i < W && i < H; ++i) for (usz j = 0; j < H && j < W; ++j) res.m[j][i] = m[i][j]; return res; } //Helpers inline Buffer toData() const { return Buffer((u8*)f, (u8*)(f + N)); } template<typename T2, usz W2, usz H2> constexpr inline Mat<T2, W2, H2> cast() const { Mat<T2, W2, H2> res{}; for (usz i = 0; i < W && i < W2; ++i) for (usz j = 0; j < H && j < H2; ++j) res.m[i][j] = T2(m[i][j]); return res; } template<typename T2> constexpr inline T2 cast() const { T2 res{}; for (usz i = 0; i < W && i < T2::horizontal(); ++i) for (usz j = 0; j < H && j < T2::vertical(); ++j) res.m[i][j] = typename T2::Type(m[i][j]); return res; } }; //Helper functions that carry to multiple types of matrices template<typename Mat, typename T> struct TMatHelper { static constexpr inline Mat rotateX(T v) { static_assert( std::is_floating_point_v<typename Mat::Type>, "Can't call TMatHelper<Mat>::rotateX if T isn't a floating point" ); static_assert( Mat::horizontal() > 2 && Mat::vertical() > 2, "Can't call TMatHelper<Mat>::rotateX if Mat's dimensions are less than 3x3" ); Mat res{}; res[1][1] = std::cos(v); res[2][1] = -std::sin(v); res[1][2] = std::sin(v); res[2][2] = std::cos(v); return res; } static constexpr inline Mat rotateY(T v) { static_assert( std::is_floating_point_v<typename Mat::Type>, "Can't call TMatHelper<Mat>::rotateY if T isn't a floating point" ); static_assert( Mat::horizontal() > 2 && Mat::vertical() > 2, "Can't call TMatHelper<Mat>::rotateY if Mat's dimensions are less than 3x3" ); Mat res{}; res[0][0] = std::cos(v); res[0][2] = -std::sin(v); res[2][0] = std::sin(v); res[2][2] = std::cos(v); return res; } static constexpr inline Mat rotateZ(T v) { static_assert( std::is_floating_point_v<typename Mat::Type>, "Can't call TMatHelper<Mat>::rotateZ if T isn't a floating point" ); static_assert( Mat::horizontal() > 1 && Mat::vertical() > 1, "Can't call TMatHelper<Mat>::rotateZ if Mat's dimensions are less than 2x2" ); Mat res{}; res[0][0] = std::cos(v); res[0][1] = -std::sin(v); res[1][0] = std::sin(v); res[1][1] = std::cos(v); return res; } }; //2x2 matrix template<typename T> struct Mat2x2 : public Mat<T, 2, 2> { using Mat<T, 2, 2>::Mat; using Mat<T, 2, 2>::f; constexpr inline Mat2x2(const Mat<T, 2, 2> &dat) : Mat<T, 2, 2>(dat) {} constexpr inline Mat2x2(Mat<T, 2, 2> &&dat) : Mat<T, 2, 2>(dat) {} //Rotate z static constexpr inline Mat2x2 rotateZ(T v) { return TMatHelper<Mat2x2, T>::rotateZ(v); } //Pad to vec4s inline Buffer toGPUData() const { Buffer result(0x20); //2 vec4s std::memcpy(result.data() + 0x00, f + 0x00, 0x08); std::memcpy(result.data() + 0x10, f + 0x08, 0x08); return result; } }; //3x3 matrix template<typename T> struct Mat3x3 : public Mat<T, 3, 3> { using Mat<T, 3, 3>::Mat; using Mat<T, 3, 3>::f; constexpr inline Mat3x3(const Mat<T, 3, 3> &dat) : Mat<T, 3, 3>(dat) {} constexpr inline Mat3x3(Mat<T, 3, 3> &&dat) : Mat<T, 3, 3>(dat) {} //TODO: rotateY3D, rotateZ3D, translate2D, transform2D, orientation3D, perspective/ortho //Rotate z static constexpr Mat3x3 rotateZ(T v) { return TMatHelper<Mat3x3, T>::rotateZ(v); } //Pad to vec4s inline Buffer toGPUData() const { Buffer result(0x30); //3 vec4s std::memcpy(result.data() + 0x00, f + 0x00, 0x0C); std::memcpy(result.data() + 0x10, f + 0x0C, 0x0C); std::memcpy(result.data() + 0x20, f + 0x18, 0x0C); return result; } }; //4x4 matrix template<typename T, usz W, usz H, typename = std::enable_if_t<W == 4 && (H == 3 || W == 4)>> struct MatOT : public Mat<T, W, H> { using Mat<T, W, H>::Mat; using Mat<T, W, H>::f; using Mat<T, W, H>::toData; constexpr inline MatOT(const Mat<T, W, H> &dat) : Mat<T, W, H>(dat) { } constexpr inline MatOT(Mat<T, W, H> &&dat) : Mat<T, W, H>(dat) {} //Rotation static constexpr inline MatOT rotateX(T v) { return TMatHelper<MatOT, T>::rotateX(v); } static constexpr inline MatOT rotateY(T v) { return TMatHelper<MatOT, T>::rotateY(v); } static constexpr inline MatOT rotateZ(T v) { return TMatHelper<MatOT, T>::rotateZ(v); } //Helper functions static constexpr inline MatOT translate(const Vec3<T> &pos) { MatOT res{}; res.pos = pos; return res; } static inline MatOT perspective(T fov, T asp, T n, T f) { static_assert( std::is_floating_point_v<T>, "Can't call MatOT::perspective if T isn't a floating point" ); static_assert(H == 4, "MatOT::perspective only allowed on 4x4 matrices"); T scale = T(1 / tan(fov / 2)); MatOT res( Vec4<T>(scale / asp, -scale, n / (f - n), 0) ); res.m[2][3] = -1; res.m[3][2] = f * n / (f - n); return res; } //TODO: Ortho static constexpr inline MatOT rotate(const Vec3<T> &rot) { return rotateX(rot.x) * rotateY(rot.y) * rotateZ(rot.z); } static constexpr inline MatOT scale(const Vec3<T> &scl) { if constexpr (H == 4) return Mat4x4<T>(Vec4<T>(scl.x, scl.y, scl.z, 1)); else return Mat4x3<T>(Vec3<T>(scl.x, scl.y, scl.z)); } static constexpr inline MatOT transform( const Vec3<T> &pos, const Vec3<T> &rot, const Vec3<T> &scl ) { return translate(pos) * rotate(rot) * scale(scl); } static constexpr inline MatOT view( const Vec3<T> &pos, const Vec3<T> &rot ) { return translate(-pos) * rotate(rot); } static constexpr inline MatOT lookAt( const Vec3<T> &eye, const Vec3<T> &center, const Vec3<T> &up ) { Vec3<T> z = (eye - center).normalize(); Vec3<T> x = (up.cross(z)).normalize(); Vec3<T> y = (z.cross(x)).normalize(); MatOT res; res.x = x; res.y = y; res.z = z; res.pos = -eye; if constexpr (H == 4) res.one = 1; return res; } static constexpr inline MatOT lookDirection( const Vec3<T> &eye, const Vec3<T> &dir, const Vec3<T> &up ) { Vec3<T> z = dir.normalize(); Vec3<T> x = (z.cross(up)).normalize(); Vec3<T> y = (x.cross(z)).normalize(); MatOT res; res.x = x; res.y = y; res.z = z; res.pos = -eye; if constexpr (H == 4) res.one = 1; return res; } //Get gpu data inline Buffer toGPUData() const { return toData(); } }; //Types //2x2 matrices (2d orientation) using Mat2x2i16 = Mat2x2<i16>; using Mat2x2u16 = Mat2x2<u16>; using Mat2x2i16 = Mat2x2<i16>; using Mat2x2u16 = Mat2x2<u16>; using Mat2x2b32 = Mat2x2<u32>; using Mat2x2f32 = Mat2x2<f32>; using Mat2x2i32 = Mat2x2<i32>; using Mat2x2u32 = Mat2x2<u32>; using Mat2x2i64 = Mat2x2<i64>; using Mat2x2u64 = Mat2x2<u64>; using Mat2x2f64 = Mat2x2<f64>; //3x3 matrices (3d orientation or 2d orientation + translation) using Mat3x3i16 = Mat3x3<i16>; using Mat3x3u16 = Mat3x3<u16>; using Mat3x3i16 = Mat3x3<i16>; using Mat3x3u16 = Mat3x3<u16>; using Mat3x3b32 = Mat3x3<u32>; using Mat3x3f32 = Mat3x3<f32>; using Mat3x3i32 = Mat3x3<i32>; using Mat3x3u32 = Mat3x3<u32>; using Mat3x3i64 = Mat3x3<i64>; using Mat3x3u64 = Mat3x3<u64>; using Mat3x3f64 = Mat3x3<f64>; //4x4 matrices (3d orientation + translation) template<typename T> using Mat4x4 = MatOT<T, 4, 4>; using Mat4x4i16 = Mat4x4<i16>; using Mat4x4u16 = Mat4x4<u16>; using Mat4x4i16 = Mat4x4<i16>; using Mat4x4u16 = Mat4x4<u16>; using Mat4x4b32 = Mat4x4<u32>; using Mat4x4f32 = Mat4x4<f32>; using Mat4x4i32 = Mat4x4<i32>; using Mat4x4u32 = Mat4x4<u32>; using Mat4x4i64 = Mat4x4<i64>; using Mat4x4u64 = Mat4x4<u64>; using Mat4x4f64 = Mat4x4<f64>; //4x3 matrices (3d orientation + translation) template<typename T> using Mat4x3 = MatOT<T, 4, 3>; using Mat4x3i16 = Mat4x3<i16>; using Mat4x3u16 = Mat4x3<u16>; using Mat4x3i16 = Mat4x3<i16>; using Mat4x3u16 = Mat4x3<u16>; using Mat4x3b32 = Mat4x3<u32>; using Mat4x3f32 = Mat4x3<f32>; using Mat4x3i32 = Mat4x3<i32>; using Mat4x3u32 = Mat4x3<u32>; using Mat4x3i64 = Mat4x3<i64>; using Mat4x3u64 = Mat4x3<u64>; using Mat4x3f64 = Mat4x3<f64>; namespace oic { template<typename T> struct is_matrix { static constexpr bool value = false; }; template<typename T, usz W, usz H> struct is_matrix<Mat<T, W, H>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat2x2<T>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat3x3<T>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat4x4<T>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat4x3<T>> { static constexpr bool value = true; }; template<typename T> static constexpr bool is_matrix_v = is_matrix<T>::value; }
23.112179
138
0.630495
dd67e82e2b5df1e6dae23bcb1b1e013aedecc0ed
1,542
cpp
C++
src/DynamicRank.FreeForm.Library/libs/External/FreeForm2ExternalData.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
17
2021-11-02T13:52:10.000Z
2022-02-10T07:43:38.000Z
src/DynamicRank.FreeForm.Library/libs/External/FreeForm2ExternalData.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
2
2022-01-23T16:15:40.000Z
2022-03-07T15:54:34.000Z
src/DynamicRank.FreeForm.Library/libs/External/FreeForm2ExternalData.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
1
2022-01-21T09:42:59.000Z
2022-01-21T09:42:59.000Z
/*! * Copyright (c) 2021 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for * license information. */ #include "FreeForm2ExternalData.h" #include <string> #include "FreeForm2Type.h" #include "TypeImpl.h" #include "TypeManager.h" FreeForm2::ExternalData::ExternalData(const std::string &p_name, const FreeForm2::TypeImpl &p_typeImpl) : m_name(p_name), m_type(&p_typeImpl), m_isCompileTimeConst(false) {} FreeForm2::ExternalData::ExternalData(const std::string &p_name, const TypeImpl &p_typeImpl, ConstantValue p_value) : m_name(p_name), m_type(&p_typeImpl), m_isCompileTimeConst(true), m_constantValue(p_value) {} FreeForm2::ExternalData::~ExternalData() {} const std::string &FreeForm2::ExternalData::GetName() const { return m_name; } const FreeForm2::TypeImpl &FreeForm2::ExternalData::GetType() const { return *m_type; } bool FreeForm2::ExternalData::IsCompileTimeConstant() const { return m_isCompileTimeConst; } FreeForm2::ConstantValue FreeForm2::ExternalData::GetCompileTimeValue() const { return m_constantValue; } FreeForm2::ExternalDataManager::ExternalDataManager() : m_typeFactory(new TypeFactory(TypeManager::CreateTypeManager())) {} FreeForm2::ExternalDataManager::~ExternalDataManager() {} FreeForm2::TypeFactory &FreeForm2::ExternalDataManager::GetTypeFactory() { return *m_typeFactory; }
30.84
79
0.705577
dd6bc353fe58b13922c2ef58692429852b1ed9ef
2,360
hpp
C++
framework/platform/android/tcuAndroidWindow.hpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
framework/platform/android/tcuAndroidWindow.hpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
framework/platform/android/tcuAndroidWindow.hpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
#ifndef _TCUANDROIDWINDOW_HPP #define _TCUANDROIDWINDOW_HPP /*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Android window. *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "tcuVector.hpp" #include "deSemaphore.hpp" #include "deMutex.hpp" #include <vector> #include <android/native_window.h> namespace tcu { namespace Android { // \note Window is thread-safe, WindowRegistry is not class Window { public: enum State { STATE_AVAILABLE = 0, STATE_IN_USE, STATE_PENDING_DESTROY, STATE_READY_FOR_DESTROY, STATE_ACQUIRED_FOR_DESTROY, STATE_LAST }; Window (ANativeWindow* window); ~Window (void); bool tryAcquire (void); void release (void); void markForDestroy (void); bool isPendingDestroy (void) const; bool tryAcquireForDestroy(bool onlyMarked); ANativeWindow* getNativeWindow (void) { return m_window; } void setBuffersGeometry (int width, int height, int32_t format); IVec2 getSize (void) const; private: Window (const Window& other); Window& operator= (const Window& other); ANativeWindow* m_window; mutable de::Mutex m_stateLock; State m_state; }; class WindowRegistry { public: WindowRegistry (void); ~WindowRegistry (void); void addWindow (ANativeWindow* window); void destroyWindow (ANativeWindow* window); Window* tryAcquireWindow (void); void garbageCollect (void); private: std::vector<Window*> m_windows; }; } // Android } // tcu #endif // _TCUANDROIDWINDOW_HPP
23.137255
75
0.645339
dd6d7a2708379614a1841ffc927dedf6ff8c7859
4,257
cpp
C++
blast/src/objtools/eutils/api/elink.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/eutils/api/elink.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/eutils/api/elink.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
/* $Id: elink.cpp 196493 2010-07-06 00:37:12Z dicuccio $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * EFetch request * */ #include <ncbi_pch.hpp> #include <objtools/eutils/api/elink.hpp> #include <cgi/cgi_util.hpp> BEGIN_NCBI_SCOPE CELink_Request::CELink_Request(const string& db, CRef<CEUtils_ConnContext>& ctx) : CEUtils_Request(ctx, "elink.fcgi"), m_RelDate(0), m_RetMode(eRetMode_none), m_Cmd(eCmd_none) { SetDatabase(db); } CELink_Request::~CELink_Request(void) { } inline const char* CELink_Request::x_GetRetModeName(void) const { static const char* s_RetModeName[] = { "none", "xml", "ref" }; return s_RetModeName[m_RetMode]; } inline const char* CELink_Request::x_GetCommandName(void) const { static const char* s_CommandName[] = { "none", "prlinks", "llinks", "llinkslib", "lcheck", "ncheck", "neighbor", "neighbor_score", "neighbor_history", "acheck" }; return s_CommandName[m_Cmd]; } string CELink_Request::GetQueryString(void) const { string args = TParent::GetQueryString(); if ( !m_DbFrom.empty() ) { args += "&dbfrom=" + NStr::URLEncode(m_DbFrom, NStr::eUrlEnc_ProcessMarkChars); } string ids = m_IdGroups.AsQueryString(); if ( !ids.empty() ) { args += "&" + ids; } if ( !m_Term.empty() ) { args += "&term=" + NStr::URLEncode(m_Term, NStr::eUrlEnc_ProcessMarkChars); } if ( m_RelDate ) { args += "&reldate" + NStr::IntToString(m_RelDate); } if ( !m_MinDate.IsEmpty() ) { args += "&mindate=" + NStr::URLEncode(m_MinDate.AsString("M/D/Y"), NStr::eUrlEnc_ProcessMarkChars); } if ( !m_MaxDate.IsEmpty() ) { args += "&maxdate=" + NStr::URLEncode(m_MaxDate.AsString("M/D/Y"), NStr::eUrlEnc_ProcessMarkChars); } if ( !m_DateType.empty() ) { args += "&datetype=" + m_DateType; } if ( m_RetMode != eRetMode_none ) { args += "&retmode="; args += x_GetRetModeName(); } if ( m_Cmd != eCmd_none ) { args += "&cmd="; args += x_GetCommandName(); } if ( !m_LinkName.empty() ) { args += "&linkname="; args += NStr::URLEncode(m_LinkName, NStr::eUrlEnc_ProcessMarkChars); } if ( !m_Holding.empty() ) { args += "&holding="; args += NStr::URLEncode(m_Holding, NStr::eUrlEnc_ProcessMarkChars); } if ( !m_Version.empty() ) { args += "&version="; args += NStr::URLEncode(m_Version, NStr::eUrlEnc_ProcessMarkChars); } return args; } ESerialDataFormat CELink_Request::GetSerialDataFormat(void) const { return eSerial_Xml; } CRef<elink::CELinkResult> CELink_Request::GetELinkResult(void) { CObjectIStream* is = GetObjectIStream(); _ASSERT(is); CRef<elink::CELinkResult> res(new elink::CELinkResult); *is >> *res; Disconnect(); return res; } END_NCBI_SCOPE
28.192053
77
0.612403
dd6fc2943c3e92cafa915e06f0f9a2191e0dbd71
7,484
cpp
C++
source/MultiLibrary/Filesystem/Windows/Filesystem.cpp
danielga/multilibrary
3d1177dd3affa875e06015f5e3e42dda525f3336
[ "BSD-3-Clause" ]
2
2018-06-22T12:43:57.000Z
2019-05-31T21:56:27.000Z
source/MultiLibrary/Filesystem/Windows/Filesystem.cpp
danielga/multilibrary
3d1177dd3affa875e06015f5e3e42dda525f3336
[ "BSD-3-Clause" ]
1
2017-09-09T01:21:31.000Z
2017-11-12T17:52:56.000Z
source/MultiLibrary/Filesystem/Windows/Filesystem.cpp
danielga/multilibrary
3d1177dd3affa875e06015f5e3e42dda525f3336
[ "BSD-3-Clause" ]
1
2022-03-30T18:57:41.000Z
2022-03-30T18:57:41.000Z
/************************************************************************* * MultiLibrary - https://danielga.github.io/multilibrary/ * A C++ library that covers multiple low level systems. *------------------------------------------------------------------------ * Copyright (c) 2014-2022, Daniel Almeida * 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. *************************************************************************/ #include <MultiLibrary/Filesystem/Filesystem.hpp> #include <MultiLibrary/Filesystem/File.hpp> #include <MultiLibrary/Filesystem/FileSimple.hpp> #include <MultiLibrary/Common/Unicode.hpp> #include <cstdlib> #include <cstdio> #include <iterator> #include <sys/stat.h> #include <windows.h> #include <direct.h> #undef CreateFile namespace MultiLibrary { namespace Internal { static uint64_t Find( const std::wstring &widefind, std::vector<std::wstring> &files, std::vector<std::wstring> &folders ) { WIN32_FIND_DATA find_data; uint64_t num_files = 0; HANDLE find_handle = FindFirstFileEx( widefind.c_str( ), FindExInfoStandard, &find_data, FindExSearchNameMatch, nullptr, 0 ); while( find_handle != INVALID_HANDLE_VALUE ) { std::wstring filename = find_data.cFileName; if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if( filename != L"." && filename != L".." ) { folders.push_back( filename ); ++num_files; } } else { files.push_back( filename ); ++num_files; } if( FindNextFile( find_handle, &find_data ) == FALSE ) break; } FindClose( find_handle ); return num_files; } static bool IsFolder( const std::wstring &widepath ) { struct _stat64 stat; if( _wstat64( widepath.c_str( ), &stat ) != 0 ) return false; return ( stat.st_mode & S_IFMT ) == S_IFDIR; } static bool RemoveFolder( const std::wstring &widepath, bool recursive ) { if( !IsFolder( widepath ) ) return false; if( recursive ) { std::vector<std::wstring> files; std::vector<std::wstring> folders; Find( widepath + L"/*", files, folders ); for( size_t k = 0; k != files.size( ); ++k ) if ( _wunlink( widepath.c_str( ) ) != 0 ) return false; for( size_t k = 0; k < folders.size( ); ++k ) if ( !RemoveFolder( widepath + L"/" + folders[k], true ) ) return false; } return _wrmdir( widepath.c_str( ) ) == 0; } } Filesystem::~Filesystem( ) { std::vector<FileInternal *>::iterator it, end = open_files.end( ); for( it = open_files.begin( ); it != end; ++it ) fclose( static_cast<FILE *>( ( *it )->Release( ) ) ); } File Filesystem::Open( const std::string &path, const char *mode ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); std::wstring widemode; UTF16::FromUTF8( mode, mode + strlen( mode ), std::back_inserter( widemode ) ); FILE *file = _wfopen( widepath.c_str( ), widemode.c_str( ) ); if( file == nullptr ) return File( std::shared_ptr<FileInternal>( ) ); FileSimple *finternal = new FileSimple( this, file, path ); open_files.push_back( finternal ); return File( std::shared_ptr<FileInternal>( finternal ) ); } int64_t Filesystem::Size( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); struct _stat64 stat; if( _wstat64( widepath.c_str( ), &stat ) == 0 ) return stat.st_size; return -1; } bool Filesystem::Exists( const std::string &path ) { File file = Open( path, "r" ); if( file.IsValid( ) ) { file.Close( ); return true; } return false; } bool Filesystem::RemoveFile( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return _wunlink( widepath.c_str( ) ) == 0; } uint64_t Filesystem::Find( const std::string &find, std::vector<std::string> &files, std::vector<std::string> &folders ) { std::wstring widefind; UTF16::FromUTF8( find.begin( ), find.end( ), std::back_inserter( widefind ) ); std::vector<std::wstring> wfiles; std::vector<std::wstring> wfolders; uint64_t num_files = Internal::Find( widefind, wfiles, wfolders ); files.reserve( wfiles.size( ) ); folders.reserve( wfolders.size( ) ); for( std::vector<std::wstring>::iterator it = wfiles.begin( ); it != wfiles.end( ); ++it ) { std::wstring &wfile = *it; std::string file; UTF8::FromUTF16( wfile.begin( ), wfile.end( ), std::back_inserter( file ) ); files.push_back( file ); } for( std::vector<std::wstring>::iterator it = wfolders.begin( ); it != wfolders.end( ); ++it ) { std::wstring &wfolder = *it; std::string folder; UTF8::FromUTF16( wfolder.begin( ), wfolder.end( ), std::back_inserter( folder ) ); folders.push_back( folder ); } return num_files; } bool Filesystem::IsFolder( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return Internal::IsFolder( widepath ); } bool Filesystem::CreateFolder( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return _wmkdir( widepath.c_str( ) ) == 0; } bool Filesystem::RemoveFolder( const std::string &path, bool recursive ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return Internal::RemoveFolder( widepath, recursive ); } std::string Filesystem::GetExecutablePath( ) { std::string path; wchar_t *widepath = _wpgmptr; if( widepath == nullptr ) return path; UTF8::FromUTF16( widepath, widepath + wcslen( widepath ), std::back_inserter( path ) ); return path; } bool Filesystem::Close( FileInternal *file ) { if( file == nullptr ) return false; std::vector<FileInternal *>::iterator it, end = open_files.end( ); for( it = open_files.begin( ); it != end; ++it ) if( *it == file ) { fclose( static_cast<FILE *>( file->Release( ) ) ); open_files.erase( it ); return true; } return false; } } // namespace MultiLibrary
29.234375
126
0.671833
dd707db35956550729f91f23ed4253756285de90
644
hpp
C++
C++/problems/0182_n_queens.hpp
raulhsant/algorithms
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
[ "MIT" ]
6
2019-03-20T22:23:26.000Z
2020-08-28T03:10:27.000Z
C++/problems/0182_n_queens.hpp
raulhsant/algorithms
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
[ "MIT" ]
15
2019-10-13T20:53:53.000Z
2022-03-31T02:01:35.000Z
C++/problems/0182_n_queens.hpp
raulhsant/algorithms
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
[ "MIT" ]
3
2019-03-11T10:57:46.000Z
2020-02-26T21:13:21.000Z
#ifndef N_QUEENS_HPP_INCLUDED #define N_QUEENS_HPP_INCLUDED #include <bits/stdc++.h> using namespace std; class Solution { private: vector<vector<string>> result; vector<string> createBoard(int n); bool checkColumn(const vector<string> &board,const int &row,const int & column); bool checkDiagonal(const vector<string> &board, const int &row, const int &column); bool checkIDiagonal(const vector<string> &board, const int &row, const int &column); void placeQueen(vector<string> board, int row); public: vector<vector<string>> solveNQueens(int n); }; #include "0182_n_queens.cpp" #endif
23.851852
88
0.704969
dd76f65c64e9fe7e05db1dd8378cf9c66fc19ec5
7,863
cpp
C++
bases/bases.cpp
mgaurav/sandbox
913d6a48ff77068a9bc18a77f51f79551933a71a
[ "MIT" ]
1
2018-08-30T10:17:38.000Z
2018-08-30T10:17:38.000Z
bases/bases.cpp
mgaurav/sandbox
913d6a48ff77068a9bc18a77f51f79551933a71a
[ "MIT" ]
null
null
null
bases/bases.cpp
mgaurav/sandbox
913d6a48ff77068a9bc18a77f51f79551933a71a
[ "MIT" ]
null
null
null
#include <bases.h> // Bases::toBase16, toBase36 #include <cmath> // std::ceil, std::log2 #include <stdexcept> // std::range_error #include <string> // std::string #include <vector> // std::vector namespace { char const BASE_16_CHARS[] = "0123456789abcdef"; char const BASE_36_CHARS[] = "0123456789abcdefghijklmnopqrstuvwxyz"; static_assert( sizeof( BASE_16_CHARS ) == 16 + 1 ); static_assert( sizeof( BASE_36_CHARS ) == 36 + 1 ); constexpr double DIGITS_RATIO_16_TO_36 = std::log2( 16 ) / std::log2( 36 ); constexpr double DIGITS_RATIO_36_TO_16 = std::log2( 36 ) / std::log2( 16 ); size_t digitToIndex( char const digit ) { if( digit >= '0' && digit <= '9' ) return digit - '0'; else if( digit >= 'a' && digit <= 'z' ) return 10 + ( digit - 'a' ); else throw std::range_error( "Invalid input digit: " + digit ); } } // namespace namespace Bases { /* ** Base-36 to Base-16 conversion. ** Doesn't handle the case where evaluated value of Base-36 input ** can overflow size_t range. */ std::string toBase16( std::string const& input ) { if( input.empty() ) return input; if( input.length() == 1 && input[ 0 ] <= 'f' ) return input; size_t const numDigits = std::ceil( input.length() * DIGITS_RATIO_36_TO_16 ); std::string result( numDigits, '0' ); size_t value = digitToIndex( input[ 0 ] ); for( size_t j = 1; j < input.length(); ++j ) value = digitToIndex( input[ j ] ) + 36 * value; size_t i = 0; do { result[ numDigits - i - 1 ] = BASE_16_CHARS[ value % 16 ]; value /= 16; ++i; } while( value != 0 ); // Strip leading zeroes size_t pos = result.find_first_not_of( '0' ); if( pos != std::string::npos ) result.erase( 0, pos ); return result; } /* ** Base-16 to Base-36 conversion. ** Doesn't handle the case where evaluated value of Base-16 input ** can overflow size_t range. */ std::string toBase36( std::string const& input ) { if( input.empty() || input.length() == 1 ) return input; size_t const numDigits = std::ceil( input.length() * DIGITS_RATIO_16_TO_36 ); std::string result( numDigits, '0' ); size_t value = digitToIndex( input[ 0 ] ); for( size_t j = 1; j < input.length(); ++j ) value = digitToIndex( input[ j ] ) + 16 * value; size_t i = 0; do { result[ numDigits - i - 1 ] = BASE_36_CHARS[ value % 36 ]; value /= 36; ++i; } while( value != 0 ); // Strip leading zeroes size_t pos = result.find_first_not_of( '0' ); if( pos != std::string::npos ) result.erase( 0, pos ); return result; } /* ** Base-36 to Base-16 conversion. ** Handles the overflow case. */ std::string toBase16Horner( std::string const& input ) { if( input.empty() ) return input; if( input.length() == 1 && input[ 0 ] <= 'f' ) return input; size_t const numDigits = std::ceil( input.length() * DIGITS_RATIO_36_TO_16 ); std::vector< int > digits( numDigits ); size_t value = digitToIndex( input[ 0 ] ); // Single Base-36 digit can be represented by at most 2 Base-16 digits digits[ 0 ] = value % 16; digits[ 1 ] = value / 16; for( size_t j = 1; j < input.length(); ++j ) { size_t carry = digitToIndex( input[ j ] ); for( size_t i = 0; i < numDigits; ++i ) { size_t const value = carry + digits[ i ] * 36; digits[ i ] = value % 16; carry = value / 16; } } std::string result( numDigits, '0' ); for( size_t i = 0; i < numDigits; ++i ) result[ numDigits - i - 1 ] = BASE_16_CHARS[ digits[ i ] ]; // Strip leading zeroes size_t pos = result.find_first_not_of( '0' ); if( pos != std::string::npos ) result.erase( 0, pos ); return result; } /* ** Base-16 to Base-36 conversion. ** Handles the overflow case. */ std::string toBase36Horner( std::string const& input ) { if( input.empty() || input.length() == 1 ) return input; size_t const numDigits = std::ceil( input.length() * DIGITS_RATIO_16_TO_36 ); std::vector< int > digits( numDigits ); size_t value = digitToIndex( input[ 0 ] ); digits[ 0 ] = value % 36; for( size_t j = 1; j < input.length(); ++j ) { size_t carry = digitToIndex( input[ j ] ); for( size_t i = 0; i < numDigits; ++i ) { size_t const value = carry + digits[ i ] * 16; digits[ i ] = value % 36; carry = value / 36; } } std::string result( numDigits, '0' ); for( size_t i = 0; i < numDigits; ++i ) result[ numDigits - i - 1 ] = BASE_36_CHARS[ digits[ i ] ]; // Strip leading zeroes size_t pos = result.find_first_not_of( '0' ); if( pos != std::string::npos ) result.erase( 0, pos ); return result; } /* ** Base-16 to Base-36 conversion. ** Handles the overflow case and optimized to work with multiple ** digits at a time while performing arithmetic */ std::string toBase36HornerOptimized( std::string const& input ) { if( input.empty() || input.length() == 1 ) return input; std::vector< uint8_t > inputDigits( input.length() ); for( size_t i = 0; i < input.length(); ++i ) inputDigits[ i ] = digitToIndex( input[ i ] ); size_t const numBase36Digits = std::ceil( input.length() * DIGITS_RATIO_16_TO_36 ); // Can handle 6 digits of Base-36 in one go without overflowing size_t // when performing arithmetic according to Horner's method size_t const base36ChunkSize = 6; std::vector< size_t > digits( std::ceil( static_cast< double >( numBase36Digits ) / base36ChunkSize ) ); size_t const numDigits = digits.size(); size_t constexpr base36Divisor = std::pow( 36, base36ChunkSize ); // Can handle 8 digits of Base-16 in one go without overflowing size_t // when performing arithmetic according to Horner's method size_t const base16ChunkSize = 8; size_t const numChunks = input.length() / base16ChunkSize; size_t endOffset = input.length() % base16ChunkSize; auto evaluateBase16Value = [inputDigits]( size_t start, size_t end ) { size_t value = inputDigits[ start ]; for( size_t i = start + 1; i < end; ++i ) value = inputDigits[ i ] + 16 * value; return value; }; // Handle any extra digits at the beginning which is not included in chunks if( endOffset != 0 ) { size_t carry = evaluateBase16Value( 0, endOffset ); int i = 0; do { digits[ i++ ] = carry % base36Divisor; carry /= base36Divisor; } while( carry != 0 ); } for( size_t j = 0; j < numChunks; ++j ) { endOffset += base16ChunkSize; size_t carry = evaluateBase16Value( endOffset - base16ChunkSize, endOffset ); for( size_t i = 0; i < numDigits; ++i ) { size_t const value = carry + digits[ i ] * ( size_t{ 1 } << 32 ); // 16^8 digits[ i ] = value % base36Divisor; carry = value / base36Divisor; } } // Convert each chunk digit to 6 Base-36 digits std::string result( numDigits * base36ChunkSize, '0' ); size_t const len = result.length(); for( size_t i = 0; i < numDigits; ++i ) { size_t value = digits[ i ]; size_t j = 0; size_t const offset = len - base36ChunkSize * i; do { result[ offset - j - 1 ] = BASE_36_CHARS[ value % 36 ]; value /= 36; ++j; } while( j < base36ChunkSize ); } // Strip leading zeroes size_t pos = result.find_first_not_of( '0' ); if( pos != std::string::npos ) result.erase( 0, pos ); return result; } } // namespace Bases
29.784091
108
0.579041
dd79134f524c1814c3c0b766e319640d6e358297
3,301
cpp
C++
libraries/ArduinoJson/test/JsonArray/add.cpp
tarontop/IRmqtt
5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8
[ "MIT" ]
null
null
null
libraries/ArduinoJson/test/JsonArray/add.cpp
tarontop/IRmqtt
5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8
[ "MIT" ]
1
2020-01-09T07:07:44.000Z
2020-01-09T07:07:44.000Z
libraries/ArduinoJson/test/JsonArray/add.cpp
tarontop/IRmqtt
5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8
[ "MIT" ]
null
null
null
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #include <ArduinoJson.h> #include <catch.hpp> TEST_CASE("JsonArray::add()") { DynamicJsonDocument doc; JsonArray _array = doc.to<JsonArray>(); SECTION("int") { _array.add(123); REQUIRE(123 == _array[0].as<int>()); REQUIRE(_array[0].is<int>()); REQUIRE(_array[0].is<double>()); } SECTION("double") { _array.add(123.45); REQUIRE(123.45 == _array[0].as<double>()); REQUIRE(_array[0].is<double>()); REQUIRE_FALSE(_array[0].is<bool>()); } SECTION("bool") { _array.add(true); REQUIRE(true == _array[0].as<bool>()); REQUIRE(_array[0].is<bool>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("const char*") { const char* str = "hello"; _array.add(str); REQUIRE(str == _array[0].as<std::string>()); REQUIRE(_array[0].is<const char*>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("nested array") { DynamicJsonDocument doc2; JsonArray arr = doc2.to<JsonArray>(); _array.add(arr); REQUIRE(arr == _array[0].as<JsonArray>()); REQUIRE(_array[0].is<JsonArray>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("nested object") { DynamicJsonDocument doc2; JsonObject obj = doc2.to<JsonObject>(); _array.add(obj); REQUIRE(obj == _array[0].as<JsonObject>()); REQUIRE(_array[0].is<JsonObject>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("array subscript") { const char* str = "hello"; DynamicJsonDocument doc2; JsonArray arr = doc2.to<JsonArray>(); arr.add(str); _array.add(arr[0]); REQUIRE(str == _array[0]); } SECTION("object subscript") { const char* str = "hello"; DynamicJsonDocument doc2; JsonObject obj = doc2.to<JsonObject>(); obj["x"] = str; _array.add(obj["x"]); REQUIRE(str == _array[0]); } SECTION("should not duplicate const char*") { _array.add("world"); const size_t expectedSize = JSON_ARRAY_SIZE(1); REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate char*") { _array.add(const_cast<char*>("world")); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate std::string") { _array.add(std::string("world")); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should not duplicate serialized(const char*)") { _array.add(serialized("{}")); const size_t expectedSize = JSON_ARRAY_SIZE(1); REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate serialized(char*)") { _array.add(serialized(const_cast<char*>("{}"))); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 2; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate serialized(std::string)") { _array.add(serialized(std::string("{}"))); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 2; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate serialized(std::string)") { _array.add(serialized(std::string("\0XX", 3))); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 3; REQUIRE(expectedSize == doc.memoryUsage()); } }
25.992126
59
0.633141
dd7ff997434a60045ef2756e488b922394b5f920
2,285
cc
C++
cc_mocks/socket.cc
piskorzj/node-packet-socket
151d985dced6fbbd3619e46572b9a6006a689d7a
[ "MIT" ]
7
2017-02-28T14:07:10.000Z
2019-10-08T18:49:42.000Z
cc_mocks/socket.cc
piskorzj/node-packet-socket
151d985dced6fbbd3619e46572b9a6006a689d7a
[ "MIT" ]
2
2017-04-02T12:24:00.000Z
2017-06-08T23:03:00.000Z
cc_mocks/socket.cc
piskorzj/node-packet-socket
151d985dced6fbbd3619e46572b9a6006a689d7a
[ "MIT" ]
null
null
null
#include "CppUTestExt/MockSupport.h" #include "socket.hh" #include <stdexcept> Socket::Socket(const char * device) { mock().actualCall("socket_constructor") .withStringParameter("device", device); if(!mock().returnBoolValueOrDefault(true)) { throw std::runtime_error("forced creation failure"); } } Socket::~Socket() {} int Socket::get_descriptor(void) { return mock().actualCall("get_descriptor").returnIntValue(); } int Socket::send_message(const unsigned char *destination_address, const char *message, int message_length) { mock().actualCall("send_message") .withMemoryBufferParameter("destination_address", destination_address, ETHER_ADDR_LEN) .withMemoryBufferParameter("message", (const unsigned char*)message, message_length) .withIntParameter("message_length", message_length); int return_value = mock().returnIntValueOrDefault(6); if(return_value == -1) { throw std::runtime_error("forced send_message failure"); } return return_value; } int Socket::receive_message(unsigned char *source_address, unsigned char *destination_address, char *buffer, int buffer_size) { mock().actualCall("receive_message") .withOutputParameter("source_address", source_address) .withOutputParameter("destination_address", destination_address) .withOutputParameter("buffer", buffer) .withIntParameter("buffer_size", buffer_size); int return_value = mock().returnIntValueOrDefault(6); if(return_value == -1) { throw std::runtime_error("forced receive_message failure"); } return return_value; } void Socket::add_membership(Socket::MembershipType type, const unsigned char *multicast_address) { mock().actualCall("add_membership") .withIntParameter("type", type) .withMemoryBufferParameter("multicast_address", multicast_address, ETHER_ADDR_LEN); if(!mock().returnBoolValueOrDefault(true)) { throw std::runtime_error("forced add_membership failure"); } } void Socket::drop_membership(Socket::MembershipType type, const unsigned char *multicast_address) { mock().actualCall("drop_membership") .withIntParameter("type", type) .withMemoryBufferParameter("multicast_address", multicast_address, ETHER_ADDR_LEN); if(!mock().returnBoolValueOrDefault(true)) { throw std::runtime_error("forced drop_membership failure"); } }
34.621212
89
0.76849
dd832ab319ce4878ad080464c4635919732aee27
1,687
hpp
C++
jsonrpc/serverMgr.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
null
null
null
jsonrpc/serverMgr.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
null
null
null
jsonrpc/serverMgr.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
2
2019-12-26T13:54:29.000Z
2020-10-31T10:19:13.000Z
/* * serverMgr.hpp * * Created on: Oct 8, 2015 * Author: romeo */ #ifndef INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ #define INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ #include "flexibity/jsonrpc/jsonRpcSerial.hpp" #include "flexibity/jsonrpc/jsonRpcWebsocketClient.hpp" #include "flexibity/genericMgr.hpp" namespace Flexibity{ class serverMgr: public genericMgr<jsonRpcTransport::sPtr>{ public: static constexpr const char* uriOption = "uri"; static constexpr const char* nameOption = "name"; static constexpr const char* serialPrefix = "serial://"; static constexpr const char* wsPrefix = "ws://"; static constexpr const char* wssPrefix = "wss://"; serverMgr(const Json::Value& cfg, serialPortMgr::sPtr pm){ ILOG_INIT(); populateItems(cfg, [&](const Json::Value& iCfg){ return serverFactory(iCfg, pm); }); } static jsonRpcTransport::sPtr serverFactory(const Json::Value& iCfg, serialPortMgr::sPtr pm){ string uri = iCfg[uriOption].asString(); string name = iCfg[nameOption].asString(); //setInstanceName(name); auto resource = getResource(uri, serialPrefix); if (resource.length() > 0) { auto srv = make_shared<jsonRpcSerial>(pm, resource); srv->setInstanceName(name); return srv; } resource = getResource(uri, wsPrefix); if (resource.length() > 0) { return make_shared<jsonRpcWebsocketClient>(iCfg); } //TODO: wss scheme return make_shared<jsonRpcTransport>(); } static const string getResource(const string& uri, const string& prefix){ auto pos = uri.find(prefix); if(pos == 0){ return string(uri, prefix.length()); } return ""; } }; } #endif /* INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ */
23.109589
94
0.713693
dd8497defaf062ee6fc3a88753ba4c155c430632
717
hpp
C++
include/SerialFiller/Crc16Ccitt1021.hpp
gbmhunter/SerialFiller
d678acbf6d29de7042d48c6be8ecef556bb6d857
[ "MIT" ]
9
2019-04-01T16:27:15.000Z
2022-03-14T19:45:34.000Z
include/SerialFiller/Crc16Ccitt1021.hpp
gbmhunter/SerialFiller
d678acbf6d29de7042d48c6be8ecef556bb6d857
[ "MIT" ]
12
2017-06-18T05:06:36.000Z
2018-01-30T21:55:39.000Z
include/SerialFiller/Crc16Ccitt1021.hpp
mbedded-ninja/SerialFiller
d678acbf6d29de7042d48c6be8ecef556bb6d857
[ "MIT" ]
3
2019-09-07T16:56:57.000Z
2022-02-08T03:25:28.000Z
/// /// \file Crc16Ccitt1021.hpp /// \author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja) /// \edited n/a /// \created 2017-06-10 /// \last-modified 2018-01-25 /// \brief Contains the Crc16Ccitt1021 class. /// \details /// See README.rst in root dir for more info. #ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_ #define MN_SERIAL_FILLER_CRC16_CCITT_1021_H_ // Local includes #include "SerialFiller/SerialFiller.hpp" namespace mn { namespace SerialFiller { class Crc16Ccitt1021 { public: static uint16_t Calc(ByteArray data); }; } // namespace SerialFiller } // namespace mn #endif // #ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
24.724138
72
0.680614
dd849dbe0685f69864b08ab75120ea54905c2858
2,024
cpp
C++
DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2021-08-11T06:36:42.000Z
2021-08-11T06:36:42.000Z
/* Minimum Cost of ropes ===================== There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost. Example 1: Input: n = 4 arr[] = {4, 3, 2, 6} Output: 29 Explanation: For example if we are given 4 ropes of lengths 4, 3, 2 and 6. We can connect the ropes in following ways. 1) First connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6 and 5. 2) Now connect ropes of lengths 4 and 5. Now we have two ropes of lengths 6 and 9. 3) Finally connect the two ropes and all ropes have connected. Total cost for connecting all ropes is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes. Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three strings of 3, 2 and 10), then connect 10 and 3 (we get two strings of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38. Example 2: Input: n = 5 arr[] = {4, 2, 7, 6, 9} Output: 62 Explanation: First, connect ropes 4 and 2, which makes the array {6,7,6,9}. Next, add ropes 6 and 6, which results in {12,7,9}. Then, add 7 and 9, which makes the array {12,16}. And finally add these two which gives {28}. Hence, the total cost is 6 + 12 + 16 + 28 = 62. Your Task: You don't need to read input or print anything. Your task isto complete the function minCost() which takes 2 arguments and returns the minimum cost. Expected Time Complexity : O(nlogn) Expected Auxilliary Space : O(n) Constraints: 1 ≤ N ≤ 100000 1 ≤ arr[i] ≤ 106 */ long long minCost(long long arr[], long long n) { priority_queue<long long, vector<long long>, greater<long long>> pq; long long cost = 0; for (int i = 0; i < n; ++i) pq.push(arr[i]); while (pq.size() > 1) { auto a = pq.top(); pq.pop(); auto b = pq.top(); pq.pop(); cost += (a + b); pq.push(a + b); } return cost; }
25.948718
207
0.676877
dd8952d0b69de72be8b0c6ffe35dd52fcdaa906f
769
cpp
C++
exception/IndexOutOfBoundException.cpp
JerryJin93/DataStructure
814857a064495eea51dd76bf85b6f706d6a5ba1f
[ "Apache-2.0" ]
null
null
null
exception/IndexOutOfBoundException.cpp
JerryJin93/DataStructure
814857a064495eea51dd76bf85b6f706d6a5ba1f
[ "Apache-2.0" ]
null
null
null
exception/IndexOutOfBoundException.cpp
JerryJin93/DataStructure
814857a064495eea51dd76bf85b6f706d6a5ba1f
[ "Apache-2.0" ]
null
null
null
// // Created by Jerry on 2021/5/15. // #include "IndexOutOfBoundException.h" #include <cstring> const char *IndexOutOfBoundException::DEFAULT_NAME = "Index out of bound!"; IndexOutOfBoundException::IndexOutOfBoundException(const string& name) { char* origin = const_cast<char*>(name.data()); this->name = static_cast<char *>(malloc(sizeof(char *))); strcpy(this->name, origin); } const char *IndexOutOfBoundException::what() const noexcept { return name; } IndexOutOfBoundException::IndexOutOfBoundException():name(const_cast<char *>(DEFAULT_NAME)) { } char* IndexOutOfBoundException::getMsg() const { return name; } IndexOutOfBoundException::~IndexOutOfBoundException() { if (name) { free(name); name = nullptr; } }
23.30303
93
0.706112
dd8ef8e0c9f40df27ada5889ed871b1821998a93
12,579
cpp
C++
experiments/rmi_lookup.cpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
9
2021-07-01T17:00:42.000Z
2022-03-23T09:21:17.000Z
experiments/rmi_lookup.cpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
1
2021-07-20T13:39:27.000Z
2021-07-20T13:39:27.000Z
experiments/rmi_lookup.cpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
1
2022-01-25T16:39:34.000Z
2022-01-25T16:39:34.000Z
#include <chrono> #include <random> #include "argparse/argparse.hpp" #include "rmi/models.hpp" #include "rmi/rmi.hpp" #include "rmi/util/fn.hpp" #include "rmi/util/search.hpp" using key_type = uint64_t; using namespace std::chrono; std::size_t s_glob; ///< global size_t variable /** * Measures lookup times of @p samples on a given @p Rmi and writes results to `std::cout`. * @tparam Key key type * @tparam Rmi RMI type * @tparam Search search type * @param keys on which the RMI is built * @param n_models number of models in the second layer of the RMI * @param samples for which the lookup time is measured * @param n_reps number of repetitions * @param dataset_name name of the dataset * @param layer1 model type of the first layer * @param layer2 model type of the second layer * @param bound_type used by the RMI * @param search used by the RMI for correction prediction errors */ template<typename Key, typename Rmi, typename Search> void experiment(const std::vector<key_type> &keys, const std::size_t n_models, const std::vector<key_type> &samples, const std::size_t n_reps, const std::string dataset_name, const std::string layer1, const std::string layer2, const std::string bound_type, const std::string search) { using rmi_type = Rmi; auto search_fn = Search(); // Build RMI. rmi_type rmi(keys, n_models); // Perform n_reps runs. for (std::size_t rep = 0; rep != n_reps; ++rep) { // Lookup time. std::size_t lookup_accu = 0; auto start = steady_clock::now(); for (std::size_t i = 0; i != samples.size(); ++i) { auto key = samples.at(i); auto range = rmi.search(key); auto pos = search_fn(keys.begin() + range.lo, keys.begin() + range.hi, keys.begin() + range.pos, key); lookup_accu += std::distance(keys.begin(), pos); } auto stop = steady_clock::now(); auto lookup_time = duration_cast<nanoseconds>(stop - start).count(); s_glob = lookup_accu; // Report results. // Dataset std::cout << dataset_name << ',' << keys.size() << ',' // Index << layer1 << ',' << layer2 << ',' << n_models << ',' << bound_type << ',' << search << ',' << rmi.size_in_bytes() << ',' // Experiment << rep << ',' << samples.size() << ',' // Results << lookup_time << ',' // Checksums << lookup_accu << std::endl; } // reps } /** * @brief experiment function pointer */ typedef void (*exp_fn_ptr)(const std::vector<key_type>&, const std::size_t, const std::vector<key_type>&, const std::size_t, const std::string, const std::string, const std::string, const std::string, const std::string); /** * RMI configuration that holds the string representation of model types of layer 1 and layer 2, error bound type, and * search algorithm. */ struct Config { std::string layer1; std::string layer2; std::string bound_type; std::string search; }; /** * Comparator class for @p Config objects. */ struct ConfigCompare { bool operator() (const Config &lhs, const Config &rhs) const { if (lhs.layer1 != rhs.layer1) return lhs.layer1 < rhs.layer1; if (lhs.layer2 != rhs.layer2) return lhs.layer2 < rhs.layer2; if (lhs.bound_type != rhs.bound_type) return lhs.bound_type < rhs.bound_type; return lhs.search < rhs.search; } }; #define ENTRIES(L1, L2, LT1, LT2) \ { {#L1, #L2, "none", "binary"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "labs", "binary"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "lind", "binary"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "gabs", "binary"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "gind", "binary"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "none", "model_biased_binary"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "labs", "model_biased_binary"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "lind", "model_biased_binary"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "gabs", "model_biased_binary"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "gind", "model_biased_binary"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "none", "linear"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "labs", "linear"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "lind", "linear"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "gabs", "linear"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "gind", "linear"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "none", "model_biased_linear"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "labs", "model_biased_linear"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "lind", "model_biased_linear"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "gabs", "model_biased_linear"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "gind", "model_biased_linear"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "none", "exponential"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "labs", "exponential"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "lind", "exponential"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "gabs", "exponential"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "gind", "exponential"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "none", "model_biased_exponential"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "labs", "model_biased_exponential"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "lind", "model_biased_exponential"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "gabs", "model_biased_exponential"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "gind", "model_biased_exponential"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ static std::map<Config, exp_fn_ptr, ConfigCompare> exp_map { ENTRIES(linear_regression, linear_regression, rmi::LinearRegression, rmi::LinearRegression) ENTRIES(linear_regression, linear_spline, rmi::LinearRegression, rmi::LinearSpline) ENTRIES(linear_spline, linear_regression, rmi::LinearSpline, rmi::LinearRegression) ENTRIES(linear_spline, linear_spline, rmi::LinearSpline, rmi::LinearSpline) ENTRIES(cubic_spline, linear_regression, rmi::CubicSpline, rmi::LinearRegression) ENTRIES(cubic_spline, linear_spline, rmi::CubicSpline, rmi::LinearSpline) ENTRIES(radix, linear_regression, rmi::Radix<key_type>, rmi::LinearRegression) ENTRIES(radix, linear_spline, rmi::Radix<key_type>, rmi::LinearSpline) }; ///< Map that assigns an experiment function pointer to RMI configurations. #undef ENTRIES /** * Triggers measurement of lookup times for an RMI configuration provided via command line arguments. * @param argc arguments counter * @param argv arguments vector */ int main(int argc, char *argv[]) { // Initialize argument parser. argparse::ArgumentParser program(argv[0], "0.1"); // Define arguments. program.add_argument("filename") .help("path to binary file containing uin64_t keys"); program.add_argument("layer1") .help("layer1 model type, either linear_regression, linear_spline, cubic_spline, or radix."); program.add_argument("layer2") .help("layer2 model type, either linear_regression, linear_spline, or cubic_spline."); program.add_argument("n_models") .help("number of models on layer2, power of two is recommended.") .action([](const std::string &s) { return std::stoul(s); }); program.add_argument("bound_type") .help("type of error bounds used, either none, labs, lind, gabs, or gind."); program.add_argument("search") .help("search algorithm for error correction, either binary, model_biased_binary, exponential, model_biased_exponential, linear, or model_biased_linear."); program.add_argument("-n", "--n_reps") .help("number of experiment repetitions") .default_value(std::size_t(3)) .action([](const std::string &s) { return std::stoul(s); }); program.add_argument("-s", "--n_samples") .help("number of sampled lookup keys") .default_value(std::size_t(1'000'000)) .action([](const std::string &s) { return std::stoul(s); }); program.add_argument("--header") .help("output csv header") .default_value(false) .implicit_value(true); // Parse arguments. try { program.parse_args(argc, argv); } catch (const std::runtime_error &err) { std::cout << err.what() << '\n' << program; exit(EXIT_FAILURE); } // Read arguments. const auto filename = program.get<std::string>("filename"); const auto dataset_name = split(filename, '/').back(); const auto layer1 = program.get<std::string>("layer1"); const auto layer2 = program.get<std::string>("layer2"); const auto n_models = program.get<std::size_t>("n_models"); const auto bound_type = program.get<std::string>("bound_type"); const auto search = program.get<std::string>("search"); const auto n_reps = program.get<std::size_t>("-n"); const auto n_samples = program.get<std::size_t>("-s"); // Load keys. auto keys = load_data<key_type>(filename); // Sample keys. uint64_t seed = 42; std::mt19937 gen(seed); std::uniform_int_distribution<> distrib(0, keys.size() - 1); std::vector<key_type> samples; samples.reserve(n_samples); for (std::size_t i = 0; i != n_samples; ++i) samples.push_back(keys[distrib(gen)]); // Lookup experiment. Config config{layer1, layer2, bound_type, search}; if (exp_map.find(config) == exp_map.end()) { std::cerr << "Error: " << layer1 << ',' << layer2 << ',' << bound_type << ',' << search << " is not a valid RMI configuration." << std::endl; exit(EXIT_FAILURE); } exp_fn_ptr exp_fn = exp_map[config]; // Output header. if (program["--header"] == true) std::cout << "dataset," << "n_keys," << "layer1," << "layer2," << "n_models," << "bounds," << "search," << "size_in_bytes," << "rep," << "n_samples," << "lookup_time," << "lookup_accu," << std::endl; // Run experiment. (*exp_fn)(keys, n_models, samples, n_reps, dataset_name, layer1, layer2, bound_type, search); exit(EXIT_SUCCESS); }
45.908759
163
0.608156
dd9a19698deae1729c3f357c3c054c787efda000
2,605
hpp
C++
Source/ReplicantHook/ReplicantHook.hpp
Asiern/ReplicantHook
63cbfd361d738dc37177c8fcf6e2657dc20bd9aa
[ "MIT" ]
11
2021-04-25T15:29:29.000Z
2022-02-27T09:49:54.000Z
Source/ReplicantHook/ReplicantHook.hpp
Asiern/ReplicantHook
63cbfd361d738dc37177c8fcf6e2657dc20bd9aa
[ "MIT" ]
6
2021-04-26T07:39:52.000Z
2021-10-06T14:12:09.000Z
Source/ReplicantHook/ReplicantHook.hpp
Asiern/ReplicantHook
63cbfd361d738dc37177c8fcf6e2657dc20bd9aa
[ "MIT" ]
1
2021-08-28T22:13:50.000Z
2021-08-28T22:13:50.000Z
#pragma once #include <Windows.h> #include <TlHelp32.h> #include <string> #include "Offsets.hpp" #include <map> class ReplicantHook { private: DWORD _pID; uintptr_t _baseAddress; uintptr_t actorPlayable; bool _hooked; offsets _offsets; int _version; std::map<std::string, uintptr_t> _inventory; int gold; std::string zone; std::string name; int health; float magic; int level; double playtime; float x; float y; float z; DWORD _getProcessID(void); uintptr_t _getModuleBaseAddress(DWORD procId, const wchar_t* modName); void _hook(void); void _unHook(void); void _patch(BYTE* destination, BYTE* src, unsigned int size); template <typename T> T readMemory(uintptr_t address); template <typename T> void writeMemory(uintptr_t address, T value); std::string readMemoryString(uintptr_t address); void writeMemoryString(uintptr_t address, std::string value); void loadInventory(); uintptr_t getItemAddress(std::string name); public: ReplicantHook(int version); ~ReplicantHook(); DWORD getProcessID(void); uintptr_t getBaseAddress(void); void start(void); void stop(void); void hookStatus(void); void update(); //Getters bool isHooked(void); int getGold(); std::string getZone(); std::string getName(); int getHealth(); float getMagic(); int getLevel(); double getPlaytime(); float getX(); float getY(); float getZ(); //Setters void setGold(int value); void setZone(std::string value); void setName(std::string value); void setHealth(int value); void setMagic(float value); void setLevel(int value); void setPlaytime(double value); void setX(float value); void setY(float value); void setZ(float value); void setPosition(float x, float y, float z); //Cheats void InfiniteHealth(bool enabled); void InfiniteMagic(bool enabled); //Models void setActorModel(std::string model); std::string getActorModel(); //Inventory std::map<std::string, uintptr_t> getInventory(void); int addItem(std::string name, int quantity); int removeItem(std::string name); }; template<typename T> inline T ReplicantHook::readMemory(uintptr_t address) { T value; HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, this->_pID); ReadProcessMemory(pHandle, (LPCVOID)(address), &value, sizeof(value), NULL); CloseHandle(pHandle); //Close handle to prevent memory leaks return value; } template<typename T> inline void ReplicantHook::writeMemory(uintptr_t address, T value) { HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, NULL, this->_pID); WriteProcessMemory(pHandle, (LPVOID)(address), &value, sizeof(value), NULL); CloseHandle(pHandle); }
23.053097
77
0.74357
dd9b7497e85b64798b1f7286795583dba4fa3aa6
12,213
cpp
C++
Pratica2Final/AlgoritmosBoost.cpp
RafaelDM/Tarea-4
85d5915cce9055245ee35367950b0ed147a634c6
[ "Apache-2.0" ]
null
null
null
Pratica2Final/AlgoritmosBoost.cpp
RafaelDM/Tarea-4
85d5915cce9055245ee35367950b0ed147a634c6
[ "Apache-2.0" ]
null
null
null
Pratica2Final/AlgoritmosBoost.cpp
RafaelDM/Tarea-4
85d5915cce9055245ee35367950b0ed147a634c6
[ "Apache-2.0" ]
null
null
null
/* Rafael Díaz Medina A01024592 David Benjamin Ruiz A01020825 https://www.boost.org/doc/libs/1_55_0/libs/graph/example/ https://www.boost.org/doc/libs/1_55_0/libs/graph/example/dfs-example.cpp https://www.boost.org/doc/libs/1_55_0/libs/graph/example/kruskal-example.cpp https://www.boost.org/doc/libs/1_55_0/libs/graph/example/bfs-example.cpp https://www.boost.org/doc/libs/1_55_0/libs/graph/example/prim-example.cpp https://www.boost.org/doc/libs/1_55_0/libs/graph/example/dijkstra-example.cpp Para poder correr este programa en windows se necesitaron de muchos pasos pero como se consiguio finalmente fue así: 1- Descargar dev-c++ 2- Descargar Boost 3- Configurar las librerías de boost para que el compilador las pudiera leer automaticamente 4- Ejecutar el programa Tenemos contadores en cada uno de los algoritmos y también en las operaciones de inserción y delete Complejidad de crear Vertice O(1) Complejidad de borrar Vertice O(m+n) Complejidad de crear Aristas O(1) Complejidad de borrar Aristas O(1) Complejidad de DFS O(m+n) Este algoritmo utiliza una tecnica Branch and bound Complejidad de BFS O(m+n) Este algoritmo utiliza una tecnica Branch and bound Complejidad de Dijkstra O(n log n) Este algoritmo utiliza una tecnica Avida Complejidad de Prim O(n log n) Este algoritmo utiliza una tecnica Avida Complejidad de Kruskal O(n log n) Este algoritmo utiliza una tecnica Avida Complejidad de Floyd Warshall O(n^3) Este algoritmo utiliza una tecnica de programacion dinamica */ #include <iostream> #include <fstream> #include <stack> #include <map> #include <queue> #include <vector> #include <iostream> #include <iomanip> #include <chrono> #include <string.h> #include <bits/stdc++.h> #include <ctype.h> #include <stdio.h> #include <cstdio> #include <stdio.h> #include <stdlib.h> #include "time.h" #include <ctime> #include <string> #include <algorithm> #include <tuple> #include <iterator> using namespace std; using namespace boost; using namespace std::chrono; #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/graphviz.hpp> #include <boost/tuple/tuple.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/prim_minimum_spanning_tree.hpp> #include <boost/graph/kruskal_min_spanning_tree.hpp> #include <boost/graph/dijsktra_shortest_paths_no_color_map.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/exterior_property.hpp> typedef property<vertex_distance_t, int> Vdistance; typedef property<edge_weight_t, int> EdgeWeight; typedef adjacency_list <vecS, vecS, bidirectionalS, Vdistance, EdgeWeight> Grafo; typedef property_map<Grafo, edge_weight_t>::type EdgeWeights; typedef boost::graph_traits<Grafo>::vertex_descriptor vertex_t; typedef graph_traits < Grafo >::edge_descriptor Edge; typedef boost::exterior_vertex_property<Grafo, int> DistanceProperty; typedef DistanceProperty::matrix_type DistanceMatrix; typedef DistanceProperty::matrix_map_type DistanceMatrixMap; class dfsVisitor : public boost::default_dfs_visitor{ public: void discover_vertex(vertex_t v, const Grafo& n) const{ std::cerr << v << " " ; return; } }; class bfsVisitor : public boost::default_bfs_visitor{ public: void discover_vertex(vertex_t v, const Grafo& n) const{ std::cerr << v << " "; return; } }; //Complejidad del Algoritmo: O(1) Grafo crearVertices(Grafo p,int vertex){ vertex_t u; u= crear_vertice(p); name.push_back( std::to_string(vertex)); std::cout << "Se puso el vertice "<< vertex << "\n"; return p; } //Complejidad del Algoritmo: O(1) Grafo crearAristas(Grafo p, int sale, int entra, int peso){ crear_aristas(sale, entra, peso, p); std::cout << "Se puso la arista de " << sale << " a " << entra << "\n"; return p; } //Complejidad del Algoritmo: O(1) Grafo borrarArista(Grafo p, int sale, int entra){ borrar_arista(sale, entra, p); std::cout << "Se removio la arista de " << sale << " a " << entra << "\n"; return p; } //Complejidad del Algoritmo: O(1) Grafo borrarVertice(Grafo p, int u){ clear_vertex(u,p); borrar_vertice(u, p); std::cout << "Se ha removido el vertice " << u; return p; } //Complejidad del Algoritmo: O(M+N) //Este algoritmo utiliza una tecnica Branch and bound void DFS(Grafo p){ dfsVisitor temp; std::cout << "DFS: \n"; depth_first_search(p, visitor(temp)); } //Complejidad del Algoritmo: O(M+N) //Este algoritmo utiliza una tecnica Branch and bound void BFS(Grafo p, int inicio){ bfsVisitor temp; std::cout << "BFS: \n"; breadth_first_search(p,inicio, visitor(temp)); } //Complejidad del Algoritmo: O(N^2) //Este algoritmo utiliza una tecnica Avida void dijsktra(Grafo n){ std::vector<vertex_t> p(num_vertices(n)); std::vector<int> d(num_vertices(n)); vertex_t s = vertex(1, n); property_map<Grafo, vertex_index_t>::type indexmap = get(vertex_index, n); property_map<Grafo, edge_weight_t>::type weightmap = get(edge_weight, n); dijsktra_shortest_paths(n, s, &p[0], &d[0], weightmap, indexmap, std::less<int>(), closed_plus<int>(),(std::numeric_limits<int>::max)(), 0,default_dijsktra_visitor()); graph_traits <Grafo>::vertex_iterator vi, vend; for (tie(vi, vend) = vertices(n); vi != vend; ++vi){ std::cout << "distancia al vertice " << name[*vi] << " = " << d[*vi] << ", "; std::cout << " con padre " << name[p[*vi]] << std:: endl; } } //Complejidad del Algoritmo: O(N Log(M)) //Este algoritmo utiliza una tecnica Avido void prim(Grafo p){ std::vector<vertex_t> v(num_vertices(p)); property_map<Grafo, vertex_index_t>::type indexmap = get(vertex_index, p); property_map<Grafo, vertex_distance_t>::type distance = get(vertex_distance, p); property_map<Grafo, edge_weight_t>::type weightmap = get(edge_weight, p); prim_minimum_spanning_tree(p, *vertices(p).first,&v[0],distance,weightmap,indexmap, default_dijsktra_visitor()); for (std::size_t i = 1; i != v.size(); ++i){ if (v[i] != i){ std::cout << "parent[" << i << "] = " << v[i] << std::endl; } else{ std::cout << "parent[" << i << "] = no hay padre" << std::endl; } } } //Complejidad del Algoritmo: O(N Log(N)) //Este algoritmo utiliza una tecnica Avido void kruskal(Grafo p){ property_map < Grafo, edge_weight_t >::type weight = get(edge_weight, p); std::vector < Edge > spanning_tree; kruskal_minimum_spanning_tree(p, std::back_inserter(spanning_tree)); std::cout << "Kruskal: \n"; for (std::vector < Edge >::iterator ei = spanning_tree.begin(); ei != spanning_tree.end(); ++ei) { std::cout << source(*ei, p) << " <--> " << target(*ei, p)<< " con peso " << weight[*ei] << std::endl; } } //Complejidad del Algoritmo: O(N^3) //Este algoritmo utiliza una tecnica de programacion dinamica void floydWarshall(Grafo p){ DistanceMatrix distancias(num_vertices(p)); DistanceMatrixMap dm(distancias, p); property_map < Grafo, edge_weight_t >::type weight = get(edge_weight, p); floyd_warshall_all_pairs_shortest_paths(p, dm,boost::weight_map(weight)); std::cout << "\n Floyd-Warshall AP-SP: " << std::endl; for (std::size_t i = 1; i < num_vertices(p); ++i) { for (std::size_t j = 1; j < num_vertices(p); ++j) { std::cout << "del vertice " << i << " al " << j << " : "; if (distancias[i][j] == std::numeric_limits<int>::max()){ std::cout << "X" << std::endl; } else{ std::cout << distancias[i][j] << std::endl; } } std::cout << std::endl; } } }; class GrafoC{ public: std::vector<std::string> name = { "1","2","3","4","5","6","7","8","9","10","11","12","13","14" }; public: Grafo crearGrafo(){ std::vector<int> vertices = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 }; Grafo n(vertices.size()); std::vector<int> pesos = { 8,8,8,7,4,7,9,4,6,2,3,1,2,6,3,3,2,4,10,6,8,6,2,9 }; crear_aristas(1,3,8,n); crear_aristas(1, 4,8,n); crear_aristas(3,5,8,n); crear_aristas(3,2,7,n); crear_aristas(3,10,4,n); crear_aristas(2,5,7,n); crear_aristas(5,6,9,n); crear_aristas(6,13,4,n); crear_aristas(13,14,6,n); crear_aristas(14,13,2,n); crear_aristas(4,7,3,n); crear_aristas(4,5,1,n); crear_aristas(4,8,2,n); crear_aristas(7,4,6,n); crear_aristas(8,7,3, n); crear_aristas(8,9,3, n); crear_aristas(9,10,2, n); crear_aristas(9,12,4, n); crear_aristas(10,3,10, n); crear_aristas(10,6,6, n); crear_aristas(12,11,8, n); crear_aristas(11,12,6, n); crear_aristas(12,9,2, n); crear_aristas(12,14,9, n); return n; } int main(){ high_resolution_clock::time_point t1; high_resolution_clock::time_point t2; duration<double> tiempo; GrafoC test; Grafo n = test.crearGrafo(); int s; while (1){ printf("1.Crear vertice\n2.Borrar vertice\n3.Crear arista\n4.Borrar arista\n5.DFS\n6.BFS\n7.Prim y Kruskal\n8.dijsktra y Floyd-Warshall\n"); scanf("%d", &s); if(s==1){ printf("Ingresa el numero\n"); int num; scanf("%d", &num); t1=high_resolution_clock::now(); test.crearVertices(n, num); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==2){ printf("Ingresa el numero\n"); int num; scanf("%d", &num); t1=high_resolution_clock::now(); test.borrarVertice(n, num); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==3){ printf("Los numeros que vamos a ingresar son 14, 15, 2\n"); t1=high_resolution_clock::now(); test.crearAristas(n, 14, 15, 2); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==4){ printf("Borraremos 10, 3"); t1=high_resolution_clock::now(); test.borrarArista(n, 10, 3); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==5){ printf("Hacemos el corrido de DFS"); t1=high_resolution_clock::now(); test.DFS(n); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==6){ printf("Hacemos el corrido de BFS"); t1=high_resolution_clock::now(); test.BFS(n,1); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==7){ printf("Arbol de recubrimiento Minimo con Prim y Kruskal"); t1=high_resolution_clock::now(); test.prim(n); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; //------------------------------------------------------ t1=high_resolution_clock::now(); test.kruskal(n); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else if(s==8){ printf("Ruta minima con dijsktra y Floyd-Warshall"); t1=high_resolution_clock::now(); test.dijsktra(n); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; //------------------------------------------------- t1=high_resolution_clock::now(); test.FloydWarshall(n); t2=high_resolution_clock::now(); tiempo = duration_cast<duration<double>>(t2-t1); tiempo=tiempo*1000; cout << tiempo.count() << "milisegundos" << endl; } else break; } return 0; }
34.019499
142
0.654876
dd9df012e1a640f25433cf2e364c3ebc8b1c7482
4,275
hpp
C++
src/stm32/registers/cpu_registers.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
null
null
null
src/stm32/registers/cpu_registers.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
2
2021-04-01T21:31:55.000Z
2021-04-06T07:35:04.000Z
src/stm32/registers/cpu_registers.hpp
Rexagon/stm32-emulator
4b4bc449a787c3f79c4e7e9dd563dcb4abc9abeb
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> #include "../utils/general.hpp" namespace stm32::rg { /** * The special-purpose program status registers, xPSR */ DEFINE_REG(ApplicationProgramStatusRegister, { RESERVE(27); ///< bits[26:0] bool Q : 1; ///< bit[27] ///< Set to 1 if a SSAT or USAT instruction changes the input value for the signed or unsigned range ///< of the result. In a processor that implements the DSP extension, the processor sets this bit ///< to 1 to indicate an overflow on some multiplies. Setting this bit to 1 is called saturation. bool V : 1; ///< overflow, bit[28] ///< Overflow condition code flag. Set to 1 if the instruction results in an overflow condition, for ///< example a signed overflow on an addition. bool C : 1; ///< carry, bit[29] ///< Carry condition code flag. Set to 1 if the instruction results in a carry condition, for example an ///< unsigned overflow on an addition. bool Z : 1; ///< zero, bit[30] ///< Zero condition code flag. Set to 1 if the result of the instruction is zero, and to 0 otherwise. A ///< result of zero often indicates an equal result from a comparison. bool N : 1; ///< negative, bit[31] ///< Negative condition code flag. Set to bit[31] of the result of the instruction. If the result is ///< regarded as a two's complement signed integer, then N == 1 if the result is negative and N == 0 if ///< it is positive or zero. }); DEFINE_REG(InterruptProgramStatusRegister, { uint16_t exceptionNumber : 9; ///< bits[8:0] ///< When the processor is executing an exception handler, holds the exception number ///< of the exception being processed. Otherwise, the IPSR value is zero. RESERVE(23); ///< bits[31:9] }); DEFINE_REG(ExecutionProgramStatusRegister, { RESERVE(10); ///< bits[9:0] uint8_t ITlo : 6; ///< bits[15:10] ///< high 6 bits of IT bool T : 1; ///< bit[24] ///< T bit, that is set to 1 to indicate that the processor executes Thumb instructions uint8_t IThi : 2; ///< bits[26:25] ///< low two bits of ITd RESERVE(5); ///< bits[31:27] }); /** * The special-purpose mask registers */ DEFINE_REG(ExceptionMaskRegister, { bool PM : 1; ///< bit[0] ///< Setting PRIMASK to 1 raises the execution priority to 0. RESERVE(31); ///< bits[31:1] }); DEFINE_REG(BasePriorityMaskRegister, { uint8_t level : 8; ///< bit[7:0] ///< Changes the priority level required for exception preemption. It has an effect only when ///< it has a lower value than the unmasked priority level of the currently executing software. RESERVE(24); ///< bits[31:8] }); DEFINE_REG(FaultMaskRegister, { bool FM : 1; ///< bit[0] ///< Setting FM to 1 raises the execution priority to -1, the priority of HardFault. Only ///< privileged software executing at a priority below -1 can set FM to 1. This means ///< HardFault and NMI handlers cannot set FM to 1. Returning from any exception except NMI ///< clears FM to 0. RESERVE(31); ///< bits[31:1] }); /** * The special-purpose CONTROL 2-bit register */ struct __attribute__((__packed__)) ControlRegister { bool nPRIV : 1; ///< bit[0] ///< Defines the execution privilege in Thread mode ///< ///< false - Thread mode has privileged access. ///< ///< true - Thread mode has unprivileged access. bool SPSEL : 1; ///< bit[1] ///< Defines the stack to be used ///< ///< false - Use SP_main as the current stack. ///< ///< true - In Thread mode, use SP_process as the current stack. ///< In Handler mode, this value is reserved }; } // namespace stm32::rg
38.863636
121
0.56
dd9ee85db0caffeef07daeaec74107f9f0614fd0
23,906
cpp
C++
saber/funcs/impl/arm/neon/saber_softmax.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
533
2018-05-18T06:14:04.000Z
2022-03-23T11:46:30.000Z
saber/funcs/impl/arm/neon/saber_softmax.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
100
2018-05-26T08:32:48.000Z
2022-03-17T03:26:25.000Z
saber/funcs/impl/arm/neon/saber_softmax.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
167
2018-05-18T06:14:35.000Z
2022-02-14T01:44:20.000Z
#include "saber/funcs/impl/arm/saber_softmax.h" #include "saber/funcs/impl/arm/neon/impl/neon_mathfun.h" namespace anakin{ namespace saber{ void softmax_basic(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size) { #pragma omp parallel for for (int i = 0; i < compute_size; ++i) { int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_channel_in8(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size){ int cmp_cnt = compute_size >> 3; int remain = compute_size % 8; float32x4_t vone = vdupq_n_f32(1.0f); #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 8; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; //! get max axis_size == 4 const float* din_ptr = din + real_index; const float* din_ptr1 = din_ptr + inner_num; const float* din_ptr2 = din_ptr1 + inner_num; const float* din_ptr3 = din_ptr2 + inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr1); float32x4_t vdata2 = vld1q_f32(din_ptr2); float32x4_t vdata3 = vld1q_f32(din_ptr3); float32x4_t vdata01 = vld1q_f32(din_ptr + 4); float32x4_t vdata11 = vld1q_f32(din_ptr1 + 4); float32x4_t vdata21 = vld1q_f32(din_ptr2 + 4); float32x4_t vdata31 = vld1q_f32(din_ptr3 + 4); float* dout_ptr0 = dout + real_index; float* dout_ptr1 = dout_ptr0 + inner_num; float32x4_t vmax1 = vmaxq_f32(vdata0, vdata1); float32x4_t vmax2 = vmaxq_f32(vdata2, vdata3); float32x4_t vmax11 = vmaxq_f32(vdata01, vdata11); float32x4_t vmax21 = vmaxq_f32(vdata21, vdata31); float* dout_ptr2 = dout_ptr1 + inner_num; float* dout_ptr3 = dout_ptr2 + inner_num; float32x4_t vmax = vmaxq_f32(vmax1, vmax2); float32x4_t vmax_1 = vmaxq_f32(vmax11, vmax21); //! sub, exp and sum float32x4_t vsum0 = exp_ps(vsubq_f32(vdata0, vmax)); float32x4_t vsum1 = exp_ps(vsubq_f32(vdata1, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax)); float32x4_t vsum3 = exp_ps(vsubq_f32(vdata3, vmax)); float32x4_t vsum01 = exp_ps(vsubq_f32(vdata01, vmax_1)); float32x4_t vsum11 = exp_ps(vsubq_f32(vdata11, vmax_1)); float32x4_t vsum21 = exp_ps(vsubq_f32(vdata21, vmax_1)); float32x4_t vsum31 = exp_ps(vsubq_f32(vdata31, vmax_1)); float32x4_t vsum_1 = vaddq_f32(vsum0, vsum1); float32x4_t vsum_2 = vaddq_f32(vsum2, vsum3); float32x4_t vsum_11 = vaddq_f32(vsum01, vsum11); float32x4_t vsum_21 = vaddq_f32(vsum21, vsum31); float32x4_t vsum = vaddq_f32(vsum_1, vsum_2); float32x4_t vsum111 = vaddq_f32(vsum_11, vsum_21); float32x4_t vinf = div_ps(vone, vsum); float32x4_t vinf1 = div_ps(vone, vsum111); vsum0 = vmulq_f32(vsum0, vinf); vsum1 = vmulq_f32(vsum1, vinf); vsum2 = vmulq_f32(vsum2, vinf); vsum3 = vmulq_f32(vsum3, vinf); vsum01 = vmulq_f32(vsum01, vinf1); vsum11 = vmulq_f32(vsum11, vinf1); vsum21 = vmulq_f32(vsum21, vinf1); vsum31 = vmulq_f32(vsum31, vinf1); vst1q_f32(dout_ptr0, vsum0); vst1q_f32(dout_ptr1, vsum1); vst1q_f32(dout_ptr2, vsum2); vst1q_f32(dout_ptr3, vsum3); vst1q_f32(dout_ptr0 + 4, vsum01); vst1q_f32(dout_ptr1 + 4, vsum11); vst1q_f32(dout_ptr2 + 4, vsum21); vst1q_f32(dout_ptr3 + 4, vsum31); } int i = cmp_cnt * 8; if (remain > 4){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; //! get max axis_size == 4 const float* din_ptr = din + real_index; const float* din_ptr1 = din_ptr + inner_num; const float* din_ptr2 = din_ptr1 + inner_num; const float* din_ptr3 = din_ptr2 + inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr1); float32x4_t vdata2 = vld1q_f32(din_ptr2); float32x4_t vdata3 = vld1q_f32(din_ptr3); float* dout_ptr0 = dout + real_index; float* dout_ptr1 = dout_ptr0 + inner_num; float32x4_t vmax1 = vmaxq_f32(vdata0, vdata1); float32x4_t vmax2 = vmaxq_f32(vdata2, vdata3); float* dout_ptr2 = dout_ptr1 + inner_num; float* dout_ptr3 = dout_ptr2 + inner_num; float32x4_t vmax = vmaxq_f32(vmax1, vmax2); //! sub, exp and sum float32x4_t vsum0 = exp_ps(vsubq_f32(vdata0, vmax)); float32x4_t vsum1 = exp_ps(vsubq_f32(vdata1, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax)); float32x4_t vsum3 = exp_ps(vsubq_f32(vdata3, vmax)); float32x4_t vsum_1 = vaddq_f32(vsum0, vsum1); float32x4_t vsum_2 = vaddq_f32(vsum2, vsum3); float32x4_t vsum = vaddq_f32(vsum_1, vsum_2); float32x4_t vone = vdupq_n_f32(1.0f); float32x4_t vinf = div_ps(vone, vsum); vsum0 = vmulq_f32(vsum0, vinf); vsum1 = vmulq_f32(vsum1, vinf); vsum2 = vmulq_f32(vsum2, vinf); vsum3 = vmulq_f32(vsum3, vinf); vst1q_f32(dout_ptr0, vsum0); vst1q_f32(dout_ptr1, vsum1); vst1q_f32(dout_ptr2, vsum2); vst1q_f32(dout_ptr3, vsum3); i += 4; } for (; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_channel_in4(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size){ int cmp_cnt = compute_size >> 2; int remain = compute_size % 4; float32x4_t vone = vdupq_n_f32(1.0f); #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 4; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; //! get max axis_size == 4 const float* din_ptr = din + real_index; const float* din_ptr1 = din_ptr + inner_num; const float* din_ptr2 = din_ptr1 + inner_num; const float* din_ptr3 = din_ptr2 + inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr1); float32x4_t vdata2 = vld1q_f32(din_ptr2); float32x4_t vdata3 = vld1q_f32(din_ptr3); float* dout_ptr0 = dout + real_index; float* dout_ptr1 = dout_ptr0 + inner_num; float32x4_t vmax1 = vmaxq_f32(vdata0, vdata1); float32x4_t vmax2 = vmaxq_f32(vdata2, vdata3); float* dout_ptr2 = dout_ptr1 + inner_num; float* dout_ptr3 = dout_ptr2 + inner_num; float32x4_t vmax = vmaxq_f32(vmax1, vmax2); //! sub, exp and sum float32x4_t vsum0 = exp_ps(vsubq_f32(vdata0, vmax)); float32x4_t vsum1 = exp_ps(vsubq_f32(vdata1, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax)); float32x4_t vsum3 = exp_ps(vsubq_f32(vdata3, vmax)); float32x4_t vsum_1 = vaddq_f32(vsum0, vsum1); float32x4_t vsum_2 = vaddq_f32(vsum2, vsum3); float32x4_t vsum = vaddq_f32(vsum_1, vsum_2); float32x4_t vinf = div_ps(vone, vsum); vsum0 = vmulq_f32(vsum0, vinf); vsum1 = vmulq_f32(vsum1, vinf); vsum2 = vmulq_f32(vsum2, vinf); vsum3 = vmulq_f32(vsum3, vinf); vst1q_f32(dout_ptr0, vsum0); vst1q_f32(dout_ptr1, vsum1); vst1q_f32(dout_ptr2, vsum2); vst1q_f32(dout_ptr3, vsum3); } int i = cmp_cnt * 8; for (; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; // printf("real_index: %d, din: %x\n", real_index, din); float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_in8(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size) { int cmp_cnt = compute_size >> 3; #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 8; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; const float* din_ptr = din + real_index; float32x4_t vmax = vld1q_f32(din_ptr); float32x4_t vmax2 = vld1q_f32(din_ptr + 4); //! get max for (int j = 1; j < axis_size; ++j) { din_ptr += inner_num; float32x4_t vdata = vld1q_f32(din_ptr); float32x4_t vdata2 = vld1q_f32(din_ptr + 4); vmax = vmaxq_f32(vmax, vdata); vmax2 = vmaxq_f32(vmax2, vdata2); } //! sub, exp and sum // dout[real_index] = expf(din[real_index] - max_data); din_ptr = din + real_index; float* dout_ptr = dout + real_index; float32x4_t vdata = vld1q_f32(din_ptr); float32x4_t vdata2 = vld1q_f32(din_ptr + 4); float32x4_t vsum = exp_ps(vsubq_f32(vdata, vmax)); float32x4_t vsum2 = exp_ps(vsubq_f32(vdata2, vmax2)); din_ptr += inner_num; vst1q_f32(dout_ptr, vsum); vst1q_f32(dout_ptr + 4, vsum2); dout_ptr += inner_num; //float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { // real_index += inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); float32x4_t vdata1 = vld1q_f32(din_ptr + 4); vdata0 = exp_ps(vsubq_f32(vdata0, vmax)); vdata1 = exp_ps(vsubq_f32(vdata1, vmax2)); din_ptr += inner_num; vsum = vaddq_f32(vsum, vdata0); vsum2 = vaddq_f32(vsum2, vdata1); vst1q_f32(dout_ptr, vdata0); vst1q_f32(dout_ptr + 4, vdata1); dout_ptr += inner_num; } // float sum_inv = 1.f / sum_data; float32x4_t vone = vdupq_n_f32(1.0f); float32x4_t vinf = div_ps(vone, vsum); float32x4_t vinf2 = div_ps(vone, vsum2); dout_ptr = dout + real_index; //printf("real_index: %d, dout: %x, dout_ptr: %x \n", real_index, dout, dout_ptr); // real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { float32x4_t vdata0 = vld1q_f32(dout_ptr); float32x4_t vdata1 = vld1q_f32(dout_ptr + 4); vdata0 = vmulq_f32(vdata0, vinf); vdata1 = vmulq_f32(vdata1, vinf2); vst1q_f32(dout_ptr, vdata0); vst1q_f32(dout_ptr + 4, vdata1); dout_ptr += inner_num; } } for (int i = cmp_cnt * 8; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; // printf("real_index: %d, din: %x\n", real_index, din); float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } void softmax_arm_lite_in4(const float* din, float* dout, \ const int axis_size, const int inner_num, \ const int outer_num, const int compute_size) { int cmp_cnt = compute_size >> 2; #pragma omp parallel for for (int c = 0; c < cmp_cnt; ++c) { int i = c * 4; int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; //float max_data = din[real_index]; const float* din_ptr = din + real_index; float32x4_t vmax = vld1q_f32(din_ptr); //! get max for (int j = 1; j < axis_size; ++j) { din_ptr += inner_num; float32x4_t vdata = vld1q_f32(din_ptr); vmax = vmaxq_f32(vmax, vdata); } //! sub, exp and sum // dout[real_index] = expf(din[real_index] - max_data); din_ptr = din + real_index; float* dout_ptr = dout + real_index; float32x4_t vdata = vld1q_f32(din_ptr); float32x4_t vsum = exp_ps(vsubq_f32(vdata, vmax)); din_ptr += inner_num; vst1q_f32(dout_ptr, vsum); dout_ptr += inner_num; //float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { // real_index += inner_num; float32x4_t vdata0 = vld1q_f32(din_ptr); vdata0 = exp_ps(vsubq_f32(vdata0, vmax)); din_ptr += inner_num; vsum = vaddq_f32(vsum, vdata0); vst1q_f32(dout_ptr, vdata0); dout_ptr += inner_num; } // float sum_inv = 1.f / sum_data; float32x4_t vone = vdupq_n_f32(1.0f); float32x4_t vinf = div_ps(vone, vsum); dout_ptr = dout + real_index; //! get softmax result for (int j = 0; j < axis_size; ++j) { float32x4_t vdata0 = vld1q_f32(dout_ptr); vdata0 = vmulq_f32(vdata0, vinf); vst1q_f32(dout_ptr, vdata0); dout_ptr += inner_num; } } for (int i = cmp_cnt * 4; i < compute_size; i++){ int idx_inner = i % inner_num; int idx_outer = (i / inner_num) * axis_size; int real_index = idx_outer * inner_num + idx_inner; float max_data = din[real_index]; //! get max for (int j = 1; j < axis_size; ++j) { real_index += inner_num; max_data = din[real_index] > max_data? din[real_index] : max_data; } real_index = idx_outer * inner_num + idx_inner; //! sub, exp and sum dout[real_index] = expf(din[real_index] - max_data); float sum_data = dout[real_index]; for (int j = 1; j < axis_size; ++j) { real_index += inner_num; dout[real_index] = expf(din[real_index] - max_data); sum_data += dout[real_index]; } float sum_inv = 1.f / sum_data; real_index = idx_outer * inner_num + idx_inner; //! get softmax result for (int j = 0; j < axis_size; ++j) { dout[real_index] *= sum_inv; real_index += inner_num; } } } //! for inner size == 1 void softmax_inner1(const float* din, float* dout, \ const int outer_size, const int axis_size) { #pragma omp parallel for for (int i = 0; i < outer_size; ++i) { const float* din_ptr = din + i * axis_size; float* dout_ptr = dout + i * axis_size; const float* din_max_ptr = din_ptr; int nn = axis_size >> 2; //! get max float32x4_t vmax = vld1q_f32(din_max_ptr); din_max_ptr += 4; int j = 1; for (; j < nn; ++j) { vmax = vmaxq_f32(vmax, vld1q_f32(din_max_ptr)); din_max_ptr += 4; } float32x2_t vhmax = vmax_f32(vget_high_f32(vmax), vget_low_f32(vmax)); float max_data = std::max(vget_lane_f32(vhmax, 0), vget_lane_f32(vhmax, 1)); for (j = 4 * j; j < axis_size; ++j) { max_data = std::max(max_data, din_max_ptr[0]); din_max_ptr++; } //printf("max data: %.2f\n", max_data); //! sub, exp and sum const float* din_sum_ptr = din_ptr; float* dout_sum_ptr = dout_ptr; vmax = vdupq_n_f32(max_data); float32x4_t vsub_exp = exp_ps(vsubq_f32(vld1q_f32(din_sum_ptr), vmax)); float32x4_t vsum = vsub_exp; vst1q_f32(dout_sum_ptr, vsub_exp); din_sum_ptr += 4; dout_sum_ptr += 4; j = 1; for (; j < nn; ++j) { vsub_exp = exp_ps(vsubq_f32(vld1q_f32(din_sum_ptr), vmax)); vst1q_f32(dout_sum_ptr, vsub_exp); vsum = vaddq_f32(vsum, vsub_exp); din_sum_ptr += 4; dout_sum_ptr += 4; } float32x2_t vhsum = vadd_f32(vget_high_f32(vsum), vget_low_f32(vsum)); float sum_data = vget_lane_f32(vhsum, 0) + vget_lane_f32(vhsum, 1); for (j = 4 * j; j < axis_size; ++j) { dout_sum_ptr[0] = expf(din_sum_ptr[0] - max_data); sum_data += dout_sum_ptr[0]; din_sum_ptr++; dout_sum_ptr++; } //printf("sum data: %.2f\n", sum_data); float sum_inv = 1.f / sum_data; float* dout_res_ptr = dout_ptr; float32x4_t vinv = vdupq_n_f32(sum_inv); //! get softmax result j = 0; for (; j < nn; ++j) { float32x4_t vout = vld1q_f32(dout_res_ptr); float32x4_t vres= vmulq_f32(vout, vinv); vst1q_f32(dout_res_ptr, vres); dout_res_ptr += 4; } for (j = nn * 4; j < axis_size; ++j) { dout_ptr[j] *= sum_inv; } } } //! for inner size == 1 aixs_size < 4 void softmax_inner1_s(const float* din, float* dout, \ const int outer_size, const int axis_size) { #pragma omp parallel for for (int i = 0; i < outer_size; ++i) { const float* din_ptr = din + i * axis_size; float* dout_ptr = dout + i * axis_size; //! get max float max_data = din_ptr[0]; for (int j =1; j < axis_size; ++j) { max_data = std::max(max_data, din_ptr[j]); } //printf("max data: %.2f\n", max_data); //! sub, exp and sum float sum_data = 0.f; for (int j = 0; j < axis_size; ++j) { dout_ptr[j] = expf(din_ptr[j] - max_data); sum_data += dout_ptr[j]; } //printf("sum data: %.2f\n", sum_data); float sum_inv = 1.f / sum_data; for (int j = 0; j < axis_size; ++j) { dout_ptr[j] *= sum_inv; } } } template <> SaberStatus SaberSoftmax<ARM, AK_FLOAT>::dispatch(\ const std::vector<Tensor<ARM> *>& inputs, std::vector<Tensor<ARM> *>& outputs, SoftmaxParam<ARM> &param) { #ifdef ENABLE_OP_TIMER this->_timer.clear(); this->_timer.start(*this->_ctx); #endif float* dout = static_cast<float*>(outputs[0]->mutable_data()); const float* din = static_cast<const float*>(inputs[0]->data()); if (this->_inner_num == 1) { if (_axis_size >= 4){ softmax_inner1(din, dout, _outer_num, _axis_size); }else{ softmax_inner1_s(din, dout, _outer_num, _axis_size); } } else { int compute_size = inputs[0]->valid_size() / _axis_size; // softmax_basic(din, dout, _axis_size, _inner_num, _outer_num, compute_size); if (_axis_size == 4 && _inner_num % 8 == 0){ softmax_arm_lite_channel_in8(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else if (_axis_size == 4 && _inner_num % 4 == 0){ softmax_arm_lite_channel_in4(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else{ if (this->_inner_num % 8 == 0){ softmax_arm_lite_in8(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else if (this->_inner_num % 4 == 0){ softmax_arm_lite_in4(din, dout, _axis_size, _inner_num, _outer_num, compute_size); }else{ softmax_basic(din, dout, _axis_size, _inner_num, _outer_num, compute_size); } } } #ifdef ENABLE_OP_TIMER this->_timer.end(*this->_ctx); float ts = this->_timer.get_average_ms(); LOG(INFO) << "Softmax : " << this->_op_name.c_str() << " : time: " << ts; GOPS ops; float op_macs = 2.f * inputs[0]->valid_size() * 3; //fixme ops.ops = op_macs; ops.ts = ts; OpTimer::add_timer("Softmax", ops); OpTimer::add_timer("total", ops); #endif return SaberSuccess; } DEFINE_OP_TEMPLATE(SaberSoftmax, SoftmaxParam, ARM, AK_HALF); DEFINE_OP_TEMPLATE(SaberSoftmax, SoftmaxParam, ARM, AK_INT8); } //namespace anakin } //namespace anakin
36.609495
102
0.582364
dda1d5424118961cb5c53d2751a15a6381c31ee2
1,259
cpp
C++
UCF HSPT Documents/2007/Solutions/zero.cpp
p473lr/i-urge-mafia-gear
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
[ "Apache-2.0" ]
null
null
null
UCF HSPT Documents/2007/Solutions/zero.cpp
p473lr/i-urge-mafia-gear
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
[ "Apache-2.0" ]
null
null
null
UCF HSPT Documents/2007/Solutions/zero.cpp
p473lr/i-urge-mafia-gear
ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e
[ "Apache-2.0" ]
null
null
null
// Guitar Zero solution // Written in C++ by Jobby Johns // UCF 2007 High School Programming Contest /* The solution is very simple. Get the number of score changes. Start the * score at 0. Then, get each score change one at a time and adjust the score * accordingly. Once all the score changes are done, output the result * ("Shreddin" if score is positive, "Guitar Zero" otherwise). */ #include <iostream> #include <fstream> using namespace std; int main() { // open the file ifstream infile("zero.in", ios::in); // variables int n; int songNum = 1; char c; // get the input value for each song and solve (stop if 0) while (infile >> n && n != 0) { // start the score and adjust it based on the input int score = 0; for (int i = 0; i < n; ++i) { infile >> c; if (c == '+') { score++; } else if (c == '-') { score--; } } // output the result cout << "Song " << songNum << ": "; if (score > 0) { cout << "Shreddin" << endl; } else { cout << "Guitar Zero" << endl; } // increment song number for next possible song songNum++; } //close the file and quit infile.close(); return 0; }
19.984127
79
0.560763
dda483d94ce9cfa55a437bb7b8b995b0db566d45
358
hpp
C++
src/engineModules/eFont.hpp
psjuan97/JamEngine
20d98e6f3e962a518cc519fecd90205a52aba249
[ "MIT" ]
3
2019-09-30T08:23:03.000Z
2020-07-18T09:09:56.000Z
src/engineModules/eFont.hpp
psjuan97/JamEngine
20d98e6f3e962a518cc519fecd90205a52aba249
[ "MIT" ]
1
2019-09-28T14:17:05.000Z
2019-09-28T14:17:05.000Z
src/engineModules/eFont.hpp
psjuan97/JamEngine
20d98e6f3e962a518cc519fecd90205a52aba249
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <SDL2/SDL_ttf.h> ///////// /// TODO /// liberar la fuente en el destructor class eFont{ public: eFont(const char* str, int size); ~eFont(); inline TTF_Font* getSDLFont() const { return sdl_font; }; private: TTF_Font* sdl_font = nullptr; };
16.272727
45
0.539106
dda5c67804d14f06cabfc9360bcb4c7d47d84892
286
hpp
C++
astronomy/solar_system_fingerprints.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
astronomy/solar_system_fingerprints.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
astronomy/solar_system_fingerprints.hpp
madman2003/Principia
c757f840f5278ca3480799cee297238697868283
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> namespace principia { namespace astronomy { constexpr std::uint64_t KSPStockSystemFingerprint = 0x54B6323B3376D6F3; constexpr std::uint64_t KSPStabilizedSystemFingerprint = 0xB57B58F9CF757C62; } // namespace astronomy } // namespace principia
22
76
0.793706
dda802b3b39ca7770bd99d0241c745b1a170b539
21,721
cpp
C++
ExternalSource/myOptimizer/ConicSolver/src/solver/optimizer/IPSolver.cpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
1
2020-05-04T22:36:54.000Z
2020-05-04T22:36:54.000Z
ExternalSource/myOptimizer/ConicSolver/src/solver/optimizer/IPSolver.cpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
null
null
null
ExternalSource/myOptimizer/ConicSolver/src/solver/optimizer/IPSolver.cpp
shbang91/PnC
880cbbcf96a48a93a0ab646634781e4f112a71f6
[ "MIT" ]
null
null
null
/* * * ECOS - Embedded Conic Solver * Copyright (C) [2012-2015] A. Domahidi [domahidi@embotech.com], * Automatic Control Lab, ETH Zurich & embotech GmbH, Zurich, Switzerland. * * Copyright [2017] Max Planck Society. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <ExternalSource/myOptimizer/ConicSolver/include/solver/optimizer/IPSolver.hpp> namespace solver { inline double dotProduct(int n, double* x, double* y) { double z = 0; int i; for( i=0; i<n; i++ ){ z += x[i]*y[i]; } return z; } void InteriorPointSolver::initialize(SolverStorage& stg, Cone& cone, SolverSetting& stgs) { // setup problem stg_ = &stg; stgs_ = &stgs; cone_ = &cone; this->internalInitialization(); } void InteriorPointSolver::internalInitialization() { // setup message printer this->getPrinter().initialize(this->getStgs()); // equilibration of problem data this->getEqRoutine().setEquilibration(this->getCone(), this->getStgs(), this->getStg()); this->getStg().At() = this->getStg().A().transpose(); this->getStg().Gt() = this->getStg().G().transpose(); this->getLinSolver().initialize(this->getCone(), this->getStgs(), this->getStg()); // initialize problem variables rho_.initialize(this->getCone()); opt_.initialize(this->getCone()); res_.initialize(this->getCone()); RHS1_.initialize(this->getCone()); RHS2_.initialize(this->getCone()); lbar_.initialize(this->getCone()); dopt1_.initialize(this->getCone()); dopt2_.initialize(this->getCone()); sigma_.initialize(this->getCone()); lambda_.initialize(this->getCone()); best_opt_.initialize(this->getCone()); ds_combined_.initialize(this->getCone()); dz_combined_.initialize(this->getCone()); ds_affine_by_W_.initialize(this->getCone()); W_times_dz_affine_.initialize(this->getCone()); } ExitCode InteriorPointSolver::initializeVariables() { // get scalings of problem data inires_x_ = std::max(1.0, this->getStg().c().norm()); inires_y_ = std::max(1.0, this->getStg().b().norm()); inires_z_ = std::max(1.0, this->getStg().h().norm()); // initialize KKT matrix and perform numeric factorization this->getLinSolver().initializeMatrix(); if ( this->getLinSolver().numericFactorization() != FactStatus::Optimal ){ this->getPrinter().display(Msg::MatrixFactorization, this->getInfo()); return ExitCode::Indeterminate; } // initialize primal variables int* invPerm = this->getLinSolver().invPerm().indices().data(); for (int i=0; i<this->getCone().numVars(); i++) { RHS1_[invPerm[i]] = 0; } for (int i=0; i<this->getCone().numLeq(); i++ ) { RHS1_[invPerm[this->getCone().numVars()+i]] = this->getStg().b()[i]; } for (int i=0; i<this->getCone().sizeLpc(); i++) { RHS1_[invPerm[this->getCone().lpConeStart()+i]] = this->getStg().h()[i]; } for (int l=0; l<this->getCone().numSoc(); l++ ){ for (int i=0; i<this->getCone().sizeSoc(l); i++) RHS1_[invPerm[this->getCone().extStartSoc(l)+i]] = this->getStg().cbh()[this->getCone().optStartSoc(l)+i]; } this->getInfo().get(SolverIntParam_NumRefsLinSolve) = this->getLinSolver().solve(RHS1_, dopt2_, true); opt_.x() = dopt2_.x(); opt_.s() = -dopt2_.z(); this->getCone().conicProjection(opt_.s()); // initialize dual variables for (int i=0; i<this->getCone().numVars(); i++){ RHS2_[invPerm[i]] = -this->getStg().c()[i]; } this->getInfo().get(SolverIntParam_NumRefsLinSolveAffine) = this->getLinSolver().solve(RHS2_, dopt1_, true); opt_.y() = dopt1_.y(); opt_.z() = dopt1_.z(); this->getCone().conicProjection(opt_.z()); // initialize variables for optimization for (int i=0; i<this->getCone().numVars(); i++) { RHS1_[invPerm[i]] = -this->getStg().c()[i]; } opt_.kappa() = opt_.tau() = 1.0; this->getInfo().get(SolverDoubleParam_StepLength) = this->getInfo().get(SolverDoubleParam_AffineStepLength) = 0.0; return ExitCode::Optimal; } void InteriorPointSolver::computeResiduals() { this->getLinSolver().matrixTransposeTimesVector(this->getStg().A(), opt_.y(), res_.x(), false, true); this->getLinSolver().matrixTransposeTimesVector(this->getStg().G(), opt_.z(), res_.x(), false, false); residual_x_ = res_.x().norm(); this->getLinSolver().matrixTransposeTimesVector(this->getStg().At(), opt_.x(), res_.y(), true, true); residual_y_ = res_.y().norm(); this->getLinSolver().matrixTransposeTimesVector(this->getStg().Gt(), opt_.x(), res_.z(), true, true); res_.z() += opt_.s(); residual_z_ = res_.z().norm(); cx_ = this->getStg().c().dot(opt_.x()); by_ = this->getStg().b().dot(opt_.y()); hz_ = this->getStg().h().dot(opt_.z()); res_ -= opt_.tau()*this->getStg().cbh(); residual_t_ = opt_.kappa() + cx_ + by_ + hz_; } double InteriorPointSolver::lineSearch(const Eigen::Ref<const Eigen::VectorXd>& dsvec, const Eigen::Ref<const Eigen::VectorXd>& dzvec, double tau, double dtau, double kappa, double dkappa) { int conestart, conesize; const double *lk, *dsk, *dzk; double *lkbar, *rhok, *sigmak; const double* ds = dsvec.data(); const double* dz = dzvec.data(); const double* lambda = lambda_.data(); double conicres_lk, conicres_ds, conicres_dz, inv_conicres, factor1, factor2; // Linear cone double rhomin = ds[0]/lambda[0]; double sigmamin = dz[0]/lambda[0]; for (int i=1; i<this->getCone().sizeLpc(); i++){ if (ds[i]/lambda[i]<rhomin) { rhomin = ds[i]/lambda[i]; } if (dz[i]/lambda[i]<sigmamin) { sigmamin = dz[i]/lambda[i]; } } double alpha = std::min(sigmamin,rhomin)<0.0 ? -1.0/std::min(sigmamin,rhomin) : 1.0/this->getStgs().get(SolverDoubleParam_DynamicRegularizationThresh); // Tau and kappa if (-tau/dtau>0 && -tau/dtau<alpha) { alpha = -tau/dtau; } if (-kappa/dkappa>0 && -kappa/dkappa<alpha) { alpha = -kappa/dkappa; } // Second order cone for (int i=0; i<this->getCone().numSoc(); i++) { // indices conesize = this->getCone().sizeSoc(i); conestart = this->getCone().startSoc(i); dsk = ds + conestart; dzk = dz + conestart; lk = lambda + conestart; lkbar = lbar_.data() + conestart; rhok = rho_.data() + conestart; sigmak = sigma_.data() + conestart; Eigen::Map<const Eigen::VectorXd> eig_lk(lk,conesize); Eigen::Map<const Eigen::VectorXd> eig_rhok(rhok, conesize); Eigen::Map<const Eigen::VectorXd> eig_sigmak(sigmak, conesize); // find residuals conicres_lk = this->getCone().conicResidual(eig_lk); if (conicres_lk <= 0.0) { continue; } for (int j=0; j<conesize; j++) { lkbar[j] = lk[j]/std::sqrt(conicres_lk); } conicres_ds = lkbar[0]*dsk[0]; for (int j=1; j<conesize; j++) { conicres_ds -= lkbar[j]*dsk[j]; } conicres_dz = lkbar[0]*dzk[0]; for (int j=1; j<conesize; j++) { conicres_dz -= lkbar[j]*dzk[j]; } // construct rhok and sigmak inv_conicres = 1.0/std::sqrt(conicres_lk); factor1 = (conicres_ds+dsk[0])/(lkbar[0]+1); factor2 = (conicres_dz+dzk[0])/(lkbar[0]+1); rhok[0] = inv_conicres * conicres_ds; sigmak[0] = inv_conicres * conicres_dz; for (int j=1; j<conesize; j++) { rhok[j] = inv_conicres*(dsk[j]-factor1*lkbar[j]); } for (int j=1; j<conesize; j++) { sigmak[j] = inv_conicres*(dzk[j]-factor2*lkbar[j]); } // update alpha alpha = std::min(alpha,1.0/std::max(std::max(eig_rhok.tail(conesize-1).norm()-rhok[0],eig_sigmak.tail(conesize-1).norm()-sigmak[0]),0.0)); } return std::max(std::min(alpha,this->getStgs().get(SolverDoubleParam_MaximumStepLength)),this->getStgs().get(SolverDoubleParam_MinimumStepLength)); } void InteriorPointSolver::updateStatistics() { this->getInfo().get(SolverDoubleParam_PrimalCost) = cx_ / opt_.tau(); this->getInfo().get(SolverDoubleParam_DualityGap) = opt_.s().dot(opt_.z()); this->getInfo().get(SolverDoubleParam_DualCost) = -(hz_ + by_) / opt_.tau(); this->getInfo().get(SolverDoubleParam_KappaOverTau) = opt_.kappa() / opt_.tau(); this->getInfo().get(SolverDoubleParam_MeritFunction) = (this->getInfo().get(SolverDoubleParam_DualityGap) + opt_.kappa()*opt_.tau()) / (this->getCone().sizeCone()+1); // relative duality gap if (this->getInfo().get(SolverDoubleParam_PrimalCost) < 0.0) { this->getInfo().get(SolverDoubleParam_RelativeDualityGap) = this->getInfo().get(SolverDoubleParam_DualityGap) / (-this->getInfo().get(SolverDoubleParam_PrimalCost)); } else if (this->getInfo().get(SolverDoubleParam_DualCost) > 0.0) { this->getInfo().get(SolverDoubleParam_RelativeDualityGap) = this->getInfo().get(SolverDoubleParam_DualityGap) / this->getInfo().get(SolverDoubleParam_DualCost); } else { this->getInfo().get(SolverDoubleParam_RelativeDualityGap) = SolverSetting::nan; } // residuals this->getInfo().get(SolverDoubleParam_PrimalResidual) = std::max(res_.y().norm()/std::max(inires_y_+opt_.x().norm(),1.0), res_.z().norm()/std::max(inires_z_+opt_.x().norm()+opt_.s().norm(),1.0)) / opt_.tau(); this->getInfo().get(SolverDoubleParam_DualResidual) = res_.x().norm()/std::max(inires_x_+opt_.y().norm()+opt_.z().norm(),1.0) / opt_.tau(); // infeasibility measures this->getInfo().get(SolverDoubleParam_PrimalInfeasibility) = (hz_ + by_)/std::max(opt_.y().norm()+opt_.z().norm(),1.0) < -this->getStgs().get(SolverDoubleParam_DualityGapRelTol) ? residual_x_ / std::max(opt_.y().norm()+opt_.z().norm(),1.0) : SolverSetting::nan; this->getInfo().get(SolverDoubleParam_DualInfeasibility) = cx_/std::max(opt_.x().norm(),1.0) < -this->getStgs().get(SolverDoubleParam_DualityGapRelTol) ? std::max(residual_y_/std::max(opt_.x().norm(),1.0), residual_z_/std::max(opt_.x().norm()+opt_.s().norm(),1.0)) : SolverSetting::nan; } ExitCode InteriorPointSolver::convergenceCheck(const PrecisionConvergence& mode) { this->getInfo().mode() = mode; double feastol, abstol, reltol; ExitCode exitcode = ExitCode::NotConverged; // set accuracy if ( mode == PrecisionConvergence::Full) { feastol = this->getStgs().get(SolverDoubleParam_FeasibilityTol); abstol = this->getStgs().get(SolverDoubleParam_DualityGapAbsTol); reltol = this->getStgs().get(SolverDoubleParam_DualityGapRelTol); } else { feastol = this->getStgs().get(SolverDoubleParam_FeasibilityTolInacc); abstol = this->getStgs().get(SolverDoubleParam_DualityGapAbsTolInacc); reltol = this->getStgs().get(SolverDoubleParam_DualityGapRelTolInacc); } // Optimality if ( (cx_<0.0 || by_+hz_<=abstol) && (this->getInfo().get(SolverDoubleParam_PrimalResidual)<feastol && this->getInfo().get(SolverDoubleParam_DualResidual)<feastol) && (this->getInfo().get(SolverDoubleParam_DualityGap)<abstol || this->getInfo().get(SolverDoubleParam_RelativeDualityGap)<reltol)) { this->getPrinter().display(Msg::OptimalityReached, this->getInfo()); (mode==PrecisionConvergence::Full ? exitcode=ExitCode::Optimal : exitcode=ExitCode::OptimalInacc); } // Dual infeasible else if( (this->getInfo().get(SolverDoubleParam_DualInfeasibility)!=SolverSetting::nan) && (this->getInfo().get(SolverDoubleParam_DualInfeasibility)<feastol) && (opt_.tau()<opt_.kappa()) ){ this->getPrinter().display(Msg::DualInfeasibility, this->getInfo()); (mode==PrecisionConvergence::Full ? exitcode=ExitCode::DualInf : exitcode=ExitCode::DualInfInacc); } // Primal infeasible else if( ((this->getInfo().get(SolverDoubleParam_PrimalInfeasibility)!=SolverSetting::nan && this->getInfo().get(SolverDoubleParam_PrimalInfeasibility)<feastol) && (opt_.tau()<opt_.kappa())) || (opt_.tau()<feastol && opt_.kappa()<feastol && this->getInfo().get(SolverDoubleParam_PrimalInfeasibility)<feastol)) { this->getPrinter().display(Msg::PrimalInfeasibility, this->getInfo()); (mode==PrecisionConvergence::Full ? exitcode=ExitCode::PrimalInf : exitcode=ExitCode::PrimalInfInacc); } return exitcode; } void InteriorPointSolver::saveIterateAsBest() { best_opt_ = opt_; this->getBestInfo() = this->getInfo(); this->getBestInfo().get(SolverIntParam_NumIter) = this->getInfo().get(SolverIntParam_NumIter); } void InteriorPointSolver::restoreBestIterate() { opt_ = best_opt_; this->getInfo() = this->getBestInfo(); } void InteriorPointSolver::rhsAffineStep() { const int* invPerm = this->getLinSolver().invPerm().indices().data(); for (int i=0; i<this->getCone().numVars(); i++ ) { RHS2_[invPerm[i]] = res_.x()[i]; } for (int i=0; i<this->getCone().numLeq(); i++ ) { RHS2_[invPerm[this->getCone().numVars()+i]] = -res_.y()[i]; } for (int i=0; i<this->getCone().sizeLpc(); i++ ) { RHS2_[invPerm[this->getCone().lpConeStart()+i]] = opt_.s()[i] - res_.z()[i]; } for (int l=0; l<this->getCone().numSoc(); l++) { for (int i=0; i < this->getCone().sizeSoc(l); i++ ) RHS2_[invPerm[this->getCone().extStartSoc(l)+i]] = opt_.s()[this->getCone().startSoc(l)+i] - res_.z()[this->getCone().startSoc(l)+i]; } } void InteriorPointSolver::rhsCenteringPredictorStep() { double* dz_combined_ptr = dz_combined_.data(); const int* invPerm = this->getLinSolver().invPerm().indices().data(); double factor = 1.0 - this->getInfo().get(SolverDoubleParam_CorrectionStepLength); for (int i=0; i<this->getCone().numVars(); i++) { RHS2_[invPerm[i]] *= factor; } for (int i=0; i<this->getCone().numLeq(); i++ ) { RHS2_[invPerm[this->getCone().numVars()+i]] *= factor; } for (int i=0; i<this->getCone().sizeLpc(); i++) { RHS2_[invPerm[this->getCone().lpConeStart()+i]] = dz_combined_ptr[i]; } for (int l=0; l < this->getCone().numSoc(); l++ ){ for (int i=0; i<this->getCone().sizeSoc(l); i++) RHS2_[invPerm[this->getCone().extStartSoc(l)+i]] = dz_combined_ptr[this->getCone().startSoc(l)+i]; } } ExitCode InteriorPointSolver::optimize() { prev_pres_ = SolverSetting::nan; exitcode_ = ExitCode::Indeterminate; if (initializeVariables() == ExitCode::Indeterminate) return ExitCode::Indeterminate; for (this->getInfo().get(SolverIntParam_NumIter)=0; this->getInfo().get(SolverIntParam_NumIter)<=this->getStgs().get(SolverIntParam_SolverMaxIters); this->getInfo().get(SolverIntParam_NumIter)++) { computeResiduals(); updateStatistics(); this->getPrinter().display(Msg::OptimizationProgress, this->getInfo()); // SAFEGUARD: Bad update or DualityGap became negative if (this->getInfo().get(SolverIntParam_NumIter)>0 && (this->getInfo().get(SolverDoubleParam_PrimalResidual)>this->getStgs().get(SolverDoubleParam_SafeGuard)*prev_pres_ || this->getInfo().get(SolverDoubleParam_DualityGap)<0)) { this->getPrinter().display(Msg::SearchDirection, best_info_); restoreBestIterate(); exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { this->getPrinter().display(Msg::NumericalProblem, info_); exitcode_ = ExitCode::PrSearchDirection; } break; } prev_pres_ = this->getInfo().get(SolverDoubleParam_PrimalResidual); // Check termination to full precision, mininum stepLength and maxNumIters reached exitcode_ = convergenceCheck(PrecisionConvergence::Full); if (exitcode_ == ExitCode::NotConverged) { // Mininum stepLength if (this->getInfo().get(SolverIntParam_NumIter)>0 && this->getInfo().get(SolverDoubleParam_StepLength)==this->getStgs().get(SolverDoubleParam_MinimumStepLength)*this->getStgs().get(SolverDoubleParam_StepLengthScaling)) { this->getPrinter().display(Msg::LineSearchStagnation, this->getBestInfo()); restoreBestIterate(); exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { exitcode_ = ExitCode::PrSearchDirection; this->getPrinter().display(Msg::NumericalProblem, this->getInfo()); } break; } // Reached maxNumIters else if (this->getInfo().get(SolverIntParam_NumIter)==this->getStgs().get(SolverIntParam_SolverMaxIters)) { if (!this->getInfo().isBetterThan(this->getBestInfo())) { restoreBestIterate(); } exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { exitcode_ = ExitCode::ReachMaxIters; this->getPrinter().display(Msg::MaxItersReached, this->getInfo()); } break; } } else { break; } // SAFEGUARD: Compare statistics if (this->getInfo().get(SolverIntParam_NumIter)==0) { saveIterateAsBest(); } else if (this->getInfo().isBetterThan(this->getBestInfo())) { saveIterateAsBest(); } // update NTscalings, numeric factorization and solve linear system if (this->getCone().updateNTScalings(this->opt_.s(), this->opt_.z(), this->lambda_)==ConeStatus::Outside) { this->getPrinter().display(Msg::VariablesLeavingCone, this->getBestInfo()); restoreBestIterate(); exitcode_ = convergenceCheck(PrecisionConvergence::Reduced); if (exitcode_ == ExitCode::NotConverged) { this->getPrinter().display(Msg::NumericalProblem, this->getInfo()); return ExitCode::PrSlacksLeaveCone; } else { break; } } this->getLinSolver().updateMatrix(); if (this->getLinSolver().numericFactorization()!=FactStatus::Optimal) { this->getPrinter().display(Msg::MatrixFactorization, this->getInfo()); return ExitCode::Indeterminate; } this->getInfo().get(SolverIntParam_NumRefsLinSolve) = this->getLinSolver().solve(RHS1_, dopt2_); // Affine Step rhsAffineStep(); this->getInfo().get(SolverIntParam_NumRefsLinSolveAffine) = this->getLinSolver().solve(RHS2_, dopt1_); dt_denom_ = opt_.kappa()/opt_.tau() - dotProduct(this->getCone().numVars(), this->getStg().c().data(), dopt2_.x().data()) - dotProduct(this->getCone().numLeq(), this->getStg().b().data(), dopt2_.y().data()) - dotProduct(this->getCone().sizeCone(), this->getStg().h().data(), dopt2_.z().data()); dt_affine_ = (residual_t_ - opt_.kappa() + dotProduct(this->getCone().numVars(), this->getStg().c().data(), dopt1_.x().data()) + dotProduct(this->getCone().numLeq(), this->getStg().b().data(), dopt1_.y().data()) + dotProduct(this->getCone().sizeCone(), this->getStg().h().data(), dopt1_.z().data())) / dt_denom_; dk_affine_ = -this->opt_.kappa() - this->opt_.kappa()/this->opt_.tau()*dt_affine_; for (int i=0; i<this->getCone().sizeCone(); i++) { dopt1_.z()[i] += dt_affine_*dopt2_.z()[i]; } W_times_dz_affine_ = this->getCone().W()*dopt1_.z(); for (int i=0; i<this->getCone().sizeCone(); i++) { ds_affine_by_W_[i] = -W_times_dz_affine_[i] - lambda_[i]; } this->getInfo().get(SolverDoubleParam_AffineStepLength) = lineSearch(ds_affine_by_W_, W_times_dz_affine_, this->opt_.tau(), dt_affine_, this->opt_.kappa(), dk_affine_); this->getInfo().get(SolverDoubleParam_CorrectionStepLength) = std::max(std::min(std::pow(1.0-this->getInfo().get(SolverDoubleParam_AffineStepLength),3.0),this->getStgs().get(SolverDoubleParam_MaximumCenteringStep)),this->getStgs().get(SolverDoubleParam_MinimumCenteringStep)); // Centering and Corrector Step ds_combined_ = lambda_*lambda_ + ds_affine_by_W_*W_times_dz_affine_- (this->getInfo().get(SolverDoubleParam_CorrectionStepLength)*this->getInfo().get(SolverDoubleParam_MeritFunction)); ds_affine_by_W_ = lambda_/ds_combined_; dz_combined_ = (this->getInfo().get(SolverDoubleParam_CorrectionStepLength)-1.0)*res_.z() + this->getCone().W()*ds_affine_by_W_; dk_combined_ = this->opt_.kappa()*this->opt_.tau() + dk_affine_*dt_affine_ - this->getInfo().get(SolverDoubleParam_CorrectionStepLength)*this->getInfo().get(SolverDoubleParam_MeritFunction); rhsCenteringPredictorStep(); this->getInfo().get(SolverIntParam_NumRefsLinSolveCorrector) = this->getLinSolver().solve(RHS2_, dopt1_); dopt1_.tau() = ((1-this->getInfo().get(SolverDoubleParam_CorrectionStepLength))*this->residual_t_ - dk_combined_/this->opt_.tau() + dotProduct(this->getCone().numVars(), this->getStg().c().data(), dopt1_.x().data()) + dotProduct(this->getCone().numLeq(), this->getStg().b().data(), dopt1_.y().data()) + dotProduct(this->getCone().sizeCone(), this->getStg().h().data(), dopt1_.z().data())) / dt_denom_; dopt1_.xyz() += dopt1_.tau()*dopt2_.xyz(); W_times_dz_affine_ = this->getCone().W()*dopt1_.z(); for (int i=0; i<this->getCone().sizeCone(); i++) { ds_affine_by_W_[i] = -(ds_affine_by_W_[i] + W_times_dz_affine_[i]); } dopt1_.kappa() = -(dk_combined_ + this->opt_.kappa()*dopt1_.tau())/this->opt_.tau(); this->getInfo().get(SolverDoubleParam_StepLength) = lineSearch(ds_affine_by_W_, W_times_dz_affine_, this->opt_.tau(), dopt1_.tau(), this->opt_.kappa(), dopt1_.kappa()) * this->getStgs().get(SolverDoubleParam_StepLengthScaling); dopt1_.s() = this->getCone().W()*ds_affine_by_W_; // Update variables opt_ += this->getInfo().get(SolverDoubleParam_StepLength) * dopt1_; } this->getEqRoutine().scaleVariables(opt_); return exitcode_; } }
51.716667
404
0.676718
ddad148892cd9abc74175c5f961396e5081ce719
14,159
cpp
C++
sources/tests/clone_generation_tests.cpp
greati/logicantsy
11d1f33f57df6fc77c3c18b506fc98f9b9a88794
[ "MIT" ]
2
2022-01-22T13:18:35.000Z
2022-02-12T22:56:34.000Z
sources/tests/clone_generation_tests.cpp
greati/logicantsy
11d1f33f57df6fc77c3c18b506fc98f9b9a88794
[ "MIT" ]
27
2020-06-06T18:32:02.000Z
2021-05-02T22:16:49.000Z
sources/tests/clone_generation_tests.cpp
greati/logicantsy
11d1f33f57df6fc77c3c18b506fc98f9b9a88794
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "core/common.h" #include "core/utils.h" #include "core/parser/fmla/fmla_parser.h" #include "apps/clones/clone_generation.h" namespace { TEST(CloneGen, GenerateCloneGodel) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("q"); auto neg_p = parser.parse("neg p"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto p_to_q = parser.parse("p -> q"); auto tt_neg = ltsy::TruthTable<std::set<int>>(3, { {{0},{2}}, {{1},{0}}, {{2},{0}}, }, neg_p); auto tt_and = ltsy::TruthTable<std::set<int>>(3, { {{0,0},{0}}, {{0,1},{0}}, {{0,2},{0}}, {{1,0},{0}}, {{1,1},{1}}, {{1,2},{1}}, {{2,0},{0}}, {{2,1},{1}}, {{2,2},{2}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(3, { {{0,0},{0}}, {{0,1},{1}}, {{0,2},{2}}, {{1,0},{1}}, {{1,1},{1}}, {{1,2},{2}}, {{2,0},{2}}, {{2,1},{2}}, {{2,2},{2}}, }, p_or_q); auto tt_to = ltsy::TruthTable<std::set<int>>(3, { {{0,0},{2}}, {{0,1},{2}}, {{0,2},{2}}, {{1,0},{0}}, {{1,1},{2}}, {{1,2},{2}}, {{2,0},{0}}, {{2,1},{1}}, {{2,2},{2}}, }, p_to_q); //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_frown, tt_smile, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_and, tt_or}}; ltsy::CloneGenerator generator {3, {tt_to,tt_and,tt_or,tt_neg}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateCloneDeterministicTeamFour) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("p"); auto smile_p = parser.parse("s(p)"); auto frown_p = parser.parse("f(p)"); auto csmile_p = parser.parse("cs(p)"); auto cfrown_p = parser.parse("cf(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto tt_and = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{1}}, {{0,2},{2}}, {{0,3},{3}}, {{1,0},{1}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{3}}, {{2,0},{2}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{3}}, {{3,0},{3}}, {{3,1},{3}}, {{3,2},{3}}, {{3,3},{3}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{0}}, {{0,2},{0}}, {{0,3},{0}}, {{1,0},{0}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{1}}, {{2,0},{0}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{2}}, {{3,0},{0}}, {{3,1},{1}}, {{3,2},{2}}, {{3,3},{3}}, }, p_or_q); auto tt_smile = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{1}}, {{2},{0}}, {{3},{0}}, }, smile_p); auto tt_frown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{3}}, {{2},{2}}, {{3},{0}}, }, frown_p); auto tt_csmile = ltsy::TruthTable<std::set<int>>(4, { {{0},{0}}, {{1},{3}}, {{2},{1}}, {{3},{0}}, }, csmile_p); auto tt_cfrown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{2}}, {{2},{0}}, {{3},{3}}, }, cfrown_p); //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_frown, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_frown, tt_smile, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_csmile, tt_cfrown, tt_and, tt_or}}; //ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_and, tt_or}}; ltsy::CloneGenerator generator {4, {tt_smile, tt_csmile, tt_cfrown, tt_and, tt_or}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateCloneDeterministicFDE) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("p"); auto smile_p = parser.parse("s(p)"); auto frown_p = parser.parse("f(p)"); auto csmile_p = parser.parse("cs(p)"); auto cfrown_p = parser.parse("cf(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto tt_and = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{1}}, {{0,2},{2}}, {{0,3},{3}}, {{1,0},{1}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{3}}, {{2,0},{2}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{3}}, {{3,0},{3}}, {{3,1},{3}}, {{3,2},{3}}, {{3,3},{3}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(4, { {{0,0},{0}}, {{0,1},{0}}, {{0,2},{0}}, {{0,3},{0}}, {{1,0},{0}}, {{1,1},{1}}, {{1,2},{3}}, {{1,3},{1}}, {{2,0},{0}}, {{2,1},{3}}, {{2,2},{2}}, {{2,3},{2}}, {{3,0},{0}}, {{3,1},{1}}, {{3,2},{2}}, {{3,3},{3}}, }, p_or_q); auto tt_dmneg = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{1}}, {{2},{2}}, {{3},{0}}, }, smile_p); auto tt_smile = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{1}}, {{2},{0}}, {{3},{0}}, }, smile_p); auto tt_frown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{3}}, {{2},{2}}, {{3},{0}}, }, frown_p); auto tt_csmile = ltsy::TruthTable<std::set<int>>(4, { {{0},{0}}, {{1},{3}}, {{2},{1}}, {{3},{0}}, }, csmile_p); auto tt_cfrown = ltsy::TruthTable<std::set<int>>(4, { {{0},{3}}, {{1},{2}}, {{2},{0}}, {{3},{3}}, }, cfrown_p); ltsy::CloneGenerator generator {4, {tt_or, tt_dmneg, tt_and}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateClone) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("q"); auto neg_p = parser.parse("neg p"); auto conf_p = parser.parse("conf(p)"); auto conv_p = parser.parse("conv(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto tt_neg = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3}}, {{3},{2,4}}, {{4},{2,4}}, }, neg_p); auto tt_conf = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3}}, {{3},{2,4}}, {{4},{2,}}, }, conf_p); auto tt_conv = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3,2}}, {{3},{2,4}}, {{4},{2,4}}, }, conv_p); ltsy::CloneGenerator generator {5, {tt_neg, tt_conv, tt_conf}}; const auto unary_clone = generator.generate(1, {p, q}); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } TEST(CloneGen, GenerateUnaryCloneMci) { ltsy::BisonFmlaParser parser; auto p = parser.parse("p"); auto q = parser.parse("q"); auto neg_p = parser.parse("neg p"); auto conf_p = parser.parse("o(p)"); auto p_and_q = parser.parse("p and q"); auto p_or_q = parser.parse("p or q"); auto p_to_q = parser.parse("p -> q"); auto tt_neg = ltsy::TruthTable<std::set<int>>(5, { {{0},{1}}, {{1},{0}}, {{2},{3}}, {{3},{2,4}}, {{4},{2,4}}, }, neg_p); auto tt_conf = ltsy::TruthTable<std::set<int>>(5, { {{0},{0}}, {{1},{0}}, {{2},{0}}, {{3},{0}}, {{4},{1}}, }, conf_p); auto tt_and = ltsy::TruthTable<std::set<int>>(5, { {{0,0},{2,4}}, {{1,0},{3}}, {{2,0},{2,4}}, {{3,0},{3}}, {{4,0},{2,4}}, {{0,1},{3}}, {{1,1},{3}}, {{2,1},{3}}, {{3,1},{3}}, {{4,1},{3}}, {{0,2},{2,4}}, {{1,2},{3}}, {{2,2},{2,4}}, {{3,2},{3}}, {{4,2},{2,4}}, {{0,3},{3}}, {{1,3},{3}}, {{2,3},{3}}, {{3,3},{3}}, {{4,3},{3}}, {{0,4},{2,4}}, {{1,4},{3}}, {{2,4},{2,4}}, {{3,4},{3}}, {{4,4},{2,4}}, }, p_and_q); auto tt_or = ltsy::TruthTable<std::set<int>>(5, { {{0,0},{2,4}}, {{1,0},{2,4}}, {{2,0},{2,4}}, {{3,0},{2,4}}, {{4,0},{2,4}}, {{0,1},{2,4}}, {{1,1},{3}}, {{2,1},{2,4}}, {{3,1},{3}}, {{4,1},{2,4}}, {{0,2},{2,4}}, {{1,2},{2,4}}, {{2,2},{2,4}}, {{3,2},{2,4}}, {{4,2},{2,4}}, {{0,3},{2,4}}, {{1,3},{3}}, {{2,3},{2,4}}, {{3,3},{3}}, {{4,3},{2,4}}, {{0,4},{2,4}}, {{1,4},{2,4}}, {{2,4},{2,4}}, {{3,4},{2,4}}, {{4,4},{2,4}}, }, p_or_q); auto tt_to = ltsy::TruthTable<std::set<int>>(5, { {{0,0},{2,4}}, {{1,0},{2,4}}, {{2,0},{2,4}}, {{3,0},{2,4}}, {{4,0},{2,4}}, {{0,1},{3}}, {{1,1},{2,4}}, {{2,1},{3}}, {{3,1},{2,4}}, {{4,1},{3}}, {{0,2},{2,4}}, {{1,2},{2,4}}, {{2,2},{2,4}}, {{3,2},{2,4}}, {{4,2},{2,4}}, {{0,3},{3}}, {{1,3},{2,4}}, {{2,3},{3}}, {{3,3},{2,4}}, {{4,3},{3}}, {{0,4},{2,4}}, {{1,4},{2,4}}, {{2,4},{2,4}}, {{3,4},{2,4}}, {{4,4},{2,4}}, }, p_to_q); ltsy::CloneGenerator generator {5, {tt_neg, tt_and, tt_or, tt_to, tt_conf}}; std::set<int> D = {0,2,4}; std::set<int> U = {1,3}; const auto unary_clone = generator.generate(1, {p, q}, std::nullopt, std::make_pair<>([&](ltsy::NDTruthTable tt) -> bool { auto A = tt.at({0}); auto B = tt.at({2}); return (ltsy::utils::is_subset(A, D) and ltsy::utils::is_subset(B, U)) or (ltsy::utils::is_subset(B, D) and ltsy::utils::is_subset(A, U)); }, 2) ); for (const auto& f : unary_clone) { std::cout << *f.fmla() << std::endl; std::cout << f.print().str() << std::endl; } } }
32.106576
104
0.322127
ddb127e79811d14f6a32686dfbc2d5d990d73fbc
15,108
cpp
C++
frontends/common/resolveReferences/resolveReferences.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
frontends/common/resolveReferences/resolveReferences.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
frontends/common/resolveReferences/resolveReferences.cpp
pierce-m/p4c
afe96cf5a658f7bf5e1b95a044c241d9afb13dc6
[ "Apache-2.0" ]
null
null
null
/* Copyright 2013-present Barefoot Networks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "resolveReferences.h" #include <sstream> namespace P4 { std::vector<const IR::IDeclaration*>* ResolutionContext::resolve(IR::ID name, P4::ResolutionType type, bool previousOnly) const { static std::vector<const IR::IDeclaration*> empty; std::vector<const IR::INamespace*> toTry; toTry = stack; toTry.insert(toTry.end(), globals.begin(), globals.end()); for (auto it = toTry.rbegin(); it != toTry.rend(); ++it) { const IR::INamespace* current = *it; LOG2("Trying to resolve in " << current->toString()); if (current->is<IR::IGeneralNamespace>()) { auto gen = current->to<IR::IGeneralNamespace>(); Util::Enumerator<const IR::IDeclaration*>* decls = gen->getDeclsByName(name); switch (type) { case P4::ResolutionType::Any: break; case P4::ResolutionType::Type: { std::function<bool(const IR::IDeclaration*)> kindFilter = [](const IR::IDeclaration* d) { return d->is<IR::Type>(); }; decls = decls->where(kindFilter); break; } case P4::ResolutionType::TypeVariable: { std::function<bool(const IR::IDeclaration*)> kindFilter = [](const IR::IDeclaration* d) { return d->is<IR::Type_Var>(); }; decls = decls->where(kindFilter); break; } default: BUG("Unexpected enumeration value %1%", static_cast<int>(type)); } if (previousOnly) { std::function<bool(const IR::IDeclaration*)> locationFilter = [name](const IR::IDeclaration* d) { Util::SourceInfo nsi = name.srcInfo; Util::SourceInfo dsi = d->getNode()->srcInfo; bool before = dsi <= nsi; LOG2("\tPosition test:" << dsi << "<=" << nsi << "=" << before); return before; }; decls = decls->where(locationFilter); } auto vector = decls->toVector(); if (!vector->empty()) { LOG2("Resolved in " << current->getNode()); return vector; } else { continue; } } else { auto simple = current->to<IR::ISimpleNamespace>(); auto decl = simple->getDeclByName(name); if (decl == nullptr) continue; switch (type) { case P4::ResolutionType::Any: break; case P4::ResolutionType::Type: { if (!decl->is<IR::Type>()) continue; break; } case P4::ResolutionType::TypeVariable: { if (!decl->is<IR::Type_Var>()) continue; break; } default: BUG("Unexpected enumeration value %1%", static_cast<int>(type)); } if (previousOnly) { Util::SourceInfo nsi = name.srcInfo; Util::SourceInfo dsi = decl->getNode()->srcInfo; bool before = dsi <= nsi; LOG2("\tPosition test:" << dsi << "<=" << nsi << "=" << before); if (!before) continue; } LOG2("Resolved in " << current->getNode()); auto result = new std::vector<const IR::IDeclaration*>(); result->push_back(decl); return result; } } return &empty; } void ResolutionContext::done() { pop(rootNamespace); if (!stack.empty()) BUG("ResolutionContext::stack not empty"); } const IR::IDeclaration* ResolutionContext::resolveUnique(IR::ID name, P4::ResolutionType type, bool previousOnly) const { auto decls = resolve(name, type, previousOnly); if (decls->empty()) { ::error("Could not find declaration for %1%", name); return nullptr; } if (decls->size() > 1) { ::error("Multiple matching declarations for %1%", name); for (auto a : *decls) ::error("Candidate: %1%", a); return nullptr; } return decls->at(0); } void ResolutionContext::dbprint(std::ostream& out) const { out << "Context stack[" << stack.size() << "]" << std::endl; for (auto it = stack.begin(); it != stack.end(); it++) { const IR::INamespace* ns = *it; const IR::Node* node = ns->getNode(); node->dbprint(out); out << std::endl; } out << "Globals[" << stack.size() << "]" << std::endl; for (auto it = globals.begin(); it != globals.end(); it++) { const IR::INamespace* ns = *it; const IR::Node* node = ns->getNode(); node->dbprint(out); out << std::endl; } out << "----------" << std::endl; } ///////////////////////////////////////////////////// ResolveReferences::ResolveReferences(ReferenceMap* refMap, bool checkShadow) : refMap(refMap), context(nullptr), rootNamespace(nullptr), anyOrder(false), checkShadow(checkShadow) { CHECK_NULL(refMap); setName("ResolveReferences"); visitDagOnce = false; } void ResolveReferences::addToContext(const IR::INamespace* ns) { LOG1("Adding to context " << ns); if (context == nullptr) BUG("No resolution context; did not start at P4Program?"); context->push(ns); } void ResolveReferences::addToGlobals(const IR::INamespace* ns) { if (context == nullptr) BUG("No resolution context; did not start at P4Program?"); context->addGlobal(ns); } void ResolveReferences::removeFromContext(const IR::INamespace* ns) { LOG1("Removing from context " << ns); if (context == nullptr) BUG("No resolution context; did not start at P4Program?"); context->pop(ns); } ResolutionContext* ResolveReferences::resolvePathPrefix(const IR::PathPrefix* prefix) const { ResolutionContext* result = context; if (prefix == nullptr) return result; if (prefix->absolute) result = new ResolutionContext(rootNamespace); for (IR::ID id : prefix->components) { const IR::IDeclaration* decl = result->resolveUnique(id, ResolutionType::Any, !anyOrder); if (decl == nullptr) return nullptr; const IR::Node* node = decl->getNode(); if (!node->is<IR::INamespace>()) { ::error("%1%: %2% is not a namespace", prefix, decl); return nullptr; } result = new ResolutionContext(node->to<IR::INamespace>()); } return result; } void ResolveReferences::resolvePath(const IR::Path* path, bool isType) const { LOG1("Resolving " << path << " " << (isType ? "as type" : "as identifier")); ResolutionContext* ctx = resolvePathPrefix(path->prefix); ResolutionType k = isType ? ResolutionType::Type : ResolutionType::Any; if (resolveForward.empty()) BUG("Empty resolveForward"); bool allowForward = resolveForward.back(); const IR::IDeclaration* decl = ctx->resolveUnique(path->name, k, !allowForward); if (decl == nullptr) { refMap->usedName(path->name.name); return; } refMap->setDeclaration(path, decl); } void ResolveReferences::checkShadowing(const IR::INamespace*ns) const { if (!checkShadow) return; auto e = ns->getDeclarations(); while (e->moveNext()) { const IR::IDeclaration* decl = e->getCurrent(); const IR::Node* node = decl->getNode(); auto prev = context->resolve(decl->getName(), ResolutionType::Any, !anyOrder); if (prev->empty()) continue; for (auto p : *prev) { const IR::Node* pnode = p->getNode(); if (pnode == node) continue; if (pnode->is<IR::Type_Method>() && node->is<IR::Type_Method>()) { auto md = node->to<IR::Type_Method>(); auto mp = pnode->to<IR::Type_Method>(); if (md->parameters->size() != mp->parameters->size()) continue; } ::warning("%1% shadows %2%", decl->getName(), p->getName()); } } } Visitor::profile_t ResolveReferences::init_apply(const IR::Node* node) { anyOrder = refMap->isV1(); if (!refMap->checkMap(node)) refMap->clear(); return Inspector::init_apply(node); } void ResolveReferences::end_apply(const IR::Node* node) { refMap->updateMap(node); } /////////////////// visitor methods //////////////////////// // visitor should be invoked here bool ResolveReferences::preorder(const IR::P4Program* program) { if (refMap->checkMap(program)) return false; if (!resolveForward.empty()) BUG("Expected empty resolvePath"); resolveForward.push_back(anyOrder); if (rootNamespace != nullptr) BUG("Root namespace already set"); rootNamespace = program; context = new ResolutionContext(rootNamespace); return true; } void ResolveReferences::postorder(const IR::P4Program*) { rootNamespace = nullptr; context->done(); resolveForward.pop_back(); if (!resolveForward.empty()) BUG("Expected empty resolvePath"); context = nullptr; LOG1("Reference map " << refMap); } bool ResolveReferences::preorder(const IR::PathExpression* path) { resolvePath(path->path, false); return true; } bool ResolveReferences::preorder(const IR::Type_Name* type) { resolvePath(type->path, true); return true; } bool ResolveReferences::preorder(const IR::P4Control *c) { refMap->usedName(c->name.name); addToContext(c); addToContext(c->type->typeParameters); addToContext(c->type->applyParams); addToContext(c->constructorParams); return true; } void ResolveReferences::postorder(const IR::P4Control *c) { removeFromContext(c->constructorParams); removeFromContext(c->type->applyParams); removeFromContext(c->type->typeParameters); removeFromContext(c); checkShadowing(c); } bool ResolveReferences::preorder(const IR::P4Parser *c) { refMap->usedName(c->name.name); addToContext(c); addToContext(c->type->typeParameters); addToContext(c->type->applyParams); addToContext(c->constructorParams); return true; } void ResolveReferences::postorder(const IR::P4Parser *c) { removeFromContext(c->constructorParams); removeFromContext(c->type->applyParams); removeFromContext(c->type->typeParameters); removeFromContext(c); checkShadowing(c); } bool ResolveReferences::preorder(const IR::Function* function) { refMap->usedName(function->name.name); addToContext(function->type->parameters); return true; } void ResolveReferences::postorder(const IR::Function* function) { removeFromContext(function->type->parameters); } bool ResolveReferences::preorder(const IR::P4Table* t) { refMap->usedName(t->name.name); addToContext(t->parameters); return true; } void ResolveReferences::postorder(const IR::P4Table* t) { removeFromContext(t->parameters); } bool ResolveReferences::preorder(const IR::TableProperties *p) { addToContext(p); return true; } void ResolveReferences::postorder(const IR::TableProperties *p) { removeFromContext(p); } bool ResolveReferences::preorder(const IR::P4Action *c) { refMap->usedName(c->name.name); addToContext(c); addToContext(c->parameters); return true; } void ResolveReferences::postorder(const IR::P4Action *c) { removeFromContext(c->parameters); removeFromContext(c); checkShadowing(c); } bool ResolveReferences::preorder(const IR::Type_Method *t) { // Function return values in generic functions may depend on the type arguments: // T f<T>() // where T is declared *after* its first use resolveForward.push_back(true); if (t->typeParameters != nullptr) addToContext(t->typeParameters); addToContext(t->parameters); return true; } void ResolveReferences::postorder(const IR::Type_Method *t) { removeFromContext(t->parameters); if (t->typeParameters != nullptr) removeFromContext(t->typeParameters); resolveForward.pop_back(); } bool ResolveReferences::preorder(const IR::Type_Extern *t) { refMap->usedName(t->name.name); addToContext(t->typeParameters); return true; } void ResolveReferences::postorder(const IR::Type_Extern *t) { removeFromContext(t->typeParameters); } bool ResolveReferences::preorder(const IR::ParserState *s) { refMap->usedName(s->name.name); // State references may be resolved forward resolveForward.push_back(true); addToContext(s); return true; } void ResolveReferences::postorder(const IR::ParserState *s) { removeFromContext(s); resolveForward.pop_back(); checkShadowing(s); } bool ResolveReferences::preorder(const IR::Declaration_Errors *d) { addToGlobals(d); return true; } bool ResolveReferences::preorder(const IR::Declaration_MatchKind *d) { addToGlobals(d); return true; } bool ResolveReferences::preorder(const IR::Type_ArchBlock *t) { resolveForward.push_back(anyOrder); addToContext(t->typeParameters); return true; } void ResolveReferences::postorder(const IR::Type_ArchBlock *t) { refMap->usedName(t->name.name); removeFromContext(t->typeParameters); resolveForward.pop_back(); } bool ResolveReferences::preorder(const IR::Type_StructLike *t) { refMap->usedName(t->name.name); addToContext(t); return true; } void ResolveReferences::postorder(const IR::Type_StructLike *t) { removeFromContext(t); } bool ResolveReferences::preorder(const IR::BlockStatement *b) { addToContext(b); return true; } void ResolveReferences::postorder(const IR::BlockStatement *b) { removeFromContext(b); checkShadowing(b); } bool ResolveReferences::preorder(const IR::Declaration_Instance *decl) { refMap->usedName(decl->name.name); if (decl->initializer != nullptr) addToContext(decl->initializer); return true; } void ResolveReferences::postorder(const IR::Declaration_Instance *decl) { if (decl->initializer != nullptr) removeFromContext(decl->initializer); } #undef PROCESS_NAMESPACE } // namespace P4
32.560345
97
0.60458
ddb19031941d6712f7139733b6aaeda26c2f1e09
1,552
cpp
C++
Depth_Estimation_Pipeline/app/driver.cpp
jasonpilbrough/Mesh-Based-Depth-Estimation
fe82eab3b064c3fa6a543fa83f626e7d948d2335
[ "MIT" ]
null
null
null
Depth_Estimation_Pipeline/app/driver.cpp
jasonpilbrough/Mesh-Based-Depth-Estimation
fe82eab3b064c3fa6a543fa83f626e7d948d2335
[ "MIT" ]
null
null
null
Depth_Estimation_Pipeline/app/driver.cpp
jasonpilbrough/Mesh-Based-Depth-Estimation
fe82eab3b064c3fa6a543fa83f626e7d948d2335
[ "MIT" ]
null
null
null
#include "pipeline.h" //#include "colourmap.h" //#include <opencv2/viz.hpp> int main(int argc, char* argv[]) { // ######### EuRoC ######### //std::string dataset_path_left = "data/EuRoC/MH1/cam0/data/%10d.png"; //std::string dataset_path_right = "data/EuRoC/MH1/cam1/data/%10d.png"; // ######### ETH3D ######### std::string dataset_path_left = "data/ETH3D/delivery_area/cam4_brighter/%10d.png"; std::string dataset_path_right = "data/ETH3D/delivery_area/cam5_brighter/%10d.png"; std::string dataset_path_gnd = "data/ETH3D/delivery_area/gnd/%10d.png"; // ######### OXFORD ######### (This is actually MVSEC) //std::string dataset_path_left = "data/Oxford/indoor_flying1/cam0/%10d.png"; //std::string dataset_path_right = "data/Oxford/indoor_flying1/cam1/%10d.png"; //std::string dataset_path_gnd = "data/Oxford/indoor_flying1/gnd/%10d.png"; sandbox::Pipeline p(dataset_path_left,dataset_path_right,dataset_path_gnd); p.run(); return 0; } // ######### KITTI ######### //std::string dataset_path_left = "data/KITTI/2011_09_26_drive_0002_sync/image_00/data/%10d.png"; //std::string dataset_path_right = "data/KITTI/2011_09_26_drive_0002_sync/image_01/data/%10d.png"; //std::string dataset_path_left = "data/KITTI/data_stereo_flow/image_00/%10d.png"; //std::string dataset_path_right = "data/KITTI/data_stereo_flow/image_01/%10d.png"; //std::string dataset_path_gnd = "data/KITTI/data_stereo_flow/disp_noc/%10d.png"; //sandbox::Pipeline p(dataset_path_left,dataset_path_right);
36.093023
98
0.691366
ddb1bc6b58aa8666fe1bd5ef983591fbeb7c216d
1,181
cpp
C++
test/ext/std/integral_constant/bug_datatype_inheritance.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
test/ext/std/integral_constant/bug_datatype_inheritance.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
test/ext/std/integral_constant/bug_datatype_inheritance.cpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/* @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #include <boost/hana/ext/std/integral_constant.hpp> #include <boost/hana/core/datatype.hpp> #include <type_traits> using namespace boost::hana; struct inherit_simple : std::integral_constant<int, 3> { }; struct inherit_no_default : std::integral_constant<int, 3> { inherit_no_default() = delete; }; struct incomplete; struct empty { }; struct non_pod { virtual ~non_pod() { } }; int main() { static_assert(std::is_same<datatype_t<inherit_simple>, StdIntegralConstant>{}, ""); static_assert(std::is_same<datatype_t<inherit_no_default>, StdIntegralConstant>{}, ""); static_assert(std::is_same<datatype_t<std::is_pointer<int*>>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<incomplete>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<empty>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<non_pod>, StdIntegralConstant>{}, ""); static_assert(!std::is_same<datatype_t<void>, StdIntegralConstant>{}, ""); }
34.735294
94
0.730737
ddb25dd6ff068f1ee904f061f903794d46277de1
878
cpp
C++
examples/test.cpp
EBoespflug/multi_array
61ce2540bf5e4c3c9b7266ae5958eaad433481a4
[ "CC0-1.0" ]
null
null
null
examples/test.cpp
EBoespflug/multi_array
61ce2540bf5e4c3c9b7266ae5958eaad433481a4
[ "CC0-1.0" ]
null
null
null
examples/test.cpp
EBoespflug/multi_array
61ce2540bf5e4c3c9b7266ae5958eaad433481a4
[ "CC0-1.0" ]
null
null
null
#include "../multi_array.hpp" #include <iostream> #include <numeric> template<typename Container> void print(Container c) { std::cout << c.size() << '\n'; for(auto&& v : c) std::cout << v << ' '; std::cout << '\n'; } int main() { eb::multi_array<int, 3, 2, 2> arr1{0}; eb::multi_array<int, 3, 2, 2> arr2{0}; std::iota(arr1.begin(), arr1.end(), 1); print(arr1); print(arr2); arr2(0, 0, 0) = 0; arr2(0, 0, 1) = 1; arr2(0, 1, 0) = 2; arr2(0, 1, 1) = 3; arr2(1, 0, 0) = 4; arr2(1, 0, 1) = 5; arr2(1, 1, 0) = 6; arr2(1, 1, 1) = 7; arr2(2, 0, 0) = 8; arr2(2, 0, 1) = 9; arr2(2, 1, 0) = 10; arr2(2, 1, 1) = 11; for(auto& i : arr1) --i; print(arr1); print(arr2); if(arr1 == arr2) std::cout << "Equals !\n"; else std::cout << "Not equals !\n"; }
17.918367
43
0.458998
ddb41032afaac83ba298fd4710593472b69f5ec3
27,241
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgscreencapture/osgscreencapture.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgscreencapture/osgscreencapture.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/examples/osgscreencapture/osgscreencapture.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial applications, * as long as this copyright notice is maintained. * * This application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <osg/CoordinateSystemNode> #include <osg/Switch> #include <osgText/Text> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/DriveManipulator> #include <osgGA/KeySwitchMatrixManipulator> #include <osgGA/StateSetManipulator> #include <osgGA/AnimationPathManipulator> #include <osgGA/TerrainManipulator> #include <iostream> #include <sstream> #include <string.h> class WindowCaptureCallback : public osg::Camera::DrawCallback { public: enum Mode { READ_PIXELS, SINGLE_PBO, DOUBLE_PBO, TRIPLE_PBO }; enum FramePosition { START_FRAME, END_FRAME }; struct ContextData : public osg::Referenced { ContextData(osg::GraphicsContext* gc, Mode mode, GLenum readBuffer, const std::string& name): _gc(gc), _mode(mode), _readBuffer(readBuffer), _fileName(name), _pixelFormat(GL_BGRA), _type(GL_UNSIGNED_BYTE), _width(0), _height(0), _currentImageIndex(0), _currentPboIndex(0), _reportTimingFrequency(100), _numTimeValuesRecorded(0), _timeForReadPixels(0.0), _timeForFullCopy(0.0), _timeForMemCpy(0.0) { _previousFrameTick = osg::Timer::instance()->tick(); if (gc->getTraits()) { if (gc->getTraits()->alpha) { osg::notify(osg::NOTICE)<<"Select GL_BGRA read back format"<<std::endl; _pixelFormat = GL_BGRA; } else { osg::notify(osg::NOTICE)<<"Select GL_BGR read back format"<<std::endl; _pixelFormat = GL_BGR; } } getSize(gc, _width, _height); std::cout<<"Window size "<<_width<<", "<<_height<<std::endl; // single buffered image _imageBuffer.push_back(new osg::Image); // double buffer PBO. switch(_mode) { case(READ_PIXELS): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with out PixelBufferObject."<<std::endl; break; case(SINGLE_PBO): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with a single PixelBufferObject."<<std::endl; _pboBuffer.push_back(0); break; case(DOUBLE_PBO): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with a double buffer PixelBufferObject."<<std::endl; _pboBuffer.push_back(0); _pboBuffer.push_back(0); break; case(TRIPLE_PBO): osg::notify(osg::NOTICE)<<"Reading window usig glReadPixels, with a triple buffer PixelBufferObject."<<std::endl; _pboBuffer.push_back(0); _pboBuffer.push_back(0); _pboBuffer.push_back(0); break; default: break; } } void getSize(osg::GraphicsContext* gc, int& width, int& height) { if (gc->getTraits()) { width = gc->getTraits()->width; height = gc->getTraits()->height; } } void updateTimings(osg::Timer_t tick_start, osg::Timer_t tick_afterReadPixels, osg::Timer_t tick_afterMemCpy, unsigned int dataSize); void read() { osg::BufferObject::Extensions* ext = osg::BufferObject::getExtensions(_gc->getState()->getContextID(),true); if (ext->isPBOSupported() && !_pboBuffer.empty()) { if (_pboBuffer.size()==1) { singlePBO(ext); } else { multiPBO(ext); } } else { readPixels(); } } void readPixels(); void singlePBO(osg::BufferObject::Extensions* ext); void multiPBO(osg::BufferObject::Extensions* ext); typedef std::vector< osg::ref_ptr<osg::Image> > ImageBuffer; typedef std::vector< GLuint > PBOBuffer; osg::GraphicsContext* _gc; Mode _mode; GLenum _readBuffer; std::string _fileName; GLenum _pixelFormat; GLenum _type; int _width; int _height; unsigned int _currentImageIndex; ImageBuffer _imageBuffer; unsigned int _currentPboIndex; PBOBuffer _pboBuffer; unsigned int _reportTimingFrequency; unsigned int _numTimeValuesRecorded; double _timeForReadPixels; double _timeForFullCopy; double _timeForMemCpy; osg::Timer_t _previousFrameTick; }; WindowCaptureCallback(Mode mode, FramePosition position, GLenum readBuffer): _mode(mode), _position(position), _readBuffer(readBuffer) { } FramePosition getFramePosition() const { return _position; } ContextData* createContextData(osg::GraphicsContext* gc) const { std::stringstream filename; filename << "test_"<<_contextDataMap.size()<<".jpg"; return new ContextData(gc, _mode, _readBuffer, filename.str()); } ContextData* getContextData(osg::GraphicsContext* gc) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex); osg::ref_ptr<ContextData>& data = _contextDataMap[gc]; if (!data) data = createContextData(gc); return data.get(); } virtual void operator () (osg::RenderInfo& renderInfo) const { glReadBuffer(_readBuffer); osg::GraphicsContext* gc = renderInfo.getState()->getGraphicsContext(); osg::ref_ptr<ContextData> cd = getContextData(gc); cd->read(); } typedef std::map<osg::GraphicsContext*, osg::ref_ptr<ContextData> > ContextDataMap; Mode _mode; FramePosition _position; GLenum _readBuffer; mutable OpenThreads::Mutex _mutex; mutable ContextDataMap _contextDataMap; }; void WindowCaptureCallback::ContextData::updateTimings(osg::Timer_t tick_start, osg::Timer_t tick_afterReadPixels, osg::Timer_t tick_afterMemCpy, unsigned int dataSize) { if (!_reportTimingFrequency) return; double timeForReadPixels = osg::Timer::instance()->delta_s(tick_start, tick_afterReadPixels); double timeForFullCopy = osg::Timer::instance()->delta_s(tick_start, tick_afterMemCpy); double timeForMemCpy = osg::Timer::instance()->delta_s(tick_afterReadPixels, tick_afterMemCpy); _timeForReadPixels += timeForReadPixels; _timeForFullCopy += timeForFullCopy; _timeForMemCpy += timeForMemCpy; ++_numTimeValuesRecorded; if (_numTimeValuesRecorded==_reportTimingFrequency) { timeForReadPixels = _timeForReadPixels/double(_numTimeValuesRecorded); timeForFullCopy = _timeForFullCopy/double(_numTimeValuesRecorded); timeForMemCpy = _timeForMemCpy/double(_numTimeValuesRecorded); double averageFrameTime = osg::Timer::instance()->delta_s(_previousFrameTick, tick_afterMemCpy)/double(_numTimeValuesRecorded); double fps = 1.0/averageFrameTime; _previousFrameTick = tick_afterMemCpy; _timeForReadPixels = 0.0; _timeForFullCopy = 0.0; _timeForMemCpy = 0.0; _numTimeValuesRecorded = 0; double numMPixels = double(_width * _height) / 1000000.0; double numMb = double(dataSize) / (1024*1024); int prec = osg::notify(osg::NOTICE).precision(5); if (timeForMemCpy==0.0) { osg::notify(osg::NOTICE)<<"fps = "<<fps<<", full frame copy = "<<timeForFullCopy*1000.0f<<"ms rate = "<<numMPixels / timeForFullCopy<<" Mpixel/sec, copy speed = "<<numMb / timeForFullCopy<<" Mb/sec"<<std::endl; } else { osg::notify(osg::NOTICE)<<"fps = "<<fps<<", full frame copy = "<<timeForFullCopy*1000.0f<<"ms rate = "<<numMPixels / timeForFullCopy<<" Mpixel/sec, "<<numMb / timeForFullCopy<< " Mb/sec "<< "time for memcpy = "<<timeForMemCpy*1000.0<<"ms memcpy speed = "<<numMb / timeForMemCpy<<" Mb/sec"<<std::endl; } osg::notify(osg::NOTICE).precision(prec); } } void WindowCaptureCallback::ContextData::readPixels() { // std::cout<<"readPixels("<<_fileName<<" image "<<_currentImageIndex<<" "<<_currentPboIndex<<std::endl; unsigned int nextImageIndex = (_currentImageIndex+1)%_imageBuffer.size(); unsigned int nextPboIndex = _pboBuffer.empty() ? 0 : (_currentPboIndex+1)%_pboBuffer.size(); int width=0, height=0; getSize(_gc, width, height); if (width!=_width || _height!=height) { std::cout<<" Window resized "<<width<<", "<<height<<std::endl; _width = width; _height = height; } osg::Image* image = _imageBuffer[_currentImageIndex].get(); osg::Timer_t tick_start = osg::Timer::instance()->tick(); #if 1 image->readPixels(0,0,_width,_height, _pixelFormat,_type); #endif osg::Timer_t tick_afterReadPixels = osg::Timer::instance()->tick(); updateTimings(tick_start, tick_afterReadPixels, tick_afterReadPixels, image->getTotalSizeInBytes()); if (!_fileName.empty()) { // osgDB::writeImageFile(*image, _fileName); } _currentImageIndex = nextImageIndex; _currentPboIndex = nextPboIndex; } void WindowCaptureCallback::ContextData::singlePBO(osg::BufferObject::Extensions* ext) { // std::cout<<"singelPBO( "<<_fileName<<" image "<<_currentImageIndex<<" "<<_currentPboIndex<<std::endl; unsigned int nextImageIndex = (_currentImageIndex+1)%_imageBuffer.size(); int width=0, height=0; getSize(_gc, width, height); if (width!=_width || _height!=height) { std::cout<<" Window resized "<<width<<", "<<height<<std::endl; _width = width; _height = height; } GLuint& pbo = _pboBuffer[0]; osg::Image* image = _imageBuffer[_currentImageIndex].get(); if (image->s() != _width || image->t() != _height) { osg::notify(osg::NOTICE)<<"Allocating image "<<std::endl; image->allocateImage(_width, _height, 1, _pixelFormat, _type); if (pbo!=0) { osg::notify(osg::NOTICE)<<"deleting pbo "<<pbo<<std::endl; ext->glDeleteBuffers (1, &pbo); pbo = 0; } } if (pbo==0) { ext->glGenBuffers(1, &pbo); ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pbo); ext->glBufferData(GL_PIXEL_PACK_BUFFER_ARB, image->getTotalSizeInBytes(), 0, GL_STREAM_READ); osg::notify(osg::NOTICE)<<"Generating pbo "<<pbo<<std::endl; } else { ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pbo); } osg::Timer_t tick_start = osg::Timer::instance()->tick(); #if 1 glReadPixels(0, 0, _width, _height, _pixelFormat, _type, 0); #endif osg::Timer_t tick_afterReadPixels = osg::Timer::instance()->tick(); GLubyte* src = (GLubyte*)ext->glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { memcpy(image->data(), src, image->getTotalSizeInBytes()); ext->glUnmapBuffer(GL_PIXEL_PACK_BUFFER_ARB); } ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, 0); osg::Timer_t tick_afterMemCpy = osg::Timer::instance()->tick(); updateTimings(tick_start, tick_afterReadPixels, tick_afterMemCpy, image->getTotalSizeInBytes()); if (!_fileName.empty()) { // osgDB::writeImageFile(*image, _fileName); } _currentImageIndex = nextImageIndex; } void WindowCaptureCallback::ContextData::multiPBO(osg::BufferObject::Extensions* ext) { // std::cout<<"multiPBO( "<<_fileName<<" image "<<_currentImageIndex<<" "<<_currentPboIndex<<std::endl; unsigned int nextImageIndex = (_currentImageIndex+1)%_imageBuffer.size(); unsigned int nextPboIndex = (_currentPboIndex+1)%_pboBuffer.size(); int width=0, height=0; getSize(_gc, width, height); if (width!=_width || _height!=height) { std::cout<<" Window resized "<<width<<", "<<height<<std::endl; _width = width; _height = height; } GLuint& copy_pbo = _pboBuffer[_currentPboIndex]; GLuint& read_pbo = _pboBuffer[nextPboIndex]; osg::Image* image = _imageBuffer[_currentImageIndex].get(); if (image->s() != _width || image->t() != _height) { osg::notify(osg::NOTICE)<<"Allocating image "<<std::endl; image->allocateImage(_width, _height, 1, _pixelFormat, _type); if (read_pbo!=0) { osg::notify(osg::NOTICE)<<"deleting pbo "<<read_pbo<<std::endl; ext->glDeleteBuffers (1, &read_pbo); read_pbo = 0; } if (copy_pbo!=0) { osg::notify(osg::NOTICE)<<"deleting pbo "<<copy_pbo<<std::endl; ext->glDeleteBuffers (1, &copy_pbo); copy_pbo = 0; } } bool doCopy = copy_pbo!=0; if (copy_pbo==0) { ext->glGenBuffers(1, &copy_pbo); ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, copy_pbo); ext->glBufferData(GL_PIXEL_PACK_BUFFER_ARB, image->getTotalSizeInBytes(), 0, GL_STREAM_READ); osg::notify(osg::NOTICE)<<"Generating pbo "<<read_pbo<<std::endl; } if (read_pbo==0) { ext->glGenBuffers(1, &read_pbo); ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, read_pbo); ext->glBufferData(GL_PIXEL_PACK_BUFFER_ARB, image->getTotalSizeInBytes(), 0, GL_STREAM_READ); osg::notify(osg::NOTICE)<<"Generating pbo "<<read_pbo<<std::endl; } else { ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, read_pbo); } osg::Timer_t tick_start = osg::Timer::instance()->tick(); #if 1 glReadPixels(0, 0, _width, _height, _pixelFormat, _type, 0); #endif osg::Timer_t tick_afterReadPixels = osg::Timer::instance()->tick(); if (doCopy) { ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, copy_pbo); GLubyte* src = (GLubyte*)ext->glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB); if(src) { memcpy(image->data(), src, image->getTotalSizeInBytes()); ext->glUnmapBuffer(GL_PIXEL_PACK_BUFFER_ARB); } if (!_fileName.empty()) { // osgDB::writeImageFile(*image, _fileName); } } ext->glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, 0); osg::Timer_t tick_afterMemCpy = osg::Timer::instance()->tick(); updateTimings(tick_start, tick_afterReadPixels, tick_afterMemCpy, image->getTotalSizeInBytes()); _currentImageIndex = nextImageIndex; _currentPboIndex = nextPboIndex; } void addCallbackToViewer(osgViewer::ViewerBase& viewer, WindowCaptureCallback* callback) { if (callback->getFramePosition()==WindowCaptureCallback::START_FRAME) { osgViewer::ViewerBase::Windows windows; viewer.getWindows(windows); for(osgViewer::ViewerBase::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) { osgViewer::GraphicsWindow* window = *itr; osg::GraphicsContext::Cameras& cameras = window->getCameras(); osg::Camera* firstCamera = 0; for(osg::GraphicsContext::Cameras::iterator cam_itr = cameras.begin(); cam_itr != cameras.end(); ++cam_itr) { if (firstCamera) { if ((*cam_itr)->getRenderOrder() < firstCamera->getRenderOrder()) { firstCamera = (*cam_itr); } if ((*cam_itr)->getRenderOrder() == firstCamera->getRenderOrder() && (*cam_itr)->getRenderOrderNum() < firstCamera->getRenderOrderNum()) { firstCamera = (*cam_itr); } } else { firstCamera = *cam_itr; } } if (firstCamera) { osg::notify(osg::NOTICE)<<"First camera "<<firstCamera<<std::endl; firstCamera->setInitialDrawCallback(callback); } else { osg::notify(osg::NOTICE)<<"No camera found"<<std::endl; } } } else { osgViewer::ViewerBase::Windows windows; viewer.getWindows(windows); for(osgViewer::ViewerBase::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) { osgViewer::GraphicsWindow* window = *itr; osg::GraphicsContext::Cameras& cameras = window->getCameras(); osg::Camera* lastCamera = 0; for(osg::GraphicsContext::Cameras::iterator cam_itr = cameras.begin(); cam_itr != cameras.end(); ++cam_itr) { if (lastCamera) { if ((*cam_itr)->getRenderOrder() > lastCamera->getRenderOrder()) { lastCamera = (*cam_itr); } if ((*cam_itr)->getRenderOrder() == lastCamera->getRenderOrder() && (*cam_itr)->getRenderOrderNum() >= lastCamera->getRenderOrderNum()) { lastCamera = (*cam_itr); } } else { lastCamera = *cam_itr; } } if (lastCamera) { osg::notify(osg::NOTICE)<<"Last camera "<<lastCamera<<std::endl; lastCamera->setFinalDrawCallback(callback); } else { osg::notify(osg::NOTICE)<<"No camera found"<<std::endl; } } } } int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); osgViewer::Viewer viewer(arguments); unsigned int helpType = 0; if ((helpType = arguments.readHelpType())) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (arguments.argc()<=1) { arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION); return 1; } // set up the camera manipulators. { osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() ); keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() ); keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() ); keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() ); std::string pathfile; char keyForAnimationPath = '5'; while (arguments.read("-p",pathfile)) { osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile); if (apm || !apm->valid()) { unsigned int num = keyswitchManipulator->getNumMatrixManipulators(); keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm ); keyswitchManipulator->selectMatrixManipulator(num); ++keyForAnimationPath; } } viewer.setCameraManipulator( keyswitchManipulator.get() ); } // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // add the record camera path handler viewer.addEventHandler(new osgViewer::RecordCameraPathHandler); // add the LOD Scale handler viewer.addEventHandler(new osgViewer::LODScaleHandler); GLenum readBuffer = GL_BACK; WindowCaptureCallback::FramePosition position = WindowCaptureCallback::END_FRAME; WindowCaptureCallback::Mode mode = WindowCaptureCallback::DOUBLE_PBO; while (arguments.read("--start-frame")) { position = WindowCaptureCallback::START_FRAME; readBuffer = GL_FRONT; } while (arguments.read("--end-frame")) position = WindowCaptureCallback::END_FRAME; while (arguments.read("--front")) readBuffer = GL_FRONT; while (arguments.read("--back")) readBuffer = GL_BACK; while (arguments.read("--no-pbo")) mode = WindowCaptureCallback::READ_PIXELS; while (arguments.read("--single-pbo")) mode = WindowCaptureCallback::SINGLE_PBO; while (arguments.read("--double-pbo")) mode = WindowCaptureCallback::DOUBLE_PBO; while (arguments.read("--triple-pbo")) mode = WindowCaptureCallback::TRIPLE_PBO; unsigned int width=1280; unsigned int height=1024; bool pbufferOnly = false; osg::ref_ptr<osg::GraphicsContext> pbuffer; if (arguments.read("--pbuffer",width,height) || (pbufferOnly = arguments.read("--pbuffer-only",width,height))) { osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->red = 8; traits->green = 8; traits->blue = 8; traits->alpha = 8; traits->windowDecoration = false; traits->pbuffer = true; traits->doubleBuffer = true; traits->sharedContext = 0; pbuffer = osg::GraphicsContext::createGraphicsContext(traits.get()); if (pbuffer.valid()) { osg::notify(osg::NOTICE)<<"Pixel buffer has been created successfully."<<std::endl; } else { osg::notify(osg::NOTICE)<<"Pixel buffer has not been created successfully."<<std::endl; } } // load the data osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments); if (!loadedModel) { std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; return 1; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); viewer.setSceneData( loadedModel.get() ); if (pbuffer.valid()) { osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(pbuffer.get()); camera->setViewport(new osg::Viewport(0,0,width,height)); GLenum buffer = pbuffer->getTraits()->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); camera->setFinalDrawCallback(new WindowCaptureCallback(mode, position, readBuffer)); if (pbufferOnly) { viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd()); viewer.realize(); } else { viewer.realize(); viewer.stopThreading(); pbuffer->realize(); viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd()); viewer.startThreading(); } } else { viewer.realize(); addCallbackToViewer(viewer, new WindowCaptureCallback(mode, position, readBuffer)); } return viewer.run(); }
34.395202
222
0.562645
ddb4b869c05f3c26a91225833baa2ebffa91a990
2,823
cc
C++
cc/whocc-scan-titers.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/whocc-scan-titers.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
cc/whocc-scan-titers.cc
acorg/acmacs-whocc
af508bd4651ffb565cd4cf771200540918b1b2bd
[ "MIT" ]
null
null
null
#include <string> #include "acmacs-base/argv.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-chart-2/chart.hh" #include "acmacs-chart-2/factory-import.hh" // ---------------------------------------------------------------------- void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files); void scan_titers(const fs::path& filename, std::set<acmacs::chart::Titer>& titers); // ---------------------------------------------------------------------- using namespace acmacs::argv; struct Options : public argv { Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); } argument<str> source_dir{*this, arg_name{"source-dir"}, mandatory}; }; int main(int argc, const char* argv[]) { int exit_code = 0; try { Options opt(argc, argv); std::vector<fs::path> ace_files; find_ace_files(fs::path(*opt.source_dir), ace_files); fmt::print("Total .ace files found: {}\n", ace_files.size()); std::set<acmacs::chart::Titer> titers; for (const auto& filename : ace_files) scan_titers(filename, titers); fmt::print("{}\n", titers); } catch (std::exception& err) { fmt::print(stderr, "ERROR: {}\n", err); exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- void find_ace_files(const fs::path& source_dir, std::vector<fs::path>& ace_files) { if (!fs::is_directory(source_dir)) throw std::runtime_error(source_dir.string() + " is not a directory"); for (const auto& dirent: fs::directory_iterator(source_dir)) { if (fs::is_directory(dirent.status())) find_ace_files(dirent.path(), ace_files); else if (is_regular_file(dirent.status()) && dirent.path().extension().string() == ".ace") ace_files.push_back(dirent.path()); } } // find_ace_files // ---------------------------------------------------------------------- void scan_titers(const fs::path& filename, std::set<acmacs::chart::Titer>& titers) { auto chart = acmacs::chart::import_from_file(filename, acmacs::chart::Verify::None, report_time::no); auto chart_titers = chart->titers(); const auto number_of_antigens = chart_titers->number_of_antigens(), number_of_sera = chart_titers->number_of_sera(); for (size_t antigen_no = 0; antigen_no < number_of_antigens; ++antigen_no) { for (size_t serum_no = 0; serum_no < number_of_sera; ++serum_no) { titers.insert(chart_titers->titer(antigen_no, serum_no)); } } } // scan_titers // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
36.662338
129
0.569607
ddb8c1a668ae4b09afe226003e27e8d7b3fb0006
34,652
cpp
C++
Gunz/xpsupport/xpcrt.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
Gunz/xpsupport/xpcrt.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
Gunz/xpsupport/xpcrt.cpp
WhyWolfie/Repack-Aren
4839db138a502ca4cfac8c2a8c950f1b59064955
[ "FSFAP" ]
null
null
null
/* Copyright (c) 2012 Mike Ryan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // XPSupport CRT Wrappers // Written by Mike Ryan (aka Ted.) // http://tedwvc.wordpress.com // see also http://connect.microsoft.com/VisualStudio/feedback/details/690617/ // Version history // 2012-03-11 1.0 initial release // 2012-03-13 1.01 Added msvcp110 stuff (InitializeCriticalSectionEx, CreateSymbolicLink(A/W) // 2012-03-15 1.02 (MFC updates) // 2012-03-15 1.03 Added fix for ConCRT runtime resource manager initialization (so std::thread can now be used) // 2012-03-15 1.04 (MFC updates) // 2012-03-29 1.05 added wrapper for EnumSystemLocalesEx // 2012-05-05 1.06 added wrapper for GetLogicalProcessorInformation (allows unofficial XP SP2 support) - thanks to Michael Chourdakis for this implementation // 2012-05-09 1.07 added wrapper for InitOnceExecuteOnce // 2012-05-26 1.08 added XP/2003 x64 edition support (in xpcrtwrap64.asm) // - thanks to Antony Vennard (https://vennard.org.uk) for testing and correcting several errors in my initial test x64 release // 2012-05-27 1.09 fixed non-Unicode (MBCS) builds (thanks to Latency for suggesting and helping with this fix) // 2012-06-28 1.10 added support for Vista threadpooling functions (added to pre-RTM version of CRT), added MIT license #include "stdafx.h" #ifndef _UNICODE #include <io.h> #include <stdio.h> #endif // we'll be using ntdll.dll so pull in a reference here #pragma comment (lib, "ntdll.lib") static BOOL IsVista = ((BYTE)::GetVersion() >= 6); // GetTickCount64 implementation for XP (32 bit) // IMPORTANT NOTE: this is the only undocumented part of the solution - if you're uncomfortable with this part, // please substitute it with an alternative of your choice! // For XP, we will use some undocumented features of Windows to emulate GetTickCount64 // see also: http://uninformed.org/index.cgi?v=7&a=2&p=12 for formula explanation and the offset used below #define CONST_SCALING_FACTOR 78 // see #include "winternl.h" in SDK headers for documented parts of these structures and enums // NOTE: only tested on XP 32 bit OS. 64 bit structures may differ!! // expanded from Microsoft's winternl.h - documented as size 48 typedef struct _SYSTEM_TIMEOFDAY_INFORMATION { LARGE_INTEGER TimeOfBoot; BYTE unused[40]; } SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION; // copied from Microsoft's winternl.h typedef enum _SYSTEM_INFORMATION_CLASS { SystemTimeOfDayInformation = 3, } SYSTEM_INFORMATION_CLASS; extern "C" __kernel_entry LONG NTAPI NtQuerySystemInformation ( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL); extern "C" __kernel_entry LONG NTAPI NtQuerySystemTime (OUT PLARGE_INTEGER SystemTime); static ULONGLONG UndocumentedGetTickCount64ImplementationForXP32() { static ULONGLONG StartTimeOfServer = static_cast<ULONGLONG>(-1); if (StartTimeOfServer == -1) { // undocumented - before using, please see comment above SYSTEM_TIMEOFDAY_INFORMATION timeofDayInfo = {0}; // see http://msdn.microsoft.com/en-us/library/windows/desktop/ms724509(v=vs.85).aspx NtQuerySystemInformation (SystemTimeOfDayInformation, &timeofDayInfo, sizeof(timeofDayInfo), 0); StartTimeOfServer = timeofDayInfo.TimeOfBoot.QuadPart; } // NtQuerySystemTime documented by Microsoft // http://msdn.microsoft.com/en-us/library/windows/desktop/ms724512(v=vs.85).aspx LARGE_INTEGER now; NtQuerySystemTime( &now ); return (ULONGLONG)(((now.QuadPart - StartTimeOfServer) / 10000.0) + CONST_SCALING_FACTOR); } typedef ULONGLONG (WINAPI *pGetTickCount64)(void); extern "C" ULONGLONG WINAPI AfxGetTickCount64(void) { static pGetTickCount64 GetTickCount64_p = NULL; if (IsVista) { // Vista or higher if (!GetTickCount64_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetTickCount64_p = (pGetTickCount64) GetProcAddress(mod, "GetTickCount64"); } return GetTickCount64_p(); } else return UndocumentedGetTickCount64ImplementationForXP32(); // see above } // the following two functions wrap LCIDToLocaleName/LocaleNameToLCID // we wrap them here so several locale name based APIs can convert back and forth to LCIDs on XP (which doesn't support LCIDs) // Note: this requires the use of NLSDL.DLL which ships with Internet Explorer 7 or later // if you really need to support XP3 + IE6 then please use the redistributable download available here: // http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=25241 // the above installs nlsdl to the windows system32 folder // or alternatively, modify the functions below to use MLANG instead (older technology but should work for the most part) // see: http://qualapps.blogspot.com/2011/10/convert-locale-name-to-lcid-in-c.html for an MLANG implementation typedef int (WINAPI *pLCIDToLocaleName)(__in LCID Locale, __out_opt LPWSTR lpName, int cchName,__in DWORD dwFlags); int WINAPI AfxLCIDToLocaleName( __in LCID Locale, __out_opt LPWSTR lpName, int cchName,__in DWORD dwFlags ) { static pLCIDToLocaleName LCIDToLocaleName_p = NULL ; LCID lcid = GetUserDefaultLCID() ; if( LCIDToLocaleName_p == NULL ){ HMODULE mod = NULL ; if( IsVista ){ // for Vista and up mod = GetModuleHandle( _T( "KERNEL32.dll" ) ) ; if( mod ){ LCIDToLocaleName_p = ( pLCIDToLocaleName ) GetProcAddress( mod, "LCIDToLocaleName" ) ; } } else{ // for XP and below - only support nlsdl.dll in system32 folder (comes with IE7 or nlsdl redist) TCHAR systempath[_MAX_PATH]; GetSystemDirectory(systempath , _countof(systempath)); TCHAR FullPath[_MAX_PATH] ; wsprintf(FullPath, _T( "%s\\%s" ) , systempath,_T( "nlsdl.dll" ) ) ; if (_taccess(FullPath, 00) == 0) mod = LoadLibrary( FullPath ) ; if( mod ){ LCIDToLocaleName_p = ( pLCIDToLocaleName ) GetProcAddress( mod, "DownlevelLCIDToLocaleName" ) ; } } } if( LCIDToLocaleName_p ){ // call function lcid = LCIDToLocaleName_p( Locale, lpName, cchName, dwFlags ) ; } return lcid ; } typedef LCID (WINAPI *pLocaleNameToLCID)(__in LPCWSTR lpName,__in DWORD dwFlags); LCID WINAPI AfxLocaleNameToLCID( __in LPCWSTR lpName, __in DWORD dwFlags ) { static pLocaleNameToLCID LocaleNameToLCID_p = NULL ; LCID lcid = GetUserDefaultLCID() ; if( LocaleNameToLCID_p == NULL ){ HMODULE mod = NULL ; if( IsVista ){ // for Vista and up mod = GetModuleHandle( _T( "KERNEL32.dll" ) ) ; if( mod ){ LocaleNameToLCID_p = ( pLocaleNameToLCID ) GetProcAddress( mod, "LocaleNameToLCID" ) ; } } else{ // for XP and below - only support nlsdl.dll in system32 folder (comes with IE7) TCHAR systempath[_MAX_PATH] = {0}; GetSystemDirectory(systempath , _countof(systempath)); TCHAR FullPath[_MAX_PATH] = {0}; wsprintf(FullPath, _T( "%s\\%s" ) , systempath,_T( "nlsdl.dll" ) ) ; if (_taccess(FullPath, 00) == 0) mod = LoadLibrary( FullPath ) ; if( mod ){ LocaleNameToLCID_p = ( pLocaleNameToLCID ) GetProcAddress( mod, "DownlevelLocaleNameToLCID" ) ; } } } if( LocaleNameToLCID_p ){ // call function lcid = LocaleNameToLCID_p( lpName, dwFlags ) ; } return lcid ; } typedef BOOL (WINAPI *pIsValidLocaleName)(LPCWSTR lpLocaleName); extern "C" BOOL WINAPI AfxIsValidLocaleName(_In_ LPCWSTR lpLocaleName) { static pIsValidLocaleName IsValidLocaleName_p = NULL; if (IsVista) { // Vista or higher if (!IsValidLocaleName_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) IsValidLocaleName_p = (pIsValidLocaleName) GetProcAddress(mod, "IsValidLocaleName"); } return IsValidLocaleName_p(lpLocaleName); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else return TRUE; // assume valid return IsValidLocale(lcid, 0); } } typedef int (WINAPI *pLCMapStringEx)( LPCWSTR lpLocaleName, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM sortHandle ); extern "C" int WINAPI AfxLCMapStringEx( LPCWSTR lpLocaleName, DWORD dwMapFlags, LPCWSTR lpSrcStr, int cchSrc, LPWSTR lpDestStr, int cchDest, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM sortHandle ) { static pLCMapStringEx LCMapStringEx_p = NULL; if (IsVista) { // Vista or higher if (!LCMapStringEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) LCMapStringEx_p = (pLCMapStringEx) GetProcAddress(mod, "LCMapStringEx"); } return LCMapStringEx_p(lpLocaleName, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest, lpVersionInformation, lpReserved, sortHandle); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return LCMapStringW(lcid, dwMapFlags, lpSrcStr, cchSrc, lpDestStr, cchDest); } } typedef int (WINAPI *pCompareStringEx)( LPCWSTR lpLocaleName, DWORD dwCmpFlags, LPCWSTR lpString1, int cchCount1, LPCWSTR lpString2, int cchCount2, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM lParam ); extern "C" int WINAPI AfxCompareStringEx( LPCWSTR lpLocaleName, DWORD dwCmpFlags, LPCWSTR lpString1, int cchCount1, LPCWSTR lpString2, int cchCount2, LPNLSVERSIONINFO lpVersionInformation, LPVOID lpReserved, LPARAM lParam ) { static pCompareStringEx CompareStringEx_p = NULL; if (IsVista) { // Vista or higher if (!CompareStringEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CompareStringEx_p = (pCompareStringEx) GetProcAddress(mod, "CompareStringEx"); } return CompareStringEx_p(lpLocaleName, dwCmpFlags, lpString1, cchCount1, lpString2, cchCount2, lpVersionInformation, lpReserved, lParam); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return CompareStringW(lcid, dwCmpFlags,lpString1, cchCount1, lpString2, cchCount2); } } typedef int (WINAPI *pGetLocaleInfoEx)(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData); extern "C" int WINAPI AfxGetLocaleInfoEx(LPCWSTR lpLocaleName, LCTYPE LCType, LPWSTR lpLCData, int cchData) { static pGetLocaleInfoEx GetLocaleInfoEx_p = NULL; if (IsVista) { // Vista or higher if (!GetLocaleInfoEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetLocaleInfoEx_p = (pGetLocaleInfoEx) GetProcAddress(mod, "GetLocaleInfoEx"); } return GetLocaleInfoEx_p(lpLocaleName, LCType, lpLCData, cchData); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return GetLocaleInfoW(lcid, LCType, lpLCData, cchData); } } typedef int (WINAPI *pGetUserDefaultLocaleName)( __out LPWSTR lpLocaleName, __in int cchLocaleName); extern "C" int WINAPI AfxGetUserDefaultLocaleName( __out LPWSTR lpLocaleName, __in int cchLocaleName) { static pGetUserDefaultLocaleName GetUserDefaultLocaleName_p = NULL; if (IsVista) { // Vista or higher if (!GetUserDefaultLocaleName_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetUserDefaultLocaleName_p = (pGetUserDefaultLocaleName) GetProcAddress(mod, "GetUserDefaultLocaleName"); } return GetUserDefaultLocaleName_p(lpLocaleName, cchLocaleName); } else { LCID lcid = GetUserDefaultLCID(); return AfxLCIDToLocaleName(lcid, lpLocaleName, cchLocaleName, 0); } } typedef BOOL (WINAPI *pEnumSystemLocalesEx)(__in LOCALE_ENUMPROCEX lpLocaleEnumProcEx,__in DWORD dwFlags, __in LPARAM lParam, __in_opt LPVOID lpReserved); LOCALE_ENUMPROCEX pLocaleEnumProcEx = 0; BOOL CALLBACK EnumLocalesProcWrapper (LPWSTR lpLocaleString) { LCID localeID = 0; wchar_t localeName[100] = {0}; swscanf_s( lpLocaleString, L"%x", &localeID ); AfxLCIDToLocaleName(localeID, localeName, _countof(localeName), 0); return pLocaleEnumProcEx(localeName, 0, 0); } extern "C" BOOL WINAPI AfxEnumSystemLocalesEx(__in LOCALE_ENUMPROCEX lpLocaleEnumProcEx,__in DWORD dwFlags, __in LPARAM lParam, __in_opt LPVOID lpReserved) { static pEnumSystemLocalesEx EnumSystemLocalesEx_p = NULL; if (IsVista) { // Vista or higher if (!EnumSystemLocalesEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) EnumSystemLocalesEx_p = (pEnumSystemLocalesEx) GetProcAddress(mod, "EnumSystemLocalesEx"); } return EnumSystemLocalesEx_p(lpLocaleEnumProcEx, dwFlags, lParam, lpReserved); } else { // fallback to EnumSystemLocales on XP // not even close to being thread-safe (left as exercise for reader) pLocaleEnumProcEx = lpLocaleEnumProcEx; // global variable return EnumSystemLocalesW(EnumLocalesProcWrapper, LCID_INSTALLED); } } // FLS functions - idea borrowed from VC9 and below's CRT source code (this is how they handle it) typedef DWORD (WINAPI *pFlsAlloc) (IN PFLS_CALLBACK_FUNCTION lpCallback OPTIONAL); typedef PVOID (WINAPI *pFlsGetValue) (IN DWORD dwFlsIndex); typedef BOOL (WINAPI *pFlsSetValue) (IN DWORD dwFlsIndex,IN PVOID lpFlsData); typedef BOOL (WINAPI *pFlsFree) ( IN DWORD dwFlsIndex); pFlsAlloc gpFlsAlloc = NULL; pFlsGetValue gpFlsGetValue = NULL; pFlsSetValue gpFlsSetValue = NULL; pFlsFree gpFlsFree = NULL; DWORD WINAPI __noParamTlsAlloc( PFLS_CALLBACK_FUNCTION ) { return TlsAlloc(); } static BOOL FlsInited = FALSE; void FlsInit() { HINSTANCE hKernel32 = GetModuleHandle(_T("kernel32.dll")); if (hKernel32) { gpFlsAlloc = (pFlsAlloc)GetProcAddress(hKernel32, "FlsAlloc"); if (gpFlsAlloc) { // if first one is missing don't bother with the others. gpFlsGetValue = (pFlsGetValue)GetProcAddress(hKernel32,"FlsGetValue"); gpFlsSetValue = (pFlsSetValue)GetProcAddress(hKernel32, "FlsSetValue"); gpFlsFree = (pFlsFree)GetProcAddress(hKernel32, "FlsFree"); } } if (!gpFlsAlloc) { gpFlsAlloc = (pFlsAlloc)__noParamTlsAlloc; gpFlsGetValue = (pFlsGetValue)TlsGetValue; gpFlsSetValue = (pFlsSetValue)TlsSetValue; gpFlsFree = (pFlsFree)TlsFree; } FlsInited = TRUE; } extern "C" DWORD WINAPI AfxFlsAlloc(__in PFLS_CALLBACK_FUNCTION lpCallback) { // this function is called by CRT before any globals are initialized so we have to call the initialization of the function pointers here if (!FlsInited) FlsInit(); return gpFlsAlloc(lpCallback); } extern "C" PVOID WINAPI AfxFlsGetValue( __in DWORD dwFlsIndex) { return gpFlsGetValue(dwFlsIndex); } extern "C" BOOL WINAPI AfxFlsSetValue(__in DWORD dwFlsIndex, __in_opt PVOID lpFlsData) { return gpFlsSetValue(dwFlsIndex, lpFlsData); } extern "C" BOOL WINAPI AfxFlsFree(__in DWORD dwFlsIndex) { return gpFlsFree(dwFlsIndex); } // miscellaneous functions // this helper function copied from http://www.scss.tcd.ie/Jeremy.Jones/GetCurrentProcessorNumberXP.htm DWORD GetCurrentProcessorNumberXP(void) { #ifndef _WIN64 _asm {mov eax, 1} _asm {cpuid} _asm {shr ebx, 24} _asm {mov eax, ebx} #else return 0; #endif } typedef DWORD (WINAPI *pGetCurrentProcessorNumber)(void); extern "C" DWORD WINAPI AfxGetCurrentProcessorNumber() { static pGetCurrentProcessorNumber GetCurrentProcessorNumber_p = NULL; static BOOL looked = FALSE; // native version of this function available on Vista and Server 2003 if (!looked && !GetCurrentProcessorNumber_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetCurrentProcessorNumber_p = (pGetCurrentProcessorNumber) GetProcAddress(mod, "GetCurrentProcessorNumber"); else looked = TRUE; } if (GetCurrentProcessorNumber_p) return GetCurrentProcessorNumber_p(); else return GetCurrentProcessorNumberXP(); } typedef void (WINAPI *pFlushProcessWriteBuffers)(void); extern "C" void WINAPI AfxFlushProcessWriteBuffers() { static pFlushProcessWriteBuffers FlushProcessWriteBuffers_p = NULL; if (IsVista) { // Vista or higher if (!FlushProcessWriteBuffers_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) FlushProcessWriteBuffers_p = (pFlushProcessWriteBuffers) GetProcAddress(mod, "FlushProcessWriteBuffers"); } if (FlushProcessWriteBuffers_p) FlushProcessWriteBuffers_p(); } // no implementation for XP } typedef HANDLE (WINAPI *pCreateSemaphoreExW)(__in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,__in LONG lInitialCount, __in LONG lMaximumCount, __in_opt LPCWSTR lpName, __reserved DWORD dwFlags, __in DWORD dwDesiredAccess); extern "C" HANDLE WINAPI AfxCreateSemaphoreExW(__in_opt LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,__in LONG lInitialCount, __in LONG lMaximumCount, __in_opt LPCWSTR lpName, __reserved DWORD dwFlags, __in DWORD dwDesiredAccess) { static pCreateSemaphoreExW CreateSemaphoreExW_p = NULL; if (IsVista) { // Vista or higher if (!CreateSemaphoreExW_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateSemaphoreExW_p = (pCreateSemaphoreExW) GetProcAddress(mod, "CreateSemaphoreExW"); } return CreateSemaphoreExW_p(lpSemaphoreAttributes,lInitialCount,lMaximumCount, lpName, dwFlags, dwDesiredAccess); } else { // XP can't support last two parameters of CreateSemaphoreExW return CreateSemaphoreW(lpSemaphoreAttributes,lInitialCount,lMaximumCount, lpName); } } typedef int (WINAPI *pGetTimeFormatEx)(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpTime, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpTimeStr, __in int cchTime); extern "C" int WINAPI AfxGetTimeFormatEx(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpTime, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpTimeStr, __in int cchTime) { static pGetTimeFormatEx GetTimeFormatEx_p = NULL; if (IsVista) { // Vista or higher if (!GetTimeFormatEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetTimeFormatEx_p = (pGetTimeFormatEx) GetProcAddress(mod, "GetTimeFormatEx"); } return GetTimeFormatEx_p(lpLocaleName, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return GetTimeFormatW(lcid, dwFlags, lpTime, lpFormat, lpTimeStr, cchTime); } } typedef int (WINAPI *pGetDateFormatEx)(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpDate, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpDateStr, __in int cchDate, __in_opt LPCWSTR lpCalendar); extern "C" int WINAPI AfxGetDateFormatEx(__in_opt LPCWSTR lpLocaleName, __in DWORD dwFlags, __in_opt const SYSTEMTIME *lpDate, __in_opt LPCWSTR lpFormat, __out_opt LPWSTR lpDateStr, __in int cchDate, __in_opt LPCWSTR lpCalendar) { static pGetDateFormatEx GetDateFormatEx_p = NULL; if (IsVista) { // Vista or higher if (!GetDateFormatEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetDateFormatEx_p = (pGetDateFormatEx) GetProcAddress(mod, "GetDateFormatEx"); } return GetDateFormatEx_p(lpLocaleName, dwFlags, lpDate, lpFormat, lpDateStr, cchDate, lpCalendar); } else { LCID lcid = 0; if (lpLocaleName) lcid = AfxLocaleNameToLCID(lpLocaleName, 0); else lcid = GetUserDefaultLCID(); return GetDateFormatW(lcid, dwFlags, lpDate, lpFormat, lpDateStr, cchDate); } } typedef BOOL (WINAPI *pSetThreadStackGuarantee)(__inout PULONG StackSizeInBytes); // available on Vista, XPx64, Server 2003 with SP1 but not XP x86 extern "C" BOOL WINAPI AfxSetThreadStackGuarantee(__inout PULONG StackSizeInBytes) { static pSetThreadStackGuarantee SetThreadStackGuarantee_p = NULL; static BOOL looked = FALSE; if (!looked && !SetThreadStackGuarantee_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) SetThreadStackGuarantee_p = (pSetThreadStackGuarantee) GetProcAddress(mod, "SetThreadStackGuarantee"); else looked = TRUE; } if (SetThreadStackGuarantee_p) return SetThreadStackGuarantee_p(StackSizeInBytes); else { // for XP we only need to support stack size query (if you pass in 0 as the stack size) - see _resetstkoflw in CRT source // not completed - left as an exercise to reader if (StackSizeInBytes && *StackSizeInBytes == 0) { *StackSizeInBytes = 0; return 1; } } return 0; } // STL stuff typedef BOOL (WINAPI *pInitializeCriticalSectionEx)(__out LPCRITICAL_SECTION lpCriticalSection, __in DWORD dwSpinCount, __in DWORD Flags); extern "C" BOOL WINAPI AfxInitializeCriticalSectionEx(__out LPCRITICAL_SECTION lpCriticalSection, __in DWORD dwSpinCount, __in DWORD Flags) { static pInitializeCriticalSectionEx InitializeCriticalSectionEx_p = NULL; if (IsVista) { // Vista or higher if (!InitializeCriticalSectionEx_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) InitializeCriticalSectionEx_p = (pInitializeCriticalSectionEx) GetProcAddress(mod, "InitializeCriticalSectionEx"); } return InitializeCriticalSectionEx_p(lpCriticalSection, dwSpinCount, Flags); } // on XP we'll just use InitializeCriticalSection for now InitializeCriticalSection(lpCriticalSection); return TRUE; } typedef BOOLEAN (WINAPI *pCreateSymbolicLinkA)(__in LPSTR lpSymlinkFileName, __in LPSTR lpTargetFileName, __in DWORD dwFlags); extern "C" BOOLEAN WINAPI AfxCreateSymbolicLinkA(__in LPSTR lpSymlinkFileName, __in LPSTR lpTargetFileName, __in DWORD dwFlags) { static pCreateSymbolicLinkA CreateSymbolicLinkA_p = NULL; if (IsVista) { // Vista or higher if (!CreateSymbolicLinkA_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateSymbolicLinkA_p = (pCreateSymbolicLinkA) GetProcAddress(mod, "CreateSymbolicLinkA"); } return CreateSymbolicLinkA_p(lpSymlinkFileName, lpTargetFileName, dwFlags); } return 0; } typedef BOOLEAN (WINAPI *pCreateSymbolicLinkW)(__in LPWSTR lpSymlinkFileName, __in LPWSTR lpTargetFileName, __in DWORD dwFlags); extern "C" BOOLEAN WINAPI AfxCreateSymbolicLinkW(__in LPWSTR lpSymlinkFileName, __in LPWSTR lpTargetFileName, __in DWORD dwFlags) { static pCreateSymbolicLinkW CreateSymbolicLinkW_p = NULL; if (IsVista) { // Vista or higher if (!CreateSymbolicLinkW_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateSymbolicLinkW_p = (pCreateSymbolicLinkW) GetProcAddress(mod, "CreateSymbolicLinkW"); } return CreateSymbolicLinkW_p(lpSymlinkFileName, lpTargetFileName, dwFlags); } return 0; } // GetLogicalProcessorInformationXP implementation provided by Michael Chourdakis of TurboIRC.COM BOOL GetLogicalProcessorInformationXP(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer,__inout PDWORD dwLength) { if (!dwLength) return 0; if (*dwLength < sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)) { SetLastError(ERROR_INSUFFICIENT_BUFFER); *dwLength = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); return FALSE; } if (Buffer == 0) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } SYSTEM_LOGICAL_PROCESSOR_INFORMATION& g1 = Buffer[0]; g1.ProcessorMask = 0x1; g1.Relationship = RelationProcessorCore; g1.ProcessorCore.Flags = 0; *dwLength = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); SetLastError(0); return TRUE; } typedef BOOL (WINAPI *pGetLogicalProcessorInformation)(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, __inout PDWORD ReturnLength); // GetLogicalProcessorInformation available on XP SP3 and above but not XP SP2 extern "C" BOOL WINAPI AfxGetLogicalProcessorInformation(__out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, __inout PDWORD ReturnLength) { static pGetLogicalProcessorInformation GetLogicalProcessorInformation_p = NULL; static BOOL looked = FALSE; if (!looked && !GetLogicalProcessorInformation_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetLogicalProcessorInformation_p = (pGetLogicalProcessorInformation) GetProcAddress(mod, "GetLogicalProcessorInformation"); else looked = TRUE; } if (GetLogicalProcessorInformation_p) return GetLogicalProcessorInformation_p(Buffer, ReturnLength); else return GetLogicalProcessorInformationXP(Buffer, ReturnLength); } // not thread-safe - may not even be correct BOOL WINAPI InitOnceExecuteOnceXP(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context) { BOOL ret = TRUE; static BOOL calledOnce = FALSE; if (!calledOnce) { ret = InitFn(InitOnce, Parameter, Context); calledOnce = TRUE; } return ret; } typedef BOOL (WINAPI *pInitOnceExecuteOnce)(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context); extern "C" BOOL WINAPI AfxInitOnceExecuteOnce(__inout PINIT_ONCE InitOnce, __in PINIT_ONCE_FN InitFn, __inout_opt PVOID Parameter, __out_opt LPVOID *Context) { static pInitOnceExecuteOnce InitOnceExecuteOnce_p = NULL; if (IsVista) { // Vista or higher if (!InitOnceExecuteOnce_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) InitOnceExecuteOnce_p = (pInitOnceExecuteOnce) GetProcAddress(mod, "InitOnceExecuteOnce"); } return InitOnceExecuteOnce_p(InitOnce, InitFn, Parameter, Context); } else return InitOnceExecuteOnceXP(InitOnce, InitFn, Parameter, Context); } // RTM added 8 new Vista+ APIs: // // CloseThreadpoolTimer // CloseThreadpoolWait // CreateThreadpoolTimer // CreateThreadpoolWait // FreeLibraryWhenCallbackReturns // SetThreadpoolTimer // SetThreadpoolWait // WaitForThreadpoolTimerCallbacks typedef VOID (WINAPI *pCloseThreadpoolTimer)(__inout PTP_TIMER pti); extern "C" VOID WINAPI AfxCloseThreadpoolTimer(__inout PTP_TIMER pti) { static pCloseThreadpoolTimer CloseThreadpoolTimer_p = NULL; if (IsVista) { // Vista or higher if (!CloseThreadpoolTimer_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CloseThreadpoolTimer_p = (pCloseThreadpoolTimer) GetProcAddress(mod, "CloseThreadpoolTimer"); } CloseThreadpoolTimer_p(pti); } return; } typedef VOID (WINAPI *pCloseThreadpoolWait)(__inout PTP_WAIT pwa); extern "C" VOID WINAPI AfxCloseThreadpoolWait(__inout PTP_WAIT pwa) { static pCloseThreadpoolWait CloseThreadpoolWait_p = NULL; if (IsVista) { // Vista or higher if (!CloseThreadpoolWait_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CloseThreadpoolWait_p = (pCloseThreadpoolWait) GetProcAddress(mod, "CloseThreadpoolWait"); } CloseThreadpoolWait_p(pwa); } return; } typedef PTP_TIMER (WINAPI *pCreateThreadpoolTimer)(__in PTP_TIMER_CALLBACK pfnti, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe); extern "C" PTP_TIMER WINAPI AfxCreateThreadpoolTimer(__in PTP_TIMER_CALLBACK pfnti, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe) { static pCreateThreadpoolTimer CreateThreadpoolTimer_p = NULL; if (IsVista) { // Vista or higher if (!CreateThreadpoolTimer_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateThreadpoolTimer_p = (pCreateThreadpoolTimer) GetProcAddress(mod, "CreateThreadpoolTimer"); } return CreateThreadpoolTimer_p(pfnti, pv, pcbe); } return 0; } typedef PTP_WAIT (WINAPI *pCreateThreadpoolWait)(__in PTP_WAIT_CALLBACK pfnwa, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe); extern "C" PTP_WAIT WINAPI AfxCreateThreadpoolWait(__in PTP_WAIT_CALLBACK pfnwa, __inout_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe) { static pCreateThreadpoolWait CreateThreadpoolWait_p = NULL; if (IsVista) { // Vista or higher if (!CreateThreadpoolWait_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) CreateThreadpoolWait_p = (pCreateThreadpoolWait) GetProcAddress(mod, "CreateThreadpoolWait"); } return CreateThreadpoolWait_p(pfnwa, pv, pcbe); } return 0; } typedef VOID (WINAPI *pFreeLibraryWhenCallbackReturns)(__inout PTP_CALLBACK_INSTANCE pci, __in HMODULE mod); extern "C" VOID WINAPI AfxFreeLibraryWhenCallbackReturns(__inout PTP_CALLBACK_INSTANCE pci, __in HMODULE mod) { static pFreeLibraryWhenCallbackReturns FreeLibraryWhenCallbackReturns_p = NULL; if (IsVista) { // Vista or higher if (!FreeLibraryWhenCallbackReturns_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) FreeLibraryWhenCallbackReturns_p = (pFreeLibraryWhenCallbackReturns) GetProcAddress(mod, "FreeLibraryWhenCallbackReturns"); } FreeLibraryWhenCallbackReturns_p(pci, mod); } return; } typedef VOID (WINAPI *pSetThreadpoolTimer)(__inout PTP_TIMER pti, __in_opt PFILETIME pftDueTime, __in DWORD msPeriod, __in_opt DWORD msWindowLength); extern "C" VOID WINAPI AfxSetThreadpoolTimer(__inout PTP_TIMER pti, __in_opt PFILETIME pftDueTime, __in DWORD msPeriod, __in_opt DWORD msWindowLength) { static pSetThreadpoolTimer SetThreadpoolTimer_p = NULL; if (IsVista) { // Vista or higher if (!SetThreadpoolTimer_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) SetThreadpoolTimer_p = (pSetThreadpoolTimer) GetProcAddress(mod, "SetThreadpoolTimer"); } SetThreadpoolTimer_p(pti, pftDueTime, msPeriod, msWindowLength); } return; } typedef VOID (WINAPI *pSetThreadpoolWait)(__inout PTP_WAIT pwa, __in_opt HANDLE h, __in_opt PFILETIME pftTimeout); extern "C" VOID WINAPI AfxSetThreadpoolWait(__inout PTP_WAIT pwa, __in_opt HANDLE h, __in_opt PFILETIME pftTimeout) { static pSetThreadpoolWait SetThreadpoolWait_p = NULL; if (IsVista) { // Vista or higher if (!SetThreadpoolWait_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) SetThreadpoolWait_p = (pSetThreadpoolWait) GetProcAddress(mod, "SetThreadpoolWait"); } SetThreadpoolWait_p(pwa, h, pftTimeout); } return; } typedef VOID (WINAPI *pWaitForThreadpoolTimerCallbacks)(__inout PTP_TIMER pti, __in BOOL fCancelPendingCallbacks); extern "C" VOID WINAPI AfxWaitForThreadpoolTimerCallbacks(__inout PTP_TIMER pti, __in BOOL fCancelPendingCallbacks) { static pWaitForThreadpoolTimerCallbacks WaitForThreadpoolTimerCallbacks_p = NULL; if (IsVista) { // Vista or higher if (!WaitForThreadpoolTimerCallbacks_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) WaitForThreadpoolTimerCallbacks_p = (pWaitForThreadpoolTimerCallbacks) GetProcAddress(mod, "WaitForThreadpoolTimerCallbacks"); } WaitForThreadpoolTimerCallbacks_p(pti, fCancelPendingCallbacks); } return; } // need to hook GetVersionEx for concrt runtime to initialized correctly // uses some globals (probably not thread-safe) typedef BOOL (WINAPI *pGetVersionExW)(__inout LPOSVERSIONINFO lpVersionInfo); static BOOL fakeVersion = FALSE; extern "C" BOOL WINAPI AfxGetVersionExW(__inout LPOSVERSIONINFO lpVersionInfo) { static pGetVersionExW GetVersionExW_p = NULL; BOOL retVal = FALSE; if (!GetVersionExW_p) { HMODULE mod = GetModuleHandle( _T("KERNEL32.DLL")); if (mod) GetVersionExW_p = (pGetVersionExW) GetProcAddress(mod, "GetVersionExW"); } if (GetVersionExW_p) retVal = GetVersionExW_p(lpVersionInfo); if (!IsVista && fakeVersion) { // XP and lower - trick ConCRT into thinking that it's Vista lpVersionInfo->dwMajorVersion = 6; lpVersionInfo->dwMinorVersion = 0; } return retVal; } #if !defined(_DEBUG) || !defined(_MFC_VER) || _MSC_FULL_VER >= 170050503 // sorry this workaround only works in release builds of MFC until Microsoft fixes this bug in VC11 // http://connect.microsoft.com/VisualStudio/feedback/details/630105/ #include <concrt.h> #if _MSC_FULL_VER >= 170050623 // pre-RTM // The following code accesses some private ConCRT data and is necessary because of the new threadpool support written // for Vista only should not be called on XP so we need to switch the Resource Manager's version back to XP after sucessfully // initializing it. class VersionSetterHack; #include <concrtrm.h> namespace Concurrency { namespace details { class ResourceManager : public Concurrency::IResourceManager { friend class VersionSetterHack; private: static IResourceManager::OSVersion s_version; public: static ResourceManager* CreateSingleton(); }; } } class VersionSetterHack { public: VersionSetterHack() { // s_version has private linkage: accessing private member using friend hack Concurrency::details::ResourceManager::s_version = Concurrency::details::ResourceManager::OSVersion::XP; } }; #endif void InitializeConCRT() { fakeVersion = TRUE; // the following function loads the resource manager using a temporary fake version (Vista) by hacking GetVersionEx Concurrency::details::_GetConcurrency(); #if _MSC_FULL_VER >= 170050623 // pre-RTM if (!IsVista) { // this needs to be done before setting back to XP because of an assertion checking for Vista Concurrency::details::ResourceManager::CreateSingleton(); // On XP OS reset version back to XP so ConCRT fallbacks will be used instead of Vista threadpooling functions VersionSetterHack versionSet; } #endif fakeVersion = FALSE; } class ForceConCRTInit { public: ForceConCRTInit() { InitializeConCRT(); } }; // this gets called before main() so allows ConCRT Resource Manager to be initialized early ForceConCRTInit init; #endif
34.791165
157
0.75303
ddb931107eeba6b3642942bac5d454e2310eb50f
2,248
cpp
C++
src/Context.cpp
santa01/frank-luna-dx11
57172ca245f7933116ad8ab1974a1ff95c6a4f4c
[ "MIT" ]
null
null
null
src/Context.cpp
santa01/frank-luna-dx11
57172ca245f7933116ad8ab1974a1ff95c6a4f4c
[ "MIT" ]
null
null
null
src/Context.cpp
santa01/frank-luna-dx11
57172ca245f7933116ad8ab1974a1ff95c6a4f4c
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Pavlo Lavrenenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "Context.h" #include "Application.h" #include <chrono> Context::Context(Application& application, const ContextParams& params) : m_Application(application) , m_Params(params) { m_Window.reset(new Window(*this)); m_Device.reset(new DX11Device(*this)); } const ContextParams& Context::GetParams() const { return m_Params; } Window& Context::GetWindow() const { return *m_Window; } DX11Device& Context::GetDevice() const { return *m_Device; } float Context::GetFrameTime() const { return m_FrameTime; } void Context::Run() { m_Application.Start(*this); while (!m_Terminate) { auto frameBegin = std::chrono::high_resolution_clock::now(); m_Device->Begin(*this); m_Window->Update(*this); m_Application.Update(*this); m_Device->End(*this); auto frameEnd = std::chrono::high_resolution_clock::now(); std::chrono::duration<float> frameDuration = frameEnd - frameBegin; m_FrameTime = frameDuration.count(); } m_Application.Shutdown(*this); } void Context::Terminate() { m_Terminate = true; }
27.084337
81
0.711744
ddba5cf6d9aad6ae6bad3b4345ffd496eb24dd05
1,259
cpp
C++
11497/11497.cpp
retroinspect/my-first-ps
89c583cd7207b32465c9616b032dd1c3f1f54438
[ "Apache-2.0" ]
null
null
null
11497/11497.cpp
retroinspect/my-first-ps
89c583cd7207b32465c9616b032dd1c3f1f54438
[ "Apache-2.0" ]
null
null
null
11497/11497.cpp
retroinspect/my-first-ps
89c583cd7207b32465c9616b032dd1c3f1f54438
[ "Apache-2.0" ]
null
null
null
// 통나무 건너뛰기 #include <iostream> #include <string> #include <vector> #include <cassert> #include <cmath> #include <algorithm> #include <list> using namespace std; vector<int> input; int N; int logJumping() { sort(input.begin(), input.end()); list<int> reorder; for (int i=0; i<N; i++) { int e = input[i]; if (i%2 == 0) reorder.push_back(e); else reorder.push_front(e); } int maxDiff = -1; for (list<int>::iterator iter = reorder.begin(); iter != reorder.end(); iter++) { list<int>::iterator tmpIt = iter; tmpIt++; int num1 = *iter; int num2 = (tmpIt == reorder.end()) ? reorder.front() : *tmpIt; int tmp = abs(num1-num2); if (tmp > maxDiff) maxDiff = tmp; } return maxDiff; } int main() { string tmpString; cin >> tmpString; int T = stoi(tmpString); vector<int> answers; for (int i=0; i<T; i++) { cin >> tmpString; N = stoi(tmpString); for (int j=0; j<N; j++) { cin >> tmpString; int num = stoi(tmpString); input.push_back(num); } int answer = logJumping(); answers.push_back(answer); input.clear(); } for (vector<int>::iterator iter=answers.begin(); iter != answers.end(); iter++) { cout << *iter << endl; } return 0; }
17.985714
81
0.58062
ddbebac1a83fa5be9674f895330b132b682461fb
6,612
cpp
C++
src/lpython/tests/test_parse.cpp
akshanshbhatt/lpython
70fef49dbbb6cbb0447f7013231171e5c8b8e5df
[ "BSD-3-Clause" ]
31
2022-01-07T23:56:33.000Z
2022-03-29T16:09:02.000Z
src/lpython/tests/test_parse.cpp
akshanshbhatt/lpython
70fef49dbbb6cbb0447f7013231171e5c8b8e5df
[ "BSD-3-Clause" ]
197
2021-12-29T19:01:41.000Z
2022-03-31T15:58:25.000Z
src/lpython/tests/test_parse.cpp
akshanshbhatt/lpython
70fef49dbbb6cbb0447f7013231171e5c8b8e5df
[ "BSD-3-Clause" ]
17
2022-01-06T15:34:36.000Z
2022-03-31T13:55:33.000Z
#include <tests/doctest.h> #include <iostream> #include <sstream> #include <chrono> #include <string> #include <lpython/bigint.h> using LFortran::TRY; using LFortran::Result; using LFortran::BigInt::is_int_ptr; using LFortran::BigInt::ptr_to_int; using LFortran::BigInt::int_to_ptr; using LFortran::BigInt::string_to_largeint; using LFortran::BigInt::largeint_to_string; using LFortran::BigInt::MAX_SMALL_INT; using LFortran::BigInt::MIN_SMALL_INT; // Print any vector like iterable to a string template <class T> inline std::ostream &print_vec(std::ostream &out, T &d) { out << "["; for (auto p = d.begin(); p != d.end(); p++) { if (p != d.begin()) out << ", "; out << *p; } out << "]"; return out; } namespace doctest { // Convert std::vector<T> to string for doctest template<typename T> struct StringMaker<std::vector<T>> { static String convert(const std::vector<T> &value) { std::ostringstream oss; print_vec(oss, value); return oss.str().c_str(); } }; } class TokenizerError0 { }; TEST_CASE("Test Big Int") { int64_t i; void *p, *p2; /* Integer tests */ i = 0; CHECK(!is_int_ptr(i)); i = 5; CHECK(!is_int_ptr(i)); i = -5; CHECK(!is_int_ptr(i)); // Largest integer that is allowed is 2^62-1 i = 4611686018427387903LL; CHECK(i == MAX_SMALL_INT); CHECK(!is_int_ptr(i)); // this is an integer i = 4611686018427387904LL; CHECK(is_int_ptr(i)); // this is a pointer // Smallest integer that is allowed is -2^63 i = -9223372036854775808ULL; CHECK(i == MIN_SMALL_INT); CHECK(!is_int_ptr(i)); // this is an integer i = -9223372036854775809ULL; // This does not fit into a signed 64bit int CHECK(is_int_ptr(i)); // this is a pointer /* Pointer tests */ // Smallest pointer value is 0 (nullptr) p = nullptr; i = ptr_to_int(p); CHECK(is_int_ptr(i)); p2 = int_to_ptr(i); CHECK(p == p2); // Second smallest pointer value aligned to 4 is 4 p = (void*)4; i = ptr_to_int(p); CHECK(is_int_ptr(i)); p2 = int_to_ptr(i); CHECK(p == p2); // Maximum pointer value aligned to 4 is (2^64-1)-3 p = (void*)18446744073709551612ULL; i = ptr_to_int(p); CHECK(is_int_ptr(i)); p2 = int_to_ptr(i); CHECK(p == p2); /* Big int tests */ Allocator al(1024); LFortran::Str s; char *cs; s.from_str(al, "123"); i = string_to_largeint(al, s); CHECK(is_int_ptr(i)); cs = largeint_to_string(i); CHECK(std::string(cs) == "123"); s.from_str(al, "123567890123456789012345678901234567890"); i = string_to_largeint(al, s); CHECK(is_int_ptr(i)); cs = largeint_to_string(i); CHECK(std::string(cs) == "123567890123456789012345678901234567890"); } TEST_CASE("Test LFortran::Vec") { Allocator al(1024); LFortran::Vec<int> v; v.reserve(al, 2); CHECK(v.size() == 0); CHECK(v.capacity() == 2); v.push_back(al, 1); CHECK(v.size() == 1); CHECK(v.capacity() == 2); CHECK(v.p[0] == 1); CHECK(v[0] == 1); v.push_back(al, 2); CHECK(v.size() == 2); CHECK(v.capacity() == 2); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v[0] == 1); CHECK(v[1] == 2); v.push_back(al, 3); CHECK(v.size() == 3); CHECK(v.capacity() == 4); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v.p[2] == 3); CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 3); v.push_back(al, 4); CHECK(v.size() == 4); CHECK(v.capacity() == 4); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v.p[2] == 3); CHECK(v.p[3] == 4); CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 3); CHECK(v[3] == 4); v.push_back(al, 5); CHECK(v.size() == 5); CHECK(v.capacity() == 8); CHECK(v.p[0] == 1); CHECK(v.p[1] == 2); CHECK(v.p[2] == 3); CHECK(v.p[3] == 4); CHECK(v.p[4] == 5); CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 3); CHECK(v[3] == 4); CHECK(v[4] == 5); std::vector<int> sv = v.as_vector(); CHECK(sv.size() == 5); CHECK(&(sv[0]) != &(v.p[0])); CHECK(sv[0] == 1); CHECK(sv[1] == 2); CHECK(sv[2] == 3); CHECK(sv[3] == 4); CHECK(sv[4] == 5); } TEST_CASE("LFortran::Vec iterators") { Allocator al(1024); LFortran::Vec<int> v; v.reserve(al, 2); v.push_back(al, 1); v.push_back(al, 2); v.push_back(al, 3); v.push_back(al, 4); // Check reference (auto) int i = 0; for (auto &a : v) { i += a; } CHECK(i == 10); // Check reference (must be const) i = 0; for (const int &a : v) { i += a; } CHECK(i == 10); // Check direct type (auto) i = 0; for (auto a : v) { i += a; } CHECK(i == 10); // Check direct type (const) i = 0; for (const int a : v) { i += a; } CHECK(i == 10); // Check direct type (non const) i = 0; for (int a : v) { i += a; } CHECK(i == 10); } TEST_CASE("Test LFortran::Str") { Allocator al(1024); LFortran::Str s; const char *data = "Some string."; s.p = const_cast<char*>(data); s.n = 2; CHECK(s.size() == 2); CHECK(s.p == data); CHECK(s.str() == "So"); std::string scopy = s.str(); CHECK(s.p != &scopy[0]); CHECK(scopy == "So"); CHECK(scopy[0] == 'S'); CHECK(scopy[1] == 'o'); CHECK(scopy[2] == '\x00'); char *copy = s.c_str(al); CHECK(s.p != copy); CHECK(copy[0] == 'S'); CHECK(copy[1] == 'o'); CHECK(copy[2] == '\x00'); } TEST_CASE("Test LFortran::Allocator") { Allocator al(32); // Size is what we asked (32) plus alignment (8) = 40 CHECK(al.size_total() == 40); // Fits in the pre-allocated chunk al.alloc(32); CHECK(al.size_total() == 40); // Chunk doubles al.alloc(32); CHECK(al.size_total() == 80); // Chunk doubles al.alloc(90); CHECK(al.size_total() == 160); // We asked more than can fit in the doubled chunk (2*160), // so the chunk will be equal to what we asked (1024) plus alignment (8) al.alloc(1024); CHECK(al.size_total() == 1032); } TEST_CASE("Test LFortran::Allocator 2") { Allocator al(32); int *p = al.allocate<int>(); p[0] = 5; p = al.allocate<int>(3); p[0] = 1; p[1] = 2; p[2] = 3; std::vector<int> *v = al.make_new<std::vector<int>>(5); CHECK(v->size() == 5); // Must manually call the destructor: v->~vector<int>(); }
22.187919
77
0.535088
ddbee71b4aee7077c83aaaa0be21fd6a14bc25e3
3,804
cpp
C++
google_analytics.cpp
mgoin/tiniest-analytics
4adae359d0c261fe61bc4206bc8c2b5619413f17
[ "MIT" ]
null
null
null
google_analytics.cpp
mgoin/tiniest-analytics
4adae359d0c261fe61bc4206bc8c2b5619413f17
[ "MIT" ]
null
null
null
google_analytics.cpp
mgoin/tiniest-analytics
4adae359d0c261fe61bc4206bc8c2b5619413f17
[ "MIT" ]
null
null
null
/* Tiniest Analytics - v1.1 - MIT License (i.e. can use it for whatever purpose) Version history: v1.1 - 2017/12/15 - changed to C-style C++ Original authors: Mihai Dragomir, email:dmc@pixelshard.com Mihai Gosa, email:pintea@inthekillhouse.com twitter: @gosamihai */ #include "google_analytics.h" #include "curl/curl.h" #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <dbg.h> static CURLM *g_pMultiHandle = NULL; static char g_strServicePath[2048] = {'\0'}; // caches clientID and trackingID after calling init() (http://www.google-analytics.com/collect?v=1&tid=%s&cid=%s) // utility function, used to replace spaces with pluses for URLs static void replace_str_char(char *s, const int len, const char what, const char with) { for (int i = 0; i < len; ++i) { if (s[i] == what) s[i] = with; } } // utility function, used to send the HTTP get static bool execute_curl_url(const char *url, ...) { dbg(g_pMultiHandle); if (!g_pMultiHandle) { return false; } va_list argptr; va_start(argptr, url); char strAddr[2048] = {'\0'}; int slen = vsprintf(strAddr, url, argptr); va_end(argptr); replace_str_char(strAddr, slen, ' ', '+'); dbg(strAddr); CURL *pCurlHandle = curl_easy_init(); curl_easy_setopt(pCurlHandle, CURLOPT_URL, strAddr); curl_easy_setopt(pCurlHandle, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(pCurlHandle, CURLOPT_TIMEOUT, 20); CURLMcode result = curl_multi_add_handle(g_pMultiHandle, pCurlHandle); return (result == CURLM_OK); } bool google_analytics_init(const char *trackingId, const char *uniqueClientId) { curl_global_init(CURL_GLOBAL_ALL); g_pMultiHandle = curl_multi_init(); dbg(g_pMultiHandle); if (!g_pMultiHandle) { return false; } sprintf(g_strServicePath, "https://www.google-analytics.com/collect?v=1&tid=%s&cid=%s", trackingId, uniqueClientId); dbg(g_strServicePath); return true; } void google_analytics_shutdown() { dbg(g_pMultiHandle); if (!g_pMultiHandle) { return; } google_analytics_update(); // one last update to remove handles from stack if they're ready curl_multi_cleanup(g_pMultiHandle); g_pMultiHandle = NULL; } void google_analytics_event(const char *category, const char *action, const char *label, unsigned int value) { execute_curl_url("%s&t=event&ec=%s&ea=%s&el=%s&ev=%u&z=%d", g_strServicePath, category, action, label, value, rand()); } void google_analytics_event(const char *category, const char *action, const char *label) { execute_curl_url("%s&t=event&ec=%s&ea=%s&el=%s&z=%d", g_strServicePath, category, action, label, rand()); } void google_analytics_event(const char *category, const char *action) { execute_curl_url("%s&t=event&ec=%s&ea=%s&z=%d", g_strServicePath, category, action, rand()); } void google_analytics_update() { if (!g_pMultiHandle) { return; } int stillRunning = 0; curl_multi_perform(g_pMultiHandle, &stillRunning); CURLMsg *pMsg = NULL; do { int msgsInQueue = 0; pMsg = curl_multi_info_read(g_pMultiHandle, &msgsInQueue); if (pMsg && (pMsg->msg == CURLMSG_DONE)) { dbg(pMsg); long response_code; curl_easy_getinfo(pMsg->easy_handle, CURLINFO_RESPONSE_CODE, &response_code); dbg(response_code); if (response_code != 200) { const char *urlp; curl_easy_getinfo(pMsg->easy_handle, CURLINFO_EFFECTIVE_URL, &urlp); char strerr[2048]; sprintf(strerr, "[Error] google_analytics_Update() failed for URL '%s' with error %ld\n", urlp ? urlp : "?", response_code); assert(response_code == 200 && strerr); } curl_multi_remove_handle(g_pMultiHandle, pMsg->easy_handle); curl_easy_cleanup(pMsg->easy_handle); } } while (pMsg); }
27.565217
160
0.694532
ddc43cf6da150fb602bef9745593a4c071d4c933
30,276
cpp
C++
Javelin/Assembler/arm64/Assembler.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
10
2016-04-06T01:24:00.000Z
2021-11-16T10:16:51.000Z
Javelin/Assembler/arm64/Assembler.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
1
2016-05-06T05:38:58.000Z
2016-05-09T16:42:43.000Z
Javelin/Assembler/arm64/Assembler.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
null
null
null
//============================================================================ #if defined(__arm64__) //============================================================================ #include "Javelin/Assembler/arm64/Assembler.h" #include "Javelin/Assembler/JitMemoryManager.h" #include <algorithm> #include <stdint.h> //============================================================================ #if DEBUG #define USE_GOTO_LABELS 0 #else #define USE_GOTO_LABELS 1 #endif #define USE_OPTIMIZED_APPEND_INSTRUCTION_DATA 1 //============================================================================ using namespace Javelin; using namespace Javelin::arm64Assembler; //============================================================================ static int64_t cls(int64_t v) { int64_t result; asm("cls %0, %1" : "=r"(result) : "r"(v)); return result; } //============================================================================ SegmentAssembler::SegmentAssembler(JitMemoryManager &aMemoryManager) : memoryManager(aMemoryManager) { buildData.Reserve(8192); } //============================================================================ #if USE_OPTIMIZED_APPEND_INSTRUCTION_DATA __attribute__((naked)) void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s, uint32_t referenceAndDataLength, uint32_t labelData) { // Define JIT_OFFSETOF to avoid compiler warnings on offsetof() #define JIT_OFFSETOF(t,f) (size_t(&((t*)64)->f) - 64) asm volatile(".global __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj"); // Update numberOfLabels, numberOfForwardLabelReferences asm volatile("ldp w6, w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.numberOfLabels))); asm volatile("add w6, w6, w4, uxtb"); asm volatile("add w7, w7, w4, lsr #8"); asm volatile("stp w6, w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.numberOfLabels))); asm volatile("b __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj"); // Definition of AppendInstructionData(blockByteCodeSize, s); asm volatile(".global __ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKh"); asm volatile("__ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKh:"); asm volatile("mov w3, %0" : : "i"(sizeof(AppendAssemblyReference))); // Definition for AppendInstructionData(blockByteCodeSize, s, referenceAndDataLength); asm volatile("__ZN7Javelin16SegmentAssembler21AppendInstructionDataEjPKhj:"); // Update byteCodeSize asm volatile("ldr w5, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.byteCodeSize))); asm volatile("add w5, w5, w1"); asm volatile("str w5, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, aggregateData.byteCodeSize))); // buildData.Append, x5 = offset, x6 = capacity. asm volatile("ldp w5, w6, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData))); asm volatile("add w7, w5, w3"); asm volatile("cmp w7, w6"); asm volatile("b.hi 1f"); asm volatile("str w7, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData))); asm volatile("ldr x0, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data))); asm volatile("add x0, x0, x5"); // Write referenceSize and assemblerData asm volatile("stp x2, x3, [x0]"); asm volatile("ret"); asm volatile("1:"); // Update offset and capacity asm volatile("add w1, w7, w7"); asm volatile("stp w7, w1, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData))); // Update data (inline of JitVectorBase::ExpandAndAppend asm volatile("stp x2, lr, [sp, #-48]!"); asm volatile("stp x0, x3, [sp, #16]"); asm volatile("str x5, [sp, #32]"); asm volatile("ldr x0, [x0, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data))); asm volatile("bl _realloc"); asm volatile("ldr x5, [sp, #32]"); asm volatile("ldp x7, x3, [sp, #16]"); asm volatile("ldp x2, lr, [sp], #48"); asm volatile("str x0, [x7, %0]" : : "i"(JIT_OFFSETOF(Assembler, buildData.data))); asm volatile("add x0, x0, x5"); // Write referenceSize and assemblerData asm volatile("stp x2, x3, [x0]"); asm volatile("ret"); } void* (SegmentAssembler::*volatile reference0)(uint32_t, const uint8_t*, uint32_t, uint32_t); //void* (SegmentAssembler::*volatile reference1)(uint32_t, const uint8_t*, uint32_t); //void (SegmentAssembler::*volatile reference2)(uint32_t, const uint8_t*); __attribute__((constructor)) static void EnsureLinkage() { reference0 = &SegmentAssembler::AppendInstructionData; // reference1 = &SegmentAssembler::AppendInstructionData; // reference2 = &SegmentAssembler::AppendInstructionData; } #else void SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s) { AppendInstructionData(blockByteCodeSize, s, sizeof(AppendAssemblyReference), 0); } void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s, uint32_t referenceAndDataLength) { return AppendInstructionData(blockByteCodeSize, s, referenceAndDataLength, 0); } void* SegmentAssembler::AppendInstructionData(uint32_t blockByteCodeSize, const uint8_t *s, uint32_t referenceAndDataLength, uint32_t labelData) { aggregateData.byteCodeSize += blockByteCodeSize; ProcessLabelData(labelData); AppendAssemblyReference *reference = (AppendAssemblyReference*) buildData.Append(referenceAndDataLength); reference->referenceSize = referenceAndDataLength; reference->assemblerData = s; return reference; } void SegmentAssembler::ProcessLabelData(uint32_t labelData) { int numberOfLabels = labelData & 0xff; int numberOfForwardLabelReferences = labelData >> 8; aggregateData.numberOfLabels += numberOfLabels; aggregateData.numberOfForwardLabelReferences += numberOfForwardLabelReferences; } #endif void* SegmentAssembler::AppendData(uint32_t byteSize) { static constexpr ActionType appendDataActions[2] = { ActionType::DataBlock, ActionType::Return, }; static_assert(sizeof(AppendByteReference) == 16, "Expected AppendByteReference to be 16 bytes"); uint32_t allocationSize = (sizeof(AppendByteReference) + byteSize + 7) & -8; AppendByteReference *reference = (AppendByteReference*) AppendInstructionData(byteSize, (const uint8_t*) &appendDataActions, allocationSize); reference->dataSize = byteSize; return reference + 1; } void SegmentAssembler::AppendDataPointer(const void *data, uint32_t byteSize) { static constexpr ActionType appendDataActions[2] = { ActionType::DataPointer, ActionType::Return, }; AppendDataPointerReference *reference = (AppendDataPointerReference*) AppendInstructionData(byteSize, (const uint8_t*) &appendDataActions, sizeof(AppendDataPointerReference)); reference->dataSize = byteSize; reference->pData = (const uint8_t*) data; } //============================================================================ __attribute__((always_inline)) int32_t SegmentAssembler::ReadSigned16(const uint8_t* &s) { int16_t result; memcpy(&result, s, sizeof(result)); s += sizeof(result); return result; } __attribute__((always_inline)) uint32_t SegmentAssembler::ReadUnsigned16(const uint8_t* &s) { uint16_t result; memcpy(&result, s, sizeof(result)); s += sizeof(result); return result; } __attribute__((always_inline)) uint32_t SegmentAssembler::ReadUnsigned32(const uint8_t* &s) { uint32_t result; memcpy(&result, s, sizeof(result)); s += sizeof(result); return result; } uint32_t SegmentAssembler::LogicalOpcodeValue(uint64_t v) { BitMaskEncodeResult result = EncodeBitMask(v); assert(result.size != 0 && "Unable to encode logical immediate"); uint32_t opcodeValue = result.rotate << 16; if(result.size == 64) opcodeValue |= 1 << 22; uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f; opcodeValue |= imms << 10; return opcodeValue; } void SegmentAssembler::Patch(uint8_t *p, RelEncoding encoding, int64_t delta) { switch(encoding) { case RelEncoding::Rel26: { uint32_t opcode; memcpy(&opcode, p, 4); assert((delta & 3) == 0); delta = opcode + (delta >> 2); opcode = (opcode & ~0x3ffffff) | (delta & 0x3ffffff); memcpy(p, &opcode, 4); } break; case RelEncoding::Rel19Offset5: { uint32_t opcode; memcpy(&opcode, p, 4); assert((delta & 3) == 0); delta = opcode + (uint32_t(delta) << 3); opcode = (opcode & ~0xffffe0) | (delta & 0xffffe0); memcpy(p, &opcode, 4); } break; case RelEncoding::Adrp: { uint64_t current = uint64_t(p) >> 12; uint64_t target = uint64_t(p + delta) >> 12; delta = target - current; } [[fallthrough]]; case RelEncoding::Rel21HiLo: { // struct Opcode // { // uint32_t _dummy0 : 5; // uint32_t offsetHi : 19; // uint32_t _dummy24 : 5; // uint32_t offsetLo : 2; // uint32_t _dummy31 : 1; // }; // // Opcode opcode; // memcpy(&opcode, p, 4); // // uint32_t rel = (opcode.offsetHi << 2) | opcode.offsetLo; // rel += delta; // opcode.offsetLo = rel; // opcode.offsetHi = rel >> 2; // memcpy(p, &opcode, 4); // The compiler does a poor job with the above code. It generates a // constant that is hoisted all the way to the start of // GenerateByteCode, which becomes overhead for every single call. // Attempts to use uint32_t with appropriate shift and masking still do // not result in the desired generated code. // -> Manually code it. It is both shorter and has less register pressure. uint32_t opcode; memcpy(&opcode, p, 4); uint32_t rel; asm volatile("sbfx %w1, %w0, #3, #21 \n\t" "bfxil %w1, %w0, #29, #2 \n\t" "add %w1, %w1, %w2 \n\t" "bfi %w0, %w1, #29, #2 \n\t" "lsr %w1, %w1, #2 \n\t" "bfi %w0, %w1, #5, #19 \n\t" : "+r"(opcode), "=&r"(rel) : "r"(delta)); memcpy(p, &opcode, 4); } break; case RelEncoding::Rel14Offset5: { uint32_t opcode; memcpy(&opcode, p, 4); delta = opcode + (uint32_t(delta) << 3); opcode = (opcode & ~0x7ffe0) | (delta & 0x7ffe0); memcpy(p, &opcode, 4); } break; case RelEncoding::Imm12: { uint32_t opcode; memcpy(&opcode, p, 4); uint32_t rel = (opcode >> 10) & 0xfff; if(int64_t(p) + delta == 0) rel = int32_t(delta); else rel += (int64_t(p) + delta); opcode = (opcode & ~0x3ffc00) | ((rel << 10) & 0x3ffc00); memcpy(p, &opcode, 4); } break; case RelEncoding::Rel64: { int64_t rel; memcpy(&rel, p, 8); rel += delta; memcpy(p, &rel, 8); } break; default: __builtin_unreachable(); } } //============================================================================ void SegmentAssembler::ProcessByteCode() { programStart = (uint8_t*) memoryManager.Allocate(aggregateData.byteCodeSize+4); // +4 is because some actions assume extra buffer. uint8_t *programEnd = GenerateByteCode(programStart); // Shrink allocation memoryManager.EndWrite(programStart); codeSize = uint32_t(programEnd - programStart); assert(codeSize <= aggregateData.byteCodeSize); memoryManager.Shrink(programStart, codeSize); } /** * There is a lot of function call overhead in GenerateBytecode() because a call to memcpy * requires the compiler to preserve all registers. * InlineMemcpy means that no external calls are made, and the compiler can make more use * of scracth registers. */ __attribute__((always_inline)) static void InlineMemcpyAndAdvancePointers(uint8_t* &dest, const uint8_t* &source, uint64_t dataSize) { int64_t scratch; asm volatile(" tst %1, #3 \n\t" " b.eq 2f \n\t" "1: \n\t" " ldrb %w0, [%3], #1 \n\t" " strb %w0, [%2], #1 \n\t" " sub %1, %1, #1 \n\t" " tst %1, #3 \n\t" " b.ne 1b \n\t" "2: \n\t" " tbz %1, #2, 1f \n\t" " ldr %w0, [%3], #4 \n\t" " str %w0, [%2], #4 \n\t" " sub %1, %1, #4 \n\t" "1: \n\t" " tbz %1, #3, 1f \n\t" " ldr %0, [%3], #8 \n\t" " str %0, [%2], #8 \n\t" " sub %1, %1, #8 \n\t" "1: \n\t" " tbz %1, #4, 1f \n\t" " ldr q0, [%3], #16 \n\t" " str q0, [%2], #16 \n\t" " sub %1, %1, #16 \n\t" "1: \n\t" " cbz %1, 2f \n\t" "1: \n\t" " ldp q0, q1, [%3], #32 \n\t" " stp q0, q1, [%2], #32 \n\t" " subs %1, %1, #32 \n\t" " b.ne 1b \n\t" "2: \n\t" : "=&r"(scratch), "+r"(dataSize), "+r"(dest), "+r"(source) : : "v0", "v1", "memory"); } #if USE_GOTO_LABELS #define CASE(x) x #define CONTINUE1(x) do { const uint8_t* pAction = s+x; void *jumpTarget = jumpOffsets[*pAction]; #define CONTINUE2 assert(s == pAction); ++s; goto *jumpTarget; } while(0) #define CONTINUE goto *jumpOffsets[*s++] #else #define CASE(x) case ActionType::x #define CONTINUE1(x) { const uint8_t* pAction = s+x; #define CONTINUE2 assert(s == pAction); continue; } #define CONTINUE continue #endif uint8_t *SegmentAssembler::GenerateByteCode(__restrict uint8_t* p) { #if USE_GOTO_LABELS static constexpr void *jumpOffsets[] = { #define TAG(x) &&x, #include "ActionTypeTags.h" #undef TAG }; #endif const AppendAssemblyReference *blockData = (AppendAssemblyReference*) buildData.begin(); const AppendAssemblyReference *const blockDataEnd = (AppendAssemblyReference*) buildData.end(); const __restrict uint8_t* s = blockData->assemblerData; #if !USE_GOTO_LABELS uint32_t opcodeValue; for(;;) { #endif #if USE_GOTO_LABELS CONTINUE; #else switch((ActionType) *s++) #endif { CASE(Return): blockData = blockData->GetNext(); if(blockData == blockDataEnd) return p; s = blockData->assemblerData; CONTINUE; CASE(Literal4): CONTINUE1(4); memcpy(p, s, 4); p += 4; s += 4; CONTINUE2; CASE(Literal8): CONTINUE1(8); memcpy(p, s, 8); p += 8; s += 8; CONTINUE2; CASE(Literal12): CONTINUE1(12); memcpy(p, s, 16); p += 12; s += 12; CONTINUE2; CASE(Literal16): CONTINUE1(16); memcpy(p, s, 16); p += 16; s += 16; CONTINUE2; CASE(Literal20): CONTINUE1(20); memcpy(p, s, 20); p += 20; s += 20; CONTINUE2; CASE(Literal24): CONTINUE1(24); memcpy(p, s, 24); p += 24; s += 24; CONTINUE2; CASE(Literal28): CONTINUE1(28); memcpy(p, s, 32); p += 28; s += 28; CONTINUE2; CASE(Literal32): CONTINUE1(32); memcpy(p, s, 32); p += 32; s += 32; CONTINUE2; CASE(LiteralBlock): { uint32_t length = ReadUnsigned16(s); InlineMemcpyAndAdvancePointers(p, s, length); CONTINUE; } CASE(Align): { CONTINUE1(1); uint8_t alignmentM1 = *s++; while(size_t(p) & 3) *p++ = 0; while(size_t(p) & alignmentM1) { const uint32_t opcode = 0xd503201f; memcpy(p, &opcode, 4); p += 4; } CONTINUE2; } CASE(Unalign): { CONTINUE1(1); uint8_t alignmentM1 = *s++; assert(alignmentM1 > 3); if(((size_t) p & alignmentM1) == 0) { const uint32_t opcode = 0xd503201f; memcpy(p, &opcode, 4); p += 4; } CONTINUE2; } CASE(Jump): s += *s + 1; CONTINUE; #if USE_GOTO_LABELS { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint32_t opcodeValue; #pragma clang diagnostic pop #endif #ifndef NDEBUG // Masked, unsigned and signed all have the same implementation in release mode, // If asserts are enabled, build 3 separate versions, where unsigned and signed // check the bounds of the provided expression. CASE(MaskedPatchB1Opcode): { int bitMask = *s++; int bitOffset = *s++; int valueShift = *s++; uint8_t value = ReadB1ExpressionValue(s, blockData); opcodeValue = ((value >> valueShift) & bitMask) << bitOffset; goto ProcessPatchOpcode; } CASE(UnsignedPatchB1Opcode): { int bitMask = *s++; int bitOffset = *s++; int valueShift = *s++; uint8_t value = ReadB1ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); assert((value & ~bitMask) == 0); opcodeValue = value >> valueShift << bitOffset; goto ProcessPatchOpcode; } #else CASE(MaskedPatchB1Opcode): CASE(UnsignedPatchB1Opcode): #endif CASE(SignedPatchB1Opcode): { int bitMask = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB1ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert((value & ~bitMask) == 0 || (value | bitMask) == -1); opcodeValue = (value & bitMask) << bitOffset; goto ProcessPatchOpcode; } #ifndef NDEBUG CASE(MaskedPatchB2Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB2ExpressionValue(s, blockData); value >>= valueShift; uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } #else CASE(MaskedPatchB2Opcode): #endif CASE(SignedPatchB2Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB2ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert(value >> numberOfBits == 0 || value >> numberOfBits == -1); uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } #ifndef NDEBUG CASE(MaskedPatchB4Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB4ExpressionValue(s, blockData); value >>= valueShift; uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } #else CASE(MaskedPatchB4Opcode): #endif CASE(SignedPatchB4Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; int32_t value = ReadB4ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert(value >> numberOfBits == 0 || value >> numberOfBits == -1); uint32_t mask = (1 << numberOfBits) - 1; opcodeValue = (value & mask) << bitOffset; goto ProcessPatchOpcode; } CASE(UnsignedPatchB2Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; uint16_t value = ReadB2ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); assert(value >> (numberOfBits + valueShift) == 0); (void) numberOfBits; opcodeValue = value >> valueShift << bitOffset; goto ProcessPatchOpcode; } CASE(UnsignedPatchB4Opcode): { int numberOfBits = *s++; int bitOffset = *s++; int valueShift = *s++; uint32_t value = ReadB4ExpressionValue(s, blockData); assert((value & ((1<<valueShift)-1)) == 0); value >>= valueShift; assert(value >> numberOfBits == 0); (void) numberOfBits; opcodeValue = value << bitOffset; goto ProcessPatchOpcode; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" { uint64_t v; #pragma clang diagnostic pop CASE(LogicalImmediatePatchB4Opcode): { uint32_t value = ReadB4ExpressionValue(s, blockData); v = (uint64_t(value)<<32) | value; goto ProcessPatchLogical; } CASE(LogicalImmediatePatchB8Opcode): v = ReadB8ExpressionValue(s, blockData); ProcessPatchLogical: opcodeValue = LogicalOpcodeValue(v); goto ProcessPatchOpcode; } CASE(RepeatPatchOpcode): ProcessPatchOpcode: { int offset = ReadSigned16(s); uint32_t opcode; memcpy(&opcode, p+offset, 4); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wconditional-uninitialized" opcode |= opcodeValue; #pragma clang diagnostic pop memcpy(p+offset, &opcode, 4); CONTINUE; } #if USE_GOTO_LABELS } #endif CASE(B1Expression): *p++ = ReadB1ExpressionValue(s, blockData); CONTINUE; CASE(B2Expression): { int16_t v = ReadB2ExpressionValue(s, blockData); memcpy(p, &v, sizeof(v)); p += sizeof(v); CONTINUE; } CASE(B4Expression): { int32_t v = ReadB4ExpressionValue(s, blockData); memcpy(p, &v, sizeof(v)); p += sizeof(v); CONTINUE; } CASE(B8Expression): { int64_t v = ReadB8ExpressionValue(s, blockData); memcpy(p, &v, sizeof(v)); p += sizeof(v); CONTINUE; } CASE(DataBlock): { uint32_t dataSize = ((const AppendByteReference*) blockData)->dataSize; const uint8_t *expressionData = (const uint8_t*) blockData + sizeof(AppendByteReference); InlineMemcpyAndAdvancePointers(p, expressionData, dataSize); CONTINUE; } CASE(DataPointer): { uint32_t dataSize = ((const AppendDataPointerReference*) blockData)->dataSize; const uint8_t *pData = ((const AppendDataPointerReference*) blockData)->pData; InlineMemcpyAndAdvancePointers(p, pData, dataSize); CONTINUE; } { // Scope block for v #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint64_t v; #pragma clang diagnostic pop CASE(Imm0B1Condition): v = ReadB1ExpressionValue(s, blockData); goto ProcessImm0Condition; CASE(Imm0B2Condition): v = ReadB2ExpressionValue(s, blockData); goto ProcessImm0Condition; CASE(Imm0B4Condition): v = ReadB4ExpressionValue(s, blockData); goto ProcessImm0Condition; CASE(Imm0B8Condition): v = ReadB8ExpressionValue(s, blockData); ProcessImm0Condition: asm volatile("; This comment prevents the compiler from expanding code inappropriately."); uint32_t offset = *s++; if(v != 0) s += offset; CONTINUE; } CASE(Delta21Condition): { // ADR has 21 bits int64_t v = ReadB8ExpressionValue(s, blockData); uint32_t offset = *s++; int64_t currentP = int64_t(p); int64_t delta = v - currentP; if(cls(delta) < 64-21) s += offset; CONTINUE; } CASE(Delta26x4Condition): { // Direct branches have 26 bits, representing delta*4 int64_t v = ReadB8ExpressionValue(s, blockData); uint32_t offset = *s++; int64_t currentP = int64_t(p); int64_t delta = v - currentP; if((delta & 3) != 0 || cls(delta) < 64-26-2) s += offset; CONTINUE; } CASE(AdrpCondition): { // ADRP has 21 bits uint64_t v = ReadB8ExpressionValue(s, blockData); uint32_t offset = *s++; uint64_t currentP = uint64_t(p); int64_t delta = (v >> 12) - (currentP >> 12); if(cls(delta) < 64-21) s += offset; CONTINUE; } { // Scope block for labelId #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint32_t labelId; #pragma clang diagnostic pop CASE(Label): labelId = ReadUnsigned32(s); goto ProcessLabel; CASE(ExpressionLabel): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); ProcessLabel: asm volatile("; This comment prevents the compiler from expanding code inappropriately."); // Insert into map. labels.Set(labelId, p); JitForwardReferenceMapLookupResult result = unresolvedLabels.Find(labelId); if(result.reference) { JitForwardReferenceData *data = result.reference; JitForwardReferenceData *last; do { Patch(data->p, (RelEncoding) data->data, (intptr_t) p - (intptr_t) data->p); last = data; data = data->next; } while(data); unresolvedLabels.Remove(result, last); } CONTINUE; } { // Scope block for encoding, labelId #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" uint32_t labelId; const uint8_t *target; #pragma clang diagnostic pop CASE(PatchExpression): target = (const uint8_t*) ReadB8ExpressionValue(s, blockData); goto ProcessBackwardTarget; CASE(PatchExpressionLabel): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); goto ProcessPatchLabel; CASE(PatchLabel): labelId = ReadUnsigned32(s); ProcessPatchLabel: target = (const uint8_t*) labels.GetIfExists(labelId); if(target == nullptr) goto ProcessForwardLabel; else goto ProcessBackwardTarget; CASE(PatchLabelForward): labelId = ReadUnsigned32(s); goto ProcessForwardLabel; CASE(PatchExpressionLabelForward): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); ProcessForwardLabel: { JitForwardReferenceData *refData = unresolvedLabels.Add(labelId); RelEncoding encoding = (RelEncoding) *s++; uint8_t *patchAddress = p + ReadSigned16(s); refData->data = (uint32_t) encoding; refData->p = patchAddress; } CONTINUE; CASE(PatchLabelBackward): labelId = ReadUnsigned32(s); goto ProcessBackwardLabel; CASE(PatchExpressionLabelBackward): labelId = GetLabelIdForExpression(ReadB4ExpressionValue(s, blockData)); ProcessBackwardLabel: target = (uint8_t*) labels.Get(labelId); ProcessBackwardTarget: RelEncoding encoding = (RelEncoding) *s++; uint8_t *patchAddress = p + ReadSigned16(s); int64_t delta = target - patchAddress; Patch(patchAddress, encoding, delta); } CONTINUE; // Continue outside variable scope produces better register allocations CASE(PatchAbsoluteAddress): { int offset = ReadSigned16(s); uint64_t v; memcpy(&v, p + offset, 8); v += (uint64_t) p + offset; memcpy(p + offset, &v, 8); CONTINUE; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" { uint32_t opcode; uint64_t value; uint64_t notValue; uint64_t logicalValue; #pragma clang diagnostic pop CASE(MovReg32Expression): opcode = *s++; value = (uint32_t) ReadB4ExpressionValue(s, blockData); notValue = ~uint32_t(value); logicalValue = value | (value << 32); goto ProcessMovExpression; CASE(MovReg64Expression): opcode = *s++ | 0x80000000; value = ReadB8ExpressionValue(s, blockData); notValue = ~value; logicalValue = value; ProcessMovExpression: if((value & 0xffffffffffff0000) == 0) opcode |= 0x52800000 | (value << 5); else if((value & 0xffffffff0000ffff) == 0) opcode |= 0x52a00000 | (value >> 11); else if((notValue & 0xffffffffffff0000) == 0) opcode |= 0x12800000 | (notValue << 5); else if((notValue & 0xffffffff0000ffff) == 0) opcode |= 0x12a00000 | (notValue >> 11); else if((value & 0xffff0000ffffffff) == 0) opcode |= 0x52c00000 | (value >> 27); else if((value & 0x0000ffffffffffff) == 0) opcode |= 0x52e00000 | (value >> 43); else if((notValue & 0xffff0000ffffffff) == 0) opcode |= 0x12c00000 | (notValue >> 27); else if((notValue & 0x0000ffffffffffff) == 0) opcode |= 0x12e00000 | (notValue >> 43); else { BitMaskEncodeResult result = EncodeBitMask(logicalValue); assert(result.size != 0 && "Unable to encode logical immediate"); if(result.size == 64) opcode |= 1 << 22; uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f; opcode |= 0x320003e0 | (result.rotate << 16) | (imms << 10); } memcpy(p, &opcode, 4); p += 4; } CONTINUE; #if !USE_GOTO_LABELS default: assert(!"Unhandled opcode"); #endif } #if !USE_GOTO_LABELS } #endif } //============================================================================ int8_t SegmentAssembler::ReadB1ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); return expressionData[offset]; } int32_t SegmentAssembler::ReadB2ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); int16_t result; memcpy(&result, expressionData + offset, sizeof(result)); return result; } int32_t SegmentAssembler::ReadB4ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); int32_t result; memcpy(&result, expressionData + offset, sizeof(result)); return result; } int64_t SegmentAssembler::ReadB8ExpressionValue(const uint8_t *&s, const AppendAssemblyReference *reference) { const uint8_t *expressionData = (const uint8_t*) reference; uint32_t offset = ReadUnsigned16(s); int64_t result; memcpy(&result, expressionData + offset, sizeof(result)); return result; } //============================================================================ bool SegmentAssembler::IsValidBitmask64(uint64_t value) { return EncodeBitMask(value).size != 0; } //============================================================================ #pragma mark - Assembler //============================================================================ Assembler::Assembler(JitMemoryManager *codeSegmentMemoryManager, JitMemoryManager *dataSegmentMemoryManager) : SegmentAssembler(*codeSegmentMemoryManager) { if(dataSegmentMemoryManager) { hasDataSegment = true; new(&dataSegment) SegmentAssembler(*dataSegmentMemoryManager); } } Assembler::~Assembler() { if(hasDataSegment) dataSegment.~SegmentAssembler(); } __attribute__((flatten)) void* Assembler::Build() { if(hasDataSegment) { uint32_t numberOfLabels = aggregateData.numberOfLabels + dataSegment.aggregateData.numberOfLabels; uint32_t numberOfForwardLabelReferences = aggregateData.numberOfForwardLabelReferences + dataSegment.aggregateData.numberOfForwardLabelReferences; labels.Reserve(numberOfLabels); unresolvedLabels.Reserve(numberOfForwardLabelReferences); dataSegment.labels.StartUseBacking(labels); dataSegment.unresolvedLabels.StartUseBacking(unresolvedLabels); dataSegment.ProcessByteCode(); dataSegment.labels.StopUseBacking(labels); dataSegment.unresolvedLabels.StopUseBacking(unresolvedLabels); } else { labels.Reserve(aggregateData.numberOfLabels); unresolvedLabels.Reserve(aggregateData.numberOfForwardLabelReferences); } ProcessByteCode(); assert(!unresolvedLabels.HasData() && "Not all references have been resolved"); return programStart; } //============================================================================ #endif // defined(__arm64__) //============================================================================
30.862385
148
0.647113
ddc72e086394b9020cfa8da295a9b09421540bdb
1,203
cpp
C++
Lab1_String_Class_Concepts/program2/functions.cpp
sanatRR/Data-Structures-ICT
c87f52987b3449ad902ffb1b37c198a0a50d480a
[ "MIT" ]
1
2021-07-07T14:38:08.000Z
2021-07-07T14:38:08.000Z
Lab1_String_Class_Concepts/program2/functions.cpp
sanatRR/Data-Structures-ICT
c87f52987b3449ad902ffb1b37c198a0a50d480a
[ "MIT" ]
null
null
null
Lab1_String_Class_Concepts/program2/functions.cpp
sanatRR/Data-Structures-ICT
c87f52987b3449ad902ffb1b37c198a0a50d480a
[ "MIT" ]
null
null
null
//Copyright (c) 2021 Sanat Raorane #include<iostream> #include"student.h" using namespace std; void student::read(student arrayA[],int num){ for(int i=0;i<num;i++){ cout<<"\n\n"; //Lines for spacing cout<<"Enter details for student "<<(i+1)<<endl; cout<<"Enter Name:"<<endl; cin.sync(); cin.get(arrayA[i].name,50); cout<<"Enter roll-number:"<<endl; cin>>arrayA[i].rollNo; cout<<"Enter grade:"<<endl; cin.sync(); cin>>arrayA[i].grade; } } void student::display(student arrayA[],int num){ cout<<"\n\n\n"; //lines for spacing for(int i=0;i<num;i++){ cout<<"The details for roll no "<<arrayA[i].rollNo<<" are"<<endl; cout<<"Name: "<<arrayA[i].name<<endl; cout<<"Grade: "<<arrayA[i].grade<<endl; } } void student::sortArr(student arrayA[],int num){ student temp; /* *Using Bubble Sort */ for(int i=0;i<num-1;i++){ for(int j=0;j<num-i-1;j++){ if(arrayA[j].rollNo>arrayA[j+1].rollNo){ temp=arrayA[j]; arrayA[j]=arrayA[j+1]; arrayA[j+1]=temp; } } } }
26.152174
73
0.512884
ddc7df328a0a0fc63c0eb711853554763af5474b
26,301
cpp
C++
keymaster/authorization_set_test.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
9
2017-11-10T15:54:02.000Z
2021-04-15T20:57:29.000Z
keymaster/authorization_set_test.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
null
null
null
keymaster/authorization_set_test.cpp
Keneral/asystem
df12381b72ef3d629c8efc61100cc8c714195320
[ "Unlicense" ]
7
2018-01-08T02:53:32.000Z
2020-10-15T13:01:46.000Z
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <keymaster/authorization_set.h> #include <keymaster/android_keymaster_utils.h> #include "android_keymaster_test_utils.h" namespace keymaster { namespace test { TEST(Construction, ListProvided) { keymaster_key_param_t params[] = { Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY), Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA), Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD), Authorization(TAG_APPLICATION_ID, "my_app", 6), Authorization(TAG_KEY_SIZE, 256), Authorization(TAG_AUTH_TIMEOUT, 300), }; AuthorizationSet set(params, array_length(params)); EXPECT_EQ(8U, set.size()); } TEST(Construction, Copy) { keymaster_key_param_t params[] = { Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY), Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA), Authorization(TAG_USER_ID, 7), Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD), Authorization(TAG_APPLICATION_ID, "my_app", 6), Authorization(TAG_KEY_SIZE, 256), Authorization(TAG_AUTH_TIMEOUT, 300), }; AuthorizationSet set(params, array_length(params)); AuthorizationSet set2(set); EXPECT_EQ(set, set2); } TEST(Construction, NullProvided) { keymaster_key_param_t params[] = { Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN), Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY), }; AuthorizationSet set1(params, 0); EXPECT_EQ(0U, set1.size()); EXPECT_EQ(AuthorizationSet::OK, set1.is_valid()); AuthorizationSet set2(reinterpret_cast<keymaster_key_param_t*>(NULL), array_length(params)); EXPECT_EQ(0U, set2.size()); EXPECT_EQ(AuthorizationSet::OK, set2.is_valid()); } TEST(Lookup, NonRepeated) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); EXPECT_EQ(8U, set.size()); int pos = set.find(TAG_ALGORITHM); ASSERT_NE(-1, pos); EXPECT_EQ(KM_TAG_ALGORITHM, set[pos].tag); EXPECT_EQ(KM_ALGORITHM_RSA, set[pos].enumerated); pos = set.find(TAG_MAC_LENGTH); EXPECT_EQ(-1, pos); uint32_t int_val = 0; EXPECT_TRUE(set.GetTagValue(TAG_USER_ID, &int_val)); EXPECT_EQ(7U, int_val); keymaster_blob_t blob_val; EXPECT_TRUE(set.GetTagValue(TAG_APPLICATION_ID, &blob_val)); EXPECT_EQ(6U, blob_val.data_length); EXPECT_EQ(0, memcmp(blob_val.data, "my_app", 6)); } TEST(Lookup, Repeated) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_SECURE_ID, 47727) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); EXPECT_EQ(9U, set.size()); int pos = set.find(TAG_PURPOSE); ASSERT_FALSE(pos == -1); EXPECT_EQ(KM_TAG_PURPOSE, set[pos].tag); EXPECT_EQ(KM_PURPOSE_SIGN, set[pos].enumerated); pos = set.find(TAG_PURPOSE, pos); EXPECT_EQ(KM_TAG_PURPOSE, set[pos].tag); EXPECT_EQ(KM_PURPOSE_VERIFY, set[pos].enumerated); EXPECT_EQ(-1, set.find(TAG_PURPOSE, pos)); pos = set.find(TAG_USER_SECURE_ID, pos); EXPECT_EQ(KM_TAG_USER_SECURE_ID, set[pos].tag); EXPECT_EQ(47727U, set[pos].long_integer); } TEST(Lookup, Indexed) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); EXPECT_EQ(8U, set.size()); EXPECT_EQ(KM_TAG_PURPOSE, set[0].tag); EXPECT_EQ(KM_PURPOSE_SIGN, set[0].enumerated); // Lookup beyond end doesn't work, just returns zeros, but doens't blow up either (verify by // running under valgrind). EXPECT_EQ(KM_TAG_INVALID, set[10].tag); } TEST(Serialization, RoundTrip) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_USER_SECURE_ID, 47727) .Authorization(TAG_AUTH_TIMEOUT, 300) .Authorization(TAG_ALL_USERS) .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3) .Authorization(TAG_ACTIVE_DATETIME, 10)); size_t size = set.SerializedSize(); EXPECT_TRUE(size > 0); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); AuthorizationSet deserialized(buf.get(), size); EXPECT_EQ(AuthorizationSet::OK, deserialized.is_valid()); EXPECT_EQ(set, deserialized); int pos = deserialized.find(TAG_APPLICATION_ID); ASSERT_NE(-1, pos); EXPECT_EQ(KM_TAG_APPLICATION_ID, deserialized[pos].tag); EXPECT_EQ(6U, deserialized[pos].blob.data_length); EXPECT_EQ(0, memcmp(deserialized[pos].blob.data, "my_app", 6)); } TEST(Deserialization, Deserialize) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); size_t size = set.SerializedSize(); EXPECT_TRUE(size > 0); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); AuthorizationSet deserialized; const uint8_t* p = buf.get(); EXPECT_TRUE(deserialized.Deserialize(&p, p + size)); EXPECT_EQ(p, buf.get() + size); EXPECT_EQ(AuthorizationSet::OK, deserialized.is_valid()); EXPECT_EQ(set.size(), deserialized.size()); for (size_t i = 0; i < set.size(); ++i) { EXPECT_EQ(set[i].tag, deserialized[i].tag); } int pos = deserialized.find(TAG_APPLICATION_ID); ASSERT_NE(-1, pos); EXPECT_EQ(KM_TAG_APPLICATION_ID, deserialized[pos].tag); EXPECT_EQ(6U, deserialized[pos].blob.data_length); EXPECT_EQ(0, memcmp(deserialized[pos].blob.data, "my_app", 6)); } TEST(Deserialization, TooShortBuffer) { uint8_t buf[] = {0, 0, 0}; AuthorizationSet deserialized(buf, array_length(buf)); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); const uint8_t* p = buf; EXPECT_FALSE(deserialized.Deserialize(&p, p + array_length(buf))); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); } TEST(Deserialization, InvalidLengthField) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300)); size_t size = set.SerializedSize(); EXPECT_TRUE(size > 0); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); *reinterpret_cast<uint32_t*>(buf.get()) = 9; AuthorizationSet deserialized(buf.get(), size); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); const uint8_t* p = buf.get(); EXPECT_FALSE(deserialized.Deserialize(&p, p + size)); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized.is_valid()); } static uint32_t read_uint32(const uint8_t* buf) { uint32_t val; memcpy(&val, buf, sizeof(val)); return val; } static void add_to_uint32(uint8_t* buf, int delta) { uint32_t val; memcpy(&val, buf, sizeof(val)); val += delta; memcpy(buf, &val, sizeof(val)); } TEST(Deserialization, MalformedIndirectData) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_APPLICATION_DATA, "foo", 3)); size_t size = set.SerializedSize(); UniquePtr<uint8_t[]> buf(new uint8_t[size]); EXPECT_EQ(buf.get() + size, set.Serialize(buf.get(), buf.get() + size)); // This sucks. This test, as written, requires intimate knowledge of the serialized layout of // this particular set, which means it's brittle. But it's important to test that we handle // broken serialized data and I can't think of a better way to write this. // // The contents of buf are: // // Bytes: Content: // 0-3 Length of string data, which is 9. // 4-9 "my_app" // 10-12 "foo" // 13-16 Number of elements, which is 2. // 17-20 Length of elements, which is 24. // 21-24 First tag, TAG_APPLICATION_ID // 25-28 Length of string "my_app", 6 // 29-32 Offset of string "my_app", 0 // 33-36 Second tag, TAG_APPLICATION_DATA // 37-40 Length of string "foo", 3 // 41-44 Offset of string "foo", 6 // Check that stuff is where we think. EXPECT_EQ('m', buf[4]); EXPECT_EQ('f', buf[10]); // Length of "my_app" EXPECT_EQ(6U, read_uint32(buf.get() + 25)); // Offset of "my_app" EXPECT_EQ(0U, read_uint32(buf.get() + 29)); // Length of "foo" EXPECT_EQ(3U, read_uint32(buf.get() + 37)); // Offset of "foo" EXPECT_EQ(6U, read_uint32(buf.get() + 41)); // Check that deserialization works. AuthorizationSet deserialized1(buf.get(), size); EXPECT_EQ(AuthorizationSet::OK, deserialized1.is_valid()); const uint8_t* p = buf.get(); EXPECT_TRUE(deserialized1.Deserialize(&p, p + size)); EXPECT_EQ(AuthorizationSet::OK, deserialized1.is_valid()); // // Now mess them up in various ways: // // Move "foo" offset so offset + length goes off the end add_to_uint32(buf.get() + 41, 1); AuthorizationSet deserialized2(buf.get(), size); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized2.is_valid()); add_to_uint32(buf.get() + 41, -1); // Shorten the "my_app" length to make a gap between the blobs. add_to_uint32(buf.get() + 25, -1); AuthorizationSet deserialized3(buf.get(), size); EXPECT_EQ(AuthorizationSet::MALFORMED_DATA, deserialized3.is_valid()); add_to_uint32(buf.get() + 25, 1); // Extend the "my_app" length to make them overlap, and decrease the "foo" length to keep the // total length the same. We don't detect this but should. // TODO(swillden): Detect overlaps and holes that leave total size correct. add_to_uint32(buf.get() + 25, 1); add_to_uint32(buf.get() + 37, -1); AuthorizationSet deserialized4(buf.get(), size); EXPECT_EQ(AuthorizationSet::OK, deserialized4.is_valid()); } TEST(Growable, SuccessfulRoundTrip) { AuthorizationSet growable; EXPECT_TRUE(growable.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA))); EXPECT_EQ(1U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY))); EXPECT_EQ(2U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN))); EXPECT_EQ(3U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_ID, "data", 4))); EXPECT_EQ(4U, growable.size()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_DATA, "some more data", 14))); EXPECT_EQ(5U, growable.size()); size_t serialize_size = growable.SerializedSize(); UniquePtr<uint8_t[]> serialized(new uint8_t[serialize_size]); EXPECT_EQ(serialized.get() + serialize_size, growable.Serialize(serialized.get(), serialized.get() + serialize_size)); AuthorizationSet deserialized(serialized.get(), serialize_size); EXPECT_EQ(growable, deserialized); } TEST(Growable, InsufficientElemBuf) { AuthorizationSet growable; EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); // First insertion fits. EXPECT_TRUE(growable.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA))); EXPECT_EQ(1U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); // Second does too. EXPECT_TRUE(growable.push_back(Authorization(TAG_RSA_PUBLIC_EXPONENT, 3))); EXPECT_EQ(2U, growable.size()); } TEST(Growable, InsufficientIndirectBuf) { AuthorizationSet growable; EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); EXPECT_TRUE(growable.push_back(Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA))); EXPECT_EQ(1U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_ID, "1234567890", 10))); EXPECT_EQ(2U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); EXPECT_TRUE(growable.push_back(Authorization(TAG_APPLICATION_DATA, "1", 1))); EXPECT_EQ(3U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); // Can still add another entry without indirect data. Now it's full. EXPECT_TRUE(growable.push_back(Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN))); EXPECT_EQ(4U, growable.size()); EXPECT_EQ(AuthorizationSet::OK, growable.is_valid()); } TEST(Growable, PushBackSets) { AuthorizationSetBuilder builder; builder.Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_KEY_SIZE, 256) .Authorization(TAG_AUTH_TIMEOUT, 300); AuthorizationSet set1(builder.build()); AuthorizationSet set2(builder.build()); AuthorizationSet combined; EXPECT_TRUE(combined.push_back(set1)); EXPECT_TRUE(combined.push_back(set2)); EXPECT_EQ(set1.size() + set2.size(), combined.size()); EXPECT_EQ(12U, combined.indirect_size()); } TEST(GetValue, GetInt) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); uint32_t val; EXPECT_TRUE(set.GetTagValue(TAG_USER_ID, &val)); EXPECT_EQ(7U, val); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_KEY_SIZE, &val)); } TEST(GetValue, GetLong) { AuthorizationSet set1(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)); AuthorizationSet set2(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)); uint64_t val; EXPECT_TRUE(set1.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &val)); EXPECT_EQ(3U, val); // Find one that isn't there EXPECT_FALSE(set2.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &val)); } TEST(GetValue, GetLongRep) { AuthorizationSet set1(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_SECURE_ID, 8338) .Authorization(TAG_USER_SECURE_ID, 4334) .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)); AuthorizationSet set2(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)); uint64_t val; EXPECT_TRUE(set1.GetTagValue(TAG_USER_SECURE_ID, 0, &val)); EXPECT_EQ(8338U, val); EXPECT_TRUE(set1.GetTagValue(TAG_USER_SECURE_ID, 1, &val)); EXPECT_EQ(4334U, val); // Find one that isn't there EXPECT_FALSE(set2.GetTagValue(TAG_USER_SECURE_ID, &val)); } TEST(GetValue, GetEnum) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); keymaster_algorithm_t val; EXPECT_TRUE(set.GetTagValue(TAG_ALGORITHM, &val)); EXPECT_EQ(KM_ALGORITHM_RSA, val); // Find one that isn't there keymaster_padding_t val2; EXPECT_FALSE(set.GetTagValue(TAG_PADDING, &val2)); } TEST(GetValue, GetEnumRep) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); keymaster_purpose_t val; EXPECT_TRUE(set.GetTagValue(TAG_PURPOSE, 0, &val)); EXPECT_EQ(KM_PURPOSE_SIGN, val); EXPECT_TRUE(set.GetTagValue(TAG_PURPOSE, 1, &val)); EXPECT_EQ(KM_PURPOSE_VERIFY, val); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_PURPOSE, 2, &val)); } TEST(GetValue, GetDate) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); uint64_t val; EXPECT_TRUE(set.GetTagValue(TAG_ACTIVE_DATETIME, &val)); EXPECT_EQ(10U, val); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_USAGE_EXPIRE_DATETIME, &val)); } TEST(GetValue, GetBlob) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_SIGN) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD) .Authorization(TAG_APPLICATION_ID, "my_app", 6) .Authorization(TAG_AUTH_TIMEOUT, 300)); keymaster_blob_t val; EXPECT_TRUE(set.GetTagValue(TAG_APPLICATION_ID, &val)); EXPECT_EQ(6U, val.data_length); EXPECT_EQ(0, memcmp(val.data, "my_app", 6)); // Find one that isn't there EXPECT_FALSE(set.GetTagValue(TAG_APPLICATION_DATA, &val)); } TEST(Deduplication, NoDuplicates) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); EXPECT_EQ(copy.size(), set.size()); // Sets no longer compare equal, because of ordering (ugh, maybe it should be // AuthorizationList, not AuthorizationSet). EXPECT_NE(copy, set); } TEST(Deduplication, NoDuplicatesHasInvalid) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_INVALID) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); // Deduplicate should have removed the invalid. EXPECT_EQ(copy.size() - 1, set.size()); EXPECT_NE(copy, set); } TEST(Deduplication, DuplicateEnum) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); EXPECT_EQ(copy.size() - 2, set.size()); EXPECT_NE(copy, set); } TEST(Deduplication, DuplicateBlob) { AuthorizationSet set(AuthorizationSetBuilder() .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_ACTIVE_DATETIME, 10) .Authorization(TAG_APPLICATION_DATA, "data", 4) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_USER_ID, 7) .Authorization(TAG_PURPOSE, KM_PURPOSE_VERIFY) .Authorization(TAG_APPLICATION_DATA, "data", 4) .Authorization(TAG_APPLICATION_DATA, "foo", 3) .Authorization(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD)); AuthorizationSet copy(set); EXPECT_EQ(copy, set); set.Deduplicate(); EXPECT_EQ(copy.size() - 3, set.size()); EXPECT_NE(copy, set); // The real test here is that valgrind reports no leak. } } // namespace test } // namespace keymaster
41.681458
99
0.63393
ddcb34f1d4f4a1b84dff19e87cc67b491ab0c5af
264
cc
C++
source/skyline/solution_unittest.cc
Yang-33/SpatialSkylineQueries-on-TIN
82b828ccc5fe1e772fbfa04627cf6a8d8d69aaa1
[ "MIT" ]
null
null
null
source/skyline/solution_unittest.cc
Yang-33/SpatialSkylineQueries-on-TIN
82b828ccc5fe1e772fbfa04627cf6a8d8d69aaa1
[ "MIT" ]
null
null
null
source/skyline/solution_unittest.cc
Yang-33/SpatialSkylineQueries-on-TIN
82b828ccc5fe1e772fbfa04627cf6a8d8d69aaa1
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <vector> // See main.cc TEST(SolutionTest, NaiveAndFast) { std::vector<int> a{1, 2, 3}; std::vector<int> b{1, 2, 3}; ASSERT_EQ(a.size(), b.size()); for (size_t i = 0; i < a.size(); ++i) { EXPECT_EQ(a[i], b[i]); } }
20.307692
41
0.568182
ddcca0f40ab90bb6e024256380939f74eaa3a966
2,393
cpp
C++
scisim/ConstrainedMaps/FrictionMaps/FrictionOperator.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
scisim/ConstrainedMaps/FrictionMaps/FrictionOperator.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
scisim/ConstrainedMaps/FrictionMaps/FrictionOperator.cpp
Lyestria/scisim
e2c2abc8d38ea9b07717841782c5c723fce37ce5
[ "Apache-2.0" ]
null
null
null
// FrictionOperator.cpp // // Breannan Smith // Last updated: 09/22/2015 #include "FrictionOperator.h" #include "scisim/Constraints/Constraint.h" FrictionOperator::~FrictionOperator() {} // TODO: Despecialize from smooth void FrictionOperator::formGeneralizedSmoothFrictionBasis( const unsigned ndofs, const unsigned ncons, const VectorXs& q, const std::vector<std::unique_ptr<Constraint>>& K, const MatrixXXsc& bases, SparseMatrixsc& D ) { assert( ncons == K.size() ); const unsigned nambientdims{ static_cast<unsigned>( bases.rows() ) }; const unsigned nsamples{ nambientdims - 1 }; D.resize( ndofs, nsamples * ncons ); auto itr = K.cbegin(); { VectorXi column_nonzeros( D.cols() ); for( unsigned collision_number = 0; collision_number < ncons; ++collision_number ) { for( unsigned sample_number = 0; sample_number < nsamples; ++sample_number ) { assert( nsamples * collision_number + sample_number < column_nonzeros.size() ); column_nonzeros( nsamples * collision_number + sample_number ) = (*itr)->frictionStencilSize(); } ++itr; } assert( ( column_nonzeros.array() > 0 ).all() ); assert( itr == K.cend() ); D.reserve( column_nonzeros ); } itr = K.cbegin(); for( unsigned collision_number = 0; collision_number < ncons; ++collision_number ) { for( unsigned sample_number = 0; sample_number < nsamples; ++sample_number ) { const unsigned current_column{ nsamples * collision_number + sample_number }; const VectorXs current_sample{ bases.col( nambientdims * collision_number + sample_number + 1 ) }; assert( fabs( current_sample.dot( bases.col( nambientdims * collision_number ) ) ) <= 1.0e-6 ); (*itr)->computeGeneralizedFrictionGivenTangentSample( q, current_sample, current_column, D ); } ++itr; } assert( itr == K.cend() ); D.prune( []( const Eigen::Index& row, const Eigen::Index& col, const scalar& value ) { return value != 0.0; } ); assert( D.innerNonZeroPtr() == nullptr ); } #include <iostream> void FrictionOperator::formGeneralizedFrictionBasis( const VectorXs& q, const VectorXs& v, const std::vector<std::unique_ptr<Constraint>>& K, SparseMatrixsc& D, VectorXs& drel ) { std::cerr << "Deprecated method FrictionOperator::formGeneralizedFrictionBasis not implemented for " << name() << std::endl; std::exit( EXIT_FAILURE ); }
36.815385
217
0.689929
ddce127677fce6623d4d0bced04fc24d66d7e2a1
242
hpp
C++
src/main/Input/Input.hpp
ramp-eu/AGILPLAS
b2ae7a234859d758dbc6c8a876329a4060c53bd1
[ "Apache-2.0" ]
null
null
null
src/main/Input/Input.hpp
ramp-eu/AGILPLAS
b2ae7a234859d758dbc6c8a876329a4060c53bd1
[ "Apache-2.0" ]
5
2021-05-28T15:17:38.000Z
2021-06-15T10:04:29.000Z
src/main/Input/Input.hpp
ramp-eu/AGILPLAS
b2ae7a234859d758dbc6c8a876329a4060c53bd1
[ "Apache-2.0" ]
1
2021-05-31T14:39:14.000Z
2021-05-31T14:39:14.000Z
#ifndef INPUT_H_INCLUDED #define INPUT_H_INCLUDED class Input { private: int reference; String alias; public: Input(int reference, String alias); int getReference(); String getAlias(); void serialPrint(); }; #endif
13.444444
39
0.690083
ddd09e71ba385f83682379de1e163d780b5bbfbb
515
cpp
C++
solved/o-q/odd-sum/odd.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/o-q/odd-sum/odd.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/o-q/odd-sum/odd.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> int a, b; int sum(int lo, int hi) { if (lo < 1) lo = 1; if (lo > hi) return 0; if (lo == hi) return lo; return (hi*(hi+1) - (lo-1)*lo)/2; } int solve() { int x = a % 2 == 0 ? a / 2 : (a - 1) / 2; int y = b % 2 == 0 ? b / 2 - 1 : (b - 1) / 2; return sum(x, y)*2 + y - x + 1; } int main() { int T; scanf("%d", &T); int ncase = 0; while (T--) { scanf("%d%d", &a, &b); printf("Case %d: %d\n", ++ncase, solve()); } return 0; }
15.147059
50
0.4
ddd1d520109b5d536a00417fab5cb54c369f7a74
4,524
cpp
C++
src/main/c++/TestAPI/testMemIO.cpp
yildiz-online/component-native-freeimage
cb329c74ebe0aa16d8349a213e1e4b95204fce58
[ "MIT" ]
null
null
null
src/main/c++/TestAPI/testMemIO.cpp
yildiz-online/component-native-freeimage
cb329c74ebe0aa16d8349a213e1e4b95204fce58
[ "MIT" ]
1
2018-11-19T19:12:58.000Z
2018-11-19T19:12:58.000Z
src/main/c++/TestAPI/testMemIO.cpp
yildiz-online/component-native-freeimage
cb329c74ebe0aa16d8349a213e1e4b95204fce58
[ "MIT" ]
null
null
null
// ========================================================== // FreeImage 3 Test Script // // Design and implementation by // - Herv� Drolon (drolon@infonie.fr) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "TestSuite.h" void testSaveMemIO(const char *lpszPathName) { FIMEMORY *hmem = NULL; // load a regular file FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName); FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, 0); // open a memory handle hmem = FreeImage_OpenMemory(); // save the file to memory FreeImage_SaveToMemory(fif, dib, hmem, 0); // at this point, hmem contains the entire FREE_IMAGE_FORMAT data in memory. // the amount of space used by the memory is equal to file_size FreeImage_SeekMemory(hmem, 0, SEEK_END); long file_size = FreeImage_TellMemory(hmem); printf("File size : %ld\n", file_size); // its easy load an image from memory as well // seek to the start of the memory stream FreeImage_SeekMemory(hmem, 0L, SEEK_SET); // get the file type FREE_IMAGE_FORMAT mem_fif = FreeImage_GetFileTypeFromMemory(hmem, 0); // load an image from the memory handle FIBITMAP *check = FreeImage_LoadFromMemory(mem_fif, hmem, 0); // save as a regular file FreeImage_Save(FIF_PNG, check, "dump.png", PNG_DEFAULT); // make sure to free the data since FreeImage_SaveToMemory // will cause it to be malloc'd FreeImage_CloseMemory(hmem); FreeImage_Unload(check); FreeImage_Unload(dib); } //you could also have image data in memory via some other method, and just set //fmh.data to point to it, and set both fmh.datalen and fmh.filelen to the //size of that data, then FreeImage_LoadFromMemory could load the image from that memory void testLoadMemIO(const char *lpszPathName) { struct stat buf; int result; // get data associated with lpszPathName result = stat(lpszPathName, &buf); if(result == 0) { // allocate a memory buffer and load temporary data BYTE *mem_buffer = (BYTE*)malloc(buf.st_size * sizeof(BYTE)); if(mem_buffer) { FILE *stream = fopen(lpszPathName, "rb"); if(stream) { fread(mem_buffer, sizeof(BYTE), buf.st_size, stream); fclose(stream); // attach the binary data to a memory stream FIMEMORY *hmem = FreeImage_OpenMemory(mem_buffer, buf.st_size); // get the file type FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(hmem, 0); // load an image from the memory stream FIBITMAP *check = FreeImage_LoadFromMemory(fif, hmem, PNG_DEFAULT); // save as a regular file FreeImage_Save(FIF_PNG, check, "blob.png", PNG_DEFAULT); FreeImage_Unload(check); // close the stream FreeImage_CloseMemory(hmem); } } // user is responsible for freeing the data free(mem_buffer); } } void testAcquireMemIO(const char *lpszPathName) { FIMEMORY *hmem = NULL; // load a regular file FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName); FIBITMAP *dib = FreeImage_Load(fif, lpszPathName, 0); // open and allocate a memory stream hmem = FreeImage_OpenMemory(); // save the file to memory FreeImage_SaveToMemory(FIF_PNG, dib, hmem, PNG_DEFAULT); FreeImage_Unload(dib); // get the buffer from the memory stream BYTE *mem_buffer = NULL; DWORD size_in_bytes = 0; FreeImage_AcquireMemory(hmem, &mem_buffer, &size_in_bytes); // save the buffer in a file stream FILE *stream = fopen("buffer.png", "wb"); if(stream) { fwrite(mem_buffer, sizeof(BYTE), size_in_bytes, stream); fclose(stream); } // close and free the memory stream FreeImage_CloseMemory(hmem); } void testMemIO(const char *lpszPathName) { printf("testMemIO ...\n"); testSaveMemIO(lpszPathName); testLoadMemIO(lpszPathName); testAcquireMemIO(lpszPathName); }
30.362416
89
0.715075
ddd40ffa25cb716b4e26db8746e71abad6f85a73
3,167
cpp
C++
sniper/pico/Response.cpp
rtbtech/libsniper
0828df9da74f8ed11a1273c61c15dfb5816c3c1e
[ "Apache-2.0" ]
9
2020-05-08T21:17:12.000Z
2021-06-04T18:38:35.000Z
sniper/pico/Response.cpp
rtbtech/libsniper
0828df9da74f8ed11a1273c61c15dfb5816c3c1e
[ "Apache-2.0" ]
null
null
null
sniper/pico/Response.cpp
rtbtech/libsniper
0828df9da74f8ed11a1273c61c15dfb5816c3c1e
[ "Apache-2.0" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com /* * Copyright (c) 2018 - 2019, MetaHash, Oleg Romanenko (oleg@romanenko.ro) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sniper/pico/picohttpparser.h> #include <sniper/strings/ascii_case.h> #include <sniper/strings/atoi.h> #include "Response.h" namespace sniper::pico { void Response::clear() noexcept { status = -1; header_size = 0; content_length = 0; keep_alive = false; headers.clear(); } ParseResult Response::parse(char* data, size_t size) noexcept { if (!data || !size) return ParseResult::Err; if (size < 5) return ParseResult::Partial; struct phr_header pico_headers[MAX_HEADERS]; size_t num_headers = sizeof(pico_headers) / sizeof(headers[0]); int pico_minor_version = -1; const char* msg = nullptr; size_t msg_len = 0; int ssize = phr_parse_response(data, size, &pico_minor_version, &status, &msg, &msg_len, pico_headers, &num_headers, 0); if (ssize > 0) { header_size = ssize; if (pico_minor_version == 1) keep_alive = true; bool content_length_found = false; bool connection_found = false; for (unsigned i = 0; i < num_headers; i++) { strings::to_lower_ascii(const_cast<char*>(pico_headers[i].name), pico_headers[i].name_len); strings::to_lower_ascii(const_cast<char*>(pico_headers[i].value), pico_headers[i].value_len); string_view key(pico_headers[i].name, pico_headers[i].name_len); string_view val(pico_headers[i].value, pico_headers[i].value_len); // content-length if (!content_length_found && key == "content-length") { content_length_found = true; if (auto len = strings::fast_atoi64(val); len) content_length = *len; else return ParseResult::Err; } // connection if (!connection_found && key == "connection") { connection_found = true; if (pico_minor_version == 0 && val == "keep-alive") keep_alive = true; else if (val == "close") keep_alive = false; } headers.emplace_back(key, val); } return ParseResult::Complete; } else if (ssize == -2) { return ParseResult::Partial; } else { return ParseResult::Err; } } } // namespace sniper::pico
30.747573
116
0.616672
ddd4d5ab025307843be0b62229c0d85036cf370d
582
cpp
C++
Notes_Week2/multipleInput.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
1
2019-01-06T22:36:01.000Z
2019-01-06T22:36:01.000Z
Notes_Week2/multipleInput.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
Notes_Week2/multipleInput.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
/********************************************************************* ** Author: Wei-Chien Hsu ** Date: 04/09/18 ** Description: Asks the user enters width and height, and output the Area. *********************************************************************/ #include <iostream> using namespace std; int main() { float width, height; int area; cout << "Please enters the width and height (in float): " << endl; cin >> width >> height; area = static_cast<int>(width * height); cout << "The area is : " << area << endl; return 0; }
27.714286
70
0.450172
ddd720b0fcd290ae56e957915fd210698ee5186e
5,636
cpp
C++
main01_c.cpp
mlytle4218/ffmpeg-tutorial
5ff665e60f14f366c7334a48e57caffbac48e0bf
[ "OML" ]
null
null
null
main01_c.cpp
mlytle4218/ffmpeg-tutorial
5ff665e60f14f366c7334a48e57caffbac48e0bf
[ "OML" ]
null
null
null
main01_c.cpp
mlytle4218/ffmpeg-tutorial
5ff665e60f14f366c7334a48e57caffbac48e0bf
[ "OML" ]
null
null
null
// tutorial02.c // A pedagogical video player that will stream through every video frame as fast as it can. // // Code based on FFplay, Copyright (c) 2003 Fabrice Bellard, // and a tutorial by Martin Bohme (boehme@inb.uni-luebeckREMOVETHIS.de) // Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1 // With updates from https://github.com/chelyaev/ffmpeg-tutorial // Updates tested on: // LAVC 54.59.100, LAVF 54.29.104, LSWS 2.1.101, SDL 1.2.15 // on GCC 4.7.2 in Debian February 2015 // // Use // // gcc -o tutorial02 tutorial02.c -lavformat -lavcodec -lswscale -lz -lm `sdl-config --cflags --libs` // to build (assuming libavformat and libavcodec are correctly installed, // and assuming you have sdl-config. Please refer to SDL docs for your installation.) // // Run using // tutorial02 myvideofile.mpg // // to play the video stream on your screen. #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <SDL.h> #include <SDL_thread.h> #ifdef __MINGW32__ #undef main /* Prevents SDL from overriding main() */ #endif #include <stdio.h> // compatibility with newer API #if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1) #define av_frame_alloc avcodec_alloc_frame #define av_frame_free avcodec_free_frame #endif int main(int argc, char *argv[]) { AVFormatContext *pFormatCtx = NULL; int i, videoStream; AVCodecContext *pCodecCtxOrig = NULL; AVCodecContext *pCodecCtx = NULL; AVCodec *pCodec = NULL; AVFrame *pFrame = NULL; AVPacket packet; int frameFinished; float aspect_ratio; struct SwsContext *sws_ctx = NULL; SDL_Overlay *bmp; SDL_Surface *screen; SDL_Rect rect; SDL_Event event; if(argc < 2) { fprintf(stderr, "Usage: test <file>\n"); exit(1); } // Register all formats and codecs av_register_all(); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } // Open video file if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0) return -1; // Couldn't open file // Retrieve stream information if(avformat_find_stream_info(pFormatCtx, NULL)<0) return -1; // Couldn't find stream information // Dump information about file onto standard error av_dump_format(pFormatCtx, 0, argv[1], 0); // Find the first video stream videoStream=-1; for(i=0; i<pFormatCtx->nb_streams; i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) { videoStream=i; break; } if(videoStream==-1) return -1; // Didn't find a video stream // Get a pointer to the codec context for the video stream pCodecCtxOrig=pFormatCtx->streams[videoStream]->codec; // Find the decoder for the video stream pCodec=avcodec_find_decoder(pCodecCtxOrig->codec_id); if(pCodec==NULL) { fprintf(stderr, "Unsupported codec!\n"); return -1; // Codec not found } // Copy context pCodecCtx = avcodec_alloc_context3(pCodec); if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) { fprintf(stderr, "Couldn't copy codec context"); return -1; // Error copying codec context } // Open codec if(avcodec_open2(pCodecCtx, pCodec, NULL)<0) return -1; // Could not open codec // Allocate video frame pFrame=av_frame_alloc(); // Make a screen to put our video #ifndef __DARWIN__ screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0); #else screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 24, 0); #endif if(!screen) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } // Allocate a place to put our YUV image on that screen bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height, SDL_YV12_OVERLAY, screen); // initialize SWS context for software scaling sws_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL ); // Read frames and save first five frames to disk i=0; while(av_read_frame(pFormatCtx, &packet)>=0) { // Is this a packet from the video stream? if(packet.stream_index==videoStream) { // Decode video frame avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet); // Did we get a video frame? if(frameFinished) { SDL_LockYUVOverlay(bmp); AVPicture pict; pict.data[0] = bmp->pixels[0]; pict.data[1] = bmp->pixels[2]; pict.data[2] = bmp->pixels[1]; pict.linesize[0] = bmp->pitches[0]; pict.linesize[1] = bmp->pitches[2]; pict.linesize[2] = bmp->pitches[1]; // Convert the image into YUV format that SDL uses sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pict.data, pict.linesize); SDL_UnlockYUVOverlay(bmp); rect.x = 0; rect.y = 0; rect.w = pCodecCtx->width; rect.h = pCodecCtx->height; SDL_DisplayYUVOverlay(bmp, &rect); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); SDL_PollEvent(&event); switch(event.type) { case SDL_QUIT: SDL_Quit(); exit(0); break; default: break; } } // Free the YUV frame av_frame_free(&pFrame); // Close the codec avcodec_close(pCodecCtx); avcodec_close(pCodecCtxOrig); // Close the video file avformat_close_input(&pFormatCtx); return 0; }
26.838095
101
0.671398
ddd9d252ff1a1c5ec59f6dad71df542a8c0c6727
510
cpp
C++
src/resource.cpp
ayumi1139/altv-python-module
469efe9b619cd66874e1b9f10af46ec46accde83
[ "MIT" ]
1
2021-12-30T19:21:30.000Z
2021-12-30T19:21:30.000Z
src/resource.cpp
ayumi1139/altv-python-module
469efe9b619cd66874e1b9f10af46ec46accde83
[ "MIT" ]
null
null
null
src/resource.cpp
ayumi1139/altv-python-module
469efe9b619cd66874e1b9f10af46ec46accde83
[ "MIT" ]
null
null
null
#include "resource.h" bool PythonResource::Start() { return true; } bool PythonResource::Stop() { return Impl::Stop(); } bool PythonResource::OnEvent(const alt::CEvent *ev) { return Impl::OnEvent(ev); } void PythonResource::OnTick() { Impl::OnTick(); } void PythonResource::OnCreateBaseObject(alt::Ref<alt::IBaseObject> object) { Impl::OnCreateBaseObject(object); } void PythonResource::OnRemoveBaseObject(alt::Ref<alt::IBaseObject> object) { Impl::OnRemoveBaseObject(object); }
15.454545
74
0.703922
dddafcbbe3971a518cafdb18249ca33a8ffe9536
1,668
cc
C++
src/sockio.cc
SanczoPL/QtServer
c8350e920cadc215ad306592460cc16031eefff9
[ "MIT" ]
null
null
null
src/sockio.cc
SanczoPL/QtServer
c8350e920cadc215ad306592460cc16031eefff9
[ "MIT" ]
null
null
null
src/sockio.cc
SanczoPL/QtServer
c8350e920cadc215ad306592460cc16031eefff9
[ "MIT" ]
null
null
null
#include "../include/sockio.h" SockIO::SockIO(QTcpSocket* a_socket, QObject* parent) : QObject(parent) , m_socket{ a_socket } { connect(m_socket, &QTcpSocket::readyRead, this, &SockIO::onReadyRead); } bool SockIO::hasMessages() { return !m_messageQueue.isEmpty(); } Message SockIO::nextMessage() { if (!hasMessages()) qFatal("No mesages in queue!"); Message const MESSAGE{ m_messageQueue[0] }; m_messageQueue.pop_front(); return MESSAGE; } bool SockIO::sendMessage(Message const& a_message) { Logger->trace("SockIO::sendMessage()"); if (m_socket->write(a_message.rawData()) < 0) { Logger->warn("Failed to send message to host", m_socket->peerAddress().toString().toStdString()); return false; } return true; } void SockIO::onReadyRead() { m_bufer += m_socket->readAll(); Logger->trace("Recived data from ip:{}, bufSize:{}", m_socket->peerAddress().toString().toStdString(), m_bufer.size()); Logger->trace("while({} >= {})", m_bufer.size() ,static_cast<int>(sizeof(Message::Header)) ); while (m_bufer.size() >= static_cast<int>(sizeof(Message::Header))) { Logger->trace("checkPrefix:{}", Message::checkPrefix(m_bufer)); if (Message::checkPrefix(m_bufer)) { auto messageSize = Message::validate(m_bufer); Logger->trace("validate:{}", messageSize); if (messageSize > 0) { m_messageQueue.push_back(Message{ m_bufer }); m_bufer.remove(0, messageSize); Logger->trace("emit new message:"); emit(newMessage()); } else { Logger->trace("messageSize = 0"); break; } } else { Logger->warn("Buffer out of order {}", m_socket->peerAddress().toString().toStdString()); m_bufer.remove(0, 1); } } }
26.903226
120
0.676259
50af57283f0874a8f209829a0822eb507912716d
536
hpp
C++
YYSloth/include/drivers/pic/pic8259.hpp
notYuriy/yayaos
4df7b015cb6e572797dd40a5d2891cf24abcb4d1
[ "MIT" ]
12
2020-04-13T12:38:54.000Z
2021-08-31T07:03:14.000Z
YYSloth/include/drivers/pic/pic8259.hpp
YayOrg/YayOS
4df7b015cb6e572797dd40a5d2891cf24abcb4d1
[ "MIT" ]
null
null
null
YYSloth/include/drivers/pic/pic8259.hpp
YayOrg/YayOS
4df7b015cb6e572797dd40a5d2891cf24abcb4d1
[ "MIT" ]
1
2020-07-18T12:11:37.000Z
2020-07-18T12:11:37.000Z
#ifndef __PIC_8259_HPP_INCLUDED__ #define __PIC_8259_HPP_INCLUDED__ #include <drivers/pic/pic.hpp> #include <utils.hpp> namespace drivers { class PIC8259 : public IPIC { uint8_t m_picMasterMask; uint8_t m_picSlaveMask; public: void init(); bool registerLegacyIrq(uint8_t irq, x86_64::IDTVector vec); virtual bool enableLegacyIrq(uint8_t irq); virtual bool disableLegacyIrq(uint8_t irq); virtual bool endOfLegacyIrq(uint8_t irq); }; }; // namespace drivers #endif
23.304348
67
0.695896
50af8f89a9594ef35a72183c8ffc3c849c577598
6,043
hpp
C++
src/accelerator/Component.hpp
chrpilat/mnemosyne
bde60abf5e2be614dadf599e9e7b6a44afa83907
[ "BSD-2-Clause" ]
6
2017-03-02T16:02:00.000Z
2022-02-15T13:25:50.000Z
src/accelerator/Component.hpp
chrpilat/mnemosyne
bde60abf5e2be614dadf599e9e7b6a44afa83907
[ "BSD-2-Clause" ]
null
null
null
src/accelerator/Component.hpp
chrpilat/mnemosyne
bde60abf5e2be614dadf599e9e7b6a44afa83907
[ "BSD-2-Clause" ]
2
2019-04-25T15:53:20.000Z
2020-02-10T02:45:32.000Z
/** * @copyright * Copyright (c) 2017 - SLD Group @ Columbia University. All Rights Reserved. * * This file is part of Mnemosyne. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file Component.hpp * @author Christian Pilato <pilato.christian@gmail.com> * * @brief Class to describe a component with memory access * */ #ifndef _COMPONENT_HPP_ #define _COMPONENT_HPP_ #include "utils.hpp" FORWARD_DECL(Array); FORWARD_DECL(ArrayList); FORWARD_DECL(ComponentList); FORWARD_DECL(MemoryWrapper); #include "UGraph.hpp" /** * @brief Component Declaration */ struct Component { //! Identifier of the component. const std::string name; std::string clock_name; std::string reset_name; std::string conf_done_name; std::string acc_done_name; std::set<std::string> dmain_prefix; std::set<std::string> dmaout_prefix; std::set<std::string> rdreq_prefix; std::set<std::string> wrreq_prefix; std::set<std::string> read_interfaces; std::set<std::string> write_interfaces; std::map<std::string, std::string> darkmem_to_buffer; std::map<std::string, std::set<std::string> > buffer_to_darkmem; /** * @brief Constructor */ Component(const std::string& name); /** * @brief Print method * @param os is the output stream */ void print(std::ostream& os) const; /** * @brief Overloaded operator to support print * @param os is the output stream * @param b is the component to be printed * @return is the returned stream */ friend std::ostream& operator<<(std::ostream& os, const Component& b) { b.print(os); return os; } void parse_interface(const YAML::Node& interface, const std::map<std::string, MemoryWrapperPtr> &buffer_to_wrapper); std::string get_rdreq_prefix() const; std::string get_wrreq_prefix() const; std::string get_dmain_prefix() const; std::string get_dmaout_prefix() const; }; ///refcount definition typedef boost::shared_ptr<Component> ComponentPtr; struct ComponentList { ///verbosity level of the class unsigned int verbosity; ///name of the top component std::string top_name; ///archive of components std::map<std::string, ComponentPtr> list; ///list of buffers to be stored ArrayListPtr buffers; typedef std::tuple<UGraphPtr, UNode> node_t; std::map<std::string, ArrayPtr> id_to_buffer; std::map<std::string, node_t> id_to_node; std::map<UGraphPtr, std::map<UNode, ArrayPtr> > node_to_buffer; std::map<UGraphPtr, std::string> graph_to_acc_name; std::vector<node_t> node_list; std::map<node_t, std::set<node_t> > comp_list; /** * @brief Component * @param verbosity is the verbosity level of the class */ ComponentList(unsigned int verbosity); /** * @brief Create single array * @param name is the id of the array * @param width is the bitwidth * @param height is the number of words * @param interfaces is the list of interfaces * @param init_file is the name of the initialization file (if any) */ void create_array(const std::string& name, const unsigned int width, unsigned int height, const std::string& interfaces, const std::string& init_file); /** * @brief Parse the multi-component definitions * @param name is the name of the top component * @param multiacc_config is the path to the file to be parsed */ bool parse_config(const std::string& name, const std::string& multiacc_config); /** * @brief Parse a single component definition * @param name is the name of the component * @param acc_config is the path to the configuration file to be parsed * @param input_cgraph is the path to the compatibility graph file to be parsed */ bool parse_config(const std::string& name, const std::string& acc_config, const std::string& input_cgraph, const std::string& scenario_config); /** * @brief Prepare buffer data structures for the given accelerator * @param name is the name of the accelerator */ void bufferLoad(const std::string& name); /** * @brief Parse the file describing the compatibilities * @param name is the name of the current component to be analyzed * @param input_cgraph is the file describing the compatibilities */ void parse_accelerator_config(const std::string& name, const std::string& input_cgraph); /** * @brief Get a string-based representation of the given clique * @param clique is the set of nodes composing the clique * @return the string representing the clique */ std::string get_clique_string(const std::set<node_t>& clique); }; ///refcount definition typedef boost::shared_ptr<ComponentList> ComponentListPtr; #endif
33.949438
154
0.707761
50b20c1135034b5cd83271592d6a03f873ae1c5f
1,326
cc
C++
modules/planning/tasks/traffic_decider/front_vehicle.cc
delding/apollo
22d67d6c2e28550105e04defdf61ce82f2f7e50f
[ "Apache-2.0" ]
null
null
null
modules/planning/tasks/traffic_decider/front_vehicle.cc
delding/apollo
22d67d6c2e28550105e04defdf61ce82f2f7e50f
[ "Apache-2.0" ]
null
null
null
modules/planning/tasks/traffic_decider/front_vehicle.cc
delding/apollo
22d67d6c2e28550105e04defdf61ce82f2f7e50f
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/traffic_decider/front_vehicle.h" #include <string> #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::util::WithinBound; using apollo::hdmap::PathOverlap; CIPV::CIPV(const TrafficRuleConfig& config) : TrafficRule(config) {} bool CIPV::ApplyRule(Frame* frame, ReferenceLineInfo* reference_line_info) { CHECK_NOTNULL(frame); CHECK_NOTNULL(reference_line_info); return true; } } // namespace planning } // namespace apollo
30.136364
79
0.662142
50b3329138cbe81855eaf86cf22bec99ae8d8dcc
935
hpp
C++
libs/libSocketHandler/src/SocketHandler.hpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
libs/libSocketHandler/src/SocketHandler.hpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
libs/libSocketHandler/src/SocketHandler.hpp
maxDcb/ExplorationC2
f7366118eaa43ca5172b5e9d4a03156d724748b1
[ "MIT" ]
null
null
null
#pragma once #include <fstream> #include <memory> #include <chrono> #include <random> #include <vector> #include <thread> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> class Server { public: Server(int port); ~Server(); bool send(std::string& data); bool receive(std::string& data); private: void initServer(); void creatServerTcp(int port); bool m_initDone; int m_port; std::thread* threadInit; boost::asio::io_service m_ioService; boost::asio::ip::tcp::socket* m_socketTcp; boost::system::error_code m_error; }; class Client { public: Client(std::string& ip, int port); ~Client(); bool send(std::string& data); bool receive(std::string& data); private: void creatClientTcp(int port, std::string& ip); std::string m_ipServer; int m_port; boost::asio::io_service m_ioService; boost::asio::ip::tcp::socket* m_socketTcp; boost::system::error_code m_error; };
15.327869
48
0.708021
50b528ab4d6ecd9b379fd23b296cae56f26bb391
2,047
cc
C++
src/image/b3TxSaveInfo.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/image/b3TxSaveInfo.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/image/b3TxSaveInfo.cc
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: b3TxSaveInfo.cc $ ** $Release: Dortmund 2001, 2016 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - File format encoder ** ** (C) Copyright 2001 - 2021 Steffen A. Mork ** All Rights Reserved ** ** */ /************************************************************************* ** ** ** Blizzard III includes ** ** ** *************************************************************************/ #include "blz3/image/b3Tx.h" #include "b3TxSaveInfo.h" /************************************************************************* ** ** ** PNG ** ** ** *************************************************************************/ b3TxSaveInfo::b3TxSaveInfo(b3Tx * tx, const char * filename, const char * write_mode) { m_Tx = tx; m_Tx->b3Name(filename); bzero(m_SaveBuffer, sizeof(m_SaveBuffer)); m_ThisRow = b3TypedAlloc<b3_pkd_color>(tx->xSize); if (m_ThisRow == nullptr) { b3PrintF(B3LOG_NORMAL, "Save Image: not enough memory!\n"); B3_THROW(b3TxException, B3_TX_MEMORY); } if (write_mode == nullptr) { m_FileHandle = nullptr; if (!m_File.b3Open(filename, B_WRITE)) { b3Free(); b3PrintF(B3LOG_NORMAL, "Save Image: file \"%s\" not created!\n", filename); B3_THROW(b3TxException, B3_TX_NOT_SAVED); } } else { m_FileHandle = fopen(filename, write_mode); if (m_FileHandle == nullptr) { b3Free(); b3PrintF(B3LOG_NORMAL, "Save Image: file \"%s\" not created!\n", filename); B3_THROW(b3TxException, B3_TX_NOT_SAVED); } } } b3TxSaveInfo::~b3TxSaveInfo() { if (m_FileHandle != nullptr) { fclose(m_FileHandle); } else { m_File.b3Close(); } }
25.5875
85
0.429897
50b69ba7a31c994d4e138ca87f9a08b483c9e6de
2,811
hpp
C++
include/codegen/include/Oculus/Platform/RoomType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Oculus/Platform/RoomType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Oculus/Platform/RoomType.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:08 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.Enum #include "System/Enum.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: Oculus.Platform namespace Oculus::Platform { // Autogenerated type: Oculus.Platform.RoomType struct RoomType : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public Oculus.Platform.RoomType Unknown static constexpr const int Unknown = 0; // Get static field: static public Oculus.Platform.RoomType Unknown static Oculus::Platform::RoomType _get_Unknown(); // Set static field: static public Oculus.Platform.RoomType Unknown static void _set_Unknown(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Matchmaking static constexpr const int Matchmaking = 1; // Get static field: static public Oculus.Platform.RoomType Matchmaking static Oculus::Platform::RoomType _get_Matchmaking(); // Set static field: static public Oculus.Platform.RoomType Matchmaking static void _set_Matchmaking(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Moderated static constexpr const int Moderated = 2; // Get static field: static public Oculus.Platform.RoomType Moderated static Oculus::Platform::RoomType _get_Moderated(); // Set static field: static public Oculus.Platform.RoomType Moderated static void _set_Moderated(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Private static constexpr const int Private = 3; // Get static field: static public Oculus.Platform.RoomType Private static Oculus::Platform::RoomType _get_Private(); // Set static field: static public Oculus.Platform.RoomType Private static void _set_Private(Oculus::Platform::RoomType value); // static field const value: static public Oculus.Platform.RoomType Solo static constexpr const int Solo = 4; // Get static field: static public Oculus.Platform.RoomType Solo static Oculus::Platform::RoomType _get_Solo(); // Set static field: static public Oculus.Platform.RoomType Solo static void _set_Solo(Oculus::Platform::RoomType value); // Creating value type constructor for type: RoomType RoomType(int value_ = {}) : value{value_} {} }; // Oculus.Platform.RoomType } DEFINE_IL2CPP_ARG_TYPE(Oculus::Platform::RoomType, "Oculus.Platform", "RoomType"); #pragma pack(pop)
49.315789
83
0.728211
50bb67be19b9e4f3024490551da250d377d80309
1,743
cpp
C++
UVa 11496 musical loop/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 11496 musical loop/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 11496 musical loop/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <iostream> #include <vector> using namespace std; int main(void) { int n, first, last, current, sz; bool increasing; while (cin >> n) { if (n == 0) break; increasing = true; vector<int> points; for (int i = 0; i < n; i++) { cin >> current; if (i == 0) first = current; if (i == n - 1) last = current; if (points.size() < 2) { points.push_back(current); continue; } sz = points.size(); increasing = (points[sz - 1] > points[sz - 2]); if (current > points[sz - 1] && increasing) points[sz - 1] = current; else if (current < points[sz - 1] && !increasing) points[sz - 1] = current; else if (current > points[sz - 1]) { increasing = true; points.push_back(current); } else if (current < points[sz - 1]) { increasing = false; points.push_back(current); } } sz = points.size(); int result = sz; bool last_growing = (points[sz - 2] < points[sz - 1]); bool first_growing = (points[1] > points[0]); if (last_growing && points[0] > points[sz - 1]) result--; else if (first_growing && points[0] > points[sz - 1]) result--; else if (!last_growing && points[0] < points[sz - 1]) result--; else if (!first_growing && points[0] < points[sz - 1]) result--; cout << result << endl; } return 0; }
30.051724
62
0.430866
50be740fd5091b26478e43a76633c15e31d3e26c
1,586
cpp
C++
2017/February/Silver/Why Did the Cow Cross the Road III.cpp
Sumitkk10/USACO-submissions
543dafe041356e83a18e7a57e5d93d24bc266682
[ "MIT" ]
2
2020-12-09T05:43:19.000Z
2020-12-09T06:24:45.000Z
2017/February/Silver/Why Did the Cow Cross the Road III.cpp
Sumitkk10/USACO-submissions
543dafe041356e83a18e7a57e5d93d24bc266682
[ "MIT" ]
null
null
null
2017/February/Silver/Why Did the Cow Cross the Road III.cpp
Sumitkk10/USACO-submissions
543dafe041356e83a18e7a57e5d93d24bc266682
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) using namespace std; const int N = 100 + 5; const int MOD = 1e9 + 7; int n, k, m, sol; set<pair<int, pair<int, pair<int, int> > > > s; bool ok, vis[N][N]; map<pair<int, int>, int> mp; void check(int i, int j){ if(i <= 0 or j <= 0 or i > n or j > n or vis[i][j]) return; sol += mp[{i,j}]; vis[i][j] = true; if(s.find({i, {j, {i + 1, j}}}) == s.end()) check(i + 1, j); if(s.find({i, {j, {i - 1, j}}}) == s.end()) check(i - 1, j); if(s.find({i, {j, {i, j + 1}}}) == s.end()) check(i, j + 1); if(s.find({i, {j, {i, j - 1}}}) == s.end()) check(i, j - 1); } int main() { fast; freopen("countcross.in", "r", stdin); freopen("countcross.out", "w", stdout); cin >> n >> k >> m; for(int i = 0; i < m; ++i){ int a, b, x, y; cin >> a >> b >> x >> y; s.insert({a, {b, {x, y}}}); s.insert({x, {y, {a, b}}}); } vector<pair<int, int> > cows; for(int i = 0; i < k; ++i) { int u, v; cin >> u >> v; mp[{u, v}]++; } long long ans1 = 0; vector<int> ans; for(int i = 1; i <= n; ++i){ for(int j = 1; j <= n; ++j){ if(!vis[i][j]){ check(i, j); ans.push_back(sol); sol = 0; } } } for(int i = 0; i < ans.size(); ++i) for(int j = i + 1; j < ans.size(); ++j) ans1 += (ans[i] * ans[j]); cout << ans1 << '\n'; return 0; }
26.433333
70
0.406053
50c0dcfccd74614378c4bf6189216683d5a33079
551
cpp
C++
acmicpc/14789.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/14789.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/14789.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> using namespace std; int t, k; string s; int main() { cin >> t; for (int T=1; T<=t; ++T) { cin >> s >> k; int cnt = 0; int n = s.length(); for (int i=0; i<=n-k; ++i) { if (s[i] == '-') { cnt++; for (int j=i; j<i+k; ++j) s[j] = s[j] == '+' ? '-' : '+'; } } bool flag = true; for (int i=0; i<n; ++i) { if (s[i] == '-') { flag = false; break; } } if (flag) cout << "Case #" << T << ": " << cnt << '\n'; else cout << "Case #" << T << ": IMPOSSIBLE\n"; } return 0; }
14.128205
48
0.3902
50c316fdf459561e0def613aad0f9139b8a64c68
71,364
cpp
C++
PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp
rbnbr/S4
61534933e305e76d00cbefb75fc5c713c5b90c74
[ "MIT" ]
1
2021-09-27T11:29:48.000Z
2021-09-27T11:29:48.000Z
PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp
rbnbr/S4
61534933e305e76d00cbefb75fc5c713c5b90c74
[ "MIT" ]
null
null
null
PythonExtrasC/PythonExtrasC/PythonExtrasC.cpp
rbnbr/S4
61534933e305e76d00cbefb75fc5c713c5b90c74
[ "MIT" ]
1
2022-02-10T16:07:27.000Z
2022-02-10T16:07:27.000Z
#pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include <vector> #include <numeric> #include <cmath> #include <cstring> #include <algorithm> #include <functional> #include <random> #include <thread> #include <atomic> #include <chrono> #include <ctime> #include <iostream> #include "macros.h" #include "BufferedNdArray.hpp" #include "PythonExtrasCLib.h" template<typename T> void resize_array_point(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { T* pInput = static_cast<T*>(pInputRaw); T* pOutput = static_cast<T*>(pOutputRaw); for (int x = 0; x < targetWidth; x++) { double tX = targetWidth > 1 ? static_cast<double>(x) / (targetWidth - 1) : 0; int sourceX = lround(tX * (sourceWidth - 1)); for (int y = 0; y < targetHeight; y++) { double tY = targetHeight > 1 ? static_cast<double>(y) / (targetHeight - 1) : 0; int sourceY = lround(tY * (sourceHeight - 1)); for (int z = 0; z < targetDepth; z++) { double tZ = targetDepth > 1 ? static_cast<double>(z) / (targetDepth - 1) : 0; int sourceZ = lround(tZ * (sourceDepth - 1)); size_t sourceIndexFlat = sourceX * sourceHeight * sourceDepth + sourceY * sourceDepth + sourceZ; pOutput[x * targetHeight * targetDepth + y * targetDepth + z] = pInput[sourceIndexFlat]; } } } } /// /// Compute the number of patches along each *patched* dimension. /// Old function kept for compatibility. New ones don't use 'source axes' and patch all the dimensions. /// std::vector<size_t> compute_patch_number_generic(const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, const std::vector<size_t>& patchInnerStride, size_t predictionDelay) { std::vector<size_t> patchNumber(sourceAxes.size()); for (size_t i = 0; i < sourceAxes.size(); i++) { size_t dim = sourceAxes[i]; size_t stride = patchStride[i]; // How many voxels a patch covers. // Last point in time (Y-value) is 'predictionDelay' frames away from the previous frame. // E.g. if 'lastFrameGap' is 1, it immediately follows it. size_t patchSupport = i > 0 ? (patchSize[i] - 1) * patchInnerStride[i] + 1 : (patchSize[i] - 2) * patchInnerStride[i] + 1 + predictionDelay; size_t totalPatchNumber = dataSize[dim] - patchSupport + 1; patchNumber[i] = (totalPatchNumber + stride - 1) / stride; // Round up. } return patchNumber; } //todo this code (and functions called by it) has too many vector allocations. look at '4d_fast' methods for optimization. // The problem mostly is that the std vector doesn't have a small size optimization, // and always allocates stuff on the heap. template<typename T> void extract_patches_batched(void* pDataVoid, void* pOutputVoid, size_t* pOutputCenters, size_t ndim, const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, size_t firstPatchIndex, size_t patchesPerBatch, bool isBatchSizedBuffer = false) { T* pData = static_cast<T*>(pDataVoid); T* pOutput = static_cast<T*>(pOutputVoid); auto multiplies = std::multiplies<size_t>(); // Cache the functor, don't recreate it in a loop. // Number of patched dimensions. size_t nPatchDim = sourceAxes.size(); std::vector<size_t> patchInnerStride(nPatchDim, size_t{1}); // Number of patches along the patched dimensions. std::vector<size_t> patchNumber = compute_patch_number_generic(dataSize, sourceAxes, patchSize, patchStride, patchInnerStride, 1ULL); // Compute the (data)size of each patch. // (Depends on the spatial extent a.k.a. 'patch size' of each patch, and on the size of the orig. data. std::vector<size_t> patchDataSize(ndim, 0); for (size_t dim = 0; dim < ndim; dim++) { auto itSourceDim = std::find(sourceAxes.begin(), sourceAxes.end(), dim); if (itSourceDim != sourceAxes.end()) { // If the dimension is patched, use the patch size. size_t patchDim = itSourceDim - sourceAxes.begin(); patchDataSize[dim] = patchSize[patchDim]; } else { // Otherwise, take all data along that dimension. patchDataSize[dim] = dataSize[dim]; } } // Total number of elements in a patch. size_t patchDataSizeFlat = std::accumulate(patchDataSize.begin(), patchDataSize.end(), size_t{1}, multiplies); std::vector<size_t> patchCenterShift(nPatchDim); for (size_t patchDim = 0; patchDim < nPatchDim; patchDim++) patchCenterShift[patchDim] = patchSize[patchDim] / 2; // For efficiency, we don't copy data element-by-element, but copy // continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension of the orig. data. std::vector<size_t> patchDataColumnNumber = std::vector<size_t>(patchDataSize.begin(), patchDataSize.end() - 1); size_t patchDataColumnNumberFlat = std::accumulate(patchDataColumnNumber.begin(), patchDataColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchDataSize[ndim - 1]; // This function supports batching, i.e. we only extract 'patchesPerBatch' patches // starting with 'firstPatchIndex' patch. // Loop over all patches in a batch. // Since the number of dimensions is dynamic, we loop over a flat index // and then unflatten it. for (size_t indexFlat = firstPatchIndex; indexFlat < firstPatchIndex + patchesPerBatch; indexFlat++) { std::vector<size_t> patchIndexNd = unflattenIndex(indexFlat, patchNumber); // Figure out where in the orig. data the patch begins. // For patched dimensions, this is index * stride. // For the rest it's zero, since the whole dim. is copied. std::vector<size_t> dataSelectorStart(ndim, 0); std::vector<size_t> patchCenter(nPatchDim); for (size_t dim = 0; dim < ndim; dim++) { auto itSourceDim = std::find(sourceAxes.begin(), sourceAxes.end(), dim); if (itSourceDim != sourceAxes.end()) { size_t patchDim = itSourceDim - sourceAxes.begin(); dataSelectorStart[dim] = patchIndexNd[patchDim] * patchStride[patchDim]; // Keep the location of the patch's center, which needs to be returned to the caller. patchCenter[patchDim] = dataSelectorStart[dim] + patchCenterShift[patchDim]; } } // Where in the output array should we write. // All the patches are stacked one after another. size_t outputOffset = indexFlat * patchDataSizeFlat; size_t centerOutputOffset = indexFlat * nPatchDim; // If the output buffer is batch-sized. Adjust the offset to the batch. if (isBatchSizedBuffer) { outputOffset = (indexFlat - firstPatchIndex) * patchDataSizeFlat; centerOutputOffset = (indexFlat - firstPatchIndex) * nPatchDim; } for (size_t columnIndexFlat = 0; columnIndexFlat < patchDataColumnNumberFlat; columnIndexFlat++) { std::vector<size_t> columnIndexNd = unflattenIndex(columnIndexFlat, patchDataColumnNumber); // Where the column starts in the original data . std::vector<size_t> sourceIndexNd(ndim); for (size_t dim = 0; dim < ndim; dim++) sourceIndexNd[dim] = dataSelectorStart[dim] + columnIndexNd[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd[ndim - 1] = dataSelectorStart[ndim - 1]; size_t sourceIndexFlat = flattenIndex(sourceIndexNd, dataSize); // Copy a whole column. std::copy(&pData[sourceIndexFlat], &pData[sourceIndexFlat + columnSize], pOutput + outputOffset + columnIndexFlat * columnSize); } // Copy the patch center. std::copy(patchCenter.begin(), patchCenter.end(), pOutputCenters + centerOutputOffset); } } template<typename T> void extract_patches(void* pDataVoid, void* pOutputVoid, size_t* pOutputCenters, size_t ndim, const std::vector<size_t>& dataSize, const std::vector<size_t>& sourceAxes, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride) { auto multiplies = std::multiplies<size_t>(); // Cache the functor, don't recreate it in a loop. // Number of patches along the patched dimensions. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, sourceAxes, patchSize, patchStride, 1ULL); // Total flat number of patches that will be returned. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); extract_patches_batched<T>(pDataVoid, pOutputVoid, pOutputCenters, ndim, dataSize, sourceAxes, patchSize, patchStride, 0, patchNumberFlat); } /** * \brief * * Extract patches/windows from a 4-dimensional array. * Each patch gets split into training data: X and Y. * X holds the whole hypercube, except for the last frame. Y holds a single scalar * from the center of the last frame. (Time is the first dimension, C-order is assumed.) * 'Empty' patches are those, where all values in X and the Y value are equal to the 'empty value'. * Empty patches do not get extracted. * Extraction is performed in batches, returning control after 'batchSize' patches were extracted. * */ template<typename T> void extract_patched_training_data_without_empty_4d( T* pData, size_t dataStartFlat, size_t dataEndFlat, const std::vector<size_t>& dataSize, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, const std::vector<size_t>& patchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, T emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, T* pOutX, T* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { // Cache the functor, don't recreate it in a loop. auto multiplies = std::multiplies<size_t>(); // Prepare the random distribution for undersampling. std::random_device r; std::default_random_engine randomEngine(r()); std::uniform_real_distribution<float_t> randomDist(0.0f, 1.0f); const size_t ndim = 4; if (dataSize.size() != ndim || patchSize.size() != ndim || patchStride.size() != ndim) throw std::runtime_error("Invalid number of dimensions. Expected four."); if (patchInnerStride[3] != 1) { printf("Inner stride is probably broken, since we copy patch by columns. \n"); throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n"); } // Number of patches along each dimension. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); // For efficiency, we don't copy data element-by-element, but copy // continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension. std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1); size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(), patchXColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchSize[ndim - 1]; // This function supports batching, i.e. we only extract 'batchSize' patches // starting with 'batchStartIndex' patch. // Loop over all patches in a batch. Skip 'empty' patches. // We loop over a flat index and then unflatten it. We could write 'ndim' nested loops, // but this way is a little less verbose and more flexible. // Optimization: prepare allocate all vectors that we'll need, instead doing it in the loop. Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber); IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber); Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize); Index4d dataIndexNd{}; Index4d patchIndexNd{}; IndexNd<3> columnIndexNd{}; Index4d sourceIndexNd{}; Index4d sourceIndexNdY{}; bool pInputEndReached = false; size_t patchesExtracted = 0; size_t indexFlat = batchStartIndex; while (patchesExtracted < batchSize && indexFlat < patchNumberFlat) { // Skip some of the patches according to the provided probability. float_t random = randomDist(randomEngine); bool dontUndersample = undersamplingProb > 0.999; // Floating-point comparison. if (dontUndersample || random < undersamplingProb) { unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd); // Figure out where in the orig. data the patch begins. for (size_t dim = 0; dim < ndim; dim++) dataIndexNd.X[dim] = patchIndexNd.X[dim] * patchStride[dim]; // Where in the output array should we write. // All the patches are stacked one after another. size_t outputOffsetX = patchesExtracted * patchSizeXFlat; size_t outputOffsetY = patchesExtracted; size_t outputOffsetIndices = patchesExtracted * ndim; bool xIsEmpty = skipEmptyPatches; // Init to false, if not skipping empty patches. for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++) { unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd); // Where the column starts in the original data . for (size_t dim = 0; dim < ndim - 1; dim++) sourceIndexNd.X[dim] = dataIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd.X[ndim - 1] = dataIndexNd.X[ndim - 1]; size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS); size_t sourceIndexRel = sourceIndexFlat - dataStartFlat; // The input data is buffered, i.e. we only have a chunk of it. // Check if the buffer has the data we need. if (sourceIndexFlat + columnSize >= dataEndFlat) { pInputEndReached = true; break; } // Check if the column is empty. auto first = &pData[sourceIndexRel]; auto last = &pData[sourceIndexRel + columnSize]; bool allValuesEqual = skipEmptyPatches && std::adjacent_find(first, last, std::not_equal_to<T>()) == last; xIsEmpty = xIsEmpty && *first == emptyValue && allValuesEqual; // Copy the whole column, even if it's empty. We don't know if the whole patch is empty or not. std::copy(first, last, pOutX + outputOffsetX + columnIndexFlat * columnSize); } // Extract Y. // Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead. sourceIndexNdY.X[0] = dataIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap; for (size_t dim = 1; dim < ndim; dim++) { // Take the value in the middle of the patch. sourceIndexNdY.X[dim] = dataIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim]; } size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS); size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat; // Check if the buffer has the data we need. if (pInputEndReached || sourceIndexYFlat >= dataEndFlat) { pInputEndReached = true; break; } T y = pData[sourceIndexYRel]; bool yIsEmpty = y == emptyValue; if (!xIsEmpty || !yIsEmpty) { // Copy the results. *(pOutY + outputOffsetY) = y; std::copy(&dataIndexNd.X[0], &dataIndexNd.X[4], pOutIndices + outputOffsetIndices); // Advance the output offset. patchesExtracted += 1; } } indexFlat += 1; } // Return the information about the extracted batch. *pOutPatchesExtracted = patchesExtracted; *pOutNextBatchIndex = indexFlat; *pOutInputEndReached = pInputEndReached; } /// /// A multithreaded version of the same method. Uses an atomic counter to synchronize output to the buffer. /// template<typename T> void extract_patched_training_data_without_empty_4d_multi( T* pData, size_t dataStartFlat, size_t dataEndFlat, const std::vector<size_t>& dataSize, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchStride, const std::vector<size_t>& patchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, T emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, std::atomic<size_t>& globalBufferOffset, T* pOutX, T* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutPatchesEmpty, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { // Cache the functor, don't recreate it in a loop. auto multiplies = std::multiplies<size_t>(); // Prepare the random distribution for undersampling. std::random_device r; std::default_random_engine randomEngine(r()); std::uniform_real_distribution<float_t> randomDist(0.0f, 1.0f); const size_t ndim = 4; if (dataSize.size() != ndim || patchSize.size() != ndim || patchStride.size() != ndim) throw std::runtime_error("Invalid number of dimensions. Expected four."); if (patchInnerStride[3] != 1) { printf("Inner stride is probably broken, since we copy patch by columns. \n"); throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n"); } // Number of patches along each dimension. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); // For efficiency, we don't copy data element-by-element, but copy continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension. std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1); size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(), patchXColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchSize[ndim - 1]; // Consistency check: A thread should be allocated at least some work. if (batchStartIndex >= patchNumberFlat) { printf("Thread's start index is larger than the total number of patches.\n"); throw std::runtime_error("Thread's start index is larger than the total number of patches."); } // This function supports batching, i.e. we only extract 'batchSize' patches // starting with 'batchStartIndex' patch. // Loop over all patches in a batch. Skip 'empty' patches. // We loop over a flat index and then unflatten it. We could write 'ndim' nested loops, // but this way is a little less verbose and more flexible. // Optimization: allocate all the vectors that we'll need, instead of doing it in the loop. Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber); IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber); Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize); Index4d dataIndexNd{}; Index4d patchIndexNd{}; IndexNd<3> columnIndexNd{}; Index4d sourceIndexNd{}; Index4d sourceIndexNdY{}; // Allocate memory for storing a single patch that is being processed. // When it's assembled, it will be copied to the global buffer. // If we don't have an intermediate buffer, another thread can write over our results. std::vector<T> patchDataX(patchSizeXFlat); bool inputEndReached = false; size_t patchesExtracted = 0; size_t patchesEmpty = 0; size_t indexFlat = batchStartIndex; // Batch counts input patches, not the output (like in single-threaded code). // This makes the code more deterministic, i.e. we are sure that at the end // all input has been processed. // But this also means, that fewer (or even zero) patches could be returned. size_t batchEndIndex = batchStartIndex + batchSize; while (indexFlat < batchEndIndex && indexFlat < patchNumberFlat) // Note: break conditions below, due to convenience. { // Skip some of the patches according to the provided probability. float_t random = randomDist(randomEngine); bool dontUndersample = undersamplingProb > 0.999; // Floating-point comparison. if (dontUndersample || random < undersamplingProb) { unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd); // Figure out where in the orig. data the patch begins. for (size_t dim = 0; dim < ndim; dim++) dataIndexNd.X[dim] = patchIndexNd.X[dim] * patchStride[dim]; bool xIsEmpty = skipEmptyPatches; // Init to false, if not skipping empty patches. for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++) { unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd); // Where the column starts in the original data . for (size_t dim = 0; dim < ndim - 1; dim++) sourceIndexNd.X[dim] = dataIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd.X[ndim - 1] = dataIndexNd.X[ndim - 1]; size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS); size_t sourceIndexRel = sourceIndexFlat - dataStartFlat; // The input data is buffered, i.e. we only have a chunk of it. // Check if the buffer has the data we need. if (sourceIndexFlat + columnSize >= dataEndFlat) { inputEndReached = true; break; } // Check if the column is empty. auto first = &pData[sourceIndexRel]; auto last = &pData[sourceIndexRel + columnSize]; bool allValuesEqual = skipEmptyPatches && std::adjacent_find(first, last, std::not_equal_to<T>()) == last; xIsEmpty = xIsEmpty && *first == emptyValue && allValuesEqual; // Copy the whole column, even if it's empty. We don't know if the whole patch is empty or not. std::copy(first, last, patchDataX.data() + columnIndexFlat * columnSize); } // Extract Y. // Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead. sourceIndexNdY.X[0] = dataIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap; for (size_t dim = 1; dim < ndim; dim++) { // Take the value in the middle of the patch. sourceIndexNdY.X[dim] = dataIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim]; } size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS); size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat; // Check if the buffer has the data we need. if (inputEndReached || sourceIndexYFlat >= dataEndFlat) { inputEndReached = true; break; } T y = pData[sourceIndexYRel]; bool yIsEmpty = y == emptyValue; if (!xIsEmpty || !yIsEmpty) { // Claim output buffer space by advancing the atomic counter. // Atomic fetch_add performs read-modify-write as a single operation, so we are thread safe. size_t outputOffset = globalBufferOffset.fetch_add(1); // Where in the output array should we write. size_t outputOffsetX = outputOffset * patchSizeXFlat; size_t outputOffsetY = outputOffset; size_t outputOffsetIndices = outputOffset * ndim; // Write the results. std::copy(patchDataX.begin(), patchDataX.end(), pOutX + outputOffsetX); *(pOutY + outputOffsetY) = y; std::copy(&dataIndexNd.X[0], &dataIndexNd.X[4], pOutIndices + outputOffsetIndices); // Count how many patches this thread has extracted. patchesExtracted += 1; } else { patchesEmpty += 1; } } indexFlat += 1; } // Return the information about the extracted batch. *pOutPatchesExtracted = patchesExtracted; *pOutPatchesEmpty = patchesEmpty; *pOutNextBatchIndex = indexFlat; *pOutInputEndReached = inputEndReached; } /** * * This version doesn't use undersampling, empty patch skipping or striding. * It's meant for dense multi-threaded patch extraction. * */ template<typename T> void extract_patched_training_data_dense_4d(T* pData, size_t dataStartFlat, size_t dataEndFlat, const std::vector<size_t>& dataSize, const std::vector<size_t>& patchSize, const std::vector<size_t>& patchInnerStride, size_t lastFrameGap, size_t batchStartIndex, size_t batchSize, T* pOutX, T* pOutY, size_t* pOutPatchesExtracted, bool* pOutInputEndReached) { const size_t ndim = 4; const std::vector<size_t> patchStride{ 1, 1, 1, 1 }; // Cache the functor, don't recreate it in a loop. auto multiplies = std::multiplies<size_t>(); if (dataSize.size() != ndim || patchSize.size() != ndim) throw std::runtime_error("Invalid number of dimensions. Expected four."); if (patchInnerStride[3] != 1) { printf("Inner stride is probably broken, since we copy patch by columns. \n"); throw std::runtime_error("Inner stride is probably broken, since we copy patch by columns. \n"); } // Number of patches along each dimension. std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, multiplies); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); // For efficiency, we don't copy data element-by-element, but copy // continuous columns in the memory. // When dealing with columns, we simply ignore the last dimension (arrays are C-ordered) // in index computations and copy whole lines along that dimension. // The number of columns in each dimension. std::vector<size_t> patchXColumnNumber = std::vector<size_t>(patchSizeX.begin(), patchSizeX.end() - 1); size_t patchXColumnNumberFlat = std::accumulate(patchXColumnNumber.begin(), patchXColumnNumber.end(), size_t{1}, multiplies); // Length of a single column. size_t columnSize = patchSize[ndim - 1]; // This function supports batching, i.e. we only extract 'batchSize' patches // starting with 'batchStartIndex' patch. // We loop over a flat index and then unflatten it. We could write 'ndim' nested loops, // but this way is a little less verbose and more flexible. // Optimization: allocate all vectors that we'll need, instead of doing it in the loop. Index4d patchNumberSS = compute_slice_sizes_fast<4>(patchNumber); Index4d dataSizeSS = compute_slice_sizes_fast<4>(dataSize); IndexNd<3> patchXColumnNumberSS = compute_slice_sizes_fast<3>(patchXColumnNumber); // index4d_t dataIndexNd{}; <-- Is the same as patch index, since we have no striding. Index4d patchIndexNd{}; IndexNd<3> columnIndexNd{}; Index4d sourceIndexNd{}; Index4d sourceIndexNdY{}; bool inputEndReached = false; size_t patchesExtracted = 0; while (patchesExtracted < batchSize && batchStartIndex + patchesExtracted < patchNumberFlat) { // Since we don't skip patches, flat index follows 'patchesExtracted'. size_t indexFlat = batchStartIndex + patchesExtracted; unflattenIndex_fast(indexFlat, patchNumberSS, patchIndexNd); // Where in the output array should we write. // All the patches are stacked one after another. size_t outputOffsetX = patchesExtracted * patchSizeXFlat; size_t outputOffsetY = patchesExtracted; for (size_t columnIndexFlat = 0; columnIndexFlat < patchXColumnNumberFlat; columnIndexFlat++) { unflattenIndex_fast(columnIndexFlat, patchXColumnNumberSS, columnIndexNd); // Where the column starts in the original data . for (size_t dim = 0; dim < ndim - 1; dim++) sourceIndexNd.X[dim] = patchIndexNd.X[dim] + columnIndexNd.X[dim] * patchInnerStride[dim]; // Handle the last 'column' dimension: point to its start, we take all the data. sourceIndexNd.X[ndim - 1] = patchIndexNd.X[ndim - 1]; size_t sourceIndexFlat = flattenIndex_fast(sourceIndexNd, dataSizeSS); size_t sourceIndexRel = sourceIndexFlat - dataStartFlat; // The input data is buffered, i.e. we only have a chunk of it. // Check if the buffer has the data we need. if (sourceIndexFlat + columnSize >= dataEndFlat) { inputEndReached = true; break; } // Copy the whole column. auto first = &pData[sourceIndexRel]; auto last = &pData[sourceIndexRel + columnSize]; std::copy(first, last, pOutX + outputOffsetX + columnIndexFlat * columnSize); } // Extract Y. // Take the last timestep. Note that Y ignores the inner stride, and uses 'lastFrameGap' instead. sourceIndexNdY.X[0] = patchIndexNd.X[0] + (patchSize[0] - 2) * patchInnerStride[0] + lastFrameGap; for (size_t dim = 1; dim < ndim; dim++) { // Take the value in the middle of the patch. sourceIndexNdY.X[dim] = patchIndexNd.X[dim] + patchSize[dim] / 2 * patchInnerStride[dim]; } size_t sourceIndexYFlat = flattenIndex_fast(sourceIndexNdY, dataSizeSS); size_t sourceIndexYRel = sourceIndexYFlat - dataStartFlat; // Check if the buffer has the data we need. if (inputEndReached || sourceIndexYFlat >= dataEndFlat) { inputEndReached = true; break; } // Copy the Y *(pOutY + outputOffsetY) = pData[sourceIndexYRel]; // Advance the output offset. patchesExtracted += 1; } // Return the information about the extracted batch. *pOutPatchesExtracted = patchesExtracted; *pOutInputEndReached = inputEndReached; } template <typename T> void sparse_insert_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues, size_t valueNumber) { size_t ndim = pArray->GetNdim(); typename BufferedNdArray<T>::Tuple indexNd(ndim); for (size_t i = 0; i < valueNumber; i++) { size_t const* pIndex = pIndices + i * ndim; std::copy(pIndex, pIndex + ndim, indexNd.data()); pArray->Write(indexNd, *(pValues + i)); } } template <typename T> void sparse_insert_slices_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues, size_t sliceNdim, size_t sliceNumber) { size_t ndim = pArray->GetNdim(); // Total array axis number. size_t sliceIndexNdim = ndim - sliceNdim; // Length of a slice index (non-sliced axis number). typename BufferedNdArray<T>::Tuple sliceIndexNd(sliceIndexNdim); size_t sliceSizeFlat = pArray->GetSliceSizeFromNdim(sliceNdim); for (size_t i = 0; i < sliceNumber; i++) { size_t const* pIndex = pIndices + i * sliceIndexNdim; std::copy(pIndex, pIndex + sliceIndexNdim, sliceIndexNd.data()); pArray->WriteSlice(sliceIndexNd, sliceNdim, pValues + i * sliceSizeFlat); } } /// /// Insert patches at location specified by the indices (lower patch corner). /// If 'isConstPatch' is false, expect a buffer with N patches, otherwise take a buffer with a single patch. /// template <typename T> void sparse_insert_patches_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const* pValues, size_t const* pPatchSize, size_t patchNumber, bool isConstPatch) { size_t ndim = pArray->GetNdim(); typename BufferedNdArray<T>::Tuple patchSize(pPatchSize, pPatchSize + ndim); size_t patchSizeFlat = std::accumulate(patchSize.begin(), patchSize.end(), 1, std::multiplies<>()); typename BufferedNdArray<T>::Tuple patchIndexNd(ndim, 0); for (size_t i = 0; i < patchNumber; i++) { size_t const* pIndex = pIndices + i * ndim; std::copy(pIndex, pIndex + ndim, patchIndexNd.data()); if (!isConstPatch) pArray->WritePatch(patchIndexNd, patchSize, pValues + i * patchSizeFlat); else pArray->WritePatch(patchIndexNd, patchSize, pValues); // Always write the same patch. } } template <typename T> void sparse_insert_const_into_bna(BufferedNdArray<T>* pArray, size_t const* pIndices, T const& constValue, size_t valuesToInsert) { size_t ndim = pArray->GetNdim(); typename BufferedNdArray<T>::Tuple indexNd(ndim); for (size_t i = 0; i < valuesToInsert; i++) { size_t const* pIndex = pIndices + i * ndim; std::copy(pIndex, pIndex + ndim, indexNd.data()); pArray->Write(indexNd, constValue); } } void _multithreading_test_worker(uint8_t* pData, uint64_t offset, uint64_t size) { for (size_t i = 0; i < size; i++) { size_t computationNumber = 20; size_t dummyResult = 0; for (size_t j = 0; j < computationNumber; j++) { dummyResult += 13 + dummyResult * 5 % 3; } pData[offset + i] += static_cast<uint8_t>(dummyResult % 256); } } //todo Keeping state between calls experiment. uint64_t StaticState = 5; extern "C" { // todo Get rid of the void pointers. Ctypes can handle typed pointers. // todo remove the test code. __DLLEXPORT void test(void* pInput, int width, int height) { double* pData = static_cast<double *>(pInput); for (int i = 0; i < width * height; ++i) { pData[i] = pData[i] * 2; } } __DLLEXPORT void static_state_test(uint64_t increment, uint64_t* out) { StaticState += increment; *out = StaticState; } __DLLEXPORT void multithreading_test(uint8_t* pData, uint64_t size, uint64_t threadNumber) { std::vector<std::thread> threads{}; size_t chunkSize = size / threadNumber; for (size_t i = 0; i < threadNumber; i++) { size_t chunkOffset = i * chunkSize; size_t actualChunkSize = std::min(chunkSize, size - chunkOffset); threads.emplace_back([=]() { _multithreading_test_worker(pData, chunkOffset, actualChunkSize); }); } for (auto& thread : threads) thread.join(); } __DLLEXPORT void resize_array_point_float32(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { resize_array_point<float_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth, pOutputRaw, targetWidth, targetHeight, targetDepth); } __DLLEXPORT void resize_array_point_float64(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { resize_array_point<double_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth, pOutputRaw, targetWidth, targetHeight, targetDepth); } __DLLEXPORT void resize_array_point_uint8(void* pInputRaw, int sourceWidth, int sourceHeight, int sourceDepth, void* pOutputRaw, int targetWidth, int targetHeight, int targetDepth) { resize_array_point<uint8_t>(pInputRaw, sourceWidth, sourceHeight, sourceDepth, pOutputRaw, targetWidth, targetHeight, targetDepth); } __DLLEXPORT void extract_patches_uint8(void* data, void* output, size_t* outputCenters, size_t ndim, size_t* dataSize, size_t dataSizeL, size_t* sourceAxes, size_t sourceAxesL, size_t* patchSize, size_t patchSizeL, size_t* patchStride, size_t patchStrideL) { extract_patches<uint8_t>(data, output, outputCenters, ndim, std::vector<size_t>(dataSize, dataSize + dataSizeL), std::vector<size_t>(sourceAxes, sourceAxes + sourceAxesL), std::vector<size_t>(patchSize, patchSize + patchSizeL), std::vector<size_t>(patchStride, patchStride + patchStrideL)); } __DLLEXPORT void extract_patches_batched_uint8(void* data, void* output, size_t* outputCenters, size_t ndim, size_t* dataSize, size_t dataSizeL, size_t* sourceAxes, size_t sourceAxesL, size_t* patchSize, size_t patchSizeL, size_t* patchStride, size_t patchStrideL, size_t firstPatchIndex, size_t patchesPerBatch, bool isBatchSizedBuffer) { extract_patches_batched<uint8_t>(data, output, outputCenters, ndim, std::vector<size_t>(dataSize, dataSize + dataSizeL), std::vector<size_t>(sourceAxes, sourceAxes + sourceAxesL), std::vector<size_t>(patchSize, patchSize + patchSizeL), std::vector<size_t>(patchStride, patchStride + patchStrideL), firstPatchIndex, patchesPerBatch, isBatchSizedBuffer); } __DLLEXPORT void extract_patched_training_data_without_empty_4d_uint8( uint8_t* pData, size_t dataStartFlat, size_t dataEndFlat, size_t* dataSize, size_t* patchSize, size_t* patchStride, size_t* patchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, uint8_t emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, uint8_t* pOutX, uint8_t* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { extract_patched_training_data_without_empty_4d<uint8_t>(pData, dataStartFlat, dataEndFlat, std::vector<size_t>(dataSize, dataSize + 4), std::vector<size_t>(patchSize, patchSize + 4), std::vector<size_t>(patchStride, patchStride + 4), std::vector<size_t>(patchInnerStride, patchInnerStride + 4), lastFrameGap, skipEmptyPatches, emptyValue, batchStartIndex, batchSize, undersamplingProb, pOutX, pOutY, pOutIndices, pOutPatchesExtracted, pOutNextBatchIndex, pOutInputEndReached); } __DLLEXPORT void extract_patched_training_data_without_empty_4d_multithreaded_uint8( uint8_t* pData, size_t dataStartFlat, size_t dataEndFlat, size_t* pDataSize, size_t* pPatchSize, size_t* pPatchStride, size_t* pPatchInnerStride, size_t lastFrameGap, bool skipEmptyPatches, uint8_t emptyValue, size_t batchStartIndex, size_t batchSize, float_t undersamplingProb, size_t threadNumber, uint8_t* pOutX, uint8_t* pOutY, size_t* pOutIndices, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { const size_t ndim = 4; std::vector<size_t> dataSize(pDataSize, pDataSize + ndim); std::vector<size_t> patchSize(pPatchSize, pPatchSize + ndim); std::vector<size_t> patchStride(pPatchStride, pPatchStride + ndim); std::vector<size_t> patchInnerStride(pPatchInnerStride, pPatchInnerStride + ndim); std::vector<std::thread> threads{}; std::atomic<size_t> globalBufferOffset{0}; std::vector<size_t> patchNumber = compute_patch_number_old(dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap); // Total flat number of patches. size_t patchNumberFlat = std::accumulate(patchNumber.begin(), patchNumber.end(), size_t{1}, std::multiplies<>()); size_t patchesToProcess = std::min(batchSize, patchNumberFlat - batchStartIndex); size_t chunkSize = patchesToProcess / threadNumber; // Output buffers. std::vector<size_t> patchesExtracted(threadNumber, 0); std::vector<size_t> patchesEmpty(threadNumber, 0); std::vector<size_t> nextBatchIndex(threadNumber, 0); bool* inputEndReached = new bool[threadNumber]; for (size_t i = 0; i < threadNumber; i++) { // Each thread gets allocated a fixed chunk of the input. // But a thread can write out an arbitrary number of patches, due to undersampling, // running out of input buffer or empty patch skipping. size_t chunkOffset = i * chunkSize; size_t actualChunkSize = i < threadNumber - 1 ? chunkSize : patchesToProcess - chunkOffset; threads.emplace_back([&, i, chunkOffset, actualChunkSize]() // Capture local vars by value! { extract_patched_training_data_without_empty_4d_multi<uint8_t>( pData, dataStartFlat, dataEndFlat, dataSize, patchSize, patchStride, patchInnerStride, lastFrameGap, skipEmptyPatches, emptyValue, batchStartIndex + chunkOffset, actualChunkSize, undersamplingProb, globalBufferOffset, pOutX, pOutY, pOutIndices, &patchesExtracted[i], &patchesEmpty[i], &nextBatchIndex[i], &inputEndReached[i]); }); } for (auto& thread : threads) thread.join(); // Stop collecting results after encountering the first thread that couldn't finish. bool endReached = false; size_t totalPatchesExtracted = 0; size_t lastNextBatchIndex = nextBatchIndex[threadNumber - 1]; // By default, the last thread is the last ;). for (size_t i = 0; i < threadNumber; i++) { // printf("Thread %zu extracted %zu patches and skipped %zu. Run out: %d\n", i, patchesExtracted[i], patchesEmpty[i], inputEndReached[i]); totalPatchesExtracted += patchesExtracted[i]; if (!endReached && inputEndReached[i]) { endReached = true; // If we didn't have enough data - start over (next batch) at the first thread that had to stop. lastNextBatchIndex = nextBatchIndex[i]; } else if (endReached) { // Validate the assumption that if a thread runs out of input data, // then all the following threads extracted zero patches. // We assume that patches are layed out linearly wrt. to input, // if one thread requires an input element with at least index X, all following // threads require that or even higher indices. if (patchesExtracted[i] > 0) { printf("ASSUMPTION FAILED: We have run out of input data, \n"); printf("but the next thread %zu still extracted %zu patches. ", i, patchesExtracted[i]); abort(); } } } delete[] inputEndReached; // Do a consistency check: number of global output buffer increments should be the same // as the sum of local patch counters. if (totalPatchesExtracted != globalBufferOffset) { printf("FAILED THE CONSISTENCY CHECK: PATCHES MISSING DUE TO A RACE CONDITION?\n"); printf("Expected %zu patches to be written, got %zu instead\n", totalPatchesExtracted, globalBufferOffset.load()); abort(); } *pOutPatchesExtracted = totalPatchesExtracted; *pOutNextBatchIndex = lastNextBatchIndex; *pOutInputEndReached = endReached; } __DLLEXPORT void extract_patched_training_data_multithreaded_uint8( uint8_t* pData, size_t dataStartFlat, size_t dataEndFlat, size_t* dataSize, size_t* patchSize, size_t* patchInnerStride, size_t lastFrameGap, size_t batchStartIndex, size_t batchSize, size_t threadNumber, uint8_t* pOutX, uint8_t* pOutY, size_t* pOutPatchesExtracted, size_t* pOutNextBatchIndex, bool* pOutInputEndReached) { const int ndim = 4; auto multiplies = std::multiplies<size_t>(); // Total number of elements in an 'X' patch. std::vector<size_t> patchSizeX(patchSize, patchSize + 4); // The 'X' part includes all timesteps but the last. The last timestep is used for 'Y'. patchSizeX[0] -= 1; size_t patchSizeXFlat = std::accumulate(patchSizeX.begin(), patchSizeX.end(), size_t{1}, multiplies); std::vector<std::thread> threads{}; size_t chunkSize = batchSize / threadNumber; // Output buffers. std::vector<size_t> patchesExtracted(threadNumber, 0); std::vector<size_t> nextBatchIndex(threadNumber, 0); bool* inputEndReached = new bool[threadNumber]; for (size_t i = 0; i < threadNumber; i++) { size_t chunkOffset = i * chunkSize; size_t actualChunkSize = i < threadNumber - 1 ? chunkSize : batchSize - chunkOffset; threads.emplace_back([&, i, chunkOffset, actualChunkSize]() { extract_patched_training_data_dense_4d<uint8_t>( pData, dataStartFlat, dataEndFlat, std::vector<size_t>(dataSize, dataSize + ndim), std::vector<size_t>(patchSize, patchSize + ndim), std::vector<size_t>(patchInnerStride, patchInnerStride + ndim), lastFrameGap, batchStartIndex + chunkOffset, actualChunkSize, pOutX + chunkOffset * patchSizeXFlat, pOutY + chunkOffset, &patchesExtracted[i], &inputEndReached[i] ); }); } for (auto& thread : threads) thread.join(); // Stop collecting results after encountering the first thread that couldn't finish. bool endReached = false; size_t totalPatchesExtracted = 0; for (size_t i = 0; i < threadNumber; i++) { totalPatchesExtracted += patchesExtracted[i]; if (inputEndReached[i]) { endReached = true; break; } } *pOutPatchesExtracted = totalPatchesExtracted; *pOutNextBatchIndex = batchStartIndex + totalPatchesExtracted; // No empty skipping, so it's the same. *pOutInputEndReached = endReached; delete[] inputEndReached; } __DLLEXPORT void sparse_insert_into_bna_uint8(void* pArrayRaw, size_t const* pIndices, uint8_t const* pValues, size_t valuesToInsert) { BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw); sparse_insert_into_bna<uint8_t>(pArray, pIndices, pValues, valuesToInsert); } __DLLEXPORT void sparse_insert_slices_into_bna_float32(void* pArrayRaw, size_t const* pIndices, float_t const* pValues, size_t sliceNdim, size_t valueNumber) { auto pArray = reinterpret_cast<BufferedNdArray<float_t>*>(pArrayRaw); sparse_insert_slices_into_bna<float_t>(pArray, pIndices, pValues, sliceNdim, valueNumber); } __DLLEXPORT void sparse_insert_patches_into_bna_uint8(void* pArrayRaw, size_t const* pIndices, uint8_t const* pValues, size_t const* pPatchSize, size_t patchNumber, bool isConstPatch) { BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw); sparse_insert_patches_into_bna(pArray, pIndices, pValues, pPatchSize, patchNumber, isConstPatch); } __DLLEXPORT void sparse_insert_patches_into_bna_float32(void* pArrayRaw, size_t const* pIndices, float_t const* pValues, size_t const* pPatchSize, size_t patchNumber, bool isConstPatch) { BufferedNdArray<float_t>* pArray = reinterpret_cast<BufferedNdArray<float_t>*>(pArrayRaw); sparse_insert_patches_into_bna(pArray, pIndices, pValues, pPatchSize, patchNumber, isConstPatch); } __DLLEXPORT void sparse_insert_const_into_bna_uint8(void* pArrayRaw, size_t const* pIndices, uint8_t constValue, size_t valueNumber) { BufferedNdArray<uint8_t>* pArray = reinterpret_cast<BufferedNdArray<uint8_t>*>(pArrayRaw); sparse_insert_const_into_bna<uint8_t>(pArray, pIndices, constValue, valueNumber); } __DLLEXPORT void smooth_3d_array_average_float(float_t const* pInputData, size_t const* pDataSize, size_t kernelRadius, float_t* pOutputData) { smooth_3d_array_average(pInputData, IndexNd<3>(pDataSize, pDataSize + 3), kernelRadius, pOutputData); } void upscale_attention_patch(float_t const* pAttPatchSource, std::vector<size_t> const& attPatchSize, std::vector<size_t> const& attPatchSliceSizes, std::vector<size_t> const& targetSize, Index4d const& targetSliceSizes, std::vector<float_t>& outputPatch) { for (size_t targetT = 0; targetT < targetSize[0]; targetT++) { size_t patchT = int(roundf(static_cast<float>(targetT) / (targetSize[0] - 1) * (attPatchSize[0] - 1))); for (size_t targetZ = 0; targetZ < targetSize[1]; targetZ++) { // An edge-case for 2D data. size_t patchZ = targetSize[1] > 1 ? int(roundf(static_cast<float>(targetZ) / (targetSize[1] - 1) * (attPatchSize[1] - 1))) : 0; for (size_t targetY = 0; targetY < targetSize[2]; targetY++) { size_t patchY = int(roundf(static_cast<float>(targetY) / (targetSize[2] - 1) * (attPatchSize[2] - 1))); for (size_t targetX = 0; targetX < targetSize[3]; targetX++) { size_t patchX = int(roundf(static_cast<float>(targetX) / (targetSize[3] - 1) * (attPatchSize[3] - 1))); size_t outputIndexFlat = targetT * targetSliceSizes.X[0] + targetZ * targetSliceSizes.X[1] + targetY * targetSliceSizes.X[2] + targetX * targetSliceSizes.X[3]; size_t attIndexFlat = patchT * attPatchSliceSizes[0] + patchZ * attPatchSliceSizes[1] + patchY * attPatchSliceSizes[2] + patchX * attPatchSliceSizes[3]; outputPatch[outputIndexFlat] = *(pAttPatchSource + attIndexFlat); } } } } } /// /// Aggregates a raw 8D attention volume into a 4D volume /// by adding attention from each patch to spatial positions. /// Essentially computes "overall voxel importance". /// // todo Move to a separate project? __DLLEXPORT void aggregate_attention_volume(void* pAttentionRawArray, size_t* pDataSize, size_t* pPatchXSize, size_t* pPredictionStride, void* pAttentionOutArray) { // todo prediction delay isn't needed anymore, because attention is written based on X-indices. constexpr size_t DataNdim = 4; constexpr size_t AttNdim = 8; auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray); auto pAttentionOut = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionOutArray); std::vector<size_t> dataSize{ pDataSize, pDataSize + DataNdim }; std::vector<size_t> patchXSize{ pPatchXSize, pPatchXSize + DataNdim }; Index4d patchXSizeNd{pPatchXSize, pPatchXSize + DataNdim}; std::vector<size_t> predictionStride{ pPredictionStride, pPredictionStride + DataNdim }; std::vector<size_t> attVolSize = pAttentionRaw->GetShape(); // Domain size includes only the spatiotemporal dimensions. std::vector<size_t> attVolDomainSize{ attVolSize.data(), attVolSize.data() + DataNdim }; std::vector<size_t> attPatchSize{ attVolSize.begin() + DataNdim, attVolSize.end() }; auto multiplesFunc = std::multiplies<>(); size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc); size_t patchXSizeFlat = std::accumulate(patchXSize.begin(), patchXSize.end(), size_t{1}, multiplesFunc); size_t attVolDomainSizeFlat = std::accumulate(attVolDomainSize.begin(), attVolDomainSize.end(), size_t{1}, multiplesFunc); std::vector<size_t> attPatchSliceSizes = compute_slice_sizes(attPatchSize); Index4d patchXSliceSizes = compute_slice_sizes_fast<DataNdim>(patchXSize); Index4d dataSliceSizes = compute_slice_sizes_fast<DataNdim>(dataSize); Index4d attVolDomainSliceSizes = compute_slice_sizes_fast<DataNdim>(attVolDomainSize); std::vector<float_t> attPatchRaw(attPatchSizeFlat); std::vector<float_t> attPatchScaled(patchXSizeFlat); std::vector<size_t> attIndexVec(DataNdim, 0); for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++) { Index4d attIndexNd{}; Index4d dataIndexNd{}; unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd); std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector. // Compute the data index of the lower patch corner. Att volume can be smaller in the case of strided prediction. for (size_t dim = 0; dim < DataNdim; dim++) dataIndexNd[dim] = attIndexNd[dim] * predictionStride[dim]; if (attIndexNd[1] == 0 && attIndexNd[2] == 0 && attIndexNd[3] == 0) { auto time = std::chrono::system_clock::now(); std::time_t timeC = std::chrono::system_clock::to_time_t(time); std::string timeStr{std::ctime(&timeC)}; timeStr.pop_back(); printf("[%s] Processing frame %zu / %zu. \n", timeStr.c_str(), attIndexNd[0], attVolSize[0]); std::cout.flush(); } // Read the raw attention patch. pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data()); // Upscale it to match the data patch size. upscale_attention_patch(attPatchRaw.data(), attPatchSize, attPatchSliceSizes, patchXSize, patchXSliceSizes, attPatchScaled); size_t firstIndexFlat = flattenIndex_fast(dataIndexNd, dataSliceSizes); size_t lastIndexFlat = flattenIndex_fast(dataIndexNd + patchXSizeNd, dataSliceSizes); pAttentionOut->_assureRangeInBuffer(firstIndexFlat, lastIndexFlat); for (size_t patchIndexFlat = 0; patchIndexFlat < patchXSizeFlat; patchIndexFlat++) { Index4d patchIndexNd{}; unflattenIndex_fast(patchIndexFlat, patchXSliceSizes, patchIndexNd); size_t outputIndexFlat = flattenIndex_fast(dataIndexNd + patchIndexNd, dataSliceSizes); size_t relIndexFlat = outputIndexFlat - pAttentionOut->_bufferOffset; pAttentionOut->_buffer[relIndexFlat] = pAttentionOut->_buffer[relIndexFlat] + attPatchScaled[patchIndexFlat]; pAttentionOut->_isBufferDirty = true; } } printf("Input buffer efficiency: %f\n", pAttentionRaw->ComputeBufferEfficiency()); printf("Output buffer efficiency: %f\n", pAttentionOut->ComputeBufferEfficiency()); std::cout.flush(); } /// /// A dumb version of attention aggregation that works much faster. /// Used for debugging purposes. /// __DLLEXPORT void aggregate_attention_volume_dumb(void* pAttentionRawArray, size_t* pDataSize, size_t* pPatchSize, size_t predictionDelay, void* pAttentionOutArray) { const size_t dataNdim = 4; const size_t attNdim = 8; auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray); auto pAttentionOut = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionOutArray); std::vector<size_t> dataSize{ pDataSize, pDataSize + dataNdim }; std::vector<size_t> patchSize{ pPatchSize, pPatchSize + dataNdim }; std::vector<size_t> attVolSize = pAttentionRaw->GetShape(); std::vector<size_t> attPatchSize{ attVolSize[4], attVolSize[5], attVolSize[6], attVolSize[7] }; auto multiplesFunc = std::multiplies<>(); size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc); size_t patchSizeFlat = std::accumulate(patchSize.begin(), patchSize.end(), size_t{1}, multiplesFunc); size_t dataSizeFlat = std::accumulate(dataSize.begin(), dataSize.end(), size_t{1}, multiplesFunc); Index4d dataSliceSizes = compute_slice_sizes_fast<4>(dataSize); std::vector<size_t> attPatchSliceSizes = compute_slice_sizes(attPatchSize); std::vector<size_t> attVolSliceSizesVec = compute_slice_sizes(attVolSize); std::vector<float_t> attPatchRaw(attPatchSizeFlat); std::vector<float_t> attPatchScaled(patchSizeFlat); std::vector<size_t> domainLow{ patchSize[0] - 2 + predictionDelay, patchSize[1] / 2, patchSize[2] / 2, patchSize[3] / 2 }; std::vector<size_t> domainHigh{ dataSize[0], dataSize[1] - (patchSize[1] - patchSize[1] / 2) + 1, dataSize[2] - (patchSize[2] - patchSize[2] / 2) + 1, dataSize[3] - (patchSize[3] - patchSize[3] / 2) + 1 }; std::vector<size_t> dataIndexVec(dataNdim, 0); for (size_t dataIndexFlat = 0; dataIndexFlat < dataSizeFlat; dataIndexFlat++) { Index4d dataIndexNd{}; unflattenIndex_fast(dataIndexFlat, dataSliceSizes, dataIndexNd); std::copy(dataIndexNd.X, dataIndexNd.X + dataNdim, dataIndexVec.data()); // Convert to vector. if (dataIndexNd.X[1] == 0 && dataIndexNd.X[2] == 0 && dataIndexNd.X[3] == 0) printf("Processing frame %zu. \n", dataIndexNd.X[0]); if (dataIndexNd.X[0] < domainLow[0] || dataIndexNd.X[0] >= domainHigh[0] || dataIndexNd.X[1] < domainLow[1] || dataIndexNd.X[1] >= domainHigh[1] || dataIndexNd.X[2] < domainLow[2] || dataIndexNd.X[2] >= domainHigh[2] || dataIndexNd.X[3] < domainLow[3] || dataIndexNd.X[3] >= domainHigh[3]) { continue; } // Read the raw attention patch. pAttentionRaw->ReadSlice(dataIndexVec, attNdim - dataNdim, attPatchRaw.data()); // size_t attentionPatchIndexFlat = attPatchRaw.size() / 2; size_t attentionPatchIndexFlat = 0; // printf("%f \n", attPatchRaw[0]); float_t oldValue = pAttentionOut->Read(dataIndexFlat); pAttentionOut->Write(dataIndexFlat, oldValue + attPatchRaw[attentionPatchIndexFlat]); } printf("Input buffer efficiency: %f\n", pAttentionRaw->ComputeBufferEfficiency()); printf("Output buffer efficiency: %f\n", pAttentionOut->ComputeBufferEfficiency()); } /// /// /// __DLLEXPORT void aggregate_attention_volume_local_attention(void* pAttentionRawArray, double_t* pOutAttentionAvg, double_t* pOutAttentionVar) { constexpr size_t DataNdim = 4; constexpr size_t AttNdim = 8; auto pAttentionRaw = reinterpret_cast<BufferedNdArray<float_t>*>(pAttentionRawArray); std::vector<size_t> attVolSize = pAttentionRaw->GetShape(); // Domain size includes only the spatiotemporal dimensions. std::vector<size_t> attVolDomainSize{ attVolSize.data(), attVolSize.data() + DataNdim }; std::vector<size_t> attPatchSize{ attVolSize.begin() + DataNdim, attVolSize.end() }; auto multiplesFunc = std::multiplies<>(); size_t attPatchSizeFlat = std::accumulate(attPatchSize.begin(), attPatchSize.end(), size_t{1}, multiplesFunc); size_t attVolDomainSizeFlat = std::accumulate(attVolDomainSize.begin(), attVolDomainSize.end(), size_t{1}, multiplesFunc); Index4d attVolDomainSliceSizes = compute_slice_sizes_fast<DataNdim>(attVolDomainSize); // Zero-fill the output buffers to be safe. memset(pOutAttentionAvg, 0, attPatchSizeFlat); memset(pOutAttentionVar, 0, attPatchSizeFlat); std::vector<float_t> attPatchRaw(attPatchSizeFlat); std::vector<size_t> attIndexVec(DataNdim, 0); for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++) { Index4d attIndexNd{}; unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd); std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector. // Read the raw attention patch. pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data()); // For each voxel of the attention patch, add its value to the avg. patch buffer. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t oldValue = *(pOutAttentionAvg + patchIndexFlat); *(pOutAttentionAvg + patchIndexFlat) = oldValue + attPatchRaw[patchIndexFlat]; } } // Now that we have a sum of all attention patches, we can compute the average by dividing. // For each voxel of the attention patch, add its value to the avg. patch buffer. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t sum = *(pOutAttentionAvg + patchIndexFlat); *(pOutAttentionAvg + patchIndexFlat) = sum / static_cast<double_t>(attVolDomainSizeFlat); } // Repeat the same loop over the attention patches, now computing their variance. for (size_t attDomainIndexFlat = 0; attDomainIndexFlat < attVolDomainSizeFlat; attDomainIndexFlat++) { Index4d attIndexNd{}; unflattenIndex_fast(attDomainIndexFlat, attVolDomainSliceSizes, attIndexNd); std::copy(attIndexNd.begin(), attIndexNd.end(), attIndexVec.data()); // Convert to vector. // Read the raw attention patch. pAttentionRaw->ReadSlice(attIndexVec, AttNdim - DataNdim, attPatchRaw.data()); // For each voxel of the attention patch, add its value to the avg. patch buffer. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t oldValue = *(pOutAttentionVar + patchIndexFlat); double_t mean = *(pOutAttentionAvg + patchIndexFlat); // Sum average square deviation from the mean. *(pOutAttentionVar + patchIndexFlat) = oldValue + std::pow(attPatchRaw[patchIndexFlat] - mean, 2); } } // Divide by the number of patches to get variance. for (size_t patchIndexFlat = 0; patchIndexFlat < attPatchSizeFlat; patchIndexFlat++) { double_t sum = *(pOutAttentionVar + patchIndexFlat); *(pOutAttentionVar + patchIndexFlat) = sum / static_cast<double_t>(attVolDomainSizeFlat); } } }
46.011605
149
0.606749
50c650e0f191878630bdfa2f07e11db89750fae1
4,011
cpp
C++
flakor/math/GLMatrix.cpp
sainthsu/Flakor
c414502f85d637b82a47754f20d1175e747b0a7d
[ "Libpng", "Apache-2.0", "MIT" ]
4
2015-01-26T08:42:51.000Z
2015-04-14T09:22:12.000Z
flakor/math/GLMatrix.cpp
sainthsu/Flakor
c414502f85d637b82a47754f20d1175e747b0a7d
[ "Libpng", "Apache-2.0", "MIT" ]
null
null
null
flakor/math/GLMatrix.cpp
sainthsu/Flakor
c414502f85d637b82a47754f20d1175e747b0a7d
[ "Libpng", "Apache-2.0", "MIT" ]
null
null
null
#include "macros.h" #include <assert.h> #include "math/GLMatrix.h" FLAKOR_NS_BEGIN MatrixStack* modelviewStack; MatrixStack* projectionStack; MatrixStack* textureStack; MatrixStack* currentStack = NULL; static unsigned char initialized = 0; #ifdef __cplusplus extern "C" { #endif void lazyInitialize() { if (!initialized) { Matrix4* identity = new Matrix4(); //Temporary identity matrix //Initialize all 3 stacks modelviewStack = new MatrixStack(); projectionStack = new MatrixStack(); textureStack = new MatrixStack(); currentStack = modelviewStack; initialized = 1; //Make sure that each stack has the identity matrix modelviewStack->push(identity); projectionStack->push(identity); textureStack->push(identity); } } void GLMode(StackMode mode) { lazyInitialize(); switch(mode) { case GL_MODELVIEW: currentStack = modelviewStack; break; case GL_PROJECTION: currentStack = projectionStack; break; case GL_TEXTURE: currentStack = textureStack; break; default: assert(0 && "Invalid matrix mode specified"); //TODO: Proper error handling break; } } void GLPush(void) { Matrix4* top = new Matrix4(); lazyInitialize(); //Initialize the stacks if they haven't been already //Duplicate the top of the stack (i.e the current matrix) top->set(currentStack->top->get(),COLUMN_MAJOR); currentStack->push(top); } void GLPop(void) { assert(initialized && "Cannot Pop empty matrix stack"); //No need to lazy initialize, you shouldn't be popping first anyway! currentStack->pop(NULL); } void GLLoadIdentity() { lazyInitialize(); currentStack->top->identity(); //Replace the top matrix with the identity matrix } void GLFreeAll() { //Clear the matrix stacks modelviewStack->release(); projectionStack->release(); textureStack->release(); //Delete the matrices initialized = 0; //Set to uninitialized currentStack = NULL; //Set the current stack to point nowhere } void GLMultiply(const Matrix4* in) { lazyInitialize(); *currentStack->top = (*currentStack->top)*(*in); } void GLLoad(Matrix4* in) { lazyInitialize(); in->set(currentStack->top->get(),COLUMN_MAJOR); } void GLGet(StackMode mode, Matrix4* out) { lazyInitialize(); switch(mode) { case GL_MODELVIEW: FKLOG("MV TOP:%s",modelviewStack->top->toString()); out->set(modelviewStack->top->get(),COLUMN_MAJOR); break; case GL_PROJECTION: FKLOG("P TOP:%s",projectionStack->top->toString()); out->set(projectionStack->top->get(),COLUMN_MAJOR); break; case GL_TEXTURE: FKLOG("Tex TOP:%s",textureStack->top->toString()); out->set(textureStack->top->get(),COLUMN_MAJOR); break; default: assert(1 && "Invalid matrix mode specified"); //TODO: Proper error handling break; } } void GLTranslatef(float x, float y, float z) { Matrix4 *translation = new Matrix4(); //Create a rotation matrix using the axis and the angle translation->translate(x,y,z); //Multiply the rotation matrix by the current matrix *currentStack->top = (*currentStack->top)*(*translation); } void GLRotatef(float angle, float x, float y, float z) { //Create an axis vector Vector3* axis = new Vector3(x, y, z); Matrix4* rotation = new Matrix4(); //Create a rotation matrix using the axis and the angle rotation->rotate(angle, *axis); //Multiply the rotation matrix by the current matrix *currentStack->top = (*currentStack->top)*(*rotation); } void GLScalef(float x, float y, float z) { Matrix4* scaling = new Matrix4(); scaling->scale(x, y, z); *currentStack->top = (*currentStack->top)*(*scaling); } #ifdef __cplusplus } #endif FLAKOR_NS_END
23.051724
87
0.640987
50c673c4e99d14630c64df5ad4f9829184d85221
9,577
cpp
C++
src/gfx/graphics/vulkan/swapchain_vulkan.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
src/gfx/graphics/vulkan/swapchain_vulkan.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
src/gfx/graphics/vulkan/swapchain_vulkan.cpp
johannes-braun/graphics_utilities
191772a3ff1c14eea74b9b5614b6226cf1f8abb7
[ "MIT" ]
null
null
null
#include "init_struct.hpp" #include "swapchain_vulkan.hpp" #include "image_view_vulkan.hpp" #include "result.hpp" namespace gfx { inline namespace v1 { namespace vulkan { uint32_t swapchain_implementation::current_image() const noexcept { return _current_image; } void swapchain_implementation::present() { if (_presented) { vkResetCommandBuffer(_primary_command_buffers[_current_image], 0); init<VkCommandBufferBeginInfo> begin_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; vkBeginCommandBuffer(_primary_command_buffers[_current_image], &begin_info); init<VkImageMemoryBarrier> imb{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; imb.srcAccessMask = 0; imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT; imb.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imb.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imb.image = _temp_images[_current_image]; imb.oldLayout = VK_IMAGE_LAYOUT_GENERAL; imb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; imb.subresourceRange.baseArrayLayer = 0; imb.subresourceRange.baseMipLevel = 0; imb.subresourceRange.layerCount = 1; imb.subresourceRange.levelCount = 1; vkCmdPipelineBarrier(_primary_command_buffers[_current_image], VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 0, nullptr, 1, &imb); vkEndCommandBuffer(_primary_command_buffers[_current_image]); std::array<VkSemaphore, 1> wait_semaphores{_present_semaphore}; std::array<VkPipelineStageFlags, 1> wait_masks{VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; std::array<VkCommandBuffer, 1> command_buffers{_primary_command_buffers[_current_image]}; init<VkSubmitInfo> submit{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submit.commandBufferCount = 1; submit.pCommandBuffers = &_primary_command_buffers[_current_image]; submit.pWaitSemaphores = std::data(wait_semaphores); submit.waitSemaphoreCount = static_cast<u32>(std::size(wait_semaphores)); submit.pSignalSemaphores = &_render_semaphore; submit.signalSemaphoreCount = 1; submit.pWaitDstStageMask = std::data(wait_masks); // In graphics queue. Waits on all posted semaphores. check_result(vkQueueSubmit(_graphics_queue, 1, &submit, _render_fences[_current_image])); uint32_t idx = _current_image; init<VkPresentInfoKHR> present_info{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; present_info.pImageIndices = &idx; present_info.pSwapchains = &_swapchain; present_info.swapchainCount = 1; present_info.pWaitSemaphores = &_render_semaphore; present_info.waitSemaphoreCount = 1; VkResult swapchain_result; present_info.pResults = &swapchain_result; // Solely in present queue, but waits for _render_semaphore which is triggered only after all posted semaphores are signaled. VkResult present_result = check_result(vkQueuePresentKHR(_present_queue, &present_info)); check_result(swapchain_result); } check_result(vkAcquireNextImageKHR(_device, _swapchain, std::numeric_limits<uint64_t>::max(), _present_semaphore, nullptr, &_current_image)); // Wait until last frame using this image has finished rendering check_result(vkWaitForFences(_device, 1, &_render_fences[_current_image], true, std::numeric_limits<uint64_t>::max())); check_result(vkResetFences(_device, 1, &_render_fences[_current_image])); _presented = true; } void swapchain_implementation::resize(uint32_t width, uint32_t height) { auto& ctx = context::current(); _ctx_impl = static_cast<context_implementation*>(std::any_cast<detail::context_implementation*>(ctx->implementation())); if (!_render_fences.empty()) vkWaitForFences(_ctx_impl->device(), static_cast<u32>(_render_fences.size()), _render_fences.data(), true, default_fence_timeout); vkDeviceWaitIdle(_ctx_impl->device()); this->~swapchain_implementation(); _presented = false; _device = _ctx_impl->device(); init<VkSwapchainCreateInfoKHR> swapchain_info{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; swapchain_info.clipped = true; swapchain_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; swapchain_info.imageArrayLayers = 1; swapchain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; swapchain_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_STORAGE_BIT; swapchain_info.pQueueFamilyIndices = &(_ctx_impl->queue_families()[fam::present]); swapchain_info.queueFamilyIndexCount = 1; VkSurfaceCapabilitiesKHR capabilities; check_result(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &capabilities)); swapchain_info.surface = _ctx_impl->surface(); swapchain_info.imageExtent = VkExtent2D{width, height}; swapchain_info.minImageCount = ctx->options().framebuffer_images; swapchain_info.preTransform = capabilities.currentTransform; u32 fmt_count = 0; check_result(vkGetPhysicalDeviceSurfaceFormatsKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &fmt_count, nullptr)); std::vector<VkSurfaceFormatKHR> formats(fmt_count); check_result(vkGetPhysicalDeviceSurfaceFormatsKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &fmt_count, formats.data())); if (const auto it = std::find_if(formats.begin(), formats.end(), [](const VkSurfaceFormatKHR& fmt) { return fmt.format == VK_FORMAT_B8G8R8A8_UNORM && fmt.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; }); it == formats.end()) { elog << "Did not find bgra8 format with srgb-nonlinear color space."; } else { swapchain_info.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; swapchain_info.imageFormat = VK_FORMAT_B8G8R8A8_UNORM; } u32 pm_count = 0; check_result(vkGetPhysicalDeviceSurfacePresentModesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &pm_count, nullptr)); std::vector<VkPresentModeKHR> present_modes(pm_count); check_result(vkGetPhysicalDeviceSurfacePresentModesKHR(_ctx_impl->gpu(), _ctx_impl->surface(), &pm_count, present_modes.data())); if (const auto it = std::find_if(present_modes.begin(), present_modes.end(), [](const VkPresentModeKHR& mode) { return mode == VK_PRESENT_MODE_MAILBOX_KHR; }); it == present_modes.end()) { elog << "Did not find mailbox present mode."; } else swapchain_info.presentMode = VK_PRESENT_MODE_MAILBOX_KHR; check_result(vkCreateSwapchainKHR(_device, &swapchain_info, nullptr, &_swapchain)); _present_queue = _ctx_impl->queues()[fam::present]; _graphics_queue = _ctx_impl->queues()[fam::graphics]; // TODO: u32 img_count = 0; check_result(vkGetSwapchainImagesKHR(_device, _swapchain, &img_count, nullptr)); _temp_images.resize(img_count); check_result(vkGetSwapchainImagesKHR(_device, _swapchain, &img_count, _temp_images.data())); init<VkCommandBufferAllocateInfo> cmd_info{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cmd_info.commandBufferCount = static_cast<uint32_t>(_temp_images.size()); cmd_info.commandPool = _ctx_impl->command_pools()[fam::graphics]; cmd_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; _primary_command_buffers.resize(_temp_images.size()); check_result(vkAllocateCommandBuffers(_device, &cmd_info, _primary_command_buffers.data())); _command_pool = _ctx_impl->command_pools()[fam::graphics]; init<VkSemaphoreCreateInfo> sem_info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; check_result(vkCreateSemaphore(_device, &sem_info, nullptr, &_present_semaphore)); check_result(vkCreateSemaphore(_device, &sem_info, nullptr, &_render_semaphore)); init<VkFenceCreateInfo> fen_info{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; fen_info.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (int i = 0; i < _temp_images.size(); ++i) { check_result(vkCreateFence(_device, &fen_info, nullptr, &_render_fences.emplace_back())); image_view& view = _image_views.emplace_back(); static_cast<image_view_implementation*>(&*view.implementation())->initialize_vk(gfx::imgv_type::image2d, gfx::format::bgra8unorm, _temp_images[i], 0, 1, 0, 1); } } const std::vector<image_view>& swapchain_implementation::image_views() const { return _image_views; } handle swapchain_implementation::api_handle() { return _swapchain; } swapchain_implementation::~swapchain_implementation() { if (_swapchain) vkDestroySwapchainKHR(_device, _swapchain, nullptr); for (auto& f : _render_fences) vkDestroyFence(_device, f, nullptr); if (_device && !_primary_command_buffers.empty()) vkFreeCommandBuffers(_device, _command_pool, static_cast<u32>(_primary_command_buffers.size()), _primary_command_buffers.data()); if (_present_semaphore) vkDestroySemaphore(_device, _present_semaphore, nullptr); if (_render_semaphore) vkDestroySemaphore(_device, _render_semaphore, nullptr); } } // namespace vulkan } // namespace v1 } // namespace gfx
49.365979
161
0.732066
50c7ba74baa9d0d989196197f1e0fc6c28ef57e1
1,044
cc
C++
shuffle-an-array.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
shuffle-an-array.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
shuffle-an-array.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <vector> #include <random> class Solution { public: std::vector<int> arr_; std::random_device dev_; std::mt19937 rng_; std::vector<std::uniform_int_distribution<int>> dists_; std::vector<int> res_; Solution(std::vector<int>& nums) : arr_(nums), dev_(), rng_(dev_()), res_(nums) { dists_.reserve(nums.size()); for (int i = 0; i < res_.size() - 1; i++) dists_.emplace_back(i, res_.size() - 1); } /** Resets the array to its original configuration and return it. */ std::vector<int> reset() { return arr_; } /** Returns a random shuffling of the array. */ std::vector<int> shuffle() { for (int i = 0; i < res_.size() - 1; i++) { std::swap(res_[dists_[i](rng_)], res_[i]); } return res_; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(nums); * vector<int> param_1 = obj->reset(); * vector<int> param_2 = obj->shuffle(); */
26.1
83
0.564176
50c7d8124ac98e54fedf686fc71097ffdb7e174f
4,919
cpp
C++
src/qt/distributedcomputingdialog.cpp
wolfeye88/BiblePay-BBP-
fc668d5b4051e51c48e944c9687587300ce25946
[ "MIT" ]
null
null
null
src/qt/distributedcomputingdialog.cpp
wolfeye88/BiblePay-BBP-
fc668d5b4051e51c48e944c9687587300ce25946
[ "MIT" ]
null
null
null
src/qt/distributedcomputingdialog.cpp
wolfeye88/BiblePay-BBP-
fc668d5b4051e51c48e944c9687587300ce25946
[ "MIT" ]
null
null
null
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "distributedcomputingdialog.h" #include "ui_distributedcomputingdialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "util.h" #include "optionsmodel.h" #include "platformstyle.h" #include "receiverequestdialog.h" #include "recentrequeststablemodel.h" #include "walletmodel.h" #include "main.h" #include "podc.h" #include <QAction> #include <QCursor> #include <QItemSelection> #include <QMessageBox> #include <QScrollBar> #include <QTextDocument> QString ToQstring(std::string s); std::string FromQStringW(QString qs); std::string RoundToString(double d, int place); double GetTaskWeight(std::string sCPID); double GetUTXOWeight(std::string sCPID); std::string AssociateDCAccount(std::string sProjectId, std::string sBoincEmail, std::string sBoincPassword, std::string sUnbankedPublicKey, bool fForce); std::string FixRosetta(std::string sEmail, std::string sPass, std::string& sError); std::string RosettaDiagnostics(std::string sEmail, std::string sPass, std::string& sError); int GetBoincTaskCount(); DistributedComputingDialog::DistributedComputingDialog(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::DistributedComputingDialog), model(0), platformStyle(platformStyle) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!platformStyle->getImagesOnButtons()) { ui->btnAssociate->setIcon(QIcon()); } else { ui->btnAssociate->setIcon(QIcon(":/icons/" + theme + "/receiving_addresses")); } std::string sProject = "Rosetta@Home"; ui->cmbProjectName->clear(); ui->cmbProjectName->addItem(ToQstring(sProject)); // Populate the CPIDs and Magnitude UpdateMagnitudeDisplay(); } void DistributedComputingDialog::UpdateMagnitudeDisplay() { std::string sPrimaryCPID = GetElement(msGlobalCPID, ";", 0); double dTaskWeight = GetTaskWeight(sPrimaryCPID); double dUTXOWeight = GetUTXOWeight(sPrimaryCPID); std::string sInfo = "<br> CPIDS: " + msGlobalCPID + "<br> Magnitude: " + RoundToString(mnMagnitude,2) + "<br> Task Weight: " + RoundToString(dTaskWeight, 0) + "; UTXO Weight: " + RoundToString(dUTXOWeight, 0); ui->txtInfo->setText(ToQstring(sInfo)); int nTasks = GetBoincTaskCount(); ui->lcdTasks->display(nTasks); } void DistributedComputingDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) { UpdateMagnitudeDisplay(); } } DistributedComputingDialog::~DistributedComputingDialog() { delete ui; } void DistributedComputingDialog::clear() { ui->txtPassword->setText(""); ui->txtEmail->setText(""); } /* void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); } */ void DistributedComputingDialog::on_btnAssociate_clicked() { if(!model || !model->getOptionsModel()) return; std::string sEmail = FromQStringW(ui->txtEmail->text()); std::string sPassword = FromQStringW(ui->txtPassword->text()); std::string sError = AssociateDCAccount("project1", sEmail, sPassword, "", false); std::string sNarr = (sError.empty()) ? "Successfully advertised DC-Key. Type exec getboincinfo to find more researcher information. Welcome Aboard! Thank you for donating your clock-cycles to help cure cancer!" : sError; QMessageBox::warning(this, tr("Boinc Researcher Association Result"), ToQstring(sNarr), QMessageBox::Ok, QMessageBox::Ok); clear(); UpdateMagnitudeDisplay(); } void DistributedComputingDialog::on_btnFix_clicked() { if(!model || !model->getOptionsModel()) return; std::string sEmail = FromQStringW(ui->txtEmail->text()); std::string sPassword = FromQStringW(ui->txtPassword->text()); std::string sError = ""; std::string sHTML = FixRosetta(sEmail, sPassword, sError); sHTML = strReplace(sHTML, "\n", "<br>"); std::string sNarr = (sError.empty()) ? sHTML : sError; QMessageBox::warning(this, tr("Fix BOINC Configuration"), ToQstring(sNarr), QMessageBox::Ok, QMessageBox::Ok); clear(); UpdateMagnitudeDisplay(); } void DistributedComputingDialog::on_btnDiagnostics_clicked() { if(!model || !model->getOptionsModel()) return; std::string sEmail = FromQStringW(ui->txtEmail->text()); std::string sPassword = FromQStringW(ui->txtPassword->text()); std::string sError = ""; std::string sHTML = RosettaDiagnostics(sEmail, sPassword, sError); sHTML = strReplace(sHTML, "\n", "<br>"); std::string sNarr = (sError.empty()) ? sHTML : sError; QMessageBox::warning(this, tr("BOINC Diagnostics Result"), ToQstring(sNarr), QMessageBox::Ok, QMessageBox::Ok); clear(); UpdateMagnitudeDisplay(); }
32.150327
224
0.725351
50ccf6e8002517cfa041552b8f5ac2102158a917
83
cpp
C++
ksn-2021-pertahanan/solution-1.cpp
ia-toki/ksn-2021
e925029fa9ce6198aae489c5f8505c47078da28e
[ "CC-BY-4.0" ]
null
null
null
ksn-2021-pertahanan/solution-1.cpp
ia-toki/ksn-2021
e925029fa9ce6198aae489c5f8505c47078da28e
[ "CC-BY-4.0" ]
null
null
null
ksn-2021-pertahanan/solution-1.cpp
ia-toki/ksn-2021
e925029fa9ce6198aae489c5f8505c47078da28e
[ "CC-BY-4.0" ]
1
2021-12-05T04:17:41.000Z
2021-12-05T04:17:41.000Z
#include <bits/stdc++.h> using namespace std; int main() { cout << 9 << '\n'; }
11.857143
24
0.554217
50cd5b9f93c313756548633084e08427f4b688bd
8,537
cpp
C++
src/SamplesLibElise/CPP_CilliaImg.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
src/SamplesLibElise/CPP_CilliaImg.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
src/SamplesLibElise/CPP_CilliaImg.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MiccMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSCoordones_global_essai.txte image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "StdAfx.h" int Homol2GCP_main(int argc,char ** argv) { std::string aFile1; std::string aFile2; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Sentinel Homol" ) << EAMC(aFile2, "tfw file") << EAMC(aFileOut, "out= global coordinate file"), LArgMain() ); ELISE_fp aFIn(aFile1.c_str(),ELISE_fp::READ); ELISE_fp aFIn2(aFile2.c_str(),ELISE_fp::READ); FILE * aFOut = FopenNN(aFileOut.c_str(),"w","Cillia") ; char * aLine; std::vector<Pt2dr> aV2Ok; // std::vector<Pt3dr> aV3Ok; std::vector<double> tfw; while ((aLine = aFIn2.std_fgets())) { double V ; int aNb=sscanf(aLine,"%lf ",&V ); ELISE_ASSERT(aNb==1,"Could not read 2 double values"); tfw.push_back(V); } double tfw1 = tfw.at(0); double tfw4 = tfw.at(3); double tfw5 = tfw.at(4); double tfw6 = tfw.at(5); while ((aLine = aFIn.std_fgets())) { Pt2dr aP; int aNb = sscanf(aLine,"%lf %lf",&aP.x , &aP.y); ELISE_ASSERT(aNb==2,"Could not read 2 double values"); aV2Ok.push_back(aP); fprintf(aFOut,"%lf %.14lf ", aP.x *tfw1 + tfw5 , aP.y * tfw4 + tfw6 ); } return (1); delete aLine; delete aFOut; fclose(aFOut); // return(1); } int GlobToLocal_main(int argc,char ** argv) { std::string aFile1; std::string aFile2; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Global coordinate " ) << EAMC(aFile2, " tfw file") << EAMC(aFileOut, "Out= Local coordinate file"), LArgMain() ); ELISE_fp aFIn2(aFile2.c_str(),ELISE_fp::READ); char * aLine; std::vector<double> tfw; while ((aLine = aFIn2.std_fgets())) { double V ; int aNb=sscanf(aLine,"%lf ",&V ); ELISE_ASSERT(aNb==1,"Could not read 2 double values") tfw.push_back(V); } double tfw1 = tfw.at(0); double tfw4 = tfw.at(3); double tfw5 = tfw.at(4); double tfw6 = tfw.at(5); ELISE_fp aFIn(aFile1.c_str(),ELISE_fp::READ); FILE * aFOut = FopenNN(aFileOut.c_str(),"w","Cilliap") ; char * aLine2; std::vector<Pt2dr> aV2Ok; int aCnt=0; while ((aLine2 = aFIn.std_fgets())) { aCnt++; Pt2dr aP; int aNb= sscanf(aLine2,"%lf %lf",&aP.x , &aP.y); ELISE_ASSERT(aNb==2,"Could not read 2 double values"); aV2Ok.push_back(aP); std::cout << aCnt << " " << aP << "\n"; } for(int aK=0; aK<int(aV2Ok.size()-1); aK++) { fprintf(aFOut,"%.14lf %.14lf\n ", (aV2Ok.at(aK).x - tfw5)/ tfw1 , (aV2Ok.at(aK).y- tfw6) / tfw4 ); } fprintf(aFOut,"%.14lf %.14lf ", (aV2Ok.at(aV2Ok.size()-1).x - tfw5)/ tfw1 , (aV2Ok.at(aV2Ok.size()-1).y- tfw6) / tfw4 ); fclose(aFOut); delete aLine; delete aLine2; return EXIT_SUCCESS; } int ExtractZ_main(int argc,char ** argv) { std::string aFile1; std::string aImg; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Local coordinate " ) << EAMC(aImg, "SRTM image") << EAMC(aFileOut, "Out= coordinate xyz file"), LArgMain() ); // Read of an image Tiff_Im ImgTiff = Tiff_Im::UnivConvStd(aImg.c_str()); Im2D_REAL4 I(ImgTiff.sz().x, ImgTiff.sz().y); ELISE_COPY ( I.all_pts(), ImgTiff.in(), I.out() ); //interpolation cInterpolBilineaire<REAL4> * bicu = new cInterpolBilineaire<REAL4>; //Lecture de point qui sont deja dans l'espace d'image SRTM" ELISE_fp aFIn(aFile1.c_str(),ELISE_fp::READ); std::vector<Pt2dr> aV2Ok; char * aLine; while ((aLine = aFIn.std_fgets())) { Pt2dr aP; int aNb=sscanf(aLine,"%lf %lf",&aP.x , &aP.y); ELISE_ASSERT(aNb==2,"Could not read 2 double values"); aV2Ok.push_back(aP); //std::cout << " " << aP << "\n"; } // Pt2dr aP; // Recuperation de valeurs Z sur SRTM FILE *aFOut = FopenNN(aFileOut.c_str(),"w","Cillia") ; double aZTmp=0; int aCntOut=0; for(int aK=0; aK< int(aV2Ok.size()); aK++) { if( (aV2Ok.at(aK).x >=0) && (aV2Ok.at(aK).x <ImgTiff.sz().x) && (aV2Ok.at(aK).y >=0) && (aV2Ok.at(aK).y <ImgTiff.sz().y) ) { aZTmp = I.Get(aV2Ok.at(aK), *bicu , 0.5); fprintf(aFOut, "%lf %lf %lf \n", aV2Ok.at(aK).x, aV2Ok.at(aK).y, aZTmp); } else { aCntOut++; std::cout << "Point out of image=" << aV2Ok.at(aK) << " " << aCntOut << "\n"; } } return EXIT_SUCCESS; fclose(aFOut); } int XYZ_Global_main(int argc,char ** argv) { std::string aFile1; std::string aFile2; std::string aFileOut; ElInitArgMain ( argc ,argv , LArgMain() << EAMC(aFile1, "Global coordinate " ) << EAMC(aFile2, " xyz file") << EAMC(aFileOut, "Out= file XYZ global"), LArgMain() ); ELISE_fp aFIn1(aFile1.c_str(),ELISE_fp::READ); ELISE_fp aFIn2(aFile2.c_str(),ELISE_fp::READ); // std::string aNameOut="XYZ_global_Full_final.txt"; FILE * aFOut = FopenNN(aFileOut.c_str(),"w","Cillia") ; std::vector<Pt2dr> aV2Ok; char * aLine1; std::vector<Pt3dr> aV3Ok; char * aLine2; Pt3dr aP3d; Pt2dr aP2d; std::vector<Pt2dr> aVXY; std::vector<double> aVZ; //read the first file while ( (aLine1 = aFIn1.std_fgets()) ) { int aNb1 = sscanf(aLine1,"%lf %lf", &aP2d.x , &aP2d.y); ELISE_ASSERT(aNb1==2,"Could not read 2 double values"); aVXY.push_back(aP2d); std::cout << "AA=" << aP2d.x <<"\n" ; } //read the second file while ( (aLine2=aFIn2.std_fgets()) ) { int aNb2 = sscanf(aLine2,"%lf %lf %lf", &aP3d.x , &aP3d.y , &aP3d.z); ELISE_ASSERT(aNb2==3,"Could not read 3 double values"); aVZ.push_back(aP3d.z); } if( aVZ.size() == aVXY.size() ) for( int aK=0; aK<int(aVZ.size()); aK++) fprintf(aFOut, "%lf %lf %lf\n",aVXY.at(aK).x ,aVXY.at(aK).y , aVZ.at(aK) ); else ELISE_ASSERT(false,"The number of points in your files is not the same") return(1); }
26.512422
121
0.538597
50cd7e3c47b62a36e926996848352808662522a0
831
hh
C++
src/websocket_server/Packets/Out/WeatherStatusPacket.hh
3n16m4/websocket-server
5b6575bbd459feeef459b20a093ada3fd9d035e5
[ "MIT" ]
2
2020-11-16T15:53:39.000Z
2021-03-20T09:08:36.000Z
src/websocket_server/Packets/Out/WeatherStatusPacket.hh
3n16m4/websocket-server
5b6575bbd459feeef459b20a093ada3fd9d035e5
[ "MIT" ]
2
2020-12-09T23:54:55.000Z
2020-12-11T20:14:52.000Z
src/websocket_server/Packets/Out/WeatherStatusPacket.hh
3n16m4/websocket-server
5b6575bbd459feeef459b20a093ada3fd9d035e5
[ "MIT" ]
1
2021-03-20T09:08:41.000Z
2021-03-20T09:08:41.000Z
#ifndef WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH #define WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH #include <array> namespace amadeus { enum class WebSocketSessionFlag : std::uint8_t; #pragma pack(push, 1) namespace out { /// \brief Defines the WeatherStatusPacket which is sent by the server if a /// WebSocketSession requested a weather update for a specific TCP connection /// (µC). struct WeatherStatusPacket { /// Packet header. std::uint8_t header{0x04}; /// A unique identifier for the corresponding TCP Client which is used for /// authentication. std::array<std::uint8_t, 16> uuid; /// Reserved server specific flag, not used anymore. WebSocketSessionFlag flag; }; #pragma pack(pop) } // namespace out } // namespace amadeus #endif // !WEBSOCKET_SERVER_OUT_WEATHER_STATUS_PACKET_HH
29.678571
78
0.758123
50d35331a0380b1acbd4127c8f8c2c6966f4b433
831
hpp
C++
cpp2c/test_data/mmalloc.hpp
mendlin/SIMD-libgen
0f386bb639c829275a00f46c4b31d59c5ed84a28
[ "AFL-1.1" ]
1
2021-01-07T03:18:27.000Z
2021-01-07T03:18:27.000Z
cpp2c/test_data/mmalloc.hpp
Logicalmars/SIMD-libgen
0f386bb639c829275a00f46c4b31d59c5ed84a28
[ "AFL-1.1" ]
null
null
null
cpp2c/test_data/mmalloc.hpp
Logicalmars/SIMD-libgen
0f386bb639c829275a00f46c4b31d59c5ed84a28
[ "AFL-1.1" ]
1
2021-11-29T07:28:13.000Z
2021-11-29T07:28:13.000Z
#ifndef ALIGNED_MMALLOC_HPP #define ALIGNED_MMALLOC_HPP /*============================================================================= allocator.hpp - Platform independent aligned memory allocation. Created on: 06-December-2011 Author: Ken Herdy Description: TODO - Wrap routines inside a class scope and/or C++ custom namespace. =============================================================================*/ #include "bitblock.hpp" #if defined USE_NEON #error "Neon aligned memory allocation not implemented. Aborting compilation." #else // USE_SSE template <class T> T * simd_malloc(uint32_t n) { return (T*)_mm_malloc(n*sizeof(T), sizeof(BitBlock)); } template <class T> void simd_free(T* p) { if(p != NULL) { _mm_free(p); p = NULL; } } #endif #endif // ALIGNED_MMALLOC_HPP
22.459459
79
0.565584
50dae8608e9b682934ff5632912f808772132924
4,010
cpp
C++
test/test_array_derivatives.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
131
2016-07-06T04:06:49.000Z
2022-03-19T22:34:47.000Z
test/test_array_derivatives.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
19
2016-06-20T20:20:23.000Z
2022-02-15T14:55:01.000Z
test/test_array_derivatives.cpp
yairchu/Adept-2
3b4f898c74139618464ccd8e8df0934aed9ed6a2
[ "Apache-2.0" ]
31
2017-10-07T00:07:49.000Z
2022-03-05T17:51:17.000Z
/* test_array_derivatives.cpp - Test derivatives of array expressions Copyright (C) 2017 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. */ #include <adept_arrays.h> // Arbitrary algorithm converting array of general type A to scalar of // type S, which may be active or passive template <class A, class S> void algorithm(const A& x, S& y) { using namespace adept; A tmp; intVector index(2); index << 1, 0; tmp = atan2((exp(x) * x), spread<0>(x(index,1),2)) / x(0,0); y = sum(tmp); } int main(int argc, const char** argv) { using namespace adept; Stack stack; // Matrix dimension static const int N = 2; static const Real MAX_FRAC_ERR = 1.0e-5; // Perturbation size for numerical calculation Real dx = 1.0e-6; if (sizeof(Real) < 8) { // Single precision only works with larger perturbations dx = 1.0e-4; } // Maximum fractional error Real max_frac_err; bool error_too_large = false; // Input data Matrix X(N,N); X << 2, 3, 5, 7; // Numerical calculation std::cout << "NUMERICAL CALCULATION\n"; Matrix dJ_dx_num(N,N); { Real J; algorithm(X, J); std::cout << "J = " << J << "\n"; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { Matrix Xpert(N,N); Xpert = X; Xpert(i,j) += dx; Real Jpert; algorithm(Xpert, Jpert); dJ_dx_num(i,j) = (Jpert - J) / dx; } } } std::cout << "dJ_dx_num = " << dJ_dx_num << "\n"; std::cout << "\nNUMERICAL CALCULATION WITH \"FixedArray\"\n"; Matrix22 dJ_dx_num_FixedArray; { Real J; algorithm(X, J); std::cout << "J = " << J << "\n"; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { Matrix22 Xpert = X; Xpert(i,j) += dx; Real Jpert; algorithm(Xpert, Jpert); dJ_dx_num_FixedArray(i,j) = (Jpert - J) / dx; } } } std::cout << "dJ_dx_num_FixedArray = " << dJ_dx_num_FixedArray << "\n"; // Adept calculation with aArray std::cout << "\nADEPT CALCULATION WITH \"aArray\"\n"; Matrix dJ_dx_adept_Array(N,N); { aMatrix aX = X; stack.new_recording(); aReal aJ; algorithm(aX, aJ); std::cout << "J = " << aJ << "\n"; aJ.set_gradient(1.0); stack.reverse(); dJ_dx_adept_Array = aX.get_gradient(); } std::cout << "dJ_dx_adept_Array = " << dJ_dx_adept_Array << "\n"; max_frac_err = maxval(abs(dJ_dx_adept_Array-dJ_dx_num)/dJ_dx_num); if (max_frac_err <= MAX_FRAC_ERR) { std::cout << "max fractional error = " << max_frac_err << ": PASSED\n"; } else { std::cout << "max fractional error = " << max_frac_err << ": FAILED\n"; error_too_large = true; } // Adept calculation with aFixedArray std::cout << "\nADEPT CALCULATION WITH \"aFixedArray\"\n"; Matrix dJ_dx_adept_FixedArray; { aMatrix22 aX = X; stack.new_recording(); aReal aJ; algorithm(aX, aJ); std::cout << "J = " << aJ << "\n"; aJ.set_gradient(1.0); stack.reverse(); dJ_dx_adept_FixedArray = aX.get_gradient(); } std::cout << "dJ_dx_adept_FixedArray = " << dJ_dx_adept_FixedArray << "\n"; max_frac_err = maxval(abs(dJ_dx_adept_FixedArray-dJ_dx_num)/dJ_dx_num); if (max_frac_err <= MAX_FRAC_ERR) { std::cout << "max fractional error = " << max_frac_err << ": PASSED\n"; } else { std::cout << "max fractional error = " << max_frac_err << ": FAILED\n"; error_too_large = true; } std::cout << "\n"; if (error_too_large) { std::cerr << "*** Error: fractional error in the derivatives of some configurations too large\n"; if (sizeof(Real) < 8) { std::cerr << "*** (but you are using less than double precision so it is not surprising)\n"; } return 1; } else { return 0; } }
23.727811
101
0.610474
50db783e21b99550fa09f93b00936396feab61e9
9,908
hpp
C++
ze_common/include/ze/common/ringbuffer.hpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
30
2016-09-27T07:41:28.000Z
2021-12-03T20:44:28.000Z
ze_common/include/ze/common/ringbuffer.hpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
1
2018-12-18T15:53:06.000Z
2018-12-21T03:10:06.000Z
ze_common/include/ze/common/ringbuffer.hpp
rockenbf/ze_oss
ee04158e2d51acb07a267196f618e9afbc3ffd83
[ "BSD-3-Clause" ]
12
2016-11-05T07:51:29.000Z
2020-07-13T02:26:08.000Z
// Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL ETH Zurich, Wyss Zurich, Zurich Eye BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #include <map> #include <tuple> #include <thread> #include <utility> #include <mutex> #include <Eigen/Dense> #include <ze/common/logging.hpp> #include <ze/common/ring_view.hpp> #include <ze/common/types.hpp> #include <ze/common/time_conversions.hpp> namespace ze { //! @todo: move the interpolators somewhere where they make more sense? //! //! Interpolators have to implement: //! _ interpolate(Ringbuffer<...>*, int64_t time, Ringbuffer<...>timering_t::iterator); //! Passing the (optional) interator to the timestamp right before the to be //! interpolated value speeds up the process. //! The passed it_before is expected to be valid. //! //! A nearest neighbour "interpolator". struct InterpolatorNearest { template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time, typename Ringbuffer_T::timering_t::iterator it_before) { // the end value auto it_after = it_before + 1; if (it_after == buffer->times_.end()) { LOG(WARNING) << "Interpolation hit end of buffer."; return buffer->dataAtTimeIterator(it_before); } // The times are ordered, we can guarantee those differences to be positive if ((time - *it_before) < (*it_after - time)) { return buffer->dataAtTimeIterator(it_before); } return buffer->dataAtTimeIterator(it_after); } template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time) { auto it_before = buffer->iterator_equal_or_before(time); // caller should check the bounds: CHECK(it_before != buffer->times_.end()); return interpolate(buffer, time, it_before); } }; //! A simple linear interpolator struct InterpolatorLinear { template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time, typename Ringbuffer_T::timering_t::iterator it_before) { // the end value auto it_after = it_before + 1; if (it_after == buffer->times_.end()) { LOG(WARNING) << "Interpolation hit end of buffer."; return buffer->dataAtTimeIterator(it_before); } const real_t w1 = static_cast<real_t>(time - *it_before) / static_cast<real_t>(*it_after - *it_before); return (real_t{1.0} - w1) * buffer->dataAtTimeIterator(it_before) + w1 * buffer->dataAtTimeIterator(it_after); } template<typename Ringbuffer_T> static typename Ringbuffer_T::DataType interpolate( Ringbuffer_T* buffer, int64_t time) { auto it_before = buffer->iterator_equal_or_before(time); // caller should check the bounds: CHECK(it_before != buffer->times_.end()); return interpolate(buffer, time, it_before); } }; using DefaultInterpolator = InterpolatorLinear; //! A fixed size timed buffer templated on the number of entries. //! Opposed to the `Buffer`, values are expected to be received ORDERED in //! TIME! // Oldest entry: buffer.begin(), newest entry: buffer.rbegin() template <typename Scalar, size_t ValueDim, size_t Size> class Ringbuffer { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW //! Ringbuffer is friend with the interpolator types. friend struct InterpolatorNearest; friend struct InterpolatorLinear; typedef int64_t time_t; typedef Eigen::Matrix<time_t, Size, 1> times_t; typedef Eigen::Matrix<time_t, Eigen::Dynamic, 1> times_dynamic_t; typedef Eigen::Matrix<Scalar, ValueDim, Size> data_t; typedef Eigen::Matrix<Scalar, ValueDim, Eigen::Dynamic> data_dynamic_t; // time ring is used to keep track of the positions of the data // in the dataring // uses fixed size ring_view typedef ring_view<time_t> timering_t; using DataType = Eigen::Matrix<Scalar, ValueDim, 1>; using DataTypeMap = Eigen::Map<DataType>; // a series of return types using DataBoolPair = std::pair<DataType, bool>; using TimeDataBoolTuple = std::tuple<time_t, DataType, bool>; using TimeDataRangePair = std::pair<times_dynamic_t, data_dynamic_t>; Ringbuffer() : times_(timering_t(times_raw_.data(), times_raw_.data() + Size, times_raw_.data(), 0)) {} //! no copy, no move as there is no way to track the mutex Ringbuffer(const Ringbuffer& from) = delete; Ringbuffer(const Ringbuffer&& from) = delete; inline void insert(time_t stamp, const DataType& data) { std::lock_guard<std::mutex> lock(mutex_); times_.push_back(stamp); data_.col(times_.back_idx()) = data; } //! Get value with timestamp closest to stamp. Boolean returns if successful. std::tuple<time_t, DataType, bool> getNearestValue(time_t stamp); //! Get oldest value in buffer. std::pair<DataType, bool> getOldestValue() const; //! Get newest value in buffer. std::pair<DataType, bool> getNewestValue() const; //! Get timestamps of newest and oldest entry. std::tuple<time_t, time_t, bool> getOldestAndNewestStamp() const; /*! @brief Get Values between timestamps. * * If timestamps are not matched, the values * are interpolated. Returns a vector of timestamps and a block matrix with * values as columns. Returns empty matrices if not successful. */ template <typename Interpolator = DefaultInterpolator> TimeDataRangePair getBetweenValuesInterpolated(time_t stamp_from, time_t stamp_to); //! Get the values of the container at the given timestamps //! The requested timestamps are expected to be in order! template <typename Interpolator = DefaultInterpolator> data_dynamic_t getValuesInterpolated(times_dynamic_t stamps); //! Interpolate a single value template <typename Interpolator = DefaultInterpolator> bool getValueInterpolated(time_t t, Eigen::Ref<data_dynamic_t> out); inline void clear() { std::lock_guard<std::mutex> lock(mutex_); times_.reset(); } inline size_t size() const { std::lock_guard<std::mutex> lock(mutex_); return times_.size(); } inline bool empty() const { std::lock_guard<std::mutex> lock(mutex_); return times_.empty(); } //! technically does not remove but only moves the beginning of the ring inline void removeDataBeforeTimestamp(time_t stamp) { std::lock_guard<std::mutex> lock(mutex_); removeDataBeforeTimestamp_impl(stamp); } inline void removeDataOlderThan(real_t seconds) { std::lock_guard<std::mutex> lock(mutex_); if(times_.empty()) { return; } removeDataBeforeTimestamp_impl( times_.back() - secToNanosec(seconds)); } inline void lock() const { mutex_.lock(); } inline void unlock() const { mutex_.unlock(); } const data_t& data() const { CHECK(!mutex_.try_lock()) << "Call lock() before accessing data."; return data_; } const timering_t& times() const { CHECK(!mutex_.try_lock()) << "Call lock() before accessing data."; return times_; } typename timering_t::iterator iterator_equal_or_before(time_t stamp); typename timering_t::iterator iterator_equal_or_after(time_t stamp); //! returns an iterator to the first element in the times_ ring that //! is greater or equal to stamp inline typename timering_t::iterator lower_bound(time_t stamp); inline std::mutex& mutex() {return mutex_;} protected: mutable std::mutex mutex_; data_t data_; times_t times_raw_; timering_t times_; //! return the data at a given point in time inline DataType dataAtTimeIterator(typename timering_t::iterator iter) const { //! @todo: i believe this is wrong. return data_.col(iter.container_index()); } //! return the data at a given point in time (const) inline DataType dataAtTimeIterator(typename timering_t::const_iterator iter) const { //! @todo: i believe this is wrong. return data_.col(iter.container_index()); } //! shifts the starting point of the ringbuffer to the given timestamp //! no resizing or deletion happens. inline void removeDataBeforeTimestamp_impl(time_t stamp) { auto it = lower_bound(stamp); times_.reset_front(it.container_index()); } }; } // namespace ze #include <ze/common/ringbuffer-inl.hpp>
31.858521
87
0.709931
50db7ca281441c15525ea23e0f2a09d9258fc9dd
3,198
cpp
C++
src/libraries/core/primitives/strings/lists/hashedWordList.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/primitives/strings/lists/hashedWordList.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/primitives/strings/lists/hashedWordList.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "hashedWordList.hpp" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // void CML::hashedWordList::rehash() { indices_.clear(); forAll(*this, i) { indices_.insert(List<word>::operator[](i), i); } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // CML::hashedWordList::hashedWordList() : List<word>() {} CML::hashedWordList::hashedWordList(const UList<word>& names) : List<word>(names) { rehash(); } CML::hashedWordList::hashedWordList(const hashedWordList& names) : List<word>(static_cast<const UList<word>&>(names)) { rehash(); } CML::hashedWordList::hashedWordList(const Xfer< List<word> >& names) : List<word>(names) { rehash(); } CML::hashedWordList::hashedWordList ( const label nNames, const char** names ) : List<word>(nNames) { forAll(*this, i) { List<word>::operator[](i) = names[i]; } rehash(); } CML::hashedWordList::hashedWordList ( const char** names ) { // count names label nNames = 0; for (unsigned i = 0; names[i] && *(names[i]); ++i) { ++nNames; } List<word>::setSize(nNames); forAll(*this, i) { List<word>::operator[](i) = names[i]; } rehash(); } CML::hashedWordList::hashedWordList(Istream& is) { is >> *this; } // * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * // void CML::hashedWordList::clear() { List<word>::clear(); indices_.clear(); } void CML::hashedWordList::append(const word& name) { const label idx = size(); List<word>::append(name); indices_.insert(name, idx); } void CML::hashedWordList::transfer(List<word>& lst) { List<word>::transfer(lst); rehash(); } // * * * * * * * * * * * * * * * IOstream Operators * * * * * * * * * * * * // CML::Istream& CML::operator>>(Istream& is, hashedWordList& lst) { is >> static_cast<List<word>&>(lst); lst.rehash(); return is; } CML::Ostream& CML::operator<<(Ostream& os, const hashedWordList& lst) { os << static_cast<const List<word>&>(lst); return os; } // ************************************************************************* //
20.5
79
0.530019
50e125deb4b320ce3f86b69e55896749b3dd1652
70
cpp
C++
gui/applicationdata.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
4
2016-02-18T00:48:10.000Z
2016-03-02T23:41:54.000Z
gui/applicationdata.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
null
null
null
gui/applicationdata.cpp
UnnamedCompany/UnnamedSoftware
3251dc9844f35622f616fd3d5a40cb8c89ac0b28
[ "MIT" ]
1
2016-02-29T18:13:34.000Z
2016-02-29T18:13:34.000Z
#include "applicationdata.h" ApplicationData::ApplicationData() { }
14
38
0.757143
50e27a852f0b1d876c84eba4259fca8df2a4e44b
11,149
cc
C++
store/benchmark/retwisClient.cc
yc1111/tapir
2ce0f57725611076cd76ad7374b44f887d8618d8
[ "MIT" ]
437
2016-01-13T23:06:06.000Z
2022-03-07T07:41:55.000Z
store/benchmark/retwisClient.cc
yc1111/tapir
2ce0f57725611076cd76ad7374b44f887d8618d8
[ "MIT" ]
13
2016-01-14T06:12:21.000Z
2021-09-15T07:45:17.000Z
store/benchmark/retwisClient.cc
yc1111/tapir
2ce0f57725611076cd76ad7374b44f887d8618d8
[ "MIT" ]
58
2016-01-14T05:54:13.000Z
2022-03-08T02:56:33.000Z
// -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*- /*********************************************************************** * * store/benchmark/retwisClient.cc: * Retwis benchmarking client for a distributed transactional store. * **********************************************************************/ #include "store/common/truetime.h" #include "store/common/frontend/client.h" #include "store/strongstore/client.h" #include "store/weakstore/client.h" #include "store/tapirstore/client.h" #include <algorithm> using namespace std; // Function to pick a random key according to some distribution. int rand_key(); bool ready = false; double alpha = -1; double *zipf; vector<string> keys; int nKeys = 100; int main(int argc, char **argv) { const char *configPath = NULL; const char *keysPath = NULL; int duration = 10; int nShards = 1; int closestReplica = -1; // Closest replica id. int skew = 0; // difference between real clock and TrueTime int error = 0; // error bars Client *client; enum { MODE_UNKNOWN, MODE_TAPIR, MODE_WEAK, MODE_STRONG } mode = MODE_UNKNOWN; // Mode for strongstore. strongstore::Mode strongmode; int opt; while ((opt = getopt(argc, argv, "c:d:N:k:f:m:e:s:z:r:")) != -1) { switch (opt) { case 'c': // Configuration path { configPath = optarg; break; } case 'f': // Generated keys path { keysPath = optarg; break; } case 'N': // Number of shards. { char *strtolPtr; nShards = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (nShards <= 0)) { fprintf(stderr, "option -N requires a numeric arg\n"); } break; } case 'd': // Duration in seconds to run. { char *strtolPtr; duration = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (duration <= 0)) { fprintf(stderr, "option -d requires a numeric arg\n"); } break; } case 'k': // Number of keys to operate on. { char *strtolPtr; nKeys = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (nKeys <= 0)) { fprintf(stderr, "option -k requires a numeric arg\n"); } break; } case 's': // Simulated clock skew. { char *strtolPtr; skew = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (skew < 0)) { fprintf(stderr, "option -s requires a numeric arg\n"); } break; } case 'e': // Simulated clock error. { char *strtolPtr; error = strtoul(optarg, &strtolPtr, 10); if ((*optarg == '\0') || (*strtolPtr != '\0') || (error < 0)) { fprintf(stderr, "option -e requires a numeric arg\n"); } break; } case 'z': // Zipf coefficient for key selection. { char *strtolPtr; alpha = strtod(optarg, &strtolPtr); if ((*optarg == '\0') || (*strtolPtr != '\0')) { fprintf(stderr, "option -z requires a numeric arg\n"); } break; } case 'r': // Preferred closest replica. { char *strtolPtr; closestReplica = strtod(optarg, &strtolPtr); if ((*optarg == '\0') || (*strtolPtr != '\0')) { fprintf(stderr, "option -r requires a numeric arg\n"); } break; } case 'm': // Mode to run in [occ/lock/...] { if (strcasecmp(optarg, "txn-l") == 0) { mode = MODE_TAPIR; } else if (strcasecmp(optarg, "txn-s") == 0) { mode = MODE_TAPIR; } else if (strcasecmp(optarg, "qw") == 0) { mode = MODE_WEAK; } else if (strcasecmp(optarg, "occ") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_OCC; } else if (strcasecmp(optarg, "lock") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_LOCK; } else if (strcasecmp(optarg, "span-occ") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_SPAN_OCC; } else if (strcasecmp(optarg, "span-lock") == 0) { mode = MODE_STRONG; strongmode = strongstore::MODE_SPAN_LOCK; } else { fprintf(stderr, "unknown mode '%s'\n", optarg); exit(0); } break; } default: fprintf(stderr, "Unknown argument %s\n", argv[optind]); break; } } if (mode == MODE_TAPIR) { client = new tapirstore::Client(configPath, nShards, closestReplica, TrueTime(skew, error)); } else if (mode == MODE_WEAK) { client = new weakstore::Client(configPath, nShards, closestReplica); } else if (mode == MODE_STRONG) { client = new strongstore::Client(strongmode, configPath, nShards, closestReplica, TrueTime(skew, error)); } else { fprintf(stderr, "option -m is required\n"); exit(0); } // Read in the keys from a file. string key, value; ifstream in; in.open(keysPath); if (!in) { fprintf(stderr, "Could not read keys from: %s\n", keysPath); exit(0); } for (int i = 0; i < nKeys; i++) { getline(in, key); keys.push_back(key); } in.close(); struct timeval t0, t1, t2; int nTransactions = 0; // Number of transactions attempted. int ttype; // Transaction type. int ret; bool status; vector<int> keyIdx; gettimeofday(&t0, NULL); srand(t0.tv_sec + t0.tv_usec); while (1) { keyIdx.clear(); // Begin a transaction. client->Begin(); gettimeofday(&t1, NULL); status = true; // Decide which type of retwis transaction it is going to be. ttype = rand() % 100; if (ttype < 5) { // 5% - Add user transaction. 1,3 keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); sort(keyIdx.begin(), keyIdx.end()); if ((ret = client->Get(keys[keyIdx[0]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[0]].c_str(), ret); status = false; } for (int i = 0; i < 3 && status; i++) { client->Put(keys[keyIdx[i]], keys[keyIdx[i]]); } ttype = 1; } else if (ttype < 20) { // 15% - Follow/Unfollow transaction. 2,2 keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); sort(keyIdx.begin(), keyIdx.end()); for (int i = 0; i < 2 && status; i++) { if ((ret = client->Get(keys[keyIdx[i]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[i]].c_str(), ret); status = false; } client->Put(keys[keyIdx[i]], keys[keyIdx[i]]); } ttype = 2; } else if (ttype < 50) { // 30% - Post tweet transaction. 3,5 keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); keyIdx.push_back(rand_key()); sort(keyIdx.begin(), keyIdx.end()); for (int i = 0; i < 3 && status; i++) { if ((ret = client->Get(keys[keyIdx[i]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[i]].c_str(), ret); status = false; } client->Put(keys[keyIdx[i]], keys[keyIdx[i]]); } for (int i = 0; i < 2; i++) { client->Put(keys[keyIdx[i+3]], keys[keyIdx[i+3]]); } ttype = 3; } else { // 50% - Get followers/timeline transaction. rand(1,10),0 int nGets = 1 + rand() % 10; for (int i = 0; i < nGets; i++) { keyIdx.push_back(rand_key()); } sort(keyIdx.begin(), keyIdx.end()); for (int i = 0; i < nGets && status; i++) { if ((ret = client->Get(keys[keyIdx[i]], value))) { Warning("Aborting due to %s %d", keys[keyIdx[i]].c_str(), ret); status = false; } } ttype = 4; } if (status) { status = client->Commit(); } else { Debug("Aborting transaction due to failed Read"); } gettimeofday(&t2, NULL); long latency = (t2.tv_sec - t1.tv_sec) * 1000000 + (t2.tv_usec - t1.tv_usec); int retries = 0; if (!client->Stats().empty()) { retries = client->Stats()[0]; } fprintf(stderr, "%d %ld.%06ld %ld.%06ld %ld %d %d %d", ++nTransactions, t1.tv_sec, t1.tv_usec, t2.tv_sec, t2.tv_usec, latency, status?1:0, ttype, retries); fprintf(stderr, "\n"); if (((t2.tv_sec-t0.tv_sec)*1000000 + (t2.tv_usec-t0.tv_usec)) > duration*1000000) break; } fprintf(stderr, "# Client exiting..\n"); return 0; } int rand_key() { if (alpha < 0) { // Uniform selection of keys. return (rand() % nKeys); } else { // Zipf-like selection of keys. if (!ready) { zipf = new double[nKeys]; double c = 0.0; for (int i = 1; i <= nKeys; i++) { c = c + (1.0 / pow((double) i, alpha)); } c = 1.0 / c; double sum = 0.0; for (int i = 1; i <= nKeys; i++) { sum += (c / pow((double) i, alpha)); zipf[i-1] = sum; } ready = true; } double random = 0.0; while (random == 0.0 || random == 1.0) { random = (1.0 + rand())/RAND_MAX; } // binary search to find key; int l = 0, r = nKeys, mid; while (l < r) { mid = (l + r) / 2; if (random > zipf[mid]) { l = mid + 1; } else if (random < zipf[mid]) { r = mid - 1; } else { break; } } return mid; } }
30.545205
90
0.44865
50e2b45736a4cb23039bc11d8b549132c96b556b
94
cpp
C++
src/cli/InvalidCommandSyntaxException.cpp
mbassale/ownpass
a84e0cd3933ec8c3febf0e09647990baf3c2d506
[ "MIT" ]
null
null
null
src/cli/InvalidCommandSyntaxException.cpp
mbassale/ownpass
a84e0cd3933ec8c3febf0e09647990baf3c2d506
[ "MIT" ]
null
null
null
src/cli/InvalidCommandSyntaxException.cpp
mbassale/ownpass
a84e0cd3933ec8c3febf0e09647990baf3c2d506
[ "MIT" ]
null
null
null
// // Created by Marco Bassaletti on 18-03-21. // #include "InvalidCommandSyntaxException.h"
15.666667
43
0.734043
50e75f1d819c1c35e5f770807a9f53e427904d2f
1,144
hpp
C++
DOS_Boat_Source/RequireSpace.hpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
DOS_Boat_Source/RequireSpace.hpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
DOS_Boat_Source/RequireSpace.hpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
/**************************************************************************** * Author: Michael S. Lewis * * Date: 6/3/2016 * * Description: RequireSpace.hpp is the RequireSpace class declaration * * (interface) file (for Final Project "DOS Boat"). * * A Require Space tests whether a specific object is in * * inventory before allowing the user to proceed to a * * particular adjacent space. * *****************************************************************************/ #ifndef REQUIRESPACE_HPP #define REQUIRESPACE_HPP #include <string> #include "Ocean.hpp" class Babbage; // Declaration of Babbage class. class RequireSpace : public Ocean { private: virtual void playSpace(Babbage* babbage, bool displayHint); virtual void nextSpace(Babbage* babbage); std::string required; std::string restricted; public: RequireSpace(); RequireSpace(std::string nameSpacem, std::string spaceHeading, std::string spaceType, std::string requiredItem, std::string restrictedArea); }; #endif // REQUIRESPACE_HPP
35.75
79
0.566434
50e780b7bab76861f125a4c3ff88c3d8acf4c755
360
cpp
C++
books/C++_advanced_course/Chapter6/template_parameter_4.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
books/C++_advanced_course/Chapter6/template_parameter_4.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
books/C++_advanced_course/Chapter6/template_parameter_4.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include <iostream> using std::cout; using std::endl; template<class T, int a> class X { public: T valX[a]; }; template<class T, int a> class Y { X<T, a> valY; public: void Set(T t) { valY.valX[0] = t; } void ShowFirst() { cout << valY.valX[0] << endl; } }; int main() { Y<double, 3> y; y.Set(0.8); y.ShowFirst(); system("pause"); return 0; }
10.588235
51
0.586111
50e8fb9c008d57e9f0091fbfd6c1d3c827741bbc
1,836
cpp
C++
tests/rect_follow_mouse.cpp
AlexandruIca/SoftRender
9466251ad919d6896a1e3d1455a156186106cbaa
[ "Unlicense" ]
null
null
null
tests/rect_follow_mouse.cpp
AlexandruIca/SoftRender
9466251ad919d6896a1e3d1455a156186106cbaa
[ "Unlicense" ]
null
null
null
tests/rect_follow_mouse.cpp
AlexandruIca/SoftRender
9466251ad919d6896a1e3d1455a156186106cbaa
[ "Unlicense" ]
null
null
null
#include <chrono> #include <cmath> #include "softrender.hpp" struct rect_t { softrender::point_t pos{ 0, 0 }; int w{ 0 }; int h{ 0 }; }; using microsecond_t = decltype(std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::seconds(1)) .count()); auto follow_mouse(rect_t& t_rect, softrender::point_t const& t_mouse_pos, microsecond_t const t_elapsed_time) noexcept -> void { double const elapsed = t_elapsed_time / double{ 1e6 }; int constexpr velocity = 300; // pixels double const center_x = t_rect.pos.x + t_rect.w / 2.0; double const center_y = t_rect.pos.y + t_rect.h / 2.0; double const dest_x = t_mouse_pos.x; double const dest_y = t_mouse_pos.y; double const dx = dest_x - center_x; double const dy = dest_y - center_y; double const distance = std::sqrt(dx * dx + dy * dy); if(distance < 5) { return; } t_rect.pos.x += static_cast<int>(velocity * elapsed * dx / distance); t_rect.pos.y += static_cast<int>(velocity * elapsed * dy / distance); } auto main(int, char*[]) -> int { using namespace softrender; window_t window{ 1280, 720 }; microsecond_t elapsed{ 0 }; rect_t rect{ { window.width() / 2 - 200, window.height() / 2 - 200 }, 400, 400 }; auto start = std::chrono::high_resolution_clock::now(); while(!window.closed()) { auto end = std::chrono::high_resolution_clock::now(); elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start) .count(); start = end; follow_mouse(rect, window.get_mouse_position(), elapsed); window.draw_rectangle(rect.pos, rect.w, rect.h, pink); window.draw(); } }
26.228571
78
0.594227
50e90c212b6c069bf716bd2de7e2fd50dc270404
4,508
cpp
C++
Code/GraphMol/catch_tests.cpp
Mike575/rdkit
373a89021e478f878c6011a201e3fb8f4a122093
[ "PostgreSQL" ]
1
2019-01-23T06:02:24.000Z
2019-01-23T06:02:24.000Z
Code/GraphMol/catch_tests.cpp
Mike575/rdkit
373a89021e478f878c6011a201e3fb8f4a122093
[ "PostgreSQL" ]
null
null
null
Code/GraphMol/catch_tests.cpp
Mike575/rdkit
373a89021e478f878c6011a201e3fb8f4a122093
[ "PostgreSQL" ]
null
null
null
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do // this in one cpp file #include "catch.hpp" #include <GraphMol/RDKitBase.h> #include <GraphMol/RDKitQueries.h> #include <GraphMol/Chirality.h> #include <GraphMol/FileParsers/FileParsers.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/SmilesParse/SmartsWrite.h> using namespace RDKit; TEST_CASE("SMILES Parsing works", "[molops]") { std::unique_ptr<RWMol> mol(SmilesToMol("C1CC1")); REQUIRE(mol); REQUIRE(mol->getNumAtoms() == 3); } TEST_CASE("Sanitization tests", "[molops]") { std::unique_ptr<RWMol> mol(SmilesToMol("C1=CC=CC=C1Cc2ccccc2", false, false)); REQUIRE(mol); REQUIRE(mol->getNumAtoms() == 13); SECTION("properties") { mol->updatePropertyCache(); CHECK(mol->getAtomWithIdx(0)->getTotalNumHs() == 1); CHECK(!mol->getAtomWithIdx(0)->getIsAromatic()); CHECK(mol->getAtomWithIdx(7)->getIsAromatic()); SECTION("aromaticity") { unsigned int opThatFailed; MolOps::sanitizeMol(*mol, opThatFailed, MolOps::SANITIZE_SETAROMATICITY); // mol->debugMol(std::cerr); CHECK(mol->getAtomWithIdx(7)->getIsAromatic()); // blocked by #1730 // CHECK(mol->getAtomWithIdx(0)->getIsAromatic()); } SECTION("kekulize") { unsigned int opThatFailed; MolOps::sanitizeMol(*mol, opThatFailed, MolOps::SANITIZE_KEKULIZE); CHECK(!mol->getAtomWithIdx(0)->getIsAromatic()); CHECK(!mol->getAtomWithIdx(7)->getIsAromatic()); } } } TEST_CASE("Github #2062", "[bug, molops]") { SmilesParserParams ps; ps.removeHs = false; ps.sanitize = true; std::unique_ptr<RWMol> mol(SmilesToMol("[C:1][C:2]([H:3])([H])[O:4][H]", ps)); REQUIRE(mol); CHECK(mol->getNumAtoms() == 6); mol->getAtomWithIdx(1)->setProp("intProp", 42); MolOps::mergeQueryHs(*mol); CHECK(mol->getNumAtoms() == 3); SECTION("basics") { CHECK(mol->getAtomWithIdx(1)->getAtomMapNum() == 2); } SECTION("other props") { REQUIRE(mol->getAtomWithIdx(1)->hasProp("intProp")); CHECK(mol->getAtomWithIdx(1)->getProp<int>("intProp") == 42); } } TEST_CASE("Github #2086", "[bug, molops]") { SECTION("reported version") { auto mol = "C1CCCC1"_smiles; REQUIRE(mol); MolOps::addHs(*mol); REQUIRE(mol->getNumAtoms() == 15); mol->removeBond(4, 13); MolOps::removeHs(*mol); REQUIRE(mol->getNumAtoms() == 6); } } TEST_CASE("github #299", "[bug, molops, SSSR]"){ SECTION("simplified"){ auto mol = "C13%13%14.C124%18.C25%13%15.C368%17.C4679.C75%10%17.C8%11%14%16.C9%11%12%18.C%10%12%15%16"_smiles; REQUIRE(mol); REQUIRE(mol->getNumAtoms()==9); } SECTION("old example from molopstest"){ auto mol = "C123C45C11C44C55C22C33C14C523"_smiles; REQUIRE(mol); REQUIRE(mol->getNumAtoms()==9); } SECTION("carborane"){ std::unique_ptr<RWMol> mol(SmilesToMol("[B]1234[B]567[B]118[B]229[B]33%10[B]454[B]656[B]711[B]822[C]933[B]%1045[C]6123",0,false)); REQUIRE(mol); CHECK(mol->getNumAtoms()==12); mol->updatePropertyCache(false); MolOps::findSSSR(*mol); REQUIRE(mol->getRingInfo()->isInitialized()); } SECTION("original report from ChEbI"){ std::string pathName = getenv("RDBASE"); pathName += "/Code/GraphMol/test_data/"; std::unique_ptr<RWMol> mol(MolFileToMol(pathName + "ChEBI_50252.mol",false)); REQUIRE(mol); CHECK(mol->getNumAtoms()==80); mol->updatePropertyCache(false); MolOps::findSSSR(*mol); REQUIRE(mol->getRingInfo()->isInitialized()); } } TEST_CASE("github #2224", "[bug, molops, removeHs, query]"){ SECTION("the original report"){ std::string pathName = getenv("RDBASE"); pathName += "/Code/GraphMol/test_data/"; std::unique_ptr<RWMol> mol(MolFileToMol(pathName + "github2224_1.mol")); REQUIRE(mol); REQUIRE(mol->getNumAtoms()==7); } SECTION("basics") { SmilesParserParams ps; ps.removeHs = false; ps.sanitize = true; std::unique_ptr<ROMol> mol(SmilesToMol("C[H]", ps)); REQUIRE(mol); REQUIRE(mol->getNumAtoms()==2); { // The H without a query is removed std::unique_ptr<ROMol> m2(MolOps::removeHs(*mol)); CHECK(m2->getNumAtoms()==1); } { // but if we add a query feature it's not removed RWMol m2(*mol); m2.replaceAtom(1,new QueryAtom(1)); m2.getAtomWithIdx(1)->setAtomicNum(1); MolOps::removeHs(m2); CHECK(m2.getNumAtoms()==2); } } }
32.2
134
0.648625
50eb9c8a790c3cdc7a4a284c23365dca8452f292
973
cpp
C++
Problems/IEEEXtreme/IEEEXtreme_11.0/Codes/Full.Pyramid.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/IEEEXtreme/IEEEXtreme_11.0/Codes/Full.Pyramid.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/IEEEXtreme/IEEEXtreme_11.0/Codes/Full.Pyramid.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fi first #define se second #define maxk 17 #define maxn 100003 #define mod 1000000007 using namespace std; typedef pair<int,int> pi; int s; int comb[maxk][maxk]; pi dp[maxn][maxk]; int f( int ind , int step , int rem ) { if( ind == step ) return 1; if( dp[rem][ind].se == step + 1 ) return dp[rem][ind].fi; dp[rem][ind] = pi( 0 , step + 1 ); dp[rem][ind].fi = ( dp[rem][ind].fi + f( ind + 1 , step , rem ) ) % mod; if( comb[step][ind] <= rem ) dp[rem][ind].fi = ( dp[rem][ind].fi + f( ind , step , rem - comb[step][ind] ) ) % mod; return dp[rem][ind].fi; } int main() { for( int i = 0 ; i < maxk ; i++ ) comb[i][0] = 1; for( int i = 1 ; i < maxk ; i++ ) for( int j = 1 ; j <= i ; j++ ) comb[i][j] = ( comb[i-1][j-1] + comb[i-1][j] ) % mod; scanf( "%d" , &s ); int ans = 0; for( int i = 0 ; (1<<i) <= s ; i++ ) ans = ( ans + f( 0 , i , s - (1 << i) ) ) % mod; printf( "%d\n" , ans ); return 0; }
20.702128
88
0.50668