hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
eb96b13213aab751bebf510d4f8a5e4af804c137
2,343
cpp
C++
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/obmc-phosphor-buttons/1.0+gitAUTOINC+1ac9ab6d29-r1/git/src/main.cpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/obmc-phosphor-buttons/1.0+gitAUTOINC+1ac9ab6d29-r1/git/src/main.cpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/obmc-phosphor-buttons/1.0+gitAUTOINC+1ac9ab6d29-r1/git/src/main.cpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "id_button.hpp" #include "power_button.hpp" #include "reset_button.hpp" int main(int argc, char* argv[]) { int ret = 0; phosphor::logging::log<phosphor::logging::level::INFO>( "Start power button service..."); sd_event* event = nullptr; ret = sd_event_default(&event); if (ret < 0) { phosphor::logging::log<phosphor::logging::level::ERR>( "Error creating a default sd_event handler"); return ret; } EventPtr eventP{event}; event = nullptr; sdbusplus::bus::bus bus = sdbusplus::bus::new_default(); sdbusplus::server::manager::manager objManager{ bus, "/xyz/openbmc_project/Chassis/Buttons"}; bus.request_name("xyz.openbmc_project.Chassis.Buttons"); std::unique_ptr<PowerButton> pb; if (hasGpio<PowerButton>()) { pb = std::make_unique<PowerButton>(bus, POWER_DBUS_OBJECT_NAME, eventP); } std::unique_ptr<ResetButton> rb; if (hasGpio<ResetButton>()) { rb = std::make_unique<ResetButton>(bus, RESET_DBUS_OBJECT_NAME, eventP); } std::unique_ptr<IDButton> ib; if (hasGpio<IDButton>()) { ib = std::make_unique<IDButton>(bus, ID_DBUS_OBJECT_NAME, eventP); } try { bus.attach_event(eventP.get(), SD_EVENT_PRIORITY_NORMAL); ret = sd_event_loop(eventP.get()); if (ret < 0) { phosphor::logging::log<phosphor::logging::level::ERR>( "Error occurred during the sd_event_loop", phosphor::logging::entry("RET=%d", ret)); } } catch (std::exception& e) { phosphor::logging::log<phosphor::logging::level::ERR>(e.what()); ret = -1; } return ret; }
28.925926
80
0.637644
sotaoverride
eb978dad3af8589d102fe466e1899304c74afb4e
2,754
hpp
C++
pythran/pythonic/numpy/transpose.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/transpose.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/numpy/transpose.hpp
Pikalchemist/Pythran
17d4108b56b3b365e089a4e1b01a09eb7e12942b
[ "BSD-3-Clause" ]
1
2017-03-12T20:32:36.000Z
2017-03-12T20:32:36.000Z
#ifndef PYTHONIC_NUMPY_TRANSPOSE_HPP #define PYTHONIC_NUMPY_TRANSPOSE_HPP #include "pythonic/utils/proxy.hpp" #include "pythonic/utils/numpy_conversion.hpp" #include "pythonic/utils/nested_container.hpp" #include "pythonic/types/ndarray.hpp" #include "pythonic/types/numpy_type.hpp" #include "pythonic/__builtin__/ValueError.hpp" namespace pythonic { namespace numpy { template<class T> types::numpy_texpr<types::ndarray<T, 2>> transpose(types::ndarray<T, 2> const& arr) { return types::numpy_texpr<types::ndarray<T, 2>>(arr); } template<class T, unsigned long N, class... C> types::ndarray<T,N> _transpose(types::ndarray<T,N> const & a, long const l[N]) { auto shape = a.shape; types::array<long, N> shp; for(unsigned long i=0; i<N; ++i) shp[i] = shape[l[i]]; types::ndarray<T,N> new_array(shp, __builtin__::None); types::array<long, N> new_strides; new_strides[N-1] = 1; std::transform(new_strides.rbegin(), new_strides.rend() -1, shp.rbegin(), new_strides.rbegin() + 1, std::multiplies<long>()); types::array<long, N> old_strides; old_strides[N-1] = 1; std::transform(old_strides.rbegin(), old_strides.rend() -1, shape.rbegin(), old_strides.rbegin() + 1, std::multiplies<long>()); auto iter = a.buffer, iter_end = a.buffer + a.flat_size(); for(long i=0; iter!=iter_end; ++iter, ++i) { long offset = 0; for(unsigned long s=0; s<N; s++) offset += ((i/old_strides[l[s]]) % shape[l[s]])*new_strides[s]; new_array.buffer[offset] = *iter; } return new_array; } template<class T, size_t N> types::ndarray<T,N> transpose(types::ndarray<T,N> const & a) { long t[N]; for(unsigned long i = 0; i<N; ++i) t[N-1-i] = i; return _transpose(a, t); } template<class T, size_t N, size_t M> types::ndarray<T,N> transpose(types::ndarray<T,N> const & a, types::array<long, M> const& t) { static_assert(N==M, "axes don't match array"); long val = t[M-1]; if(val>=long(N)) throw types::ValueError("invalid axis for this array"); return _transpose(a, &t[0]); } NUMPY_EXPR_TO_NDARRAY0(transpose); PROXY(pythonic::numpy, transpose); } } #endif
34.860759
143
0.520334
Pikalchemist
eb98fed3c3f064bcd619fa4677f9c09aeddffa18
1,828
cpp
C++
SimCalorimetry/EcalSimAlgos/test/ESDigitizerTest.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
SimCalorimetry/EcalSimAlgos/test/ESDigitizerTest.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
SimCalorimetry/EcalSimAlgos/test/ESDigitizerTest.cpp
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "DataFormats/EcalDetId/interface/ESDetId.h" #include "DataFormats/EcalDigi/interface/ESDataFrame.h" #include "SimDataFormats/CaloHit/interface/PCaloHit.h" #include "SimCalorimetry/CaloSimAlgos/interface/CaloHitResponse.h" #include "SimCalorimetry/CaloSimAlgos/interface/CaloTDigitizer.h" #include "SimCalorimetry/EcalSimAlgos/interface/EcalSimParameterMap.h" #include "SimCalorimetry/EcalSimAlgos/interface/ESShape.h" #include "SimCalorimetry/EcalSimAlgos/interface/EcalDigitizerTraits.h" #include "SimCalorimetry/EcalSimAlgos/interface/ESElectronicsSim.h" #include "SimDataFormats/CrossingFrame/interface/CrossingFrame.h" #include <vector> #include <iostream> #include <iterator> int main() { // make a silly little hit in each subdetector, which should // correspond to a 300 keV particle ESDetId ESDetId(1, 1, 1, 1, 1); PCaloHit ESHit(ESDetId.rawId(), 0.0003, 0.); vector<DetId> ESDetIds; ESDetIds.push_back(ESDetId); vector<PCaloHit> ESHits; ESHits.push_back(ESHit); string ESName = "EcalHitsES"; edm::EventID id; CrossingFrame<PCaloHit> crossingFrame(-5, 5, 25, ESName, 1); crossingFrame.addSignals(&ESHits,id); EcalSimParameterMap parameterMap; ESShape shape(1); CaloHitResponse ESResponse(&parameterMap, &shape); ESElectronicsSim electronicsSim(true, 3, 1, 1000, 9, 78.47); bool addNoise = false; CaloTDigitizer<ESDigitizerTraits> ESDigitizer(&ESResponse, &electronicsSim, addNoise); ESDigitizer.setDetIds(ESDetIds); unique_ptr<ESDigiCollection> ESResult(new ESDigiCollection); MixCollection<PCaloHit> ESHitCollection(&crossingFrame); ESDigitizer.run(ESHitCollection, *ESResult); // print out all the digis cout << "ES Frames" << endl; copy(ESResult->begin(), ESResult->end(), std::ostream_iterator<ESDataFrame>(std::cout, "\n")); return 0; }
30.983051
96
0.769147
ckamtsikis
eba233191f70e61054b58edd9042d737ac537d7c
9,636
hpp
C++
lib/include/efyj/matrix.hpp
quesnel/efyj
5f214449e26000fb30f3a037cac52269704fe703
[ "MIT" ]
1
2021-05-04T16:06:55.000Z
2021-05-04T16:06:55.000Z
lib/include/efyj/matrix.hpp
quesnel/efyj
5f214449e26000fb30f3a037cac52269704fe703
[ "MIT" ]
null
null
null
lib/include/efyj/matrix.hpp
quesnel/efyj
5f214449e26000fb30f3a037cac52269704fe703
[ "MIT" ]
null
null
null
/* Copyright (C) 2016-2017 INRA * * 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. */ #ifndef ORG_VLEPROJECT_EFYJ_MATRIX_HPP #define ORG_VLEPROJECT_EFYJ_MATRIX_HPP #include <algorithm> #include <initializer_list> #include <vector> #include <cassert> namespace efyj { /** * An \e matrix defined a two-dimensional template array. Informations are * stored into a \e std::vector<T> by default. * * \tparam T Type of element * \tparam Containre Type of container to store two-dimensional array. */ template<typename T, class Container = std::vector<T>> class matrix { public: using container_type = Container; using value_type = T; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator; using reverse_iterator = typename container_type::reverse_iterator; using const_reverse_iterator = typename container_type::const_reverse_iterator; using size_type = typename container_type::size_type; protected: container_type m_c; size_type m_rows, m_columns; public: matrix(); explicit matrix(size_type rows, size_type cols); explicit matrix(size_type rows, size_type cols, const value_type& value); ~matrix() = default; matrix(const matrix& q) = default; matrix(matrix&& q) = default; matrix& operator=(const matrix& q) = default; matrix& operator=(matrix&& q) = default; void assign(std::initializer_list<value_type> list); void resize(size_type rows, size_type cols); void resize(size_type rows, size_type cols, const value_type& value); iterator begin() noexcept; const_iterator begin() const noexcept; iterator end() noexcept; const_iterator end() const noexcept; reverse_iterator rbegin() noexcept; const_reverse_iterator rbegin() const noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rend() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; bool empty() const noexcept; size_type size() const noexcept; size_type rows() const noexcept; size_type columns() const noexcept; void set(size_type row, size_type col, const value_type& x); void set(size_type row, size_type col, value_type&& x); template<class... Args> void emplace(size_type row, size_type col, Args&&... args); const_reference operator()(size_type row, size_type col) const; reference operator()(size_type row, size_type col); void swap(matrix& c) noexcept(noexcept(m_c.swap(c.m_c))); void clear() noexcept; private: void m_check_index(size_type row, size_type col) const; }; template<typename T, class Container> matrix<T, Container>::matrix() : m_c() , m_rows(0) , m_columns(0) {} template<typename T, class Container> matrix<T, Container>::matrix(size_type rows, size_type columns) : m_c(rows * columns) , m_rows(rows) , m_columns(columns) {} template<typename T, class Container> matrix<T, Container>::matrix(size_type rows, size_type columns, const value_type& value) : m_c(rows * columns, value) , m_rows(rows) , m_columns(columns) {} template<typename T, class Container> void matrix<T, Container>::assign(std::initializer_list<value_type> list) { m_c.assign(list.begin(), list.end()); } template<typename T, class Container> void matrix<T, Container>::resize(size_type rows, size_type cols) { container_type new_c(rows * cols); size_type rmin = std::min(rows, m_rows); size_type cmin = std::min(cols, m_columns); for (size_type r = 0; r != rmin; ++r) for (size_type c = 0; c != cmin; ++c) new_c[r * cols + c] = m_c[r * m_columns + c]; m_columns = cols; m_rows = rows; std::swap(new_c, m_c); } template<typename T, class Container> void matrix<T, Container>::resize(size_type rows, size_type cols, const value_type& value) { m_c.resize(rows * cols); m_rows = rows; m_columns = cols; std::fill(m_c.begin(), m_c.end(), value); } template<typename T, class Container> typename matrix<T, Container>::iterator matrix<T, Container>::begin() noexcept { return m_c.begin(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::begin() const noexcept { return m_c.begin(); } template<typename T, class Container> typename matrix<T, Container>::iterator matrix<T, Container>::end() noexcept { return m_c.end(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::end() const noexcept { return m_c.end(); } template<typename T, class Container> typename matrix<T, Container>::reverse_iterator matrix<T, Container>::rbegin() noexcept { return m_c.rbegin(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::rbegin() const noexcept { return m_c.rbegin(); } template<typename T, class Container> typename matrix<T, Container>::reverse_iterator matrix<T, Container>::rend() noexcept { return m_c.rend(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::rend() const noexcept { return m_c.rend(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::cbegin() const noexcept { return m_c.cbegin(); } template<typename T, class Container> typename matrix<T, Container>::const_iterator matrix<T, Container>::cend() const noexcept { return m_c.cend(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::crbegin() const noexcept { return m_c.crbegin(); } template<typename T, class Container> typename matrix<T, Container>::const_reverse_iterator matrix<T, Container>::crend() const noexcept { return m_c.crend(); } template<typename T, class Container> bool matrix<T, Container>::empty() const noexcept { return m_c.empty(); } template<typename T, class Container> typename matrix<T, Container>::size_type matrix<T, Container>::size() const noexcept { return m_c.size(); } template<typename T, class Container> typename matrix<T, Container>::size_type matrix<T, Container>::rows() const noexcept { return m_rows; } template<typename T, class Container> typename matrix<T, Container>::size_type matrix<T, Container>::columns() const noexcept { return m_columns; } template<typename T, class Container> void matrix<T, Container>::set(size_type row, size_type column, const value_type& x) { m_check_index(row, column); m_c[row * m_columns + column] = x; } template<typename T, class Container> void matrix<T, Container>::set(size_type row, size_type column, value_type&& x) { m_check_index(row, column); m_c.emplace(m_c.begin() + (row * m_columns + column), std::move(x)); } template<typename T, class Container> template<class... Args> void matrix<T, Container>::emplace(size_type row, size_type column, Args&&... args) { m_check_index(row, column); m_c.emplace(m_c.begin() + (row * m_columns + column), std::forward<Args>(args)...); } template<typename T, class Container> typename matrix<T, Container>::const_reference matrix<T, Container>::operator()(size_type row, size_type column) const { m_check_index(row, column); return m_c[row * m_columns + column]; } template<typename T, class Container> typename matrix<T, Container>::reference matrix<T, Container>::operator()(size_type row, size_type column) { m_check_index(row, column); return m_c[row * m_columns + column]; } template<typename T, class Container> void matrix<T, Container>::swap(matrix& c) noexcept(noexcept(m_c.swap(c.m_c))) { std::swap(m_c, c.m_c); std::swap(m_columns, c.m_columns); std::swap(m_rows, c.m_rows); } template<typename T, class Container> void matrix<T, Container>::clear() noexcept { m_c.clear(); m_rows = 0; m_columns = 0; } template<typename T, class Container> void matrix<T, Container>::m_check_index([[maybe_unused]] size_type row, [[maybe_unused]] size_type column) const { assert(column < m_columns || row < m_rows); } } #endif
26.766667
79
0.709734
quesnel
eba3edf7b9de7a2dad2aa25bddbc1f57d1ebfca3
10,787
cpp
C++
lonestar/gmetis/GMetis.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestar/gmetis/GMetis.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
lonestar/gmetis/GMetis.cpp
bowu/Galois
81f619a2bb1bdc95899729f2d96a7da38dd0c0a3
[ "BSD-3-Clause" ]
null
null
null
/* * This file belongs to the Galois project, a C++ library for exploiting parallelism. * The code is being released under the terms of the 3-Clause BSD License (a * copy is located in LICENSE.txt at the top-level directory). * * Copyright (C) 2018, The University of Texas at Austin. All rights reserved. * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF * DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances * shall University be liable for incidental, special, indirect, direct or * consequential damages or loss of profits, interruption of business, or * related expenses which may arise from use of Software or Documentation, * including but not limited to those resulting from defects in Software and/or * Documentation, or loss or inaccuracy of data of any kind. */ #include <vector> #include <set> #include <map> #include <iostream> #include <string.h> #include <stdlib.h> #include <numeric> #include <algorithm> #include <cmath> #include <fstream> #include "Metis.h" #include "galois/graphs/ReadGraph.h" #include "galois/Timer.h" //#include "GraphReader.h" #include "Lonestar/BoilerPlate.h" #include "galois/graphs/FileGraph.h" #include "galois/LargeArray.h" namespace cll = llvm::cl; static const char* name = "GMetis"; static const char* desc = "Partitions a graph into K parts and minimizing the graph cut"; static const char* url = "gMetis"; static cll::opt<InitialPartMode> partMode( cll::desc("Choose a inital part mode:"), cll::values(clEnumVal(GGP, "GGP"), clEnumVal(GGGP, "GGGP (default)"), clEnumVal(MGGGP, "MGGGP")), cll::init(GGGP)); static cll::opt<refinementMode> refineMode( cll::desc("Choose a refinement mode:"), cll::values(clEnumVal(BKL, "BKL"), clEnumVal(BKL2, "BKL2 (default)"), clEnumVal(ROBO, "ROBO"), clEnumVal(GRACLUS, "GRACLUS") ), cll::init(BKL2)); static cll::opt<bool> mtxInput("mtxinput", cll::desc("Use text mtx files instead of binary galois gr files"), cll::init(false)); static cll::opt<bool> weighted("weighted", cll::desc("weighted"), cll::init(false)); static cll::opt<bool> verbose("verbose", cll::desc("verbose output (debugging mode, takes extra time)"), cll::init(false)); static cll::opt<std::string> outfile("output", cll::desc("output partition file name")); static cll::opt<std::string> orderedfile("ordered", cll::desc("output ordered graph file name")); static cll::opt<std::string> permutationfile("permutation", cll::desc("output permutation file name")); static cll::opt<std::string> filename(cll::Positional, cll::desc("<input file>"), cll::Required); static cll::opt<int> numPartitions(cll::Positional, cll::desc("<Number of partitions>"), cll::Required); static cll::opt<double> imbalance( "balance", cll::desc("Fraction deviated from mean partition size (default 0.01)"), cll::init(0.01)); // const double COARSEN_FRACTION = 0.9; /** * KMetis Algorithm */ void Partition(MetisGraph* metisGraph, unsigned nparts) { galois::StatTimer TM; TM.start(); unsigned fineMetisGraphWeight = metisGraph->getTotalWeight(); unsigned meanWeight = ((double)fineMetisGraphWeight) / (double)nparts; // unsigned coarsenTo = std::max(metisGraph->getNumNodes() / (40 * // intlog2(nparts)), 20 * (nparts)); unsigned coarsenTo = 20 * nparts; if (verbose) std::cout << "Starting coarsening: \n"; galois::StatTimer T("Coarsen"); T.start(); MetisGraph* mcg = coarsen(metisGraph, coarsenTo, verbose); T.stop(); if (verbose) std::cout << "Time coarsen: " << T.get() << "\n"; galois::StatTimer T2("Partition"); T2.start(); std::vector<partInfo> parts; parts = partition(mcg, fineMetisGraphWeight, nparts, partMode); T2.stop(); if (verbose) std::cout << "Init edge cut : " << computeCut(*mcg->getGraph()) << "\n\n"; std::vector<partInfo> initParts = parts; if (verbose) std::cout << "Time clustering: " << T2.get() << '\n'; if (verbose) { switch (refineMode) { case BKL2: std::cout << "Sorting refinnement with BKL2\n"; break; case BKL: std::cout << "Sorting refinnement with BKL\n"; break; case ROBO: std::cout << "Sorting refinnement with ROBO\n"; break; case GRACLUS: std::cout << "Sorting refinnement with GRACLUS\n"; break; default: abort(); } } galois::StatTimer T3("Refine"); T3.start(); refine(mcg, parts, meanWeight - (unsigned)(meanWeight * imbalance), meanWeight + (unsigned)(meanWeight * imbalance), refineMode, verbose); T3.stop(); if (verbose) std::cout << "Time refinement: " << T3.get() << "\n"; TM.stop(); std::cout << "Initial dist\n"; printPartStats(initParts); std::cout << "\n"; std::cout << "Refined dist\n"; printPartStats(parts); std::cout << "\n"; std::cout << "Time: " << TM.get() << '\n'; return; } // printGraphBeg(*graph) typedef galois::graphs::FileGraph FG; typedef FG::GraphNode FN; template <typename GNode, typename Weights> struct order_by_degree { GGraph& graph; Weights& weights; order_by_degree(GGraph& g, Weights& w) : graph(g), weights(w) {} bool operator()(const GNode& a, const GNode& b) { uint64_t wa = weights[a]; uint64_t wb = weights[b]; int pa = graph.getData(a, galois::MethodFlag::UNPROTECTED).getPart(); int pb = graph.getData(b, galois::MethodFlag::UNPROTECTED).getPart(); if (pa != pb) { return pa < pb; } return wa < wb; } }; typedef galois::substrate::PerThreadStorage<std::map<GNode, uint64_t>> PerThreadDegInfo; int main(int argc, char** argv) { galois::SharedMemSys G; LonestarStart(argc, argv, name, desc, url); srand(-1); MetisGraph metisGraph; GGraph& graph = *metisGraph.getGraph(); galois::graphs::readGraph(graph, filename); galois::do_all(galois::iterate(graph), [&](GNode node) { for (auto jj : graph.edges(node)) { graph.getEdgeData(jj) = 1; // weight+=1; } }, galois::loopname("initMorphGraph")); graphStat(graph); std::cout << "\n"; galois::preAlloc(galois::runtime::numPagePoolAllocTotal() * 5); galois::reportPageAlloc("MeminfoPre"); Partition(&metisGraph, numPartitions); galois::reportPageAlloc("MeminfoPost"); std::cout << "Total edge cut: " << computeCut(graph) << "\n"; if (outfile != "") { MetisGraph* coarseGraph = &metisGraph; while (coarseGraph->getCoarserGraph()) coarseGraph = coarseGraph->getCoarserGraph(); std::ofstream outFile(outfile.c_str()); for (auto it = graph.begin(), ie = graph.end(); it != ie; it++) { unsigned gPart = graph.getData(*it).getPart(); outFile << gPart << '\n'; } } if (orderedfile != "" || permutationfile != "") { galois::graphs::FileGraph g; g.fromFile(filename); typedef galois::LargeArray<GNode> Permutation; Permutation perm; perm.create(g.size()); std::copy(graph.begin(), graph.end(), perm.begin()); PerThreadDegInfo threadDegInfo; std::vector<int> parts(numPartitions); for (unsigned int i = 0; i < parts.size(); i++) { parts[i] = i; } using WL = galois::worklists::PerSocketChunkFIFO<16>; galois::for_each( galois::iterate(parts), [&](int part, auto& lwl) { constexpr auto flag = galois::MethodFlag::UNPROTECTED; typedef std::vector< std::pair<unsigned, GNode>, galois::PerIterAllocTy::rebind<std::pair<unsigned, GNode>>::other> GD; // copy and translate all edges GD orderedNodes(GD::allocator_type(lwl.getPerIterAlloc())); for (auto n : graph) { auto& nd = graph.getData(n, flag); if (static_cast<int>(nd.getPart()) == part) { int edges = std::distance(graph.edge_begin(n, flag), graph.edge_end(n, flag)); orderedNodes.push_back(std::make_pair(edges, n)); } } std::sort(orderedNodes.begin(), orderedNodes.end()); int index = 0; std::map<GNode, uint64_t>& threadMap(*threadDegInfo.getLocal()); for (auto p : orderedNodes) { GNode n = p.second; threadMap[n] += index; for (auto eb : graph.edges(n, flag)) { GNode neigh = graph.getEdgeDst(eb); auto& nd = graph.getData(neigh, flag); if (static_cast<int>(nd.getPart()) == part) { threadMap[neigh] += index; } } index++; } }, galois::wl<WL>(), galois::per_iter_alloc(), galois::loopname("Order Graph")); std::map<GNode, uint64_t> globalMap; for (unsigned int i = 0; i < threadDegInfo.size(); i++) { std::map<GNode, uint64_t>& localMap(*threadDegInfo.getRemote(i)); for (auto mb = localMap.begin(), me = localMap.end(); mb != me; mb++) { globalMap[mb->first] = mb->second; } } order_by_degree<GNode, std::map<GNode, uint64_t>> fn(graph, globalMap); std::map<GNode, int> nodeIdMap; int id = 0; for (auto nb = graph.begin(), ne = graph.end(); nb != ne; nb++) { nodeIdMap[*nb] = id; id++; } // compute inverse std::stable_sort(perm.begin(), perm.end(), fn); galois::LargeArray<uint64_t> perm2; perm2.create(g.size()); // compute permutation id = 0; for (auto pb = perm.begin(), pe = perm.end(); pb != pe; pb++) { int prevId = nodeIdMap[*pb]; perm2[prevId] = id; // std::cout<<prevId <<" "<<id<<std::endl; id++; } galois::graphs::FileGraph out; galois::graphs::permute<int>(g, perm2, out); if (orderedfile != "") out.toFile(orderedfile); if (permutationfile != "") { std::ofstream file(permutationfile.c_str()); galois::LargeArray<uint64_t> transpose; transpose.create(g.size()); uint64_t id = 0; for (auto& ii : perm2) { transpose[ii] = id++; } for (auto& ii : transpose) { file << ii << "\n"; } } } return 0; }
33.5
85
0.605266
bowu
eba72406c8bd972322ff51424249df7f49ea68b4
388
hpp
C++
parpm/grid.hpp
shigh/parpm
45d09bfa3103244fd8559dc32bc7c3ad5f83f614
[ "MIT" ]
null
null
null
parpm/grid.hpp
shigh/parpm
45d09bfa3103244fd8559dc32bc7c3ad5f83f614
[ "MIT" ]
null
null
null
parpm/grid.hpp
shigh/parpm
45d09bfa3103244fd8559dc32bc7c3ad5f83f614
[ "MIT" ]
null
null
null
#pragma once #include "types.hpp" struct Grid { // Number of grid points int Nx; int Ny; int Nz; // Starting grid points int Nx0; int Ny0; int Nz0; // Length of domain in this grid // Domain in this grid is [L0,L0+L] FLOAT Lx; FLOAT Ly; FLOAT Lz; FLOAT Lx0; FLOAT Ly0; FLOAT Lz0; // MPI info int rank; int size; int[3][3][3] neighbors; };
11.411765
37
0.597938
shigh
eba7f09abce753624cea5622578aac1653fa435a
28,858
cpp
C++
es/src/v20180416/EsClient.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
es/src/v20180416/EsClient.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
es/src/v20180416/EsClient.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/es/v20180416/EsClient.h> #include <tencentcloud/core/Executor.h> #include <tencentcloud/core/Runnable.h> using namespace TencentCloud; using namespace TencentCloud::Es::V20180416; using namespace TencentCloud::Es::V20180416::Model; using namespace std; namespace { const string VERSION = "2018-04-16"; const string ENDPOINT = "es.tencentcloudapi.com"; } EsClient::EsClient(const Credential &credential, const string &region) : EsClient(credential, region, ClientProfile()) { } EsClient::EsClient(const Credential &credential, const string &region, const ClientProfile &profile) : AbstractClient(ENDPOINT, VERSION, credential, region, profile) { } EsClient::CreateInstanceOutcome EsClient::CreateInstance(const CreateInstanceRequest &request) { auto outcome = MakeRequest(request, "CreateInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); CreateInstanceResponse rsp = CreateInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return CreateInstanceOutcome(rsp); else return CreateInstanceOutcome(o.GetError()); } else { return CreateInstanceOutcome(outcome.GetError()); } } void EsClient::CreateInstanceAsync(const CreateInstanceRequest& request, const CreateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->CreateInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::CreateInstanceOutcomeCallable EsClient::CreateInstanceCallable(const CreateInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<CreateInstanceOutcome()>>( [this, request]() { return this->CreateInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DeleteInstanceOutcome EsClient::DeleteInstance(const DeleteInstanceRequest &request) { auto outcome = MakeRequest(request, "DeleteInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DeleteInstanceResponse rsp = DeleteInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DeleteInstanceOutcome(rsp); else return DeleteInstanceOutcome(o.GetError()); } else { return DeleteInstanceOutcome(outcome.GetError()); } } void EsClient::DeleteInstanceAsync(const DeleteInstanceRequest& request, const DeleteInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DeleteInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DeleteInstanceOutcomeCallable EsClient::DeleteInstanceCallable(const DeleteInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<DeleteInstanceOutcome()>>( [this, request]() { return this->DeleteInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeInstanceLogsOutcome EsClient::DescribeInstanceLogs(const DescribeInstanceLogsRequest &request) { auto outcome = MakeRequest(request, "DescribeInstanceLogs"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeInstanceLogsResponse rsp = DescribeInstanceLogsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeInstanceLogsOutcome(rsp); else return DescribeInstanceLogsOutcome(o.GetError()); } else { return DescribeInstanceLogsOutcome(outcome.GetError()); } } void EsClient::DescribeInstanceLogsAsync(const DescribeInstanceLogsRequest& request, const DescribeInstanceLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeInstanceLogs(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeInstanceLogsOutcomeCallable EsClient::DescribeInstanceLogsCallable(const DescribeInstanceLogsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeInstanceLogsOutcome()>>( [this, request]() { return this->DescribeInstanceLogs(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeInstanceOperationsOutcome EsClient::DescribeInstanceOperations(const DescribeInstanceOperationsRequest &request) { auto outcome = MakeRequest(request, "DescribeInstanceOperations"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeInstanceOperationsResponse rsp = DescribeInstanceOperationsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeInstanceOperationsOutcome(rsp); else return DescribeInstanceOperationsOutcome(o.GetError()); } else { return DescribeInstanceOperationsOutcome(outcome.GetError()); } } void EsClient::DescribeInstanceOperationsAsync(const DescribeInstanceOperationsRequest& request, const DescribeInstanceOperationsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeInstanceOperations(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeInstanceOperationsOutcomeCallable EsClient::DescribeInstanceOperationsCallable(const DescribeInstanceOperationsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeInstanceOperationsOutcome()>>( [this, request]() { return this->DescribeInstanceOperations(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeInstancesOutcome EsClient::DescribeInstances(const DescribeInstancesRequest &request) { auto outcome = MakeRequest(request, "DescribeInstances"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeInstancesResponse rsp = DescribeInstancesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeInstancesOutcome(rsp); else return DescribeInstancesOutcome(o.GetError()); } else { return DescribeInstancesOutcome(outcome.GetError()); } } void EsClient::DescribeInstancesAsync(const DescribeInstancesRequest& request, const DescribeInstancesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeInstances(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeInstancesOutcomeCallable EsClient::DescribeInstancesCallable(const DescribeInstancesRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeInstancesOutcome()>>( [this, request]() { return this->DescribeInstances(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DescribeViewsOutcome EsClient::DescribeViews(const DescribeViewsRequest &request) { auto outcome = MakeRequest(request, "DescribeViews"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DescribeViewsResponse rsp = DescribeViewsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DescribeViewsOutcome(rsp); else return DescribeViewsOutcome(o.GetError()); } else { return DescribeViewsOutcome(outcome.GetError()); } } void EsClient::DescribeViewsAsync(const DescribeViewsRequest& request, const DescribeViewsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DescribeViews(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DescribeViewsOutcomeCallable EsClient::DescribeViewsCallable(const DescribeViewsRequest &request) { auto task = std::make_shared<std::packaged_task<DescribeViewsOutcome()>>( [this, request]() { return this->DescribeViews(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::DiagnoseInstanceOutcome EsClient::DiagnoseInstance(const DiagnoseInstanceRequest &request) { auto outcome = MakeRequest(request, "DiagnoseInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); DiagnoseInstanceResponse rsp = DiagnoseInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return DiagnoseInstanceOutcome(rsp); else return DiagnoseInstanceOutcome(o.GetError()); } else { return DiagnoseInstanceOutcome(outcome.GetError()); } } void EsClient::DiagnoseInstanceAsync(const DiagnoseInstanceRequest& request, const DiagnoseInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->DiagnoseInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::DiagnoseInstanceOutcomeCallable EsClient::DiagnoseInstanceCallable(const DiagnoseInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<DiagnoseInstanceOutcome()>>( [this, request]() { return this->DiagnoseInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::GetRequestTargetNodeTypesOutcome EsClient::GetRequestTargetNodeTypes(const GetRequestTargetNodeTypesRequest &request) { auto outcome = MakeRequest(request, "GetRequestTargetNodeTypes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); GetRequestTargetNodeTypesResponse rsp = GetRequestTargetNodeTypesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return GetRequestTargetNodeTypesOutcome(rsp); else return GetRequestTargetNodeTypesOutcome(o.GetError()); } else { return GetRequestTargetNodeTypesOutcome(outcome.GetError()); } } void EsClient::GetRequestTargetNodeTypesAsync(const GetRequestTargetNodeTypesRequest& request, const GetRequestTargetNodeTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->GetRequestTargetNodeTypes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::GetRequestTargetNodeTypesOutcomeCallable EsClient::GetRequestTargetNodeTypesCallable(const GetRequestTargetNodeTypesRequest &request) { auto task = std::make_shared<std::packaged_task<GetRequestTargetNodeTypesOutcome()>>( [this, request]() { return this->GetRequestTargetNodeTypes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::RestartInstanceOutcome EsClient::RestartInstance(const RestartInstanceRequest &request) { auto outcome = MakeRequest(request, "RestartInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); RestartInstanceResponse rsp = RestartInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return RestartInstanceOutcome(rsp); else return RestartInstanceOutcome(o.GetError()); } else { return RestartInstanceOutcome(outcome.GetError()); } } void EsClient::RestartInstanceAsync(const RestartInstanceRequest& request, const RestartInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->RestartInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::RestartInstanceOutcomeCallable EsClient::RestartInstanceCallable(const RestartInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<RestartInstanceOutcome()>>( [this, request]() { return this->RestartInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::RestartKibanaOutcome EsClient::RestartKibana(const RestartKibanaRequest &request) { auto outcome = MakeRequest(request, "RestartKibana"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); RestartKibanaResponse rsp = RestartKibanaResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return RestartKibanaOutcome(rsp); else return RestartKibanaOutcome(o.GetError()); } else { return RestartKibanaOutcome(outcome.GetError()); } } void EsClient::RestartKibanaAsync(const RestartKibanaRequest& request, const RestartKibanaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->RestartKibana(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::RestartKibanaOutcomeCallable EsClient::RestartKibanaCallable(const RestartKibanaRequest &request) { auto task = std::make_shared<std::packaged_task<RestartKibanaOutcome()>>( [this, request]() { return this->RestartKibana(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::RestartNodesOutcome EsClient::RestartNodes(const RestartNodesRequest &request) { auto outcome = MakeRequest(request, "RestartNodes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); RestartNodesResponse rsp = RestartNodesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return RestartNodesOutcome(rsp); else return RestartNodesOutcome(o.GetError()); } else { return RestartNodesOutcome(outcome.GetError()); } } void EsClient::RestartNodesAsync(const RestartNodesRequest& request, const RestartNodesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->RestartNodes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::RestartNodesOutcomeCallable EsClient::RestartNodesCallable(const RestartNodesRequest &request) { auto task = std::make_shared<std::packaged_task<RestartNodesOutcome()>>( [this, request]() { return this->RestartNodes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateDiagnoseSettingsOutcome EsClient::UpdateDiagnoseSettings(const UpdateDiagnoseSettingsRequest &request) { auto outcome = MakeRequest(request, "UpdateDiagnoseSettings"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateDiagnoseSettingsResponse rsp = UpdateDiagnoseSettingsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateDiagnoseSettingsOutcome(rsp); else return UpdateDiagnoseSettingsOutcome(o.GetError()); } else { return UpdateDiagnoseSettingsOutcome(outcome.GetError()); } } void EsClient::UpdateDiagnoseSettingsAsync(const UpdateDiagnoseSettingsRequest& request, const UpdateDiagnoseSettingsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateDiagnoseSettings(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateDiagnoseSettingsOutcomeCallable EsClient::UpdateDiagnoseSettingsCallable(const UpdateDiagnoseSettingsRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateDiagnoseSettingsOutcome()>>( [this, request]() { return this->UpdateDiagnoseSettings(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateDictionariesOutcome EsClient::UpdateDictionaries(const UpdateDictionariesRequest &request) { auto outcome = MakeRequest(request, "UpdateDictionaries"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateDictionariesResponse rsp = UpdateDictionariesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateDictionariesOutcome(rsp); else return UpdateDictionariesOutcome(o.GetError()); } else { return UpdateDictionariesOutcome(outcome.GetError()); } } void EsClient::UpdateDictionariesAsync(const UpdateDictionariesRequest& request, const UpdateDictionariesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateDictionaries(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateDictionariesOutcomeCallable EsClient::UpdateDictionariesCallable(const UpdateDictionariesRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateDictionariesOutcome()>>( [this, request]() { return this->UpdateDictionaries(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateInstanceOutcome EsClient::UpdateInstance(const UpdateInstanceRequest &request) { auto outcome = MakeRequest(request, "UpdateInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateInstanceResponse rsp = UpdateInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateInstanceOutcome(rsp); else return UpdateInstanceOutcome(o.GetError()); } else { return UpdateInstanceOutcome(outcome.GetError()); } } void EsClient::UpdateInstanceAsync(const UpdateInstanceRequest& request, const UpdateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateInstanceOutcomeCallable EsClient::UpdateInstanceCallable(const UpdateInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateInstanceOutcome()>>( [this, request]() { return this->UpdateInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateJdkOutcome EsClient::UpdateJdk(const UpdateJdkRequest &request) { auto outcome = MakeRequest(request, "UpdateJdk"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateJdkResponse rsp = UpdateJdkResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateJdkOutcome(rsp); else return UpdateJdkOutcome(o.GetError()); } else { return UpdateJdkOutcome(outcome.GetError()); } } void EsClient::UpdateJdkAsync(const UpdateJdkRequest& request, const UpdateJdkAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateJdk(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateJdkOutcomeCallable EsClient::UpdateJdkCallable(const UpdateJdkRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateJdkOutcome()>>( [this, request]() { return this->UpdateJdk(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdatePluginsOutcome EsClient::UpdatePlugins(const UpdatePluginsRequest &request) { auto outcome = MakeRequest(request, "UpdatePlugins"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdatePluginsResponse rsp = UpdatePluginsResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdatePluginsOutcome(rsp); else return UpdatePluginsOutcome(o.GetError()); } else { return UpdatePluginsOutcome(outcome.GetError()); } } void EsClient::UpdatePluginsAsync(const UpdatePluginsRequest& request, const UpdatePluginsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdatePlugins(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdatePluginsOutcomeCallable EsClient::UpdatePluginsCallable(const UpdatePluginsRequest &request) { auto task = std::make_shared<std::packaged_task<UpdatePluginsOutcome()>>( [this, request]() { return this->UpdatePlugins(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpdateRequestTargetNodeTypesOutcome EsClient::UpdateRequestTargetNodeTypes(const UpdateRequestTargetNodeTypesRequest &request) { auto outcome = MakeRequest(request, "UpdateRequestTargetNodeTypes"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpdateRequestTargetNodeTypesResponse rsp = UpdateRequestTargetNodeTypesResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpdateRequestTargetNodeTypesOutcome(rsp); else return UpdateRequestTargetNodeTypesOutcome(o.GetError()); } else { return UpdateRequestTargetNodeTypesOutcome(outcome.GetError()); } } void EsClient::UpdateRequestTargetNodeTypesAsync(const UpdateRequestTargetNodeTypesRequest& request, const UpdateRequestTargetNodeTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpdateRequestTargetNodeTypes(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpdateRequestTargetNodeTypesOutcomeCallable EsClient::UpdateRequestTargetNodeTypesCallable(const UpdateRequestTargetNodeTypesRequest &request) { auto task = std::make_shared<std::packaged_task<UpdateRequestTargetNodeTypesOutcome()>>( [this, request]() { return this->UpdateRequestTargetNodeTypes(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpgradeInstanceOutcome EsClient::UpgradeInstance(const UpgradeInstanceRequest &request) { auto outcome = MakeRequest(request, "UpgradeInstance"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpgradeInstanceResponse rsp = UpgradeInstanceResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpgradeInstanceOutcome(rsp); else return UpgradeInstanceOutcome(o.GetError()); } else { return UpgradeInstanceOutcome(outcome.GetError()); } } void EsClient::UpgradeInstanceAsync(const UpgradeInstanceRequest& request, const UpgradeInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpgradeInstance(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpgradeInstanceOutcomeCallable EsClient::UpgradeInstanceCallable(const UpgradeInstanceRequest &request) { auto task = std::make_shared<std::packaged_task<UpgradeInstanceOutcome()>>( [this, request]() { return this->UpgradeInstance(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); } EsClient::UpgradeLicenseOutcome EsClient::UpgradeLicense(const UpgradeLicenseRequest &request) { auto outcome = MakeRequest(request, "UpgradeLicense"); if (outcome.IsSuccess()) { auto r = outcome.GetResult(); string payload = string(r.Body(), r.BodySize()); UpgradeLicenseResponse rsp = UpgradeLicenseResponse(); auto o = rsp.Deserialize(payload); if (o.IsSuccess()) return UpgradeLicenseOutcome(rsp); else return UpgradeLicenseOutcome(o.GetError()); } else { return UpgradeLicenseOutcome(outcome.GetError()); } } void EsClient::UpgradeLicenseAsync(const UpgradeLicenseRequest& request, const UpgradeLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) { auto fn = [this, request, handler, context]() { handler(this, request, this->UpgradeLicense(request), context); }; Executor::GetInstance()->Submit(new Runnable(fn)); } EsClient::UpgradeLicenseOutcomeCallable EsClient::UpgradeLicenseCallable(const UpgradeLicenseRequest &request) { auto task = std::make_shared<std::packaged_task<UpgradeLicenseOutcome()>>( [this, request]() { return this->UpgradeLicense(request); } ); Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); })); return task->get_future(); }
33.555814
215
0.682306
suluner
ebacd0352d7062bcc1367156311b30e3282f5317
864
hpp
C++
irohad/ametsuchi/wsv_restorer.hpp
IvanTyulyandin/iroha
442a08325c7b808236569600653370e28ec5eff6
[ "Apache-2.0" ]
24
2016-09-26T17:11:46.000Z
2020-03-03T13:42:58.000Z
irohad/ametsuchi/wsv_restorer.hpp
ecsantana76/iroha
9cc430bb2c8eb885393e2a636fa92d1e605443ae
[ "Apache-2.0" ]
11
2016-10-13T10:09:55.000Z
2019-06-13T08:49:11.000Z
irohad/ametsuchi/wsv_restorer.hpp
ecsantana76/iroha
9cc430bb2c8eb885393e2a636fa92d1e605443ae
[ "Apache-2.0" ]
4
2016-09-27T13:18:28.000Z
2019-08-05T20:47:15.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_WSVRESTORER_HPP #define IROHA_WSVRESTORER_HPP #include "common/result.hpp" namespace iroha { namespace ametsuchi { class Storage; /** * Interface for World State View restoring from the storage */ class WsvRestorer { public: virtual ~WsvRestorer() = default; /** * Recover WSV (World State View). * @param storage storage of blocks in ledger * @return ledger state after restoration on success, otherwise error * string */ virtual iroha::expected:: Result<boost::optional<std::unique_ptr<LedgerState>>, std::string> restoreWsv(Storage &storage) = 0; }; } // namespace ametsuchi } // namespace iroha #endif // IROHA_WSVRESTORER_HPP
23.351351
76
0.649306
IvanTyulyandin
ebae262b24238eda226ca36a0f1d84f6f2c93374
2,486
cpp
C++
test/std/utilities/function.objects/comparisons/transparent.pass.cpp
AOSiP/platform_external_libcxx
eb2115113f10274c0d25523ba44c3c7373ea3209
[ "MIT" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
test/std/utilities/function.objects/comparisons/transparent.pass.cpp
AOSiP/platform_external_libcxx
eb2115113f10274c0d25523ba44c3c7373ea3209
[ "MIT" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
test/std/utilities/function.objects/comparisons/transparent.pass.cpp
AOSiP/platform_external_libcxx
eb2115113f10274c0d25523ba44c3c7373ea3209
[ "MIT" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11 #include <functional> #include <string> template <class T> struct is_transparent { private: struct two {char lx; char lxx;}; template <class U> static two test(...); template <class U> static char test(typename U::is_transparent* = 0); public: static const bool value = sizeof(test<T>(0)) == 1; }; int main () { static_assert ( !is_transparent<std::less<int>>::value, "" ); static_assert ( !is_transparent<std::less<std::string>>::value, "" ); static_assert ( is_transparent<std::less<void>>::value, "" ); static_assert ( is_transparent<std::less<>>::value, "" ); static_assert ( !is_transparent<std::less_equal<int>>::value, "" ); static_assert ( !is_transparent<std::less_equal<std::string>>::value, "" ); static_assert ( is_transparent<std::less_equal<void>>::value, "" ); static_assert ( is_transparent<std::less_equal<>>::value, "" ); static_assert ( !is_transparent<std::equal_to<int>>::value, "" ); static_assert ( !is_transparent<std::equal_to<std::string>>::value, "" ); static_assert ( is_transparent<std::equal_to<void>>::value, "" ); static_assert ( is_transparent<std::equal_to<>>::value, "" ); static_assert ( !is_transparent<std::not_equal_to<int>>::value, "" ); static_assert ( !is_transparent<std::not_equal_to<std::string>>::value, "" ); static_assert ( is_transparent<std::not_equal_to<void>>::value, "" ); static_assert ( is_transparent<std::not_equal_to<>>::value, "" ); static_assert ( !is_transparent<std::greater<int>>::value, "" ); static_assert ( !is_transparent<std::greater<std::string>>::value, "" ); static_assert ( is_transparent<std::greater<void>>::value, "" ); static_assert ( is_transparent<std::greater<>>::value, "" ); static_assert ( !is_transparent<std::greater_equal<int>>::value, "" ); static_assert ( !is_transparent<std::greater_equal<std::string>>::value, "" ); static_assert ( is_transparent<std::greater_equal<void>>::value, "" ); static_assert ( is_transparent<std::greater_equal<>>::value, "" ); return 0; }
41.433333
82
0.613837
AOSiP
ebae48b12ed38473e0991443ea1b7902cb844a6c
19,369
cpp
C++
src/maze.cpp
TimQuelch/mazes
486291e0c84264664953b1bebfa77593854d9e77
[ "MIT" ]
1
2018-05-15T02:27:12.000Z
2018-05-15T02:27:12.000Z
src/maze.cpp
TimQuelch/mazes
486291e0c84264664953b1bebfa77593854d9e77
[ "MIT" ]
null
null
null
src/maze.cpp
TimQuelch/mazes
486291e0c84264664953b1bebfa77593854d9e77
[ "MIT" ]
null
null
null
/// \author Tim Quelch #include <algorithm> #include <chrono> #include <cmath> #include <deque> #include <iomanip> #include <iostream> #include <png++/png.hpp> #include <random> #include <tuple> #include "maze.h" namespace mazes { namespace detail { /// Holds the x y coordinates of a point in the maze struct Point { int x; ///< x coordinate int y; ///< y coordinate /// Construct with given values /// \param x The x coordinate /// \param y The y coordinate Point(int x = 0, int y = 0) : x{x} , y{y} {} /// Orders points lexicographically by x coordinate then y coordinate /// \param rhs Another point /// \returns true if the point is lexicographically less than the other by x then y bool operator<(const Point& rhs) { return std::tie(x, y) < std::tie(rhs.x, rhs.y); } /// Points are equal if both x and y are equal /// \param rhs Another point /// \returns true if both x and y are equal bool operator==(const Point& rhs) { return x == rhs.x && y == rhs.y; } }; /// Generates a random integer between a and b int randInt(int a, int b) { static auto seed = std::chrono::system_clock::now().time_since_epoch().count(); static auto randEngine = std::default_random_engine{seed}; auto dist = std::uniform_int_distribution{a, b}; return dist(randEngine); } /// Checks if a coordinate is within the boundaries of the maze. That is, if it x and y are /// greater than 1 and less than size - 1 /// \param p A Point /// \param gridSize the length of the side of the maze /// \returns true if the point is within the walls of the maze bool isLegal(Point p, int gridSize) { return p.x > 0 && p.x < gridSize - 1 && p.y > 0 && p.y < gridSize - 1; } /// Checks if point is a wall that can be removed to form a loop. Wall must be a vertical or /// horizontal wall, not a T wall, or X wall. /// \param grid Grid of the maze /// \param p A Point /// \returns true if the point can be removed to form a loop bool isWall(const std::vector<std::vector<bool>>& grid, Point p) { int countWalls = 0; countWalls += grid[p.x - 1][p.y] ? 0 : 1; countWalls += grid[p.x + 1][p.y] ? 0 : 1; countWalls += grid[p.x][p.y - 1] ? 0 : 1; countWalls += grid[p.x][p.y + 1] ? 0 : 1; bool wall = !grid[p.x][p.y]; bool nsWall = !grid[p.x][p.y + 1] && !grid[p.x][p.y - 1]; bool esWall = !grid[p.x - 1][p.y] && !grid[p.x + 1][p.y]; return wall && (nsWall || esWall) && !(nsWall && esWall) && (countWalls < 3); } /// Returns a list the points of the neighbours of a point. Neighbours are in the four /// cardinal directions and are a distance of two away. They are two away so that the wall /// inbetween is jumped. std::list<Point> getNeighbours(unsigned gridSize, Point p) { auto newNodes = std::list<Point>{}; newNodes.push_back({p.x - 2, p.y}); newNodes.push_back({p.x, p.y - 2}); newNodes.push_back({p.x, p.y + 2}); newNodes.push_back({p.x + 2, p.y}); newNodes.remove_if([gridSize](Point p) { return !isLegal(p, gridSize); }); return newNodes; } /// Returns and removes a random point from a list /// \param points Reference to a list of points. A random point is removed from this list /// \returns The Point removed from the list Point popPoint(std::list<Point>& points) { unsigned index = randInt(0, points.size() - 1); auto it = points.begin(); for (unsigned i = 0; i < index; i++) { it++; } points.erase(it); return *it; } /// Check if a point is a horizontal corridor. That is, it has corridors to the left and /// right, and walls to the top and bottom bool isHCorridor(Point p, const std::vector<std::vector<bool>>& grid) { return grid[p.x - 1][p.y] && grid[p.x + 1][p.y] && !grid[p.x][p.y - 1] && !grid[p.x][p.y + 1]; } /// Check if a point is a vertical corridor. That is, it has corridors to the top and /// bottom, and walls to the left and right bool isVCorridor(Point p, const std::vector<std::vector<bool>>& grid) { return !grid[p.x - 1][p.y] && !grid[p.x + 1][p.y] && grid[p.x][p.y - 1] && grid[p.x][p.y + 1]; } /// Calculate the manhatten distance between two points int calcCost(Point one, Point two) { return std::abs(one.x - two.x) + std::abs(one.y - two.y); } /// Initialise a grid to false std::vector<std::vector<bool>> initGrid(unsigned size) { auto grid = std::vector<std::vector<bool>>(); grid.resize(size); for (unsigned i = 0; i < size; i++) { grid[i].resize(size, false); } return grid; } /// Generate maze with Prims method void generatePrims(std::vector<std::vector<bool>>& grid) { const auto size = grid.size(); // Randomly generate initial point auto init = Point{randInt(0, (size - 2) / 2) * 2 + 1, randInt(0, (size - 2) / 2) * 2 + 1}; grid[init.x][init.y] = true; // Generate frontier points from neighbours auto frontierPoints = std::list<Point>{getNeighbours(size, init)}; // Expand maze until grid is full while (!frontierPoints.empty()) { // Pick random frontier point and set it to true auto p1 = Point{popPoint(frontierPoints)}; grid[p1.x][p1.y] = true; // Pick a random neighbours which is a pathway, and link the two points by setting // the intermediate point to a pathway auto neighbours = std::list<Point>{getNeighbours(size, p1)}; neighbours.remove_if([&grid](Point p) { return !grid[p.x][p.y]; }); auto p2 = Point{popPoint(neighbours)}; grid[p2.x - (p2.x - p1.x) / 2][p2.y - (p2.y - p1.y) / 2] = true; // Find and add the new frontier points auto newFrontierPoints = std::list<Point>{getNeighbours(size, p1)}; newFrontierPoints.remove_if([&grid](Point p) { return grid[p.x][p.y]; }); frontierPoints.merge(newFrontierPoints); frontierPoints.unique(); } } std::list<std::pair<Point, Point>> divideChamber(std::vector<std::vector<bool>>& grid, std::pair<Point, Point> chamber) { const auto x1 = chamber.first.x; const auto y1 = chamber.first.y; const auto x2 = chamber.second.x; const auto y2 = chamber.second.y; const auto size = x2 - x1; const auto mid = (size + 1) / 2; if (size < 2) { return {}; } // Set chamber to pathways for (auto i = x1; i <= x2; i++) { for (auto j = y1; j <= y2; j++) { grid[i][j] = true; } } // Set inner walls to walls for (auto i = x1; i <= x2; i++) { grid[i][y1 + mid] = false; } for (auto j = y1; j <= y2; j++) { grid[x1 + mid][j] = false; } // Create openings in walls const auto rand = [mid]() { return randInt(0, mid / 2) * 2; }; auto openings = std::vector<Point>{{x1 + mid, y1 + rand()}, {x1 + mid, y1 + mid + 1 + rand()}, {x1 + rand(), y1 + mid}, {x1 + mid + 1 + rand(), y1 + mid}}; openings.erase(openings.cbegin() + randInt(0, 3)); for (auto p : openings) { grid[p.x][p.y] = true; } // Return the subdivided chambers return {{{x1, y1}, {x1 + mid - 1, y1 + mid - 1}}, {{x1 + mid + 1, y1 + mid + 1}, {x2, y2}}, {{x1 + mid + 1, y1}, {x2, y1 + mid - 1}}, {{x1, y1 + mid + 1}, {x1 + mid - 1, y2}}}; } /// Generate maze with recursive division method void generateDivision(std::vector<std::vector<bool>>& grid) { const auto size = static_cast<int>(grid.size()); auto chambers = std::deque<std::pair<Point, Point>>{}; chambers.push_back({{1, 1}, {size - 2, size - 2}}); while (!chambers.empty()) { auto newChambers = divideChamber(grid, chambers.front()); chambers.pop_front(); for (const auto& c : newChambers) { chambers.push_back(c); } } } /// Remove walls to create multiple paths in the maze. Pick random points until a valid /// wall is found, then set it to be a pathway void addLoops(std::vector<std::vector<bool>>& grid, double loopFactor) { const auto size = grid.size(); const unsigned loops = size * size * loopFactor * loopFactor; for (unsigned i = 0; i < loops; i++) { Point p; do { p = Point(randInt(1, size - 2), randInt(1, size - 2)); } while (!isWall(grid, p)); grid[p.x][p.y] = true; } } /// Add the entrance and exit of the maze void addEntranceAndExit(std::vector<std::vector<bool>>& grid) { const auto size = grid.size(); grid[1][0] = true; grid[size - 2][size - 1] = true; } /// Generate the grid of a maze. There is an entrance in the top left, and an exit in the /// bottom right. /// \param size the length of the side of the maze /// \param loopFactor the factor of loopiness in the maze. 0 means there is a single /// solution, increasing increases number of solutions /// \returns the grid of the maze. can be indexed with v[x][y] /// \callgraph std::vector<std::vector<bool>> generateGrid(unsigned size, double loopFactor, Maze::Method method) { auto grid = initGrid(size); switch (method) { case Maze::Method::prims: generatePrims(grid); break; case Maze::Method::division: generateDivision(grid); break; } addLoops(grid, loopFactor); addEntranceAndExit(grid); return grid; } /// Generate the graph of a maze from the grid. The maze is sorted left to right, then top /// to bottom, therefore the entrance is the first node, and the exit is the last node /// \param grid The Maze grid to generate the graph from /// \returns A list of Nodes that make up the graph of the maze std::list<std::shared_ptr<Maze::Node>> generateGraph(const std::vector<std::vector<bool>>& grid) { using Node = Maze::Node; using Edge = Maze::Edge; const int size = grid.size(); auto graph = std::list<std::shared_ptr<Node>>{}; // nodes in the graph auto above = std::list<std::shared_ptr<Node>>{}; // nodes that are above current // Add start node auto first = std::make_shared<Node>(1, 0, std::list<Edge>{}); graph.push_back(first); above.push_back(first); // Iterate through whole grid for (int j = 1; j < size; j++) { auto left = std::shared_ptr<Node>{nullptr}; // The node that is left of present auto nodeAbove = above.begin(); // Iterator to start of above nodes for (int i = 1; i < size - 1; i++) { if (grid[i][j]) { // Ignore point if it is a corridor if (!isHCorridor({i, j}, grid) && !isVCorridor({i, j}, grid)) { auto edges = std::list<Edge>{}; // Add edge if there is a node to the left if (left) { int cost = calcCost({i, j}, {left->x, left->y}); edges.push_back({left, cost}); } // Add edge if there is a node above if (nodeAbove != above.end() && (*nodeAbove)->x == i) { int cost = calcCost({i, j}, {(*nodeAbove)->x, (*nodeAbove)->y}); edges.push_back({*nodeAbove, cost}); nodeAbove = above.erase(nodeAbove); } // Create the node auto node = std::make_shared<Node>(i, j, edges); graph.push_back(node); above.insert(nodeAbove, node); left = node; // Add edges to this node from all edges for (const auto& edge : edges) { edge.node->edges.push_back({node, edge.cost}); } } // Iterate above iterator if needed if (isVCorridor({i, j}, grid) && nodeAbove != above.end() && (*nodeAbove)->x == i) { nodeAbove++; } } else { // If current is wall, reset left and iterate above left = nullptr; if (nodeAbove != above.end() && (*nodeAbove)->x == i) { nodeAbove = above.erase(nodeAbove); } } } } // Sort the list of nodes. Entrance will be first, exit will be last graph.sort([](auto& one, auto& two) { return std::tie(one->x, one->y) < std::tie(two->x, two->y); }); return graph; } } // namespace detail // Construct maze with given size. Generate grid and graph Maze::Maze(unsigned size, double loopFactor, Maze::Method method) : size_{size} , grid_{detail::generateGrid(size, loopFactor, method)} , graph_{detail::generateGraph(grid_)} {} // Print the maze to stdout void Maze::print() const { std::cout << " "; for (unsigned i = 0; i < size_; i++) { std::cout << std::setw(2) << i << " "; } std::cout << "\n\n"; for (unsigned j = 0; j < size_; j++) { std::cout << std::setw(2) << j << " "; for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { std::cout << " "; } else { std::cout << " # "; } } std::cout << "\n"; } std::cout << "\n"; } // Print the graph nodes over the maze to stdout void Maze::printGraph() const { // Create grid where nodes are true auto graphGrid = std::vector<std::vector<bool>>{}; graphGrid.resize(size_); for (unsigned i = 0; i < size_; i++) { graphGrid[i].resize(size_, false); } for (auto nodePtr : graph_) { graphGrid[nodePtr->x][nodePtr->y] = true; } // Print to output std::cout << " "; for (unsigned i = 0; i < size_; i++) { std::cout << std::setw(2) << i << " "; } std::cout << "\n\n"; for (unsigned j = 0; j < size_; j++) { std::cout << std::setw(2) << j << " "; for (unsigned i = 0; i < size_; i++) { if (graphGrid[i][j]) { std::cout << " o "; } else if (grid_[i][j]) { std::cout << " "; } else { std::cout << " # "; } } std::cout << "\n"; } std::cout << "\n"; } // Write the maze to PNG void Maze::writePng(std::string_view filename) const { auto image = png::image<png::rgb_pixel>{size_, size_}; for (unsigned j = 0; j < size_; j++) { for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { image[j][i] = png::rgb_pixel(255, 255, 255); } else { image[j][i] = png::rgb_pixel(0, 0, 0); } } } image.write(filename.data()); } // Write the graph nodes over the maze to PNG void Maze::writePngGraph(std::string_view filename) const { auto image = png::image<png::rgb_pixel>{size_, size_}; // Write maze for (unsigned j = 0; j < size_; j++) { for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { image[j][i] = png::rgb_pixel(255, 255, 255); } else { image[j][i] = png::rgb_pixel(0, 0, 0); } } } // Write graph for (auto nodePtr : graph_) { image[nodePtr->y][nodePtr->x] = png::rgb_pixel(255, 0, 0); } image.write(filename.data()); } // Write the maze with a given path to PNG void Maze::writePngPath(std::list<std::shared_ptr<Node>> path, std::string_view filename) const { auto image = png::image<png::rgb_pixel>{size_, size_}; // Write maze for (unsigned j = 0; j < size_; j++) { for (unsigned i = 0; i < size_; i++) { if (grid_[i][j]) { image[j][i] = png::rgb_pixel(255, 255, 255); } else { image[j][i] = png::rgb_pixel(0, 0, 0); } } } // Write path auto prev = detail::Point{path.front()->x, path.front()->y}; for (const auto& node : path) { auto start = detail::Point{std::min(prev.x, node->x), std::min(prev.y, node->y)}; auto end = detail::Point{std::max(prev.x + 1, node->x + 1), std::max(prev.y + 1, node->y + 1)}; for (int i = start.x; i != end.x; i++) { for (int j = start.y; j != end.y; j++) { image[j][i] = png::rgb_pixel(255, 0, 0); } } prev = {node->x, node->y}; } image.write(filename.data()); } } // namespace mazes
40.268191
100
0.466209
TimQuelch
ebaf7015eb587472504c212dabecb2225cd1d243
3,365
cc
C++
hbase-native-client/src/hbase/test-util/test-util.cc
bijugs/hbase-1.1.2.2.6.3.22-1
56954ebd740994c90ce872c732c1637a65e4865e
[ "Apache-2.0" ]
null
null
null
hbase-native-client/src/hbase/test-util/test-util.cc
bijugs/hbase-1.1.2.2.6.3.22-1
56954ebd740994c90ce872c732c1637a65e4865e
[ "Apache-2.0" ]
null
null
null
hbase-native-client/src/hbase/test-util/test-util.cc
bijugs/hbase-1.1.2.2.6.3.22-1
56954ebd740994c90ce872c732c1637a65e4865e
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "hbase/test-util/test-util.h" #include <string.h> #include <folly/Format.h> #include "hbase/client/zk-util.h" using hbase::TestUtil; using folly::Random; std::string TestUtil::RandString(int len) { // Create the whole string. // Filling everything with z's auto s = std::string(len, 'z'); // Now pick a bunch of random numbers for (int i = 0; i < len; i++) { // use Folly's random to get the numbers // as I don't want to have to learn // all the cpp rand invocation magic. auto r = Random::rand32('a', 'z'); // Cast that to ascii. s[i] = static_cast<char>(r); } return s; } TestUtil::TestUtil() : temp_dir_(TestUtil::RandString()) {} TestUtil::~TestUtil() { if (mini_) { StopMiniCluster(); mini_ = nullptr; } } void TestUtil::StartMiniCluster(int32_t num_region_servers) { mini_ = std::make_unique<MiniCluster>(); mini_->StartCluster(num_region_servers); conf()->Set(ZKUtil::kHBaseZookeeperQuorum_, mini_->GetConfValue(ZKUtil::kHBaseZookeeperQuorum_)); conf()->Set(ZKUtil::kHBaseZookeeperClientPort_, mini_->GetConfValue(ZKUtil::kHBaseZookeeperClientPort_)); } void TestUtil::StopMiniCluster() { mini_->StopCluster(); } void TestUtil::CreateTable(const std::string &table, const std::string &family) { mini_->CreateTable(table, family); } void TestUtil::CreateTable(const std::string &table, const std::vector<std::string> &families) { mini_->CreateTable(table, families); } void TestUtil::CreateTable(const std::string &table, const std::string &family, const std::vector<std::string> &keys) { mini_->CreateTable(table, family, keys); } void TestUtil::CreateTable(const std::string &table, const std::vector<std::string> &families, const std::vector<std::string> &keys) { mini_->CreateTable(table, families, keys); } void TestUtil::MoveRegion(const std::string &region, const std::string &server) { mini_->MoveRegion(region, server); } void TestUtil::StartStandAloneInstance() { auto p = temp_dir_.path().string(); auto cmd = std::string{"bin/start-local-hbase.sh " + p}; auto res_code = std::system(cmd.c_str()); CHECK_EQ(res_code, 0); } void TestUtil::StopStandAloneInstance() { auto res_code = std::system("bin/stop-local-hbase.sh"); CHECK_EQ(res_code, 0); } void TestUtil::RunShellCmd(const std::string &command) { auto cmd_string = folly::sformat("echo \"{}\" | ../bin/hbase shell", command); auto res_code = std::system(cmd_string.c_str()); CHECK_EQ(res_code, 0); }
31.745283
99
0.695097
bijugs
ebb2bb4ff11aaa03b6edc0e46b316ba4638a2023
1,009
hpp
C++
test/test_localization.hpp
enterstudio/aeon
7e1af0387815b4c90de2a289fb2cfb4a6f5ae9d3
[ "Apache-2.0" ]
null
null
null
test/test_localization.hpp
enterstudio/aeon
7e1af0387815b4c90de2a289fb2cfb4a6f5ae9d3
[ "Apache-2.0" ]
null
null
null
test/test_localization.hpp
enterstudio/aeon
7e1af0387815b4c90de2a289fb2cfb4a6f5ae9d3
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 Nervana Systems 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. */ #pragma once #include <vector> #include <string> #include <opencv2/core/core.hpp> extern std::vector<std::string> label_list; std::vector<uint8_t> make_image_from_metadata(const std::string& metadata); nervana::boundingbox::box crop_single_box(nervana::boundingbox::box expected, cv::Rect cropbox, float scale); void plot(const std::vector<nervana::box>& list, const std::string& prefix); void plot(const std::string& path);
36.035714
87
0.766105
enterstudio
ebb692aeee5113ec9f14ba526ce5b8d0584b6d55
11,876
cc
C++
src/lib/dhcpsrv/client_class_def.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
2
2020-11-02T19:38:10.000Z
2020-11-02T19:38:13.000Z
src/lib/dhcpsrv/client_class_def.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
null
null
null
src/lib/dhcpsrv/client_class_def.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2015-2019 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <eval/dependency.h> #include <dhcpsrv/client_class_def.h> #include <dhcpsrv/cfgmgr.h> #include <boost/foreach.hpp> using namespace isc::data; namespace isc { namespace dhcp { //********** ClientClassDef ******************// ClientClassDef::ClientClassDef(const std::string& name, const ExpressionPtr& match_expr, const CfgOptionPtr& cfg_option) : name_(name), match_expr_(match_expr), required_(false), depend_on_known_(false), cfg_option_(cfg_option), next_server_(asiolink::IOAddress::IPV4_ZERO_ADDRESS()) { // Name can't be blank if (name_.empty()) { isc_throw(BadValue, "Client Class name cannot be blank"); } // We permit an empty expression for now. This will likely be useful // for automatic classes such as vendor class. // For classes without options, make sure we have an empty collection if (!cfg_option_) { cfg_option_.reset(new CfgOption()); } } ClientClassDef::ClientClassDef(const ClientClassDef& rhs) : name_(rhs.name_), match_expr_(ExpressionPtr()), required_(false), depend_on_known_(false), cfg_option_(new CfgOption()), next_server_(asiolink::IOAddress::IPV4_ZERO_ADDRESS()) { if (rhs.match_expr_) { match_expr_.reset(new Expression()); *match_expr_ = *(rhs.match_expr_); } if (rhs.cfg_option_def_) { rhs.cfg_option_def_->copyTo(*cfg_option_def_); } if (rhs.cfg_option_) { rhs.cfg_option_->copyTo(*cfg_option_); } required_ = rhs.required_; depend_on_known_ = rhs.depend_on_known_; next_server_ = rhs.next_server_; sname_ = rhs.sname_; filename_ = rhs.filename_; } ClientClassDef::~ClientClassDef() { } std::string ClientClassDef::getName() const { return (name_); } void ClientClassDef::setName(const std::string& name) { name_ = name; } const ExpressionPtr& ClientClassDef::getMatchExpr() const { return (match_expr_); } void ClientClassDef::setMatchExpr(const ExpressionPtr& match_expr) { match_expr_ = match_expr; } std::string ClientClassDef::getTest() const { return (test_); } void ClientClassDef::setTest(const std::string& test) { test_ = test; } bool ClientClassDef::getRequired() const { return (required_); } void ClientClassDef::setRequired(bool required) { required_ = required; } bool ClientClassDef::getDependOnKnown() const { return (depend_on_known_); } void ClientClassDef::setDependOnKnown(bool depend_on_known) { depend_on_known_ = depend_on_known; } const CfgOptionDefPtr& ClientClassDef::getCfgOptionDef() const { return (cfg_option_def_); } void ClientClassDef::setCfgOptionDef(const CfgOptionDefPtr& cfg_option_def) { cfg_option_def_ = cfg_option_def; } const CfgOptionPtr& ClientClassDef::getCfgOption() const { return (cfg_option_); } void ClientClassDef::setCfgOption(const CfgOptionPtr& cfg_option) { cfg_option_ = cfg_option; } bool ClientClassDef::dependOnClass(const std::string& name) const { return (isc::dhcp::dependOnClass(match_expr_, name)); } bool ClientClassDef::equals(const ClientClassDef& other) const { return ((name_ == other.name_) && ((!match_expr_ && !other.match_expr_) || (match_expr_ && other.match_expr_ && (*match_expr_ == *(other.match_expr_)))) && ((!cfg_option_ && !other.cfg_option_) || (cfg_option_ && other.cfg_option_ && (*cfg_option_ == *other.cfg_option_))) && ((!cfg_option_def_ && !other.cfg_option_def_) || (cfg_option_def_ && other.cfg_option_def_ && (*cfg_option_def_ == *other.cfg_option_def_))) && (required_ == other.required_) && (depend_on_known_ == other.depend_on_known_) && (next_server_ == other.next_server_) && (sname_ == other.sname_) && (filename_ == other.filename_)); } ElementPtr ClientClassDef:: toElement() const { uint16_t family = CfgMgr::instance().getFamily(); ElementPtr result = Element::createMap(); // Set user-context contextToElement(result); // Set name result->set("name", Element::create(name_)); // Set original match expression (empty string won't parse) if (!test_.empty()) { result->set("test", Element::create(test_)); } // Set only-if-required if (required_) { result->set("only-if-required", Element::create(required_)); } // Set option-def (used only by DHCPv4) if (cfg_option_def_ && (family == AF_INET)) { result->set("option-def", cfg_option_def_->toElement()); } // Set option-data result->set("option-data", cfg_option_->toElement()); if (family != AF_INET) { // Other parameters are DHCPv4 specific return (result); } // Set next-server result->set("next-server", Element::create(next_server_.toText())); // Set server-hostname result->set("server-hostname", Element::create(sname_)); // Set boot-file-name result->set("boot-file-name", Element::create(filename_)); return (result); } std::ostream& operator<<(std::ostream& os, const ClientClassDef& x) { os << "ClientClassDef:" << x.getName(); return (os); } //********** ClientClassDictionary ******************// ClientClassDictionary::ClientClassDictionary() : map_(new ClientClassDefMap()), list_(new ClientClassDefList()) { } ClientClassDictionary::ClientClassDictionary(const ClientClassDictionary& rhs) : map_(new ClientClassDefMap()), list_(new ClientClassDefList()) { BOOST_FOREACH(ClientClassDefPtr cclass, *(rhs.list_)) { ClientClassDefPtr copy(new ClientClassDef(*cclass)); addClass(copy); } } ClientClassDictionary::~ClientClassDictionary() { } void ClientClassDictionary::addClass(const std::string& name, const ExpressionPtr& match_expr, const std::string& test, bool required, bool depend_on_known, const CfgOptionPtr& cfg_option, CfgOptionDefPtr cfg_option_def, ConstElementPtr user_context, asiolink::IOAddress next_server, const std::string& sname, const std::string& filename) { ClientClassDefPtr cclass(new ClientClassDef(name, match_expr, cfg_option)); cclass->setTest(test); cclass->setRequired(required); cclass->setDependOnKnown(depend_on_known); cclass->setCfgOptionDef(cfg_option_def); cclass->setContext(user_context), cclass->setNextServer(next_server); cclass->setSname(sname); cclass->setFilename(filename); addClass(cclass); } void ClientClassDictionary::addClass(ClientClassDefPtr& class_def) { if (!class_def) { isc_throw(BadValue, "ClientClassDictionary::addClass " " - class definition cannot be null"); } if (findClass(class_def->getName())) { isc_throw(DuplicateClientClassDef, "Client Class: " << class_def->getName() << " has already been defined"); } list_->push_back(class_def); (*map_)[class_def->getName()] = class_def; } ClientClassDefPtr ClientClassDictionary::findClass(const std::string& name) const { ClientClassDefMap::iterator it = map_->find(name); if (it != map_->end()) { return (*it).second; } return(ClientClassDefPtr()); } void ClientClassDictionary::removeClass(const std::string& name) { for (ClientClassDefList::iterator this_class = list_->begin(); this_class != list_->end(); ++this_class) { if ((*this_class)->getName() == name) { list_->erase(this_class); break; } } map_->erase(name); } const ClientClassDefListPtr& ClientClassDictionary::getClasses() const { return (list_); } bool ClientClassDictionary::dependOnClass(const std::string& name, std::string& dependent_class) const { // Skip previous classes as they should not depend on name. bool found = false; for (ClientClassDefList::iterator this_class = list_->begin(); this_class != list_->end(); ++this_class) { if (found) { if ((*this_class)->dependOnClass(name)) { dependent_class = (*this_class)->getName(); return (true); } } else { if ((*this_class)->getName() == name) { found = true; } } } return (false); } bool ClientClassDictionary::equals(const ClientClassDictionary& other) const { if (list_->size() != other.list_->size()) { return (false); } ClientClassDefList::const_iterator this_class = list_->cbegin(); ClientClassDefList::const_iterator other_class = other.list_->cbegin(); while (this_class != list_->cend() && other_class != other.list_->cend()) { if (!*this_class || !*other_class || **this_class != **other_class) { return false; } ++this_class; ++other_class; } return (true); } ElementPtr ClientClassDictionary::toElement() const { ElementPtr result = Element::createList(); // Iterate on the map for (ClientClassDefList::const_iterator this_class = list_->begin(); this_class != list_->cend(); ++this_class) { result->add((*this_class)->toElement()); } return (result); } std::list<std::string> builtinNames = { // DROP is not in this list because it is special but not built-in. // In fact DROP is set from an expression as callouts can drop // directly the incoming packet. The expression must not depend on // KNOWN/UNKNOWN which are set far after the drop point. "ALL", "KNOWN", "UNKNOWN", "BOOTP" }; std::list<std::string> builtinPrefixes = { "VENDOR_CLASS_", "HA_", "AFTER_", "EXTERNAL_" }; bool isClientClassBuiltIn(const ClientClass& client_class) { for (std::list<std::string>::const_iterator bn = builtinNames.cbegin(); bn != builtinNames.cend(); ++bn) { if (client_class == *bn) { return true; } } for (std::list<std::string>::const_iterator bt = builtinPrefixes.cbegin(); bt != builtinPrefixes.cend(); ++bt) { if (client_class.size() <= bt->size()) { continue; } auto mis = std::mismatch(bt->cbegin(), bt->cend(), client_class.cbegin()); if (mis.first == bt->cend()) { return true; } } return false; } bool isClientClassDefined(ClientClassDictionaryPtr& class_dictionary, bool& depend_on_known, const ClientClass& client_class) { // First check built-in classes if (isClientClassBuiltIn(client_class)) { // Check direct dependency on [UN]KNOWN if ((client_class == "KNOWN") || (client_class == "UNKNOWN")) { depend_on_known = true; } return (true); } // Second check already defined, i.e. in the dictionary ClientClassDefPtr def = class_dictionary->findClass(client_class); if (def) { // Check indirect dependency on [UN]KNOWN if (def->getDependOnKnown()) { depend_on_known = true; } return (true); } // Not defined... return (false); } } // namespace isc::dhcp } // namespace isc
29.107843
82
0.623947
svenauhagen
ebb83be9b4f4f129f5275956a96bcaa9e416ebc4
2,720
hpp
C++
include/libtorrent/aux_/deferred_handler.hpp
projectxorg/libtorrent
449b39318796addaafc6e655c9affc88706b8aa7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
50
2016-01-26T15:42:58.000Z
2022-02-27T11:32:58.000Z
include/libtorrent/aux_/deferred_handler.hpp
projectxorg/libtorrent
449b39318796addaafc6e655c9affc88706b8aa7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2016-04-05T02:38:33.000Z
2017-06-01T20:16:29.000Z
include/libtorrent/aux_/deferred_handler.hpp
projectxorg/libtorrent
449b39318796addaafc6e655c9affc88706b8aa7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
53
2016-01-25T01:14:54.000Z
2022-03-13T10:20:36.000Z
/* Copyright (c) 2017, Arvid Norberg 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 author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEFERRED_HANDLER_HPP #define TORRENT_DEFERRED_HANDLER_HPP #include "libtorrent/assert.hpp" #include "libtorrent/io_service.hpp" namespace libtorrent { namespace aux { template <typename Handler> struct handler_wrapper { handler_wrapper(bool& in_flight, Handler&& h) : m_handler(std::move(h)) , m_in_flight(in_flight) {} template <typename... Args> void operator()(Args&&... a) { TORRENT_ASSERT(m_in_flight); m_in_flight = false; m_handler(std::forward<Args>(a)...); } // forward asio handler allocator to the underlying handler's friend void* asio_handler_allocate( std::size_t size, handler_wrapper<Handler>* h) { return asio_handler_allocate(size, &h->m_handler); } friend void asio_handler_deallocate( void* ptr, std::size_t size, handler_wrapper<Handler>* h) { asio_handler_deallocate(ptr, size, &h->m_handler); } private: Handler m_handler; bool& m_in_flight; }; struct deferred_handler { template <typename Handler> void post(io_service& ios, Handler&& h) { if (m_in_flight) return; m_in_flight = true; ios.post(handler_wrapper<Handler>(m_in_flight, std::forward<Handler>(h))); } private: bool m_in_flight = false; }; }} #endif
30.909091
78
0.766176
projectxorg
ebb8b68a37b50af44db4f0b268185c3f9781b188
842
cpp
C++
pix/Color.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
3
2019-04-20T10:16:36.000Z
2021-03-21T19:51:38.000Z
pix/Color.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
null
null
null
pix/Color.cpp
Andrewich/deadjustice
48bea56598e79a1a10866ad41aa3517bf7d7c724
[ "BSD-3-Clause" ]
2
2020-04-18T20:04:24.000Z
2021-09-19T05:07:41.000Z
#include "Color.h" #include "Colorf.h" #include <assert.h> #include "config.h" //----------------------------------------------------------------------------- namespace pix { inline static uint8_t convertColorFloatToByte( float src ) { float f = src; if ( f < 0.f ) f = 0.f; else if ( f > 1.f ) f = 1.f; int i = (int)( f*255.f + .5f ); if ( i < 0 ) i = 0; else if ( i > 255 ) i = 255; assert( i >= 0 && i < 256 ); return (uint8_t)i; } //----------------------------------------------------------------------------- Color::Color( const Colorf& source ) { setRed( convertColorFloatToByte(source.red()) ); setGreen( convertColorFloatToByte(source.green()) ); setBlue( convertColorFloatToByte(source.blue()) ); setAlpha( convertColorFloatToByte(source.alpha()) ); } } // pix
20.047619
80
0.472684
Andrewich
ebb8f703da9b516850c25d0045d70df9301eb9fb
596
cpp
C++
LeetCode/0003. Longest Substring Without Repeating Characters.cpp
null-kryptonian/ProblemSolving
e11daca211a45b72316d3aea7b373e97b81e986b
[ "MIT" ]
1
2021-09-15T19:08:17.000Z
2021-09-15T19:08:17.000Z
LeetCode/0003. Longest Substring Without Repeating Characters.cpp
superior-prog/ProblemSolving
bf56f6b12196ff02c34fe4d14db64f4e5f58b990
[ "MIT" ]
null
null
null
LeetCode/0003. Longest Substring Without Repeating Characters.cpp
superior-prog/ProblemSolving
bf56f6b12196ff02c34fe4d14db64f4e5f58b990
[ "MIT" ]
null
null
null
class Solution { public: int max(int a, int b) { if(a > b) return a; else return b; } int lengthOfLongestSubstring(string s) { if(s.length() == 0) return 0; set<char> set; int left = 0, right = 0, length = 0; while(right < s.length()) { if(set.find(s[right]) == set.end()){ set.insert(s[right]); right++; length = max(length, set.size()); } else { set.erase(s[left]); left++; } } return length; } };s
25.913043
49
0.421141
null-kryptonian
ebb9c905af47c4e3fd9c1e69f364d2108a856508
4,311
hpp
C++
modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/remquo.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/remquo.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/include/boost/simd/arithmetic/functions/generic/remquo.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REMQUO_HPP_INCLUDED #define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REMQUO_HPP_INCLUDED #include <boost/simd/arithmetic/functions/remquo.hpp> #include <boost/simd/include/functions/simd/round2even.hpp> #include <boost/simd/include/functions/simd/toint.hpp> #include <boost/simd/include/functions/simd/minus.hpp> #include <boost/simd/include/functions/simd/is_eqz.hpp> #include <boost/simd/include/functions/simd/divides.hpp> #include <boost/simd/include/functions/simd/is_invalid.hpp> #include <boost/simd/include/functions/simd/logical_or.hpp> #include <boost/simd/include/functions/simd/multiplies.hpp> #include <boost/simd/include/functions/simd/if_allbits_else.hpp> #include <boost/simd/sdk/config.hpp> #include <boost/dispatch/meta/as_integer.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/dispatch/attributes.hpp> namespace boost { namespace simd { namespace ext { BOOST_DISPATCH_IMPLEMENT_IF ( remquo_ , tag::cpu_ , (A0)(A1) , ( boost::is_same < typename dispatch::meta:: as_integer<A0,signed>::type , A1 > ) , (generic_< floating_<A0> >) (generic_< floating_<A0> >) (generic_< integer_<A1> > ) ) { typedef A0 result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1,A1& a3) const { result_type a2; boost::simd::remquo(a0, a1, a2, a3); return a2; } }; BOOST_DISPATCH_IMPLEMENT ( remquo_, tag::cpu_ , (A0) , (generic_< floating_<A0> >) (generic_< floating_<A0> >) ) { typedef typename dispatch::meta::as_integer<A0, signed>::type quo_t; typedef std::pair<A0,quo_t> result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1) const { A0 first; quo_t second; boost::simd::remquo( a0, a1, first, second ); return result_type(first, second); } }; BOOST_DISPATCH_IMPLEMENT_IF ( remquo_, tag::cpu_ , (A0)(A1) , ( boost::is_same < typename dispatch::meta:: as_integer<A0,signed>::type , A1 > ) , (generic_<floating_<A0> >) (generic_<floating_<A0> >) (generic_<floating_<A0> >) (generic_<integer_ <A1> >) ) { typedef void result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0, A0 const& a1,A0& a2, A1& a3) const { A0 const d = round2even(a0/a1); #if defined(BOOST_SIMD_NO_INVALIDS) a2 = if_allbits_else(is_eqz(a1), a0-d*a1); #else a2 = if_allbits_else(l_or(is_invalid(a0), is_eqz(a1)), a0-d*a1); #endif a3 = toint(d); } }; } } } #endif
40.28972
81
0.474136
psiha
ebba73b7af656c138d1b132edd1532a3d4521e9f
3,460
cpp
C++
tests/unit/app/ping.t.cpp
yoursunny/NDNph
58be392af444d6f1f19fd67f2d2a8c123b0e9076
[ "0BSD" ]
2
2020-03-06T02:07:21.000Z
2021-12-29T04:53:58.000Z
tests/unit/app/ping.t.cpp
yoursunny/NDNph
58be392af444d6f1f19fd67f2d2a8c123b0e9076
[ "0BSD" ]
null
null
null
tests/unit/app/ping.t.cpp
yoursunny/NDNph
58be392af444d6f1f19fd67f2d2a8c123b0e9076
[ "0BSD" ]
2
2020-02-26T20:31:07.000Z
2021-04-22T18:27:19.000Z
#include "ndnph/app/ping-client.hpp" #include "ndnph/app/ping-server.hpp" #include "ndnph/keychain/ec.hpp" #include "ndnph/keychain/null.hpp" #include "mock/bridge-fixture.hpp" #include "mock/mock-key.hpp" #include "mock/mock-transport.hpp" #include "test-common.hpp" namespace ndnph { namespace { TEST(Ping, Client) { g::NiceMock<MockTransport> transport; Face face(transport); StaticRegion<1024> region; PingClient client(Name::parse(region, "/ping"), face, 10); int nInterests = 0; EXPECT_CALL(transport, doSend) .Times(g::Between(5, 20)) .WillRepeatedly([&](std::vector<uint8_t> wire, uint64_t) { StaticRegion<1024> region; Interest interest = region.create<Interest>(); EXPECT_TRUE(Decoder(wire.data(), wire.size()).decode(interest)); EXPECT_EQ(interest.getName().size(), 2); EXPECT_FALSE(interest.getCanBePrefix()); EXPECT_TRUE(interest.getMustBeFresh()); ++nInterests; if (nInterests == 2) { Data data = region.create<Data>(); data.setName(interest.getName().getPrefix(-1)); data.setFreshnessPeriod(1); transport.receive(data.sign(NullKey::get())); } else if (nInterests == 4) { // no response } else { Data data = region.create<Data>(); data.setName(interest.getName()); data.setFreshnessPeriod(1); transport.receive(data.sign(NullKey::get())); } return true; }); for (int i = 0; i < 120; ++i) { face.loop(); port::Clock::sleep(1); } auto cnt = client.readCounters(); EXPECT_EQ(cnt.nTxInterests, nInterests); EXPECT_EQ(cnt.nRxData, cnt.nTxInterests - 2); } TEST(Ping, Server) { g::NiceMock<MockTransport> transport; Face face(transport); StaticRegion<1024> sRegion; EcPrivateKey pvt; EcPublicKey pub; ASSERT_TRUE(ec::generate(sRegion, Name::parse(sRegion, "/server"), pvt, pub)); PingServer server(Name::parse(sRegion, "/ping"), face, pvt); std::set<std::string> interestNames; std::set<std::string> dataNames; EXPECT_CALL(transport, doSend).Times(20).WillRepeatedly([&](std::vector<uint8_t> wire, uint64_t) { StaticRegion<1024> tRegion; Data data = tRegion.create<Data>(); EXPECT_TRUE(Decoder(wire.data(), wire.size()).decode(data)); EXPECT_TRUE(data.verify(pub)); std::string uri; boost::conversion::try_lexical_convert(data.getName(), uri); dataNames.insert(uri); EXPECT_THAT(dataNames, g::ElementsAreArray(interestNames)); return true; }); for (int i = 0; i < 20; ++i) { std::string uri = "/8=ping/8=" + std::to_string(i); interestNames.insert(uri); StaticRegion<1024> cRegion; Interest interest = cRegion.create<Interest>(); interest.setName(Name::parse(cRegion, uri.data())); interest.setMustBeFresh(true); transport.receive(interest); face.loop(); } EXPECT_THAT(dataNames, g::ElementsAreArray(interestNames)); } using PingEndToEndFixture = BridgeFixture; TEST_F(PingEndToEndFixture, EndToEnd) { StaticRegion<1024> region; PingServer serverA(Name::parse(region, "/ping"), faceA); PingClient clientB(Name::parse(region, "/ping"), faceB, 10); int i = 120; runInThreads([] {}, [&] { return --i >= 0; }); auto cnt = clientB.readCounters(); EXPECT_GE(cnt.nTxInterests, 5); EXPECT_LE(cnt.nTxInterests, 20); EXPECT_GE(cnt.nRxData, cnt.nTxInterests - 2); EXPECT_LE(cnt.nRxData, cnt.nTxInterests); } } // namespace } // namespace ndnph
29.322034
100
0.666474
yoursunny
ebbe3a0da76db2d6c2e4c61e9df51b8cc68913c6
7,879
cpp
C++
src/OccamComponent.cpp
MuhammadAbuBakar95/OCCAM
4ffec0043caa6003288520a42838a0226eb6cfa3
[ "BSD-3-Clause" ]
null
null
null
src/OccamComponent.cpp
MuhammadAbuBakar95/OCCAM
4ffec0043caa6003288520a42838a0226eb6cfa3
[ "BSD-3-Clause" ]
null
null
null
src/OccamComponent.cpp
MuhammadAbuBakar95/OCCAM
4ffec0043caa6003288520a42838a0226eb6cfa3
[ "BSD-3-Clause" ]
null
null
null
// // OCCAM // // Copyright (c) 2011-2016, SRI International // // 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 SRI International 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 "llvm/ADT/StringMap.h" #include "llvm/IR/User.h" #include "llvm/IR/InstVisitor.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Pass.h" //#include "llvm/IR/PassManager.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/raw_ostream.h" #include "PrevirtualizeInterfaces.h" #include <vector> #include <string> #include <fstream> using namespace llvm; static cl::opt<std::string> KeepExternalFile("Pkeep-external", cl::desc("<file> : list of function names to be whitelisted"), cl::init("")); namespace previrt { static inline GlobalValue::LinkageTypes localizeLinkage(GlobalValue::LinkageTypes l) { switch (l) { case GlobalValue::ExternalLinkage: return GlobalValue::InternalLinkage; case GlobalValue::ExternalWeakLinkage: return GlobalValue::WeakODRLinkage; case GlobalValue::AppendingLinkage: return GlobalValue::AppendingLinkage; case GlobalValue::CommonLinkage: // CommonLinkage is most similar to weak linkage // However, we mark it as internal linkage so that other // optimizations are applicable. //return GlobalValue::WeakODRLinkage; return GlobalValue::InternalLinkage; // TODO I'm not sure if all external definitions have an // appropriate internal counterpart default: errs() << "Got other linkage! " << l << "\n"; return l; } } /* * Remove all code from the given module that is not necessary to * implement the given interface. */ bool MinimizeComponent(Module& M, const ComponentInterface& I) { bool modified = false; int hidden = 0; int internalized = 0; /* errs() << "<interface>\n"; I.dump(); errs() << "</interface>\n"; */ std::set<std::string> keep_external; if (KeepExternalFile != "") { std::ifstream infile(KeepExternalFile); if (infile.is_open()) { std::string line; while (std::getline(infile, line)) { //errs() << "Adding " << line << " to the white list.\n"; keep_external.insert(line); } infile.close(); } else { errs() << "Warning: ignored whitelist because something failed.\n"; } } // Set all functions that are not in the interface to internal linkage only for (auto &f: M) { if (keep_external.count(f.getName())) { errs() << "Did not internalize " << f.getName() << " because it is whitelisted.\n"; continue; } if (!f.isDeclaration() && f.hasExternalLinkage() && I.calls.find(f.getName()) == I.calls.end() && I.references.find(f.getName()) == I.references.end()) { errs() << "Hiding '" << f.getName() << "'\n"; f.setLinkage(GlobalValue::InternalLinkage); hidden++; modified = true; } } // Set all initialized global variables that are not referenced in // the interface to "localized linkage" only for (auto &gv: M.globals()) { if (gv.hasName() && keep_external.count(gv.getName())) { errs() << "Did not internalize " << gv.getName() << " because it is whitelisted.\n"; continue; } if ((gv.hasExternalLinkage() || gv.hasCommonLinkage()) && gv.hasInitializer() && I.references.find(gv.getName()) == I.references.end()) { errs() << "internalizing '" << gv.getName() << "'\n"; gv.setLinkage(localizeLinkage(gv.getLinkage())); internalized++; modified = true; } } /* TODO: We want to do this, but libc has some problems... for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e; ++i) { if (i->hasExternalLinkage() && I.references.find(i->getName()) == I.references.end() && I.calls.find(i->getName()) == end) { errs() << "internalizing '" << i->getName() << "'\n"; i->setLinkage(localizeLinkage(i->getLinkage())); modified = true; } } */ // Perform global dead code elimination // TODO: To what extent should we do this here, versus // doing it elsewhere? legacy::PassManager cdeMgr; legacy::PassManager mcMgr; ModulePass* modulePassDCE = createGlobalDCEPass(); cdeMgr.add(modulePassDCE); //mfMgr.add(createMergeFunctionsPass()); ModulePass* constantMergePass = createConstantMergePass(); mcMgr.add(constantMergePass); bool moreToDo = true; unsigned int iters = 0; while (moreToDo && iters < 10000) { moreToDo = false; if (cdeMgr.run(M)) moreToDo = true; // (originally commented) if (mfMgr.run(M)) moreToDo = true; if (mcMgr.run(M)) moreToDo = true; modified = modified || moreToDo; ++iters; } if (moreToDo) { if (cdeMgr.run(M)) errs() << "GlobalDCE still had more to do\n"; //if (mfMgr.run(M)) errs() << "MergeFunctions still had more to do\n"; if (mcMgr.run(M)) errs() << "MergeConstants still had more to do\n"; } if (modified) { errs() << "Progress: hidden = " << hidden << " internalized " << internalized << "\n"; } return modified; } static cl::list<std::string> OccamComponentInput( "Poccam-input", cl::NotHidden, cl::desc( "specifies the interface to prune with respect to")); class OccamPass : public ModulePass { public: ComponentInterface interface; static char ID; public: OccamPass() : ModulePass(ID) { errs() << "OccamPass()\n"; for (cl::list<std::string>::const_iterator b = OccamComponentInput.begin(), e = OccamComponentInput.end(); b != e; ++b) { errs() << "Reading file '" << *b << "'..."; if (interface.readFromFile(*b)) { errs() << "success\n"; } else { errs() << "failed\n"; } } errs() << "Done reading.\n"; } virtual ~OccamPass() { } public: virtual bool runOnModule(Module& M) { errs() << "OccamPass::runOnModule: " << M.getModuleIdentifier() << "\n"; return MinimizeComponent(M, this->interface); } }; char OccamPass::ID; static RegisterPass<OccamPass> X("Poccam", "hide/eliminate all non-external dependencies", false, false); }
31.64257
92
0.642467
MuhammadAbuBakar95
ebbfad0796ffae5b6ca5cfef50b3b69190d2175d
474
cpp
C++
tests/src/simple_modifications_json/src/simple_modifications_json_test.cpp
egelwan/Karabiner-Elements
896439dd2130904275553282063dd7fe4852e1a8
[ "Unlicense" ]
2
2021-03-24T17:34:09.000Z
2021-07-01T12:16:54.000Z
tests/src/simple_modifications_json/src/simple_modifications_json_test.cpp
XXXalice/Karabiner-Elements
52f579cbf60251cf18915bd938eb4431360b763b
[ "Unlicense" ]
null
null
null
tests/src/simple_modifications_json/src/simple_modifications_json_test.cpp
XXXalice/Karabiner-Elements
52f579cbf60251cf18915bd938eb4431360b763b
[ "Unlicense" ]
null
null
null
#include <catch2/catch.hpp> #include "../../share/json_helper.hpp" #include "manipulator/types.hpp" #include <pqrs/json.hpp> TEST_CASE("simple_modifications.json") { auto json = krbn::unit_testing::json_helper::load_jsonc("../../../src/apps/PreferencesWindow/Resources/simple_modifications.json"); for (const auto& entry : json) { if (auto data = pqrs::json::find_object(entry, "data")) { krbn::manipulator::to_event_definition e(data->value()); } } }
31.6
133
0.694093
egelwan
ebc66fbe4477496f88babdff871bf18700c7e690
539
cc
C++
src/openvslam/data/bow_vocabulary.cc
soallak/openvslam
23d155918a89eb791cf98bc25e1758b6e44f4f85
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
src/openvslam/data/bow_vocabulary.cc
soallak/openvslam
23d155918a89eb791cf98bc25e1758b6e44f4f85
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
src/openvslam/data/bow_vocabulary.cc
soallak/openvslam
23d155918a89eb791cf98bc25e1758b6e44f4f85
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#include "openvslam/data/bow_vocabulary.h" namespace openvslam { namespace data { namespace bow_vocabulary_util { void compute_bow(data::bow_vocabulary* bow_vocab, const cv::Mat& descriptors, data::bow_vector& bow_vec, data::bow_feature_vector& bow_feat_vec) { #ifdef USE_DBOW2 bow_vocab->transform(util::converter::to_desc_vec(descriptors), bow_vec, bow_feat_vec, 4); #else bow_vocab->transform(descriptors, 4, bow_vec, bow_feat_vec); #endif } }; // namespace bow_vocabulary_util }; // namespace data }; // namespace openvslam
29.944444
146
0.7718
soallak
ebc78addb8dbf2038ce1d61b33f5b6652537fd82
14,499
cpp
C++
ZooidEngine/ResourceManagers/MeshManager.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
4
2019-05-31T22:55:49.000Z
2020-11-26T11:55:34.000Z
ZooidEngine/ResourceManagers/MeshManager.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
null
null
null
ZooidEngine/ResourceManagers/MeshManager.cpp
azon04/Z0-Engine
1a44781fb5308c11c3b63b954ad683a51e9ba271
[ "MIT" ]
1
2018-04-11T02:50:47.000Z
2018-04-11T02:50:47.000Z
#include "MeshManager.h" #include "BufferManager.h" #include "MaterialManager.h" #include "SkeletonManager.h" #include "Resources/Mesh.h" #include "Resources/Material.h" #include "FileSystem/FileReader.h" #include "FileSystem/DirectoryHelper.h" #include "Renderer/IRenderer.h" #include "Physics/Physics.h" #include "ZEGameContext.h" #define RETURN_SHAPE_IF(shapeType, s) \ if (StringFunc::Compare(s, #shapeType ) == 0) \ { \ return shapeType; \ } namespace ZE { IMPLEMENT_CLASS_1(MeshManager, ResourceManager) struct MeshSkinData { Float32 Position[3]; Float32 Normal[3]; Float32 TexCoord[2]; Int32 BoneIDs[4]; Float32 BoneWeights[4]; }; struct MeshSkinDataWithTangent { Float32 Position[3]; Float32 Normal[3]; Float32 TexCoord[2]; Int32 BoneIDs[4]; Float32 BoneWeights[4]; Float32 Tangent[3]; }; MeshManager* MeshManager::s_instance = nullptr; void MeshManager::Init() { Handle hMeshManager("Mesh Manager", sizeof(MeshManager)); s_instance = new(hMeshManager) MeshManager(); } void MeshManager::Destroy() { if(s_instance) s_instance->unloadResources(); delete s_instance; s_instance = nullptr; } ZE::MeshManager* MeshManager::GetInstance() { return s_instance; } PhysicsShape GetShapeFromString(const char* shapeName) { RETURN_SHAPE_IF(BOX, shapeName) RETURN_SHAPE_IF(SPHERE, shapeName) RETURN_SHAPE_IF(CAPSULE, shapeName) RETURN_SHAPE_IF(PLANE, shapeName) RETURN_SHAPE_IF(CONVEX_MESHES, shapeName) RETURN_SHAPE_IF(TRIANGLE_MESHES, shapeName) RETURN_SHAPE_IF(HEIGHT_FIELDS, shapeName) return PHYSICS_SHAPE_NONE; } void MeshManager::loadPhysicsBodySetup(FileReader* fileReader, Mesh* pMesh) { Handle hPhysicsBodySetup("Physics Body Setup", sizeof(PhysicsBodySetup)); PhysicsBodySetup* pPhysicsBodySetup = new(hPhysicsBodySetup) PhysicsBodySetup(); char tokenBuffer[64]; // Read physic data type : single/file/multi fileReader->readNextString(tokenBuffer); if (StringFunc::Compare(tokenBuffer, "single") == 0) { PhysicsBodyDesc bodyDesc; fileReader->readNextString(tokenBuffer); bodyDesc.ShapeType = GetShapeFromString(tokenBuffer); switch (bodyDesc.ShapeType) { case BOX: bodyDesc.HalfExtent.setX(fileReader->readNextFloat()); bodyDesc.HalfExtent.setY(fileReader->readNextFloat()); bodyDesc.HalfExtent.setZ(fileReader->readNextFloat()); break; case SPHERE: bodyDesc.Radius = fileReader->readNextFloat(); break; case CAPSULE: bodyDesc.Radius = fileReader->readNextFloat(); bodyDesc.HalfHeight = fileReader->readNextFloat(); break; case PLANE: break; case CONVEX_MESHES: // #TODO Read buffer break; case TRIANGLE_MESHES: // #TODO Read buffer break; case HEIGHT_FIELDS: // #TODO Read HeightField break; } // Mass expected fileReader->readNextString(tokenBuffer); if (StringFunc::Compare(tokenBuffer, "Mass") == 0) { pPhysicsBodySetup->Mass = fileReader->readNextFloat(); } pPhysicsBodySetup->m_bodies.push_back(bodyDesc); } else if (StringFunc::Compare(tokenBuffer, "multi") == 0) { // #TODO need to implement multi descriptor } else if (StringFunc::Compare(tokenBuffer, "file") == 0) { // #TODO need to implement file descriptor for this } pMesh->m_hPhysicsBodySetup = hPhysicsBodySetup; } ZE::ERenderTopologyEnum getTopologyByName(const char* stringType) { COMPARE_RETURN(stringType, TOPOLOGY_TRIANGLE_STRIP); COMPARE_RETURN(stringType, TOPOLOGY_POINT); COMPARE_RETURN(stringType, TOPOLOGY_LINE); COMPARE_RETURN(stringType, TOPOLOGY_LINE_STRIP); return TOPOLOGY_TRIANGLE; } void MeshManager::loadBuffers(FileReader* fileReader, Mesh* pMesh) { char buffer[256]; // READ VERTEX BUFFER fileReader->readNextString(buffer); int bufferLayoutType = getBufferLayoutByString(buffer); if (bufferLayoutType == -1) { ZEINFO("BufferManager: Can't find buffer layout type for %s", buffer); return; } Handle hVertexBufferData("Buffer Data", sizeof(BufferData)); BufferData* pVertexBuffer = new(hVertexBufferData) BufferData(VERTEX_BUFFER); pVertexBuffer->setBufferLayout(bufferLayoutType); int numVertex = fileReader->readNextInt(); Handle dataHandle; if (bufferLayoutType == BUFFER_LAYOUT_V3_N3_TC2_SKIN) { dataHandle = Handle("Data", sizeof(MeshSkinData) * numVertex); MeshSkinData* pData = new(dataHandle) MeshSkinData[numVertex]; Vector3 minVertex(999999.9f); Vector3 maxVertex(-999999.9f); Vector3 centerVertex(0.0f); for (int i = 0; i < numVertex; i++) { pData[i].Position[0] = fileReader->readNextFloat(); pData[i].Position[1] = fileReader->readNextFloat(); pData[i].Position[2] = fileReader->readNextFloat(); pData[i].Normal[0] = fileReader->readNextFloat(); pData[i].Normal[1] = fileReader->readNextFloat(); pData[i].Normal[2] = fileReader->readNextFloat(); pData[i].TexCoord[0] = fileReader->readNextFloat(); pData[i].TexCoord[1] = fileReader->readNextFloat(); pData[i].BoneIDs[0] = fileReader->readNextInt(); pData[i].BoneIDs[1] = fileReader->readNextInt(); pData[i].BoneIDs[2] = fileReader->readNextInt(); pData[i].BoneIDs[3] = fileReader->readNextInt(); pData[i].BoneWeights[0] = fileReader->readNextFloat(); pData[i].BoneWeights[1] = fileReader->readNextFloat(); pData[i].BoneWeights[2] = fileReader->readNextFloat(); pData[i].BoneWeights[3] = fileReader->readNextFloat(); if (minVertex.m_x > pData[i].Position[0]) { minVertex.m_x = pData[i].Position[0]; } if (minVertex.m_y > pData[i].Position[1]) { minVertex.m_y = pData[i].Position[1]; } if (minVertex.m_z > pData[i].Position[2]) { minVertex.m_z = pData[i].Position[2]; } if (maxVertex.m_x < pData[i].Position[0]) { maxVertex.m_x = pData[i].Position[0]; } if (maxVertex.m_y < pData[i].Position[1]) { maxVertex.m_y = pData[i].Position[1]; } if (maxVertex.m_z < pData[i].Position[2]) { maxVertex.m_z = pData[i].Position[2]; } centerVertex = centerVertex + Vector3(pData[i].Position); } centerVertex = (minVertex + maxVertex) * 0.5f; pMesh->m_boxMin = minVertex; pMesh->m_boxMax = maxVertex; pMesh->m_centerOffset = centerVertex; Vector3 centerToMax = maxVertex - centerVertex; pMesh->m_radius = centerToMax.length(); pVertexBuffer->SetData(pData, sizeof(MeshSkinData), numVertex); } else if (bufferLayoutType == BUFFER_LAYOUT_V3_N3_T3_TC2_SKIN) { dataHandle = Handle("Data", sizeof(MeshSkinDataWithTangent) * numVertex); MeshSkinDataWithTangent* pData = new(dataHandle) MeshSkinDataWithTangent[numVertex]; Vector3 minVertex(9999.9f); Vector3 maxVertex(-9999.9f); Vector3 centerVertex(0.0f); for (int i = 0; i < numVertex; i++) { pData[i].Position[0] = fileReader->readNextFloat(); pData[i].Position[1] = fileReader->readNextFloat(); pData[i].Position[2] = fileReader->readNextFloat(); pData[i].Normal[0] = fileReader->readNextFloat(); pData[i].Normal[1] = fileReader->readNextFloat(); pData[i].Normal[2] = fileReader->readNextFloat(); pData[i].TexCoord[0] = fileReader->readNextFloat(); pData[i].TexCoord[1] = fileReader->readNextFloat(); pData[i].Tangent[0] = fileReader->readNextFloat(); pData[i].Tangent[1] = fileReader->readNextFloat(); pData[i].Tangent[2] = fileReader->readNextFloat(); pData[i].BoneIDs[0] = fileReader->readNextInt(); pData[i].BoneIDs[1] = fileReader->readNextInt(); pData[i].BoneIDs[2] = fileReader->readNextInt(); pData[i].BoneIDs[3] = fileReader->readNextInt(); pData[i].BoneWeights[0] = fileReader->readNextFloat(); pData[i].BoneWeights[1] = fileReader->readNextFloat(); pData[i].BoneWeights[2] = fileReader->readNextFloat(); pData[i].BoneWeights[3] = fileReader->readNextFloat(); if (minVertex.m_x > pData[i].Position[0]) { minVertex.m_x = pData[i].Position[0]; } if (minVertex.m_y > pData[i].Position[1]) { minVertex.m_y = pData[i].Position[1]; } if (minVertex.m_z > pData[i].Position[2]) { minVertex.m_z = pData[i].Position[2]; } if (maxVertex.m_x < pData[i].Position[0]) { maxVertex.m_x = pData[i].Position[0]; } if (maxVertex.m_y < pData[i].Position[1]) { maxVertex.m_y = pData[i].Position[1]; } if (maxVertex.m_z < pData[i].Position[2]) { maxVertex.m_z = pData[i].Position[2]; } } centerVertex = (minVertex + maxVertex) * 0.5f; pMesh->m_boxMin = minVertex; pMesh->m_boxMax = maxVertex; pMesh->m_centerOffset = centerVertex; Vector3 centerToMax = maxVertex - centerVertex; pMesh->m_radius = centerToMax.length(); pVertexBuffer->SetData(pData, sizeof(MeshSkinDataWithTangent), numVertex); } else { int dataPerVertex = 6; switch (bufferLayoutType) { case BUFFER_LAYOUT_V3_C3: dataPerVertex = 6; break; case BUFFER_LAYOUT_V3_N3_TC2: dataPerVertex = 8; break; case BUFFER_LAYOUT_V3_N3_T3_TC2: dataPerVertex = 11; break; case BUFFER_LAYOUT_V3_N3_TC2_SKIN: dataPerVertex = 16; break; default: break; } int totalSize = dataPerVertex * numVertex; dataHandle = Handle("Data", sizeof(Float32) * totalSize); Float32* pData = new(dataHandle) Float32[totalSize]; Vector3 minVertex(999999.9f); Vector3 maxVertex(-999999.9f); Vector3 centerVertex(0.0f); for (int i = 0; i < totalSize; ++i) { pData[i] = fileReader->readNextFloat(); if (i % dataPerVertex == 0) { if (minVertex.m_x > pData[i]) { minVertex.m_x = pData[i]; } if (maxVertex.m_x < pData[i]) { maxVertex.m_x = pData[i]; } } else if (i % dataPerVertex == 1) { if (minVertex.m_y > pData[i]) { minVertex.m_y = pData[i]; } if (maxVertex.m_y < pData[i]) { maxVertex.m_y = pData[i]; } } else if (i % dataPerVertex == 2) { if (minVertex.m_z > pData[i]) { minVertex.m_z = pData[i]; } if (maxVertex.m_z < pData[i]) { maxVertex.m_z = pData[i]; } } } centerVertex = (minVertex + maxVertex) * 0.5f; pMesh->m_boxMin = minVertex; pMesh->m_boxMax = maxVertex; pMesh->m_centerOffset = centerVertex; Vector3 centerToMax = maxVertex - centerVertex; pMesh->m_radius = centerToMax.length(); pVertexBuffer->SetData(pData, sizeof(Float32) * dataPerVertex, numVertex); } // READ OPTIONAL INDEX BUFFER Handle hIndexBufferData("Buffer Data", sizeof(BufferData)); BufferData* pIndexBuffer = nullptr; Handle indexDataHandle; fileReader->readNextString(buffer); if (StringFunc::Compare(buffer, "INDICE_BUFFER_NONE") != 0) { int numIndex = fileReader->readNextInt(); indexDataHandle = Handle("Data", sizeof(Int32) * numIndex); UInt32* indexData = new(indexDataHandle) UInt32[numIndex]; for (int i = 0; i < numIndex; ++i) { indexData[i] = fileReader->readNextInt(); } pIndexBuffer = new(hIndexBufferData) BufferData(INDEX_BUFFER); pIndexBuffer->SetData(indexData, sizeof(UInt32), numIndex); } ScopedRenderThreadOwnership renderLock(gGameContext->getRenderer()); Handle hResult = BufferManager::getInstance()->createBufferArray(pVertexBuffer, pIndexBuffer, nullptr); if (hVertexBufferData.isValid()) { hVertexBufferData.release(); dataHandle.release(); } if (hIndexBufferData.isValid()) { hIndexBufferData.release(); indexDataHandle.release(); } pMesh->m_bufferArray = hResult.getObject<IGPUBufferArray>(); fileReader->readNextString(buffer); if (StringFunc::Compare(buffer, "TOPOLOGY") == 0) { fileReader->readNextString(buffer); if (pMesh->m_bufferArray) { pMesh->m_bufferArray->setRenderTopology(getTopologyByName(buffer)); } } fileReader->close(); } int MeshManager::getBufferLayoutByString(const char* stringType) { COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_C3); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_TC2); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_TC2_SKIN); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_TC2); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_TC2_SKIN); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_B3_TC2); COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_B3_TC2_SKIN); return -1; } ZE::Handle MeshManager::loadResource_Internal(const char* resourceFilePath, ResourceCreateSettings* settings) { Handle meshHandle("Mesh Handle", sizeof(Mesh)); Mesh* pMesh; FileReader reader(resourceFilePath); if (!reader.isValid()) { ZEWARNING("Mesh file not found : %s", resourceFilePath); return meshHandle; } char tokenBuffer[256]; pMesh = new(meshHandle) Mesh(); while (!reader.eof()) { reader.readNextString(tokenBuffer); if (StringFunc::Compare(tokenBuffer, "vbuff") == 0) { reader.readNextString(tokenBuffer); String path = GetResourcePath(tokenBuffer); FileReader bufferFileReader(path.c_str()); if (!bufferFileReader.isValid()) { ZEINFO("BufferManager: File %s not find", path.c_str()); return Handle(); } loadBuffers(&bufferFileReader, pMesh); } else if (StringFunc::Compare(tokenBuffer, "mat") == 0) { reader.readNextString(tokenBuffer); Handle hMaterial = MaterialManager::GetInstance()->loadResource(GetResourcePath(tokenBuffer).c_str()); if (hMaterial.isValid()) { pMesh->m_material = hMaterial.getObject<Material>(); } } else if (StringFunc::Compare(tokenBuffer, "double_side") == 0) { pMesh->m_doubleSided = true; } else if (StringFunc::Compare(tokenBuffer, "physics") == 0) { loadPhysicsBodySetup(&reader, pMesh); } else if (StringFunc::Compare(tokenBuffer, "skeleton") == 0) { reader.readNextString(tokenBuffer); Handle hSkeleton = SkeletonManager::GetInstance()->loadResource(GetResourcePath(tokenBuffer).c_str()); if (hSkeleton.isValid()) { pMesh->m_hSkeleton = hSkeleton; } } } reader.close(); return meshHandle; } void MeshManager::preUnloadResource(Resource* _resource) { Mesh* pMesh = _resource->m_hActual.getObject<Mesh>(); if (pMesh) { if (pMesh->m_hPhysicsBodySetup.isValid()) { pMesh->m_hPhysicsBodySetup.release(); } if (pMesh->m_bufferArray) { pMesh->m_bufferArray->release(); } } } }
26.313975
110
0.682254
azon04
ebc7ebe677453a33460d0d33c349895dbe0871ca
5,036
hpp
C++
components/scream/src/share/util/scream_std_meta.hpp
AaronDonahue/scream
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
null
null
null
components/scream/src/share/util/scream_std_meta.hpp
AaronDonahue/scream
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
3
2019-04-25T18:18:33.000Z
2019-05-07T16:43:36.000Z
components/scream/src/share/util/scream_std_meta.hpp
AaronDonahue/scream
a1e1cc67ac6db87ce6525315a5548d0e7b0f5e97
[ "zlib-acknowledgement", "FTL", "RSA-MD" ]
null
null
null
#ifndef SCREAM_STD_META_HPP #define SCREAM_STD_META_HPP /* * Emulating c++1z features * * This file contains some features that belongs to the std namespace, * and that are likely (if not already scheduled) to be in future standards. * However, we have limited access to c++1z standard on target platforms, * so we can only rely on c++11 features. Everything else that we may need, * we try to emulate here. */ #include <memory> #include "share/scream_assert.hpp" namespace scream { namespace util { // =============== type_traits utils ============== // // <type_traits> has remove_all_extents but lacks the analogous // remove_all_pointers template<typename T> struct remove_all_pointers { using type = T; }; template<typename T> struct remove_all_pointers<T*> { using type = typename remove_all_pointers<T>::type; }; // std::remove_const does not remove the leading const cv from // the type <const T*>. Indeed, remove_const can only remove the // const cv from the pointer, not the pointee. template<typename T> struct remove_all_consts : std::remove_const<T> {}; template<typename T> struct remove_all_consts<T*> { using type = typename remove_all_consts<T>::type*; }; // ================ std::any ================= // namespace impl { class holder_base { public: virtual ~holder_base() = default; virtual const std::type_info& type () const = 0; }; template <typename HeldType> class holder : public holder_base { public: template<typename... Args> static holder<HeldType>* create(const Args&... args) { holder* ptr = new holder<HeldType>(); ptr->m_value = std::make_shared<HeldType>(args...); return ptr; } template<typename T> static typename std::enable_if<std::is_base_of<HeldType,T>::value,holder<HeldType>*>::type create(std::shared_ptr<T> ptr_in) { holder* ptr = new holder<HeldType>(); ptr->m_value = ptr_in; return ptr; } const std::type_info& type () const { return typeid(HeldType); } HeldType& value () { return *m_value; } std::shared_ptr<HeldType> ptr () const { return m_value; } private: holder () = default; // Note: we store a shared_ptr rather than a HeldType directly, // since we may store multiple copies of the concrete object. // Since we don't know if the actual object is copiable, we need // to store copiable pointers (hence, cannot use unique_ptr). std::shared_ptr<HeldType> m_value; }; } // namespace impl class any { public: any () = default; template<typename T, typename... Args> void reset (Args... args) { m_content.reset( impl::holder<T>::create(args...) ); } impl::holder_base& content () const { error::runtime_check(static_cast<bool>(m_content), "Error! Object not yet initialized.\n", -1); return *m_content; } impl::holder_base* content_ptr () const { return m_content.get(); } private: std::shared_ptr<impl::holder_base> m_content; }; template<typename ConcreteType> bool any_is_type (const any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); return src_type==req_type; } template<typename ConcreteType> ConcreteType& any_cast (any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1); impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr()); error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1); return ptr->value(); } template<typename ConcreteType> const ConcreteType& any_cast (const any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1); impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr()); error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1); return ptr->value(); } template<typename ConcreteType> std::shared_ptr<ConcreteType> any_ptr_cast (any& src) { const auto& src_type = src.content().type(); const auto& req_type = typeid(ConcreteType); error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1); impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr()); error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1); return ptr->ptr(); } } // namespace util } // namespace scream #endif // SCREAM_STD_META_HPP
29.109827
157
0.691422
AaronDonahue
1b0b49e5a32b03a5dbbc1dc4786f26ec12ffe853
4,133
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Editor/IntroTutorials/Private/EditorTutorial.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Editor/IntroTutorials/Private/EditorTutorial.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Editor/IntroTutorials/Private/EditorTutorial.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "IntroTutorialsPrivatePCH.h" #include "LevelEditor.h" #include "SDockTab.h" #include "EditorTutorial.h" #if WITH_EDITORONLY_DATA namespace { void GatherEditorTutorialForLocalization(const UObject* const Object, FPropertyLocalizationDataGatherer& PropertyLocalizationDataGatherer, const EPropertyLocalizationGathererTextFlags GatherTextFlags) { const UEditorTutorial* const EditorTutorial = CastChecked<UEditorTutorial>(Object); // Editor Tutorial assets never exist at runtime, so treat all of their properties and script data as editor-only (as they may be derived from by a blueprint) PropertyLocalizationDataGatherer.GatherLocalizationDataFromObject(EditorTutorial, GatherTextFlags | EPropertyLocalizationGathererTextFlags::ForceEditorOnly); } } #endif UEditorTutorial::UEditorTutorial(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { #if WITH_EDITORONLY_DATA static struct FAutomaticRegistrationOfLocalizationGatherer { FAutomaticRegistrationOfLocalizationGatherer() { FPropertyLocalizationDataGatherer::GetTypeSpecificLocalizationDataGatheringCallbacks().Add(UEditorTutorial::StaticClass(), &GatherEditorTutorialForLocalization); } } AutomaticRegistrationOfLocalizationGatherer; #endif } UWorld* UEditorTutorial::GetWorld() const { #if WITH_EDITOR if (GIsEditor) { return GWorld; } #endif // WITH_EDITOR return GEngine->GetWorldContexts()[0].World(); } void UEditorTutorial::GoToNextTutorialStage() { FIntroTutorials& IntroTutorials = FModuleManager::GetModuleChecked<FIntroTutorials>(TEXT("IntroTutorials")); IntroTutorials.GoToNextStage(nullptr); } void UEditorTutorial::GoToPreviousTutorialStage() { FIntroTutorials& IntroTutorials = FModuleManager::GetModuleChecked<FIntroTutorials>(TEXT("IntroTutorials")); IntroTutorials.GoToPreviousStage(); } void UEditorTutorial::BeginTutorial(UEditorTutorial* TutorialToStart, bool bRestart) { FIntroTutorials& IntroTutorials = FModuleManager::GetModuleChecked<FIntroTutorials>(TEXT("IntroTutorials")); IntroTutorials.LaunchTutorial(TutorialToStart, bRestart ? IIntroTutorials::ETutorialStartType::TST_RESTART : IIntroTutorials::ETutorialStartType::TST_CONTINUE); } void UEditorTutorial::HandleTutorialStageStarted(FName StageName) { FEditorScriptExecutionGuard ScriptGuard; OnTutorialStageStarted(StageName); } void UEditorTutorial::HandleTutorialStageEnded(FName StageName) { FEditorScriptExecutionGuard ScriptGuard; OnTutorialStageEnded(StageName); } void UEditorTutorial::HandleTutorialLaunched() { FEditorScriptExecutionGuard ScriptGuard; FLevelEditorModule& LevelEditorModule = FModuleManager::GetModuleChecked<FLevelEditorModule>(TEXT("LevelEditor")); LevelEditorModule.GetLevelEditorTabManager()->InvokeTab(FTabId("TutorialsBrowser"))->RequestCloseTab(); OnTutorialLaunched(); } void UEditorTutorial::HandleTutorialClosed() { FEditorScriptExecutionGuard ScriptGuard; OnTutorialClosed(); } void UEditorTutorial::OpenAsset(UObject* Asset) { FAssetEditorManager::Get().OpenEditorForAsset(Asset); } AActor* UEditorTutorial::GetActorReference(FString PathToActor) { #if WITH_EDITOR return Cast<AActor>(StaticFindObject(AActor::StaticClass(), GEditor->GetEditorWorldContext().World(), *PathToActor, false)); #else return nullptr; #endif //WITH_EDITOR } void UEditorTutorial::SetEngineFolderVisibilty(bool bNewVisibility) { bool bDisplayEngine = GetDefault<UContentBrowserSettings>()->GetDisplayEngineFolder(); // If we cannot change the vis state, or it matches the new request leave it if (bDisplayEngine == bNewVisibility) { return; } if (bNewVisibility) { GetMutableDefault<UContentBrowserSettings>()->SetDisplayEngineFolder(true); } else { GetMutableDefault<UContentBrowserSettings>()->SetDisplayEngineFolder(false); GetMutableDefault<UContentBrowserSettings>()->SetDisplayEngineFolder(false, true); } GetMutableDefault<UContentBrowserSettings>()->PostEditChange(); } bool UEditorTutorial::GetEngineFolderVisibilty() { return GetDefault<UContentBrowserSettings>()->GetDisplayEngineFolder(); }
30.614815
201
0.819744
armroyce
1b0e95d2748790bdffc792425db167c8f505d6c4
11,094
cpp
C++
logdevice/lib/test/copyloadtestapp/client/CopyLoadTestClient.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
1
2018-10-17T06:49:04.000Z
2018-10-17T06:49:04.000Z
logdevice/lib/test/copyloadtestapp/client/CopyLoadTestClient.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
null
null
null
logdevice/lib/test/copyloadtestapp/client/CopyLoadTestClient.cpp
msdgwzhy6/LogDevice
bc2491b7dfcd129e25490c7d5321d3d701f53ac4
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <cstdlib> #include <memory> #include <random> #include <unistd.h> #include <folly/Memory.h> #include <folly/Singleton.h> #include <folly/io/async/EventBase.h> #include <thrift/lib/cpp/async/TAsyncSocket.h> #include <thrift/lib/cpp2/async/HeaderClientChannel.h> #include "common/init/Init.h" #include "logdevice/lib/test/copyloadtestapp/server/gen-cpp2/CopyLoaderTest.h" #include "logdevice/common/Checksum.h" #include "logdevice/common/commandline_util.h" #include "logdevice/common/commandline_util_chrono.h" #include "logdevice/common/debug.h" #include "logdevice/common/EpochMetaData.h" #include "logdevice/common/Timer.h" #include "logdevice/common/ReaderImpl.h" #include "logdevice/common/Semaphore.h" #include "logdevice/common/util.h" #include "logdevice/include/Client.h" #include "logdevice/include/Err.h" #include "logdevice/include/Record.h" #include "logdevice/include/types.h" #include "logdevice/lib/ClientSettingsImpl.h" using namespace facebook; using namespace facebook::logdevice; using apache::thrift::HeaderClientChannel; using apache::thrift::async::TAsyncSocket; using folly::EventBase; using std::make_unique; using std::chrono::steady_clock; struct CommandLineSettings { bool no_payload; size_t total_buffer_size = 2000000; std::chrono::milliseconds findtime_timeout{10000}; std::chrono::milliseconds confirmation_duration{60 * 1000}; boost::program_options::options_description desc; std::string config_path; std::string host_ip; uint32_t num_threads; uint32_t port; uint32_t task_index; }; void parse_command_line(int argc, const char* argv[], CommandLineSettings& command_line_settings, ClientSettingsImpl& client_settings) { using boost::program_options::bool_switch; using boost::program_options::value; // clang-format off command_line_settings.desc.add_options() ("help,h", "produce this help message and exit") ("verbose,v", "also include a description of all LogDevice Client settings in the help " "message") ("config-path", value<std::string>(&command_line_settings.config_path) ->required(), "path to config file") ("port", value<uint32_t>(&command_line_settings.port) ->default_value(1739), "Port for thrift service") ("task-index", value<uint32_t>(&command_line_settings.task_index) ->default_value(0), "tupperware task index used for process identication") ("server-address", value<std::string>(&command_line_settings.host_ip) ->default_value("127.0.0.1"), "host server ip address. Default is 127.0.0.1") ("threads-number", value<uint32_t>(&command_line_settings.num_threads) ->default_value(10), "number of threads that are going to execute tasks independently") ("no-payload", bool_switch(&command_line_settings.no_payload) ->default_value(false), "request storage servers send records without paylaod") ("buffer-size", value<size_t>(&command_line_settings.total_buffer_size) ->default_value(command_line_settings.total_buffer_size), "client read buffer size for all logs") ("loglevel", value<std::string>() ->default_value("info") ->notifier(dbg::parseLoglevelOption), "One of the following: critical, error, warning, info, debug") ("findtime-timeout", chrono_value(&command_line_settings.findtime_timeout) ->notifier([](std::chrono::milliseconds val) -> void { if (val.count() < 0) { throw boost::program_options::error("findtime-timeout must be > 0"); } }), "Timeout for calls to findTime") ; // clang-format on try { auto fallback_fn = [&](int ac, const char* av[]) { boost::program_options::variables_map parsed = program_options_parse_no_positional( ac, av, command_line_settings.desc); // Check for --help before calling notify(), so that required options // aren't required. if (parsed.count("help")) { std::cout << "Test application that connects to LogDevice and reads logs.\n\n" << command_line_settings.desc; if (parsed.count("verbose")) { std::cout << std::endl; std::cout << "LogDevice Client settings:" << std::endl << std::endl; std::cout << client_settings.getSettingsUpdater()->help( SettingFlag::CLIENT); } exit(0); } // Surface any errors boost::program_options::notify(parsed); }; client_settings.getSettingsUpdater()->parseFromCLI( argc, argv, &SettingsUpdater::mustBeClientOption, fallback_fn); } catch (const boost::program_options::error& ex) { std::cerr << argv[0] << ": " << ex.what() << '\n'; exit(1); } } void client_thread(CommandLineSettings command_line_settings, const ClientSettingsImpl& client_settings, int thread_id) { EventBase eventBase; uint64_t client_id = (uint64_t(command_line_settings.task_index) << 32) | uint64_t(thread_id); try { // Create a client to the service auto socket = TAsyncSocket::newSocket( &eventBase, command_line_settings.host_ip, command_line_settings.port); auto channel = HeaderClientChannel::newChannel(socket); auto thrift_client = make_unique<thrift::CopyLoaderTestAsyncClient>(std::move(channel)); auto local_client_settings = std::make_unique<ClientSettingsImpl>(client_settings); std::shared_ptr<Client> logdevice_client = Client::create("Test cluster", command_line_settings.config_path, "none", command_line_settings.findtime_timeout, std::move(local_client_settings)); if (!logdevice_client) { ld_error("Could not create client: %s", error_description(err)); return; } // Reader will read one log at one range at once. // stopReading() will be invoced after end of each reading. auto reader = logdevice_client->createReader(1); reader->waitOnlyWhenNoData(); reader->setTimeout(std::chrono::seconds(1)); unsigned long wait_time = 100; std::default_random_engine generator; std::string process_info; process_info.append("Tupperware task id: ") .append(std::to_string(command_line_settings.task_index)) .append(". Thread id: ") .append(std::to_string(thread_id)); while (1) { // Get a tasks std::vector<thrift::Task> tasks; while (true) { thrift_client->sync_getTask(tasks, client_id, process_info); if (tasks.size() != 0) { wait_time = 1000; break; } else { // radnomize wait time std::uniform_int_distribution<int> distribution( wait_time / 2 * 3, wait_time * 3); wait_time = std::min(distribution(generator), 60 * 1000); LOG(INFO) << "Thread " << thread_id << " is about to sleep " << wait_time << "ms."; std::this_thread::sleep_for(std::chrono::milliseconds(wait_time)); } } for (int i = 0; i < tasks.size(); ++i) { lsn_t lsn_start = compose_lsn(epoch_t(tasks[i].start_lsn.lsn_hi), esn_t(tasks[i].start_lsn.lsn_lo)); lsn_t lsn_end = compose_lsn( epoch_t(tasks[i].end_lsn.lsn_hi), esn_t(tasks[i].end_lsn.lsn_lo)); LOG(INFO) << "Task id: " << tasks[i].id << " thread id: " << thread_id << " lsn: " << lsn_start << " - " << lsn_end << "start procesing."; auto ret = reader->startReading((logid_t)tasks[i].log_id, lsn_start, lsn_end); ld_check(ret == 0); auto time_begin = std::chrono::steady_clock::now(); auto last_time_confirmed = time_begin; std::vector<std::unique_ptr<DataRecord>> records; GapRecord gap; size_t all_records_size = 0; size_t all_records_count = 0; bool is_confirmed = true; while (reader->isReading((logid_t)tasks[i].log_id)) { records.clear(); int nread = reader->read(100, &records, &gap); all_records_size += std::accumulate( std::begin(records), std::end(records), std::size_t(0), [](size_t& sum, std::unique_ptr<DataRecord>& record) { return sum + record->payload.size(); }); all_records_count += records.size(); auto cur_time = std::chrono::steady_clock::now(); auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( cur_time - last_time_confirmed); if (time_elapsed > command_line_settings.confirmation_duration) { bool rv = thrift_client->sync_confirmOngoingTaskExecution( tasks[i].id, client_id); if (!rv) { is_confirmed = false; break; } last_time_confirmed = cur_time; } } if (!is_confirmed) { continue; } auto time_all = std::chrono::steady_clock::now() - time_begin; double time_elapsed_sec = double( std::chrono::duration_cast<std::chrono::milliseconds>(time_all) .count()) / 1000; char buf[128]; snprintf(buf, sizeof buf, "%.3f", time_elapsed_sec); std::string logging_info; logging_info.append(process_info) .append(". Records size read: ") .append(std::to_string(all_records_count)) .append(". Data loaded: ") .append(std::to_string(all_records_size)) .append(". Time spent to read in seconds: ") .append(buf); thrift_client->sync_informTaskFinished( tasks[i].id, client_id, logging_info, all_records_size); } } } catch (apache::thrift::transport::TTransportException& ex) { LOG(ERROR) << "Request failed " << ex.what(); } } int main(int argc, const char* argv[]) { logdeviceInit(); ClientSettingsImpl client_settings; CommandLineSettings command_line_settings; parse_command_line(argc, argv, command_line_settings, client_settings); std::vector<std::thread> client_threads; for (int i = 0; i < command_line_settings.num_threads; ++i) { client_threads.emplace_back( client_thread, command_line_settings, std::ref(client_settings), i); } for (auto& client_thread : client_threads) { client_thread.join(); } // Don't use custom command line parameters in in initFacebook() // to prevent parsing errors argc = 0; initFacebook(&argc, const_cast<char***>(&argv)); return 0; }
34.560748
80
0.634127
msdgwzhy6
1b0ecd9d9b84ecee10157c72e9177550b3170fc2
1,200
hpp
C++
WinFelix/EncodingRenderer.hpp
42Bastian/Felix
3c0b31a245a7c73bae97ad39a378edcdde1e386d
[ "MIT" ]
19
2021-10-31T20:57:14.000Z
2022-03-22T11:48:56.000Z
WinFelix/EncodingRenderer.hpp
42Bastian/Felix
3c0b31a245a7c73bae97ad39a378edcdde1e386d
[ "MIT" ]
99
2021-10-29T20:31:09.000Z
2022-02-09T12:24:03.000Z
WinFelix/EncodingRenderer.hpp
42Bastian/Felix
3c0b31a245a7c73bae97ad39a378edcdde1e386d
[ "MIT" ]
3
2021-11-05T15:14:41.000Z
2021-12-11T14:16:11.000Z
#pragma once class IEncoder; class EncodingRenderer { public: EncodingRenderer( std::shared_ptr<IEncoder> encoder, ComPtr<ID3D11Device> pD3DDevice, ComPtr<ID3D11DeviceContext> pImmediateContext, boost::rational<int32_t> refreshRate ); void renderEncoding( ID3D11ShaderResourceView* srv ); private: std::shared_ptr<IEncoder> mEncoder; ComPtr<ID3D11Device> mD3DDevice; ComPtr<ID3D11DeviceContext> mImmediateContext; ComPtr<ID3D11Texture2D> mPreStagingY; ComPtr<ID3D11Texture2D> mPreStagingU; ComPtr<ID3D11Texture2D> mPreStagingV; ComPtr<ID3D11Texture2D> mStagingY; ComPtr<ID3D11Texture2D> mStagingU; ComPtr<ID3D11Texture2D> mStagingV; ComPtr<ID3D11UnorderedAccessView> mPreStagingYUAV; ComPtr<ID3D11UnorderedAccessView> mPreStagingUUAV; ComPtr<ID3D11UnorderedAccessView> mPreStagingVUAV; ComPtr<ID3D11Buffer> mVSizeCB; ComPtr<ID3D11ComputeShader> mRendererYUVCS; struct CBVSize { uint32_t vscale; uint32_t padding1; uint32_t padding2; uint32_t padding3; } mCb; boost::rational<int32_t> mRefreshRate; };
30.769231
175
0.706667
42Bastian
1b125aa56306752283b50e452d90206398929640
3,377
cc
C++
chrome/browser/enterprise/connectors/connectors_prefs.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/enterprise/connectors/connectors_prefs.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/enterprise/connectors/connectors_prefs.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <string> #include <vector> #include "chrome/browser/enterprise/connectors/connectors_prefs.h" #include "chrome/browser/enterprise/connectors/connectors_service.h" #include "chrome/browser/enterprise/connectors/file_system/account_info_utils.h" #include "chrome/browser/enterprise/connectors/service_provider_config.h" #include "components/prefs/pref_registry_simple.h" namespace enterprise_connectors { const char kSendDownloadToCloudPref[] = "enterprise_connectors.send_download_to_cloud"; const char kOnFileAttachedPref[] = "enterprise_connectors.on_file_attached"; const char kOnFileDownloadedPref[] = "enterprise_connectors.on_file_downloaded"; const char kOnBulkDataEntryPref[] = "enterprise_connectors.on_bulk_data_entry"; const char kOnSecurityEventPref[] = "enterprise_connectors.on_security_event"; const char kContextAwareAccessSignalsAllowlistPref[] = "enterprise_connectors.device_trust.origins"; const char kDeviceTrustPrivateKeyPref[] = "enterprise_connectors.device_trust.private_key"; const char kDeviceTrustPublicKeyPref[] = "enterprise_connectors.device_trust.public_key"; const char kOnFileAttachedScopePref[] = "enterprise_connectors.scope.on_file_attached"; const char kOnFileDownloadedScopePref[] = "enterprise_connectors.scope.on_file_downloaded"; const char kOnBulkDataEntryScopePref[] = "enterprise_connectors.scope.on_bulk_data_entry"; const char kOnSecurityEventScopePref[] = "enterprise_connectors.scope.on_security_event"; namespace { void RegisterFileSystemPrefs(PrefRegistrySimple* registry) { std::vector<std::string> all_service_providers = GetServiceProviderConfig()->GetServiceProviderNames(); std::vector<std::string> fs_service_providers; std::copy_if(all_service_providers.begin(), all_service_providers.end(), std::back_inserter(fs_service_providers), [](const auto& name) { const ServiceProviderConfig::ServiceProvider* provider = GetServiceProviderConfig()->GetServiceProvider(name); return !provider->fs_home_url().empty(); }); for (const auto& name : fs_service_providers) { RegisterFileSystemPrefsForServiceProvider(registry, name); } } } // namespace void RegisterProfilePrefs(PrefRegistrySimple* registry) { registry->RegisterListPref(kSendDownloadToCloudPref); registry->RegisterListPref(kOnFileAttachedPref); registry->RegisterListPref(kOnFileDownloadedPref); registry->RegisterListPref(kOnBulkDataEntryPref); registry->RegisterListPref(kOnSecurityEventPref); registry->RegisterIntegerPref(kOnFileAttachedScopePref, 0); registry->RegisterIntegerPref(kOnFileDownloadedScopePref, 0); registry->RegisterIntegerPref(kOnBulkDataEntryScopePref, 0); registry->RegisterIntegerPref(kOnSecurityEventScopePref, 0); registry->RegisterListPref(kContextAwareAccessSignalsAllowlistPref); RegisterFileSystemPrefs(registry); } void RegisterLocalPrefs(PrefRegistrySimple* registry) { registry->RegisterStringPref(kDeviceTrustPrivateKeyPref, std::string()); registry->RegisterStringPref(kDeviceTrustPublicKeyPref, std::string()); } } // namespace enterprise_connectors
39.267442
80
0.795084
zealoussnow
1b1384289e352902a898f4aac94bc8790edc804b
850
hpp
C++
game/code/common/engine/game/timetask.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/engine/game/timetask.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
null
null
null
game/code/common/engine/game/timetask.hpp
justinctlam/MarbleStrike
64fe36a5a4db2b299983b0e2556ab1cd8126259b
[ "MIT" ]
2
2019-03-08T03:02:45.000Z
2019-05-14T08:41:26.000Z
#ifndef TIME_TASK_HPP #define TIME_TASK_HPP ////////////////////////////////////////////////////// // INCLUDES ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // FORWARD DECLARATIONS ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// // CLASS ////////////////////////////////////////////////////// class TimeTask { public: TimeTask( float startTime, float endTime, void (*OnTrigger)( void* ), void* context ); ~TimeTask(); void Update( float elapsedTime ); float GetElapsedTimeSeconds(); float GetStartTimeSeconds(); float GetEndTimeSeconds(); void OnTrigger(); private: float mStartTimeSeconds; float mEndTimeSeconds; float mElapsedTimeSeconds; void (*OnTriggerCallback)( void* ); void* mContext; }; #endif
22.368421
87
0.452941
justinctlam
1b13f28f1279403494424d114386aa573c87d590
3,243
hpp
C++
hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.hpp
dbac/jdk8
abfce42ff6d4b8b77d622157519ecd211ba0aa8f
[ "MIT" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.hpp
dbac/jdk8
abfce42ff6d4b8b77d622157519ecd211ba0aa8f
[ "MIT" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.hpp
dbac/jdk8
abfce42ff6d4b8b77d622157519ecd211ba0aa8f
[ "MIT" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef CPU_SPARC_VM_C1_LIRASSEMBLER_SPARC_HPP #define CPU_SPARC_VM_C1_LIRASSEMBLER_SPARC_HPP private: ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Sparc load/store emission // // The sparc ld/st instructions cannot accomodate displacements > 13 bits long. // The following "pseudo" sparc instructions (load/store) make it easier to use the indexed addressing mode // by allowing 32 bit displacements: // // When disp <= 13 bits long, a single load or store instruction is emitted with (disp + [d]). // When disp > 13 bits long, code is emitted to set the displacement into the O7 register, // and then a load or store is emitted with ([O7] + [d]). // int store(LIR_Opr from_reg, Register base, int offset, BasicType type, bool wide, bool unaligned); int store(LIR_Opr from_reg, Register base, Register disp, BasicType type, bool wide); int load(Register base, int offset, LIR_Opr to_reg, BasicType type, bool wide, bool unaligned); int load(Register base, Register disp, LIR_Opr to_reg, BasicType type, bool wide); void monitorexit(LIR_Opr obj_opr, LIR_Opr lock_opr, Register hdr, int monitor_no); int shift_amount(BasicType t); static bool is_single_instruction(LIR_Op* op); // Record the type of the receiver in ReceiverTypeData void type_profile_helper(Register mdo, int mdo_offset_bias, ciMethodData *md, ciProfileData *data, Register recv, Register tmp1, Label* update_done); // Setup pointers to MDO, MDO slot, also compute offset bias to access the slot. void setup_md_access(ciMethod* method, int bci, ciMethodData*& md, ciProfileData*& data, int& mdo_offset_bias); public: void pack64(LIR_Opr src, LIR_Opr dst); void unpack64(LIR_Opr src, LIR_Opr dst); enum { #ifdef _LP64 call_stub_size = 68, #else call_stub_size = 20, #endif // _LP64 exception_handler_size = DEBUG_ONLY(1*K) NOT_DEBUG(128), deopt_handler_size = DEBUG_ONLY(1*K) NOT_DEBUG(64) }; #endif // CPU_SPARC_VM_C1_LIRASSEMBLER_SPARC_HPP
42.671053
124
0.691952
dbac
1b149f1db4bb7c19cb37799ea23ea87660e90c69
1,027
cpp
C++
GeeksForGeeks/Practice/GetMinimumElementFromStack.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
GeeksForGeeks/Practice/GetMinimumElementFromStack.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
GeeksForGeeks/Practice/GetMinimumElementFromStack.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
/* The structure of the class is as follows class _stack{ stack<int> s; int minEle; public : int getMin(); int pop(); void push(int); }; */ /*returns min element from stack*/ stack<int> st; int _stack :: getMin() { if(s.empty()){ while(!st.empty()){ st.pop(); } } //Your code here if(st.empty()){ return -1; } return st.top(); } /*returns poped element from stack*/ int _stack ::pop() { if(s.empty()){ while(!st.empty()){ st.pop(); } } //Your code here int ans = -1; if(!s.empty()){ ans = s.top(); s.pop(); st.pop(); } return ans; } /*push element x into the stack*/ void _stack::push(int x) { //Your code here if(s.empty()){ while(!st.empty()){ st.pop(); } s.push(x); st.push(x); return; } s.push(x); if(st.top() > x){ st.push(x); } else{ st.push(st.top()); } }
13.337662
40
0.447907
Ashwanigupta9125
1b17a79dbcbd4f9185be1bf7554e09d938888aea
6,191
cpp
C++
Compiler/AST/ASTExpr.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
1
2018-12-31T03:57:28.000Z
2018-12-31T03:57:28.000Z
Compiler/AST/ASTExpr.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
null
null
null
Compiler/AST/ASTExpr.cpp
rozaxe/emojicode
de62ef1871859429e569e4275c38c18bd43c5271
[ "Artistic-2.0" ]
1
2019-01-01T13:34:14.000Z
2019-01-01T13:34:14.000Z
// // ASTExpr.cpp // Emojicode // // Created by Theo Weidmann on 03/08/2017. // Copyright © 2017 Theo Weidmann. All rights reserved. // #include "ASTExpr.hpp" #include "Analysis/FunctionAnalyser.hpp" #include "Compiler.hpp" #include "Functions/Initializer.hpp" #include "MemoryFlowAnalysis/MFFunctionAnalyser.hpp" #include "Scoping/SemanticScoper.hpp" #include "Types/Class.hpp" #include "Types/Enum.hpp" #include "Types/TypeExpectation.hpp" namespace EmojicodeCompiler { void ASTUnaryMFForwarding::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { expr_->analyseMemoryFlow(analyser, type); } Type ASTTypeAsValue::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { auto &type = type_->analyseType(analyser->typeContext()); ASTTypeValueType::checkTypeValue(tokenType_, type, analyser->typeContext(), position()); return Type(MakeTypeAsValue, type); } Type ASTSizeOf::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { type_->analyseType(analyser->typeContext()); return analyser->integer(); } Type ASTConditionalAssignment::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { Type t = analyser->expect(TypeExpectation(false, false), &expr_); if (t.unboxedType() != TypeType::Optional) { throw CompilerError(position(), "Condition assignment can only be used with optionals."); } t = t.optionalType(); auto &variable = analyser->scoper().currentScope().declareVariable(varName_, t, true, position()); variable.initialize(); varId_ = variable.id(); return analyser->boolean(); } void ASTConditionalAssignment::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { analyser->recordVariableSet(varId_, expr_.get(), expr_->expressionType().optionalType()); analyser->take(expr_.get()); } Type ASTSuper::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { if (isSuperconstructorRequired(analyser->functionType())) { analyseSuperInit(analyser); return Type::noReturn(); } if (analyser->functionType() != FunctionType::ObjectMethod) { throw CompilerError(position(), "Not within an object-context."); } Class *superclass = analyser->typeContext().calleeType().klass()->superclass(); if (superclass == nullptr) { throw CompilerError(position(), "Class has no superclass."); } function_ = superclass->getMethod(name_, Type(superclass), analyser->typeContext(), args_.mood(), position()); calleeType_ = Type(superclass); return analyser->analyseFunctionCall(&args_, calleeType_, function_); } void ASTSuper::analyseSuperInit(ExpressionAnalyser *analyser) { if (analyser->typeContext().calleeType().klass()->superclass() == nullptr) { throw CompilerError(position(), "Class does not have a super class"); } if (analyser->pathAnalyser().hasPotentially(PathAnalyserIncident::CalledSuperInitializer)) { analyser->compiler()->error(CompilerError(position(), "Superinitializer might have already been called.")); } analyser->scoper().instanceScope()->uninitializedVariablesCheck(position(), "Instance variable \"", "\" must be " "initialized before calling the superinitializer."); init_ = true; auto eclass = analyser->typeContext().calleeType().klass(); auto initializer = eclass->superclass()->getInitializer(name_, Type(eclass), analyser->typeContext(), position()); calleeType_ = Type(eclass->superclass()); analyser->analyseFunctionCall(&args_, calleeType_, initializer); analyseSuperInitErrorProneness(analyser, initializer); function_ = initializer; analyser->pathAnalyser().recordIncident(PathAnalyserIncident::CalledSuperInitializer); } void ASTSuper::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { analyser->recordThis(function_->memoryFlowTypeForThis()); analyser->analyseFunctionCall(&args_, nullptr, function_); } void ASTSuper::analyseSuperInitErrorProneness(ExpressionAnalyser *eanalyser, const Initializer *initializer) { auto analyser = dynamic_cast<FunctionAnalyser *>(eanalyser); if (initializer->errorProne()) { auto thisInitializer = dynamic_cast<const Initializer*>(analyser->function()); if (!thisInitializer->errorProne()) { throw CompilerError(position(), "Cannot call an error-prone super initializer in a non ", "error-prone initializer."); } if (!initializer->errorType()->type().identicalTo(thisInitializer->errorType()->type(), analyser->typeContext(), nullptr)) { throw CompilerError(position(), "Super initializer must have same error enum type."); } manageErrorProneness_ = true; analyseInstanceVariables(analyser); } } Type ASTCallableCall::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) { Type type = analyser->expect(TypeExpectation(false, false), &callable_); if (type.type() != TypeType::Callable) { throw CompilerError(position(), "Given value is not callable."); } if (args_.args().size() != type.genericArguments().size() - 1) { throw CompilerError(position(), "Callable expects ", type.genericArguments().size() - 1, " arguments but ", args_.args().size(), " were supplied."); } for (size_t i = 1; i < type.genericArguments().size(); i++) { analyser->expectType(type.genericArguments()[i], &args_.args()[i - 1]); } return type.genericArguments()[0]; } void ASTCallableCall::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) { callable_->analyseMemoryFlow(analyser, MFFlowCategory::Borrowing); for (auto &arg : args_.args()) { analyser->take(arg.get()); arg->analyseMemoryFlow(analyser, MFFlowCategory::Escaping); // We cannot at all say what the callable will do. } } } // namespace EmojicodeCompiler
42.696552
120
0.689065
rozaxe
1b1829b43ebd11fe9d8b39428e4f8a9d294d88ea
19,043
cc
C++
chromium/components/html_viewer/html_frame_apptest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/html_viewer/html_frame_apptest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/html_viewer/html_frame_apptest.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include <stdint.h> #include <utility> #include "base/auto_reset.h" #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/stringprintf.h" #include "base/test/test_timeouts.h" #include "base/time/time.h" #include "base/values.h" #include "build/build_config.h" #include "components/html_viewer/public/interfaces/test_html_viewer.mojom.h" #include "components/mus/public/cpp/tests/window_server_test_base.h" #include "components/mus/public/cpp/window.h" #include "components/mus/public/cpp/window_tree_connection.h" #include "components/web_view/frame.h" #include "components/web_view/frame_connection.h" #include "components/web_view/frame_tree.h" #include "components/web_view/public/interfaces/frame.mojom.h" #include "components/web_view/test_frame_tree_delegate.h" #include "mojo/services/accessibility/public/interfaces/accessibility.mojom.h" #include "mojo/shell/public/cpp/application_impl.h" #include "net/test/embedded_test_server/embedded_test_server.h" using mus::mojom::WindowTreeClientPtr; using mus::WindowServerTestBase; using web_view::Frame; using web_view::FrameConnection; using web_view::FrameTree; using web_view::FrameTreeDelegate; using web_view::mojom::FrameClient; namespace mojo { namespace { const char kAddFrameWithEmptyPageScript[] = "var iframe = document.createElement(\"iframe\");" "iframe.src = \"http://127.0.0.1:%u/empty_page.html\";" "document.body.appendChild(iframe);"; void OnGotContentHandlerForRoot(bool* got_callback) { *got_callback = true; ignore_result(WindowServerTestBase::QuitRunLoop()); } mojo::ApplicationConnection* ApplicationConnectionForFrame(Frame* frame) { return static_cast<FrameConnection*>(frame->user_data()) ->application_connection(); } std::string GetFrameText(ApplicationConnection* connection) { html_viewer::TestHTMLViewerPtr test_html_viewer; connection->ConnectToService(&test_html_viewer); std::string result; test_html_viewer->GetContentAsText([&result](const String& mojo_string) { result = mojo_string; ASSERT_TRUE(WindowServerTestBase::QuitRunLoop()); }); if (!WindowServerTestBase::DoRunLoopWithTimeout()) ADD_FAILURE() << "Timed out waiting for execute to complete"; // test_html_viewer.WaitForIncomingResponse(); return result; } scoped_ptr<base::Value> ExecuteScript(ApplicationConnection* connection, const std::string& script) { html_viewer::TestHTMLViewerPtr test_html_viewer; connection->ConnectToService(&test_html_viewer); scoped_ptr<base::Value> result; test_html_viewer->ExecuteScript(script, [&result](const String& json_string) { result = base::JSONReader::Read(json_string.To<std::string>()); ASSERT_TRUE(WindowServerTestBase::QuitRunLoop()); }); if (!WindowServerTestBase::DoRunLoopWithTimeout()) ADD_FAILURE() << "Timed out waiting for execute to complete"; return result; } // FrameTreeDelegate that can block waiting for navigation to start. class TestFrameTreeDelegateImpl : public web_view::TestFrameTreeDelegate { public: explicit TestFrameTreeDelegateImpl(mojo::ApplicationImpl* app) : TestFrameTreeDelegate(app), frame_tree_(nullptr) {} ~TestFrameTreeDelegateImpl() override {} void set_frame_tree(FrameTree* frame_tree) { frame_tree_ = frame_tree; } // Resets the navigation state for |frame|. void ClearGotNavigate(Frame* frame) { frames_navigated_.erase(frame); } // Waits until |frame| has |count| children and the last child has navigated. bool WaitForChildFrameCount(Frame* frame, size_t count) { if (DidChildNavigate(frame, count)) return true; waiting_for_frame_child_count_.reset(new FrameAndChildCount); waiting_for_frame_child_count_->frame = frame; waiting_for_frame_child_count_->count = count; return WindowServerTestBase::DoRunLoopWithTimeout(); } // Returns true if |frame| has navigated. If |frame| hasn't navigated runs // a nested message loop until |frame| navigates. bool WaitForFrameNavigation(Frame* frame) { if (frames_navigated_.count(frame)) return true; frames_waiting_for_navigate_.insert(frame); return WindowServerTestBase::DoRunLoopWithTimeout(); } // TestFrameTreeDelegate: void DidStartNavigation(Frame* frame) override { frames_navigated_.insert(frame); if (waiting_for_frame_child_count_ && DidChildNavigate(waiting_for_frame_child_count_->frame, waiting_for_frame_child_count_->count)) { waiting_for_frame_child_count_.reset(); ASSERT_TRUE(WindowServerTestBase::QuitRunLoop()); } if (frames_waiting_for_navigate_.count(frame)) { frames_waiting_for_navigate_.erase(frame); ignore_result(WindowServerTestBase::QuitRunLoop()); } } private: struct FrameAndChildCount { Frame* frame; size_t count; }; // Returns true if |frame| has |count| children and the last child frame // has navigated. bool DidChildNavigate(Frame* frame, size_t count) { return ((frame->children().size() == count) && (frames_navigated_.count(frame->children()[count - 1]))); } FrameTree* frame_tree_; // Any time DidStartNavigation() is invoked the frame is added here. Frames // are inserted as void* as this does not track destruction of the frames. std::set<void*> frames_navigated_; // The set of frames waiting for a navigation to occur. std::set<Frame*> frames_waiting_for_navigate_; // Set of frames waiting for a certain number of children and navigation. scoped_ptr<FrameAndChildCount> waiting_for_frame_child_count_; DISALLOW_COPY_AND_ASSIGN(TestFrameTreeDelegateImpl); }; } // namespace class HTMLFrameTest : public WindowServerTestBase { public: HTMLFrameTest() {} ~HTMLFrameTest() override {} protected: // Creates the frame tree showing an empty page at the root and adds (via // script) a frame showing the same empty page. Frame* LoadEmptyPageAndCreateFrame() { mus::Window* embed_window = window_manager()->NewWindow(); frame_tree_delegate_.reset( new TestFrameTreeDelegateImpl(application_impl())); FrameConnection* root_connection = InitFrameTree( embed_window, "http://127.0.0.1:%u/empty_page2.html"); if (!root_connection) { ADD_FAILURE() << "unable to establish root connection"; return nullptr; } const std::string frame_text = GetFrameText(root_connection->application_connection()); if (frame_text != "child2") { ADD_FAILURE() << "unexpected text " << frame_text; return nullptr; } return CreateEmptyChildFrame(frame_tree_->root()); } Frame* CreateEmptyChildFrame(Frame* parent) { const size_t initial_frame_count = parent->children().size(); // Dynamically add a new frame. ExecuteScript(ApplicationConnectionForFrame(parent), AddPortToString(kAddFrameWithEmptyPageScript)); frame_tree_delegate_->WaitForChildFrameCount(parent, initial_frame_count + 1); if (HasFatalFailure()) return nullptr; return parent->FindFrame(parent->window()->children().back()->id()); } std::string AddPortToString(const std::string& string) { const uint16_t assigned_port = http_server_->host_port_pair().port(); return base::StringPrintf(string.c_str(), assigned_port); } mojo::URLRequestPtr BuildRequestForURL(const std::string& url_string) { mojo::URLRequestPtr request(mojo::URLRequest::New()); request->url = mojo::String::From(AddPortToString(url_string)); return request; } FrameConnection* InitFrameTree(mus::Window* view, const std::string& url_string) { frame_tree_delegate_.reset( new TestFrameTreeDelegateImpl(application_impl())); scoped_ptr<FrameConnection> frame_connection(new FrameConnection); bool got_callback = false; frame_connection->Init( application_impl(), BuildRequestForURL(url_string), base::Bind(&OnGotContentHandlerForRoot, &got_callback)); ignore_result(WindowServerTestBase::DoRunLoopWithTimeout()); if (!got_callback) return nullptr; FrameConnection* result = frame_connection.get(); FrameClient* frame_client = frame_connection->frame_client(); WindowTreeClientPtr tree_client = frame_connection->GetWindowTreeClient(); frame_tree_.reset(new FrameTree( result->GetContentHandlerID(), view, std::move(tree_client), frame_tree_delegate_.get(), frame_client, std::move(frame_connection), Frame::ClientPropertyMap(), base::TimeTicks::Now())); frame_tree_delegate_->set_frame_tree(frame_tree_.get()); return result; } // ViewManagerTest: void SetUp() override { WindowServerTestBase::SetUp(); // Start a test server. http_server_.reset(new net::EmbeddedTestServer); http_server_->ServeFilesFromSourceDirectory( "components/test/data/html_viewer"); ASSERT_TRUE(http_server_->Start()); } void TearDown() override { frame_tree_.reset(); http_server_.reset(); WindowServerTestBase::TearDown(); } scoped_ptr<net::EmbeddedTestServer> http_server_; scoped_ptr<FrameTree> frame_tree_; scoped_ptr<TestFrameTreeDelegateImpl> frame_tree_delegate_; private: DISALLOW_COPY_AND_ASSIGN(HTMLFrameTest); }; // Crashes on linux_chromium_rel_ng only. http://crbug.com/567337 #if defined(OS_LINUX) #define MAYBE_PageWithSingleFrame DISABLED_PageWithSingleFrame #else #define MAYBE_PageWithSingleFrame PageWithSingleFrame #endif TEST_F(HTMLFrameTest, MAYBE_PageWithSingleFrame) { mus::Window* embed_window = window_manager()->NewWindow(); FrameConnection* root_connection = InitFrameTree( embed_window, "http://127.0.0.1:%u/page_with_single_frame.html"); ASSERT_TRUE(root_connection); ASSERT_EQ("Page with single frame", GetFrameText(root_connection->application_connection())); ASSERT_NO_FATAL_FAILURE( frame_tree_delegate_->WaitForChildFrameCount(frame_tree_->root(), 1u)); ASSERT_EQ(1u, embed_window->children().size()); Frame* child_frame = frame_tree_->root()->FindFrame(embed_window->children()[0]->id()); ASSERT_TRUE(child_frame); ASSERT_EQ("child", GetFrameText(static_cast<FrameConnection*>(child_frame->user_data()) ->application_connection())); } // Creates two frames. The parent navigates the child frame by way of changing // the location of the child frame. // Crashes on linux_chromium_rel_ng only. http://crbug.com/567337 #if defined(OS_LINUX) #define MAYBE_ChangeLocationOfChildFrame DISABLED_ChangeLocationOfChildFrame #else #define MAYBE_ChangeLocationOfChildFrame ChangeLocationOfChildFrame #endif TEST_F(HTMLFrameTest, MAYBE_ChangeLocationOfChildFrame) { mus::Window* embed_window = window_manager()->NewWindow(); ASSERT_TRUE(InitFrameTree( embed_window, "http://127.0.0.1:%u/page_with_single_frame.html")); // page_with_single_frame contains a child frame. The child frame should // create a new View and Frame. ASSERT_NO_FATAL_FAILURE( frame_tree_delegate_->WaitForChildFrameCount(frame_tree_->root(), 1u)); Frame* child_frame = frame_tree_->root()->children().back(); ASSERT_EQ("child", GetFrameText(static_cast<FrameConnection*>(child_frame->user_data()) ->application_connection())); // Change the location and wait for the navigation to occur. const char kNavigateFrame[] = "window.frames[0].location = " "'http://127.0.0.1:%u/empty_page2.html'"; frame_tree_delegate_->ClearGotNavigate(child_frame); ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()), AddPortToString(kNavigateFrame)); ASSERT_TRUE(frame_tree_delegate_->WaitForFrameNavigation(child_frame)); // There should still only be one frame. ASSERT_EQ(1u, frame_tree_->root()->children().size()); // The navigation should have changed the text of the frame. ASSERT_TRUE(child_frame->user_data()); ASSERT_EQ("child2", GetFrameText(static_cast<FrameConnection*>(child_frame->user_data()) ->application_connection())); } TEST_F(HTMLFrameTest, DynamicallyAddFrameAndVerifyParent) { Frame* child_frame = LoadEmptyPageAndCreateFrame(); ASSERT_TRUE(child_frame); mojo::ApplicationConnection* child_frame_connection = ApplicationConnectionForFrame(child_frame); ASSERT_EQ("child", GetFrameText(child_frame_connection)); // The child's parent should not be itself: const char kGetWindowParentNameScript[] = "window.parent == window ? 'parent is self' : 'parent not self';"; scoped_ptr<base::Value> parent_value( ExecuteScript(child_frame_connection, kGetWindowParentNameScript)); ASSERT_TRUE(parent_value->IsType(base::Value::TYPE_LIST)); base::ListValue* parent_list; ASSERT_TRUE(parent_value->GetAsList(&parent_list)); ASSERT_EQ(1u, parent_list->GetSize()); std::string parent_name; ASSERT_TRUE(parent_list->GetString(0u, &parent_name)); EXPECT_EQ("parent not self", parent_name); } TEST_F(HTMLFrameTest, DynamicallyAddFrameAndSeeNameChange) { Frame* child_frame = LoadEmptyPageAndCreateFrame(); ASSERT_TRUE(child_frame); mojo::ApplicationConnection* child_frame_connection = ApplicationConnectionForFrame(child_frame); // Change the name of the child's window. ExecuteScript(child_frame_connection, "window.name = 'new_child';"); // Eventually the parent should see the change. There is no convenient way // to observe this change, so we repeatedly ask for it and timeout if we // never get the right value. const base::TimeTicks start_time(base::TimeTicks::Now()); std::string find_window_result; do { find_window_result.clear(); scoped_ptr<base::Value> script_value( ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()), "window.frames['new_child'] != null ? 'found frame' : " "'unable to find frame';")); if (script_value->IsType(base::Value::TYPE_LIST)) { base::ListValue* script_value_as_list; if (script_value->GetAsList(&script_value_as_list) && script_value_as_list->GetSize() == 1) { script_value_as_list->GetString(0u, &find_window_result); } } } while (find_window_result != "found frame" && base::TimeTicks::Now() - start_time < TestTimeouts::action_timeout()); EXPECT_EQ("found frame", find_window_result); } // Triggers dynamic addition and removal of a frame. TEST_F(HTMLFrameTest, FrameTreeOfThreeLevels) { // Create a child frame, and in that child frame create another child frame. Frame* child_frame = LoadEmptyPageAndCreateFrame(); ASSERT_TRUE(child_frame); ASSERT_TRUE(CreateEmptyChildFrame(child_frame)); // Make sure the parent can see the child and child's child. There is no // convenient way to observe this change, so we repeatedly ask for it and // timeout if we never get the right value. const char kGetChildChildFrameCount[] = "if (window.frames.length > 0)" " window.frames[0].frames.length.toString();" "else" " '0';"; const base::TimeTicks start_time(base::TimeTicks::Now()); std::string child_child_frame_count; do { child_child_frame_count.clear(); scoped_ptr<base::Value> script_value( ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()), kGetChildChildFrameCount)); if (script_value->IsType(base::Value::TYPE_LIST)) { base::ListValue* script_value_as_list; if (script_value->GetAsList(&script_value_as_list) && script_value_as_list->GetSize() == 1) { script_value_as_list->GetString(0u, &child_child_frame_count); } } } while (child_child_frame_count != "1" && base::TimeTicks::Now() - start_time < TestTimeouts::action_timeout()); EXPECT_EQ("1", child_child_frame_count); // Remove the child's child and make sure the root doesn't see it anymore. const char kRemoveLastIFrame[] = "document.body.removeChild(document.body.lastChild);"; ExecuteScript(ApplicationConnectionForFrame(child_frame), kRemoveLastIFrame); do { child_child_frame_count.clear(); scoped_ptr<base::Value> script_value( ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()), kGetChildChildFrameCount)); if (script_value->IsType(base::Value::TYPE_LIST)) { base::ListValue* script_value_as_list; if (script_value->GetAsList(&script_value_as_list) && script_value_as_list->GetSize() == 1) { script_value_as_list->GetString(0u, &child_child_frame_count); } } } while (child_child_frame_count != "0" && base::TimeTicks::Now() - start_time < TestTimeouts::action_timeout()); ASSERT_EQ("0", child_child_frame_count); } // Verifies PostMessage() works across frames. TEST_F(HTMLFrameTest, PostMessage) { Frame* child_frame = LoadEmptyPageAndCreateFrame(); ASSERT_TRUE(child_frame); mojo::ApplicationConnection* child_frame_connection = ApplicationConnectionForFrame(child_frame); ASSERT_EQ("child", GetFrameText(child_frame_connection)); // Register an event handler in the child frame. const char kRegisterPostMessageHandler[] = "window.messageData = null;" "function messageFunction(event) {" " window.messageData = event.data;" "}" "window.addEventListener('message', messageFunction, false);"; ExecuteScript(child_frame_connection, kRegisterPostMessageHandler); // Post a message from the parent to the child. const char kPostMessageFromParent[] = "window.frames[0].postMessage('hello from parent', '*');"; ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()), kPostMessageFromParent); // Wait for the child frame to see the message. const base::TimeTicks start_time(base::TimeTicks::Now()); std::string message_in_child; do { const char kGetMessageData[] = "window.messageData;"; scoped_ptr<base::Value> script_value( ExecuteScript(child_frame_connection, kGetMessageData)); if (script_value->IsType(base::Value::TYPE_LIST)) { base::ListValue* script_value_as_list; if (script_value->GetAsList(&script_value_as_list) && script_value_as_list->GetSize() == 1) { script_value_as_list->GetString(0u, &message_in_child); } } } while (message_in_child != "hello from parent" && base::TimeTicks::Now() - start_time < TestTimeouts::action_timeout()); EXPECT_EQ("hello from parent", message_in_child); } } // namespace mojo
38.00998
80
0.722365
wedataintelligence
1b1906b70da6c93af4fefdbc3fae9f7ef1b124c0
1,554
hh
C++
StRoot/StarClassLibrary/StMemoryInfo.hh
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StarClassLibrary/StMemoryInfo.hh
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StarClassLibrary/StMemoryInfo.hh
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id: StMemoryInfo.hh,v 1.5 2013/01/17 14:40:04 fisyak Exp $ * * Author: Thomas Ullrich, June 1999 *************************************************************************** * * Description: * *************************************************************************** * * $Log: StMemoryInfo.hh,v $ * Revision 1.5 2013/01/17 14:40:04 fisyak * Add APPLE * * Revision 1.4 2003/09/02 17:59:35 perev * gcc 3.2 updates + WarnOff * * Revision 1.3 2000/01/04 14:57:54 ullrich * Added friend declaration to avoid warning messages * under Linux. * * Revision 1.2 1999/12/21 15:14:18 ullrich * Modified to cope with new compiler version on Sun (CC5.0). * * Revision 1.1 1999/06/04 17:57:02 ullrich * Initial Revision * **************************************************************************/ #ifndef StMemoryInfo_hh #define StMemoryInfo_hh #ifndef __APPLE__ #include <malloc.h> #endif #include <Stiostream.h> class StMemoryInfo { public: static StMemoryInfo* instance(); void snapshot(); void print(ostream& = cout); friend class nobody; private: StMemoryInfo(); StMemoryInfo(const StMemoryInfo &); const StMemoryInfo & operator=(const StMemoryInfo &); void printLine(ostream&, const char*, int, int, const char* = 0); static StMemoryInfo* mMemoryInfo; #ifndef __APPLE__ struct mallinfo mInfo; struct mallinfo mOldInfo; #endif size_t mCounter; }; #endif
25.47541
76
0.532175
xiaohaijin
1b19c1da753967c960e5297f2bd9a409517e6f77
31,795
cpp
C++
libs/vision/src/tracking.cpp
mrliujie/mrpt-learning-code
7b41a9501fc35c36580c93bc1499f5a36d26c216
[ "BSD-3-Clause" ]
2
2020-04-21T08:51:21.000Z
2022-03-21T10:47:52.000Z
libs/vision/src/tracking.cpp
qifengl/mrpt
979a458792273a86ec5ab105e0cd6c963c65ea73
[ "BSD-3-Clause" ]
null
null
null
libs/vision/src/tracking.cpp
qifengl/mrpt
979a458792273a86ec5ab105e0cd6c963c65ea73
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "vision-precomp.h" // Precompiled headers #include <mrpt/vision/tracking.h> #include <mrpt/vision/CFeatureExtraction.h> // Universal include for all versions of OpenCV #include <mrpt/otherlibs/do_opencv_includes.h> using namespace mrpt; using namespace mrpt::vision; using namespace mrpt::img; using namespace mrpt::tfest; using namespace mrpt::math; using namespace std; // ------------------------------- internal helper templates // --------------------------------- namespace mrpt::vision::detail { template <typename FEATLIST> inline void trackFeatures_checkResponses( FEATLIST& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y); template <> inline void trackFeatures_checkResponses<CFeatureList>( CFeatureList& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y) { const auto itFeatEnd = featureList.end(); for (auto itFeat = featureList.begin(); itFeat != itFeatEnd; ++itFeat) { CFeature* ft = itFeat->get(); if (ft->track_status != status_TRACKED) continue; // Skip if it's not correctly tracked. const unsigned int x = ft->x; const unsigned int y = ft->y; if (x > KLT_response_half_win && y > KLT_response_half_win && x < max_x && y < max_y) { // Update response: ft->response = cur_gray.KLT_response(x, y, KLT_response_half_win); // Is it good enough? // http://grooveshark.com/s/Goonies+Are+Good+Enough/2beBfO?src=5 if (ft->response < minimum_KLT_response) { // Nope! ft->track_status = status_LOST; } } else { // Out of bounds ft->response = 0; ft->track_status = status_OOB; } } } // end of trackFeatures_checkResponses<> template <class FEAT_LIST> inline void trackFeatures_checkResponses_impl_simple( FEAT_LIST& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x_, const unsigned int max_y_) { if (featureList.empty()) return; using pixel_coord_t = typename FEAT_LIST::feature_t::pixel_coord_t; const auto half_win = static_cast<pixel_coord_t>(KLT_response_half_win); const auto max_x = static_cast<pixel_coord_t>(max_x_); const auto max_y = static_cast<pixel_coord_t>(max_y_); for (int N = featureList.size() - 1; N >= 0; --N) { typename FEAT_LIST::feature_t& ft = featureList[N]; if (ft.track_status != status_TRACKED) continue; // Skip if it's not correctly tracked. if (ft.pt.x > half_win && ft.pt.y > half_win && ft.pt.x < max_x && ft.pt.y < max_y) { // Update response: ft.response = cur_gray.KLT_response(ft.pt.x, ft.pt.y, KLT_response_half_win); // Is it good enough? // http://grooveshark.com/s/Goonies+Are+Good+Enough/2beBfO?src=5 if (ft.response < minimum_KLT_response) { // Nope! ft.track_status = status_LOST; } } else { // Out of bounds ft.response = 0; ft.track_status = status_OOB; } } } // end of trackFeatures_checkResponses<> template <> inline void trackFeatures_checkResponses<TSimpleFeatureList>( TSimpleFeatureList& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y) { trackFeatures_checkResponses_impl_simple<TSimpleFeatureList>( featureList, cur_gray, minimum_KLT_response, KLT_response_half_win, max_x, max_y); } template <> inline void trackFeatures_checkResponses<TSimpleFeaturefList>( TSimpleFeaturefList& featureList, const CImage& cur_gray, const float minimum_KLT_response, const unsigned int KLT_response_half_win, const unsigned int max_x, const unsigned int max_y) { trackFeatures_checkResponses_impl_simple<TSimpleFeaturefList>( featureList, cur_gray, minimum_KLT_response, KLT_response_half_win, max_x, max_y); } template <typename FEATLIST> inline void trackFeatures_updatePatch( FEATLIST& featureList, const CImage& cur_gray); template <> inline void trackFeatures_updatePatch<CFeatureList>( CFeatureList& featureList, const CImage& cur_gray) { for (auto& itFeat : featureList) { CFeature* ft = itFeat.get(); if (ft->track_status != status_TRACKED) continue; // Skip if it's not correctly tracked. const size_t patch_width = ft->patch.getWidth(); const size_t patch_height = ft->patch.getHeight(); if (patch_width > 0 && patch_height > 0) { try { const int offset = (int)patch_width / 2; // + 1; cur_gray.extract_patch( ft->patch, round(ft->x) - offset, round(ft->y) - offset, patch_width, patch_height); } catch (std::exception&) { ft->track_status = status_OOB; // Out of bounds! } } } } // end of trackFeatures_updatePatch<> template <> inline void trackFeatures_updatePatch<TSimpleFeatureList>( TSimpleFeatureList& featureList, const CImage& cur_gray) { MRPT_UNUSED_PARAM(featureList); MRPT_UNUSED_PARAM(cur_gray); // This list type does not have patch stored explicitly } // end of trackFeatures_updatePatch<> template <> inline void trackFeatures_updatePatch<TSimpleFeaturefList>( TSimpleFeaturefList& featureList, const CImage& cur_gray) { MRPT_UNUSED_PARAM(featureList); MRPT_UNUSED_PARAM(cur_gray); // This list type does not have patch stored explicitly } // end of trackFeatures_updatePatch<> template <typename FEATLIST> inline void trackFeatures_addNewFeats( FEATLIST& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input); template <> inline void trackFeatures_addNewFeats<CFeatureList>( CFeatureList& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { const TImageSize imgSize = cur_gray.getSize(); const int offset = (int)patchSize / 2 + 1; const int w_off = int(imgSize.x - offset); const int h_off = int(imgSize.y - offset); for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures; i++) { const TSimpleFeature& feat = new_feats[sorted_indices[i]]; if (feat.response < minimum_KLT_response_to_add) continue; double min_dist_sqr = square(10000); if (!featureList.empty()) { // m_timlog.enter("[CGenericFeatureTracker] add new // features.kdtree"); min_dist_sqr = featureList.kdTreeClosestPoint2DsqrError(feat.pt.x, feat.pt.y); // m_timlog.leave("[CGenericFeatureTracker] add new // features.kdtree"); } if (min_dist_sqr > threshold_sqr_dist_to_add_new && feat.pt.x > offset && feat.pt.y > offset && feat.pt.x < w_off && feat.pt.y < h_off) { // Add new feature: CFeature::Ptr ft = mrpt::make_aligned_shared<CFeature>(); ft->type = featFAST; ft->ID = ++max_feat_ID_at_input; ft->x = feat.pt.x; ft->y = feat.pt.y; ft->response = feat.response; ft->orientation = 0; ft->scale = 1; ft->patchSize = patchSize; // The size of the feature patch if (patchSize > 0) cur_gray.extract_patch( ft->patch, round(ft->x) - offset, round(ft->y) - offset, patchSize, patchSize); // Image patch surronding the feature featureList.push_back(ft); } } } // end of trackFeatures_addNewFeats<> template <class FEAT_LIST> inline void trackFeatures_addNewFeats_simple_list( FEAT_LIST& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { #if 0 // Brute-force version: const int max_manhatan_dist = std::sqrt(2*threshold_sqr_dist_to_add_new); for (size_t i=0;i<nNewToCheck && featureList.size()<maxNumFeatures;i++) { const TSimpleFeature &feat = new_feats[ sorted_indices[i] ]; if (feat.response<minimum_KLT_response_to_add) break; // continue; // Check the min-distance: int manh_dist = std::numeric_limits<int>::max(); for (size_t j=0;j<featureList.size();j++) { const TSimpleFeature &existing = featureList[j]; const int d = std::abs(existing.pt.x-feat.pt.x)+std::abs(existing.pt.y-feat.pt.y); mrpt::keep_min(manh_dist, d); } if (manh_dist<max_manhatan_dist) continue; // Already occupied! skip. // OK: accept it featureList.push_back_fast(feat.pt.x,feat.pt.y); // (x,y) //featureList.mark_kdtree_as_outdated(); // Fill out the rest of data: TSimpleFeature &newFeat = featureList.back(); newFeat.ID = ++max_feat_ID_at_input; newFeat.response = feat.response; newFeat.octave = 0; /** Inactive: right after detection, and before being tried to track */ newFeat.track_status = status_IDLE; } #elif 0 // Version with an occupancy grid: const int grid_cell_log2 = round( std::log(std::sqrt(threshold_sqr_dist_to_add_new) * 0.5) / std::log(2.0)); int grid_lx = 1 + (cur_gray.getWidth() >> grid_cell_log2); int grid_ly = 1 + (cur_gray.getHeight() >> grid_cell_log2); mrpt::math::CMatrixBool& occupied_sections = featureList.getOccupiedSectionsMatrix(); occupied_sections.setSize( grid_lx, grid_ly); // See the comments above for an explanation. occupied_sections.fillAll(false); for (size_t i = 0; i < featureList.size(); i++) { const TSimpleFeature& feat = featureList[i]; const int section_idx_x = feat.pt.x >> grid_cell_log2; const int section_idx_y = feat.pt.y >> grid_cell_log2; if (!section_idx_x || !section_idx_y || section_idx_x >= grid_lx - 1 || section_idx_y >= grid_ly - 1) continue; // This may be too radical, but speeds up the logic // below... // Mark sections as occupied bool* ptr1 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y - 1); bool* ptr2 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y); bool* ptr3 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y + 1); ptr1[0] = ptr1[1] = ptr1[2] = true; ptr2[0] = ptr2[1] = ptr2[2] = true; ptr3[0] = ptr3[1] = ptr3[2] = true; } for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures; i++) { const TSimpleFeature& feat = new_feats[sorted_indices[i]]; if (feat.response < minimum_KLT_response_to_add) break; // continue; // Check the min-distance: const int section_idx_x = feat.pt.x >> grid_cell_log2; const int section_idx_y = feat.pt.y >> grid_cell_log2; if (!section_idx_x || !section_idx_y || section_idx_x >= grid_lx - 2 || section_idx_y >= grid_ly - 2) continue; // This may be too radical, but speeds up the logic // below... if (occupied_sections(section_idx_x, section_idx_y)) continue; // Already occupied! skip. // Mark section as occupied bool* ptr1 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y - 1); bool* ptr2 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y); bool* ptr3 = &occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y + 1); ptr1[0] = ptr1[1] = ptr1[2] = true; ptr2[0] = ptr2[1] = ptr2[2] = true; ptr3[0] = ptr3[1] = ptr3[2] = true; // OK: accept it featureList.push_back_fast(feat.pt.x, feat.pt.y); // (x,y) // featureList.mark_kdtree_as_outdated(); // Fill out the rest of data: TSimpleFeature& newFeat = featureList.back(); newFeat.ID = ++max_feat_ID_at_input; newFeat.response = feat.response; newFeat.octave = 0; /** Inactive: right after detection, and before being tried to track */ newFeat.track_status = status_IDLE; } #else MRPT_UNUSED_PARAM(patchSize); MRPT_UNUSED_PARAM(cur_gray); // Version with KD-tree CFeatureListKDTree<typename FEAT_LIST::feature_t> kdtree( featureList.getVector()); for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures; i++) { const TSimpleFeature& feat = new_feats[sorted_indices[i]]; if (feat.response < minimum_KLT_response_to_add) break; // continue; // Check the min-distance: double min_dist_sqr = std::numeric_limits<double>::max(); if (!featureList.empty()) { // m_timlog.enter("[CGenericFeatureTracker] add new // features.kdtree"); min_dist_sqr = kdtree.kdTreeClosestPoint2DsqrError(feat.pt.x, feat.pt.y); // m_timlog.leave("[CGenericFeatureTracker] add new // features.kdtree"); } if (min_dist_sqr > threshold_sqr_dist_to_add_new) { // OK: accept it featureList.push_back_fast(feat.pt.x, feat.pt.y); // (x,y) kdtree.mark_as_outdated(); // Fill out the rest of data: typename FEAT_LIST::feature_t& newFeat = featureList.back(); newFeat.ID = ++max_feat_ID_at_input; newFeat.response = feat.response; newFeat.octave = 0; /** Inactive: right after detection, and before being tried to track */ newFeat.track_status = status_IDLE; } } #endif } // end of trackFeatures_addNewFeats<> template <> inline void trackFeatures_addNewFeats<TSimpleFeatureList>( TSimpleFeatureList& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { trackFeatures_addNewFeats_simple_list<TSimpleFeatureList>( featureList, new_feats, sorted_indices, nNewToCheck, maxNumFeatures, minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize, cur_gray, max_feat_ID_at_input); } template <> inline void trackFeatures_addNewFeats<TSimpleFeaturefList>( TSimpleFeaturefList& featureList, const TSimpleFeatureList& new_feats, const std::vector<size_t>& sorted_indices, const size_t nNewToCheck, const size_t maxNumFeatures, const float minimum_KLT_response_to_add, const double threshold_sqr_dist_to_add_new, const size_t patchSize, const CImage& cur_gray, TFeatureID& max_feat_ID_at_input) { trackFeatures_addNewFeats_simple_list<TSimpleFeaturefList>( featureList, new_feats, sorted_indices, nNewToCheck, maxNumFeatures, minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize, cur_gray, max_feat_ID_at_input); } // Return the number of removed features template <typename FEATLIST> inline size_t trackFeatures_deleteOOB( FEATLIST& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING); template <typename FEATLIST> inline size_t trackFeatures_deleteOOB_impl_simple_feat( FEATLIST& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { if (trackedFeats.empty()) return 0; std::vector<size_t> survival_idxs; const size_t N = trackedFeats.size(); // 1st: Build list of survival indexes: survival_idxs.reserve(N); for (size_t i = 0; i < N; i++) { const typename FEATLIST::feature_t& ft = trackedFeats[i]; const TFeatureTrackStatus status = ft.track_status; bool eras = (status_TRACKED != status && status_IDLE != status); if (!eras) { // Also, check if it's too close to the image border: const int x = ft.pt.x; const int y = ft.pt.y; if (x < MIN_DIST_MARGIN_TO_STOP_TRACKING || y < MIN_DIST_MARGIN_TO_STOP_TRACKING || x > static_cast<int>( img_width - MIN_DIST_MARGIN_TO_STOP_TRACKING) || y > static_cast<int>( img_height - MIN_DIST_MARGIN_TO_STOP_TRACKING)) { eras = true; } } if (!eras) survival_idxs.push_back(i); } // 2nd: Build updated list: const size_t N2 = survival_idxs.size(); const size_t n_removed = N - N2; for (size_t i = 0; i < N2; i++) { if (survival_idxs[i] != i) trackedFeats[i] = trackedFeats[survival_idxs[i]]; } trackedFeats.resize(N2); return n_removed; } // end of trackFeatures_deleteOOB template <> inline size_t trackFeatures_deleteOOB( TSimpleFeatureList& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { return trackFeatures_deleteOOB_impl_simple_feat<TSimpleFeatureList>( trackedFeats, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING); } template <> inline size_t trackFeatures_deleteOOB( TSimpleFeaturefList& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { return trackFeatures_deleteOOB_impl_simple_feat<TSimpleFeaturefList>( trackedFeats, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING); } template <> inline size_t trackFeatures_deleteOOB( CFeatureList& trackedFeats, const size_t img_width, const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING) { auto itFeat = trackedFeats.begin(); size_t n_removed = 0; while (itFeat != trackedFeats.end()) { const TFeatureTrackStatus status = (*itFeat)->track_status; bool eras = (status_TRACKED != status && status_IDLE != status); if (!eras) { // Also, check if it's too close to the image border: const float x = (*itFeat)->x; const float y = (*itFeat)->y; if (x < MIN_DIST_MARGIN_TO_STOP_TRACKING || y < MIN_DIST_MARGIN_TO_STOP_TRACKING || x > (img_width - MIN_DIST_MARGIN_TO_STOP_TRACKING) || y > (img_height - MIN_DIST_MARGIN_TO_STOP_TRACKING)) { eras = true; } } if (eras) // Erase or keep? { itFeat = trackedFeats.erase(itFeat); n_removed++; } else ++itFeat; } return n_removed; } // end of trackFeatures_deleteOOB } // namespace mrpt::vision::detail // ---------------------------- end of internal helper templates // ------------------------------- void CGenericFeatureTracker::trackFeatures_impl( const CImage& old_img, const CImage& new_img, TSimpleFeaturefList& inout_featureList) { MRPT_UNUSED_PARAM(old_img); MRPT_UNUSED_PARAM(new_img); MRPT_UNUSED_PARAM(inout_featureList); THROW_EXCEPTION("Method not implemented by derived class!"); } /** Perform feature tracking from "old_img" to "new_img", with a (possibly *empty) list of previously tracked features "featureList". * This is a list of parameters (in "extraParams") accepted by ALL *implementations of feature tracker (see each derived class for more specific *parameters). * - "add_new_features" (Default=0). If set to "1", new features will be *also *added to the existing ones in areas of the image poor of features. * This method actually first call the pure virtual "trackFeatures_impl" *method, then implements the optional detection of new features if *"add_new_features"!=0. */ template <typename FEATLIST> void CGenericFeatureTracker::internal_trackFeatures( const CImage& old_img, const CImage& new_img, FEATLIST& featureList) { m_timlog.enter( "[CGenericFeatureTracker::trackFeatures] Complete iteration"); const size_t img_width = new_img.getWidth(); const size_t img_height = new_img.getHeight(); // Take the maximum ID of "old" features so new feats (if // "add_new_features==true") will be id+1, id+2, ... TFeatureID max_feat_ID_at_input = 0; if (!featureList.empty()) max_feat_ID_at_input = featureList.getMaxID(); // Grayscale images // ========================================= m_timlog.enter("[CGenericFeatureTracker] Convert grayscale"); const CImage prev_gray(old_img, FAST_REF_OR_CONVERT_TO_GRAY); const CImage cur_gray(new_img, FAST_REF_OR_CONVERT_TO_GRAY); m_timlog.leave("[CGenericFeatureTracker] Convert grayscale"); // ================================= // (1st STEP) Do the actual tracking // ================================= m_newly_detected_feats.clear(); m_timlog.enter("[CGenericFeatureTracker] trackFeatures_impl"); trackFeatures_impl(prev_gray, cur_gray, featureList); m_timlog.leave("[CGenericFeatureTracker] trackFeatures_impl"); // ======================================================== // (2nd STEP) For successfully followed features, check their KLT response?? // ======================================================== const int check_KLT_response_every = extra_params.getWithDefaultVal("check_KLT_response_every", 0); const float minimum_KLT_response = extra_params.getWithDefaultVal("minimum_KLT_response", 5); const unsigned int KLT_response_half_win = extra_params.getWithDefaultVal("KLT_response_half_win", 4); if (check_KLT_response_every > 0 && ++m_check_KLT_counter >= size_t(check_KLT_response_every)) { m_timlog.enter("[CGenericFeatureTracker] check KLT responses"); m_check_KLT_counter = 0; const unsigned int max_x = img_width - KLT_response_half_win; const unsigned int max_y = img_height - KLT_response_half_win; detail::trackFeatures_checkResponses( featureList, cur_gray, minimum_KLT_response, KLT_response_half_win, max_x, max_y); m_timlog.leave("[CGenericFeatureTracker] check KLT responses"); } // end check_KLT_response_every // ============================================================ // (3rd STEP) Remove Out-of-bounds or badly tracked features // or those marked as "bad" by their low KLT response // ============================================================ const bool remove_lost_features = extra_params.getWithDefaultVal("remove_lost_features", 0) != 0; if (remove_lost_features) { m_timlog.enter("[CGenericFeatureTracker] removal of OOB"); static const int MIN_DIST_MARGIN_TO_STOP_TRACKING = 10; const size_t nRemoved = detail::trackFeatures_deleteOOB( featureList, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING); m_timlog.leave("[CGenericFeatureTracker] removal of OOB"); last_execution_extra_info.num_deleted_feats = nRemoved; } else { last_execution_extra_info.num_deleted_feats = 0; } // ======================================================== // (4th STEP) For successfully followed features, update its patch: // ======================================================== const int update_patches_every = extra_params.getWithDefaultVal("update_patches_every", 0); if (update_patches_every > 0 && ++m_update_patches_counter >= size_t(update_patches_every)) { m_timlog.enter("[CGenericFeatureTracker] update patches"); m_update_patches_counter = 0; // Update the patch for each valid feature: detail::trackFeatures_updatePatch(featureList, cur_gray); m_timlog.leave("[CGenericFeatureTracker] update patches"); } // end if update_patches_every // ======================================================== // (5th STEP) Do detection of new features?? // ======================================================== const bool add_new_features = extra_params.getWithDefaultVal("add_new_features", 0) != 0; const double threshold_dist_to_add_new = extra_params.getWithDefaultVal("add_new_feat_min_separation", 15); // Additional operation: if "add_new_features==true", find new features and // add them in // areas spare of valid features: if (add_new_features) { m_timlog.enter("[CGenericFeatureTracker] add new features"); // Look for new features and save in "m_newly_detected_feats", if // they're not already computed: if (m_newly_detected_feats.empty()) { // Do the detection CFeatureExtraction::detectFeatures_SSE2_FASTER12( cur_gray, m_newly_detected_feats, m_detector_adaptive_thres); } const size_t N = m_newly_detected_feats.size(); last_execution_extra_info.raw_FAST_feats_detected = N; // Extra out info. // Update the adaptive threshold. const size_t desired_num_features = extra_params.getWithDefaultVal( "desired_num_features_adapt", size_t((img_width * img_height) >> 9)); updateAdaptiveNewFeatsThreshold(N, desired_num_features); // Use KLT response instead of the OpenCV's original "response" field: { const unsigned int max_x = img_width - KLT_response_half_win; const unsigned int max_y = img_height - KLT_response_half_win; for (size_t i = 0; i < N; i++) { const unsigned int x = m_newly_detected_feats[i].pt.x; const unsigned int y = m_newly_detected_feats[i].pt.y; if (x > KLT_response_half_win && y > KLT_response_half_win && x < max_x && y < max_y) m_newly_detected_feats[i].response = cur_gray.KLT_response(x, y, KLT_response_half_win); else m_newly_detected_feats[i].response = 0; // Out of bounds } } // Sort them by "response": It's ~100 times faster to sort a list of // indices "sorted_indices" than sorting directly the actual list // of features "m_newly_detected_feats" std::vector<size_t> sorted_indices(N); for (size_t i = 0; i < N; i++) sorted_indices[i] = i; std::sort( sorted_indices.begin(), sorted_indices.end(), KeypointResponseSorter<TSimpleFeatureList>(m_newly_detected_feats)); // For each new good feature, add it to the list of tracked ones only if // it's pretty // isolated: const size_t nNewToCheck = std::min(size_t(1500), N); const double threshold_sqr_dist_to_add_new = square(threshold_dist_to_add_new); const size_t maxNumFeatures = extra_params.getWithDefaultVal("add_new_feat_max_features", 100); const size_t patchSize = extra_params.getWithDefaultVal("add_new_feat_patch_size", 11); const float minimum_KLT_response_to_add = extra_params.getWithDefaultVal("minimum_KLT_response_to_add", 10); // Do it: detail::trackFeatures_addNewFeats( featureList, m_newly_detected_feats, sorted_indices, nNewToCheck, maxNumFeatures, minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize, cur_gray, max_feat_ID_at_input); m_timlog.leave("[CGenericFeatureTracker] add new features"); } m_timlog.leave( "[CGenericFeatureTracker::trackFeatures] Complete iteration"); } // end of CGenericFeatureTracker::trackFeatures void CGenericFeatureTracker::trackFeatures( const CImage& old_img, const CImage& new_img, CFeatureList& featureList) { internal_trackFeatures<CFeatureList>(old_img, new_img, featureList); } void CGenericFeatureTracker::trackFeatures( const CImage& old_img, const CImage& new_img, TSimpleFeatureList& featureList) { internal_trackFeatures<TSimpleFeatureList>(old_img, new_img, featureList); } void CGenericFeatureTracker::trackFeatures( const CImage& old_img, const CImage& new_img, TSimpleFeaturefList& featureList) { internal_trackFeatures<TSimpleFeaturefList>(old_img, new_img, featureList); } void CGenericFeatureTracker::updateAdaptiveNewFeatsThreshold( const size_t nNewlyDetectedFeats, const size_t desired_num_features) { const size_t hysteresis_min_num_feats = desired_num_features * 0.9; const size_t hysteresis_max_num_feats = desired_num_features * 1.1; if (nNewlyDetectedFeats < hysteresis_min_num_feats) m_detector_adaptive_thres = std::max( 2.0, std::min( m_detector_adaptive_thres - 1.0, m_detector_adaptive_thres * 0.8)); else if (nNewlyDetectedFeats > hysteresis_max_num_feats) m_detector_adaptive_thres = std::max( m_detector_adaptive_thres + 1.0, m_detector_adaptive_thres * 1.2); } /*------------------------------------------------------------ checkTrackedFeatures -------------------------------------------------------------*/ void vision::checkTrackedFeatures( CFeatureList& leftList, CFeatureList& rightList, vision::TMatchingOptions options) { ASSERT_(leftList.size() == rightList.size()); // std::cout << std::endl << "Tracked features checking ..." << std::endl; CFeatureList::iterator itLeft, itRight; size_t u, v; double res; for (itLeft = leftList.begin(), itRight = rightList.begin(); itLeft != leftList.end();) { bool delFeat = false; if ((*itLeft)->x < 0 || (*itLeft)->y < 0 || // Out of bounds (*itRight)->x < 0 || (*itRight)->y < 0 || // Out of bounds fabs((*itLeft)->y - (*itRight)->y) > options .epipolar_TH) // Not fulfillment of the epipolar constraint { // Show reason std::cout << "Bad tracked match:"; if ((*itLeft)->x < 0 || (*itLeft)->y < 0 || (*itRight)->x < 0 || (*itRight)->y < 0) std::cout << " Out of bounds: (" << (*itLeft)->x << "," << (*itLeft)->y << " & (" << (*itRight)->x << "," << (*itRight)->y << ")" << std::endl; if (fabs((*itLeft)->y - (*itRight)->y) > options.epipolar_TH) std::cout << " Bad row checking: " << fabs((*itLeft)->y - (*itRight)->y) << std::endl; delFeat = true; } else { // Compute cross correlation: openCV_cross_correlation( (*itLeft)->patch, (*itRight)->patch, u, v, res); if (res < options.minCC_TH) { std::cout << "Bad tracked match (correlation failed):" << " CC Value: " << res << std::endl; delFeat = true; } } // end if if (delFeat) // Erase the pair of features { itLeft = leftList.erase(itLeft); itRight = rightList.erase(itRight); } else { itLeft++; itRight++; } } // end for } // end checkTrackedFeatures /*------------------------------------------------------------- filterBadCorrsByDistance -------------------------------------------------------------*/ void vision::filterBadCorrsByDistance( TMatchingPairList& feat_list, unsigned int numberOfSigmas) { ASSERT_(numberOfSigmas > 0); // MRPT_UNUSED_PARAM( numberOfSigmas ); MRPT_START TMatchingPairList::iterator itPair; CMatrix dist; double v_mean, v_std; unsigned int count = 0; dist.setSize(feat_list.size(), 1); // v_mean.resize(1); // v_std.resize(1); // Compute mean and standard deviation of the distance for (itPair = feat_list.begin(); itPair != feat_list.end(); itPair++, count++) { // cout << "(" << itPair->other_x << "," << itPair->other_y << "," << // itPair->this_z << ")" << "- (" << itPair->this_x << "," << // itPair->this_y << "," << itPair->other_z << "): "; // cout << sqrt( square( itPair->other_x - itPair->this_x ) + square( // itPair->other_y - itPair->this_y ) + square( itPair->other_z - // itPair->this_z ) ) << endl; dist(count, 0) = sqrt( square(itPair->other_x - itPair->this_x) + square(itPair->other_y - itPair->this_y) + square(itPair->other_z - itPair->this_z)); } dist.meanAndStdAll(v_mean, v_std); cout << endl << "*****************************************************" << endl; cout << "Mean: " << v_mean << " - STD: " << v_std << endl; cout << endl << "*****************************************************" << endl; // Filter out bad points unsigned int idx = 0; // for( int idx = (int)feat_list.size()-1; idx >= 0; idx-- ) for (itPair = feat_list.begin(); itPair != feat_list.end(); idx++) { // if( dist( idx, 0 ) > 1.2 ) if (fabs(dist(idx, 0) - v_mean) > v_std * numberOfSigmas) { cout << "Outlier deleted: " << dist(idx, 0) << " vs " << v_std * numberOfSigmas << endl; itPair = feat_list.erase(itPair); } else itPair++; } MRPT_END } // end filterBadCorrsByDistance
34.005348
88
0.692436
mrliujie
1b1c2b6586c3a6de8fc761325bb22f65b1775fd5
14,936
cpp
C++
Runtime/Resource/Import/ImageImporter.cpp
slimlime/SpartanEngine
9f1b14dc158eda0e951ee05824c5a4a1084dde14
[ "MIT" ]
null
null
null
Runtime/Resource/Import/ImageImporter.cpp
slimlime/SpartanEngine
9f1b14dc158eda0e951ee05824c5a4a1084dde14
[ "MIT" ]
null
null
null
Runtime/Resource/Import/ImageImporter.cpp
slimlime/SpartanEngine
9f1b14dc158eda0e951ee05824c5a4a1084dde14
[ "MIT" ]
null
null
null
/* Copyright(c) 2016-2021 Panos Karabelas 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. */ //= INCLUDES ========================= #include "Spartan.h" #include "ImageImporter.h" #define FREEIMAGE_LIB #include <FreeImage.h> #include <Utilities.h> #include "../../Threading/Threading.h" #include "../../RHI/RHI_Texture2D.h" //==================================== //= NAMESPACES ===== using namespace std; //================== namespace Spartan { static FREE_IMAGE_FILTER filter_downsample = FREE_IMAGE_FILTER::FILTER_BOX; // A struct that rescaling threads will work with struct RescaleJob { uint32_t width = 0; uint32_t height = 0; uint32_t channel_count = 0; RHI_Texture_Mip* mip = nullptr; bool done = false; RescaleJob(const uint32_t width, const uint32_t height, const uint32_t channel_count) { this->width = width; this->height = height; this->channel_count = channel_count; } }; static uint32_t get_bytes_per_channel(FIBITMAP* bitmap) { if (!bitmap) { LOG_ERROR_INVALID_PARAMETER(); return 0; } const auto type = FreeImage_GetImageType(bitmap); uint32_t size = 0; if (type == FIT_BITMAP) { size = sizeof(BYTE); } else if (type == FIT_UINT16 || type == FIT_RGB16 || type == FIT_RGBA16) { size = sizeof(WORD); } else if (type == FIT_FLOAT || type == FIT_RGBF || type == FIT_RGBAF) { size = sizeof(float); } return size; } static uint32_t get_channel_count(FIBITMAP* bitmap) { if (!bitmap) { LOG_ERROR_INVALID_PARAMETER(); return 0; } const uint32_t bytes_per_pixel = FreeImage_GetLine(bitmap) / FreeImage_GetWidth(bitmap); const uint32_t channel_count = bytes_per_pixel / get_bytes_per_channel(bitmap); return channel_count; } static RHI_Format get_rhi_format(const uint32_t bytes_per_channel, const uint32_t channel_count) { const uint32_t bits_per_channel = bytes_per_channel * 8; if (channel_count == 1) { if (bits_per_channel == 8) return RHI_Format_R8_Unorm; } else if (channel_count == 2) { if (bits_per_channel == 8) return RHI_Format_R8G8_Unorm; } else if (channel_count == 3) { if (bits_per_channel == 32) return RHI_Format_R32G32B32A32_Float; } else if (channel_count == 4) { if (bits_per_channel == 8) return RHI_Format_R8G8B8A8_Unorm; if (bits_per_channel == 16) return RHI_Format_R16G16B16A16_Float; if (bits_per_channel == 32) return RHI_Format_R32G32B32A32_Float; } LOG_ERROR("Could not deduce format"); return RHI_Format_Undefined; } static FIBITMAP* convert_to_32bits(FIBITMAP* bitmap) { if (!bitmap) { LOG_ERROR_INVALID_PARAMETER(); return nullptr; } const auto previous_bitmap = bitmap; bitmap = FreeImage_ConvertTo32Bits(previous_bitmap); if (!bitmap) { LOG_ERROR("Failed (%d bpp, %d channels).", FreeImage_GetBPP(previous_bitmap), get_channel_count(previous_bitmap)); return nullptr; } FreeImage_Unload(previous_bitmap); return bitmap; } static FIBITMAP* apply_bitmap_corrections(FIBITMAP* bitmap) { SP_ASSERT(bitmap != nullptr); // Convert to a standard bitmap. FIT_UINT16 and FIT_RGBA16 are processed without errors // but show up empty in the editor. For now, we convert everything to a standard bitmap. const FREE_IMAGE_TYPE type = FreeImage_GetImageType(bitmap); if (type != FIT_BITMAP) { // FreeImage can't convert FIT_RGBF if (type != FIT_RGBF) { const auto previous_bitmap = bitmap; bitmap = FreeImage_ConvertToType(bitmap, FIT_BITMAP); FreeImage_Unload(previous_bitmap); } } // Convert it to 32 bits (if lower) if (FreeImage_GetBPP(bitmap) < 32) { bitmap = convert_to_32bits(bitmap); } // Most GPUs can't use a 32 bit RGB texture as a color attachment. // Vulkan tells you, your GPU doesn't support it. // D3D11 seems to be doing some sort of emulation under the hood while throwing some warnings regarding sampling it. // So to prevent that, we maintain the 32 bits and convert to an RGBA format. const uint32_t image_bits_per_channel = get_bytes_per_channel(bitmap) * 8; const uint32_t image_channels = get_channel_count(bitmap); const bool is_r32g32b32_float = image_channels == 3 && image_bits_per_channel == 32; if (is_r32g32b32_float) { const auto previous_bitmap = bitmap; bitmap = FreeImage_ConvertToRGBAF(bitmap); FreeImage_Unload(previous_bitmap); } // Convert BGR to RGB (if needed) if (FreeImage_GetBPP(bitmap) == 32) { if (FreeImage_GetRedMask(bitmap) == 0xff0000 && get_channel_count(bitmap) >= 2) { if (!SwapRedBlue32(bitmap)) { LOG_ERROR("Failed to swap red with blue channel"); } } } // Flip it vertically FreeImage_FlipVertical(bitmap); return bitmap; } static FIBITMAP* rescale(FIBITMAP* bitmap, const uint32_t width, const uint32_t height) { if (!bitmap || width == 0 || height == 0) { LOG_ERROR_INVALID_PARAMETER(); return nullptr; } const auto previous_bitmap = bitmap; bitmap = FreeImage_Rescale(previous_bitmap, width, height, filter_downsample); if (!bitmap) { LOG_ERROR("Failed"); return previous_bitmap; } FreeImage_Unload(previous_bitmap); return bitmap; } ImageImporter::ImageImporter(Context* context) { // Initialize m_context = context; FreeImage_Initialise(); // Register error handler const auto free_image_error_handler = [](const FREE_IMAGE_FORMAT fif, const char* message) { const auto text = (message != nullptr) ? message : "Unknown error"; const auto format = (fif != FIF_UNKNOWN) ? FreeImage_GetFormatFromFIF(fif) : "Unknown"; LOG_ERROR("%s, Format: %s", text, format); }; FreeImage_SetOutputMessage(free_image_error_handler); // Get version m_context->GetSubsystem<Settings>()->RegisterThirdPartyLib("FreeImage", FreeImage_GetVersion(), "http://freeimage.sourceforge.net/download.html"); } ImageImporter::~ImageImporter() { FreeImage_DeInitialise(); } bool ImageImporter::Load(const string& file_path, const uint32_t slice_index, RHI_Texture* texture) { SP_ASSERT(texture != nullptr); if (!FileSystem::Exists(file_path)) { LOG_ERROR("Path \"%s\" is invalid.", file_path.c_str()); return false; } // Acquire image format FREE_IMAGE_FORMAT format = FreeImage_GetFileType(file_path.c_str(), 0); format = (format == FIF_UNKNOWN) ? FreeImage_GetFIFFromFilename(file_path.c_str()) : format; // If the format is unknown, try to work it out from the file path if (!FreeImage_FIFSupportsReading(format)) // If the format is still unknown, give up { LOG_ERROR("Unsupported format"); return false; } // Load the image auto bitmap = FreeImage_Load(format, file_path.c_str()); if (!bitmap) { LOG_ERROR("Failed to load \"%s\"", file_path.c_str()); return false; } // Deduce image properties. Important that this is done here, before ApplyBitmapCorrections(), as after that, results for grayscale seem to be always false const bool image_is_transparent = FreeImage_IsTransparent(bitmap); const bool image_is_grayscale = FreeImage_GetColorType(bitmap) == FREE_IMAGE_COLOR_TYPE::FIC_MINISBLACK; // Perform some fix ups bitmap = apply_bitmap_corrections(bitmap); if (!bitmap) { LOG_ERROR("Failed to apply bitmap corrections"); return false; } // Deduce image properties const uint32_t image_bytes_per_channel = get_bytes_per_channel(bitmap); const uint32_t image_channel_count = get_channel_count(bitmap); const RHI_Format image_format = get_rhi_format(image_bytes_per_channel, image_channel_count); // Perform any scaling (if necessary) const auto user_define_dimensions = (texture->GetWidth() != 0 && texture->GetHeight() != 0); const auto dimension_mismatch = (FreeImage_GetWidth(bitmap) != texture->GetWidth() && FreeImage_GetHeight(bitmap) != texture->GetHeight()); const auto scale = user_define_dimensions && dimension_mismatch; bitmap = scale ? rescale(bitmap, texture->GetWidth(), texture->GetHeight()) : bitmap; // Deduce image properties const unsigned int image_width = FreeImage_GetWidth(bitmap); const unsigned int image_height = FreeImage_GetHeight(bitmap); // Fill RGBA vector with the data from the FIBITMAP RHI_Texture_Mip& mip = texture->CreateMip(slice_index); GetBitsFromFibitmap(&mip, bitmap, image_width, image_height, image_channel_count); // If the texture supports mipmaps, generate them if (texture->GetFlags() & RHI_Texture_GenerateMipsWhenLoading) { GenerateMipmaps(bitmap, texture, image_width, image_height, image_channel_count, slice_index); } // Free memory FreeImage_Unload(bitmap); // Fill RHI_Texture with image properties texture->SetBitsPerChannel(image_bytes_per_channel * 8); texture->SetWidth(image_width); texture->SetHeight(image_height); texture->SetChannelCount(image_channel_count); texture->SetTransparency(image_is_transparent); texture->SetFormat(image_format); texture->SetGrayscale(image_is_grayscale); return true; } bool ImageImporter::GetBitsFromFibitmap(RHI_Texture_Mip* mip, FIBITMAP* bitmap, const uint32_t width, const uint32_t height, const uint32_t channels) const { // Validate SP_ASSERT(mip != nullptr); SP_ASSERT(width != 0); SP_ASSERT(height != 0); SP_ASSERT(channels != 0); // Compute expected data size and reserve enough memory const size_t size_bytes = width * height * channels * get_bytes_per_channel(bitmap); if (size_bytes != mip->bytes.size()) { mip->bytes.clear(); mip->bytes.reserve(size_bytes); mip->bytes.resize(size_bytes); } // Copy the data over to our vector const auto bits = FreeImage_GetBits(bitmap); memcpy(&mip->bytes[0], bits, size_bytes); return true; } void ImageImporter::GenerateMipmaps(FIBITMAP* bitmap, RHI_Texture* texture, uint32_t width, uint32_t height, uint32_t channels, const uint32_t slice_index) { // Validate SP_ASSERT(texture != nullptr); // Create a RescaleJob for every mip that we need vector<RescaleJob> jobs; while (width > 1 && height > 1) { width = Math::Helper::Max(width / 2, static_cast<uint32_t>(1)); height = Math::Helper::Max(height / 2, static_cast<uint32_t>(1)); jobs.emplace_back(width, height, channels); // Resize the RHI_Texture vector accordingly const auto size = width * height * channels; RHI_Texture_Mip& mip = texture->CreateMip(slice_index); mip.bytes.reserve(size); mip.bytes.resize(size); } // Pass data pointers (now that the RHI_Texture mip vector has been constructed) for (uint32_t i = 0; i < jobs.size(); i++) { // reminder: i + 1 because the 0 mip is the default image size jobs[i].mip = &texture->GetMip(0, i + 1); } // Parallelize mipmap generation using multiple threads (because FreeImage_Rescale() is expensive) auto threading = m_context->GetSubsystem<Threading>(); for (auto& job : jobs) { threading->AddTask([this, &job, &bitmap]() { FIBITMAP* bitmap_scaled = FreeImage_Rescale(bitmap, job.width, job.height, filter_downsample); if (!GetBitsFromFibitmap(job.mip, bitmap_scaled, job.width, job.height, job.channel_count)) { LOG_ERROR("Failed to create mip level %dx%d", job.width, job.height); } FreeImage_Unload(bitmap_scaled); job.done = true; }); } // Wait until all mipmaps have been generated auto ready = false; while (!ready) { ready = true; for (const auto& job : jobs) { if (!job.done) { ready = false; } } this_thread::sleep_for(chrono::milliseconds(16)); } } }
36.518337
189
0.601834
slimlime
1b1d68671ed680f0f527da6a34e540434d5ad10f
9,920
cpp
C++
src/logical_camera_plugin/src/logical_camera_plugin.cpp
brimoo/Robotics
9886d7146e9352a370bf00d8bfd0e7700e6a94fb
[ "BSD-2-Clause" ]
null
null
null
src/logical_camera_plugin/src/logical_camera_plugin.cpp
brimoo/Robotics
9886d7146e9352a370bf00d8bfd0e7700e6a94fb
[ "BSD-2-Clause" ]
null
null
null
src/logical_camera_plugin/src/logical_camera_plugin.cpp
brimoo/Robotics
9886d7146e9352a370bf00d8bfd0e7700e6a94fb
[ "BSD-2-Clause" ]
null
null
null
#include "logical_camera_plugin/logical_camera_plugin.hh" #include <gazebo/physics/Link.hh> #include <gazebo/physics/Model.hh> #include <gazebo/physics/World.hh> #include <gazebo/sensors/Sensor.hh> #include <gazebo/sensors/SensorManager.hh> #include "std_msgs/String.h" #include "logical_camera_plugin/logicalImage.h" #include <sstream> #include <string> #include <algorithm> using namespace gazebo; GZ_REGISTER_MODEL_PLUGIN(LogicalCameraPlugin); LogicalCameraPlugin::LogicalCameraPlugin() { } LogicalCameraPlugin::~LogicalCameraPlugin() { this->rosnode->shutdown(); } void LogicalCameraPlugin::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { gzdbg << "Called Load!" << "\n"; initTable(); this->robotNamespace = "logical_camera"; if(_sdf->HasElement("robotNamespace")) { this->robotNamespace = _sdf->GetElement("robotNamespace")->Get<std::string>() + "/"; } this->world = _parent->GetWorld(); this->name = _parent->GetName(); if (!ros::isInitialized()) { ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized," << "unable to load plugin. Load the Gazebo system plugin " << "'libgazebo_ros_api_plugin.so' in the gazebo_ros package)"); return; } this->modelFramePrefix = this->name + "_"; if (_sdf->HasElement("model_frame_prefix")) { this->modelFramePrefix = _sdf->GetElement("model_frame_prefix")->Get<std::string>(); } gzdbg << "Using model frame prefix of: " << this->modelFramePrefix << std::endl; this->model = _parent; this->node = transport::NodePtr(new transport::Node()); this->node->Init(this->model->GetWorld()->GetName()); this->rosnode = new ros::NodeHandle(this->robotNamespace); this->findLogicalCamera(); if ( !this->sensor) { gzerr << "No logical camera found on any link\n"; return; } for (int i=0;i<4;i++){ this->joint[i] = this->model->GetJoints()[i]; gzdbg << "Joints found are: " <<this->joint[i]->GetScopedName() << "\n"; } std::string imageTopic_ros = this->name; if (_sdf->HasElement("image_topic_ros")) { imageTopic_ros = _sdf->Get<std::string>("image_topic_ros"); } this->imageSub = this->node->Subscribe(this->sensor->Topic(), &LogicalCameraPlugin::onImage, this); gzdbg << "Subscribing to gazebo topic: "<< this->sensor->Topic() << "\n"; imagePub = this->rosnode->advertise<logical_camera_plugin::logicalImage>("/objectsDetected", 1000); gzdbg << "Publishing to ROS topic: " << imagePub.getTopic() << "\n"; transformBroadcaster = boost::shared_ptr<tf::TransformBroadcaster>(new tf::TransformBroadcaster()); } void LogicalCameraPlugin::initTable() { gzdbg << "Initializing hash table!" << "\n"; this->matchModel.emplace("intersection_33","West_se101"); this->matchModel.emplace("intersection_33_clone","West_se102"); this->matchModel.emplace("intersection_33_clone_14","North_se104"); this->matchModel.emplace("intersection_33_clone_13","West_se104"); this->matchModel.emplace("intersection_33_clone_12","West_se105"); this->matchModel.emplace("intersection_33_clone_11","East_se106"); this->matchModel.emplace("intersection_33_clone_10","se110"); this->matchModel.emplace("intersection_33_clone_9","se111"); this->matchModel.emplace("intersection_33_clone_0","se112"); this->matchModel.emplace("intersection_33_clone_8","se113"); this->matchModel.emplace("intersection_33_clone_7","se114"); this->matchModel.emplace("intersection_33_clone_1","se115"); this->matchModel.emplace("intersection_33_clone_2","se116"); this->matchModel.emplace("intersection_33_clone_6","se119"); this->matchModel.emplace("intersection_33_clone_3","se117"); this->matchModel.emplace("intersection_33_clone_4","se118"); this->matchModel.emplace("intersection_33_clone_5","se118"); this->matchModel.emplace("intersection_32","intersection_East_1a"); this->matchModel.emplace("intersection_31","intersection_West_1b"); this->matchModel.emplace("intersection_29","intersection_East_1b"); this->matchModel.emplace("intersection_37","intersection_North_1b"); this->matchModel.emplace("intersection_28","intersection_West_1c"); this->matchModel.emplace("intersection_30","intersection_East_1c"); this->matchModel.emplace("intersection_0","intersection_North_1c"); this->matchModel.emplace("intersection_34","intersection_West_1d"); this->matchModel.emplace("intersection_2","intersection_North_1d"); this->matchModel.emplace("intersection_38","intersection_South_2a"); this->matchModel.emplace("intersection_56","intersection_North_2a"); this->matchModel.emplace("intersection_3","intersection_West_2a"); this->matchModel.emplace("intersection_46","intersection_South_2c"); this->matchModel.emplace("intersection_9","intersection_East_2c"); this->matchModel.emplace("intersection_45","intersection_North_2c"); this->matchModel.emplace("intersection_45_clone","intersection_South_2d"); this->matchModel.emplace("intersection_4","intersection_North_2d"); this->matchModel.emplace("intersection_8","intersection_West_2d"); this->matchModel.emplace("intersection_58","intersection_East6_101"); this->matchModel.emplace("intersection_40","intersection_South7_104"); this->matchModel.emplace("intersection_41","intersection_East_104"); this->matchModel.emplace("intersection_35","intersection_South__4i"); this->matchModel.emplace("intersection_36","intersection_North__4i"); this->matchModel.emplace("intersection_1","intersection_West__4i"); this->matchModel.emplace("intersection_36_clone","intersection_South__4h"); this->matchModel.emplace("intersection_39","intersection_North__4h"); this->matchModel.emplace("intersection_10","intersection_West__4h"); this->matchModel.emplace("corridor","corridor_1a"); this->matchModel.emplace("corridor_0","corridor_1b"); this->matchModel.emplace("corridor_1","corridor_1c"); this->matchModel.emplace("corridor_2","corridor_1d"); this->matchModel.emplace("corridor_22","corridor_2a"); this->matchModel.emplace("corridor_23","corridor_2b"); this->matchModel.emplace("corridor_19","corridor_2c"); this->matchModel.emplace("corridor_18","corridor_2d"); this->matchModel.emplace("corridor_13","corridor_2e"); this->matchModel.emplace("corridor_11","corridor_2f"); this->matchModel.emplace("corridor_10","corridor_2g"); this->matchModel.emplace("corridor_6","corridor_2h"); this->matchModel.emplace("corridor_4","corridor_3a"); this->matchModel.emplace("corridor_3","corridor_3b"); this->matchModel.emplace("corridor_5","corridor_3c"); this->matchModel.emplace("corridor_9","corridor_4a"); this->matchModel.emplace("corridor_8","corridor_4b"); this->matchModel.emplace("corridor_7","corridor_4c"); this->matchModel.emplace("corridor_14","corridor_4d"); this->matchModel.emplace("corridor_15","corridor_4e"); this->matchModel.emplace("corridor_16","corridor_4f"); this->matchModel.emplace("corridor_17","corridor_4g"); this->matchModel.emplace("corridor_20","corridor_4h"); this->matchModel.emplace("corridor_21","corridor_4i"); } string LogicalCameraPlugin::checkIfRoom(string modelName){ unordered_map<string,string>::const_iterator map_find = this->matchModel.find(modelName); if ( map_find == this->matchModel.end() ) { gzdbg << "This is not a model to identify room: " << modelName << "!\n"; return modelName; } else { gzdbg << "Matched the model " << map_find->first << "for a room: " << map_find->second << "!\n"; return map_find->second; } } void LogicalCameraPlugin::findLogicalCamera() { sensors::SensorManager* sensorManager = sensors::SensorManager::Instance(); for (physics::LinkPtr link : this->model->GetLinks()) { for (unsigned int i =0; i < link->GetSensorCount(); ++i) { sensors::SensorPtr sensor = sensorManager->GetSensor(link->GetSensorName(i)); if (sensor->Type() == "logical_camera") { this->sensor = sensor; break; } } if (this->sensor) { this->cameraLink = link; break; } } } void LogicalCameraPlugin::onImage(ConstLogicalCameraImagePtr &_msg) { gazebo::msgs::LogicalCameraImage imageMsg; math::Vector3 modelPosition; math::Quaternion modelOrientation; math::Pose modelPose; for (int i = 0;i < _msg->model_size();++i) { modelPosition = math::Vector3(msgs::ConvertIgn(_msg->model(i).pose().position())); modelOrientation = math::Quaternion(msgs::ConvertIgn(_msg->model(i).pose().orientation())); modelPose = math::Pose(modelPosition, modelOrientation); std::string modelName = _msg->model(i).name(); std::string modelFrameId = this->modelFramePrefix + modelName + "harsha"; if ( modelName != "asphalt_plane" && modelName.find("jersey_barrier") ==string::npos && modelName != "ground_plane" ) { //if ( modelName != "se1f1" ) { gzdbg << "Model detected: " << modelName << "with pose" << modelPose << "\n"; //this->publishTF(modelPose, this->name,modelFrameId); logical_camera_plugin::logicalImage msg; string finModelName = checkIfRoom(modelName); msg.modelName = finModelName; msg.pose_pos_x = modelPose.pos.x; msg.pose_pos_y = modelPose.pos.y; msg.pose_pos_z = modelPose.pos.z; msg.pose_rot_x = modelPose.rot.x; msg.pose_rot_y = modelPose.rot.y; msg.pose_rot_z = modelPose.rot.z; msg.pose_rot_w = modelPose.rot.w; this->imagePub.publish(msg); } } } void LogicalCameraPlugin::publishTF( const math::Pose &pose, const std::string &parentFrame, const std::string &frame) { ros::Time currentTime = ros::Time::now(); tf::Quaternion qt(pose.rot.x, pose.rot.y, pose.rot.z, pose.rot.w); tf::Vector3 vt(pose.pos.x, pose.pos.y, pose.pos.z); tf::Transform transform(qt, vt); transformBroadcaster->sendTransform(tf::StampedTransform(transform, currentTime, parentFrame, frame)); }
36.877323
125
0.719052
brimoo
1b1f432683175f3753b72f8c9853fec747556e13
2,028
hpp
C++
include/nanorange/algorithm/min_element.hpp
paulbendixen/NanoRange
993dc03ebb2d3de5395648f3c0d112d230127c65
[ "BSL-1.0" ]
null
null
null
include/nanorange/algorithm/min_element.hpp
paulbendixen/NanoRange
993dc03ebb2d3de5395648f3c0d112d230127c65
[ "BSL-1.0" ]
null
null
null
include/nanorange/algorithm/min_element.hpp
paulbendixen/NanoRange
993dc03ebb2d3de5395648f3c0d112d230127c65
[ "BSL-1.0" ]
null
null
null
// nanorange/algorithm/min_element.hpp // // Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail dot com) // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef NANORANGE_ALGORITHM_MIN_ELEMENT_HPP_INCLUDED #define NANORANGE_ALGORITHM_MIN_ELEMENT_HPP_INCLUDED #include <nanorange/ranges.hpp> NANO_BEGIN_NAMESPACE namespace detail { struct min_element_fn { private: friend struct nth_element_fn; template <typename I, typename S, typename Comp, typename Proj> static constexpr I impl(I first, S last, Comp& comp, Proj& proj) { if (first == last) { return first; } I i = nano::next(first); while (i != last) { if (nano::invoke(comp, nano::invoke(proj, *i), nano::invoke(proj, *first))) { first = i; } ++i; } return first; } public: template <typename I, typename S, typename Comp = ranges::less, typename Proj = identity> constexpr std::enable_if_t< forward_iterator<I> && sentinel_for<S, I> && indirect_strict_weak_order<Comp, projected<I, Proj>>, I> operator()(I first, S last, Comp comp = Comp{}, Proj proj = Proj{}) const { return min_element_fn::impl(std::move(first), std::move(last), comp, proj); } template <typename Rng, typename Comp = ranges::less, typename Proj = identity> constexpr std::enable_if_t< forward_range<Rng> && indirect_strict_weak_order<Comp, projected<iterator_t<Rng>, Proj>>, safe_iterator_t<Rng>> operator()(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}) const { return min_element_fn::impl(nano::begin(rng), nano::end(rng), comp, proj); } }; } NANO_INLINE_VAR(detail::min_element_fn, min_element) NANO_END_NAMESPACE #endif
28.971429
83
0.611933
paulbendixen
1b2102649b8327917e9f3305a46ab5cea968329c
632
cpp
C++
Kattis_Problems/MosiquitoMultiplication.cpp
MAXI0008/Kattis-Problems
ff6ec752b741a56fc37a993c528fc925ca302cc8
[ "MIT" ]
3
2019-04-01T05:38:09.000Z
2021-11-17T11:43:20.000Z
Kattis_Problems/MosiquitoMultiplication.cpp
MAXI0008/Algorithms-Practices
ff6ec752b741a56fc37a993c528fc925ca302cc8
[ "MIT" ]
null
null
null
Kattis_Problems/MosiquitoMultiplication.cpp
MAXI0008/Algorithms-Practices
ff6ec752b741a56fc37a993c528fc925ca302cc8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #define FOR(i, a, b) for(int (i) = (a); (i) <= (b); (i)++) int main() { int M, P, L, E, R, S, N; int pre_M; int pre_L; int pre_P; while (cin >> M && cin >> P && cin >> L && cin >> E && cin >> R && cin >> S && cin >> N) { FOR(i, 0, N - 1) { pre_M = M; pre_L = L; pre_P = P; M -= pre_M; L += pre_M * E; L -= pre_L; P += (int)(((1 / (double)R)) * pre_L); P -= pre_P; M += (int)(((1 / (double)S)) * pre_P); } cout << M << endl; } }
20.387097
94
0.351266
MAXI0008
1b22d1c2d3a704e52f4de711ce5baac8cb8b4d86
3,179
cc
C++
src/gui/plugins/transform_control/TransformControl.cc
ForrestHurley/ign-gazebo
8c748eac85e652aad1bafb02928a6f01ea5683af
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/gui/plugins/transform_control/TransformControl.cc
ForrestHurley/ign-gazebo
8c748eac85e652aad1bafb02928a6f01ea5683af
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/gui/plugins/transform_control/TransformControl.cc
ForrestHurley/ign-gazebo
8c748eac85e652aad1bafb02928a6f01ea5683af
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 Open Source Robotics Foundation * * 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 <ignition/msgs/boolean.pb.h> #include <ignition/msgs/stringmsg.pb.h> #include <iostream> #include <ignition/common/Console.hh> #include <ignition/gui/Application.hh> #include <ignition/gui/MainWindow.hh> #include <ignition/plugin/Register.hh> #include <ignition/transport/Node.hh> #include <ignition/transport/Publisher.hh> #include "ignition/gazebo/components/Name.hh" #include "ignition/gazebo/components/ParentEntity.hh" #include "ignition/gazebo/EntityComponentManager.hh" #include "ignition/gazebo/gui/GuiEvents.hh" #include "TransformControl.hh" namespace ignition::gazebo { class TransformControlPrivate { /// \brief Ignition communication node. public: transport::Node node; /// \brief Mutex to protect mode public: std::mutex mutex; /// \brief Transform control service name public: std::string service; }; } using namespace ignition; using namespace gazebo; ///////////////////////////////////////////////// TransformControl::TransformControl() : ignition::gui::Plugin(), dataPtr(std::make_unique<TransformControlPrivate>()) { } ///////////////////////////////////////////////// TransformControl::~TransformControl() = default; ///////////////////////////////////////////////// void TransformControl::LoadConfig(const tinyxml2::XMLElement *) { if (this->title.empty()) this->title = "Transform control"; // For transform requests this->dataPtr->service = "/gui/transform_mode"; } ///////////////////////////////////////////////// void TransformControl::OnSnapUpdate( double _x, double _y, double _z, double _roll, double _pitch, double _yaw, double _scaleX, double _scaleY, double _scaleZ) { auto event = new gui::events::SnapIntervals( math::Vector3d(_x, _y, _z), math::Vector3d(_roll, _pitch, _yaw), math::Vector3d(_scaleX, _scaleY, _scaleZ)); ignition::gui::App()->sendEvent( ignition::gui::App()->findChild<ignition::gui::MainWindow *>(), event); } ///////////////////////////////////////////////// void TransformControl::OnMode(const QString &_mode) { std::function<void(const ignition::msgs::Boolean &, const bool)> cb = [](const ignition::msgs::Boolean &/*_rep*/, const bool _result) { if (!_result) ignerr << "Error setting transform mode" << std::endl; }; ignition::msgs::StringMsg req; req.set_data(_mode.toStdString()); this->dataPtr->node.Request(this->dataPtr->service, req, cb); } // Register this plugin IGNITION_ADD_PLUGIN(ignition::gazebo::TransformControl, ignition::gui::Plugin)
30.567308
77
0.662472
ForrestHurley
1b22d3d8058cbc13b2f313ae6a9a9071f0727ba4
268
cpp
C++
(1)Beginner/1174/c++/1174.cpp
G4DavidAlmeida/mySolutionsUriOnline
47e427e3205124da00a8a44fb9900086d85c30ec
[ "MIT" ]
null
null
null
(1)Beginner/1174/c++/1174.cpp
G4DavidAlmeida/mySolutionsUriOnline
47e427e3205124da00a8a44fb9900086d85c30ec
[ "MIT" ]
null
null
null
(1)Beginner/1174/c++/1174.cpp
G4DavidAlmeida/mySolutionsUriOnline
47e427e3205124da00a8a44fb9900086d85c30ec
[ "MIT" ]
null
null
null
#include<iostream> #include<iomanip> using namespace std; int main(){ double x[100]; int i; for(i=0;i<100;i++)cin >> x[i]; for(i=0;i<100;i++){ if(x[i]<=10){ cout << "A[" << i << "] = " << fixed << setprecision(1) << x[i] << endl; } } return 0; }
14.105263
76
0.503731
G4DavidAlmeida
1b23af7d6f946985e4d8751b28ec07c5d8e08820
2,670
cpp
C++
src/tests/test_mutex.cpp
OnikenX/SO2-notes
fb106cb46453baa61b16fc17fdf8aab54541ebc9
[ "MIT" ]
null
null
null
src/tests/test_mutex.cpp
OnikenX/SO2-notes
fb106cb46453baa61b16fc17fdf8aab54541ebc9
[ "MIT" ]
null
null
null
src/tests/test_mutex.cpp
OnikenX/SO2-notes
fb106cb46453baa61b16fc17fdf8aab54541ebc9
[ "MIT" ]
null
null
null
#include <windows.h> #include <stdio.h> #define THREADCOUNT 2 HANDLE ghMutex; DWORD WINAPI WriteToDatabase( LPVOID ); int main( void ) { HANDLE aThread[THREADCOUNT]; DWORD ThreadID; int i; // Create a mutex with no initial owner ghMutex = CreateMutex( NULL, // default security attributes FALSE, // initially not owned NULL); // unnamed mutex if (ghMutex == NULL) { printf("CreateMutex error: %d\n", GetLastError()); return 1; } // Create worker threads for( i=0; i < THREADCOUNT; i++ ) { aThread[i] = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE) WriteToDatabase, NULL, // no thread function arguments 0, // default creation flags &ThreadID); // receive thread identifier if( aThread[i] == NULL ) { printf("CreateThread error: %d\n", GetLastError()); return 1; } } // Wait for all threads to terminate WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE); // Close thread and mutex handles for( i=0; i < THREADCOUNT; i++ ) CloseHandle(aThread[i]); CloseHandle(ghMutex); return 0; } DWORD WINAPI WriteToDatabase( LPVOID lpParam ) { // lpParam not used in this example UNREFERENCED_PARAMETER(lpParam); DWORD dwCount=0, dwWaitResult; // Request ownership of mutex. while( dwCount < 20 ) { dwWaitResult = WaitForSingleObject( ghMutex, // handle to mutex INFINITE); // no time-out interval switch (dwWaitResult) { // The thread got ownership of the mutex case WAIT_OBJECT_0: __try { // TODO: Write to the database printf("Thread %d writing to database...\n", GetCurrentThreadId()); dwCount++; } __finally { // Release ownership of the mutex object if (! ReleaseMutex(ghMutex)) { // Handle error. } } break; // The thread got ownership of an abandoned mutex // The database is in an indeterminate state case WAIT_ABANDONED: return FALSE; } } return TRUE; }
25.673077
65
0.499625
OnikenX
1b2688575d9fca5eb44b23be640d94591e0bbacd
336
cpp
C++
src/common/file_util.cpp
cugdc/Jumpy-Thieves
fc5a68ed6854dd9a057d433910ccfb1f6031256e
[ "Apache-2.0" ]
2
2020-03-21T09:49:27.000Z
2020-03-31T16:59:59.000Z
src/common/file_util.cpp
cugdc/Jumpy-Thieves
fc5a68ed6854dd9a057d433910ccfb1f6031256e
[ "Apache-2.0" ]
null
null
null
src/common/file_util.cpp
cugdc/Jumpy-Thieves
fc5a68ed6854dd9a057d433910ccfb1f6031256e
[ "Apache-2.0" ]
null
null
null
#include "file_util.hpp" auto read_file(std::string_view path) -> std::string { std::ifstream file{path.data()}; if (!file.is_open()) { spdlog::error("Cannot open file {}\n", path); std::fflush(stdout); } std::stringstream ss; // read file's buffer contents into streams ss << file.rdbuf(); return ss.str(); }
18.666667
52
0.633929
cugdc
1b2b98101105315bf3d6eaae77eb3c1ef04e2077
1,782
hpp
C++
src/Rect.hpp
JesseMaurais/SGe
f73bd03d30074a54642847b05f82151128481371
[ "MIT" ]
1
2017-04-20T06:27:36.000Z
2017-04-20T06:27:36.000Z
src/Rect.hpp
JesseMaurais/SGe
f73bd03d30074a54642847b05f82151128481371
[ "MIT" ]
null
null
null
src/Rect.hpp
JesseMaurais/SGe
f73bd03d30074a54642847b05f82151128481371
[ "MIT" ]
null
null
null
#ifndef Rect_hpp #define Rect_hpp #include "SDL.hpp" #include <vector> #include <utility> namespace SDL { using namespace std::rel_ops; struct Size { int w, h; }; using Point = SDL_Point; using Rect = SDL_Rect; using Points = std::vector<Point>; using Rects = std::vector<Rect>; using Line = std::pair<Point, Point>; using Lines = std::vector<Line>; using Sizes = std::vector<Size>; inline bool operator!(Rect const &A) { return SDL_RectEmpty(&A); } inline bool operator<(Rect const &A, Rect const &B) { return A.w < B.w and A.h < B.h and A.x > B.x and A.y > B.y; } inline bool operator==(Rect const &A, Rect const &B) { return SDL_RectEquals(&A, &B); } inline bool operator&&(Rect const &A, Rect const &B) { return SDL_HasIntersection(&A, &B); } inline bool operator&&(Rect const &A, Point const &B) { return SDL_PointInRect(&B, &A); } inline bool operator&&(Rect const &A, Line B) { return SDL_IntersectRectAndLine(&A, &B.first.x, &B.first.y, &B.second.x, &B.second.y); } inline Line operator&(Rect const &A, Line B) { if (not SDL_IntersectRectAndLine(&A, &B.first.x, &B.first.y, &B.second.x, &B.second.y)) { B.first.x = B.first.y = B.second.x = B.second.y = 0; } return B; } inline Rect operator&(Rect const &A, Rect const &B) { Rect C; if (not SDL_IntersectRect(&A, &B, &C)) { C.x = C.y = C.w = C.h = 0; } return C; } inline Rect operator|(Rect const &A, Rect const &B) { Rect C; SDL_UnionRect(&A, &B, &C); return C; } } #endif // file
21.46988
95
0.540404
JesseMaurais
1b2d111e3006f2d2d8e266b63978175dbc3a4f73
11,793
cc
C++
Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
Calibration/EcalCalibAlgos/src/ECALpedestalPCLHarvester.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
// system include files #include <memory> // user include files #include "Calibration/EcalCalibAlgos/interface/ECALpedestalPCLHarvester.h" #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/EventSetup.h" #include "CondFormats/EcalObjects/interface/EcalChannelStatus.h" #include "CondFormats/EcalObjects/interface/EcalChannelStatusCode.h" #include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h" #include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h" #include "CommonTools/Utils/interface/StringToEnumValue.h" #include <iostream> #include <string> ECALpedestalPCLHarvester::ECALpedestalPCLHarvester(const edm::ParameterSet& ps) : currentPedestals_(nullptr), channelStatus_(nullptr) { chStatusToExclude_ = StringToEnumValue<EcalChannelStatusCode::Code>( ps.getParameter<std::vector<std::string> >("ChannelStatusToExclude")); minEntries_ = ps.getParameter<int>("MinEntries"); checkAnomalies_ = ps.getParameter<bool>("checkAnomalies"); nSigma_ = ps.getParameter<double>("nSigma"); thresholdAnomalies_ = ps.getParameter<double>("thresholdAnomalies"); dqmDir_ = ps.getParameter<std::string>("dqmDir"); labelG6G1_ = ps.getParameter<std::string>("labelG6G1"); threshDiffEB_ = ps.getParameter<double>("threshDiffEB"); threshDiffEE_ = ps.getParameter<double>("threshDiffEE"); threshChannelsAnalyzed_ = ps.getParameter<double>("threshChannelsAnalyzed"); } void ECALpedestalPCLHarvester::dqmEndJob(DQMStore::IBooker& ibooker_, DQMStore::IGetter& igetter_) { // calculate pedestals and fill db record EcalPedestals pedestals; float kBarrelSize = 61200; float kEndcapSize = 2 * 7324; float skipped_channels_EB = 0; float skipped_channels_EE = 0; for (uint16_t i = 0; i < EBDetId::kSizeForDenseIndexing; ++i) { std::string hname = dqmDir_ + "/EB/" + std::to_string(int(i / 100)) + "/eb_" + std::to_string(i); MonitorElement* ch = igetter_.get(hname); if (ch == nullptr) { edm::LogWarning("MissingMonitorElement") << "failed to find MonitorElement " << hname; entriesEB_[i] = 0; continue; } double mean = ch->getMean(); double rms = ch->getRMS(); entriesEB_[i] = ch->getEntries(); DetId id = EBDetId::detIdFromDenseIndex(i); EcalPedestal ped; EcalPedestal oldped = *currentPedestals_->find(id.rawId()); EcalPedestal g6g1ped = *g6g1Pedestals_->find(id.rawId()); ped.mean_x12 = mean; ped.rms_x12 = rms; float diff = std::abs(mean - oldped.mean_x12); // if bad channel or low stat skip or the difference is too large wrt to previous record if (ch->getEntries() < minEntries_ || !checkStatusCode(id) || diff > threshDiffEB_) { ped.mean_x12 = oldped.mean_x12; ped.rms_x12 = oldped.rms_x12; skipped_channels_EB++; } // copy g6 and g1 from the corressponding record ped.mean_x6 = g6g1ped.mean_x6; ped.rms_x6 = g6g1ped.rms_x6; ped.mean_x1 = g6g1ped.mean_x1; ped.rms_x1 = g6g1ped.rms_x1; pedestals.setValue(id.rawId(), ped); } for (uint16_t i = 0; i < EEDetId::kSizeForDenseIndexing; ++i) { std::string hname = dqmDir_ + "/EE/" + std::to_string(int(i / 100)) + "/ee_" + std::to_string(i); MonitorElement* ch = igetter_.get(hname); if (ch == nullptr) { edm::LogWarning("MissingMonitorElement") << "failed to find MonitorElement " << hname; entriesEE_[i] = 0; continue; } double mean = ch->getMean(); double rms = ch->getRMS(); entriesEE_[i] = ch->getEntries(); DetId id = EEDetId::detIdFromDenseIndex(i); EcalPedestal ped; EcalPedestal oldped = *currentPedestals_->find(id.rawId()); EcalPedestal g6g1ped = *g6g1Pedestals_->find(id.rawId()); ped.mean_x12 = mean; ped.rms_x12 = rms; float diff = std::abs(mean - oldped.mean_x12); // if bad channel or low stat skip or the difference is too large wrt to previous record if (ch->getEntries() < minEntries_ || !checkStatusCode(id) || diff > threshDiffEE_) { ped.mean_x12 = oldped.mean_x12; ped.rms_x12 = oldped.rms_x12; skipped_channels_EE++; } // copy g6 and g1 pedestals from corresponding record ped.mean_x6 = g6g1ped.mean_x6; ped.rms_x6 = g6g1ped.rms_x6; ped.mean_x1 = g6g1ped.mean_x1; ped.rms_x1 = g6g1ped.rms_x1; pedestals.setValue(id.rawId(), ped); } bool enough_stat = false; if ((kBarrelSize - skipped_channels_EB) / kBarrelSize > threshChannelsAnalyzed_ && (kEndcapSize - skipped_channels_EE) / kEndcapSize > threshChannelsAnalyzed_) { enough_stat = true; } dqmPlots(pedestals, ibooker_); // check if there are large variations wrt exisiting pedstals if (checkAnomalies_) { if (checkVariation(*currentPedestals_, pedestals)) { edm::LogError("Large Variations found wrt to old pedestals, no file created"); return; } } if (!enough_stat) return; // write out pedestal record edm::Service<cond::service::PoolDBOutputService> poolDbService; if (!poolDbService.isAvailable()) { throw std::runtime_error("PoolDBService required."); } poolDbService->writeOne(&pedestals, poolDbService->currentTime(), "EcalPedestalsRcd"); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void ECALpedestalPCLHarvester::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } void ECALpedestalPCLHarvester::endRun(edm::Run const& run, edm::EventSetup const& isetup) { edm::ESHandle<EcalChannelStatus> chStatus; isetup.get<EcalChannelStatusRcd>().get(chStatus); channelStatus_ = chStatus.product(); edm::ESHandle<EcalPedestals> peds; isetup.get<EcalPedestalsRcd>().get(peds); currentPedestals_ = peds.product(); edm::ESHandle<EcalPedestals> g6g1peds; isetup.get<EcalPedestalsRcd>().get(labelG6G1_, g6g1peds); g6g1Pedestals_ = g6g1peds.product(); } bool ECALpedestalPCLHarvester::checkStatusCode(const DetId& id) { EcalChannelStatusMap::const_iterator dbstatusPtr; dbstatusPtr = channelStatus_->getMap().find(id.rawId()); EcalChannelStatusCode::Code dbstatus = dbstatusPtr->getStatusCode(); std::vector<int>::const_iterator res = std::find(chStatusToExclude_.begin(), chStatusToExclude_.end(), dbstatus); if (res != chStatusToExclude_.end()) return false; return true; } bool ECALpedestalPCLHarvester::isGood(const DetId& id) { EcalChannelStatusMap::const_iterator dbstatusPtr; dbstatusPtr = channelStatus_->getMap().find(id.rawId()); if (dbstatusPtr == channelStatus_->getMap().end()) edm::LogError("Invalid DetId supplied"); EcalChannelStatusCode::Code dbstatus = dbstatusPtr->getStatusCode(); if (dbstatus == 0) return true; return false; } bool ECALpedestalPCLHarvester::checkVariation(const EcalPedestalsMap& oldPedestals, const EcalPedestalsMap& newPedestals) { uint32_t nAnomaliesEB = 0; uint32_t nAnomaliesEE = 0; for (uint16_t i = 0; i < EBDetId::kSizeForDenseIndexing; ++i) { DetId id = EBDetId::detIdFromDenseIndex(i); const EcalPedestal& newped = *newPedestals.find(id.rawId()); const EcalPedestal& oldped = *oldPedestals.find(id.rawId()); if (std::abs(newped.mean_x12 - oldped.mean_x12) > nSigma_ * oldped.rms_x12) nAnomaliesEB++; } for (uint16_t i = 0; i < EEDetId::kSizeForDenseIndexing; ++i) { DetId id = EEDetId::detIdFromDenseIndex(i); const EcalPedestal& newped = *newPedestals.find(id.rawId()); const EcalPedestal& oldped = *oldPedestals.find(id.rawId()); if (std::abs(newped.mean_x12 - oldped.mean_x12) > nSigma_ * oldped.rms_x12) nAnomaliesEE++; } if (nAnomaliesEB > thresholdAnomalies_ * EBDetId::kSizeForDenseIndexing || nAnomaliesEE > thresholdAnomalies_ * EEDetId::kSizeForDenseIndexing) return true; return false; } void ECALpedestalPCLHarvester::dqmPlots(const EcalPedestals& newpeds, DQMStore::IBooker& ibooker) { ibooker.cd(); ibooker.setCurrentFolder(dqmDir_ + "/Summary"); MonitorElement* pmeb = ibooker.book2D("meaneb", "Pedestal Means EB", 360, 1., 361., 171, -85., 86.); MonitorElement* preb = ibooker.book2D("rmseb", "Pedestal RMS EB ", 360, 1., 361., 171, -85., 86.); MonitorElement* pmeep = ibooker.book2D("meaneep", "Pedestal Means EEP", 100, 1, 101, 100, 1, 101); MonitorElement* preep = ibooker.book2D("rmseep", "Pedestal RMS EEP", 100, 1, 101, 100, 1, 101); MonitorElement* pmeem = ibooker.book2D("meaneem", "Pedestal Means EEM", 100, 1, 101, 100, 1, 101); MonitorElement* preem = ibooker.book2D("rmseem", "Pedestal RMS EEM", 100, 1, 101, 100, 1, 101); MonitorElement* pmebd = ibooker.book2D("meanebdiff", "Abs Rel Pedestal Means Diff EB", 360, 1., 361., 171, -85., 86.); MonitorElement* prebd = ibooker.book2D("rmsebdiff", "Abs Rel Pedestal RMS Diff E ", 360, 1., 361., 171, -85., 86.); MonitorElement* pmeepd = ibooker.book2D("meaneepdiff", "Abs Rel Pedestal Means Diff EEP", 100, 1, 101, 100, 1, 101); MonitorElement* preepd = ibooker.book2D("rmseepdiff", "Abs Rel Pedestal RMS Diff EEP", 100, 1, 101, 100, 1, 101); MonitorElement* pmeemd = ibooker.book2D("meaneemdiff", "Abs Rel Pedestal Means Diff EEM", 100, 1, 101, 100, 1, 101); MonitorElement* preemd = ibooker.book2D("rmseemdiff", "Abs RelPedestal RMS Diff EEM", 100, 1, 101, 100, 1, 101); MonitorElement* poeb = ibooker.book2D("occeb", "Occupancy EB", 360, 1., 361., 171, -85., 86.); MonitorElement* poeep = ibooker.book2D("occeep", "Occupancy EEP", 100, 1, 101, 100, 1, 101); MonitorElement* poeem = ibooker.book2D("occeem", "Occupancy EEM", 100, 1, 101, 100, 1, 101); MonitorElement* hdiffeb = ibooker.book1D("diffeb", "Pedestal Differences EB", 100, -2.5, 2.5); MonitorElement* hdiffee = ibooker.book1D("diffee", "Pedestal Differences EE", 100, -2.5, 2.5); for (int hash = 0; hash < EBDetId::kSizeForDenseIndexing; ++hash) { EBDetId di = EBDetId::detIdFromDenseIndex(hash); float mean = newpeds[di].mean_x12; float rms = newpeds[di].rms_x12; float cmean = (*currentPedestals_)[di].mean_x12; float crms = (*currentPedestals_)[di].rms_x12; if (!isGood(di)) continue; // only good channels are plotted pmeb->Fill(di.iphi(), di.ieta(), mean); preb->Fill(di.iphi(), di.ieta(), rms); if (cmean) pmebd->Fill(di.iphi(), di.ieta(), std::abs(mean - cmean) / cmean); if (crms) prebd->Fill(di.iphi(), di.ieta(), std::abs(rms - crms) / crms); poeb->Fill(di.iphi(), di.ieta(), entriesEB_[hash]); hdiffeb->Fill(mean - cmean); } for (int hash = 0; hash < EEDetId::kSizeForDenseIndexing; ++hash) { EEDetId di = EEDetId::detIdFromDenseIndex(hash); float mean = newpeds[di].mean_x12; float rms = newpeds[di].rms_x12; float cmean = (*currentPedestals_)[di].mean_x12; float crms = (*currentPedestals_)[di].rms_x12; if (!isGood(di)) continue; // only good channels are plotted if (di.zside() > 0) { pmeep->Fill(di.ix(), di.iy(), mean); preep->Fill(di.ix(), di.iy(), rms); poeep->Fill(di.ix(), di.iy(), entriesEE_[hash]); if (cmean) pmeepd->Fill(di.ix(), di.iy(), std::abs(mean - cmean) / cmean); if (crms) preepd->Fill(di.ix(), di.iy(), std::abs(rms - crms) / crms); } else { pmeem->Fill(di.ix(), di.iy(), mean); preem->Fill(di.ix(), di.iy(), rms); if (cmean) pmeemd->Fill(di.ix(), di.iy(), std::abs(mean - cmean) / cmean); poeem->Fill(di.ix(), di.iy(), entriesEE_[hash]); if (crms) preemd->Fill(di.ix(), di.iy(), std::abs(rms - crms) / crms); } hdiffee->Fill(mean - cmean); } }
38.792763
120
0.684389
ckamtsikis
1b2f38e0e299b0cfe98825544ad980435b2968e8
1,313
cpp
C++
4.3A.cpp
SushmaNagaraj/Coding
9ec85c117fceb6b77512b0af513671bb8adce815
[ "Apache-2.0" ]
1
2019-05-19T19:59:55.000Z
2019-05-19T19:59:55.000Z
4.3A.cpp
SushmaNagaraj/Coding
9ec85c117fceb6b77512b0af513671bb8adce815
[ "Apache-2.0" ]
null
null
null
4.3A.cpp
SushmaNagaraj/Coding
9ec85c117fceb6b77512b0af513671bb8adce815
[ "Apache-2.0" ]
null
null
null
/** Given pointers start and end that point to the first and past the last element of a segment inside an array, reverse all elements in the segment. */ void reverse(int* start, int* end) { int * tempEnd = end-1; while(start < tempEnd) { int temp = *start; *start = *tempEnd; *tempEnd = temp; start++; tempEnd--; } } #include <iostream> using namespace std; void reverse(int* start, int* end); void print(int* a, int n) { cout << "{"; for (int i = 0; i < n; i++) { cout << " " << a[i]; if (i < n - 1) cout << ","; } cout << " }" << endl; } int main() { int a[] = { 5, 1, 4, 9, -4, 8, -9, 0 }; reverse(a + 1, a + 5); print(a, sizeof(a) / sizeof(a[0])); cout << "Expected: { 5, -4, 9, 4, 1, 8, -9, 0 }" << endl; int b[] = { 1, 4, 9, 0 }; reverse(b + 1, b + 4); print(b, sizeof(b) / sizeof(b[0])); cout << "Expected: { 1, 0, 9, 4 }" << endl; int c[] = { 12, 13 }; reverse(c, c + 1); print(c, sizeof(c) / sizeof(c[0])); cout << "Expected: { 12, 13 }" << endl; int d[] = { 14, 15 }; reverse(d, d); print(d, sizeof(d) / sizeof(d[0])); cout << "Expected: { 14, 15 }" << endl; return 0; }
20.84127
61
0.450114
SushmaNagaraj
1b2f85a1efd4185d3a0a3898bc24641c1d85851f
1,773
cpp
C++
src/omwmm/extractor.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/extractor.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/extractor.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
#include <omwmm/extractor.hpp> #include <filesystem> #include <memory> #include <string> #include <string_view> #include <unordered_map> #include <algorithm> #include <cctype> #include <7zpp/7zpp.h> #include <omwmm/exceptions.hpp> using SevenZip::SevenZipLibrary; using SevenZip::SevenZipExtractor; using SevenZipString = SevenZip::TString; using SevenZip::CompressionFormat; using SevenZip::CompressionFormatEnum; namespace fs = std::filesystem; namespace omwmm { using namespace exceptions; Extractor::Extractor() : _data(SevenZipLibrary()) { auto lzma_lib = std::any_cast<SevenZipLibrary>(&_data); if (!lzma_lib->Load()) throw ExtractorException("Failed to load 7z dll"); } static const std::unordered_map<std::string_view, CompressionFormatEnum> extensions{ {".7z", CompressionFormat::SevenZip}, {".zip", CompressionFormat::Zip}, {".rar", CompressionFormat::Rar} }; void Extractor::extract(const fs::path& source, const fs::path& dest) { if (!fs::exists(source)) throw ExtractorException("Source file doesn't exist"); if (!fs::exists(dest)) fs::create_directory(dest); auto lib = std::any_cast<SevenZipLibrary>(&_data); auto str = fs::path(source).make_preferred().native(); SevenZipString name; name.assign(str.begin(), str.end()); auto ext = SevenZipExtractor(*lib, name); str.assign(dest.native()); name.assign(str.begin(), str.end()); if (!ext.DetectCompressionFormat()) { auto sf = source.extension().string(); std::transform(sf.begin(), sf.end(), sf.begin(), std::tolower); if (extensions.find(sf) != extensions.end()) ext.SetCompressionFormat(extensions.at(sf)); else ext.SetCompressionFormat(CompressionFormat::Zip); } if (!ext.ExtractArchive(name)) throw ExtractorException("Failed to extract file"); } }
25.328571
72
0.72758
luluco250
1b2fba2d04eb922606dcd40ed10f58c7689e3ec8
665
cpp
C++
src/vswhere.lib/Exceptions.cpp
www22111/vswhere
ded0fdd04473772af1dd001d82b6e3c871731788
[ "MIT" ]
335
2019-05-08T04:02:50.000Z
2022-03-30T20:41:31.000Z
src/vswhere.lib/Exceptions.cpp
www22111/vswhere
ded0fdd04473772af1dd001d82b6e3c871731788
[ "MIT" ]
79
2019-05-07T18:48:27.000Z
2022-03-16T22:27:59.000Z
src/vswhere.lib/Exceptions.cpp
www22111/vswhere
ded0fdd04473772af1dd001d82b6e3c871731788
[ "MIT" ]
39
2019-06-26T22:04:30.000Z
2022-01-07T15:09:44.000Z
// <copyright file="Exceptions.cpp" company="Microsoft Corporation"> // Copyright (C) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE.txt in the project root for license information. // </copyright> #include "stdafx.h" using namespace std; wstring win32_error::format_message(_In_ int code) { const size_t max = 65536; wstring err(max, wstring::value_type()); if (auto ch = ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0, const_cast<LPWSTR>(err.c_str()), err.size(), NULL)) { err.resize(ch); return err; } return L"unknown error"; }
28.913043
161
0.703759
www22111
1b30f172071d772a7a87ad2e57ff672cd5a28725
648
cpp
C++
c_plus_demo/libstl/src/insert_demo.cpp
xiaoyuan94/c_cpuls_learning
6e3a9fe02412ce7d6f32f53b8094f3d5212e0ff7
[ "Apache-2.0" ]
null
null
null
c_plus_demo/libstl/src/insert_demo.cpp
xiaoyuan94/c_cpuls_learning
6e3a9fe02412ce7d6f32f53b8094f3d5212e0ff7
[ "Apache-2.0" ]
null
null
null
c_plus_demo/libstl/src/insert_demo.cpp
xiaoyuan94/c_cpuls_learning
6e3a9fe02412ce7d6f32f53b8094f3d5212e0ff7
[ "Apache-2.0" ]
null
null
null
// // Created by ubuntu on 2021/4/16. // #include <iostream> #include "insert_demo.h" void InsertDemo::InsertMap() { MElement element; element.name = "element1"; map_.insert(std::make_pair("key_element1", element)); } void InsertDemo::ShowMap() { std::map<std::string, MElement>::iterator it; for (it = map_.begin(); it != map_.end(); it++) { MElement element = std::move(it->second); std::cout << ("element name :" + element.name) << std::endl; } } MElement InsertDemo::FindKey() { std::map<std::string, MElement>::iterator iter; iter = map_.find("key_element1"); return iter->second; }
19.058824
68
0.618827
xiaoyuan94
1b30fee36c666567d384bd513bc0f88e782eb7e3
12,586
cpp
C++
mlir/lib/Analysis/PresburgerSet.cpp
acidburn0zzz/llvm-project
7ca7a2547f00e34f5ec91be776a1d0bbca74b7a9
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
mlir/lib/Analysis/PresburgerSet.cpp
acidburn0zzz/llvm-project
7ca7a2547f00e34f5ec91be776a1d0bbca74b7a9
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
mlir/lib/Analysis/PresburgerSet.cpp
acidburn0zzz/llvm-project
7ca7a2547f00e34f5ec91be776a1d0bbca74b7a9
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
//===- Set.cpp - MLIR PresburgerSet Class ---------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "mlir/Analysis/PresburgerSet.h" #include "mlir/Analysis/Presburger/Simplex.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallBitVector.h" using namespace mlir; PresburgerSet::PresburgerSet(const FlatAffineConstraints &fac) : nDim(fac.getNumDimIds()), nSym(fac.getNumSymbolIds()) { unionFACInPlace(fac); } unsigned PresburgerSet::getNumFACs() const { return flatAffineConstraints.size(); } unsigned PresburgerSet::getNumDims() const { return nDim; } unsigned PresburgerSet::getNumSyms() const { return nSym; } ArrayRef<FlatAffineConstraints> PresburgerSet::getAllFlatAffineConstraints() const { return flatAffineConstraints; } const FlatAffineConstraints & PresburgerSet::getFlatAffineConstraints(unsigned index) const { assert(index < flatAffineConstraints.size() && "index out of bounds!"); return flatAffineConstraints[index]; } /// Assert that the FlatAffineConstraints and PresburgerSet live in /// compatible spaces. static void assertDimensionsCompatible(const FlatAffineConstraints &fac, const PresburgerSet &set) { assert(fac.getNumDimIds() == set.getNumDims() && "Number of dimensions of the FlatAffineConstraints and PresburgerSet" "do not match!"); assert(fac.getNumSymbolIds() == set.getNumSyms() && "Number of symbols of the FlatAffineConstraints and PresburgerSet" "do not match!"); } /// Assert that the two PresburgerSets live in compatible spaces. static void assertDimensionsCompatible(const PresburgerSet &setA, const PresburgerSet &setB) { assert(setA.getNumDims() == setB.getNumDims() && "Number of dimensions of the PresburgerSets do not match!"); assert(setA.getNumSyms() == setB.getNumSyms() && "Number of symbols of the PresburgerSets do not match!"); } /// Mutate this set, turning it into the union of this set and the given /// FlatAffineConstraints. void PresburgerSet::unionFACInPlace(const FlatAffineConstraints &fac) { assertDimensionsCompatible(fac, *this); flatAffineConstraints.push_back(fac); } /// Mutate this set, turning it into the union of this set and the given set. /// /// This is accomplished by simply adding all the FACs of the given set to this /// set. void PresburgerSet::unionSetInPlace(const PresburgerSet &set) { assertDimensionsCompatible(set, *this); for (const FlatAffineConstraints &fac : set.flatAffineConstraints) unionFACInPlace(fac); } /// Return the union of this set and the given set. PresburgerSet PresburgerSet::unionSet(const PresburgerSet &set) const { assertDimensionsCompatible(set, *this); PresburgerSet result = *this; result.unionSetInPlace(set); return result; } /// A point is contained in the union iff any of the parts contain the point. bool PresburgerSet::containsPoint(ArrayRef<int64_t> point) const { for (const FlatAffineConstraints &fac : flatAffineConstraints) { if (fac.containsPoint(point)) return true; } return false; } PresburgerSet PresburgerSet::getUniverse(unsigned nDim, unsigned nSym) { PresburgerSet result(nDim, nSym); result.unionFACInPlace(FlatAffineConstraints::getUniverse(nDim, nSym)); return result; } PresburgerSet PresburgerSet::getEmptySet(unsigned nDim, unsigned nSym) { return PresburgerSet(nDim, nSym); } // Return the intersection of this set with the given set. // // We directly compute (S_1 or S_2 ...) and (T_1 or T_2 ...) // as (S_1 and T_1) or (S_1 and T_2) or ... PresburgerSet PresburgerSet::intersect(const PresburgerSet &set) const { assertDimensionsCompatible(set, *this); PresburgerSet result(nDim, nSym); for (const FlatAffineConstraints &csA : flatAffineConstraints) { for (const FlatAffineConstraints &csB : set.flatAffineConstraints) { FlatAffineConstraints intersection(csA); intersection.append(csB); if (!intersection.isEmpty()) result.unionFACInPlace(std::move(intersection)); } } return result; } /// Return `coeffs` with all the elements negated. static SmallVector<int64_t, 8> getNegatedCoeffs(ArrayRef<int64_t> coeffs) { SmallVector<int64_t, 8> negatedCoeffs; negatedCoeffs.reserve(coeffs.size()); for (int64_t coeff : coeffs) negatedCoeffs.emplace_back(-coeff); return negatedCoeffs; } /// Return the complement of the given inequality. /// /// The complement of a_1 x_1 + ... + a_n x_ + c >= 0 is /// a_1 x_1 + ... + a_n x_ + c < 0, i.e., -a_1 x_1 - ... - a_n x_ - c - 1 >= 0. static SmallVector<int64_t, 8> getComplementIneq(ArrayRef<int64_t> ineq) { SmallVector<int64_t, 8> coeffs; coeffs.reserve(ineq.size()); for (int64_t coeff : ineq) coeffs.emplace_back(-coeff); --coeffs.back(); return coeffs; } /// Return the set difference b \ s and accumulate the result into `result`. /// `simplex` must correspond to b. /// /// In the following, V denotes union, ^ denotes intersection, \ denotes set /// difference and ~ denotes complement. /// Let b be the FlatAffineConstraints and s = (V_i s_i) be the set. We want /// b \ (V_i s_i). /// /// Let s_i = ^_j s_ij, where each s_ij is a single inequality. To compute /// b \ s_i = b ^ ~s_i, we partition s_i based on the first violated inequality: /// ~s_i = (~s_i1) V (s_i1 ^ ~s_i2) V (s_i1 ^ s_i2 ^ ~s_i3) V ... /// And the required result is (b ^ ~s_i1) V (b ^ s_i1 ^ ~s_i2) V ... /// We recurse by subtracting V_{j > i} S_j from each of these parts and /// returning the union of the results. Each equality is handled as a /// conjunction of two inequalities. /// /// As a heuristic, we try adding all the constraints and check if simplex /// says that the intersection is empty. Also, in the process we find out that /// some constraints are redundant. These redundant constraints are ignored. static void subtractRecursively(FlatAffineConstraints &b, Simplex &simplex, const PresburgerSet &s, unsigned i, PresburgerSet &result) { if (i == s.getNumFACs()) { result.unionFACInPlace(b); return; } const FlatAffineConstraints &sI = s.getFlatAffineConstraints(i); assert(sI.getNumLocalIds() == 0 && "Subtracting sets with divisions is not yet supported!"); unsigned initialSnapshot = simplex.getSnapshot(); unsigned offset = simplex.numConstraints(); simplex.intersectFlatAffineConstraints(sI); if (simplex.isEmpty()) { /// b ^ s_i is empty, so b \ s_i = b. We move directly to i + 1. simplex.rollback(initialSnapshot); subtractRecursively(b, simplex, s, i + 1, result); return; } simplex.detectRedundant(); llvm::SmallBitVector isMarkedRedundant; for (unsigned j = 0; j < 2 * sI.getNumEqualities() + sI.getNumInequalities(); j++) isMarkedRedundant.push_back(simplex.isMarkedRedundant(offset + j)); simplex.rollback(initialSnapshot); // Recurse with the part b ^ ~ineq. Note that b is modified throughout // subtractRecursively. At the time this function is called, the current b is // actually equal to b ^ s_i1 ^ s_i2 ^ ... ^ s_ij, and ineq is the next // inequality, s_{i,j+1}. This function recurses into the next level i + 1 // with the part b ^ s_i1 ^ s_i2 ^ ... ^ s_ij ^ ~s_{i,j+1}. auto recurseWithInequality = [&, i](ArrayRef<int64_t> ineq) { size_t snapshot = simplex.getSnapshot(); b.addInequality(ineq); simplex.addInequality(ineq); subtractRecursively(b, simplex, s, i + 1, result); b.removeInequality(b.getNumInequalities() - 1); simplex.rollback(snapshot); }; // For each inequality ineq, we first recurse with the part where ineq // is not satisfied, and then add the ineq to b and simplex because // ineq must be satisfied by all later parts. auto processInequality = [&](ArrayRef<int64_t> ineq) { recurseWithInequality(getComplementIneq(ineq)); b.addInequality(ineq); simplex.addInequality(ineq); }; // processInequality appends some additional constraints to b. We want to // rollback b to its initial state before returning, which we will do by // removing all constraints beyond the original number of inequalities // and equalities, so we store these counts first. unsigned originalNumIneqs = b.getNumInequalities(); unsigned originalNumEqs = b.getNumEqualities(); for (unsigned j = 0, e = sI.getNumInequalities(); j < e; j++) { if (isMarkedRedundant[j]) continue; processInequality(sI.getInequality(j)); } offset = sI.getNumInequalities(); for (unsigned j = 0, e = sI.getNumEqualities(); j < e; ++j) { const ArrayRef<int64_t> &coeffs = sI.getEquality(j); // Same as the above loop for inequalities, done once each for the positive // and negative inequalities that make up this equality. if (!isMarkedRedundant[offset + 2 * j]) processInequality(coeffs); if (!isMarkedRedundant[offset + 2 * j + 1]) processInequality(getNegatedCoeffs(coeffs)); } // Rollback b and simplex to their initial states. for (unsigned i = b.getNumInequalities(); i > originalNumIneqs; --i) b.removeInequality(i - 1); for (unsigned i = b.getNumEqualities(); i > originalNumEqs; --i) b.removeEquality(i - 1); simplex.rollback(initialSnapshot); } /// Return the set difference fac \ set. /// /// The FAC here is modified in subtractRecursively, so it cannot be a const /// reference even though it is restored to its original state before returning /// from that function. PresburgerSet PresburgerSet::getSetDifference(FlatAffineConstraints fac, const PresburgerSet &set) { assertDimensionsCompatible(fac, set); assert(fac.getNumLocalIds() == 0 && "Subtracting sets with divisions is not yet supported!"); if (fac.isEmptyByGCDTest()) return PresburgerSet::getEmptySet(fac.getNumDimIds(), fac.getNumSymbolIds()); PresburgerSet result(fac.getNumDimIds(), fac.getNumSymbolIds()); Simplex simplex(fac); subtractRecursively(fac, simplex, set, 0, result); return result; } /// Return the complement of this set. PresburgerSet PresburgerSet::complement() const { return getSetDifference( FlatAffineConstraints::getUniverse(getNumDims(), getNumSyms()), *this); } /// Return the result of subtract the given set from this set, i.e., /// return `this \ set`. PresburgerSet PresburgerSet::subtract(const PresburgerSet &set) const { assertDimensionsCompatible(set, *this); PresburgerSet result(nDim, nSym); // We compute (V_i t_i) \ (V_i set_i) as V_i (t_i \ V_i set_i). for (const FlatAffineConstraints &fac : flatAffineConstraints) result.unionSetInPlace(getSetDifference(fac, set)); return result; } /// Two sets S and T are equal iff S contains T and T contains S. /// By "S contains T", we mean that S is a superset of or equal to T. /// /// S contains T iff T \ S is empty, since if T \ S contains a /// point then this is a point that is contained in T but not S. /// /// Therefore, S is equal to T iff S \ T and T \ S are both empty. bool PresburgerSet::isEqual(const PresburgerSet &set) const { assertDimensionsCompatible(set, *this); return this->subtract(set).isIntegerEmpty() && set.subtract(*this).isIntegerEmpty(); } /// Return true if all the sets in the union are known to be integer empty, /// false otherwise. bool PresburgerSet::isIntegerEmpty() const { // The set is empty iff all of the disjuncts are empty. for (const FlatAffineConstraints &fac : flatAffineConstraints) { if (!fac.isIntegerEmpty()) return false; } return true; } bool PresburgerSet::findIntegerSample(SmallVectorImpl<int64_t> &sample) { // A sample exists iff any of the disjuncts contains a sample. for (const FlatAffineConstraints &fac : flatAffineConstraints) { if (Optional<SmallVector<int64_t, 8>> opt = fac.findIntegerSample()) { sample = std::move(*opt); return true; } } return false; } void PresburgerSet::print(raw_ostream &os) const { os << getNumFACs() << " FlatAffineConstraints:\n"; for (const FlatAffineConstraints &fac : flatAffineConstraints) { fac.print(os); os << '\n'; } } void PresburgerSet::dump() const { print(llvm::errs()); }
37.909639
80
0.694979
acidburn0zzz
1b3117f16bc8bf11fc671f0daced6e48d1ff6f83
321
hpp
C++
driver/src/common/Typed.hpp
vishalbelsare/Birch
ead17b181a058250e9f5896d64954232d19e43f0
[ "Apache-2.0" ]
86
2017-10-29T15:46:41.000Z
2022-01-17T07:18:16.000Z
driver/src/common/Typed.hpp
vishalbelsare/Birch
ead17b181a058250e9f5896d64954232d19e43f0
[ "Apache-2.0" ]
13
2020-09-27T03:31:57.000Z
2021-05-27T00:39:14.000Z
driver/src/common/Typed.hpp
vishalbelsare/Birch
ead17b181a058250e9f5896d64954232d19e43f0
[ "Apache-2.0" ]
12
2018-08-21T12:57:18.000Z
2021-05-26T18:41:50.000Z
/** * @file */ #pragma once #include "src/type/Type.hpp" #include "src/type/EmptyType.hpp" namespace birch { /** * Typed expression or statement. * * @ingroup common */ class Typed { public: /** * Constructor. * * @param type Type. */ Typed(Type* type); /** * Type. */ Type* type; }; }
10.7
33
0.557632
vishalbelsare
1b31e8d961b9759faeb0de8ae6c48283cbb46899
624
cpp
C++
src/p259.cpp
DirkyJerky/Study-C2
97204a70340380d980e5a3778395408b8d2c3142
[ "MIT" ]
null
null
null
src/p259.cpp
DirkyJerky/Study-C2
97204a70340380d980e5a3778395408b8d2c3142
[ "MIT" ]
null
null
null
src/p259.cpp
DirkyJerky/Study-C2
97204a70340380d980e5a3778395408b8d2c3142
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <fstream> #include <stdlib.h> #include "common.h" #define MAX_BUF 512 int main(int argc, char *argv[]) { if(argc != 2) { printf("Usage: %s <file>\n", argv[0]); exit(1); } std::ifstream fin(argv[1]); if(!fin) { println("Error opening file \"" << argv[1] << '"' << std::endl); } int temp = (EOF + 1); fin.seekg(-1, fin.end); int length = fin.tellg(); for(int i = length - 1; i >= EOF; i--) { temp = fin.peek(); fin.seekg(i, fin.beg); std::cout << ((char) temp); } println(""); }
18.909091
72
0.498397
DirkyJerky
1b323dc164b2b53e4f2f7e516b224d02093d42ff
61,762
cxx
C++
src/ramsesio.cxx
bwvdnbro/VELOCIraptor-STF
9c4a07eee20309152bcde40602029315c8bd50ca
[ "MIT" ]
4
2020-08-28T11:29:09.000Z
2021-10-16T20:17:54.000Z
src/ramsesio.cxx
bwvdnbro/VELOCIraptor-STF
9c4a07eee20309152bcde40602029315c8bd50ca
[ "MIT" ]
118
2019-05-06T11:46:28.000Z
2022-03-14T17:14:37.000Z
src/ramsesio.cxx
bwvdnbro/VELOCIraptor-STF
9c4a07eee20309152bcde40602029315c8bd50ca
[ "MIT" ]
4
2020-10-01T05:22:31.000Z
2021-07-26T13:07:42.000Z
/*! \file ramsesio.cxx * \brief this file contains routines for ramses snapshot file io * * \todo need to check if amr file quantity ngrid_current is actually the number of cells in the file as * an example fortran code I have been given seems to also use the ngridlevel array, which stores the number of cells * at a given resolution level. * \todo need to add in ability for multiple read threads and sends between read threads * * * Edited by: Rodrigo Ca\~nas * rodrigo.canas@icrar.org * * Last edited: 7 - Jun - 2017 * * */ //-- RAMSES SPECIFIC IO #include "stf.h" #include "io.h" #include "ramsesitems.h" #include "endianutils.h" int RAMSES_fortran_read(fstream &F, int &i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)&i,sizeof(int)); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, RAMSESFLOAT &f){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)&f,sizeof(RAMSESFLOAT)); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, int *i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)i,dummy); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, unsigned int *i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy)); byteoffset += sizeof(int); F.read((char*)i,dummy); byteoffset += dummy; F.read((char*)&dummy, sizeof(dummy)); byteoffset += sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, long long *i){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)i,dummy); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_read(fstream &F, RAMSESFLOAT *f){ int dummy,byteoffset=0; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.read((char*)f,dummy); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); return byteoffset; } int RAMSES_fortran_skip(fstream &F, int nskips){ int dummy,byteoffset=0; for (int i=0;i<nskips;i++) { F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); F.seekg(dummy,ios::cur); byteoffset+=dummy; F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int); } return byteoffset; } Int_t RAMSES_get_nbodies(char *fname, int ptype, Options &opt) { char buf[2000],buf1[2000],buf2[2000]; double * dummy_age, * dummy_mass; double dmp_mass; double OmegaM, OmegaB; int totalghost = 0; int totalstars = 0; int totaldm = 0; int alltotal = 0; int ghoststars = 0; string stringbuf; int ninputoffset = 0; sprintf(buf1,"%s/amr_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); else { printf("Error. Can't find AMR data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2); exit(9); } //if gas searched in some fashion then load amr/hydro data if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) { sprintf(buf1,"%s/hydro_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/hydro_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); else { printf("Error. Can't find Hydro data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2); exit(9); } } sprintf(buf1,"%s/part_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/part_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); else { printf("Error. Can't find Particle data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2); exit(9); } fstream Framses; RAMSES_Header ramses_header_info; //buffers to load data int intbuff[NRAMSESTYPE]; long long longbuff[NRAMSESTYPE]; int i,j,k,ireaderror=0; Int_t nbodies=0; //IntType inttype; int dummy; int nusetypes,usetypes[NRAMSESTYPE]; if (ptype==PSTALL) {nusetypes=4;usetypes[0]=RAMSESGASTYPE;usetypes[1]=RAMSESDMTYPE;usetypes[2]=RAMSESSTARTYPE;usetypes[3]=RAMSESBHTYPE;} else if (ptype==PSTDARK) {nusetypes=1;usetypes[0]=RAMSESDMTYPE;} else if (ptype==PSTGAS) {nusetypes=1;usetypes[0]=RAMSESGASTYPE;} else if (ptype==PSTSTAR) {nusetypes=1;usetypes[0]=RAMSESSTARTYPE;} else if (ptype==PSTBH) {nusetypes=1;usetypes[0]=RAMSESBHTYPE;} for (j = 0; j < NRAMSESTYPE; j++) ramses_header_info.npartTotal[j] = 0; //Open the specified file and the specified dataset in the file. //first open amr data sprintf(buf1,"%s/amr_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); //read header info //this is based on a ramsestotipsy fortran code that does not detail everything in the header block but at least its informative. The example has /* read(10)ncpu read(10)ndim read(10)nx,ny,nz read(10)nlevelmax read(10)ngridmax read(10)nboundary read(10)ngrid_current read(10)boxlen read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10) read(10)msph close(10) */ // Number of files Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.num_files, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); opt.num_files=ramses_header_info.num_files; // Number of dimensions Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.ndim, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nx, sizeof(int)); Framses.read((char*)&ramses_header_info.ny, sizeof(int)); Framses.read((char*)&ramses_header_info.nz, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Maximum refinement level Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nlevelmax, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.ngridmax, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nboundary, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); //this would be number of active grids but ignore for now Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Boxsize Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.BoxSize, sizeof(RAMSESFLOAT)); Framses.read((char*)&dummy, sizeof(dummy)); //now skip 10 blocks for (i=0;i<10;i++) { Framses.read((char*)&dummy, sizeof(dummy)); //skip block size given by dummy Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.mass[RAMSESGASTYPE], sizeof(RAMSESFLOAT)); Framses.read((char*)&dummy, sizeof(dummy)); Framses.close(); //reopen to get number of amr cells might need to alter to read grid information and what cells have no so-called son cells if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) { for (i=0;i<ramses_header_info.num_files;i++) { sprintf(buf1,"%s/amr_%s.out%05d",fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); for (j=0;j<6;j++) { Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.npart[RAMSESGASTYPE], sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); ramses_header_info.npartTotal[RAMSESGASTYPE]+=ramses_header_info.npart[RAMSESGASTYPE]; } //now hydro header data sprintf(buf1,"%s/hydro_%s.out00001",fname,opt.ramsessnapname); sprintf(buf2,"%s/hydro_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nvarh, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); for (i=0;i<3;i++) { Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.gamma_index, sizeof(RAMSESFLOAT)); Framses.read((char*)&dummy, sizeof(dummy)); Framses.close(); } // // Compute Mass of DM particles in RAMSES code units // fstream Finfo; sprintf(buf1,"%s/info_%s.txt", fname,opt.ramsessnapname); Finfo.open(buf1, ios::in); Finfo>>stringbuf>>stringbuf>>opt.num_files; getline(Finfo,stringbuf);//ndim getline(Finfo,stringbuf);//lmin getline(Finfo,stringbuf);//lmax getline(Finfo,stringbuf);//ngridmax getline(Finfo,stringbuf);//nstep getline(Finfo,stringbuf);//blank getline(Finfo,stringbuf);//box getline(Finfo,stringbuf);//time getline(Finfo,stringbuf);//a getline(Finfo,stringbuf);//hubble Finfo>>stringbuf>>stringbuf>>OmegaM; getline(Finfo,stringbuf); getline(Finfo,stringbuf); getline(Finfo,stringbuf); Finfo>>stringbuf>>stringbuf>>OmegaB; Finfo.close(); dmp_mass = 1.0 / (opt.Neff*opt.Neff*opt.Neff) * (OmegaM - OmegaB) / OmegaM; //now particle info for (i=0;i<ramses_header_info.num_files;i++) { sprintf(buf1,"%s/part_%s.out%05d",fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/part_%s.out",fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Framses.open(buf, ios::binary|ios::in); ramses_header_info.npart[RAMSESDMTYPE] = 0; ramses_header_info.npart[RAMSESSTARTYPE] = 0; ramses_header_info.npart[RAMSESSINKTYPE] = 0; //number of cpus Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); //number of dimensions Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Total number of LOCAL particles Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.npartlocal, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Random seeds Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Total number of Stars over all processors Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.nstarTotal, sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); // Total mass of stars Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Total lost mass of stars Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Number of sink particles over the whole simulation (all are included in // all processors) Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&ramses_header_info.npartTotal[RAMSESSINKTYPE], sizeof(int)); Framses.read((char*)&dummy, sizeof(dummy)); //to determine how many particles of each type, need to look at the mass // Skip pos, vel, mass for (j = 0; j < 6; j++) { Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); } //allocate memory to store masses and ages dummy_mass = new double [ramses_header_info.npartlocal]; dummy_age = new double [ramses_header_info.npartlocal]; // Read Mass Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&dummy_mass[0], dummy); Framses.read((char*)&dummy, sizeof(dummy)); // Skip Id Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Skip level Framses.read((char*)&dummy, sizeof(dummy)); Framses.seekg(dummy,ios::cur); Framses.read((char*)&dummy, sizeof(dummy)); // Read Birth epoch //necessary to separate ghost star particles with negative ages from real one Framses.read((char*)&dummy, sizeof(dummy)); Framses.read((char*)&dummy_age[0], dummy); Framses.read((char*)&dummy, sizeof(dummy)); ghoststars = 0; for (j = 0; j < ramses_header_info.npartlocal; j++) { if (fabs((dummy_mass[j]-dmp_mass)/dmp_mass) < 1e-5) ramses_header_info.npart[RAMSESDMTYPE]++; else if (dummy_age[j] != 0.0) ramses_header_info.npart[RAMSESSTARTYPE]++; else ghoststars++; } delete [] dummy_age; delete [] dummy_mass; Framses.close(); totalghost += ghoststars; totalstars += ramses_header_info.npart[RAMSESSTARTYPE]; totaldm += ramses_header_info.npart[RAMSESDMTYPE]; alltotal += ramses_header_info.npartlocal; //now with information loaded, set totals ramses_header_info.npartTotal[RAMSESDMTYPE]+=ramses_header_info.npart[RAMSESDMTYPE]; ramses_header_info.npartTotal[RAMSESSTARTYPE]+=ramses_header_info.npart[RAMSESSTARTYPE]; ramses_header_info.npartTotal[RAMSESSINKTYPE]+=ramses_header_info.npart[RAMSESSINKTYPE]; } for(j=0, nbodies=0; j<nusetypes; j++) { k=usetypes[j]; nbodies+=ramses_header_info.npartTotal[k]; //nbodies+=((long long)(ramses_header_info.npartTotalHW[k]) << 32); } for (j=0;j<NPARTTYPES;j++) opt.numpart[j]=0; if (ptype==PSTALL || ptype==PSTDARK) opt.numpart[DARKTYPE]=ramses_header_info.npartTotal[RAMSESDMTYPE]; if (ptype==PSTALL || ptype==PSTGAS) opt.numpart[GASTYPE]=ramses_header_info.npartTotal[RAMSESGASTYPE]; if (ptype==PSTALL || ptype==PSTSTAR) opt.numpart[STARTYPE]=ramses_header_info.npartTotal[RAMSESSTARTYPE]; if (ptype==PSTALL || ptype==PSTBH) opt.numpart[BHTYPE]=ramses_header_info.npartTotal[RAMSESSINKTYPE]; return nbodies; } /// Reads a ramses file. If cosmological simulation uses cosmology (generally /// assuming LCDM or small deviations from this) to estimate the mean interparticle /// spacing and scales physical linking length passed by this distance. Also reads /// header and overrides passed cosmological parameters with ones stored in header. void ReadRamses(Options &opt, vector<Particle> &Part, const Int_t nbodies, Particle *&Pbaryons, Int_t nbaryons) { char buf[2000],buf1[2000],buf2[2000]; string stringbuf,orderingstring; fstream Finfo; fstream *Famr; fstream *Fhydro; fstream *Fpart, *Fpartvel,*Fpartid,*Fpartmass, *Fpartlevel, *Fpartage, *Fpartmet; RAMSES_Header *header; int intbuff[NRAMSESTYPE]; long long longbuff[NRAMSESTYPE]; int i,j,k,n,idim,ivar,igrid,ireaderror=0; Int_t count2,bcount2; //IntType inttype; int dummy,byteoffset; Double_t MP_DM=MAXVALUE,LN,N_DM,MP_B=0; double z,aadjust,Hubble,Hubbleflow; Double_t mscale,lscale,lvscale,rhoscale; Double_t mtemp,utemp,rhotemp,Ztemp,Ttemp; Coordinate xpos,vpos; RAMSESFLOAT xtemp[3],vtemp[3]; RAMSESIDTYPE idval; int typeval; RAMSESFLOAT ageval,metval; int *ngridlevel,*ngridbound,*ngridfile; int lmin=1000000,lmax=0; double dmp_mass; int ninputoffset = 0; int ifirstfile=0,ibuf=0; std::vector<int> ireadfile; Int_t ibufindex; int *ireadtask,*readtaskID; #ifndef USEMPI int ThisTask=0,NProcs=1; ireadfile = std::vector<int>(opt.num_files, 1); #else MPI_Bcast (&(opt.num_files), sizeof(opt.num_files), MPI_BYTE, 0, MPI_COMM_WORLD); MPI_Barrier (MPI_COMM_WORLD); #endif ///\todo because of the stupid fortran format, easier if chunksize is BIG so that ///number of particles local to a file are smaller Int_t chunksize=RAMSESCHUNKSIZE,nchunk; RAMSESFLOAT *xtempchunk, *vtempchunk, *mtempchunk, *sphtempchunk, *agetempchunk, *mettempchunk, *hydrotempchunk; RAMSESIDTYPE *idvalchunk, *levelchunk; int *icellchunk; Famr = new fstream[opt.num_files]; Fhydro = new fstream[opt.num_files]; Fpart = new fstream[opt.num_files]; Fpartvel = new fstream[opt.num_files]; Fpartmass = new fstream[opt.num_files]; Fpartid = new fstream[opt.num_files]; Fpartlevel = new fstream[opt.num_files]; Fpartage = new fstream[opt.num_files]; Fpartmet = new fstream[opt.num_files]; header = new RAMSES_Header[opt.num_files]; Particle *Pbuf; #ifdef USEMPI MPI_Status status; MPI_Comm mpi_comm_read; vector<Particle> *Preadbuf; //for parallel io Int_t BufSize=opt.mpiparticlebufsize; Int_t Nlocalbuf,*Nbuf, *Nreadbuf,*nreadoffset; Int_t *Nlocalthreadbuf,Nlocaltotalbuf; int *irecv, sendTask,recvTask,irecvflag, *mpi_irecvflag; MPI_Request *mpi_request; Int_t inreadsend,totreadsend; Int_t *mpi_nsend_baryon; Int_t *mpi_nsend_readthread; Int_t *mpi_nsend_readthread_baryon; if (opt.iBaryonSearch) mpi_nsend_baryon=new Int_t[NProcs*NProcs]; if (opt.nsnapread>1) { mpi_nsend_readthread=new Int_t[opt.nsnapread*opt.nsnapread]; if (opt.iBaryonSearch) mpi_nsend_readthread_baryon=new Int_t[opt.nsnapread*opt.nsnapread]; } Nbuf=new Int_t[NProcs]; nreadoffset=new Int_t[opt.nsnapread]; ireadtask=new int[NProcs]; readtaskID=new int[opt.nsnapread]; MPIDistributeReadTasks(opt,ireadtask,readtaskID); MPI_Comm_split(MPI_COMM_WORLD, (ireadtask[ThisTask]>=0), ThisTask, &mpi_comm_read); if (ireadtask[ThisTask]>=0) { //to temporarily store data Pbuf=new Particle[BufSize*NProcs]; Nreadbuf=new Int_t[opt.nsnapread]; for (int j=0;j<NProcs;j++) Nbuf[j]=0; for (int j=0;j<opt.nsnapread;j++) Nreadbuf[j]=0; if (opt.nsnapread>1){ Preadbuf=new vector<Particle>[opt.nsnapread]; for (int j=0;j<opt.nsnapread;j++) Preadbuf[j].reserve(BufSize); } //to determine which files the thread should read ireadfile = std::vector<int>(opt.num_files); ifirstfile=MPISetFilesRead(opt,ireadfile,ireadtask); inreadsend=0; for (int j=0;j<opt.num_files;j++) inreadsend+=ireadfile[j]; MPI_Allreduce(&inreadsend,&totreadsend,1,MPI_Int_t,MPI_MIN,mpi_comm_read); } else { Nlocalthreadbuf=new Int_t[opt.nsnapread]; irecv=new int[opt.nsnapread]; mpi_irecvflag=new int[opt.nsnapread]; for (i=0;i<opt.nsnapread;i++) irecv[i]=1; mpi_request=new MPI_Request[opt.nsnapread]; } Nlocal=0; if (opt.iBaryonSearch) Nlocalbaryon[0]=0; if (ireadtask[ThisTask]>=0) { #endif //first read cosmological information sprintf(buf1,"%s/info_%s.txt",opt.fname,opt.ramsessnapname); Finfo.open(buf1, ios::in); getline(Finfo,stringbuf);//nfiles getline(Finfo,stringbuf);//ndim Finfo>>stringbuf>>stringbuf>>header[ifirstfile].levelmin; getline(Finfo,stringbuf);//lmax getline(Finfo,stringbuf);//ngridmax getline(Finfo,stringbuf);//nstep getline(Finfo,stringbuf);//blank Finfo>>stringbuf>>stringbuf>>header[ifirstfile].BoxSize; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].time; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].aexp; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].HubbleParam; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegam; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].OmegaLambda; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegak; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegab; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_l; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_d; Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_t; //convert boxsize to comoving kpc/h header[ifirstfile].BoxSize*=header[ifirstfile].scale_l/3.086e21/header[ifirstfile].aexp*header[ifirstfile].HubbleParam/100.0; getline(Finfo,stringbuf); Finfo>>stringbuf>>orderingstring; getline(Finfo,stringbuf); Finfo.close(); opt.p = header[ifirstfile].BoxSize; opt.a = header[ifirstfile].aexp; opt.Omega_m = header[ifirstfile].Omegam; opt.Omega_Lambda = header[ifirstfile].OmegaLambda; opt.Omega_b = header[ifirstfile].Omegab; opt.h = header[ifirstfile].HubbleParam/100.0; opt.Omega_cdm = opt.Omega_m-opt.Omega_b; //set hubble unit to km/s/kpc opt.H = 0.1; //set Gravity to value for kpc (km/s)^2 / solar mass opt.G = 4.30211349e-6; //and for now fix the units opt.lengthtokpc=opt.velocitytokms=opt.masstosolarmass=1.0; //Hubble flow if (opt.comove) aadjust=1.0; else aadjust=opt.a; CalcOmegak(opt); Hubble=GetHubble(opt, aadjust); CalcCriticalDensity(opt, aadjust); CalcBackgroundDensity(opt, aadjust); CalcVirBN98(opt,aadjust); //if opt.virlevel<0, then use virial overdensity based on Bryan and Norman 1997 virialization level is given by if (opt.virlevel<0) opt.virlevel=opt.virBN98; PrintCosmology(opt); //adjust length scale so that convert from 0 to 1 (box units) to kpc comoving //to scale mpi domains correctly need to store in opt.lengthinputconversion the box size in comoving little h value //opt.lengthinputconversion= opt.p*opt.h/opt.a; opt.lengthinputconversion = header[ifirstfile].BoxSize; //adjust velocity scale to that ramses is converted to km/s from which you can convert again; opt.velocityinputconversion = header[ifirstfile].scale_l/header[ifirstfile].scale_t*1e-5; //convert mass from code units to Solar Masses mscale = header[ifirstfile].scale_d * (header[ifirstfile].scale_l * header[ifirstfile].scale_l * header[ifirstfile].scale_l) / 1.988e+33; //convert length from code units to kpc (this lscale includes the physical box size) lscale = header[ifirstfile].scale_l/3.086e21; //convert velocity from code units to km/s lvscale = header[ifirstfile].scale_l/header[ifirstfile].scale_t*1e-5; //convert density to Msun/kpc^3 rhoscale = mscale/(lscale*lscale*lscale); //ignore hubble flow Hubbleflow=0.; //for (int j=0;j<NPARTTYPES;j++) nbodies+=opt.numpart[j]; cout<<"Particle system contains "<<nbodies<<" particles (of interest) at is at time "<<opt.a<<" in a box of size "<<opt.p<<endl; //number of DM particles //NOTE: this assumes a uniform box resolution. However this is not used in the rest of this function N_DM = opt.Neff*opt.Neff*opt.Neff; //interparticle spacing (assuming a uniform resolution box) LN = (lscale/(double)opt.Neff); opt.ellxscale = LN; //grab from the first particle file the dimensions of the arrays and also the number of cpus (should be number of files) sprintf(buf1,"%s/part_%s.out00001",opt.fname,opt.ramsessnapname); Fpart[ifirstfile].open(buf1, ios::binary|ios::in); RAMSES_fortran_read(Fpart[ifirstfile],header[ifirstfile].nfiles); RAMSES_fortran_read(Fpart[ifirstfile],header[ifirstfile].ndim); //adjust the number of files opt.num_files=header[ifirstfile].nfiles; Fpart[ifirstfile].close(); #ifdef USEMPI //now read tasks prepped and can read files to send information } #endif #ifdef USEMPI if (ireadtask[ThisTask]>=0) { #endif dmp_mass = 1.0 / (opt.Neff*opt.Neff*opt.Neff) * opt.Omega_cdm / opt.Omega_m; #ifdef USEMPI } MPI_Bcast (&dmp_mass, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); #endif //if not only gas being searched open particle data count2=bcount2=0; if (opt.partsearchtype!=PSTGAS) { #ifdef USEMPI if (ireadtask[ThisTask]>=0) { inreadsend=0; #endif //read particle files consists of positions,velocities, mass, id, and level (along with ages and met if some flags set) for (i=0;i<opt.num_files;i++) { if (ireadfile[i]) { sprintf(buf1,"%s/part_%s.out%05d",opt.fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/part_%s.out",opt.fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Fpart[i].open(buf, ios::binary|ios::in); Fpartvel[i].open(buf, ios::binary|ios::in); Fpartmass[i].open(buf, ios::binary|ios::in); Fpartid[i].open(buf, ios::binary|ios::in); Fpartlevel[i].open(buf, ios::binary|ios::in); Fpartage[i].open(buf, ios::binary|ios::in); Fpartmet[i].open(buf, ios::binary|ios::in); //skip header information in each file save for number in the file //@{ byteoffset=0; // ncpus byteoffset+=RAMSES_fortran_skip(Fpart[i]); // ndims byteoffset+=RAMSES_fortran_skip(Fpart[i]); // store number of particles locally in file byteoffset+=RAMSES_fortran_read(Fpart[i],header[i].npartlocal); // skip local seeds, nstartot, mstartot, mstarlost, nsink byteoffset+=RAMSES_fortran_skip(Fpart[i],5); //byteoffset now stores size of header offset for particles Fpartvel[i].seekg(byteoffset,ios::cur); Fpartmass[i].seekg(byteoffset,ios::cur); Fpartid[i].seekg(byteoffset,ios::cur); Fpartlevel[i].seekg(byteoffset,ios::cur); Fpartage[i].seekg(byteoffset,ios::cur); Fpartmet[i].seekg(byteoffset,ios::cur); //skip positions for(idim=0;idim<header[ifirstfile].ndim;idim++) { RAMSES_fortran_skip(Fpartvel[i]); RAMSES_fortran_skip(Fpartmass[i]); RAMSES_fortran_skip(Fpartid[i]); RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); } //skip velocities for(idim=0;idim<header[ifirstfile].ndim;idim++) { RAMSES_fortran_skip(Fpartmass[i]); RAMSES_fortran_skip(Fpartid[i]); RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); } //skip mass RAMSES_fortran_skip(Fpartid[i]); RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); //skip ids; RAMSES_fortran_skip(Fpartlevel[i]); RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); //skip levels RAMSES_fortran_skip(Fpartage[i]); RAMSES_fortran_skip(Fpartmet[i]); //skip ages RAMSES_fortran_skip(Fpartmet[i]); //@} //data loaded into memory in chunks chunksize = nchunk = header[i].npartlocal; ninputoffset = 0; xtempchunk = new RAMSESFLOAT [3*chunksize]; vtempchunk = new RAMSESFLOAT [3*chunksize]; mtempchunk = new RAMSESFLOAT [chunksize]; idvalchunk = new RAMSESIDTYPE [chunksize]; levelchunk = new RAMSESIDTYPE [chunksize]; agetempchunk = new RAMSESFLOAT [chunksize]; mettempchunk = new RAMSESFLOAT [chunksize]; for(idim=0;idim<header[ifirstfile].ndim;idim++) { RAMSES_fortran_read(Fpart[i],&xtempchunk[idim*nchunk]); RAMSES_fortran_read(Fpartvel[i],&vtempchunk[idim*nchunk]); } RAMSES_fortran_read(Fpartmass[i], mtempchunk); RAMSES_fortran_read(Fpartid[i], idvalchunk); RAMSES_fortran_read(Fpartlevel[i], levelchunk); RAMSES_fortran_read(Fpartage[i], agetempchunk); RAMSES_fortran_read(Fpartmet[i], mettempchunk); RAMSES_fortran_read(Fpartid[i],idvalchunk); for (int nn=0;nn<nchunk;nn++) { if (fabs((mtempchunk[nn]-dmp_mass)/dmp_mass) > 1e-5 && (agetempchunk[nn] == 0.0)) { // GHOST PARTIRCLE!!! } else { xtemp[0] = xtempchunk[nn]; xtemp[1] = xtempchunk[nn+nchunk]; xtemp[2] = xtempchunk[nn+2*nchunk]; vtemp[0] = vtempchunk[nn]; vtemp[1] = vtempchunk[nn+nchunk]; vtemp[2] = vtempchunk[nn+2*nchunk]; idval = idvalchunk[nn]; ///Need to check this for correct 'endianness' // for (int kk=0;kk<3;kk++) {xtemp[kk]=LittleRAMSESFLOAT(xtemp[kk]);vtemp[kk]=LittleRAMSESFLOAT(vtemp[kk]);} #ifndef NOMASS mtemp=mtempchunk[nn]; #else mtemp=1.0; #endif ageval = agetempchunk[nn]; if (fabs((mtemp-dmp_mass)/dmp_mass) < 1e-5) typeval = DARKTYPE; else typeval = STARTYPE; /* if (ageval==0 && idval>0) typeval=DARKTYPE; else if (idval>0) typeval=STARTYPE; else typeval=BHTYPE; */ #ifdef USEMPI //determine processor this particle belongs on based on its spatial position ibuf=MPIGetParticlesProcessor(opt, xtemp[0],xtemp[1],xtemp[2]); ibufindex=ibuf*BufSize+Nbuf[ibuf]; #endif //reset hydro quantities of buffer #ifdef USEMPI #ifdef GASON Pbuf[ibufindex].SetU(0); #ifdef STARON Pbuf[ibufindex].SetSFR(0); Pbuf[ibufindex].SetZmet(0); #endif #endif #ifdef STARON Pbuf[ibufindex].SetZmet(0); Pbuf[ibufindex].SetTage(0); #endif #ifdef BHON #endif #endif if (opt.partsearchtype==PSTALL) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[ibufindex].SetInputFileID(i); Part[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Part[count2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif count2++; } else if (opt.partsearchtype==PSTDARK) { if (!(typeval==STARTYPE||typeval==BHTYPE)) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,DARKTYPE); Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif //ensure that store number of particles to be sent to other reading threads Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Part[count2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif count2++; } else if (opt.iBaryonSearch) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2); Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif if (typeval==STARTYPE) Pbuf[ibufindex].SetType(STARTYPE); else if (typeval==BHTYPE) Pbuf[ibufindex].SetType(BHTYPE); //ensure that store number of particles to be sent to the reading threads Nbuf[ibuf]++; if (ibuf==ThisTask) { if (k==RAMSESSTARTYPE) Nlocalbaryon[2]++; else if (k==RAMSESSINKTYPE) Nlocalbaryon[3]++; } MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocalbaryon[0], Pbaryons, Nreadbuf, Preadbuf); #else Pbaryons[bcount2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Pbaryons[bcount2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[bcount2].SetInputFileID(i); Part[bcount2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif bcount2++; } } else if (opt.partsearchtype==PSTSTAR) { if (typeval==STARTYPE) { #ifdef USEMPI //if using MPI, determine proccessor and place in ibuf, store particle in particle buffer and if buffer full, broadcast data //unless ibuf is 0, then just store locally Pbuf[ibufindex]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,STARTYPE); //ensure that store number of particles to be sent to the reading threads Pbuf[ibufindex].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset); } #endif Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale, vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0], vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1], vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2], count2,typeval); Part[count2].SetPID(idval); #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(nn+ninputoffset); } #endif #endif count2++; } } }//end of ghost particle check }//end of loop over chunk delete[] xtempchunk; delete[] vtempchunk; delete[] mtempchunk; delete[] idvalchunk; delete[] agetempchunk; delete[] levelchunk; delete[] mettempchunk; Fpart[i].close(); Fpartvel[i].close(); Fpartmass[i].close(); Fpartid[i].close(); Fpartlevel[i].close(); Fpartage[i].close(); Fpartmet[i].close(); #ifdef USEMPI //send information between read threads if (opt.nsnapread>1&&inreadsend<totreadsend){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); inreadsend++; for(ibuf = 0; ibuf < opt.nsnapread; ibuf++) Nreadbuf[ibuf]=0; } #endif }//end of whether reading a file }//end of loop over file #ifdef USEMPI //once finished reading the file if there are any particles left in the buffer broadcast them for(ibuf = 0; ibuf < NProcs; ibuf++) if (ireadtask[ibuf]<0) { MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t, ibuf, ibuf+NProcs, MPI_COMM_WORLD); if (Nbuf[ibuf]>0) { MPI_Ssend(&Pbuf[ibuf*BufSize], sizeof(Particle)*Nbuf[ibuf], MPI_BYTE, ibuf, ibuf, MPI_COMM_WORLD); Nbuf[ibuf]=0; //last broadcast with Nbuf[ibuf]=0 so that receiver knows no more particles are to be broadcast MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t,ibuf,ibuf+NProcs,MPI_COMM_WORLD); } } if (opt.nsnapread>1){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); } }//end of ireadtask[ibuf]>0 #endif #ifdef USEMPI else { MPIReceiveParticlesFromReadThreads(opt,Pbuf,Part.data(),readtaskID, irecv, mpi_irecvflag, Nlocalthreadbuf, mpi_request,Pbaryons); } #endif } //if gas searched in some fashion then load amr/hydro data if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) { #ifdef USEMPI if (ireadtask[ThisTask]>=0) { inreadsend=0; #endif for (i=0;i<opt.num_files;i++) if (ireadfile[i]) { sprintf(buf1,"%s/amr_%s.out%05d",opt.fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/amr_%s.out",opt.fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Famr[i].open(buf, ios::binary|ios::in); sprintf(buf1,"%s/hydro_%s.out%05d",opt.fname,opt.ramsessnapname,i+1); sprintf(buf2,"%s/hydro_%s.out",opt.fname,opt.ramsessnapname); if (FileExists(buf1)) sprintf(buf,"%s",buf1); else if (FileExists(buf2)) sprintf(buf,"%s",buf2); Fhydro[i].open(buf, ios::binary|ios::in); //read some of the amr header till get to number of cells in current file //@{ byteoffset=0; byteoffset+=RAMSES_fortran_read(Famr[i],header[i].ndim); header[i].twotondim=pow(2,header[i].ndim); Famr[i].read((char*)&dummy, sizeof(dummy)); Famr[i].read((char*)&header[i].nx, sizeof(int)); Famr[i].read((char*)&header[i].ny, sizeof(int)); Famr[i].read((char*)&header[i].nz, sizeof(int)); Famr[i].read((char*)&dummy, sizeof(dummy)); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].nlevelmax); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].ngridmax); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].nboundary); byteoffset+=RAMSES_fortran_read(Famr[i],header[i].npart[RAMSESGASTYPE]); //then skip the rest for (j=0;j<14;j++) RAMSES_fortran_skip(Famr[i]); if (lmin>header[i].nlevelmax) lmin=header[i].nlevelmax; if (lmax<header[i].nlevelmax) lmax=header[i].nlevelmax; //@} //read header info from hydro files //@{ RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_read(Fhydro[i],header[i].nvarh); RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_skip(Fhydro[i]); RAMSES_fortran_read(Fhydro[i],header[i].gamma_index); //@} } for (i=0;i<opt.num_files;i++) if (ireadfile[i]) { //then apparently read ngridlevels, which appears to be an array storing the number of grids at a given level ngridlevel=new int[header[i].nlevelmax]; ngridfile=new int[(1+header[i].nboundary)*header[i].nlevelmax]; RAMSES_fortran_read(Famr[i],ngridlevel); for (j=0;j<header[i].nlevelmax;j++) ngridfile[j]=ngridlevel[j]; //skip some more RAMSES_fortran_skip(Famr[i]); //if nboundary>0 then need two skip twice then read ngridbound if(header[i].nboundary>0) { ngridbound=new int[header[i].nboundary*header[i].nlevelmax]; RAMSES_fortran_skip(Famr[i]); RAMSES_fortran_skip(Famr[i]); //ngridbound is an array of some sort but I don't see what it is used for RAMSES_fortran_read(Famr[i],ngridbound); for (j=0;j<header[i].nlevelmax;j++) ngridfile[header[i].nlevelmax+j]=ngridbound[j]; } //skip some more RAMSES_fortran_skip(Famr[i],2); //if odering list in info is bisection need to skip more if (orderingstring==string("bisection")) RAMSES_fortran_skip(Famr[i],5); else RAMSES_fortran_skip(Famr[i],4); ninputoffset=0; for (k=0;k<header[i].nboundary+1;k++) { for (j=0;j<header[i].nlevelmax;j++) { //first read amr for positions chunksize=nchunk=ngridfile[k*header[i].nlevelmax+j]; if (chunksize>0) { xtempchunk=new RAMSESFLOAT[3*chunksize]; //store son value in icell icellchunk=new int[header[i].twotondim*chunksize]; //skip grid index, next index and prev index. RAMSES_fortran_skip(Famr[i],3); //now read grid centre for (idim=0;idim<header[i].ndim;idim++) { RAMSES_fortran_read(Famr[i],&xtempchunk[idim*chunksize]); } //skip father index, then neighbours index RAMSES_fortran_skip(Famr[i],1+2*header[i].ndim); //read son index to determine if a cell in a specific grid is at the highest resolution and needs to be represented by a particle for (idim=0;idim<header[i].twotondim;idim++) { RAMSES_fortran_read(Famr[i],&icellchunk[idim*chunksize]); } //skip cpu map and refinement map (2^ndim*2) RAMSES_fortran_skip(Famr[i],2*header[i].twotondim); } RAMSES_fortran_skip(Fhydro[i]); //then read hydro for other variables (first is density, then velocity, then pressure, then metallicity ) if (chunksize>0) { hydrotempchunk=new RAMSESFLOAT[chunksize*header[i].twotondim*header[i].nvarh]; //first read velocities (for 2 cells per number of dimensions (ie: cell corners?)) for (idim=0;idim<header[i].twotondim;idim++) { for (ivar=0;ivar<header[i].nvarh;ivar++) { RAMSES_fortran_read(Fhydro[i],&hydrotempchunk[idim*chunksize*header[i].nvarh+ivar*chunksize]); for (igrid=0;igrid<chunksize;igrid++) { //once we have looped over all the hydro data then can start actually storing it into the particle structures if (ivar==header[i].nvarh-1) { //if cell has no internal cells or at maximum level produce a particle if (icellchunk[idim*chunksize+igrid]==0 || j==header[i].nlevelmax-1) { //first suggestion is to add some jitter to the particle positions double dx = pow(0.5, j); int ix, iy, iz; //below assumes three dimensions with 8 corners (? maybe cells) per grid iz = idim/4; iy = (idim - (4*iz))/2; ix = idim - (2*iy) - (4*iz); // Calculate absolute coordinates + jitter, and generate particle xpos[0] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid] + (double(ix)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ; xpos[1] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid+1*chunksize] + (double(iy)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ; xpos[2] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid+2*chunksize] + (double(iz)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ; #ifdef USEMPI //determine processor this particle belongs on based on its spatial position ibuf=MPIGetParticlesProcessor(opt, xpos[0],xpos[1],xpos[2]); ibufindex=ibuf*BufSize+Nbuf[ibuf]; #endif vpos[0]=hydrotempchunk[idim*chunksize*header[i].nvarh+1*chunksize+igrid]; vpos[1]=hydrotempchunk[idim*chunksize*header[i].nvarh+2*chunksize+igrid]; vpos[2]=hydrotempchunk[idim*chunksize*header[i].nvarh+3*chunksize+igrid]; mtemp=dx*dx*dx*hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]; //the self energy P/rho is given by utemp=hydrotempchunk[idim*chunksize*header[i].nvarh+4*chunksize+igrid]/hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]/(header[i].gamma_index-1.0); rhotemp=hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]*rhoscale; Ztemp=hydrotempchunk[idim*chunksize*header[i].nvarh+5*chunksize+igrid]; if (opt.partsearchtype==PSTALL) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Pbuf[ibufindex].SetPID(idval); #ifdef GASON Pbuf[ibufindex].SetU(utemp); Pbuf[ibufindex].SetSPHDen(rhotemp); #ifdef STARON Pbuf[ibufindex].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif //ensure that store number of particles to be sent to the threads involved with reading snapshot files Nbuf[ibuf]++; MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf); #else Part[count2]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Part[count2].SetPID(idval); #ifdef GASON Part[count2].SetU(utemp); Part[count2].SetSPHDen(rhotemp); #ifdef STARON Part[count2].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Part[count2].SetInputFileID(i); Part[count2].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif #endif count2++; } else if (opt.partsearchtype==PSTDARK&&opt.iBaryonSearch) { #ifdef USEMPI Pbuf[ibufindex]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Pbuf[ibufindex].SetPID(idval); #ifdef GASON Pbuf[ibufindex].SetU(utemp); Pbuf[ibufindex].SetSPHDen(rhotemp); #ifdef STARON Pbuf[ibufindex].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbuf[ibufindex].SetInputFileID(i); Pbuf[ibufindex].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif //ensure that store number of particles to be sent to the reading threads if (ibuf==ThisTask) { Nlocalbaryon[1]++; } MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocalbaryon[0], Pbaryons, Nreadbuf, Preadbuf); #else Pbaryons[bcount2]=Particle(mtemp*mscale, xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale, vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0], vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1], vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2], count2,GASTYPE); Pbaryons[bcount2].SetPID(idval); #ifdef GASON Pbaryons[bcount2].SetU(utemp); Pbaryons[bcount2].SetSPHDen(rhotemp); #ifdef STARON Pbaryons[bcount2].SetZmet(Ztemp); #endif #endif #ifdef EXTRAINPUTINFO if (opt.iextendedoutput) { Pbaryons[bcount2].SetInputFileID(i); Pbaryons[bcount2].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset); } #endif #endif bcount2++; } } } } } } } if (chunksize>0) { delete[] xtempchunk; delete[] hydrotempchunk; } } } Famr[i].close(); #ifdef USEMPI //send information between read threads if (opt.nsnapread>1&&inreadsend<totreadsend){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); inreadsend++; for(ibuf = 0; ibuf < opt.nsnapread; ibuf++) Nreadbuf[ibuf]=0; } #endif } #ifdef USEMPI //once finished reading the file if there are any particles left in the buffer broadcast them for(ibuf = 0; ibuf < NProcs; ibuf++) if (ireadtask[ibuf]<0) { MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t, ibuf, ibuf+NProcs, MPI_COMM_WORLD); if (Nbuf[ibuf]>0) { MPI_Ssend(&Pbuf[ibuf*BufSize], sizeof(Particle)*Nbuf[ibuf], MPI_BYTE, ibuf, ibuf, MPI_COMM_WORLD); MPISendHydroInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf); MPISendStarInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf); MPISendBHInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf); Nbuf[ibuf]=0; //last broadcast with Nbuf[ibuf]=0 so that receiver knows no more particles are to be broadcast MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t,ibuf,ibuf+NProcs,MPI_COMM_WORLD); } } if (opt.nsnapread>1){ MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read); MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon); } }//end of reading task #endif #ifdef USEMPI //if not reading information than waiting to receive information else { MPIReceiveParticlesFromReadThreads(opt,Pbuf,Part.data(),readtaskID, irecv, mpi_irecvflag, Nlocalthreadbuf, mpi_request,Pbaryons); } #endif }//end of check if gas loaded //update info opt.p*=opt.a/opt.h; #ifdef HIGHRES opt.zoomlowmassdm=MP_DM*mscale; #endif #ifdef USEMPI MPI_Barrier(MPI_COMM_WORLD); //update cosmological data and boundary in code units MPI_Bcast(&(opt.p),sizeof(opt.p),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.a),sizeof(opt.a),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_cdm),sizeof(opt.Omega_cdm),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_b),sizeof(opt.Omega_b),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_m),sizeof(opt.Omega_m),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.Omega_Lambda),sizeof(opt.Omega_Lambda),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.h),sizeof(opt.h),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.rhocrit),sizeof(opt.rhocrit),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.rhobg),sizeof(opt.rhobg),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.virlevel),sizeof(opt.virlevel),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.virBN98),sizeof(opt.virBN98),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.ellxscale),sizeof(opt.ellxscale),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.lengthinputconversion),sizeof(opt.lengthinputconversion),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.velocityinputconversion),sizeof(opt.velocityinputconversion),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.massinputconversion),sizeof(opt.massinputconversion),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&(opt.G),sizeof(opt.G),MPI_BYTE,0,MPI_COMM_WORLD); #ifdef NOMASS MPI_Bcast(&(opt.MassValue),sizeof(opt.MassValue),MPI_BYTE,0,MPI_COMM_WORLD); #endif MPI_Bcast(&(Ntotal),sizeof(Ntotal),MPI_BYTE,0,MPI_COMM_WORLD); MPI_Bcast(&opt.zoomlowmassdm,sizeof(opt.zoomlowmassdm),MPI_BYTE,0,MPI_COMM_WORLD); #endif //store how to convert input internal energies to physical output internal energies //as we already convert ramses units to sensible output units, nothing to do. opt.internalenergyinputconversion = 1.0; //a bit of clean up #ifdef USEMPI MPI_Comm_free(&mpi_comm_read); if (opt.iBaryonSearch) delete[] mpi_nsend_baryon; if (opt.nsnapread>1) { delete[] mpi_nsend_readthread; if (opt.iBaryonSearch) delete[] mpi_nsend_readthread_baryon; if (ireadtask[ThisTask]>=0) delete[] Preadbuf; } delete[] Nbuf; if (ireadtask[ThisTask]>=0) { delete[] Nreadbuf; delete[] Pbuf; } delete[] ireadtask; delete[] readtaskID; #endif }
45.114682
221
0.595884
bwvdnbro
1b33777a2a36ad950befdfe2fc1206700de58728
4,432
cpp
C++
tools/nx_probe.cpp
tienex/apfs
afc6041c6078d3bc96c2ffec8ea6a8e572b79678
[ "MIT" ]
42
2017-12-01T15:23:20.000Z
2022-02-25T07:08:28.000Z
tools/nx_probe.cpp
tienex/apfs
afc6041c6078d3bc96c2ffec8ea6a8e572b79678
[ "MIT" ]
3
2017-12-04T19:31:53.000Z
2018-07-27T22:47:41.000Z
tools/nx_probe.cpp
tienex/apfs
afc6041c6078d3bc96c2ffec8ea6a8e572b79678
[ "MIT" ]
5
2017-12-02T22:10:53.000Z
2019-11-15T05:06:46.000Z
/* * Copyright (c) 2017-present Orlando Bassotto * * 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 "nx/nx.h" #include "nxcompat/nxcompat.h" #include <cstdio> #include <cstdlib> #include <memory> #include <string> #include <vector> #define INVALID_XID (static_cast<uint64_t>(-1)) static void usage(char const *progname) { fprintf(stderr, "usage: %s [-f|-x xid] [-kpq] device\n", progname); } enum action { ACTION_PRINT_NAME, ACTION_PRINT_UUID, ACTION_CHECK }; int main(int argc, char **argv) { char const *progname = *argv; bool first_xid = false; uint64_t xid = INVALID_XID; enum action action = ACTION_PRINT_NAME; int c; while ((c = getopt(argc, argv, "fkpqx:")) != EOF) { switch (c) { case 'p': action = ACTION_PRINT_NAME; break; case 'k': action = ACTION_PRINT_UUID; break; case 'q': action = ACTION_CHECK; break; case 'f': first_xid = true; break; case 'x': xid = strtoull(optarg, nullptr, 0); break; default: usage(progname); exit(EXIT_FAILURE); } } argc -= optind; argv += optind; if (argc < 1) { usage(progname); exit(EXIT_FAILURE); } std::string devname = argv[0]; // // Is this a real path? // if (access(devname.c_str(), R_OK) != 0 && errno == ENOENT) { std::string devname2 = "/dev/" + devname; if (access(devname2.c_str(), R_OK) != 0) { fprintf(stderr, "error: cannot find '%s' for reading: %s\n", devname.c_str(), strerror(errno)); exit(EXIT_FAILURE); } devname = devname2; } nx::context context; nx::device device; context.set_main_device(&device); if (!device.open(devname.c_str())) { fprintf(stderr, "error: cannot open '%s' for reading: %s\n", devname.c_str(), strerror(errno)); exit(EXIT_FAILURE); } auto container = new nx::container(&context); bool opened; if (xid != INVALID_XID) { opened = container->open_at(xid); } else { opened = container->open(!first_xid); } if (!opened) { exit(EXIT_FAILURE); } nx::container::info info; if (!container->get_info(info)) { exit(EXIT_FAILURE); } char buf[128]; auto vused = info.volumes - info.vfree; if (vused > 1) { auto uuid = container->get_uuid(); nx_uuid_format(&uuid, buf, sizeof(buf)); if (action == ACTION_PRINT_UUID) { printf("%s\n", buf); } else if (action == ACTION_PRINT_NAME) { printf("APFS Container %s\n", buf); } } else { auto volume = container->open_volume(0); if (volume == nullptr) { exit(EXIT_FAILURE); } if (action == ACTION_PRINT_UUID) { auto uuid = volume->get_uuid(); nx_uuid_format(&uuid, buf, sizeof(buf)); printf("%s\n", buf); } else if (action == ACTION_PRINT_NAME) { printf("%s\n", volume->get_name()); } delete volume; } delete container; exit(EXIT_SUCCESS); return EXIT_SUCCESS; }
26.538922
81
0.580325
tienex
1b33bc669f78412647362d828eaa5216b33aa488
632
cpp
C++
3425/6859847_AC_16MS_236K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
3425/6859847_AC_16MS_236K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
3425/6859847_AC_16MS_236K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<iostream> #include<map> using namespace std; int main(){ int answerNum; cin>>answerNum; map<int,int> correctAnswerNum; int payment=0; while(answerNum--){ int questionID; bool correct,withExplanaion; cin>>questionID>>correct>>withExplanaion; if(correct){ if(withExplanaion) payment+=40; else payment+=20; if(correctAnswerNum.find(questionID)==correctAnswerNum.end()) correctAnswerNum[questionID]=1; else{ payment+=10*correctAnswerNum[questionID]; correctAnswerNum[questionID]++; } } else payment+=10; } cout<<payment<<endl; return 0; }
20.387097
65
0.664557
vandreas19
1b33e290fe7aadf4e139364e21a216ca8e69e244
8,237
cc
C++
chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/views/permission_bubble/chooser_bubble_ui.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/callback_helpers.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/views/bubble_anchor_util_views.h" #include "chrome/browser/ui/views/device_chooser_content_view.h" #include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h" #include "chrome/browser/ui/views/title_origin_label.h" #include "components/permissions/chooser_controller.h" #include "extensions/buildflags/buildflags.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/styled_label.h" #include "ui/views/controls/table/table_view_observer.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/chrome_extension_chooser_dialog.h" #include "extensions/browser/app_window/app_window_registry.h" #endif using bubble_anchor_util::AnchorConfiguration; namespace { AnchorConfiguration GetChooserAnchorConfiguration(Browser* browser) { return bubble_anchor_util::GetPageInfoAnchorConfiguration(browser); } gfx::Rect GetChooserAnchorRect(Browser* browser) { return bubble_anchor_util::GetPageInfoAnchorRect(browser); } } // namespace /////////////////////////////////////////////////////////////////////////////// // View implementation for the chooser bubble. class ChooserBubbleUiViewDelegate : public LocationBarBubbleDelegateView, public views::TableViewObserver { public: METADATA_HEADER(ChooserBubbleUiViewDelegate); ChooserBubbleUiViewDelegate( Browser* browser, content::WebContents* web_contents, std::unique_ptr<permissions::ChooserController> chooser_controller); ChooserBubbleUiViewDelegate(const ChooserBubbleUiViewDelegate&) = delete; ChooserBubbleUiViewDelegate& operator=(const ChooserBubbleUiViewDelegate&) = delete; ~ChooserBubbleUiViewDelegate() override; // views::View: void AddedToWidget() override; // views::WidgetDelegate: std::u16string GetWindowTitle() const override; // views::DialogDelegate: bool IsDialogButtonEnabled(ui::DialogButton button) const override; views::View* GetInitiallyFocusedView() override; // views::TableViewObserver: void OnSelectionChanged() override; // Updates the anchor's arrow and view. Also repositions the bubble so it's // displayed in the correct location. void UpdateAnchor(Browser* browser); void UpdateTableView() const; base::OnceClosure MakeCloseClosure(); void Close(); private: raw_ptr<DeviceChooserContentView> device_chooser_content_view_ = nullptr; base::WeakPtrFactory<ChooserBubbleUiViewDelegate> weak_ptr_factory_{this}; }; ChooserBubbleUiViewDelegate::ChooserBubbleUiViewDelegate( Browser* browser, content::WebContents* contents, std::unique_ptr<permissions::ChooserController> chooser_controller) : LocationBarBubbleDelegateView( GetChooserAnchorConfiguration(browser).anchor_view, contents) { // ------------------------------------ // | Chooser bubble title | // | -------------------------------- | // | | option 0 | | // | | option 1 | | // | | option 2 | | // | | | | // | | | | // | | | | // | -------------------------------- | // | [ Connect ] [ Cancel ] | // |----------------------------------| // | Get help | // ------------------------------------ SetButtonLabel(ui::DIALOG_BUTTON_OK, chooser_controller->GetOkButtonLabel()); SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, chooser_controller->GetCancelButtonLabel()); SetLayoutManager(std::make_unique<views::FillLayout>()); device_chooser_content_view_ = new DeviceChooserContentView(this, std::move(chooser_controller)); AddChildView(device_chooser_content_view_.get()); SetExtraView(device_chooser_content_view_->CreateExtraView()); SetAcceptCallback( base::BindOnce(&DeviceChooserContentView::Accept, base::Unretained(device_chooser_content_view_))); SetCancelCallback( base::BindOnce(&DeviceChooserContentView::Cancel, base::Unretained(device_chooser_content_view_))); SetCloseCallback( base::BindOnce(&DeviceChooserContentView::Close, base::Unretained(device_chooser_content_view_))); chrome::RecordDialogCreation(chrome::DialogIdentifier::CHOOSER_UI); } ChooserBubbleUiViewDelegate::~ChooserBubbleUiViewDelegate() = default; void ChooserBubbleUiViewDelegate::AddedToWidget() { GetBubbleFrameView()->SetTitleView(CreateTitleOriginLabel(GetWindowTitle())); } std::u16string ChooserBubbleUiViewDelegate::GetWindowTitle() const { return device_chooser_content_view_->GetWindowTitle(); } views::View* ChooserBubbleUiViewDelegate::GetInitiallyFocusedView() { return GetCancelButton(); } bool ChooserBubbleUiViewDelegate::IsDialogButtonEnabled( ui::DialogButton button) const { return device_chooser_content_view_->IsDialogButtonEnabled(button); } void ChooserBubbleUiViewDelegate::OnSelectionChanged() { DialogModelChanged(); } void ChooserBubbleUiViewDelegate::UpdateAnchor(Browser* browser) { AnchorConfiguration configuration = GetChooserAnchorConfiguration(browser); SetAnchorView(configuration.anchor_view); SetHighlightedButton(configuration.highlighted_button); if (!configuration.anchor_view) SetAnchorRect(GetChooserAnchorRect(browser)); SetArrow(configuration.bubble_arrow); } void ChooserBubbleUiViewDelegate::UpdateTableView() const { device_chooser_content_view_->UpdateTableView(); } base::OnceClosure ChooserBubbleUiViewDelegate::MakeCloseClosure() { return base::BindOnce(&ChooserBubbleUiViewDelegate::Close, weak_ptr_factory_.GetWeakPtr()); } void ChooserBubbleUiViewDelegate::Close() { if (GetWidget()) GetWidget()->CloseWithReason(views::Widget::ClosedReason::kUnspecified); } BEGIN_METADATA(ChooserBubbleUiViewDelegate, LocationBarBubbleDelegateView) END_METADATA namespace chrome { base::OnceClosure ShowDeviceChooserDialog( content::RenderFrameHost* owner, std::unique_ptr<permissions::ChooserController> controller) { auto* contents = content::WebContents::FromRenderFrameHost(owner); #if BUILDFLAG(ENABLE_EXTENSIONS) if (extensions::AppWindowRegistry::Get(owner->GetBrowserContext()) ->GetAppWindowForWebContents(contents)) { ShowConstrainedDeviceChooserDialog(contents, std::move(controller)); // This version of the chooser dialog does not support being closed by the // code which created it. return base::DoNothing(); } #endif auto* browser = chrome::FindBrowserWithWebContents(contents); if (!browser) return base::DoNothing(); if (browser->tab_strip_model()->GetActiveWebContents() != contents) return base::DoNothing(); auto bubble = std::make_unique<ChooserBubbleUiViewDelegate>( browser, contents, std::move(controller)); // Set |parent_window_| because some valid anchors can become hidden. views::Widget* parent_widget = views::Widget::GetWidgetForNativeWindow( browser->window()->GetNativeWindow()); gfx::NativeView parent = parent_widget->GetNativeView(); DCHECK(parent); bubble->set_parent_window(parent); bubble->UpdateAnchor(browser); base::OnceClosure close_closure = bubble->MakeCloseClosure(); views::Widget* widget = views::BubbleDialogDelegateView::CreateBubble(std::move(bubble)); if (browser->window()->IsActive()) widget->Show(); else widget->ShowInactive(); return close_closure; } } // namespace chrome
35.051064
83
0.717373
chromium
1b35b13dfbc9ac339d9e12246414b4aa61a1a6c6
624
cpp
C++
LeetCode/Problems/Algorithms/#1695_MaximumErasureValue_sol2_sliding_window_O(N+MAX_ELEM)_time_O(MAX_ELEM)_extra_space_156ms_89.1MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1695_MaximumErasureValue_sol2_sliding_window_O(N+MAX_ELEM)_time_O(MAX_ELEM)_extra_space_156ms_89.1MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1695_MaximumErasureValue_sol2_sliding_window_O(N+MAX_ELEM)_time_O(MAX_ELEM)_extra_space_156ms_89.1MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int maximumUniqueSubarray(vector<int>& nums) { const int N = nums.size(); const int MAX_ELEM = *max_element(nums.begin(), nums.end()); int answer = 0; vector<bool> vis(MAX_ELEM + 1, false); for(int i = 0, j = 0, sum = 0; j < N; ++j){ while(vis[nums[j]]){ vis[nums[i]] = false; sum -= nums[i]; i += 1; } vis[nums[j]] = true; sum += nums[j]; answer = max(sum, answer); } return answer; } };
28.363636
69
0.410256
Tudor67
1b38aac35db9f5c16cc5068e19416838a2645978
1,581
cc
C++
tensorflow/core/graph/while_context.cc
tianyapiaozi/tensorflow
fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a
[ "Apache-2.0" ]
71
2017-05-25T16:02:15.000Z
2021-06-09T16:08:08.000Z
tensorflow/core/graph/while_context.cc
shrikunjsarda/tensorflow
7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae
[ "Apache-2.0" ]
133
2017-04-26T16:49:49.000Z
2019-10-15T11:39:26.000Z
tensorflow/core/graph/while_context.cc
shrikunjsarda/tensorflow
7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae
[ "Apache-2.0" ]
31
2018-09-11T02:17:17.000Z
2021-12-15T10:33:35.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/graph/while_context.h" namespace tensorflow { WhileContext::WhileContext(StringPiece frame_name, std::vector<Node*> enter_nodes, std::vector<Node*> exit_nodes, OutputTensor cond_output, std::vector<OutputTensor> body_inputs, std::vector<OutputTensor> body_outputs) : frame_name_(std::string(frame_name)), enter_nodes_(std::move(enter_nodes)), exit_nodes_(std::move(exit_nodes)), cond_output_(cond_output), body_inputs_(std::move(body_inputs)), body_outputs_(std::move(body_outputs)) { const size_t num_loop_vars = enter_nodes_.size(); DCHECK_EQ(exit_nodes_.size(), num_loop_vars); DCHECK_EQ(body_inputs_.size(), num_loop_vars); DCHECK_EQ(body_outputs_.size(), num_loop_vars); } } // namespace tensorflow
40.538462
80
0.664769
tianyapiaozi
1b3a262e959eca2cba52e2f2f5e971429ce17db9
568
cpp
C++
Engine/SQ/Renderer/Renderer.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
Engine/SQ/Renderer/Renderer.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
Engine/SQ/Renderer/Renderer.cpp
chry003/SqEngine
bb98881a29da48c8c92b33c3534da1fcdd46b92a
[ "MIT" ]
null
null
null
#include "pch.hpp" #include "Renderer.hpp" namespace Sq { Renderer::OrthographicCameraMatrix* Renderer::m_RendererElements = new Renderer::OrthographicCameraMatrix; void Renderer::Begin(OrthographicCamera& camera) { m_RendererElements->ViewProjectionMatrix = camera.GetViewProjectionMatrix(); } void Renderer::Submit(const Ref<VertexArray>& vertexArray, const Ref<Shader>& shader) { shader->Bind(); vertexArray->Bind(); shader->SetMat4("u_ViewPorjectionMatrix", m_RendererElements->ViewProjectionMatrix); RendererCommand::Draw(vertexArray); } }
25.818182
107
0.772887
chry003
1b3a7e04b3e2384f8f7c4fec8d5927b598e19444
4,804
cpp
C++
apps/ossim-cli/ossim-cli.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
1
2018-03-04T10:45:56.000Z
2018-03-04T10:45:56.000Z
apps/ossim-cli/ossim-cli.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
null
null
null
apps/ossim-cli/ossim-cli.cpp
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
null
null
null
//************************************************************************************************** // // OSSIM Open Source Geospatial Data Processing Library // See top level LICENSE.txt file for license information // //************************************************************************************************** #include <iostream> #include <sstream> #include <map> using namespace std; #include <ossim/init/ossimInit.h> #include <ossim/base/ossimArgumentParser.h> #include <ossim/base/ossimApplicationUsage.h> #include <ossim/base/ossimStdOutProgress.h> #include <ossim/base/ossimTimer.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/util/ossimToolRegistry.h> #include <ossim/base/ossimException.h> #define CINFO ossimNotify(ossimNotifyLevel_INFO) #define CWARN ossimNotify(ossimNotifyLevel_WARN) #define CFATAL ossimNotify(ossimNotifyLevel_FATAL) void showAvailableCommands() { ossimToolFactoryBase* factory = ossimToolRegistry::instance(); map<string, string> capabilities; factory->getCapabilities(capabilities); map<string, string>::iterator iter = capabilities.begin(); CINFO<<"\nAvailable commands:\n"<<endl; for (;iter != capabilities.end(); ++iter) CINFO<<" "<<iter->first<<" -- "<<iter->second<<endl; CINFO<<endl; } void usage(char* appName) { CINFO << "\nUsages: \n" << " "<<appName<<" <command> [command options and parameters]\n" << " "<<appName<<" --spec <command-spec-file>\n" << " "<<appName<<" --version\n" << " "<<appName<<" help <command> -- To get help on specific command."<<endl; showAvailableCommands(); } bool runCommand(ossimArgumentParser& ap) { ossimString command = ap[1]; ap.remove(1); ossimToolFactoryBase* factory = ossimToolRegistry::instance(); ossimRefPtr<ossimTool> utility = factory->createTool(command); if (!utility.valid()) { CWARN << "\nDid not understand command <"<<command<<">"<<endl; showAvailableCommands(); return false; } ossimTimer* timer = ossimTimer::instance(); timer->setStartTick(); if (!utility->initialize(ap)) { CWARN << "\nCould not execute command <"<<command<<"> with arguments and options " "provided."<<endl; return false; } if (utility->helpRequested()) return true; if (!utility->execute()) { CWARN << "\nAn error was encountered executing the command. Check options."<<endl; return false; } //CINFO << "\nElapsed time after initialization: "<<timer->time_s()<<" s.\n"<<endl; return true; } int main(int argc, char *argv[]) { ossimArgumentParser ap (&argc, argv); ap.getApplicationUsage()->setApplicationName(argv[0]); bool status_ok = true; try { // Initialize ossim stuff, factories, plugin, etc. ossimInit::instance()->initialize(ap); do { if (argc == 1) { // Blank command line: usage(argv[0]); break; } // Spec file provided containing command's arguments and options? ossimString argv1 = argv[1]; if (( argv1 == "--spec") && (argc > 2)) { // Command line provided in spec file: ifstream ifs (argv[2]); if (ifs.fail()) { CWARN<<"\nCould not open the spec file at <"<<argv[2]<<">\n"<<endl; status_ok = false; break; } ossimString spec; ifs >> spec; ifs.close(); ossimArgumentParser new_ap(spec); status_ok = runCommand(new_ap); break; } // Need help with app or specific command? if (argv1.contains("help")) { // If no command was specified, then general usage help shown: if (argc == 2) { // Blank command line: usage(argv[0]); break; } else { // rearrange command line for individual utility help: ostringstream cmdline; cmdline<<argv[0]<<" "<<argv[2]<<" --help"; ossimArgumentParser new_ap(cmdline.str()); status_ok = runCommand(new_ap); break; } } if (argv1.string()[0] == '-') { // Treat as info call: ap.insert(1, "info"); status_ok = runCommand(ap); break; } // Conventional command line, just remove this app's name: status_ok = runCommand(ap); } while (false); } catch (const exception& e) { CFATAL<<e.what()<<endl; exit(1); } if (status_ok) exit(0); exit(1); }
28.093567
100
0.541216
IvanLJF
1b3d730d31d8ba59d01928ed4ffef1d92a825262
1,065
hpp
C++
libs/cg/include/sge/cg/parameter/detail/check_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/cg/include/sge/cg/parameter/detail/check_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/cg/include/sge/cg/parameter/detail/check_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_CG_PARAMETER_DETAIL_CHECK_TYPE_HPP_INCLUDED #define SGE_CG_PARAMETER_DETAIL_CHECK_TYPE_HPP_INCLUDED #include <sge/cg/detail/symbol.hpp> #include <sge/cg/parameter/object_fwd.hpp> #include <sge/cg/parameter/detail/pp_types.hpp> #include <fcppt/config/external_begin.hpp> #include <boost/preprocessor/seq/for_each.hpp> #include <fcppt/config/external_end.hpp> namespace sge::cg::parameter::detail { template <typename Type> SGE_CG_DETAIL_SYMBOL void check_type(sge::cg::parameter::object const &); } #define SGE_CG_PARAMETER_DETAIL_DECLARE_CHECK_TYPE(seq, _, base_type) \ extern template SGE_CG_DETAIL_SYMBOL void sge::cg::parameter::detail::check_type<base_type>( \ sge::cg::parameter::object const &); BOOST_PP_SEQ_FOR_EACH( SGE_CG_PARAMETER_DETAIL_DECLARE_CHECK_TYPE, _, SGE_CG_PARAMETER_DETAIL_PP_TYPES) #endif
33.28125
96
0.781221
cpreh
1b42156890e93c25f7cb3fb2fbd55c5270efd3ec
745
cpp
C++
third_party/sol2/examples/require_dll_example/my_object.cpp
EricWang1hitsz/osrm-backend
ff1af413d6c78f8e454584fe978d5468d984d74a
[ "BSD-2-Clause" ]
4,526
2015-01-01T15:31:00.000Z
2022-03-31T17:33:49.000Z
third_party/sol2/examples/require_dll_example/my_object.cpp
wsx9527/osrm-backend
1e70b645e480946dad313b67f6a7d331baecfe3c
[ "BSD-2-Clause" ]
4,497
2015-01-01T15:29:12.000Z
2022-03-31T19:19:35.000Z
third_party/sol2/examples/require_dll_example/my_object.cpp
wsx9527/osrm-backend
1e70b645e480946dad313b67f6a7d331baecfe3c
[ "BSD-2-Clause" ]
3,023
2015-01-01T18:40:53.000Z
2022-03-30T13:30:46.000Z
#include "my_object.hpp" #define SOL_CHECK_ARGUMENTS 1 #include <sol.hpp> namespace my_object { sol::table open_my_object(sol::this_state L) { sol::state_view lua(L); sol::table module = lua.create_table(); module.new_usertype<test>("test", sol::constructors<test(), test(int)>(), "value", &test::value ); return module; } } // namespace my_object extern "C" int luaopen_my_object(lua_State* L) { // pass the lua_State, // the index to start grabbing arguments from, // and the function itself // optionally, you can pass extra arguments to the function if that's necessary, // but that's advanced usage and is generally reserved for internals only return sol::stack::call_lua(L, 1, my_object::open_my_object ); }
25.689655
81
0.714094
EricWang1hitsz
1b44f1786a0e9ff5bb3663ab4bfc25af064cea78
8,420
hpp
C++
include/codegen/include/Zenject/PlaceholderFactory_11.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/PlaceholderFactory_11.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/PlaceholderFactory_11.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:44 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: Zenject.PlaceholderFactoryBase`1 #include "Zenject/PlaceholderFactoryBase_1.hpp" // Including type: Zenject.IFactory`11 #include "Zenject/IFactory_11.hpp" // Including type: System.Collections.Generic.IEnumerable`1 #include "System/Collections/Generic/IEnumerable_1.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Zenject namespace Zenject { // Skipping declaration: <get_ParamTypes>d__2 because it is already included! } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.PlaceholderFactory`11 template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10> class PlaceholderFactory_11 : public Zenject::PlaceholderFactoryBase_1<TValue>, public Zenject::IFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>, public Zenject::IFactory { public: // Nested type: Zenject::PlaceholderFactory_11::$get_ParamTypes$d__2<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue> class $get_ParamTypes$d__2; // Autogenerated type: Zenject.PlaceholderFactory`11/<get_ParamTypes>d__2 class $get_ParamTypes$d__2 : public ::Il2CppObject, public ::il2cpp_utils::il2cpp_type_check::NestedType, public System::Collections::Generic::IEnumerable_1<System::Type*>, public System::Collections::IEnumerable, public System::Collections::Generic::IEnumerator_1<System::Type*>, public System::Collections::IEnumerator, public System::IDisposable { public: using declaring_type = PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*; // private System.Int32 <>1__state // Offset: 0x0 int $$1__state; // private System.Type <>2__current // Offset: 0x0 System::Type* $$2__current; // private System.Int32 <>l__initialThreadId // Offset: 0x0 int $$l__initialThreadId; // public System.Void .ctor(System.Int32 $$1__state) // Offset: 0x15D5C40 static typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2* New_ctor(int $$1__state) { return (typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2*>::get(), $$1__state)); } // private System.Void System.IDisposable.Dispose() // Offset: 0x15D5C80 // Implemented from: System.IDisposable // Base method: System.Void IDisposable::Dispose() void System_IDisposable_Dispose() { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.IDisposable.Dispose")); } // private System.Boolean MoveNext() // Offset: 0x15D5C84 // Implemented from: System.Collections.IEnumerator // Base method: System.Boolean IEnumerator::MoveNext() bool MoveNext() { return CRASH_UNLESS(il2cpp_utils::RunMethod<bool>(this, "MoveNext")); } // private System.Type System.Collections.Generic.IEnumerator<System.Type>.get_Current() // Offset: 0x15D6090 // Implemented from: System.Collections.Generic.IEnumerator`1 // Base method: T IEnumerator`1::get_Current() System::Type* System_Collections_Generic_IEnumerator_1_get_Current() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Type*>(this, "System.Collections.Generic.IEnumerator<System.Type>.get_Current")); } // private System.Void System.Collections.IEnumerator.Reset() // Offset: 0x15D6098 // Implemented from: System.Collections.IEnumerator // Base method: System.Void IEnumerator::Reset() void System_Collections_IEnumerator_Reset() { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.Collections.IEnumerator.Reset")); } // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0x15D60F8 // Implemented from: System.Collections.IEnumerator // Base method: System.Object IEnumerator::get_Current() ::Il2CppObject* System_Collections_IEnumerator_get_Current() { return CRASH_UNLESS(il2cpp_utils::RunMethod<::Il2CppObject*>(this, "System.Collections.IEnumerator.get_Current")); } // private System.Collections.Generic.IEnumerator`1<System.Type> System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator() // Offset: 0x15D6100 // Implemented from: System.Collections.Generic.IEnumerable`1 // Base method: System.Collections.Generic.IEnumerator`1<T> IEnumerable`1::GetEnumerator() System::Collections::Generic::IEnumerator_1<System::Type*>* System_Collections_Generic_IEnumerable_1_GetEnumerator() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerator_1<System::Type*>*>(this, "System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator")); } // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0x15D6194 // Implemented from: System.Collections.IEnumerable // Base method: System.Collections.IEnumerator IEnumerable::GetEnumerator() System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::IEnumerator*>(this, "System.Collections.IEnumerable.GetEnumerator")); } }; // Zenject.PlaceholderFactory`11/<get_ParamTypes>d__2 // public TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10) // Offset: 0x15D61B8 TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10) { return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Create", param1, param2, param3, param4, param5, param6, param7, param8, param9, param10)); } // protected override System.Collections.Generic.IEnumerable`1<System.Type> get_ParamTypes() // Offset: 0x15D64AC // Implemented from: Zenject.PlaceholderFactoryBase`1 // Base method: System.Collections.Generic.IEnumerable`1<System.Type> PlaceholderFactoryBase`1::get_ParamTypes() System::Collections::Generic::IEnumerable_1<System::Type*>* get_ParamTypes() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerable_1<System::Type*>*>(this, "get_ParamTypes")); } // public System.Void .ctor() // Offset: 0x15D650C // Implemented from: Zenject.PlaceholderFactoryBase`1 // Base method: System.Void PlaceholderFactoryBase`1::.ctor() // Base method: System.Void Object::.ctor() static PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>* New_ctor() { return (PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*>::get())); } }; // Zenject.PlaceholderFactory`11 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::PlaceholderFactory_11, "Zenject", "PlaceholderFactory`11"); #pragma pack(pop)
65.78125
428
0.740855
Futuremappermydud
1b46e1fbcd5e96681945dca1dce78d1d4eed6306
524
cpp
C++
src/utils.cpp
armagidon-exception/watch-os
83c9adf814313f88101d8a57da1e50c45e98bb49
[ "MIT" ]
null
null
null
src/utils.cpp
armagidon-exception/watch-os
83c9adf814313f88101d8a57da1e50c45e98bb49
[ "MIT" ]
null
null
null
src/utils.cpp
armagidon-exception/watch-os
83c9adf814313f88101d8a57da1e50c45e98bb49
[ "MIT" ]
null
null
null
#include "utils.h" void setBit(uint8_t* data, uint8_t bit, bool flag) { if (flag) { *data = *data | (1 << bit); } else { *data = *data & ~(1 << bit); } } Dimension createDimension(unit w, unit h) { return {w, h}; } Vec2D createVec2D(unit x, unit y) { return {x, y}; } sunit getVecX(Vec2D* vec) { return (sunit) vec->x; } sunit getVecY(Vec2D* vec) { return (sunit) vec->y; } unit abs(sunit x) { if (x & (1 << 7) != 0) { x = ~x; x + 1; } return x; }
16.375
52
0.5
armagidon-exception
1b4738d727dd738d156ea45e7f725d74c208cc7c
10,090
cpp
C++
modules/serialflash/spiflash.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
13
2018-02-26T14:56:02.000Z
2022-03-31T06:01:56.000Z
modules/serialflash/spiflash.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
null
null
null
modules/serialflash/spiflash.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
3
2020-11-04T09:15:01.000Z
2021-07-06T09:42:00.000Z
/* ----------------------------------------------------------------------------- * This file is a part of the NVCM project: https://github.com/nvitya/nvcm * Copyright (c) 2018 Viktor Nagy, nvitya * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. Permission is granted to anyone to use this * software for any purpose, including commercial applications, and to alter * it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * --------------------------------------------------------------------------- */ /* * file: spiflash.cpp * brief: SPI Flash Memory Implementation * version: 1.00 * date: 2018-02-10 * authors: nvitya */ #include "spiflash.h" bool TSpiFlash::InitInherited() { if (!pin_cs.Assigned()) { return false; } if (!txdma.initialized || !rxdma.initialized) { return false; } spi.DmaAssign(true, &txdma); spi.DmaAssign(false, &rxdma); return true; } bool TSpiFlash::ReadIdCode() { txbuf[0] = 0x9F; txbuf[1] = 0x00; txbuf[2] = 0x00; txbuf[3] = 0x00; rxbuf[0] = 0; rxbuf[1] = 0; rxbuf[2] = 0; rxbuf[3] = 0; //rxbuf[0] = 0x55; rxbuf[1] = 0x56; rxbuf[2] = 0x57; rxbuf[3] = 0x58; ExecCmd(4); unsigned * up = (unsigned *)&(rxbuf[0]); idcode = (*up >> 8); if ((idcode == 0) || (idcode == 0x00FFFFFF)) { // SPI communication error return false; } return true; } void TSpiFlash::StartCmd(unsigned acmdlen) { pin_cs.Set1(); curcmdlen = acmdlen; txfer.srcaddr = &txbuf[0]; txfer.bytewidth = 1; txfer.count = curcmdlen; txfer.flags = 0; rxfer.dstaddr = &rxbuf[0]; rxfer.bytewidth = 1; rxfer.flags = 0; rxfer.count = txfer.count; pin_cs.Set0(); // activate CS spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); } void TSpiFlash::ExecCmd(unsigned acmdlen) { StartCmd(acmdlen); while (!spi.DmaRecvCompleted()) { // wait } pin_cs.Set1(); } void TSpiFlash::Run() { if (0 == state) { // idle return; } if (SERIALFLASH_STATE_READMEM == state) // read memory { switch (phase) { case 0: // start remaining = datalen; txbuf[0] = 0x03; // read command txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too phase = 1; break; case 1: // wait for address phase completition if (spi.DmaRecvCompleted()) { phase = 2; Run(); // phase jump return; } break; case 2: // start read next data chunk if (remaining == 0) { // finished. phase = 10; Run(); // phase jump return; } // start data phase chunksize = maxchunksize; if (chunksize > remaining) chunksize = remaining; txbuf[0] = 0; txfer.srcaddr = &txbuf[0]; txfer.bytewidth = 1; txfer.count = chunksize; txfer.flags = DMATR_NO_ADDR_INC; // sending the same zero character rxfer.dstaddr = dataptr; rxfer.bytewidth = 1; rxfer.flags = 0; rxfer.count = chunksize; spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); phase = 3; break; case 3: // wait for completion if (spi.DmaRecvCompleted()) { // read next chunk dataptr += chunksize; remaining -= chunksize; phase = 2; Run(); // phase jump return; } // TODO: timeout handling break; case 10: // finished pin_cs.Set1(); completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_WRITEMEM == state) // write memory { switch (phase) { case 0: // initialization remaining = datalen; ++phase; break; // write next chunk case 1: // set write enable if (remaining == 0) { // finished. phase = 20; Run(); // phase jump return; } // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // write data txbuf[0] = 0x02; // page program command txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { ++phase; Run(); // phase jump return; } break; case 5: // data phase chunksize = 256 - (address & 0xFF); // page size if (chunksize > remaining) chunksize = remaining; txfer.srcaddr = dataptr; txfer.bytewidth = 1; txfer.count = chunksize; txfer.flags = 0; rxfer.dstaddr = &rxbuf[0]; rxfer.bytewidth = 1; rxfer.flags = DMATR_NO_ADDR_INC; // ignore the received data rxfer.count = chunksize; spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); ++phase; break; case 6: // wait for completion if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); return; } // TODO: timeout handling break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // Write finished. address += chunksize; dataptr += chunksize; remaining -= chunksize; phase = 1; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_ERASE == state) // erase memory { switch (phase) { case 0: // initialization // correct start address if necessary if (address & erasemask) { // correct the length too datalen += (address & erasemask); address &= ~erasemask; } // round up to 4k the data length datalen = ((datalen + erasemask) & ~erasemask); remaining = datalen; ++phase; break; // erase next sector case 1: // set write enable if (remaining == 0) { // finished. phase = 20; Run(); // phase jump return; } // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // erase sector / block if (has4kerase && ((address & 0xFFFF) || (datalen < 0x10000))) { // 4k sector erase chunksize = 0x01000; txbuf[0] = 0x20; } else { // 64k block erase chunksize = 0x10000; txbuf[0] = 0xD8; } txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { phase = 7; Run(); // phase jump return; } break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // Write finished. address += chunksize; remaining -= chunksize; phase = 1; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_ERASEALL == state) // erase all / chip { switch (phase) { case 0: // initialization ++phase; break; case 1: // set write enable // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // issue bulk erase txbuf[0] = 0xC7; StartCmd(1); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { phase = 7; Run(); // phase jump return; } break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // finished. phase = 20; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } } bool TSpiFlash::StartReadStatus() { txbuf[0] = 0x05; txbuf[1] = 0x00; rxbuf[1] = 0x7F; StartCmd(2); return true; } void TSpiFlash::ResetChip() { txbuf[0] = 0x66; ExecCmd(1); txbuf[0] = 0x99; ExecCmd(1); }
20.50813
81
0.56888
nvitya
1b48126693701bb59724b694e26e7b2bfdd01d09
1,781
cpp
C++
project/c++/mri/src/PI-slim-napa/recdopt/ipconnstats/ipconnstats.cpp
jia57196/code41
df611f84592afd453ccb2d22a7ad999ddb68d028
[ "Apache-2.0" ]
null
null
null
project/c++/mri/src/PI-slim-napa/recdopt/ipconnstats/ipconnstats.cpp
jia57196/code41
df611f84592afd453ccb2d22a7ad999ddb68d028
[ "Apache-2.0" ]
null
null
null
project/c++/mri/src/PI-slim-napa/recdopt/ipconnstats/ipconnstats.cpp
jia57196/code41
df611f84592afd453ccb2d22a7ad999ddb68d028
[ "Apache-2.0" ]
null
null
null
#include "ipconnstats.h" #include "IPUtility.h" // // JSON formatted output strings // ostream& operator<<(ostream &out, const IPConnStatsKey &key) { string src = IPUtility::int_to_ip_str(key.isIpv6, &key.ipSrc[0]); string dst = IPUtility::int_to_ip_str(key.isIpv6, &key.ipDst[0]); out << "\"src_ip\" : \""<< src <<"\", "; out << "\"dst_ip\" : \""<< dst <<"\""; return out; } ostream& operator<<(ostream &out, const IPConnStatsData &data) { out << "\"src_bytes\" : " << data.src_bytes << ", "; out << "\"dst_bytes\" : " << data.dst_bytes << ", "; out << "\"src_frames\" : " << data.src_frames << ", "; out << "\"dst_frames\" : " << data.dst_frames << ", "; if(data.src_frames == 0) { out << "\"src_min_len\" : 0, "; out << "\"src_max_len\" : 0, "; } else { out << "\"src_min_len\" : " << data.src_min_len << ", "; out << "\"src_max_len\" : " << data.src_max_len << ", "; } if(data.dst_frames == 0) { out << "\"dst_min_len\" : 0, "; out << "\"dst_max_len\" : 0, "; } else { out << "\"dst_min_len\" : " << data.dst_min_len << ", "; out << "\"dst_max_len\" : " << data.dst_max_len << ", "; } out << "\"start_time\" : " << data.start_time << ", "; const int num_bins = 10; out << "\"src_bins\" : [ "; for(int i=0; i<num_bins; ++i) { out << data.src_bins[i]; if(i+1<num_bins) out << ", "; } out << "], "; out << "\"dst_bins\" : [ "; for(int i=0; i<num_bins; ++i) { out << data.dst_bins[i]; if(i+1<num_bins) out << ", "; } out << "] "; return out; }
25.084507
70
0.444133
jia57196
1b48e13003361890ece0a6ccd6af14a81d94865b
48
hpp
C++
examples/shared-sources/Source/Hello.hpp
chaos0x8/rake-builder
6320739bc1f4e9a9ec31af5cb12bf813b30eed66
[ "MIT" ]
2
2020-10-27T11:32:42.000Z
2020-10-28T21:12:20.000Z
examples/shared-sources/Source/Hello.hpp
chaos0x8/rake-builder
6320739bc1f4e9a9ec31af5cb12bf813b30eed66
[ "MIT" ]
null
null
null
examples/shared-sources/Source/Hello.hpp
chaos0x8/rake-builder
6320739bc1f4e9a9ec31af5cb12bf813b30eed66
[ "MIT" ]
null
null
null
#pragma once namespace lib { void hello(); }
8
15
0.645833
chaos0x8
1b4bdb5f79b497bb857543feb488bf793f0d6b23
3,179
cpp
C++
sDNA/geos/drop/src/geomgraph/index/SweepLineSegment.cpp
chrisc20042001/sDNA
22d11f150c28574c339457ce5cb0ad1d59b06277
[ "MIT" ]
48
2015-01-02T23:10:03.000Z
2021-12-23T01:37:22.000Z
sDNA/geos/drop/src/geomgraph/index/SweepLineSegment.cpp
chrisc20042001/sDNA
22d11f150c28574c339457ce5cb0ad1d59b06277
[ "MIT" ]
9
2019-05-31T14:19:43.000Z
2021-10-16T16:09:52.000Z
sDNA/geos/drop/src/geomgraph/index/SweepLineSegment.cpp
chrisc20042001/sDNA
22d11f150c28574c339457ce5cb0ad1d59b06277
[ "MIT" ]
28
2015-01-07T18:41:16.000Z
2021-03-25T02:29:13.000Z
/********************************************************************** * $Id: SweepLineSegment.cpp 1820 2006-09-06 16:54:23Z mloskot $ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geomgraph/index/SweepLineSegment.h> #include <geos/geomgraph/index/SegmentIntersector.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/Coordinate.h> #include <geos/geomgraph/Edge.h> using namespace geos::geom; namespace geos { namespace geomgraph { // geos.geomgraph namespace index { // geos.geomgraph.index SweepLineSegment::SweepLineSegment(Edge *newEdge, int newPtIndex): edge(newEdge), pts(newEdge->getCoordinates()), ptIndex(newPtIndex) { //pts=newEdge->getCoordinates(); //edge=newEdge; //ptIndex=newPtIndex; } SweepLineSegment::~SweepLineSegment() { } double SweepLineSegment::getMinX() { double x1=pts->getAt(ptIndex).x; double x2=pts->getAt(ptIndex+1).x; return x1<x2?x1:x2; } double SweepLineSegment::getMaxX() { double x1=pts->getAt(ptIndex).x; double x2=pts->getAt(ptIndex+1).x; return x1>x2?x1:x2; } void SweepLineSegment::computeIntersections(SweepLineSegment *ss, SegmentIntersector *si) { si->addIntersections(edge, ptIndex, ss->edge, ss->ptIndex); } } // namespace geos.geomgraph.index } // namespace geos.geomgraph } // namespace geos /********************************************************************** * $Log$ * Revision 1.6 2006/03/15 17:16:31 strk * streamlined headers inclusion * * Revision 1.5 2006/03/09 16:46:47 strk * geos::geom namespace definition, first pass at headers split * * Revision 1.4 2006/02/19 19:46:49 strk * Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs. * * Revision 1.3 2005/11/15 10:04:37 strk * * Reduced heap allocations (vectors, mostly). * Enforced const-correctness, changed some interfaces * to use references rather then pointers when appropriate. * * Revision 1.2 2004/07/02 13:28:27 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.1 2004/04/14 06:04:26 ybychkov * "geomgraph/index" committ problem fixed. * * Revision 1.10 2004/03/19 09:49:29 ybychkov * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4 * * Revision 1.9 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.8 2003/10/15 15:30:32 strk * Declared a SweepLineEventOBJ from which MonotoneChain and * SweepLineSegment derive to abstract SweepLineEvent object * previously done on void * pointers. * No more compiler warnings... * **********************************************************************/
29.165138
124
0.664674
chrisc20042001
1b4dc36550029270b7674cb5c6607127fc4f5938
556
hpp
C++
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/audio.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
1,414
2015-06-28T09:57:51.000Z
2021-10-14T03:51:10.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/audio.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
2,369
2015-06-25T01:45:44.000Z
2021-10-16T08:44:18.000Z
Real-Time Corruptor/BizHawk_RTC/waterbox/libsnes/bsnes/snes/system/audio.hpp
redscientistlabs/Bizhawk50X-Vanguard
96e0f5f87671a1230784c8faf935fe70baadfe48
[ "MIT" ]
430
2015-06-29T04:28:58.000Z
2021-10-05T18:24:17.000Z
struct Audio { void coprocessor_enable(bool state); void coprocessor_frequency(double frequency); void sample(int16 lsample, int16 rsample); void coprocessor_sample(int16 lsample, int16 rsample); void init(); private: nall::DSP dspaudio; bool coprocessor; enum : unsigned { buffer_size = 256, buffer_mask = buffer_size - 1 }; uint32 dsp_buffer[buffer_size], cop_buffer[buffer_size]; unsigned dsp_rdoffset, cop_rdoffset; unsigned dsp_wroffset, cop_wroffset; unsigned dsp_length, cop_length; void flush(); }; extern Audio audio;
26.47619
71
0.757194
redscientistlabs
1b51f0f5083947eacae4626a9abc0faf9a1f657b
7,706
cpp
C++
artifact/storm/src/storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.h" #include "storm/adapters/RationalNumberAdapter.h" #include "storm/storage/SparseMatrix.h" #include "storm/storage/BitVector.h" #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/utility/macros.h" namespace storm { namespace modelchecker { namespace helper { template<typename ValueType> BaierUpperRewardBoundsComputer<ValueType>::BaierUpperRewardBoundsComputer(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& rewards, std::vector<ValueType> const& oneStepTargetProbabilities) : _transitionMatrix(transitionMatrix), _rewards(rewards), _oneStepTargetProbabilities(oneStepTargetProbabilities) { // Intentionally left empty. } template<typename ValueType> std::vector<ValueType> BaierUpperRewardBoundsComputer<ValueType>::computeUpperBoundOnExpectedVisitingTimes(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& oneStepTargetProbabilities) { std::vector<uint64_t> stateToScc(transitionMatrix.getRowGroupCount()); { // Start with an SCC decomposition of the system. storm::storage::StronglyConnectedComponentDecomposition<ValueType> sccDecomposition(transitionMatrix); uint64_t sccIndex = 0; for (auto const& block : sccDecomposition) { for (auto const& state : block) { stateToScc[state] = sccIndex; } ++sccIndex; } } // The states that we still need to assign a value. storm::storage::BitVector remainingStates(transitionMatrix.getRowGroupCount(), true); // A choice is valid iff it goes to non-remaining states with non-zero probability. storm::storage::BitVector validChoices(transitionMatrix.getRowCount()); // Initially, mark all choices as valid that have non-zero probability to go to the target states directly. uint64_t index = 0; for (auto const& e : oneStepTargetProbabilities) { if (!storm::utility::isZero(e)) { validChoices.set(index); } ++index; } // Vector that holds the result. std::vector<ValueType> result(transitionMatrix.getRowGroupCount()); // Process all states as long as there are remaining ones. std::vector<uint64_t> newStates; while (!remainingStates.empty()) { for (auto state : remainingStates) { bool allChoicesValid = true; for (auto row = transitionMatrix.getRowGroupIndices()[state], endRow = transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { if (validChoices.get(row)) { continue; } bool choiceValid = false; for (auto const& entry : transitionMatrix.getRow(row)) { if (storm::utility::isZero(entry.getValue())) { continue; } if (!remainingStates.get(entry.getColumn())) { choiceValid = true; break; } } if (choiceValid) { validChoices.set(row); } else { allChoicesValid = false; } } if (allChoicesValid) { newStates.push_back(state); } } // Compute d_t over the newly found states. for (auto state : newStates) { result[state] = storm::utility::one<ValueType>(); for (auto row = transitionMatrix.getRowGroupIndices()[state], endRow = transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { ValueType rowValue = oneStepTargetProbabilities[row]; for (auto const& entry : transitionMatrix.getRow(row)) { if (!remainingStates.get(entry.getColumn())) { rowValue += entry.getValue() * (stateToScc[state] == stateToScc[entry.getColumn()] ? result[entry.getColumn()] : storm::utility::one<ValueType>()); } } STORM_LOG_ASSERT(rowValue > storm::utility::zero<ValueType>(), "Expected entry with value greater 0."); result[state] = std::min(result[state], rowValue); } } remainingStates.set(newStates.begin(), newStates.end(), false); newStates.clear(); } // Transform the d_t to an upper bound for zeta(t) for (auto& r : result) { r = storm::utility::one<ValueType>() / r; } return result; } template<typename ValueType> ValueType BaierUpperRewardBoundsComputer<ValueType>::computeUpperBound() { STORM_LOG_TRACE("Computing upper reward bounds using variant-2 of Baier et al."); std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); auto expVisits = computeUpperBoundOnExpectedVisitingTimes(_transitionMatrix, _oneStepTargetProbabilities); ValueType upperBound = storm::utility::zero<ValueType>(); for (uint64_t state = 0; state < expVisits.size(); ++state) { ValueType maxReward = storm::utility::zero<ValueType>(); for (auto row = _transitionMatrix.getRowGroupIndices()[state], endRow = _transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { maxReward = std::max(maxReward, _rewards[row]); } upperBound += expVisits[state] * maxReward; } STORM_LOG_TRACE("Baier algorithm for reward bound computation (variant 2) computed bound " << upperBound << "."); std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now(); STORM_LOG_TRACE("Computed upper bounds on rewards in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms."); return upperBound; } template class BaierUpperRewardBoundsComputer<double>; #ifdef STORM_HAVE_CARL template class BaierUpperRewardBoundsComputer<storm::RationalNumber>; #endif } } }
53.513889
363
0.511549
glatteis
1b52e38aa535264607607b5afb0abd5e3a2be306
2,044
cpp
C++
AISD1/main.cpp
rubikshift/AISD1
08b569fb3a7c426aa7eda6e12507c755a1aa9487
[ "MIT" ]
null
null
null
AISD1/main.cpp
rubikshift/AISD1
08b569fb3a7c426aa7eda6e12507c755a1aa9487
[ "MIT" ]
null
null
null
AISD1/main.cpp
rubikshift/AISD1
08b569fb3a7c426aa7eda6e12507c755a1aa9487
[ "MIT" ]
null
null
null
#include <iostream> #include "stack.h" #define INCREASE_SWITCH 'z' #define DECREASE_SWITCH 'o' #define PUSH_CARS 'w' #define POP_CARS 'j' #define RAIL_SWITCH_SIZE 10 using namespace std; int main() { char command; int temp, numberOFTracks, numberofCars, commandArg, numberOfCommands, currentTrack = 0; Stack railSwitch(RAIL_SWITCH_SIZE); Stack** tracks; cin >> numberOFTracks; tracks = new Stack*[numberOFTracks]; for (int i = 0; i < numberOFTracks; i++) { cin >> numberofCars; tracks[i] = new Stack(512 + numberofCars); for (int q = 0; q < numberofCars; q++) { cin >> temp; tracks[i]->pushToPosition(temp, numberofCars - q -1); } } currentTrack = 0; cin >> numberOfCommands; for (int i = 0; i < numberOfCommands; i++) { cin >> command; cin >> commandArg; switch (command) { case INCREASE_SWITCH: currentTrack += commandArg % numberOFTracks; if (currentTrack >= numberOFTracks) currentTrack -= numberOFTracks; break; case DECREASE_SWITCH: currentTrack -= commandArg % numberOFTracks; if (currentTrack < 0) currentTrack += numberOFTracks; break; case POP_CARS: for (int q = 0; q < commandArg; q++) { if (!railSwitch.isEmpty() && !(tracks[currentTrack]->isFull())) tracks[currentTrack]->push(railSwitch.pop()); } break; case PUSH_CARS: for (int q = 0; q < commandArg; q++) { if (!railSwitch.isFull() && !(tracks[currentTrack]->isEmpty())) railSwitch.push(tracks[currentTrack]->pop()); } break; default: break; } } cout << railSwitch.getSize(); while(!railSwitch.isEmpty()) cout << " " << railSwitch.pop(); cout << endl; for (int i = 0; i < numberOFTracks; i++) { cout << tracks[currentTrack]->getSize(); while(!(tracks[currentTrack]->isEmpty())) cout << " " << tracks[currentTrack]->pop(); cout << endl; currentTrack++; if (currentTrack >= numberOFTracks) currentTrack = 0; } for(int i = 0; i < numberOFTracks; i++) delete tracks[i]; delete[] tracks; return 0; }
23.227273
88
0.637476
rubikshift
1b53a37578a685ec07c72fc040ef7929d3048973
1,378
cpp
C++
Deitel/Chapter06/exercises/6.17/ex_617.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter06/exercises/6.17/ex_617.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter06/exercises/6.17/ex_617.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> #include <random> #include <vector> std::random_device rd; std::mt19937 gen(rd()); int getRandomNumber(const int&, const int&); int main(int argc, const char *argv[]) { // offsets v set 1 v v set 2 v v set 3 v std::vector<int> set {2, 4, 6, 8, 10, 2, 5, 7, 9, 11, 6, 10, 14, 18, 22}; std::cout << "Random number from each of the following sets: " << std::endl; std::cout << "\n2 4 6 8 10: " << set[getRandomNumber(0, 4)]; std::cout << "\n2 5 7 9 11: " << set[getRandomNumber(5, 9)]; std::cout << "\n6 10 14 18 22: " << set[getRandomNumber(10, set.size() - 1)] << std::endl; return 0; } /** * Creates a random distribution and returns a value in the range min max. * @param int * @param int * @return int */ int getRandomNumber(const int& min, const int& max) { return std::uniform_int_distribution<int>{min, max}(gen); } // end method getRandomNumber
28.708333
94
0.498549
SebastianTirado
1b5a2aa51cc41d3ff4c88bb8338c2a3da5f65380
87
cpp
C++
Source/FSD/Private/CloudLoadAllResponse.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/CloudLoadAllResponse.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
Source/FSD/Private/CloudLoadAllResponse.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
null
null
null
#include "CloudLoadAllResponse.h" FCloudLoadAllResponse::FCloudLoadAllResponse() { }
14.5
48
0.804598
trumank
1b5e0ce8d017488337862f7e9b41acfffb6ff73d
1,936
cpp
C++
src/trace/buffer.cpp
ArnauBigas/chopstix
37831cdbddf8ad3b11e9cc8fd2dd2999907e44ed
[ "Apache-2.0" ]
3
2019-06-06T12:57:24.000Z
2020-03-21T15:25:48.000Z
src/trace/buffer.cpp
ArnauBigas/chopstix
37831cdbddf8ad3b11e9cc8fd2dd2999907e44ed
[ "Apache-2.0" ]
32
2019-06-17T20:31:33.000Z
2022-03-02T16:43:41.000Z
src/trace/buffer.cpp
ArnauBigas/chopstix
37831cdbddf8ad3b11e9cc8fd2dd2999907e44ed
[ "Apache-2.0" ]
5
2019-06-06T12:57:41.000Z
2020-06-29T14:42:02.000Z
/* # # ---------------------------------------------------------------------------- # # Copyright 2019 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ---------------------------------------------------------------------------- # */ #include "buffer.h" #include "support/check.h" #include "support/safeformat.h" #include <fcntl.h> #include <linux/limits.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <sys/syscall.h> using namespace chopstix; #define PERM_664 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH TraceBuffer::~TraceBuffer() { if (pos_ > 0) write_back(); if (fd_ != -1) { syscall(SYS_close, fd_); fd_ = -1; } } void TraceBuffer::setup(const char *trace_root) { char fpath[PATH_MAX]; sfmt::format(fpath, sizeof(fpath), "%s/trace.bin", trace_root); fd_ = syscall(SYS_openat, AT_FDCWD, fpath, O_WRONLY | O_CREAT | O_TRUNC, PERM_664); check(fd_ != -1, "Unable to open 'trace.bin'"); } void TraceBuffer::start_trace(int trace_id, bool isNewInvocation) { if(isNewInvocation) write(-3); write(-1); } void TraceBuffer::stop_trace(int trace_id) { write(-2); } void TraceBuffer::save_page(long page_addr) { write(page_addr); } void TraceBuffer::write_back() { syscall(SYS_write, fd_, buf_, pos_ * sizeof(long)); pos_ = 0; } void TraceBuffer::write(long dat) { if (pos_ == buf_size) write_back(); buf_[pos_++] = dat; }
27.657143
111
0.63843
ArnauBigas
1b60fca499d8249d90597edeaa64c9917e27fabf
4,794
hpp
C++
src/helics/core/core-data.hpp
aenkoji1/HELICS
91f4cbcfb2a003cae955521a22e83461cbf2b629
[ "BSD-3-Clause" ]
59
2019-06-26T22:40:37.000Z
2022-03-28T18:00:23.000Z
src/helics/core/core-data.hpp
aenkoji1/HELICS
91f4cbcfb2a003cae955521a22e83461cbf2b629
[ "BSD-3-Clause" ]
748
2019-06-19T14:15:49.000Z
2022-03-31T17:26:18.000Z
src/helics/core/core-data.hpp
aenkoji1/HELICS
91f4cbcfb2a003cae955521a22e83461cbf2b629
[ "BSD-3-Clause" ]
53
2019-07-19T17:22:21.000Z
2022-03-28T18:00:38.000Z
/* Copyright (c) 2017-2021, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "SmallBuffer.hpp" #include "helics/helics-config.h" #include "helicsTime.hpp" #include <memory> #include <string> #include <utility> #include <vector> /** @file @details defining data used for storing the data for values and for messages */ /** \namespace helics @details the core namespace for the helics C++ library all user functions are found in this namespace along with many other functions in the Core API */ namespace helics { /** class containing a message structure*/ class Message { public: Time time = timeZero; //!< the event time the message is sent std::uint16_t flags{0}; //!< message flags std::uint16_t messageValidation{0U}; //!< extra field for user object usage, not used by HELICS std::int32_t messageID{0}; //!< the messageID for a message SmallBuffer data; //!< the data packet for the message std::string dest; //!< the destination of the message std::string source; //!< the most recent source of the message std::string original_source; //!< the original source of the message std::string original_dest; //!< the original destination of a message std::int32_t counter{0}; //!< indexing counter not used directly by helics void* backReference{nullptr}; //!< back referencing pointer not used by helics /** default constructor*/ Message() = default; /** swap operation for the Message*/ void swap(Message& m2) noexcept { std::swap(time, m2.time); std::swap(flags, m2.flags); std::swap(messageID, m2.messageID); original_source.swap(m2.original_source); source.swap(m2.source); dest.swap(m2.dest); data.swap(m2.data); original_dest.swap(m2.original_dest); } /** check if the Message contains an actual Message @return false if there is no Message data*/ bool isValid() const noexcept { return (!data.empty()) ? true : ((!source.empty()) ? true : (!dest.empty())); } /** get the payload as a string*/ std::string_view to_string() const { return data.to_string(); } /** clear all data from the message*/ void clear() { time = timeZero; flags = 0; messageID = 0; data.resize(0); dest.clear(); source.clear(); original_source.clear(); original_dest.clear(); counter = 0; } }; /** * FilterOperator abstract class @details FilterOperators will transform a message in some way in a direct fashion * */ class FilterOperator { public: /** default constructor*/ FilterOperator() = default; /**virtual destructor*/ virtual ~FilterOperator() = default; /** filter the message either modify the message or generate a new one*/ virtual std::unique_ptr<Message> process(std::unique_ptr<Message> message) = 0; /** filter the message either modify the message or generate a new one*/ virtual std::vector<std::unique_ptr<Message>> processVector(std::unique_ptr<Message> message) { std::vector<std::unique_ptr<Message>> ret; auto res = process(std::move(message)); if (res) { ret.push_back(std::move(res)); } return ret; } /** make the operator work like one @details calls the process function*/ std::unique_ptr<Message> operator()(std::unique_ptr<Message> message) { return process(std::move(message)); } /** indicator if the filter Operator has the capability of generating completely new messages or * redirecting messages*/ virtual bool isMessageGenerating() const { return false; } }; /** special filter operator defining no operation the original message is simply returned */ class NullFilterOperator final: public FilterOperator { public: /**default constructor*/ NullFilterOperator() = default; virtual std::unique_ptr<Message> process(std::unique_ptr<Message> message) override { return message; } }; /** helper template to check whether an index is actually valid for a particular vector @tparam SizedDataType a vector like data type that must have a size function @param testSize an index to test @param vec a reference to a vector like object that has a size method @return true if it is a valid index false otherwise*/ template<class sizeType, class SizedDataType> inline bool isValidIndex(sizeType testSize, const SizedDataType& vec) { return ((testSize >= sizeType(0)) && (testSize < static_cast<sizeType>(vec.size()))); } } // namespace helics
34.73913
100
0.678348
aenkoji1
1b62def7ce8e586f33b3d5b271743adf094d9136
2,987
cpp
C++
aws-cpp-sdk-imagebuilder/source/model/PipelineExecutionStartCondition.cpp
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-imagebuilder/source/model/PipelineExecutionStartCondition.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-imagebuilder/source/model/PipelineExecutionStartCondition.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/imagebuilder/model/PipelineExecutionStartCondition.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace imagebuilder { namespace Model { namespace PipelineExecutionStartConditionMapper { static const int EXPRESSION_MATCH_ONLY_HASH = HashingUtils::HashString("EXPRESSION_MATCH_ONLY"); static const int EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE_HASH = HashingUtils::HashString("EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"); PipelineExecutionStartCondition GetPipelineExecutionStartConditionForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == EXPRESSION_MATCH_ONLY_HASH) { return PipelineExecutionStartCondition::EXPRESSION_MATCH_ONLY; } else if (hashCode == EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE_HASH) { return PipelineExecutionStartCondition::EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<PipelineExecutionStartCondition>(hashCode); } return PipelineExecutionStartCondition::NOT_SET; } Aws::String GetNameForPipelineExecutionStartCondition(PipelineExecutionStartCondition enumValue) { switch(enumValue) { case PipelineExecutionStartCondition::EXPRESSION_MATCH_ONLY: return "EXPRESSION_MATCH_ONLY"; case PipelineExecutionStartCondition::EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE: return "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace PipelineExecutionStartConditionMapper } // namespace Model } // namespace imagebuilder } // namespace Aws
36.876543
160
0.709742
grujicbr
1b631c7c7a28579242e46cd9139055fbffacf805
2,805
cpp
C++
src/WorkShift.cpp
harmim/vut-ims-project
2156a181778c124bb19a02fb3b863211cbadb6d8
[ "MIT" ]
null
null
null
src/WorkShift.cpp
harmim/vut-ims-project
2156a181778c124bb19a02fb3b863211cbadb6d8
[ "MIT" ]
null
null
null
src/WorkShift.cpp
harmim/vut-ims-project
2156a181778c124bb19a02fb3b863211cbadb6d8
[ "MIT" ]
1
2020-12-05T13:02:54.000Z
2020-12-05T13:02:54.000Z
/** * VUT FIT IMS project - Freshbox food distribution. * * @file Work shift process implementation. * @author Dominik Harmim <xharmi00@stud.fit.vutbr.cz> * @author Vojtech Hertl <xhertl04@stud.fit.vutbr.cz> */ #include <iostream> #include "WorkShift.hpp" #include "WorkShiftTimer.hpp" #include "Car.hpp" #include "AverageUniformDistribution.hpp" using namespace std; WorkShift::WorkShift( unsigned long cars, double foodAverage, double foodDeviation ) { this->cars = new Store("Car store", cars); // Round number of food to be divisible by car capacity. food = new unsigned long(static_cast<unsigned long>( AverageUniformDistribution::Generate(foodAverage, foodDeviation) )); unsigned long remainder = *food % Car::CAR_CAPACITY; if (remainder < Car::CAR_CAPACITY / 2.0) { *food -= remainder; } else { *food += Car::CAR_CAPACITY - remainder; } carLoadingStat = new Stat("Car loading duration"); carRideStat = new Stat("Car ride duration"); carRideDistanceStat = new Stat("Car ride distance"); carRideConsumptionStat = new Stat("Car ride consumption"); PrintStartOfShift(); } WorkShift::~WorkShift() { PrintEndOfShift(); delete food; delete carLoadingStat; delete carRideStat; delete carRideDistanceStat; delete carRideConsumptionStat; } void WorkShift::Behavior() { auto *workShiftTimer = new WorkShiftTimer(this); // While there is food left and there is free car, take it and start // car process. while (*food > 0) { Enter(*cars, 1); // If food has been taken during waiting for car, leave the car. if (*food == 0) { Leave(*cars, 1); break; } *food -= Car::CAR_CAPACITY; // Start car process. (new Car( cars, carLoadingStat, carRideStat, carRideDistanceStat, carRideConsumptionStat ))->Activate(); } // Wait for all cars and then end the work shift. Enter(*cars, cars->Capacity()); Leave(*cars, cars->Capacity()); delete workShiftTimer; } void WorkShift::PrintStartOfShift() { cout << "////////////////////////////////////////////////////////////\n" << "Work shift started.\n" << "\tStart time: " << Time << ".\n" << "\tNumber of cars: " << cars->Capacity() << ".\n" << "\tNumber of food: " << *food << ".\n" << endl; } void WorkShift::PrintEndOfShift() { cout << "End of work shift.\n" << "\tEnd time: " << Time << ".\n" << "\tNumber of food left: " << *food << ".\n" << "\tTotal car ride distance: " << carRideDistanceStat->Sum() << ".\n" << "\tTotal cars consumption: " << carRideDistanceStat->Sum() / 100.0 * Car::CAR_CONSUMPTION << ".\n" << endl; cars->Output(); carLoadingStat->Output(); carRideStat->Output(); carRideDistanceStat->Output(); carRideConsumptionStat->Output(); cout << "////////////////////////////////////////////////////////////\n"; }
21.914063
74
0.63672
harmim
1b66205636344040cd32ed0528606e802d6995e8
34,219
cpp
C++
libs/openFrameworks/gl/ofGLRenderer.cpp
Studio236/project-440
4608d029ef5ef422f776804ff13736c1ec5565a9
[ "MIT" ]
1
2016-03-13T15:04:27.000Z
2016-03-13T15:04:27.000Z
libs/openFrameworks/gl/ofGLRenderer.cpp
Studio236/project-440
4608d029ef5ef422f776804ff13736c1ec5565a9
[ "MIT" ]
1
2015-09-11T15:09:39.000Z
2015-09-11T15:09:39.000Z
libs/openFrameworks/gl/ofGLRenderer.cpp
Studio236/project-440
4608d029ef5ef422f776804ff13736c1ec5565a9
[ "MIT" ]
null
null
null
#include "ofGLRenderer.h" #include "ofMesh.h" #include "ofPath.h" #include "ofGraphics.h" #include "ofAppRunner.h" #include "ofMesh.h" #include "ofBitmapFont.h" #include "ofGLUtils.h" #include "ofImage.h" #include "ofFbo.h" //---------------------------------------------------------- ofGLRenderer::ofGLRenderer(bool useShapeColor){ bBackgroundAuto = true; linePoints.resize(2); rectPoints.resize(4); triPoints.resize(3); currentFbo = NULL; } //---------------------------------------------------------- void ofGLRenderer::update(){ } //---------------------------------------------------------- void ofGLRenderer::draw(ofMesh & vertexData, bool useColors, bool useTextures, bool useNormals){ if(vertexData.getNumVertices()){ glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData.getVerticesPointer()->x); } if(vertexData.getNumNormals() && useNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, sizeof(ofVec3f), &vertexData.getNormalsPointer()->x); } if(vertexData.getNumColors() && useColors){ glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), &vertexData.getColorsPointer()->r); } if(vertexData.getNumTexCoords() && useTextures){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(ofVec2f), &vertexData.getTexCoordsPointer()->x); } if(vertexData.getNumIndices()){ #ifdef TARGET_OPENGLES glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer()); #else glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_INT,vertexData.getIndexPointer()); #endif }else{ glDrawArrays(ofGetGLPrimitiveMode(vertexData.getMode()), 0, vertexData.getNumVertices()); } if(vertexData.getNumColors()){ glDisableClientState(GL_COLOR_ARRAY); } if(vertexData.getNumNormals()){ glDisableClientState(GL_NORMAL_ARRAY); } if(vertexData.getNumTexCoords()){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofMesh & vertexData, ofPolyRenderMode renderType, bool useColors, bool useTextures, bool useNormals){ if (bSmoothHinted) startSmoothing(); #ifndef TARGET_OPENGLES glPushAttrib(GL_POLYGON_BIT); glPolygonMode(GL_FRONT_AND_BACK, ofGetGLPolyMode(renderType)); draw(vertexData,useColors,useTextures,useNormals); glPopAttrib(); //TODO: GLES doesnt support polygon mode, add renderType to gl renderer? #else if(vertexData.getNumVertices()){ glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), vertexData.getVerticesPointer()); } if(vertexData.getNumNormals() && useNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, vertexData.getNormalsPointer()); } if(vertexData.getNumColors() && useColors){ glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), vertexData.getColorsPointer()); } if(vertexData.getNumTexCoords() && useTextures){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, vertexData.getTexCoordsPointer()); } GLenum drawMode; switch(renderType){ case OF_MESH_POINTS: drawMode = GL_POINTS; break; case OF_MESH_WIREFRAME: drawMode = GL_LINES; break; case OF_MESH_FILL: drawMode = ofGetGLPrimitiveMode(vertexData.getMode()); break; default: drawMode = ofGetGLPrimitiveMode(vertexData.getMode()); break; } if(vertexData.getNumIndices()){ glDrawElements(drawMode, vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer()); }else{ glDrawArrays(drawMode, 0, vertexData.getNumVertices()); } if(vertexData.getNumColors() && useColors){ glDisableClientState(GL_COLOR_ARRAY); } if(vertexData.getNumNormals() && useNormals){ glDisableClientState(GL_NORMAL_ARRAY); } if(vertexData.getNumTexCoords() && useTextures){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); } #endif if (bSmoothHinted) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::draw(vector<ofPoint> & vertexData, ofPrimitiveMode drawMode){ if(!vertexData.empty()) { if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData[0].x); glDrawArrays(ofGetGLPrimitiveMode(drawMode), 0, vertexData.size()); if (bSmoothHinted) endSmoothing(); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofPolyline & poly){ if(!poly.getVertices().empty()) { // use smoothness, if requested: if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &poly.getVertices()[0].x); glDrawArrays(poly.isClosed()?GL_LINE_LOOP:GL_LINE_STRIP, 0, poly.size()); // use smoothness, if requested: if (bSmoothHinted) endSmoothing(); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofPath & shape){ ofColor prevColor; if(shape.getUseShapeColor()){ prevColor = ofGetStyle().color; } if(shape.isFilled()){ ofMesh & mesh = shape.getTessellation(); if(shape.getUseShapeColor()){ setColor( shape.getFillColor() * ofGetStyle().color,shape.getFillColor().a/255. * ofGetStyle().color.a); } draw(mesh); } if(shape.hasOutline()){ float lineWidth = ofGetStyle().lineWidth; if(shape.getUseShapeColor()){ setColor( shape.getStrokeColor() * ofGetStyle().color, shape.getStrokeColor().a/255. * ofGetStyle().color.a); } setLineWidth( shape.getStrokeWidth() ); vector<ofPolyline> & outlines = shape.getOutline(); for(int i=0; i<(int)outlines.size(); i++) draw(outlines[i]); setLineWidth(lineWidth); } if(shape.getUseShapeColor()){ setColor(prevColor); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::draw(ofFloatImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::draw(ofShortImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::setCurrentFBO(ofFbo * fbo){ currentFbo = fbo; } //---------------------------------------------------------- void ofGLRenderer::pushView() { GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); ofRectangle currentViewport; currentViewport.set(viewport[0], viewport[1], viewport[2], viewport[3]); viewportHistory.push(currentViewport); /*glMatrixMode(GL_PROJECTION); glPushMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix();*/ // done like this cause i was getting GL_STACK_UNDERFLOW // should ofPush/PopMatrix work the same way, what if it's mixed with glPush/PopMatrix ofMatrix4x4 m; glGetFloatv(GL_PROJECTION_MATRIX,m.getPtr()); projectionStack.push(m); glGetFloatv(GL_MODELVIEW_MATRIX,m.getPtr()); modelViewStack.push(m); } //---------------------------------------------------------- void ofGLRenderer::popView() { if( viewportHistory.size() ){ ofRectangle viewRect = viewportHistory.top(); viewport(viewRect.x, viewRect.y, viewRect.width, viewRect.height,false); viewportHistory.pop(); } /*glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix();*/ // done like this cause i was getting GL_STACK_UNDERFLOW // should ofPush/PopMatrix work the same way, what if it's mixed with glPush/PopMatrix glMatrixMode(GL_PROJECTION); if(!projectionStack.empty()){ glLoadMatrixf(projectionStack.top().getPtr()); projectionStack.pop(); }else{ ofLogError() << "popView: couldn't pop projection matrix, stack empty. probably wrong anidated push/popView"; } glMatrixMode(GL_MODELVIEW); if(!modelViewStack.empty()){ glLoadMatrixf(modelViewStack.top().getPtr()); modelViewStack.pop(); }else{ ofLogError() << "popView: couldn't pop modelView matrix, stack empty. probably wrong anidated push/popView"; } } //---------------------------------------------------------- void ofGLRenderer::viewport(ofRectangle viewport_){ viewport(viewport_.x, viewport_.y, viewport_.width, viewport_.height,true); } //---------------------------------------------------------- void ofGLRenderer::viewport(float x, float y, float width, float height, bool invertY) { if(width == 0) width = ofGetWindowWidth(); if(height == 0) height = ofGetWindowHeight(); if (invertY){ if(currentFbo){ y = currentFbo->getHeight() - (y + height); }else{ y = ofGetWindowHeight() - (y + height); } } glViewport(x, y, width, height); } //---------------------------------------------------------- ofRectangle ofGLRenderer::getCurrentViewport(){ // I am using opengl calls here instead of returning viewportRect // since someone might use glViewport instead of ofViewport... GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); ofRectangle view; view.x = viewport[0]; view.y = viewport[1]; view.width = viewport[2]; view.height = viewport[3]; return view; } //---------------------------------------------------------- int ofGLRenderer::getViewportWidth(){ GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); return viewport[2]; } //---------------------------------------------------------- int ofGLRenderer::getViewportHeight(){ GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); return viewport[3]; } //---------------------------------------------------------- void ofGLRenderer::setCoordHandedness(ofHandednessType handedness) { coordHandedness = handedness; } //---------------------------------------------------------- ofHandednessType ofGLRenderer::getCoordHandedness() { return coordHandedness; } //---------------------------------------------------------- void ofGLRenderer::setupScreenPerspective(float width, float height, ofOrientation orientation, bool vFlip, float fov, float nearDist, float farDist) { if(width == 0) width = ofGetWidth(); if(height == 0) height = ofGetHeight(); float viewW = ofGetViewportWidth(); float viewH = ofGetViewportHeight(); float eyeX = viewW / 2; float eyeY = viewH / 2; float halfFov = PI * fov / 360; float theTan = tanf(halfFov); float dist = eyeY / theTan; float aspect = (float) viewW / viewH; if(nearDist == 0) nearDist = dist / 10.0f; if(farDist == 0) farDist = dist * 10.0f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); ofMatrix4x4 persp; persp.makePerspectiveMatrix(fov, aspect, nearDist, farDist); loadMatrix( persp ); //gluPerspective(fov, aspect, nearDist, farDist); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); ofMatrix4x4 lookAt; lookAt.makeLookAtViewMatrix( ofVec3f(eyeX, eyeY, dist), ofVec3f(eyeX, eyeY, 0), ofVec3f(0, 1, 0) ); loadMatrix( lookAt ); //gluLookAt(eyeX, eyeY, dist, eyeX, eyeY, 0, 0, 1, 0); //note - theo checked this on iPhone and Desktop for both vFlip = false and true if(ofDoesHWOrientation()){ if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } }else{ if( orientation == OF_ORIENTATION_UNKNOWN ) orientation = ofGetOrientation(); switch(orientation) { case OF_ORIENTATION_180: glRotatef(-180, 0, 0, 1); if(vFlip){ glScalef(1, -1, 1); glTranslatef(-width, 0, 0); }else{ glTranslatef(-width, -height, 0); } break; case OF_ORIENTATION_90_RIGHT: glRotatef(-90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); }else{ glScalef(-1, -1, 1); glTranslatef(0, -height, 0); } break; case OF_ORIENTATION_90_LEFT: glRotatef(90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); glTranslatef(-width, -height, 0); }else{ glScalef(-1, -1, 1); glTranslatef(-width, 0, 0); } break; case OF_ORIENTATION_DEFAULT: default: if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } break; } } } //---------------------------------------------------------- void ofGLRenderer::setupScreenOrtho(float width, float height, ofOrientation orientation, bool vFlip, float nearDist, float farDist) { if(width == 0) width = ofGetWidth(); if(height == 0) height = ofGetHeight(); float viewW = ofGetViewportWidth(); float viewH = ofGetViewportHeight(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); ofSetCoordHandedness(OF_RIGHT_HANDED); #ifndef TARGET_OPENGLES if(vFlip) { ofSetCoordHandedness(OF_LEFT_HANDED); } if(nearDist == -1) nearDist = 0; if(farDist == -1) farDist = 10000; glOrtho(0, viewW, 0, viewH, nearDist, farDist); #else if(vFlip) { ofMatrix4x4 ortho = ofMatrix4x4::newOrthoMatrix(0, width, height, 0, nearDist, farDist); ofSetCoordHandedness(OF_LEFT_HANDED); } ofMatrix4x4 ortho = ofMatrix4x4::newOrthoMatrix(0, viewW, 0, viewH, nearDist, farDist); glMultMatrixf(ortho.getPtr()); #endif glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //note - theo checked this on iPhone and Desktop for both vFlip = false and true if(ofDoesHWOrientation()){ if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } }else{ if( orientation == OF_ORIENTATION_UNKNOWN ) orientation = ofGetOrientation(); switch(orientation) { case OF_ORIENTATION_180: glRotatef(-180, 0, 0, 1); if(vFlip){ glScalef(1, -1, 1); glTranslatef(-width, 0, 0); }else{ glTranslatef(-width, -height, 0); } break; case OF_ORIENTATION_90_RIGHT: glRotatef(-90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); }else{ glScalef(-1, -1, 1); glTranslatef(0, -height, 0); } break; case OF_ORIENTATION_90_LEFT: glRotatef(90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); glTranslatef(-width, -height, 0); }else{ glScalef(-1, -1, 1); glTranslatef(-width, 0, 0); } break; case OF_ORIENTATION_DEFAULT: default: if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } break; } } } //---------------------------------------------------------- //Resets openGL parameters back to OF defaults void ofGLRenderer::setupGraphicDefaults(){ glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } //---------------------------------------------------------- void ofGLRenderer::setupScreen(){ setupScreenPerspective(); // assume defaults } //---------------------------------------------------------- void ofGLRenderer::setCircleResolution(int res){ if((int)circlePolyline.size()!=res+1){ circlePolyline.clear(); circlePolyline.arc(0,0,0,1,1,0,360,res); circlePoints.resize(circlePolyline.size()); } } //---------------------------------------------------------- void ofGLRenderer::setSphereResolution(int res) { if(sphereMesh.getNumVertices() == 0 || res != ofGetStyle().sphereResolution) { int n = res * 2; float ndiv2=(float)n/2; /* Original code by Paul Bourke A more efficient contribution by Federico Dosil (below) Draw a point for zero radius spheres Use CCW facet ordering http://paulbourke.net/texture_colour/texturemap/ */ float theta2 = TWO_PI; float phi1 = -HALF_PI; float phi2 = HALF_PI; float r = 1.f; // normalize the verts // sphereMesh.clear(); sphereMesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP); int i, j; float theta1 = 0.f; float jdivn,j1divn,idivn,dosdivn,unodivn=1/(float)n,t1,t2,t3,cost1,cost2,cte1,cte3; cte3 = (theta2-theta1)/n; cte1 = (phi2-phi1)/ndiv2; dosdivn = 2*unodivn; ofVec3f e,p,e2,p2; if (n < 0){ n = -n; ndiv2 = -ndiv2; } if (n < 4) {n = 4; ndiv2=(float)n/2;} if(r <= 0) r = 1; t2=phi1; cost2=cos(phi1); j1divn=0; ofVec3f vert, normal; ofVec2f tcoord; for (j=0;j<ndiv2;j++) { t1 = t2; t2 += cte1; t3 = theta1 - cte3; cost1 = cost2; cost2 = cos(t2); e.y = sin(t1); e2.y = sin(t2); p.y = r * e.y; p2.y = r * e2.y; idivn=0; jdivn=j1divn; j1divn+=dosdivn; for (i=0;i<=n;i++) { t3 += cte3; e.x = cost1 * cos(t3); e.z = cost1 * sin(t3); p.x = r * e.x; p.z = r * e.z; normal.set( e.x, e.y, e.z ); tcoord.set( idivn, jdivn ); vert.set( p.x, p.y, p.z ); sphereMesh.addNormal(normal); sphereMesh.addTexCoord(tcoord); sphereMesh.addVertex(vert); e2.x = cost2 * cos(t3); e2.z = cost2 * sin(t3); p2.x = r * e2.x; p2.z = r * e2.z; normal.set(e2.x, e2.y, e2.z); tcoord.set(idivn, j1divn); vert.set(p2.x, p2.y, p2.z); sphereMesh.addNormal(normal); sphereMesh.addTexCoord(tcoord); sphereMesh.addVertex(vert); idivn += unodivn; } } } } //our openGL wrappers //---------------------------------------------------------- void ofGLRenderer::pushMatrix(){ glPushMatrix(); } //---------------------------------------------------------- void ofGLRenderer::popMatrix(){ glPopMatrix(); } //---------------------------------------------------------- void ofGLRenderer::translate(const ofPoint& p){ glTranslatef(p.x, p.y, p.z); } //---------------------------------------------------------- void ofGLRenderer::translate(float x, float y, float z){ glTranslatef(x, y, z); } //---------------------------------------------------------- void ofGLRenderer::scale(float xAmnt, float yAmnt, float zAmnt){ glScalef(xAmnt, yAmnt, zAmnt); } //---------------------------------------------------------- void ofGLRenderer::rotate(float degrees, float vecX, float vecY, float vecZ){ glRotatef(degrees, vecX, vecY, vecZ); } //---------------------------------------------------------- void ofGLRenderer::rotateX(float degrees){ glRotatef(degrees, 1, 0, 0); } //---------------------------------------------------------- void ofGLRenderer::rotateY(float degrees){ glRotatef(degrees, 0, 1, 0); } //---------------------------------------------------------- void ofGLRenderer::rotateZ(float degrees){ glRotatef(degrees, 0, 0, 1); } //same as ofRotateZ //---------------------------------------------------------- void ofGLRenderer::rotate(float degrees){ glRotatef(degrees, 0, 0, 1); } //---------------------------------------------------------- void ofGLRenderer::loadIdentityMatrix (void){ glLoadIdentity(); } //---------------------------------------------------------- void ofGLRenderer::loadMatrix (const ofMatrix4x4 & m){ loadMatrix( m.getPtr() ); } //---------------------------------------------------------- void ofGLRenderer::loadMatrix (const float *m){ glLoadMatrixf(m); } //---------------------------------------------------------- void ofGLRenderer::multMatrix (const ofMatrix4x4 & m){ multMatrix( m.getPtr() ); } //---------------------------------------------------------- void ofGLRenderer::multMatrix (const float *m){ glMultMatrixf(m); } //---------------------------------------------------------- void ofGLRenderer::setColor(const ofColor & color){ setColor(color.r,color.g,color.b,color.a); } //---------------------------------------------------------- void ofGLRenderer::setColor(const ofColor & color, int _a){ setColor(color.r,color.g,color.b,_a); } //---------------------------------------------------------- void ofGLRenderer::setColor(int _r, int _g, int _b){ glColor4f(_r/255.f,_g/255.f,_b/255.f,1.f); } //---------------------------------------------------------- void ofGLRenderer::setColor(int _r, int _g, int _b, int _a){ glColor4f(_r/255.f,_g/255.f,_b/255.f,_a/255.f); } //---------------------------------------------------------- void ofGLRenderer::setColor(int gray){ setColor(gray, gray, gray); } //---------------------------------------------------------- void ofGLRenderer::setHexColor(int hexColor){ int r = (hexColor >> 16) & 0xff; int g = (hexColor >> 8) & 0xff; int b = (hexColor >> 0) & 0xff; setColor(r,g,b); } //---------------------------------------------------------- void ofGLRenderer::clear(float r, float g, float b, float a) { glClearColor(r / 255., g / 255., b / 255., a / 255.); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------- void ofGLRenderer::clear(float brightness, float a) { clear(brightness, brightness, brightness, a); } //---------------------------------------------------------- void ofGLRenderer::clearAlpha() { glColorMask(0, 0, 0, 1); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glColorMask(1, 1, 1, 1); } //---------------------------------------------------------- void ofGLRenderer::setBackgroundAuto(bool bAuto){ bBackgroundAuto = bAuto; } //---------------------------------------------------------- bool ofGLRenderer::bClearBg(){ return bBackgroundAuto; } //---------------------------------------------------------- ofFloatColor & ofGLRenderer::getBgColor(){ return bgColor; } //---------------------------------------------------------- void ofGLRenderer::background(const ofColor & c){ bgColor = c; glClearColor(bgColor[0],bgColor[1],bgColor[2], bgColor[3]); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------- void ofGLRenderer::background(float brightness) { background(brightness); } //---------------------------------------------------------- void ofGLRenderer::background(int hexColor, float _a){ background ( (hexColor >> 16) & 0xff, (hexColor >> 8) & 0xff, (hexColor >> 0) & 0xff, _a); } //---------------------------------------------------------- void ofGLRenderer::background(int r, int g, int b, int a){ background(ofColor(r,g,b,a)); } //---------------------------------------------------------- void ofGLRenderer::setFillMode(ofFillFlag fill){ bFilled = fill; } //---------------------------------------------------------- ofFillFlag ofGLRenderer::getFillMode(){ return bFilled; } //---------------------------------------------------------- void ofGLRenderer::setRectMode(ofRectMode mode){ rectMode = mode; } //---------------------------------------------------------- ofRectMode ofGLRenderer::getRectMode(){ return rectMode; } //---------------------------------------------------------- void ofGLRenderer::setLineWidth(float lineWidth){ glLineWidth(lineWidth); } //---------------------------------------------------------- void ofGLRenderer::setLineSmoothing(bool smooth){ bSmoothHinted = smooth; } //---------------------------------------------------------- void ofGLRenderer::startSmoothing(){ #ifndef TARGET_OPENGLES glPushAttrib(GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT); #endif glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_LINE_SMOOTH); //why do we need this? glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //---------------------------------------------------------- void ofGLRenderer::endSmoothing(){ #ifndef TARGET_OPENGLES glPopAttrib(); #endif } //---------------------------------------------------------- void ofGLRenderer::setBlendMode(ofBlendMode blendMode){ switch (blendMode){ case OF_BLENDMODE_ALPHA:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } case OF_BLENDMODE_ADD:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; } case OF_BLENDMODE_MULTIPLY:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA /* GL_ZERO or GL_ONE_MINUS_SRC_ALPHA */); break; } case OF_BLENDMODE_SCREEN:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE); break; } case OF_BLENDMODE_SUBTRACT:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); #else ofLog(OF_LOG_WARNING, "OF_BLENDMODE_SUBTRACT not currently supported on OpenGL/ES"); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; } default: break; } } //---------------------------------------------------------- void ofGLRenderer::enablePointSprites(){ #ifdef TARGET_OPENGLES glEnable(GL_POINT_SPRITE_OES); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE); // does look like this needs to be enabled in ES because // it is always eneabled... //glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #else glEnable(GL_POINT_SPRITE); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif } //---------------------------------------------------------- void ofGLRenderer::disablePointSprites(){ #ifdef TARGET_OPENGLES glDisable(GL_POINT_SPRITE_OES); #else glDisable(GL_POINT_SPRITE); #endif } //---------------------------------------------------------- void ofGLRenderer::drawLine(float x1, float y1, float z1, float x2, float y2, float z2){ linePoints[0].set(x1,y1,z1); linePoints[1].set(x2,y2,z2); // use smoothness, if requested: if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &linePoints[0].x); glDrawArrays(GL_LINES, 0, 2); // use smoothness, if requested: if (bSmoothHinted) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawRectangle(float x, float y, float z,float w, float h){ if (rectMode == OF_RECTMODE_CORNER){ rectPoints[0].set(x,y,z); rectPoints[1].set(x+w, y, z); rectPoints[2].set(x+w, y+h, z); rectPoints[3].set(x, y+h, z); }else{ rectPoints[0].set(x-w/2.0f, y-h/2.0f, z); rectPoints[1].set(x+w/2.0f, y-h/2.0f, z); rectPoints[2].set(x+w/2.0f, y+h/2.0f, z); rectPoints[3].set(x-w/2.0f, y+h/2.0f, z); } // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &rectPoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 4); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){ triPoints[0].set(x1,y1,z1); triPoints[1].set(x2,y2,z2); triPoints[2].set(x3,y3,z3); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &triPoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 3); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawCircle(float x, float y, float z, float radius){ vector<ofPoint> & circleCache = circlePolyline.getVertices(); for(int i=0;i<(int)circleCache.size();i++){ circlePoints[i].set(radius*circleCache[i].x+x,radius*circleCache[i].y+y,z); } // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size()); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawSphere(float x, float y, float z, float radius) { glEnable(GL_NORMALIZE); glPushMatrix(); glScalef(radius, radius, radius); if(bFilled) { sphereMesh.draw(); } else { sphereMesh.drawWireframe(); } glPopMatrix(); glDisable(GL_NORMALIZE); } //---------------------------------------------------------- void ofGLRenderer::drawEllipse(float x, float y, float z, float width, float height){ float radiusX = width*0.5; float radiusY = height*0.5; vector<ofPoint> & circleCache = circlePolyline.getVertices(); for(int i=0;i<(int)circleCache.size();i++){ circlePoints[i].set(radiusX*circlePolyline[i].x+x,radiusY*circlePolyline[i].y+y,z); } // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size()); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawString(string textString, float x, float y, float z, ofDrawBitmapMode mode){ // this is copied from the ofTrueTypeFont //GLboolean blend_enabled = glIsEnabled(GL_BLEND); //TODO: this is not used? GLint blend_src, blend_dst; glGetIntegerv( GL_BLEND_SRC, &blend_src ); glGetIntegerv( GL_BLEND_DST, &blend_dst ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int len = (int)textString.length(); //float yOffset = 0; float fontSize = 8.0f; bool bOrigin = false; float sx = 0; float sy = -fontSize; /////////////////////////// // APPLY TRANSFORM / VIEW /////////////////////////// // bool hasModelView = false; bool hasProjection = false; bool hasViewport = false; ofRectangle rViewport; #ifdef TARGET_OPENGLES if(mode == OF_BITMAPMODE_MODEL_BILLBOARD) { mode = OF_BITMAPMODE_SIMPLE; } #endif switch (mode) { case OF_BITMAPMODE_SIMPLE: sx += x; sy += y; break; case OF_BITMAPMODE_SCREEN: hasViewport = true; ofPushView(); rViewport = ofGetWindowRect(); ofViewport(rViewport); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(-1, 1, 0); glScalef(2/rViewport.width, -2/rViewport.height, 1); ofTranslate(x, y, 0); break; case OF_BITMAPMODE_VIEWPORT: rViewport = ofGetCurrentViewport(); hasProjection = true; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); hasModelView = true; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(-1, 1, 0); glScalef(2/rViewport.width, -2/rViewport.height, 1); ofTranslate(x, y, 0); break; case OF_BITMAPMODE_MODEL: hasModelView = true; glMatrixMode(GL_MODELVIEW); glPushMatrix(); ofTranslate(x, y, z); ofScale(1, -1, 0); break; case OF_BITMAPMODE_MODEL_BILLBOARD: //our aim here is to draw to screen //at the viewport position related //to the world position x,y,z // *************** // this will not compile for opengl ES // *************** #ifndef TARGET_OPENGLES //gluProject method GLdouble modelview[16], projection[16]; GLint view[4]; double dScreenX, dScreenY, dScreenZ; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, view); view[0] = 0; view[1] = 0; //we're already drawing within viewport gluProject(x, y, z, modelview, projection, view, &dScreenX, &dScreenY, &dScreenZ); if (dScreenZ >= 1) return; rViewport = ofGetCurrentViewport(); hasProjection = true; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); hasModelView = true; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(-1, -1, 0); glScalef(2/rViewport.width, 2/rViewport.height, 1); glTranslatef(dScreenX, dScreenY, 0); if(currentFbo == NULL) { glScalef(1, -1, 1); } else { glScalef(1, 1, 1); // invert when rendering inside an fbo } #endif break; default: break; } // /////////////////////////// // (c) enable texture once before we start drawing each char (no point turning it on and off constantly) //We do this because its way faster ofDrawBitmapCharacterStart(textString.size()); for(int c = 0; c < len; c++){ if(textString[c] == '\n'){ sy += bOrigin ? -1 : 1 * (fontSize*1.7); if(mode == OF_BITMAPMODE_SIMPLE) { sx = x; } else { sx = 0; } //glRasterPos2f(x,y + (int)yOffset); } else if (textString[c] >= 32){ // < 32 = control characters - don't draw // solves a bug with control characters // getting drawn when they ought to not be ofDrawBitmapCharacter(textString[c], (int)sx, (int)sy); sx += fontSize; } } //We do this because its way faster ofDrawBitmapCharacterEnd(); if (hasModelView) glPopMatrix(); if (hasProjection) { glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } if (hasViewport) ofPopView(); glBlendFunc(blend_src, blend_dst); }
27.353317
151
0.603086
Studio236
1b67d5e5998f2a27552bcc2d9fadeeb5aaf37287
399
cpp
C++
async-list/MainWindow.cpp
topecongiro/qt-toy-projects
ccf71acb0b0a896f4f231f11a5ad3b8f1f6b3e6f
[ "MIT" ]
null
null
null
async-list/MainWindow.cpp
topecongiro/qt-toy-projects
ccf71acb0b0a896f4f231f11a5ad3b8f1f6b3e6f
[ "MIT" ]
null
null
null
async-list/MainWindow.cpp
topecongiro/qt-toy-projects
ccf71acb0b0a896f4f231f11a5ad3b8f1f6b3e6f
[ "MIT" ]
null
null
null
#include "MainWindow.h" #include "ui_MainWindow.h" #include <QVBoxLayout> #include "MyWidget.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); auto* pLayout = new QVBoxLayout(this); ui->centralwidget->setLayout(pLayout); pLayout->addWidget(new MyWidget(this)); } MainWindow::~MainWindow() { delete ui; }
16.625
43
0.681704
topecongiro
1b68b4a476bbd148890f6550ab6b3c2b6e2d64b0
2,102
cpp
C++
RoboRoboPi/servo_old.cpp
vanklompf/RoboRoboPi
344d025ae374720a88c761d97ed3010c5c577602
[ "Beerware" ]
null
null
null
RoboRoboPi/servo_old.cpp
vanklompf/RoboRoboPi
344d025ae374720a88c761d97ed3010c5c577602
[ "Beerware" ]
null
null
null
RoboRoboPi/servo_old.cpp
vanklompf/RoboRoboPi
344d025ae374720a88c761d97ed3010c5c577602
[ "Beerware" ]
null
null
null
#include <wiringPi.h> #include <stdio.h> #include "servo.h" #include "logger.h" namespace robo { /* * Clock and range values from * http://stackoverflow.com/questions/20081286/controlling-a-servo-with-raspberry-pi-using-the-hardware-pwm-with-wiringpi * Range tests: * Clock: 384 Range: 30 - 115 * Clock: 500 Range: 25 - 80 * Clock: 400 Range: 29 - 111 * Clock: 250 Range: 46 - 178 * Clock: 200 Range: 57 - 223 * Clock: 100 Not working */ static const int SERVO_PIN = 1; static const int MIN = 30; static const int MAX = 115; static const int ZERO = (MIN + MAX) / 2; static constexpr char const * const arr[] = { "INFO", "WARNING", "ERROR", "CRASH" }; static const char * const error_values[] = { "SERVO_OK", "SERVO_OUT_OF_RANGE", "SERVO_ERROR" }; void Servo::Init() { //pinMode(SERVO_PIN, PWM_OUTPUT); //pwmSetMode(PWM_MODE_MS); //pwmSetClock(384); //pwmSetRange(1000); SetAngle(0); LogDebug("Servo Initialized."); } servo_status_t Servo::setGpioRegister(int16_t value) { auto status = servo_status_t::SERVO_ERROR; if (value > MAX) { status = servo_status_t::SERVO_OUT_OF_RANGE; value = MAX; } else if (value < MIN) { status = servo_status_t::SERVO_OUT_OF_RANGE; value = MIN; } else { status = servo_status_t::SERVO_OK; } LogDebug("Setting servo gpio: %d", value); m_gpio_value = value; pwmWrite(SERVO_PIN, value); return status; } servo_status_t Servo::SetAngle(int16_t angle) { return setGpioRegister(angleToGpioValue(angle)); } int Servo::angleToGpioValue(int16_t angle) const { return ZERO + angle; } int16_t Servo::gpioValueToAngle(int value) const { return value - ZERO; } servo_status_t Servo::StepLeft() { return setGpioRegister(m_gpio_value - 10); } servo_status_t Servo::StepRight() { return setGpioRegister(m_gpio_value + 10); } const char* Servo::getStatusText(servo_status_t status) const { return error_values[status]; } }
21.232323
124
0.639867
vanklompf
1b6a6df75a2234e4c07ca8fa96c8dabcc825fc54
293
cpp
C++
AtCoder/abc078/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/abc078/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/abc078/b/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int X, Y, Z; cin >> X >> Y >> Z; int sum = 0, cnt = 0; while(true) { sum += Y + Z; if (sum + Z > X) break; cnt++; } printf("%d\n", cnt); }
18.3125
36
0.488055
H-Tatsuhiro
1b6c9c377f95d075492e3b91e97e52149277653d
1,988
cpp
C++
sources/thelib/src/mediaformats/readers/ts/streamdescriptors.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
3
2020-07-30T19:41:00.000Z
2020-10-28T12:52:37.000Z
sources/thelib/src/mediaformats/readers/ts/streamdescriptors.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
null
null
null
sources/thelib/src/mediaformats/readers/ts/streamdescriptors.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
2
2020-05-11T03:19:00.000Z
2021-07-07T17:40:47.000Z
/** ########################################################################## # If not stated otherwise in this file or this component's LICENSE # file the following copyright and licenses apply: # # Copyright 2019 RDK Management # # 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. ########################################################################## **/ #ifdef HAS_MEDIA_TS #include "mediaformats/readers/ts/streamdescriptors.h" #include "mediaformats/readers/ts/tsboundscheck.h" bool ReadStreamDescriptor(StreamDescriptor &descriptor, uint8_t *pBuffer, uint32_t &cursor, uint32_t maxCursor) { TS_CHECK_BOUNDS(2); descriptor.type = pBuffer[cursor++]; descriptor.length = pBuffer[cursor++]; TS_CHECK_BOUNDS(descriptor.length); //iso13818-1.pdf Table 2-39, page 81/174 switch (descriptor.type) { case 14://Maximum_bitrate_descriptor { TS_CHECK_BOUNDS(3); descriptor.payload.maximum_bitrate_descriptor.maximum_bitrate = (((pBuffer[cursor] << 16) | (pBuffer[cursor + 1] << 8) | (pBuffer[cursor + 2]))&0x3fffff) * 50 * 8; break; } #ifdef HAS_MULTIPROGRAM_TS case DESCRIPTOR_TYPE_ISO_639_LANGUAGE: { TS_CHECK_BOUNDS(4); for (uint8_t i = 0; i < 3; i++) descriptor.payload.iso_639_descriptor.language_code[i] = pBuffer[cursor + i]; descriptor.payload.iso_639_descriptor.audio_type = pBuffer[cursor + 3]; break; } #endif /* HAS_MULTIPROGRAM_TS */ default: break; } cursor += descriptor.length; return true; } #endif /* HAS_MEDIA_TS */
32.064516
104
0.682596
rdkcmf
1b6d603ae3ef0dc21e806606e8b3fb7a7398527d
274
cpp
C++
Week05/ClassTasks/Main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
3
2018-03-05T13:57:56.000Z
2018-05-03T19:25:05.000Z
Week05/ClassTasks/Main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
null
null
null
Week05/ClassTasks/Main.cpp
Stoefff/Object-Oriented-Programming-FMI-2017
d2f8083ff146fb3cc68425cbd9af50bc37581e19
[ "MIT" ]
null
null
null
#include <iostream> #include "Line.h" #include "Rectangle.h" #include "Color.h" using namespace std; int main() { Point p1(1, 2); Point p2(3, 4); Line l1(p1, p2, RED); l1.setA(p2); l1.setB(Point(2, 3)); l1.print(); Rectangle rec(p1, 3, 4, BLUE); return 0; }
12.454545
31
0.609489
Stoefff
1b6e4256c62acc0629aa644780f7a1377abf3af7
10,450
cpp
C++
src/mc_exe/kcCatScene_functional.cpp
trigger-segfault/catsystem-py
2e2d7c64ad530e896739f81109c6e108e663fee7
[ "MIT" ]
6
2020-10-20T13:26:56.000Z
2022-02-15T05:26:38.000Z
src/mc_exe/kcCatScene_functional.cpp
trigger-segfault/catsystem-py
2e2d7c64ad530e896739f81109c6e108e663fee7
[ "MIT" ]
2
2020-10-20T16:15:35.000Z
2021-07-08T18:15:23.000Z
src/mc_exe/kcCatScene_functional.cpp
trigger-segfault/catsystem-py
2e2d7c64ad530e896739f81109c6e108e663fee7
[ "MIT" ]
1
2020-10-19T15:20:50.000Z
2020-10-19T15:20:50.000Z
#include "common_mc.h" #ifndef KCLIB_OOP #include "kcCatScene_functional.h" #include "../ac_exe/ghidra_types_min.h" #include "kcFileInfo_functional.h" ///WARNING: This file is outdated compared to the OOP version "kcDoubleBuffer.cpp", /// which has more up to date refactoring and code //unsigned int * __thiscall kcMacroReader_initRun(void *this, char *param_1) ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004119a0 kcCatScene * __thiscall kcCatScene_ctor(kcCatScene *this, IN const char *filename) { this->LineBuffer = nullptr; this->MemoryLines = nullptr; this->LineOffsets = nullptr; this->MemoryOffsets = nullptr; this->BufferSize = 0; this->LineCount = 0; this->MacUnk0 = 0; // ??? this->LastLineMultibyteContinue = FALSE; std::strcpy(&this->Filename[0], filename); kcCatScene_Read(this, filename); return this; } // undefined4 __thiscall kcCatScene_Read(int this,char *filename) ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004114d0 BOOL __thiscall kcCatScene_Read(kcCatScene *this, IN const char *filename) { HGLOBAL hMemLines = nullptr; HGLOBAL hMemOffsets = nullptr; char *lineBuffer = nullptr; unsigned int *lineOffsets = nullptr; unsigned int lineCount = 0; // all this just to read fileSize... nice FILE_READER *fileinfo = (FILE_READER *)std::malloc(0x598);//_newalloc(0x598); if (fileinfo != nullptr) { fileinfo = (FILE_READER *)kcFileInfo_ctor(fileinfo, filename); } kcFileInfo_SetReadMode(fileinfo); unsigned int bufferSize = kcFileInfo_GetSize(fileinfo); if (fileinfo != nullptr) { kcFileInfo_scalar_dtor(fileinfo, 1); } // allocate MemoryLines and copy lines into buffer, // nullterminated with newlines and control chars removed if ((int)bufferSize > 0) { // the original source was likely a goto-failure control flow, // decompiled it's just layers upon layers of if statements, so it has been cleaned up bufferSize += 0x10; // extra space, for unknown reasons. Could be useful? *shrug* FILE *file = nullptr; // text file (mode "rt") //0x42 (GHND, GMEM_MOVEABLE | GMEM_ZEROINIT) hMemLines = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, bufferSize); if (hMemLines != nullptr) { lineBuffer = (char *)::GlobalLock(hMemLines); } if (lineBuffer != nullptr) { file = std::fopen(filename, "rt"); } // reading file (final 'if' in setup) if (file != nullptr) { int offset = 0; while (!std::feof(file) && std::fgets(&lineBuffer[offset], bufferSize - offset, file)) { // trim control chars from end of line (excluding whitespace) int length = (int)std::strlen(&lineBuffer[offset]); for (; length > 0; length--) { if ((unsigned int)lineBuffer[offset + length - 1] >= 0x20 || lineBuffer[offset + length - 1] == '\t') break; } lineBuffer[offset + length] = '\0'; offset += length + 1; // +1 for null-termination lineCount++; } // cleanup file std::fclose(file); } // cleanup if (lineBuffer != nullptr) { ::GlobalUnlock(hMemLines); } // done } // No lines in the file? That's a paddlin' (return FALSE) if (lineCount < 1) { if (hMemLines != nullptr) { ::GlobalFree(hMemLines); } return FALSE; } // allocate MemoryOffsets and add byte offsets of each line in MemoryLines (return TRUE) else //if (lineCount >= 1) { // the original source was likely a goto-failure control flow, // decompiled it's just layers upon layers of if statements, so it has been cleaned up this->LineCount = lineCount; this->BufferSize = bufferSize; this->MemoryLines = hMemLines; lineBuffer = nullptr; lineOffsets = nullptr; //0x42 (GHND, GMEM_MOVEABLE | GMEM_ZEROINIT) hMemOffsets = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, lineCount * sizeof(unsigned int)); if (hMemOffsets != nullptr) { lineBuffer = (char *)::GlobalLock(hMemLines); } if (lineBuffer != nullptr) { lineOffsets = (unsigned int *)::GlobalLock(hMemOffsets); } // reading file (final 'if' in setup) if (lineOffsets != nullptr) { // unsigned int offset = 0; for (unsigned int line = 0, offset = 0; line < this->LineCount; line++) { lineOffsets[line] = offset; offset += (unsigned int)std::strlen(&lineBuffer[offset]) + 1; // +1 for null-termination } ::GlobalUnlock(hMemOffsets); } // cleanup if (lineBuffer != nullptr) { ::GlobalUnlock(hMemLines); } // done this->MemoryOffsets = hMemOffsets; return TRUE; } } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411410 BOOL __fastcall kcCatScene_LockBuffers(kcCatScene *this) { LPVOID pvVar1; undefined4 uVar2; if (this->LineBuffer == nullptr || this->LineOffsets == nullptr) // 0x8, 0xc { if (this->MemoryLines != nullptr) // 0x414 { this->LineBuffer = (char *)::GlobalLock(this->MemoryLines); // 0x8, 0x414 } if (this->MemoryOffsets != nullptr) // 0x418 { this->LineOffsets = (unsigned int *)::GlobalLock(this->MemoryOffsets); // 0xc, 0x418 } } if (this->LineBuffer == nullptr || this->LineOffsets == nullptr) // 0x8, 0xc { kcCatScene_UnlockBuffers(this); return FALSE; } return TRUE; } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004113b0 void __fastcall kcCatScene_UnlockBuffers(kcCatScene *this) { if (this->LineBuffer != nullptr) // 0x8 { ::GlobalUnlock(this->MemoryLines); // 0x414 this->LineBuffer = nullptr; // 0x8 } if (this->LineOffsets != nullptr) // 0xc { ::GlobalUnlock(this->MemoryOffsets); // 0x418 this->LineOffsets = nullptr; // 0xc } } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004114a0 BOOL __fastcall kcCatScene_IsLocked(kcCatScene *this) { undefined4 uVar1; if (this->LineBuffer == nullptr || this->LineOffsets == nullptr) { uVar1 = 0; } else { uVar1 = 1; } return uVar1; } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411920 const char * __thiscall kcCatScene_GetLineAt(kcCatScene *this, int index) { int iVar1; // iVar1 = ; if (!kcCatScene_IsLocked(this)) return nullptr; // if ((index < 0) || (*(int *)(this + 4) <= index)) if (index < 0 || index >= this->LineCount) return nullptr; return &this->LineBuffer[this->LineOffsets[index]]; // iVar1 = *(int *)(this + 8) + *(int *)(*(int *)(this + 0xc) + index * 4); } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411970 BOOL __thiscall kcCatScene_HasLineAt(kcCatScene *this, int index) { // int iVar1; // iVar1 = kcCatScene_GetLineAt(this, index); // return (BOOL)(iVar1 != 0); return (BOOL)(kcCatScene_GetLineAt(this, index) != nullptr); } ///FLAG: ALLOW_LINE_CONTINUE 0x1 ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411a30 unsigned int __thiscall kcCatScene_CopyLineAt(kcCatScene *this, OUT char *outBuffer, int bufferSize, IN OUT int *inoutIndex, unsigned int flags) { int index = *inoutIndex; char *out_ptr = outBuffer; bool lineContinued = false; while (true) { if (false) // probably a preprocessor flag (that's changed based on the needs of a specific script type) break; const char *line_ptr = kcCatScene_GetLineAt(this, index); if (line_ptr == nullptr) break; // no more lines, finish index++; // increment index (moved up for visibility) if (this->LastLineMultibyteContinue != FALSE) { this->LastLineMultibyteContinue = FALSE; // only set back to false if a line at index exists } //TRIM: when continuing, trim (skip) control chars and whitespace from start of line while (lineContinued && line_ptr[0] != '\0' && (unsigned char)line_ptr[0] <= 0x20) // '\0', 0x21 { line_ptr++; } //COPY: copy current line into buffer int line_len = (int)std::strlen(line_ptr); if (line_len >= bufferSize) { std::memcpy(out_ptr, line_ptr, bufferSize - 1U); out_ptr += (bufferSize - 1U); // lineEnd = out_ptr + (bufferSize - 1U); break; // end of buffer reached, finish here } std::memcpy(out_ptr, line_ptr, line_len); ///FIXME: Buffer size subtraction doesn't account for -1 from skipping '\\' (non-fatal, minor issue) bufferSize -= line_len; //CONTINUE?: some flags (it's that "allow line comment/continue?" flag again!) if ((flags & 1) == 0 || line_len < 1 || out_ptr[line_len - 1] != '\\') break; // no line continuation, finish //CHECK: A VERY rudimentary scan of multibyte characters in the line to see if // the final '\\' isn't actually part of a double-byte Shift_JIS character. int i, char_width; for (i = 0, char_width = 0; i + 1 < line_len; i += char_width) // while (line_len >= 2) { if ((unsigned char)out_ptr[i] >= 0x80) char_width = 2; else char_width = 1; } if (i == line_len && char_width == 2 && out_ptr[i - 1] == '\\') // 0x5c { this->LastLineMultibyteContinue = TRUE; // *(unk4 *)0x10 = 1 break; // multi-byte ending in '\\' (0x5c) not a line continuation } //NEXT: normal line continuation, keep going and copy next line lineContinued = true; out_ptr += line_len - 1; // -1 to overwrite (ignore) '\\' line continuation char } *inoutIndex = index; out_ptr[0] = '\0'; // null-terminate ///PTRMATH: string distance return (unsigned int)(out_ptr - outBuffer); } #endif
33.06962
144
0.586124
trigger-segfault
1b6f981d5208ba3f6153bedb5c8ebd04f5f55de7
1,750
cpp
C++
Release/src/granada/util/application.cpp
htmlpuzzle/moonlynx
c098b30ab8689fc8ea25fa375c337afa9964af81
[ "MIT" ]
null
null
null
Release/src/granada/util/application.cpp
htmlpuzzle/moonlynx
c098b30ab8689fc8ea25fa375c337afa9964af81
[ "MIT" ]
null
null
null
Release/src/granada/util/application.cpp
htmlpuzzle/moonlynx
c098b30ab8689fc8ea25fa375c337afa9964af81
[ "MIT" ]
null
null
null
#include "granada/util/application.h" namespace granada{ namespace util{ namespace application{ const std::string& get_selfpath(){ if (selfpath.empty()){ #ifdef __APPLE__ int ret; pid_t pid; char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; pid = getpid(); ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf)); if ( ret > 0 ) { std::string totalPath = std::string(pathbuf); selfpath = totalPath.substr(0,totalPath.find_last_of("/")); } #elif _WIN32 std::vector<wchar_t> pathBuf; DWORD copied = 0; do { pathBuf.resize(pathBuf.size() + MAX_PATH); copied = GetModuleFileName(0, (PWSTR)&pathBuf.at(0), pathBuf.size()); } while (copied >= pathBuf.size()); pathBuf.resize(copied); selfpath = utility::conversions::to_utf8string(std::wstring(pathBuf.begin(), pathBuf.end())); selfpath = selfpath.substr(0, selfpath.find_last_of("\\")); #else char buff[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; std::string totalPath = std::string(buff); selfpath = totalPath.substr(0,totalPath.find_last_of("/")); } #endif } return selfpath; } const std::string GetProperty(const std::string& name){ if (property_file_ == NULL){ std::string configuration_file_path = get_selfpath() + "/server.conf"; property_file_ = std::unique_ptr<granada::util::file::PropertyFile>(new granada::util::file::PropertyFile(configuration_file_path)); } return property_file_->GetProperty(name); } } } }
32.407407
142
0.589143
htmlpuzzle
1b7279ff95d35a91c3a2428067d398f2b19bbeba
3,202
cc
C++
chrome/browser/apps/app_service/fake_lacros_web_apps_host.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/browser/apps/app_service/fake_lacros_web_apps_host.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/browser/apps/app_service/fake_lacros_web_apps_host.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_service/fake_lacros_web_apps_host.h" #include <utility> #include <vector> #include "base/notreached.h" #include "chromeos/lacros/lacros_service.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "mojo/public/cpp/bindings/remote.h" namespace { // Test push one test app. void PushOneApp() { auto* service = chromeos::LacrosService::Get(); std::vector<apps::mojom::AppPtr> apps; apps::mojom::AppPtr app = apps::mojom::App::New(); app->app_type = apps::mojom::AppType::kWeb; app->app_id = "abcdefg"; app->readiness = apps::mojom::Readiness::kReady; app->name = "lacros test name"; app->short_name = "lacros test name"; app->last_launch_time = base::Time(); app->install_time = base::Time(); app->install_source = apps::mojom::InstallSource::kUser; app->is_platform_app = apps::mojom::OptionalBool::kFalse; app->recommendable = apps::mojom::OptionalBool::kTrue; app->searchable = apps::mojom::OptionalBool::kTrue; app->paused = apps::mojom::OptionalBool::kFalse; app->show_in_launcher = apps::mojom::OptionalBool::kTrue; app->show_in_shelf = apps::mojom::OptionalBool::kTrue; app->show_in_search = apps::mojom::OptionalBool::kTrue; app->show_in_management = apps::mojom::OptionalBool::kTrue; apps.push_back(std::move(app)); service->GetRemote<crosapi::mojom::AppPublisher>()->OnApps(std::move(apps)); } // Test push one test capability_access. void PushOneCapabilityAccess() { auto* service = chromeos::LacrosService::Get(); std::vector<apps::mojom::CapabilityAccessPtr> capability_accesses; apps::mojom::CapabilityAccessPtr capability_access = apps::mojom::CapabilityAccess::New(); capability_access->app_id = "abcdefg"; capability_access->camera = apps::mojom::OptionalBool::kTrue; capability_access->microphone = apps::mojom::OptionalBool::kFalse; capability_accesses.push_back(std::move(capability_access)); service->GetRemote<crosapi::mojom::AppPublisher>()->OnCapabilityAccesses( std::move(capability_accesses)); } } // namespace namespace apps { FakeLacrosWebAppsHost::FakeLacrosWebAppsHost() {} FakeLacrosWebAppsHost::~FakeLacrosWebAppsHost() = default; void FakeLacrosWebAppsHost::Init() { auto* service = chromeos::LacrosService::Get(); if (!service) { return; } if (!service->IsAvailable<crosapi::mojom::AppPublisher>()) return; if (service->init_params()->web_apps_enabled) { service->GetRemote<crosapi::mojom::AppPublisher>()->RegisterAppController( receiver_.BindNewPipeAndPassRemote()); PushOneApp(); PushOneCapabilityAccess(); } } void FakeLacrosWebAppsHost::Uninstall( const std::string& app_id, apps::mojom::UninstallSource uninstall_source, bool clear_site_data, bool report_abuse) { NOTIMPLEMENTED(); } void FakeLacrosWebAppsHost::PauseApp(const std::string& app_id) { NOTIMPLEMENTED(); } void FakeLacrosWebAppsHost::UnpauseApp(const std::string& app_id) { NOTIMPLEMENTED(); } } // namespace apps
30.207547
78
0.729544
DamieFC
1b72f062fad295c5177a4fe6682f580ff306147f
12,171
cpp
C++
Unpacker/crass/cui/ADX/vgmstream-r526/fb2k/in_vgmstream.cpp
weimingtom/X-moe
8bcca62db18800cb5ac7ad1309535c4c95156eb6
[ "MIT" ]
6
2018-10-12T05:01:49.000Z
2020-11-01T02:47:22.000Z
Unpacker/crass/cui/ADX/vgmstream-r526/fb2k/in_vgmstream.cpp
weimingtom/X-moe
8bcca62db18800cb5ac7ad1309535c4c95156eb6
[ "MIT" ]
null
null
null
Unpacker/crass/cui/ADX/vgmstream-r526/fb2k/in_vgmstream.cpp
weimingtom/X-moe
8bcca62db18800cb5ac7ad1309535c4c95156eb6
[ "MIT" ]
3
2017-09-27T17:28:30.000Z
2019-11-21T15:13:57.000Z
/* Winamp plugin interface for vgmstream */ /* Based on: */ /* ** Example Winamp .RAW input plug-in ** Copyright (c) 1998, Justin Frankel/Nullsoft Inc. */ #ifdef _MSC_VER #define _CRT_SECURE_NO_DEPRECATE #endif #include <windows.h> #include <windowsx.h> #include <commctrl.h> #include <stdio.h> #include <io.h> #include <foobar2000.h> #include <helpers.h> #include <shared.h> extern "C" { #include "../src/vgmstream.h" #include "../src/util.h" } #include "foo_vgmstream.h" #ifndef VERSION #define VERSION #endif #define APP_NAME "vgmstream plugin" #define PLUGIN_DESCRIPTION "vgmstream plugin " VERSION " " __DATE__ #define PLUGIN_VERSION VERSION " " __DATE__ #define INI_NAME "plugin.ini" #define DECODE_SIZE 1024 /* format detection and VGMSTREAM setup, uses default parameters */ VGMSTREAM * init_vgmstream_foo(const char * const filename, abort_callback & p_abort) { VGMSTREAM *vgmstream = NULL; STREAMFILE *streamFile = open_foo_streamfile(filename, &p_abort); if (streamFile) { vgmstream = init_vgmstream_from_STREAMFILE(streamFile); close_streamfile(streamFile); } return vgmstream; } class input_vgmstream { public: void open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) { currentreason = p_reason; if(p_path) strcpy(filename, p_path); switch(p_reason) { case input_open_decode: vgmstream = init_vgmstream_foo(p_path, p_abort); /* were we able to open it? */ if (!vgmstream) { return; } if (ignore_loop) vgmstream->loop_flag = 0; /* will we be able to play it? */ if (vgmstream->channels <= 0) { close_vgmstream(vgmstream); vgmstream=NULL; return; } decode_abort = 0; seek_needed_samples = -1; decode_pos_ms = 0; decode_pos_samples = 0; paused = 0; stream_length_samples = get_vgmstream_play_samples(loop_count,fade_seconds,fade_delay_seconds,vgmstream); fade_samples = (int)(fade_seconds * vgmstream->sample_rate); break; case input_open_info_read: break; case input_open_info_write: //cant write...ever break; default: break; } } void get_info(file_info & p_info,abort_callback & p_abort ) { int length_in_ms=0, channels = 0, samplerate = 0; char title[256]; getfileinfo(filename, title, &length_in_ms, &samplerate, &channels, p_abort); p_info.info_set_int("samplerate", samplerate); p_info.info_set_int("channels", channels); p_info.info_set_int("bitspersample",16); p_info.info_set("encoding","lossless"); p_info.info_set_bitrate(16); p_info.set_length(((double)length_in_ms)/1000); } void decode_initialize(unsigned p_flags,abort_callback & p_abort) { }; bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) { int l = 0, samples_to_do = DECODE_SIZE, t= 0; if(vgmstream && (seek_needed_samples == -1 )) { if (decode_pos_samples+DECODE_SIZE>stream_length_samples && (!loop_forever || !vgmstream->loop_flag)) samples_to_do=stream_length_samples-decode_pos_samples; else samples_to_do=DECODE_SIZE; l = (samples_to_do*vgmstream->channels*2); if (samples_to_do /*< DECODE_SIZE*/ == 0) { return false; } t = ((test_length*vgmstream->sample_rate)/1000); render_vgmstream(sample_buffer,samples_to_do,vgmstream); /* fade! */ if (vgmstream->loop_flag && fade_samples > 0 && !loop_forever) { int samples_into_fade = decode_pos_samples - (stream_length_samples - fade_samples); if (samples_into_fade + samples_to_do > 0) { int j,k; for (j=0;j<samples_to_do;j++,samples_into_fade++) { if (samples_into_fade > 0) { double fadedness = (double)(fade_samples-samples_into_fade)/fade_samples; for (k=0;k<vgmstream->channels;k++) { sample_buffer[j*vgmstream->channels+k] = (short)(sample_buffer[j*vgmstream->channels+k]*fadedness); } } } } } p_chunk.set_data_fixedpoint((char*)sample_buffer, l, vgmstream->sample_rate,vgmstream->channels,16,audio_chunk::g_guess_channel_config(vgmstream->channels)); decode_pos_samples+=samples_to_do; decode_pos_ms=decode_pos_samples*1000LL/vgmstream->sample_rate; return true; } return false; } void decode_seek(double p_seconds,abort_callback & p_abort) { } input_vgmstream() { vgmstream = NULL; decode_thread_handle = INVALID_HANDLE_VALUE; paused = 0; decode_abort = 0; seek_needed_samples = -1; decode_pos_ms = 0; decode_pos_samples = 0; stream_length_samples = 0; fade_samples = 0; fade_seconds = 10.0f; fade_delay_seconds = 0.0f; loop_count = 2.0f; thread_priority = 3; loop_forever = 0; ignore_loop = 0; } ~input_vgmstream() { } t_filestats get_file_stats(abort_callback & p_abort) { t_filestats t; return t; } bool decode_can_seek() {return false;} /*not implemented yet*/ bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) { //do we need anything else 'cept the samplrate return true; } bool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return false;} void decode_on_idle(abort_callback & p_abort) {/*m_file->on_idle(p_abort);*/} void retag(const file_info & p_info,abort_callback & p_abort) {}; static bool g_is_our_content_type(const char * p_content_type) {return false;} static bool g_is_our_path(const char * p_path,const char * p_extension) { if(!stricmp_utf8(p_extension,"adx")) return 1; if(!stricmp_utf8(p_extension,"afc")) return 1; if(!stricmp_utf8(p_extension,"agsc")) return 1; if(!stricmp_utf8(p_extension,"ast")) return 1; if(!stricmp_utf8(p_extension,"brstm")) return 1; if(!stricmp_utf8(p_extension,"brstmspm")) return 1; if(!stricmp_utf8(p_extension,"hps")) return 1; if(!stricmp_utf8(p_extension,"strm")) return 1; if(!stricmp_utf8(p_extension,"adp")) return 1; if(!stricmp_utf8(p_extension,"rsf")) return 1; if(!stricmp_utf8(p_extension,"dsp")) return 1; if(!stricmp_utf8(p_extension,"gcw")) return 1; if(!stricmp_utf8(p_extension,"ads")) return 1; if(!stricmp_utf8(p_extension,"ss2")) return 1; if(!stricmp_utf8(p_extension,"npsf")) return 1; if(!stricmp_utf8(p_extension,"rwsd")) return 1; if(!stricmp_utf8(p_extension,"xa")) return 1; if(!stricmp_utf8(p_extension,"rxw")) return 1; if(!stricmp_utf8(p_extension,"int")) return 1; if(!stricmp_utf8(p_extension,"sts")) return 1; if(!stricmp_utf8(p_extension,"svag")) return 1; if(!stricmp_utf8(p_extension,"mib")) return 1; if(!stricmp_utf8(p_extension,"mi4")) return 1; if(!stricmp_utf8(p_extension,"mpdsp")) return 1; if(!stricmp_utf8(p_extension,"mic")) return 1; if(!stricmp_utf8(p_extension,"gcm")) return 1; if(!stricmp_utf8(p_extension,"mss")) return 1; if(!stricmp_utf8(p_extension,"raw")) return 1; if(!stricmp_utf8(p_extension,"vag")) return 1; if(!stricmp_utf8(p_extension,"gms")) return 1; if(!stricmp_utf8(p_extension,"str")) return 1; if(!stricmp_utf8(p_extension,"ild")) return 1; if(!stricmp_utf8(p_extension,"pnb")) return 1; if(!stricmp_utf8(p_extension,"wavm")) return 1; if(!stricmp_utf8(p_extension,"xwav")) return 1; if(!stricmp_utf8(p_extension,"wp2")) return 1; if(!stricmp_utf8(p_extension,"pnb")) return 1; if(!stricmp_utf8(p_extension,"str")) return 1; if(!stricmp_utf8(p_extension,"sng")) return 1; if(!stricmp_utf8(p_extension,"asf")) return 1; if(!stricmp_utf8(p_extension,"eam")) return 1; if(!stricmp_utf8(p_extension,"cfn")) return 1; if(!stricmp_utf8(p_extension,"vpk")) return 1; if(!stricmp_utf8(p_extension,"genh")) return 1; return 0; } public: service_ptr_t<file> m_file; char filename[260]; t_input_open_reason currentreason; VGMSTREAM * vgmstream; HANDLE decode_thread_handle; int paused; int decode_abort; int seek_needed_samples; int decode_pos_ms; int decode_pos_samples; int stream_length_samples; int fade_samples; int test_length; double fade_seconds; double fade_delay_seconds; double loop_count; int thread_priority; int loop_forever; int ignore_loop; short sample_buffer[576*2*2]; /* 576 16-bit samples, stereo, possibly doubled in size for DSP */ void getfileinfo(char *filename, char *title, int *length_in_ms, int *sample_rate, int *channels, abort_callback & p_abort); }; /* retrieve information on this or possibly another file */ void input_vgmstream::getfileinfo(char *filename, char *title, int *length_in_ms, int *sample_rate, int *channels, abort_callback & p_abort) { VGMSTREAM * infostream; if (length_in_ms) { *length_in_ms=-1000; if ((infostream=init_vgmstream_foo(filename, p_abort))) { *length_in_ms = get_vgmstream_play_samples(loop_count,fade_seconds,fade_delay_seconds,infostream)*1000LL/infostream->sample_rate; test_length = *length_in_ms; *sample_rate = infostream->sample_rate; *channels = infostream->channels; close_vgmstream(infostream); infostream=NULL; } } if (title) { char *p=filename+strlen(filename); while (*p != '\\' && p >= filename) p--; strcpy(title,++p); } } static input_singletrack_factory_t<input_vgmstream> g_input_vgmstream_factory; DECLARE_COMPONENT_VERSION(APP_NAME,PLUGIN_VERSION,PLUGIN_DESCRIPTION); DECLARE_MULTIPLE_FILE_TYPE("ADX Audio File (*.ADX)", adx); DECLARE_MULTIPLE_FILE_TYPE("AFC Audio File (*.AFC)", afc); DECLARE_MULTIPLE_FILE_TYPE("AGSC Audio File (*.AGSC)", agsc); DECLARE_MULTIPLE_FILE_TYPE("AST Audio File (*.AST)", ast); DECLARE_MULTIPLE_FILE_TYPE("BRSTM Audio File (*.BRSTM)", brstm); DECLARE_MULTIPLE_FILE_TYPE("BRSTM Audio File (*.BRSTMSPM)", brstmspm); DECLARE_MULTIPLE_FILE_TYPE("HALPST Audio File (*.HPS)", hps); DECLARE_MULTIPLE_FILE_TYPE("STRM Audio File (*.STRM)", strm); DECLARE_MULTIPLE_FILE_TYPE("ADP Audio File (*.ADP)", adp); DECLARE_MULTIPLE_FILE_TYPE("RSF Audio File (*.RSF)", rsf); DECLARE_MULTIPLE_FILE_TYPE("DSP Audio File (*.DSP)", dsp); DECLARE_MULTIPLE_FILE_TYPE("GCW Audio File (*.GCW)", gcw); DECLARE_MULTIPLE_FILE_TYPE("PS2 ADS Audio File (*.ADS)", ads); DECLARE_MULTIPLE_FILE_TYPE("PS2 SS2 Audio File (*.SS2)", ss2); DECLARE_MULTIPLE_FILE_TYPE("PS2 NPSF Audio File (*.NPSF)", npsf); DECLARE_MULTIPLE_FILE_TYPE("RWSD Audio File (*.RWSD)", rwsd); DECLARE_MULTIPLE_FILE_TYPE("PSX CD-XA File (*.XA)", xa); DECLARE_MULTIPLE_FILE_TYPE("PS2 RXWS File (*.RXW)", rxw); DECLARE_MULTIPLE_FILE_TYPE("PS2 RAW Interleaved PCM (*.INT)", int); DECLARE_MULTIPLE_FILE_TYPE("PS2 EXST Audio File (*.STS)", sts); DECLARE_MULTIPLE_FILE_TYPE("PS2 SVAG Audio File (*.SVAG)", svag); DECLARE_MULTIPLE_FILE_TYPE("PS2 MIB Audio File (*.MIB)", mib); DECLARE_MULTIPLE_FILE_TYPE("PS2 MI4 Audio File (*.MI4)", mi4); DECLARE_MULTIPLE_FILE_TYPE("MPDSP Audio File (*.MPDSP)", mpdsp); DECLARE_MULTIPLE_FILE_TYPE("PS2 MIC Audio File (*.MIC)", mic); DECLARE_MULTIPLE_FILE_TYPE("GCM Audio File (*.GCM)", gcm); DECLARE_MULTIPLE_FILE_TYPE("MSS Audio File (*.MSS)", mss); DECLARE_MULTIPLE_FILE_TYPE("RAW Audio File (*.RAW)", raw); DECLARE_MULTIPLE_FILE_TYPE("VAG Audio File (*.VAG)", vag); DECLARE_MULTIPLE_FILE_TYPE("GMS Audio File (*.GMS)", gms); DECLARE_MULTIPLE_FILE_TYPE("STR Audio File (*.STR)", str);
35.176301
170
0.663709
weimingtom
1b7520c37f1409c60529d6ab0b69a816c720f707
8,867
cpp
C++
cuda/laghos_assembly.cpp
artv3/Laghos
64449d427349b0ca35086a63ae4e7d1ed5894f08
[ "BSD-2-Clause" ]
1
2022-03-24T07:03:23.000Z
2022-03-24T07:03:23.000Z
cuda/laghos_assembly.cpp
jeffhammond/Laghos
12e62aa7eb6175f27380106b40c9286d710a0f52
[ "BSD-2-Clause" ]
null
null
null
cuda/laghos_assembly.cpp
jeffhammond/Laghos
12e62aa7eb6175f27380106b40c9286d710a0f52
[ "BSD-2-Clause" ]
3
2020-04-12T20:07:41.000Z
2022-03-24T07:07:52.000Z
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights // reserved. See files LICENSE and NOTICE for details. // // This file is part of CEED, a collection of benchmarks, miniapps, software // libraries and APIs for efficient high-order finite element and spectral // element discretizations for exascale applications. For more information and // source code availability see http://github.com/ceed. // // The CEED research is supported by the Exascale Computing Project (17-SC-20-SC) // a collaborative effort of two U.S. Department of Energy organizations (Office // of Science and the National Nuclear Security Administration) responsible for // the planning and preparation of a capable exascale ecosystem, including // software, applications, hardware, advanced system engineering and early // testbed platforms, in support of the nation's exascale computing imperative. #include "laghos_assembly.hpp" #ifdef MFEM_USE_MPI using namespace std; namespace mfem { namespace hydrodynamics { QuadratureData::QuadratureData(int dim, int nzones, int nqp) { Setup(dim, nzones, nqp); } void QuadratureData::Setup(int dim, int nzones, int nqp) { rho0DetJ0w.SetSize(nqp * nzones); stressJinvT.SetSize(dim * dim * nqp * nzones); dtEst.SetSize(nqp * nzones); } void DensityIntegrator::AssembleRHSElementVect(const FiniteElement &fe, ElementTransformation &Tr, Vector &elvect) { const int ip_cnt = integ_rule.GetNPoints(); Vector shape(fe.GetDof()); Vector rho0DetJ0w = quad_data.rho0DetJ0w; elvect.SetSize(fe.GetDof()); elvect = 0.0; for (int q = 0; q < ip_cnt; q++) { fe.CalcShape(integ_rule.IntPoint(q), shape); shape *= rho0DetJ0w(Tr.ElementNo*ip_cnt + q); elvect += shape; } } // ***************************************************************************** CudaMassOperator::CudaMassOperator(CudaFiniteElementSpace &fes_, const IntegrationRule &integ_rule_, QuadratureData *quad_data_) : CudaOperator(fes_.GetTrueVSize()), fes(fes_), integ_rule(integ_rule_), ess_tdofs_count(0), bilinearForm(&fes), quad_data(quad_data_), x_gf(fes), y_gf(fes) {} // ***************************************************************************** CudaMassOperator::~CudaMassOperator() { } // ***************************************************************************** void CudaMassOperator::Setup() { dim=fes.GetMesh()->Dimension(); nzones=fes.GetMesh()->GetNE(); CudaMassIntegrator &massInteg = *(new CudaMassIntegrator()); massInteg.SetIntegrationRule(integ_rule); massInteg.SetOperator(quad_data->rho0DetJ0w); bilinearForm.AddDomainIntegrator(&massInteg); bilinearForm.Assemble(); bilinearForm.FormOperator(Array<int>(), massOperator); } // ************************************************************************* void CudaMassOperator::SetEssentialTrueDofs(Array<int> &dofs) { ess_tdofs_count = dofs.Size(); if (ess_tdofs.Size()==0) { #ifdef MFEM_USE_MPI int global_ess_tdofs_count; const MPI_Comm comm = fes.GetParMesh()->GetComm(); MPI_Allreduce(&ess_tdofs_count,&global_ess_tdofs_count, 1, MPI_INT, MPI_SUM, comm); assert(global_ess_tdofs_count>0); ess_tdofs.allocate(global_ess_tdofs_count); #else assert(ess_tdofs_count>0); ess_tdofs.allocate(ess_tdofs_count); #endif } else { assert(ess_tdofs_count<=ess_tdofs.Size()); } assert(ess_tdofs.ptr()); if (ess_tdofs_count == 0) { return; } assert(ess_tdofs_count>0); assert(dofs.GetData()); rHtoD(ess_tdofs.ptr(),dofs.GetData(),ess_tdofs_count*sizeof(int)); } // ***************************************************************************** void CudaMassOperator::EliminateRHS(CudaVector &b) { if (ess_tdofs_count > 0) { b.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count); } } // ************************************************************************* void CudaMassOperator::Mult(const CudaVector &x, CudaVector &y) const { distX = x; if (ess_tdofs_count) { distX.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count); } massOperator->Mult(distX, y); if (ess_tdofs_count) { y.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count); } } // ***************************************************************************** // * CudaForceOperator // ***************************************************************************** CudaForceOperator::CudaForceOperator(CudaFiniteElementSpace &h1fes_, CudaFiniteElementSpace &l2fes_, const IntegrationRule &integ_rule_, const QuadratureData *quad_data_) : CudaOperator(l2fes_.GetTrueVSize(), h1fes_.GetTrueVSize()), dim(h1fes_.GetMesh()->Dimension()), nzones(h1fes_.GetMesh()->GetNE()), h1fes(h1fes_), l2fes(l2fes_), integ_rule(integ_rule_), quad_data(quad_data_), gVecL2(l2fes.GetLocalDofs() * nzones), gVecH1(h1fes.GetVDim() * h1fes.GetLocalDofs() * nzones) { } // ***************************************************************************** CudaForceOperator::~CudaForceOperator() {} // ************************************************************************* void CudaForceOperator::Setup() { h1D2Q = CudaDofQuadMaps::Get(h1fes, integ_rule); l2D2Q = CudaDofQuadMaps::Get(l2fes, integ_rule); } // ************************************************************************* void CudaForceOperator::Mult(const CudaVector &vecL2, CudaVector &vecH1) const { l2fes.GlobalToLocal(vecL2, gVecL2); const int NUM_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; const IntegrationRule &ir1D = IntRules.Get(Geometry::SEGMENT, integ_rule.GetOrder()); const int NUM_QUAD_1D = ir1D.GetNPoints(); const int L2_DOFS_1D = l2fes.GetFE(0)->GetOrder()+1; const int H1_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; if (rconfig::Get().Share()) rForceMultS(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->dofToQuad, h1D2Q->quadToDof, h1D2Q->quadToDofD, quad_data->stressJinvT, gVecL2, gVecH1); else rForceMult(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->dofToQuad, h1D2Q->quadToDof, h1D2Q->quadToDofD, quad_data->stressJinvT, gVecL2, gVecH1); h1fes.LocalToGlobal(gVecH1, vecH1); } // ************************************************************************* void CudaForceOperator::MultTranspose(const CudaVector &vecH1, CudaVector &vecL2) const { h1fes.GlobalToLocal(vecH1, gVecH1); const int NUM_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; const IntegrationRule &ir1D = IntRules.Get(Geometry::SEGMENT, integ_rule.GetOrder()); const int NUM_QUAD_1D = ir1D.GetNPoints(); const int L2_DOFS_1D = l2fes.GetFE(0)->GetOrder()+1; const int H1_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; if (rconfig::Get().Share()) rForceMultTransposeS(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->quadToDof, h1D2Q->dofToQuad, h1D2Q->dofToQuadD, quad_data->stressJinvT, gVecH1, gVecL2); else rForceMultTranspose(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->quadToDof, h1D2Q->dofToQuad, h1D2Q->dofToQuadD, quad_data->stressJinvT, gVecH1, gVecL2); l2fes.LocalToGlobal(gVecL2, vecL2); } } // namespace hydrodynamics } // namespace mfem #endif // MFEM_USE_MPI
34.772549
81
0.523627
artv3
1b76030b9f9bc6b349ad56b325924f2df6d977d9
190
cpp
C++
ios/versioned-react-native/ABI26_0_0/ReactCommon/ABI26_0_0privatedata/ABI26_0_0PrivateDataBase.cpp
ThakurKarthik/expo
ed78ed4f07c950184a59422ebd95645253f44e3d
[ "Apache-2.0", "MIT" ]
2
2019-08-15T19:24:41.000Z
2020-09-28T00:44:04.000Z
ios/versioned-react-native/ABI26_0_0/ReactCommon/ABI26_0_0privatedata/ABI26_0_0PrivateDataBase.cpp
ThakurKarthik/expo
ed78ed4f07c950184a59422ebd95645253f44e3d
[ "Apache-2.0", "MIT" ]
2
2022-02-14T18:22:55.000Z
2022-02-26T02:17:58.000Z
ios/versioned-react-native/ABI26_0_0/ReactCommon/ABI26_0_0privatedata/ABI26_0_0PrivateDataBase.cpp
ThakurKarthik/expo
ed78ed4f07c950184a59422ebd95645253f44e3d
[ "Apache-2.0", "MIT" ]
1
2020-03-01T01:28:59.000Z
2020-03-01T01:28:59.000Z
// Copyright 2004-present Facebook. All Rights Reserved. #include "ABI26_0_0PrivateDataBase.h" namespace facebook { namespace ReactABI26_0_0 { PrivateDataBase::~PrivateDataBase() {} } }
17.272727
56
0.773684
ThakurKarthik
1b7768553c1533a091c75d5d3e93211c2ce76500
849
cpp
C++
src/transcrLUSS/fv2id.cpp
jvitkauskas/liepa
2a1e0d27e326a739691414b59474cd09dce16bfa
[ "0BSD" ]
null
null
null
src/transcrLUSS/fv2id.cpp
jvitkauskas/liepa
2a1e0d27e326a739691414b59474cd09dce16bfa
[ "0BSD" ]
null
null
null
src/transcrLUSS/fv2id.cpp
jvitkauskas/liepa
2a1e0d27e326a739691414b59474cd09dce16bfa
[ "0BSD" ]
null
null
null
#include "stdafx.h" #include "fv2id.h" #include <string.h> char* strtokf(char*, const char*, char**); unsigned short fv2id(char *fpav) { for (int i = 0; i < FonSk; i++) if (strcmp(fpav, FonV[i].fv) == 0) return FonV[i].id; return FonV[0].id; //pauze "_" } char* id2fv(unsigned short id) { for (int i = 0; i < FonSk; i++) if (id == FonV[i].id) return FonV[i].fv; return FonV[0].fv; //pauze "_" } int trText2UnitList(char *TrSakinys, unsigned short *units, unsigned short *unitseparators) { char temp[500], *pos, *newpos; //turetu pakakti 480 strcpy(temp, TrSakinys); int i = 0; pos = strtokf(temp, "+- ", &newpos); while (pos != NULL) { units[i] = fv2id(pos); pos = strtokf(NULL, "+- ", &newpos); if (pos == NULL) unitseparators[i] = '+'; else unitseparators[i] = TrSakinys[pos - temp - 1]; i++; } return i; }
19.744186
91
0.605418
jvitkauskas
1b77ccb65d9cd0496c26d804b80a70fc35ea99e2
4,712
cc
C++
deepmath/zz/Generics/Main_test.cc
LaudateCorpus1/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
[ "Apache-2.0" ]
830
2016-11-07T21:46:27.000Z
2022-03-23T08:01:03.000Z
deepmath/zz/Generics/Main_test.cc
LaudateCorpus1/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
[ "Apache-2.0" ]
26
2016-11-07T22:06:31.000Z
2022-02-16T00:18:29.000Z
deepmath/zz/Generics/Main_test.cc
LaudateCorpus1/deepmath
b5b721f54de1d5d6a02d78f5da5995237f9995f9
[ "Apache-2.0" ]
168
2016-11-07T21:48:55.000Z
2022-03-19T02:47:14.000Z
#include ZZ_Prelude_hh #include "PArr.hh" #include <vector> #include <memory> using namespace ZZ; //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm struct MyInt { uint n; uint waste[15]; MyInt(uint n = 0) : n(n) {} operator uint() const { return n; } }; int main(int argc, char** argv) { ZZ_Init; #if 0 // Simple test: PArr<int> arr; arr = arr.push(1); arr = arr.push(2); arr = arr.push(3); PArr<int> arr2 = arr.pop(); Dump(arr); Dump(arr2); arr2 = arr2.set(100, 42); Dump(arr2); wr("numbers:"); arr2.enumAll([](uind idx, int n){ wr(" %_=%_", idx, n); return true; }); newLn(); #endif #if 0 // Correctness test: uint64 seed = 0; #if 0 Vec<PArr<int>> arrs(10); #else Vec<vector<int>> arrs(10, vector<int>(30)); #endif for (uint n = 0; n < 1000000; n++){ uint i = irand(seed, arrs.size()); uint j = irand(seed, 30); uint v = irand(seed, 10000 - 1000) + 1000; //**/wrLn("arrs[%_].set(%_, %_)", i, j, v); #if 0 arrs[i] = arrs[i].set(j, v); #else arrs[i][j] = v; #endif //**/wr(" -> "); arrs[i].dump(); newLn(); if (n % 1000 == 0){ uint i0 = irand(seed, arrs.size()); uint i1 = irand(seed, arrs.size()); arrs[i0] = arrs[i1]; } } wrLn("%\n_", arrs); #endif #if 0 uint64 seed = 0; Vec<PArr<MyInt, 8, 2>> arrs(10); // Speed test: uint N = 1000000; uint sz = 30000; double T0 = realTime(); for (uint n = 0; n < N; n++){ uint i = irand(seed, arrs.size()); uint j = irand(seed, sz); uint v = irand(seed, 10000 - 1000) + 1000; arrs[i] = arrs[i].set(j, v); if (n % 1000 == 0){ uint i0 = irand(seed, arrs.size()); uint i1 = irand(seed, arrs.size()); arrs[i0] = arrs[i1]; } } double T1 = realTime(); wrLn("Cycles/write: %_", (T1-T0) / N * 2.4e9); #endif // Iteration speed test: uint N = 10000; PArr<MyInt,4> arr; for (uint i = 0; i < 20; i++) arr = arr.push(i); { double T0 = realTime(); uint64 sum = 0; for (uint n = 0; n < N; n++){ for (uint i = 0; i < arr.size(); i++) sum += arr[i]; } double T1 = realTime(); wrLn("LOOP: sum=%_ time=%t (%.0f cycles)", sum, (T1-T0) / N, (T1-T0) / N * 2.4e9); } { double T0 = realTime(); uint64 sum = 0; for (uint n = 0; n < N; n++){ arr.forAllCondRev([&](MyInt const& v) { sum += v; return true; }); } double T1 = realTime(); wrLn("ITER: sum=%_ time=%t (%.0f cycles)", sum, (T1-T0) / N, (T1-T0) / N * 2.4e9); } return 0; } /* [1195, 8025, 2330, 6909, 6214, 9379, 9308, 8788, 6198, 4952, 1802, 1087, 2321, 4546, 8536, 4030, 8695, 5455, 8509, 4664, 7999, 1533, 6433, 2418, 1532, 7387, 5372, 7431, 6036, 1711] [4240, 6760, 7950, 3579, 8589, 4009, 4333, 6233, 4888, 2592, 3177, 4712, 2216, 2231, 8506, 8830, 3885, 4125, 1849, 3144, 6444, 1598, 4723, 8338, 5192, 5247, 5897, 1121, 5161, 2486] [6340, 1005, 2170, 1384, 8589, 4094, 5023, 7018, 2393, 2592, 2692, 6242, 9446, 5686, 8506, 9150, 3390, 7975, 5414, 3144, 4494, 9868, 8118, 6838, 5192, 4592, 5272, 5721, 3096, 2486] [4960, 8950, 6005, 9649, 5194, 2984, 3743, 6043, 8173, 9317, 7917, 1697, 5041, 5531, 4526, 1140, 9185, 9435, 5454, 7469, 7579, 4693, 4933, 9068, 2067, 8467, 2997, 3251, 1281, 7426] [9030, 5110, 5550, 3409, 2909, 8284, 5978, 1398, 5088, 4952, 4547, 9207, 9046, 9296, 1256, 9580, 5650, 5710, 9434, 9224, 7044, 3608, 2148, 8418, 5637, 9242, 7357, 1721, 5256, 4016] [3940, 7485, 5575, 6754, 5044, 5739, 7138, 6693, 1053, 2162, 3827, 8352, 2326, 2851, 8001, 1225, 4220, 8410, 9444, 9059, 1129, 1023, 1913, 3618, 9047, 5147, 6047, 3556, 6601, 3261] [2985, 5480, 5640, 8119, 9344, 1814, 6538, 7908, 8088, 1667, 8417, 5317, 7841, 5341, 5726, 4895, 9170, 1285, 1214, 6434, 2349, 4898, 4978, 1773, 8462, 2637, 5712, 5256, 1516, 5826] [6585, 1125, 2105, 3629, 1579, 8169, 7858, 4408, 3173, 9277, 8087, 9712, 9541, 9271, 7776, 1260, 5275, 7905, 9459, 5024, 9349, 6183, 8963, 9993, 2837, 4602, 1357, 1581, 2661, 3931] [1775, 8070, 9145, 4074, 4729, 3974, 8663, 1203, 1158, 2632, 8697, 8402, 1336, 1916, 4556, 5855, 2115, 5275, 1069, 3439, 3709, 8618, 5438, 3203, 4137, 8992, 2742, 9881, 7821, 7611] [4960, 4425, 1625, 6909, 1364, 2984, 1343, 4713, 6198, 8852, 7917, 9827, 1441, 4546, 1831, 1140, 7655, 8180, 8509, 2579, 7579, 9238, 7268, 2418, 1222, 8467, 5837, 2051, 6036, 6851] */
33.899281
180
0.545204
LaudateCorpus1
1b797aa0c5f3b55f246455346a249c582dead4b3
2,385
cpp
C++
projects/Vk_12/src/timer.cpp
AnselmoGPP/Vulkan_samples
9aaefcff024962b41539be70a9179e78856ff6a7
[ "MIT" ]
null
null
null
projects/Vk_12/src/timer.cpp
AnselmoGPP/Vulkan_samples
9aaefcff024962b41539be70a9179e78856ff6a7
[ "MIT" ]
null
null
null
projects/Vk_12/src/timer.cpp
AnselmoGPP/Vulkan_samples
9aaefcff024962b41539be70a9179e78856ff6a7
[ "MIT" ]
null
null
null
#include "timer.hpp" #include <iostream> #include <thread> #include <chrono> #include <cmath> TimerSet::TimerSet(int maximumFPS) : currentTime(std::chrono::system_clock::duration::zero()), maxFPS(maximumFPS) { startTimer(); time = 0; deltaTime = 0; FPS = 0; frameCounter = 0; } void TimerSet::startTimer() { startTime = std::chrono::high_resolution_clock::now(); prevTime = startTime; //std::this_thread::sleep_for(std::chrono::microseconds(1000)); // Avoids deltaTime == 0 (i.e. currentTime == lastTime) } void TimerSet::computeDeltaTime() { // Get deltaTime currentTime = std::chrono::high_resolution_clock::now(); //time = std::chrono::duration_cast<std::chrono::microseconds>(currentTime - startTime).count() / 1000000.l; //time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); deltaTime = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - prevTime).count(); // Add some time to deltaTime to adjust the FPS (if FPS control is enabled) if (maxFPS > 0) { int waitTime = (1.l / maxFPS - deltaTime) * 1000000; // microseconds (for the sleep) if (waitTime > 0) { std::this_thread::sleep_for(std::chrono::microseconds(waitTime)); currentTime = std::chrono::high_resolution_clock::now(); deltaTime = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - prevTime).count(); } } prevTime = currentTime; // Get FPS FPS = std::round(1 / deltaTime); // Get time time = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - startTime).count(); // Increment the frame count ++frameCounter; } long double TimerSet::getDeltaTime() { return deltaTime; } long double TimerSet::getTime() { return time; } long double TimerSet::getTimeNow() { std::chrono::high_resolution_clock::time_point timeNow = std::chrono::high_resolution_clock::now(); return std::chrono::duration<long double, std::chrono::seconds::period>(timeNow - startTime).count(); } int TimerSet::getFPS() { return FPS; } void TimerSet::setMaxFPS(int newFPS) { maxFPS = newFPS; } size_t TimerSet::getFrameCounter() { return frameCounter; };
32.22973
126
0.646122
AnselmoGPP
1b799112689c41db6f923b8bb8dd200ae6eccc44
5,147
cpp
C++
ofApp.cpp
SJ-magic-study-oF/study__DmxToPwm
70a27f8697b72f94652ad5c03e84f0737c8a4a2b
[ "MIT" ]
null
null
null
ofApp.cpp
SJ-magic-study-oF/study__DmxToPwm
70a27f8697b72f94652ad5c03e84f0737c8a4a2b
[ "MIT" ]
null
null
null
ofApp.cpp
SJ-magic-study-oF/study__DmxToPwm
70a27f8697b72f94652ad5c03e84f0737c8a4a2b
[ "MIT" ]
null
null
null
/************************************************************ ************************************************************/ #include "ofApp.h" /************************************************************ ************************************************************/ char targetIP[] = "10.7.206.7"; enum LED_TYPE{ LEDTYPE_STAGELIGHT, LEDTYPE_TAPE, }; struct Led{ LED_TYPE LedType; int OdeOffset; }; /* */ Led Led[] = { // DMX/PWM converter 1 { LEDTYPE_TAPE , 0 }, // 0 HardOffset = 1 { LEDTYPE_TAPE , 3 }, // 1 { LEDTYPE_TAPE , 6 }, // 2 { LEDTYPE_TAPE , 9 }, // 3 { LEDTYPE_TAPE , 12 }, // 4 { LEDTYPE_TAPE , 15 }, // 5 { LEDTYPE_TAPE , 18 }, // 6 { LEDTYPE_TAPE , 21 }, // 7 // DMX/PWM converter 2 { LEDTYPE_TAPE , 24 }, // 8 HardOffset = 25 { LEDTYPE_TAPE , 27 }, // 9 { LEDTYPE_TAPE , 30 }, // 10 { LEDTYPE_TAPE , 33 }, // 11 { LEDTYPE_TAPE , 36 }, // 12 { LEDTYPE_TAPE , 39 }, // 13 { LEDTYPE_TAPE , 42 }, // 14 { LEDTYPE_TAPE , 45 }, // 15 // Stage Light { LEDTYPE_STAGELIGHT , 48 }, // 16 HardOffset = 49 }; const int NUM_LEDS = sizeof(Led)/sizeof(Led[0]); /************************************************************ ************************************************************/ //-------------------------------------------------------------- void ofApp::setup(){ /******************** ********************/ ofSetWindowShape(600, 400); ofSetVerticalSync(false); ofSetFrameRate(60); //at first you must specify the Ip address of this machine artnet.setup("10.0.0.2"); //make sure the firewall is deactivated at this point /******************** ********************/ for(int i = 0; i < DMX_SIZE; i++){ data[i] = 0; } /******************** ********************/ ofColor initColor = ofColor(0, 0, 0, 255); ofColor minColor = ofColor(0, 0, 0, 0); ofColor maxColor = ofColor(255, 255, 255, 255); /******************** ********************/ gui.setup(); gui.add(LedId.setup("LedId", 0, 0, NUM_LEDS - 1)); gui.add(color.setup("color", initColor, minColor, maxColor)); } //-------------------------------------------------------------- void ofApp::update(){ /* // All Led on ofColor CurrentColor = color; for(int i = 0; i < NUM_LEDS; i++){ set_dataArray(i, CurrentColor); } /*/ // single Led on for(int i = 0; i < DMX_SIZE; i++){ data[i] = 0; } ofColor CurrentColor = color; set_dataArray(LedId, CurrentColor); //*/ } //-------------------------------------------------------------- void ofApp::set_dataArray(int id, ofColor CurrentColor){ switch(Led[id].LedType){ case LEDTYPE_STAGELIGHT: data[Led[id].OdeOffset + 0] = CurrentColor.a; data[Led[id].OdeOffset + 1] = CurrentColor.r; data[Led[id].OdeOffset + 2] = CurrentColor.g; data[Led[id].OdeOffset + 3] = CurrentColor.b; data[Led[id].OdeOffset + 4] = 0; // w; data[Led[id].OdeOffset + 5] = 1; // Strobe. 1-9:open break; case LEDTYPE_TAPE: data[Led[id].OdeOffset + 0] = CurrentColor.r; data[Led[id].OdeOffset + 1] = CurrentColor.g; data[Led[id].OdeOffset + 2] = CurrentColor.b; break; } } //-------------------------------------------------------------- void ofApp::exit(){ for(int i = 0; i < DMX_SIZE; i++){ data[i] = 0; } artnet.sendDmx(targetIP, data, DMX_SIZE); } //-------------------------------------------------------------- void ofApp::draw(){ /******************** ********************/ ofBackground(30); /******************** ********************/ // list nodes for sending // with subnet / universe // artnet.sendDmx("10.0.0.149", 0xf, 0xf, testImage.getPixels(), 512); artnet.sendDmx(targetIP, data, DMX_SIZE); /******************** ********************/ gui.draw(); /******************** ********************/ printf("%5.1f\r", ofGetFrameRate()); fflush(stdout); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
24.626794
83
0.39693
SJ-magic-study-oF
1b79f27ffad12fcd0bf4681b0ca5a2d5409af313
1,460
cpp
C++
20_VECTORS_STRUCTURES/main.cpp
CrispenGari/cool-cpp
bcbf9e0df7af07f8b12aa554fd15d977ecb47f60
[ "MIT" ]
null
null
null
20_VECTORS_STRUCTURES/main.cpp
CrispenGari/cool-cpp
bcbf9e0df7af07f8b12aa554fd15d977ecb47f60
[ "MIT" ]
null
null
null
20_VECTORS_STRUCTURES/main.cpp
CrispenGari/cool-cpp
bcbf9e0df7af07f8b12aa554fd15d977ecb47f60
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdlib> #include <ctime> #include <afxres.h> #include <fstream> #include <sstream> #include <vector> using namespace std; //#include <Crispen.h> // #include <sqlite3.h/sqlite3> #include <iostream> #include <cstdlib> using namespace std; #include <map> #include <vector> #include <string> /* VECTORS AND STRUCTURES */ struct Person{ int age;double weight;string name; string surname; }person[5]; /// creating vectors of ages, weight, names and surnames vector<int> ages = {22, 20, 21, 21,27}; vector<double> weights ={78.7, 69.4,88.9,100,79.8}; vector<string> names = {"Grossary", "Maxwell", "Clocktick", "Rebbalion", "Stalion"}; vector<string> surnames = {"Mark", "Zoran", "Clasic", "Mark", "Peter"}; void printSruct(); int main(){ /// inserting names into our structur person int i=0; for(string nam: names){ person[i].name = nam; i++; } /// inserting surnames into our structure person int s=0; for(string element: surnames){ person[s].surname = element; s++; } int k=0; for(int i: ages){ person[k].age =i; k++; } size_t j=0; for(double w: weights){ person[j].weight = w; j++; } printSruct(); return 0; } void printSruct(){ for(int i =0; i<sizeof(person)/sizeof(person[0]);i++){ cout<<"("<<person[i].name<<", " <<person[i].surname<<", " <<person[i].age<<", " <<person[i].weight<<")"<<endl; } }
21.470588
117
0.615753
CrispenGari
1b7a1fc489c7c804698a5427fec651904f781e9d
2,162
cpp
C++
StateManager.cpp
JorgeAndd/NeoEngine
c83b0c21fd97fe4976c3cf142fc93814e8f0892c
[ "MIT" ]
null
null
null
StateManager.cpp
JorgeAndd/NeoEngine
c83b0c21fd97fe4976c3cf142fc93814e8f0892c
[ "MIT" ]
null
null
null
StateManager.cpp
JorgeAndd/NeoEngine
c83b0c21fd97fe4976c3cf142fc93814e8f0892c
[ "MIT" ]
null
null
null
#include "StateManager.h" StateManager::StateManager() { SDLBase::initSDL(); inst = InputManager::getInstance(); currentState = new State_Splash(); currentState->load(); srand(time(NULL)); inst->update(); stack = 0; } StateManager::~StateManager() { SDLBase::exitSDL(); currentState->unload(); free(currentState); } void StateManager::run() { bool quit = false; float accumulator, lastTime; const float dt = TIME_STEP; lastTime = SDL_GetTicks()/1000.f; accumulator = 0.f; while(!quit) { float nowTime = SDL_GetTicks()/1000.f; float frameTime = nowTime - lastTime; lastTime = nowTime; accumulator += frameTime; if(accumulator >= dt) { inst->update(); if(inst->quitGame()) { quit = true; continue; } switch(currentState->update()) { case STATE: break; case STATE_SPLASH: stack = currentState->unload(); delete(currentState); currentState = new State_Splash(); currentState->load(stack); break; case STATE_GAME: stack = currentState->unload(); delete(currentState); currentState = new State_Game(); currentState->load(stack); break; case STATE_END: stack = currentState->unload(); delete(currentState); currentState = new State_End(); currentState->load(stack); break; case STATE_QUIT: quit = true; break; } accumulator -= dt; } currentState->render(); SDLBase::updateScreen(); /* now = SDL_GetTicks(); if(next_time > now) SDL_Delay(next_time - now); next_time += TICK_INTERVAL; */ } }
24.022222
54
0.466235
JorgeAndd
1b7b62adc99e85e5d461a5ffcf705f038004383b
7,231
hpp
C++
src/uml/src_gen/uml/StructuralFeatureAction.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
null
null
null
src/uml/src_gen/uml/StructuralFeatureAction.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
null
null
null
src/uml/src_gen/uml/StructuralFeatureAction.hpp
dataliz9r/MDE4CPP
9c5ce01c800fb754c371f1a67f648366eeabae49
[ "MIT" ]
null
null
null
//******************************************************************** //* //* Warning: This file was generated by ecore4CPP Generator //* //******************************************************************** #ifndef UML_STRUCTURALFEATUREACTION_HPP #define UML_STRUCTURALFEATUREACTION_HPP #include <map> #include <list> #include <memory> #include <string> // forward declarations template<class T, class ... U> class Subset; class AnyObject; typedef std::shared_ptr<AnyObject> Any; //********************************* // generated Includes #include <map> namespace persistence { namespace interfaces { class XLoadHandler; // used for Persistence class XSaveHandler; // used for Persistence } } namespace uml { class UmlFactory; } //Forward Declaration for used types namespace uml { class Action; } namespace uml { class Activity; } namespace uml { class ActivityEdge; } namespace uml { class ActivityGroup; } namespace uml { class ActivityNode; } namespace uml { class ActivityPartition; } namespace uml { class Classifier; } namespace uml { class Comment; } namespace uml { class Constraint; } namespace uml { class Dependency; } namespace uml { class Element; } namespace uml { class ExceptionHandler; } namespace uml { class InputPin; } namespace uml { class InterruptibleActivityRegion; } namespace uml { class Namespace; } namespace uml { class OutputPin; } namespace uml { class RedefinableElement; } namespace uml { class StringExpression; } namespace uml { class StructuralFeature; } namespace uml { class StructuredActivityNode; } // base class includes #include "uml/Action.hpp" // enum includes #include "uml/VisibilityKind.hpp" //********************************* namespace uml { /*! StructuralFeatureAction is an abstract class for all Actions that operate on StructuralFeatures. <p>From package UML::Actions.</p> */ class StructuralFeatureAction:virtual public Action { public: StructuralFeatureAction(const StructuralFeatureAction &) {} StructuralFeatureAction& operator=(StructuralFeatureAction const&) = delete; protected: StructuralFeatureAction(){} public: virtual std::shared_ptr<ecore::EObject> copy() const = 0; //destructor virtual ~StructuralFeatureAction() {} //********************************* // Operations //********************************* /*! The multiplicity of the object InputPin must be 1..1. object.is(1,1) */ virtual bool multiplicity(Any diagnostics,std::map < Any, Any > context) = 0; /*! The structuralFeature must not be static. not structuralFeature.isStatic */ virtual bool not_static(Any diagnostics,std::map < Any, Any > context) = 0; /*! The structuralFeature must either be an owned or inherited feature of the type of the object InputPin, or it must be an owned end of a binary Association whose opposite end had as a type to which the type of the object InputPin conforms. object.type.oclAsType(Classifier).allFeatures()->includes(structuralFeature) or object.type.conformsTo(structuralFeature.oclAsType(Property).opposite.type) */ virtual bool object_type(Any diagnostics,std::map < Any, Any > context) = 0; /*! The structuralFeature must have exactly one featuringClassifier. structuralFeature.featuringClassifier->size() = 1 */ virtual bool one_featuring_classifier(Any diagnostics,std::map < Any, Any > context) = 0; /*! The visibility of the structuralFeature must allow access from the object performing the ReadStructuralFeatureAction. structuralFeature.visibility = VisibilityKind::public or _'context'.allFeatures()->includes(structuralFeature) or structuralFeature.visibility=VisibilityKind::protected and _'context'.conformsTo(structuralFeature.oclAsType(Property).opposite.type.oclAsType(Classifier)) */ virtual bool visibility(Any diagnostics,std::map < Any, Any > context) = 0; //********************************* // Attributes Getter Setter //********************************* //********************************* // Reference //********************************* /*! The InputPin from which the object whose StructuralFeature is to be read or written is obtained. <p>From package UML::Actions.</p> */ virtual std::shared_ptr<uml::InputPin > getObject() const = 0; /*! The InputPin from which the object whose StructuralFeature is to be read or written is obtained. <p>From package UML::Actions.</p> */ virtual void setObject(std::shared_ptr<uml::InputPin> _object_object) = 0; /*! The StructuralFeature to be read or written. <p>From package UML::Actions.</p> */ virtual std::shared_ptr<uml::StructuralFeature > getStructuralFeature() const = 0; /*! The StructuralFeature to be read or written. <p>From package UML::Actions.</p> */ virtual void setStructuralFeature(std::shared_ptr<uml::StructuralFeature> _structuralFeature_structuralFeature) = 0; protected: //********************************* // Attribute Members //********************************* //********************************* // Reference Members //********************************* /*! The InputPin from which the object whose StructuralFeature is to be read or written is obtained. <p>From package UML::Actions.</p> */ std::shared_ptr<uml::InputPin > m_object; /*! The StructuralFeature to be read or written. <p>From package UML::Actions.</p> */ std::shared_ptr<uml::StructuralFeature > m_structuralFeature; public: //********************************* // Union Getter //********************************* /*! ActivityGroups containing the ActivityNode. <p>From package UML::Activities.</p> */ virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const = 0;/*! The ordered set of InputPins representing the inputs to the Action. <p>From package UML::Actions.</p> */ virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const = 0;/*! The Elements owned by this Element. <p>From package UML::CommonStructure.</p> */ virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;/*! The Element that owns this Element. <p>From package UML::CommonStructure.</p> */ virtual std::weak_ptr<uml::Element > getOwner() const = 0;/*! The RedefinableElement that is being redefined by this element. <p>From package UML::Classification.</p> */ virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const = 0; virtual std::shared_ptr<ecore::EObject> eContainer() const = 0; //********************************* // Persistence Functions //********************************* virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0; virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) = 0; virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0; }; } #endif /* end of include guard: UML_STRUCTURALFEATUREACTION_HPP */
25.283217
241
0.641958
dataliz9r
1b7b9f1cec1989838303cc66ce439547ab85be90
1,263
cpp
C++
tests/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp
zlc18/LocalJudge
e8b141d2e80087d447a45cce36bac27b4ddb9cd1
[ "MIT" ]
null
null
null
tests/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp
zlc18/LocalJudge
e8b141d2e80087d447a45cce36bac27b4ddb9cd1
[ "MIT" ]
null
null
null
tests/cpp/productOfArrayExceptSelf/ProductOfArrayExceptSelf.cpp
zlc18/LocalJudge
e8b141d2e80087d447a45cce36bac27b4ddb9cd1
[ "MIT" ]
null
null
null
// Source : https://leetcode.com/problems/product-of-array-except-self/ // Author : Hao Chen // Date : 2015-07-17 /********************************************************************************** * * Given an array of n integers where n > 1, nums, return an array output such that * output[i] is equal to the product of all the elements of nums except nums[i]. * * Solve it without division and in O(n). * * For example, given [1,2,3,4], return [24,12,8,6]. * * Follow up: * Could you solve it with constant space complexity? (Note: The output array does not * count as extra space for the purpose of space complexity analysis.) * **********************************************************************************/ class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int len = nums.size(); vector<int> result(len, 1); //from the left to right for (int i=1; i<len; i++) { result[i] = result[i-1]*nums[i-1]; } //from the right to left int factorial = 1; for (int i=len-2; i>=0; i--){ factorial *= nums[i+1]; result[i] *= factorial; } return result; } };
29.372093
87
0.490895
zlc18
1b7c46559fd305323b46041721f565ffccd092a4
885
cpp
C++
src/musl/futex.cpp
paulyc/IncludeOS
5c82bad4a22838bc2219fbadef57d94f006b4760
[ "Apache-2.0" ]
5
2016-10-01T11:50:51.000Z
2019-10-24T12:54:36.000Z
src/musl/futex.cpp
paulyc/IncludeOS
5c82bad4a22838bc2219fbadef57d94f006b4760
[ "Apache-2.0" ]
1
2019-03-07T13:31:20.000Z
2019-03-07T13:37:49.000Z
src/musl/futex.cpp
AndreasAakesson/IncludeOS
891b960a0a7473c08cd0d93a2bba7569c6d88b48
[ "Apache-2.0" ]
3
2016-09-28T18:15:50.000Z
2017-07-18T17:02:25.000Z
#include "stub.hpp" #include <errno.h> #include <kprint> #define FUTEX_WAIT 0 #define FUTEX_WAKE 1 #define FUTEX_FD 2 #define FUTEX_REQUEUE 3 #define FUTEX_CMP_REQUEUE 4 #define FUTEX_WAKE_OP 5 #define FUTEX_LOCK_PI 6 #define FUTEX_UNLOCK_PI 7 #define FUTEX_TRYLOCK_PI 8 #define FUTEX_WAIT_BITSET 9 #define FUTEX_PRIVATE 128 #define FUTEX_CLOCK_REALTIME 256 extern void print_backtrace(); static int sys_futex(int *uaddr, int /*futex_op*/, int val, const struct timespec *timeout, int /*val3*/) { if (*uaddr != val){ return EAGAIN; } else { *uaddr = 0; } if (timeout == nullptr){ kprintf("No timeout\n"); } return 0; } extern "C" int syscall_SYS_futex(int *uaddr, int futex_op, int val, const struct timespec *timeout, int val3) { return stubtrace(sys_futex, "futex", uaddr, futex_op, val, timeout, val3); }
20.581395
76
0.685876
paulyc
1b7d22df872ed883508b237b1561b43faf6a288a
18,461
cpp
C++
RescueMyDoggo/Classes/Enemy.cpp
furryicedragon/VTCA_F03
c29f5ecbe461461c5ed769b7732afde8d509c117
[ "MIT" ]
null
null
null
RescueMyDoggo/Classes/Enemy.cpp
furryicedragon/VTCA_F03
c29f5ecbe461461c5ed769b7732afde8d509c117
[ "MIT" ]
null
null
null
RescueMyDoggo/Classes/Enemy.cpp
furryicedragon/VTCA_F03
c29f5ecbe461461c5ed769b7732afde8d509c117
[ "MIT" ]
null
null
null
#include"Enemy.h" USING_NS_CC; using namespace std; int hitSound = experimental::AudioEngine::play2d("sounds/hit.mp3", false, 0); Enemy* Enemy::create(int xMapNumber, int xWaveNumber, int xBossNumber) { Enemy* pSprite = new Enemy(); pSprite->eeeFrames = SpriteFrameCache::getInstance(); if (pSprite && pSprite->initWithSpriteFrame(pSprite->eeeFrames->getSpriteFrameByName (std::to_string(xMapNumber) + std::to_string(xWaveNumber) + std::to_string(xBossNumber) + "0_idle0.png"))) { pSprite->autorelease(); pSprite->mapNumber = xMapNumber; pSprite->waveNumber = xWaveNumber; pSprite->bossNumber = xBossNumber; pSprite->isSpawned = false; return pSprite; } CC_SAFE_DELETE(pSprite); return nullptr; } void Enemy::initOption() { this->direction = 0; this->canDrop = false; this->canChase = true; this->canRespawn = true; this->getHitTime = 0; this->inviTime = 1.8; if (this->bossNumber == 1) inviTime = 6; if (this->bossNumber == 2) inviTime = 8; if (this->bossNumber == 3) inviTime = 10; this->isDead = false; this->getLastFrameNumberOf("attack"); this->getLastFrameNumberOf("projectile"); spell = Sprite::create(); //spell->setAnchorPoint(Vec2(0.5, 0)); //if (this->waveNumber == 2 && this->mapNumber == 1) spell->setAnchorPoint(Vec2(0, 0)); spellLanded = Sprite::create(); spellLanded->setAnchorPoint(Vec2(0.5f, 0.3f)); spellLanded->setScale(2); spell->setScale(2); this->isOnCD = false; this->isAttacking = false; this->isMoving = false; this->canDamage = false; this->canSpawn = true; attackHelper = Sprite::create(); if(attackHelper) this->addChild(attackHelper); movementHelper = Sprite::create(); if(movementHelper) this->addChild(movementHelper); this->hp->setVisible(false); this->idleStatus(); this->scheduleUpdate(); } void Enemy::setHP(int HP) { if (hp == nullptr) { hp = Label::create(); hp->setAnchorPoint(Vec2(0.5, 0)); hp->setPosition(this->getPosition().x + (this->getContentSize().width / 2), this->getPosition().y + this->getContentSize().height); hp->setColor(Color3B(255, 0, 0)); //hp->setColor(Color4B::RED); hp->setSystemFontSize(16); this->hpBar = false; } hp->setString(std::to_string(HP)); if (!hpBar && hp) { this->addChild(hp, 1); this->hpBar = true; } } void Enemy::getLastFrameNumberOf(std::string actionName) { for (int i = 0; i < 99; i++) { auto frameName = std::to_string(mapNumber) + std::to_string(waveNumber) + std::to_string(bossNumber) +std::to_string(this->direction) +"_" + actionName + std::to_string(i) + ".png"; SpriteFrame* test = eeeFrames->getSpriteFrameByName(frameName); if (!test) { if (actionName == "attack") useSkillLastFN = i; if (actionName == "projectile") skillLastFN = i; break; } } } void Enemy::idleStatus() { if (!this->isIdle &&( !this->isDead || this->canRespawn)) { this->stopAllActionsByTag(1); this->stopAllActionsByTag(3); //auto idleState = RepeatForever::create(animation("Idle", 0.12f)); auto idleState = RepeatForever::create(makeAnimation("idle", 0.12f)); idleState->setTag(1); this->runAction(idleState); this->isIdle = true; this->canMove = true; this->canChase = true; } } void Enemy::movingAnimation() { if (this->mapNumber == 2 && this->waveNumber == 1) { //what does the tree do? } else if (this->canMove) { this->stopAllActionsByTag(1); this->stopAllActionsByTag(3); //auto anim = RepeatForever::create(animation("Moving", 0.12f)); auto anim = RepeatForever::create(makeAnimation("moving", 0.12f)); anim->setTag(3); this->runAction(anim); this->isMoving = true; canMove = false; } } void Enemy::chasing() { float howFar = std::fabsf(ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2)); if (this->canChase && !this->isMoving && !this->isAttacking &&this->isChasing && howFar>skillRange-69) { float pppX = ppp->getPosition().x; this->canChase = false; this->isIdle = false; this->isMoving = true; this->breakTime = false; float moveByX = pppX - (this->getPosition().x + this->getContentSize().width / 2); if (moveByX < 0) this->direction = 0; else this->direction = 1; this->movingAnimation(); this->stopAllActionsByTag(4); if (this->mapNumber == 2 && this->waveNumber == 1) { //what a tree should do } else { auto move2 = Sequence::create(DelayTime::create(std::fabsf(moveByX)/moveSpeed), CallFunc::create([=]() {this->breakTime = false; this->canMove = true; this->canChase = true; this->isMoving = false; if (std::fabsf(ppp->getPosition().x - this->getPosition().x) > visionRange + 100) this->isChasing = false; this->idleStatus(); }), nullptr); //could need some fix?! nah move2->setTag(4); this->runAction(move2); } } } void Enemy::randomMoving() { this->isMoving = true; if((this->waveNumber==1 || this->bossNumber==1) && (this->mapNumber != 2 || (this->mapNumber == 2 && this->bossNumber == 0))) randomX = RandomHelper::random_real(listLineX.at(0), listLineX.at(1)); //di chuyen trong 1 khoang giua line1 va line2 trong tiledMap if((this->waveNumber==2 || this->bossNumber==2) && (this->mapNumber!=2 || (this->mapNumber==2 && this->bossNumber==0))) randomX = RandomHelper::random_real(listLineX.at(2), listLineX.at(3)); if (this->mapNumber == 2 && this->bossNumber > 0) randomX = RandomHelper::random_real(listLineX.at(4), listLineX.at(5)); float eX = this->getPositionX(); float moveByX = randomX - eX; this->isIdle = false; this->stopAllActionsByTag(4); if (moveByX > 0) this->direction = 1; //done else { moveByX *= -1; this->direction = 0; } this->movingAnimation(); if (this->mapNumber == 2 && this->waveNumber == 1) { //wat a tree shoud do } else { auto seq = Sequence::create(DelayTime::create(moveByX/moveSpeed), CallFunc::create([=]() {this->isMoving = false; this->canMove = true; this->idleStatus(); }), DelayTime::create(RandomHelper::random_real(0.5f, 1.0f)), CallFunc::create([=]() { this->breakTime = false; }), nullptr); seq->setTag(4); this->runAction(seq); } } void Enemy::moving() { float howFar = std::fabsf(ppp->getPosition().x - this->getPosition().x); auto eeePosY = this->getPositionY() - 43; if (this->mapNumber == 3 && bossNumber != 1) { if (this->bossNumber == 2) eeePosY -= 69; else eeePosY -= 40; } if (howFar < skillRange && !this->isAttacking && !this->isOnCD && std::fabsf(ppp->getPosition().y - eeePosY) < 145 && (ppp->getPositionY() - eeePosY)>0 && ppp->getPositionX() > spotPlayerLineLeft && ppp->getPositionX()<spotPlayerLineRight) { this->attack(); } if (ppp->getPosition().y - eeePosY > 145 || ppp->getPositionX() < spotPlayerLineLeft || ppp->getPositionX() > spotPlayerLineRight) this->isChasing = false; if (howFar < visionRange && !this->isChasing && !this->isAttacking && std::fabsf(ppp->getPosition().y - eeePosY) < 145 && (ppp->getPositionY() - eeePosY)>0 && ppp->getPositionX() > spotPlayerLineLeft && ppp->getPositionX()<spotPlayerLineRight) { this->isChasing = true; } else { if (!this->isMoving && !this->isAttacking && !this->isChasing && !this->breakTime) { this->breakTime = true; this->randomMoving(); } else { this->chasing(); } } } void Enemy::attack() { if (this->isSpawned) { float howFar = ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2); if (howFar < skillRange) { if (howFar < 0) this->direction = 0; else this->direction = 1; //if (checkFrame("projectile")) // this->spell->setFlippedX(this->isFlippedX()); this->stopAllActions(); this->isIdle = false; this->isAttacking = true; this->isOnCD = true; this->isMoving = false; this->canMove = true; this->breakTime = false; //this->runAction(Sequence::create(animation("SkillUsing", castSpeed), this->runAction(Sequence::create(makeAnimation("attack", castSpeed), CallFunc::create([=]() {this->canDamage = false; this->isAttacking = false; this->idleStatus(); }), nullptr)); if (this->isCaster) { this->casterSpell(); } if (this->isSSMobility) { this->mobilitySS(); } if (!this->isCaster && !this->isSSMobility) { this->runAction(Sequence::create(DelayTime::create(castSpeed*norAtkDmgAfterF), CallFunc::create([=]() {this->canDamage = true; }), DelayTime::create(castSpeed*doneAtkAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr)); } this->attackHelper->runAction(Sequence::create(DelayTime::create(0.12*useSkillLastFN*skillCD), CallFunc::create([=]() {this->isOnCD = false; }), nullptr)); } } } void Enemy::casterSpell() { float range = 500.f; if (this->direction==0) range *= -1; float move2X = this->getPosition().x; float move2Y = this->getPositionY(); if (this->mapNumber == 2 && this->bossNumber == 2)move2Y -= 20; if (this->mapNumber == 1 && this->waveNumber == 1) move2Y += 10; if (this->direction==1) { move2X += this->getContentSize().width/2; } else move2X -= this->getContentSize().width / 2; if(this->waveNumber==2 && this->mapNumber == 1) this->spell->runAction(Sequence::create( MoveTo::create(0, Vec2(move2X, this->getPosition().y+this->getContentSize().height/2)), CallFunc::create([=]() {this->spell->setVisible(true); }), makeAnimation("projectile", castSpeed), CallFunc::create([=]() {this->spell->setVisible(false); this->attackLandedEffect(); }), nullptr)); if ((this->waveNumber == 1 && this->mapNumber == 1)||(this->mapNumber==2 && this->bossNumber==2)) { this->spell->runAction(RepeatForever::create(makeAnimation("projectile", castSpeed))); this->spell->runAction(Sequence::create( CallFunc::create([=]() {this->interuptable=true; }), DelayTime::create(castSpeed * skillAtkAfterF), CallFunc::create([=]() { this->interuptable = false; this->spell->setPosition(move2X, move2Y); this->spell->setVisible(true); }), MoveBy::create(0.69f, Vec2(range, 0)), CallFunc::create([=]() {this->spell->setVisible(false); this->spell->setPosition(0, 0); }), nullptr)); } if (this->mapNumber == 2 && this->bossNumber == 1) { this->spell->runAction(Sequence::create(CallFunc::create([=]() {this->interuptable = true; }), DelayTime::create(castSpeed * skillAtkAfterF), CallFunc::create([=]() { this->interuptable = false; this->spell->setPosition(ppp->getPositionX(), ppp->getPositionY() + 10); this->spell->setVisible(true); this->spell->runAction(Sequence::create(makeAnimation("projectile", castSpeed), CallFunc::create([=]() {this->spell->setVisible(false); }), nullptr)); }), DelayTime::create(castSpeed * 2), CallFunc::create([=]() {this->attackLandedEffect(); }),nullptr)); } //this->spell->runAction(RepeatForever::create(animation("Spell", castSpeed))); } void Enemy::mobilitySS() { this->mobilityUsing = true; this->invulnerable = true; this->movementHelper->stopActionByTag(123); float howFar = ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2); if (howFar < 0) howFar *= -1; if (this->bossNumber == 1 && this->mapNumber == 1) this->runAction(Sequence::create(DelayTime::create(castSpeed*(mobilitySSAt + 1)), JumpTo::create(castSpeed*mobilitySpeed, Vec2(ppp->getPosition().x - this->getContentSize().width / 2, this->getPosition().y), 72, 1), CallFunc::create([=]() {this->mobilityUsing = false; this->canDamage = true; this->invulnerable = false; }), DelayTime::create(castSpeed*mobilityDoneAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr)); else this->runAction(Sequence::create(DelayTime::create(castSpeed*(mobilitySSAt + 1)), MoveTo::create(castSpeed*mobilitySpeed, Vec2(ppp->getPosition().x - this->getContentSize().width / 2, this->getPosition().y)), CallFunc::create([=]() {this->mobilityUsing = false; this->canDamage = true; this->invulnerable = false; }), DelayTime::create(castSpeed*mobilityDoneAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr)); } void Enemy::attackLandedEffect() { if (this->checkFrame("impact")) { this->spellLanded->setPosition(Vec2(ppp->getPosition().x, ppp->getPosition().y)); this->spellLanded->runAction(Sequence::create( //CallFunc::create([=]() {this->canDamage = true; this->spellLanded->setVisible(true); }), animation("SkillLanded", 0.12f), CallFunc::create([=]() {this->canDamage = false; this->spellLanded->setVisible(false); this->spellLanded->setPosition(0, 0); }), nullptr)); CallFunc::create([=]() {this->canDamage = true; this->spellLanded->setVisible(true); }), makeAnimation("impact", 0.12f), CallFunc::create([=]() {this->canDamage = false; this->spellLanded->setVisible(false); this->spellLanded->setPosition(0, 0); }), nullptr)); } } void Enemy::getHit(int damage) { if (!this->isDead && this->isSpawned && !this->invulnerable) { /* if(this->mapNumber==1 || this->mapNumber==2) this->stopAllActions(); else */ this->forbidAllAction(); this->canChase = true; this->isIdle = false; this->isAttacking = false; this->isMoving = false; this->breakTime = false; this->getHitTime++; if (getHitTime == 3) { getHitTime = 0; this->invulnerable = true; auto doIt = Sequence::create(DelayTime::create(inviTime), CallFunc::create([=]() {this->invulnerable = false; }), nullptr); doIt->setTag(123); this->movementHelper->runAction(doIt); } SpriteFrame * hit = eeeFrames->getSpriteFrameByName(std::to_string(mapNumber) + std::to_string(waveNumber) + std::to_string(bossNumber) + std::to_string(this->direction) + "_hurt0.png"); if(hit) this->setSpriteFrame(hit); int x = -16; if (ppp->getPositionX() - 25 < this->getPositionX()) { x *= -1; this->direction = 0; } else this->direction = 1; this->runAction(MoveBy::create(0.33f,Vec2(x, 0))); int healthP = std::stoi(this->hp->getString()); healthP -= damage; if (healthP < 0 || healthP == 0) { this->hp->setString("0"); this->dead(); } else this->hp->setString(std::to_string(healthP)); if(!this->isDead) this->runAction(Sequence::create(DelayTime::create(0.3f), CallFunc::create([=]() { this->idleStatus(); }), DelayTime::create(0.4f), CallFunc::create([=]() {this->isMoving=false; this->canMove = true; this->breakTime = false; }), nullptr)); } } void Enemy::autoRespawn() { if (this->canRespawn && this->bossNumber==0) { float timeTillRespawn = RandomHelper::random_real(5.0f, 10.0f); //this->setVisible(true); //this->setOpacity(0); this->runAction( Sequence::create( DelayTime::create(timeTillRespawn), CallFunc::create([=]() {this->idleStatus(); }), FadeIn::create(1.0f), nullptr)); this->runAction( Sequence::create( DelayTime::create(timeTillRespawn + 1.0f), CallFunc::create([=]() { this->isDead = false; this->isSpawned = true; this->setHP(this->baseHP); this->canRespawn = false; }), nullptr)); } } void Enemy::dead() { if (this->waveNumber == 1) ppp->w1kills++; if (this->waveNumber == 2) ppp->w2kills++; this->isDead = true; this->isSpawned = false; this->canRespawn = true; this->canDrop = true; //this->stopAllActions(); this->forbidAllAction(); experimental::AudioEngine::play2d("sounds/monsterdie.mp3", false, 0.4f); if(this->checkFrame("die")) this->runAction(Sequence::create(makeAnimation("die", 0.12f), FadeOut::create(0), CallFunc::create([=]() {this->autoRespawn(); }), nullptr)); auto howFar = ppp->getPosition().x - this->getPosition().x; auto theX = 40.f; if (howFar > 0) theX *= -1; this->runAction(MoveBy::create(0.5, Vec2(theX, 0))); ppp->currentEXP += this->expReward; } void Enemy::forbidAllAction() { this->stopAllActions(); if ((this->mapNumber == 1 && this->waveNumber > 0)||this->interuptable) { this->spell->stopAllActions(); this->spell->setVisible(false); } } bool Enemy::checkFrame(std::string action) { action = "_" + action + "0.png"; //auto checkSprite = Sprite::create(combination +"/"+ action); auto checkSprite = eeeFrames->getSpriteFrameByName (std::to_string(this->mapNumber) + std::to_string(this->waveNumber) + std::to_string(this->bossNumber) + std::to_string(this->direction) + action); if (checkSprite) return true; else return false; } void Enemy::update(float elapsed) { if(!this->isDead && this->isSpawned) moving(); if (this->isChasing && !this->canChase && !this->isAttacking) { if (this->direction==0 && ppp->getPositionX() > this->getPositionX()+this->getContentSize().width) { this->stopAllActionsByTag(3); this->stopAllActionsByTag(4); if(!this->mobilityUsing) this->direction = 1; this->canChase = true; this->isMoving = false; this->idleStatus(); } else if (this->direction==1 && ppp->getPositionX() < this->getPositionX() - this->getContentSize().width) { this->stopAllActionsByTag(3); this->stopAllActionsByTag(4); if(!this->mobilityUsing) this->direction = 0; this->canChase = true; this->isMoving = false; this->idleStatus(); } } if (this->isMoving && (this->mapNumber!=2 || (this->mapNumber==2 && this->waveNumber!=1))) { this->setPositionX(this->getPositionX() + ( this->direction ? (moveSpeed * elapsed) : - (moveSpeed * elapsed) ) ); } } Animate* Enemy::makeAnimation(std::string actionName, float timeEachFrame) { std::string key = std::to_string(this->mapNumber) + std::to_string(this->waveNumber) + std::to_string(this->bossNumber) + std::to_string(this->direction) + "_" + actionName; Animate* anim = listAnimations.at(key); if (anim == nullptr) { Vector<SpriteFrame*> runningFrames; for (int i = 0; i < 99; i++) { auto frameName = key + std::to_string(i) + ".png"; SpriteFrame* frame = eeeFrames->getSpriteFrameByName(frameName); if (!frame) break; runningFrames.pushBack(frame); } Animation* runningAnimation = Animation::createWithSpriteFrames(runningFrames, timeEachFrame); anim = Animate::create(runningAnimation); listAnimations.insert(key, anim); } return anim; }
35.638996
361
0.644981
furryicedragon
1b7f2b4d2e606144b9ad14f3ff944ee3d1e5ba62
7,444
hpp
C++
examples/include/stereo.hpp
Russ76/zed-open-capture
969d153c75badb97c12fa9a70056eabc4317bdfa
[ "MIT" ]
null
null
null
examples/include/stereo.hpp
Russ76/zed-open-capture
969d153c75badb97c12fa9a70056eabc4317bdfa
[ "MIT" ]
null
null
null
examples/include/stereo.hpp
Russ76/zed-open-capture
969d153c75badb97c12fa9a70056eabc4317bdfa
[ "MIT" ]
null
null
null
#ifndef STEREO_HPP #define STEREO_HPP #include <iostream> #include <opencv2/opencv.hpp> #include "calibration.hpp" namespace sl_oc { namespace tools { /*! * \brief STEREO_PAR_FILENAME default stereo parameter configuration file */ const std::string STEREO_PAR_FILENAME = "zed_oc_stereo.yaml"; /*! * \brief The StereoSgbmPar class is used to store/retrieve the stereo matching parameters */ class StereoSgbmPar { public: /*! * \brief Default constructor */ StereoSgbmPar() { setDefaultValues(); } /*! * \brief load stereo matching parameters * \return true if a configuration file exists */ bool load(); /*! * \brief save stereo matching parameters * \return true if a configuration file has been correctly created */ bool save(); /*! * \brief set default stereo matching parameters */ void setDefaultValues(); /*! * \brief print the current stereo matching parameters on standard output */ void print(); public: int blockSize; //!< [default: 3] Matched block size. It must be an odd number >=1 . Normally, it should be somewhere in the 3..11 range. int minDisparity; //!< [default: 0] Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. int numDisparities; //!< [default: 96] Maximum disparity minus minimum disparity. The value is always greater than zero. In the current implementation, this parameter must be divisible by 16. int mode; //!< Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming algorithm. It will consume O(W*H*numDisparities) bytes, which is large for 640x480 stereo and huge for HD-size pictures. By default, it is set to `cv::StereoSGBM::MODE_SGBM_3WAY`. int P1; //!< [default: 24*blockSize*blockSize] The first parameter controlling the disparity smoothness. See below. int P2; //!< [default: 4*PI]The second parameter controlling the disparity smoothness. The larger the values are, the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor pixels. The algorithm requires P2 > P1 . See stereo_match.cpp sample where some reasonably good P1 and P2 values are shown (like 8*number_of_image_channels*blockSize*blockSize and 32*number_of_image_channels*blockSize*blockSize , respectively). int disp12MaxDiff; //!< [default: 96] Maximum allowed difference (in integer pixel units) in the left-right disparity check. Set it to a non-positive value to disable the check. int preFilterCap; //!< [default: 63] Truncation value for the prefiltered image pixels. The algorithm first computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. The result values are passed to the Birchfield-Tomasi pixel cost function. int uniquenessRatio; //!< [default: 5] Margin in percentage by which the best (minimum) computed cost function value should "win" the second best value to consider the found match correct. Normally, a value within the 5-15 range is good enough. int speckleWindowSize; //!< [default: 255] Maximum size of smooth disparity regions to consider their noise speckles and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the 50-200 range. int speckleRange; //!< [default: 1] Maximum disparity variation within each connected component. If you do speckle filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. Normally, 1 or 2 is good enough. float minDepth_mm; //!< [default: 300] Minimum value of depth for the extracted depth map float maxDepth_mm; //!< [default: 10000] Maximum value of depth for the extracted depth map }; void StereoSgbmPar::setDefaultValues() { blockSize = 3; minDisparity = 0; numDisparities = 96; mode = cv::StereoSGBM::MODE_SGBM_3WAY; // MODE_SGBM = 0, MODE_HH = 1, MODE_SGBM_3WAY = 2, MODE_HH4 = 3 P1 = 24*blockSize*blockSize; P2 = 4*P1; disp12MaxDiff = 96; preFilterCap = 63; uniquenessRatio = 5; speckleWindowSize = 255; speckleRange = 1; minDepth_mm = 300.f; maxDepth_mm = 10000.f; } bool StereoSgbmPar::load() { std::string path = getHiddenDir(); std::string par_file = path + STEREO_PAR_FILENAME; cv::FileStorage fs; if(!fs.open(par_file, cv::FileStorage::READ)) { std::cerr << "Error opening stereo parameters file. Using default values." << std::endl << std::endl; setDefaultValues(); return false; } fs["blockSize"] >> blockSize; fs["minDisparity"] >> minDisparity; fs["numDisparities"] >> numDisparities; fs["mode"] >> mode; fs["disp12MaxDiff"] >> disp12MaxDiff; fs["preFilterCap"] >> preFilterCap; fs["uniquenessRatio"] >> uniquenessRatio; fs["speckleWindowSize"] >> speckleWindowSize; fs["speckleRange"] >> speckleRange; P1 = 24*blockSize*blockSize; P2 = 96*blockSize*blockSize; fs["minDepth_mm"] >> minDepth_mm; fs["maxDepth_mm"] >> maxDepth_mm; std::cout << "Stereo parameters load done: " << par_file << std::endl << std::endl; return true; } bool StereoSgbmPar::save() { std::string path = getHiddenDir(); std::string par_file = path + STEREO_PAR_FILENAME; cv::FileStorage fs; if(!fs.open(par_file, cv::FileStorage::WRITE)) { std::cerr << "Error saving stereo parameters. Cannot open file for writing: " << par_file << std::endl << std::endl; return false; } fs << "blockSize" << blockSize; fs << "minDisparity" << minDisparity; fs << "numDisparities" << numDisparities; fs << "mode" << mode; fs << "disp12MaxDiff" << disp12MaxDiff; fs << "preFilterCap" << preFilterCap; fs << "uniquenessRatio" << uniquenessRatio; fs << "speckleWindowSize" << speckleWindowSize; fs << "speckleRange" << speckleRange; fs << "minDepth_mm" << minDepth_mm; fs << "maxDepth_mm" << maxDepth_mm; std::cout << "Stereo parameters write done: " << par_file << std::endl << std::endl; return true; } void StereoSgbmPar::print() { std::cout << "Stereo SGBM parameters:" << std::endl; std::cout << "------------------------------------------" << std::endl; std::cout << "blockSize:\t\t" << blockSize << std::endl; std::cout << "minDisparity:\t" << minDisparity << std::endl; std::cout << "numDisparities:\t" << numDisparities << std::endl; std::cout << "mode:\t\t" << mode << std::endl; std::cout << "disp12MaxDiff:\t" << disp12MaxDiff << std::endl; std::cout << "preFilterCap:\t" << preFilterCap << std::endl; std::cout << "uniquenessRatio:\t" << uniquenessRatio << std::endl; std::cout << "speckleWindowSize:\t" << speckleWindowSize << std::endl; std::cout << "speckleRange:\t" << speckleRange << std::endl; std::cout << "P1:\t\t" << P1 << " [Calculated]" << std::endl; std::cout << "P2:\t\t" << P2 << " [Calculated]" << std::endl; std::cout << "minDepth_mm:\t" << minDepth_mm << std::endl; std::cout << "maxDepth_mm:\t" << maxDepth_mm << std::endl; std::cout << "------------------------------------------" << std::endl << std::endl; } } // namespace tools } // namespace sl_oc #endif // STEREO_HPP
42.295455
553
0.670607
Russ76
1b80f9ca0c4ee7562f726b58763a219ee9416e3a
20,225
cc
C++
google/cloud/storage/internal/grpc_object_request_parser.cc
LaudateCorpus1/google-cloud-cpp
a9575c5af5e3938efc71bf5822e79b73027d1f3b
[ "Apache-2.0" ]
null
null
null
google/cloud/storage/internal/grpc_object_request_parser.cc
LaudateCorpus1/google-cloud-cpp
a9575c5af5e3938efc71bf5822e79b73027d1f3b
[ "Apache-2.0" ]
null
null
null
google/cloud/storage/internal/grpc_object_request_parser.cc
LaudateCorpus1/google-cloud-cpp
a9575c5af5e3938efc71bf5822e79b73027d1f3b
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/grpc_object_request_parser.h" #include "google/cloud/storage/internal/grpc_common_request_params.h" #include "google/cloud/storage/internal/grpc_object_access_control_parser.h" #include "google/cloud/storage/internal/grpc_object_metadata_parser.h" #include "google/cloud/storage/internal/openssl_util.h" #include "google/cloud/internal/invoke_result.h" #include "google/cloud/internal/time_utils.h" #include "google/cloud/log.h" #include <crc32c/crc32c.h> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { template <typename GrpcRequest, typename StorageRequest> Status SetCommonObjectParameters(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<EncryptionKey>()) { auto data = req.template GetOption<EncryptionKey>().value(); auto key_bytes = Base64Decode(data.key); if (!key_bytes) return std::move(key_bytes).status(); auto key_sha256_bytes = Base64Decode(data.sha256); if (!key_sha256_bytes) return std::move(key_sha256_bytes).status(); request.mutable_common_object_request_params()->set_encryption_algorithm( std::move(data.algorithm)); request.mutable_common_object_request_params()->set_encryption_key_bytes( std::string{key_bytes->begin(), key_bytes->end()}); request.mutable_common_object_request_params() ->set_encryption_key_sha256_bytes( std::string{key_sha256_bytes->begin(), key_sha256_bytes->end()}); } return Status{}; } template <typename GrpcRequest> struct GetPredefinedAcl { auto operator()(GrpcRequest const& q) -> decltype(q.predefined_acl()); }; template < typename GrpcRequest, typename StorageRequest, typename std::enable_if< std::is_same<google::storage::v2::PredefinedObjectAcl, google::cloud::internal::invoke_result_t< GetPredefinedAcl<GrpcRequest>, GrpcRequest>>::value, int>::type = 0> void SetPredefinedAcl(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<PredefinedAcl>()) { request.set_predefined_acl(GrpcObjectRequestParser::ToProtoObject( req.template GetOption<PredefinedAcl>())); } } template <typename GrpcRequest, typename StorageRequest> void SetPredefinedDefaultObjectAcl(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<PredefinedDefaultObjectAcl>()) { request.set_predefined_default_object_acl( ToProto(req.template GetOption<PredefinedDefaultObjectAcl>())); } } template <typename GrpcRequest, typename StorageRequest> void SetMetagenerationConditions(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<IfMetagenerationMatch>()) { request.set_if_metageneration_match( req.template GetOption<IfMetagenerationMatch>().value()); } if (req.template HasOption<IfMetagenerationNotMatch>()) { request.set_if_metageneration_not_match( req.template GetOption<IfMetagenerationNotMatch>().value()); } } template <typename GrpcRequest, typename StorageRequest> void SetGenerationConditions(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<IfGenerationMatch>()) { request.set_if_generation_match( req.template GetOption<IfGenerationMatch>().value()); } if (req.template HasOption<IfGenerationNotMatch>()) { request.set_if_generation_not_match( req.template GetOption<IfGenerationNotMatch>().value()); } } template <typename StorageRequest> void SetResourceOptions(google::storage::v2::Object& resource, StorageRequest const& request) { if (request.template HasOption<ContentEncoding>()) { resource.set_content_encoding( request.template GetOption<ContentEncoding>().value()); } if (request.template HasOption<ContentType>()) { resource.set_content_type( request.template GetOption<ContentType>().value()); } if (request.template HasOption<KmsKeyName>()) { resource.set_kms_key(request.template GetOption<KmsKeyName>().value()); } } template <typename StorageRequest> Status SetObjectMetadata(google::storage::v2::Object& resource, StorageRequest const& req) { if (!req.template HasOption<WithObjectMetadata>()) { return Status{}; } auto metadata = req.template GetOption<WithObjectMetadata>().value(); if (!metadata.content_encoding().empty()) { resource.set_content_encoding(metadata.content_encoding()); } if (!metadata.content_disposition().empty()) { resource.set_content_disposition(metadata.content_disposition()); } if (!metadata.cache_control().empty()) { resource.set_cache_control(metadata.cache_control()); } for (auto const& acl : metadata.acl()) { *resource.add_acl() = GrpcObjectAccessControlParser::ToProto(acl); } if (!metadata.content_language().empty()) { resource.set_content_language(metadata.content_language()); } if (!metadata.content_type().empty()) { resource.set_content_type(metadata.content_type()); } if (metadata.event_based_hold()) { resource.set_event_based_hold(metadata.event_based_hold()); } for (auto const& kv : metadata.metadata()) { (*resource.mutable_metadata())[kv.first] = kv.second; } if (!metadata.storage_class().empty()) { resource.set_storage_class(metadata.storage_class()); } resource.set_temporary_hold(metadata.temporary_hold()); if (metadata.has_customer_encryption()) { auto encryption = GrpcObjectMetadataParser::ToProto(metadata.customer_encryption()); if (!encryption) return std::move(encryption).status(); *resource.mutable_customer_encryption() = *std::move(encryption); } return Status{}; } google::storage::v2::PredefinedObjectAcl ToProtoObjectAcl( std::string const& value) { if (value == PredefinedAcl::BucketOwnerFullControl().value()) { return google::storage::v2::OBJECT_ACL_BUCKET_OWNER_FULL_CONTROL; } if (value == PredefinedAcl::BucketOwnerRead().value()) { return google::storage::v2::OBJECT_ACL_BUCKET_OWNER_READ; } if (value == PredefinedAcl::AuthenticatedRead().value()) { return google::storage::v2::OBJECT_ACL_AUTHENTICATED_READ; } if (value == PredefinedAcl::Private().value()) { return google::storage::v2::OBJECT_ACL_PRIVATE; } if (value == PredefinedAcl::ProjectPrivate().value()) { return google::storage::v2::OBJECT_ACL_PROJECT_PRIVATE; } if (value == PredefinedAcl::PublicRead().value()) { return google::storage::v2::OBJECT_ACL_PUBLIC_READ; } if (value == PredefinedAcl::PublicReadWrite().value()) { GCP_LOG(ERROR) << "Invalid predefinedAcl value " << value; return google::storage::v2::PREDEFINED_OBJECT_ACL_UNSPECIFIED; } GCP_LOG(ERROR) << "Unknown predefinedAcl value " << value; return google::storage::v2::PREDEFINED_OBJECT_ACL_UNSPECIFIED; } } // namespace google::storage::v2::PredefinedObjectAcl GrpcObjectRequestParser::ToProtoObject( PredefinedAcl const& acl) { return ToProtoObjectAcl(acl.value()); } google::storage::v2::PredefinedObjectAcl GrpcObjectRequestParser::ToProtoObject( DestinationPredefinedAcl const& acl) { return ToProtoObjectAcl(acl.value()); } google::storage::v2::DeleteObjectRequest GrpcObjectRequestParser::ToProto( DeleteObjectRequest const& request) { google::storage::v2::DeleteObjectRequest result; SetGenerationConditions(result, request); SetMetagenerationConditions(result, request); SetCommonParameters(result, request); result.set_bucket("projects/_/buckets/" + request.bucket_name()); result.set_object(request.object_name()); result.set_generation(request.GetOption<Generation>().value_or(0)); return result; } google::storage::v2::GetObjectRequest GrpcObjectRequestParser::ToProto( GetObjectMetadataRequest const& request) { google::storage::v2::GetObjectRequest result; SetGenerationConditions(result, request); SetMetagenerationConditions(result, request); SetCommonParameters(result, request); result.set_bucket("projects/_/buckets/" + request.bucket_name()); result.set_object(request.object_name()); result.set_generation(request.GetOption<Generation>().value_or(0)); auto projection = request.GetOption<Projection>().value_or(""); if (projection == "full") result.mutable_read_mask()->add_paths("*"); return result; } StatusOr<google::storage::v2::ReadObjectRequest> GrpcObjectRequestParser::ToProto(ReadObjectRangeRequest const& request) { google::storage::v2::ReadObjectRequest r; auto status = SetCommonObjectParameters(r, request); if (!status.ok()) return status; r.set_object(request.object_name()); r.set_bucket("projects/_/buckets/" + request.bucket_name()); if (request.HasOption<Generation>()) { r.set_generation(request.GetOption<Generation>().value()); } if (request.HasOption<ReadRange>()) { auto const range = request.GetOption<ReadRange>().value(); r.set_read_offset(range.begin); r.set_read_limit(range.end - range.begin); } if (request.HasOption<ReadLast>()) { auto const offset = request.GetOption<ReadLast>().value(); r.set_read_offset(-offset); } if (request.HasOption<ReadFromOffset>()) { auto const offset = request.GetOption<ReadFromOffset>().value(); if (offset > r.read_offset()) { if (r.read_limit() > 0) { r.set_read_limit(offset - r.read_offset()); } r.set_read_offset(offset); } } SetGenerationConditions(r, request); SetMetagenerationConditions(r, request); SetCommonParameters(r, request); return r; } StatusOr<google::storage::v2::WriteObjectRequest> GrpcObjectRequestParser::ToProto(InsertObjectMediaRequest const& request) { google::storage::v2::WriteObjectRequest r; auto& object_spec = *r.mutable_write_object_spec(); auto& resource = *object_spec.mutable_resource(); SetResourceOptions(resource, request); auto status = SetObjectMetadata(resource, request); if (!status.ok()) return status; SetPredefinedAcl(object_spec, request); SetGenerationConditions(object_spec, request); SetMetagenerationConditions(object_spec, request); status = SetCommonObjectParameters(r, request); if (!status.ok()) return status; SetCommonParameters(r, request); resource.set_bucket("projects/_/buckets/" + request.bucket_name()); resource.set_name(request.object_name()); r.set_write_offset(0); auto& checksums = *r.mutable_object_checksums(); if (request.HasOption<Crc32cChecksumValue>()) { // The client library accepts CRC32C checksums in the format required by the // REST APIs (base64-encoded big-endian, 32-bit integers). We need to // convert this to the format expected by proto, which is just a 32-bit // integer. But the value received by the application might be incorrect, so // we need to validate it. auto as_proto = GrpcObjectMetadataParser::Crc32cToProto( request.GetOption<Crc32cChecksumValue>().value()); if (!as_proto.ok()) return std::move(as_proto).status(); checksums.set_crc32c(*as_proto); } else if (request.GetOption<DisableCrc32cChecksum>().value_or(false)) { // Nothing to do, the option is disabled (mostly useful in tests). } else { checksums.set_crc32c(crc32c::Crc32c(request.contents())); } if (request.HasOption<MD5HashValue>()) { auto as_proto = GrpcObjectMetadataParser::MD5ToProto( request.GetOption<MD5HashValue>().value()); if (!as_proto.ok()) return std::move(as_proto).status(); checksums.set_md5_hash(*std::move(as_proto)); } else if (request.GetOption<DisableMD5Hash>().value_or(false)) { // Nothing to do, the option is disabled. } else { checksums.set_md5_hash( GrpcObjectMetadataParser::ComputeMD5Hash(request.contents())); } return r; } ResumableUploadResponse GrpcObjectRequestParser::FromProto( google::storage::v2::WriteObjectResponse const& p, Options const& options) { ResumableUploadResponse response; response.upload_state = ResumableUploadResponse::kInProgress; if (p.has_persisted_size()) { response.committed_size = static_cast<std::uint64_t>(p.persisted_size()); } if (p.has_resource()) { response.payload = GrpcObjectMetadataParser::FromProto(p.resource(), options); response.upload_state = ResumableUploadResponse::kDone; } return response; } google::storage::v2::ListObjectsRequest GrpcObjectRequestParser::ToProto( ListObjectsRequest const& request) { google::storage::v2::ListObjectsRequest result; result.set_parent("projects/_/buckets/" + request.bucket_name()); auto const page_size = request.GetOption<MaxResults>().value_or(0); // Clamp out of range values. The service will clamp to its own range // ([0, 1000] as of this writing) anyway. if (page_size < 0) { result.set_page_size(0); } else if (page_size < std::numeric_limits<std::int32_t>::max()) { result.set_page_size(static_cast<std::int32_t>(page_size)); } else { result.set_page_size(std::numeric_limits<std::int32_t>::max()); } result.set_page_token(request.page_token()); result.set_delimiter(request.GetOption<Delimiter>().value_or("")); result.set_include_trailing_delimiter( request.GetOption<IncludeTrailingDelimiter>().value_or(false)); result.set_prefix(request.GetOption<Prefix>().value_or("")); result.set_versions(request.GetOption<Versions>().value_or("")); result.set_lexicographic_start(request.GetOption<StartOffset>().value_or("")); result.set_lexicographic_end(request.GetOption<EndOffset>().value_or("")); SetCommonParameters(result, request); return result; } ListObjectsResponse GrpcObjectRequestParser::FromProto( google::storage::v2::ListObjectsResponse const& response, Options const& options) { ListObjectsResponse result; result.next_page_token = response.next_page_token(); for (auto const& o : response.objects()) { result.items.push_back(GrpcObjectMetadataParser::FromProto(o, options)); } for (auto const& p : response.prefixes()) result.prefixes.push_back(p); return result; } StatusOr<google::storage::v2::RewriteObjectRequest> GrpcObjectRequestParser::ToProto(RewriteObjectRequest const& request) { google::storage::v2::RewriteObjectRequest result; SetCommonParameters(result, request); auto status = SetCommonObjectParameters(result, request); if (!status.ok()) return status; auto& destination = *result.mutable_destination(); destination.set_name(request.destination_object()); destination.set_bucket("projects/_/buckets/" + request.destination_bucket()); destination.set_kms_key( request.GetOption<DestinationKmsKeyName>().value_or("")); if (request.HasOption<WithObjectMetadata>()) { // Only a few fields can be set as part of the metadata request. auto m = request.GetOption<WithObjectMetadata>().value(); destination.set_storage_class(m.storage_class()); destination.set_content_encoding(m.content_encoding()); destination.set_content_disposition(m.content_disposition()); destination.set_cache_control(m.cache_control()); destination.set_content_language(m.content_language()); destination.set_content_type(m.content_type()); destination.set_temporary_hold(m.temporary_hold()); for (auto const& kv : m.metadata()) { (*destination.mutable_metadata())[kv.first] = kv.second; } if (m.event_based_hold()) { // The proto is an optional<bool>, avoid setting it to `false`, seems // confusing. destination.set_event_based_hold(m.event_based_hold()); } if (m.has_custom_time()) { *destination.mutable_custom_time() = google::cloud::internal::ToProtoTimestamp(m.custom_time()); } } result.set_source_bucket("projects/_/buckets/" + request.source_bucket()); result.set_source_object(request.source_object()); result.set_source_generation( request.GetOption<SourceGeneration>().value_or(0)); result.set_rewrite_token(request.rewrite_token()); if (request.HasOption<DestinationPredefinedAcl>()) { result.set_destination_predefined_acl( ToProtoObject(request.GetOption<DestinationPredefinedAcl>())); } SetGenerationConditions(result, request); SetMetagenerationConditions(result, request); if (request.HasOption<IfSourceGenerationMatch>()) { result.set_if_source_generation_match( request.GetOption<IfSourceGenerationMatch>().value()); } if (request.HasOption<IfSourceGenerationNotMatch>()) { result.set_if_source_generation_not_match( request.GetOption<IfSourceGenerationNotMatch>().value()); } if (request.HasOption<IfSourceMetagenerationMatch>()) { result.set_if_source_metageneration_match( request.GetOption<IfSourceMetagenerationMatch>().value()); } if (request.HasOption<IfSourceMetagenerationNotMatch>()) { result.set_if_source_metageneration_not_match( request.GetOption<IfSourceMetagenerationNotMatch>().value()); } result.set_max_bytes_rewritten_per_call( request.GetOption<MaxBytesRewrittenPerCall>().value_or(0)); if (request.HasOption<SourceEncryptionKey>()) { auto data = request.template GetOption<SourceEncryptionKey>().value(); auto key_bytes = Base64Decode(data.key); if (!key_bytes) return std::move(key_bytes).status(); auto key_sha256_bytes = Base64Decode(data.sha256); if (!key_sha256_bytes) return std::move(key_sha256_bytes).status(); result.set_copy_source_encryption_algorithm(data.algorithm); result.set_copy_source_encryption_key_bytes( std::string{key_bytes->begin(), key_bytes->end()}); result.set_copy_source_encryption_key_sha256_bytes( std::string{key_sha256_bytes->begin(), key_sha256_bytes->end()}); } return result; } RewriteObjectResponse GrpcObjectRequestParser::FromProto( google::storage::v2::RewriteResponse const& response, Options const& options) { RewriteObjectResponse result; result.done = response.done(); result.object_size = response.object_size(); result.total_bytes_rewritten = response.total_bytes_rewritten(); result.rewrite_token = response.rewrite_token(); if (response.has_resource()) { result.resource = GrpcObjectMetadataParser::FromProto(response.resource(), options); } return result; } StatusOr<google::storage::v2::StartResumableWriteRequest> GrpcObjectRequestParser::ToProto(ResumableUploadRequest const& request) { google::storage::v2::StartResumableWriteRequest result; auto status = SetCommonObjectParameters(result, request); if (!status.ok()) return status; auto& object_spec = *result.mutable_write_object_spec(); auto& resource = *object_spec.mutable_resource(); SetResourceOptions(resource, request); status = SetObjectMetadata(resource, request); if (!status.ok()) return status; SetPredefinedAcl(object_spec, request); SetGenerationConditions(object_spec, request); SetMetagenerationConditions(object_spec, request); SetCommonParameters(result, request); resource.set_bucket("projects/_/buckets/" + request.bucket_name()); resource.set_name(request.object_name()); return result; } google::storage::v2::QueryWriteStatusRequest GrpcObjectRequestParser::ToProto( QueryResumableUploadRequest const& request) { google::storage::v2::QueryWriteStatusRequest r; r.set_upload_id(request.upload_session_url()); return r; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google
40.208748
80
0.737009
LaudateCorpus1